1 | 'use strict';
|
2 |
|
3 | const csprng = require('@lukeed/csprng');
|
4 |
|
5 | let IDX = 256, HEX = [];
|
6 | for (; IDX--;)
|
7 | HEX[IDX] = (IDX + 256).toString(16).substring(1);
|
8 |
|
9 | const to_hex = (arr) => {
|
10 | let i = 0, output = '';
|
11 |
|
12 | for (; i < arr.length; i++)
|
13 | output += HEX[arr[i]];
|
14 | return output;
|
15 | };
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 | const trace_id_size = 16;
|
28 | const parent_id_size = 8;
|
29 | const W3C_TRACEPARENT_VERSION = '00';
|
30 | const sampled_flag = '00';
|
31 | const 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 | });
|
43 | const 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 | };
|
48 | const 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 |
|
55 | exports.make = make;
|
56 | exports.parse = parse;
|