@rawdash/connector-circleci 0.17.0 → 0.20.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 +202 -0
- package/dist/index.js +0 -15
- package/dist/index.js.map +1 -1
- package/package.json +13 -13
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/dist/index.js
CHANGED
|
@@ -225,9 +225,6 @@ var CircleCIConnector = class _CircleCIConnector extends BaseConnector {
|
|
|
225
225
|
signal
|
|
226
226
|
});
|
|
227
227
|
}
|
|
228
|
-
// -------------------------------------------------------------------------
|
|
229
|
-
// Resource enablement
|
|
230
|
-
// -------------------------------------------------------------------------
|
|
231
228
|
activePhases() {
|
|
232
229
|
return selectActivePhases(
|
|
233
230
|
() => "pipelines",
|
|
@@ -238,9 +235,6 @@ var CircleCIConnector = class _CircleCIConnector extends BaseConnector {
|
|
|
238
235
|
workflowsNeeded() {
|
|
239
236
|
return this.isResourceEnabled("workflows") || this.isResourceEnabled("pipeline_events") || this.isResourceEnabled("jobs");
|
|
240
237
|
}
|
|
241
|
-
// -------------------------------------------------------------------------
|
|
242
|
-
// Cursor + URL building
|
|
243
|
-
// -------------------------------------------------------------------------
|
|
244
238
|
slugSet() {
|
|
245
239
|
return new Set(this.settings.projectSlugs);
|
|
246
240
|
}
|
|
@@ -327,9 +321,6 @@ var CircleCIConnector = class _CircleCIConnector extends BaseConnector {
|
|
|
327
321
|
const days = this.settings.pipelinesLookbackDays ?? DEFAULT_LOOKBACK_DAYS;
|
|
328
322
|
return Date.now() - days * MS_PER_DAY;
|
|
329
323
|
}
|
|
330
|
-
// -------------------------------------------------------------------------
|
|
331
|
-
// Fetchers
|
|
332
|
-
// -------------------------------------------------------------------------
|
|
333
324
|
async fetchAllWorkflowsForPipeline(pipelineId, signal) {
|
|
334
325
|
const out = [];
|
|
335
326
|
let token = null;
|
|
@@ -410,9 +401,6 @@ var CircleCIConnector = class _CircleCIConnector extends BaseConnector {
|
|
|
410
401
|
}
|
|
411
402
|
return { items: [batch], next };
|
|
412
403
|
}
|
|
413
|
-
// -------------------------------------------------------------------------
|
|
414
|
-
// Writers
|
|
415
|
-
// -------------------------------------------------------------------------
|
|
416
404
|
async writeBatch(storage, batch) {
|
|
417
405
|
const writePipelines = this.isResourceEnabled("pipelines");
|
|
418
406
|
const writeWorkflows = this.isResourceEnabled("workflows");
|
|
@@ -514,9 +502,6 @@ var CircleCIConnector = class _CircleCIConnector extends BaseConnector {
|
|
|
514
502
|
}
|
|
515
503
|
}
|
|
516
504
|
}
|
|
517
|
-
// -------------------------------------------------------------------------
|
|
518
|
-
// sync
|
|
519
|
-
// -------------------------------------------------------------------------
|
|
520
505
|
async sync(options, storage, signal) {
|
|
521
506
|
const cursor = this.resolveCursor(options.cursor);
|
|
522
507
|
const isFull = options.mode === "full";
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../connector-shared/src/errors.ts","../../../connector-shared/src/retry.ts","../../../connector-shared/src/version.ts","../../../connector-shared/src/request.ts","../../../connector-shared/src/rate-limit.ts","../../../connector-shared/src/sanitize.ts","../../../connector-shared/src/epoch.ts","../../../connector-shared/src/pagination.ts","../../../connector-shared/src/logger.ts","../src/circleci.ts","../src/index.ts"],"sourcesContent":["import type { HttpResponse } from './types';\n\nexport type HttpErrorKind =\n | 'transient'\n | 'rate_limit'\n | 'auth'\n | 'upstream_bug'\n | 'client_bug';\n\nexport abstract class HttpClientError extends Error {\n abstract readonly kind: HttpErrorKind;\n readonly response?: HttpResponse;\n\n constructor(message: string, response?: HttpResponse) {\n super(message);\n this.name = new.target.name;\n this.response = response;\n }\n}\n\nexport class TransientError extends HttpClientError {\n readonly kind = 'transient' as const;\n}\n\nexport class RateLimitError extends HttpClientError {\n readonly kind = 'rate_limit' as const;\n readonly retryAfter?: Date;\n\n constructor(message: string, response?: HttpResponse, retryAfter?: Date) {\n super(message, response);\n this.retryAfter = retryAfter;\n }\n}\n\nexport class AuthError extends HttpClientError {\n readonly kind = 'auth' as const;\n}\n\nexport class UpstreamBugError extends HttpClientError {\n readonly kind = 'upstream_bug' as const;\n}\n\nexport class ClientBugError extends HttpClientError {\n readonly kind = 'client_bug' as const;\n}\n\nexport function classifyStatus(status: number): HttpErrorKind {\n if (status === 429) {\n return 'rate_limit';\n }\n if (status === 401 || status === 403) {\n return 'auth';\n }\n if (status === 408) {\n return 'transient';\n }\n if (status >= 500) {\n return 'upstream_bug';\n }\n if (status >= 400) {\n return 'client_bug';\n }\n return 'client_bug';\n}\n\nexport function errorForStatus(\n message: string,\n response: HttpResponse,\n retryAfter?: Date,\n): HttpClientError {\n const kind = classifyStatus(response.status);\n switch (kind) {\n case 'rate_limit':\n return new RateLimitError(message, response, retryAfter);\n case 'auth':\n return new AuthError(message, response);\n case 'transient':\n return new TransientError(message, response);\n case 'upstream_bug':\n return new UpstreamBugError(message, response);\n case 'client_bug':\n return new ClientBugError(message, response);\n }\n}\n","import { HttpClientError, RateLimitError, TransientError } from './errors';\n\nexport interface RetryPolicy {\n maxAttempts?: number;\n initialDelayMs?: number;\n maxDelayMs?: number;\n retryOn?: (status: number | null, err?: Error) => boolean;\n}\n\nexport const defaultRetryOn = (status: number | null, err?: Error): boolean => {\n if (err instanceof RateLimitError) {\n return true;\n }\n if (err instanceof TransientError) {\n return true;\n }\n if (status === null) {\n return err instanceof Error && !(err instanceof HttpClientError);\n }\n if (status === 408 || status === 429) {\n return true;\n }\n if (status >= 500) {\n return true;\n }\n return false;\n};\n\nexport function backoffDelayMs(\n attempt: number,\n policy: Required<Pick<RetryPolicy, 'initialDelayMs' | 'maxDelayMs'>>,\n): number {\n const base = policy.initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, policy.maxDelayMs);\n}\n\nexport function parseRetryAfter(\n headerValue: string | null,\n now: Date = new Date(),\n): Date | undefined {\n if (!headerValue) {\n return undefined;\n }\n const trimmed = headerValue.trim();\n if (/^\\d+$/.test(trimmed)) {\n return new Date(now.getTime() + Number(trimmed) * 1000);\n }\n const parsed = Date.parse(trimmed);\n if (Number.isNaN(parsed)) {\n return undefined;\n }\n return new Date(parsed);\n}\n\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) {\n return Promise.reject(signal.reason ?? new Error('Aborted'));\n }\n return new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal!.reason ?? new Error('Aborted'));\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n","export const HTTP_CLIENT_VERSION = '0.0.0';\n\nexport const DEFAULT_USER_AGENT = `rawdash-connector/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n\nexport function connectorUserAgent(connectorId: string): string {\n return `rawdash-connector-${connectorId}/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n}\n","import {\n AuthError,\n ClientBugError,\n HttpClientError,\n RateLimitError,\n TransientError,\n UpstreamBugError,\n errorForStatus,\n} from './errors';\nimport { defaultRetryOn, parseRetryAfter, sleep } from './retry';\nimport type { FetchLike, HttpMethod, HttpRequest, HttpResponse } from './types';\nimport { DEFAULT_USER_AGENT } from './version';\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_ATTEMPTS = 3;\nconst DEFAULT_INITIAL_DELAY_MS = 1000;\nconst DEFAULT_MAX_DELAY_MS = 60_000;\nconst OBSERVER_TIMEOUT_MS = 250;\n\nexport interface RequestObservation {\n url: string;\n method: HttpMethod;\n status: number;\n resource: string;\n requestId: string;\n body: unknown;\n}\n\nexport type RequestObserver = (\n event: RequestObservation,\n) => void | Promise<void>;\n\nexport interface RequestOptions {\n fetch?: FetchLike;\n observer?: RequestObserver;\n resource: string;\n requestId?: string;\n}\n\nasync function notifyObserver(\n observer: RequestObserver,\n event: RequestObservation,\n): Promise<void> {\n let result: void | Promise<void>;\n try {\n result = observer(event);\n } catch (err) {\n console.warn('[connector-shared] request observer threw:', err);\n return;\n }\n if (!(result instanceof Promise)) {\n return;\n }\n const guarded = result.catch((err) => {\n console.warn('[connector-shared] request observer rejected:', err);\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, OBSERVER_TIMEOUT_MS);\n });\n try {\n await Promise.race([guarded, timeout]);\n } finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n}\n\nfunction newRequestId(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) {\n return c.randomUUID();\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\nfunction mergeHeaders(\n defaults: Record<string, string>,\n overrides: Record<string, string> | undefined,\n): Record<string, string> {\n const merged: Record<string, string> = {};\n for (const [k, v] of Object.entries(defaults)) {\n merged[k.toLowerCase()] = v;\n }\n if (overrides) {\n for (const [k, v] of Object.entries(overrides)) {\n merged[k.toLowerCase()] = v;\n }\n }\n return merged;\n}\n\nfunction linkTimeoutSignal(\n parent: AbortSignal | undefined,\n timeoutMs: number,\n): { signal: AbortSignal; cancel: () => void } {\n const controller = new AbortController();\n const onParentAbort = () => {\n controller.abort(parent?.reason);\n };\n if (parent) {\n if (parent.aborted) {\n controller.abort(parent.reason);\n } else {\n parent.addEventListener('abort', onParentAbort, { once: true });\n }\n }\n const timer = setTimeout(() => {\n controller.abort(new Error(`Request timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n return {\n signal: controller.signal,\n cancel: () => {\n clearTimeout(timer);\n if (parent) {\n parent.removeEventListener('abort', onParentAbort);\n }\n },\n };\n}\n\nasync function readBody(res: Response, parseJson: boolean): Promise<unknown> {\n if (res.status === 204 || res.status === 205) {\n return null;\n }\n const contentType = res.headers.get('content-type') ?? '';\n if (parseJson && contentType.includes('application/json')) {\n const text = await res.text();\n if (text.length === 0) {\n return null;\n }\n return JSON.parse(text);\n }\n return res.text();\n}\n\nexport async function request<T = unknown>(\n req: HttpRequest,\n options: RequestOptions,\n): Promise<HttpResponse<T>> {\n const fetchImpl: FetchLike = options.fetch ?? (globalThis.fetch as FetchLike);\n const retry = req.retry ?? {};\n const maxAttempts = retry.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n const initialDelayMs = retry.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;\n const maxDelayMs = retry.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;\n const retryOn = retry.retryOn ?? defaultRetryOn;\n const timeoutMs = req.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const parseJson = req.parseJson ?? true;\n\n const headers = mergeHeaders(\n {\n 'User-Agent': DEFAULT_USER_AGENT,\n Accept: 'application/json',\n },\n req.headers,\n );\n\n let lastErr: Error | undefined;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n req.signal?.throwIfAborted();\n\n const { signal, cancel } = linkTimeoutSignal(req.signal, timeoutMs);\n let res: Response;\n try {\n res = await fetchImpl(req.url, {\n method: req.method ?? 'GET',\n headers,\n body: req.body as RequestInit['body'],\n signal,\n });\n } catch (err) {\n cancel();\n if (req.signal?.aborted) {\n throw req.signal.reason ?? err;\n }\n const error = err instanceof Error ? err : new Error(String(err));\n lastErr = error;\n if (attempt < maxAttempts - 1 && retryOn(null, error)) {\n const delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n await sleep(delay, req.signal);\n continue;\n }\n throw new TransientError(error.message);\n }\n cancel();\n\n const body = await readBody(res, parseJson);\n const httpResponse: HttpResponse<T> = {\n status: res.status,\n headers: res.headers,\n body: body as T,\n };\n if (req.rateLimit) {\n const state = req.rateLimit.parse(res.headers);\n if (state) {\n httpResponse.rateLimitState = state;\n }\n }\n\n if (options.observer) {\n await notifyObserver(options.observer, {\n url: req.url,\n method: req.method ?? 'GET',\n status: res.status,\n resource: options.resource,\n requestId: options.requestId ?? newRequestId(),\n body,\n });\n }\n\n if (res.ok) {\n return httpResponse;\n }\n\n const retryAfter = parseRetryAfter(res.headers.get('retry-after'));\n const message = `HTTP ${res.status} ${res.statusText} for ${req.method ?? 'GET'} ${req.url}`;\n const err = errorForStatus(message, httpResponse, retryAfter);\n\n if (\n attempt < maxAttempts - 1 &&\n retryOn(res.status, err) &&\n !(err instanceof AuthError) &&\n !(err instanceof ClientBugError)\n ) {\n lastErr = err;\n let delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n if (err instanceof RateLimitError && retryAfter) {\n const wait = retryAfter.getTime() - Date.now();\n if (wait > 0) {\n delay = Math.min(wait, maxDelayMs);\n }\n }\n await sleep(delay, req.signal);\n continue;\n }\n\n throw err;\n }\n\n throw lastErr ?? new UpstreamBugError('Exhausted retry attempts');\n}\n\nfunction computeDelay(\n attempt: number,\n initialDelayMs: number,\n maxDelayMs: number,\n): number {\n const base = initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, maxDelayMs);\n}\n\nexport { HttpClientError };\n","export interface RateLimitState {\n remaining: number;\n resetAt: Date;\n}\n\nexport interface RateLimitPolicy {\n parse(headers: Headers): RateLimitState | null;\n}\n\nexport interface StandardRateLimitPolicyConfig {\n remainingHeader: string;\n resetHeader: string;\n resetUnit: 's' | 'ms';\n resetFallbackMs?: number;\n}\n\nexport function standardRateLimitPolicy(\n config: StandardRateLimitPolicyConfig,\n): RateLimitPolicy {\n const { remainingHeader, resetHeader, resetUnit, resetFallbackMs } = config;\n const multiplier = resetUnit === 's' ? 1000 : 1;\n return {\n parse(h) {\n const remainingRaw = h.get(remainingHeader);\n if (remainingRaw === null || remainingRaw.trim() === '') {\n return null;\n }\n const remaining = Number(remainingRaw);\n if (!Number.isFinite(remaining)) {\n return null;\n }\n const resetRaw = h.get(resetHeader);\n if (resetRaw === null) {\n if (resetFallbackMs === undefined) {\n return null;\n }\n return {\n remaining,\n resetAt: new Date(Date.now() + resetFallbackMs),\n };\n }\n if (resetRaw.trim() === '') {\n return null;\n }\n const reset = Number(resetRaw);\n if (!Number.isFinite(reset) || reset < 0) {\n return null;\n }\n const resetMs = reset * multiplier;\n if (!Number.isFinite(resetMs)) {\n return null;\n }\n return { remaining, resetAt: new Date(resetMs) };\n },\n };\n}\n","export interface SanitizeAllowedUrlOptions {\n url: string | null;\n host: string;\n pathname: string;\n protocol?: 'https:' | 'http:';\n}\n\nexport function sanitizeAllowedUrl(\n options: SanitizeAllowedUrlOptions,\n): string | null {\n const { url, host, pathname, protocol = 'https:' } = options;\n if (url === null) {\n return null;\n }\n try {\n const u = new URL(url);\n if (u.protocol !== protocol || u.host !== host || u.pathname !== pathname) {\n return null;\n }\n return u.toString();\n } catch {\n return null;\n }\n}\n","export type EpochUnit = 'ms' | 's' | 'iso';\n\nexport function parseEpoch(\n value: number | string | null | undefined,\n unit: EpochUnit,\n): number | null {\n if (value === null || value === undefined) {\n return null;\n }\n if (unit === 'iso') {\n if (typeof value !== 'string') {\n return null;\n }\n const ms = new Date(value).getTime();\n return Number.isFinite(ms) ? ms : null;\n }\n if (typeof value === 'string' && value.trim() === '') {\n return null;\n }\n const n = typeof value === 'number' ? value : Number(value);\n if (!Number.isFinite(n)) {\n return null;\n }\n const result = unit === 's' ? n * 1000 : n;\n return Number.isFinite(result) ? result : null;\n}\n","import { request } from './request';\nimport type { HttpRequest } from './types';\n\nexport function parseLinkHeader(header: string | null): Record<string, string> {\n if (!header) {\n return {};\n }\n const result: Record<string, string> = {};\n for (const part of header.split(',')) {\n const match = part.match(/<([^>]+)>\\s*;\\s*rel=\"([^\"]+)\"/);\n if (match) {\n result[match[2]!] = match[1]!;\n }\n }\n return result;\n}\n\nexport async function* paginateLink<T>(\n initial: HttpRequest,\n parse: (body: unknown) => T[],\n options: { resource: string },\n): AsyncIterable<T> {\n let next: string | null = initial.url;\n while (next) {\n const res: Awaited<ReturnType<typeof request>> = await request(\n {\n ...initial,\n url: next,\n },\n { resource: options.resource },\n );\n for (const item of parse(res.body)) {\n yield item;\n }\n const links = parseLinkHeader(res.headers.get('link'));\n next = links['next'] ?? null;\n }\n}\n\nexport async function* paginateCursor<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; nextCursor: string | null },\n buildNext: (req: HttpRequest, cursor: string) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let req: HttpRequest = initial;\n while (true) {\n const res = await request(req, { resource: options.resource });\n const { items, nextCursor } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!nextCursor) {\n return;\n }\n req = buildNext(req, nextCursor);\n }\n}\n\nexport async function* paginatePage<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; hasMore: boolean },\n buildPage: (req: HttpRequest, page: number) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let page = 1;\n while (true) {\n const req = page === 1 ? initial : buildPage(initial, page);\n const res = await request(req, { resource: options.resource });\n const { items, hasMore } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!hasMore || items.length === 0) {\n return;\n }\n page++;\n }\n}\n","export type LogFields = Record<string, unknown>;\n\nexport interface ConnectorLogger {\n info(event: string, fields?: LogFields): void;\n warn(event: string, fields?: LogFields): void;\n}\n\nexport interface ConnectorLoggerOptions {\n scope: string;\n}\n\nconst MAX_VALUE_LEN = 120;\n\nfunction truncate(s: string, max = MAX_VALUE_LEN): string {\n if (s.length <= max) {\n return s;\n }\n return `${s.slice(0, max - 1)}…`;\n}\n\nfunction formatValue(value: unknown): string {\n if (value === null) {\n return 'null';\n }\n if (value === undefined) {\n return '';\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n if (typeof value === 'string') {\n const t = truncate(value);\n if (/[\\s\"=]/.test(t)) {\n return JSON.stringify(t);\n }\n return t;\n }\n if (typeof value === 'bigint') {\n return value.toString();\n }\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch {\n json = undefined;\n }\n return truncate(json ?? String(value));\n}\n\nexport function formatLogFields(fields?: LogFields): string {\n if (!fields) {\n return '';\n }\n const parts: string[] = [];\n for (const [k, v] of Object.entries(fields)) {\n if (v === undefined) {\n continue;\n }\n parts.push(`${k}=${formatValue(v)}`);\n }\n return parts.length > 0 ? ` ${parts.join(' ')}` : '';\n}\n\nexport function formatLogLine(\n scope: string,\n event: string,\n fields?: LogFields,\n): string {\n return `[${scope}] ${event}${formatLogFields(fields)}`;\n}\n\nexport function createDefaultConnectorLogger(\n opts: ConnectorLoggerOptions,\n): ConnectorLogger {\n return {\n info(event, fields) {\n console.info(formatLogLine(opts.scope, event, fields));\n },\n warn(event, fields) {\n console.warn(formatLogLine(opts.scope, event, fields));\n },\n };\n}\n\nconst NOOP_LOGGER: ConnectorLogger = {\n info() {},\n warn() {},\n};\n\nexport function noopConnectorLogger(): ConnectorLogger {\n return NOOP_LOGGER;\n}\n","import {\n type HttpResponse,\n connectorUserAgent,\n parseEpoch,\n} from '@rawdash/connector-shared';\nimport {\n BaseConnector,\n type ChunkedSyncCursor,\n type ConnectorContext,\n type ConnectorDoc,\n type CredentialsSchema,\n type JSONValue,\n type StorageHandle,\n type SyncOptions,\n type SyncResult,\n defineConfigFields,\n defineConnectorDoc,\n defineResources,\n makeChunkedCursorGuard,\n paginateChunked,\n schemasFromResources,\n selectActivePhases,\n} from '@rawdash/core';\nimport { z } from 'zod';\n\n// ---------------------------------------------------------------------------\n// configFields\n// ---------------------------------------------------------------------------\n\nexport const configFields = defineConfigFields(\n z.object({\n apiToken: z.object({ $secret: z.string() }).meta({\n label: 'API Token',\n description:\n 'CircleCI personal API token (read-only is sufficient). Create one at CircleCI -> User Settings -> Personal API Tokens.',\n placeholder: 'circleci_token',\n secret: true,\n }),\n projectSlugs: z\n .array(z.string().min(1))\n .nonempty()\n .refine((slugs) => new Set(slugs).size === slugs.length, {\n error: 'Project slugs must be unique.',\n })\n .meta({\n label: 'Project slugs',\n description:\n \"CircleCI project slugs to sync, e.g. 'gh/my-org/my-repo' or 'circleci/<orgId>/<projectId>'.\",\n }),\n branch: z.string().min(1).optional().meta({\n label: 'Branch (optional)',\n description:\n 'Restrict pipeline sync to a single branch. Omit to sync all branches.',\n placeholder: 'main',\n }),\n resources: z\n .array(z.enum(['pipelines', 'workflows', 'jobs', 'pipeline_events']))\n .nonempty()\n .optional()\n .meta({\n label: 'Resources',\n description:\n 'Which CircleCI resources to sync. Omit to sync pipelines, workflows, and pipeline_events (jobs are off by default because they add a per-workflow API call). Workflows must be fetched whenever workflows, jobs, or pipeline_events are enabled.',\n }),\n pipelinesLookbackDays: z\n .number()\n .int()\n .positive()\n .max(365)\n .optional()\n .meta({\n label: 'Pipelines lookback (days)',\n description:\n 'How many days back to fetch pipelines on a full sync. Defaults to 30. CircleCI does not expose a server-side since filter, so the connector paginates newest-first and stops once it crosses this window.',\n placeholder: '30',\n }),\n }),\n);\n\nexport type CircleCIResource =\n | 'pipelines'\n | 'workflows'\n | 'jobs'\n | 'pipeline_events';\n\nexport interface CircleCISettings {\n projectSlugs: readonly string[];\n branch?: string;\n resources?: readonly CircleCIResource[];\n pipelinesLookbackDays?: number;\n}\n\nconst circleciCredentials = {\n apiToken: {\n description: 'CircleCI personal API token',\n auth: 'required' as const,\n },\n} satisfies CredentialsSchema;\n\ntype CircleCICredentials = typeof circleciCredentials;\n\n// ---------------------------------------------------------------------------\n// Connector documentation metadata\n// ---------------------------------------------------------------------------\n\nexport const doc: ConnectorDoc = defineConnectorDoc({\n displayName: 'CircleCI',\n category: 'engineering',\n brandColor: '#161616',\n tagline:\n 'Sync CircleCI pipelines, workflows, jobs, and workflow state-transition events so build success rate and duration land on dashboards.',\n vendor: {\n name: 'CircleCI',\n apiDocs: 'https://circleci.com/docs/api/v2/',\n website: 'https://circleci.com',\n },\n auth: {\n summary:\n 'A CircleCI personal API token is required. Tokens authenticate against the v2 REST API and inherit the creating user permissions on the configured projects.',\n setup: [\n 'Open CircleCI -> User Settings -> Personal API Tokens (https://app.circleci.com/settings/user/tokens).',\n 'Create a token with a descriptive name (e.g. \"rawdash sync\") and copy the value.',\n 'Store it as a secret and reference it from the connector config as `apiToken: secret(\"CIRCLECI_API_TOKEN\")`.',\n \"Set `projectSlugs` to the projects you want to sync, e.g. ['gh/my-org/my-repo'].\",\n ],\n },\n rateLimit:\n 'CircleCI enforces a per-token rate limit of roughly 3,500 requests per hour. The connector paginates pipelines newest-first and fans out one extra request per pipeline for workflows (and one more per workflow for jobs when enabled), so cap `projectSlugs` and `pipelinesLookbackDays` accordingly.',\n limitations: [\n 'CircleCI v2 has no server-side since filter for pipelines, so the connector paginates newest-first and stops once it crosses `pipelinesLookbackDays` (default 30).',\n 'The `jobs` resource is off by default because it adds an extra API call per workflow. Enable it explicitly in `resources` if you need per-job entities.',\n 'Insights API (pre-aggregated workflow stats) and the self-hosted CircleCI Server are out of scope for v1.',\n ],\n});\n\n// ---------------------------------------------------------------------------\n// Sync phases + cursor\n// ---------------------------------------------------------------------------\n\nconst PHASE_ORDER = ['pipelines'] as const;\n\ntype CircleCIPhase = (typeof PHASE_ORDER)[number];\n\ntype CircleCISyncCursor = ChunkedSyncCursor<CircleCIPhase, string>;\n\nconst isCircleCISyncCursor = makeChunkedCursorGuard(PHASE_ORDER);\n\n// page-cursor encoding: a JSON object {slug, token} stringified to fit the\n// string-typed `page` slot. `slug` is one of the configured projectSlugs;\n// `token` is the CircleCI next_page_token (or null when starting that slug).\nconst pageCursorSchema = z.object({\n slug: z.string().min(1),\n token: z.string().nullable(),\n});\n\ninterface CirclePageCursor {\n slug: string;\n token: string | null;\n}\n\n// ---------------------------------------------------------------------------\n// CircleCI API types\n// ---------------------------------------------------------------------------\n\ninterface CircleCIPipeline {\n id: string;\n number: number;\n project_slug: string;\n state: string;\n created_at: string;\n updated_at: string;\n trigger?: {\n type?: string | null;\n actor?: { login?: string | null } | null;\n } | null;\n vcs?: {\n revision?: string | null;\n branch?: string | null;\n tag?: string | null;\n target_repository_url?: string | null;\n origin_repository_url?: string | null;\n } | null;\n}\n\ninterface CircleCIPipelinesResponse {\n items: CircleCIPipeline[];\n next_page_token: string | null;\n}\n\ninterface CircleCIWorkflow {\n id: string;\n name: string;\n pipeline_id: string;\n pipeline_number?: number;\n project_slug: string;\n status:\n | 'success'\n | 'running'\n | 'not_run'\n | 'failed'\n | 'error'\n | 'failing'\n | 'on_hold'\n | 'canceled'\n | 'unauthorized'\n | string;\n created_at: string;\n stopped_at?: string | null;\n started_by?: string | null;\n tag?: string | null;\n}\n\ninterface CircleCIWorkflowsResponse {\n items: CircleCIWorkflow[];\n next_page_token: string | null;\n}\n\ninterface CircleCIJob {\n id: string;\n name: string;\n status: string;\n type?: string;\n job_number?: number | null;\n started_at?: string | null;\n stopped_at?: string | null;\n project_slug?: string;\n dependencies?: string[];\n}\n\ninterface CircleCIJobsResponse {\n items: CircleCIJob[];\n next_page_token: string | null;\n}\n\n// ---------------------------------------------------------------------------\n// Schemas\n// ---------------------------------------------------------------------------\n\nconst idString = z.string().min(1);\nconst isoString = z.string().min(1);\n\nconst pipelineSchema = z.object({\n id: idString,\n number: z.number().int().nonnegative(),\n project_slug: idString,\n state: z.string().min(1),\n created_at: isoString,\n updated_at: isoString,\n trigger: z\n .object({\n type: z.string().nullable().optional(),\n actor: z\n .object({ login: z.string().nullable().optional() })\n .nullable()\n .optional(),\n })\n .nullable()\n .optional(),\n vcs: z\n .object({\n revision: z.string().nullable().optional(),\n branch: z.string().nullable().optional(),\n tag: z.string().nullable().optional(),\n })\n .nullable()\n .optional(),\n});\n\nconst pipelinesResponseSchema = z.object({\n items: z.array(pipelineSchema),\n next_page_token: z.string().nullable(),\n});\n\nconst workflowSchema = z.object({\n id: idString,\n name: z.string().min(1),\n pipeline_id: idString,\n project_slug: idString,\n status: z.string().min(1),\n created_at: isoString,\n stopped_at: z.string().nullable().optional(),\n started_by: z.string().nullable().optional(),\n});\n\nconst workflowsResponseSchema = z.object({\n items: z.array(workflowSchema),\n next_page_token: z.string().nullable(),\n});\n\nconst jobSchema = z.object({\n id: idString,\n name: z.string().min(1),\n status: z.string().min(1),\n type: z.string().optional(),\n job_number: z.number().int().nullable().optional(),\n started_at: z.string().nullable().optional(),\n stopped_at: z.string().nullable().optional(),\n project_slug: z.string().optional(),\n});\n\nconst jobsResponseSchema = z.object({\n items: z.array(jobSchema),\n next_page_token: z.string().nullable(),\n});\n\nexport const circleciResources = defineResources({\n circleci_pipeline: {\n shape: 'entity',\n description:\n 'CircleCI pipelines with state, trigger, git ref, project slug, and create/update timestamps.',\n endpoint: 'GET /api/v2/project/{project_slug}/pipeline',\n notes:\n 'Pipelines are paginated newest-first; the connector stops once it crosses `pipelinesLookbackDays`.',\n responses: { pipelines: pipelinesResponseSchema },\n },\n circleci_workflow: {\n shape: 'entity',\n description:\n 'Workflows belonging to each pipeline, including status, name, and start/stop timestamps. Fetched per pipeline with one extra API call.',\n endpoint: 'GET /api/v2/pipeline/{pipeline_id}/workflow',\n responses: { workflows: workflowsResponseSchema },\n },\n circleci_job: {\n shape: 'entity',\n description:\n 'Jobs belonging to each workflow, including status, type, and start/stop timestamps. Off by default; enable via `resources` because it adds an API call per workflow.',\n endpoint: 'GET /api/v2/workflow/{workflow_id}/job',\n responses: { jobs: jobsResponseSchema },\n },\n circleci_pipeline_event: {\n shape: 'event',\n description:\n 'Each workflow emitted as a time-bounded event spanning its created_at to stopped_at, carrying the same status, project, and pipeline attributes.',\n endpoint: 'GET /api/v2/pipeline/{pipeline_id}/workflow',\n },\n});\n\n// ---------------------------------------------------------------------------\n// CircleCIConnector\n// ---------------------------------------------------------------------------\n\nconst CIRCLECI_API_BASE = 'https://circleci.com/api/v2';\nconst DEFAULT_RESOURCES: readonly CircleCIResource[] = [\n 'pipelines',\n 'workflows',\n 'pipeline_events',\n];\nconst DEFAULT_LOOKBACK_DAYS = 30;\nconst MS_PER_DAY = 24 * 60 * 60 * 1000;\n\nexport const id = 'circleci';\n\nexport class CircleCIConnector extends BaseConnector<\n CircleCISettings,\n CircleCICredentials\n> {\n static readonly id = id;\n\n static readonly resources = circleciResources;\n\n static readonly schemas = schemasFromResources(circleciResources);\n\n static create(input: unknown, ctx?: ConnectorContext): CircleCIConnector {\n const parsed = configFields.parse(input);\n return new CircleCIConnector(\n {\n projectSlugs: parsed.projectSlugs,\n branch: parsed.branch,\n resources: parsed.resources ?? DEFAULT_RESOURCES,\n pipelinesLookbackDays: parsed.pipelinesLookbackDays,\n },\n { apiToken: parsed.apiToken },\n ctx,\n );\n }\n\n readonly id = id;\n override readonly credentials = circleciCredentials;\n\n private buildHeaders(): Record<string, string> {\n return {\n 'Circle-Token': this.creds.apiToken,\n Accept: 'application/json',\n 'User-Agent': connectorUserAgent('circleci'),\n };\n }\n\n private fetch<T>(\n url: string,\n resource: string,\n signal?: AbortSignal,\n ): Promise<HttpResponse<T>> {\n return this.get<T>(url, {\n resource,\n headers: this.buildHeaders(),\n signal,\n });\n }\n\n // -------------------------------------------------------------------------\n // Resource enablement\n // -------------------------------------------------------------------------\n\n private activePhases(): CircleCIPhase[] {\n return selectActivePhases<CircleCIResource, CircleCIPhase>(\n () => 'pipelines',\n PHASE_ORDER,\n this.settings.resources,\n );\n }\n\n private workflowsNeeded(): boolean {\n return (\n this.isResourceEnabled('workflows') ||\n this.isResourceEnabled('pipeline_events') ||\n this.isResourceEnabled('jobs')\n );\n }\n\n // -------------------------------------------------------------------------\n // Cursor + URL building\n // -------------------------------------------------------------------------\n\n private slugSet(): Set<string> {\n return new Set(this.settings.projectSlugs);\n }\n\n private decodePageCursor(page: string | null): CirclePageCursor | null {\n if (page === null) {\n return null;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(page);\n } catch {\n return null;\n }\n const res = pageCursorSchema.safeParse(parsed);\n if (!res.success) {\n return null;\n }\n if (!this.slugSet().has(res.data.slug)) {\n return null;\n }\n return res.data;\n }\n\n private encodePageCursor(cursor: CirclePageCursor): string {\n return JSON.stringify(cursor);\n }\n\n private resolveCursor(cursor: unknown): CircleCISyncCursor | undefined {\n if (!isCircleCISyncCursor(cursor)) {\n return undefined;\n }\n if (cursor.page === null) {\n return { phase: cursor.phase, page: null };\n }\n const decoded = this.decodePageCursor(cursor.page);\n if (!decoded) {\n return { phase: cursor.phase, page: null };\n }\n return { phase: cursor.phase, page: this.encodePageCursor(decoded) };\n }\n\n private buildPipelinesUrl(slug: string, token: string | null): string {\n const u = new URL(\n `${CIRCLECI_API_BASE}/project/${encodeURI(slug)}/pipeline`,\n );\n if (this.settings.branch !== undefined) {\n u.searchParams.set('branch', this.settings.branch);\n }\n if (token !== null) {\n u.searchParams.set('page-token', token);\n }\n return u.toString();\n }\n\n private buildWorkflowsUrl(pipelineId: string, token: string | null): string {\n const u = new URL(\n `${CIRCLECI_API_BASE}/pipeline/${encodeURIComponent(pipelineId)}/workflow`,\n );\n if (token !== null) {\n u.searchParams.set('page-token', token);\n }\n return u.toString();\n }\n\n private buildJobsUrl(workflowId: string, token: string | null): string {\n const u = new URL(\n `${CIRCLECI_API_BASE}/workflow/${encodeURIComponent(workflowId)}/job`,\n );\n if (token !== null) {\n u.searchParams.set('page-token', token);\n }\n return u.toString();\n }\n\n private nextSlug(currentSlug: string): string | null {\n const slugs = this.settings.projectSlugs;\n const idx = slugs.indexOf(currentSlug);\n if (idx < 0 || idx >= slugs.length - 1) {\n return null;\n }\n return slugs[idx + 1] ?? null;\n }\n\n private cutoffMs(options: SyncOptions): number | null {\n if (options.since) {\n const ms = parseEpoch(options.since, 'iso');\n if (ms !== null) {\n return ms;\n }\n }\n const days = this.settings.pipelinesLookbackDays ?? DEFAULT_LOOKBACK_DAYS;\n return Date.now() - days * MS_PER_DAY;\n }\n\n // -------------------------------------------------------------------------\n // Fetchers\n // -------------------------------------------------------------------------\n\n private async fetchAllWorkflowsForPipeline(\n pipelineId: string,\n signal: AbortSignal | undefined,\n ): Promise<CircleCIWorkflow[]> {\n const out: CircleCIWorkflow[] = [];\n let token: string | null = null;\n do {\n const url = this.buildWorkflowsUrl(pipelineId, token);\n const res = await this.fetch<CircleCIWorkflowsResponse>(\n url,\n 'workflows',\n signal,\n );\n out.push(...res.body.items);\n token = res.body.next_page_token ?? null;\n } while (token !== null);\n return out;\n }\n\n private async fetchAllJobsForWorkflow(\n workflowId: string,\n signal: AbortSignal | undefined,\n ): Promise<CircleCIJob[]> {\n const out: CircleCIJob[] = [];\n let token: string | null = null;\n do {\n const url = this.buildJobsUrl(workflowId, token);\n const res = await this.fetch<CircleCIJobsResponse>(url, 'jobs', signal);\n out.push(...res.body.items);\n token = res.body.next_page_token ?? null;\n } while (token !== null);\n return out;\n }\n\n private async fetchPipelinesPage(\n page: string | null,\n options: SyncOptions,\n signal: AbortSignal | undefined,\n ): Promise<{ items: PipelinePageBatch[]; next: string | null }> {\n const decoded = page !== null ? this.decodePageCursor(page) : null;\n const slug = decoded?.slug ?? this.settings.projectSlugs[0]!;\n const token = decoded?.token ?? null;\n const url = this.buildPipelinesUrl(slug, token);\n const res = await this.fetch<CircleCIPipelinesResponse>(\n url,\n 'pipelines',\n signal,\n );\n\n const cutoff = this.cutoffMs(options);\n const pipelines = res.body.items;\n\n const inWindow: CircleCIPipeline[] = [];\n let crossedCutoff = false;\n for (const p of pipelines) {\n const updatedMs = parseEpoch(p.updated_at, 'iso');\n if (cutoff !== null && updatedMs !== null && updatedMs < cutoff) {\n crossedCutoff = true;\n continue;\n }\n inWindow.push(p);\n }\n\n const workflowsBySlug = new Map<string, CircleCIWorkflow[]>();\n const jobsByWorkflow = new Map<string, CircleCIJob[]>();\n if (this.workflowsNeeded()) {\n for (const p of inWindow) {\n signal?.throwIfAborted();\n const wfs = await this.fetchAllWorkflowsForPipeline(p.id, signal);\n workflowsBySlug.set(p.id, wfs);\n if (this.isResourceEnabled('jobs')) {\n for (const wf of wfs) {\n signal?.throwIfAborted();\n const jobs = await this.fetchAllJobsForWorkflow(wf.id, signal);\n jobsByWorkflow.set(wf.id, jobs);\n }\n }\n }\n }\n\n const batch: PipelinePageBatch = {\n slug,\n pipelines: inWindow,\n workflowsByPipeline: workflowsBySlug,\n jobsByWorkflow,\n };\n\n let next: string | null;\n const nextToken = res.body.next_page_token ?? null;\n if (nextToken !== null && !crossedCutoff) {\n next = this.encodePageCursor({ slug, token: nextToken });\n } else {\n const nextSlug = this.nextSlug(slug);\n next =\n nextSlug !== null\n ? this.encodePageCursor({ slug: nextSlug, token: null })\n : null;\n }\n\n return { items: [batch], next };\n }\n\n // -------------------------------------------------------------------------\n // Writers\n // -------------------------------------------------------------------------\n\n private async writeBatch(\n storage: StorageHandle,\n batch: PipelinePageBatch,\n ): Promise<void> {\n const writePipelines = this.isResourceEnabled('pipelines');\n const writeWorkflows = this.isResourceEnabled('workflows');\n const writeJobs = this.isResourceEnabled('jobs');\n const writeEvents = this.isResourceEnabled('pipeline_events');\n\n for (const p of batch.pipelines) {\n const createdMs = parseEpoch(p.created_at, 'iso');\n const updatedMs = parseEpoch(p.updated_at, 'iso');\n if (createdMs === null || updatedMs === null) {\n console.warn(\n `[connector-circleci] skipping pipeline ${p.id} with unparseable timestamps`,\n );\n continue;\n }\n\n if (writePipelines) {\n await storage.entity({\n type: 'circleci_pipeline',\n id: p.id,\n attributes: {\n pipelineId: p.id,\n number: p.number,\n projectSlug: p.project_slug,\n state: p.state,\n branch: p.vcs?.branch ?? null,\n revision: p.vcs?.revision ?? null,\n tag: p.vcs?.tag ?? null,\n triggerType: p.trigger?.type ?? null,\n triggerActor: p.trigger?.actor?.login ?? null,\n createdAt: createdMs,\n updatedAt: updatedMs,\n },\n updated_at: updatedMs,\n });\n }\n\n const workflows = batch.workflowsByPipeline.get(p.id) ?? [];\n for (const wf of workflows) {\n const wfCreatedMs = parseEpoch(wf.created_at, 'iso');\n const wfStoppedMs = parseEpoch(wf.stopped_at ?? null, 'iso');\n if (wfCreatedMs === null) {\n console.warn(\n `[connector-circleci] skipping workflow ${wf.id} with unparseable created_at`,\n );\n continue;\n }\n const durationMs =\n wfStoppedMs !== null && wfStoppedMs >= wfCreatedMs\n ? wfStoppedMs - wfCreatedMs\n : null;\n const wfAttrs: Record<string, JSONValue> = {\n workflowId: wf.id,\n pipelineId: wf.pipeline_id,\n projectSlug: wf.project_slug,\n name: wf.name,\n status: wf.status,\n startedBy: wf.started_by ?? null,\n createdAt: wfCreatedMs,\n stoppedAt: wfStoppedMs,\n durationMs,\n };\n\n if (writeWorkflows) {\n await storage.entity({\n type: 'circleci_workflow',\n id: wf.id,\n attributes: wfAttrs,\n updated_at: wfStoppedMs ?? wfCreatedMs,\n });\n }\n\n if (writeEvents) {\n await storage.event({\n name: 'circleci_pipeline_event',\n start_ts: wfCreatedMs,\n end_ts: wfStoppedMs,\n attributes: wfAttrs,\n });\n }\n\n if (writeJobs) {\n const jobs = batch.jobsByWorkflow.get(wf.id) ?? [];\n for (const job of jobs) {\n const startedMs = parseEpoch(job.started_at ?? null, 'iso');\n const stoppedMs = parseEpoch(job.stopped_at ?? null, 'iso');\n const jobDurationMs =\n startedMs !== null && stoppedMs !== null && stoppedMs >= startedMs\n ? stoppedMs - startedMs\n : null;\n await storage.entity({\n type: 'circleci_job',\n id: job.id,\n attributes: {\n jobId: job.id,\n workflowId: wf.id,\n pipelineId: wf.pipeline_id,\n projectSlug: job.project_slug ?? wf.project_slug,\n name: job.name,\n status: job.status,\n type: job.type ?? null,\n jobNumber: job.job_number ?? null,\n startedAt: startedMs,\n stoppedAt: stoppedMs,\n durationMs: jobDurationMs,\n },\n updated_at: stoppedMs ?? startedMs ?? wfCreatedMs,\n });\n }\n }\n }\n }\n }\n\n // -------------------------------------------------------------------------\n // sync\n // -------------------------------------------------------------------------\n\n async sync(\n options: SyncOptions,\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<SyncResult> {\n const cursor = this.resolveCursor(options.cursor);\n const isFull = options.mode === 'full';\n const phases = this.activePhases();\n\n return paginateChunked<CircleCIPhase, string>({\n phases,\n cursor,\n signal,\n logger: this.logger,\n fetchPage: async (_phase, page, sig) =>\n this.fetchPipelinesPage(page, options, sig),\n writeBatch: async (_phase, items, page) => {\n if (isFull && page === null) {\n if (this.isResourceEnabled('pipelines')) {\n await storage.entities([], { types: ['circleci_pipeline'] });\n }\n if (this.isResourceEnabled('workflows')) {\n await storage.entities([], { types: ['circleci_workflow'] });\n }\n if (this.isResourceEnabled('jobs')) {\n await storage.entities([], { types: ['circleci_job'] });\n }\n if (this.isResourceEnabled('pipeline_events')) {\n await storage.events([], { names: ['circleci_pipeline_event'] });\n }\n }\n for (const batch of items as PipelinePageBatch[]) {\n await this.writeBatch(storage, batch);\n }\n },\n });\n }\n}\n\ninterface PipelinePageBatch {\n slug: string;\n pipelines: CircleCIPipeline[];\n workflowsByPipeline: Map<string, CircleCIWorkflow[]>;\n jobsByWorkflow: Map<string, CircleCIJob[]>;\n}\n","import { CircleCIConnector } from './circleci';\n\nexport {\n circleciResources as resources,\n CircleCIConnector,\n configFields,\n doc,\n id,\n} from './circleci';\nexport type { CircleCIResource, CircleCISettings } from './circleci';\nexport default CircleCIConnector;\n"],"mappings":";AEAO,IAAM,sBAAsB;AAE5B,IAAM,qBAAqB,qBAAqB,mBAAmB;AAEnE,SAAS,mBAAmB,aAA6B;AAC9D,SAAO,qBAAqB,WAAW,IAAI,mBAAmB;AAChE;AIJO,SAAS,WACd,OACA,MACe;AACf,MAAI,UAAU,QAAQ,UAAU,QAAW;AACzC,WAAO;EACT;AACA,MAAI,SAAS,OAAO;AAClB,QAAI,OAAO,UAAU,UAAU;AAC7B,aAAO;IACT;AACA,UAAM,KAAK,IAAI,KAAK,KAAK,EAAE,QAAQ;AACnC,WAAO,OAAO,SAAS,EAAE,IAAI,KAAK;EACpC;AACA,MAAI,OAAO,UAAU,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YAAY,aAAa,aAAa;AAAA,YACxC,CAAC;AAAA,UACH;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,KACJ,SACA,SACA,QACqB;AACrB,UAAM,SAAS,KAAK,cAAc,QAAQ,MAAM;AAChD,UAAM,SAAS,QAAQ,SAAS;AAChC,UAAM,SAAS,KAAK,aAAa;AAEjC,WAAO,gBAAuC;AAAA,MAC5C;AAAA,MACA;AAAA,MACA;AAAA,MACA,QAAQ,KAAK;AAAA,MACb,WAAW,OAAO,QAAQ,MAAM,QAC9B,KAAK,mBAAmB,MAAM,SAAS,GAAG;AAAA,MAC5C,YAAY,OAAO,QAAQ,OAAO,SAAS;AACzC,YAAI,UAAU,SAAS,MAAM;AAC3B,cAAI,KAAK,kBAAkB,WAAW,GAAG;AACvC,kBAAM,QAAQ,SAAS,CAAC,GAAG,EAAE,OAAO,CAAC,mBAAmB,EAAE,CAAC;AAAA,UAC7D;AACA,cAAI,KAAK,kBAAkB,WAAW,GAAG;AACvC,kBAAM,QAAQ,SAAS,CAAC,GAAG,EAAE,OAAO,CAAC,mBAAmB,EAAE,CAAC;AAAA,UAC7D;AACA,cAAI,KAAK,kBAAkB,MAAM,GAAG;AAClC,kBAAM,QAAQ,SAAS,CAAC,GAAG,EAAE,OAAO,CAAC,cAAc,EAAE,CAAC;AAAA,UACxD;AACA,cAAI,KAAK,kBAAkB,iBAAiB,GAAG;AAC7C,kBAAM,QAAQ,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,yBAAyB,EAAE,CAAC;AAAA,UACjE;AAAA,QACF;AACA,mBAAW,SAAS,OAA8B;AAChD,gBAAM,KAAK,WAAW,SAAS,KAAK;AAAA,QACtC;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AACF;;;ACxwBA,IAAO,gBAAQ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../connector-shared/src/errors.ts","../../../connector-shared/src/retry.ts","../../../connector-shared/src/version.ts","../../../connector-shared/src/request.ts","../../../connector-shared/src/rate-limit.ts","../../../connector-shared/src/map-concurrent.ts","../../../connector-shared/src/sanitize.ts","../../../connector-shared/src/epoch.ts","../../../connector-shared/src/pagination.ts","../../../connector-shared/src/logger.ts","../src/circleci.ts","../src/index.ts"],"sourcesContent":["import type { HttpResponse } from './types';\n\nexport type HttpErrorKind =\n | 'transient'\n | 'rate_limit'\n | 'auth'\n | 'upstream_bug'\n | 'client_bug';\n\nexport abstract class HttpClientError extends Error {\n abstract readonly kind: HttpErrorKind;\n readonly response?: HttpResponse;\n\n constructor(message: string, response?: HttpResponse) {\n super(message);\n this.name = new.target.name;\n this.response = response;\n }\n}\n\nexport class TransientError extends HttpClientError {\n readonly kind = 'transient' as const;\n}\n\nexport class RateLimitError extends HttpClientError {\n readonly kind = 'rate_limit' as const;\n readonly retryAfter?: Date;\n\n constructor(message: string, response?: HttpResponse, retryAfter?: Date) {\n super(message, response);\n this.retryAfter = retryAfter;\n }\n}\n\nexport class AuthError extends HttpClientError {\n readonly kind = 'auth' as const;\n}\n\nexport class UpstreamBugError extends HttpClientError {\n readonly kind = 'upstream_bug' as const;\n}\n\nexport class ClientBugError extends HttpClientError {\n readonly kind = 'client_bug' as const;\n}\n\nexport function classifyStatus(status: number): HttpErrorKind {\n if (status === 429) {\n return 'rate_limit';\n }\n if (status === 401 || status === 403) {\n return 'auth';\n }\n if (status === 408) {\n return 'transient';\n }\n if (status >= 500) {\n return 'upstream_bug';\n }\n if (status >= 400) {\n return 'client_bug';\n }\n return 'client_bug';\n}\n\nexport function errorForStatus(\n message: string,\n response: HttpResponse,\n retryAfter?: Date,\n): HttpClientError {\n const kind = classifyStatus(response.status);\n switch (kind) {\n case 'rate_limit':\n return new RateLimitError(message, response, retryAfter);\n case 'auth':\n return new AuthError(message, response);\n case 'transient':\n return new TransientError(message, response);\n case 'upstream_bug':\n return new UpstreamBugError(message, response);\n case 'client_bug':\n return new ClientBugError(message, response);\n }\n}\n","import { HttpClientError, RateLimitError, TransientError } from './errors';\n\nexport interface RetryPolicy {\n maxAttempts?: number;\n initialDelayMs?: number;\n maxDelayMs?: number;\n retryOn?: (status: number | null, err?: Error) => boolean;\n}\n\nexport const defaultRetryOn = (status: number | null, err?: Error): boolean => {\n if (err instanceof RateLimitError) {\n return true;\n }\n if (err instanceof TransientError) {\n return true;\n }\n if (status === null) {\n return err instanceof Error && !(err instanceof HttpClientError);\n }\n if (status === 408 || status === 429) {\n return true;\n }\n if (status >= 500) {\n return true;\n }\n return false;\n};\n\nexport function backoffDelayMs(\n attempt: number,\n policy: Required<Pick<RetryPolicy, 'initialDelayMs' | 'maxDelayMs'>>,\n): number {\n const base = policy.initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, policy.maxDelayMs);\n}\n\nexport function parseRetryAfter(\n headerValue: string | null,\n now: Date = new Date(),\n): Date | undefined {\n if (!headerValue) {\n return undefined;\n }\n const trimmed = headerValue.trim();\n if (/^\\d+$/.test(trimmed)) {\n return new Date(now.getTime() + Number(trimmed) * 1000);\n }\n const parsed = Date.parse(trimmed);\n if (Number.isNaN(parsed)) {\n return undefined;\n }\n return new Date(parsed);\n}\n\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) {\n return Promise.reject(signal.reason ?? new Error('Aborted'));\n }\n return new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal!.reason ?? new Error('Aborted'));\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n","export const HTTP_CLIENT_VERSION = '0.0.0';\n\nexport const DEFAULT_USER_AGENT = `rawdash-connector/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n\nexport function connectorUserAgent(connectorId: string): string {\n return `rawdash-connector-${connectorId}/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n}\n","import {\n AuthError,\n ClientBugError,\n HttpClientError,\n RateLimitError,\n TransientError,\n UpstreamBugError,\n errorForStatus,\n} from './errors';\nimport { defaultRetryOn, parseRetryAfter, sleep } from './retry';\nimport type { FetchLike, HttpMethod, HttpRequest, HttpResponse } from './types';\nimport { DEFAULT_USER_AGENT } from './version';\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_ATTEMPTS = 3;\nconst DEFAULT_INITIAL_DELAY_MS = 1000;\nconst DEFAULT_MAX_DELAY_MS = 60_000;\nconst OBSERVER_TIMEOUT_MS = 250;\n\nexport interface RequestObservation {\n url: string;\n method: HttpMethod;\n status: number;\n resource: string;\n requestId: string;\n body: unknown;\n}\n\nexport type RequestObserver = (\n event: RequestObservation,\n) => void | Promise<void>;\n\nexport interface RequestOptions {\n fetch?: FetchLike;\n observer?: RequestObserver;\n resource: string;\n requestId?: string;\n}\n\nasync function notifyObserver(\n observer: RequestObserver,\n event: RequestObservation,\n): Promise<void> {\n let result: void | Promise<void>;\n try {\n result = observer(event);\n } catch (err) {\n console.warn('[connector-shared] request observer threw:', err);\n return;\n }\n if (!(result instanceof Promise)) {\n return;\n }\n const guarded = result.catch((err) => {\n console.warn('[connector-shared] request observer rejected:', err);\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, OBSERVER_TIMEOUT_MS);\n });\n try {\n await Promise.race([guarded, timeout]);\n } finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n}\n\nfunction newRequestId(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) {\n return c.randomUUID();\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\nfunction mergeHeaders(\n defaults: Record<string, string>,\n overrides: Record<string, string> | undefined,\n): Record<string, string> {\n const merged: Record<string, string> = {};\n for (const [k, v] of Object.entries(defaults)) {\n merged[k.toLowerCase()] = v;\n }\n if (overrides) {\n for (const [k, v] of Object.entries(overrides)) {\n merged[k.toLowerCase()] = v;\n }\n }\n return merged;\n}\n\nfunction linkTimeoutSignal(\n parent: AbortSignal | undefined,\n timeoutMs: number,\n): { signal: AbortSignal; cancel: () => void } {\n const controller = new AbortController();\n const onParentAbort = () => {\n controller.abort(parent?.reason);\n };\n if (parent) {\n if (parent.aborted) {\n controller.abort(parent.reason);\n } else {\n parent.addEventListener('abort', onParentAbort, { once: true });\n }\n }\n const timer = setTimeout(() => {\n controller.abort(new Error(`Request timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n return {\n signal: controller.signal,\n cancel: () => {\n clearTimeout(timer);\n if (parent) {\n parent.removeEventListener('abort', onParentAbort);\n }\n },\n };\n}\n\nasync function readBody(res: Response, parseJson: boolean): Promise<unknown> {\n if (res.status === 204 || res.status === 205) {\n return null;\n }\n const contentType = res.headers.get('content-type') ?? '';\n if (parseJson && contentType.includes('application/json')) {\n const text = await res.text();\n if (text.length === 0) {\n return null;\n }\n return JSON.parse(text);\n }\n return res.text();\n}\n\nexport async function request<T = unknown>(\n req: HttpRequest,\n options: RequestOptions,\n): Promise<HttpResponse<T>> {\n const fetchImpl: FetchLike = options.fetch ?? (globalThis.fetch as FetchLike);\n const retry = req.retry ?? {};\n const maxAttempts = retry.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n const initialDelayMs = retry.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;\n const maxDelayMs = retry.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;\n const retryOn = retry.retryOn ?? defaultRetryOn;\n const timeoutMs = req.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const parseJson = req.parseJson ?? true;\n\n const headers = mergeHeaders(\n {\n 'User-Agent': DEFAULT_USER_AGENT,\n Accept: 'application/json',\n },\n req.headers,\n );\n\n let lastErr: Error | undefined;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n req.signal?.throwIfAborted();\n\n const { signal, cancel } = linkTimeoutSignal(req.signal, timeoutMs);\n let res: Response;\n try {\n res = await fetchImpl(req.url, {\n method: req.method ?? 'GET',\n headers,\n body: req.body as RequestInit['body'],\n signal,\n });\n } catch (err) {\n cancel();\n if (req.signal?.aborted) {\n throw req.signal.reason ?? err;\n }\n const error = err instanceof Error ? err : new Error(String(err));\n lastErr = error;\n if (attempt < maxAttempts - 1 && retryOn(null, error)) {\n const delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n await sleep(delay, req.signal);\n continue;\n }\n throw new TransientError(error.message);\n }\n cancel();\n\n const body = await readBody(res, parseJson);\n const httpResponse: HttpResponse<T> = {\n status: res.status,\n headers: res.headers,\n body: body as T,\n };\n if (req.rateLimit) {\n const state = req.rateLimit.parse(res.headers);\n if (state) {\n httpResponse.rateLimitState = state;\n }\n }\n\n if (options.observer) {\n await notifyObserver(options.observer, {\n url: req.url,\n method: req.method ?? 'GET',\n status: res.status,\n resource: options.resource,\n requestId: options.requestId ?? newRequestId(),\n body,\n });\n }\n\n if (res.ok) {\n return httpResponse;\n }\n\n const retryAfter = parseRetryAfter(res.headers.get('retry-after'));\n const message = `HTTP ${res.status} ${res.statusText} for ${req.method ?? 'GET'} ${req.url}`;\n const err = errorForStatus(message, httpResponse, retryAfter);\n\n if (\n attempt < maxAttempts - 1 &&\n retryOn(res.status, err) &&\n !(err instanceof AuthError) &&\n !(err instanceof ClientBugError)\n ) {\n lastErr = err;\n let delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n if (err instanceof RateLimitError && retryAfter) {\n const wait = retryAfter.getTime() - Date.now();\n if (wait > 0) {\n delay = Math.min(wait, maxDelayMs);\n }\n }\n await sleep(delay, req.signal);\n continue;\n }\n\n throw err;\n }\n\n throw lastErr ?? new UpstreamBugError('Exhausted retry attempts');\n}\n\nfunction computeDelay(\n attempt: number,\n initialDelayMs: number,\n maxDelayMs: number,\n): number {\n const base = initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, maxDelayMs);\n}\n\nexport { HttpClientError };\n","export interface RateLimitState {\n remaining: number;\n resetAt: Date;\n}\n\nexport interface RateLimitPolicy {\n parse(headers: Headers): RateLimitState | null;\n}\n\nexport interface StandardRateLimitPolicyConfig {\n remainingHeader: string;\n resetHeader: string;\n resetUnit: 's' | 'ms';\n resetFallbackMs?: number;\n}\n\nexport function standardRateLimitPolicy(\n config: StandardRateLimitPolicyConfig,\n): RateLimitPolicy {\n const { remainingHeader, resetHeader, resetUnit, resetFallbackMs } = config;\n const multiplier = resetUnit === 's' ? 1000 : 1;\n return {\n parse(h) {\n const remainingRaw = h.get(remainingHeader);\n if (remainingRaw === null || remainingRaw.trim() === '') {\n return null;\n }\n const remaining = Number(remainingRaw);\n if (!Number.isFinite(remaining)) {\n return null;\n }\n const resetRaw = h.get(resetHeader);\n if (resetRaw === null) {\n if (resetFallbackMs === undefined) {\n return null;\n }\n return {\n remaining,\n resetAt: new Date(Date.now() + resetFallbackMs),\n };\n }\n if (resetRaw.trim() === '') {\n return null;\n }\n const reset = Number(resetRaw);\n if (!Number.isFinite(reset) || reset < 0) {\n return null;\n }\n const resetMs = reset * multiplier;\n if (!Number.isFinite(resetMs)) {\n return null;\n }\n return { remaining, resetAt: new Date(resetMs) };\n },\n };\n}\n","export async function mapWithConcurrency<T, R>(\n items: readonly T[],\n concurrency: number,\n fn: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const results = new Array<R>(items.length);\n if (items.length === 0) {\n return results;\n }\n const normalized = Number.isFinite(concurrency) ? Math.floor(concurrency) : 1;\n const limit = Math.max(1, Math.min(normalized, items.length));\n let next = 0;\n let failed = false;\n\n async function worker(): Promise<void> {\n while (!failed) {\n const i = next++;\n if (i >= items.length) {\n return;\n }\n try {\n results[i] = await fn(items[i]!, i);\n } catch (err) {\n failed = true;\n throw err;\n }\n }\n }\n\n const workers: Promise<void>[] = [];\n for (let w = 0; w < limit; w++) {\n workers.push(worker());\n }\n await Promise.all(workers);\n return results;\n}\n","export interface SanitizeAllowedUrlOptions {\n url: string | null;\n host: string;\n pathname: string;\n protocol?: 'https:' | 'http:';\n}\n\nexport function sanitizeAllowedUrl(\n options: SanitizeAllowedUrlOptions,\n): string | null {\n const { url, host, pathname, protocol = 'https:' } = options;\n if (url === null) {\n return null;\n }\n try {\n const u = new URL(url);\n if (u.protocol !== protocol || u.host !== host || u.pathname !== pathname) {\n return null;\n }\n return u.toString();\n } catch {\n return null;\n }\n}\n","export type EpochUnit = 'ms' | 's' | 'iso';\n\nexport function parseEpoch(\n value: number | string | null | undefined,\n unit: EpochUnit,\n): number | null {\n if (value === null || value === undefined) {\n return null;\n }\n if (unit === 'iso') {\n if (typeof value !== 'string') {\n return null;\n }\n const ms = new Date(value).getTime();\n return Number.isFinite(ms) ? ms : null;\n }\n if (typeof value === 'string' && value.trim() === '') {\n return null;\n }\n const n = typeof value === 'number' ? value : Number(value);\n if (!Number.isFinite(n)) {\n return null;\n }\n const result = unit === 's' ? n * 1000 : n;\n return Number.isFinite(result) ? result : null;\n}\n","import { request } from './request';\nimport type { HttpRequest } from './types';\n\nexport function parseLinkHeader(header: string | null): Record<string, string> {\n if (!header) {\n return {};\n }\n const result: Record<string, string> = {};\n for (const part of header.split(',')) {\n const match = part.match(/<([^>]+)>\\s*;\\s*rel=\"([^\"]+)\"/);\n if (match) {\n result[match[2]!] = match[1]!;\n }\n }\n return result;\n}\n\nexport async function* paginateLink<T>(\n initial: HttpRequest,\n parse: (body: unknown) => T[],\n options: { resource: string },\n): AsyncIterable<T> {\n let next: string | null = initial.url;\n while (next) {\n const res: Awaited<ReturnType<typeof request>> = await request(\n {\n ...initial,\n url: next,\n },\n { resource: options.resource },\n );\n for (const item of parse(res.body)) {\n yield item;\n }\n const links = parseLinkHeader(res.headers.get('link'));\n next = links['next'] ?? null;\n }\n}\n\nexport async function* paginateCursor<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; nextCursor: string | null },\n buildNext: (req: HttpRequest, cursor: string) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let req: HttpRequest = initial;\n while (true) {\n const res = await request(req, { resource: options.resource });\n const { items, nextCursor } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!nextCursor) {\n return;\n }\n req = buildNext(req, nextCursor);\n }\n}\n\nexport async function* paginatePage<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; hasMore: boolean },\n buildPage: (req: HttpRequest, page: number) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let page = 1;\n while (true) {\n const req = page === 1 ? initial : buildPage(initial, page);\n const res = await request(req, { resource: options.resource });\n const { items, hasMore } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!hasMore || items.length === 0) {\n return;\n }\n page++;\n }\n}\n","export type LogFields = Record<string, unknown>;\n\nexport interface ConnectorLogger {\n info(event: string, fields?: LogFields): void;\n warn(event: string, fields?: LogFields): void;\n}\n\nexport interface ConnectorLoggerOptions {\n scope: string;\n}\n\nconst MAX_VALUE_LEN = 120;\n\nfunction truncate(s: string, max = MAX_VALUE_LEN): string {\n if (s.length <= max) {\n return s;\n }\n return `${s.slice(0, max - 1)}…`;\n}\n\nfunction formatValue(value: unknown): string {\n if (value === null) {\n return 'null';\n }\n if (value === undefined) {\n return '';\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n if (typeof value === 'string') {\n const t = truncate(value);\n if (/[\\s\"=]/.test(t)) {\n return JSON.stringify(t);\n }\n return t;\n }\n if (typeof value === 'bigint') {\n return value.toString();\n }\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch {\n json = undefined;\n }\n return truncate(json ?? String(value));\n}\n\nexport function formatLogFields(fields?: LogFields): string {\n if (!fields) {\n return '';\n }\n const parts: string[] = [];\n for (const [k, v] of Object.entries(fields)) {\n if (v === undefined) {\n continue;\n }\n parts.push(`${k}=${formatValue(v)}`);\n }\n return parts.length > 0 ? ` ${parts.join(' ')}` : '';\n}\n\nexport function formatLogLine(\n scope: string,\n event: string,\n fields?: LogFields,\n): string {\n return `[${scope}] ${event}${formatLogFields(fields)}`;\n}\n\nexport function createDefaultConnectorLogger(\n opts: ConnectorLoggerOptions,\n): ConnectorLogger {\n return {\n info(event, fields) {\n console.info(formatLogLine(opts.scope, event, fields));\n },\n warn(event, fields) {\n console.warn(formatLogLine(opts.scope, event, fields));\n },\n };\n}\n\nconst NOOP_LOGGER: ConnectorLogger = {\n info() {},\n warn() {},\n};\n\nexport function noopConnectorLogger(): ConnectorLogger {\n return NOOP_LOGGER;\n}\n","import {\n type HttpResponse,\n connectorUserAgent,\n parseEpoch,\n} from '@rawdash/connector-shared';\nimport {\n BaseConnector,\n type ChunkedSyncCursor,\n type ConnectorContext,\n type ConnectorDoc,\n type CredentialsSchema,\n type JSONValue,\n type StorageHandle,\n type SyncOptions,\n type SyncResult,\n defineConfigFields,\n defineConnectorDoc,\n defineResources,\n makeChunkedCursorGuard,\n paginateChunked,\n schemasFromResources,\n selectActivePhases,\n} from '@rawdash/core';\nimport { z } from 'zod';\n\nexport const configFields = defineConfigFields(\n z.object({\n apiToken: z.object({ $secret: z.string() }).meta({\n label: 'API Token',\n description:\n 'CircleCI personal API token (read-only is sufficient). Create one at CircleCI -> User Settings -> Personal API Tokens.',\n placeholder: 'circleci_token',\n secret: true,\n }),\n projectSlugs: z\n .array(z.string().min(1))\n .nonempty()\n .refine((slugs) => new Set(slugs).size === slugs.length, {\n error: 'Project slugs must be unique.',\n })\n .meta({\n label: 'Project slugs',\n description:\n \"CircleCI project slugs to sync, e.g. 'gh/my-org/my-repo' or 'circleci/<orgId>/<projectId>'.\",\n }),\n branch: z.string().min(1).optional().meta({\n label: 'Branch (optional)',\n description:\n 'Restrict pipeline sync to a single branch. Omit to sync all branches.',\n placeholder: 'main',\n }),\n resources: z\n .array(z.enum(['pipelines', 'workflows', 'jobs', 'pipeline_events']))\n .nonempty()\n .optional()\n .meta({\n label: 'Resources',\n description:\n 'Which CircleCI resources to sync. Omit to sync pipelines, workflows, and pipeline_events (jobs are off by default because they add a per-workflow API call). Workflows must be fetched whenever workflows, jobs, or pipeline_events are enabled.',\n }),\n pipelinesLookbackDays: z\n .number()\n .int()\n .positive()\n .max(365)\n .optional()\n .meta({\n label: 'Pipelines lookback (days)',\n description:\n 'How many days back to fetch pipelines on a full sync. Defaults to 30. CircleCI does not expose a server-side since filter, so the connector paginates newest-first and stops once it crosses this window.',\n placeholder: '30',\n }),\n }),\n);\n\nexport type CircleCIResource =\n | 'pipelines'\n | 'workflows'\n | 'jobs'\n | 'pipeline_events';\n\nexport interface CircleCISettings {\n projectSlugs: readonly string[];\n branch?: string;\n resources?: readonly CircleCIResource[];\n pipelinesLookbackDays?: number;\n}\n\nconst circleciCredentials = {\n apiToken: {\n description: 'CircleCI personal API token',\n auth: 'required' as const,\n },\n} satisfies CredentialsSchema;\n\ntype CircleCICredentials = typeof circleciCredentials;\n\nexport const doc: ConnectorDoc = defineConnectorDoc({\n displayName: 'CircleCI',\n category: 'engineering',\n brandColor: '#161616',\n tagline:\n 'Sync CircleCI pipelines, workflows, jobs, and workflow state-transition events so build success rate and duration land on dashboards.',\n vendor: {\n name: 'CircleCI',\n apiDocs: 'https://circleci.com/docs/api/v2/',\n website: 'https://circleci.com',\n },\n auth: {\n summary:\n 'A CircleCI personal API token is required. Tokens authenticate against the v2 REST API and inherit the creating user permissions on the configured projects.',\n setup: [\n 'Open CircleCI -> User Settings -> Personal API Tokens (https://app.circleci.com/settings/user/tokens).',\n 'Create a token with a descriptive name (e.g. \"rawdash sync\") and copy the value.',\n 'Store it as a secret and reference it from the connector config as `apiToken: secret(\"CIRCLECI_API_TOKEN\")`.',\n \"Set `projectSlugs` to the projects you want to sync, e.g. ['gh/my-org/my-repo'].\",\n ],\n },\n rateLimit:\n 'CircleCI enforces a per-token rate limit of roughly 3,500 requests per hour. The connector paginates pipelines newest-first and fans out one extra request per pipeline for workflows (and one more per workflow for jobs when enabled), so cap `projectSlugs` and `pipelinesLookbackDays` accordingly.',\n limitations: [\n 'CircleCI v2 has no server-side since filter for pipelines, so the connector paginates newest-first and stops once it crosses `pipelinesLookbackDays` (default 30).',\n 'The `jobs` resource is off by default because it adds an extra API call per workflow. Enable it explicitly in `resources` if you need per-job entities.',\n 'Insights API (pre-aggregated workflow stats) and the self-hosted CircleCI Server are out of scope for v1.',\n ],\n});\n\nconst PHASE_ORDER = ['pipelines'] as const;\n\ntype CircleCIPhase = (typeof PHASE_ORDER)[number];\n\ntype CircleCISyncCursor = ChunkedSyncCursor<CircleCIPhase, string>;\n\nconst isCircleCISyncCursor = makeChunkedCursorGuard(PHASE_ORDER);\n\nconst pageCursorSchema = z.object({\n slug: z.string().min(1),\n token: z.string().nullable(),\n});\n\ninterface CirclePageCursor {\n slug: string;\n token: string | null;\n}\n\ninterface CircleCIPipeline {\n id: string;\n number: number;\n project_slug: string;\n state: string;\n created_at: string;\n updated_at: string;\n trigger?: {\n type?: string | null;\n actor?: { login?: string | null } | null;\n } | null;\n vcs?: {\n revision?: string | null;\n branch?: string | null;\n tag?: string | null;\n target_repository_url?: string | null;\n origin_repository_url?: string | null;\n } | null;\n}\n\ninterface CircleCIPipelinesResponse {\n items: CircleCIPipeline[];\n next_page_token: string | null;\n}\n\ninterface CircleCIWorkflow {\n id: string;\n name: string;\n pipeline_id: string;\n pipeline_number?: number;\n project_slug: string;\n status:\n | 'success'\n | 'running'\n | 'not_run'\n | 'failed'\n | 'error'\n | 'failing'\n | 'on_hold'\n | 'canceled'\n | 'unauthorized'\n | string;\n created_at: string;\n stopped_at?: string | null;\n started_by?: string | null;\n tag?: string | null;\n}\n\ninterface CircleCIWorkflowsResponse {\n items: CircleCIWorkflow[];\n next_page_token: string | null;\n}\n\ninterface CircleCIJob {\n id: string;\n name: string;\n status: string;\n type?: string;\n job_number?: number | null;\n started_at?: string | null;\n stopped_at?: string | null;\n project_slug?: string;\n dependencies?: string[];\n}\n\ninterface CircleCIJobsResponse {\n items: CircleCIJob[];\n next_page_token: string | null;\n}\n\nconst idString = z.string().min(1);\nconst isoString = z.string().min(1);\n\nconst pipelineSchema = z.object({\n id: idString,\n number: z.number().int().nonnegative(),\n project_slug: idString,\n state: z.string().min(1),\n created_at: isoString,\n updated_at: isoString,\n trigger: z\n .object({\n type: z.string().nullable().optional(),\n actor: z\n .object({ login: z.string().nullable().optional() })\n .nullable()\n .optional(),\n })\n .nullable()\n .optional(),\n vcs: z\n .object({\n revision: z.string().nullable().optional(),\n branch: z.string().nullable().optional(),\n tag: z.string().nullable().optional(),\n })\n .nullable()\n .optional(),\n});\n\nconst pipelinesResponseSchema = z.object({\n items: z.array(pipelineSchema),\n next_page_token: z.string().nullable(),\n});\n\nconst workflowSchema = z.object({\n id: idString,\n name: z.string().min(1),\n pipeline_id: idString,\n project_slug: idString,\n status: z.string().min(1),\n created_at: isoString,\n stopped_at: z.string().nullable().optional(),\n started_by: z.string().nullable().optional(),\n});\n\nconst workflowsResponseSchema = z.object({\n items: z.array(workflowSchema),\n next_page_token: z.string().nullable(),\n});\n\nconst jobSchema = z.object({\n id: idString,\n name: z.string().min(1),\n status: z.string().min(1),\n type: z.string().optional(),\n job_number: z.number().int().nullable().optional(),\n started_at: z.string().nullable().optional(),\n stopped_at: z.string().nullable().optional(),\n project_slug: z.string().optional(),\n});\n\nconst jobsResponseSchema = z.object({\n items: z.array(jobSchema),\n next_page_token: z.string().nullable(),\n});\n\nexport const circleciResources = defineResources({\n circleci_pipeline: {\n shape: 'entity',\n description:\n 'CircleCI pipelines with state, trigger, git ref, project slug, and create/update timestamps.',\n endpoint: 'GET /api/v2/project/{project_slug}/pipeline',\n notes:\n 'Pipelines are paginated newest-first; the connector stops once it crosses `pipelinesLookbackDays`.',\n responses: { pipelines: pipelinesResponseSchema },\n },\n circleci_workflow: {\n shape: 'entity',\n description:\n 'Workflows belonging to each pipeline, including status, name, and start/stop timestamps. Fetched per pipeline with one extra API call.',\n endpoint: 'GET /api/v2/pipeline/{pipeline_id}/workflow',\n responses: { workflows: workflowsResponseSchema },\n },\n circleci_job: {\n shape: 'entity',\n description:\n 'Jobs belonging to each workflow, including status, type, and start/stop timestamps. Off by default; enable via `resources` because it adds an API call per workflow.',\n endpoint: 'GET /api/v2/workflow/{workflow_id}/job',\n responses: { jobs: jobsResponseSchema },\n },\n circleci_pipeline_event: {\n shape: 'event',\n description:\n 'Each workflow emitted as a time-bounded event spanning its created_at to stopped_at, carrying the same status, project, and pipeline attributes.',\n endpoint: 'GET /api/v2/pipeline/{pipeline_id}/workflow',\n },\n});\n\nconst CIRCLECI_API_BASE = 'https://circleci.com/api/v2';\nconst DEFAULT_RESOURCES: readonly CircleCIResource[] = [\n 'pipelines',\n 'workflows',\n 'pipeline_events',\n];\nconst DEFAULT_LOOKBACK_DAYS = 30;\nconst MS_PER_DAY = 24 * 60 * 60 * 1000;\n\nexport const id = 'circleci';\n\nexport class CircleCIConnector extends BaseConnector<\n CircleCISettings,\n CircleCICredentials\n> {\n static readonly id = id;\n\n static readonly resources = circleciResources;\n\n static readonly schemas = schemasFromResources(circleciResources);\n\n static create(input: unknown, ctx?: ConnectorContext): CircleCIConnector {\n const parsed = configFields.parse(input);\n return new CircleCIConnector(\n {\n projectSlugs: parsed.projectSlugs,\n branch: parsed.branch,\n resources: parsed.resources ?? DEFAULT_RESOURCES,\n pipelinesLookbackDays: parsed.pipelinesLookbackDays,\n },\n { apiToken: parsed.apiToken },\n ctx,\n );\n }\n\n readonly id = id;\n override readonly credentials = circleciCredentials;\n\n private buildHeaders(): Record<string, string> {\n return {\n 'Circle-Token': this.creds.apiToken,\n Accept: 'application/json',\n 'User-Agent': connectorUserAgent('circleci'),\n };\n }\n\n private fetch<T>(\n url: string,\n resource: string,\n signal?: AbortSignal,\n ): Promise<HttpResponse<T>> {\n return this.get<T>(url, {\n resource,\n headers: this.buildHeaders(),\n signal,\n });\n }\n\n private activePhases(): CircleCIPhase[] {\n return selectActivePhases<CircleCIResource, CircleCIPhase>(\n () => 'pipelines',\n PHASE_ORDER,\n this.settings.resources,\n );\n }\n\n private workflowsNeeded(): boolean {\n return (\n this.isResourceEnabled('workflows') ||\n this.isResourceEnabled('pipeline_events') ||\n this.isResourceEnabled('jobs')\n );\n }\n\n private slugSet(): Set<string> {\n return new Set(this.settings.projectSlugs);\n }\n\n private decodePageCursor(page: string | null): CirclePageCursor | null {\n if (page === null) {\n return null;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(page);\n } catch {\n return null;\n }\n const res = pageCursorSchema.safeParse(parsed);\n if (!res.success) {\n return null;\n }\n if (!this.slugSet().has(res.data.slug)) {\n return null;\n }\n return res.data;\n }\n\n private encodePageCursor(cursor: CirclePageCursor): string {\n return JSON.stringify(cursor);\n }\n\n private resolveCursor(cursor: unknown): CircleCISyncCursor | undefined {\n if (!isCircleCISyncCursor(cursor)) {\n return undefined;\n }\n if (cursor.page === null) {\n return { phase: cursor.phase, page: null };\n }\n const decoded = this.decodePageCursor(cursor.page);\n if (!decoded) {\n return { phase: cursor.phase, page: null };\n }\n return { phase: cursor.phase, page: this.encodePageCursor(decoded) };\n }\n\n private buildPipelinesUrl(slug: string, token: string | null): string {\n const u = new URL(\n `${CIRCLECI_API_BASE}/project/${encodeURI(slug)}/pipeline`,\n );\n if (this.settings.branch !== undefined) {\n u.searchParams.set('branch', this.settings.branch);\n }\n if (token !== null) {\n u.searchParams.set('page-token', token);\n }\n return u.toString();\n }\n\n private buildWorkflowsUrl(pipelineId: string, token: string | null): string {\n const u = new URL(\n `${CIRCLECI_API_BASE}/pipeline/${encodeURIComponent(pipelineId)}/workflow`,\n );\n if (token !== null) {\n u.searchParams.set('page-token', token);\n }\n return u.toString();\n }\n\n private buildJobsUrl(workflowId: string, token: string | null): string {\n const u = new URL(\n `${CIRCLECI_API_BASE}/workflow/${encodeURIComponent(workflowId)}/job`,\n );\n if (token !== null) {\n u.searchParams.set('page-token', token);\n }\n return u.toString();\n }\n\n private nextSlug(currentSlug: string): string | null {\n const slugs = this.settings.projectSlugs;\n const idx = slugs.indexOf(currentSlug);\n if (idx < 0 || idx >= slugs.length - 1) {\n return null;\n }\n return slugs[idx + 1] ?? null;\n }\n\n private cutoffMs(options: SyncOptions): number | null {\n if (options.since) {\n const ms = parseEpoch(options.since, 'iso');\n if (ms !== null) {\n return ms;\n }\n }\n const days = this.settings.pipelinesLookbackDays ?? DEFAULT_LOOKBACK_DAYS;\n return Date.now() - days * MS_PER_DAY;\n }\n\n private async fetchAllWorkflowsForPipeline(\n pipelineId: string,\n signal: AbortSignal | undefined,\n ): Promise<CircleCIWorkflow[]> {\n const out: CircleCIWorkflow[] = [];\n let token: string | null = null;\n do {\n const url = this.buildWorkflowsUrl(pipelineId, token);\n const res = await this.fetch<CircleCIWorkflowsResponse>(\n url,\n 'workflows',\n signal,\n );\n out.push(...res.body.items);\n token = res.body.next_page_token ?? null;\n } while (token !== null);\n return out;\n }\n\n private async fetchAllJobsForWorkflow(\n workflowId: string,\n signal: AbortSignal | undefined,\n ): Promise<CircleCIJob[]> {\n const out: CircleCIJob[] = [];\n let token: string | null = null;\n do {\n const url = this.buildJobsUrl(workflowId, token);\n const res = await this.fetch<CircleCIJobsResponse>(url, 'jobs', signal);\n out.push(...res.body.items);\n token = res.body.next_page_token ?? null;\n } while (token !== null);\n return out;\n }\n\n private async fetchPipelinesPage(\n page: string | null,\n options: SyncOptions,\n signal: AbortSignal | undefined,\n ): Promise<{ items: PipelinePageBatch[]; next: string | null }> {\n const decoded = page !== null ? this.decodePageCursor(page) : null;\n const slug = decoded?.slug ?? this.settings.projectSlugs[0]!;\n const token = decoded?.token ?? null;\n const url = this.buildPipelinesUrl(slug, token);\n const res = await this.fetch<CircleCIPipelinesResponse>(\n url,\n 'pipelines',\n signal,\n );\n\n const cutoff = this.cutoffMs(options);\n const pipelines = res.body.items;\n\n const inWindow: CircleCIPipeline[] = [];\n let crossedCutoff = false;\n for (const p of pipelines) {\n const updatedMs = parseEpoch(p.updated_at, 'iso');\n if (cutoff !== null && updatedMs !== null && updatedMs < cutoff) {\n crossedCutoff = true;\n continue;\n }\n inWindow.push(p);\n }\n\n const workflowsBySlug = new Map<string, CircleCIWorkflow[]>();\n const jobsByWorkflow = new Map<string, CircleCIJob[]>();\n if (this.workflowsNeeded()) {\n for (const p of inWindow) {\n signal?.throwIfAborted();\n const wfs = await this.fetchAllWorkflowsForPipeline(p.id, signal);\n workflowsBySlug.set(p.id, wfs);\n if (this.isResourceEnabled('jobs')) {\n for (const wf of wfs) {\n signal?.throwIfAborted();\n const jobs = await this.fetchAllJobsForWorkflow(wf.id, signal);\n jobsByWorkflow.set(wf.id, jobs);\n }\n }\n }\n }\n\n const batch: PipelinePageBatch = {\n slug,\n pipelines: inWindow,\n workflowsByPipeline: workflowsBySlug,\n jobsByWorkflow,\n };\n\n let next: string | null;\n const nextToken = res.body.next_page_token ?? null;\n if (nextToken !== null && !crossedCutoff) {\n next = this.encodePageCursor({ slug, token: nextToken });\n } else {\n const nextSlug = this.nextSlug(slug);\n next =\n nextSlug !== null\n ? this.encodePageCursor({ slug: nextSlug, token: null })\n : null;\n }\n\n return { items: [batch], next };\n }\n\n private async writeBatch(\n storage: StorageHandle,\n batch: PipelinePageBatch,\n ): Promise<void> {\n const writePipelines = this.isResourceEnabled('pipelines');\n const writeWorkflows = this.isResourceEnabled('workflows');\n const writeJobs = this.isResourceEnabled('jobs');\n const writeEvents = this.isResourceEnabled('pipeline_events');\n\n for (const p of batch.pipelines) {\n const createdMs = parseEpoch(p.created_at, 'iso');\n const updatedMs = parseEpoch(p.updated_at, 'iso');\n if (createdMs === null || updatedMs === null) {\n console.warn(\n `[connector-circleci] skipping pipeline ${p.id} with unparseable timestamps`,\n );\n continue;\n }\n\n if (writePipelines) {\n await storage.entity({\n type: 'circleci_pipeline',\n id: p.id,\n attributes: {\n pipelineId: p.id,\n number: p.number,\n projectSlug: p.project_slug,\n state: p.state,\n branch: p.vcs?.branch ?? null,\n revision: p.vcs?.revision ?? null,\n tag: p.vcs?.tag ?? null,\n triggerType: p.trigger?.type ?? null,\n triggerActor: p.trigger?.actor?.login ?? null,\n createdAt: createdMs,\n updatedAt: updatedMs,\n },\n updated_at: updatedMs,\n });\n }\n\n const workflows = batch.workflowsByPipeline.get(p.id) ?? [];\n for (const wf of workflows) {\n const wfCreatedMs = parseEpoch(wf.created_at, 'iso');\n const wfStoppedMs = parseEpoch(wf.stopped_at ?? null, 'iso');\n if (wfCreatedMs === null) {\n console.warn(\n `[connector-circleci] skipping workflow ${wf.id} with unparseable created_at`,\n );\n continue;\n }\n const durationMs =\n wfStoppedMs !== null && wfStoppedMs >= wfCreatedMs\n ? wfStoppedMs - wfCreatedMs\n : null;\n const wfAttrs: Record<string, JSONValue> = {\n workflowId: wf.id,\n pipelineId: wf.pipeline_id,\n projectSlug: wf.project_slug,\n name: wf.name,\n status: wf.status,\n startedBy: wf.started_by ?? null,\n createdAt: wfCreatedMs,\n stoppedAt: wfStoppedMs,\n durationMs,\n };\n\n if (writeWorkflows) {\n await storage.entity({\n type: 'circleci_workflow',\n id: wf.id,\n attributes: wfAttrs,\n updated_at: wfStoppedMs ?? wfCreatedMs,\n });\n }\n\n if (writeEvents) {\n await storage.event({\n name: 'circleci_pipeline_event',\n start_ts: wfCreatedMs,\n end_ts: wfStoppedMs,\n attributes: wfAttrs,\n });\n }\n\n if (writeJobs) {\n const jobs = batch.jobsByWorkflow.get(wf.id) ?? [];\n for (const job of jobs) {\n const startedMs = parseEpoch(job.started_at ?? null, 'iso');\n const stoppedMs = parseEpoch(job.stopped_at ?? null, 'iso');\n const jobDurationMs =\n startedMs !== null && stoppedMs !== null && stoppedMs >= startedMs\n ? stoppedMs - startedMs\n : null;\n await storage.entity({\n type: 'circleci_job',\n id: job.id,\n attributes: {\n jobId: job.id,\n workflowId: wf.id,\n pipelineId: wf.pipeline_id,\n projectSlug: job.project_slug ?? wf.project_slug,\n name: job.name,\n status: job.status,\n type: job.type ?? null,\n jobNumber: job.job_number ?? null,\n startedAt: startedMs,\n stoppedAt: stoppedMs,\n durationMs: jobDurationMs,\n },\n updated_at: stoppedMs ?? startedMs ?? wfCreatedMs,\n });\n }\n }\n }\n }\n }\n\n async sync(\n options: SyncOptions,\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<SyncResult> {\n const cursor = this.resolveCursor(options.cursor);\n const isFull = options.mode === 'full';\n const phases = this.activePhases();\n\n return paginateChunked<CircleCIPhase, string>({\n phases,\n cursor,\n signal,\n logger: this.logger,\n fetchPage: async (_phase, page, sig) =>\n this.fetchPipelinesPage(page, options, sig),\n writeBatch: async (_phase, items, page) => {\n if (isFull && page === null) {\n if (this.isResourceEnabled('pipelines')) {\n await storage.entities([], { types: ['circleci_pipeline'] });\n }\n if (this.isResourceEnabled('workflows')) {\n await storage.entities([], { types: ['circleci_workflow'] });\n }\n if (this.isResourceEnabled('jobs')) {\n await storage.entities([], { types: ['circleci_job'] });\n }\n if (this.isResourceEnabled('pipeline_events')) {\n await storage.events([], { names: ['circleci_pipeline_event'] });\n }\n }\n for (const batch of items as PipelinePageBatch[]) {\n await this.writeBatch(storage, batch);\n }\n },\n });\n }\n}\n\ninterface PipelinePageBatch {\n slug: string;\n pipelines: CircleCIPipeline[];\n workflowsByPipeline: Map<string, CircleCIWorkflow[]>;\n jobsByWorkflow: Map<string, CircleCIJob[]>;\n}\n","import { CircleCIConnector } from './circleci';\n\nexport {\n circleciResources as resources,\n CircleCIConnector,\n configFields,\n doc,\n id,\n} from './circleci';\nexport type { CircleCIResource, CircleCISettings } from './circleci';\nexport default CircleCIConnector;\n"],"mappings":";AEAO,IAAM,sBAAsB;AAE5B,IAAM,qBAAqB,qBAAqB,mBAAmB;AAEnE,SAAS,mBAAmB,aAA6B;AAC9D,SAAO,qBAAqB,WAAW,IAAI,mBAAmB;AAChE;AKJO,SAAS,WACd,OACA,MACe;AACf,MAAI,UAAU,QAAQ,UAAU,QAAW;AACzC,WAAO;EACT;AACA,MAAI,SAAS,OAAO;AAClB,QAAI,OAAO,UAAU,UAAU;AAC7B,aAAO;IACT;AACA,UAAM,KAAK,IAAI,KAAK,KA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ector-circleci",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.20.0",
|
|
4
4
|
"description": "Rawdash connector for CircleCI — pipelines, workflows, jobs, and workflow state-transition events",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
@@ -22,22 +22,22 @@
|
|
|
22
22
|
"import": "./dist/index.js"
|
|
23
23
|
}
|
|
24
24
|
},
|
|
25
|
-
"scripts": {
|
|
26
|
-
"build": "tsup",
|
|
27
|
-
"typecheck": "tsc --noEmit",
|
|
28
|
-
"lint": "eslint src",
|
|
29
|
-
"test": "vitest run"
|
|
30
|
-
},
|
|
31
25
|
"dependencies": {
|
|
32
|
-
"
|
|
33
|
-
"
|
|
26
|
+
"zod": "^4.4.3",
|
|
27
|
+
"@rawdash/core": "0.20.0"
|
|
34
28
|
},
|
|
35
29
|
"devDependencies": {
|
|
36
|
-
"@rawdash/connector-shared": "workspace:*",
|
|
37
|
-
"@rawdash/connector-test-utils": "workspace:*",
|
|
38
30
|
"fast-check": "^4.8.0",
|
|
39
31
|
"tsup": "^8.0.0",
|
|
40
32
|
"typescript": "^5.7.2",
|
|
41
|
-
"vitest": "^4.1.4"
|
|
33
|
+
"vitest": "^4.1.4",
|
|
34
|
+
"@rawdash/connector-shared": "0.3.1",
|
|
35
|
+
"@rawdash/connector-test-utils": "0.0.7"
|
|
36
|
+
},
|
|
37
|
+
"scripts": {
|
|
38
|
+
"build": "tsup",
|
|
39
|
+
"typecheck": "tsc --noEmit",
|
|
40
|
+
"lint": "eslint src",
|
|
41
|
+
"test": "vitest run"
|
|
42
42
|
}
|
|
43
|
-
}
|
|
43
|
+
}
|