@contractspec/lib.bus 1.57.0 → 1.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/auditableBus.d.ts +76 -80
  2. package/dist/auditableBus.d.ts.map +1 -1
  3. package/dist/auditableBus.js +149 -132
  4. package/dist/browser/auditableBus.js +153 -0
  5. package/dist/browser/eventBus.js +28 -0
  6. package/dist/browser/filtering.js +147 -0
  7. package/dist/browser/inMemoryBus.js +25 -0
  8. package/dist/browser/index.js +373 -0
  9. package/dist/browser/metadata.js +60 -0
  10. package/dist/browser/subscriber.js +37 -0
  11. package/dist/eventBus.d.ts +9 -13
  12. package/dist/eventBus.d.ts.map +1 -1
  13. package/dist/eventBus.js +23 -26
  14. package/dist/filtering.d.ts +53 -57
  15. package/dist/filtering.d.ts.map +1 -1
  16. package/dist/filtering.js +139 -125
  17. package/dist/inMemoryBus.d.ts +6 -10
  18. package/dist/inMemoryBus.d.ts.map +1 -1
  19. package/dist/inMemoryBus.js +25 -28
  20. package/dist/index.d.ts +7 -7
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +374 -8
  23. package/dist/metadata.d.ts +60 -63
  24. package/dist/metadata.d.ts.map +1 -1
  25. package/dist/metadata.js +55 -76
  26. package/dist/node/auditableBus.js +153 -0
  27. package/dist/node/eventBus.js +28 -0
  28. package/dist/node/filtering.js +147 -0
  29. package/dist/node/inMemoryBus.js +25 -0
  30. package/dist/node/index.js +373 -0
  31. package/dist/node/metadata.js +60 -0
  32. package/dist/node/subscriber.js +37 -0
  33. package/dist/subscriber.d.ts +6 -10
  34. package/dist/subscriber.d.ts.map +1 -1
  35. package/dist/subscriber.js +35 -16
  36. package/package.json +69 -28
  37. package/dist/auditableBus.js.map +0 -1
  38. package/dist/eventBus.js.map +0 -1
  39. package/dist/filtering.js.map +0 -1
  40. package/dist/inMemoryBus.js.map +0 -1
  41. package/dist/metadata.js.map +0 -1
  42. package/dist/subscriber.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,8 +1,374 @@
1
- import { decodeEvent, encodeEvent, makePublisher } from "./eventBus.js";
2
- import { AuditableEventBus, InMemoryAuditStorage, createAuditableEventBus, makeAuditablePublisher } from "./auditableBus.js";
3
- import { DomainEventBus, EventRouter, createDomainBus, createEventRouter, createFilteredSubscriber, matchesFilter } from "./filtering.js";
4
- import { InMemoryBus } from "./inMemoryBus.js";
5
- import { subscribeEvent } from "./subscriber.js";
6
- import { MetadataContext, createMetadataContext, createMetadataFromContext, mergeMetadata } from "./metadata.js";
7
-
8
- export { AuditableEventBus, DomainEventBus, EventRouter, InMemoryAuditStorage, InMemoryBus, MetadataContext, createAuditableEventBus, createDomainBus, createEventRouter, createFilteredSubscriber, createMetadataContext, createMetadataFromContext, decodeEvent, encodeEvent, makeAuditablePublisher, makePublisher, matchesFilter, mergeMetadata, subscribeEvent };
1
+ // @bun
2
+ // src/eventBus.ts
3
+ import {
4
+ eventKey
5
+ } from "@contractspec/lib.contracts";
6
+ function encodeEvent(envelope) {
7
+ return new TextEncoder().encode(JSON.stringify(envelope));
8
+ }
9
+ function decodeEvent(data) {
10
+ return JSON.parse(new TextDecoder().decode(data));
11
+ }
12
+ function makePublisher(bus, spec) {
13
+ return async (payload, traceId) => {
14
+ const envelope = {
15
+ id: crypto.randomUUID(),
16
+ occurredAt: new Date().toISOString(),
17
+ key: spec.meta.key,
18
+ version: spec.meta.version,
19
+ payload,
20
+ traceId
21
+ };
22
+ await bus.publish(eventKey(spec.meta.key, spec.meta.version), encodeEvent(envelope));
23
+ };
24
+ }
25
+
26
+ // src/auditableBus.ts
27
+ import {
28
+ eventKey as eventKey2
29
+ } from "@contractspec/lib.contracts";
30
+ class AuditableEventBus {
31
+ bus;
32
+ storage;
33
+ defaultMetadata;
34
+ shouldAudit;
35
+ transformAuditRecord;
36
+ constructor(options) {
37
+ this.bus = options.bus;
38
+ this.storage = options.storage;
39
+ this.defaultMetadata = options.defaultMetadata ?? {};
40
+ this.shouldAudit = options.shouldAudit ?? (() => true);
41
+ this.transformAuditRecord = options.transformAuditRecord;
42
+ }
43
+ async publish(topic, bytes) {
44
+ await this.bus.publish(topic, bytes);
45
+ if (this.storage) {
46
+ try {
47
+ const envelope = decodeEvent(bytes);
48
+ if (this.shouldAudit(envelope.key, envelope)) {
49
+ let record = {
50
+ id: crypto.randomUUID(),
51
+ eventKey: envelope.key,
52
+ eventVersion: envelope.version,
53
+ payload: envelope.payload,
54
+ metadata: {
55
+ ...this.defaultMetadata,
56
+ ...envelope.metadata
57
+ },
58
+ occurredAt: envelope.occurredAt,
59
+ traceId: envelope.traceId,
60
+ recordedAt: new Date
61
+ };
62
+ if (this.transformAuditRecord) {
63
+ record = this.transformAuditRecord(record);
64
+ }
65
+ await this.storage.store(record);
66
+ }
67
+ } catch (error) {
68
+ console.error("Failed to record audit:", error);
69
+ }
70
+ }
71
+ }
72
+ async subscribe(topic, handler) {
73
+ return this.bus.subscribe(topic, handler);
74
+ }
75
+ async queryAudit(options) {
76
+ if (!this.storage?.query) {
77
+ throw new Error("Audit storage does not support querying");
78
+ }
79
+ return this.storage.query(options);
80
+ }
81
+ }
82
+ function makeAuditablePublisher(bus, spec, defaultMetadata) {
83
+ return async (payload, options) => {
84
+ const envelope = {
85
+ id: crypto.randomUUID(),
86
+ occurredAt: new Date().toISOString(),
87
+ key: spec.meta.key,
88
+ version: spec.meta.version,
89
+ payload,
90
+ traceId: options?.traceId,
91
+ metadata: {
92
+ ...defaultMetadata,
93
+ ...options?.metadata
94
+ }
95
+ };
96
+ await bus.publish(eventKey2(spec.meta.key, spec.meta.version), encodeEvent(envelope));
97
+ };
98
+ }
99
+
100
+ class InMemoryAuditStorage {
101
+ records = [];
102
+ async store(record) {
103
+ this.records.push(record);
104
+ }
105
+ async query(options) {
106
+ let results = [...this.records];
107
+ if (options.eventKey) {
108
+ results = results.filter((r) => r.eventKey === options.eventKey);
109
+ }
110
+ if (options.actorId) {
111
+ results = results.filter((r) => r.metadata?.actorId === options.actorId);
112
+ }
113
+ if (options.targetId) {
114
+ results = results.filter((r) => r.metadata?.targetId === options.targetId);
115
+ }
116
+ if (options.orgId) {
117
+ results = results.filter((r) => r.metadata?.orgId === options.orgId);
118
+ }
119
+ if (options.traceId) {
120
+ results = results.filter((r) => r.traceId === options.traceId);
121
+ }
122
+ if (options.from) {
123
+ const from = options.from;
124
+ results = results.filter((r) => new Date(r.occurredAt) >= from);
125
+ }
126
+ if (options.to) {
127
+ const to = options.to;
128
+ results = results.filter((r) => new Date(r.occurredAt) <= to);
129
+ }
130
+ results.sort((a, b) => new Date(b.occurredAt).getTime() - new Date(a.occurredAt).getTime());
131
+ const offset = options.offset ?? 0;
132
+ const limit = options.limit ?? 100;
133
+ return results.slice(offset, offset + limit);
134
+ }
135
+ getAll() {
136
+ return [...this.records];
137
+ }
138
+ clear() {
139
+ this.records = [];
140
+ }
141
+ }
142
+ function createAuditableEventBus(bus, options) {
143
+ return new AuditableEventBus({
144
+ bus,
145
+ storage: options?.storage ?? new InMemoryAuditStorage,
146
+ ...options
147
+ });
148
+ }
149
+
150
+ // src/filtering.ts
151
+ import { satisfies } from "compare-versions";
152
+ function matchesFilter(envelope, filter) {
153
+ if (filter.eventName) {
154
+ const pattern = filter.eventName.replace(/\*/g, ".*");
155
+ const regex = new RegExp(`^${pattern}$`);
156
+ if (!regex.test(envelope.key)) {
157
+ return false;
158
+ }
159
+ }
160
+ if (filter.domain) {
161
+ if (!envelope.key.startsWith(filter.domain + ".")) {
162
+ return false;
163
+ }
164
+ }
165
+ if (filter.version) {
166
+ if (!envelope.version || !satisfies(envelope.version, filter.version)) {
167
+ return false;
168
+ }
169
+ }
170
+ if (filter.actorId && envelope.metadata?.actorId !== filter.actorId) {
171
+ return false;
172
+ }
173
+ if (filter.orgId && envelope.metadata?.orgId !== filter.orgId) {
174
+ return false;
175
+ }
176
+ if (filter.tags) {
177
+ const eventTags = envelope.metadata?.tags ?? {};
178
+ for (const [key, value] of Object.entries(filter.tags)) {
179
+ if (eventTags[key] !== value) {
180
+ return false;
181
+ }
182
+ }
183
+ }
184
+ if (filter.predicate && !filter.predicate(envelope)) {
185
+ return false;
186
+ }
187
+ return true;
188
+ }
189
+ function createFilteredSubscriber(bus, filter, handler) {
190
+ return async (topic) => {
191
+ return bus.subscribe(topic, async (bytes) => {
192
+ const envelope = decodeEvent(bytes);
193
+ if (matchesFilter(envelope, filter)) {
194
+ await handler(envelope);
195
+ }
196
+ });
197
+ };
198
+ }
199
+
200
+ class DomainEventBus {
201
+ bus;
202
+ domain;
203
+ constructor(bus, domain) {
204
+ this.bus = bus;
205
+ this.domain = domain;
206
+ }
207
+ async publish(spec, payload, metadata) {
208
+ const eventName = spec.meta.key.startsWith(this.domain + ".") ? spec.meta.key : `${this.domain}.${spec.meta.key}`;
209
+ const envelope = {
210
+ id: crypto.randomUUID(),
211
+ occurredAt: new Date().toISOString(),
212
+ key: eventName,
213
+ version: spec.meta.version,
214
+ payload,
215
+ metadata
216
+ };
217
+ const bytes = new TextEncoder().encode(JSON.stringify(envelope));
218
+ await this.bus.publish(`${eventName}.v${spec.meta.version}`, bytes);
219
+ }
220
+ async subscribeAll(handler) {
221
+ return this.bus.subscribe(`${this.domain}.*`, async (bytes) => {
222
+ const envelope = decodeEvent(bytes);
223
+ await handler(envelope);
224
+ });
225
+ }
226
+ async subscribeFiltered(filter, handler) {
227
+ const fullFilter = {
228
+ ...filter,
229
+ domain: this.domain
230
+ };
231
+ return this.bus.subscribe(`${this.domain}.*`, async (bytes) => {
232
+ const envelope = decodeEvent(bytes);
233
+ if (matchesFilter(envelope, fullFilter)) {
234
+ await handler(envelope);
235
+ }
236
+ });
237
+ }
238
+ }
239
+ function createDomainBus(bus, domain) {
240
+ return new DomainEventBus(bus, domain);
241
+ }
242
+
243
+ class EventRouter {
244
+ routes = [];
245
+ route(filter, handler) {
246
+ this.routes.push({ filter, handler });
247
+ return this;
248
+ }
249
+ async dispatch(envelope) {
250
+ const matchingRoutes = this.routes.filter((r) => matchesFilter(envelope, r.filter));
251
+ await Promise.all(matchingRoutes.map((r) => r.handler(envelope)));
252
+ }
253
+ createSubscriber(bus) {
254
+ return async (topic) => {
255
+ return bus.subscribe(topic, async (bytes) => {
256
+ const envelope = decodeEvent(bytes);
257
+ await this.dispatch(envelope);
258
+ });
259
+ };
260
+ }
261
+ }
262
+ function createEventRouter() {
263
+ return new EventRouter;
264
+ }
265
+
266
+ // src/inMemoryBus.ts
267
+ class InMemoryBus {
268
+ listeners = new Map;
269
+ async publish(topic, payload) {
270
+ const handlers = this.listeners.get(topic);
271
+ if (!handlers)
272
+ return;
273
+ await Promise.all([...handlers].map((h) => h(payload)));
274
+ }
275
+ async subscribe(topic, handler) {
276
+ const topicStr = String(topic);
277
+ let set = this.listeners.get(topicStr);
278
+ if (!set) {
279
+ set = new Set;
280
+ this.listeners.set(topicStr, set);
281
+ }
282
+ set.add(handler);
283
+ return async () => {
284
+ set?.delete(handler);
285
+ };
286
+ }
287
+ }
288
+
289
+ // src/subscriber.ts
290
+ async function subscribeEvent(bus, spec, handler) {
291
+ const topic = `${spec.meta.key}.v${spec.meta.version}`;
292
+ return bus.subscribe(topic, async (u8) => {
293
+ const env = decodeEvent(u8);
294
+ if (env.key !== spec.meta.key || env.version !== spec.meta.version)
295
+ return;
296
+ await handler(env.payload, { traceId: env.traceId, deliveryId: env.id });
297
+ });
298
+ }
299
+
300
+ // src/metadata.ts
301
+ function createMetadataFromContext(context) {
302
+ return {
303
+ actorId: context.userId,
304
+ actorType: context.userId ? "user" : "system",
305
+ orgId: context.orgId,
306
+ tenantId: context.orgId,
307
+ sessionId: context.sessionId,
308
+ requestId: context.requestId,
309
+ traceId: context.traceId || crypto.randomUUID(),
310
+ clientIp: context.clientIp,
311
+ userAgent: context.userAgent
312
+ };
313
+ }
314
+ function mergeMetadata(base, overrides) {
315
+ return {
316
+ ...base,
317
+ ...overrides,
318
+ tags: {
319
+ ...base.tags,
320
+ ...overrides.tags
321
+ }
322
+ };
323
+ }
324
+
325
+ class MetadataContext {
326
+ metadata;
327
+ constructor(initial = {}) {
328
+ this.metadata = { ...initial };
329
+ if (!this.metadata.traceId) {
330
+ this.metadata.traceId = crypto.randomUUID();
331
+ }
332
+ }
333
+ get() {
334
+ return { ...this.metadata };
335
+ }
336
+ set(key, value) {
337
+ this.metadata[key] = value;
338
+ return this;
339
+ }
340
+ tag(key, value) {
341
+ this.metadata.tags = { ...this.metadata.tags, [key]: value };
342
+ return this;
343
+ }
344
+ child(overrides = {}) {
345
+ return new MetadataContext(mergeMetadata(this.metadata, {
346
+ ...overrides,
347
+ spanId: crypto.randomUUID()
348
+ }));
349
+ }
350
+ }
351
+ function createMetadataContext(initial) {
352
+ return new MetadataContext(initial);
353
+ }
354
+ export {
355
+ subscribeEvent,
356
+ mergeMetadata,
357
+ matchesFilter,
358
+ makePublisher,
359
+ makeAuditablePublisher,
360
+ encodeEvent,
361
+ decodeEvent,
362
+ createMetadataFromContext,
363
+ createMetadataContext,
364
+ createFilteredSubscriber,
365
+ createEventRouter,
366
+ createDomainBus,
367
+ createAuditableEventBus,
368
+ MetadataContext,
369
+ InMemoryBus,
370
+ InMemoryAuditStorage,
371
+ EventRouter,
372
+ DomainEventBus,
373
+ AuditableEventBus
374
+ };
@@ -1,82 +1,79 @@
1
- //#region src/metadata.d.ts
2
1
  /**
3
2
  * Event metadata that enriches events with contextual information.
4
3
  */
5
- interface EventMetadata {
6
- /** ID of the actor (user) who triggered the event */
7
- actorId?: string;
8
- /** Type of actor (user, system, service) */
9
- actorType?: 'user' | 'system' | 'service';
10
- /** Target resource ID */
11
- targetId?: string;
12
- /** Target resource type */
13
- targetType?: string;
14
- /** Organization context */
15
- orgId?: string;
16
- /** Tenant context (if different from org) */
17
- tenantId?: string;
18
- /** Distributed trace ID */
19
- traceId?: string;
20
- /** Parent span ID */
21
- spanId?: string;
22
- /** Client IP address */
23
- clientIp?: string;
24
- /** Client user agent */
25
- userAgent?: string;
26
- /** Session ID */
27
- sessionId?: string;
28
- /** Request ID */
29
- requestId?: string;
30
- /** Source service name */
31
- source?: string;
32
- /** Correlation ID for related events */
33
- correlationId?: string;
34
- /** Custom tags for filtering/routing */
35
- tags?: Record<string, string>;
4
+ export interface EventMetadata {
5
+ /** ID of the actor (user) who triggered the event */
6
+ actorId?: string;
7
+ /** Type of actor (user, system, service) */
8
+ actorType?: 'user' | 'system' | 'service';
9
+ /** Target resource ID */
10
+ targetId?: string;
11
+ /** Target resource type */
12
+ targetType?: string;
13
+ /** Organization context */
14
+ orgId?: string;
15
+ /** Tenant context (if different from org) */
16
+ tenantId?: string;
17
+ /** Distributed trace ID */
18
+ traceId?: string;
19
+ /** Parent span ID */
20
+ spanId?: string;
21
+ /** Client IP address */
22
+ clientIp?: string;
23
+ /** Client user agent */
24
+ userAgent?: string;
25
+ /** Session ID */
26
+ sessionId?: string;
27
+ /** Request ID */
28
+ requestId?: string;
29
+ /** Source service name */
30
+ source?: string;
31
+ /** Correlation ID for related events */
32
+ correlationId?: string;
33
+ /** Custom tags for filtering/routing */
34
+ tags?: Record<string, string>;
36
35
  }
37
36
  /**
38
37
  * Create metadata from request context.
39
38
  */
40
- declare function createMetadataFromContext(context: {
41
- userId?: string;
42
- orgId?: string;
43
- sessionId?: string;
44
- requestId?: string;
45
- traceId?: string;
46
- clientIp?: string;
47
- userAgent?: string;
39
+ export declare function createMetadataFromContext(context: {
40
+ userId?: string;
41
+ orgId?: string;
42
+ sessionId?: string;
43
+ requestId?: string;
44
+ traceId?: string;
45
+ clientIp?: string;
46
+ userAgent?: string;
48
47
  }): EventMetadata;
49
48
  /**
50
49
  * Merge metadata with overrides.
51
50
  */
52
- declare function mergeMetadata(base: EventMetadata, overrides: Partial<EventMetadata>): EventMetadata;
51
+ export declare function mergeMetadata(base: EventMetadata, overrides: Partial<EventMetadata>): EventMetadata;
53
52
  /**
54
53
  * Create a metadata context that can be passed through operations.
55
54
  */
56
- declare class MetadataContext {
57
- private metadata;
58
- constructor(initial?: EventMetadata);
59
- /**
60
- * Get the current metadata.
61
- */
62
- get(): EventMetadata;
63
- /**
64
- * Set a metadata value.
65
- */
66
- set<K extends keyof EventMetadata>(key: K, value: EventMetadata[K]): this;
67
- /**
68
- * Add a tag.
69
- */
70
- tag(key: string, value: string): this;
71
- /**
72
- * Create a child context with the same trace.
73
- */
74
- child(overrides?: Partial<EventMetadata>): MetadataContext;
55
+ export declare class MetadataContext {
56
+ private metadata;
57
+ constructor(initial?: EventMetadata);
58
+ /**
59
+ * Get the current metadata.
60
+ */
61
+ get(): EventMetadata;
62
+ /**
63
+ * Set a metadata value.
64
+ */
65
+ set<K extends keyof EventMetadata>(key: K, value: EventMetadata[K]): this;
66
+ /**
67
+ * Add a tag.
68
+ */
69
+ tag(key: string, value: string): this;
70
+ /**
71
+ * Create a child context with the same trace.
72
+ */
73
+ child(overrides?: Partial<EventMetadata>): MetadataContext;
75
74
  }
76
75
  /**
77
76
  * Create a new metadata context.
78
77
  */
79
- declare function createMetadataContext(initial?: EventMetadata): MetadataContext;
80
- //#endregion
81
- export { EventMetadata, MetadataContext, createMetadataContext, createMetadataFromContext, mergeMetadata };
78
+ export declare function createMetadataContext(initial?: EventMetadata): MetadataContext;
82
79
  //# sourceMappingURL=metadata.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"metadata.d.ts","names":[],"sources":["../src/metadata.ts"],"mappings":";;AAGA;;UAAiB,aAAA;EA8BF;EA5Bb,OAAA;EAEA;EAAA,SAAA;EAIA;EAFA,QAAA;EAMA;EAJA,UAAA;EAQA;EANA,KAAA;EAUA;EARA,QAAA;EAYA;EAVA,OAAA;EAcA;EAZA,MAAA;EAcO;EAZP,QAAA;EAYa;EAVb,SAAA;EAgBuC;EAdvC,SAAA;EAsBe;EApBf,SAAA;EAcA;EAZA,MAAA;EAcA;EAZA,aAAA;EAcA;EAZA,IAAA,GAAO,MAAA;AAAA;;;;iBAMO,yBAAA,CAA0B,OAAA;EACxC,MAAA;EACA,KAAA;EACA,SAAA;EACA,S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@
1
- //#region src/metadata.ts
2
- /**
3
- * Create metadata from request context.
4
- */
1
+ // @bun
2
+ // src/metadata.ts
5
3
  function createMetadataFromContext(context) {
6
- return {
7
- actorId: context.userId,
8
- actorType: context.userId ? "user" : "system",
9
- orgId: context.orgId,
10
- tenantId: context.orgId,
11
- sessionId: context.sessionId,
12
- requestId: context.requestId,
13
- traceId: context.traceId || crypto.randomUUID(),
14
- clientIp: context.clientIp,
15
- userAgent: context.userAgent
16
- };
4
+ return {
5
+ actorId: context.userId,
6
+ actorType: context.userId ? "user" : "system",
7
+ orgId: context.orgId,
8
+ tenantId: context.orgId,
9
+ sessionId: context.sessionId,
10
+ requestId: context.requestId,
11
+ traceId: context.traceId || crypto.randomUUID(),
12
+ clientIp: context.clientIp,
13
+ userAgent: context.userAgent
14
+ };
17
15
  }
18
- /**
19
- * Merge metadata with overrides.
20
- */
21
16
  function mergeMetadata(base, overrides) {
22
- return {
23
- ...base,
24
- ...overrides,
25
- tags: {
26
- ...base.tags,
27
- ...overrides.tags
28
- }
29
- };
17
+ return {
18
+ ...base,
19
+ ...overrides,
20
+ tags: {
21
+ ...base.tags,
22
+ ...overrides.tags
23
+ }
24
+ };
25
+ }
26
+
27
+ class MetadataContext {
28
+ metadata;
29
+ constructor(initial = {}) {
30
+ this.metadata = { ...initial };
31
+ if (!this.metadata.traceId) {
32
+ this.metadata.traceId = crypto.randomUUID();
33
+ }
34
+ }
35
+ get() {
36
+ return { ...this.metadata };
37
+ }
38
+ set(key, value) {
39
+ this.metadata[key] = value;
40
+ return this;
41
+ }
42
+ tag(key, value) {
43
+ this.metadata.tags = { ...this.metadata.tags, [key]: value };
44
+ return this;
45
+ }
46
+ child(overrides = {}) {
47
+ return new MetadataContext(mergeMetadata(this.metadata, {
48
+ ...overrides,
49
+ spanId: crypto.randomUUID()
50
+ }));
51
+ }
30
52
  }
31
- /**
32
- * Create a metadata context that can be passed through operations.
33
- */
34
- var MetadataContext = class MetadataContext {
35
- metadata;
36
- constructor(initial = {}) {
37
- this.metadata = { ...initial };
38
- if (!this.metadata.traceId) this.metadata.traceId = crypto.randomUUID();
39
- }
40
- /**
41
- * Get the current metadata.
42
- */
43
- get() {
44
- return { ...this.metadata };
45
- }
46
- /**
47
- * Set a metadata value.
48
- */
49
- set(key, value) {
50
- this.metadata[key] = value;
51
- return this;
52
- }
53
- /**
54
- * Add a tag.
55
- */
56
- tag(key, value) {
57
- this.metadata.tags = {
58
- ...this.metadata.tags,
59
- [key]: value
60
- };
61
- return this;
62
- }
63
- /**
64
- * Create a child context with the same trace.
65
- */
66
- child(overrides = {}) {
67
- return new MetadataContext(mergeMetadata(this.metadata, {
68
- ...overrides,
69
- spanId: crypto.randomUUID()
70
- }));
71
- }
72
- };
73
- /**
74
- * Create a new metadata context.
75
- */
76
53
  function createMetadataContext(initial) {
77
- return new MetadataContext(initial);
54
+ return new MetadataContext(initial);
78
55
  }
79
-
80
- //#endregion
81
- export { MetadataContext, createMetadataContext, createMetadataFromContext, mergeMetadata };
82
- //# sourceMappingURL=metadata.js.map
56
+ export {
57
+ mergeMetadata,
58
+ createMetadataFromContext,
59
+ createMetadataContext,
60
+ MetadataContext
61
+ };