@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.
- package/AGENTS.md +58 -2
- package/README.md +61 -18
- package/dist/contributions/action.d.ts +0 -5
- package/dist/contributions/action.js +12 -0
- 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
package/testing/index.mjs
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { access, readFile, realpath } from 'node:fs/promises';
|
|
2
3
|
import path from 'node:path';
|
|
3
4
|
import { pathToFileURL } from 'node:url';
|
|
4
5
|
import { createJiti } from 'jiti';
|
|
5
|
-
import { describeModule, packagePluginId } from '@bitakit/discovery';
|
|
6
|
+
import { describeModule, loadDiscoveryConfig, packagePluginId } from '@bitakit/discovery';
|
|
6
7
|
import {
|
|
7
8
|
createRuntime,
|
|
8
9
|
discoverActions,
|
|
9
10
|
discoverConfig,
|
|
10
11
|
discoverEvents,
|
|
12
|
+
discoverPermissions,
|
|
11
13
|
discoverSettings,
|
|
12
14
|
discoverInterceptors,
|
|
13
15
|
discoverServices,
|
|
@@ -15,6 +17,7 @@ import {
|
|
|
15
17
|
discoveredFile,
|
|
16
18
|
configureAuthPaths,
|
|
17
19
|
} from '../dist/core.js';
|
|
20
|
+
import { createServer, requestContext } from '../dist/server/index.js';
|
|
18
21
|
|
|
19
22
|
/** The plugin ID a package declares (`bitakit.id`), or one derived from its name. */
|
|
20
23
|
async function packageId(directory) {
|
|
@@ -41,6 +44,21 @@ async function manifestOf(directory) {
|
|
|
41
44
|
.then((manifest) => manifest ?? {});
|
|
42
45
|
}
|
|
43
46
|
|
|
47
|
+
/** The ID of a mounted folder: `id`, then `plugin.config.ts`, the folder under `plugins/`, or the package name. */
|
|
48
|
+
async function pluginIdOf(directory, folder, manifest, id) {
|
|
49
|
+
id =
|
|
50
|
+
id ??
|
|
51
|
+
manifest.id ??
|
|
52
|
+
(path.basename(path.dirname(folder)) === 'plugins'
|
|
53
|
+
? path.basename(folder)
|
|
54
|
+
: await packageId(folder));
|
|
55
|
+
if (!id)
|
|
56
|
+
throw new Error(
|
|
57
|
+
`No plugin ID for ${directory}: pass { id }, set one in plugin.config.ts, or run inside a package with a name.`,
|
|
58
|
+
);
|
|
59
|
+
return id;
|
|
60
|
+
}
|
|
61
|
+
|
|
44
62
|
/**
|
|
45
63
|
* Builds the headless plugin of one folder: services, actions, events, settings, configs,
|
|
46
64
|
* interceptors, slot definitions and `setup.ts`, discovered with the same conventions as apps.
|
|
@@ -50,16 +68,7 @@ async function manifestOf(directory) {
|
|
|
50
68
|
async function loadPlugin(directory, id) {
|
|
51
69
|
const module = await describeModule(path.resolve(directory));
|
|
52
70
|
const manifest = await manifestOf(module.directory);
|
|
53
|
-
id =
|
|
54
|
-
id ??
|
|
55
|
-
manifest.id ??
|
|
56
|
-
(path.basename(path.dirname(module.directory)) === 'plugins'
|
|
57
|
-
? path.basename(module.directory)
|
|
58
|
-
: await packageId(module.directory));
|
|
59
|
-
if (!id)
|
|
60
|
-
throw new Error(
|
|
61
|
-
`No plugin ID for ${directory}: pass { id }, set one in plugin.config.ts, or run inside a package with a name.`,
|
|
62
|
-
);
|
|
71
|
+
id = await pluginIdOf(directory, module.directory, manifest, id);
|
|
63
72
|
const importDefault = async (file) => (await import(pathToFileURL(file).href)).default;
|
|
64
73
|
const load = (entries) =>
|
|
65
74
|
Promise.all(
|
|
@@ -92,7 +101,9 @@ async function loadPlugin(directory, id) {
|
|
|
92
101
|
* Files load through Node's TypeScript type stripping, so keep them free of JSX.
|
|
93
102
|
* `options.plugins` adds further plugins: `Plugin` objects or other plugin folders, so an
|
|
94
103
|
* integration test mounts two real folders without a hand-built `definePlugin`.
|
|
95
|
-
* The returned `events.recorded` lists every event emitted while mounted.
|
|
104
|
+
* The returned `events.recorded` lists every event emitted while mounted. `options.remote`
|
|
105
|
+
* replaces the client `remote`: a stub, or `mountServer(...).as(identity(...))` so the client half
|
|
106
|
+
* calls its real server half in-process.
|
|
96
107
|
*/
|
|
97
108
|
export async function mountPlugin(directory = 'src', options = {}) {
|
|
98
109
|
const plugin = await loadPlugin(directory, options.id);
|
|
@@ -102,7 +113,7 @@ export async function mountPlugin(directory = 'src', options = {}) {
|
|
|
102
113
|
);
|
|
103
114
|
const runtime = createRuntime(
|
|
104
115
|
{ plugins: [plugin, ...others], configOverrides: options.configOverrides },
|
|
105
|
-
{ services: options.services },
|
|
116
|
+
{ services: options.services, remote: options.remote },
|
|
106
117
|
);
|
|
107
118
|
const recorded = [];
|
|
108
119
|
const unobserve = runtime.events.observe((event) =>
|
|
@@ -143,6 +154,330 @@ export async function mountPlugin(directory = 'src', options = {}) {
|
|
|
143
154
|
};
|
|
144
155
|
}
|
|
145
156
|
|
|
157
|
+
/**
|
|
158
|
+
* The first `@bitakit/discovery` release whose `describeModule` reports a module's `server/`
|
|
159
|
+
* folder; `mountServer` reads it from there.
|
|
160
|
+
*/
|
|
161
|
+
const serverDiscoveryVersion = '0.3.1';
|
|
162
|
+
|
|
163
|
+
/** The nearest `tsconfig.json` at or above `directory`, whose `paths` server files may import through. */
|
|
164
|
+
async function tsconfigOf(directory) {
|
|
165
|
+
for (let folder = directory; ; folder = path.dirname(folder)) {
|
|
166
|
+
const file = path.join(folder, 'tsconfig.json');
|
|
167
|
+
if (
|
|
168
|
+
await access(file).then(
|
|
169
|
+
() => true,
|
|
170
|
+
() => false,
|
|
171
|
+
)
|
|
172
|
+
)
|
|
173
|
+
return file;
|
|
174
|
+
if (path.dirname(folder) === folder) return undefined;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* The project around a mounted folder: the nearest folder with a package.json, its manifest and
|
|
180
|
+
* its `bitakit.config.ts` (`{}` without one). `undefined` outside every package.
|
|
181
|
+
*/
|
|
182
|
+
async function projectOf(directory) {
|
|
183
|
+
for (let folder = directory; ; folder = path.dirname(folder)) {
|
|
184
|
+
const manifest = await readFile(path.join(folder, 'package.json'), 'utf8').then(
|
|
185
|
+
JSON.parse,
|
|
186
|
+
() => undefined,
|
|
187
|
+
);
|
|
188
|
+
if (manifest)
|
|
189
|
+
return { root: folder, manifest, config: (await loadDiscoveryConfig(folder)).config };
|
|
190
|
+
if (path.dirname(folder) === folder) return undefined;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Frameworks that make a package an app, as the CLI detects them. */
|
|
195
|
+
const frameworks = ['next', '@tanstack/react-start', '@tanstack/react-router'];
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* The app module's folder (`directory` of bitakit.config.ts, `./src` by default), or `undefined`
|
|
199
|
+
* in a plugin package, whose `src` is the plugin.
|
|
200
|
+
*/
|
|
201
|
+
function appDirectoryOf(project) {
|
|
202
|
+
if (!project) return undefined;
|
|
203
|
+
const { manifest, config, root } = project;
|
|
204
|
+
const dependencies = { ...manifest.dependencies, ...manifest.devDependencies };
|
|
205
|
+
if (
|
|
206
|
+
(manifest.bitakit ?? manifest.foundation)?.plugin &&
|
|
207
|
+
!frameworks.some((name) => dependencies[name])
|
|
208
|
+
)
|
|
209
|
+
return undefined;
|
|
210
|
+
return path.resolve(root, config.directory ?? './src');
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const realOrSelf = (file) => realpath(file).catch(() => path.resolve(file));
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* A loader for server files. Unlike `mountPlugin` (Node's own type stripping), it goes through
|
|
217
|
+
* jiti, so `@/server/db` (any `compilerOptions.paths` alias of the nearest tsconfig.json) and
|
|
218
|
+
* extensionless `./helpers` resolve as they do in the app. jiti caches modules for the process
|
|
219
|
+
* apart from Node's own ESM cache: an Action and a service share one helper module, but a test
|
|
220
|
+
* that imports that module natively gets a second copy. Tests therefore reach server modules
|
|
221
|
+
* through `module` (`mounted.import()`). Packages such as `@bitakit/core/server` load natively,
|
|
222
|
+
* as the same instances the test uses.
|
|
223
|
+
*/
|
|
224
|
+
async function serverLoader(directory) {
|
|
225
|
+
const tsconfig = await tsconfigOf(directory);
|
|
226
|
+
const jiti = createJiti(path.join(directory, 'index.ts'), {
|
|
227
|
+
fsCache: false,
|
|
228
|
+
tsconfigPaths: tsconfig ?? false,
|
|
229
|
+
});
|
|
230
|
+
// A path relative to the working directory, as mountServer takes folders, or an alias or a
|
|
231
|
+
// package, resolved as the app resolves them.
|
|
232
|
+
const target = (specifier) =>
|
|
233
|
+
path.isAbsolute(specifier) ||
|
|
234
|
+
/^\.\.?(?:[\\/]|$)/.test(specifier) ||
|
|
235
|
+
existsSync(path.resolve(specifier.split(/[\\/]/)[0]))
|
|
236
|
+
? path.resolve(specifier)
|
|
237
|
+
: specifier;
|
|
238
|
+
return {
|
|
239
|
+
definition: (file) => jiti.import(file, { default: true }),
|
|
240
|
+
module: (specifier) => jiti.import(target(specifier)),
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** A service that answers the `requestContext` contract; the test provider takes its place. */
|
|
245
|
+
const providesRequestContext = (service) =>
|
|
246
|
+
[service.id, service.provides, service.exposeAs].includes(requestContext);
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* The server half of one folder, as discovery writes it into `src/bitakit.gen.server.ts`: the
|
|
250
|
+
* shared `events.ts`, `settings.ts`, `permissions.ts` and `configs/`, plus `server/services`,
|
|
251
|
+
* `server/actions`, `server/interceptors` and the files of the server-only contribution `kinds`
|
|
252
|
+
* (`server/contributions/<dir>`), normalized by each kind's `from` module (a relative `from`
|
|
253
|
+
* resolves against `kindBase`, the app folder the generated file lives in). Client files, `ui/`,
|
|
254
|
+
* `setup.ts` and the rest of `server/` (the module's own code) are not mounted; files they import
|
|
255
|
+
* load on demand. The app module (`app`) has the ID `id ?? plugin.config.ts id ?? 'app'` and
|
|
256
|
+
* unprefixed Actions and services, as in the generated file.
|
|
257
|
+
*/
|
|
258
|
+
async function loadServerModule(directory, { id, app = false, load, kinds, kindBase }) {
|
|
259
|
+
const module = await describeModule(path.resolve(directory), { kinds });
|
|
260
|
+
if (!module.server)
|
|
261
|
+
throw new Error(
|
|
262
|
+
`mountServer needs @bitakit/discovery ${serverDiscoveryVersion} or newer: the installed version does not report server/ folders. Update @bitakit/discovery to ${serverDiscoveryVersion} or newer.`,
|
|
263
|
+
);
|
|
264
|
+
const manifest = await manifestOf(module.directory);
|
|
265
|
+
id = app
|
|
266
|
+
? (id ?? manifest.id ?? 'app')
|
|
267
|
+
: await pluginIdOf(directory, module.directory, manifest, id);
|
|
268
|
+
const prefix = app ? '' : id;
|
|
269
|
+
const files = (entries) =>
|
|
270
|
+
Promise.all(
|
|
271
|
+
entries.map(async (entry) =>
|
|
272
|
+
discoveredFile(
|
|
273
|
+
await load.definition(entry.file),
|
|
274
|
+
entry.path,
|
|
275
|
+
path.relative(process.cwd(), entry.file),
|
|
276
|
+
),
|
|
277
|
+
),
|
|
278
|
+
);
|
|
279
|
+
const permissionsFile = path.join(module.directory, 'permissions.ts');
|
|
280
|
+
const permissions = await access(permissionsFile).then(
|
|
281
|
+
() => files([{ file: permissionsFile, path: '' }]),
|
|
282
|
+
() => [],
|
|
283
|
+
);
|
|
284
|
+
const contributions = {};
|
|
285
|
+
for (const kind of kinds) {
|
|
286
|
+
const entries = module.server.contributions?.[kind.name] ?? [];
|
|
287
|
+
if (kind.runtime !== 'server' || !entries.length) continue;
|
|
288
|
+
const from = /^\.\.?[\\/]/.test(kind.from) ? path.resolve(kindBase, kind.from) : kind.from;
|
|
289
|
+
const normalize = (await load.module(from))[kind.normalize];
|
|
290
|
+
if (typeof normalize !== 'function')
|
|
291
|
+
throw new Error(
|
|
292
|
+
`Contribution kind "${kind.name}": ${kind.from} has no export ${kind.normalize}.`,
|
|
293
|
+
);
|
|
294
|
+
contributions[kind.name] = normalize(await files(entries), id);
|
|
295
|
+
}
|
|
296
|
+
return {
|
|
297
|
+
id,
|
|
298
|
+
dependencies: manifest.dependencies,
|
|
299
|
+
metadata: manifest.metadata,
|
|
300
|
+
events: discoverEvents(await files(module.events)),
|
|
301
|
+
settings: discoverSettings(await files(module.settings)),
|
|
302
|
+
permissions: discoverPermissions(permissions),
|
|
303
|
+
config: discoverConfig(await files(module.configs)),
|
|
304
|
+
services: discoverServices(await files(module.server.services), prefix).filter(
|
|
305
|
+
(service) => !providesRequestContext(service),
|
|
306
|
+
),
|
|
307
|
+
actions: discoverActions(await files(module.server.actions), prefix),
|
|
308
|
+
interceptors: discoverInterceptors(await files(module.server.interceptors)),
|
|
309
|
+
contributions,
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Mounts the server half of one folder for tests (see `loadServerModule`) and boots it. The
|
|
315
|
+
* project's app folder (`directory` of bitakit.config.ts, `src` by default; `options.app`
|
|
316
|
+
* decides explicitly) mounts as the app module, with unprefixed operations; any other folder
|
|
317
|
+
* mounts as a plugin. `as(identity)` calls every operation, also private ones, with the same
|
|
318
|
+
* access checks, input validation and interceptors as over HTTP. A test `requestContext`
|
|
319
|
+
* provider answers each `as()` caller with its identity; it replaces any provider the mounted
|
|
320
|
+
* folders declare (their file is still imported, but the service is left out), so tests never
|
|
321
|
+
* need a real session. `options.plugins` adds plugin folders (their server halves) or `Plugin`
|
|
322
|
+
* objects. As in the generated server file, a folder keeps only its dependencies on mounted
|
|
323
|
+
* modules: package plugins such as `shell` have no server half. Server-only contribution kinds
|
|
324
|
+
* come from bitakit.config.ts `kinds` and `options.kinds` (kinds a package declares through its
|
|
325
|
+
* discovery hook). `import()` loads a server module as the mounted Actions see it. Rejects with
|
|
326
|
+
* the attributed startup error after releasing what started.
|
|
327
|
+
*/
|
|
328
|
+
export async function mountServer(directory = 'src', options = {}) {
|
|
329
|
+
if (options.services && Object.hasOwn(options.services, requestContext))
|
|
330
|
+
throw new Error(
|
|
331
|
+
'mountServer provides requestContext itself: pass identities to as(identity({ ... })) instead of a requestContext service.',
|
|
332
|
+
);
|
|
333
|
+
const target = path.resolve(directory);
|
|
334
|
+
const project = await projectOf(target);
|
|
335
|
+
const appDirectory = appDirectoryOf(project);
|
|
336
|
+
const app =
|
|
337
|
+
options.app ??
|
|
338
|
+
(appDirectory !== undefined && (await realOrSelf(target)) === (await realOrSelf(appDirectory)));
|
|
339
|
+
const configured = project?.config.kinds ?? [];
|
|
340
|
+
if (!Array.isArray(configured)) throw new Error('Discovery "kinds" must be an array.');
|
|
341
|
+
// bitakit.config.ts `kinds`, then `options.kinds`; the later one wins by name, as in discovery.
|
|
342
|
+
const kinds = [
|
|
343
|
+
...new Map(
|
|
344
|
+
[...configured, ...(options.kinds ?? [])].map((kind) => [kind?.name, kind]),
|
|
345
|
+
).values(),
|
|
346
|
+
];
|
|
347
|
+
const load = await serverLoader(target);
|
|
348
|
+
const context = { load, kinds, kindBase: appDirectory ?? target };
|
|
349
|
+
const main = await loadServerModule(directory, { ...context, id: options.id, app });
|
|
350
|
+
const others = await Promise.all(
|
|
351
|
+
(options.plugins ?? []).map(async (other) => {
|
|
352
|
+
if (typeof other === 'string')
|
|
353
|
+
return { folder: true, plugin: await loadServerModule(other, context) };
|
|
354
|
+
if (!other?.services) return { folder: false, plugin: other };
|
|
355
|
+
const services = Array.isArray(other.services)
|
|
356
|
+
? other.services.filter((service) => !providesRequestContext(service))
|
|
357
|
+
: Object.fromEntries(
|
|
358
|
+
Object.entries(other.services).filter(
|
|
359
|
+
([name, service]) => !providesRequestContext({ id: name, ...service }),
|
|
360
|
+
),
|
|
361
|
+
);
|
|
362
|
+
return { folder: false, plugin: { ...other, services } };
|
|
363
|
+
}),
|
|
364
|
+
);
|
|
365
|
+
const mounted = new Set(
|
|
366
|
+
[main, ...others.map(({ plugin }) => plugin)].map((item) => item?.id?.toLowerCase()),
|
|
367
|
+
);
|
|
368
|
+
const kept = (module) => ({
|
|
369
|
+
...module,
|
|
370
|
+
dependencies: module.dependencies?.filter((id) => mounted.has(String(id).toLowerCase())),
|
|
371
|
+
});
|
|
372
|
+
const plugins = others.map(({ folder, plugin }) => (folder ? kept(plugin) : plugin));
|
|
373
|
+
const own = kept(main);
|
|
374
|
+
// The app module is the configuration's top level, as in the generated server file.
|
|
375
|
+
const config = app
|
|
376
|
+
? {
|
|
377
|
+
appId: own.id,
|
|
378
|
+
dependencies: own.dependencies,
|
|
379
|
+
events: own.events,
|
|
380
|
+
settings: own.settings,
|
|
381
|
+
permissions: own.permissions,
|
|
382
|
+
config: own.config,
|
|
383
|
+
services: own.services,
|
|
384
|
+
actions: own.actions,
|
|
385
|
+
interceptors: own.interceptors,
|
|
386
|
+
contributions: own.contributions,
|
|
387
|
+
plugins,
|
|
388
|
+
configOverrides: options.configOverrides,
|
|
389
|
+
}
|
|
390
|
+
: { plugins: [own, ...plugins], configOverrides: options.configOverrides };
|
|
391
|
+
const identities = new WeakMap();
|
|
392
|
+
const provider = { resolve: (request) => identities.get(request) ?? { user: null } };
|
|
393
|
+
const server = createServer(config, {
|
|
394
|
+
services: { ...options.services, [requestContext]: provider },
|
|
395
|
+
});
|
|
396
|
+
let completion;
|
|
397
|
+
const release = () => (completion ??= server.stop());
|
|
398
|
+
try {
|
|
399
|
+
await server.ready;
|
|
400
|
+
} catch (error) {
|
|
401
|
+
try {
|
|
402
|
+
await release();
|
|
403
|
+
} catch (cleanupError) {
|
|
404
|
+
throw new AggregateError([error, cleanupError], 'Server startup and cleanup failed.');
|
|
405
|
+
}
|
|
406
|
+
throw error;
|
|
407
|
+
}
|
|
408
|
+
return {
|
|
409
|
+
id: main.id,
|
|
410
|
+
server,
|
|
411
|
+
/** An in-process caller with this identity: `as(identity({ organization: 'org-1' })).todos.add(input)`. */
|
|
412
|
+
as(who) {
|
|
413
|
+
if (!who || typeof who !== 'object')
|
|
414
|
+
throw new TypeError(
|
|
415
|
+
'as() takes an identity: as(identity({ organization: "org-1" })), or identity({ user: null }) for a signed-out caller.',
|
|
416
|
+
);
|
|
417
|
+
const request = new Request('http://bitakit.test/');
|
|
418
|
+
identities.set(request, who);
|
|
419
|
+
return server.as(request);
|
|
420
|
+
},
|
|
421
|
+
/** A server module as the mounted Actions and services see it (the same instance). */
|
|
422
|
+
import: (specifier) => load.module(specifier),
|
|
423
|
+
stop: release,
|
|
424
|
+
[Symbol.asyncDispose]: release,
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/** `'*'` or a list of operations, as `permissions` takes them per resource. */
|
|
429
|
+
function grants(listed, operations) {
|
|
430
|
+
if (listed === '*') return true;
|
|
431
|
+
return Array.isArray(listed) && operations.every((operation) => listed.includes(operation));
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* A test identity for `mountServer(...).as()`. `user` is a user ID or object (`null` signs out;
|
|
436
|
+
* default `{ id: 'user-1' }`); `organization` an organization ID or `{ id }` (a membership the
|
|
437
|
+
* provider verified); `member` the membership record. `can` grants exactly the listed
|
|
438
|
+
* `permissions` (`{ todos: ['create'] }`; `'*'` grants every resource, a resource's `'*'` every
|
|
439
|
+
* operation) and nothing else. `reason` explains a missing organization.
|
|
440
|
+
*/
|
|
441
|
+
export function identity({ user, organization, member, permissions, reason } = {}) {
|
|
442
|
+
if (
|
|
443
|
+
permissions !== undefined &&
|
|
444
|
+
permissions !== '*' &&
|
|
445
|
+
(!permissions ||
|
|
446
|
+
typeof permissions !== 'object' ||
|
|
447
|
+
Array.isArray(permissions) ||
|
|
448
|
+
Object.values(permissions).some((listed) => listed !== '*' && !Array.isArray(listed)))
|
|
449
|
+
)
|
|
450
|
+
throw new TypeError(
|
|
451
|
+
"identity(): permissions is '*' or { <resource>: ['<operation>', ...] | '*' }.",
|
|
452
|
+
);
|
|
453
|
+
const can = (request) => {
|
|
454
|
+
if (permissions === '*') return true;
|
|
455
|
+
const entries = Object.entries(request ?? {});
|
|
456
|
+
return (
|
|
457
|
+
entries.length > 0 &&
|
|
458
|
+
entries.every(
|
|
459
|
+
([resource, operations]) =>
|
|
460
|
+
Object.hasOwn(permissions ?? {}, resource) &&
|
|
461
|
+
Array.isArray(operations) &&
|
|
462
|
+
grants(permissions[resource], operations),
|
|
463
|
+
)
|
|
464
|
+
);
|
|
465
|
+
};
|
|
466
|
+
return {
|
|
467
|
+
user:
|
|
468
|
+
user === null ? null : typeof user === 'string' ? { id: user } : (user ?? { id: 'user-1' }),
|
|
469
|
+
organization:
|
|
470
|
+
organization === undefined || organization === null
|
|
471
|
+
? null
|
|
472
|
+
: typeof organization === 'string'
|
|
473
|
+
? { id: organization }
|
|
474
|
+
: organization,
|
|
475
|
+
member: member ?? null,
|
|
476
|
+
...(reason === undefined ? {} : { reason }),
|
|
477
|
+
can,
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
|
|
146
481
|
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
|
|
147
482
|
|
|
148
483
|
/** Waits until `ready()` holds, failing with `message` after `timeout` milliseconds. */
|