@mark1russell7/otel-ts 0.3.0 → 0.3.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.
@@ -0,0 +1,90 @@
1
+ /**
2
+ * The entry `@mark1russell7/otel-ts/context`: the one call that adds context
3
+ * ids, for browsers and Node.js (docs/CONTEXT-DESIGN.md, section 3).
4
+ *
5
+ * This entry depends on `@opentelemetry/api` only. It registers nothing: the
6
+ * context manager, the propagators and the processors come from `init()` or
7
+ * `startNodeTelemetry()`. Without a registered context manager, `withContext`
8
+ * still runs its function, but the values do not stay after an `await`.
9
+ *
10
+ * - The keys are data: `defineContextKeys` names each key, its cardinality and
11
+ * where it may go. A key that no call defined is refused.
12
+ * - A key with `propagate: "internal"` goes in the W3C baggage, so the
13
+ * propagator of otel-ts can send it on an internal call.
14
+ * - A key with `propagate: "none"` stays in a context entry of its own. No
15
+ * baggage propagator sees it, so it never leaves the process.
16
+ *
17
+ * @packageDocumentation
18
+ */
19
+ import { type Context } from "@opentelemetry/api";
20
+ /** How many distinct values a key has: "low" may become a metric attribute, "high" never does */
21
+ export type ContextKeyCardinality = "low" | "high";
22
+ /** Where a key may go: "internal" on internal calls (in the baggage), "none" never out of the process */
23
+ export type ContextKeyPropagation = "internal" | "none";
24
+ /** The rules of one context key */
25
+ export interface ContextKeySpec {
26
+ readonly cardinality: ContextKeyCardinality;
27
+ readonly propagate: ContextKeyPropagation;
28
+ /** The longest value, in UTF-16 code units. Default: 256. */
29
+ readonly maxLength?: number;
30
+ }
31
+ /** The rules of one key, with each default filled in */
32
+ export interface ContextKeyRule {
33
+ readonly key: string;
34
+ readonly cardinality: ContextKeyCardinality;
35
+ readonly propagate: ContextKeyPropagation;
36
+ readonly maxLength: number;
37
+ }
38
+ /** The values of a set of keys. An `undefined` or `null` value adds nothing. */
39
+ export type ContextValues<K extends string = string> = {
40
+ readonly [P in K]?: string | null | undefined;
41
+ };
42
+ /** The keys that one call of `defineContextKeys` defined, with typed calls */
43
+ export interface ContextKeys<K extends string> {
44
+ /** The rules of each key of this set */
45
+ readonly rules: ReadonlyMap<K, ContextKeyRule>;
46
+ /** `withContext`, with the key names of this set */
47
+ with<T>(values: ContextValues<K>, fn: () => T): T;
48
+ /** `contextValue`, with the key names of this set */
49
+ get(key: K, from?: Context): string | undefined;
50
+ }
51
+ /** The default of `maxLength` */
52
+ export declare const DEFAULT_MAX_LENGTH = 256;
53
+ /**
54
+ * Define context keys, one time for each program part. A second definition of
55
+ * a key with the same rules is accepted, so a library and an app can both
56
+ * define `request.id`. A second definition with other rules is an error.
57
+ */
58
+ export declare function defineContextKeys<K extends string>(specs: {
59
+ readonly [P in K]: ContextKeySpec;
60
+ }): ContextKeys<K>;
61
+ /** The rules of a defined key, or undefined. The processors and the propagator read them. */
62
+ export declare function contextKeyRule(key: string): ContextKeyRule | undefined;
63
+ /** The rules of each defined key */
64
+ export declare function contextKeyRules(): readonly ContextKeyRule[];
65
+ /**
66
+ * Run `fn` in a new context with these values, on top of the values of the
67
+ * active context. The async storage keeps the context through `await`,
68
+ * timers and callbacks. A key that is not defined, a value that is not a
69
+ * string and a value longer than the `maxLength` of its key are errors.
70
+ */
71
+ export declare function withContext<T>(values: ContextValues, fn: () => T): T;
72
+ /** The active context (or `from`) with these values: `withContext` without the call */
73
+ export declare function contextWith(values: ContextValues, from?: Context): Context;
74
+ /** The value of a defined key in the active context (or `from`), or undefined */
75
+ export declare function contextValue(key: string, from?: Context): string | undefined;
76
+ /**
77
+ * The value of each defined key in the active context (or `from`). A baggage
78
+ * entry of a key that is not defined is not in the result: an entry from
79
+ * outside does not become an attribute.
80
+ */
81
+ export declare function contextValues(from?: Context): Readonly<Record<string, string>>;
82
+ /**
83
+ * Run `fn` with the internal mark: the propagator of otel-ts sends the baggage
84
+ * only on a call that starts in such a context. `@procedures/client` sets the
85
+ * mark around the send of each of its transports.
86
+ */
87
+ export declare function withInternalCall<T>(fn: () => T): T;
88
+ /** True when the active context (or `from`) has the internal mark */
89
+ export declare function isInternalCall(from?: Context): boolean;
90
+ //# sourceMappingURL=context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,EAA0C,KAAK,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAE1F,iGAAiG;AACjG,MAAM,MAAM,qBAAqB,GAAG,KAAK,GAAG,MAAM,CAAC;AAEnD,yGAAyG;AACzG,MAAM,MAAM,qBAAqB,GAAG,UAAU,GAAG,MAAM,CAAC;AAExD,mCAAmC;AACnC,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,WAAW,EAAE,qBAAqB,CAAC;IAC5C,QAAQ,CAAC,SAAS,EAAE,qBAAqB,CAAC;IAC1C,6DAA6D;IAC7D,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED,wDAAwD;AACxD,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,WAAW,EAAE,qBAAqB,CAAC;IAC5C,QAAQ,CAAC,SAAS,EAAE,qBAAqB,CAAC;IAC1C,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;CAC5B;AAED,gFAAgF;AAChF,MAAM,MAAM,aAAa,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM,IAAI;IAAE,QAAQ,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS;CAAE,CAAC;AAEzG,8EAA8E;AAC9E,MAAM,WAAW,WAAW,CAAC,CAAC,SAAS,MAAM;IAC3C,wCAAwC;IACxC,QAAQ,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC,EAAE,cAAc,CAAC,CAAC;IAC/C,oDAAoD;IACpD,IAAI,CAAC,CAAC,EAAE,MAAM,EAAE,aAAa,CAAC,CAAC,CAAC,EAAE,EAA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-ts/context`: the one call that adds context
3
+ * ids, for browsers and Node.js (docs/CONTEXT-DESIGN.md, section 3).
4
+ *
5
+ * This entry depends on `@opentelemetry/api` only. It registers nothing: the
6
+ * context manager, the propagators and the processors come from `init()` or
7
+ * `startNodeTelemetry()`. Without a registered context manager, `withContext`
8
+ * still runs its function, but the values do not stay after an `await`.
9
+ *
10
+ * - The keys are data: `defineContextKeys` names each key, its cardinality and
11
+ * where it may go. A key that no call defined is refused.
12
+ * - A key with `propagate: "internal"` goes in the W3C baggage, so the
13
+ * propagator of otel-ts can send it on an internal call.
14
+ * - A key with `propagate: "none"` stays in a context entry of its own. No
15
+ * baggage propagator sees it, so it never leaves the process.
16
+ *
17
+ * @packageDocumentation
18
+ */
19
+ import { context, createContextKey, propagation } from "@opentelemetry/api";
20
+ /** The default of `maxLength` */
21
+ export const DEFAULT_MAX_LENGTH = 256;
22
+ /*
23
+ * The W3C baggage key is a token (RFC 7230): letters, digits and
24
+ * !#$%&'*+-.^_`|~. A dot is the separator of the semantic conventions.
25
+ */
26
+ const KEY_PATTERN = /^[A-Za-z0-9!#$%&'*+\-.^_`|~]+$/;
27
+ /*
28
+ * The registry is on globalThis, so two copies of this package in one program
29
+ * share their keys, as the copies of @opentelemetry/api share their globals.
30
+ */
31
+ const REGISTRY = Symbol.for("@mark1russell7/otel-ts/context-keys");
32
+ function registry() {
33
+ const holder = globalThis;
34
+ return (holder[REGISTRY] ??= new Map());
35
+ }
36
+ /** The context entry of the keys with `propagate: "none"` */
37
+ const LOCAL_VALUES = createContextKey("@mark1russell7/otel-ts/context local values");
38
+ /** The context entry of the internal mark */
39
+ const INTERNAL_CALL = createContextKey("@mark1russell7/otel-ts/context internal call");
40
+ function ruleOf(key, spec) {
41
+ if (!KEY_PATTERN.test(key))
42
+ throw new TypeError(`The context key "${key}" is not a W3C baggage key: use letters, digits and . _ -`);
43
+ if (spec.cardinality !== "low" && spec.cardinality !== "high")
44
+ throw new TypeError(`The context key "${key}" has no cardinality "low" or "high"`);
45
+ if (spec.propagate !== "internal" && spec.propagate !== "none")
46
+ throw new TypeError(`The context key "${key}" has no propagate "internal" or "none"`);
47
+ const maxLength = spec.maxLength ?? DEFAULT_MAX_LENGTH;
48
+ if (!Number.isInteger(maxLength) || maxLength < 1)
49
+ throw new TypeError(`The maxLength of the context key "${key}" is not a positive integer`);
50
+ return { key, cardinality: spec.cardinality, propagate: spec.propagate, maxLength };
51
+ }
52
+ function sameRule(a, b) {
53
+ return a.cardinality === b.cardinality && a.propagate === b.propagate && a.maxLength === b.maxLength;
54
+ }
55
+ /**
56
+ * Define context keys, one time for each program part. A second definition of
57
+ * a key with the same rules is accepted, so a library and an app can both
58
+ * define `request.id`. A second definition with other rules is an error.
59
+ */
60
+ export function defineContextKeys(specs) {
61
+ const rules = new Map();
62
+ for (const key of Object.keys(specs))
63
+ rules.set(key, ruleOf(key, specs[key]));
64
+ const known = registry();
65
+ // Check all keys first, so a refused set registers no key
66
+ for (const rule of rules.values()) {
67
+ const earlier = known.get(rule.key);
68
+ if (earlier && !sameRule(earlier, rule)) {
69
+ throw new Error(`The context key "${rule.key}" is defined already with other rules (${describe(earlier)}), not ${describe(rule)}`);
70
+ }
71
+ }
72
+ for (const rule of rules.values())
73
+ known.set(rule.key, rule);
74
+ return {
75
+ rules,
76
+ with: (values, fn) => withContext(values, fn),
77
+ get: (key, from) => contextValue(key, from),
78
+ };
79
+ }
80
+ function describe(rule) {
81
+ return `cardinality ${rule.cardinality}, propagate ${rule.propagate}, maxLength ${rule.maxLength}`;
82
+ }
83
+ function knownRule(key) {
84
+ const rule = registry().get(key);
85
+ if (!rule)
86
+ throw new Error(`The context key "${key}" is not defined: call defineContextKeys first`);
87
+ return rule;
88
+ }
89
+ /** The rules of a defined key, or undefined. The processors and the propagator read them. */
90
+ export function contextKeyRule(key) {
91
+ return registry().get(key);
92
+ }
93
+ /** The rules of each defined key */
94
+ export function contextKeyRules() {
95
+ return [...registry().values()];
96
+ }
97
+ /**
98
+ * Run `fn` in a new context with these values, on top of the values of the
99
+ * active context. The async storage keeps the context through `await`,
100
+ * timers and callbacks. A key that is not defined, a value that is not a
101
+ * string and a value longer than the `maxLength` of its key are errors.
102
+ */
103
+ export function withContext(values, fn) {
104
+ return context.with(contextWith(values), fn);
105
+ }
106
+ /** The active context (or `from`) with these values: `withContext` without the call */
107
+ export function contextWith(values, from = context.active()) {
108
+ let baggage = propagation.getBaggage(from) ?? propagation.createBaggage();
109
+ let local;
110
+ for (const [key, value] of Object.entries(values)) {
111
+ if (value === undefined || value === null)
112
+ continue;
113
+ const rule = knownRule(key);
114
+ if (typeof value !== "string")
115
+ throw new TypeError(`The value of the context key "${key}" is not a string`);
116
+ if (value.length > rule.maxLength)
117
+ throw new RangeError(`The value of the context key "${key}" has ${value.length} characters, more than its maxLength ${rule.maxLength}`);
118
+ if (rule.propagate === "internal") {
119
+ baggage = baggage.setEntry(key, { value });
120
+ }
121
+ else {
122
+ local ??= new Map(localValues(from));
123
+ local.set(key, value);
124
+ }
125
+ }
126
+ let next = propagation.setBaggage(from, baggage);
127
+ if (local)
128
+ next = next.setValue(LOCAL_VALUES, local);
129
+ return next;
130
+ }
131
+ function localValues(from) {
132
+ return from.getValue(LOCAL_VALUES) ?? new Map();
133
+ }
134
+ /** The value of a defined key in the active context (or `from`), or undefined */
135
+ export function contextValue(key, from = context.active()) {
136
+ const rule = knownRule(key);
137
+ if (rule.propagate === "none")
138
+ return localValues(from).get(key);
139
+ return propagation.getBaggage(from)?.getEntry(key)?.value;
140
+ }
141
+ /**
142
+ * The value of each defined key in the active context (or `from`). A baggage
143
+ * entry of a key that is not defined is not in the result: an entry from
144
+ * outside does not become an attribute.
145
+ */
146
+ export function contextValues(from = context.active()) {
147
+ const result = {};
148
+ const known = registry();
149
+ for (const [key, entry] of propagation.getBaggage(from)?.getAllEntries() ?? []) {
150
+ if (known.get(key)?.propagate === "internal")
151
+ result[key] = entry.value;
152
+ }
153
+ for (const [key, value] of localValues(from))
154
+ result[key] = value;
155
+ return result;
156
+ }
157
+ /**
158
+ * Run `fn` with the internal mark: the propagator of otel-ts sends the baggage
159
+ * only on a call that starts in such a context. `@procedures/client` sets the
160
+ * mark around the send of each of its transports.
161
+ */
162
+ export function withInternalCall(fn) {
163
+ return context.with(context.active().setValue(INTERNAL_CALL, true), fn);
164
+ }
165
+ /** True when the active context (or `from`) has the internal mark */
166
+ export function isInternalCall(from = context.active()) {
167
+ return from.getValue(INTERNAL_CALL) === true;
168
+ }
169
+ //# sourceMappingURL=context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.js","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,EAAE,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAgB,MAAM,oBAAoB,CAAC;AAqC1F,iCAAiC;AACjC,MAAM,CAAC,MAAM,kBAAkB,GAAG,GAAG,CAAC;AAEtC;;;GAGG;AACH,MAAM,WAAW,GAAG,gCAAgC,CAAC;AAErD;;;GAGG;AACH,MAAM,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAC,qCAAqC,CAAC,CAAC;AAEnE,SAAS,QAAQ;IACf,MAAM,MAAM,GAAG,UAAuC,CAAC;IACvD,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,IAAI,GAAG,EAAE,CAAC,CAAC;AAC1C,CAAC;AAED,6DAA6D;AAC7D,MAAM,YAAY,GAAG,gBAAgB,CAAC,6CAA6C,CAAC,CAAC;AACrF,6CAA6C;AAC7C,MAAM,aAAa,GAAG,gBAAgB,CAAC,8CAA8C,CAAC,CAAC;AAEvF,SAAS,MAAM,CAAC,GAAW,EAAE,IAAoB;IAC/C,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC;QAAE,MAAM,IAAI,SAAS,CAAC,oBAAoB,GAAG,2DAA2D,CAAC,CAAC;IACpI,IAAI,IAAI,CAAC,WAAW,KAAK,KAAK,IAAI,IAAI,CAAC,WAA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ClE,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,gBAAgB,CAAI,EAAW;IAC7C,OAAO,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,aAAa,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC,CAAC;AAC1E,CAAC;AAED,qEAAqE;AACrE,MAAM,UAAU,cAAc,CAAC,OAAgB,OAAO,CAAC,MAAM,EAAE;IAC7D,OAAO,IAAI,CAAC,QAAQ,CAAC,aAAa,CAAC,KAAK,IAAI,CAAC;AAC/C,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/otel-ts",
4
- "version": "0.3.0",
4
+ "version": "0.3.1",
5
5
  "description": "Frontend observability in one init() call — OpenTelemetry + Grafana Faro for any TypeScript web app",
6
6
  "license": "MIT",
7
7
  "author": "Mark Russell (https://github.com/mark1russell7)",
@@ -29,6 +29,10 @@
29
29
  "types": "./dist/core.d.ts",
30
30
  "import": "./dist/core.js"
31
31
  },
32
+ "./context": {
33
+ "types": "./dist/context.d.ts",
34
+ "import": "./dist/context.js"
35
+ },
32
36
  "./node": {
33
37
  "types": "./dist/node.d.ts",
34
38
  "import": "./dist/node.js"
package/src/context.ts ADDED
@@ -0,0 +1,207 @@
1
+ /**
2
+ * The entry `@mark1russell7/otel-ts/context`: the one call that adds context
3
+ * ids, for browsers and Node.js (docs/CONTEXT-DESIGN.md, section 3).
4
+ *
5
+ * This entry depends on `@opentelemetry/api` only. It registers nothing: the
6
+ * context manager, the propagators and the processors come from `init()` or
7
+ * `startNodeTelemetry()`. Without a registered context manager, `withContext`
8
+ * still runs its function, but the values do not stay after an `await`.
9
+ *
10
+ * - The keys are data: `defineContextKeys` names each key, its cardinality and
11
+ * where it may go. A key that no call defined is refused.
12
+ * - A key with `propagate: "internal"` goes in the W3C baggage, so the
13
+ * propagator of otel-ts can send it on an internal call.
14
+ * - A key with `propagate: "none"` stays in a context entry of its own. No
15
+ * baggage propagator sees it, so it never leaves the process.
16
+ *
17
+ * @packageDocumentation
18
+ */
19
+ import { context, createContextKey, propagation, type Context } from "@opentelemetry/api";
20
+
21
+ /** How many distinct values a key has: "low" may become a metric attribute, "high" never does */
22
+ export type ContextKeyCardinality = "low" | "high";
23
+
24
+ /** Where a key may go: "internal" on internal calls (in the baggage), "none" never out of the process */
25
+ export type ContextKeyPropagation = "internal" | "none";
26
+
27
+ /** The rules of one context key */
28
+ export interface ContextKeySpec {
29
+ readonly cardinality: ContextKeyCardinality;
30
+ readonly propagate: ContextKeyPropagation;
31
+ /** The longest value, in UTF-16 code units. Default: 256. */
32
+ readonly maxLength?: number;
33
+ }
34
+
35
+ /** The rules of one key, with each default filled in */
36
+ export interface ContextKeyRule {
37
+ readonly key: string;
38
+ readonly cardinality: ContextKeyCardinality;
39
+ readonly propagate: ContextKeyPropagation;
40
+ readonly maxLength: number;
41
+ }
42
+
43
+ /** The values of a set of keys. An `undefined` or `null` value adds nothing. */
44
+ export type ContextValues<K extends string = string> = { readonly [P in K]?: string | null | undefined };
45
+
46
+ /** The keys that one call of `defineContextKeys` defined, with typed calls */
47
+ export interface ContextKeys<K extends string> {
48
+ /** The rules of each key of this set */
49
+ readonly rules: ReadonlyMap<K, ContextKeyRule>;
50
+ /** `withContext`, with the key names of this set */
51
+ with<T>(values: ContextValues<K>, fn: () => T): T;
52
+ /** `contextValue`, with the key names of this set */
53
+ get(key: K, from?: Context): string | undefined;
54
+ }
55
+
56
+ /** The default of `maxLength` */
57
+ export const DEFAULT_MAX_LENGTH = 256;
58
+
59
+ /*
60
+ * The W3C baggage key is a token (RFC 7230): letters, digits and
61
+ * !#$%&'*+-.^_`|~. A dot is the separator of the semantic conventions.
62
+ */
63
+ const KEY_PATTERN = /^[A-Za-z0-9!#$%&'*+\-.^_`|~]+$/;
64
+
65
+ /*
66
+ * The registry is on globalThis, so two copies of this package in one program
67
+ * share their keys, as the copies of @opentelemetry/api share their globals.
68
+ */
69
+ const REGISTRY = Symbol.for("@mark1russell7/otel-ts/context-keys");
70
+ type Registry = Map<string, ContextKeyRule>;
71
+ function registry(): Registry {
72
+ const holder = globalThis as { [REGISTRY]?: Registry };
73
+ return (holder[REGISTRY] ??= new Map());
74
+ }
75
+
76
+ /** The context entry of the keys with `propagate: "none"` */
77
+ const LOCAL_VALUES = createContextKey("@mark1russell7/otel-ts/context local values");
78
+ /** The context entry of the internal mark */
79
+ const INTERNAL_CALL = createContextKey("@mark1russell7/otel-ts/context internal call");
80
+
81
+ function ruleOf(key: string, spec: ContextKeySpec): ContextKeyRule {
82
+ if (!KEY_PATTERN.test(key)) throw new TypeError(`The context key "${key}" is not a W3C baggage key: use letters, digits and . _ -`);
83
+ if (spec.cardinality !== "low" && spec.cardinality !== "high") throw new TypeError(`The context key "${key}" has no cardinality "low" or "high"`);
84
+ if (spec.propagate !== "internal" && spec.propagate !== "none") throw new TypeError(`The context key "${key}" has no propagate "internal" or "none"`);
85
+ const maxLength = spec.maxLength ?? DEFAULT_MAX_LENGTH;
86
+ if (!Number.isInteger(maxLength) || maxLength < 1) throw new TypeError(`The maxLength of the context key "${key}" is not a positive integer`);
87
+ return { key, cardinality: spec.cardinality, propagate: spec.propagate, maxLength };
88
+ }
89
+
90
+ function sameRule(a: ContextKeyRule, b: ContextKeyRule): boolean {
91
+ return a.cardinality === b.cardinality && a.propagate === b.propagate && a.maxLength === b.maxLength;
92
+ }
93
+
94
+ /**
95
+ * Define context keys, one time for each program part. A second definition of
96
+ * a key with the same rules is accepted, so a library and an app can both
97
+ * define `request.id`. A second definition with other rules is an error.
98
+ */
99
+ export function defineContextKeys<K extends string>(specs: { readonly [P in K]: ContextKeySpec }): ContextKeys<K> {
100
+ const rules = new Map<K, ContextKeyRule>();
101
+ for (const key of Object.keys(specs) as K[]) rules.set(key, ruleOf(key, specs[key]));
102
+ const known = registry();
103
+ // Check all keys first, so a refused set registers no key
104
+ for (const rule of rules.values()) {
105
+ const earlier = known.get(rule.key);
106
+ if (earlier && !sameRule(earlier, rule)) {
107
+ throw new Error(`The context key "${rule.key}" is defined already with other rules (${describe(earlier)}), not ${describe(rule)}`);
108
+ }
109
+ }
110
+ for (const rule of rules.values()) known.set(rule.key, rule);
111
+ return {
112
+ rules,
113
+ with: (values, fn) => withContext(values, fn),
114
+ get: (key, from) => contextValue(key, from),
115
+ };
116
+ }
117
+
118
+ function describe(rule: ContextKeyRule): string {
119
+ return `cardinality ${rule.cardinality}, propagate ${rule.propagate}, maxLength ${rule.maxLength}`;
120
+ }
121
+
122
+ function knownRule(key: string): ContextKeyRule {
123
+ const rule = registry().get(key);
124
+ if (!rule) throw new Error(`The context key "${key}" is not defined: call defineContextKeys first`);
125
+ return rule;
126
+ }
127
+
128
+ /** The rules of a defined key, or undefined. The processors and the propagator read them. */
129
+ export function contextKeyRule(key: string): ContextKeyRule | undefined {
130
+ return registry().get(key);
131
+ }
132
+
133
+ /** The rules of each defined key */
134
+ export function contextKeyRules(): readonly ContextKeyRule[] {
135
+ return [...registry().values()];
136
+ }
137
+
138
+ /**
139
+ * Run `fn` in a new context with these values, on top of the values of the
140
+ * active context. The async storage keeps the context through `await`,
141
+ * timers and callbacks. A key that is not defined, a value that is not a
142
+ * string and a value longer than the `maxLength` of its key are errors.
143
+ */
144
+ export function withContext<T>(values: ContextValues, fn: () => T): T {
145
+ return context.with(contextWith(values), fn);
146
+ }
147
+
148
+ /** The active context (or `from`) with these values: `withContext` without the call */
149
+ export function contextWith(values: ContextValues, from: Context = context.active()): Context {
150
+ let baggage = propagation.getBaggage(from) ?? propagation.createBaggage();
151
+ let local: Map<string, string> | undefined;
152
+ for (const [key, value] of Object.entries(values)) {
153
+ if (value === undefined || value === null) continue;
154
+ const rule = knownRule(key);
155
+ if (typeof value !== "string") throw new TypeError(`The value of the context key "${key}" is not a string`);
156
+ if (value.length > rule.maxLength) throw new RangeError(`The value of the context key "${key}" has ${value.length} characters, more than its maxLength ${rule.maxLength}`);
157
+ if (rule.propagate === "internal") {
158
+ baggage = baggage.setEntry(key, { value });
159
+ } else {
160
+ local ??= new Map(localValues(from));
161
+ local.set(key, value);
162
+ }
163
+ }
164
+ let next = propagation.setBaggage(from, baggage);
165
+ if (local) next = next.setValue(LOCAL_VALUES, local);
166
+ return next;
167
+ }
168
+
169
+ function localValues(from: Context): ReadonlyMap<string, string> {
170
+ return (from.getValue(LOCAL_VALUES) as ReadonlyMap<string, string> | undefined) ?? new Map();
171
+ }
172
+
173
+ /** The value of a defined key in the active context (or `from`), or undefined */
174
+ export function contextValue(key: string, from: Context = context.active()): string | undefined {
175
+ const rule = knownRule(key);
176
+ if (rule.propagate === "none") return localValues(from).get(key);
177
+ return propagation.getBaggage(from)?.getEntry(key)?.value;
178
+ }
179
+
180
+ /**
181
+ * The value of each defined key in the active context (or `from`). A baggage
182
+ * entry of a key that is not defined is not in the result: an entry from
183
+ * outside does not become an attribute.
184
+ */
185
+ export function contextValues(from: Context = context.active()): Readonly<Record<string, string>> {
186
+ const result: Record<string, string> = {};
187
+ const known = registry();
188
+ for (const [key, entry] of propagation.getBaggage(from)?.getAllEntries() ?? []) {
189
+ if (known.get(key)?.propagate === "internal") result[key] = entry.value;
190
+ }
191
+ for (const [key, value] of localValues(from)) result[key] = value;
192
+ return result;
193
+ }
194
+
195
+ /**
196
+ * Run `fn` with the internal mark: the propagator of otel-ts sends the baggage
197
+ * only on a call that starts in such a context. `@procedures/client` sets the
198
+ * mark around the send of each of its transports.
199
+ */
200
+ export function withInternalCall<T>(fn: () => T): T {
201
+ return context.with(context.active().setValue(INTERNAL_CALL, true), fn);
202
+ }
203
+
204
+ /** True when the active context (or `from`) has the internal mark */
205
+ export function isInternalCall(from: Context = context.active()): boolean {
206
+ return from.getValue(INTERNAL_CALL) === true;
207
+ }