@rawdash/connector-branch 0.0.1 → 0.24.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.d.ts +2 -0
- package/dist/index.js +2 -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.d.ts
CHANGED
|
@@ -140,6 +140,7 @@ declare const branchResources: {
|
|
|
140
140
|
readonly name: "clicks";
|
|
141
141
|
readonly description: "Click count for the bucket.";
|
|
142
142
|
}];
|
|
143
|
+
readonly filterable: [];
|
|
143
144
|
readonly responses: {
|
|
144
145
|
readonly deep_link_events: z.ZodObject<{
|
|
145
146
|
results: z.ZodArray<z.ZodObject<{
|
|
@@ -264,6 +265,7 @@ declare class BranchConnector extends BaseConnector<BranchSettings, BranchCreden
|
|
|
264
265
|
readonly name: "clicks";
|
|
265
266
|
readonly description: "Click count for the bucket.";
|
|
266
267
|
}];
|
|
268
|
+
readonly filterable: [];
|
|
267
269
|
readonly responses: {
|
|
268
270
|
readonly deep_link_events: z.ZodObject<{
|
|
269
271
|
results: z.ZodArray<z.ZodObject<{
|
package/dist/index.js
CHANGED
|
@@ -165,6 +165,7 @@ var branchResources = defineResources({
|
|
|
165
165
|
},
|
|
166
166
|
{ name: "clicks", description: "Click count for the bucket." }
|
|
167
167
|
],
|
|
168
|
+
filterable: [],
|
|
168
169
|
responses: { deep_link_events: clickResponseSchema }
|
|
169
170
|
}
|
|
170
171
|
});
|
|
@@ -226,7 +227,7 @@ function normalizeDateBucket(timestamp) {
|
|
|
226
227
|
return timestamp.slice(0, 10);
|
|
227
228
|
}
|
|
228
229
|
function bucketKey(date, channel, campaign) {
|
|
229
|
-
return `${date}
|
|
230
|
+
return `${date}|${channel ?? ""}|${campaign ?? ""}`;
|
|
230
231
|
}
|
|
231
232
|
function mergeInstallBuckets(rowsByDataSource) {
|
|
232
233
|
const buckets = /* @__PURE__ */ new Map();
|
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/branch.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 { connectorUserAgent } from '@rawdash/connector-shared';\nimport {\n BaseConnector,\n type ChunkedSyncCursor,\n type ConnectorContext,\n type ConnectorDoc,\n type CredentialsSchema,\n type Event,\n type MetricSample,\n type StorageHandle,\n type SyncOptions,\n type SyncResult,\n defineConfigFields,\n defineConnectorDoc,\n defineResources,\n makeChunkedCursorGuard,\n paginateChunked,\n schemasFromResources,\n selectActivePhases,\n} from '@rawdash/core';\nimport { z } from 'zod';\n\nexport const configFields = defineConfigFields(\n z.object({\n branchKey: z.object({ $secret: z.string() }).meta({\n label: 'Branch key',\n description:\n 'Your Branch app key (starts with `key_live_`). Find it in the Branch dashboard under Account Settings -> Profile.',\n placeholder: 'key_live_xxxxxxxxxxxxxxxxxxxxxxxxxx',\n secret: true,\n }),\n branchSecret: z.object({ $secret: z.string() }).meta({\n label: 'Branch secret',\n description:\n 'Your Branch app secret (starts with `secret_live_`). Find it next to the key in the Branch dashboard.',\n placeholder: 'secret_live_xxxxxxxxxxxxxxxxxxxxxxxxxx',\n secret: true,\n }),\n lookbackDays: z.number().int().positive().optional().meta({\n label: 'Lookback days (full sync)',\n description:\n 'How many calendar days of metrics/events to fetch on a full sync. Defaults to 90.',\n placeholder: '90',\n }),\n resources: z\n .array(z.enum(['install_metrics', 'deep_link_events']))\n .nonempty()\n .optional()\n .meta({\n label: 'Resources',\n description:\n 'Which Branch resources to sync. Omit to sync all of them.',\n }),\n }),\n);\n\nexport const doc: ConnectorDoc = defineConnectorDoc({\n displayName: 'Branch',\n category: 'marketing',\n brandColor: '#7CB833',\n tagline:\n 'Sync Branch install attribution metrics (installs, opens, conversions) and deep-link click events from the Cross-Platform Analytics API for mobile attribution dashboards.',\n vendor: {\n name: 'Branch',\n domain: 'branch.io',\n apiDocs: 'https://help.branch.io/developers-hub/reference',\n website: 'https://www.branch.io',\n },\n auth: {\n summary:\n 'A Branch app key and secret, used together to authenticate Cross-Platform Analytics API requests.',\n setup: [\n 'In the Branch dashboard, open Account Settings -> Profile and copy the Branch Key (starts with `key_live_`).',\n 'On the same screen, reveal and copy the Branch Secret (starts with `secret_live_`). Both values are app-scoped; keep them in a secret store.',\n 'Reference them from the connector config as `branchKey: secret(\"BRANCH_KEY\")` and `branchSecret: secret(\"BRANCH_SECRET\")`.',\n ],\n },\n rateLimit:\n 'Branch enforces a per-app request quota on the Cross-Platform Analytics API (roughly 1 request/second). The connector issues one POST per data source per resource per sync and respects 429 + Retry-After backoff via the shared HTTP client.',\n limitations: [\n 'Daily granularity only - the connector requests `granularity=day` from the Branch Aggregate API to keep result cardinality bounded.',\n 'Cost attribution is best-effort - Branch only exposes `cost_in_local_currency` for ad-network-integrated channels. Rows without cost data carry `costEstimated: 0`.',\n 'Deep-link events are aggregated daily click counts per (date, channel, campaign, feature). Individual click-level records require the Branch Daily Export API which is intentionally out of scope.',\n ],\n});\n\nexport interface BranchSettings {\n lookbackDays?: number;\n resources?: readonly BranchResource[];\n}\n\nconst branchCredentials = {\n branchKey: {\n description: 'Branch app key (key_live_...)',\n auth: 'required' as const,\n },\n branchSecret: {\n description: 'Branch app secret (secret_live_...)',\n auth: 'required' as const,\n },\n} satisfies CredentialsSchema;\n\ntype BranchCredentials = typeof branchCredentials;\n\nconst PHASE_ORDER = ['install_metrics', 'deep_link_events'] as const;\n\ntype BranchPhase = (typeof PHASE_ORDER)[number];\n\nexport type BranchResource = BranchPhase;\n\ntype BranchSyncCursor = ChunkedSyncCursor<BranchPhase, string>;\n\nconst isBranchSyncCursor = makeChunkedCursorGuard(PHASE_ORDER);\n\nconst ANALYTICS_API_URL = 'https://api2.branch.io/v1/query/analytics';\nconst MS_PER_DAY = 24 * 60 * 60 * 1000;\nconst DEFAULT_LOOKBACK_DAYS = 90;\nconst INCREMENTAL_LOOKBACK_DAYS = 14;\n\nconst INSTALL_METRIC_NAME = 'branch_install_metrics';\nconst DEEP_LINK_EVENT_NAME = 'branch_deep_link_event';\n\nconst CHANNEL_DIMENSION = 'last_attributed_touch_data_tilde_channel';\nconst CAMPAIGN_DIMENSION = 'last_attributed_touch_data_tilde_campaign';\nconst FEATURE_DIMENSION = 'last_attributed_touch_data_tilde_feature';\n\nconst INSTALL_DATA_SOURCES = ['eo_install', 'eo_open', 'eo_event'] as const;\ntype InstallDataSource = (typeof INSTALL_DATA_SOURCES)[number];\n\nconst COUNT_FIELD_BY_DATA_SOURCE: Record<InstallDataSource, string> = {\n eo_install: 'installs',\n eo_open: 'opens',\n eo_event: 'conversions',\n};\n\nconst isoDateString = z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/);\nconst numericLike = z.union([z.number(), z.string(), z.null()]).optional();\n\nconst installResultRowSchema = z.object({\n unique_count: numericLike,\n result: z.object({\n timestamp: isoDateString,\n [CHANNEL_DIMENSION]: z.string().nullish(),\n [CAMPAIGN_DIMENSION]: z.string().nullish(),\n cost_in_local_currency: numericLike,\n }),\n});\n\nconst installResponseSchema = z.object({\n results: z.array(installResultRowSchema),\n});\n\nconst clickResultRowSchema = z.object({\n unique_count: numericLike,\n result: z.object({\n timestamp: isoDateString,\n [CHANNEL_DIMENSION]: z.string().nullish(),\n [CAMPAIGN_DIMENSION]: z.string().nullish(),\n [FEATURE_DIMENSION]: z.string().nullish(),\n }),\n});\n\nconst clickResponseSchema = z.object({\n results: z.array(clickResultRowSchema),\n});\n\nexport const branchResources = defineResources({\n [INSTALL_METRIC_NAME]: {\n shape: 'metric',\n description:\n 'Daily Branch attribution metrics bucketed by channel and campaign. Primary value is `installs`; `opens`, `conversions`, and `costEstimated` are carried as attributes.',\n endpoint: 'POST /v1/query/analytics',\n unit: 'installs',\n granularity: 'day',\n notes:\n 'Merges three Aggregate API calls (data_source=eo_install, eo_open, eo_event) keyed by (date, channel, campaign). Rows with missing channel or campaign are recorded as `null` for that attribute.',\n dimensions: [\n { name: 'date', description: 'Calendar day of the metric sample (UTC).' },\n { name: 'channel', description: 'Branch last-attributed channel.' },\n { name: 'campaign', description: 'Branch last-attributed campaign.' },\n { name: 'installs', description: 'Attributed installs on the day.' },\n { name: 'opens', description: 'Attributed app opens on the day.' },\n {\n name: 'conversions',\n description: 'Attributed in-app conversion events on the day.',\n },\n {\n name: 'costEstimated',\n description:\n 'Estimated cost in the app local currency (only populated for ad-network-integrated channels; 0 otherwise).',\n },\n ],\n responses: {\n install_metrics_installs: installResponseSchema,\n install_metrics_opens: installResponseSchema,\n install_metrics_conversions: installResponseSchema,\n },\n },\n [DEEP_LINK_EVENT_NAME]: {\n shape: 'event',\n description:\n 'Daily aggregated Branch deep-link click events bucketed by channel, campaign, and feature. One event per (date, channel, campaign, feature) row carrying the daily click count.',\n endpoint: 'POST /v1/query/analytics',\n notes:\n 'Sourced from data_source=eo_click. Event id encodes the bucket so resyncs are idempotent.',\n fields: [\n { name: 'date', description: 'Calendar day of the click bucket (UTC).' },\n { name: 'channel', description: 'Branch last-attributed channel.' },\n { name: 'campaign', description: 'Branch last-attributed campaign.' },\n {\n name: 'feature',\n description: 'Branch last-attributed feature (e.g. `sharing`).',\n },\n { name: 'clicks', description: 'Click count for the bucket.' },\n ],\n responses: { deep_link_events: clickResponseSchema },\n },\n});\n\nexport type BranchInstallResultRow = z.infer<typeof installResultRowSchema>;\nexport type BranchClickResultRow = z.infer<typeof clickResultRowSchema>;\n\ninterface BranchWindow {\n from: string;\n to: string;\n}\n\nfunction pad2(n: number): string {\n return String(n).padStart(2, '0');\n}\n\nfunction toIsoDate(ms: number): string {\n const d = new Date(ms);\n return `${d.getUTCFullYear()}-${pad2(d.getUTCMonth() + 1)}-${pad2(d.getUTCDate())}`;\n}\n\nfunction startOfUtcDay(ms: number): number {\n return Math.floor(ms / MS_PER_DAY) * MS_PER_DAY;\n}\n\nexport function getWindow(\n options: SyncOptions,\n lookbackDays: number,\n now: number = Date.now(),\n): BranchWindow {\n const today = startOfUtcDay(now);\n if (options.mode === 'latest') {\n return {\n from: toIsoDate(today - (INCREMENTAL_LOOKBACK_DAYS - 1) * MS_PER_DAY),\n to: toIsoDate(today),\n };\n }\n if (options.since) {\n const sinceMs = new Date(options.since).getTime();\n if (Number.isFinite(sinceMs)) {\n const requested = Math.max(\n 1,\n Math.ceil((today - startOfUtcDay(sinceMs)) / MS_PER_DAY) + 1,\n );\n const capped = Math.min(requested, lookbackDays);\n return {\n from: toIsoDate(today - (capped - 1) * MS_PER_DAY),\n to: toIsoDate(today),\n };\n }\n }\n return {\n from: toIsoDate(today - (lookbackDays - 1) * MS_PER_DAY),\n to: toIsoDate(today),\n };\n}\n\nfunction isoDateToMs(date: string): number {\n const [y, m, d] = date.split('-').map((part) => Number(part));\n if (\n y === undefined ||\n m === undefined ||\n d === undefined ||\n !Number.isFinite(y) ||\n !Number.isFinite(m) ||\n !Number.isFinite(d)\n ) {\n return NaN;\n }\n return Date.UTC(y, m - 1, d);\n}\n\nfunction parseNumber(value: unknown): number {\n if (typeof value === 'number' && Number.isFinite(value)) {\n return value;\n }\n if (typeof value === 'string' && value.trim() !== '') {\n const n = Number(value);\n return Number.isFinite(n) ? n : 0;\n }\n return 0;\n}\n\nfunction normalizeDateBucket(timestamp: string): string {\n return timestamp.slice(0, 10);\n}\n\ninterface InstallBucket {\n date: string;\n channel: string | null;\n campaign: string | null;\n installs: number;\n opens: number;\n conversions: number;\n costEstimated: number;\n}\n\nfunction bucketKey(\n date: string,\n channel: string | null,\n campaign: string | null,\n): string {\n return `${date}\u0001${channel ?? ''}\u0001${campaign ?? ''}`;\n}\n\nexport function mergeInstallBuckets(\n rowsByDataSource: Record<InstallDataSource, BranchInstallResultRow[]>,\n): InstallBucket[] {\n const buckets = new Map<string, InstallBucket>();\n for (const dataSource of INSTALL_DATA_SOURCES) {\n const field = COUNT_FIELD_BY_DATA_SOURCE[dataSource];\n for (const row of rowsByDataSource[dataSource]) {\n const date = normalizeDateBucket(row.result.timestamp);\n const channel =\n (row.result[CHANNEL_DIMENSION] as string | null | undefined) ?? null;\n const campaign =\n (row.result[CAMPAIGN_DIMENSION] as string | null | undefined) ?? null;\n const key = bucketKey(date, channel, campaign);\n let bucket = buckets.get(key);\n if (!bucket) {\n bucket = {\n date,\n channel,\n campaign,\n installs: 0,\n opens: 0,\n conversions: 0,\n costEstimated: 0,\n };\n buckets.set(key, bucket);\n }\n const count = parseNumber(row.unique_count);\n if (field === 'installs') {\n bucket.installs += count;\n } else if (field === 'opens') {\n bucket.opens += count;\n } else {\n bucket.conversions += count;\n }\n if (dataSource === 'eo_install') {\n bucket.costEstimated += parseNumber(row.result.cost_in_local_currency);\n }\n }\n }\n return Array.from(buckets.values()).sort((a, b) =>\n a.date < b.date ? -1 : a.date > b.date ? 1 : 0,\n );\n}\n\nexport function installBucketToMetricSample(\n bucket: InstallBucket,\n): MetricSample {\n const ts = isoDateToMs(bucket.date);\n return {\n name: INSTALL_METRIC_NAME,\n ts: Number.isFinite(ts) ? ts : 0,\n value: bucket.installs,\n attributes: {\n date: bucket.date,\n channel: bucket.channel,\n campaign: bucket.campaign,\n installs: bucket.installs,\n opens: bucket.opens,\n conversions: bucket.conversions,\n costEstimated: bucket.costEstimated,\n },\n };\n}\n\nexport function clickRowToEventRecord(row: BranchClickResultRow): Event {\n const date = normalizeDateBucket(row.result.timestamp);\n const channel =\n (row.result[CHANNEL_DIMENSION] as string | null | undefined) ?? null;\n const campaign =\n (row.result[CAMPAIGN_DIMENSION] as string | null | undefined) ?? null;\n const feature =\n (row.result[FEATURE_DIMENSION] as string | null | undefined) ?? null;\n const ts = isoDateToMs(date);\n const clicks = parseNumber(row.unique_count);\n const startTs = Number.isFinite(ts) ? ts : 0;\n return {\n name: DEEP_LINK_EVENT_NAME,\n start_ts: startTs,\n end_ts: startTs,\n attributes: {\n bucketKey: `${date}|${channel ?? ''}|${campaign ?? ''}|${feature ?? ''}`,\n date,\n channel,\n campaign,\n feature,\n clicks,\n },\n };\n}\n\nexport const id = 'branch';\n\nexport class BranchConnector extends BaseConnector<\n BranchSettings,\n BranchCredentials\n> {\n static readonly id = id;\n\n static readonly resources = branchResources;\n\n static readonly schemas = schemasFromResources(branchResources);\n\n static create(input: unknown, ctx?: ConnectorContext): BranchConnector {\n const parsed = configFields.parse(input);\n return new BranchConnector(\n { lookbackDays: parsed.lookbackDays, resources: parsed.resources },\n { branchKey: parsed.branchKey, branchSecret: parsed.branchSecret },\n ctx,\n );\n }\n\n readonly id = id;\n override readonly credentials = branchCredentials;\n\n private buildHeaders(): Record<string, string> {\n return {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'User-Agent': connectorUserAgent('branch'),\n };\n }\n\n private buildBody(\n dataSource: string,\n dimensions: string[],\n window: BranchWindow,\n ): string {\n return JSON.stringify({\n branch_key: this.creds.branchKey,\n branch_secret: this.creds.branchSecret,\n start_date: window.from,\n end_date: window.to,\n data_source: dataSource,\n dimensions,\n granularity: 'day',\n aggregation: 'unique_count',\n ordered: 'ascending',\n ordered_by: 'timestamp',\n });\n }\n\n private async fetchAggregate<T>(\n resource: string,\n dataSource: string,\n dimensions: string[],\n window: BranchWindow,\n signal?: AbortSignal,\n ): Promise<{ results?: T[] }> {\n const res = await this.post<{ results?: T[] }>(ANALYTICS_API_URL, {\n resource,\n headers: this.buildHeaders(),\n body: this.buildBody(dataSource, dimensions, window),\n signal,\n });\n return res.body;\n }\n\n private async fetchInstallBuckets(\n window: BranchWindow,\n signal?: AbortSignal,\n ): Promise<InstallBucket[]> {\n const dims = [CHANNEL_DIMENSION, CAMPAIGN_DIMENSION];\n const rowsByDataSource = {\n eo_install: [] as BranchInstallResultRow[],\n eo_open: [] as BranchInstallResultRow[],\n eo_event: [] as BranchInstallResultRow[],\n };\n for (const dataSource of INSTALL_DATA_SOURCES) {\n const field = COUNT_FIELD_BY_DATA_SOURCE[dataSource];\n const tag = `install_metrics_${field}`;\n const body = await this.fetchAggregate<BranchInstallResultRow>(\n tag,\n dataSource,\n dims,\n window,\n signal,\n );\n rowsByDataSource[dataSource] = body.results ?? [];\n }\n return mergeInstallBuckets(rowsByDataSource);\n }\n\n private async fetchClickRows(\n window: BranchWindow,\n signal?: AbortSignal,\n ): Promise<BranchClickResultRow[]> {\n const body = await this.fetchAggregate<BranchClickResultRow>(\n 'deep_link_events',\n 'eo_click',\n [CHANNEL_DIMENSION, CAMPAIGN_DIMENSION, FEATURE_DIMENSION],\n window,\n signal,\n );\n return body.results ?? [];\n }\n\n private async writePhase(\n storage: StorageHandle,\n phase: BranchPhase,\n window: BranchWindow,\n signal?: AbortSignal,\n ): Promise<void> {\n if (phase === 'install_metrics') {\n const buckets = await this.fetchInstallBuckets(window, signal);\n await storage.metrics([], { names: [INSTALL_METRIC_NAME] });\n for (const bucket of buckets) {\n await storage.metric(installBucketToMetricSample(bucket));\n }\n return;\n }\n const rows = await this.fetchClickRows(window, signal);\n for (const row of rows) {\n await storage.event(clickRowToEventRecord(row));\n }\n }\n\n async sync(\n options: SyncOptions,\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<SyncResult> {\n const cursor: BranchSyncCursor | undefined = isBranchSyncCursor(\n options.cursor,\n )\n ? options.cursor\n : undefined;\n const lookbackDays = this.settings.lookbackDays ?? DEFAULT_LOOKBACK_DAYS;\n const window = getWindow(options, lookbackDays);\n\n const phases = selectActivePhases<BranchResource, BranchPhase>(\n (r) => r,\n PHASE_ORDER,\n this.settings.resources,\n );\n\n return paginateChunked<BranchPhase, string>({\n phases,\n cursor,\n signal,\n logger: this.logger,\n fetchPage: async (_phase, _page, _sig) => ({ items: [null], next: null }),\n writeBatch: async (phase, _items, _page) => {\n await this.writePhase(storage, phase, window, signal);\n },\n });\n }\n}\n","import { BranchConnector } from './branch';\n\nexport {\n BranchConnector,\n branchResources as resources,\n clickRowToEventRecord,\n configFields,\n doc,\n getWindow,\n id,\n installBucketToMetricSample,\n mergeInstallBuckets,\n} from './branch';\nexport type {\n BranchClickResultRow,\n BranchInstallResultRow,\n BranchResource,\n BranchSettings,\n} from './branch';\nexport default BranchConnector;\n"],"mappings":";AEAO,IAAM,sBAAsB;AAE5B,IAAM,qBAAqB,qBAAqB,mBAAmB;AAEnE,SAAS,mBAAmB,aAA6B;AAC9D,SAAO,qBAAqB,WAAW,IAAI,mBAAmB;AAChE;;;AQLA;AAAA,EACE;AAAA,EAUA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,SAAS;AAEX,IAAM,eAAe;AAAA,EAC1B,EAAE,OAAO;AAAA,IACP,WAAW,EAAE,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC,EAAE,KAAK;AAAA,MAChD,OAAO;AAAA,MACP,aACE;AAAA,MACF,aAAa;AAAA,MACb,QAAQ;AAAA,IACV,CAAC;AAAA,IACD,cAAc,EAAE,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC,EAAE,KAAK;AAAA,MACnD,OAAO;AAAA,MACP,aACE;AAAA,MACF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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/branch.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 { connectorUserAgent } from '@rawdash/connector-shared';\nimport {\n BaseConnector,\n type ChunkedSyncCursor,\n type ConnectorContext,\n type ConnectorDoc,\n type CredentialsSchema,\n type Event,\n type MetricSample,\n type StorageHandle,\n type SyncOptions,\n type SyncResult,\n defineConfigFields,\n defineConnectorDoc,\n defineResources,\n makeChunkedCursorGuard,\n paginateChunked,\n schemasFromResources,\n selectActivePhases,\n} from '@rawdash/core';\nimport { z } from 'zod';\n\nexport const configFields = defineConfigFields(\n z.object({\n branchKey: z.object({ $secret: z.string() }).meta({\n label: 'Branch key',\n description:\n 'Your Branch app key (starts with `key_live_`). Find it in the Branch dashboard under Account Settings -> Profile.',\n placeholder: 'key_live_xxxxxxxxxxxxxxxxxxxxxxxxxx',\n secret: true,\n }),\n branchSecret: z.object({ $secret: z.string() }).meta({\n label: 'Branch secret',\n description:\n 'Your Branch app secret (starts with `secret_live_`). Find it next to the key in the Branch dashboard.',\n placeholder: 'secret_live_xxxxxxxxxxxxxxxxxxxxxxxxxx',\n secret: true,\n }),\n lookbackDays: z.number().int().positive().optional().meta({\n label: 'Lookback days (full sync)',\n description:\n 'How many calendar days of metrics/events to fetch on a full sync. Defaults to 90.',\n placeholder: '90',\n }),\n resources: z\n .array(z.enum(['install_metrics', 'deep_link_events']))\n .nonempty()\n .optional()\n .meta({\n label: 'Resources',\n description:\n 'Which Branch resources to sync. Omit to sync all of them.',\n }),\n }),\n);\n\nexport const doc: ConnectorDoc = defineConnectorDoc({\n displayName: 'Branch',\n category: 'marketing',\n brandColor: '#7CB833',\n tagline:\n 'Sync Branch install attribution metrics (installs, opens, conversions) and deep-link click events from the Cross-Platform Analytics API for mobile attribution dashboards.',\n vendor: {\n name: 'Branch',\n domain: 'branch.io',\n apiDocs: 'https://help.branch.io/developers-hub/reference',\n website: 'https://www.branch.io',\n },\n auth: {\n summary:\n 'A Branch app key and secret, used together to authenticate Cross-Platform Analytics API requests.',\n setup: [\n 'In the Branch dashboard, open Account Settings -> Profile and copy the Branch Key (starts with `key_live_`).',\n 'On the same screen, reveal and copy the Branch Secret (starts with `secret_live_`). Both values are app-scoped; keep them in a secret store.',\n 'Reference them from the connector config as `branchKey: secret(\"BRANCH_KEY\")` and `branchSecret: secret(\"BRANCH_SECRET\")`.',\n ],\n },\n rateLimit:\n 'Branch enforces a per-app request quota on the Cross-Platform Analytics API (roughly 1 request/second). The connector issues one POST per data source per resource per sync and respects 429 + Retry-After backoff via the shared HTTP client.',\n limitations: [\n 'Daily granularity only - the connector requests `granularity=day` from the Branch Aggregate API to keep result cardinality bounded.',\n 'Cost attribution is best-effort - Branch only exposes `cost_in_local_currency` for ad-network-integrated channels. Rows without cost data carry `costEstimated: 0`.',\n 'Deep-link events are aggregated daily click counts per (date, channel, campaign, feature). Individual click-level records require the Branch Daily Export API which is intentionally out of scope.',\n ],\n});\n\nexport interface BranchSettings {\n lookbackDays?: number;\n resources?: readonly BranchResource[];\n}\n\nconst branchCredentials = {\n branchKey: {\n description: 'Branch app key (key_live_...)',\n auth: 'required' as const,\n },\n branchSecret: {\n description: 'Branch app secret (secret_live_...)',\n auth: 'required' as const,\n },\n} satisfies CredentialsSchema;\n\ntype BranchCredentials = typeof branchCredentials;\n\nconst PHASE_ORDER = ['install_metrics', 'deep_link_events'] as const;\n\ntype BranchPhase = (typeof PHASE_ORDER)[number];\n\nexport type BranchResource = BranchPhase;\n\ntype BranchSyncCursor = ChunkedSyncCursor<BranchPhase, string>;\n\nconst isBranchSyncCursor = makeChunkedCursorGuard(PHASE_ORDER);\n\nconst ANALYTICS_API_URL = 'https://api2.branch.io/v1/query/analytics';\nconst MS_PER_DAY = 24 * 60 * 60 * 1000;\nconst DEFAULT_LOOKBACK_DAYS = 90;\nconst INCREMENTAL_LOOKBACK_DAYS = 14;\n\nconst INSTALL_METRIC_NAME = 'branch_install_metrics';\nconst DEEP_LINK_EVENT_NAME = 'branch_deep_link_event';\n\nconst CHANNEL_DIMENSION = 'last_attributed_touch_data_tilde_channel';\nconst CAMPAIGN_DIMENSION = 'last_attributed_touch_data_tilde_campaign';\nconst FEATURE_DIMENSION = 'last_attributed_touch_data_tilde_feature';\n\nconst INSTALL_DATA_SOURCES = ['eo_install', 'eo_open', 'eo_event'] as const;\ntype InstallDataSource = (typeof INSTALL_DATA_SOURCES)[number];\n\nconst COUNT_FIELD_BY_DATA_SOURCE: Record<InstallDataSource, string> = {\n eo_install: 'installs',\n eo_open: 'opens',\n eo_event: 'conversions',\n};\n\nconst isoDateString = z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/);\nconst numericLike = z.union([z.number(), z.string(), z.null()]).optional();\n\nconst installResultRowSchema = z.object({\n unique_count: numericLike,\n result: z.object({\n timestamp: isoDateString,\n [CHANNEL_DIMENSION]: z.string().nullish(),\n [CAMPAIGN_DIMENSION]: z.string().nullish(),\n cost_in_local_currency: numericLike,\n }),\n});\n\nconst installResponseSchema = z.object({\n results: z.array(installResultRowSchema),\n});\n\nconst clickResultRowSchema = z.object({\n unique_count: numericLike,\n result: z.object({\n timestamp: isoDateString,\n [CHANNEL_DIMENSION]: z.string().nullish(),\n [CAMPAIGN_DIMENSION]: z.string().nullish(),\n [FEATURE_DIMENSION]: z.string().nullish(),\n }),\n});\n\nconst clickResponseSchema = z.object({\n results: z.array(clickResultRowSchema),\n});\n\nexport const branchResources = defineResources({\n [INSTALL_METRIC_NAME]: {\n shape: 'metric',\n description:\n 'Daily Branch attribution metrics bucketed by channel and campaign. Primary value is `installs`; `opens`, `conversions`, and `costEstimated` are carried as attributes.',\n endpoint: 'POST /v1/query/analytics',\n unit: 'installs',\n granularity: 'day',\n notes:\n 'Merges three Aggregate API calls (data_source=eo_install, eo_open, eo_event) keyed by (date, channel, campaign). Rows with missing channel or campaign are recorded as `null` for that attribute.',\n dimensions: [\n { name: 'date', description: 'Calendar day of the metric sample (UTC).' },\n { name: 'channel', description: 'Branch last-attributed channel.' },\n { name: 'campaign', description: 'Branch last-attributed campaign.' },\n { name: 'installs', description: 'Attributed installs on the day.' },\n { name: 'opens', description: 'Attributed app opens on the day.' },\n {\n name: 'conversions',\n description: 'Attributed in-app conversion events on the day.',\n },\n {\n name: 'costEstimated',\n description:\n 'Estimated cost in the app local currency (only populated for ad-network-integrated channels; 0 otherwise).',\n },\n ],\n responses: {\n install_metrics_installs: installResponseSchema,\n install_metrics_opens: installResponseSchema,\n install_metrics_conversions: installResponseSchema,\n },\n },\n [DEEP_LINK_EVENT_NAME]: {\n shape: 'event',\n description:\n 'Daily aggregated Branch deep-link click events bucketed by channel, campaign, and feature. One event per (date, channel, campaign, feature) row carrying the daily click count.',\n endpoint: 'POST /v1/query/analytics',\n notes:\n 'Sourced from data_source=eo_click. Event id encodes the bucket so resyncs are idempotent.',\n fields: [\n { name: 'date', description: 'Calendar day of the click bucket (UTC).' },\n { name: 'channel', description: 'Branch last-attributed channel.' },\n { name: 'campaign', description: 'Branch last-attributed campaign.' },\n {\n name: 'feature',\n description: 'Branch last-attributed feature (e.g. `sharing`).',\n },\n { name: 'clicks', description: 'Click count for the bucket.' },\n ],\n filterable: [],\n responses: { deep_link_events: clickResponseSchema },\n },\n});\n\nexport type BranchInstallResultRow = z.infer<typeof installResultRowSchema>;\nexport type BranchClickResultRow = z.infer<typeof clickResultRowSchema>;\n\ninterface BranchWindow {\n from: string;\n to: string;\n}\n\nfunction pad2(n: number): string {\n return String(n).padStart(2, '0');\n}\n\nfunction toIsoDate(ms: number): string {\n const d = new Date(ms);\n return `${d.getUTCFullYear()}-${pad2(d.getUTCMonth() + 1)}-${pad2(d.getUTCDate())}`;\n}\n\nfunction startOfUtcDay(ms: number): number {\n return Math.floor(ms / MS_PER_DAY) * MS_PER_DAY;\n}\n\nexport function getWindow(\n options: SyncOptions,\n lookbackDays: number,\n now: number = Date.now(),\n): BranchWindow {\n const today = startOfUtcDay(now);\n if (options.mode === 'latest') {\n return {\n from: toIsoDate(today - (INCREMENTAL_LOOKBACK_DAYS - 1) * MS_PER_DAY),\n to: toIsoDate(today),\n };\n }\n if (options.since) {\n const sinceMs = new Date(options.since).getTime();\n if (Number.isFinite(sinceMs)) {\n const requested = Math.max(\n 1,\n Math.ceil((today - startOfUtcDay(sinceMs)) / MS_PER_DAY) + 1,\n );\n const capped = Math.min(requested, lookbackDays);\n return {\n from: toIsoDate(today - (capped - 1) * MS_PER_DAY),\n to: toIsoDate(today),\n };\n }\n }\n return {\n from: toIsoDate(today - (lookbackDays - 1) * MS_PER_DAY),\n to: toIsoDate(today),\n };\n}\n\nfunction isoDateToMs(date: string): number {\n const [y, m, d] = date.split('-').map((part) => Number(part));\n if (\n y === undefined ||\n m === undefined ||\n d === undefined ||\n !Number.isFinite(y) ||\n !Number.isFinite(m) ||\n !Number.isFinite(d)\n ) {\n return NaN;\n }\n return Date.UTC(y, m - 1, d);\n}\n\nfunction parseNumber(value: unknown): number {\n if (typeof value === 'number' && Number.isFinite(value)) {\n return value;\n }\n if (typeof value === 'string' && value.trim() !== '') {\n const n = Number(value);\n return Number.isFinite(n) ? n : 0;\n }\n return 0;\n}\n\nfunction normalizeDateBucket(timestamp: string): string {\n return timestamp.slice(0, 10);\n}\n\ninterface InstallBucket {\n date: string;\n channel: string | null;\n campaign: string | null;\n installs: number;\n opens: number;\n conversions: number;\n costEstimated: number;\n}\n\nfunction bucketKey(\n date: string,\n channel: string | null,\n campaign: string | null,\n): string {\n return `${date}|${channel ?? ''}|${campaign ?? ''}`;\n}\n\nexport function mergeInstallBuckets(\n rowsByDataSource: Record<InstallDataSource, BranchInstallResultRow[]>,\n): InstallBucket[] {\n const buckets = new Map<string, InstallBucket>();\n for (const dataSource of INSTALL_DATA_SOURCES) {\n const field = COUNT_FIELD_BY_DATA_SOURCE[dataSource];\n for (const row of rowsByDataSource[dataSource]) {\n const date = normalizeDateBucket(row.result.timestamp);\n const channel =\n (row.result[CHANNEL_DIMENSION] as string | null | undefined) ?? null;\n const campaign =\n (row.result[CAMPAIGN_DIMENSION] as string | null | undefined) ?? null;\n const key = bucketKey(date, channel, campaign);\n let bucket = buckets.get(key);\n if (!bucket) {\n bucket = {\n date,\n channel,\n campaign,\n installs: 0,\n opens: 0,\n conversions: 0,\n costEstimated: 0,\n };\n buckets.set(key, bucket);\n }\n const count = parseNumber(row.unique_count);\n if (field === 'installs') {\n bucket.installs += count;\n } else if (field === 'opens') {\n bucket.opens += count;\n } else {\n bucket.conversions += count;\n }\n if (dataSource === 'eo_install') {\n bucket.costEstimated += parseNumber(row.result.cost_in_local_currency);\n }\n }\n }\n return Array.from(buckets.values()).sort((a, b) =>\n a.date < b.date ? -1 : a.date > b.date ? 1 : 0,\n );\n}\n\nexport function installBucketToMetricSample(\n bucket: InstallBucket,\n): MetricSample {\n const ts = isoDateToMs(bucket.date);\n return {\n name: INSTALL_METRIC_NAME,\n ts: Number.isFinite(ts) ? ts : 0,\n value: bucket.installs,\n attributes: {\n date: bucket.date,\n channel: bucket.channel,\n campaign: bucket.campaign,\n installs: bucket.installs,\n opens: bucket.opens,\n conversions: bucket.conversions,\n costEstimated: bucket.costEstimated,\n },\n };\n}\n\nexport function clickRowToEventRecord(row: BranchClickResultRow): Event {\n const date = normalizeDateBucket(row.result.timestamp);\n const channel =\n (row.result[CHANNEL_DIMENSION] as string | null | undefined) ?? null;\n const campaign =\n (row.result[CAMPAIGN_DIMENSION] as string | null | undefined) ?? null;\n const feature =\n (row.result[FEATURE_DIMENSION] as string | null | undefined) ?? null;\n const ts = isoDateToMs(date);\n const clicks = parseNumber(row.unique_count);\n const startTs = Number.isFinite(ts) ? ts : 0;\n return {\n name: DEEP_LINK_EVENT_NAME,\n start_ts: startTs,\n end_ts: startTs,\n attributes: {\n bucketKey: `${date}|${channel ?? ''}|${campaign ?? ''}|${feature ?? ''}`,\n date,\n channel,\n campaign,\n feature,\n clicks,\n },\n };\n}\n\nexport const id = 'branch';\n\nexport class BranchConnector extends BaseConnector<\n BranchSettings,\n BranchCredentials\n> {\n static readonly id = id;\n\n static readonly resources = branchResources;\n\n static readonly schemas = schemasFromResources(branchResources);\n\n static create(input: unknown, ctx?: ConnectorContext): BranchConnector {\n const parsed = configFields.parse(input);\n return new BranchConnector(\n { lookbackDays: parsed.lookbackDays, resources: parsed.resources },\n { branchKey: parsed.branchKey, branchSecret: parsed.branchSecret },\n ctx,\n );\n }\n\n readonly id = id;\n override readonly credentials = branchCredentials;\n\n private buildHeaders(): Record<string, string> {\n return {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'User-Agent': connectorUserAgent('branch'),\n };\n }\n\n private buildBody(\n dataSource: string,\n dimensions: string[],\n window: BranchWindow,\n ): string {\n return JSON.stringify({\n branch_key: this.creds.branchKey,\n branch_secret: this.creds.branchSecret,\n start_date: window.from,\n end_date: window.to,\n data_source: dataSource,\n dimensions,\n granularity: 'day',\n aggregation: 'unique_count',\n ordered: 'ascending',\n ordered_by: 'timestamp',\n });\n }\n\n private async fetchAggregate<T>(\n resource: string,\n dataSource: string,\n dimensions: string[],\n window: BranchWindow,\n signal?: AbortSignal,\n ): Promise<{ results?: T[] }> {\n const res = await this.post<{ results?: T[] }>(ANALYTICS_API_URL, {\n resource,\n headers: this.buildHeaders(),\n body: this.buildBody(dataSource, dimensions, window),\n signal,\n });\n return res.body;\n }\n\n private async fetchInstallBuckets(\n window: BranchWindow,\n signal?: AbortSignal,\n ): Promise<InstallBucket[]> {\n const dims = [CHANNEL_DIMENSION, CAMPAIGN_DIMENSION];\n const rowsByDataSource = {\n eo_install: [] as BranchInstallResultRow[],\n eo_open: [] as BranchInstallResultRow[],\n eo_event: [] as BranchInstallResultRow[],\n };\n for (const dataSource of INSTALL_DATA_SOURCES) {\n const field = COUNT_FIELD_BY_DATA_SOURCE[dataSource];\n const tag = `install_metrics_${field}`;\n const body = await this.fetchAggregate<BranchInstallResultRow>(\n tag,\n dataSource,\n dims,\n window,\n signal,\n );\n rowsByDataSource[dataSource] = body.results ?? [];\n }\n return mergeInstallBuckets(rowsByDataSource);\n }\n\n private async fetchClickRows(\n window: BranchWindow,\n signal?: AbortSignal,\n ): Promise<BranchClickResultRow[]> {\n const body = await this.fetchAggregate<BranchClickResultRow>(\n 'deep_link_events',\n 'eo_click',\n [CHANNEL_DIMENSION, CAMPAIGN_DIMENSION, FEATURE_DIMENSION],\n window,\n signal,\n );\n return body.results ?? [];\n }\n\n private async writePhase(\n storage: StorageHandle,\n phase: BranchPhase,\n window: BranchWindow,\n signal?: AbortSignal,\n ): Promise<void> {\n if (phase === 'install_metrics') {\n const buckets = await this.fetchInstallBuckets(window, signal);\n await storage.metrics([], { names: [INSTALL_METRIC_NAME] });\n for (const bucket of buckets) {\n await storage.metric(installBucketToMetricSample(bucket));\n }\n return;\n }\n const rows = await this.fetchClickRows(window, signal);\n for (const row of rows) {\n await storage.event(clickRowToEventRecord(row));\n }\n }\n\n async sync(\n options: SyncOptions,\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<SyncResult> {\n const cursor: BranchSyncCursor | undefined = isBranchSyncCursor(\n options.cursor,\n )\n ? options.cursor\n : undefined;\n const lookbackDays = this.settings.lookbackDays ?? DEFAULT_LOOKBACK_DAYS;\n const window = getWindow(options, lookbackDays);\n\n const phases = selectActivePhases<BranchResource, BranchPhase>(\n (r) => r,\n PHASE_ORDER,\n this.settings.resources,\n );\n\n return paginateChunked<BranchPhase, string>({\n phases,\n cursor,\n signal,\n logger: this.logger,\n fetchPage: async (_phase, _page, _sig) => ({ items: [null], next: null }),\n writeBatch: async (phase, _items, _page) => {\n await this.writePhase(storage, phase, window, signal);\n },\n });\n }\n}\n","import { BranchConnector } from './branch';\n\nexport {\n BranchConnector,\n branchResources as resources,\n clickRowToEventRecord,\n configFields,\n doc,\n getWindow,\n id,\n installBucketToMetricSample,\n mergeInstallBuckets,\n} from './branch';\nexport type {\n BranchClickResultRow,\n BranchInstallResultRow,\n BranchResource,\n BranchSettings,\n} from './branch';\nexport default BranchConnector;\n"],"mappings":";AEAO,IAAM,sBAAsB;AAE5B,IAAM,qBAAqB,qBAAqB,mBAAmB;AAEnE,SAAS,mBAAmB,aAA6B;AAC9D,SAAO,qBAAqB,WAAW,IAAI,mBAAmB;AAChE;;;AQLA;AAAA,EACE;AAAA,EAUA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,SAAS;AAEX,IAAM,eAAe;AAAA,EAC1B,EAAE,OAAO;AAAA,IACP,WAAW,EAAE,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC,EAAE,KAAK;AAAA,MAChD,OAAO;AAAA,MACP,aACE;AAAA,MACF,aAAa;AAAA,MACb,QAAQ;AAAA,IACV,CAAC;AAAA,IACD,cAAc,EAAE,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC,EAAE,KAAK;AAAA,MACnD,OAAO;AAAA,MACP,aACE;AAAA,MACF,aAAa;AAAA,MACb,QAAQ;AAAA,IACV,CAAC;AAAA,IACD,cAAc,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,SAAS,EAAE,KAAK;AAAA,MACxD,OAAO;AAAA,MACP,aACE;AAAA,MACF,aAAa;AAAA,IACf,CAAC;AAAA,IACD,WAAW,EACR,MAAM,EAAE,KAAK,CAAC,mBAAmB,kBAAkB,CAAC,CAAC,EACrD,SAAS,EACT,SAAS,EACT,KAAK;AAAA,MACJ,OAAO;AAAA,MACP,aACE;AAAA,IACJ,CAAC;AAAA,EACL,CAAC;AACH;AAEO,IA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D,iBAAW,UAAU,SAAS;AAC5B,cAAM,QAAQ,OAAO,4BAA4B,MAAM,CAAC;AAAA,MAC1D;AACA;AAAA,IACF;AACA,UAAM,OAAO,MAAM,KAAK,eAAe,QAAQ,MAAM;AACrD,eAAW,OAAO,MAAM;AACtB,YAAM,QAAQ,MAAM,sBAAsB,GAAG,CAAC;AAAA,IAChD;AAAA,EACF;AAAA,EAEA,MAAM,KACJ,SACA,SACA,QACqB;AACrB,UAAM,SAAuC;AAAA,MAC3C,QAAQ;AAAA,IACV,IACI,QAAQ,SACR;AACJ,UAAM,eAAe,KAAK,SAAS,gBAAgB;AACnD,UAAM,SAAS,UAAU,SAAS,YAAY;AAE9C,UAAM,SAAS;AAAA,MACb,CAAC,MAAM;AAAA,MACP;AAAA,MACA,KAAK,SAAS;AAAA,IAChB;AAEA,WAAO,gBAAqC;AAAA,MAC1C;AAAA,MACA;AAAA,MACA;AAAA,MACA,QAAQ,KAAK;AAAA,MACb,WAAW,OAAO,QAAQ,OAAO,UAAU,EAAE,OAAO,CAAC,IAAI,GAAG,MAAM,KAAK;AAAA,MACvE,YAAY,OAAO,OAAO,QAAQ,UAAU;AAC1C,cAAM,KAAK,WAAW,SAAS,OAAO,QAAQ,MAAM;AAAA,MACtD;AAAA,IACF,CAAC;AAAA,EACH;AACF;;;ACpiBA,IAAO,gBAAQ;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rawdash/connector-branch",
|
|
3
|
-
"version": "0.0
|
|
3
|
+
"version": "0.24.0",
|
|
4
4
|
"description": "Rawdash connector for Branch — syncs daily install/open/conversion attribution metrics and deep-link click events via the Branch Cross-Platform Analytics API",
|
|
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.24.0"
|
|
34
28
|
},
|
|
35
29
|
"devDependencies": {
|
|
36
|
-
"@rawdash/connector-shared": "workspace:*",
|
|
37
|
-
"@rawdash/connector-test-utils": "workspace:*",
|
|
38
30
|
"fast-check": "^4.8.0",
|
|
39
31
|
"tsup": "^8.0.0",
|
|
40
32
|
"typescript": "^5.7.2",
|
|
41
|
-
"vitest": "^4.1.4"
|
|
33
|
+
"vitest": "^4.1.4",
|
|
34
|
+
"@rawdash/connector-shared": "0.3.1",
|
|
35
|
+
"@rawdash/connector-test-utils": "0.0.10"
|
|
36
|
+
},
|
|
37
|
+
"scripts": {
|
|
38
|
+
"build": "tsup",
|
|
39
|
+
"typecheck": "tsc --noEmit",
|
|
40
|
+
"lint": "eslint src",
|
|
41
|
+
"test": "vitest run"
|
|
42
42
|
}
|
|
43
|
-
}
|
|
43
|
+
}
|