@vanillabp/bc-module-host 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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
package/NOTICE ADDED
@@ -0,0 +1,17 @@
1
+ NOTICE file corresponding to the section 4 (d) of the Apache License, Version 2.0.
2
+
3
+ The software components provided as part of the "VanillaBP Business Cockpit Module Kit"
4
+ were developed by Phactum Softwareentwicklung GmbH (https://www.phactum.at/).
5
+
6
+ Please read the LICENSE file present in this source distribution.
7
+
8
+ You may not use files provided except in compliance with the License.
9
+ You may obtain a copy of the License at
10
+
11
+ http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ Unless required by applicable law or agreed to in writing, software
14
+ distributed under the License is distributed on an "AS IS" BASIS,
15
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ See the License for the specific language governing permissions and
17
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,9 @@
1
+ # @vanillabp/bc-module-host
2
+
3
+ A minimal host which loads the parts of a VanillaBP workflow module the way a Business Cockpit does:
4
+ a registry of modules, one loader for `bc-manifest.json` and `import()`, the steps ask, load and
5
+ draw, and the cockpit's side of the event protocol. It is for the tests of a module, not for
6
+ production.
7
+
8
+ How to use it is in the
9
+ [README of the repository](https://github.com/vanillabp/business-cockpit-module-kit#readme).
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@vanillabp/bc-module-host",
3
+ "version": "0.1.0-snapshot.0",
4
+ "description": "A minimal host which loads the parts of VanillaBP workflow modules the way a Business Cockpit does. For tests of a module, not for production.",
5
+ "license": "Apache-2.0",
6
+ "author": "Phactum Softwareentwicklung GmbH (https://www.phactum.at/)",
7
+ "homepage": "https://www.vanillabp.io",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/vanillabp/business-cockpit-module-kit.git",
11
+ "directory": "packages/bc-module-host"
12
+ },
13
+ "keywords": [
14
+ "vanillabp",
15
+ "business-cockpit",
16
+ "workflow",
17
+ "testing"
18
+ ],
19
+ "type": "module",
20
+ "sideEffects": false,
21
+ "engines": {
22
+ "node": ">=24"
23
+ },
24
+ "exports": {
25
+ ".": {
26
+ "types": "./src/index.d.ts",
27
+ "default": "./src/index.js"
28
+ },
29
+ "./package.json": "./package.json"
30
+ },
31
+ "types": "./src/index.d.ts",
32
+ "files": [
33
+ "src",
34
+ "NOTICE"
35
+ ],
36
+ "dependencies": {
37
+ "@vanillabp/bc-module-kit": "0.1.0-snapshot.0"
38
+ },
39
+ "scripts": {
40
+ "test": "node --test \"test/**/*.test.js\""
41
+ }
42
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,109 @@
1
+ import type { BcManifest, BcPageParts, GuiApiData } from '@vanillabp/bc-module-kit';
2
+
3
+ /** A workflow module as `GET /gui/api/v1/workflow-module` lists it. An empty `uri` means nothing to load. */
4
+ export interface WorkflowModule {
5
+ id: string;
6
+ version?: string;
7
+ uri?: string;
8
+ }
9
+
10
+ /** What an action handler gets besides the `args` of the request. */
11
+ export interface ActionContext {
12
+ moduleId: string;
13
+ /** The area of the element that asked; 'all' for an all-in-one form. */
14
+ area: string;
15
+ element: HTMLElement;
16
+ }
17
+
18
+ /** Runs an action of the event protocol. Throw a `BcRefusedError` to answer with `REFUSED`. */
19
+ export type ActionHandler = (args: Record<string, any>, context: ActionContext) => unknown | Promise<unknown>;
20
+
21
+ export interface ModuleHostOptions {
22
+ /** The address the module paths `/wm/<id>/` are resolved against; by default the page's address. */
23
+ baseUrl?: string;
24
+ /** The modules of the registry. Without them, `loadModules` gives the list. */
25
+ modules?: WorkflowModule[];
26
+ /** Like `GET /gui/api/v1/workflow-module`; called once. */
27
+ loadModules?: () => WorkflowModule[] | Promise<WorkflowModule[]>;
28
+ /** Like `GET /gui/api/v1/workflow-module/{id}`, for a module which registered later. */
29
+ loadModule?: (moduleId: string) => WorkflowModule | undefined | Promise<WorkflowModule | undefined>;
30
+ fetch?: typeof fetch;
31
+ /** Replaces `import()`, for example in a test under Node.js. */
32
+ importModule?: (url: string) => Promise<any>;
33
+ /** How long the host waits for a web component; by default 10 seconds. */
34
+ whenDefinedTimeoutMs?: number;
35
+ /** The actions the host runs besides the page and dialog actions it brings itself. */
36
+ actions?: Record<string, ActionHandler>;
37
+ /** Properties every drawn web component gets, for example `language` and `currentUser`. */
38
+ properties?: Record<string, unknown>;
39
+ /**
40
+ * Data entries this host knows besides the four of the kit: entry -> the name of the function
41
+ * it exports, for example `{ Header: 'header' }`. The host asks no other entry.
42
+ */
43
+ entries?: Record<string, string>;
44
+ /**
45
+ * The areas of the page of a user task or a case, for example `['body', 'actions']`. The host
46
+ * draws the areas it knows and ignores the others. Without areas, or when a module offers none
47
+ * of them, it draws the web component of 'all'. By default there are none.
48
+ */
49
+ areas?: string[];
50
+ /** Where dialogs go; by default `document.body`. */
51
+ dialogContainer?: Element;
52
+ logger?: Pick<Console, 'warn' | 'error'>;
53
+ }
54
+
55
+ /** The web components of one part in the page. */
56
+ export interface DrawnPart {
57
+ /** Area -> web component. A form shown as one web component has the one area 'all'. */
58
+ elements: Map<string, HTMLElement>;
59
+ /** Sets properties on every web component again, for example a changed user task. */
60
+ update(properties: Record<string, unknown>): void;
61
+ /** Takes the web components out of the page and drops their subscriptions. */
62
+ remove(): void;
63
+ }
64
+
65
+ export interface ModuleHost {
66
+ registry: {
67
+ load(): Promise<void>;
68
+ list(): WorkflowModule[];
69
+ get(moduleId: string): WorkflowModule | undefined;
70
+ ensure(moduleId: string): Promise<WorkflowModule | undefined>;
71
+ };
72
+ readManifest(moduleId: string): Promise<BcManifest | undefined>;
73
+ loadEntry(moduleId: string, entry: string): Promise<any>;
74
+ /** The areas this host knows, besides 'all'. */
75
+ readonly areas: readonly string[];
76
+ /** The data entries this host asks. */
77
+ readonly entries: readonly string[];
78
+ /** Area -> web component: what `draw` shows of what a data entry offers. */
79
+ pickAreas(element: BcPageParts['element']): Record<string, string>;
80
+ /** undefined for an entry this host does not know, or which the module does not offer. */
81
+ ask(moduleId: string, entry: string, args?: unknown[]): Promise<any>;
82
+ load(moduleId: string, entry: string, elements: string[]): Promise<void>;
83
+ draw(part: {
84
+ moduleId: string;
85
+ entry: string;
86
+ element: BcPageParts['element'];
87
+ container: Element;
88
+ properties?: Record<string, unknown>;
89
+ }): DrawnPart;
90
+ showUserTask(moduleId: string, userTask: GuiApiData, container: Element, properties?: Record<string, unknown>): Promise<DrawnPart | undefined>;
91
+ showWorkflow(moduleId: string, workflow: GuiApiData, container: Element, properties?: Record<string, unknown>): Promise<DrawnPart | undefined>;
92
+ }
93
+
94
+ export declare const DEFAULT_WHEN_DEFINED_TIMEOUT_MS: 10000;
95
+
96
+ export declare class BcHostError extends Error {
97
+ readonly step: 'ask' | 'load' | 'draw';
98
+ readonly moduleId: string;
99
+ readonly entry?: string;
100
+ readonly element?: string;
101
+ }
102
+
103
+ export declare class BcRefusedError extends Error {
104
+ readonly code: 'REFUSED';
105
+ readonly status: number;
106
+ constructor(status: number, message?: string);
107
+ }
108
+
109
+ export declare function createModuleHost(options?: ModuleHostOptions): ModuleHost;
package/src/index.js ADDED
@@ -0,0 +1,412 @@
1
+ /**
2
+ * A minimal host for the parts of workflow modules. It does what a cockpit does to load them:
3
+ * a registry of modules, one loader that reads the manifests and calls import(), the three steps
4
+ * ask, load and draw, and the cockpit's side of the event protocol. It is a reference for tests,
5
+ * not a cockpit: it has no lists, no routing and no login.
6
+ *
7
+ * By default it is a cockpit with the minimum of the contract: the four entries of the kit and
8
+ * the area `all`. Options add entries like `Header` and areas like `body` and `actions`. Entries
9
+ * and areas the host does not know are ignored, without an error.
10
+ *
11
+ * @module @vanillabp/bc-module-host
12
+ */
13
+
14
+ import {
15
+ ACTIONS,
16
+ AREA_ALL,
17
+ ERROR_CODES,
18
+ EXPORT_NAMES,
19
+ MANIFEST_FILE_NAME,
20
+ MESSAGE_EVENT,
21
+ REQUEST_EVENT,
22
+ RESPONSE_EVENT,
23
+ USER_TASK_FORM,
24
+ WORKFLOW_PAGE,
25
+ entryUrl,
26
+ readManifest,
27
+ } from '@vanillabp/bc-module-kit';
28
+
29
+ /** How long the host waits for a web component to be defined, in milliseconds. */
30
+ export const DEFAULT_WHEN_DEFINED_TIMEOUT_MS = 10_000;
31
+
32
+ /** A step of ask, load and draw that failed. */
33
+ export class BcHostError extends Error {
34
+ /**
35
+ * @param {{ step: 'ask' | 'load' | 'draw', moduleId: string, entry?: string, element?: string, message: string, cause?: unknown }} details
36
+ */
37
+ constructor({ step, moduleId, entry, element, message, cause }) {
38
+ super(message, { cause });
39
+ this.name = 'BcHostError';
40
+ this.step = step;
41
+ this.moduleId = moduleId;
42
+ this.entry = entry;
43
+ this.element = element;
44
+ }
45
+ }
46
+
47
+ /** An error an action handler throws to answer with `REFUSED` and an HTTP status. */
48
+ export class BcRefusedError extends Error {
49
+ /**
50
+ * @param {number} status
51
+ * @param {string} [message]
52
+ */
53
+ constructor(status, message) {
54
+ super(message ?? `refused with HTTP status ${status}`);
55
+ this.name = 'BcRefusedError';
56
+ this.code = ERROR_CODES.REFUSED;
57
+ this.status = status;
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Creates a host.
63
+ *
64
+ * @param {import('./index.js').ModuleHostOptions} [options]
65
+ * @returns {import('./index.js').ModuleHost}
66
+ */
67
+ export function createModuleHost(options = {}) {
68
+ const {
69
+ baseUrl = globalThis.location?.href,
70
+ fetch: fetchFn = globalThis.fetch?.bind(globalThis),
71
+ importModule = (url) => import(/* @vite-ignore */ /* webpackIgnore: true */ url),
72
+ loadModules,
73
+ loadModule,
74
+ whenDefinedTimeoutMs = DEFAULT_WHEN_DEFINED_TIMEOUT_MS,
75
+ actions = {},
76
+ logger = globalThis.console,
77
+ dialogContainer,
78
+ entries: extraEntries = {},
79
+ areas: pageAreas = [],
80
+ } = options;
81
+
82
+ /** @type {Record<string, string>} data entry -> the name of the function it exports */
83
+ const knownEntries = { ...EXPORT_NAMES, ...extraEntries };
84
+
85
+ /** @type {Map<string, { id: string, uri?: string, version?: string }>} */
86
+ const modules = new Map((options.modules ?? []).map((module) => [module.id, module]));
87
+ /** @type {Map<string, Promise<{ manifest: any, url: string } | undefined>>} */
88
+ const manifests = new Map();
89
+ /** @type {Map<string, Promise<any>>} */
90
+ const loadedEntries = new Map();
91
+ let registryLoaded = options.modules ? Promise.resolve() : undefined;
92
+
93
+ const manifestUrlOf = (moduleId) => new URL(`/wm/${encodeURIComponent(moduleId)}/${MANIFEST_FILE_NAME}`, baseUrl).href;
94
+
95
+ const registry = {
96
+ /** Reads the modules once, like `GET /gui/api/v1/workflow-module`. */
97
+ load() {
98
+ registryLoaded ??= Promise.resolve(loadModules?.() ?? []).then((list) => {
99
+ for (const module of list) modules.set(module.id, module);
100
+ });
101
+ return registryLoaded;
102
+ },
103
+ list: () => [...modules.values()],
104
+ get: (moduleId) => modules.get(moduleId),
105
+ /** Adds a module which registered after the page loaded, like `GET /gui/api/v1/workflow-module/{id}`. */
106
+ async ensure(moduleId) {
107
+ await registry.load();
108
+ if (!modules.has(moduleId) && loadModule) {
109
+ const module = await loadModule(moduleId);
110
+ if (module) modules.set(module.id, module);
111
+ }
112
+ return modules.get(moduleId);
113
+ },
114
+ };
115
+
116
+ /**
117
+ * Reads the manifest of a module once. A module without a manifest (404) has no parts, and the
118
+ * host does not ask again. Any other failure is forgotten, so the next call asks again.
119
+ */
120
+ function readManifestOf(moduleId) {
121
+ let promise = manifests.get(moduleId);
122
+ if (!promise) {
123
+ const url = manifestUrlOf(moduleId);
124
+ promise = (async () => {
125
+ const module = await registry.ensure(moduleId);
126
+ if (module && module.uri === '') return undefined;
127
+ const response = await fetchFn(url, { cache: 'no-cache' });
128
+ if (response.status === 404) return undefined;
129
+ if (!response.ok) throw new Error(`${url} answered with HTTP status ${response.status}`);
130
+ return { manifest: readManifest(await response.text()), url };
131
+ })();
132
+ manifests.set(moduleId, promise);
133
+ promise.catch(() => manifests.delete(moduleId));
134
+ }
135
+ return promise;
136
+ }
137
+
138
+ /**
139
+ * Loads an entry of a module once and returns its exports, or `undefined` when the module's
140
+ * manifest does not name it. A failed load is forgotten, so a retry reads the manifest again
141
+ * and calls import() again.
142
+ *
143
+ * @param {string} moduleId
144
+ * @param {string} entry
145
+ */
146
+ function loadEntry(moduleId, entry) {
147
+ const key = `${moduleId}\n${entry}`;
148
+ let promise = loadedEntries.get(key);
149
+ if (!promise) {
150
+ promise = (async () => {
151
+ const read = await readManifestOf(moduleId);
152
+ if (!read) return undefined;
153
+ const url = entryUrl(read.manifest, entry, read.url);
154
+ if (!url) return undefined;
155
+ return importModule(url);
156
+ })();
157
+ loadedEntries.set(key, promise);
158
+ promise.catch(() => {
159
+ loadedEntries.delete(key);
160
+ manifests.delete(moduleId);
161
+ });
162
+ }
163
+ return promise;
164
+ }
165
+
166
+ /**
167
+ * Step one: ask a data entry. Calls its function with the arguments and returns the answer, or
168
+ * `undefined` when the module does not name the entry or does not export the function. An entry
169
+ * this host does not know is not loaded at all, and the answer is `undefined` as well.
170
+ *
171
+ * @param {string} moduleId
172
+ * @param {string} entry a data entry, for example `UserTaskForm`
173
+ * @param {unknown[]} args
174
+ */
175
+ async function ask(moduleId, entry, args = []) {
176
+ const exportName = knownEntries[entry];
177
+ if (exportName === undefined) return undefined;
178
+ let exports;
179
+ try {
180
+ exports = await loadEntry(moduleId, entry);
181
+ } catch (cause) {
182
+ throw new BcHostError({ step: 'ask', moduleId, entry, message: `The data entry ${entry} of the module ${moduleId} failed to load`, cause });
183
+ }
184
+ if (!exports) return undefined;
185
+ const fn = exports[exportName];
186
+ if (typeof fn !== 'function') {
187
+ logger?.warn?.(`The module ${moduleId} names the entry ${entry}, but it does not export the function ${exportName}`);
188
+ return undefined;
189
+ }
190
+ return fn(...args);
191
+ }
192
+
193
+ /** Waits for a web component, at most `whenDefinedTimeoutMs`. */
194
+ function whenDefined(name) {
195
+ let timer;
196
+ return Promise.race([
197
+ customElements.whenDefined(name).then(() => true),
198
+ new Promise((resolve) => { timer = setTimeout(() => resolve(false), whenDefinedTimeoutMs); }),
199
+ ]).finally(() => clearTimeout(timer));
200
+ }
201
+
202
+ /**
203
+ * Step two: load the visual entry and wait for every web component it should define.
204
+ *
205
+ * @param {string} moduleId
206
+ * @param {string} entry
207
+ * @param {string[]} names
208
+ */
209
+ async function load(moduleId, entry, names) {
210
+ let exports;
211
+ try {
212
+ exports = await loadEntry(moduleId, entry);
213
+ } catch (cause) {
214
+ throw new BcHostError({ step: 'load', moduleId, entry, message: `The visual entry ${entry} of the module ${moduleId} failed to load`, cause });
215
+ }
216
+ if (exports === undefined) {
217
+ throw new BcHostError({ step: 'load', moduleId, entry, message: `The module ${moduleId} does not name the visual entry ${entry} in its manifest` });
218
+ }
219
+ for (const name of names) {
220
+ if (!(await whenDefined(name))) {
221
+ const message = `The visual entry ${entry} of the module ${moduleId} did not define the web component ${name} within ${whenDefinedTimeoutMs} ms`;
222
+ logger?.error?.(message);
223
+ throw new BcHostError({ step: 'load', moduleId, entry, element: name, message });
224
+ }
225
+ }
226
+ }
227
+
228
+ /**
229
+ * Picks the web components to show from what a data entry offers. The areas this host knows
230
+ * come first; the areas it does not know are ignored. When none of its areas is offered, or
231
+ * it has no areas, it shows the web component of `all`.
232
+ *
233
+ * @param {string | Record<string, string>} element
234
+ * @returns {Record<string, string>} area -> web component; empty when nothing fits
235
+ */
236
+ function pickAreas(element) {
237
+ const offered = typeof element === 'string' ? { [AREA_ALL]: element } : (element ?? {});
238
+ const known = pageAreas.filter((area) => area !== AREA_ALL && typeof offered[area] === 'string');
239
+ if (known.length > 0) return Object.fromEntries(known.map((area) => [area, offered[area]]));
240
+ return typeof offered[AREA_ALL] === 'string' ? { [AREA_ALL]: offered[AREA_ALL] } : {};
241
+ }
242
+
243
+ let nextSubscriptionId = 0;
244
+
245
+ /**
246
+ * Step three: draw web components into a container and run the cockpit's side of the event
247
+ * protocol for them. Run `load` before. Which areas are drawn follows `pickAreas`.
248
+ *
249
+ * @param {{ moduleId: string, entry: string, element: string | Record<string, string>, container: Element, properties?: Record<string, unknown> }} part
250
+ */
251
+ function draw({ moduleId, entry, element, container, properties = {} }) {
252
+ const areas = pickAreas(element);
253
+ /** @type {Map<string, HTMLElement>} */
254
+ const elements = new Map();
255
+ /** @type {Map<string, string>} area -> subscription id */
256
+ const subscriptions = new Map();
257
+ /** @type {Map<string, Array<{ from: string, message: unknown }>>} messages kept until their area subscribes */
258
+ const waiting = new Map();
259
+ /** @type {Array<() => void>} */
260
+ const cleanups = [];
261
+
262
+ const deliver = (area, from, message) => {
263
+ const subscriptionId = subscriptions.get(area);
264
+ if (subscriptionId === undefined) {
265
+ if (!waiting.has(area)) waiting.set(area, []);
266
+ waiting.get(area).push({ from, message });
267
+ return;
268
+ }
269
+ elements.get(area)?.dispatchEvent(new CustomEvent(MESSAGE_EVENT, { detail: { subscriptionId, from, message } }));
270
+ };
271
+
272
+ const pageActions = {
273
+ [ACTIONS.PAGE_SEND_TO]: ({ target, message }, { area }) => {
274
+ if (!elements.has(target)) throw Object.assign(new Error(`This page has no area ${target}`), { code: ERROR_CODES.NO_TARGET });
275
+ deliver(target, area, structuredClone(message));
276
+ },
277
+ [ACTIONS.PAGE_SUBSCRIBE]: (_args, { area }) => {
278
+ nextSubscriptionId += 1;
279
+ const subscriptionId = `subscription-${nextSubscriptionId}`;
280
+ subscriptions.set(area, subscriptionId);
281
+ // The kept messages follow the answer, so the part knows its subscription id by then.
282
+ setTimeout(() => {
283
+ for (const { from, message } of waiting.get(area)?.splice(0) ?? []) deliver(area, from, message);
284
+ });
285
+ return { subscriptionId };
286
+ },
287
+ [ACTIONS.PAGE_UNSUBSCRIBE]: ({ subscriptionId }, { area }) => {
288
+ if (subscriptions.get(area) === subscriptionId) subscriptions.delete(area);
289
+ },
290
+ };
291
+
292
+ for (const [area, name] of Object.entries(areas)) {
293
+ let created;
294
+ try {
295
+ created = document.createElement(name);
296
+ Object.assign(created, properties, { area });
297
+ } catch (cause) {
298
+ throw new BcHostError({ step: 'draw', moduleId, entry, element: name, message: `Creating the web component ${name} of the module ${moduleId} failed`, cause });
299
+ }
300
+ const onRequest = (event) => answer(created, event.detail, { moduleId, area, page: pageActions });
301
+ created.addEventListener(REQUEST_EVENT, onRequest);
302
+ cleanups.push(() => created.removeEventListener(REQUEST_EVENT, onRequest));
303
+ elements.set(area, created);
304
+ }
305
+ for (const [area, created] of elements) {
306
+ const slot = container.querySelector(`[data-bc-area="${area}"]`) ?? container;
307
+ slot.append(created);
308
+ if (!created.shadowRoot) {
309
+ logger?.warn?.(`The web component ${created.localName} of the module ${moduleId} has no open shadow root`);
310
+ }
311
+ }
312
+ return {
313
+ elements,
314
+ update(changed) {
315
+ for (const created of elements.values()) Object.assign(created, changed);
316
+ },
317
+ remove() {
318
+ for (const cleanup of cleanups.splice(0)) cleanup();
319
+ subscriptions.clear();
320
+ waiting.clear();
321
+ for (const created of elements.values()) created.remove();
322
+ },
323
+ };
324
+ }
325
+
326
+ /** @type {Map<HTMLElement, (result: unknown) => void>} open dialogs: element -> resolve */
327
+ const dialogs = new Map();
328
+
329
+ const cockpitActions = {
330
+ [ACTIONS.COCKPIT_OPEN_DIALOG]: async ({ element: name, entry, data }, { moduleId }) => {
331
+ await load(moduleId, entry, [name]);
332
+ const layer = document.createElement('dialog');
333
+ layer.setAttribute('data-bc-dialog', name);
334
+ (dialogContainer ?? document.body).append(layer);
335
+ const part = draw({ moduleId, entry, element: name, container: layer, properties: { ...options.properties, workflowModule: registry.get(moduleId), data } });
336
+ layer.showModal?.();
337
+ const [created] = part.elements.values();
338
+ return new Promise((resolve) => {
339
+ dialogs.set(created, (result) => {
340
+ dialogs.delete(created);
341
+ resolve(result);
342
+ // The answer to closeDialog goes out first. Removed before it, the web component would
343
+ // see its request fail with DISCONNECTED.
344
+ setTimeout(() => {
345
+ part.remove();
346
+ layer.remove();
347
+ });
348
+ });
349
+ });
350
+ },
351
+ [ACTIONS.COCKPIT_CLOSE_DIALOG]: ({ result }, { element }) => {
352
+ const close = dialogs.get(element);
353
+ if (!close) throw Object.assign(new Error('This element is not shown in a dialog'), { code: ERROR_CODES.FAILED });
354
+ close(result);
355
+ },
356
+ };
357
+
358
+ /**
359
+ * Answers one request exactly once, on the element it came from.
360
+ */
361
+ async function answer(element, detail, { moduleId, area, page }) {
362
+ if (!detail || typeof detail.requestId !== 'string') return;
363
+ const { requestId, action, args = {} } = detail;
364
+ const respond = (body) => element.dispatchEvent(new CustomEvent(RESPONSE_EVENT, { detail: { requestId, ...body } }));
365
+ const handler = page[action] ?? cockpitActions[action] ?? actions[action];
366
+ if (!handler) {
367
+ respond({ ok: false, error: { code: ERROR_CODES.UNKNOWN_ACTION, message: `This host does not know the action ${action}` } });
368
+ return;
369
+ }
370
+ try {
371
+ const result = await handler(args, { moduleId, area, element });
372
+ respond({ ok: true, result });
373
+ } catch (error) {
374
+ const code = error?.code && Object.values(ERROR_CODES).includes(error.code) ? error.code : ERROR_CODES.FAILED;
375
+ respond({ ok: false, error: { code, status: error?.status, message: error?.message } });
376
+ }
377
+ }
378
+
379
+ /**
380
+ * Ask, load and draw for the page of a user task or a case, in one call.
381
+ *
382
+ * @param {{ moduleId: string, entry: string, data: unknown, property: 'userTask' | 'workflow', container: Element, properties?: Record<string, unknown> }} request
383
+ */
384
+ async function showPage({ moduleId, entry, data, property, container, properties = {} }) {
385
+ const parts = await ask(moduleId, entry, [data]);
386
+ if (!parts) return undefined;
387
+ const names = Object.values(pickAreas(parts.element));
388
+ if (names.length === 0) {
389
+ const known = pageAreas.length > 0 ? `the areas ${pageAreas.join(', ')} or ${AREA_ALL}` : `the area ${AREA_ALL}`;
390
+ logger?.warn?.(`The module ${moduleId} offers no web component for ${known} in its entry ${entry}, so this host shows nothing`);
391
+ return undefined;
392
+ }
393
+ await load(moduleId, parts.entry, names);
394
+ return draw({ moduleId, entry: parts.entry, element: parts.element, container, properties: { ...options.properties, ...properties, [property]: data } });
395
+ }
396
+
397
+ return {
398
+ registry,
399
+ readManifest: (moduleId) => readManifestOf(moduleId).then((read) => read?.manifest),
400
+ loadEntry,
401
+ areas: Object.freeze([...pageAreas]),
402
+ entries: Object.freeze(Object.keys(knownEntries)),
403
+ pickAreas,
404
+ ask,
405
+ load,
406
+ draw,
407
+ showUserTask: (moduleId, userTask, container, properties) =>
408
+ showPage({ moduleId, entry: USER_TASK_FORM, data: userTask, property: 'userTask', container, properties }),
409
+ showWorkflow: (moduleId, workflow, container, properties) =>
410
+ showPage({ moduleId, entry: WORKFLOW_PAGE, data: workflow, property: 'workflow', container, properties }),
411
+ };
412
+ }