@datadog/ci-visibility 0.0.0-stage → 5.28.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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2020 Datadog, Inc.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,150 @@
1
- # Temporary Holding Version
1
+ # CI Visibility JavaScript API
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Record custom spans, tags, and measures from JavaScript in GitHub Actions without
4
+ starting a CLI process for each call. Calls record in memory; users explicitly
5
+ call `await flush()` to upload.
6
+
7
+ This package requires Node.js 20 or later and has no external runtime dependencies.
8
+ **GitHub Actions is the only supported CI provider.**
9
+
10
+ ## Usage
11
+
12
+ Install `@datadog/ci-visibility` and import its `/github` entry point
13
+ in your JavaScript action or Node.js CI script. For a custom action, bundle it with
14
+ your code following GitHub's
15
+ [JavaScript action guide](https://docs.github.com/en/actions/tutorials/create-actions/create-a-javascript-action).
16
+ The application being built can use any language.
17
+
18
+ ```js
19
+ import {span, setTags, setMeasure, flush} from '@datadog/ci-visibility/github'
20
+ import {compile, runTests} from './build.js'
21
+
22
+ try {
23
+ setTags(
24
+ {'build.mode': 'release', 'workflow.version': process.env.WORKFLOW_VERSION},
25
+ {levels: ['pipeline', 'job', 'step'], steps: 'all'}
26
+ )
27
+
28
+ await span('Compile', async current => {
29
+ const result = await compile() // Application logic.
30
+ current.setTags({'compiler.target': result.target})
31
+ current.setMeasure('output.bytes', result.bytes)
32
+ })
33
+
34
+ const result = await span('Run tests', runTests)
35
+ setMeasure('test.count', result.count, {level: 'job'})
36
+ } finally {
37
+ await flush()
38
+ }
39
+ ```
40
+
41
+ Each action's main script, post script, or instrumented child process owns its own
42
+ queue and must call `flush()`. There is no automatic upload at process exit.
43
+
44
+ `flush()` returns `{sent, failed, skipped}` request counts and drains the queue.
45
+ Reporting errors do not replace application results or errors. Failed uploads
46
+ are discarded rather than retried by a later flush.
47
+
48
+ ## Spans, tags, and measures
49
+
50
+ - `span(name, callback)` records duration and errors, preserves the callback's
51
+ result, and rethrows its original error. The callback handle annotates that
52
+ custom span only.
53
+ - `startSpan(name, tags?)` starts a manual span. Call `end({exitCode, error, tags,
54
+ measures})` to finish it; the options are optional. `end()` returns the duration
55
+ in milliseconds and queues the span only once. End manual spans before flushing.
56
+ - `recordSpan({name, startTimeMs, endTimeMs, command?, exitCode?, error?, tags?,
57
+ measures?})` queues an already completed span. Timestamps are integer milliseconds
58
+ since the Unix epoch; `endTimeMs` must be at least `startTimeMs`. Zero duration is
59
+ allowed. The command defaults to the span name. Invalid spans are skipped with a
60
+ diagnostic through the configured logger.
61
+ - `setTags(tags, {levels})` annotates existing pipeline, job, or current main-step
62
+ events. The default level is `job`; tags do not inherit between levels.
63
+ - `setMeasure(name, value, {level})` adds a numerical annotation, defaulting to `job`.
64
+ - Add `steps: 'all'` with the `step` level to tag all declared main steps of the
65
+ current job.
66
+ - `getJobName()` returns the resolved GitHub job display name, falling back to
67
+ `GITHUB_JOB`, or `undefined` outside GitHub Actions. Action code can export the
68
+ value as `DD_GITHUB_JOB_NAME` to share it with later steps and child processes.
69
+
70
+ Supply workflow, action, tool, and cache tags through these methods. Span tags can
71
+ be supplied at creation, through the span's `setTags()`, or when ending the span.
72
+ Repeated tag keys use the last supplied value.
73
+ Invalid annotation entries are skipped individually, preserving valid tags and
74
+ measures supplied in the same call.
75
+
76
+ For application code that returns an exit code, or has separate start/end callbacks:
77
+
78
+ ```js
79
+ import {startSpan, flush} from '@datadog/ci-visibility/github'
80
+ import {compile} from './build.js'
81
+
82
+ const current = startSpan('Compile', {'compiler.version': process.env.COMPILER_VERSION})
83
+ try {
84
+ const result = await compile() // Application logic.
85
+ current.end({exitCode: result.exitCode, measures: {'output.bytes': result.bytes}})
86
+ } catch (error) {
87
+ current.end({error})
88
+ throw error
89
+ } finally {
90
+ await flush()
91
+ }
92
+ ```
93
+
94
+ For build tools that report completed tasks, supply their original timestamps:
95
+
96
+ ```js
97
+ import {recordSpan, flush} from '@datadog/ci-visibility/github'
98
+ import {readCompletedTasks} from './build.js'
99
+
100
+ try {
101
+ const tasks = await readCompletedTasks() // Application logic.
102
+ for (const task of tasks) {
103
+ recordSpan({
104
+ name: task.name,
105
+ command: task.command,
106
+ startTimeMs: task.startTimeMs,
107
+ endTimeMs: task.endTimeMs,
108
+ exitCode: task.exitCode,
109
+ tags: {'build.target': task.target},
110
+ measures: {'output.bytes': task.outputBytes},
111
+ })
112
+ }
113
+ } finally {
114
+ await flush({timeoutMs: 30_000})
115
+ }
116
+ ```
117
+
118
+ `recordSpan()` captures the current job's context when called, so record completed
119
+ tasks in the same job where they ran. It makes no HTTP requests until `flush()`.
120
+
121
+ Main and post scripts use the same API. Native current-step annotations in post
122
+ scripts target the action's main step. Use the span handle to annotate a custom
123
+ span.
124
+
125
+ ## Configuration
126
+
127
+ Set `DD_API_KEY` or `DATADOG_API_KEY` before calling `flush()`. Optionally set
128
+ `DD_SITE` or `DATADOG_SITE`; the default is `datadoghq.com`. GitHub run, job, step,
129
+ and Git metadata are discovered automatically.
130
+
131
+ Set `DD_CI_VISIBILITY_ENABLED=false` to disable reporting. Wrapped application code
132
+ still executes.
133
+
134
+ `DD_CI_VISIBILITY_WARNING_LEVEL` selects the console method for SDK diagnostics:
135
+ `warn` (default), `info`, or `debug`. Set it to `off` to silence default logging.
136
+ Values are case-insensitive; unrecognized values use `warn`. This only changes
137
+ logging; recording and uploads still run. An `onWarning` callback supplied to
138
+ `createRecorder()` or `flush()` takes precedence over this setting.
139
+
140
+ Set it through the workflow, job, or step environment, for example:
141
+
142
+ ```yaml
143
+ env:
144
+ DD_CI_VISIBILITY_WARNING_LEVEL: info
145
+ ```
146
+
147
+ Uploads use at most four concurrent requests, a 4-second request deadline, and a
148
+ 10-second overall budget. HTTP 429/5xx responses receive bounded retries;
149
+ transport failures stop the remaining queue. Override the deadlines with
150
+ `flush({requestTimeoutMs, timeoutMs})`. Proxy configuration is not supported.
@@ -0,0 +1,3 @@
1
+ import type { Environment, GithubContext } from './types';
2
+ export declare const diagnosticRoots: (env: Environment) => string[];
3
+ export declare const createGithubContext: (env: Environment) => (() => GithubContext);
package/dist/github.js ADDED
@@ -0,0 +1,236 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createGithubContext = exports.diagnosticRoots = void 0;
4
+ const node_fs_1 = require("node:fs");
5
+ const node_path_1 = require("node:path");
6
+ const compact = (values) => Object.fromEntries(Object.entries(values).filter((entry) => !!entry[1]));
7
+ /** Read only the requested JSON array, respecting brackets inside quoted strings. */
8
+ const readSteps = (content) => {
9
+ const jobMessage = content.indexOf('Job message:');
10
+ if (jobMessage < 0) {
11
+ return [];
12
+ }
13
+ const key = content.indexOf('"steps"', jobMessage);
14
+ const start = key < 0 ? -1 : content.indexOf('[', key);
15
+ if (start < 0) {
16
+ return [];
17
+ }
18
+ let depth = 0;
19
+ let quoted = false;
20
+ let escaped = false;
21
+ for (let i = start; i < content.length; i++) {
22
+ const character = content[i];
23
+ if (quoted) {
24
+ if (escaped) {
25
+ escaped = false;
26
+ }
27
+ else if (character === '\\') {
28
+ escaped = true;
29
+ }
30
+ else if (character === '"') {
31
+ quoted = false;
32
+ }
33
+ }
34
+ else if (character === '"') {
35
+ quoted = true;
36
+ }
37
+ else if (character === '[') {
38
+ depth++;
39
+ }
40
+ else if (character === ']' && --depth === 0) {
41
+ const steps = JSON.parse(content.slice(start, i + 1));
42
+ return Array.isArray(steps)
43
+ ? steps.map((step) => {
44
+ if (typeof step !== 'object' || !step || !('contextName' in step) || typeof step.contextName !== 'string') {
45
+ return {};
46
+ }
47
+ return { contextName: step.contextName };
48
+ })
49
+ : [];
50
+ }
51
+ }
52
+ return [];
53
+ };
54
+ const diagnosticRoots = (env) => {
55
+ const paths = env.RUNNER_OS === 'Windows' ? node_path_1.win32 : env.RUNNER_OS ? node_path_1.posix : { resolve: node_path_1.resolve, join: node_path_1.join };
56
+ const roots = env.RUNNER_TEMP ? [paths.resolve(env.RUNNER_TEMP, '..', '..')] : [];
57
+ const home = env.HOME || env.USERPROFILE;
58
+ if (home) {
59
+ roots.push(home, paths.join(home, 'actions-runner'));
60
+ }
61
+ roots.push(...(env.RUNNER_OS === 'Windows' ? ['C:\\actions-runner'] : ['/home/runner', '/opt/actions-runner']));
62
+ return [...new Set(roots)];
63
+ };
64
+ exports.diagnosticRoots = diagnosticRoots;
65
+ // Runner versions can namespace _diag under one or two intermediate directories.
66
+ const diagnosticDirectories = (root, depth = 2) => {
67
+ const directories = [(0, node_path_1.join)(root, '_diag')];
68
+ if (depth > 0) {
69
+ try {
70
+ for (const entry of (0, node_fs_1.readdirSync)(root, { withFileTypes: true })) {
71
+ if (entry.isDirectory() &&
72
+ !entry.name.startsWith('.') &&
73
+ !['_work', '_diag', 'node_modules'].includes(entry.name)) {
74
+ directories.push(...diagnosticDirectories((0, node_path_1.join)(root, entry.name), depth - 1));
75
+ }
76
+ }
77
+ }
78
+ catch (_a) {
79
+ // Missing or unreadable layouts are normal on other runner platforms.
80
+ }
81
+ }
82
+ return directories;
83
+ };
84
+ // Keep worker-log resolution aligned with base/src/helpers/ci.ts.
85
+ // Shared fixtures in base/src/helpers/__tests__/ci-visibility-parity.test.ts compare both implementations.
86
+ const workerMetadata = (env) => {
87
+ var _a, _b;
88
+ const seen = new Set();
89
+ for (const root of (0, exports.diagnosticRoots)(env)) {
90
+ const logs = [];
91
+ for (const directory of new Set(diagnosticDirectories(root))) {
92
+ try {
93
+ logs.push(...(0, node_fs_1.readdirSync)(directory, { withFileTypes: true })
94
+ .filter((entry) => entry.isFile() && /^Worker_.*\.log$/.test(entry.name))
95
+ .map((entry) => (0, node_path_1.join)(directory, entry.name)));
96
+ }
97
+ catch (_c) {
98
+ // Try the next candidate without exposing runner paths or log contents.
99
+ }
100
+ }
101
+ logs.sort((a, b) => b.split(/[\\/]/).pop().localeCompare(a.split(/[\\/]/).pop()));
102
+ for (const file of logs) {
103
+ if (seen.has(file)) {
104
+ continue;
105
+ }
106
+ seen.add(file);
107
+ try {
108
+ const content = (0, node_fs_1.readFileSync)(file, 'utf8');
109
+ if (env.ACTIONS_ORCHESTRATION_ID &&
110
+ (!content.includes('"system.orchestrationId"') ||
111
+ !content.includes(JSON.stringify(env.ACTIONS_ORCHESTRATION_ID)))) {
112
+ continue;
113
+ }
114
+ const encodedName = (_a = content.match(/"jobDisplayName":\s*"((?:[^"\\]|\\.)*)"/)) === null || _a === void 0 ? void 0 : _a[1];
115
+ const steps = readSteps(content);
116
+ if (!encodedName) {
117
+ continue;
118
+ }
119
+ return {
120
+ jobName: JSON.parse(`"${encodedName}"`),
121
+ jobId: (_b = content.match(/"job":\s*{[\s\S]*?"v"\s*:\s*(\d+)(?:\.0)?/)) === null || _b === void 0 ? void 0 : _b[1],
122
+ steps,
123
+ };
124
+ }
125
+ catch (_d) {
126
+ // A partial worker log must not prevent recording other annotations.
127
+ }
128
+ }
129
+ }
130
+ return { steps: [] };
131
+ };
132
+ const normalizeRef = (ref = '') => ref.replace(/^(refs\/(heads|tags)\/|origin\/)/, '');
133
+ const sanitizeRepositoryUrl = (remote) => {
134
+ if (!remote || /^git@[^:@/?#\s]+:[^?#\s]+$/.test(remote)) {
135
+ return remote;
136
+ }
137
+ try {
138
+ const url = new URL(remote);
139
+ if (!url.hostname) {
140
+ return undefined;
141
+ }
142
+ url.username = '';
143
+ url.password = '';
144
+ url.search = '';
145
+ url.hash = '';
146
+ return url.toString();
147
+ }
148
+ catch (_a) {
149
+ // Omit malformed URLs rather than risking credentials in telemetry.
150
+ return undefined;
151
+ }
152
+ };
153
+ const createGithubContext = (env) => {
154
+ let metadata;
155
+ let event;
156
+ let eventRead = false;
157
+ return () => {
158
+ var _a, _b, _c, _d, _e, _f;
159
+ if (!metadata) {
160
+ metadata = workerMetadata(env);
161
+ }
162
+ if (!eventRead) {
163
+ eventRead = true;
164
+ try {
165
+ event = env.GITHUB_EVENT_PATH
166
+ ? JSON.parse((0, node_fs_1.readFileSync)(env.GITHUB_EVENT_PATH, 'utf8'))
167
+ : undefined;
168
+ }
169
+ catch (_g) {
170
+ // Metadata from the environment remains usable without an event file.
171
+ }
172
+ }
173
+ const server = (sanitizeRepositoryUrl(env.GITHUB_SERVER_URL) || 'https://github.com').replace(/\/$/, '');
174
+ const runId = env.GITHUB_RUN_ID;
175
+ const attempt = env.GITHUB_RUN_ATTEMPT || '1';
176
+ const repository = env.GITHUB_REPOSITORY;
177
+ const jobName = env.DD_GITHUB_JOB_NAME || metadata.jobName || env.GITHUB_JOB;
178
+ const resolvedJobId = env.JOB_CHECK_RUN_ID || metadata.jobId;
179
+ const jobId = resolvedJobId && /^\d+$/.test(resolvedJobId) ? resolvedJobId : undefined;
180
+ const offset = env.ACTIONS_RUNNER_HOOK_JOB_STARTED ? 1 : 0;
181
+ const declaredIndex = metadata.steps.findIndex((step) => step.contextName === env.GITHUB_ACTION);
182
+ const override = env.DD_GITHUB_STEP_INDEX;
183
+ const stepIndex = override && /^\d+$/.test(override) ? override : declaredIndex >= 0 ? String(declaredIndex + offset) : undefined;
184
+ const ciEnv = compact({
185
+ GITHUB_SERVER_URL: server,
186
+ GITHUB_REPOSITORY: repository,
187
+ GITHUB_RUN_ID: runId,
188
+ GITHUB_RUN_ATTEMPT: attempt,
189
+ GITHUB_JOB: env.GITHUB_JOB,
190
+ DD_GITHUB_JOB_NAME: jobName,
191
+ DD_GITHUB_STEP_INDEX: stepIndex,
192
+ });
193
+ const ref = env.GITHUB_HEAD_REF || env.GITHUB_REF || '';
194
+ return {
195
+ ciEnv,
196
+ stepIndices: metadata.steps.length
197
+ ? metadata.steps.map((_, i) => i + offset)
198
+ : stepIndex === undefined
199
+ ? []
200
+ : [Number(stepIndex)],
201
+ tags: compact({
202
+ 'ci.provider.name': 'github',
203
+ // Preserve the existing custom-span intake contract; attempts are also in _dd.ci.env_vars.
204
+ 'ci.pipeline.id': runId,
205
+ 'ci.pipeline.name': env.GITHUB_WORKFLOW,
206
+ 'ci.pipeline.number': env.GITHUB_RUN_NUMBER,
207
+ 'ci.pipeline.url': repository && runId ? `${server}/${repository}/actions/runs/${runId}/attempts/${attempt}` : undefined,
208
+ 'ci.job.name': jobName,
209
+ 'ci.job.id': jobId || env.GITHUB_JOB,
210
+ 'ci.job.url': repository && runId && jobId
211
+ ? `${server}/${repository}/actions/runs/${runId}/job/${jobId}`
212
+ : repository && env.GITHUB_SHA
213
+ ? `${server}/${repository}/commit/${env.GITHUB_SHA}/checks`
214
+ : undefined,
215
+ 'ci.workspace_path': env.GITHUB_WORKSPACE,
216
+ 'git.repository_url': sanitizeRepositoryUrl(env.DD_GIT_REPOSITORY_URL || (repository ? `${server}/${repository}.git` : undefined)),
217
+ 'git.commit.sha': env.DD_GIT_COMMIT_SHA || env.GITHUB_SHA,
218
+ 'git.branch': normalizeRef(env.DD_GIT_BRANCH || (!ref.startsWith('refs/tags/') ? ref : undefined)),
219
+ 'git.tag': normalizeRef(env.DD_GIT_TAG || (ref.startsWith('refs/tags/') ? ref : undefined)),
220
+ 'git.pull_request.base_branch': env.GITHUB_BASE_REF,
221
+ 'git.commit.head.sha': (_b = (_a = event === null || event === void 0 ? void 0 : event.pull_request) === null || _a === void 0 ? void 0 : _a.head) === null || _b === void 0 ? void 0 : _b.sha,
222
+ 'git.pull_request.base_branch_head_sha': (_d = (_c = event === null || event === void 0 ? void 0 : event.pull_request) === null || _c === void 0 ? void 0 : _c.base) === null || _d === void 0 ? void 0 : _d.sha,
223
+ 'pr.number': (_f = (_e = event === null || event === void 0 ? void 0 : event.pull_request) === null || _e === void 0 ? void 0 : _e.number) === null || _f === void 0 ? void 0 : _f.toString(),
224
+ '_dd.ci.env_vars': JSON.stringify(compact({
225
+ GITHUB_SERVER_URL: server,
226
+ GITHUB_REPOSITORY: repository,
227
+ GITHUB_RUN_ID: runId,
228
+ GITHUB_RUN_ATTEMPT: attempt,
229
+ DD_GITHUB_JOB_NAME: jobName,
230
+ })),
231
+ }),
232
+ };
233
+ };
234
+ };
235
+ exports.createGithubContext = createGithubContext;
236
+ //# sourceMappingURL=github.js.map
@@ -0,0 +1,20 @@
1
+ import type { Environment, FlushResult, Level, RecordSpanOptions, Span, TagOptions, Tags, UploadOptions } from './types';
2
+ export type { FlushResult, Level, Span, SpanEndOptions, TagOptions, Tags, UploadOptions } from './types';
3
+ export type { RecordSpanOptions } from './types';
4
+ export declare const createRecorder: ({ env, onWarning, }?: {
5
+ env?: Environment | undefined;
6
+ onWarning?: ((message: string) => void) | undefined;
7
+ }) => {
8
+ span: <T>(name: string, callback: (currentSpan: Span) => T | Promise<T>) => Promise<T>;
9
+ startSpan: (name: string, tags?: Tags) => Span;
10
+ recordSpan: (options: RecordSpanOptions) => void;
11
+ setTags: (tags: Tags, { levels, steps }?: TagOptions) => void;
12
+ setMeasure: (name: string, value: number, { level }?: {
13
+ level?: Level | undefined;
14
+ }) => void;
15
+ getJobName: () => string | undefined;
16
+ flush: (options?: UploadOptions) => Promise<FlushResult>;
17
+ };
18
+ export declare const span: <T>(name: string, callback: (currentSpan: Span) => T | Promise<T>) => Promise<T>, startSpan: (name: string, tags?: Tags) => Span, recordSpan: (options: RecordSpanOptions) => void, setTags: (tags: Tags, { levels, steps }?: TagOptions) => void, setMeasure: (name: string, value: number, { level }?: {
19
+ level?: Level | undefined;
20
+ }) => void, getJobName: () => string | undefined, flush: (options?: UploadOptions) => Promise<FlushResult>;
package/dist/index.js ADDED
@@ -0,0 +1,221 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var _a;
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.flush = exports.getJobName = exports.setMeasure = exports.setTags = exports.recordSpan = exports.startSpan = exports.span = exports.createRecorder = void 0;
14
+ const node_crypto_1 = require("node:crypto");
15
+ const github_1 = require("./github");
16
+ const payloads_1 = require("./payloads");
17
+ const upload_1 = require("./upload");
18
+ const validation_1 = require("./validation");
19
+ const createRecorder = ({ env = process.env, onWarning, } = {}) => {
20
+ const captureContext = (0, github_1.createGithubContext)(env);
21
+ const pending = [];
22
+ let warned = false;
23
+ let flushing;
24
+ const warnRecording = () => {
25
+ if (!warned) {
26
+ warned = true;
27
+ (0, validation_1.warn)(onWarning, 'Could not record annotation', env);
28
+ }
29
+ };
30
+ const bestEffort = (operation) => {
31
+ try {
32
+ operation();
33
+ }
34
+ catch (_a) {
35
+ warnRecording();
36
+ }
37
+ };
38
+ const enabled = () => { var _a; return env.GITHUB_ACTIONS === 'true' && ((_a = env.DD_CI_VISIBILITY_ENABLED) === null || _a === void 0 ? void 0 : _a.toLowerCase()) !== 'false'; };
39
+ const record = (event) => {
40
+ if (!event.context.ciEnv.GITHUB_REPOSITORY ||
41
+ !event.context.ciEnv.GITHUB_RUN_ID ||
42
+ !event.context.ciEnv.GITHUB_JOB) {
43
+ throw new Error('Missing GitHub context');
44
+ }
45
+ pending.push(event);
46
+ };
47
+ const recordTags = (tags, { levels = ['job'], steps = 'current' } = {}) => bestEffort(() => {
48
+ if (!enabled()) {
49
+ return;
50
+ }
51
+ if (!levels.length ||
52
+ levels.some((level) => !['pipeline', 'job', 'step'].includes(level)) ||
53
+ !['current', 'all'].includes(steps)) {
54
+ throw new Error('Unsupported annotation target');
55
+ }
56
+ const values = (0, validation_1.cleanTags)(tags, true, warnRecording);
57
+ if (Object.keys(values).length) {
58
+ record({ context: captureContext(), type: 'tags', tags: values, levels: [...new Set(levels)], steps });
59
+ }
60
+ });
61
+ const recordMeasure = (name, value, { level = 'job' } = {}) => bestEffort(() => {
62
+ if (!enabled()) {
63
+ return;
64
+ }
65
+ if (!['pipeline', 'job', 'step'].includes(level)) {
66
+ throw new Error('Unsupported annotation target');
67
+ }
68
+ const measures = (0, validation_1.cleanMeasures)({ [name]: value }, warnRecording);
69
+ if (Object.keys(measures).length) {
70
+ record({ context: captureContext(), type: 'measure', measures, level });
71
+ }
72
+ });
73
+ const recordStartSpan = (name, initialTags = {}, timing) => {
74
+ var _a;
75
+ const start = (_a = timing === null || timing === void 0 ? void 0 : timing.startTimeMs) !== null && _a !== void 0 ? _a : Date.now();
76
+ let duration;
77
+ let context;
78
+ let data;
79
+ bestEffort(() => {
80
+ var _a;
81
+ if (enabled()) {
82
+ context = captureContext();
83
+ data = {
84
+ span_id: (0, node_crypto_1.randomBytes)(8).toString('hex'),
85
+ name,
86
+ command: (_a = timing === null || timing === void 0 ? void 0 : timing.command) !== null && _a !== void 0 ? _a : name,
87
+ start_time: new Date(start).toISOString(),
88
+ end_time: '',
89
+ exit_code: 0,
90
+ error_message: '',
91
+ tags: Object.assign({}, context.tags),
92
+ measures: {},
93
+ };
94
+ }
95
+ });
96
+ const currentSpan = {
97
+ setTags: (tags) => bestEffort(() => {
98
+ if (data && duration === undefined) {
99
+ Object.assign(data.tags, (0, validation_1.cleanTags)(tags, false, warnRecording));
100
+ }
101
+ }),
102
+ setMeasure: (key, value) => bestEffort(() => {
103
+ if (data && duration === undefined) {
104
+ Object.assign(data.measures, (0, validation_1.cleanMeasures)({ [key]: value }, warnRecording));
105
+ }
106
+ }),
107
+ end: (options = {}) => {
108
+ var _a;
109
+ if (duration !== undefined) {
110
+ return duration;
111
+ }
112
+ const end = (_a = timing === null || timing === void 0 ? void 0 : timing.endTimeMs) !== null && _a !== void 0 ? _a : Date.now();
113
+ bestEffort(() => {
114
+ if (data) {
115
+ Object.assign(data.tags, (0, validation_1.cleanTags)(options.tags || {}, false, warnRecording));
116
+ }
117
+ });
118
+ bestEffort(() => {
119
+ if (data) {
120
+ Object.assign(data.measures, (0, validation_1.cleanMeasures)(options.measures || {}, warnRecording));
121
+ }
122
+ });
123
+ bestEffort(() => {
124
+ if (data) {
125
+ const exitCode = options.exitCode === undefined ? (options.error === undefined ? 0 : 1) : options.exitCode;
126
+ if (!Number.isSafeInteger(exitCode) || exitCode < 0) {
127
+ data = undefined;
128
+ throw new Error('Exit codes must be nonnegative integers');
129
+ }
130
+ data.exit_code = exitCode;
131
+ data.error_message =
132
+ exitCode === 0
133
+ ? ''
134
+ : options.error === undefined
135
+ ? 'Span failed'
136
+ : options.error instanceof Error
137
+ ? options.error.message
138
+ : String(options.error);
139
+ }
140
+ });
141
+ duration = end - start;
142
+ bestEffort(() => {
143
+ if (data && context) {
144
+ data.end_time = new Date(end).toISOString();
145
+ record({ context, type: 'span', span: data });
146
+ }
147
+ });
148
+ return duration;
149
+ },
150
+ };
151
+ currentSpan.setTags(initialTags);
152
+ return currentSpan;
153
+ };
154
+ const recordCompletedSpan = (options) => bestEffort(() => {
155
+ if (!enabled()) {
156
+ return;
157
+ }
158
+ const { name, command, startTimeMs, endTimeMs } = options;
159
+ if (typeof name !== 'string' ||
160
+ !name.trim() ||
161
+ (command !== undefined && (typeof command !== 'string' || !command.trim()))) {
162
+ throw new Error('Span name and command must be nonempty strings');
163
+ }
164
+ if (!Number.isSafeInteger(startTimeMs) || !Number.isSafeInteger(endTimeMs) || endTimeMs < startTimeMs) {
165
+ throw new Error('Span timestamps must be integer milliseconds with endTimeMs >= startTimeMs');
166
+ }
167
+ recordStartSpan(name, {}, options).end(options);
168
+ });
169
+ const wrapSpan = (name, callback) => __awaiter(void 0, void 0, void 0, function* () {
170
+ const currentSpan = recordStartSpan(name);
171
+ try {
172
+ const result = yield callback(currentSpan);
173
+ currentSpan.end();
174
+ return result;
175
+ }
176
+ catch (error) {
177
+ currentSpan.end({ error, exitCode: 1 });
178
+ throw error;
179
+ }
180
+ });
181
+ const flushRecords = (options = {}) => __awaiter(void 0, void 0, void 0, function* () {
182
+ if (!enabled()) {
183
+ const skipped = (0, payloads_1.planRequests)(pending.splice(0)).requests.length;
184
+ return { sent: 0, failed: 0, skipped };
185
+ }
186
+ if (flushing) {
187
+ yield flushing;
188
+ return flushRecords(options);
189
+ }
190
+ const records = pending.splice(0);
191
+ const plan = (0, payloads_1.planRequests)(records);
192
+ flushing = (0, upload_1.upload)(plan.requests, Object.assign(Object.assign({}, options), { apiKey: options.apiKey || env.DATADOG_API_KEY || env.DD_API_KEY, site: options.site || env.DATADOG_SITE || env.DD_SITE, onWarning: options.onWarning || onWarning }), env).then(({ sent, failed, skipped }) => ({ sent, failed, skipped: skipped + plan.skipped }));
193
+ try {
194
+ return yield flushing;
195
+ }
196
+ finally {
197
+ flushing = undefined;
198
+ }
199
+ });
200
+ const resolveJobName = () => {
201
+ let name;
202
+ bestEffort(() => {
203
+ if (env.GITHUB_ACTIONS === 'true') {
204
+ name = captureContext().ciEnv.DD_GITHUB_JOB_NAME;
205
+ }
206
+ });
207
+ return name;
208
+ };
209
+ return {
210
+ span: wrapSpan,
211
+ startSpan: (name, tags) => recordStartSpan(name, tags),
212
+ recordSpan: recordCompletedSpan,
213
+ setTags: recordTags,
214
+ setMeasure: recordMeasure,
215
+ getJobName: resolveJobName,
216
+ flush: flushRecords,
217
+ };
218
+ };
219
+ exports.createRecorder = createRecorder;
220
+ _a = (0, exports.createRecorder)(), exports.span = _a.span, exports.startSpan = _a.startSpan, exports.recordSpan = _a.recordSpan, exports.setTags = _a.setTags, exports.setMeasure = _a.setMeasure, exports.getJobName = _a.getJobName, exports.flush = _a.flush;
221
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,11 @@
1
+ import type { DatadogRoute } from './request/datadog-route';
2
+ import type { RecordedEvent } from './types';
3
+ export interface UploadRequest {
4
+ method: 'POST';
5
+ url: DatadogRoute;
6
+ data: object;
7
+ }
8
+ export declare const planRequests: (records: RecordedEvent[]) => {
9
+ requests: UploadRequest[];
10
+ skipped: number;
11
+ };
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.planRequests = void 0;
4
+ const datadog_route_1 = require("./request/datadog-route");
5
+ const validation_1 = require("./validation");
6
+ const levels = { pipeline: 0, job: 1, step: 3 };
7
+ const planRequests = (records) => {
8
+ const requests = [];
9
+ const patches = new Map();
10
+ let skipped = 0;
11
+ for (const record of records) {
12
+ if (record.type === 'span') {
13
+ requests.push({
14
+ method: 'POST',
15
+ url: (0, datadog_route_1.datadogRoute)('/api/intake/ci/custom_spans'),
16
+ data: { data: { type: 'ci_app_custom_span', attributes: Object.assign({ ci_provider: 'github' }, record.span) } },
17
+ });
18
+ continue;
19
+ }
20
+ for (const level of record.type === 'tags' ? record.levels : [record.level]) {
21
+ const ciEnv = record.context.ciEnv;
22
+ const indices = level !== 'step'
23
+ ? [undefined]
24
+ : record.type === 'tags' && record.steps === 'all'
25
+ ? record.context.stepIndices
26
+ : ciEnv.DD_GITHUB_STEP_INDEX === undefined
27
+ ? []
28
+ : [Number(ciEnv.DD_GITHUB_STEP_INDEX)];
29
+ if (!indices.length) {
30
+ skipped++;
31
+ }
32
+ for (const index of indices) {
33
+ const target = {
34
+ GITHUB_SERVER_URL: ciEnv.GITHUB_SERVER_URL,
35
+ GITHUB_REPOSITORY: ciEnv.GITHUB_REPOSITORY,
36
+ GITHUB_RUN_ID: ciEnv.GITHUB_RUN_ID,
37
+ GITHUB_RUN_ATTEMPT: ciEnv.GITHUB_RUN_ATTEMPT,
38
+ GITHUB_JOB: ciEnv.GITHUB_JOB,
39
+ };
40
+ if (level !== 'pipeline') {
41
+ target.DD_GITHUB_JOB_NAME = ciEnv.DD_GITHUB_JOB_NAME;
42
+ }
43
+ if (index !== undefined) {
44
+ target.DD_GITHUB_STEP_INDEX = String(index);
45
+ }
46
+ const key = JSON.stringify([record.type, level, target]);
47
+ const patch = patches.get(key) || {
48
+ type: record.type,
49
+ level,
50
+ ciEnv: target,
51
+ values: {},
52
+ };
53
+ Object.assign(patch.values, record.type === 'tags' ? record.tags : record.measures);
54
+ patches.set(key, patch);
55
+ }
56
+ }
57
+ }
58
+ for (const patch of patches.values()) {
59
+ const tags = patch.type === 'tags';
60
+ requests.push({
61
+ method: 'POST',
62
+ url: tags ? (0, datadog_route_1.datadogRoute)('/api/v2/ci/pipeline/tags') : (0, datadog_route_1.datadogRoute)('/api/v2/ci/pipeline/metrics'),
63
+ data: {
64
+ data: {
65
+ type: tags ? 'ci_custom_tag' : 'ci_custom_metric',
66
+ attributes: Object.assign({ ci_env: patch.ciEnv, ci_level: levels[patch.level], provider: 'github' }, (tags
67
+ ? { tags: (0, validation_1.cleanTags)(patch.values) }
68
+ : { metrics: (0, validation_1.cleanMeasures)(patch.values) })),
69
+ },
70
+ },
71
+ });
72
+ }
73
+ return { requests, skipped };
74
+ };
75
+ exports.planRequests = planRequests;
76
+ //# sourceMappingURL=payloads.js.map
@@ -0,0 +1,4 @@
1
+ /** The SDK only sends to these CI Visibility intakes. */
2
+ export declare const DATADOG_ROUTE_PATHS: readonly ["/api/intake/ci/custom_spans", "/api/v2/ci/pipeline/metrics", "/api/v2/ci/pipeline/tags"];
3
+ export type DatadogRoute = (typeof DATADOG_ROUTE_PATHS)[number];
4
+ export declare const datadogRoute: (route: DatadogRoute) => DatadogRoute;
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.datadogRoute = exports.DATADOG_ROUTE_PATHS = void 0;
4
+ /** The SDK only sends to these CI Visibility intakes. */
5
+ exports.DATADOG_ROUTE_PATHS = [
6
+ '/api/intake/ci/custom_spans',
7
+ '/api/v2/ci/pipeline/metrics',
8
+ '/api/v2/ci/pipeline/tags',
9
+ ];
10
+ const datadogRoute = (route) => route;
11
+ exports.datadogRoute = datadogRoute;
12
+ //# sourceMappingURL=datadog-route.js.map
@@ -0,0 +1,16 @@
1
+ /// <reference types="node" />
2
+ import type { DatadogRoute } from './request/datadog-route';
3
+ export declare class TransportError extends Error {
4
+ }
5
+ /**
6
+ * The SDK keeps its own CI intake transport to avoid the CLI helper's runtime dependencies.
7
+ * Keep this package dependency-free and require audited Datadog routes at call sites.
8
+ */
9
+ export declare const httpRequest: (config: {
10
+ url: DatadogRoute;
11
+ site: string;
12
+ apiKey: string;
13
+ signal: AbortSignal;
14
+ timeoutMs: number;
15
+ data: unknown;
16
+ }) => Promise<number>;
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.httpRequest = exports.TransportError = void 0;
13
+ const node_https_1 = require("node:https");
14
+ class TransportError extends Error {
15
+ }
16
+ exports.TransportError = TransportError;
17
+ /**
18
+ * The SDK keeps its own CI intake transport to avoid the CLI helper's runtime dependencies.
19
+ * Keep this package dependency-free and require audited Datadog routes at call sites.
20
+ */
21
+ const httpRequest = (config) => __awaiter(void 0, void 0, void 0, function* () {
22
+ const host = config.site === 'datad0g.com' && config.url !== '/api/intake/ci/custom_spans' ? 'app' : 'api';
23
+ const body = JSON.stringify(config.data);
24
+ if (Buffer.byteLength(body) > 4 * 1024 * 1024) {
25
+ throw new Error('Request exceeds 4 MiB');
26
+ }
27
+ return new Promise((resolve, reject) => {
28
+ const outgoing = (0, node_https_1.request)(`https://${host}.${config.site}${config.url}`, {
29
+ method: 'POST',
30
+ headers: {
31
+ 'Content-Type': 'application/json',
32
+ 'Content-Length': Buffer.byteLength(body),
33
+ 'DD-API-KEY': config.apiKey,
34
+ 'User-Agent': '@datadog/ci-visibility',
35
+ },
36
+ signal: config.signal,
37
+ }, (response) => {
38
+ response.resume();
39
+ response.once('end', () => resolve(response.statusCode || 0));
40
+ response.once('error', () => reject(new TransportError('Response interrupted')));
41
+ });
42
+ // This includes DNS and connection establishment, unlike a socket inactivity timeout.
43
+ const deadline = setTimeout(() => outgoing.destroy(new TransportError('Request timed out')), config.timeoutMs);
44
+ outgoing.once('error', () => reject(new TransportError('Request failed or timed out')));
45
+ outgoing.once('close', () => clearTimeout(deadline));
46
+ outgoing.end(body);
47
+ });
48
+ });
49
+ exports.httpRequest = httpRequest;
50
+ //# sourceMappingURL=request.js.map
@@ -0,0 +1,77 @@
1
+ export type Environment = Record<string, string | undefined>;
2
+ export type Tags = Record<string, string | undefined>;
3
+ export type Measures = Record<string, number | undefined>;
4
+ export type Level = 'pipeline' | 'job' | 'step';
5
+ export interface SpanEndOptions {
6
+ /** Defaults to 0, or 1 when an error is supplied. */
7
+ exitCode?: number;
8
+ error?: unknown;
9
+ tags?: Tags;
10
+ measures?: Measures;
11
+ }
12
+ export interface RecordSpanOptions extends SpanEndOptions {
13
+ name: string;
14
+ /** Defaults to the span name. */
15
+ command?: string;
16
+ /** Integer milliseconds since the Unix epoch. */
17
+ startTimeMs: number;
18
+ /** Integer milliseconds since the Unix epoch; may equal startTimeMs. */
19
+ endTimeMs: number;
20
+ }
21
+ export interface Span {
22
+ setTags(tags: Tags): void;
23
+ setMeasure(name: string, value: number): void;
24
+ /** Queue the completed span once and return its duration in milliseconds. */
25
+ end(options?: SpanEndOptions): number;
26
+ }
27
+ export interface TagOptions {
28
+ levels?: Level[];
29
+ /** Apply step annotations to all declared main steps of the current job. */
30
+ steps?: 'current' | 'all';
31
+ }
32
+ export interface UploadOptions {
33
+ apiKey?: string;
34
+ site?: string;
35
+ /** Overall upload budget, including retries. Defaults to 10 seconds. */
36
+ timeoutMs?: number;
37
+ /** Deadline for an individual request. Defaults to 4 seconds. */
38
+ requestTimeoutMs?: number;
39
+ onWarning?: (message: string) => void;
40
+ }
41
+ /** Counts HTTP requests, including requests abandoned after a transport failure. */
42
+ export interface FlushResult {
43
+ sent: number;
44
+ failed: number;
45
+ skipped: number;
46
+ }
47
+ export interface GithubContext {
48
+ ciEnv: Record<string, string>;
49
+ tags: Record<string, string>;
50
+ stepIndices: number[];
51
+ }
52
+ export interface SpanData {
53
+ span_id: string;
54
+ name: string;
55
+ command: string;
56
+ start_time: string;
57
+ end_time: string;
58
+ exit_code: number;
59
+ error_message: string;
60
+ tags: Record<string, string>;
61
+ measures: Record<string, number>;
62
+ }
63
+ export type RecordedEvent = {
64
+ context: GithubContext;
65
+ } & ({
66
+ type: 'span';
67
+ span: SpanData;
68
+ } | {
69
+ type: 'tags';
70
+ tags: Record<string, string>;
71
+ levels: Level[];
72
+ steps: 'current' | 'all';
73
+ } | {
74
+ type: 'measure';
75
+ measures: Record<string, number>;
76
+ level: Level;
77
+ });
package/dist/types.js ADDED
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1,3 @@
1
+ import type { UploadRequest } from './payloads';
2
+ import type { Environment, FlushResult, UploadOptions } from './types';
3
+ export declare const upload: (requests: UploadRequest[], options?: UploadOptions, env?: Environment) => Promise<FlushResult>;
package/dist/upload.js ADDED
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.upload = void 0;
13
+ const promises_1 = require("node:timers/promises");
14
+ const request_1 = require("./request");
15
+ const validation_1 = require("./validation");
16
+ const upload = (requests, options = {}, env = process.env) => __awaiter(void 0, void 0, void 0, function* () {
17
+ var _a, _b;
18
+ const result = { sent: 0, failed: 0, skipped: 0 };
19
+ if (!requests.length) {
20
+ return result;
21
+ }
22
+ const apiKey = options.apiKey || env.DATADOG_API_KEY || env.DD_API_KEY;
23
+ const site = options.site || env.DATADOG_SITE || env.DD_SITE || 'datadoghq.com';
24
+ const timeoutMs = (_a = options.timeoutMs) !== null && _a !== void 0 ? _a : 10000;
25
+ const requestTimeoutMs = (_b = options.requestTimeoutMs) !== null && _b !== void 0 ? _b : 4000;
26
+ if (!apiKey ||
27
+ !/^(?:[a-z0-9-]+\.)*(?:datadoghq\.(?:com|eu)|ddog-gov\.com|datad0g\.com)$/.test(site) ||
28
+ !Number.isSafeInteger(timeoutMs) ||
29
+ timeoutMs < 1 ||
30
+ !Number.isSafeInteger(requestTimeoutMs) ||
31
+ requestTimeoutMs < 1) {
32
+ (0, validation_1.warn)(options.onWarning, 'Upload skipped: missing API key, unsupported site, or invalid timeout', env);
33
+ result.skipped = requests.length;
34
+ return result;
35
+ }
36
+ const controller = new AbortController();
37
+ const deadline = setTimeout(() => controller.abort(), timeoutMs);
38
+ let next = 0;
39
+ try {
40
+ yield Promise.all(Array.from({ length: Math.min(4, requests.length) }, () => __awaiter(void 0, void 0, void 0, function* () {
41
+ while (!controller.signal.aborted && next < requests.length) {
42
+ const item = requests[next++];
43
+ let success = false;
44
+ try {
45
+ for (let attempt = 0;; attempt++) {
46
+ const status = yield (0, request_1.httpRequest)({
47
+ url: item.url,
48
+ site,
49
+ apiKey,
50
+ signal: controller.signal,
51
+ timeoutMs: requestTimeoutMs,
52
+ data: item.data,
53
+ });
54
+ if (status >= 200 && status < 300) {
55
+ success = true;
56
+ break;
57
+ }
58
+ if ((status !== 429 && status < 500) || attempt === 2) {
59
+ break;
60
+ }
61
+ yield (0, promises_1.setTimeout)(250 * Math.pow(2, attempt), undefined, { signal: controller.signal });
62
+ }
63
+ }
64
+ catch (error) {
65
+ if (error instanceof request_1.TransportError) {
66
+ controller.abort();
67
+ }
68
+ }
69
+ if (success) {
70
+ result.sent++;
71
+ }
72
+ else {
73
+ result.failed++;
74
+ }
75
+ }
76
+ })));
77
+ }
78
+ finally {
79
+ clearTimeout(deadline);
80
+ }
81
+ result.skipped = requests.length - result.sent - result.failed;
82
+ if (result.failed || result.skipped) {
83
+ (0, validation_1.warn)(options.onWarning, `Upload incomplete: ${result.sent} sent, ${result.failed} failed, ${result.skipped} skipped`, env);
84
+ }
85
+ return result;
86
+ });
87
+ exports.upload = upload;
88
+ //# sourceMappingURL=upload.js.map
@@ -0,0 +1,4 @@
1
+ import type { Environment, Measures, Tags } from './types';
2
+ export declare const cleanTags: (tags: Tags, limited?: boolean, onInvalid?: () => void) => Record<string, string>;
3
+ export declare const cleanMeasures: (measures: Measures, onInvalid?: () => void) => Record<string, number>;
4
+ export declare const warn: (callback: ((message: string) => void) | undefined, message: string, env?: Environment) => void;
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.warn = exports.cleanMeasures = exports.cleanTags = void 0;
4
+ const cleanTags = (tags, limited = true, onInvalid) => {
5
+ const result = {};
6
+ for (const [key, value] of Object.entries(tags)) {
7
+ if (!key || value === undefined) {
8
+ continue;
9
+ }
10
+ if (typeof value !== 'string') {
11
+ onInvalid === null || onInvalid === void 0 ? void 0 : onInvalid();
12
+ continue;
13
+ }
14
+ if (limited && (Object.keys(result).length >= 100 || key.length >= 300)) {
15
+ continue;
16
+ }
17
+ const text = value.trim();
18
+ if (text) {
19
+ result[key] = limited ? text.slice(0, 300 - key.length) : text;
20
+ }
21
+ }
22
+ return result;
23
+ };
24
+ exports.cleanTags = cleanTags;
25
+ const cleanMeasures = (measures, onInvalid) => {
26
+ const result = {};
27
+ for (const [key, value] of Object.entries(measures)) {
28
+ if (value === undefined) {
29
+ continue;
30
+ }
31
+ if (!key || typeof value !== 'number' || !Number.isFinite(value)) {
32
+ onInvalid === null || onInvalid === void 0 ? void 0 : onInvalid();
33
+ continue;
34
+ }
35
+ if (Object.keys(result).length < 100) {
36
+ result[key] = value;
37
+ }
38
+ }
39
+ return result;
40
+ };
41
+ exports.cleanMeasures = cleanMeasures;
42
+ const warn = (callback, message, env = process.env) => {
43
+ var _a;
44
+ try {
45
+ const level = (_a = env.DD_CI_VISIBILITY_WARNING_LEVEL) === null || _a === void 0 ? void 0 : _a.toLowerCase();
46
+ const log = callback !== null && callback !== void 0 ? callback : (level === 'off' ? undefined : level === 'info' || level === 'debug' ? console[level] : console.warn);
47
+ log === null || log === void 0 ? void 0 : log(`CI Visibility: ${message}`);
48
+ }
49
+ catch (_b) {
50
+ // Diagnostic callbacks must not affect instrumented work.
51
+ }
52
+ };
53
+ exports.warn = warn;
54
+ //# sourceMappingURL=validation.js.map
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@datadog/ci-visibility",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "5.28.0",
4
+ "description": "Lightweight programmatic CI Visibility recording for GitHub Actions",
5
+ "license": "Apache-2.0",
6
+ "keywords": [
7
+ "ci-visibility",
8
+ "datadog",
9
+ "datadog-ci"
10
+ ],
11
+ "homepage": "https://github.com/DataDog/datadog-ci/tree/master/packages/ci-visibility",
12
+ "bugs": {
13
+ "url": "https://github.com/DataDog/datadog-ci/issues"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/DataDog/datadog-ci.git",
18
+ "directory": "packages/ci-visibility"
19
+ },
20
+ "engines": {
21
+ "node": ">=20"
22
+ },
23
+ "main": "dist/index.js",
24
+ "types": "dist/index.d.ts",
25
+ "exports": {
26
+ "./package.json": "./package.json",
27
+ ".": {
28
+ "types": "./dist/index.d.ts",
29
+ "development": "./src/index.ts",
30
+ "default": "./dist/index.js"
31
+ },
32
+ "./github": {
33
+ "types": "./dist/index.d.ts",
34
+ "development": "./src/index.ts",
35
+ "default": "./dist/index.js"
36
+ }
37
+ },
38
+ "files": [
39
+ "dist/**/*.js",
40
+ "dist/**/*.d.ts",
41
+ "README.md",
42
+ "LICENSE"
43
+ ],
44
+ "publishConfig": {
45
+ "access": "public"
46
+ },
47
+ "scripts": {
48
+ "build": "yarn package:clean; yarn package:build",
49
+ "lint": "yarn package:lint",
50
+ "prepack": "yarn package:clean-dist"
51
+ },
52
+ "author": {
53
+ "name": "Datadog, Inc.",
54
+ "email": "package@datadoghq.com"
55
+ }
6
56
  }