@vanillabp/bc-module-kit 0.0.0-stage → 0.1.0-snapshot.0

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.
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Builds the web component of a module's part from three plain functions, so a module writes no
3
+ * shadow root and no event protocol by hand.
4
+ *
5
+ * @module @vanillabp/bc-module-kit/define-element
6
+ */
7
+
8
+ import { closeDialog, openDialog, receiveMessage, rejectOpenRequests, requestFromCockpit, sendTo, showNotification, toBcUserTask, toBcWorkflow } from './protocol.js';
9
+
10
+ /** The properties every cockpit may set on a part's web component. */
11
+ export const HOST_PROPERTIES = Object.freeze(['userTask', 'workflow', 'area', 'language', 'currentUser', 'workflowModule', 'data']);
12
+
13
+ /**
14
+ * Defines a custom element under `name`. When the cockpit puts it into the page, it attaches an
15
+ * open shadow root and calls `mount` with the root and the properties. When the cockpit sets a
16
+ * property again, it calls `update` once per task. When the element leaves the page, it calls
17
+ * `unmount`, stops every subscription the part made and rejects every open request with
18
+ * `DISCONNECTED`.
19
+ *
20
+ * @param {string} name the name of the web component; by convention it starts with the module id
21
+ * @param {import('./index.js').BcElementFunctions} functions
22
+ * @param {{ properties?: string[] }} [options] further properties an extension point of this cockpit sets
23
+ * @returns {CustomElementConstructor}
24
+ */
25
+ export function defineBcElement(name, { mount, update, unmount }, options = {}) {
26
+ if (typeof globalThis.customElements === 'undefined') {
27
+ throw new Error('defineBcElement needs a browser: customElements does not exist here');
28
+ }
29
+ if (customElements.get(name)) {
30
+ throw new Error(`The web component "${name}" is defined already. Its name must start with the module id, so it is unique.`);
31
+ }
32
+ const properties = [...HOST_PROPERTIES, ...(options.properties ?? [])];
33
+
34
+ class BcElement extends HTMLElement {
35
+ /** @type {Record<string, unknown>} */
36
+ #values = {};
37
+ /** @type {Array<{ unsubscribe: () => Promise<void> }>} */
38
+ #subscriptions = [];
39
+ #mounted = false;
40
+ #updateQueued = false;
41
+
42
+ constructor() {
43
+ super();
44
+ // A value set before the element was upgraded sits on the instance and hides the accessor.
45
+ for (const property of properties) {
46
+ if (Object.hasOwn(this, property)) {
47
+ const value = this[property];
48
+ delete this[property];
49
+ this.#values[property] = value;
50
+ }
51
+ }
52
+ }
53
+
54
+ /** @param {string} property */
55
+ bcGet(property) {
56
+ return this.#values[property];
57
+ }
58
+
59
+ /** @param {string} property @param {unknown} value */
60
+ bcSet(property, value) {
61
+ this.#values[property] = value;
62
+ this.#changed();
63
+ }
64
+
65
+ connectedCallback() {
66
+ const root = this.shadowRoot ?? this.attachShadow({ mode: 'open' });
67
+ if (this.#mounted) return;
68
+ this.#mounted = true;
69
+ mount(root, this.#props());
70
+ }
71
+
72
+ disconnectedCallback() {
73
+ if (!this.#mounted) return;
74
+ this.#mounted = false;
75
+ rejectOpenRequests(this);
76
+ for (const subscription of this.#subscriptions.splice(0)) subscription.unsubscribe().catch(() => undefined);
77
+ unmount?.(/** @type {ShadowRoot} */ (this.shadowRoot));
78
+ }
79
+
80
+ /** Collects all changes of one task into one call of `update`. */
81
+ #changed() {
82
+ if (!this.#mounted || this.#updateQueued) return;
83
+ this.#updateQueued = true;
84
+ queueMicrotask(() => {
85
+ this.#updateQueued = false;
86
+ if (this.#mounted) update?.(/** @type {ShadowRoot} */ (this.shadowRoot), this.#props());
87
+ });
88
+ }
89
+
90
+ #props() {
91
+ const receive = (handler) => {
92
+ const subscription = receiveMessage(this, handler);
93
+ this.#subscriptions.push(subscription);
94
+ return subscription;
95
+ };
96
+ /** @type {Record<string, any>} */
97
+ const props = { ...this.#values };
98
+ if (props.userTask) props.userTask = { ...toBcUserTask(this, props.userTask), receiveMessage: receive };
99
+ if (props.workflow) props.workflow = { ...toBcWorkflow(this, props.workflow), receiveMessage: receive };
100
+ return {
101
+ ...props,
102
+ element: this,
103
+ showNotification: (notification) => showNotification(this, notification),
104
+ openDialog: (dialog, data) => openDialog(this, dialog, data),
105
+ closeDialog: (result) => closeDialog(this, result),
106
+ sendTo: (target, message) => sendTo(this, target, message),
107
+ receiveMessage: receive,
108
+ request: (action, args, timeoutMs) => requestFromCockpit(this, action, args, timeoutMs),
109
+ };
110
+ }
111
+ }
112
+
113
+ for (const property of properties) {
114
+ Object.defineProperty(BcElement.prototype, property, {
115
+ configurable: true,
116
+ enumerable: true,
117
+ get() {
118
+ return this.bcGet(property);
119
+ },
120
+ set(value) {
121
+ this.bcSet(property, value);
122
+ },
123
+ });
124
+ }
125
+
126
+ customElements.define(name, BcElement);
127
+ return BcElement;
128
+ }
package/src/entries.js ADDED
@@ -0,0 +1,46 @@
1
+ /**
2
+ * The names of the entries every cockpit knows, and the names of the functions those entries
3
+ * export. This is the minimum. A cockpit may know more entries and more areas of a page, for
4
+ * example a Header entry or the areas body, information and actions. Those differ from one
5
+ * organisation to the next, so they belong to the types library of that cockpit, not here.
6
+ *
7
+ * @module @vanillabp/bc-module-kit/entries
8
+ */
9
+
10
+ /** The columns of the task lists. The entry exports `userTaskListColumns`. */
11
+ export const USER_TASK_LIST = 'UserTaskList';
12
+
13
+ /** The columns of the case list. The entry exports `workflowListColumns`. */
14
+ export const WORKFLOW_LIST = 'WorkflowList';
15
+
16
+ /** The page of a user task. The entry exports `userTaskForm`. */
17
+ export const USER_TASK_FORM = 'UserTaskForm';
18
+
19
+ /** The page of a case. The entry exports `workflowPage`. */
20
+ export const WORKFLOW_PAGE = 'WorkflowPage';
21
+
22
+ /**
23
+ * The entries which carry no framework. `bc-check-entries` checks their size and their content.
24
+ * A module with entries of its own, for example `Header`, names them with the option
25
+ * `--data-entry` of `bc-check-entries`.
26
+ */
27
+ export const DATA_ENTRIES = Object.freeze([
28
+ USER_TASK_LIST,
29
+ WORKFLOW_LIST,
30
+ USER_TASK_FORM,
31
+ WORKFLOW_PAGE,
32
+ ]);
33
+
34
+ /** For each data entry, the name of the function it exports. */
35
+ export const EXPORT_NAMES = Object.freeze({
36
+ [USER_TASK_LIST]: 'userTaskListColumns',
37
+ [WORKFLOW_LIST]: 'workflowListColumns',
38
+ [USER_TASK_FORM]: 'userTaskForm',
39
+ [WORKFLOW_PAGE]: 'workflowPage',
40
+ });
41
+
42
+ /**
43
+ * The area of the one web component which shows the whole page. Every cockpit knows it. A
44
+ * cockpit without areas of its own shows this web component.
45
+ */
46
+ export const AREA_ALL = 'all';
package/src/index.d.ts ADDED
@@ -0,0 +1,223 @@
1
+ // Types of @vanillabp/bc-module-kit. The data of the GUI API (UserTask, Workflow, CurrentUser)
2
+ // comes from the types library of a generated cockpit. The kit only knows the fields it reads,
3
+ // so it takes them as generic records.
4
+
5
+ /** Data of the GUI API: a user task, a case or the current user, as plain JSON. */
6
+ export type GuiApiData = { id?: string; [field: string]: any };
7
+
8
+ // --- entries ---------------------------------------------------------------------------------
9
+
10
+ export declare const USER_TASK_LIST: 'UserTaskList';
11
+ export declare const WORKFLOW_LIST: 'WorkflowList';
12
+ export declare const USER_TASK_FORM: 'UserTaskForm';
13
+ export declare const WORKFLOW_PAGE: 'WorkflowPage';
14
+ export declare const DATA_ENTRIES: readonly ['UserTaskList', 'WorkflowList', 'UserTaskForm', 'WorkflowPage'];
15
+ export declare const EXPORT_NAMES: Readonly<{
16
+ UserTaskList: 'userTaskListColumns';
17
+ WorkflowList: 'workflowListColumns';
18
+ UserTaskForm: 'userTaskForm';
19
+ WorkflowPage: 'workflowPage';
20
+ }>;
21
+ export declare const AREA_ALL: 'all';
22
+
23
+ /** A text per language. The keys are language codes like 'en' or 'de'. */
24
+ export interface Translatable {
25
+ [languageKey: string]: string;
26
+ }
27
+
28
+ export interface Column {
29
+ title: Translatable;
30
+ /** Path of the value within the user task or the case. */
31
+ path: string;
32
+ type?: 'value' | 'i18n' | 'person' | 'date' | 'date-time' | 'time';
33
+ priority: number;
34
+ width: string;
35
+ show: boolean;
36
+ sortable: boolean;
37
+ filterable: boolean;
38
+ resizeable: boolean;
39
+ }
40
+
41
+ /** A web component that a data entry names, and the visual entry that defines it. */
42
+ export interface BcElementRef {
43
+ element: string;
44
+ entry: string;
45
+ }
46
+
47
+ /**
48
+ * Area -> name of a web component. 'all' is the one every cockpit knows. A cockpit may know more
49
+ * areas, for example 'body' and 'actions'. It shows the areas it knows and ignores the others.
50
+ * Without areas of its own it shows the web component of 'all'.
51
+ */
52
+ export type PageAreas = { [area: string]: string };
53
+
54
+ /** One web component (the area 'all'), or one per area. */
55
+ export interface BcPageParts {
56
+ element: string | PageAreas;
57
+ entry: string;
58
+ }
59
+
60
+ export type ColumnsOfUserTaskFunction<U = GuiApiData> = (userTask: U) => Column[] | undefined;
61
+ export type ColumnsOfWorkflowFunction<W = GuiApiData> = (workflow: W) => Column[] | undefined;
62
+ /** undefined: this user task is not the module's. */
63
+ export type UserTaskFormFunction<U = GuiApiData> = (userTask: U) => BcPageParts | undefined;
64
+ /** undefined: this case is not the module's. */
65
+ export type WorkflowPageFunction<W = GuiApiData> = (workflow: W) => BcPageParts | undefined;
66
+
67
+ // --- manifest --------------------------------------------------------------------------------
68
+
69
+ export interface BcManifest {
70
+ manifestVersion: 1;
71
+ buildVersion?: string;
72
+ buildTimestamp?: string;
73
+ /** Entry name -> file, relative to the manifest. */
74
+ entries: { readonly [entry: string]: string };
75
+ }
76
+
77
+ export declare const MANIFEST_FILE_NAME: 'bc-manifest.json';
78
+ export declare const MANIFEST_VERSION: 1;
79
+ export declare class BcManifestError extends Error {
80
+ readonly problems: string[];
81
+ constructor(problems: string[]);
82
+ }
83
+ export declare function checkManifest(manifest: unknown): string[];
84
+ export declare function readManifest(source: string | object): BcManifest;
85
+ export declare function createManifest(options: {
86
+ entries: Record<string, string>;
87
+ buildVersion?: string;
88
+ buildTimestamp?: string | Date;
89
+ }): BcManifest;
90
+ export declare function entryUrl(manifest: BcManifest, entry: string, manifestUrl: string | URL): string | undefined;
91
+
92
+ // --- event protocol --------------------------------------------------------------------------
93
+
94
+ export declare const REQUEST_EVENT: 'bc-request';
95
+ export declare const RESPONSE_EVENT: 'bc-response';
96
+ export declare const MESSAGE_EVENT: 'bc-message';
97
+ export declare const ACTIONS: Readonly<{
98
+ USER_TASK_OPEN: 'userTask.open';
99
+ USER_TASK_NAVIGATE_TO_WORKFLOW: 'userTask.navigateToWorkflow';
100
+ USER_TASK_CLAIM: 'userTask.claim';
101
+ USER_TASK_UNCLAIM: 'userTask.unclaim';
102
+ USER_TASK_ASSIGN: 'userTask.assign';
103
+ USER_TASK_UNASSIGN: 'userTask.unassign';
104
+ WORKFLOW_NAVIGATE_TO_WORKFLOW: 'workflow.navigateToWorkflow';
105
+ WORKFLOW_GET_USER_TASKS: 'workflow.getUserTasks';
106
+ PAGE_SEND_TO: 'page.sendTo';
107
+ PAGE_SUBSCRIBE: 'page.subscribe';
108
+ PAGE_UNSUBSCRIBE: 'page.unsubscribe';
109
+ COCKPIT_SHOW_NOTIFICATION: 'cockpit.showNotification';
110
+ COCKPIT_OPEN_DIALOG: 'cockpit.openDialog';
111
+ COCKPIT_CLOSE_DIALOG: 'cockpit.closeDialog';
112
+ }>;
113
+ export type BcErrorCode = 'UNKNOWN_ACTION' | 'REFUSED' | 'FAILED' | 'NO_TARGET' | 'TIMEOUT' | 'DISCONNECTED';
114
+ export declare const ERROR_CODES: Readonly<{ [Code in BcErrorCode]: Code }>;
115
+ export declare const DEFAULT_TIMEOUT_MS: 30000;
116
+ export declare const ACTIONS_WITHOUT_TIMEOUT: readonly string[];
117
+
118
+ /** The detail of a `bc-request` event. */
119
+ export interface BcRequest {
120
+ requestId: string;
121
+ action: string;
122
+ args: Record<string, unknown>;
123
+ }
124
+
125
+ /** The detail of a `bc-response` event. */
126
+ export type BcResponse =
127
+ | { requestId: string; ok: true; result?: unknown }
128
+ | { requestId: string; ok: false; error: { code: BcErrorCode | string; status?: number; message?: string } };
129
+
130
+ /** The detail of a `bc-message` event. */
131
+ export interface BcMessage {
132
+ subscriptionId: string;
133
+ from: string;
134
+ message: unknown;
135
+ }
136
+
137
+ export declare class BcRequestError extends Error {
138
+ readonly code: BcErrorCode | string;
139
+ readonly status?: number;
140
+ readonly action: string;
141
+ constructor(details: { code: string; message?: string; status?: number; action: string });
142
+ }
143
+
144
+ export interface BcSubscription {
145
+ /** Resolves once the cockpit delivers messages to this area. */
146
+ ready: Promise<void>;
147
+ /** Stops the delivery. */
148
+ unsubscribe: () => Promise<void>;
149
+ }
150
+
151
+ export interface BcPageMessaging {
152
+ sendTo: (target: string, message: unknown) => Promise<void>;
153
+ receiveMessage: (handler: (message: unknown, from: string) => void) => BcSubscription;
154
+ }
155
+
156
+ export type BcUserTask<U = GuiApiData> = U & BcPageMessaging & {
157
+ open: () => Promise<void>;
158
+ navigateToWorkflow: () => Promise<void>;
159
+ assign: (userId: string) => Promise<void>;
160
+ unassign: (userId: string) => Promise<void>;
161
+ claim: () => Promise<void>;
162
+ unclaim: () => Promise<void>;
163
+ };
164
+
165
+ export type BcWorkflow<W = GuiApiData, U = GuiApiData> = W & BcPageMessaging & {
166
+ navigateToWorkflow: () => Promise<void>;
167
+ getUserTasks: (activeOnly: boolean, limitListAccordingToCurrentUsersPermissions: boolean) => Promise<Array<BcUserTask<U>>>;
168
+ };
169
+
170
+ export interface BcNotification {
171
+ level: 'info' | 'success' | 'warning' | 'error';
172
+ /** In the language the part got as 'language'. */
173
+ text: string;
174
+ /** true: stays until the user clicks it away. */
175
+ sticky?: boolean;
176
+ }
177
+
178
+ export declare function requestFromCockpit(element: EventTarget, action: string, args?: Record<string, unknown>, timeoutMs?: number): Promise<unknown>;
179
+ export declare function rejectOpenRequests(element: EventTarget): void;
180
+ export declare function sendTo(element: EventTarget, target: string, message: unknown): Promise<void>;
181
+ export declare function receiveMessage(element: EventTarget, handler: (message: unknown, from: string) => void): BcSubscription;
182
+ export declare function showNotification(element: EventTarget, notification: BcNotification): Promise<void>;
183
+ export declare function openDialog(element: EventTarget, dialog: BcElementRef, data?: unknown): Promise<unknown>;
184
+ export declare function closeDialog(element: EventTarget, result?: unknown): Promise<void>;
185
+ export declare function toBcUserTask<U extends GuiApiData>(element: EventTarget, data: U): BcUserTask<U>;
186
+ export declare function toBcWorkflow<W extends GuiApiData>(element: EventTarget, data: W): BcWorkflow<W>;
187
+
188
+ // --- web components --------------------------------------------------------------------------
189
+
190
+ /** What `mount` and `update` get: the properties the cockpit set, and the functions of the cockpit. */
191
+ export interface BcElementProps {
192
+ /** On the page of a user task. */
193
+ userTask?: BcUserTask;
194
+ /** On the page of a case. */
195
+ workflow?: BcWorkflow;
196
+ /** The area of a page, or 'all' for an all-in-one form. */
197
+ area?: string;
198
+ language?: string;
199
+ currentUser?: GuiApiData;
200
+ /** For parts outside the pages of a user task and a case: id, version, uri. */
201
+ workflowModule?: { id: string; version?: string; uri?: string };
202
+ /** For a dialog: what `openDialog` handed over. */
203
+ data?: unknown;
204
+ /** The web component itself. */
205
+ element: HTMLElement;
206
+ showNotification: (notification: BcNotification) => Promise<void>;
207
+ openDialog: (dialog: BcElementRef, data?: unknown) => Promise<unknown>;
208
+ closeDialog: (result?: unknown) => Promise<void>;
209
+ sendTo: (target: string, message: unknown) => Promise<void>;
210
+ receiveMessage: (handler: (message: unknown, from: string) => void) => BcSubscription;
211
+ /** Any further action, for example one of an extension point of this cockpit. */
212
+ request: (action: string, args?: Record<string, unknown>, timeoutMs?: number) => Promise<unknown>;
213
+ [property: string]: unknown;
214
+ }
215
+
216
+ export interface BcElementFunctions {
217
+ mount: (root: ShadowRoot, props: BcElementProps) => void;
218
+ update?: (root: ShadowRoot, props: BcElementProps) => void;
219
+ unmount?: (root: ShadowRoot) => void;
220
+ }
221
+
222
+ export declare const HOST_PROPERTIES: readonly string[];
223
+ export declare function defineBcElement(name: string, functions: BcElementFunctions, options?: { properties?: string[] }): CustomElementConstructor;
package/src/index.js ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * The module's side of the contract between a VanillaBP Business Cockpit and a workflow module.
3
+ *
4
+ * @module @vanillabp/bc-module-kit
5
+ */
6
+
7
+ export * from './entries.js';
8
+ export * from './manifest.js';
9
+ export * from './protocol.js';
10
+ export * from './define-element.js';
@@ -0,0 +1,135 @@
1
+ /**
2
+ * The manifest of a workflow module, bc-manifest.json: which entries the module offers and in
3
+ * which files they are.
4
+ *
5
+ * @module @vanillabp/bc-module-kit/manifest
6
+ */
7
+
8
+ /** The fixed name of the manifest at the root of the module's web path. */
9
+ export const MANIFEST_FILE_NAME = 'bc-manifest.json';
10
+
11
+ /** The version of the manifest format this kit writes and reads. */
12
+ export const MANIFEST_VERSION = 1;
13
+
14
+ /** Thrown when a manifest breaks the format. `problems` lists every rule it breaks. */
15
+ export class BcManifestError extends Error {
16
+ /**
17
+ * @param {string[]} problems
18
+ */
19
+ constructor(problems) {
20
+ super(`bc-manifest.json is not valid:\n- ${problems.join('\n- ')}`);
21
+ this.name = 'BcManifestError';
22
+ this.problems = problems;
23
+ }
24
+ }
25
+
26
+ const SCHEME = /^[a-z][a-z0-9+.-]*:/i;
27
+
28
+ /**
29
+ * Says what is wrong with a file of the manifest. The file must stay below the module's web
30
+ * path, so it is relative and never climbs up with `..`.
31
+ *
32
+ * @param {unknown} file
33
+ * @returns {string | undefined}
34
+ */
35
+ function problemOfFile(file) {
36
+ if (typeof file !== 'string' || file.length === 0) return 'is not a non-empty string';
37
+ if (SCHEME.test(file) || file.startsWith('//')) return 'is a whole address, but it must be relative to the manifest';
38
+ if (file.startsWith('/')) return 'starts with "/", but it must be relative to the manifest';
39
+ const path = file.split(/[?#]/, 1)[0];
40
+ if (path.split('/').includes('..')) return 'leaves the module\'s web path with ".."';
41
+ return undefined;
42
+ }
43
+
44
+ /**
45
+ * Checks a parsed manifest and lists every rule it breaks. An empty list means the manifest is
46
+ * fine. Fields this version does not know are allowed and ignored.
47
+ *
48
+ * @param {unknown} manifest
49
+ * @returns {string[]}
50
+ */
51
+ export function checkManifest(manifest) {
52
+ if (manifest === null || typeof manifest !== 'object' || Array.isArray(manifest)) {
53
+ return ['the manifest is not a JSON object'];
54
+ }
55
+ const problems = [];
56
+ const { manifestVersion, buildVersion, buildTimestamp, entries } = /** @type {any} */ (manifest);
57
+ if (!Number.isInteger(manifestVersion) || manifestVersion < 1) {
58
+ problems.push('"manifestVersion" must be a whole number from 1 on');
59
+ } else if (manifestVersion > MANIFEST_VERSION) {
60
+ problems.push(`"manifestVersion" is ${manifestVersion}, but this kit only knows version ${MANIFEST_VERSION}`);
61
+ }
62
+ if (buildVersion !== undefined && typeof buildVersion !== 'string') {
63
+ problems.push('"buildVersion" must be a string');
64
+ }
65
+ if (buildTimestamp !== undefined && (typeof buildTimestamp !== 'string' || Number.isNaN(Date.parse(buildTimestamp)))) {
66
+ problems.push('"buildTimestamp" must be a date and time like 2026-10-16T09:30:00Z');
67
+ }
68
+ if (entries === null || typeof entries !== 'object' || Array.isArray(entries)) {
69
+ problems.push('"entries" must be an object of entry name to file');
70
+ return problems;
71
+ }
72
+ for (const [name, file] of Object.entries(entries)) {
73
+ if (name.length === 0) problems.push('an entry has an empty name');
74
+ if (name.startsWith('./')) {
75
+ problems.push(`the entry "${name}" starts with "./"; write "${name.slice(2)}" instead`);
76
+ }
77
+ const problem = problemOfFile(file);
78
+ if (problem) problems.push(`the file of the entry "${name}" ${problem}`);
79
+ }
80
+ return problems;
81
+ }
82
+
83
+ /**
84
+ * Reads a manifest from its JSON text or from the parsed object, checks it and returns a frozen
85
+ * copy.
86
+ *
87
+ * @param {string | object} source
88
+ * @returns {import('./index.js').BcManifest}
89
+ * @throws {BcManifestError} when the manifest breaks the format
90
+ */
91
+ export function readManifest(source) {
92
+ let manifest = source;
93
+ if (typeof source === 'string') {
94
+ try {
95
+ manifest = JSON.parse(source);
96
+ } catch (error) {
97
+ throw new BcManifestError([`the text is not JSON: ${/** @type {Error} */ (error).message}`]);
98
+ }
99
+ }
100
+ const problems = checkManifest(manifest);
101
+ if (problems.length > 0) throw new BcManifestError(problems);
102
+ const { entries, ...rest } = /** @type {any} */ (manifest);
103
+ return Object.freeze({ ...rest, entries: Object.freeze({ ...entries }) });
104
+ }
105
+
106
+ /**
107
+ * Builds the manifest a module's build writes. A build script passes the files its bundler wrote,
108
+ * relative to the folder of the manifest.
109
+ *
110
+ * @param {{ entries: Record<string, string>, buildVersion?: string, buildTimestamp?: string | Date }} options
111
+ * @returns {import('./index.js').BcManifest}
112
+ * @throws {BcManifestError} when an entry breaks the format
113
+ */
114
+ export function createManifest({ entries, buildVersion, buildTimestamp = new Date() }) {
115
+ const manifest = {
116
+ manifestVersion: MANIFEST_VERSION,
117
+ ...(buildVersion === undefined ? {} : { buildVersion }),
118
+ buildTimestamp: buildTimestamp instanceof Date ? buildTimestamp.toISOString() : buildTimestamp,
119
+ entries,
120
+ };
121
+ return readManifest(manifest);
122
+ }
123
+
124
+ /**
125
+ * The address of an entry's file, or `undefined` when the manifest does not name the entry.
126
+ *
127
+ * @param {import('./index.js').BcManifest} manifest
128
+ * @param {string} entry
129
+ * @param {string | URL} manifestUrl the address the manifest was read from
130
+ * @returns {string | undefined}
131
+ */
132
+ export function entryUrl(manifest, entry, manifestUrl) {
133
+ if (!Object.hasOwn(manifest.entries, entry)) return undefined;
134
+ return new URL(manifest.entries[entry], manifestUrl).href;
135
+ }