UNPKG

1.64 kBJavaScriptView Raw
1'use strict';
2
3const csprng = require('@lukeed/csprng');
4
5let IDX = 256, HEX = [];
6for (; IDX--;)
7 HEX[IDX] = (IDX + 256).toString(16).substring(1);
8/*#__INLINE__*/
9const to_hex = (arr) => {
10 let i = 0, output = '';
11 // @ts-ignore
12 for (; i < arr.length; i++)
13 output += HEX[arr[i]];
14 return output;
15};
16/*
17Anatomy of a Traceparent
18
1900-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
20^ ^ ^ ^
21| | | |
22| | | flags (2 hex)
23| | parent-id (16 hex)
24| trace-id (32 hex)
25version (2 hex)
26*/
27const trace_id_size = 16;
28const parent_id_size = 8;
29const W3C_TRACEPARENT_VERSION = '00';
30const sampled_flag = '00';
31const traceparent = (version, trace_id, parent_id, flags) => ({
32 version,
33 trace_id,
34 parent_id,
35 flags,
36 child() {
37 return traceparent(this.version, this.trace_id, to_hex(csprng.random(parent_id_size)), this.flags);
38 },
39 toString() {
40 return `${this.version}-${this.trace_id}-${this.parent_id}-${this.flags}`;
41 },
42});
43const make = () => {
44 const total_size = trace_id_size + parent_id_size;
45 const id = csprng.random(total_size);
46 return traceparent(W3C_TRACEPARENT_VERSION, to_hex(id.slice(0, trace_id_size)), to_hex(id.slice(trace_id_size, total_size)), sampled_flag);
47};
48const parse = (value) => {
49 if (value.length > 55)
50 return null;
51 const segs = value.split('-');
52 return traceparent(segs[0], segs[1], segs[2], segs[3]);
53};
54
55exports.make = make;
56exports.parse = parse;