@rawdash/connector-netlify 0.19.0 → 0.21.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 +5 -1
- 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
|
@@ -457,6 +457,7 @@ var NetlifyConnector = class _NetlifyConnector extends BaseConnector {
|
|
|
457
457
|
return;
|
|
458
458
|
}
|
|
459
459
|
const batches = items;
|
|
460
|
+
const eventsById = /* @__PURE__ */ new Map();
|
|
460
461
|
for (const batch of batches) {
|
|
461
462
|
for (const d of batch.items) {
|
|
462
463
|
const createdMs = parseEpoch(d.created_at, "iso");
|
|
@@ -501,7 +502,7 @@ var NetlifyConnector = class _NetlifyConnector extends BaseConnector {
|
|
|
501
502
|
});
|
|
502
503
|
}
|
|
503
504
|
if (writeEvents) {
|
|
504
|
-
|
|
505
|
+
eventsById.set(`${batch.siteId}:${d.id}`, {
|
|
505
506
|
name: "netlify_deploy_event",
|
|
506
507
|
start_ts: createdMs,
|
|
507
508
|
end_ts: publishedMs,
|
|
@@ -510,6 +511,9 @@ var NetlifyConnector = class _NetlifyConnector extends BaseConnector {
|
|
|
510
511
|
}
|
|
511
512
|
}
|
|
512
513
|
}
|
|
514
|
+
for (const event of eventsById.values()) {
|
|
515
|
+
await storage.event(event);
|
|
516
|
+
}
|
|
513
517
|
}
|
|
514
518
|
// -------------------------------------------------------------------------
|
|
515
519
|
// sync
|
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/map-concurrent.ts","../../../connector-shared/src/sanitize.ts","../../../connector-shared/src/epoch.ts","../../../connector-shared/src/pagination.ts","../../../connector-shared/src/logger.ts","../src/netlify.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 parseLinkHeader,\n standardRateLimitPolicy,\n} from '@rawdash/connector-shared';\nimport {\n BaseConnector,\n type ChunkedSyncCursor,\n type ConnectorContext,\n type ConnectorDoc,\n type CredentialsSchema,\n type FetchPageResult,\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 'Netlify personal access token. Create one at Netlify -> User Settings -> Applications -> Personal access tokens.',\n placeholder: 'nfp_...',\n secret: true,\n }),\n siteIds: z.array(z.string().min(1)).nonempty().optional().meta({\n label: 'Site IDs (optional)',\n description:\n 'Restrict the sync to specific Netlify site IDs (the UUID-style id from the site Admin panel). Omit to sync every site the token can see.',\n }),\n resources: z\n .array(z.enum(['sites', 'deploys', 'deploy_events']))\n .nonempty()\n .optional()\n .meta({\n label: 'Resources',\n description:\n \"Which Netlify resources to sync. Omit to sync all of them. 'deploy_events' rides the 'deploys' phase - enabling it without 'deploys' still fetches deploys but skips writing deploy entities.\",\n }),\n deploysLookbackDays: z.number().int().positive().max(365).optional().meta({\n label: 'Deploys lookback (days)',\n description:\n 'Cap the deploy backfill window to this many days. If unset, the connector fetches every deploy the API returns (newest-first). Netlify has no server-side date filter on the deploys endpoint, so the cutoff is applied client-side and short-circuits pagination once a page is entirely older than the cutoff.',\n placeholder: '30',\n }),\n }),\n);\n\nexport type NetlifyResource = 'sites' | 'deploys' | 'deploy_events';\n\nexport interface NetlifySettings {\n siteIds?: readonly string[];\n resources?: readonly NetlifyResource[];\n deploysLookbackDays?: number;\n}\n\nconst netlifyCredentials = {\n apiToken: {\n description: 'Netlify personal access token',\n auth: 'required' as const,\n },\n} satisfies CredentialsSchema;\n\ntype NetlifyCredentials = typeof netlifyCredentials;\n\n// ---------------------------------------------------------------------------\n// Connector documentation metadata\n// ---------------------------------------------------------------------------\n\nexport const doc: ConnectorDoc = defineConnectorDoc({\n displayName: 'Netlify',\n category: 'infrastructure',\n brandColor: '#00C7B7',\n tagline:\n 'Sync Netlify sites and deploys - including build state, branch, commit ref, and deploy duration - across your team.',\n vendor: {\n name: 'Netlify',\n apiDocs: 'https://open-api.netlify.com/',\n website: 'https://www.netlify.com',\n },\n auth: {\n summary:\n 'A Netlify personal access token is required. The token must belong to an account with read access to the sites you want to sync.',\n setup: [\n 'Open Netlify -> User Settings -> Applications -> Personal access tokens.',\n 'Click \"New access token\", give it a name, and copy the token value.',\n 'Store it as a secret and reference it from the connector config as `apiToken: secret(\"NETLIFY_API_TOKEN\")`.',\n 'Optionally set `siteIds` to a list of site IDs to limit the sync scope.',\n ],\n },\n rateLimit:\n 'Netlify returns standard `X-RateLimit-Remaining` / `X-RateLimit-Reset` headers (reset is a Unix timestamp in seconds); list pagination uses the Link header (page size 100).',\n limitations: [\n 'Netlify has no server-side date filter on the deploys endpoint - the connector paginates newest-first and applies `deploysLookbackDays` (if set) as a client-side cutoff that short-circuits pagination once a full page is older than the cutoff.',\n 'Enabling `deploy_events` without `deploys` still runs the deploys query but skips writing deploy entities.',\n 'Netlify Analytics (paid add-on), function invocation logs, and DNS/domain APIs are out of scope.',\n ],\n});\n\n// ---------------------------------------------------------------------------\n// Rate-limit policy\n// ---------------------------------------------------------------------------\n\nconst netlifyRateLimit = standardRateLimitPolicy({\n remainingHeader: 'x-ratelimit-remaining',\n resetHeader: 'x-ratelimit-reset',\n resetUnit: 's',\n});\n\n// ---------------------------------------------------------------------------\n// Sync phases + cursor\n// ---------------------------------------------------------------------------\n\nconst PHASE_ORDER = ['sites', 'deploys'] as const;\n\ntype NetlifyPhase = (typeof PHASE_ORDER)[number];\n\ntype NetlifySyncCursor = ChunkedSyncCursor<NetlifyPhase, string>;\n\nconst isNetlifySyncCursor = makeChunkedCursorGuard(PHASE_ORDER);\n\n// Deploys page cursor encoding: `<siteIdx>|<pageUrl?>`.\n// - null page -> start at siteIdx=0 with no URL yet\n// - \"<idx>|\" -> start of site at idx, build initial URL\n// - \"<idx>|<url>\" -> continuing pagination for site at idx\nfunction decodeDeploysPage(page: string | null): {\n idx: number;\n url: string | null;\n} {\n if (page === null) {\n return { idx: 0, url: null };\n }\n const sep = page.indexOf('|');\n if (sep === -1) {\n return { idx: 0, url: null };\n }\n const idxRaw = Number.parseInt(page.slice(0, sep), 10);\n const url = page.slice(sep + 1);\n return {\n idx: Number.isFinite(idxRaw) && idxRaw >= 0 ? idxRaw : 0,\n url: url === '' ? null : url,\n };\n}\n\nfunction encodeDeploysPage(idx: number, url: string | null): string {\n return `${idx}|${url ?? ''}`;\n}\n\n// ---------------------------------------------------------------------------\n// Netlify API types\n// ---------------------------------------------------------------------------\n\ninterface NetlifySite {\n id: string;\n site_id?: string;\n name: string;\n url: string;\n admin_url?: string | null;\n account_id?: string | null;\n account_name?: string | null;\n build_settings?: {\n repo_url?: string | null;\n repo_branch?: string | null;\n cmd?: string | null;\n } | null;\n created_at: string;\n updated_at: string;\n published_deploy?: { id: string; state: string } | null;\n}\n\ninterface NetlifyDeploy {\n id: string;\n site_id: string;\n name?: string | null;\n url?: string | null;\n deploy_url?: string | null;\n state: string;\n branch?: string | null;\n context?: string | null;\n commit_ref?: string | null;\n commit_url?: string | null;\n title?: string | null;\n committer?: string | null;\n created_at: string;\n updated_at?: string | null;\n published_at?: string | null;\n deploy_time?: number | null;\n error_message?: string | null;\n}\n\n// ---------------------------------------------------------------------------\n// Zod response schemas\n// ---------------------------------------------------------------------------\n\nconst siteSchema = z.object({\n id: z.string().min(1),\n site_id: z.string().min(1).optional(),\n name: z.string().min(1),\n url: z.string(),\n admin_url: z.string().nullable().optional(),\n account_id: z.string().nullable().optional(),\n account_name: z.string().nullable().optional(),\n build_settings: z\n .object({\n repo_url: z.string().nullable().optional(),\n repo_branch: z.string().nullable().optional(),\n cmd: z.string().nullable().optional(),\n })\n .nullable()\n .optional(),\n created_at: z.iso.datetime(),\n updated_at: z.iso.datetime(),\n published_deploy: z\n .object({ id: z.string().min(1), state: z.string().min(1) })\n .nullable()\n .optional(),\n});\n\nconst sitesResponseSchema = z.array(siteSchema);\n\nconst deploySchema = z.object({\n id: z.string().min(1),\n site_id: z.string().min(1),\n name: z.string().nullable().optional(),\n url: z.string().nullable().optional(),\n deploy_url: z.string().nullable().optional(),\n state: z.string().min(1),\n branch: z.string().nullable().optional(),\n context: z.string().nullable().optional(),\n commit_ref: z.string().nullable().optional(),\n commit_url: z.string().nullable().optional(),\n title: z.string().nullable().optional(),\n committer: z.string().nullable().optional(),\n created_at: z.iso.datetime(),\n updated_at: z.iso.datetime().nullable().optional(),\n published_at: z.iso.datetime().nullable().optional(),\n deploy_time: z.number().nullable().optional(),\n error_message: z.string().nullable().optional(),\n});\n\nconst deploysResponseSchema = z.array(deploySchema);\n\nexport const netlifyResources = defineResources({\n netlify_site: {\n shape: 'entity',\n description:\n 'Netlify sites with name, primary URL, owning account, linked git repo, and create/update timestamps.',\n endpoint: 'GET /api/v1/sites',\n responses: { sites: sitesResponseSchema },\n },\n netlify_deploy: {\n shape: 'entity',\n description:\n 'Deploys with build state, branch, commit ref, deploy context (production/branch-deploy/deploy-preview), and build duration.',\n endpoint: 'GET /api/v1/sites/{site_id}/deploys',\n notes:\n 'deployTimeMs comes from the API `deploy_time` field (seconds) when present, otherwise null. gitRef prefers `commit_ref`, falling back to `branch`.',\n responses: { deploys: deploysResponseSchema },\n },\n netlify_deploy_event: {\n shape: 'event',\n description:\n 'Each deploy emitted as a time-bounded event spanning creation to publish, carrying the same attributes as the deploy entity.',\n endpoint: 'GET /api/v1/sites/{site_id}/deploys',\n },\n});\n\n// ---------------------------------------------------------------------------\n// NetlifyConnector\n// ---------------------------------------------------------------------------\n\nconst NETLIFY_API_HOST = 'api.netlify.com';\nconst NETLIFY_API_BASE = `https://${NETLIFY_API_HOST}/api/v1`;\nconst PAGE_SIZE = 100;\nconst MS_PER_DAY = 24 * 60 * 60 * 1000;\n\nexport const id = 'netlify';\n\ninterface SiteDeploysBatch {\n siteId: string;\n items: NetlifyDeploy[];\n}\n\nexport class NetlifyConnector extends BaseConnector<\n NetlifySettings,\n NetlifyCredentials\n> {\n static readonly id = id;\n\n static readonly resources = netlifyResources;\n\n static readonly schemas = schemasFromResources(netlifyResources);\n\n static create(input: unknown, ctx?: ConnectorContext): NetlifyConnector {\n const parsed = configFields.parse(input);\n return new NetlifyConnector(\n {\n siteIds: parsed.siteIds,\n resources: parsed.resources,\n deploysLookbackDays: parsed.deploysLookbackDays,\n },\n { apiToken: parsed.apiToken },\n ctx,\n );\n }\n\n readonly id = id;\n override readonly credentials = netlifyCredentials;\n\n private discoveredSiteIds: string[] | null = null;\n\n private buildHeaders(): Record<string, string> {\n return {\n Authorization: `Bearer ${this.creds.apiToken}`,\n Accept: 'application/json',\n 'User-Agent': connectorUserAgent('netlify'),\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 rateLimit: netlifyRateLimit,\n });\n }\n\n // -------------------------------------------------------------------------\n // Resource enablement\n // -------------------------------------------------------------------------\n\n private activePhases(): NetlifyPhase[] {\n return selectActivePhases<NetlifyResource, NetlifyPhase>(\n (r) => (r === 'sites' ? 'sites' : 'deploys'),\n PHASE_ORDER,\n this.settings.resources,\n );\n }\n\n // -------------------------------------------------------------------------\n // URL sanitization\n // -------------------------------------------------------------------------\n\n private sanitizeUrl(url: string | null, expectedPath: string): string | null {\n if (!url) {\n return null;\n }\n try {\n const u = new URL(url);\n if (u.protocol !== 'https:' || u.host !== NETLIFY_API_HOST) {\n return null;\n }\n if (u.pathname !== expectedPath) {\n return null;\n }\n return u.toString();\n } catch {\n return null;\n }\n }\n\n private resolveCursor(cursor: unknown): NetlifySyncCursor | undefined {\n if (!isNetlifySyncCursor(cursor)) {\n return undefined;\n }\n return { phase: cursor.phase, page: cursor.page };\n }\n\n // -------------------------------------------------------------------------\n // Sites: discovery + paginated fetch\n // -------------------------------------------------------------------------\n\n private buildInitialSitesUrl(): string {\n const u = new URL(`${NETLIFY_API_BASE}/sites`);\n u.searchParams.set('per_page', String(PAGE_SIZE));\n return u.toString();\n }\n\n private async fetchSitesPage(\n page: string | null,\n signal: AbortSignal | undefined,\n ): Promise<FetchPageResult<string>> {\n const url =\n this.sanitizeUrl(page, '/api/v1/sites') ?? this.buildInitialSitesUrl();\n const res = await this.fetch<NetlifySite[]>(url, 'sites', signal);\n const rawNext = parseLinkHeader(res.headers.get('link'))['next'] ?? null;\n const next = this.sanitizeUrl(rawNext, '/api/v1/sites');\n return { items: res.body, next };\n }\n\n // -------------------------------------------------------------------------\n // Site ID resolution for the deploys phase. If the user supplied siteIds,\n // use those directly; otherwise discover sites from the sites endpoint.\n // -------------------------------------------------------------------------\n\n private async resolveSiteIds(\n signal: AbortSignal | undefined,\n ): Promise<string[]> {\n if (this.settings.siteIds && this.settings.siteIds.length > 0) {\n return [...new Set(this.settings.siteIds)];\n }\n if (this.discoveredSiteIds !== null) {\n return this.discoveredSiteIds;\n }\n const out = new Set<string>();\n let url: string | null = this.buildInitialSitesUrl();\n while (url !== null) {\n const res = await this.fetch<NetlifySite[]>(\n url,\n 'sites_discovery',\n signal,\n );\n for (const site of res.body) {\n out.add(site.id);\n }\n const rawNext = parseLinkHeader(res.headers.get('link'))['next'] ?? null;\n url = this.sanitizeUrl(rawNext, '/api/v1/sites');\n }\n this.discoveredSiteIds = [...out];\n return this.discoveredSiteIds;\n }\n\n // -------------------------------------------------------------------------\n // Deploys: paginated per-site fetch\n // -------------------------------------------------------------------------\n\n private buildInitialDeploysUrl(siteId: string): string {\n const u = new URL(`${NETLIFY_API_BASE}/sites/${siteId}/deploys`);\n u.searchParams.set('per_page', String(PAGE_SIZE));\n return u.toString();\n }\n\n private deployUpdatedMs(deploy: NetlifyDeploy): number {\n const ms = parseEpoch(\n deploy.published_at ?? deploy.updated_at ?? deploy.created_at,\n 'iso',\n );\n if (ms !== null) {\n return ms;\n }\n return parseEpoch(deploy.created_at, 'iso') ?? 0;\n }\n\n private computeDeploysCutoffMs(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 if (\n options.mode === 'full' &&\n this.settings.deploysLookbackDays !== undefined\n ) {\n return Date.now() - this.settings.deploysLookbackDays * MS_PER_DAY;\n }\n return null;\n }\n\n private async fetchDeploysPage(\n options: SyncOptions,\n page: string | null,\n signal: AbortSignal | undefined,\n ): Promise<FetchPageResult<string>> {\n const siteIds = await this.resolveSiteIds(signal);\n if (siteIds.length === 0) {\n return { items: [], next: null };\n }\n const { idx, url: rawPageUrl } = decodeDeploysPage(page);\n if (idx >= siteIds.length) {\n return { items: [], next: null };\n }\n const siteId = siteIds[idx]!;\n const expectedPath = `/api/v1/sites/${siteId}/deploys`;\n const fetchUrl =\n this.sanitizeUrl(rawPageUrl, expectedPath) ??\n this.buildInitialDeploysUrl(siteId);\n const res = await this.fetch<NetlifyDeploy[]>(fetchUrl, 'deploys', signal);\n const rawNext = parseLinkHeader(res.headers.get('link'))['next'] ?? null;\n const safeNext = this.sanitizeUrl(rawNext, expectedPath);\n const rows = res.body;\n\n const cutoff = this.computeDeploysCutoffMs(options);\n let filtered: NetlifyDeploy[];\n let cutoffReached: boolean;\n if (cutoff !== null) {\n filtered = rows.filter((row) => this.deployUpdatedMs(row) >= cutoff);\n const last = rows.at(-1);\n cutoffReached = last !== undefined && this.deployUpdatedMs(last) < cutoff;\n } else {\n filtered = rows;\n cutoffReached = false;\n }\n\n const nextWithinSite = cutoffReached ? null : safeNext;\n const batch: SiteDeploysBatch = { siteId, items: filtered };\n if (nextWithinSite !== null) {\n return { items: [batch], next: encodeDeploysPage(idx, nextWithinSite) };\n }\n const nextIdx = idx + 1;\n const next =\n nextIdx < siteIds.length ? encodeDeploysPage(nextIdx, null) : null;\n return { items: [batch], next };\n }\n\n // -------------------------------------------------------------------------\n // Writers\n // -------------------------------------------------------------------------\n\n private async writeSites(\n storage: StorageHandle,\n items: unknown[],\n ): Promise<void> {\n const sites = items as NetlifySite[];\n const allowedSiteIds =\n this.settings.siteIds && this.settings.siteIds.length > 0\n ? new Set(this.settings.siteIds)\n : null;\n for (const s of sites) {\n if (allowedSiteIds && !allowedSiteIds.has(s.id)) {\n continue;\n }\n const createdMs = parseEpoch(s.created_at, 'iso');\n const updatedMs = parseEpoch(s.updated_at, 'iso');\n if (createdMs === null || updatedMs === null) {\n this.logger?.warn?.('skipping site with unparseable timestamps', {\n resource: 'sites',\n id: s.id,\n });\n continue;\n }\n await storage.entity({\n type: 'netlify_site',\n id: s.id,\n attributes: {\n name: s.name,\n url: s.url,\n adminUrl: s.admin_url ?? null,\n accountId: s.account_id ?? null,\n accountName: s.account_name ?? null,\n repoUrl: s.build_settings?.repo_url ?? null,\n repoBranch: s.build_settings?.repo_branch ?? null,\n publishedDeployId: s.published_deploy?.id ?? null,\n publishedDeployState: s.published_deploy?.state ?? null,\n createdAt: createdMs,\n updatedAt: updatedMs,\n },\n updated_at: updatedMs,\n });\n }\n }\n\n private async writeDeploysBatch(\n storage: StorageHandle,\n items: unknown[],\n ): Promise<void> {\n const writeEntities = this.isResourceEnabled('deploys');\n const writeEvents = this.isResourceEnabled('deploy_events');\n if (!writeEntities && !writeEvents) {\n return;\n }\n const batches = items as SiteDeploysBatch[];\n for (const batch of batches) {\n for (const d of batch.items) {\n const createdMs = parseEpoch(d.created_at, 'iso');\n if (createdMs === null) {\n this.logger?.warn?.(\n 'skipping deploy with unparseable created timestamp',\n {\n resource: 'deploys',\n id: d.id,\n },\n );\n continue;\n }\n const updatedMs = parseEpoch(d.updated_at, 'iso');\n const publishedMs = parseEpoch(d.published_at, 'iso');\n const deployTimeMs =\n d.deploy_time !== null && d.deploy_time !== undefined\n ? Math.round(d.deploy_time * 1000)\n : null;\n const gitRef = d.commit_ref ?? d.branch ?? null;\n const baseAttributes: Record<string, JSONValue> = {\n deployId: d.id,\n siteId: batch.siteId,\n name: d.name ?? null,\n url: d.url ?? d.deploy_url ?? null,\n state: d.state,\n branch: d.branch ?? null,\n context: d.context ?? null,\n gitRef,\n commitUrl: d.commit_url ?? null,\n title: d.title ?? null,\n committer: d.committer ?? null,\n errorMessage: d.error_message ?? null,\n createdAt: createdMs,\n updatedAt: updatedMs,\n publishedAt: publishedMs,\n deployTimeMs,\n };\n\n if (writeEntities) {\n await storage.entity({\n type: 'netlify_deploy',\n id: d.id,\n attributes: baseAttributes,\n updated_at: publishedMs ?? updatedMs ?? createdMs,\n });\n }\n if (writeEvents) {\n await storage.event({\n name: 'netlify_deploy_event',\n start_ts: createdMs,\n end_ts: publishedMs,\n attributes: baseAttributes,\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 this.discoveredSiteIds = null;\n const cursor = this.resolveCursor(options.cursor);\n const isFull = options.mode === 'full';\n const phases = this.activePhases();\n\n return paginateChunked<NetlifyPhase, string>({\n phases,\n cursor,\n signal,\n logger: this.logger,\n fetchPage: async (phase, page, sig) => {\n switch (phase) {\n case 'sites':\n return this.fetchSitesPage(page, sig);\n case 'deploys':\n return this.fetchDeploysPage(options, page, sig);\n }\n },\n writeBatch: async (phase, items, page) => {\n if (isFull && page === null) {\n switch (phase) {\n case 'sites':\n if (this.isResourceEnabled('sites')) {\n await storage.entities([], { types: ['netlify_site'] });\n }\n break;\n case 'deploys':\n if (this.isResourceEnabled('deploys')) {\n await storage.entities([], { types: ['netlify_deploy'] });\n }\n if (this.isResourceEnabled('deploy_events')) {\n await storage.events([], { names: ['netlify_deploy_event'] });\n }\n break;\n }\n }\n switch (phase) {\n case 'sites':\n if (!this.isResourceEnabled('sites')) {\n return;\n }\n return this.writeSites(storage, items);\n case 'deploys':\n return this.writeDeploysBatch(storage, items);\n }\n },\n });\n }\n}\n","import { NetlifyConnector } from './netlify';\n\nexport {\n configFields,\n doc,\n NetlifyConnector,\n netlifyResources as resources,\n id,\n} from './netlify';\nexport type { NetlifyResource, NetlifySettings } from './netlify';\nexport default NetlifyConnector;\n"],"mappings":";AEAO,IAAM,sBAAsB;AAE5B,IAAM,qBAAqB,qBAAqB,mBAAmB;AAEnE,SAAS,mBAAmB,aAA6B;AAC9D,SAAO,qBAAqB,WAAW,IAAI,mBAAmB;AAChE;AEUO,SAAS,wBACd,QACiB;AACjB,QAAM,EAAE,iBAAiB,aAAa,WAAW,gBAAgB,IAAI;AACrE,QAAM,aAAa,cAAc,MAAM,MAAO;AAC9C,SAAO;IACL,MAAM,GAAG;AACP,YAAM,eAAe,EAAE,IAAI,eAAe;AAC1C,UAAI,iBAAiB,QAAQ,aAAa,KAAK,MAAM,IAAI;AACvD,eAAO;MACT;AACA,YAAM,YAAY,OAAO,YAAY;AACrC,UAAI,CAAC,OAAO,SAAS,SAAS,GAAG;AAC/B,eAAO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BAAkB,eAAe,GAAG;AAC3C,sBAAM,QAAQ,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,sBAAsB,EAAE,CAAC;AAAA,cAC9D;AACA;AAAA,UACJ;AAAA,QACF;AACA,gBAAQ,OAAO;AAAA,UACb,KAAK;AACH,gBAAI,CAAC,KAAK,kBAAkB,OAAO,GAAG;AACpC;AAAA,YACF;AACA,mBAAO,KAAK,WAAW,SAAS,KAAK;AAAA,UACvC,KAAK;AACH,mBAAO,KAAK,kBAAkB,SAAS,KAAK;AAAA,QAChD;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AACF;;;ACjrBA,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/netlify.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 parseLinkHeader,\n standardRateLimitPolicy,\n} from '@rawdash/connector-shared';\nimport {\n BaseConnector,\n type ChunkedSyncCursor,\n type ConnectorContext,\n type ConnectorDoc,\n type CredentialsSchema,\n type Event,\n type FetchPageResult,\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 'Netlify personal access token. Create one at Netlify -> User Settings -> Applications -> Personal access tokens.',\n placeholder: 'nfp_...',\n secret: true,\n }),\n siteIds: z.array(z.string().min(1)).nonempty().optional().meta({\n label: 'Site IDs (optional)',\n description:\n 'Restrict the sync to specific Netlify site IDs (the UUID-style id from the site Admin panel). Omit to sync every site the token can see.',\n }),\n resources: z\n .array(z.enum(['sites', 'deploys', 'deploy_events']))\n .nonempty()\n .optional()\n .meta({\n label: 'Resources',\n description:\n \"Which Netlify resources to sync. Omit to sync all of them. 'deploy_events' rides the 'deploys' phase - enabling it without 'deploys' still fetches deploys but skips writing deploy entities.\",\n }),\n deploysLookbackDays: z.number().int().positive().max(365).optional().meta({\n label: 'Deploys lookback (days)',\n description:\n 'Cap the deploy backfill window to this many days. If unset, the connector fetches every deploy the API returns (newest-first). Netlify has no server-side date filter on the deploys endpoint, so the cutoff is applied client-side and short-circuits pagination once a page is entirely older than the cutoff.',\n placeholder: '30',\n }),\n }),\n);\n\nexport type NetlifyResource = 'sites' | 'deploys' | 'deploy_events';\n\nexport interface NetlifySettings {\n siteIds?: readonly string[];\n resources?: readonly NetlifyResource[];\n deploysLookbackDays?: number;\n}\n\nconst netlifyCredentials = {\n apiToken: {\n description: 'Netlify personal access token',\n auth: 'required' as const,\n },\n} satisfies CredentialsSchema;\n\ntype NetlifyCredentials = typeof netlifyCredentials;\n\n// ---------------------------------------------------------------------------\n// Connector documentation metadata\n// ---------------------------------------------------------------------------\n\nexport const doc: ConnectorDoc = defineConnectorDoc({\n displayName: 'Netlify',\n category: 'infrastructure',\n brandColor: '#00C7B7',\n tagline:\n 'Sync Netlify sites and deploys - including build state, branch, commit ref, and deploy duration - across your team.',\n vendor: {\n name: 'Netlify',\n apiDocs: 'https://open-api.netlify.com/',\n website: 'https://www.netlify.com',\n },\n auth: {\n summary:\n 'A Netlify personal access token is required. The token must belong to an account with read access to the sites you want to sync.',\n setup: [\n 'Open Netlify -> User Settings -> Applications -> Personal access tokens.',\n 'Click \"New access token\", give it a name, and copy the token value.',\n 'Store it as a secret and reference it from the connector config as `apiToken: secret(\"NETLIFY_API_TOKEN\")`.',\n 'Optionally set `siteIds` to a list of site IDs to limit the sync scope.',\n ],\n },\n rateLimit:\n 'Netlify returns standard `X-RateLimit-Remaining` / `X-RateLimit-Reset` headers (reset is a Unix timestamp in seconds); list pagination uses the Link header (page size 100).',\n limitations: [\n 'Netlify has no server-side date filter on the deploys endpoint - the connector paginates newest-first and applies `deploysLookbackDays` (if set) as a client-side cutoff that short-circuits pagination once a full page is older than the cutoff.',\n 'Enabling `deploy_events` without `deploys` still runs the deploys query but skips writing deploy entities.',\n 'Netlify Analytics (paid add-on), function invocation logs, and DNS/domain APIs are out of scope.',\n ],\n});\n\n// ---------------------------------------------------------------------------\n// Rate-limit policy\n// ---------------------------------------------------------------------------\n\nconst netlifyRateLimit = standardRateLimitPolicy({\n remainingHeader: 'x-ratelimit-remaining',\n resetHeader: 'x-ratelimit-reset',\n resetUnit: 's',\n});\n\n// ---------------------------------------------------------------------------\n// Sync phases + cursor\n// ---------------------------------------------------------------------------\n\nconst PHASE_ORDER = ['sites', 'deploys'] as const;\n\ntype NetlifyPhase = (typeof PHASE_ORDER)[number];\n\ntype NetlifySyncCursor = ChunkedSyncCursor<NetlifyPhase, string>;\n\nconst isNetlifySyncCursor = makeChunkedCursorGuard(PHASE_ORDER);\n\n// Deploys page cursor encoding: `<siteIdx>|<pageUrl?>`.\n// - null page -> start at siteIdx=0 with no URL yet\n// - \"<idx>|\" -> start of site at idx, build initial URL\n// - \"<idx>|<url>\" -> continuing pagination for site at idx\nfunction decodeDeploysPage(page: string | null): {\n idx: number;\n url: string | null;\n} {\n if (page === null) {\n return { idx: 0, url: null };\n }\n const sep = page.indexOf('|');\n if (sep === -1) {\n return { idx: 0, url: null };\n }\n const idxRaw = Number.parseInt(page.slice(0, sep), 10);\n const url = page.slice(sep + 1);\n return {\n idx: Number.isFinite(idxRaw) && idxRaw >= 0 ? idxRaw : 0,\n url: url === '' ? null : url,\n };\n}\n\nfunction encodeDeploysPage(idx: number, url: string | null): string {\n return `${idx}|${url ?? ''}`;\n}\n\n// ---------------------------------------------------------------------------\n// Netlify API types\n// ---------------------------------------------------------------------------\n\ninterface NetlifySite {\n id: string;\n site_id?: string;\n name: string;\n url: string;\n admin_url?: string | null;\n account_id?: string | null;\n account_name?: string | null;\n build_settings?: {\n repo_url?: string | null;\n repo_branch?: string | null;\n cmd?: string | null;\n } | null;\n created_at: string;\n updated_at: string;\n published_deploy?: { id: string; state: string } | null;\n}\n\ninterface NetlifyDeploy {\n id: string;\n site_id: string;\n name?: string | null;\n url?: string | null;\n deploy_url?: string | null;\n state: string;\n branch?: string | null;\n context?: string | null;\n commit_ref?: string | null;\n commit_url?: string | null;\n title?: string | null;\n committer?: string | null;\n created_at: string;\n updated_at?: string | null;\n published_at?: string | null;\n deploy_time?: number | null;\n error_message?: string | null;\n}\n\n// ---------------------------------------------------------------------------\n// Zod response schemas\n// ---------------------------------------------------------------------------\n\nconst siteSchema = z.object({\n id: z.string().min(1),\n site_id: z.string().min(1).optional(),\n name: z.string().min(1),\n url: z.string(),\n admin_url: z.string().nullable().optional(),\n account_id: z.string().nullable().optional(),\n account_name: z.string().nullable().optional(),\n build_settings: z\n .object({\n repo_url: z.string().nullable().optional(),\n repo_branch: z.string().nullable().optional(),\n cmd: z.string().nullable().optional(),\n })\n .nullable()\n .optional(),\n created_at: z.iso.datetime(),\n updated_at: z.iso.datetime(),\n published_deploy: z\n .object({ id: z.string().min(1), state: z.string().min(1) })\n .nullable()\n .optional(),\n});\n\nconst sitesResponseSchema = z.array(siteSchema);\n\nconst deploySchema = z.object({\n id: z.string().min(1),\n site_id: z.string().min(1),\n name: z.string().nullable().optional(),\n url: z.string().nullable().optional(),\n deploy_url: z.string().nullable().optional(),\n state: z.string().min(1),\n branch: z.string().nullable().optional(),\n context: z.string().nullable().optional(),\n commit_ref: z.string().nullable().optional(),\n commit_url: z.string().nullable().optional(),\n title: z.string().nullable().optional(),\n committer: z.string().nullable().optional(),\n created_at: z.iso.datetime(),\n updated_at: z.iso.datetime().nullable().optional(),\n published_at: z.iso.datetime().nullable().optional(),\n deploy_time: z.number().nullable().optional(),\n error_message: z.string().nullable().optional(),\n});\n\nconst deploysResponseSchema = z.array(deploySchema);\n\nexport const netlifyResources = defineResources({\n netlify_site: {\n shape: 'entity',\n description:\n 'Netlify sites with name, primary URL, owning account, linked git repo, and create/update timestamps.',\n endpoint: 'GET /api/v1/sites',\n responses: { sites: sitesResponseSchema },\n },\n netlify_deploy: {\n shape: 'entity',\n description:\n 'Deploys with build state, branch, commit ref, deploy context (production/branch-deploy/deploy-preview), and build duration.',\n endpoint: 'GET /api/v1/sites/{site_id}/deploys',\n notes:\n 'deployTimeMs comes from the API `deploy_time` field (seconds) when present, otherwise null. gitRef prefers `commit_ref`, falling back to `branch`.',\n responses: { deploys: deploysResponseSchema },\n },\n netlify_deploy_event: {\n shape: 'event',\n description:\n 'Each deploy emitted as a time-bounded event spanning creation to publish, carrying the same attributes as the deploy entity.',\n endpoint: 'GET /api/v1/sites/{site_id}/deploys',\n },\n});\n\n// ---------------------------------------------------------------------------\n// NetlifyConnector\n// ---------------------------------------------------------------------------\n\nconst NETLIFY_API_HOST = 'api.netlify.com';\nconst NETLIFY_API_BASE = `https://${NETLIFY_API_HOST}/api/v1`;\nconst PAGE_SIZE = 100;\nconst MS_PER_DAY = 24 * 60 * 60 * 1000;\n\nexport const id = 'netlify';\n\ninterface SiteDeploysBatch {\n siteId: string;\n items: NetlifyDeploy[];\n}\n\nexport class NetlifyConnector extends BaseConnector<\n NetlifySettings,\n NetlifyCredentials\n> {\n static readonly id = id;\n\n static readonly resources = netlifyResources;\n\n static readonly schemas = schemasFromResources(netlifyResources);\n\n static create(input: unknown, ctx?: ConnectorContext): NetlifyConnector {\n const parsed = configFields.parse(input);\n return new NetlifyConnector(\n {\n siteIds: parsed.siteIds,\n resources: parsed.resources,\n deploysLookbackDays: parsed.deploysLookbackDays,\n },\n { apiToken: parsed.apiToken },\n ctx,\n );\n }\n\n readonly id = id;\n override readonly credentials = netlifyCredentials;\n\n private discoveredSiteIds: string[] | null = null;\n\n private buildHeaders(): Record<string, string> {\n return {\n Authorization: `Bearer ${this.creds.apiToken}`,\n Accept: 'application/json',\n 'User-Agent': connectorUserAgent('netlify'),\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 rateLimit: netlifyRateLimit,\n });\n }\n\n // -------------------------------------------------------------------------\n // Resource enablement\n // -------------------------------------------------------------------------\n\n private activePhases(): NetlifyPhase[] {\n return selectActivePhases<NetlifyResource, NetlifyPhase>(\n (r) => (r === 'sites' ? 'sites' : 'deploys'),\n PHASE_ORDER,\n this.settings.resources,\n );\n }\n\n // -------------------------------------------------------------------------\n // URL sanitization\n // -------------------------------------------------------------------------\n\n private sanitizeUrl(url: string | null, expectedPath: string): string | null {\n if (!url) {\n return null;\n }\n try {\n const u = new URL(url);\n if (u.protocol !== 'https:' || u.host !== NETLIFY_API_HOST) {\n return null;\n }\n if (u.pathname !== expectedPath) {\n return null;\n }\n return u.toString();\n } catch {\n return null;\n }\n }\n\n private resolveCursor(cursor: unknown): NetlifySyncCursor | undefined {\n if (!isNetlifySyncCursor(cursor)) {\n return undefined;\n }\n return { phase: cursor.phase, page: cursor.page };\n }\n\n // -------------------------------------------------------------------------\n // Sites: discovery + paginated fetch\n // -------------------------------------------------------------------------\n\n private buildInitialSitesUrl(): string {\n const u = new URL(`${NETLIFY_API_BASE}/sites`);\n u.searchParams.set('per_page', String(PAGE_SIZE));\n return u.toString();\n }\n\n private async fetchSitesPage(\n page: string | null,\n signal: AbortSignal | undefined,\n ): Promise<FetchPageResult<string>> {\n const url =\n this.sanitizeUrl(page, '/api/v1/sites') ?? this.buildInitialSitesUrl();\n const res = await this.fetch<NetlifySite[]>(url, 'sites', signal);\n const rawNext = parseLinkHeader(res.headers.get('link'))['next'] ?? null;\n const next = this.sanitizeUrl(rawNext, '/api/v1/sites');\n return { items: res.body, next };\n }\n\n // -------------------------------------------------------------------------\n // Site ID resolution for the deploys phase. If the user supplied siteIds,\n // use those directly; otherwise discover sites from the sites endpoint.\n // -------------------------------------------------------------------------\n\n private async resolveSiteIds(\n signal: AbortSignal | undefined,\n ): Promise<string[]> {\n if (this.settings.siteIds && this.settings.siteIds.length > 0) {\n return [...new Set(this.settings.siteIds)];\n }\n if (this.discoveredSiteIds !== null) {\n return this.discoveredSiteIds;\n }\n const out = new Set<string>();\n let url: string | null = this.buildInitialSitesUrl();\n while (url !== null) {\n const res = await this.fetch<NetlifySite[]>(\n url,\n 'sites_discovery',\n signal,\n );\n for (const site of res.body) {\n out.add(site.id);\n }\n const rawNext = parseLinkHeader(res.headers.get('link'))['next'] ?? null;\n url = this.sanitizeUrl(rawNext, '/api/v1/sites');\n }\n this.discoveredSiteIds = [...out];\n return this.discoveredSiteIds;\n }\n\n // -------------------------------------------------------------------------\n // Deploys: paginated per-site fetch\n // -------------------------------------------------------------------------\n\n private buildInitialDeploysUrl(siteId: string): string {\n const u = new URL(`${NETLIFY_API_BASE}/sites/${siteId}/deploys`);\n u.searchParams.set('per_page', String(PAGE_SIZE));\n return u.toString();\n }\n\n private deployUpdatedMs(deploy: NetlifyDeploy): number {\n const ms = parseEpoch(\n deploy.published_at ?? deploy.updated_at ?? deploy.created_at,\n 'iso',\n );\n if (ms !== null) {\n return ms;\n }\n return parseEpoch(deploy.created_at, 'iso') ?? 0;\n }\n\n private computeDeploysCutoffMs(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 if (\n options.mode === 'full' &&\n this.settings.deploysLookbackDays !== undefined\n ) {\n return Date.now() - this.settings.deploysLookbackDays * MS_PER_DAY;\n }\n return null;\n }\n\n private async fetchDeploysPage(\n options: SyncOptions,\n page: string | null,\n signal: AbortSignal | undefined,\n ): Promise<FetchPageResult<string>> {\n const siteIds = await this.resolveSiteIds(signal);\n if (siteIds.length === 0) {\n return { items: [], next: null };\n }\n const { idx, url: rawPageUrl } = decodeDeploysPage(page);\n if (idx >= siteIds.length) {\n return { items: [], next: null };\n }\n const siteId = siteIds[idx]!;\n const expectedPath = `/api/v1/sites/${siteId}/deploys`;\n const fetchUrl =\n this.sanitizeUrl(rawPageUrl, expectedPath) ??\n this.buildInitialDeploysUrl(siteId);\n const res = await this.fetch<NetlifyDeploy[]>(fetchUrl, 'deploys', signal);\n const rawNext = parseLinkHeader(res.headers.get('link'))['next'] ?? null;\n const safeNext = this.sanitizeUrl(rawNext, expectedPath);\n const rows = res.body;\n\n const cutoff = this.computeDeploysCutoffMs(options);\n let filtered: NetlifyDeploy[];\n let cutoffReached: boolean;\n if (cutoff !== null) {\n filtered = rows.filter((row) => this.deployUpdatedMs(row) >= cutoff);\n const last = rows.at(-1);\n cutoffReached = last !== undefined && this.deployUpdatedMs(last) < cutoff;\n } else {\n filtered = rows;\n cutoffReached = false;\n }\n\n const nextWithinSite = cutoffReached ? null : safeNext;\n const batch: SiteDeploysBatch = { siteId, items: filtered };\n if (nextWithinSite !== null) {\n return { items: [batch], next: encodeDeploysPage(idx, nextWithinSite) };\n }\n const nextIdx = idx + 1;\n const next =\n nextIdx < siteIds.length ? encodeDeploysPage(nextIdx, null) : null;\n return { items: [batch], next };\n }\n\n // -------------------------------------------------------------------------\n // Writers\n // -------------------------------------------------------------------------\n\n private async writeSites(\n storage: StorageHandle,\n items: unknown[],\n ): Promise<void> {\n const sites = items as NetlifySite[];\n const allowedSiteIds =\n this.settings.siteIds && this.settings.siteIds.length > 0\n ? new Set(this.settings.siteIds)\n : null;\n for (const s of sites) {\n if (allowedSiteIds && !allowedSiteIds.has(s.id)) {\n continue;\n }\n const createdMs = parseEpoch(s.created_at, 'iso');\n const updatedMs = parseEpoch(s.updated_at, 'iso');\n if (createdMs === null || updatedMs === null) {\n this.logger?.warn?.('skipping site with unparseable timestamps', {\n resource: 'sites',\n id: s.id,\n });\n continue;\n }\n await storage.entity({\n type: 'netlify_site',\n id: s.id,\n attributes: {\n name: s.name,\n url: s.url,\n adminUrl: s.admin_url ?? null,\n accountId: s.account_id ?? null,\n accountName: s.account_name ?? null,\n repoUrl: s.build_settings?.repo_url ?? null,\n repoBranch: s.build_settings?.repo_branch ?? null,\n publishedDeployId: s.published_deploy?.id ?? null,\n publishedDeployState: s.published_deploy?.state ?? null,\n createdAt: createdMs,\n updatedAt: updatedMs,\n },\n updated_at: updatedMs,\n });\n }\n }\n\n private async writeDeploysBatch(\n storage: StorageHandle,\n items: unknown[],\n ): Promise<void> {\n const writeEntities = this.isResourceEnabled('deploys');\n const writeEvents = this.isResourceEnabled('deploy_events');\n if (!writeEntities && !writeEvents) {\n return;\n }\n const batches = items as SiteDeploysBatch[];\n const eventsById = new Map<string, Event>();\n for (const batch of batches) {\n for (const d of batch.items) {\n const createdMs = parseEpoch(d.created_at, 'iso');\n if (createdMs === null) {\n this.logger?.warn?.(\n 'skipping deploy with unparseable created timestamp',\n {\n resource: 'deploys',\n id: d.id,\n },\n );\n continue;\n }\n const updatedMs = parseEpoch(d.updated_at, 'iso');\n const publishedMs = parseEpoch(d.published_at, 'iso');\n const deployTimeMs =\n d.deploy_time !== null && d.deploy_time !== undefined\n ? Math.round(d.deploy_time * 1000)\n : null;\n const gitRef = d.commit_ref ?? d.branch ?? null;\n const baseAttributes: Record<string, JSONValue> = {\n deployId: d.id,\n siteId: batch.siteId,\n name: d.name ?? null,\n url: d.url ?? d.deploy_url ?? null,\n state: d.state,\n branch: d.branch ?? null,\n context: d.context ?? null,\n gitRef,\n commitUrl: d.commit_url ?? null,\n title: d.title ?? null,\n committer: d.committer ?? null,\n errorMessage: d.error_message ?? null,\n createdAt: createdMs,\n updatedAt: updatedMs,\n publishedAt: publishedMs,\n deployTimeMs,\n };\n\n if (writeEntities) {\n await storage.entity({\n type: 'netlify_deploy',\n id: d.id,\n attributes: baseAttributes,\n updated_at: publishedMs ?? updatedMs ?? createdMs,\n });\n }\n if (writeEvents) {\n eventsById.set(`${batch.siteId}:${d.id}`, {\n name: 'netlify_deploy_event',\n start_ts: createdMs,\n end_ts: publishedMs,\n attributes: baseAttributes,\n });\n }\n }\n }\n for (const event of eventsById.values()) {\n await storage.event(event);\n }\n }\n\n // -------------------------------------------------------------------------\n // sync\n // -------------------------------------------------------------------------\n\n async sync(\n options: SyncOptions,\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<SyncResult> {\n this.discoveredSiteIds = null;\n const cursor = this.resolveCursor(options.cursor);\n const isFull = options.mode === 'full';\n const phases = this.activePhases();\n\n return paginateChunked<NetlifyPhase, string>({\n phases,\n cursor,\n signal,\n logger: this.logger,\n fetchPage: async (phase, page, sig) => {\n switch (phase) {\n case 'sites':\n return this.fetchSitesPage(page, sig);\n case 'deploys':\n return this.fetchDeploysPage(options, page, sig);\n }\n },\n writeBatch: async (phase, items, page) => {\n if (isFull && page === null) {\n switch (phase) {\n case 'sites':\n if (this.isResourceEnabled('sites')) {\n await storage.entities([], { types: ['netlify_site'] });\n }\n break;\n case 'deploys':\n if (this.isResourceEnabled('deploys')) {\n await storage.entities([], { types: ['netlify_deploy'] });\n }\n if (this.isResourceEnabled('deploy_events')) {\n await storage.events([], { names: ['netlify_deploy_event'] });\n }\n break;\n }\n }\n switch (phase) {\n case 'sites':\n if (!this.isResourceEnabled('sites')) {\n return;\n }\n return this.writeSites(storage, items);\n case 'deploys':\n return this.writeDeploysBatch(storage, items);\n }\n },\n });\n }\n}\n","import { NetlifyConnector } from './netlify';\n\nexport {\n configFields,\n doc,\n NetlifyConnector,\n netlifyResources as resources,\n id,\n} from './netlify';\nexport type { NetlifyResource, NetlifySettings } from './netlify';\nexport default NetlifyConnector;\n"],"mappings":";AEAO,IAAM,sBAAsB;AAE5B,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AAO,OAAO,MAAM,QAAQ;AACrC,gBAAQ,OAAO;AAAA,UACb,KAAK;AACH,mBAAO,KAAK,eAAe,MAAM,GAAG;AAAA,UACtC,KAAK;AACH,mBAAO,KAAK,iBAAiB,SAAS,MAAM,GAAG;AAAA,QACnD;AAAA,MACF;AAAA,MACA,YAAY,OAAO,OAAO,OAAO,SAAS;AACxC,YAAI,UAAU,SAAS,MAAM;AAC3B,kBAAQ,OAAO;AAAA,YACb,KAAK;AACH,kBAAI,KAAK,kBAAkB,OAAO,GAAG;AACnC,sBAAM,QAAQ,SAAS,CAAC,GAAG,EAAE,OAAO,CAAC,cAAc,EAAE,CAAC;AAAA,cACxD;AACA;AAAA,YACF,KAAK;AACH,kBAAI,KAAK,kBAAkB,SAAS,GAAG;AACrC,sBAAM,QAAQ,SAAS,CAAC,GAAG,EAAE,OAAO,CAAC,gBAAgB,EAAE,CAAC;AAAA,cAC1D;AACA,kBAAI,KAAK,kBAAkB,eAAe,GAAG;AAC3C,sBAAM,QAAQ,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,sBAAsB,EAAE,CAAC;AAAA,cAC9D;AACA;AAAA,UACJ;AAAA,QACF;AACA,gBAAQ,OAAO;AAAA,UACb,KAAK;AACH,gBAAI,CAAC,KAAK,kBAAkB,OAAO,GAAG;AACpC;AAAA,YACF;AACA,mBAAO,KAAK,WAAW,SAAS,KAAK;AAAA,UACvC,KAAK;AACH,mBAAO,KAAK,kBAAkB,SAAS,KAAK;AAAA,QAChD;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AACF;;;ACtrBA,IAAO,gBAAQ;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rawdash/connector-netlify",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.21.0",
|
|
4
4
|
"description": "Rawdash connector for Netlify - sites, deploys, deploy 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.21.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-test-utils": "0.0.8",
|
|
35
|
+
"@rawdash/connector-shared": "0.3.1"
|
|
36
|
+
},
|
|
37
|
+
"scripts": {
|
|
38
|
+
"build": "tsup",
|
|
39
|
+
"typecheck": "tsc --noEmit",
|
|
40
|
+
"lint": "eslint src",
|
|
41
|
+
"test": "vitest run"
|
|
42
42
|
}
|
|
43
|
-
}
|
|
43
|
+
}
|