UNPKG

2.84 kBJavaScriptView Raw
1"use strict";
2/*
3 * Copyright The OpenTelemetry Authors
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * https://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17Object.defineProperty(exports, "__esModule", { value: true });
18exports.unregisterGlobal = exports.getGlobal = exports.registerGlobal = void 0;
19const platform_1 = require("../platform");
20const version_1 = require("../version");
21const semver_1 = require("./semver");
22const major = version_1.VERSION.split('.')[0];
23const GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`);
24const _global = platform_1._globalThis;
25function registerGlobal(type, instance, diag, allowOverride = false) {
26 var _a;
27 const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : {
28 version: version_1.VERSION,
29 });
30 if (!allowOverride && api[type]) {
31 // already registered an API of this type
32 const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`);
33 diag.error(err.stack || err.message);
34 return false;
35 }
36 if (api.version !== version_1.VERSION) {
37 // All registered APIs must be of the same version exactly
38 const err = new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${version_1.VERSION}`);
39 diag.error(err.stack || err.message);
40 return false;
41 }
42 api[type] = instance;
43 diag.debug(`@opentelemetry/api: Registered a global for ${type} v${version_1.VERSION}.`);
44 return true;
45}
46exports.registerGlobal = registerGlobal;
47function getGlobal(type) {
48 var _a, _b;
49 const globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version;
50 if (!globalVersion || !(0, semver_1.isCompatible)(globalVersion)) {
51 return;
52 }
53 return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type];
54}
55exports.getGlobal = getGlobal;
56function unregisterGlobal(type, diag) {
57 diag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${version_1.VERSION}.`);
58 const api = _global[GLOBAL_OPENTELEMETRY_API_KEY];
59 if (api) {
60 delete api[type];
61 }
62}
63exports.unregisterGlobal = unregisterGlobal;
64//# sourceMappingURL=global-utils.js.map
\No newline at end of file