@bitakit/core 0.3.1 → 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 (51) hide show
  1. package/AGENTS.md +58 -2
  2. package/README.md +61 -18
  3. package/dist/contributions/action.d.ts +0 -5
  4. package/dist/contributions/action.js +12 -0
  5. package/dist/contributions/host.d.ts +3 -0
  6. package/dist/core.d.ts +4 -0
  7. package/dist/core.js +1 -0
  8. package/dist/definitions.d.ts +10 -0
  9. package/dist/events/service.d.ts +14 -0
  10. package/dist/events/service.js +109 -39
  11. package/dist/events/types.d.ts +5 -1
  12. package/dist/inspection/inventory.d.ts +1 -1
  13. package/dist/operation-error.d.ts +75 -0
  14. package/dist/operation-error.js +123 -0
  15. package/dist/remote.d.ts +60 -0
  16. package/dist/remote.js +156 -0
  17. package/dist/request-context.d.ts +62 -0
  18. package/dist/request-context.js +2 -0
  19. package/dist/runtime-mode.d.ts +35 -0
  20. package/dist/runtime-mode.js +6 -0
  21. package/dist/runtime.d.ts +17 -1
  22. package/dist/runtime.js +118 -50
  23. package/dist/server/access.d.ts +31 -0
  24. package/dist/server/access.js +109 -0
  25. package/dist/server/compile.d.ts +59 -0
  26. package/dist/server/compile.js +211 -0
  27. package/dist/server/contributions.d.ts +13 -0
  28. package/dist/server/contributions.js +17 -0
  29. package/dist/server/create-server.d.ts +15 -0
  30. package/dist/server/create-server.js +132 -0
  31. package/dist/server/define.d.ts +40 -0
  32. package/dist/server/define.js +15 -0
  33. package/dist/server/fetch-handler.d.ts +17 -0
  34. package/dist/server/fetch-handler.js +139 -0
  35. package/dist/server/index.d.ts +22 -0
  36. package/dist/server/index.js +21 -0
  37. package/dist/server/kernel.d.ts +44 -0
  38. package/dist/server/kernel.js +278 -0
  39. package/dist/server/types.d.ts +208 -0
  40. package/dist/server/types.js +1 -0
  41. package/dist/server/validate.d.ts +31 -0
  42. package/dist/server/validate.js +60 -0
  43. package/dist/services.d.ts +5 -1
  44. package/dist/services.js +5 -1
  45. package/dist/settings/access.d.ts +5 -2
  46. package/dist/settings/access.js +7 -4
  47. package/dist/settings/server.d.ts +28 -0
  48. package/dist/settings/server.js +94 -0
  49. package/package.json +7 -3
  50. package/testing/index.d.ts +104 -0
  51. package/testing/index.mjs +349 -14
@@ -0,0 +1,139 @@
1
+ import { actionIdPattern } from '../conventions.js';
2
+ import { isOperationError, OperationError, operationErrorBody, operationStatus, } from '../operation-error.js';
3
+ import { organizationHeader } from '../remote.js';
4
+ const headers = { 'content-type': 'application/json', 'cache-control': 'no-store' };
5
+ const reply = (status, body, extra = {}) => new Response(JSON.stringify(body), { status, headers: { ...headers, ...extra } });
6
+ const failure = (error, extra) => reply(operationStatus(error.code), { error: operationErrorBody(error) }, extra);
7
+ const notFound = () => failure(new OperationError('NOT_FOUND', 'Operation not found.'));
8
+ function exactOrigin(value, option) {
9
+ let parsed;
10
+ try {
11
+ parsed = new URL(value);
12
+ }
13
+ catch {
14
+ /* rejected below */
15
+ }
16
+ if (!parsed || value === 'null' || value.includes('*') || parsed.origin !== value)
17
+ throw new TypeError(`fetchHandler: ${option} "${value}" is not an exact origin such as https://app.example.com.`);
18
+ return value;
19
+ }
20
+ /** Reads at most `limit` bytes; undefined when the body is larger. */
21
+ async function readBody(request, limit) {
22
+ if (!request.body)
23
+ return new Uint8Array();
24
+ const reader = request.body.getReader();
25
+ const chunks = [];
26
+ let size = 0;
27
+ for (;;) {
28
+ const { done, value } = await reader.read();
29
+ if (done)
30
+ break;
31
+ size += value.byteLength;
32
+ if (size > limit) {
33
+ await reader.cancel().catch(() => { });
34
+ return undefined;
35
+ }
36
+ chunks.push(value);
37
+ }
38
+ const body = new Uint8Array(size);
39
+ let offset = 0;
40
+ for (const chunk of chunks) {
41
+ body.set(chunk, offset);
42
+ offset += chunk.byteLength;
43
+ }
44
+ return body;
45
+ }
46
+ /** The `host[:port]` of an Origin header value, or undefined for anything that is not a URL. */
47
+ function hostOf(origin) {
48
+ try {
49
+ return new URL(origin).host || undefined;
50
+ }
51
+ catch {
52
+ return undefined;
53
+ }
54
+ }
55
+ /**
56
+ * The built-in HTTP transport: `POST <server.endpoint>/<operation id>` with a JSON body, answered
57
+ * with `{ "data": result }` or `{ "error": { code, message, issues?, reason?, requestId? } }`.
58
+ * Only exposed operations are reachable, by their exact ID (no case folding, no decoding). Browser
59
+ * requests must come from the app's origin or a trusted one; bodies are limited in size.
60
+ * Invalid `trustedOrigins`, `origin` or `maxBodyBytes` throw when the handler is created.
61
+ */
62
+ export function fetchHandler(server, options = {}) {
63
+ const trusted = new Set((options.trustedOrigins ?? []).map((origin) => exactOrigin(origin, 'trusted origin')));
64
+ const ownOrigin = options.origin === undefined ? undefined : exactOrigin(options.origin, 'origin');
65
+ const limit = options.maxBodyBytes ?? 1024 * 1024;
66
+ // NaN or Infinity would silently turn the limit off (`size > NaN` is never true).
67
+ if (!Number.isSafeInteger(limit) || limit < 0)
68
+ throw new TypeError(`fetchHandler: maxBodyBytes ${String(options.maxBodyBytes)} is not a whole number of bytes (0 or more).`);
69
+ const prefix = `${server.endpoint.replace(/\/+$/, '')}/`;
70
+ return async (request) => {
71
+ const url = new URL(request.url);
72
+ if (!url.pathname.startsWith(prefix))
73
+ return notFound();
74
+ if (request.method !== 'POST')
75
+ return failure(new OperationError('METHOD_NOT_SUPPORTED', 'Use POST.'), { allow: 'POST' });
76
+ const id = url.pathname.slice(prefix.length);
77
+ if (!actionIdPattern.test(id) || id.includes('/'))
78
+ return notFound();
79
+ const origin = request.headers.get('origin');
80
+ const site = request.headers.get('sec-fetch-site');
81
+ if (origin !== null
82
+ ? // The browser's own Sec-Fetch-Site (pages cannot set it) settles it; otherwise the Origin
83
+ // must be the app's. Hosts may hand route handlers another URL than the browser used
84
+ // (Next.js gives `localhost` for a page at 127.0.0.1), so without an explicit `origin`
85
+ // the Host header the browser sent counts as the app's origin too.
86
+ site !== 'same-origin' &&
87
+ !trusted.has(origin) &&
88
+ (ownOrigin !== undefined
89
+ ? origin !== ownOrigin
90
+ : origin !== url.origin && hostOf(origin) !== request.headers.get('host'))
91
+ : site !== null && site !== 'same-origin' && site !== 'none')
92
+ return failure(new OperationError('FORBIDDEN', 'Cross-origin requests are not allowed.'));
93
+ const type = (request.headers.get('content-type') ?? '').split(';')[0].trim().toLowerCase();
94
+ if (type !== 'application/json')
95
+ return failure(new OperationError('UNSUPPORTED_MEDIA_TYPE', 'Send JSON (content-type: application/json).'));
96
+ const tooLarge = () => failure(new OperationError('PAYLOAD_TOO_LARGE', 'The request body is too large.'));
97
+ const length = Number(request.headers.get('content-length'));
98
+ if (Number.isFinite(length) && length > limit)
99
+ return tooLarge();
100
+ const bytes = await readBody(request, limit);
101
+ if (!bytes)
102
+ return tooLarge();
103
+ let input;
104
+ if (bytes.byteLength) {
105
+ try {
106
+ input = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
107
+ }
108
+ catch {
109
+ return failure(new OperationError('BAD_REQUEST', 'Invalid JSON.'));
110
+ }
111
+ }
112
+ let result;
113
+ try {
114
+ result = await server.call(id, input, request, {
115
+ exposedOnly: true,
116
+ organizationId: request.headers.get(organizationHeader) ?? undefined,
117
+ });
118
+ }
119
+ catch (error) {
120
+ if (isOperationError(error))
121
+ return failure(error);
122
+ const requestId = globalThis.crypto.randomUUID();
123
+ console.error(`[bitakit] The server call failed (reference ${requestId}).`, error);
124
+ return failure(new OperationError('INTERNAL_SERVER_ERROR', `Something went wrong. Reference: ${requestId}`, {
125
+ requestId,
126
+ }));
127
+ }
128
+ try {
129
+ return reply(200, result === undefined ? {} : { data: result });
130
+ }
131
+ catch (error) {
132
+ const requestId = globalThis.crypto.randomUUID();
133
+ console.error(`[bitakit] The result of server:${id} cannot be sent as JSON (reference ${requestId}).`, error);
134
+ return failure(new OperationError('INTERNAL_SERVER_ERROR', `Something went wrong. Reference: ${requestId}`, {
135
+ requestId,
136
+ }));
137
+ }
138
+ };
139
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * `@bitakit/core/server`: the server half of a BitaKit app. Server-only; never import it from
3
+ * browser code. The `define*` helpers are the root entry's functions with server types.
4
+ */
5
+ export { defineAction, defineService, defineInterceptor } from './define.js';
6
+ export { definePlugin } from '../definitions.js';
7
+ export { defineEvents, event } from '../events/define.js';
8
+ export { defineSettings, setting } from '../settings/define.js';
9
+ export { defineContract, getService } from '../service-key.js';
10
+ export { definePermissions } from '../permissions.js';
11
+ export { settingsStorage } from '../settings/storage.js';
12
+ export { withPluginOrigin } from '../inspection/plugin-origin.js';
13
+ export { BitaKitStartupError, isBitaKitStartupError } from '../startup-error.js';
14
+ export * from '../discovered.js';
15
+ export { OperationError, isOperationError, type OperationErrorCode, type OperationErrorReason, type OperationIssue, } from '../operation-error.js';
16
+ export { requestContext, type RequestContextProvider, type RequestIdentity, type RequestUser, type RequestMember, type PublicContext, type UserContext, type OrganizationContext, type RequestContext, type ContextFor, type Access, type PermissionRequest, } from '../request-context.js';
17
+ export { createServer } from './create-server.js';
18
+ export { fetchHandler, type FetchHandlerOptions } from './fetch-handler.js';
19
+ export { contributionsOf } from './contributions.js';
20
+ export type { Server, ServerConfig, ServerOptions, Caller, CallOptions, OperationInfo, ServerActionEntry, ServerActionSpec, ServerActionSpecInput, ServerExecuteContext, ServerServiceContext, ServerServices, ServerInterceptorSpec, ServerInterceptorContext, ClientOnlyActionField, } from './types.js';
21
+ export type { ServerActionMap, ServerServiceMap } from '../remote.js';
22
+ export type { ServerSettingHandle, ServerSettingsAccess } from '../settings/server.js';
@@ -0,0 +1,21 @@
1
+ /**
2
+ * `@bitakit/core/server`: the server half of a BitaKit app. Server-only; never import it from
3
+ * browser code. The `define*` helpers are the root entry's functions with server types.
4
+ */
5
+ export { defineAction, defineService, defineInterceptor } from './define.js';
6
+ export { definePlugin } from '../definitions.js';
7
+ export { defineEvents, event } from '../events/define.js';
8
+ export { defineSettings, setting } from '../settings/define.js';
9
+ export { defineContract, getService } from '../service-key.js';
10
+ export { definePermissions } from '../permissions.js';
11
+ export { settingsStorage } from '../settings/storage.js';
12
+ export { withPluginOrigin } from '../inspection/plugin-origin.js';
13
+ export { BitaKitStartupError, isBitaKitStartupError } from '../startup-error.js';
14
+ // The discover* normalizers, expandContributions and the Discovered*Entry types, for the
15
+ // generated server file.
16
+ export * from '../discovered.js';
17
+ export { OperationError, isOperationError, } from '../operation-error.js';
18
+ export { requestContext, } from '../request-context.js';
19
+ export { createServer } from './create-server.js';
20
+ export { fetchHandler } from './fetch-handler.js';
21
+ export { contributionsOf } from './contributions.js';
@@ -0,0 +1,44 @@
1
+ import { type Identity } from './access.js';
2
+ import type { CallOptions, OperationInfo, ServerConfig, ServerOptions } from './types.js';
3
+ /** One caller's request and its identity, resolved at most once (memoized promise). */
4
+ export type CallerState = {
5
+ readonly request: Request;
6
+ identity?: Promise<Identity>;
7
+ };
8
+ export type KernelCallOptions = CallOptions & {
9
+ exposedOnly: boolean;
10
+ };
11
+ /**
12
+ * One booted composition: a server-mode runtime plus the compiled operation table. Boots once,
13
+ * lazily; a failed boot stays failed (every call answers SERVICE_UNAVAILABLE) until a new kernel
14
+ * replaces it. Calls share no mutable state except the in-flight counter `stop()` drains.
15
+ */
16
+ export declare class Kernel {
17
+ private readonly config;
18
+ private readonly options;
19
+ readonly ready: Promise<void>;
20
+ private state;
21
+ private closing;
22
+ private stopCompletion?;
23
+ private runtime?;
24
+ private operations;
25
+ private folded;
26
+ private provider?;
27
+ private services;
28
+ private inflight;
29
+ private drained?;
30
+ constructor(config: ServerConfig, options: ServerOptions);
31
+ private boot;
32
+ /** Runs one operation through the per-call order (access, input, interceptors, execute, output). */
33
+ call(id: string, input: unknown, caller: CallerState, options: KernelCallOptions): Promise<unknown>;
34
+ private run;
35
+ /** Step 3: identity, organization, stale-organization and permission checks. */
36
+ private authorize;
37
+ /**
38
+ * The compiled operations; rejects with the startup error after a failed boot and with
39
+ * SERVICE_UNAVAILABLE once stopping.
40
+ */
41
+ list(): Promise<readonly OperationInfo[]>;
42
+ /** Refuses new calls, waits for boot and in-flight calls, then stops the runtime. */
43
+ stop(): Promise<void>;
44
+ }
@@ -0,0 +1,278 @@
1
+ import { createRuntime } from '../runtime.js';
2
+ import { serverStartHooks } from '../runtime-mode.js';
3
+ import { getService } from '../service-key.js';
4
+ import { isOperationError, OperationError } from '../operation-error.js';
5
+ import { organizationHeader } from '../remote.js';
6
+ import { requestContext, } from '../request-context.js';
7
+ import { bindSettings } from '../settings/server.js';
8
+ import { isThenable } from '../schema.js';
9
+ import { normalizeIdentity, permissionCheck } from './access.js';
10
+ import { compileOperations, label, linkOperations } from './compile.js';
11
+ import { check } from './validate.js';
12
+ const notFound = () => new OperationError('NOT_FOUND', 'Operation not found.');
13
+ const unavailable = (requestId) => new OperationError('SERVICE_UNAVAILABLE', `The server is not available. Reference: ${requestId}`, {
14
+ requestId,
15
+ });
16
+ const internal = (requestId) => new OperationError('INTERNAL_SERVER_ERROR', `Something went wrong. Reference: ${requestId}`, {
17
+ requestId,
18
+ });
19
+ const newRequestId = () => globalThis.crypto.randomUUID();
20
+ /**
21
+ * One booted composition: a server-mode runtime plus the compiled operation table. Boots once,
22
+ * lazily; a failed boot stays failed (every call answers SERVICE_UNAVAILABLE) until a new kernel
23
+ * replaces it. Calls share no mutable state except the in-flight counter `stop()` drains.
24
+ */
25
+ export class Kernel {
26
+ config;
27
+ options;
28
+ ready;
29
+ state = 'booting';
30
+ closing = false;
31
+ stopCompletion;
32
+ runtime;
33
+ operations = new Map();
34
+ folded = new Map();
35
+ provider;
36
+ services;
37
+ inflight = 0;
38
+ drained;
39
+ constructor(config, options) {
40
+ this.config = config;
41
+ this.options = options;
42
+ this.ready = this.boot();
43
+ this.ready.catch(() => { });
44
+ }
45
+ async boot() {
46
+ try {
47
+ const plugins = [...(this.config.plugins ?? []), ...(this.options.plugins ?? [])];
48
+ const runtime = createRuntime({ ...this.config, plugins }, { services: this.options.services, mode: 'server' });
49
+ this.runtime = runtime;
50
+ const appId = this.config.appId ?? 'app';
51
+ const providers = [
52
+ ...Object.keys(this.options.services ?? {}),
53
+ ...runtime.modules.flatMap((module) => module.services.flatMap((service) => [service.id, service.provides, service.exposeAs])),
54
+ ].filter((name) => name === requestContext);
55
+ const table = compileOperations(runtime.modules, plugins, appId, {
56
+ providers,
57
+ operations: this.options.operations,
58
+ });
59
+ serverStartHooks.set(runtime, (parts) => linkOperations(table, parts));
60
+ runtime.mount();
61
+ await runtime.ready;
62
+ this.operations = new Map(table.exact);
63
+ this.folded = new Map(table.folded);
64
+ this.services = runtime.services;
65
+ if (runtime.hasService(requestContext))
66
+ this.provider = getService(runtime.services, requestContext);
67
+ this.state = 'ready';
68
+ }
69
+ catch (error) {
70
+ this.state = 'failed';
71
+ console.error('[bitakit] The server failed to start.', error);
72
+ await this.runtime?.stop().catch(() => { });
73
+ throw error;
74
+ }
75
+ }
76
+ /** Runs one operation through the per-call order (access, input, interceptors, execute, output). */
77
+ async call(id, input, caller, options) {
78
+ if (this.state === 'booting')
79
+ await this.ready.catch(() => { });
80
+ const requestId = options.requestId ?? newRequestId();
81
+ if (this.state === 'failed') {
82
+ console.error(`[bitakit] The server is not available (reference ${requestId}); its startup failed, see the error logged at boot.`);
83
+ throw unavailable(requestId);
84
+ }
85
+ if (this.closing)
86
+ throw unavailable(requestId);
87
+ const operation = options.exposedOnly
88
+ ? this.operations.get(id)
89
+ : (this.operations.get(id) ?? this.folded.get(id.toLowerCase()));
90
+ if (!operation || (options.exposedOnly && !operation.exposed))
91
+ throw notFound();
92
+ this.inflight++;
93
+ try {
94
+ return await this.run(operation, input, caller, options, requestId);
95
+ }
96
+ finally {
97
+ if (--this.inflight === 0)
98
+ this.drained?.();
99
+ }
100
+ }
101
+ async run(operation, input, caller, options, requestId) {
102
+ const signal = options.signal ?? caller.request.signal;
103
+ const ctx = operation.access === 'public'
104
+ ? Object.freeze({ requestId, signal })
105
+ : await this.authorize(operation, caller, options, requestId, signal);
106
+ let value = input;
107
+ if (operation.input) {
108
+ let checked = check(operation.input, input);
109
+ if (isThenable(checked))
110
+ checked = await checked;
111
+ if (!checked.ok)
112
+ throw refused(operation, 'input', checked, requestId);
113
+ value = checked.value;
114
+ }
115
+ else if (input !== undefined)
116
+ throw new OperationError('BAD_REQUEST', 'This operation takes no input.');
117
+ const services = this.services;
118
+ // Frozen: an interceptor cannot change what later interceptors, observers or execute see.
119
+ const hook = Object.freeze({
120
+ id: operation.id,
121
+ input: value,
122
+ ctx,
123
+ services,
124
+ config: operation.config,
125
+ signal,
126
+ });
127
+ try {
128
+ for (const { run } of operation.before) {
129
+ let verdict = run(hook);
130
+ if (isThenable(verdict))
131
+ verdict = await verdict;
132
+ if (verdict === false)
133
+ throw new OperationError('FORBIDDEN', 'This action is not allowed.', {
134
+ reason: 'INTERCEPTED',
135
+ });
136
+ }
137
+ let events;
138
+ let settings;
139
+ const runtime = this.runtime;
140
+ let result = operation.execute({
141
+ id: operation.id,
142
+ input: value,
143
+ ctx,
144
+ services,
145
+ config: operation.config,
146
+ signal,
147
+ get events() {
148
+ return (events ??= operation.events.withContext(ctx));
149
+ },
150
+ get settings() {
151
+ return (settings ??= bindSettings(runtime.settingsAccess, ctx));
152
+ },
153
+ });
154
+ if (isThenable(result))
155
+ result = await result;
156
+ if (operation.output) {
157
+ let checked = check(operation.output, result);
158
+ if (isThenable(checked))
159
+ checked = await checked;
160
+ if (!checked.ok)
161
+ throw refused(operation, 'output', checked, requestId);
162
+ result = checked.value;
163
+ }
164
+ if (operation.after.length) {
165
+ const context = Object.freeze({ ...hook, result });
166
+ for (const { run, module } of operation.after)
167
+ observe(() => run(context), module);
168
+ }
169
+ return result;
170
+ }
171
+ catch (error) {
172
+ if (operation.onError.length) {
173
+ const context = Object.freeze({ ...hook, error });
174
+ for (const { run, module } of operation.onError)
175
+ observe(() => run(context), module);
176
+ }
177
+ if (isOperationError(error))
178
+ throw error;
179
+ console.error(`[bitakit] ${label(operation.id)} failed (reference ${requestId}).`, error);
180
+ throw internal(requestId);
181
+ }
182
+ }
183
+ /** Step 3: identity, organization, stale-organization and permission checks. */
184
+ async authorize(operation, caller, options, requestId, signal) {
185
+ let identity;
186
+ try {
187
+ identity = await (caller.identity ??= Promise.resolve()
188
+ .then(() => this.provider.resolve(caller.request))
189
+ .then(normalizeIdentity));
190
+ }
191
+ catch (error) {
192
+ console.error(`[bitakit] The requestContext provider failed for ${label(operation.id)} (reference ${requestId}).`, error);
193
+ throw internal(requestId);
194
+ }
195
+ const { user, organization } = identity;
196
+ if (!user)
197
+ throw new OperationError('UNAUTHORIZED', 'Sign in to continue.');
198
+ if (!operation.organization)
199
+ return Object.freeze({ requestId, signal, user });
200
+ if (!organization)
201
+ throw identity.reason === 'NOT_A_MEMBER'
202
+ ? new OperationError('FORBIDDEN', 'You are not a member of this organization.', {
203
+ reason: 'NOT_A_MEMBER',
204
+ })
205
+ : new OperationError('FORBIDDEN', 'Choose an organization to continue.', {
206
+ reason: 'NO_ACTIVE_ORGANIZATION',
207
+ });
208
+ const header = caller.request.headers.get(organizationHeader);
209
+ const expected = options.organizationId !== undefined ? (options.organizationId ?? '') : (header ?? undefined);
210
+ if (expected !== undefined && expected !== organization.id)
211
+ throw new OperationError('CONFLICT', 'The active organization changed. Reload and try again.', { reason: 'ORGANIZATION_CHANGED' });
212
+ const ctx = Object.freeze({
213
+ requestId,
214
+ signal,
215
+ user,
216
+ organization,
217
+ member: identity.member,
218
+ can: permissionCheck(identity, (error) => console.error(`[bitakit] The permission check failed for ${label(operation.id)} (reference ${requestId}).`, error)),
219
+ });
220
+ if (operation.permission && (await ctx.can(operation.permission)) !== true)
221
+ throw new OperationError('FORBIDDEN', 'You do not have permission for this action.', {
222
+ reason: 'PERMISSION',
223
+ });
224
+ return ctx;
225
+ }
226
+ /**
227
+ * The compiled operations; rejects with the startup error after a failed boot and with
228
+ * SERVICE_UNAVAILABLE once stopping.
229
+ */
230
+ async list() {
231
+ await this.ready;
232
+ if (this.closing)
233
+ throw new OperationError('SERVICE_UNAVAILABLE', 'The server is not available.');
234
+ return [...this.operations.values()].map((operation) => operation.info);
235
+ }
236
+ /** Refuses new calls, waits for boot and in-flight calls, then stops the runtime. */
237
+ stop() {
238
+ this.closing = true;
239
+ return (this.stopCompletion ??= (async () => {
240
+ await this.ready.catch(() => { });
241
+ if (this.inflight > 0)
242
+ await new Promise((resolve) => (this.drained = resolve));
243
+ await this.runtime?.stop();
244
+ })());
245
+ }
246
+ }
247
+ /**
248
+ * The error of a failed check. A failing schema (`fault`) and an output the schema rejects are
249
+ * server errors: logged with the reference, answered INTERNAL_SERVER_ERROR. Invalid input is
250
+ * BAD_REQUEST with its issues; when a `parse` threw without issues, its error is logged and only
251
+ * the fixed issue text and the reference are sent.
252
+ */
253
+ function refused(operation, schema, checked, requestId) {
254
+ if ('fault' in checked) {
255
+ console.error(`[bitakit] The ${schema} schema of ${label(operation.id)} failed (reference ${requestId}).`, checked.fault);
256
+ return internal(requestId);
257
+ }
258
+ if (schema === 'output') {
259
+ console.error(`[bitakit] ${label(operation.id)} returned a value its output schema rejects (reference ${requestId}).`, 'cause' in checked ? checked.cause : checked.issues);
260
+ return internal(requestId);
261
+ }
262
+ if (!('cause' in checked))
263
+ return new OperationError('BAD_REQUEST', 'Invalid input.', { issues: checked.issues });
264
+ console.warn(`[bitakit] The input schema of ${label(operation.id)} threw without issues; the caller sees "Invalid value." (reference ${requestId}).`, checked.cause);
265
+ return new OperationError('BAD_REQUEST', 'Invalid input.', { issues: checked.issues, requestId });
266
+ }
267
+ /** `after` and `onError` observe: never awaited, their failures only logged. */
268
+ function observe(run, module) {
269
+ const report = (error) => console.error(`[bitakit] A server interceptor of "${module}" failed.`, error);
270
+ try {
271
+ const result = run();
272
+ if (isThenable(result))
273
+ Promise.resolve(result).catch(report);
274
+ }
275
+ catch (error) {
276
+ report(error);
277
+ }
278
+ }