@open-pioneer/runtime 0.1.0 → 0.1.1
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/CHANGELOG.md +9 -0
- package/CustomElement.js.map +1 -1
- package/builtin-services/ApiServiceImpl.js.map +1 -1
- package/builtin-services/ApplicationContextImpl.js.map +1 -1
- package/builtin-services/ApplicationLifecycleEventService.js.map +1 -1
- package/builtin-services/index.js.map +1 -1
- package/errors.js.map +1 -1
- package/i18n.js.map +1 -1
- package/metadata/ObservableBox.js.map +1 -1
- package/package.json +3 -3
- package/react-integration/PackageContext.js.map +1 -1
- package/react-integration/ReactIntegration.js.map +1 -1
- package/react-integration/hooks.js.map +1 -1
- package/service-layer/InterfaceSpec.js.map +1 -1
- package/service-layer/PackageRepr.js.map +1 -1
- package/service-layer/ServiceLayer.js.map +1 -1
- package/service-layer/ServiceLookup.js.map +1 -1
- package/service-layer/ServiceRepr.js.map +1 -1
- package/service-layer/verifyDependencies.js.map +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
# @open-pioneer/runtime
|
|
2
2
|
|
|
3
|
+
## 0.1.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- e1c7295: Compiled with build-package 0.5.2
|
|
8
|
+
- Updated dependencies [e1c7295]
|
|
9
|
+
- @open-pioneer/chakra-integration@0.1.1
|
|
10
|
+
- @open-pioneer/core@0.1.1
|
|
11
|
+
|
|
3
12
|
## 0.1.0
|
|
4
13
|
|
|
5
14
|
### Minor Changes
|
package/CustomElement.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CustomElement.js","sources":["open-pioneer://external-pioneer-packages/@open-pioneer/runtime/CustomElement.ts"],"sourcesContent":["// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ComponentType } from \"react\";\nimport {\n createAbortError,\n createLogger,\n createManualPromise,\n destroyResource,\n Error,\n isAbortError,\n ManualPromise,\n Resource,\n throwAbortError\n} from \"@open-pioneer/core\";\nimport { ErrorId } from \"./errors\";\nimport { ApplicationMetadata, PackageMetadata } from \"./metadata\";\nimport { PackageRepr, createPackages } from \"./service-layer/PackageRepr\";\nimport { ServiceLayer } from \"./service-layer/ServiceLayer\";\nimport { getErrorChain } from \"@open-pioneer/core\";\nimport { ReactIntegration } from \"./react-integration/ReactIntegration\";\nimport { ApiMethods, ApiService } from \"./api\";\nimport {\n createBuiltinPackage,\n RUNTIME_API_SERVICE,\n RUNTIME_APPLICATION_LIFECYCLE_EVENT_SERVICE,\n RUNTIME_AUTO_START\n} from \"./builtin-services\";\nimport { ReferenceSpec } from \"./service-layer/InterfaceSpec\";\nimport { PropertiesRegistry } from \"./PropertiesRegistry\";\nimport { AppI18n, initI18n } from \"./i18n\";\nimport { ApplicationLifecycleEventService } from \"./builtin-services/ApplicationLifecycleEventService\";\nconst LOG = createLogger(\"runtime:CustomElement\");\n\n/**\n * Options for the {@link createCustomElement} function.\n */\nexport interface CustomElementOptions {\n /**\n * Rendered UI component.\n */\n component?: ComponentType<Record<string, string>>;\n\n /**\n * Application metadata (packages, services etc.).\n * This is usually autogenerated by importing the virtual `\"open-pioneer:app\"` module.\n */\n appMetadata?: ApplicationMetadata;\n\n /**\n * Application defined configuration.\n * All instances of the web component will share this static configuration.\n *\n * These will override default properties of the application's packages.\n */\n config?: ApplicationConfig;\n\n /**\n * Function to provide additional application defined configuration parameters.\n *\n * Compared to {@link config}, this function receives a context object\n * that allows the developer to provide dynamic properties on a per-application basis.\n *\n * Parameters returned by this function take precedence over the ones defined by {@link config}.\n */\n resolveConfig?(ctx: ConfigContext): Promise<ApplicationConfig | undefined>;\n\n /**\n * Whether the shadow root element is accessible from the outside.\n * Defaults to `false` in production mode and `true` during development to make testing easier.\n */\n openShadowRoot?: boolean;\n}\n\n/**\n * A context object that is passed to the `resolveProperties` function.\n */\nexport interface ConfigContext {\n /**\n * Returns an attribute from the application's root node.\n */\n getAttribute(name: string): string | undefined;\n}\n\n/**\n * Runtime application configuration.\n */\nexport interface ApplicationConfig {\n /**\n * Set this value to a locale string (e.g. \"en\") to for the application's locale.\n * The default behavior is to choose an appropriate locale for the current user based\n * on the browser's settings.\n *\n * The locale must be supported by the application.\n */\n locale?: string | undefined;\n\n /**\n * Properties specified here will override default properties of the application's packages.\n */\n properties?: ApplicationProperties | undefined;\n}\n\n/**\n * Allows the application to override default properties in all packages.\n */\nexport interface RawApplicationProperties {\n /**\n * Key: the name of the package.\n * Value: A record of configuration properties (key/value pairs).\n *\n * Properties will override default property values in the package.\n */\n [packageName: string]: Record<string, unknown>;\n}\n\n/**\n * Allows the application to override default properties in all packages.\n *\n * Properties are typed when the package contains type definitions for them.\n */\nexport type ApplicationProperties = RawApplicationProperties & Partial<PropertiesRegistry>;\n\n/**\n * The interface implemented by web components produced via {@link createCustomElement}.\n */\nexport interface ApplicationElement extends HTMLElement {\n /** Resolves to the element's API when the application has started. */\n when(): Promise<ApiMethods>;\n}\n\n/**\n * The class returned by a call to {@link createCustomElement}.\n */\nexport interface ApplicationElementConstructor {\n new (): ApplicationElement;\n}\n\n/**\n * Creates a new custom element class (web component) that can be registered within a DOM.\n *\n * @example\n * ```ts\n * import * as appMetadata from \"open-pioneer:app\";\n *\n * const CustomElementClazz = createCustomElement({\n * component: <div>Hello World!</div>,\n * appMetadata\n * });\n * customElements.define(\"sample-element\", CustomElementClazz);\n * ```\n */\nexport function createCustomElement(options: CustomElementOptions): ApplicationElementConstructor {\n class PioneerApplication extends HTMLElement implements ApplicationElement {\n #shadowRoot: ShadowRoot;\n #state: ElementState | undefined;\n\n static get observedAttributes(): string[] {\n return [];\n }\n\n constructor() {\n super();\n\n const mode = options.openShadowRoot ?? import.meta.env.DEV ? \"open\" : \"closed\";\n this.#shadowRoot = this.attachShadow({\n mode: mode\n });\n\n if (import.meta.env.DEV) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this as any).$inspectElementState = () => this.#state;\n }\n }\n\n connectedCallback() {\n LOG.debug(\"Launching application\");\n\n if (this.#state) {\n this.#state.destroy();\n }\n\n this.#state = new ElementState(this, this.#shadowRoot, options);\n this.#state.start();\n }\n\n disconnectedCallback() {\n LOG.debug(\"Shutting down application\");\n\n this.#state?.destroy();\n this.#state = undefined;\n\n LOG.debug(\"Application destroyed\");\n }\n\n when() {\n if (!this.#state) {\n return Promise.reject(\n new Error(\n ErrorId.NOT_MOUNTED,\n \"Cannot use the application's API because the HTML element has not yet been mounted into the DOM.\"\n )\n );\n }\n\n return this.#state.whenAPI();\n }\n }\n return PioneerApplication;\n}\n\nclass ElementState {\n private hostElement: HTMLElement;\n private shadowRoot: ShadowRoot;\n private options: CustomElementOptions;\n\n // Public API\n private apiPromise: ManualPromise<ApiMethods> | undefined; // Present when callers are waiting for the API\n private api: ApiMethods | undefined; // Present once started\n\n private state = \"not-started\" as \"not-started\" | \"starting\" | \"started\" | \"destroyed\";\n private locale: string | undefined;\n private container: HTMLDivElement | undefined;\n private config: ApplicationConfig | undefined;\n private serviceLayer: ServiceLayer | undefined;\n private lifecycleEvents: ApplicationLifecycleEventService | undefined;\n private reactIntegration: ReactIntegration | undefined;\n private stylesWatch: Resource | undefined;\n\n constructor(hostElement: HTMLElement, shadowRoot: ShadowRoot, options: CustomElementOptions) {\n this.hostElement = hostElement;\n this.shadowRoot = shadowRoot;\n this.options = options;\n }\n\n start() {\n if (this.state !== \"not-started\") {\n throw new Error(ErrorId.INTERNAL, `Cannot start element in state '${this.state}'`);\n }\n\n this.state = \"starting\";\n this.startImpl().catch((e) => {\n // TODO: Error splash?\n this.destroy();\n if (!isAbortError(e)) {\n logError(e);\n }\n });\n }\n\n destroy() {\n if (this.state === \"destroyed\") {\n return;\n }\n\n // Only call event listener when 'started' was also signalled.\n if (this.state === \"started\") {\n try {\n this.triggerApplicationLifecycleEvent(\"before-stop\");\n } catch (e) {\n void e; // Ignored\n }\n }\n this.state = \"destroyed\";\n this.apiPromise?.reject(createAbortError());\n this.reactIntegration = destroyResource(this.reactIntegration);\n this.shadowRoot.replaceChildren();\n this.container = undefined;\n this.lifecycleEvents = undefined;\n this.serviceLayer = destroyResource(this.serviceLayer);\n this.stylesWatch = destroyResource(this.stylesWatch);\n }\n\n whenAPI(): Promise<ApiMethods> {\n if (this.api) {\n return Promise.resolve(this.api);\n }\n\n const apiPromise = (this.apiPromise ??= createManualPromise());\n return apiPromise.promise;\n }\n\n private async startImpl() {\n const { options, shadowRoot, hostElement } = this;\n\n // Resolve custom application config\n const config = (this.config = await gatherConfig(hostElement, options));\n this.checkAbort();\n LOG.debug(\"Application config is\", config);\n\n // Decide on locale and load i18n messages (if any).\n const i18n = await initI18n(options.appMetadata, config.locale);\n this.checkAbort();\n\n // Setup application root node in the shadow dom\n const container = (this.container = createContainer(i18n.locale));\n const styles = this.initStyles();\n shadowRoot.replaceChildren(container, ...styles);\n\n // Launch the service layer\n const { serviceLayer, packages } = this.initServiceLayer({\n container,\n properties: config.properties,\n i18n\n });\n this.lifecycleEvents = getInternalService<ApplicationLifecycleEventService>(\n serviceLayer,\n RUNTIME_APPLICATION_LIFECYCLE_EVENT_SERVICE\n );\n\n await this.initAPI(serviceLayer);\n this.checkAbort();\n\n // Launch react\n this.reactIntegration = new ReactIntegration({\n rootNode: container,\n container: shadowRoot,\n serviceLayer,\n packages\n });\n this.render();\n this.state = \"started\";\n\n this.triggerApplicationLifecycleEvent(\"after-start\");\n LOG.debug(\"Application started\");\n }\n\n private render() {\n this.reactIntegration?.render(this.options.component ?? emptyComponent, {});\n }\n\n private initStyles() {\n // Prevent inheritance of certain css values and normalize to display: block by default.\n // See https://open-wc.org/guides/knowledge/styling/styles-piercing-shadow-dom/\n const builtinStyles = \":host { all: initial; display: block; }\";\n const builtinStylesNode = document.createElement(\"style\");\n applyStyles(builtinStylesNode, { value: builtinStyles });\n\n const appStyles = this.options.appMetadata?.styles;\n const appStylesNode = document.createElement(\"style\");\n applyStyles(appStylesNode, appStyles);\n if (import.meta.hot) {\n this.stylesWatch = appStyles?.on?.(\"changed\", () => {\n LOG.debug(\"Application styles changed\");\n applyStyles(appStylesNode, appStyles);\n });\n }\n return [builtinStylesNode, appStylesNode];\n }\n\n private initServiceLayer(config: {\n container: HTMLDivElement;\n properties: ApplicationProperties;\n i18n: AppI18n;\n }) {\n const options = this.options;\n const { container, properties, i18n } = config;\n const packageMetadata = options.appMetadata?.packages ?? {};\n const builtinPackage = createBuiltinPackage({\n host: this.hostElement,\n shadowRoot: this.shadowRoot,\n container: container,\n locale: i18n.locale,\n supportedLocales: i18n.supportedLocales\n });\n const { serviceLayer, packages } = createServiceLayer({\n packageMetadata,\n builtinPackage,\n properties,\n i18n\n });\n this.serviceLayer = serviceLayer;\n\n if (LOG.isDebug()) {\n LOG.debug(\"Launching service layer with packages\", Object.fromEntries(packages));\n }\n serviceLayer.start();\n return { serviceLayer, packages };\n }\n\n private async initAPI(serviceLayer: ServiceLayer) {\n const apiService = getInternalService<ApiService>(serviceLayer, RUNTIME_API_SERVICE);\n try {\n const api = (this.api = await apiService.getApi());\n LOG.debug(\"Application API initialized to\", api);\n this.apiPromise?.resolve(api);\n } catch (e) {\n throw new Error(ErrorId.INTERNAL, \"Failed to gather the application's API methods.\", {\n cause: e\n });\n }\n }\n\n private triggerApplicationLifecycleEvent(event: \"after-start\" | \"before-stop\") {\n this.lifecycleEvents?.emitLifecycleEvent(event);\n }\n\n private checkAbort() {\n if (this.state === \"destroyed\") {\n throwAbortError();\n }\n }\n}\n\nfunction createContainer(locale: string) {\n // Setup application root node in the shadow dom\n const container = document.createElement(\"div\");\n container.classList.add(\"pioneer-root\");\n container.style.minHeight = \"100%\";\n container.style.height = \"100%\";\n if (locale) {\n container.lang = locale;\n }\n return container;\n}\n\nfunction createServiceLayer(config: {\n packageMetadata: Record<string, PackageMetadata> | undefined;\n properties: ApplicationProperties;\n builtinPackage: PackageRepr;\n i18n: AppI18n;\n}) {\n const { packageMetadata, properties, builtinPackage, i18n } = config;\n\n let packages: PackageRepr[];\n try {\n packages = createPackages(packageMetadata ?? {}, i18n, properties);\n } catch (e) {\n throw new Error(ErrorId.INVALID_METADATA, \"Failed to parse package metadata.\", {\n cause: e\n });\n }\n\n // Add builtin services defined within this package.\n {\n const index = packages.findIndex((pkg) => pkg.name === builtinPackage.name);\n if (index >= 0) {\n packages.splice(index, 1);\n }\n packages.push(builtinPackage);\n }\n\n // Automatically required references (-> forces services to start)\n const forcedReferences: ReferenceSpec[] = [\n {\n interfaceName: RUNTIME_API_SERVICE\n },\n {\n interfaceName: RUNTIME_APPLICATION_LIFECYCLE_EVENT_SERVICE\n },\n {\n interfaceName: RUNTIME_AUTO_START,\n all: true\n }\n ];\n const serviceLayer = new ServiceLayer(packages, forcedReferences);\n return {\n packages: new Map(packages.map((pkg) => [pkg.name, pkg])),\n serviceLayer: serviceLayer\n };\n}\n\nfunction getInternalService<T = unknown>(serviceLayer: ServiceLayer, interfaceName: string) {\n const result = serviceLayer.getService(\n \"@open-pioneer/runtime\",\n {\n interfaceName\n },\n { ignoreDeclarationCheck: true }\n );\n if (result.type !== \"found\") {\n throw new Error(\n ErrorId.INTERNAL,\n `Failed to find instance of '${interfaceName}' (result type '${result.type}').` +\n ` This is a builtin service that must be present exactly once.`\n );\n }\n\n return result.value.getInstanceOrThrow() as T;\n}\n\n/**\n * Gathers application properties by reading them from the options object\n * and by (optionally) invoking the `resolveProperties` hook.\n */\nasync function gatherConfig(hostElement: HTMLElement, options: CustomElementOptions) {\n let configs: ApplicationConfig[];\n try {\n const staticConfig = options.config ?? {};\n const dynamicConfig =\n (await options.resolveConfig?.({\n getAttribute(name) {\n return hostElement.getAttribute(name) ?? undefined;\n }\n })) ?? {};\n\n configs = [staticConfig, dynamicConfig];\n } catch (e) {\n throw new Error(\n ErrorId.CONFIG_RESOLUTION_FAILED,\n \"Failed to resolve application properties.\",\n {\n cause: e\n }\n );\n }\n\n return mergeConfigs(configs);\n}\n\n/**\n * Merges application configurations into a single object.\n * Properties / config parameters at a later position overwrite properties from earlier ones.\n */\nfunction mergeConfigs(configs: ApplicationConfig[]): Required<ApplicationConfig> {\n // Merge simple values by assigning them in order\n const mergedConfig: Required<ApplicationConfig> = Object.assign(\n {\n locale: undefined,\n properties: {}\n } satisfies ApplicationConfig,\n ...configs\n );\n\n // Deep merge for application properties\n const mergedProperties: ApplicationProperties = (mergedConfig.properties = {});\n for (const config of configs) {\n for (const [packageName, packageProperties] of Object.entries(config.properties ?? {})) {\n const mergedPackageProps = (mergedProperties[packageName] ??= {});\n Object.assign(mergedPackageProps, packageProperties);\n }\n }\n\n return mergedConfig;\n}\n\n// Applies application styles to the given style node.\n// Can be called multiple times in development mode to implement hot reloading.\nfunction applyStyles(styleNode: HTMLStyleElement, styles: { value: string } | undefined) {\n const cssValue = styles?.value ?? \"\";\n const cssNode = document.createTextNode(cssValue);\n styleNode.replaceChildren(cssNode);\n}\n\nfunction logError(e: unknown) {\n if (e instanceof Error) {\n const chain = getErrorChain(e).reverse();\n if (chain.length === 1) {\n console.error(e);\n return;\n }\n\n let n = 1;\n for (const error of chain) {\n console.error(`#${n}`, error);\n ++n;\n }\n } else {\n console.error(\"Unexpected error\", e);\n }\n}\n\nfunction emptyComponent() {\n return null;\n}\n"],"names":[],"mappings":";;;;;;;;AA+BA,MAAM,GAAA,GAAM,aAAa,uBAAuB,CAAA,CAAA;AAwHzC,SAAS,oBAAoB,OAA8D,EAAA;AAC9F,EAAA,MAAM,2BAA2B,WAA0C,CAAA;AAAA,IACvE,WAAA,CAAA;AAAA,IACA,MAAA,CAAA;AAAA,IAEA,WAAW,kBAA+B,GAAA;AACtC,MAAA,OAAO,EAAC,CAAA;AAAA,KACZ;AAAA,IAEA,WAAc,GAAA;AACV,MAAM,KAAA,EAAA,CAAA;AAEN,MAAA,MAAM,OAAO,OAAQ,CAAA,cAAA,IAAkB,MAAY,CAAA,IAAA,CAAA,GAAA,CAAI,MAAM,MAAS,GAAA,QAAA,CAAA;AACt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AM,KAAQ,GAAA,aAAA,CAAc,CAAC,CAAA,CAAE,OAAQ,EAAA,CAAA;AACvC,IAAI,IAAA,KAAA,CAAM,WAAW,CAAG,EAAA;AACpB,MAAA,OAAA,CAAQ,MAAM,CAAC,CAAA,CAAA;AACf,MAAA,OAAA;AAAA,KACJ;AAEA,IAAA,IAAI,CAAI,GAAA,CAAA,CAAA;AACR,IAAA,KAAA,MAAW,SAAS,KAAO,EAAA;AACvB,MAAQ,OAAA,CAAA,KAAA,CAAM,CAAI,CAAA,EAAA,CAAA,CAAA,CAAA,EAAK,KAAK,CAAA,CAAA;AAC5B,MAAE,EAAA,CAAA,CAAA;AAAA,KACN;AAAA,GACG,MAAA;AACH,IAAQ,OAAA,CAAA,KAAA,CAAM,oBAAoB,CAAC,CAAA,CAAA;AAAA,GACvC;AACJ,CAAA;AAEA,SAAS,cAAiB,GAAA;AACtB,EAAO,OAAA,IAAA,CAAA;AACX;;;;"}
|
|
1
|
+
{"version":3,"file":"CustomElement.js","sources":["CustomElement.ts"],"sourcesContent":["// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ComponentType } from \"react\";\nimport {\n createAbortError,\n createLogger,\n createManualPromise,\n destroyResource,\n Error,\n isAbortError,\n ManualPromise,\n Resource,\n throwAbortError\n} from \"@open-pioneer/core\";\nimport { ErrorId } from \"./errors\";\nimport { ApplicationMetadata, PackageMetadata } from \"./metadata\";\nimport { PackageRepr, createPackages } from \"./service-layer/PackageRepr\";\nimport { ServiceLayer } from \"./service-layer/ServiceLayer\";\nimport { getErrorChain } from \"@open-pioneer/core\";\nimport { ReactIntegration } from \"./react-integration/ReactIntegration\";\nimport { ApiMethods, ApiService } from \"./api\";\nimport {\n createBuiltinPackage,\n RUNTIME_API_SERVICE,\n RUNTIME_APPLICATION_LIFECYCLE_EVENT_SERVICE,\n RUNTIME_AUTO_START\n} from \"./builtin-services\";\nimport { ReferenceSpec } from \"./service-layer/InterfaceSpec\";\nimport { PropertiesRegistry } from \"./PropertiesRegistry\";\nimport { AppI18n, initI18n } from \"./i18n\";\nimport { ApplicationLifecycleEventService } from \"./builtin-services/ApplicationLifecycleEventService\";\nconst LOG = createLogger(\"runtime:CustomElement\");\n\n/**\n * Options for the {@link createCustomElement} function.\n */\nexport interface CustomElementOptions {\n /**\n * Rendered UI component.\n */\n component?: ComponentType<Record<string, string>>;\n\n /**\n * Application metadata (packages, services etc.).\n * This is usually autogenerated by importing the virtual `\"open-pioneer:app\"` module.\n */\n appMetadata?: ApplicationMetadata;\n\n /**\n * Application defined configuration.\n * All instances of the web component will share this static configuration.\n *\n * These will override default properties of the application's packages.\n */\n config?: ApplicationConfig;\n\n /**\n * Function to provide additional application defined configuration parameters.\n *\n * Compared to {@link config}, this function receives a context object\n * that allows the developer to provide dynamic properties on a per-application basis.\n *\n * Parameters returned by this function take precedence over the ones defined by {@link config}.\n */\n resolveConfig?(ctx: ConfigContext): Promise<ApplicationConfig | undefined>;\n\n /**\n * Whether the shadow root element is accessible from the outside.\n * Defaults to `false` in production mode and `true` during development to make testing easier.\n */\n openShadowRoot?: boolean;\n}\n\n/**\n * A context object that is passed to the `resolveProperties` function.\n */\nexport interface ConfigContext {\n /**\n * Returns an attribute from the application's root node.\n */\n getAttribute(name: string): string | undefined;\n}\n\n/**\n * Runtime application configuration.\n */\nexport interface ApplicationConfig {\n /**\n * Set this value to a locale string (e.g. \"en\") to for the application's locale.\n * The default behavior is to choose an appropriate locale for the current user based\n * on the browser's settings.\n *\n * The locale must be supported by the application.\n */\n locale?: string | undefined;\n\n /**\n * Properties specified here will override default properties of the application's packages.\n */\n properties?: ApplicationProperties | undefined;\n}\n\n/**\n * Allows the application to override default properties in all packages.\n */\nexport interface RawApplicationProperties {\n /**\n * Key: the name of the package.\n * Value: A record of configuration properties (key/value pairs).\n *\n * Properties will override default property values in the package.\n */\n [packageName: string]: Record<string, unknown>;\n}\n\n/**\n * Allows the application to override default properties in all packages.\n *\n * Properties are typed when the package contains type definitions for them.\n */\nexport type ApplicationProperties = RawApplicationProperties & Partial<PropertiesRegistry>;\n\n/**\n * The interface implemented by web components produced via {@link createCustomElement}.\n */\nexport interface ApplicationElement extends HTMLElement {\n /** Resolves to the element's API when the application has started. */\n when(): Promise<ApiMethods>;\n}\n\n/**\n * The class returned by a call to {@link createCustomElement}.\n */\nexport interface ApplicationElementConstructor {\n new (): ApplicationElement;\n}\n\n/**\n * Creates a new custom element class (web component) that can be registered within a DOM.\n *\n * @example\n * ```ts\n * import * as appMetadata from \"open-pioneer:app\";\n *\n * const CustomElementClazz = createCustomElement({\n * component: <div>Hello World!</div>,\n * appMetadata\n * });\n * customElements.define(\"sample-element\", CustomElementClazz);\n * ```\n */\nexport function createCustomElement(options: CustomElementOptions): ApplicationElementConstructor {\n class PioneerApplication extends HTMLElement implements ApplicationElement {\n #shadowRoot: ShadowRoot;\n #state: ElementState | undefined;\n\n static get observedAttributes(): string[] {\n return [];\n }\n\n constructor() {\n super();\n\n const mode = options.openShadowRoot ?? import.meta.env.DEV ? \"open\" : \"closed\";\n this.#shadowRoot = this.attachShadow({\n mode: mode\n });\n\n if (import.meta.env.DEV) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this as any).$inspectElementState = () => this.#state;\n }\n }\n\n connectedCallback() {\n LOG.debug(\"Launching application\");\n\n if (this.#state) {\n this.#state.destroy();\n }\n\n this.#state = new ElementState(this, this.#shadowRoot, options);\n this.#state.start();\n }\n\n disconnectedCallback() {\n LOG.debug(\"Shutting down application\");\n\n this.#state?.destroy();\n this.#state = undefined;\n\n LOG.debug(\"Application destroyed\");\n }\n\n when() {\n if (!this.#state) {\n return Promise.reject(\n new Error(\n ErrorId.NOT_MOUNTED,\n \"Cannot use the application's API because the HTML element has not yet been mounted into the DOM.\"\n )\n );\n }\n\n return this.#state.whenAPI();\n }\n }\n return PioneerApplication;\n}\n\nclass ElementState {\n private hostElement: HTMLElement;\n private shadowRoot: ShadowRoot;\n private options: CustomElementOptions;\n\n // Public API\n private apiPromise: ManualPromise<ApiMethods> | undefined; // Present when callers are waiting for the API\n private api: ApiMethods | undefined; // Present once started\n\n private state = \"not-started\" as \"not-started\" | \"starting\" | \"started\" | \"destroyed\";\n private locale: string | undefined;\n private container: HTMLDivElement | undefined;\n private config: ApplicationConfig | undefined;\n private serviceLayer: ServiceLayer | undefined;\n private lifecycleEvents: ApplicationLifecycleEventService | undefined;\n private reactIntegration: ReactIntegration | undefined;\n private stylesWatch: Resource | undefined;\n\n constructor(hostElement: HTMLElement, shadowRoot: ShadowRoot, options: CustomElementOptions) {\n this.hostElement = hostElement;\n this.shadowRoot = shadowRoot;\n this.options = options;\n }\n\n start() {\n if (this.state !== \"not-started\") {\n throw new Error(ErrorId.INTERNAL, `Cannot start element in state '${this.state}'`);\n }\n\n this.state = \"starting\";\n this.startImpl().catch((e) => {\n // TODO: Error splash?\n this.destroy();\n if (!isAbortError(e)) {\n logError(e);\n }\n });\n }\n\n destroy() {\n if (this.state === \"destroyed\") {\n return;\n }\n\n // Only call event listener when 'started' was also signalled.\n if (this.state === \"started\") {\n try {\n this.triggerApplicationLifecycleEvent(\"before-stop\");\n } catch (e) {\n void e; // Ignored\n }\n }\n this.state = \"destroyed\";\n this.apiPromise?.reject(createAbortError());\n this.reactIntegration = destroyResource(this.reactIntegration);\n this.shadowRoot.replaceChildren();\n this.container = undefined;\n this.lifecycleEvents = undefined;\n this.serviceLayer = destroyResource(this.serviceLayer);\n this.stylesWatch = destroyResource(this.stylesWatch);\n }\n\n whenAPI(): Promise<ApiMethods> {\n if (this.api) {\n return Promise.resolve(this.api);\n }\n\n const apiPromise = (this.apiPromise ??= createManualPromise());\n return apiPromise.promise;\n }\n\n private async startImpl() {\n const { options, shadowRoot, hostElement } = this;\n\n // Resolve custom application config\n const config = (this.config = await gatherConfig(hostElement, options));\n this.checkAbort();\n LOG.debug(\"Application config is\", config);\n\n // Decide on locale and load i18n messages (if any).\n const i18n = await initI18n(options.appMetadata, config.locale);\n this.checkAbort();\n\n // Setup application root node in the shadow dom\n const container = (this.container = createContainer(i18n.locale));\n const styles = this.initStyles();\n shadowRoot.replaceChildren(container, ...styles);\n\n // Launch the service layer\n const { serviceLayer, packages } = this.initServiceLayer({\n container,\n properties: config.properties,\n i18n\n });\n this.lifecycleEvents = getInternalService<ApplicationLifecycleEventService>(\n serviceLayer,\n RUNTIME_APPLICATION_LIFECYCLE_EVENT_SERVICE\n );\n\n await this.initAPI(serviceLayer);\n this.checkAbort();\n\n // Launch react\n this.reactIntegration = new ReactIntegration({\n rootNode: container,\n container: shadowRoot,\n serviceLayer,\n packages\n });\n this.render();\n this.state = \"started\";\n\n this.triggerApplicationLifecycleEvent(\"after-start\");\n LOG.debug(\"Application started\");\n }\n\n private render() {\n this.reactIntegration?.render(this.options.component ?? emptyComponent, {});\n }\n\n private initStyles() {\n // Prevent inheritance of certain css values and normalize to display: block by default.\n // See https://open-wc.org/guides/knowledge/styling/styles-piercing-shadow-dom/\n const builtinStyles = \":host { all: initial; display: block; }\";\n const builtinStylesNode = document.createElement(\"style\");\n applyStyles(builtinStylesNode, { value: builtinStyles });\n\n const appStyles = this.options.appMetadata?.styles;\n const appStylesNode = document.createElement(\"style\");\n applyStyles(appStylesNode, appStyles);\n if (import.meta.hot) {\n this.stylesWatch = appStyles?.on?.(\"changed\", () => {\n LOG.debug(\"Application styles changed\");\n applyStyles(appStylesNode, appStyles);\n });\n }\n return [builtinStylesNode, appStylesNode];\n }\n\n private initServiceLayer(config: {\n container: HTMLDivElement;\n properties: ApplicationProperties;\n i18n: AppI18n;\n }) {\n const options = this.options;\n const { container, properties, i18n } = config;\n const packageMetadata = options.appMetadata?.packages ?? {};\n const builtinPackage = createBuiltinPackage({\n host: this.hostElement,\n shadowRoot: this.shadowRoot,\n container: container,\n locale: i18n.locale,\n supportedLocales: i18n.supportedLocales\n });\n const { serviceLayer, packages } = createServiceLayer({\n packageMetadata,\n builtinPackage,\n properties,\n i18n\n });\n this.serviceLayer = serviceLayer;\n\n if (LOG.isDebug()) {\n LOG.debug(\"Launching service layer with packages\", Object.fromEntries(packages));\n }\n serviceLayer.start();\n return { serviceLayer, packages };\n }\n\n private async initAPI(serviceLayer: ServiceLayer) {\n const apiService = getInternalService<ApiService>(serviceLayer, RUNTIME_API_SERVICE);\n try {\n const api = (this.api = await apiService.getApi());\n LOG.debug(\"Application API initialized to\", api);\n this.apiPromise?.resolve(api);\n } catch (e) {\n throw new Error(ErrorId.INTERNAL, \"Failed to gather the application's API methods.\", {\n cause: e\n });\n }\n }\n\n private triggerApplicationLifecycleEvent(event: \"after-start\" | \"before-stop\") {\n this.lifecycleEvents?.emitLifecycleEvent(event);\n }\n\n private checkAbort() {\n if (this.state === \"destroyed\") {\n throwAbortError();\n }\n }\n}\n\nfunction createContainer(locale: string) {\n // Setup application root node in the shadow dom\n const container = document.createElement(\"div\");\n container.classList.add(\"pioneer-root\");\n container.style.minHeight = \"100%\";\n container.style.height = \"100%\";\n if (locale) {\n container.lang = locale;\n }\n return container;\n}\n\nfunction createServiceLayer(config: {\n packageMetadata: Record<string, PackageMetadata> | undefined;\n properties: ApplicationProperties;\n builtinPackage: PackageRepr;\n i18n: AppI18n;\n}) {\n const { packageMetadata, properties, builtinPackage, i18n } = config;\n\n let packages: PackageRepr[];\n try {\n packages = createPackages(packageMetadata ?? {}, i18n, properties);\n } catch (e) {\n throw new Error(ErrorId.INVALID_METADATA, \"Failed to parse package metadata.\", {\n cause: e\n });\n }\n\n // Add builtin services defined within this package.\n {\n const index = packages.findIndex((pkg) => pkg.name === builtinPackage.name);\n if (index >= 0) {\n packages.splice(index, 1);\n }\n packages.push(builtinPackage);\n }\n\n // Automatically required references (-> forces services to start)\n const forcedReferences: ReferenceSpec[] = [\n {\n interfaceName: RUNTIME_API_SERVICE\n },\n {\n interfaceName: RUNTIME_APPLICATION_LIFECYCLE_EVENT_SERVICE\n },\n {\n interfaceName: RUNTIME_AUTO_START,\n all: true\n }\n ];\n const serviceLayer = new ServiceLayer(packages, forcedReferences);\n return {\n packages: new Map(packages.map((pkg) => [pkg.name, pkg])),\n serviceLayer: serviceLayer\n };\n}\n\nfunction getInternalService<T = unknown>(serviceLayer: ServiceLayer, interfaceName: string) {\n const result = serviceLayer.getService(\n \"@open-pioneer/runtime\",\n {\n interfaceName\n },\n { ignoreDeclarationCheck: true }\n );\n if (result.type !== \"found\") {\n throw new Error(\n ErrorId.INTERNAL,\n `Failed to find instance of '${interfaceName}' (result type '${result.type}').` +\n ` This is a builtin service that must be present exactly once.`\n );\n }\n\n return result.value.getInstanceOrThrow() as T;\n}\n\n/**\n * Gathers application properties by reading them from the options object\n * and by (optionally) invoking the `resolveProperties` hook.\n */\nasync function gatherConfig(hostElement: HTMLElement, options: CustomElementOptions) {\n let configs: ApplicationConfig[];\n try {\n const staticConfig = options.config ?? {};\n const dynamicConfig =\n (await options.resolveConfig?.({\n getAttribute(name) {\n return hostElement.getAttribute(name) ?? undefined;\n }\n })) ?? {};\n\n configs = [staticConfig, dynamicConfig];\n } catch (e) {\n throw new Error(\n ErrorId.CONFIG_RESOLUTION_FAILED,\n \"Failed to resolve application properties.\",\n {\n cause: e\n }\n );\n }\n\n return mergeConfigs(configs);\n}\n\n/**\n * Merges application configurations into a single object.\n * Properties / config parameters at a later position overwrite properties from earlier ones.\n */\nfunction mergeConfigs(configs: ApplicationConfig[]): Required<ApplicationConfig> {\n // Merge simple values by assigning them in order\n const mergedConfig: Required<ApplicationConfig> = Object.assign(\n {\n locale: undefined,\n properties: {}\n } satisfies ApplicationConfig,\n ...configs\n );\n\n // Deep merge for application properties\n const mergedProperties: ApplicationProperties = (mergedConfig.properties = {});\n for (const config of configs) {\n for (const [packageName, packageProperties] of Object.entries(config.properties ?? {})) {\n const mergedPackageProps = (mergedProperties[packageName] ??= {});\n Object.assign(mergedPackageProps, packageProperties);\n }\n }\n\n return mergedConfig;\n}\n\n// Applies application styles to the given style node.\n// Can be called multiple times in development mode to implement hot reloading.\nfunction applyStyles(styleNode: HTMLStyleElement, styles: { value: string } | undefined) {\n const cssValue = styles?.value ?? \"\";\n const cssNode = document.createTextNode(cssValue);\n styleNode.replaceChildren(cssNode);\n}\n\nfunction logError(e: unknown) {\n if (e instanceof Error) {\n const chain = getErrorChain(e).reverse();\n if (chain.length === 1) {\n console.error(e);\n return;\n }\n\n let n = 1;\n for (const error of chain) {\n console.error(`#${n}`, error);\n ++n;\n }\n } else {\n console.error(\"Unexpected error\", e);\n }\n}\n\nfunction emptyComponent() {\n return null;\n}\n"],"names":[],"mappings":";;;;;;;;AA+BA,MAAM,GAAA,GAAM,aAAa,uBAAuB,CAAA,CAAA;AAwHzC,SAAS,oBAAoB,OAA8D,EAAA;AAC9F,EAAA,MAAM,2BAA2B,WAA0C,CAAA;AAAA,IACvE,WAAA,CAAA;AAAA,IACA,MAAA,CAAA;AAAA,IAEA,WAAW,kBAA+B,GAAA;AACtC,MAAA,OAAO,EAAC,CAAA;AAAA,KACZ;AAAA,IAEA,WAAc,GAAA;AACV,MAAM,KAAA,EAAA,CAAA;AAEN,MAAA,MAAM,OAAO,OAAQ,CAAA,cAAA,IAAkB,MAAY,CAAA,IAAA,CAAA,GAAA,CAAI,MAAM,MAAS,GAAA,QAAA,CAAA;AACtE,MAAK,IAAA,CAAA,WAAA,GAAc,KAAK,YAAa,CAAA;AAAA,QACjC,IAAA;AAAA,OACH,CAAA,CAAA;AAED,MAAI,IAAA,MAAA,CAAA,IAAA,CAAY,IAAI,GAAK,EAAA;AAErB,QAAC,IAAA,CAAa,oBAAuB,GAAA,MAAM,IAAK,CAAA,MAAA,CAAA;AAAA,OACpD;AAAA,KACJ;AAAA,IAEA,iBAAoB,GAAA;AAChB,MAAA,GAAA,CAAI,MAAM,uBAAuB,CAAA,CAAA;AAEjC,MAAA,IAAI,KAAK,MAAQ,EAAA;AACb,QAAA,IAAA,CAAK,OAAO,OAAQ,EAAA,CAAA;AAAA,OACxB;AAEA,MAAA,IAAA,CAAK,SAAS,IAAI,YAAA,CAAa,IAAM,EAAA,IAAA,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AA,CAAA;AAAA,GACvC;AACJ,CAAA;AAEA,SAAS,cAAiB,GAAA;AACtB,EAAO,OAAA,IAAA,CAAA;AACX;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ApiServiceImpl.js","sources":["
|
|
1
|
+
{"version":3,"file":"ApiServiceImpl.js","sources":["ApiServiceImpl.ts"],"sourcesContent":["// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ServiceOptions } from \"../Service\";\nimport { ApiExtension, ApiMethod, ApiMethods, ApiService } from \"../api\";\nimport { Error } from \"@open-pioneer/core\";\nimport { ErrorId } from \"../errors\";\n\ninterface References {\n providers: ApiExtension[];\n}\n\nexport class ApiServiceImpl implements ApiService {\n private readonly providers: [serviceId: string, provider: ApiExtension][];\n\n constructor(options: ServiceOptions<References>) {\n const providers = options.references.providers;\n const meta = options.referencesMeta.providers;\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.providers = providers.map((provider, index) => [meta[index]!.serviceId, provider]);\n }\n\n async getApi() {\n interface ProviderResult {\n serviceId: string;\n methods: ApiMethods;\n }\n\n const promises = this.providers.map(async ([serviceId, provider]) => {\n const methods = await provider.getApiMethods();\n const result: ProviderResult = {\n serviceId,\n methods\n };\n return result;\n });\n const providerMethods = await Promise.all(promises);\n\n interface MethodEntry {\n method: ApiMethod;\n serviceId: string;\n }\n\n const methodEntries = new Map<string, MethodEntry>();\n for (const { serviceId, methods } of providerMethods) {\n for (const [methodName, method] of Object.entries(methods)) {\n const existingEntry = methodEntries.get(methodName);\n if (existingEntry) {\n throw new Error(\n ErrorId.DUPLICATE_API_METHODS,\n `Cannot define API method '${methodName}' from '${serviceId}' (method is also defined by '${existingEntry.serviceId}').`\n );\n }\n\n methodEntries.set(methodName, {\n serviceId,\n method\n });\n }\n }\n\n const api: Record<string, ApiMethod> = {};\n for (const [methodName, entry] of methodEntries.entries()) {\n api[methodName] = entry.method;\n }\n return api;\n }\n}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AAA,EAA6B,UAAqB,CAAA,QAAA,EAAA,SAAA,CAAA,8BAAA,EAA0C,aAAc,CAAA,SAAA,CAAA,GAAA,CAAA;AAAA,WAC9G,CAAA;AAAA,SACJ;AAEA,QAAA,aAAA,CAAc,IAAI,UAAY,EAAA;AAAA,UAC1B,SAAA;AAAA,UACA,MAAA;AAAA,SACH,CAAA,CAAA;AAAA,OACL;AAAA,KACJ;AAEA,IAAA,MAAM,MAAiC,EAAC,CAAA;AACxC,IAAA,KAAA,MAAW,CAAC,UAAY,EAAA,KAAK,CAAK,IAAA,aAAA,CAAc,SAAW,EAAA;AACvD,MAAI,GAAA,CAAA,UAAU,IAAI,KAAM,CAAA,MAAA,CAAA;AAAA,KAC5B;AACA,IAAO,OAAA,GAAA,CAAA;AAAA,GACX;AACJ;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ApplicationContextImpl.js","sources":["
|
|
1
|
+
{"version":3,"file":"ApplicationContextImpl.js","sources":["ApplicationContextImpl.ts"],"sourcesContent":["// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ApplicationContext } from \"../api\";\nimport { ServiceOptions } from \"../Service\";\n\nexport interface ApplicationContextProperties {\n host: HTMLElement;\n shadowRoot: ShadowRoot;\n container: HTMLElement;\n locale: string;\n supportedLocales: string[];\n}\n\nexport class ApplicationContextImpl implements ApplicationContext {\n #host: HTMLElement;\n #shadowRoot: ShadowRoot;\n #container: HTMLElement;\n #locale: string;\n #supportedLocales: readonly string[];\n\n constructor(options: ServiceOptions, properties: ApplicationContextProperties) {\n this.#host = properties.host;\n this.#shadowRoot = properties.shadowRoot;\n this.#container = properties.container;\n this.#locale = properties.locale;\n this.#supportedLocales = Object.freeze(Array.from(properties.supportedLocales));\n }\n\n getHostElement(): HTMLElement {\n return this.#host;\n }\n\n getShadowRoot(): ShadowRoot {\n return this.#shadowRoot;\n }\n\n getApplicationContainer(): HTMLElement {\n return this.#container;\n }\n\n getLocale(): string {\n return this.#locale;\n }\n\n getSupportedLocales(): readonly string[] {\n return this.#supportedLocales;\n }\n}\n"],"names":[],"mappings":"AAaO,MAAM,sBAAqD,CAAA;AAAA,EAC9D,KAAA,CAAA;AAAA,EACA,WAAA,CAAA;AAAA,EACA,UAAA,CAAA;AAAA,EACA,OAAA,CAAA;AAAA,EACA,iBAAA,CAAA;AAAA,EAEA,WAAA,CAAY,SAAyB,UAA0C,EAAA;AAC3E,IAAA,IAAA,CAAK,QAAQ,UAAW,CAAA,IAAA,CAAA;AACxB,IAAA,IAAA,CAAK,cAAc,UAAW,CAAA,UAAA,CAAA;AAC9B,IAAA,IAAA,CAAK,aAAa,UAAW,CAAA,SAAA,CAAA;AAC7B,IAAA,IAAA,CAAK,UAAU,UAAW,CAAA,MAAA,CAAA;AAC1B,IAAA,IAAA,CAAK,oBAAoB,MAAO,CAAA,MAAA,CAAO,MAAM,IAAK,CAAA,UAAA,CAAW,gBAAgB,CAAC,CAAA,CAAA;AAAA,GAClF;AAAA,EAEA,cAA8B,GAAA;AAC1B,IAAA,OAAO,IAAK,CAAA,KAAA,CAAA;AAAA,GAChB;AAAA,EAEA,aAA4B,GAAA;AACxB,IAAA,OAAO,IAAK,CAAA,WAAA,CAAA;AAAA,GAChB;AAAA,EAEA,uBAAuC,GAAA;AACnC,IAAA,OAAO,IAAK,CAAA,UAAA,CAAA;AAAA,GAChB;AAAA,EAEA,SAAoB,GAAA;AAChB,IAAA,OAAO,IAAK,CAAA,OAAA,CAAA;AAAA,GAChB;AAAA,EAEA,mBAAyC,GAAA;AACrC,IAAA,OAAO,IAAK,CAAA,iBAAA,CAAA;AAAA,GAChB;AACJ;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ApplicationLifecycleEventService.js","sources":["
|
|
1
|
+
{"version":3,"file":"ApplicationLifecycleEventService.js","sources":["ApplicationLifecycleEventService.ts"],"sourcesContent":["// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport { createLogger } from \"@open-pioneer/core\";\nimport { Error } from \"@open-pioneer/core\";\nimport { ServiceOptions } from \"../Service\";\nimport { ServiceType } from \"../ServiceRegistry\";\nimport { ApplicationLifecycleListener } from \"../api\";\nimport { ErrorId } from \"../errors\";\n\nconst LOG = createLogger(\"runtime:ApplicationLifecycleEventService\");\n\ninterface References {\n listeners: ServiceType<\"runtime.ApplicationLifecycleListener\">[];\n}\n\nexport class ApplicationLifecycleEventService {\n #listeners: [serviceId: string, listener: ApplicationLifecycleListener][];\n\n constructor(options: ServiceOptions<References>) {\n const listeners = options.references.listeners;\n const listenersMeta = options.referencesMeta.listeners;\n this.#listeners = listeners.map((listener, index) => [\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n listenersMeta[index]!.serviceId,\n listener\n ]);\n }\n\n /** @internal */\n emitLifecycleEvent(event: \"after-start\" | \"before-stop\"): void {\n const methodName = (() => {\n switch (event) {\n case \"after-start\":\n return \"afterApplicationStart\";\n case \"before-stop\":\n return \"beforeApplicationStop\";\n default:\n throw new Error(ErrorId.INTERNAL, `Invalid event '${event}'`);\n }\n })();\n for (const [serviceId, listener] of this.#listeners) {\n try {\n listener[methodName]?.();\n } catch (e) {\n LOG.error(`Unexpected error from application lifecycle listener ${serviceId}`, e);\n }\n }\n }\n}\n"],"names":[],"mappings":";;;AAUA,MAAM,GAAA,GAAM,aAAa,0CAA0C,CAAA,CAAA;AAM5D,MAAM,gCAAiC,CAAA;AAAA,EAC1C,UAAA,CAAA;AAAA,EAEA,YAAY,OAAqC,EAAA;AAC7C,IAAM,MAAA,SAAA,GAAY,QAAQ,UAAW,CAAA,SAAA,CAAA;AACrC,IAAM,MAAA,aAAA,GAAgB,QAAQ,cAAe,CAAA,SAAA,CAAA;AAC7C,IAAA,IAAA,CAAK,UAAa,GAAA,SAAA,CAAU,GAAI,CAAA,CAAC,UAAU,KAAU,KAAA;AAAA;AAAA,MAEjD,aAAA,CAAc,KAAK,CAAG,CAAA,SAAA;AAAA,MACtB,QAAA;AAAA,KACH,CAAA,CAAA;AAAA,GACL;AAAA;AAAA,EAGA,mBAAmB,KAA4C,EAAA;AAC3D,IAAA,MAAM,cAAc,MAAM;AACtB,MAAA,QAAQ,KAAO;AAAA,QACX,KAAK,aAAA;AACD,UAAO,OAAA,uBAAA,CAAA;AAAA,QACX,KAAK,aAAA;AACD,UAAO,OAAA,uBAAA,CAAA;AAAA,QACX;AACI,UAAA,MAAM,IAAI,KAAA,CAAM,OAAQ,CAAA,QAAA,EAAU,kBAAkB,KAAQ,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,OACpE;AAAA,KACD,GAAA,CAAA;AACH,IAAA,KAAA,MAAW,CAAC,SAAA,EAAW,QAAQ,CAAA,IAAK,KAAK,UAAY,EAAA;AACjD,MAAI,IAAA;AACA,QAAA,QAAA,CAAS,UAAU,CAAI,IAAA,CAAA;AAAA,eAClB,CAAP,EAAA;AACE,QAAI,GAAA,CAAA,KAAA,CAAM,CAAwD,qDAAA,EAAA,SAAA,CAAA,CAAA,EAAa,CAAC,CAAA,CAAA;AAAA,OACpF;AAAA,KACJ;AAAA,GACJ;AACJ;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["
|
|
1
|
+
{"version":3,"file":"index.js","sources":["index.ts"],"sourcesContent":["// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { createEmptyI18n } from \"../i18n\";\nimport { PackageRepr } from \"../service-layer/PackageRepr\";\nimport {\n createConstructorFactory,\n createFunctionFactory,\n ServiceRepr\n} from \"../service-layer/ServiceRepr\";\nimport { ApiServiceImpl } from \"./ApiServiceImpl\";\nimport { ApplicationContextImpl, ApplicationContextProperties } from \"./ApplicationContextImpl\";\nimport { ApplicationLifecycleEventService } from \"./ApplicationLifecycleEventService\";\n\nexport const RUNTIME_PACKAGE_NAME = \"@open-pioneer/runtime\";\nexport const RUNTIME_API_EXTENSION = \"integration.ApiExtension\";\nexport const RUNTIME_API_SERVICE = \"runtime.ApiService\";\nexport const RUNTIME_APPLICATION_CONTEXT = \"runtime.ApplicationContext\";\nexport const RUNTIME_APPLICATION_LIFECYCLE_EVENT_SERVICE =\n \"runtime.ApplicationLifecycleEventService\";\nexport const RUNTIME_AUTO_START = \"runtime.AutoStart\";\n\nexport type BuiltinPackageProperties = ApplicationContextProperties;\n\n/**\n * Creates the builtin package containing the builtin services.\n *\n * The runtime package should not use services in the `build.config.mjs`\n * for a clean bootstrapping procedure (it will be instantiated without\n * generated application metadata in tests).\n *\n * This function is called as part of the service layer startup.\n * The package produced here is always part of the application.\n */\nexport function createBuiltinPackage(properties: BuiltinPackageProperties): PackageRepr {\n const i18n = createEmptyI18n();\n const apiService = new ServiceRepr({\n name: \"ApiServiceImpl\",\n packageName: RUNTIME_PACKAGE_NAME,\n factory: createConstructorFactory(ApiServiceImpl),\n intl: i18n,\n interfaces: [\n {\n interfaceName: RUNTIME_API_SERVICE,\n qualifier: \"builtin\"\n }\n ],\n dependencies: [\n {\n referenceName: \"providers\",\n interfaceName: RUNTIME_API_EXTENSION,\n all: true\n }\n ]\n });\n const appContext = new ServiceRepr({\n name: \"ApplicationContextImpl\",\n packageName: RUNTIME_PACKAGE_NAME,\n factory: createFunctionFactory(\n (options) => new ApplicationContextImpl(options, properties)\n ),\n intl: i18n,\n interfaces: [\n {\n interfaceName: RUNTIME_APPLICATION_CONTEXT,\n qualifier: \"builtin\"\n }\n ]\n });\n const lifecycleEventService = new ServiceRepr({\n name: \"ApplicationLifecycleEventServiceImpl\",\n packageName: RUNTIME_PACKAGE_NAME,\n factory: createConstructorFactory(ApplicationLifecycleEventService),\n intl: i18n,\n interfaces: [\n {\n interfaceName: RUNTIME_APPLICATION_LIFECYCLE_EVENT_SERVICE,\n qualifier: \"builtin\"\n }\n ],\n dependencies: [\n {\n referenceName: \"listeners\",\n interfaceName: \"runtime.ApplicationLifecycleListener\",\n all: true\n }\n ]\n });\n\n return new PackageRepr({\n name: RUNTIME_PACKAGE_NAME,\n services: [apiService, appContext, lifecycleEventService],\n intl: i18n\n });\n}\n"],"names":[],"mappings":";;;;;;;AAaO,MAAM,oBAAuB,GAAA,wBAAA;AAC7B,MAAM,qBAAwB,GAAA,2BAAA;AAC9B,MAAM,mBAAsB,GAAA,qBAAA;AAC5B,MAAM,2BAA8B,GAAA,6BAAA;AACpC,MAAM,2CACT,GAAA,2CAAA;AACG,MAAM,kBAAqB,GAAA,oBAAA;AAc3B,SAAS,qBAAqB,UAAmD,EAAA;AACpF,EAAA,MAAM,OAAO,eAAgB,EAAA,CAAA;AAC7B,EAAM,MAAA,UAAA,GAAa,IAAI,WAAY,CAAA;AAAA,IAC/B,IAAM,EAAA,gBAAA;AAAA,IACN,WAAa,EAAA,oBAAA;AAAA,IACb,OAAA,EAAS,yBAAyB,cAAc,CAAA;AAAA,IAChD,IAAM,EAAA,IAAA;AAAA,IACN,UAAY,EAAA;AAAA,MACR;AAAA,QACI,aAAe,EAAA,mBAAA;AAAA,QACf,SAAW,EAAA,SAAA;AAAA,OACf;AAAA,KACJ;AAAA,IACA,YAAc,EAAA;AAAA,MACV;AAAA,QACI,aAAe,EAAA,WAAA;AAAA,QACf,aAAe,EAAA,qBAAA;AAAA,QACf,GAAK,EAAA,IAAA;AAAA,OACT;AAAA,KACJ;AAAA,GACH,CAAA,CAAA;AACD,EAAM,MAAA,UAAA,GAAa,IAAI,WAAY,CAAA;AAAA,IAC/B,IAAM,EAAA,wBAAA;AAAA,IACN,WAAa,EAAA,oBAAA;AAAA,IACb,OAAS,EAAA,qBAAA;AAAA,MACL,CAAC,OAAA,KAAY,IAAI,sBAAA,CAAuB,SAAS,UAAU,CAAA;AAAA,KAC/D;AAAA,IACA,IAAM,EAAA,IAAA;AAAA,IACN,UAAY,EAAA;AAAA,MACR;AAAA,QACI,aAAe,EAAA,2BAAA;AAAA,QACf,SAAW,EAAA,SAAA;AAAA,OACf;AAAA,KACJ;AAAA,GACH,CAAA,CAAA;AACD,EAAM,MAAA,qBAAA,GAAwB,IAAI,WAAY,CAAA;AAAA,IAC1C,IAAM,EAAA,sCAAA;AAAA,IACN,WAAa,EAAA,oBAAA;AAAA,IACb,OAAA,EAAS,yBAAyB,gCAAgC,CAAA;AAAA,IAClE,IAAM,EAAA,IAAA;AAAA,IACN,UAAY,EAAA;AAAA,MACR;AAAA,QACI,aAAe,EAAA,2CAAA;AAAA,QACf,SAAW,EAAA,SAAA;AAAA,OACf;AAAA,KACJ;AAAA,IACA,YAAc,EAAA;AAAA,MACV;AAAA,QACI,aAAe,EAAA,WAAA;AAAA,QACf,aAAe,EAAA,sCAAA;AAAA,QACf,GAAK,EAAA,IAAA;AAAA,OACT;AAAA,KACJ;AAAA,GACH,CAAA,CAAA;AAED,EAAA,OAAO,IAAI,WAAY,CAAA;AAAA,IACnB,IAAM,EAAA,oBAAA;AAAA,IACN,QAAU,EAAA,CAAC,UAAY,EAAA,UAAA,EAAY,qBAAqB,CAAA;AAAA,IACxD,IAAM,EAAA,IAAA;AAAA,GACT,CAAA,CAAA;AACL;;;;"}
|
package/errors.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","sources":["
|
|
1
|
+
{"version":3,"file":"errors.js","sources":["errors.ts"],"sourcesContent":["// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nexport enum ErrorId {\n // Problems with application metadata\n INVALID_METADATA = \"runtime:invalid-metadata\",\n INVALID_PROPERTY_NAME = \"runtime:invalid-property-name\",\n REQUIRED_PROPERTY = \"runtime:required-property\",\n\n // Application lifecycle\n NOT_MOUNTED = \"runtime:element-not-mounted\",\n UNSUPPORTED_LOCALE = \"runtime:unsupported-locale\",\n CONFIG_RESOLUTION_FAILED = \"runtime:config-resolution-failed\",\n\n // Service layer\n INTERFACE_NOT_FOUND = \"runtime:interface-not-found\",\n AMBIGUOUS_DEPENDENCY = \"runtime:ambiguous-dependency\",\n UNDECLARED_DEPENDENCY = \"runtime:undeclared-dependency\",\n SERVICE_CONSTRUCTION_FAILED = \"runtime:service-construction-failed\",\n SERVICE_DESTRUCTION_FAILED = \"runtime:service-destruction-failed\",\n DUPLICATE_INTERFACE = \"runtime:duplicate-interface\",\n DEPENDENCY_CYCLE = \"runtime:dependency-cycle\",\n\n // Web component API\n DUPLICATE_API_METHODS = \"runtime:duplicate-api-methods\",\n\n // Internal\n INTERNAL = \"runtime:internal-error\"\n}\n"],"names":["ErrorId"],"mappings":"AAEY,IAAA,OAAA,qBAAAA,QAAL,KAAA;AAEH,EAAAA,SAAA,kBAAmB,CAAA,GAAA,0BAAA,CAAA;AACnB,EAAAA,SAAA,uBAAwB,CAAA,GAAA,+BAAA,CAAA;AACxB,EAAAA,SAAA,mBAAoB,CAAA,GAAA,2BAAA,CAAA;AAGpB,EAAAA,SAAA,aAAc,CAAA,GAAA,6BAAA,CAAA;AACd,EAAAA,SAAA,oBAAqB,CAAA,GAAA,4BAAA,CAAA;AACrB,EAAAA,SAAA,0BAA2B,CAAA,GAAA,kCAAA,CAAA;AAG3B,EAAAA,SAAA,qBAAsB,CAAA,GAAA,6BAAA,CAAA;AACtB,EAAAA,SAAA,sBAAuB,CAAA,GAAA,8BAAA,CAAA;AACvB,EAAAA,SAAA,uBAAwB,CAAA,GAAA,+BAAA,CAAA;AACxB,EAAAA,SAAA,6BAA8B,CAAA,GAAA,qCAAA,CAAA;AAC9B,EAAAA,SAAA,4BAA6B,CAAA,GAAA,oCAAA,CAAA;AAC7B,EAAAA,SAAA,qBAAsB,CAAA,GAAA,6BAAA,CAAA;AACtB,EAAAA,SAAA,kBAAmB,CAAA,GAAA,0BAAA,CAAA;AAGnB,EAAAA,SAAA,uBAAwB,CAAA,GAAA,+BAAA,CAAA;AAGxB,EAAAA,SAAA,UAAW,CAAA,GAAA,wBAAA,CAAA;AAxBH,EAAAA,OAAAA,QAAAA,CAAAA;AAAA,CAAA,EAAA,OAAA,IAAA,EAAA;;;;"}
|
package/i18n.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"i18n.js","sources":["
|
|
1
|
+
{"version":3,"file":"i18n.js","sources":["i18n.ts"],"sourcesContent":["// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { createIntl, createIntlCache, IntlFormatters, IntlShape } from \"@formatjs/intl\";\nimport { ErrorId } from \"./errors\";\nimport { createLogger, Error } from \"@open-pioneer/core\";\nimport { ApplicationMetadata } from \"./metadata\";\nconst LOG = createLogger(\"runtime:i18n\");\n\n/**\n * Represents i18n info for the entire application.\n * Currently not exposed to user code.\n */\nexport interface AppI18n {\n /** Chosen locale */\n readonly locale: string;\n\n /** Supported locales from app metadata. */\n readonly supportedLocales: string[];\n\n /** Given the package name, constructs a package i18n instance. */\n createPackageI18n(packageName: string): PackageIntl;\n}\n\n/**\n * Gives access to the package's i18n messages for the current locale.\n *\n * See also https://formatjs.io/docs/intl\n */\nexport type PackageIntl = Pick<IntlShape, \"locale\" | \"timeZone\"> & IntlFormatters<string>;\n\nfunction createPackageIntl(locale: string, messages: Record<string, string>) {\n const cache = createIntlCache();\n return createIntl(\n {\n locale,\n messages\n },\n cache\n );\n}\n\n/**\n * Initializes the application's locale and fetches the appropriate i18n messages.\n */\nexport async function initI18n(\n appMetadata: ApplicationMetadata | undefined,\n forcedLocale: string | undefined\n): Promise<AppI18n> {\n const supportedLocales = appMetadata?.locales ?? [];\n const userLocales = getBrowserLocales();\n if (LOG.isDebug()) {\n LOG.debug(\n `Attempting to pick locale for user (locales: ${userLocales.join(\n \", \"\n )}) from app (supported locales: ${supportedLocales.join(\n \", \"\n )}) [forcedLocale=${forcedLocale}].`\n );\n }\n\n const { locale, messageLocale } = pickLocale(\n forcedLocale,\n supportedLocales,\n getBrowserLocales()\n );\n\n if (LOG.isDebug()) {\n LOG.debug(`Using locale '${locale}' with messages from locale '${messageLocale}'.`);\n }\n\n let messages: Record<string, Record<string, string>>;\n if (supportedLocales.includes(messageLocale)) {\n try {\n messages = (await appMetadata?.loadMessages?.(messageLocale)) ?? {};\n } catch (e) {\n throw new Error(\n ErrorId.INTERNAL,\n `Failed to load messages for locale '${messageLocale}'.`,\n {\n cause: e\n }\n );\n }\n }\n return {\n locale,\n supportedLocales,\n createPackageI18n(packageName) {\n const packageMessage = messages?.[packageName] ?? {};\n return createPackageIntl(locale, packageMessage);\n }\n };\n}\n\n/** Creates an empty i18n instance, e.g. for tests. */\nexport function createEmptyI18n(locale = \"en\"): PackageIntl {\n return createPackageIntl(locale, {});\n}\n\nexport interface LocalePickResult {\n /** The actual locale (e.g. en-US) for number and date formatting etc. */\n locale: string;\n\n /**\n * The locale identifier to load messages for. E.g. \"en\".\n */\n messageLocale: string;\n}\n\n/**\n * Picks a locale for the app. Exported for tests.\n *\n * @param forcedLocale Optional forced locale (must be satisfied)\n * @param appLocales Locales the app has i18n messages for (e.g. \"en\", \"de\")\n * @param userLocales Locales requested by the user's browser\n */\nexport function pickLocale(\n forcedLocale: string | undefined,\n appLocales: string[],\n userLocales: string[]\n): LocalePickResult {\n const pickImpl = (requestedLocales: string[]): LocalePickResult | undefined => {\n for (const requestedLocale of requestedLocales) {\n // try exact match\n if (appLocales.includes(requestedLocale)) {\n return { messageLocale: requestedLocale, locale: requestedLocale };\n }\n\n // try plain language tag (e.g. \"en\") as fallback\n const plainLanguage = requestedLocale.match(/^([a-z]+)/i)?.[1];\n if (plainLanguage && appLocales.includes(plainLanguage)) {\n return { messageLocale: plainLanguage, locale: requestedLocale };\n }\n }\n return undefined;\n };\n\n // Attempt to satisfy forced locale\n if (forcedLocale) {\n const result = pickImpl([forcedLocale]);\n if (!result) {\n const localesList = appLocales.join(\", \");\n throw new Error(\n ErrorId.UNSUPPORTED_LOCALE,\n `Locale '${forcedLocale}' cannot be forced because it is not supported by the application.` +\n ` Supported locales are ${localesList}.`\n );\n }\n if (result.locale !== result.messageLocale) {\n LOG.warn(\n `Non-exact match for forced locale '${forcedLocale}': using messages from '${result.messageLocale}'.`\n );\n }\n return result;\n }\n\n // Match preferred locale\n const supportedLocale = pickImpl(userLocales);\n if (supportedLocale) {\n return supportedLocale;\n }\n\n // Fallback: Most preferred locale (for dates etc.), but some of our messages\n return { locale: userLocales[0] ?? \"en\", messageLocale: appLocales[0] ?? \"en\" };\n}\n\n/**\n * Returns locales supported by the browser, in order of preference (preferred first).\n *\n * See also https://developer.mozilla.org/en-US/docs/Web/API/Navigator/languages\n */\nfunction getBrowserLocales(): string[] {\n if (window.navigator.languages && window.navigator.languages.length) {\n return Array.from(window.navigator.languages);\n }\n return [window.navigator.language];\n}\n"],"names":[],"mappings":";;;;AAMA,MAAM,GAAA,GAAM,aAAa,cAAc,CAAA,CAAA;AAwBvC,SAAS,iBAAA,CAAkB,QAAgB,QAAkC,EAAA;AACzE,EAAA,MAAM,QAAQ,eAAgB,EAAA,CAAA;AAC9B,EAAO,OAAA,UAAA;AAAA,IACH;AAAA,MACI,MAAA;AAAA,MACA,QAAA;AAAA,KACJ;AAAA,IACA,KAAA;AAAA,GACJ,CAAA;AACJ,CAAA;AAKsB,eAAA,QAAA,CAClB,aACA,YACgB,EAAA;AAChB,EAAM,MAAA,gBAAA,GAAmB,WAAa,EAAA,OAAA,IAAW,EAAC,CAAA;AAClD,EAAA,MAAM,cAAc,iBAAkB,EAAA,CAAA;AACtC,EAAI,IAAA,GAAA,CAAI,SAAW,EAAA;AACf,IAAI,GAAA,CAAA,KAAA;AAAA,MACA,gDAAgD,WAAY,CAAA,IAAA;AAAA,QACxD,IAAA;AAAA,yCAC+B,gBAAiB,CAAA,IAAA;AAAA,QAChD,IAAA;AAAA,OACgB,CAAA,gBAAA,EAAA,YAAA,CAAA,EAAA,CAAA;AAAA,KACxB,CAAA;AAAA,GACJ;AAEA,EAAM,MAAA,EAAE,MAAQ,EAAA,aAAA,EAAkB,GAAA,UAAA;AAAA,IAC9B,YAAA;AAAA,IACA,gBAAA;AAAA,IACA,iBAAk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,CAAC,CAAA,IAAK,IAAK,EAAA,CAAA;AAClF,CAAA;AAOA,SAAS,iBAA8B,GAAA;AACnC,EAAA,IAAI,OAAO,SAAU,CAAA,SAAA,IAAa,MAAO,CAAA,SAAA,CAAU,UAAU,MAAQ,EAAA;AACjE,IAAA,OAAO,KAAM,CAAA,IAAA,CAAK,MAAO,CAAA,SAAA,CAAU,SAAS,CAAA,CAAA;AAAA,GAChD;AACA,EAAO,OAAA,CAAC,MAAO,CAAA,SAAA,CAAU,QAAQ,CAAA,CAAA;AACrC;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ObservableBox.js","sources":["
|
|
1
|
+
{"version":3,"file":"ObservableBox.js","sources":["ObservableBox.ts"],"sourcesContent":["// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { EventEmitter, Resource } from \"@open-pioneer/core\";\n\nexport interface ObservableBox<T> {\n /** The current value. */\n readonly value: T;\n\n /**\n * Changes the current value.\n *\n * Note that this function is only present during development to facilitate hot reloading.\n */\n setValue?(value: T): void;\n\n /**\n * Register a listener callback that will be invoked\n * when the value changes.\n *\n * Note that this function is only present during development to facilitate hot reloading.\n */\n on?(event: \"changed\", listener: () => void): Resource;\n}\n\n/**\n * Returns a boxed value.\n * In development node, the box value can be changed and observed.\n */\nexport function createBox<T>(value: T): ObservableBox<T> {\n if (import.meta.env.DEV) {\n return new BoxImpl(value);\n } else {\n return {\n value\n };\n }\n}\n\nclass BoxImpl<T> extends EventEmitter<{ changed: void }> implements Required<ObservableBox<T>> {\n value: T;\n\n constructor(value: T) {\n super();\n this.value = value;\n }\n\n setValue(value: T): void {\n this.value = value;\n this.emit(\"changed\");\n }\n}\n"],"names":[],"mappings":";;AA4BO,SAAS,UAAa,KAA4B,EAAA;AACrD,EAAI,IAAA,MAAA,CAAA,IAAA,CAAY,IAAI,GAAK,EAAA;AACrB,IAAO,OAAA,IAAI,QAAQ,KAAK,CAAA,CAAA;AAAA,GACrB,MAAA;AACH,IAAO,OAAA;AAAA,MACH,KAAA;AAAA,KACJ,CAAA;AAAA,GACJ;AACJ,CAAA;AAEA,MAAM,gBAAmB,YAAsE,CAAA;AAAA,EAC3F,KAAA,CAAA;AAAA,EAEA,YAAY,KAAU,EAAA;AAClB,IAAM,KAAA,EAAA,CAAA;AACN,IAAA,IAAA,CAAK,KAAQ,GAAA,KAAA,CAAA;AAAA,GACjB;AAAA,EAEA,SAAS,KAAgB,EAAA;AACrB,IAAA,IAAA,CAAK,KAAQ,GAAA,KAAA,CAAA;AACb,IAAA,IAAA,CAAK,KAAK,SAAS,CAAA,CAAA;AAAA,GACvB;AACJ;;;;"}
|
package/package.json
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"type": "module",
|
|
3
3
|
"name": "@open-pioneer/runtime",
|
|
4
|
-
"version": "0.1.
|
|
4
|
+
"version": "0.1.1",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"dependencies": {
|
|
7
7
|
"@formatjs/intl": "^2.7.2",
|
|
8
8
|
"react": "^18.2.0",
|
|
9
9
|
"react-dom": "^18.2.0",
|
|
10
|
-
"@open-pioneer/chakra-integration": "^0.1.
|
|
11
|
-
"@open-pioneer/core": "^0.1.
|
|
10
|
+
"@open-pioneer/chakra-integration": "^0.1.1",
|
|
11
|
+
"@open-pioneer/core": "^0.1.1"
|
|
12
12
|
},
|
|
13
13
|
"exports": {
|
|
14
14
|
"./package.json": "./package.json",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PackageContext.js","sources":["
|
|
1
|
+
{"version":3,"file":"PackageContext.js","sources":["PackageContext.ts"],"sourcesContent":["// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { createContext } from \"react\";\nimport { PackageIntl } from \"../i18n\";\nimport { Service } from \"../Service\";\nimport { UseServiceOptions } from \"./hooks\";\n\nexport interface PackageContextMethods {\n getService: (packageName: string, interfaceName: string, options: UseServiceOptions) => Service;\n getServices: (packageName: string, interfaceName: string) => Service[];\n getProperties: (packageName: string) => Readonly<Record<string, unknown>>;\n getIntl(packageName: string): PackageIntl;\n}\n\nexport const PackageContext = createContext<PackageContextMethods | null>(null);\n"],"names":[],"mappings":";;AAca,MAAA,cAAA,GAAiB,cAA4C,IAAI;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ReactIntegration.js","sources":["
|
|
1
|
+
{"version":3,"file":"ReactIntegration.js","sources":["ReactIntegration.tsx"],"sourcesContent":["// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ComponentType, StrictMode } from \"react\";\nimport { createRoot, Root } from \"react-dom/client\";\nimport { Error } from \"@open-pioneer/core\";\nimport { ErrorId } from \"../errors\";\nimport { ServiceLayer } from \"../service-layer/ServiceLayer\";\nimport { PackageContext, PackageContextMethods } from \"./PackageContext\";\nimport { PackageRepr } from \"../service-layer/PackageRepr\";\nimport { InterfaceSpec, renderInterfaceSpec } from \"../service-layer/InterfaceSpec\";\nimport { renderAmbiguousServiceChoices } from \"../service-layer/ServiceLookup\";\nimport { CustomChakraProvider } from \"@open-pioneer/chakra-integration\";\n\nexport interface ReactIntegrationOptions {\n packages: Map<string, PackageRepr>;\n serviceLayer: ServiceLayer;\n rootNode: HTMLDivElement;\n container: Node;\n}\n\nexport class ReactIntegration {\n private containerNode: Node;\n private packages: Map<string, PackageRepr>;\n private serviceLayer: ServiceLayer;\n private root: Root;\n private packageContext: PackageContextMethods;\n\n constructor(options: ReactIntegrationOptions) {\n this.containerNode = options.container;\n this.packages = options.packages;\n this.serviceLayer = options.serviceLayer;\n this.root = createRoot(options.rootNode);\n this.packageContext = {\n getService: (packageName, interfaceName, options) => {\n const spec: InterfaceSpec = { interfaceName, ...options };\n const result = this.serviceLayer.getService(packageName, spec);\n if (result.type === \"found\") {\n return result.value.getInstanceOrThrow();\n }\n\n const renderedSpec = renderInterfaceSpec(spec);\n switch (result.type) {\n case \"unimplemented\":\n throw new Error(\n ErrorId.INTERFACE_NOT_FOUND,\n `The UI of package '${packageName}' requested the unimplemented interface ${renderedSpec}.`\n );\n case \"undeclared\":\n throw new Error(\n ErrorId.UNDECLARED_DEPENDENCY,\n `Package '${packageName}' did not declare an UI dependency on interface ${renderedSpec}.` +\n ` Add the dependency to the package configuration or remove the usage.`\n );\n case \"ambiguous\": {\n const renderedChoices = renderAmbiguousServiceChoices(result.choices);\n throw new Error(\n ErrorId.AMBIGUOUS_DEPENDENCY,\n `The UI of package '${packageName}' requires the ambiguous interface ${renderedSpec}.` +\n ` Possible choices are: ${renderedChoices}.`\n );\n }\n }\n },\n getServices: (packageName, interfaceName) => {\n const result = this.serviceLayer.getServices(packageName, interfaceName);\n if (result.type === \"found\") {\n return result.value.map((serviceRepr) => serviceRepr.getInstanceOrThrow());\n }\n\n switch (result.type) {\n case \"undeclared\":\n throw new Error(\n ErrorId.UNDECLARED_DEPENDENCY,\n `Package '${packageName}' did not declare an UI dependency on all services implementing interface '${interfaceName}'.` +\n ` Add the dependency (\"all\": true) to the package configuration or remove the usage.`\n );\n }\n },\n getProperties: (packageName) => {\n return this.getPackage(packageName).properties;\n },\n getIntl: (packageName) => {\n return this.getPackage(packageName).intl;\n }\n };\n }\n\n render(Component: ComponentType, props: Record<string, unknown>) {\n this.root.render(\n <StrictMode>\n <CustomChakraProvider container={this.containerNode} colorMode=\"light\">\n <PackageContext.Provider value={this.packageContext}>\n <Component {...props} />\n </PackageContext.Provider>\n </CustomChakraProvider>\n </StrictMode>\n );\n }\n\n destroy() {\n this.root.unmount();\n }\n\n private getPackage(packageName: string): PackageRepr {\n const pkg = this.packages.get(packageName);\n if (!pkg) {\n throw new Error(\n ErrorId.INTERNAL,\n `Package '${packageName}' was not found in application.`\n );\n }\n return pkg;\n }\n}\n"],"names":["options"],"mappings":";;;;;;;;;;AAoBO,MAAM,gBAAiB,CAAA;AAAA,EAClB,aA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AA,CAAA,oBAAA,EAAA,EAAqB,WAAW,IAAK,CAAA,aAAA,EAAe,SAAU,EAAA,OAAA,EAC3D,QAAC,kBAAA,GAAA,CAAA,cAAA,CAAe,UAAf,EAAwB,KAAA,EAAO,KAAK,cACjC,EAAA,QAAA,kBAAA,GAAA,CAAC,aAAW,GAAG,KAAA,EAAO,CAC1B,EAAA,CAAA,EACJ,CACJ,EAAA,CAAA;AAAA,KACJ,CAAA;AAAA,GACJ;AAAA,EAEA,OAAU,GAAA;AACN,IAAA,IAAA,CAAK,KAAK,OAAQ,EAAA,CAAA;AAAA,GACtB;AAAA,EAEQ,WAAW,WAAkC,EAAA;AACjD,IAAA,MAAM,GAAM,GAAA,IAAA,CAAK,QAAS,CAAA,GAAA,CAAI,WAAW,CAAA,CAAA;AACzC,IAAA,IAAI,CAAC,GAAK,EAAA;AACN,MAAA,MAAM,IAAI,KAAA;AAAA,QACN,OAAQ,CAAA,QAAA;AAAA,QACR,CAAY,SAAA,EAAA,WAAA,CAAA,+BAAA,CAAA;AAAA,OAChB,CAAA;AAAA,KACJ;AACA,IAAO,OAAA,GAAA,CAAA;AAAA,GACX;AACJ;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hooks.js","sources":["
|
|
1
|
+
{"version":3,"file":"hooks.js","sources":["hooks.ts"],"sourcesContent":["// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { useContext, useMemo } from \"react\";\nimport { Error } from \"@open-pioneer/core\";\nimport { InterfaceName, ServiceType } from \"../ServiceRegistry\";\nimport { PackageContext as PackageContext, PackageContextMethods } from \"./PackageContext\";\nimport { ErrorId } from \"../errors\";\nimport { PackageIntl } from \"../i18n\";\n\n/*\n\n IMPORTANT\n =========\n\n The functions in this file are part of the public API.\n They are imported by code generated during separate package generation via:\n\n import { hookName } from '@open-pioneer/runtime/react-integration'\n\n The matching exports are in the neighboring `index.ts`.\n The interfaces of these hooks must remain stable so that already published packages can continue to work in the future.\n\n See also the implementation of @open-pioneer/build-package.\n\n*/\n\nexport interface UseServiceOptions {\n /** An additional qualifier to disambiguate service instances that implement the same interface. */\n qualifier?: string;\n}\n\n/**\n * Returns a service that implements the given interface.\n * Receives the package name of the importing package as a string.\n *\n * This is an internal hook that is typically called indirectly via the hook\n * provided from `\"open-pioneer:react-hooks\"`.\n *\n * @private\n */\nexport function useServiceInternal<Interface extends InterfaceName>(\n packageName: string,\n interfaceName: Interface,\n options?: UseServiceOptions\n): ServiceType<Interface>;\nexport function useServiceInternal(\n packageName: string,\n interfaceName: string,\n options?: UseServiceOptions\n): unknown;\nexport function useServiceInternal(\n packageName: string,\n interfaceName: string,\n options?: UseServiceOptions\n): unknown {\n const context = useContext(PackageContext);\n const service = useMemo(\n () =>\n checkContext(\"useService\", context).getService(\n packageName,\n interfaceName,\n options ?? {}\n ),\n [context, packageName, interfaceName, options]\n );\n return service;\n}\n\n/**\n * Returns all services that implement the given interface.\n * Receives the package name of the importing package as a string.\n *\n * This is an internal hook that is typically called indirectly via the hook\n * provided from `\"open-pioneer:react-hooks\"`.\n *\n * @private\n */\nexport function useServicesInternal<Interface extends InterfaceName>(\n packageName: string,\n interfaceName: Interface\n): ServiceType<Interface>[];\nexport function useServicesInternal(packageName: string, interfaceName: string): unknown[];\nexport function useServicesInternal(packageName: string, interfaceName: string): unknown[] {\n const context = useContext(PackageContext);\n const services = useMemo(\n () => checkContext(\"useServices\", context).getServices(packageName, interfaceName),\n [context, packageName, interfaceName]\n );\n return services;\n}\n\n/**\n * Returns the properties for the given package.\n *\n * This is an internal hook that is typically called indirectly via the hook\n * provided from `\"open-pioneer:react-hooks\"`.\n *\n * @private\n */\nexport function usePropertiesInternal(packageName: string): Readonly<Record<string, unknown>> {\n const context = useContext(PackageContext);\n return checkContext(\"useProperties\", context).getProperties(packageName);\n}\n\n/**\n * Returns the i18n object for the given package.\n *\n * This is an internal hook that is typically called indirectly via the hook\n * provided from `\"open-pioneer:react-hooks\"`.\n *\n * @private\n */\nexport function useIntlInternal(packageName: string): PackageIntl {\n const context = useContext(PackageContext);\n return checkContext(\"useIntl\", context).getIntl(packageName);\n}\n\nfunction checkContext(\n hookName: string,\n contextData: PackageContextMethods | null\n): PackageContextMethods {\n if (!contextData) {\n throw new Error(\n ErrorId.INTERNAL,\n `\"Failed to access package context from '${hookName}': react integration was not set up properly.`\n );\n }\n return contextData;\n}\n"],"names":[],"mappings":";;;;;AAkDgB,SAAA,kBAAA,CACZ,WACA,EAAA,aAAA,EACA,OACO,EAAA;AACP,EAAM,MAAA,OAAA,GAAU,WAAW,cAAc,CAAA,CAAA;AACzC,EAAA,MAAM,OAAU,GAAA,OAAA;AAAA,IACZ,MACI,YAAA,CAAa,YAAc,EAAA,OAAO,CAAE,CAAA,UAAA;AAAA,MAChC,WAAA;AAAA,MACA,aAAA;AAAA,MACA,WAAW,EAAC;AAAA,KAChB;AAAA,IACJ,CAAC,OAAA,EAAS,WAAa,EAAA,aAAA,EAAe,OAAO,CAAA;AAAA,GACjD,CAAA;AACA,EAAO,OAAA,OAAA,CAAA;AACX,CAAA;AAgBgB,SAAA,mBAAA,CAAoB,aAAqB,aAAkC,EAAA;AACvF,EAAM,MAAA,OAAA,GAAU,WAAW,cAAc,CAAA,CAAA;AACzC,EAAA,MAAM,QAAW,GAAA,OAAA;AAAA,IACb,MAAM,YAAa,CAAA,aAAA,EAAe,OAAO,CAAE,CAAA,WAAA,CAAY,aAAa,aAAa,CAAA;AAAA,IACjF,CAAC,OAAS,EAAA,WAAA,EAAa,aAAa,CAAA;AAAA,GACxC,CAAA;AACA,EAAO,OAAA,QAAA,CAAA;AACX,CAAA;AAUO,SAAS,sBAAsB,WAAwD,EAAA;AAC1F,EAAM,MAAA,OAAA,GAAU,WAAW,cAAc,CAAA,CAAA;AACzC,EAAA,OAAO,YAAa,CAAA,eAAA,EAAiB,OAAO,CAAA,CAAE,cAAc,WAAW,CAAA,CAAA;AAC3E,CAAA;AAUO,SAAS,gBAAgB,WAAkC,EAAA;AAC9D,EAAM,MAAA,OAAA,GAAU,WAAW,cAAc,CAAA,CAAA;AACzC,EAAA,OAAO,YAAa,CAAA,SAAA,EAAW,OAAO,CAAA,CAAE,QAAQ,WAAW,CAAA,CAAA;AAC/D,CAAA;AAEA,SAAS,YAAA,CACL,UACA,WACqB,EAAA;AACrB,EAAA,IAAI,CAAC,WAAa,EAAA;AACd,IAAA,MAAM,IAAI,KAAA;AAAA,MACN,OAAQ,CAAA,QAAA;AAAA,MACR,CAA2C,wCAAA,EAAA,QAAA,CAAA,6CAAA,CAAA;AAAA,KAC/C,CAAA;AAAA,GACJ;AACA,EAAO,OAAA,WAAA,CAAA;AACX;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"InterfaceSpec.js","sources":["
|
|
1
|
+
{"version":3,"file":"InterfaceSpec.js","sources":["InterfaceSpec.ts"],"sourcesContent":["// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Error } from \"@open-pioneer/core\";\nimport { ErrorId } from \"../errors\";\nimport { InterfaceReferenceMetadata } from \"../metadata\";\n\n/**\n * Describes the implementation of an interface.\n */\nexport interface InterfaceSpec {\n interfaceName: string;\n qualifier?: string | undefined;\n}\n\nexport function renderInterfaceSpec({ interfaceName, qualifier }: InterfaceSpec): string {\n return `'${interfaceName}'` + (qualifier ? ` (qualifier: '${qualifier}')` : \"\");\n}\n\nexport interface SingleImplementationSpec extends InterfaceSpec {\n all?: undefined;\n}\n\nexport interface AllImplementationsSpec extends Pick<InterfaceSpec, \"interfaceName\"> {\n all: true;\n}\n\n/**\n * Describes a reference to one or more implementations of an interface.\n */\nexport type ReferenceSpec = SingleImplementationSpec | AllImplementationsSpec;\n\nexport function parseReferenceSpec(metadata: InterfaceReferenceMetadata): ReferenceSpec {\n if (!metadata) {\n throw new Error(ErrorId.INVALID_METADATA, \"Missing reference metadata.\");\n }\n if (metadata.all && metadata.qualifier) {\n throw new Error(\n ErrorId.INVALID_METADATA,\n \"References can't use 'qualifier' and 'all' properties at the same time.\"\n );\n }\n if (metadata.all) {\n return {\n all: true,\n interfaceName: metadata.name\n };\n }\n return {\n interfaceName: metadata.name,\n qualifier: metadata.qualifier\n };\n}\n\nexport function isSingleImplementationSpec(spec: ReferenceSpec): spec is SingleImplementationSpec {\n return !spec.all;\n}\n\nexport function isAllImplementationsSpec(spec: ReferenceSpec): spec is AllImplementationsSpec {\n return spec.all === true;\n}\n"],"names":[],"mappings":";;;AAcO,SAAS,mBAAoB,CAAA,EAAE,aAAe,EAAA,SAAA,EAAoC,EAAA;AACrF,EAAA,OAAO,CAAI,CAAA,EAAA,aAAA,CAAA,CAAA,CAAA,IAAoB,SAAY,GAAA,CAAA,cAAA,EAAiB,SAAgB,CAAA,EAAA,CAAA,GAAA,EAAA,CAAA,CAAA;AAChF,CAAA;AAeO,SAAS,mBAAmB,QAAqD,EAAA;AACpF,EAAA,IAAI,CAAC,QAAU,EAAA;AACX,IAAA,MAAM,IAAI,KAAA,CAAM,OAAQ,CAAA,gBAAA,EAAkB,6BAA6B,CAAA,CAAA;AAAA,GAC3E;AACA,EAAI,IAAA,QAAA,CAAS,GAAO,IAAA,QAAA,CAAS,SAAW,EAAA;AACpC,IAAA,MAAM,IAAI,KAAA;AAAA,MACN,OAAQ,CAAA,gBAAA;AAAA,MACR,yEAAA;AAAA,KACJ,CAAA;AAAA,GACJ;AACA,EAAA,IAAI,SAAS,GAAK,EAAA;AACd,IAAO,OAAA;AAAA,MACH,GAAK,EAAA,IAAA;AAAA,MACL,eAAe,QAAS,CAAA,IAAA;AAAA,KAC5B,CAAA;AAAA,GACJ;AACA,EAAO,OAAA;AAAA,IACH,eAAe,QAAS,CAAA,IAAA;AAAA,IACxB,WAAW,QAAS,CAAA,SAAA;AAAA,GACxB,CAAA;AACJ,CAAA;AAEO,SAAS,2BAA2B,IAAuD,EAAA;AAC9F,EAAA,OAAO,CAAC,IAAK,CAAA,GAAA,CAAA;AACjB,CAAA;AAEO,SAAS,yBAAyB,IAAqD,EAAA;AAC1F,EAAA,OAAO,KAAK,GAAQ,KAAA,IAAA,CAAA;AACxB;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PackageRepr.js","sources":["
|
|
1
|
+
{"version":3,"file":"PackageRepr.js","sources":["PackageRepr.ts"],"sourcesContent":["// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Error } from \"@open-pioneer/core\";\nimport { ApplicationProperties } from \"../CustomElement\";\nimport { ErrorId } from \"../errors\";\nimport { PackageIntl, AppI18n } from \"../i18n\";\nimport { PackageMetadata, PropertyMetadata } from \"../metadata\";\nimport { parseReferenceSpec, ReferenceSpec } from \"./InterfaceSpec\";\nimport { ServiceRepr } from \"./ServiceRepr\";\n\nexport interface PackageReprOptions {\n name: string;\n intl: PackageIntl;\n services?: ServiceRepr[];\n uiReferences?: ReferenceSpec[];\n properties?: Record<string, unknown>;\n}\n\nexport class PackageRepr {\n static create(\n data: PackageMetadata,\n i18n: PackageIntl,\n customProperties?: Record<string, unknown>\n ): PackageRepr {\n const name = data.name;\n const properties = data.properties ?? {};\n const finalProperties = customizeProperties(name, properties, customProperties);\n const services = Object.entries(data.services ?? {}).map<ServiceRepr>(\n ([name, serviceData]) => {\n if (name !== serviceData.name) {\n throw new Error(\n ErrorId.INVALID_METADATA,\n \"Invalid metadata: service name mismatch.\"\n );\n }\n return ServiceRepr.create(data.name, serviceData, i18n, finalProperties);\n }\n );\n const uiReferences = data.ui?.references?.map((ref) => parseReferenceSpec(ref)) ?? [];\n return new PackageRepr({\n name,\n services,\n uiReferences,\n properties: finalProperties,\n intl: i18n\n });\n }\n\n /** Package name */\n readonly name: string;\n\n /** Services defined by the package */\n readonly services: readonly ServiceRepr[];\n\n /** Interfaces required by UI components. */\n readonly uiReferences: readonly Readonly<ReferenceSpec>[];\n\n /** Resolved (perhaps customized) package properties. */\n readonly properties: Readonly<Record<string, unknown>>;\n\n /** Locale-dependant i18n messages. */\n readonly intl: PackageIntl;\n\n constructor(options: PackageReprOptions) {\n const name = options.name;\n if (!isValidPackageName(name)) {\n throw new Error(ErrorId.INTERNAL, `Invalid package name: '${name}'.`);\n }\n\n this.name = name;\n this.services = options.services ?? [];\n this.uiReferences = options.uiReferences ?? [];\n this.properties = options.properties ?? {};\n this.intl = options.intl;\n }\n}\n\nexport function createPackages(\n packages: Record<string, PackageMetadata>,\n i18n: AppI18n,\n customProperties?: ApplicationProperties\n) {\n return Object.entries(packages).map<PackageRepr>(([name, packageMetadata]) => {\n if (name !== packageMetadata.name) {\n throw new Error(ErrorId.INVALID_METADATA, \"Invalid metadata: package name mismatch.\");\n }\n\n const packageI18n = i18n.createPackageI18n(name);\n return PackageRepr.create(packageMetadata, packageI18n, customProperties?.[name]);\n });\n}\n\n/**\n * Merges the declared properties of the package with the application-defined\n * custom properties.\n */\nfunction customizeProperties(\n packageName: string,\n properties: Record<string, PropertyMetadata>,\n customProperties: Record<string, unknown> = {}\n) {\n const merged: Record<string, unknown> = {};\n const required: string[] = [];\n for (const [key, propertyMetadata] of Object.entries(properties)) {\n merged[key] = propertyMetadata.value;\n if (propertyMetadata.required) {\n required.push(key);\n }\n }\n\n for (const [key, value] of Object.entries(customProperties)) {\n if (!hasProperty(merged, key)) {\n throw new Error(\n ErrorId.INVALID_PROPERTY_NAME,\n `Unexpected property name '${key}' for package '${packageName}': the property does not exist.`\n );\n }\n merged[key] = value;\n }\n\n for (const key of required) {\n const value = merged[key];\n if (value == null) {\n throw new Error(\n ErrorId.REQUIRED_PROPERTY,\n `Package '${packageName}' requires the property '${key}' to be initialized to a non-null value.`\n );\n }\n }\n\n return merged;\n}\n\nconst HAS_PROP = Object.prototype.hasOwnProperty;\n\nfunction hasProperty(object: unknown, key: string) {\n return HAS_PROP.call(object, key);\n}\n\n// http://json.schemastore.org/package\nconst NAME_REGEX = /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\\/)?[a-z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AAC/C,EAAO,OAAA,QAAA,CAAS,IAAK,CAAA,MAAA,EAAQ,GAAG,CAAA,CAAA;AACpC,CAAA;AAGA,MAAM,UAAa,GAAA,4DAAA,CAAA;AAEnB,SAAS,mBAAmB,IAAuB,EAAA;AAC/C,EAAO,OAAA,UAAA,CAAW,KAAK,IAAI,CAAA,CAAA;AAC/B;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ServiceLayer.js","sources":["open-pioneer://external-pioneer-packages/@open-pioneer/runtime/service-layer/ServiceLayer.ts"],"sourcesContent":["// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ServiceRepr } from \"./ServiceRepr\";\nimport { createLogger, Error } from \"@open-pioneer/core\";\nimport { ErrorId } from \"../errors\";\nimport {\n ComputedServiceDependencies,\n FrameworkDependency,\n UIDependency,\n verifyDependencies\n} from \"./verifyDependencies\";\nimport { PackageRepr } from \"./PackageRepr\";\nimport { ReadonlyServiceLookup, ServiceLookupResult, ServicesLookupResult } from \"./ServiceLookup\";\nimport {\n InterfaceSpec,\n isAllImplementationsSpec,\n isSingleImplementationSpec,\n ReferenceSpec,\n renderInterfaceSpec\n} from \"./InterfaceSpec\";\nimport { ReferenceMeta } from \"../Service\";\nimport { RUNTIME_PACKAGE_NAME } from \"../builtin-services\";\n\nconst LOG = createLogger(\"runtime:ServiceLayer\");\n\nexport type DynamicLookupResult = ServiceLookupResult | UndeclaredDependency;\n\nexport interface UndeclaredDependency {\n type: \"undeclared\";\n}\n\ninterface DependencyDeclarations {\n all: boolean;\n unqualified: boolean;\n qualifiers: Set<string>;\n}\n\nexport class ServiceLayer {\n // All services in the application.\n private allServices: ServiceRepr[];\n\n // Set of required services. These services and their dependencies will be started.\n private requiredServices: Set<ServiceRepr>;\n\n private serviceLookup: ReadonlyServiceLookup;\n\n // Service id --> Service dependencies\n private serviceDependencies: Map<string, ComputedServiceDependencies>;\n\n // Package name --> Interface name --> Declarations\n private declaredDependencies;\n private state: \"not-started\" | \"started\" | \"destroyed\" = \"not-started\";\n\n /**\n * Constructs a new service layer instance.\n * Requires the application's set of packages (from which services are taken)\n * and an optional set of forced references (interfaces whose implementing services will be started unconditionally).\n *\n * In its current form, the service layer will start only forced references and references needed by the UI (and their dependencies).\n */\n constructor(packages: readonly PackageRepr[], forcedReferences: ReferenceSpec[] = []) {\n const allServices = packages.map((pkg) => pkg.services).flat();\n const uiDependencies = packages\n .map((pkg) =>\n pkg.uiReferences.map<UIDependency>((dep) => {\n return {\n type: \"ui\",\n packageName: pkg.name,\n ...dep\n };\n })\n )\n .flat();\n const requiredReferences = [\n ...forcedReferences.map<FrameworkDependency>((r) => ({\n type: \"framework\",\n ...r\n })),\n ...uiDependencies\n ];\n const { serviceLookup, serviceDependencies } = verifyDependencies({\n services: allServices,\n requiredReferences: requiredReferences\n });\n\n this.allServices = allServices;\n this.requiredServices = getRequiredServices(requiredReferences, serviceLookup);\n this.serviceLookup = serviceLookup;\n this.serviceDependencies = serviceDependencies;\n this.declaredDependencies = buildDependencyIndex(packages);\n }\n\n destroy() {\n for (const service of this.requiredServices) {\n this.destroyService(service);\n }\n this.state = \"destroyed\";\n }\n\n start() {\n if (this.state !== \"not-started\") {\n throw new Error(ErrorId.INTERNAL, \"Service layer was already started.\");\n }\n\n for (const service of this.requiredServices) {\n this.createService(service);\n }\n this.state = \"started\";\n\n // Give warnings for unneeded services during development.\n if (import.meta.env.DEV) {\n const unneededServices = this.allServices\n .filter(\n (service) =>\n service.packageName !== RUNTIME_PACKAGE_NAME &&\n service.state === \"not-constructed\"\n )\n .map((service) => `'${service.id}'`);\n if (unneededServices.length) {\n const services = unneededServices.join(\", \");\n LOG.warn(\n `The following services are contained in the application but were not started: ${services}.`\n );\n }\n }\n }\n\n /**\n * Returns a service implementing the given interface.\n * Checks that the given package actually declared a dependency on that interface\n * to enforce coding guidelines.\n *\n * @param packageName the name of the package requesting the import\n * @param spec the interface specifier\n * @param options advanced options to customize lookup\n * @throws if the service layer is not in 'started' state or if no service implements the interface.\n */\n getService(\n packageName: string,\n spec: InterfaceSpec,\n options?: { ignoreDeclarationCheck?: boolean }\n ): ServiceLookupResult | UndeclaredDependency {\n if (this.state !== \"started\") {\n throw new Error(ErrorId.INTERNAL, \"Service layer is not started.\");\n }\n\n if (!options?.ignoreDeclarationCheck && !this.isDeclaredDependency(packageName, spec)) {\n return { type: \"undeclared\" };\n }\n\n return this.serviceLookup.lookupOne(spec);\n }\n\n /**\n * Returns all services implementing the given interface.\n * Requires that the dependency on all implementations has been declared in the package.\n *\n * @param packageName the name of the package requesting the import\n * @param interfaceName the interface name\n *\n * @throws if the service layer is not in 'started'.\n */\n getServices(\n packageName: string,\n interfaceName: string\n ): ServicesLookupResult | UndeclaredDependency {\n if (this.state !== \"started\") {\n throw new Error(ErrorId.INTERNAL, \"Service layer is not started.\");\n }\n\n if (!this.isDeclaredDependency(packageName, { interfaceName, all: true })) {\n return { type: \"undeclared\" };\n }\n\n return this.serviceLookup.lookupAll(interfaceName);\n }\n\n /**\n * Initializes the given service and its dependencies.\n * Dependencies are initialized before the service that requires them.\n */\n private createService(service: ServiceRepr) {\n if (service.state === \"constructed\") {\n const instance = service.getInstanceOrThrow();\n service.addRef();\n return instance;\n }\n if (service.state === \"constructing\") {\n throw new Error(ErrorId.INTERNAL, \"Cycle during service construction.\");\n }\n if (service.state !== \"not-constructed\") {\n throw new Error(ErrorId.INTERNAL, \"Invalid service state.\");\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const references: Record<string, any> = {};\n const referencesMeta: Record<string, ReferenceMeta | ReferenceMeta[]> = {};\n\n // Sets state to 'constructing' to detect cycles\n service.beforeCreate();\n\n // Initialize dependencies recursively before creating the current service.\n for (const [referenceName, serviceDeps] of Object.entries(this.getServiceDeps(service))) {\n const [referenceValue, referenceMeta] = this.getReference(serviceDeps);\n references[referenceName] = referenceValue;\n referencesMeta[referenceName] = referenceMeta;\n }\n\n // Sets state to 'constructed' to finish the state transition, useCount is 1.\n LOG.debug(`Creating service '${service.id}'.`);\n return service.create({ references, referencesMeta });\n }\n\n /**\n * Destroys the given service and its dependencies.\n * The dependencies are destroyed after the service.\n */\n private destroyService(service: ServiceRepr) {\n if (service.state === \"destroyed\") {\n return;\n }\n\n // Destroy the service before its dependencies (reverse order\n // compared to construction).\n if (service.removeRef() <= 0) {\n LOG.debug(`Destroying service '${service.id}'`);\n service.destroy();\n }\n\n for (const serviceDeps of Object.values(this.getServiceDeps(service))) {\n if (Array.isArray(serviceDeps)) {\n for (const dep of serviceDeps) {\n this.destroyService(dep);\n }\n } else {\n this.destroyService(serviceDeps);\n }\n }\n }\n\n private isDeclaredDependency(packageName: string, spec: ReferenceSpec) {\n const packageEntry = this.declaredDependencies.get(packageName);\n if (!packageEntry) {\n return false;\n }\n const interfaceEntry = packageEntry.get(spec.interfaceName);\n if (!interfaceEntry) {\n return false;\n }\n\n if (isSingleImplementationSpec(spec)) {\n if (spec.qualifier == null) {\n return interfaceEntry.unqualified;\n }\n return interfaceEntry.qualifiers.has(spec.qualifier);\n } else {\n return interfaceEntry.all;\n }\n }\n\n private getReference(ref: ServiceRepr): [unknown, ReferenceMeta];\n private getReference(ref: ServiceRepr[]): [unknown[], ReferenceMeta[]];\n private getReference(\n ref: ServiceRepr | ServiceRepr[]\n ): [unknown, ReferenceMeta] | [unknown[], ReferenceMeta[]];\n private getReference(\n ref: ServiceRepr | ServiceRepr[]\n ): [unknown, ReferenceMeta] | [unknown[], ReferenceMeta[]] {\n if (Array.isArray(ref)) {\n const referenceValues: unknown[] = [];\n const referenceMeta: ReferenceMeta[] = [];\n for (const d of ref) {\n const [value, meta] = this.getReference(d);\n referenceValues.push(value);\n referenceMeta.push(meta);\n }\n return [referenceValues, referenceMeta];\n }\n\n const referenceValue = this.createService(ref);\n const referenceMeta: ReferenceMeta = {\n serviceId: ref.id\n };\n return [referenceValue, referenceMeta];\n }\n\n private getServiceDeps(service: ServiceRepr) {\n const dependencies = this.serviceDependencies.get(service.id);\n if (!dependencies) {\n throw new Error(\n ErrorId.INTERNAL,\n `Failed to find precomputed service dependencies for '${service.id}'.`\n );\n }\n return dependencies;\n }\n}\n\nfunction getRequiredServices(\n requiredReferences: readonly ReferenceSpec[],\n serviceLookup: ReadonlyServiceLookup\n): Set<ServiceRepr> {\n const requiredServices = new Set<ServiceRepr>();\n for (const referenceSpec of requiredReferences) {\n const result = serviceLookup.lookup(referenceSpec);\n if (result.type !== \"found\") {\n // Should be caught by verifier\n throw new Error(\n ErrorId.INTERNAL,\n `Failed to find required reference to ${renderInterfaceSpec(referenceSpec)}.`\n );\n }\n if (Array.isArray(result.value)) {\n for (const service of result.value) {\n requiredServices.add(service);\n }\n } else {\n requiredServices.add(result.value);\n }\n }\n return requiredServices;\n}\n\nfunction buildDependencyIndex(packages: readonly PackageRepr[]) {\n // Register declared UI dependencies.\n // This is needed as a lookup structure to that dynamic service lookups\n // can be validated at runtime.\n const index = new Map<string, Map<string, DependencyDeclarations>>();\n for (const pkg of packages) {\n const packageName = pkg.name;\n const packageEntry = new Map<string, DependencyDeclarations>();\n for (const uiReference of pkg.uiReferences) {\n let interfaceEntry = packageEntry.get(uiReference.interfaceName);\n if (!interfaceEntry) {\n interfaceEntry = {\n all: false,\n unqualified: false,\n qualifiers: new Set<string>()\n };\n packageEntry.set(uiReference.interfaceName, interfaceEntry);\n }\n\n if (isAllImplementationsSpec(uiReference)) {\n interfaceEntry.all = true;\n } else if (isSingleImplementationSpec(uiReference)) {\n if (uiReference.qualifier == null) {\n interfaceEntry.unqualified = true;\n } else {\n interfaceEntry.qualifiers.add(uiReference.qualifier);\n }\n } else {\n throw new Error(ErrorId.INTERNAL, `Unexpected implementation spec.`);\n }\n }\n index.set(packageName, packageEntry);\n }\n return index;\n}\n"],"names":["referenceMeta"],"mappings":";;;;;;AAuBA,MAAM,GAAA,GAAM,aAAa,sBAAsB,CAAA,CAAA;AAcxC,MAAM,YAAa,CAAA;AAAA;AAAA,EAEd,WAAA,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A,CAAA;AAAA,OACzB,MAAA,IAAW,0BAA2B,CAAA,WAAW,CAAG,EAAA;AAChD,QAAI,IAAA,WAAA,CAAY,aAAa,IAAM,EAAA;AAC/B,UAAA,cAAA,CAAe,WAAc,GAAA,IAAA,CAAA;AAAA,SAC1B,MAAA;AACH,UAAe,cAAA,CAAA,UAAA,CAAW,GAAI,CAAA,WAAA,CAAY,SAAS,CAAA,CAAA;AAAA,SACvD;AAAA,OACG,MAAA;AACH,QAAA,MAAM,IAAI,KAAA,CAAM,OAAQ,CAAA,QAAA,EAAU,CAAiC,+BAAA,CAAA,CAAA,CAAA;AAAA,OACvE;AAAA,KACJ;AACA,IAAM,KAAA,CAAA,GAAA,CAAI,aAAa,YAAY,CAAA,CAAA;AAAA,GACvC;AACA,EAAO,OAAA,KAAA,CAAA;AACX;;;;"}
|
|
1
|
+
{"version":3,"file":"ServiceLayer.js","sources":["ServiceLayer.ts"],"sourcesContent":["// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ServiceRepr } from \"./ServiceRepr\";\nimport { createLogger, Error } from \"@open-pioneer/core\";\nimport { ErrorId } from \"../errors\";\nimport {\n ComputedServiceDependencies,\n FrameworkDependency,\n UIDependency,\n verifyDependencies\n} from \"./verifyDependencies\";\nimport { PackageRepr } from \"./PackageRepr\";\nimport { ReadonlyServiceLookup, ServiceLookupResult, ServicesLookupResult } from \"./ServiceLookup\";\nimport {\n InterfaceSpec,\n isAllImplementationsSpec,\n isSingleImplementationSpec,\n ReferenceSpec,\n renderInterfaceSpec\n} from \"./InterfaceSpec\";\nimport { ReferenceMeta } from \"../Service\";\nimport { RUNTIME_PACKAGE_NAME } from \"../builtin-services\";\n\nconst LOG = createLogger(\"runtime:ServiceLayer\");\n\nexport type DynamicLookupResult = ServiceLookupResult | UndeclaredDependency;\n\nexport interface UndeclaredDependency {\n type: \"undeclared\";\n}\n\ninterface DependencyDeclarations {\n all: boolean;\n unqualified: boolean;\n qualifiers: Set<string>;\n}\n\nexport class ServiceLayer {\n // All services in the application.\n private allServices: ServiceRepr[];\n\n // Set of required services. These services and their dependencies will be started.\n private requiredServices: Set<ServiceRepr>;\n\n private serviceLookup: ReadonlyServiceLookup;\n\n // Service id --> Service dependencies\n private serviceDependencies: Map<string, ComputedServiceDependencies>;\n\n // Package name --> Interface name --> Declarations\n private declaredDependencies;\n private state: \"not-started\" | \"started\" | \"destroyed\" = \"not-started\";\n\n /**\n * Constructs a new service layer instance.\n * Requires the application's set of packages (from which services are taken)\n * and an optional set of forced references (interfaces whose implementing services will be started unconditionally).\n *\n * In its current form, the service layer will start only forced references and references needed by the UI (and their dependencies).\n */\n constructor(packages: readonly PackageRepr[], forcedReferences: ReferenceSpec[] = []) {\n const allServices = packages.map((pkg) => pkg.services).flat();\n const uiDependencies = packages\n .map((pkg) =>\n pkg.uiReferences.map<UIDependency>((dep) => {\n return {\n type: \"ui\",\n packageName: pkg.name,\n ...dep\n };\n })\n )\n .flat();\n const requiredReferences = [\n ...forcedReferences.map<FrameworkDependency>((r) => ({\n type: \"framework\",\n ...r\n })),\n ...uiDependencies\n ];\n const { serviceLookup, serviceDependencies } = verifyDependencies({\n services: allServices,\n requiredReferences: requiredReferences\n });\n\n this.allServices = allServices;\n this.requiredServices = getRequiredServices(requiredReferences, serviceLookup);\n this.serviceLookup = serviceLookup;\n this.serviceDependencies = serviceDependencies;\n this.declaredDependencies = buildDependencyIndex(packages);\n }\n\n destroy() {\n for (const service of this.requiredServices) {\n this.destroyService(service);\n }\n this.state = \"destroyed\";\n }\n\n start() {\n if (this.state !== \"not-started\") {\n throw new Error(ErrorId.INTERNAL, \"Service layer was already started.\");\n }\n\n for (const service of this.requiredServices) {\n this.createService(service);\n }\n this.state = \"started\";\n\n // Give warnings for unneeded services during development.\n if (import.meta.env.DEV) {\n const unneededServices = this.allServices\n .filter(\n (service) =>\n service.packageName !== RUNTIME_PACKAGE_NAME &&\n service.state === \"not-constructed\"\n )\n .map((service) => `'${service.id}'`);\n if (unneededServices.length) {\n const services = unneededServices.join(\", \");\n LOG.warn(\n `The following services are contained in the application but were not started: ${services}.`\n );\n }\n }\n }\n\n /**\n * Returns a service implementing the given interface.\n * Checks that the given package actually declared a dependency on that interface\n * to enforce coding guidelines.\n *\n * @param packageName the name of the package requesting the import\n * @param spec the interface specifier\n * @param options advanced options to customize lookup\n * @throws if the service layer is not in 'started' state or if no service implements the interface.\n */\n getService(\n packageName: string,\n spec: InterfaceSpec,\n options?: { ignoreDeclarationCheck?: boolean }\n ): ServiceLookupResult | UndeclaredDependency {\n if (this.state !== \"started\") {\n throw new Error(ErrorId.INTERNAL, \"Service layer is not started.\");\n }\n\n if (!options?.ignoreDeclarationCheck && !this.isDeclaredDependency(packageName, spec)) {\n return { type: \"undeclared\" };\n }\n\n return this.serviceLookup.lookupOne(spec);\n }\n\n /**\n * Returns all services implementing the given interface.\n * Requires that the dependency on all implementations has been declared in the package.\n *\n * @param packageName the name of the package requesting the import\n * @param interfaceName the interface name\n *\n * @throws if the service layer is not in 'started'.\n */\n getServices(\n packageName: string,\n interfaceName: string\n ): ServicesLookupResult | UndeclaredDependency {\n if (this.state !== \"started\") {\n throw new Error(ErrorId.INTERNAL, \"Service layer is not started.\");\n }\n\n if (!this.isDeclaredDependency(packageName, { interfaceName, all: true })) {\n return { type: \"undeclared\" };\n }\n\n return this.serviceLookup.lookupAll(interfaceName);\n }\n\n /**\n * Initializes the given service and its dependencies.\n * Dependencies are initialized before the service that requires them.\n */\n private createService(service: ServiceRepr) {\n if (service.state === \"constructed\") {\n const instance = service.getInstanceOrThrow();\n service.addRef();\n return instance;\n }\n if (service.state === \"constructing\") {\n throw new Error(ErrorId.INTERNAL, \"Cycle during service construction.\");\n }\n if (service.state !== \"not-constructed\") {\n throw new Error(ErrorId.INTERNAL, \"Invalid service state.\");\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const references: Record<string, any> = {};\n const referencesMeta: Record<string, ReferenceMeta | ReferenceMeta[]> = {};\n\n // Sets state to 'constructing' to detect cycles\n service.beforeCreate();\n\n // Initialize dependencies recursively before creating the current service.\n for (const [referenceName, serviceDeps] of Object.entries(this.getServiceDeps(service))) {\n const [referenceValue, referenceMeta] = this.getReference(serviceDeps);\n references[referenceName] = referenceValue;\n referencesMeta[referenceName] = referenceMeta;\n }\n\n // Sets state to 'constructed' to finish the state transition, useCount is 1.\n LOG.debug(`Creating service '${service.id}'.`);\n return service.create({ references, referencesMeta });\n }\n\n /**\n * Destroys the given service and its dependencies.\n * The dependencies are destroyed after the service.\n */\n private destroyService(service: ServiceRepr) {\n if (service.state === \"destroyed\") {\n return;\n }\n\n // Destroy the service before its dependencies (reverse order\n // compared to construction).\n if (service.removeRef() <= 0) {\n LOG.debug(`Destroying service '${service.id}'`);\n service.destroy();\n }\n\n for (const serviceDeps of Object.values(this.getServiceDeps(service))) {\n if (Array.isArray(serviceDeps)) {\n for (const dep of serviceDeps) {\n this.destroyService(dep);\n }\n } else {\n this.destroyService(serviceDeps);\n }\n }\n }\n\n private isDeclaredDependency(packageName: string, spec: ReferenceSpec) {\n const packageEntry = this.declaredDependencies.get(packageName);\n if (!packageEntry) {\n return false;\n }\n const interfaceEntry = packageEntry.get(spec.interfaceName);\n if (!interfaceEntry) {\n return false;\n }\n\n if (isSingleImplementationSpec(spec)) {\n if (spec.qualifier == null) {\n return interfaceEntry.unqualified;\n }\n return interfaceEntry.qualifiers.has(spec.qualifier);\n } else {\n return interfaceEntry.all;\n }\n }\n\n private getReference(ref: ServiceRepr): [unknown, ReferenceMeta];\n private getReference(ref: ServiceRepr[]): [unknown[], ReferenceMeta[]];\n private getReference(\n ref: ServiceRepr | ServiceRepr[]\n ): [unknown, ReferenceMeta] | [unknown[], ReferenceMeta[]];\n private getReference(\n ref: ServiceRepr | ServiceRepr[]\n ): [unknown, ReferenceMeta] | [unknown[], ReferenceMeta[]] {\n if (Array.isArray(ref)) {\n const referenceValues: unknown[] = [];\n const referenceMeta: ReferenceMeta[] = [];\n for (const d of ref) {\n const [value, meta] = this.getReference(d);\n referenceValues.push(value);\n referenceMeta.push(meta);\n }\n return [referenceValues, referenceMeta];\n }\n\n const referenceValue = this.createService(ref);\n const referenceMeta: ReferenceMeta = {\n serviceId: ref.id\n };\n return [referenceValue, referenceMeta];\n }\n\n private getServiceDeps(service: ServiceRepr) {\n const dependencies = this.serviceDependencies.get(service.id);\n if (!dependencies) {\n throw new Error(\n ErrorId.INTERNAL,\n `Failed to find precomputed service dependencies for '${service.id}'.`\n );\n }\n return dependencies;\n }\n}\n\nfunction getRequiredServices(\n requiredReferences: readonly ReferenceSpec[],\n serviceLookup: ReadonlyServiceLookup\n): Set<ServiceRepr> {\n const requiredServices = new Set<ServiceRepr>();\n for (const referenceSpec of requiredReferences) {\n const result = serviceLookup.lookup(referenceSpec);\n if (result.type !== \"found\") {\n // Should be caught by verifier\n throw new Error(\n ErrorId.INTERNAL,\n `Failed to find required reference to ${renderInterfaceSpec(referenceSpec)}.`\n );\n }\n if (Array.isArray(result.value)) {\n for (const service of result.value) {\n requiredServices.add(service);\n }\n } else {\n requiredServices.add(result.value);\n }\n }\n return requiredServices;\n}\n\nfunction buildDependencyIndex(packages: readonly PackageRepr[]) {\n // Register declared UI dependencies.\n // This is needed as a lookup structure to that dynamic service lookups\n // can be validated at runtime.\n const index = new Map<string, Map<string, DependencyDeclarations>>();\n for (const pkg of packages) {\n const packageName = pkg.name;\n const packageEntry = new Map<string, DependencyDeclarations>();\n for (const uiReference of pkg.uiReferences) {\n let interfaceEntry = packageEntry.get(uiReference.interfaceName);\n if (!interfaceEntry) {\n interfaceEntry = {\n all: false,\n unqualified: false,\n qualifiers: new Set<string>()\n };\n packageEntry.set(uiReference.interfaceName, interfaceEntry);\n }\n\n if (isAllImplementationsSpec(uiReference)) {\n interfaceEntry.all = true;\n } else if (isSingleImplementationSpec(uiReference)) {\n if (uiReference.qualifier == null) {\n interfaceEntry.unqualified = true;\n } else {\n interfaceEntry.qualifiers.add(uiReference.qualifier);\n }\n } else {\n throw new Error(ErrorId.INTERNAL, `Unexpected implementation spec.`);\n }\n }\n index.set(packageName, packageEntry);\n }\n return index;\n}\n"],"names":["referenceMeta"],"mappings":";;;;;;AAuBA,MAAM,GAAA,GAAM,aAAa,sBAAsB,CAAA,CAAA;AAcxC,MAAM,YAAa,CAAA;AAAA;AAAA,EAEd,WAAA,CAAA;AAAA;AAAA,EAGA,gBAAA,CAAA;AAAA,EAEA,aAAA,CAAA;AAAA;AAAA,EAGA,mBAAA,CAAA;AAAA;AAAA,EAGA,oBAAA,CAAA;AAAA,EACA,KAAiD,GAAA,aAAA,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASzD,WAAY,CAAA,QAAA,EAAkC,gBAAoC,GAAA,EAAI,EAAA;AAClF,IAAM,MAAA,WAAA,GAAc,SAAS,GAAI,CAAA,CAAC,QAAQ,GAAI,CAAA,QAAQ,EAAE,IAAK,EAAA,CAAA;AAC7D,IAAA,MAAM,iBAAiB,QAClB,CAAA,GAAA;AAAA,MAAI,CAAC,GACF,KAAA,GAAA,CAAI,YAAa,CAAA,GAAA,CAAkB,CAAC,GAAQ,KAAA;AACxC,QAAO,OAAA;AAAA,UACH,IAAM,EAAA,IAAA;AAAA,UACN,aAAa,GAAI,CAAA,IAAA;AAAA,UACjB,GAAG,GAAA;AAAA,SACP,CAAA;AAAA,OACH,CAAA;AAAA,MAEJ,IAAK,EAAA,CAAA;AACV,IAAA,MAAM,kBAAqB,GAAA;AAAA,MACvB,GAAG,gBAAA,CAAiB,GAAyB,CAAA,CAAC,CAAO,MAAA;AAAA,QACjD,IAAM,EAAA,WAAA;AAAA,QACN,GAAG,CAAA;AAAA,OACL,CAAA,CAAA;AAAA,MACF,GAAG,cAAA;AAAA,KACP,CAAA;AACA,IAAA,MAAM,EAAE,aAAA,EAAe,mBAAoB,EAAA,GAAI,kBAAmB,CAAA;AAAA,MAC9D,QAAU,EAAA,WAAA;AAAA,MACV,kBAAA;AAAA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UAAA,sBAAgB,GAAY,EAAA;AAAA,SAChC,CAAA;AACA,QAAa,YAAA,CAAA,GAAA,CAAI,WAAY,CAAA,aAAA,EAAe,cAAc,CAAA,CAAA;AAAA,OAC9D;AAEA,MAAI,IAAA,wBAAA,CAAyB,WAAW,CAAG,EAAA;AACvC,QAAA,cAAA,CAAe,GAAM,GAAA,IAAA,CAAA;AAAA,OACzB,MAAA,IAAW,0BAA2B,CAAA,WAAW,CAAG,EAAA;AAChD,QAAI,IAAA,WAAA,CAAY,aAAa,IAAM,EAAA;AAC/B,UAAA,cAAA,CAAe,WAAc,GAAA,IAAA,CAAA;AAAA,SAC1B,MAAA;AACH,UAAe,cAAA,CAAA,UAAA,CAAW,GAAI,CAAA,WAAA,CAAY,SAAS,CAAA,CAAA;AAAA,SACvD;AAAA,OACG,MAAA;AACH,QAAA,MAAM,IAAI,KAAA,CAAM,OAAQ,CAAA,QAAA,EAAU,CAAiC,+BAAA,CAAA,CAAA,CAAA;AAAA,OACvE;AAAA,KACJ;AACA,IAAM,KAAA,CAAA,GAAA,CAAI,aAAa,YAAY,CAAA,CAAA;AAAA,GACvC;AACA,EAAO,OAAA,KAAA,CAAA;AACX;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ServiceLookup.js","sources":["open-pioneer://external-pioneer-packages/@open-pioneer/runtime/service-layer/ServiceLookup.ts"],"sourcesContent":["// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Error } from \"@open-pioneer/core\";\nimport { ErrorId } from \"../errors\";\nimport { InterfaceSpec, isSingleImplementationSpec, ReferenceSpec } from \"./InterfaceSpec\";\nimport { ServiceRepr } from \"./ServiceRepr\";\n\ninterface Services {\n // The unqualified service implementations (if any).\n unqualified: ServiceRepr[];\n\n // Services indexed by their qualifier (if any).\n byQualifier: Map<string, ServiceRepr>;\n}\n\nexport type ReadonlyServiceLookup = Pick<\n ServiceLookup,\n \"lookup\" | \"lookupOne\" | \"lookupAll\" | \"serviceCount\"\n>;\n\nexport interface Unimplemented {\n type: \"unimplemented\";\n}\n\nexport interface Ambiguous {\n type: \"ambiguous\";\n choices: AmbiguousChoice[];\n}\n\nexport type AmbiguousChoice = [serviceId: string, qualifier: string | undefined];\n\nexport interface Found<T> {\n type: \"found\";\n value: T;\n}\n\nexport type ServiceLookupResult = Unimplemented | Ambiguous | Found<ServiceRepr>;\n\nexport type ServicesLookupResult = Found<ServiceRepr[]>;\n\nexport class ServiceLookup {\n // Service implementations indexed by interface name.\n private services = new Map<string, Services>();\n\n // Total service count\n private _count = 0;\n\n /**\n * Returns the total number of registered services.\n */\n get serviceCount() {\n return this._count;\n }\n\n /**\n * Attempts to register the given service as an implementation of `interfaceName`.\n * Throws if the registration did not complete successfully.\n *\n * All services should be registered before any lookups are attempted.\n */\n register(service: ServiceRepr, { interfaceName, qualifier }: InterfaceSpec): void {\n if (!interfaceName) {\n throw new Error(\n ErrorId.INVALID_METADATA,\n `Service '${service.id}' provides invalid interface '${interfaceName}'.`\n );\n }\n if (qualifier != null && !qualifier) {\n throw new Error(\n ErrorId.INVALID_METADATA,\n `Service '${service.id}' uses an invalid qualifier for interface '${interfaceName}': '${qualifier}'.`\n );\n }\n\n const services = this.ensureInterfaceEntry(interfaceName);\n if (!qualifier) {\n services.unqualified.push(service);\n ++this._count;\n return;\n }\n\n const existingQualified = services.byQualifier.get(qualifier);\n if (existingQualified) {\n throw new Error(\n ErrorId.DUPLICATE_INTERFACE,\n `Cannot register '${service.id}' as interface '${interfaceName}' with qualifier '${qualifier}'.` +\n ` The interface is already provided by service '${existingQualified.id}'.` +\n ` You can choose a different qualifier or remove the service to resolve the collision.`\n );\n }\n services.byQualifier.set(qualifier, service);\n ++this._count;\n }\n\n /**\n * Attempts to find the service(s) required by the given reference spec.\n */\n lookup(ref: ReferenceSpec): ServiceLookupResult | ServicesLookupResult {\n if (isSingleImplementationSpec(ref)) {\n return this.lookupOne(ref);\n } else {\n return this.lookupAll(ref.interfaceName);\n }\n }\n\n /**\n * Attempts to find a service implementing the given interface.\n */\n lookupOne({ interfaceName, qualifier }: InterfaceSpec): ServiceLookupResult {\n if (!interfaceName) {\n throw new Error(\n ErrorId.INVALID_METADATA,\n `Invalid interface name during service lookup: '${interfaceName}'.`\n );\n }\n if (qualifier != null && !qualifier) {\n throw new Error(\n ErrorId.INVALID_METADATA,\n `Invalid qualifier during service lookup of interface '${interfaceName}': '${qualifier}'.`\n );\n }\n\n const services = this.services.get(interfaceName);\n if (!services) {\n return { type: \"unimplemented\" };\n }\n\n if (!qualifier) {\n // Just pick one, but the choice must be unambiguous.\n const count = services.unqualified.length + services.byQualifier.size;\n if (count > 1) {\n // [serviceId, qualifier] tuples\n const choices: AmbiguousChoice[] = [];\n choices.push(\n ...Array.from(services.byQualifier.entries()).map<AmbiguousChoice>(\n ([qualifier, service]) => [service.id, qualifier]\n )\n );\n choices.push(\n ...services.unqualified.map<AmbiguousChoice>((s) => [s.id, undefined])\n );\n return {\n type: \"ambiguous\",\n choices: choices\n };\n }\n\n const service = services.unqualified[0] ?? first(services.byQualifier);\n if (!service) {\n return { type: \"unimplemented\" };\n }\n return { type: \"found\", value: service };\n }\n\n const service = services.byQualifier.get(qualifier);\n if (!service) {\n return { type: \"unimplemented\" };\n }\n return { type: \"found\", value: service };\n }\n\n /**\n * Returns all services implementing the given interface.\n */\n lookupAll(interfaceName: string): ServicesLookupResult {\n if (!interfaceName) {\n throw new Error(\n ErrorId.INVALID_METADATA,\n `Invalid interface name during service lookup: '${interfaceName}'.`\n );\n }\n\n const services = this.services.get(interfaceName);\n if (!services) {\n return { type: \"found\", value: [] };\n }\n\n const deduped = new Set([...services.unqualified, ...services.byQualifier.values()]);\n return {\n type: \"found\",\n value: Array.from(deduped)\n };\n }\n\n private ensureInterfaceEntry(interfaceName: string): Services {\n const services = this.services;\n let entry = services.get(interfaceName);\n if (!entry) {\n entry = {\n unqualified: [],\n byQualifier: new Map()\n };\n services.set(interfaceName, entry);\n }\n return entry;\n }\n}\n\nexport function renderAmbiguousServiceChoices(choices: AmbiguousChoice[], max = 3): string {\n let message = \"\";\n let count = 0;\n for (const [serviceId, qualifier] of choices) {\n if (count) {\n message += \", \";\n }\n\n message += `'${serviceId}'`;\n if (qualifier) {\n message += ` (with qualifier '${qualifier}')`;\n }\n\n if (++count >= max) {\n break;\n }\n }\n\n const remaining = choices.length - count;\n if (remaining > 0) {\n message += ` and ${remaining} more`;\n }\n return message;\n}\n\nfunction first<K, V>(map: Map<K, V>): V | undefined {\n return map.values().next().value;\n}\n"],"names":["qualifier","service"],"mappings":";;;;AAwCO,MAAM,aAAc,CAAA;AAAA;AAAA,EAEf,QAAA,uBAAe,GAAsB,EAAA,CAAA;AAAA;AAAA,EAGrC,MAAS,GAAA,CAAA,CAAA;AAAA;AAAA;AAAA;AAAA,EAKjB,IAAI,YAAe,GAAA;AACf,IAAA,OAAO,IAAK,CAAA,MAAA,CAAA;AAAA,GAChB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,QAAS,CAAA,OAAA,EAAsB,EAAE,aAAA,EAAe,WAAkC,EAAA;AAC9E,IAAA,IAAI,CAAC,aAAe,EAAA;AAChB,MAAA,MAAM,IAAI,KAAA;AAAA,QACN,OAAQ,CAAA,gBAAA;AAAA,QACR,CAAA,SAAA,EAAY,QAAQ,EAAmC,CAAA,8BAAA,EAAA,aAAA,CAAA,EAAA,CAAA;AAAA,OAC3D,CAAA;AAAA,KACJ;AACA,IAAI,IAAA,SAAA,IAAa,IAAQ,IAAA,CAAC,SAAW,EAAA;AACjC,MAAA,MAAM,IAAI,KAAA;AAAA,QACN,OAAQ,CAAA,gBAAA;AAAA,QACR,CAAA,SAAA,EAAY,OAAQ,CAAA,EAAA,CAAA,2CAAA,EAAgD,aAAoB,CAAA,IAAA,EAAA,SAAA,CAAA,EAAA,CAAA;AAAA,OAC5F,CAAA;AAAA,KACJ;AAEA,IAAM,MAAA,QAAA,GAAW,IAAK,CAAA,oB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KAAA,CAAA;AAC/B;;;;"}
|
|
1
|
+
{"version":3,"file":"ServiceLookup.js","sources":["ServiceLookup.ts"],"sourcesContent":["// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Error } from \"@open-pioneer/core\";\nimport { ErrorId } from \"../errors\";\nimport { InterfaceSpec, isSingleImplementationSpec, ReferenceSpec } from \"./InterfaceSpec\";\nimport { ServiceRepr } from \"./ServiceRepr\";\n\ninterface Services {\n // The unqualified service implementations (if any).\n unqualified: ServiceRepr[];\n\n // Services indexed by their qualifier (if any).\n byQualifier: Map<string, ServiceRepr>;\n}\n\nexport type ReadonlyServiceLookup = Pick<\n ServiceLookup,\n \"lookup\" | \"lookupOne\" | \"lookupAll\" | \"serviceCount\"\n>;\n\nexport interface Unimplemented {\n type: \"unimplemented\";\n}\n\nexport interface Ambiguous {\n type: \"ambiguous\";\n choices: AmbiguousChoice[];\n}\n\nexport type AmbiguousChoice = [serviceId: string, qualifier: string | undefined];\n\nexport interface Found<T> {\n type: \"found\";\n value: T;\n}\n\nexport type ServiceLookupResult = Unimplemented | Ambiguous | Found<ServiceRepr>;\n\nexport type ServicesLookupResult = Found<ServiceRepr[]>;\n\nexport class ServiceLookup {\n // Service implementations indexed by interface name.\n private services = new Map<string, Services>();\n\n // Total service count\n private _count = 0;\n\n /**\n * Returns the total number of registered services.\n */\n get serviceCount() {\n return this._count;\n }\n\n /**\n * Attempts to register the given service as an implementation of `interfaceName`.\n * Throws if the registration did not complete successfully.\n *\n * All services should be registered before any lookups are attempted.\n */\n register(service: ServiceRepr, { interfaceName, qualifier }: InterfaceSpec): void {\n if (!interfaceName) {\n throw new Error(\n ErrorId.INVALID_METADATA,\n `Service '${service.id}' provides invalid interface '${interfaceName}'.`\n );\n }\n if (qualifier != null && !qualifier) {\n throw new Error(\n ErrorId.INVALID_METADATA,\n `Service '${service.id}' uses an invalid qualifier for interface '${interfaceName}': '${qualifier}'.`\n );\n }\n\n const services = this.ensureInterfaceEntry(interfaceName);\n if (!qualifier) {\n services.unqualified.push(service);\n ++this._count;\n return;\n }\n\n const existingQualified = services.byQualifier.get(qualifier);\n if (existingQualified) {\n throw new Error(\n ErrorId.DUPLICATE_INTERFACE,\n `Cannot register '${service.id}' as interface '${interfaceName}' with qualifier '${qualifier}'.` +\n ` The interface is already provided by service '${existingQualified.id}'.` +\n ` You can choose a different qualifier or remove the service to resolve the collision.`\n );\n }\n services.byQualifier.set(qualifier, service);\n ++this._count;\n }\n\n /**\n * Attempts to find the service(s) required by the given reference spec.\n */\n lookup(ref: ReferenceSpec): ServiceLookupResult | ServicesLookupResult {\n if (isSingleImplementationSpec(ref)) {\n return this.lookupOne(ref);\n } else {\n return this.lookupAll(ref.interfaceName);\n }\n }\n\n /**\n * Attempts to find a service implementing the given interface.\n */\n lookupOne({ interfaceName, qualifier }: InterfaceSpec): ServiceLookupResult {\n if (!interfaceName) {\n throw new Error(\n ErrorId.INVALID_METADATA,\n `Invalid interface name during service lookup: '${interfaceName}'.`\n );\n }\n if (qualifier != null && !qualifier) {\n throw new Error(\n ErrorId.INVALID_METADATA,\n `Invalid qualifier during service lookup of interface '${interfaceName}': '${qualifier}'.`\n );\n }\n\n const services = this.services.get(interfaceName);\n if (!services) {\n return { type: \"unimplemented\" };\n }\n\n if (!qualifier) {\n // Just pick one, but the choice must be unambiguous.\n const count = services.unqualified.length + services.byQualifier.size;\n if (count > 1) {\n // [serviceId, qualifier] tuples\n const choices: AmbiguousChoice[] = [];\n choices.push(\n ...Array.from(services.byQualifier.entries()).map<AmbiguousChoice>(\n ([qualifier, service]) => [service.id, qualifier]\n )\n );\n choices.push(\n ...services.unqualified.map<AmbiguousChoice>((s) => [s.id, undefined])\n );\n return {\n type: \"ambiguous\",\n choices: choices\n };\n }\n\n const service = services.unqualified[0] ?? first(services.byQualifier);\n if (!service) {\n return { type: \"unimplemented\" };\n }\n return { type: \"found\", value: service };\n }\n\n const service = services.byQualifier.get(qualifier);\n if (!service) {\n return { type: \"unimplemented\" };\n }\n return { type: \"found\", value: service };\n }\n\n /**\n * Returns all services implementing the given interface.\n */\n lookupAll(interfaceName: string): ServicesLookupResult {\n if (!interfaceName) {\n throw new Error(\n ErrorId.INVALID_METADATA,\n `Invalid interface name during service lookup: '${interfaceName}'.`\n );\n }\n\n const services = this.services.get(interfaceName);\n if (!services) {\n return { type: \"found\", value: [] };\n }\n\n const deduped = new Set([...services.unqualified, ...services.byQualifier.values()]);\n return {\n type: \"found\",\n value: Array.from(deduped)\n };\n }\n\n private ensureInterfaceEntry(interfaceName: string): Services {\n const services = this.services;\n let entry = services.get(interfaceName);\n if (!entry) {\n entry = {\n unqualified: [],\n byQualifier: new Map()\n };\n services.set(interfaceName, entry);\n }\n return entry;\n }\n}\n\nexport function renderAmbiguousServiceChoices(choices: AmbiguousChoice[], max = 3): string {\n let message = \"\";\n let count = 0;\n for (const [serviceId, qualifier] of choices) {\n if (count) {\n message += \", \";\n }\n\n message += `'${serviceId}'`;\n if (qualifier) {\n message += ` (with qualifier '${qualifier}')`;\n }\n\n if (++count >= max) {\n break;\n }\n }\n\n const remaining = choices.length - count;\n if (remaining > 0) {\n message += ` and ${remaining} more`;\n }\n return message;\n}\n\nfunction first<K, V>(map: Map<K, V>): V | undefined {\n return map.values().next().value;\n}\n"],"names":["qualifier","service"],"mappings":";;;;AAwCO,MAAM,aAAc,CAAA;AAAA;AAAA,EAEf,QAAA,uBAAe,GAAsB,EAAA,CAAA;AAAA;AAAA,EAGrC,MAAS,GAAA,CAAA,CAAA;AAAA;AAAA;AAAA;AAAA,EAKjB,IAAI,YAAe,GAAA;AACf,IAAA,OAAO,IAAK,CAAA,MAAA,CAAA;AAAA,GAChB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,QAAS,CAAA,OAAA,EAAsB,EAAE,aAAA,EAAe,WAAkC,EAAA;AAC9E,IAAA,IAAI,CAAC,aAAe,EAAA;AAChB,MAAA,MAAM,IAAI,KAAA;AAAA,QACN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AA,EAAA,SAAA,CAAA,EAAA,CAAA,CAAA;AAAA,KACpC;AAEA,IAAI,IAAA,EAAE,SAAS,GAAK,EAAA;AAChB,MAAA,MAAA;AAAA,KACJ;AAAA,GACJ;AAEA,EAAM,MAAA,SAAA,GAAY,QAAQ,MAAS,GAAA,KAAA,CAAA;AACnC,EAAA,IAAI,YAAY,CAAG,EAAA;AACf,IAAA,OAAA,IAAW,CAAQ,KAAA,EAAA,SAAA,CAAA,KAAA,CAAA,CAAA;AAAA,GACvB;AACA,EAAO,OAAA,OAAA,CAAA;AACX,CAAA;AAEA,SAAS,MAAY,GAA+B,EAAA;AAChD,EAAA,OAAO,GAAI,CAAA,MAAA,EAAS,CAAA,IAAA,EAAO,CAAA,KAAA,CAAA;AAC/B;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ServiceRepr.js","sources":["open-pioneer://external-pioneer-packages/@open-pioneer/runtime/service-layer/ServiceRepr.ts"],"sourcesContent":["// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ErrorId } from \"../errors\";\nimport { ServiceMetadata } from \"../metadata\";\nimport { Service, ServiceConstructor, ServiceOptions } from \"../Service\";\nimport { Error } from \"@open-pioneer/core\";\nimport { InterfaceSpec, parseReferenceSpec, ReferenceSpec } from \"./InterfaceSpec\";\nimport { PackageIntl } from \"../i18n\";\n\nexport type ServiceState = \"not-constructed\" | \"constructing\" | \"constructed\" | \"destroyed\";\n\nexport type ServiceDependency = ReferenceSpec & { referenceName: string };\n\nexport interface ConstructorFactory {\n type: \"class\";\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n clazz: ServiceConstructor<any>;\n}\n\nexport interface FunctionFactory {\n type: \"function\";\n create: (options: ServiceOptions) => Service;\n}\n\nexport type ServiceFactory = ConstructorFactory | FunctionFactory;\n\nexport interface ServiceReprOptions {\n name: string;\n packageName: string;\n factory: ServiceFactory;\n intl: PackageIntl;\n dependencies?: ServiceDependency[];\n interfaces?: InterfaceSpec[];\n properties?: Record<string, unknown>;\n}\n\n/**\n * Represents metadata and state of a service in the runtime.\n * `this.instance` is the actual service instance (when constructed).\n */\nexport class ServiceRepr {\n static create(\n packageName: string,\n data: ServiceMetadata,\n intl: PackageIntl,\n properties?: Record<string, unknown>\n ): ServiceRepr {\n const clazz = data.clazz;\n const name = data.name;\n const dependencies = Object.entries(data.references ?? {}).map(\n ([name, referenceMetadata]) => {\n return {\n referenceName: name,\n ...parseReferenceSpec(referenceMetadata)\n };\n }\n );\n const interfaces = data.provides?.map<InterfaceSpec>((i) => {\n return {\n interfaceName: i.name,\n qualifier: i.qualifier\n };\n });\n const factory: ConstructorFactory = {\n type: \"class\",\n clazz\n };\n return new ServiceRepr({\n name,\n packageName,\n factory,\n intl,\n dependencies,\n interfaces,\n properties\n });\n }\n\n /** Unique id of this service. Contains the package name and the service name. */\n readonly id: string;\n\n /** Name of this service in it's package. */\n readonly name: string;\n\n /** Name of the parent package. */\n readonly packageName: string;\n\n /** Locale-dependant i18n messages. */\n readonly intl: PackageIntl;\n\n /** Service properties made available via the service's constructor. */\n readonly properties: Readonly<Record<string, unknown>>;\n\n /** Dependencies required by the service constructor. */\n readonly dependencies: readonly ServiceDependency[];\n\n /** Interfaces provided by the service. */\n readonly interfaces: readonly Readonly<InterfaceSpec>[];\n\n /** Number of references to this service. */\n private _useCount = 0;\n\n /** Service factory to construct an instance. */\n private factory: ServiceFactory;\n\n /** Current state of this service. \"constructed\" -> instance is available. */\n private _state: ServiceState = \"not-constructed\";\n\n /** Service instance, once constructed. */\n private _instance: Service | undefined = undefined;\n\n constructor(options: ServiceReprOptions) {\n const {\n name,\n packageName,\n factory,\n intl,\n dependencies = [],\n interfaces = [],\n properties = {}\n } = options;\n if (!isValidServiceName(name)) {\n throw new Error(ErrorId.INTERNAL, `Invalid service name: '${name}'.`);\n }\n\n this.id = `${packageName}::${name}`;\n this.name = name;\n this.packageName = packageName;\n this.factory = factory;\n this.intl = intl;\n this.dependencies = dependencies;\n this.interfaces = interfaces;\n this.properties = properties;\n }\n\n /** Returns the current service instance or undefined if the service has not been constructed. */\n get instance(): Service | undefined {\n return this._instance;\n }\n\n /** Returns the current state of the service. */\n get state() {\n return this._state;\n }\n\n /** Returns the current reference count. */\n get useCount() {\n return this._useCount;\n }\n\n /**\n * Same as `instance`, but throws when the instance has not been constructed.\n */\n getInstanceOrThrow() {\n const instance = this._instance;\n if (!instance) {\n throw new Error(ErrorId.INTERNAL, \"Expected service instance to be present.\");\n }\n return instance;\n }\n\n /**\n * Called before `create()` to place the service into the `constructing` state,\n * which is currently used to detect cycles.\n */\n beforeCreate() {\n if (this._state === \"not-constructed\") {\n this._state = \"constructing\";\n } else {\n throw new Error(\n ErrorId.INTERNAL,\n \"Inconsistent state: service is already under construction.\"\n );\n }\n }\n\n /**\n * Instantiates the service by invoking the service constructor\n * with the given `options`.\n *\n * The service's use count is initialized to `1`, so every `create()`\n * should be paired with a `removeRef()`.\n *\n * `destroy()` can be invoked once the final `removeRef()` has returned zero.\n */\n create(options: Pick<ServiceOptions, \"references\" | \"referencesMeta\">) {\n if (this._state !== \"constructing\" || this.instance !== undefined) {\n throw new Error(\n ErrorId.INTERNAL,\n \"Inconsistent state: service is not being constructed.\"\n );\n }\n try {\n this._instance = createService(this.factory, {\n ...options,\n properties: this.properties,\n intl: this.intl\n });\n this._state = \"constructed\";\n this._useCount = 1;\n return this._instance;\n } catch (e) {\n throw new Error(\n ErrorId.SERVICE_CONSTRUCTION_FAILED,\n `Failed to create service instance '${this.id}'.`,\n { cause: e }\n );\n }\n }\n\n destroy() {\n if (this._instance) {\n try {\n this._instance.destroy?.();\n } catch (e) {\n throw new Error(\n ErrorId.SERVICE_DESTRUCTION_FAILED,\n `Failed to destroy service instance '${this.id}'.`,\n { cause: e }\n );\n }\n }\n this._instance = undefined;\n this._state = \"destroyed\";\n }\n\n /**\n * Adds a use to the service's use count.\n * References to a service are tracked: it should only be destroyed when it is no longer being used.\n */\n addRef() {\n return (this._useCount += 1);\n }\n\n /**\n * Removes a use from the service's use count.\n * Returns the new use count.\n */\n removeRef() {\n return (this._useCount -= 1);\n }\n}\n\nexport function createConstructorFactory<T extends {}>(\n clazz: ServiceConstructor<T>\n): ConstructorFactory {\n return { type: \"class\", clazz };\n}\n\nexport function createFunctionFactory(\n create: (options: ServiceOptions) => Service\n): FunctionFactory {\n return { type: \"function\", create };\n}\n\nconst SERVICE_NAME_REGEX = /^[a-z0-9_-]+$/i;\n\nfunction isValidServiceName(name: string) {\n return SERVICE_NAME_REGEX.test(name);\n}\n\nfunction createService(factory: ServiceFactory, options: ServiceOptions) {\n switch (factory.type) {\n case \"class\":\n return new factory.clazz(options);\n case \"function\":\n return factory.create(options);\n }\n}\n"],"names":["name"],"mappings":";;;;AAwCO,MAAM,WAAY,CAAA;AAAA,EACrB,OAAO,MAAA,CACH,WACA,EAAA,IAAA,EACA,MACA,UACW,EAAA;AACX,IAAA,MAAM,QAAQ,IAAK,CAAA,KAAA,CAAA;AACnB,IAAA,MAAM,OAAO,IAAK,CAAA,IAAA,CAAA;AAClB,IAAA,MAAM,eAAe,MAAO,CAAA,OAAA,CAAQ,KAAK,UAAc,IAAA,EAAE,CAAE,CAAA,GAAA;AAAA,MACvD,CAAC,CAACA,KAAM,EAAA,iBAAiB,CAAM,KAAA;AAC3B,QAAO,OAAA;AAAA,UACH,aAAeA,EAAAA,KAAAA;AAAA,UACf,GAAG,mBAAmB,iBAAiB,CAAA;AAAA,SAC3C,CAAA;AAAA,OACJ;AAAA,KACJ,CAAA;AACA,IAAA,MAAM,UAAa,GAAA,IAAA,CAAK,QAAU,EAAA,GAAA,CAAmB,CAAC,CAAM,KAAA;AACxD,MAAO,OAAA;AAAA,QACH,eAAe,CAAE,CAAA,IAAA;AAAA,QACjB,WAAW,CAAE,CAAA,SAAA;AAAA,OACjB,CAAA;AAAA,KACH,CAAA,CAAA;AACD,IAAA,MAAM,OAA8B,GAAA;AAAA,MAChC,IAAM,EAAA,OA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,SAAY,GAAA;AACR,IAAA,OAAQ,KAAK,SAAa,IAAA,CAAA,CAAA;AAAA,GAC9B;AACJ,CAAA;AAEO,SAAS,yBACZ,KACkB,EAAA;AAClB,EAAO,OAAA,EAAE,IAAM,EAAA,OAAA,EAAS,KAAM,EAAA,CAAA;AAClC,CAAA;AAEO,SAAS,sBACZ,MACe,EAAA;AACf,EAAO,OAAA,EAAE,IAAM,EAAA,UAAA,EAAY,MAAO,EAAA,CAAA;AACtC,CAAA;AAEA,MAAM,kBAAqB,GAAA,gBAAA,CAAA;AAE3B,SAAS,mBAAmB,IAAc,EAAA;AACtC,EAAO,OAAA,kBAAA,CAAmB,KAAK,IAAI,CAAA,CAAA;AACvC,CAAA;AAEA,SAAS,aAAA,CAAc,SAAyB,OAAyB,EAAA;AACrE,EAAA,QAAQ,QAAQ,IAAM;AAAA,IAClB,KAAK,OAAA;AACD,MAAO,OAAA,IAAI,OAAQ,CAAA,KAAA,CAAM,OAAO,CAAA,CAAA;AAAA,IACpC,KAAK,UAAA;AACD,MAAO,OAAA,OAAA,CAAQ,OAAO,OAAO,CAAA,CAAA;AAAA,GACrC;AACJ;;;;"}
|
|
1
|
+
{"version":3,"file":"ServiceRepr.js","sources":["ServiceRepr.ts"],"sourcesContent":["// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ErrorId } from \"../errors\";\nimport { ServiceMetadata } from \"../metadata\";\nimport { Service, ServiceConstructor, ServiceOptions } from \"../Service\";\nimport { Error } from \"@open-pioneer/core\";\nimport { InterfaceSpec, parseReferenceSpec, ReferenceSpec } from \"./InterfaceSpec\";\nimport { PackageIntl } from \"../i18n\";\n\nexport type ServiceState = \"not-constructed\" | \"constructing\" | \"constructed\" | \"destroyed\";\n\nexport type ServiceDependency = ReferenceSpec & { referenceName: string };\n\nexport interface ConstructorFactory {\n type: \"class\";\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n clazz: ServiceConstructor<any>;\n}\n\nexport interface FunctionFactory {\n type: \"function\";\n create: (options: ServiceOptions) => Service;\n}\n\nexport type ServiceFactory = ConstructorFactory | FunctionFactory;\n\nexport interface ServiceReprOptions {\n name: string;\n packageName: string;\n factory: ServiceFactory;\n intl: PackageIntl;\n dependencies?: ServiceDependency[];\n interfaces?: InterfaceSpec[];\n properties?: Record<string, unknown>;\n}\n\n/**\n * Represents metadata and state of a service in the runtime.\n * `this.instance` is the actual service instance (when constructed).\n */\nexport class ServiceRepr {\n static create(\n packageName: string,\n data: ServiceMetadata,\n intl: PackageIntl,\n properties?: Record<string, unknown>\n ): ServiceRepr {\n const clazz = data.clazz;\n const name = data.name;\n const dependencies = Object.entries(data.references ?? {}).map(\n ([name, referenceMetadata]) => {\n return {\n referenceName: name,\n ...parseReferenceSpec(referenceMetadata)\n };\n }\n );\n const interfaces = data.provides?.map<InterfaceSpec>((i) => {\n return {\n interfaceName: i.name,\n qualifier: i.qualifier\n };\n });\n const factory: ConstructorFactory = {\n type: \"class\",\n clazz\n };\n return new ServiceRepr({\n name,\n packageName,\n factory,\n intl,\n dependencies,\n interfaces,\n properties\n });\n }\n\n /** Unique id of this service. Contains the package name and the service name. */\n readonly id: string;\n\n /** Name of this service in it's package. */\n readonly name: string;\n\n /** Name of the parent package. */\n readonly packageName: string;\n\n /** Locale-dependant i18n messages. */\n readonly intl: PackageIntl;\n\n /** Service properties made available via the service's constructor. */\n readonly properties: Readonly<Record<string, unknown>>;\n\n /** Dependencies required by the service constructor. */\n readonly dependencies: readonly ServiceDependency[];\n\n /** Interfaces provided by the service. */\n readonly interfaces: readonly Readonly<InterfaceSpec>[];\n\n /** Number of references to this service. */\n private _useCount = 0;\n\n /** Service factory to construct an instance. */\n private factory: ServiceFactory;\n\n /** Current state of this service. \"constructed\" -> instance is available. */\n private _state: ServiceState = \"not-constructed\";\n\n /** Service instance, once constructed. */\n private _instance: Service | undefined = undefined;\n\n constructor(options: ServiceReprOptions) {\n const {\n name,\n packageName,\n factory,\n intl,\n dependencies = [],\n interfaces = [],\n properties = {}\n } = options;\n if (!isValidServiceName(name)) {\n throw new Error(ErrorId.INTERNAL, `Invalid service name: '${name}'.`);\n }\n\n this.id = `${packageName}::${name}`;\n this.name = name;\n this.packageName = packageName;\n this.factory = factory;\n this.intl = intl;\n this.dependencies = dependencies;\n this.interfaces = interfaces;\n this.properties = properties;\n }\n\n /** Returns the current service instance or undefined if the service has not been constructed. */\n get instance(): Service | undefined {\n return this._instance;\n }\n\n /** Returns the current state of the service. */\n get state() {\n return this._state;\n }\n\n /** Returns the current reference count. */\n get useCount() {\n return this._useCount;\n }\n\n /**\n * Same as `instance`, but throws when the instance has not been constructed.\n */\n getInstanceOrThrow() {\n const instance = this._instance;\n if (!instance) {\n throw new Error(ErrorId.INTERNAL, \"Expected service instance to be present.\");\n }\n return instance;\n }\n\n /**\n * Called before `create()` to place the service into the `constructing` state,\n * which is currently used to detect cycles.\n */\n beforeCreate() {\n if (this._state === \"not-constructed\") {\n this._state = \"constructing\";\n } else {\n throw new Error(\n ErrorId.INTERNAL,\n \"Inconsistent state: service is already under construction.\"\n );\n }\n }\n\n /**\n * Instantiates the service by invoking the service constructor\n * with the given `options`.\n *\n * The service's use count is initialized to `1`, so every `create()`\n * should be paired with a `removeRef()`.\n *\n * `destroy()` can be invoked once the final `removeRef()` has returned zero.\n */\n create(options: Pick<ServiceOptions, \"references\" | \"referencesMeta\">) {\n if (this._state !== \"constructing\" || this.instance !== undefined) {\n throw new Error(\n ErrorId.INTERNAL,\n \"Inconsistent state: service is not being constructed.\"\n );\n }\n try {\n this._instance = createService(this.factory, {\n ...options,\n properties: this.properties,\n intl: this.intl\n });\n this._state = \"constructed\";\n this._useCount = 1;\n return this._instance;\n } catch (e) {\n throw new Error(\n ErrorId.SERVICE_CONSTRUCTION_FAILED,\n `Failed to create service instance '${this.id}'.`,\n { cause: e }\n );\n }\n }\n\n destroy() {\n if (this._instance) {\n try {\n this._instance.destroy?.();\n } catch (e) {\n throw new Error(\n ErrorId.SERVICE_DESTRUCTION_FAILED,\n `Failed to destroy service instance '${this.id}'.`,\n { cause: e }\n );\n }\n }\n this._instance = undefined;\n this._state = \"destroyed\";\n }\n\n /**\n * Adds a use to the service's use count.\n * References to a service are tracked: it should only be destroyed when it is no longer being used.\n */\n addRef() {\n return (this._useCount += 1);\n }\n\n /**\n * Removes a use from the service's use count.\n * Returns the new use count.\n */\n removeRef() {\n return (this._useCount -= 1);\n }\n}\n\nexport function createConstructorFactory<T extends {}>(\n clazz: ServiceConstructor<T>\n): ConstructorFactory {\n return { type: \"class\", clazz };\n}\n\nexport function createFunctionFactory(\n create: (options: ServiceOptions) => Service\n): FunctionFactory {\n return { type: \"function\", create };\n}\n\nconst SERVICE_NAME_REGEX = /^[a-z0-9_-]+$/i;\n\nfunction isValidServiceName(name: string) {\n return SERVICE_NAME_REGEX.test(name);\n}\n\nfunction createService(factory: ServiceFactory, options: ServiceOptions) {\n switch (factory.type) {\n case \"class\":\n return new factory.clazz(options);\n case \"function\":\n return factory.create(options);\n }\n}\n"],"names":["name"],"mappings":";;;;AAwCO,MAAM,WAAY,CAAA;AAAA,EACrB,OAAO,MAAA,CACH,WACA,EAAA,IAAA,EACA,MACA,UACW,EAAA;AACX,IAAA,MAAM,QAAQ,IAAK,CAAA,KAAA,CAAA;AACnB,IAAA,MAAM,OAAO,IAAK,CAAA,IAAA,CAAA;AAClB,IAAA,MAAM,eAAe,MAAO,CAAA,OAAA,CAAQ,KAAK,UAAc,IAAA,EAAE,CAAE,CAAA,GAAA;AAAA,MACvD,CAAC,CAACA,KAAM,EAAA,iBAAiB,CAAM,KAAA;AAC3B,QAAO,OAAA;AAAA,UACH,aAAeA,EAAAA,KAAAA;AAAA,UACf,GAAG,mBAAmB,iBAAiB,CAAA;AAAA,SAC3C,CAAA;AAAA,OACJ;AAAA,KACJ,CAAA;AACA,IAAA,MAAM,UAAa,GAAA,IAAA,CAAK,QAAU,EAAA,GAAA,CAAmB,CAAC,CAAM,KAAA;AACxD,MAAO,OA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AA,WAAA,CAAA;AAAA,GAClB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAS,GAAA;AACL,IAAA,OAAQ,KAAK,SAAa,IAAA,CAAA,CAAA;AAAA,GAC9B;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,SAAY,GAAA;AACR,IAAA,OAAQ,KAAK,SAAa,IAAA,CAAA,CAAA;AAAA,GAC9B;AACJ,CAAA;AAEO,SAAS,yBACZ,KACkB,EAAA;AAClB,EAAO,OAAA,EAAE,IAAM,EAAA,OAAA,EAAS,KAAM,EAAA,CAAA;AAClC,CAAA;AAEO,SAAS,sBACZ,MACe,EAAA;AACf,EAAO,OAAA,EAAE,IAAM,EAAA,UAAA,EAAY,MAAO,EAAA,CAAA;AACtC,CAAA;AAEA,MAAM,kBAAqB,GAAA,gBAAA,CAAA;AAE3B,SAAS,mBAAmB,IAAc,EAAA;AACtC,EAAO,OAAA,kBAAA,CAAmB,KAAK,IAAI,CAAA,CAAA;AACvC,CAAA;AAEA,SAAS,aAAA,CAAc,SAAyB,OAAyB,EAAA;AACrE,EAAA,QAAQ,QAAQ,IAAM;AAAA,IAClB,KAAK,OAAA;AACD,MAAO,OAAA,IAAI,OAAQ,CAAA,KAAA,CAAM,OAAO,CAAA,CAAA;AAAA,IACpC,KAAK,UAAA;AACD,MAAO,OAAA,OAAA,CAAQ,OAAO,OAAO,CAAA,CAAA;AAAA,GACrC;AACJ;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"verifyDependencies.js","sources":["open-pioneer://external-pioneer-packages/@open-pioneer/runtime/service-layer/verifyDependencies.ts"],"sourcesContent":["// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Error } from \"@open-pioneer/core\";\nimport { ErrorId } from \"../errors\";\nimport { InterfaceSpec, ReferenceSpec, renderInterfaceSpec } from \"./InterfaceSpec\";\nimport {\n AmbiguousChoice,\n ReadonlyServiceLookup,\n renderAmbiguousServiceChoices,\n ServiceLookup\n} from \"./ServiceLookup\";\nimport { ServiceRepr } from \"./ServiceRepr\";\n\nexport interface DependencyOptions {\n /**\n * All services known to the service layer.\n */\n services?: readonly ServiceRepr[];\n\n /**\n * References that must be satisfied by the services.\n */\n requiredReferences?: readonly RequiredReference[];\n}\n\nexport type RequiredReference = UIDependency | FrameworkDependency;\n\nexport type UIDependency = { type: \"ui\"; packageName: string } & ReferenceSpec;\n\nexport type FrameworkDependency = { type: \"framework\" } & ReferenceSpec;\n\nexport type ComputedServiceDependencies = Record<string, ServiceRepr | ServiceRepr[]>;\n\nexport interface VerifyDependenciesResult {\n /**\n * Precomputed dependencies for every service.\n *\n * Key: service id.\n */\n serviceDependencies: Map<string, ComputedServiceDependencies>;\n\n /**\n * Index structure mapping interface names to service instances.\n */\n serviceLookup: ReadonlyServiceLookup;\n}\n\n/**\n * Visits all services and ensures that their dependencies can be satisfied by each other without a cycle.\n *\n * Throws an error if a cycle is detected or if a required service is never implemented.\n *\n * @returns an object containing the service index and precomputed dependency information\n */\nexport function verifyDependencies(options: DependencyOptions): VerifyDependenciesResult {\n const verifier = new Verifier(options);\n verifier.verify();\n return {\n serviceLookup: verifier.getServiceLookup(),\n serviceDependencies: verifier.getComputedDependencies()\n };\n}\n\ninterface GraphItem {\n state: ItemState;\n service: ServiceRepr;\n dependencies: ComputedServiceDependencies;\n}\n\ntype ItemState = \"not-visited\" | \"pending\" | \"done\";\n\n/** The reason why a graph node is being visited. */\ntype ItemVisitReason = \"root\" | InterfaceReference;\n\ntype InterfaceReference =\n | {\n type: \"framework-reference\";\n value: ReferenceSpec;\n }\n | {\n type: \"ui-reference\";\n packageName: string;\n value: ReferenceSpec;\n }\n | {\n type: \"service-reference\";\n service: ServiceRepr;\n referenceName: string;\n value: ReferenceSpec;\n };\n\nclass Verifier {\n private requiredReferences: readonly RequiredReference[];\n private items: GraphItem[];\n private serviceLookup = new ServiceLookup();\n private serviceToGraphItem = new Map<ServiceRepr, GraphItem>();\n\n // Stack of visited nodes\n private stack: [item: GraphItem, reason: ItemVisitReason][] = [];\n\n constructor(options: DependencyOptions) {\n this.requiredReferences = options.requiredReferences ?? [];\n const services = options.services ?? [];\n const items = (this.items = services.map<GraphItem>((service) => {\n return {\n service: service,\n state: \"not-visited\",\n dependencies: {}\n };\n }));\n\n for (const item of items) {\n for (const spec of item.service.interfaces) {\n this.registerService(item, spec);\n }\n }\n }\n\n verify() {\n for (const ref of this.requiredReferences) {\n let interfaceRef: InterfaceReference;\n switch (ref.type) {\n case \"framework\":\n interfaceRef = { type: \"framework-reference\", value: ref };\n break;\n case \"ui\":\n interfaceRef = {\n type: \"ui-reference\",\n packageName: ref.packageName,\n value: ref\n };\n break;\n }\n this.visitReference(interfaceRef);\n }\n for (const item of this.items) {\n this.visitItem(item, \"root\");\n }\n }\n\n getServiceLookup() {\n return this.serviceLookup;\n }\n\n getComputedDependencies() {\n return new Map(\n this.items.map<[string, ComputedServiceDependencies]>((item) => {\n return [item.service.id, item.dependencies];\n })\n );\n }\n\n private visitItem(item: GraphItem, reason: ItemVisitReason) {\n const stack = this.stack;\n const state = item.state;\n if (state === \"done\") {\n return; // Item is initialized, cycle impossible\n }\n if (state === \"pending\") {\n this.throwCycleError(item, reason);\n }\n\n stack.push([item, reason]);\n item.state = \"pending\";\n for (const dep of item.service.dependencies) {\n item.dependencies[dep.referenceName] = this.visitReference({\n type: \"service-reference\",\n service: item.service,\n referenceName: dep.referenceName,\n value: dep\n });\n }\n item.state = \"done\";\n stack.pop();\n }\n\n private visitReference(ref: InterfaceReference) {\n const itemOrItems = this.findServices(ref);\n if (Array.isArray(itemOrItems)) {\n for (const child of itemOrItems) {\n this.visitItem(child, ref);\n }\n return itemOrItems.map((item) => item.service);\n } else {\n this.visitItem(itemOrItems, ref);\n return itemOrItems.service;\n }\n }\n\n private registerService(item: GraphItem, spec: InterfaceSpec) {\n this.serviceLookup.register(item.service, spec);\n this.serviceToGraphItem.set(item.service, item);\n }\n\n private findServices(ref: InterfaceReference): GraphItem | GraphItem[] {\n const spec = ref.value;\n const lookupResult = this.serviceLookup.lookup(spec);\n switch (lookupResult.type) {\n case \"unimplemented\": {\n const message = unimplementedInterfaceMessage(ref);\n throw new Error(ErrorId.INTERFACE_NOT_FOUND, message);\n }\n case \"ambiguous\": {\n const message = ambiguousInterfaceMessage(ref, lookupResult.choices);\n throw new Error(ErrorId.AMBIGUOUS_DEPENDENCY, message);\n }\n }\n\n const value = lookupResult.value;\n if (Array.isArray(value)) {\n return value.map((service) => this.getGraphItem(service));\n } else {\n return this.getGraphItem(value);\n }\n }\n\n private getGraphItem(service: ServiceRepr): GraphItem {\n const graphItem = this.serviceToGraphItem.get(service);\n if (!graphItem || graphItem.service !== service) {\n throw new Error(\n ErrorId.INTERNAL,\n `Failed to find matching graph item for service '${service.id}'.`\n );\n }\n return graphItem;\n }\n\n private throwCycleError(item: GraphItem, reason: ItemVisitReason) {\n // Find the item on the stack (it must be there because we detected a cycle).\n const stack = this.stack;\n const ownIndex = stack.findIndex((entry) => entry[0] === item);\n if (ownIndex === -1) {\n throw new Error(ErrorId.INTERNAL, \"Failed to find cycle participant on the stack.\");\n }\n\n const cycleInfo = stack\n .slice(ownIndex)\n .concat([[item, reason]])\n .map<string>((entry, index) => {\n const item = entry[0];\n const reason = index === 0 ? \"root\" : entry[1]; // info before the cycle does not matter\n\n let message = `'${item.service.id}'`;\n if (typeof reason === \"object\") {\n message += ` (${referenceDetail(reason)})`;\n }\n return message;\n });\n throw new Error(\n ErrorId.DEPENDENCY_CYCLE,\n `Detected dependency cycle: ${cycleInfo.join(\" => \")}.`\n );\n }\n}\n\nfunction unimplementedInterfaceMessage(ref: InterfaceReference): string {\n const interfaceText = renderInterfaceSpec(ref.value);\n switch (ref.type) {\n case \"service-reference\":\n return `Service '${ref.service.id}' requires an unimplemented interface ${interfaceText} as dependency '${ref.referenceName}'.`;\n case \"ui-reference\":\n return `The UI of package '${ref.packageName}' requires an unimplemented interface ${interfaceText}.`;\n case \"framework-reference\":\n return `The framework requires an unimplemented interface ${interfaceText}.`;\n }\n}\n\nfunction ambiguousInterfaceMessage(ref: InterfaceReference, choices: AmbiguousChoice[]): string {\n const interfaceText = renderInterfaceSpec(ref.value);\n const serviceChoices = renderAmbiguousServiceChoices(choices);\n\n let message = \"\";\n switch (ref.type) {\n case \"service-reference\":\n message = `Service '${ref.service.id}' requires the ambiguous interface ${interfaceText} as dependency '${ref.referenceName}'.`;\n break;\n case \"ui-reference\":\n message = `The UI of package '${ref.packageName}' requires the ambiguous interface ${interfaceText}.`;\n break;\n case \"framework-reference\":\n message = `The framework requires the ambiguous interface ${interfaceText}.`;\n break;\n }\n message += ` Possible choices are ${serviceChoices}.`;\n return message;\n}\n\nfunction referenceDetail(reason: InterfaceReference) {\n switch (reason.type) {\n case \"service-reference\":\n return `'${reason.referenceName}' providing '${reason.value.interfaceName}'`;\n case \"ui-reference\":\n return `UI of package '${reason.packageName}' requiring '${reason.value.interfaceName}'`;\n case \"framework-reference\":\n return `framework requiring '${reason.value.interfaceName}'`;\n }\n}\n"],"names":["item","reason"],"mappings":";;;;;AAsDO,SAAS,mBAAmB,OAAsD,EAAA;AACrF,EAAM,MAAA,QAAA,GAAW,IAAI,QAAA,CAAS,OAAO,CAAA,CAAA;AACrC,EAAA,QAAA,CAAS,MAAO,EAAA,CAAA;AAChB,EAAO,OAAA;AAAA,IACH,aAAA,EAAe,SAAS,gBAAiB,EAAA;AAAA,IACzC,mBAAA,EAAqB,SAAS,uBAAwB,EAAA;AAAA,GAC1D,CAAA;AACJ,CAAA;AA8BA,MAAM,QAAS,CAAA;AAAA,EACH,kBAAA,CAAA;AAAA,EACA,KAAA,CAAA;AAAA,EACA,aAAA,GAAgB,IAAI,aAAc,EAAA,CAAA;AAAA,EAClC,kBAAA,uBAAyB,GAA4B,EAAA,CAAA;AAAA;AAAA,EAGrD,QAAsD,EAAC,CAAA;AAAA,EAE/D,YAAY,OAA4B,EAAA;AACpC,IAAK,IAAA,CAAA,kBAAA,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wB,OAAO,KAAM,CAAA,aAAA,CAAA,CAAA,CAAA,CAAA;AAAA,GACpD;AACJ;;;;"}
|
|
1
|
+
{"version":3,"file":"verifyDependencies.js","sources":["verifyDependencies.ts"],"sourcesContent":["// SPDX-FileCopyrightText: con terra GmbH and contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Error } from \"@open-pioneer/core\";\nimport { ErrorId } from \"../errors\";\nimport { InterfaceSpec, ReferenceSpec, renderInterfaceSpec } from \"./InterfaceSpec\";\nimport {\n AmbiguousChoice,\n ReadonlyServiceLookup,\n renderAmbiguousServiceChoices,\n ServiceLookup\n} from \"./ServiceLookup\";\nimport { ServiceRepr } from \"./ServiceRepr\";\n\nexport interface DependencyOptions {\n /**\n * All services known to the service layer.\n */\n services?: readonly ServiceRepr[];\n\n /**\n * References that must be satisfied by the services.\n */\n requiredReferences?: readonly RequiredReference[];\n}\n\nexport type RequiredReference = UIDependency | FrameworkDependency;\n\nexport type UIDependency = { type: \"ui\"; packageName: string } & ReferenceSpec;\n\nexport type FrameworkDependency = { type: \"framework\" } & ReferenceSpec;\n\nexport type ComputedServiceDependencies = Record<string, ServiceRepr | ServiceRepr[]>;\n\nexport interface VerifyDependenciesResult {\n /**\n * Precomputed dependencies for every service.\n *\n * Key: service id.\n */\n serviceDependencies: Map<string, ComputedServiceDependencies>;\n\n /**\n * Index structure mapping interface names to service instances.\n */\n serviceLookup: ReadonlyServiceLookup;\n}\n\n/**\n * Visits all services and ensures that their dependencies can be satisfied by each other without a cycle.\n *\n * Throws an error if a cycle is detected or if a required service is never implemented.\n *\n * @returns an object containing the service index and precomputed dependency information\n */\nexport function verifyDependencies(options: DependencyOptions): VerifyDependenciesResult {\n const verifier = new Verifier(options);\n verifier.verify();\n return {\n serviceLookup: verifier.getServiceLookup(),\n serviceDependencies: verifier.getComputedDependencies()\n };\n}\n\ninterface GraphItem {\n state: ItemState;\n service: ServiceRepr;\n dependencies: ComputedServiceDependencies;\n}\n\ntype ItemState = \"not-visited\" | \"pending\" | \"done\";\n\n/** The reason why a graph node is being visited. */\ntype ItemVisitReason = \"root\" | InterfaceReference;\n\ntype InterfaceReference =\n | {\n type: \"framework-reference\";\n value: ReferenceSpec;\n }\n | {\n type: \"ui-reference\";\n packageName: string;\n value: ReferenceSpec;\n }\n | {\n type: \"service-reference\";\n service: ServiceRepr;\n referenceName: string;\n value: ReferenceSpec;\n };\n\nclass Verifier {\n private requiredReferences: readonly RequiredReference[];\n private items: GraphItem[];\n private serviceLookup = new ServiceLookup();\n private serviceToGraphItem = new Map<ServiceRepr, GraphItem>();\n\n // Stack of visited nodes\n private stack: [item: GraphItem, reason: ItemVisitReason][] = [];\n\n constructor(options: DependencyOptions) {\n this.requiredReferences = options.requiredReferences ?? [];\n const services = options.services ?? [];\n const items = (this.items = services.map<GraphItem>((service) => {\n return {\n service: service,\n state: \"not-visited\",\n dependencies: {}\n };\n }));\n\n for (const item of items) {\n for (const spec of item.service.interfaces) {\n this.registerService(item, spec);\n }\n }\n }\n\n verify() {\n for (const ref of this.requiredReferences) {\n let interfaceRef: InterfaceReference;\n switch (ref.type) {\n case \"framework\":\n interfaceRef = { type: \"framework-reference\", value: ref };\n break;\n case \"ui\":\n interfaceRef = {\n type: \"ui-reference\",\n packageName: ref.packageName,\n value: ref\n };\n break;\n }\n this.visitReference(interfaceRef);\n }\n for (const item of this.items) {\n this.visitItem(item, \"root\");\n }\n }\n\n getServiceLookup() {\n return this.serviceLookup;\n }\n\n getComputedDependencies() {\n return new Map(\n this.items.map<[string, ComputedServiceDependencies]>((item) => {\n return [item.service.id, item.dependencies];\n })\n );\n }\n\n private visitItem(item: GraphItem, reason: ItemVisitReason) {\n const stack = this.stack;\n const state = item.state;\n if (state === \"done\") {\n return; // Item is initialized, cycle impossible\n }\n if (state === \"pending\") {\n this.throwCycleError(item, reason);\n }\n\n stack.push([item, reason]);\n item.state = \"pending\";\n for (const dep of item.service.dependencies) {\n item.dependencies[dep.referenceName] = this.visitReference({\n type: \"service-reference\",\n service: item.service,\n referenceName: dep.referenceName,\n value: dep\n });\n }\n item.state = \"done\";\n stack.pop();\n }\n\n private visitReference(ref: InterfaceReference) {\n const itemOrItems = this.findServices(ref);\n if (Array.isArray(itemOrItems)) {\n for (const child of itemOrItems) {\n this.visitItem(child, ref);\n }\n return itemOrItems.map((item) => item.service);\n } else {\n this.visitItem(itemOrItems, ref);\n return itemOrItems.service;\n }\n }\n\n private registerService(item: GraphItem, spec: InterfaceSpec) {\n this.serviceLookup.register(item.service, spec);\n this.serviceToGraphItem.set(item.service, item);\n }\n\n private findServices(ref: InterfaceReference): GraphItem | GraphItem[] {\n const spec = ref.value;\n const lookupResult = this.serviceLookup.lookup(spec);\n switch (lookupResult.type) {\n case \"unimplemented\": {\n const message = unimplementedInterfaceMessage(ref);\n throw new Error(ErrorId.INTERFACE_NOT_FOUND, message);\n }\n case \"ambiguous\": {\n const message = ambiguousInterfaceMessage(ref, lookupResult.choices);\n throw new Error(ErrorId.AMBIGUOUS_DEPENDENCY, message);\n }\n }\n\n const value = lookupResult.value;\n if (Array.isArray(value)) {\n return value.map((service) => this.getGraphItem(service));\n } else {\n return this.getGraphItem(value);\n }\n }\n\n private getGraphItem(service: ServiceRepr): GraphItem {\n const graphItem = this.serviceToGraphItem.get(service);\n if (!graphItem || graphItem.service !== service) {\n throw new Error(\n ErrorId.INTERNAL,\n `Failed to find matching graph item for service '${service.id}'.`\n );\n }\n return graphItem;\n }\n\n private throwCycleError(item: GraphItem, reason: ItemVisitReason) {\n // Find the item on the stack (it must be there because we detected a cycle).\n const stack = this.stack;\n const ownIndex = stack.findIndex((entry) => entry[0] === item);\n if (ownIndex === -1) {\n throw new Error(ErrorId.INTERNAL, \"Failed to find cycle participant on the stack.\");\n }\n\n const cycleInfo = stack\n .slice(ownIndex)\n .concat([[item, reason]])\n .map<string>((entry, index) => {\n const item = entry[0];\n const reason = index === 0 ? \"root\" : entry[1]; // info before the cycle does not matter\n\n let message = `'${item.service.id}'`;\n if (typeof reason === \"object\") {\n message += ` (${referenceDetail(reason)})`;\n }\n return message;\n });\n throw new Error(\n ErrorId.DEPENDENCY_CYCLE,\n `Detected dependency cycle: ${cycleInfo.join(\" => \")}.`\n );\n }\n}\n\nfunction unimplementedInterfaceMessage(ref: InterfaceReference): string {\n const interfaceText = renderInterfaceSpec(ref.value);\n switch (ref.type) {\n case \"service-reference\":\n return `Service '${ref.service.id}' requires an unimplemented interface ${interfaceText} as dependency '${ref.referenceName}'.`;\n case \"ui-reference\":\n return `The UI of package '${ref.packageName}' requires an unimplemented interface ${interfaceText}.`;\n case \"framework-reference\":\n return `The framework requires an unimplemented interface ${interfaceText}.`;\n }\n}\n\nfunction ambiguousInterfaceMessage(ref: InterfaceReference, choices: AmbiguousChoice[]): string {\n const interfaceText = renderInterfaceSpec(ref.value);\n const serviceChoices = renderAmbiguousServiceChoices(choices);\n\n let message = \"\";\n switch (ref.type) {\n case \"service-reference\":\n message = `Service '${ref.service.id}' requires the ambiguous interface ${interfaceText} as dependency '${ref.referenceName}'.`;\n break;\n case \"ui-reference\":\n message = `The UI of package '${ref.packageName}' requires the ambiguous interface ${interfaceText}.`;\n break;\n case \"framework-reference\":\n message = `The framework requires the ambiguous interface ${interfaceText}.`;\n break;\n }\n message += ` Possible choices are ${serviceChoices}.`;\n return message;\n}\n\nfunction referenceDetail(reason: InterfaceReference) {\n switch (reason.type) {\n case \"service-reference\":\n return `'${reason.referenceName}' providing '${reason.value.interfaceName}'`;\n case \"ui-reference\":\n return `UI of package '${reason.packageName}' requiring '${reason.value.interfaceName}'`;\n case \"framework-reference\":\n return `framework requiring '${reason.value.interfaceName}'`;\n }\n}\n"],"names":["item","reason"],"mappings":";;;;;AAsDO,SAAS,mBAAmB,OAAsD,EAAA;AACrF,EAAM,MAAA,QAAA,GAAW,IAAI,QAAA,CAAS,OAAO,CAAA,CAAA;AACrC,EAAA,QAAA,CAAS,MAAO,EAAA,CAAA;AAChB,EAAO,OAAA;AAAA,IACH,aAAA,EAAe,SAAS,gBA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