@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,109 @@
|
|
|
1
|
+
const levels = new Set(['public', 'user', 'organization']);
|
|
2
|
+
const show = (value) => {
|
|
3
|
+
try {
|
|
4
|
+
return JSON.stringify(value) ?? String(value);
|
|
5
|
+
}
|
|
6
|
+
catch {
|
|
7
|
+
return String(value);
|
|
8
|
+
}
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* The startup check of `access`: exactly one of the three levels, or `{ permission }` with at least
|
|
12
|
+
* one resource, each a non-empty list of operation names. With a permission catalog, every
|
|
13
|
+
* resource and operation must be declared. Returns the problem, or undefined.
|
|
14
|
+
*/
|
|
15
|
+
export function accessProblem(access, catalog) {
|
|
16
|
+
if (access === undefined)
|
|
17
|
+
return "needs access: 'public', 'user', 'organization' or { permission: { resource: ['operation'] } }.";
|
|
18
|
+
if (typeof access === 'string')
|
|
19
|
+
return levels.has(access)
|
|
20
|
+
? undefined
|
|
21
|
+
: `has an unknown access ${show(access)}. Use 'public', 'user', 'organization' or { permission }.`;
|
|
22
|
+
if (!access || typeof access !== 'object' || Array.isArray(access))
|
|
23
|
+
return `has an invalid access ${show(access)}.`;
|
|
24
|
+
const keys = Object.keys(access);
|
|
25
|
+
if (keys.length !== 1 || keys[0] !== 'permission')
|
|
26
|
+
return `has an invalid access ${show(access)}: an object holds only { permission }.`;
|
|
27
|
+
const permission = access.permission;
|
|
28
|
+
if (!permission || typeof permission !== 'object' || Array.isArray(permission))
|
|
29
|
+
return "needs access.permission as a record: { permission: { resource: ['operation'] } }.";
|
|
30
|
+
const resources = Object.entries(permission);
|
|
31
|
+
if (!resources.length)
|
|
32
|
+
return 'needs at least one resource in access.permission.';
|
|
33
|
+
const declared = Object.keys(catalog);
|
|
34
|
+
for (const [resource, operations] of resources) {
|
|
35
|
+
if (!Array.isArray(operations) ||
|
|
36
|
+
!operations.length ||
|
|
37
|
+
operations.some((operation) => typeof operation !== 'string' || !operation))
|
|
38
|
+
return `needs a non-empty list of operation names for "${resource}" in access.permission.`;
|
|
39
|
+
if (!declared.length)
|
|
40
|
+
continue;
|
|
41
|
+
const known = catalog[resource];
|
|
42
|
+
if (!known)
|
|
43
|
+
return `checks unknown permission resource "${resource}". Declared resources: ${declared.map((name) => `"${name}"`).join(', ')}.`;
|
|
44
|
+
const unknown = operations.filter((operation) => !known.actions.includes(operation));
|
|
45
|
+
if (unknown.length)
|
|
46
|
+
return `checks unknown operations ${unknown.map((name) => `"${name}"`).join(', ')} of "${resource}" (declared: ${known.actions.map((name) => `"${name}"`).join(', ')}).`;
|
|
47
|
+
}
|
|
48
|
+
return undefined;
|
|
49
|
+
}
|
|
50
|
+
const nonEmpty = (value) => typeof value === 'string' && value !== '';
|
|
51
|
+
const isObject = (value) => !!value && typeof value === 'object';
|
|
52
|
+
/**
|
|
53
|
+
* A frozen copy with the named fields read once from the original and written into the copy, so
|
|
54
|
+
* a getter (ORM model instances) or a non-enumerable field is never lost by the spread, and what
|
|
55
|
+
* was checked is exactly what the operation receives.
|
|
56
|
+
*/
|
|
57
|
+
function copy(value, fields) {
|
|
58
|
+
const result = { ...value };
|
|
59
|
+
for (const [field, read] of Object.entries(fields))
|
|
60
|
+
if (read === undefined)
|
|
61
|
+
delete result[field];
|
|
62
|
+
else
|
|
63
|
+
result[field] = read;
|
|
64
|
+
return Object.freeze(result);
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* A user only with a non-empty string `id`; an organization only with a user and a non-empty
|
|
68
|
+
* `id`; a non-function `can` is dropped. Each declared field (`id`, `name`, `email`; the
|
|
69
|
+
* organization's `id`; the member's `id` and `role`) is read once and checked on the value the
|
|
70
|
+
* copy holds. Copies are frozen, so no interceptor or listener can change the identity in the
|
|
71
|
+
* middle of a call.
|
|
72
|
+
*/
|
|
73
|
+
export function normalizeIdentity(raw) {
|
|
74
|
+
const value = (isObject(raw) ? raw : {});
|
|
75
|
+
const rawUser = isObject(value.user) ? value.user : undefined;
|
|
76
|
+
const userId = rawUser?.id;
|
|
77
|
+
const user = rawUser && nonEmpty(userId)
|
|
78
|
+
? copy(rawUser, { id: userId, name: rawUser.name, email: rawUser.email })
|
|
79
|
+
: null;
|
|
80
|
+
const rawOrganization = isObject(value.organization) ? value.organization : undefined;
|
|
81
|
+
const organizationId = rawOrganization?.id;
|
|
82
|
+
const organization = user && rawOrganization && nonEmpty(organizationId)
|
|
83
|
+
? copy(rawOrganization, { id: organizationId })
|
|
84
|
+
: null;
|
|
85
|
+
const rawMember = isObject(value.member) ? value.member : undefined;
|
|
86
|
+
const member = organization && rawMember
|
|
87
|
+
? copy(rawMember, { id: rawMember.id, role: rawMember.role })
|
|
88
|
+
: null;
|
|
89
|
+
const reason = value.reason === 'NO_ACTIVE_ORGANIZATION' || value.reason === 'NOT_A_MEMBER'
|
|
90
|
+
? value.reason
|
|
91
|
+
: undefined;
|
|
92
|
+
const can = typeof value.can === 'function' ? value.can.bind(value) : undefined;
|
|
93
|
+
return { user, organization, member, reason, can };
|
|
94
|
+
}
|
|
95
|
+
/** `ctx.can`: only an answer `=== true` grants; a throw or anything else denies. */
|
|
96
|
+
export function permissionCheck(identity, report) {
|
|
97
|
+
return async (permission) => {
|
|
98
|
+
if (!identity.can)
|
|
99
|
+
return false;
|
|
100
|
+
try {
|
|
101
|
+
return (await identity.can(permission)) === true;
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
104
|
+
report(error);
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
export const isOrganizationAccess = (access) => access !== 'public' && access !== 'user';
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { ConfigContext } from '../config-service.js';
|
|
2
|
+
import type { InputSchema, Plugin } from '../definitions.js';
|
|
3
|
+
import type { Events } from '../events/types.js';
|
|
4
|
+
import type { Access, PermissionRequest, RequestContext } from '../request-context.js';
|
|
5
|
+
import type { NormalizedPlugin } from '../runtime.js';
|
|
6
|
+
import type { ServerStartParts } from '../runtime-mode.js';
|
|
7
|
+
import type { OperationInfo, ServerInterceptorSpec } from './types.js';
|
|
8
|
+
type Hook<K extends 'before' | 'after' | 'onError'> = {
|
|
9
|
+
readonly run: NonNullable<ServerInterceptorSpec[K]>;
|
|
10
|
+
readonly module: string;
|
|
11
|
+
};
|
|
12
|
+
/** One server Action, compiled once at boot. Frozen; calls never mutate it. */
|
|
13
|
+
export type Operation = {
|
|
14
|
+
readonly id: string;
|
|
15
|
+
readonly module: string;
|
|
16
|
+
readonly source?: string;
|
|
17
|
+
/** The file path segments that scope `config.action`. */
|
|
18
|
+
readonly path: readonly string[];
|
|
19
|
+
readonly requires?: readonly string[];
|
|
20
|
+
readonly access: Access;
|
|
21
|
+
readonly organization: boolean;
|
|
22
|
+
readonly permission?: PermissionRequest;
|
|
23
|
+
readonly exposed: boolean;
|
|
24
|
+
readonly input?: InputSchema<unknown>;
|
|
25
|
+
readonly output?: InputSchema<unknown>;
|
|
26
|
+
readonly execute: (context: object) => unknown;
|
|
27
|
+
readonly info: OperationInfo;
|
|
28
|
+
config: ConfigContext;
|
|
29
|
+
events: {
|
|
30
|
+
readonly events: Events;
|
|
31
|
+
withContext(ctx: RequestContext): Events;
|
|
32
|
+
};
|
|
33
|
+
before: readonly Hook<'before'>[];
|
|
34
|
+
after: readonly Hook<'after'>[];
|
|
35
|
+
onError: readonly Hook<'onError'>[];
|
|
36
|
+
};
|
|
37
|
+
export type OperationTable = {
|
|
38
|
+
readonly exact: ReadonlyMap<string, Operation>;
|
|
39
|
+
readonly folded: ReadonlyMap<string, Operation>;
|
|
40
|
+
readonly all: readonly Operation[];
|
|
41
|
+
};
|
|
42
|
+
/** Server Actions print as `server:<id>` in every message. */
|
|
43
|
+
export declare const label: (id: string) => string;
|
|
44
|
+
/**
|
|
45
|
+
* The static half of compilation, before any service starts: field rules, `access`, `expose`,
|
|
46
|
+
* schemas, duplicate IDs (exact or equal ignoring case), exposure and the `requestContext`
|
|
47
|
+
* provider check. Every problem is a `BitaKitStartupError` naming the operation and its file.
|
|
48
|
+
*/
|
|
49
|
+
export declare function compileOperations(modules: readonly NormalizedPlugin[], plugins: readonly Plugin[], appId: string, options: {
|
|
50
|
+
providers: readonly string[];
|
|
51
|
+
operations?: readonly string[];
|
|
52
|
+
}): OperationTable;
|
|
53
|
+
/**
|
|
54
|
+
* The dynamic half, called by the server-mode runtime once its services exist: `requires`
|
|
55
|
+
* checks, config scopes, event scopes and the interceptor chain of each operation (exact IDs,
|
|
56
|
+
* `prefix.*` and `*`; plugin-local unless global, ordered by `order` like on the client).
|
|
57
|
+
*/
|
|
58
|
+
export declare function linkOperations(table: OperationTable, parts: ServerStartParts): void;
|
|
59
|
+
export {};
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import { contributionPath, contributionSource } from '../contribution-origin.js';
|
|
2
|
+
import { pluginOrigin } from '../inspection/plugin-origin.js';
|
|
3
|
+
import { isServiceInterceptor } from '../interceptors/define.js';
|
|
4
|
+
import { resolveName } from '../name-resolution.js';
|
|
5
|
+
import { composePermissions } from '../permissions.js';
|
|
6
|
+
import { reservedSegmentOf, reservedSegments } from '../remote.js';
|
|
7
|
+
import { BitaKitStartupError, moduleLabel } from '../startup-error.js';
|
|
8
|
+
import { accessProblem, isOrganizationAccess } from './access.js';
|
|
9
|
+
import { isSchema } from './validate.js';
|
|
10
|
+
const clientOnlyFields = [
|
|
11
|
+
'enabled',
|
|
12
|
+
'visible',
|
|
13
|
+
'href',
|
|
14
|
+
'dialog',
|
|
15
|
+
'dialogSize',
|
|
16
|
+
'confirm',
|
|
17
|
+
'slots',
|
|
18
|
+
'groups',
|
|
19
|
+
'order',
|
|
20
|
+
'dividerBefore',
|
|
21
|
+
'shortcut',
|
|
22
|
+
'icon',
|
|
23
|
+
'tooltip',
|
|
24
|
+
'variant',
|
|
25
|
+
'checked',
|
|
26
|
+
'value',
|
|
27
|
+
'concurrency',
|
|
28
|
+
'concurrencyKey',
|
|
29
|
+
'success',
|
|
30
|
+
'failure',
|
|
31
|
+
'internal',
|
|
32
|
+
];
|
|
33
|
+
/** Server Actions print as `server:<id>` in every message. */
|
|
34
|
+
export const label = (id) => `server:${id}`;
|
|
35
|
+
function startupError(id, module, appId, problem, source) {
|
|
36
|
+
return new BitaKitStartupError(`${label(id)} in ${moduleLabel(module, appId)} ${problem}${source ? `\nSource: ${source}` : ''}`, module, { source, app: module === appId });
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The static half of compilation, before any service starts: field rules, `access`, `expose`,
|
|
40
|
+
* schemas, duplicate IDs (exact or equal ignoring case), exposure and the `requestContext`
|
|
41
|
+
* provider check. Every problem is a `BitaKitStartupError` naming the operation and its file.
|
|
42
|
+
*/
|
|
43
|
+
export function compileOperations(modules, plugins, appId, options) {
|
|
44
|
+
let catalog;
|
|
45
|
+
try {
|
|
46
|
+
catalog = composePermissions(modules
|
|
47
|
+
.filter((module) => module.permissions !== undefined)
|
|
48
|
+
.map((module) => ({ owner: module.id, definition: module.permissions })));
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
catalog = {}; // The runtime constructor already reported the catalog's own problems.
|
|
52
|
+
}
|
|
53
|
+
const exact = new Map();
|
|
54
|
+
const folded = new Map();
|
|
55
|
+
const known = options.operations ? new Set(options.operations) : undefined;
|
|
56
|
+
for (const module of modules) {
|
|
57
|
+
const original = plugins.find((plugin) => plugin.id === module.id);
|
|
58
|
+
const publishes = module.id === appId || pluginOrigin(original)?.kind !== 'package';
|
|
59
|
+
for (const spec of module.actions) {
|
|
60
|
+
const id = spec.id;
|
|
61
|
+
const source = contributionSource(spec);
|
|
62
|
+
const fail = (problem) => startupError(id, module.id, appId, problem, source);
|
|
63
|
+
const fields = spec;
|
|
64
|
+
const clientField = clientOnlyFields.find((field) => fields[field] !== undefined);
|
|
65
|
+
if (clientField)
|
|
66
|
+
throw fail(`has the client-only field "${clientField}". It belongs to the button (actions/${(contributionPath(spec) ?? id.split('.')).join('/')}.ts), not the operation.`);
|
|
67
|
+
const problem = accessProblem(fields.access, catalog);
|
|
68
|
+
if (problem)
|
|
69
|
+
throw fail(problem);
|
|
70
|
+
if (fields.expose !== undefined && typeof fields.expose !== 'boolean')
|
|
71
|
+
throw fail(`has expose ${JSON.stringify(fields.expose)}; use true or false.`);
|
|
72
|
+
for (const field of ['input', 'output'])
|
|
73
|
+
if (fields[field] !== undefined && !isSchema(fields[field]))
|
|
74
|
+
throw fail(`has an ${field} that is not a schema (zod, valibot or a Standard Schema).`);
|
|
75
|
+
if (typeof spec.execute !== 'function')
|
|
76
|
+
throw fail('needs execute({ input, ctx, ... }).');
|
|
77
|
+
const reserved = reservedSegmentOf(id);
|
|
78
|
+
if (reserved !== undefined)
|
|
79
|
+
throw fail(`uses the reserved name "${reserved}"; ${[...reservedSegments].join(', ')} cannot name a server Action, because remote and the in-process caller would turn them into thenable, observable or converting objects. Rename the file (or its record key).`);
|
|
80
|
+
const twin = folded.get(id.toLowerCase());
|
|
81
|
+
if (twin)
|
|
82
|
+
throw new BitaKitStartupError(`Duplicate server Action ID${twin.id === id ? '' : ' (equal ignoring case)'}: ${label(twin.id)} in ${moduleLabel(twin.module, appId)} (${twin.source ?? 'no file'}) and ${label(id)} in ${moduleLabel(module.id, appId)} (${source ?? 'no file'}). Rename one of them.`, module.id, { source, app: module.id === appId });
|
|
83
|
+
const access = freezeAccess(fields.access);
|
|
84
|
+
const exposed = fields.expose === true && publishes;
|
|
85
|
+
if (exposed && known && !known.has(id))
|
|
86
|
+
console.warn(`[bitakit] ${label(id)} is exposed over HTTP but missing from the generated remote; discovery could not read its definition statically${source ? ` (${source})` : ''}.`);
|
|
87
|
+
const operation = {
|
|
88
|
+
id,
|
|
89
|
+
module: module.id,
|
|
90
|
+
source,
|
|
91
|
+
path: contributionPath(spec) ?? id.split('.'),
|
|
92
|
+
requires: spec.requires,
|
|
93
|
+
access,
|
|
94
|
+
organization: isOrganizationAccess(access),
|
|
95
|
+
permission: typeof access === 'object' ? access.permission : undefined,
|
|
96
|
+
exposed,
|
|
97
|
+
input: fields.input,
|
|
98
|
+
output: fields.output,
|
|
99
|
+
execute: spec.execute,
|
|
100
|
+
info: Object.freeze({
|
|
101
|
+
id,
|
|
102
|
+
plugin: module.id,
|
|
103
|
+
access,
|
|
104
|
+
exposed,
|
|
105
|
+
...(typeof spec.title === 'string' ? { title: spec.title } : {}),
|
|
106
|
+
...(typeof spec.description === 'string' ? { description: spec.description } : {}),
|
|
107
|
+
...(source ? { source } : {}),
|
|
108
|
+
}),
|
|
109
|
+
config: undefined,
|
|
110
|
+
events: undefined,
|
|
111
|
+
before: [],
|
|
112
|
+
after: [],
|
|
113
|
+
onError: [],
|
|
114
|
+
};
|
|
115
|
+
exact.set(id, operation);
|
|
116
|
+
folded.set(id.toLowerCase(), operation);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
const all = [...exact.values()];
|
|
120
|
+
const guarded = all.find((operation) => operation.access !== 'public');
|
|
121
|
+
if (guarded && !options.providers.length)
|
|
122
|
+
throw startupError(guarded.id, guarded.module, appId, `needs a signed-in caller (access ${JSON.stringify(guarded.access)}), but no service provides requestContext. Add src/server/services/request-context.ts with provides: requestContext.`, guarded.source);
|
|
123
|
+
return { exact, folded, all };
|
|
124
|
+
}
|
|
125
|
+
function freezeAccess(access) {
|
|
126
|
+
if (typeof access === 'string')
|
|
127
|
+
return access;
|
|
128
|
+
return Object.freeze({
|
|
129
|
+
permission: Object.freeze(Object.fromEntries(Object.entries(access.permission).map(([resource, operations]) => [
|
|
130
|
+
resource,
|
|
131
|
+
Object.freeze([...operations]),
|
|
132
|
+
]))),
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* The dynamic half, called by the server-mode runtime once its services exist: `requires`
|
|
137
|
+
* checks, config scopes, event scopes and the interceptor chain of each operation (exact IDs,
|
|
138
|
+
* `prefix.*` and `*`; plugin-local unless global, ordered by `order` like on the client).
|
|
139
|
+
*/
|
|
140
|
+
export function linkOperations(table, parts) {
|
|
141
|
+
const ids = table.all.map((operation) => operation.id);
|
|
142
|
+
const prefixes = new Set(ids.flatMap((id) => id
|
|
143
|
+
.split('.')
|
|
144
|
+
.slice(0, -1)
|
|
145
|
+
.map((_, index, all) => all.slice(0, index + 1).join('.'))));
|
|
146
|
+
const interceptors = parts.modules
|
|
147
|
+
.flatMap((module) => (module.interceptors ?? []).map((spec) => ({ spec, module: module.id })))
|
|
148
|
+
.filter(({ spec }) => !isServiceInterceptor(spec))
|
|
149
|
+
.sort((a, b) => (a.spec.order ?? 0) - (b.spec.order ?? 0))
|
|
150
|
+
.map(({ spec, module }) => {
|
|
151
|
+
const definition = spec;
|
|
152
|
+
const source = contributionSource(spec);
|
|
153
|
+
try {
|
|
154
|
+
parts.require(module, definition.requires, {
|
|
155
|
+
label: `A server interceptor in ${moduleLabel(module, parts.appId)}`,
|
|
156
|
+
source,
|
|
157
|
+
});
|
|
158
|
+
return {
|
|
159
|
+
definition,
|
|
160
|
+
module,
|
|
161
|
+
global: definition.scope === 'global' ||
|
|
162
|
+
(module === parts.appId && definition.scope !== 'plugin'),
|
|
163
|
+
matches: matcher(definition.action ?? '*', ids, prefixes),
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
catch (error) {
|
|
167
|
+
throw parts.attribute(error, module, 'Server interceptor', source);
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
for (const operation of table.all) {
|
|
171
|
+
try {
|
|
172
|
+
parts.require(operation.module, operation.requires, {
|
|
173
|
+
label: label(operation.id),
|
|
174
|
+
source: operation.source,
|
|
175
|
+
});
|
|
176
|
+
operation.config = parts.config(operation.module, operation.path);
|
|
177
|
+
operation.events = parts.events(operation.module);
|
|
178
|
+
}
|
|
179
|
+
catch (error) {
|
|
180
|
+
throw parts.attribute(error, operation.module, label(operation.id), operation.source);
|
|
181
|
+
}
|
|
182
|
+
const chain = interceptors.filter((entry) => (entry.global || entry.module === operation.module) && entry.matches(operation.id));
|
|
183
|
+
operation.before = hooks(chain, 'before');
|
|
184
|
+
operation.after = hooks(chain, 'after');
|
|
185
|
+
operation.onError = hooks(chain, 'onError');
|
|
186
|
+
Object.freeze(operation);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
function hooks(chain, kind) {
|
|
190
|
+
return chain.flatMap(({ definition, module }) => {
|
|
191
|
+
const run = definition[kind];
|
|
192
|
+
return typeof run === 'function'
|
|
193
|
+
? [{ run: run.bind(definition), module }]
|
|
194
|
+
: [];
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
/** Resolves each pattern once against every operation, so matching per operation is O(1). */
|
|
198
|
+
function matcher(target, ids, prefixes) {
|
|
199
|
+
const patterns = typeof target === 'string' ? [target] : target;
|
|
200
|
+
const tests = patterns.map((pattern) => {
|
|
201
|
+
if (pattern === '*')
|
|
202
|
+
return () => true;
|
|
203
|
+
if (pattern.endsWith('.*')) {
|
|
204
|
+
const prefix = `${resolveName(pattern.slice(0, -2), prefixes)}.`;
|
|
205
|
+
return (id) => id.startsWith(prefix);
|
|
206
|
+
}
|
|
207
|
+
const exact = resolveName(pattern, ids);
|
|
208
|
+
return (id) => id === exact;
|
|
209
|
+
});
|
|
210
|
+
return (id) => tests.some((test) => test(id));
|
|
211
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { ContributionMap, Plugin } from '../definitions.js';
|
|
2
|
+
import type { ServerConfig } from './types.js';
|
|
3
|
+
type ValueOf<K extends string> = K extends keyof ContributionMap ? ContributionMap[K] : unknown;
|
|
4
|
+
/**
|
|
5
|
+
* The values of one contribution kind with the module that contributed each, in composition
|
|
6
|
+
* order: the app module first (for a config), then its plugins. Pure: it reads definitions only,
|
|
7
|
+
* starts nothing and needs no installer, so hosts read server-only kinds with it.
|
|
8
|
+
*/
|
|
9
|
+
export declare function contributionsOf<K extends string>(source: ServerConfig | readonly Plugin[], kind: K): readonly {
|
|
10
|
+
readonly plugin: string;
|
|
11
|
+
readonly value: ValueOf<K>;
|
|
12
|
+
}[];
|
|
13
|
+
export {};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The values of one contribution kind with the module that contributed each, in composition
|
|
3
|
+
* order: the app module first (for a config), then its plugins. Pure: it reads definitions only,
|
|
4
|
+
* starts nothing and needs no installer, so hosts read server-only kinds with it.
|
|
5
|
+
*/
|
|
6
|
+
export function contributionsOf(source, kind) {
|
|
7
|
+
const modules = Array.isArray(source)
|
|
8
|
+
? source
|
|
9
|
+
: [
|
|
10
|
+
{
|
|
11
|
+
id: source.appId ?? 'app',
|
|
12
|
+
contributions: source.contributions,
|
|
13
|
+
},
|
|
14
|
+
...(source.plugins ?? []),
|
|
15
|
+
];
|
|
16
|
+
return Object.freeze(modules.flatMap((module) => (module.contributions?.[kind] ?? []).map((value) => Object.freeze({ plugin: module.id, value: value }))));
|
|
17
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Server, ServerConfig, ServerOptions } from './types.js';
|
|
2
|
+
/** `Headers` become a request with a fixed internal URL; a `Request` is used as it is. */
|
|
3
|
+
export declare function toRequest(request: Request | Headers): Request;
|
|
4
|
+
/**
|
|
5
|
+
* Creates the server handle. It never boots at import: the first `ready`, `as()`, `call()` or
|
|
6
|
+
* `operations()` does. With `instance`, live kernels are shared process-wide under
|
|
7
|
+
* `globalThis[Symbol.for('bitakit.servers')][instance]`: the same `stamp` reuses the live kernel;
|
|
8
|
+
* in development a newer module copy with a different stamp boots a replacement, swaps it in
|
|
9
|
+
* and stops the old one after it drains (older handles forward to the current kernel); in
|
|
10
|
+
* production the first kernel wins and a different stamp logs one warning. `stop()` stops the
|
|
11
|
+
* instance's kernel unless a newer module copy's kernel has replaced this handle's code; the
|
|
12
|
+
* stopped kernel stays registered, so the instance's other handles answer SERVICE_UNAVAILABLE
|
|
13
|
+
* rather than boot again. Without `instance` the handle owns its kernel.
|
|
14
|
+
*/
|
|
15
|
+
export declare function createServer(config: ServerConfig, options?: ServerOptions): Server;
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { OperationError } from '../operation-error.js';
|
|
2
|
+
import { reservedSegments } from '../remote.js';
|
|
3
|
+
import { Kernel } from './kernel.js';
|
|
4
|
+
const registryKey = Symbol.for('bitakit.servers');
|
|
5
|
+
const sequenceKey = Symbol.for('bitakit.servers.sequence');
|
|
6
|
+
/**
|
|
7
|
+
* Kernels by instance name, shared by every module copy in this process. A stopped kernel stays
|
|
8
|
+
* registered, so every handle of the instance answers SERVICE_UNAVAILABLE instead of booting a
|
|
9
|
+
* second kernel nobody stops; only a newer module copy replaces it in development.
|
|
10
|
+
*/
|
|
11
|
+
function registry() {
|
|
12
|
+
return (globalThis[registryKey] ??= Object.create(null));
|
|
13
|
+
}
|
|
14
|
+
function nextSequence() {
|
|
15
|
+
const global = globalThis;
|
|
16
|
+
return (global[sequenceKey] = (global[sequenceKey] ?? 0) + 1);
|
|
17
|
+
}
|
|
18
|
+
function production() {
|
|
19
|
+
const env = globalThis.process
|
|
20
|
+
?.env;
|
|
21
|
+
return env?.NODE_ENV === 'production';
|
|
22
|
+
}
|
|
23
|
+
/** `Headers` become a request with a fixed internal URL; a `Request` is used as it is. */
|
|
24
|
+
export function toRequest(request) {
|
|
25
|
+
if (typeof request.url === 'string' &&
|
|
26
|
+
typeof request.clone === 'function')
|
|
27
|
+
return request;
|
|
28
|
+
return new Request('http://bitakit.internal/', { headers: request });
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* The in-process caller: `caller.todos.add(input)` calls `todos.add`. Names are resolved per
|
|
32
|
+
* call against the live kernel (exact first, then ignoring case), so it works before boot and
|
|
33
|
+
* across development swaps. Reserved segments read as undefined, as on `remote`: never thenable,
|
|
34
|
+
* never observable (it can stand in for `remote` in client tests).
|
|
35
|
+
*/
|
|
36
|
+
function createCaller(invoke) {
|
|
37
|
+
const nodes = new Map();
|
|
38
|
+
const node = (path) => {
|
|
39
|
+
let proxy = nodes.get(path);
|
|
40
|
+
if (proxy)
|
|
41
|
+
return proxy;
|
|
42
|
+
proxy = new Proxy(() => { }, {
|
|
43
|
+
get: (_target, name) => typeof name !== 'string' || reservedSegments.has(name)
|
|
44
|
+
? undefined
|
|
45
|
+
: node(path ? `${path}.${name}` : name),
|
|
46
|
+
apply: (_target, _this, args) => path
|
|
47
|
+
? invoke(path, args[0], args[1])
|
|
48
|
+
: Promise.reject(new OperationError('NOT_FOUND', 'Operation not found.')),
|
|
49
|
+
});
|
|
50
|
+
nodes.set(path, proxy);
|
|
51
|
+
return proxy;
|
|
52
|
+
};
|
|
53
|
+
return node('');
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Creates the server handle. It never boots at import: the first `ready`, `as()`, `call()` or
|
|
57
|
+
* `operations()` does. With `instance`, live kernels are shared process-wide under
|
|
58
|
+
* `globalThis[Symbol.for('bitakit.servers')][instance]`: the same `stamp` reuses the live kernel;
|
|
59
|
+
* in development a newer module copy with a different stamp boots a replacement, swaps it in
|
|
60
|
+
* and stops the old one after it drains (older handles forward to the current kernel); in
|
|
61
|
+
* production the first kernel wins and a different stamp logs one warning. `stop()` stops the
|
|
62
|
+
* instance's kernel unless a newer module copy's kernel has replaced this handle's code; the
|
|
63
|
+
* stopped kernel stays registered, so the instance's other handles answer SERVICE_UNAVAILABLE
|
|
64
|
+
* rather than boot again. Without `instance` the handle owns its kernel.
|
|
65
|
+
*/
|
|
66
|
+
export function createServer(config, options = {}) {
|
|
67
|
+
const endpoint = `/${(options.endpoint ?? '/api/rpc').replace(/^\/+|\/+$/g, '')}`;
|
|
68
|
+
const sequence = nextSequence();
|
|
69
|
+
const { instance, stamp } = options;
|
|
70
|
+
let own;
|
|
71
|
+
let stopped = false;
|
|
72
|
+
let stopping;
|
|
73
|
+
let warned = false;
|
|
74
|
+
const kernel = () => {
|
|
75
|
+
if (instance === undefined)
|
|
76
|
+
return (own ??= new Kernel(config, options));
|
|
77
|
+
const live = registry()[instance];
|
|
78
|
+
if (!live || (live.stamp !== stamp && !production() && sequence > live.sequence)) {
|
|
79
|
+
const next = new Kernel(config, options);
|
|
80
|
+
registry()[instance] = { stamp, sequence, kernel: next };
|
|
81
|
+
if (live)
|
|
82
|
+
void live.kernel
|
|
83
|
+
.stop()
|
|
84
|
+
.catch((error) => console.error(`[bitakit] Stopping the replaced server "${instance}" failed.`, error));
|
|
85
|
+
return next;
|
|
86
|
+
}
|
|
87
|
+
if (live.stamp !== stamp && production() && !warned) {
|
|
88
|
+
warned = true;
|
|
89
|
+
console.warn(`[bitakit] Server "${instance}" is already running with different code; the first one stays in production.`);
|
|
90
|
+
}
|
|
91
|
+
return live.kernel;
|
|
92
|
+
};
|
|
93
|
+
const invoke = (id, input, caller, callOptions) => {
|
|
94
|
+
if (stopped) {
|
|
95
|
+
const requestId = callOptions.requestId ?? globalThis.crypto.randomUUID();
|
|
96
|
+
return Promise.reject(new OperationError('SERVICE_UNAVAILABLE', `The server is not available. Reference: ${requestId}`, { requestId }));
|
|
97
|
+
}
|
|
98
|
+
return kernel().call(id, input, caller, callOptions);
|
|
99
|
+
};
|
|
100
|
+
/** The kernel `stop()` may stop: the handle's own, or the instance's unless newer code replaced it. */
|
|
101
|
+
const owned = () => {
|
|
102
|
+
if (instance === undefined)
|
|
103
|
+
return own;
|
|
104
|
+
const live = registry()[instance];
|
|
105
|
+
return live && (live.stamp === stamp || live.sequence <= sequence) ? live.kernel : undefined;
|
|
106
|
+
};
|
|
107
|
+
return Object.freeze({
|
|
108
|
+
endpoint,
|
|
109
|
+
get ready() {
|
|
110
|
+
return stopped ? Promise.resolve() : kernel().ready;
|
|
111
|
+
},
|
|
112
|
+
as(request) {
|
|
113
|
+
const caller = { request: toRequest(request) };
|
|
114
|
+
return createCaller((id, input, callOptions) => invoke(id, input, caller, { ...callOptions, exposedOnly: false }));
|
|
115
|
+
},
|
|
116
|
+
call(id, input, request, callOptions = {}) {
|
|
117
|
+
return invoke(id, input, { request: toRequest(request) }, {
|
|
118
|
+
...callOptions,
|
|
119
|
+
exposedOnly: callOptions.exposedOnly ?? true,
|
|
120
|
+
});
|
|
121
|
+
},
|
|
122
|
+
operations: () => stopped
|
|
123
|
+
? Promise.reject(new OperationError('SERVICE_UNAVAILABLE', 'The server is not available.'))
|
|
124
|
+
: kernel().list(),
|
|
125
|
+
stop() {
|
|
126
|
+
return (stopping ??= (async () => {
|
|
127
|
+
stopped = true;
|
|
128
|
+
await owned()?.stop();
|
|
129
|
+
})());
|
|
130
|
+
},
|
|
131
|
+
});
|
|
132
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { type InputSchema, type SchemaOutput, type ServiceDefinition, type ServiceOptions } from '../definitions.js';
|
|
2
|
+
import { type InterceptorSpec, type ServiceInterceptorSpec } from '../interceptors/define.js';
|
|
3
|
+
import type { ServiceKey } from '../service-key.js';
|
|
4
|
+
import type { Access } from '../request-context.js';
|
|
5
|
+
import type { ServerActionSpec, ServerActionSpecInput, ServerInterceptorSpec, ServerServiceContext } from './types.js';
|
|
6
|
+
type Returned<Output, Result> = [Output] extends [undefined] ? Awaited<Result> : SchemaOutput<Output>;
|
|
7
|
+
type ContractOf<Key> = Key extends ServiceKey<infer Contract, string> ? Contract : unknown;
|
|
8
|
+
/**
|
|
9
|
+
* A server Action: the operation behind a button, in `server/actions/<name>.ts`. `access` is
|
|
10
|
+
* required; `expose: true` publishes it over HTTP and in `remote`. Client-only fields are type
|
|
11
|
+
* errors and startup errors.
|
|
12
|
+
*/
|
|
13
|
+
export declare const defineAction: {
|
|
14
|
+
<S extends InputSchema<any>, const A extends Access, Result = unknown, Output extends InputSchema<any> | undefined = undefined>(spec: ServerActionSpecInput<SchemaOutput<S>, Result, A> & {
|
|
15
|
+
input: S;
|
|
16
|
+
output?: Output;
|
|
17
|
+
}): ServerActionSpec<SchemaOutput<S>, Returned<Output, Result>, A>;
|
|
18
|
+
<const A extends Access, Result = unknown, Output extends InputSchema<any> | undefined = undefined>(spec: ServerActionSpecInput<undefined, Result, A> & {
|
|
19
|
+
input?: undefined;
|
|
20
|
+
output?: Output;
|
|
21
|
+
}): ServerActionSpec<undefined, Returned<Output, Result>, A>;
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* A server service: a process singleton (never per-user state). Methods take the request's `ctx`
|
|
25
|
+
* as an argument; settings load per request with `settings.<plugin>.<name>.load(ctx)`.
|
|
26
|
+
*/
|
|
27
|
+
export declare const defineService: {
|
|
28
|
+
<const Options extends ServiceOptions & {
|
|
29
|
+
provides: ServiceKey<any>;
|
|
30
|
+
}, T extends ContractOf<Options["provides"]>>(create: (context: ServerServiceContext) => T, options: Options): ServiceDefinition<T> & Options;
|
|
31
|
+
<T, const Options extends ServiceOptions & {
|
|
32
|
+
provides?: undefined;
|
|
33
|
+
} = {}>(create: (context: ServerServiceContext) => T, options?: Options): ServiceDefinition<T> & Options;
|
|
34
|
+
};
|
|
35
|
+
/** A server interceptor around operations (`action`) or an observer of a service (`service`). */
|
|
36
|
+
export declare const defineInterceptor: {
|
|
37
|
+
(spec: ServerInterceptorSpec): InterceptorSpec;
|
|
38
|
+
<const Name extends string, const Key extends string = string>(spec: ServiceInterceptorSpec<Name, Key>): InterceptorSpec;
|
|
39
|
+
};
|
|
40
|
+
export {};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { defineAction as defineAnyAction, defineService as defineAnyService, } from '../definitions.js';
|
|
2
|
+
import { defineInterceptor as defineAnyInterceptor, } from '../interceptors/define.js';
|
|
3
|
+
/**
|
|
4
|
+
* A server Action: the operation behind a button, in `server/actions/<name>.ts`. `access` is
|
|
5
|
+
* required; `expose: true` publishes it over HTTP and in `remote`. Client-only fields are type
|
|
6
|
+
* errors and startup errors.
|
|
7
|
+
*/
|
|
8
|
+
export const defineAction = defineAnyAction;
|
|
9
|
+
/**
|
|
10
|
+
* A server service: a process singleton (never per-user state). Methods take the request's `ctx`
|
|
11
|
+
* as an argument; settings load per request with `settings.<plugin>.<name>.load(ctx)`.
|
|
12
|
+
*/
|
|
13
|
+
export const defineService = defineAnyService;
|
|
14
|
+
/** A server interceptor around operations (`action`) or an observer of a service (`service`). */
|
|
15
|
+
export const defineInterceptor = defineAnyInterceptor;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Server } from './types.js';
|
|
2
|
+
export type FetchHandlerOptions = {
|
|
3
|
+
/** Further exact origins (`https://admin.example.com`) allowed to call; never `*` or patterns. */
|
|
4
|
+
trustedOrigins?: readonly string[];
|
|
5
|
+
/** The app's public origin behind a proxy; otherwise the request URL's origin. */
|
|
6
|
+
origin?: string;
|
|
7
|
+
/** Largest accepted body in bytes, a whole number ≥ 0; default 1 MiB. */
|
|
8
|
+
maxBodyBytes?: number;
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* The built-in HTTP transport: `POST <server.endpoint>/<operation id>` with a JSON body, answered
|
|
12
|
+
* with `{ "data": result }` or `{ "error": { code, message, issues?, reason?, requestId? } }`.
|
|
13
|
+
* Only exposed operations are reachable, by their exact ID (no case folding, no decoding). Browser
|
|
14
|
+
* requests must come from the app's origin or a trusted one; bodies are limited in size.
|
|
15
|
+
* Invalid `trustedOrigins`, `origin` or `maxBodyBytes` throw when the handler is created.
|
|
16
|
+
*/
|
|
17
|
+
export declare function fetchHandler(server: Server, options?: FetchHandlerOptions): (request: Request) => Promise<Response>;
|