@rawdash/connector-app-store-connect 0.21.1 → 0.23.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 -0
- 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
|
@@ -48,6 +48,7 @@ declare const appStoreConnectResources: {
|
|
|
48
48
|
readonly shape: "entity";
|
|
49
49
|
readonly description: "Apps registered in the team, with bundle id, SKU, and primary locale. Synced from /v1/apps.";
|
|
50
50
|
readonly endpoint: "GET /v1/apps";
|
|
51
|
+
readonly filterable: [];
|
|
51
52
|
readonly fields: [{
|
|
52
53
|
readonly name: "name";
|
|
53
54
|
readonly description: "App display name.";
|
|
@@ -163,6 +164,7 @@ declare class AppStoreConnectConnector extends BaseConnector<AppStoreConnectSett
|
|
|
163
164
|
readonly shape: "entity";
|
|
164
165
|
readonly description: "Apps registered in the team, with bundle id, SKU, and primary locale. Synced from /v1/apps.";
|
|
165
166
|
readonly endpoint: "GET /v1/apps";
|
|
167
|
+
readonly filterable: [];
|
|
166
168
|
readonly fields: [{
|
|
167
169
|
readonly name: "name";
|
|
168
170
|
readonly description: "App display name.";
|
package/dist/index.js
CHANGED
|
@@ -191,6 +191,7 @@ var appStoreConnectResources = defineResources({
|
|
|
191
191
|
shape: "entity",
|
|
192
192
|
description: "Apps registered in the team, with bundle id, SKU, and primary locale. Synced from /v1/apps.",
|
|
193
193
|
endpoint: "GET /v1/apps",
|
|
194
|
+
filterable: [],
|
|
194
195
|
fields: [
|
|
195
196
|
{ name: "name", description: "App display name." },
|
|
196
197
|
{
|
|
@@ -572,6 +573,7 @@ var AppStoreConnectConnector = class _AppStoreConnectConnector extends BaseConne
|
|
|
572
573
|
await storage.metrics(samples, { names: [APP_RATINGS_METRIC] });
|
|
573
574
|
}
|
|
574
575
|
async sync(options, storage, signal) {
|
|
576
|
+
this.cachedAppIds = null;
|
|
575
577
|
const cursor = this.resolveCursor(options.cursor);
|
|
576
578
|
const isFull = options.mode === "full";
|
|
577
579
|
const phases = selectActivePhases((r) => r, PHASE_ORDER, this.settings.resources);
|
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/app-store-connect.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 AuthError,\n connectorUserAgent,\n sanitizeAllowedUrl,\n} from '@rawdash/connector-shared';\nimport {\n BaseConnector,\n type ChunkedSyncCursor,\n type ConnectorContext,\n type ConnectorCost,\n type ConnectorDoc,\n type CredentialsSchema,\n type FetchPageResult,\n type JSONValue,\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 issuerId: z.string().min(1).meta({\n label: 'Issuer ID',\n description:\n 'App Store Connect API issuer ID (UUID). Found at Users and Access -> Integrations -> App Store Connect API.',\n placeholder: '69a6de7f-...',\n }),\n keyId: z.string().min(1).meta({\n label: 'Key ID',\n description:\n 'App Store Connect API key ID (10 characters). Shown next to the key in Users and Access -> Integrations -> App Store Connect API.',\n placeholder: 'ABC1234DEF',\n }),\n privateKey: z.object({ $secret: z.string() }).meta({\n label: 'Private key (.p8)',\n description:\n 'Contents of the App Store Connect API private key file (.p8). PKCS#8 PEM, starting with -----BEGIN PRIVATE KEY-----. Apple only lets you download the key once on creation.',\n placeholder: '-----BEGIN PRIVATE KEY-----\\n...',\n secret: true,\n }),\n vendorNumber: z\n .string()\n .regex(/^\\d{8,9}$/u, 'Vendor number must be an 8-9 digit numeric string')\n .optional()\n .meta({\n label: 'Vendor number',\n description:\n 'Apple vendor number (8-9 digit numeric). Required to sync sales reports (app_installs and app_revenue). Found in App Store Connect -> Payments and Financial Reports -> top-left dropdown.',\n placeholder: '85912345',\n }),\n resources: z\n .array(z.enum(['apps', 'app_installs', 'app_revenue', 'app_ratings']))\n .nonempty()\n .optional()\n .meta({\n label: 'Resources',\n description:\n 'Which App Store Connect resources to sync. Omit to sync all resources. Sales-derived resources (app_installs, app_revenue) require vendorNumber and are silently skipped without it.',\n }),\n salesBackfillDays: z.number().int().positive().max(365).optional().meta({\n label: 'Sales backfill window (days)',\n description:\n 'How many days of daily sales reports to pull on a full sync. Defaults to 30. Apple keeps daily reports for the last 365 days.',\n placeholder: '30',\n }),\n reviewLimit: z.number().int().positive().max(2000).optional().meta({\n label: 'Review sample size',\n description:\n 'Most-recent customer reviews to fetch per app for the app_ratings metric. Defaults to 200 (one Apple page). Higher values smooth the rolling rating at the cost of more requests.',\n placeholder: '200',\n }),\n }),\n);\n\nexport const doc: ConnectorDoc = defineConnectorDoc({\n displayName: 'App Store Connect',\n category: 'mobile',\n brandColor: '#0D96F6',\n tagline:\n 'Sync your iOS / macOS apps, daily sales (downloads and proceeds), and customer review ratings from the App Store Connect API for mobile-team dashboards.',\n vendor: {\n name: 'Apple',\n domain: 'apple.com',\n apiDocs: 'https://developer.apple.com/documentation/appstoreconnectapi',\n website: 'https://appstoreconnect.apple.com',\n },\n auth: {\n summary:\n 'App Store Connect API uses an ES256-signed JWT minted per request from an issuer ID, key ID, and a PKCS#8 EC private key (.p8) downloaded from App Store Connect. The key only needs read access to Sales and Reports.',\n setup: [\n 'Open App Store Connect -> Users and Access -> Integrations -> App Store Connect API.',\n 'Generate a key with the \"Sales\" or \"Finance\" role (read-only is enough). Copy the key ID shown in the table; capture the issuer ID at the top of the page.',\n 'Download the .p8 file once on creation - Apple does not let you re-download it.',\n 'Store the .p8 contents as a secret (e.g. APPSTORECONNECT_P8) and reference it as `privateKey: secret(\"APPSTORECONNECT_P8\")`.',\n 'Set `vendorNumber` from App Store Connect -> Payments and Financial Reports (the top-left dropdown shows the 8-9 digit number). Only required for app_installs and app_revenue.',\n ],\n },\n rateLimit:\n 'App Store Connect enforces a 3,600 requests-per-hour quota per team. The shared HTTP client backs off on 429 using Retry-After. Sales report endpoints are billed in the same bucket and cost one request per (day, report) pair.',\n limitations: [\n 'app_crashes (per-build crash counts) is not implemented. Apple only exposes crash analytics via the asynchronous Analytics Reports flow (create report request -> poll for completion -> download gzipped CSV) which spans multiple syncs; a follow-up will add it.',\n 'app_ratings is sampled from the most recent N customer reviews per app (default 200, capped at 2,000). It is a rolling rating, not the lifetime average shown in the App Store, because Apple does not expose lifetime aggregates over the REST API.',\n 'Sales reports are pulled in DAILY frequency only; weekly, monthly, and yearly summaries are not synced.',\n 'Subscription, in-app-purchase, and refund line items in the SALES summary report are aggregated into `units` and `proceeds` rather than broken out by product type. Filter by `productTypeIdentifier` on the metric sample attributes if you need to separate them.',\n ],\n});\n\nexport const cost: ConnectorCost = {\n recommendedInterval: '6 hours',\n minInterval: '1 hour',\n warning:\n 'Daily sales reports are only finalized 24-48 hours after the day closes; syncing more often than the recommended interval will not bring fresher revenue data.',\n};\n\nexport interface AppStoreConnectSettings {\n resources?: readonly AppStoreConnectResource[];\n vendorNumber?: string;\n salesBackfillDays?: number;\n reviewLimit?: number;\n}\n\nconst appStoreConnectCredentials = {\n issuerId: {\n description: 'App Store Connect API issuer ID',\n auth: 'required' as const,\n },\n keyId: {\n description: 'App Store Connect API key ID',\n auth: 'required' as const,\n },\n privateKey: {\n description: 'App Store Connect API private key (.p8 PEM contents)',\n auth: 'required' as const,\n },\n} satisfies CredentialsSchema;\n\ntype AppStoreConnectCredentials = typeof appStoreConnectCredentials;\n\nconst PHASE_ORDER = [\n 'apps',\n 'app_installs',\n 'app_revenue',\n 'app_ratings',\n] as const;\n\ntype AppStoreConnectPhase = (typeof PHASE_ORDER)[number];\n\nexport type AppStoreConnectResource = AppStoreConnectPhase;\n\nconst isAppStoreConnectCursor = makeChunkedCursorGuard(PHASE_ORDER);\n\ntype AppStoreConnectCursor = ChunkedSyncCursor<AppStoreConnectPhase, string>;\n\nconst API_HOST = 'api.appstoreconnect.apple.com';\nconst API_BASE = `https://${API_HOST}`;\nconst APPS_PATH = '/v1/apps';\nconst SALES_REPORTS_PATH = '/v1/salesReports';\nconst PER_PAGE = 200;\nconst DEFAULT_SALES_BACKFILL_DAYS = 30;\nconst DEFAULT_REVIEW_LIMIT = 200;\nconst SALES_REPORT_DELAY_HOURS = 48;\nconst MS_PER_DAY = 86_400_000;\nconst MS_PER_HOUR = 3_600_000;\n\nconst APP_ENTITY = 'app_store_connect_app';\nconst APP_INSTALLS_METRIC = 'app_store_connect_app_installs';\nconst APP_REVENUE_METRIC = 'app_store_connect_app_revenue';\nconst APP_RATINGS_METRIC = 'app_store_connect_app_ratings';\n\ninterface AppRecord {\n id: string;\n attributes?: {\n name?: string | null;\n bundleId?: string | null;\n sku?: string | null;\n primaryLocale?: string | null;\n } | null;\n}\n\ninterface ReviewRecord {\n id: string;\n attributes?: {\n rating?: number | null;\n territory?: string | null;\n title?: string | null;\n reviewerNickname?: string | null;\n createdDate?: string | null;\n } | null;\n}\n\nconst appAttributesSchema = z.object({\n name: z.string().nullish(),\n bundleId: z.string().nullish(),\n sku: z.string().nullish(),\n primaryLocale: z.string().nullish(),\n});\n\nconst appSchema = z.object({\n id: z.string().min(1),\n type: z.string().optional(),\n attributes: appAttributesSchema.nullish(),\n});\n\nconst appsResponseSchema = z.object({\n data: z.array(appSchema),\n links: z\n .object({\n next: z.string().nullish(),\n })\n .nullish(),\n});\n\nconst reviewAttributesSchema = z.object({\n rating: z.number().int().min(1).max(5).nullish(),\n territory: z.string().nullish(),\n title: z.string().nullish(),\n reviewerNickname: z.string().nullish(),\n createdDate: z.string().nullish(),\n});\n\nconst reviewSchema = z.object({\n id: z.string().min(1),\n type: z.string().optional(),\n attributes: reviewAttributesSchema.nullish(),\n});\n\nconst reviewsResponseSchema = z.object({\n data: z.array(reviewSchema),\n links: z\n .object({\n next: z.string().nullish(),\n })\n .nullish(),\n});\n\nexport const appStoreConnectResources = defineResources({\n [APP_ENTITY]: {\n shape: 'entity',\n description:\n 'Apps registered in the team, with bundle id, SKU, and primary locale. Synced from /v1/apps.',\n endpoint: 'GET /v1/apps',\n fields: [\n { name: 'name', description: 'App display name.' },\n {\n name: 'bundleId',\n description: 'Bundle identifier, e.g. com.example.app.',\n },\n {\n name: 'sku',\n description: 'App SKU set when the app was registered.',\n },\n {\n name: 'primaryLocale',\n description: 'Primary App Store locale, e.g. en-US.',\n },\n ],\n responses: { apps: appsResponseSchema },\n },\n [APP_INSTALLS_METRIC]: {\n shape: 'metric',\n description:\n 'Daily installs (units sold or downloaded) aggregated from the SALES SUMMARY report by (date, app, country code, product type). One sample per (day, app, country, productTypeIdentifier).',\n endpoint: 'GET /v1/salesReports',\n granularity: 'daily',\n notes:\n 'Requires a vendor number. Apple delays daily reports by ~24-48 hours; the connector backs off two days from today to avoid empty / partial reports. Reports are gzipped TSV under the hood.',\n dimensions: [\n {\n name: 'appId',\n description:\n 'App Store Connect app id (Apple Identifier from the report).',\n },\n {\n name: 'countryCode',\n description: 'Two-letter ISO country code from the sale.',\n },\n {\n name: 'productTypeIdentifier',\n description:\n 'Apple product type, e.g. 1 (paid app), 1F (universal app), IA1 (in-app purchase).',\n },\n ],\n responses: { sales_installs_report: z.string() },\n },\n [APP_REVENUE_METRIC]: {\n shape: 'metric',\n description:\n 'Daily developer proceeds aggregated from the SALES SUMMARY report by (date, app, country code, product type). Values are summed across rows that share a currency; rows are emitted per currency.',\n endpoint: 'GET /v1/salesReports',\n unit: 'native currency (see currency attribute)',\n granularity: 'daily',\n notes:\n 'Proceeds are NOT FX-normalised; each sample carries its native currency in the `currency` attribute. Filter or convert downstream.',\n dimensions: [\n {\n name: 'appId',\n description: 'App Store Connect app id.',\n },\n {\n name: 'countryCode',\n description: 'Two-letter ISO country code from the sale.',\n },\n {\n name: 'currency',\n description:\n 'ISO 4217 currency of the proceeds, e.g. USD, EUR, JPY (matches Apple \"Currency of Proceeds\").',\n },\n {\n name: 'productTypeIdentifier',\n description: 'Apple product type code (same as app_installs).',\n },\n ],\n responses: { sales_revenue_report: z.string() },\n },\n [APP_RATINGS_METRIC]: {\n shape: 'metric',\n description:\n 'Rolling per-review ratings sampled from the most-recent N customer reviews per app (default 200). Each sample carries one review with the rating (1-5) as the value and the territory on the attribute.',\n endpoint: 'GET /v1/apps/{id}/customerReviews',\n notes:\n 'Apple does NOT expose the lifetime average rating over the REST API. Average over a time window downstream to get a rolling rating.',\n dimensions: [\n {\n name: 'appId',\n description: 'App Store Connect app id.',\n },\n {\n name: 'territory',\n description: 'Two-letter ISO country code where the review was filed.',\n },\n ],\n responses: { customer_reviews: reviewsResponseSchema },\n },\n});\n\nexport const id = 'app-store-connect';\n\nexport class AppStoreConnectConnector extends BaseConnector<\n AppStoreConnectSettings,\n AppStoreConnectCredentials\n> {\n static readonly id = id;\n\n static readonly resources = appStoreConnectResources;\n\n static readonly schemas = schemasFromResources(appStoreConnectResources);\n\n static readonly cost = cost;\n\n static create(\n input: unknown,\n ctx?: ConnectorContext,\n ): AppStoreConnectConnector {\n const parsed = configFields.parse(input);\n return new AppStoreConnectConnector(\n {\n resources: parsed.resources,\n vendorNumber: parsed.vendorNumber,\n salesBackfillDays: parsed.salesBackfillDays,\n reviewLimit: parsed.reviewLimit,\n },\n {\n issuerId: parsed.issuerId,\n keyId: parsed.keyId,\n privateKey: parsed.privateKey,\n },\n ctx,\n );\n }\n\n readonly id = id;\n override readonly credentials = appStoreConnectCredentials;\n\n private cachedJwt: { token: string; expiresAt: number } | null = null;\n private cachedAppIds: string[] | null = null;\n\n private async buildAuthHeader(): Promise<string> {\n const now = Math.floor(Date.now() / 1000);\n if (this.cachedJwt && this.cachedJwt.expiresAt > now + 60) {\n return `Bearer ${this.cachedJwt.token}`;\n }\n const { issuerId, keyId, privateKey } = this.creds;\n if (!issuerId || !keyId || !privateKey) {\n throw new AuthError(`${this.id}: missing App Store Connect credentials`);\n }\n const exp = now + 900;\n const jwt = await signES256Jwt({\n header: { alg: 'ES256', kid: keyId, typ: 'JWT' },\n payload: {\n iss: issuerId,\n iat: now,\n exp,\n aud: 'appstoreconnect-v1',\n },\n privateKeyPem: privateKey,\n });\n this.cachedJwt = { token: jwt, expiresAt: exp };\n return `Bearer ${jwt}`;\n }\n\n private async authHeaders(): Promise<Record<string, string>> {\n return {\n Authorization: await this.buildAuthHeader(),\n Accept: 'application/json',\n 'User-Agent': connectorUserAgent(this.id),\n };\n }\n\n private sanitizeListUrl(\n phase: AppStoreConnectPhase,\n pageUrl: string | null,\n ): string | null {\n const allowedPath = phase === 'apps' ? APPS_PATH : null;\n if (allowedPath === null) {\n return null;\n }\n return sanitizeAllowedUrl({\n url: pageUrl,\n host: API_HOST,\n pathname: allowedPath,\n });\n }\n\n private resolveCursor(cursor: unknown): AppStoreConnectCursor | undefined {\n if (!isAppStoreConnectCursor(cursor)) {\n return undefined;\n }\n if (cursor.phase === 'apps') {\n return {\n phase: cursor.phase,\n page: this.sanitizeListUrl(cursor.phase, cursor.page),\n };\n }\n return { phase: cursor.phase, page: null };\n }\n\n private async listApps(signal?: AbortSignal): Promise<string[]> {\n if (this.cachedAppIds !== null) {\n return this.cachedAppIds;\n }\n const ids: string[] = [];\n let url: string | null = `${API_BASE}${APPS_PATH}?limit=${PER_PAGE}`;\n while (url !== null) {\n if (signal?.aborted) {\n return ids;\n }\n const headers = await this.authHeaders();\n const res = await this.get<z.infer<typeof appsResponseSchema>>(url, {\n resource: 'apps',\n headers,\n signal,\n });\n for (const app of res.body.data ?? []) {\n ids.push(app.id);\n }\n const next = res.body.links?.next ?? null;\n url = this.sanitizeListUrl('apps', next);\n }\n this.cachedAppIds = ids;\n return ids;\n }\n\n private async fetchAppsPage(\n page: string | null,\n signal?: AbortSignal,\n ): Promise<FetchPageResult<string>> {\n const url = page ?? `${API_BASE}${APPS_PATH}?limit=${PER_PAGE}`;\n const headers = await this.authHeaders();\n const res = await this.get<z.infer<typeof appsResponseSchema>>(url, {\n resource: 'apps',\n headers,\n signal,\n });\n const items = res.body.data ?? [];\n if (this.cachedAppIds === null) {\n this.cachedAppIds = [];\n }\n for (const app of items) {\n if (!this.cachedAppIds.includes(app.id)) {\n this.cachedAppIds.push(app.id);\n }\n }\n const rawNext = res.body.links?.next ?? null;\n const next = this.sanitizeListUrl('apps', rawNext);\n return { items, next };\n }\n\n private buildSalesReportUrl(reportDate: string): string {\n const vendor = this.settings.vendorNumber;\n if (!vendor) {\n throw new Error(\n 'vendorNumber is required for app_installs / app_revenue resources',\n );\n }\n const params = new URLSearchParams();\n params.set('filter[frequency]', 'DAILY');\n params.set('filter[reportType]', 'SALES');\n params.set('filter[reportSubType]', 'SUMMARY');\n params.set('filter[vendorNumber]', vendor);\n params.set('filter[reportDate]', reportDate);\n return `${API_BASE}${SALES_REPORTS_PATH}?${params.toString()}`;\n }\n\n private async fetchSalesReportTsv(\n reportDate: string,\n signal?: AbortSignal,\n ): Promise<string | null> {\n const url = this.buildSalesReportUrl(reportDate);\n\n const res = await this.withRetry<Response>(\n async (sig) => {\n const headers = await this.authHeaders();\n headers['Accept'] = 'application/a-gzip';\n const response = await globalThis.fetch(url, {\n method: 'GET',\n headers,\n signal: sig,\n });\n if (response.status === 429) {\n const retryAfter = Number(response.headers.get('retry-after') ?? '');\n if (Number.isFinite(retryAfter) && retryAfter > 0) {\n await this.sleep(retryAfter * 1000, sig);\n }\n return { status: 'retry' };\n }\n return { status: 'done', value: response };\n },\n { signal },\n );\n if (res === null) {\n throw new Error(\n `App Store Connect sales report ${reportDate} failed: exhausted retries on HTTP 429`,\n );\n }\n if (res.status === 404) {\n return null;\n }\n if (!res.ok) {\n throw new Error(\n `App Store Connect sales report ${reportDate} failed: HTTP ${res.status}`,\n );\n }\n const body = res.body;\n if (!body) {\n return null;\n }\n const decompressed = body.pipeThrough(new DecompressionStream('gzip'));\n return await new Response(decompressed).text();\n }\n\n private async fetchReviewsForApp(\n appId: string,\n limit: number,\n signal?: AbortSignal,\n ): Promise<ReviewRecord[]> {\n const reviews: ReviewRecord[] = [];\n const reviewsBase = `/v1/apps/${encodeURIComponent(appId)}/customerReviews`;\n let url: string | null =\n `${API_BASE}${reviewsBase}?limit=${PER_PAGE}&sort=-createdDate`;\n while (url !== null && reviews.length < limit) {\n if (signal?.aborted) {\n return reviews;\n }\n const headers = await this.authHeaders();\n const res = await this.get<z.infer<typeof reviewsResponseSchema>>(url, {\n resource: 'customer_reviews',\n headers,\n signal,\n });\n for (const review of res.body.data ?? []) {\n reviews.push(review);\n if (reviews.length >= limit) {\n break;\n }\n }\n const rawNext = res.body.links?.next ?? null;\n url = sanitizeAllowedUrl({\n url: rawNext,\n host: API_HOST,\n pathname: reviewsBase,\n });\n }\n return reviews;\n }\n\n private async writeApps(\n storage: StorageHandle,\n items: AppRecord[],\n ): Promise<void> {\n const nowMs = Date.now();\n for (const app of items) {\n const attrs = app.attributes ?? {};\n await storage.entity({\n type: APP_ENTITY,\n id: app.id,\n attributes: {\n name: attrs.name ?? null,\n bundleId: attrs.bundleId ?? null,\n sku: attrs.sku ?? null,\n primaryLocale: attrs.primaryLocale ?? null,\n },\n updated_at: nowMs,\n });\n }\n }\n\n private async syncSalesReports(\n storage: StorageHandle,\n metricName: typeof APP_INSTALLS_METRIC | typeof APP_REVENUE_METRIC,\n options: SyncOptions,\n signal?: AbortSignal,\n ): Promise<void> {\n if (!this.settings.vendorNumber) {\n this.logger.info('skipping sales report (no vendorNumber configured)', {\n resource: metricName,\n });\n await storage.metrics([], { names: [metricName] });\n return;\n }\n const dates = computeSalesReportDates(options, this.settings);\n const samples: MetricSample[] = [];\n for (const reportDate of dates) {\n if (signal?.aborted) {\n return;\n }\n let tsv: string | null;\n try {\n tsv = await this.fetchSalesReportTsv(reportDate, signal);\n } catch (err) {\n this.logger.warn('sales report fetch failed', {\n reportDate,\n resource: metricName,\n error: err instanceof Error ? err.message : String(err),\n });\n continue;\n }\n if (tsv === null || tsv.length === 0) {\n continue;\n }\n for (const sample of parseSalesReportTsv(tsv, metricName)) {\n samples.push(sample);\n }\n }\n await storage.metrics(samples, { names: [metricName] });\n }\n\n private async syncAppRatings(\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<void> {\n const appIds = await this.listApps(signal);\n const limit = this.settings.reviewLimit ?? DEFAULT_REVIEW_LIMIT;\n const samples: MetricSample[] = [];\n for (const appId of appIds) {\n if (signal?.aborted) {\n return;\n }\n const reviews = await this.fetchReviewsForApp(appId, limit, signal);\n for (const review of reviews) {\n const attrs = review.attributes ?? {};\n if (typeof attrs.rating !== 'number') {\n continue;\n }\n const ts = isoToMs(attrs.createdDate);\n if (ts === null) {\n continue;\n }\n const attributes: Record<string, JSONValue> = {\n appId,\n reviewId: review.id,\n territory: attrs.territory ?? null,\n };\n samples.push({\n name: APP_RATINGS_METRIC,\n ts,\n value: attrs.rating,\n attributes,\n });\n }\n }\n await storage.metrics(samples, { names: [APP_RATINGS_METRIC] });\n }\n\n async sync(\n options: SyncOptions,\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<SyncResult> {\n const cursor = this.resolveCursor(options.cursor);\n const isFull = options.mode === 'full';\n const phases = selectActivePhases<\n AppStoreConnectResource,\n AppStoreConnectPhase\n >((r) => r, PHASE_ORDER, this.settings.resources);\n\n return paginateChunked<AppStoreConnectPhase, string>({\n phases,\n cursor,\n signal,\n logger: this.logger,\n fetchPage: async (phase, page, sig) => {\n if (phase === 'apps') {\n return this.fetchAppsPage(page, sig);\n }\n return { items: [{ phase }], next: null };\n },\n writeBatch: async (phase, items, page) => {\n if (phase === 'apps') {\n if (page === null && isFull) {\n await storage.entities([], { types: [APP_ENTITY] });\n }\n await this.writeApps(storage, items as AppRecord[]);\n return;\n }\n if (phase === 'app_installs') {\n await this.syncSalesReports(\n storage,\n APP_INSTALLS_METRIC,\n options,\n signal,\n );\n return;\n }\n if (phase === 'app_revenue') {\n await this.syncSalesReports(\n storage,\n APP_REVENUE_METRIC,\n options,\n signal,\n );\n return;\n }\n if (phase === 'app_ratings') {\n await this.syncAppRatings(storage, signal);\n return;\n }\n },\n });\n }\n}\n\nfunction isoToMs(value: string | null | undefined): number | null {\n if (!value) {\n return null;\n }\n const ms = Date.parse(value);\n return Number.isFinite(ms) ? ms : null;\n}\n\nfunction pad2(n: number): string {\n return n < 10 ? `0${n}` : String(n);\n}\n\nfunction toIsoDate(d: Date): string {\n return `${d.getUTCFullYear()}-${pad2(d.getUTCMonth() + 1)}-${pad2(\n d.getUTCDate(),\n )}`;\n}\n\nfunction parseSalesDate(value: string): number | null {\n const m = /^(\\d{2})\\/(\\d{2})\\/(\\d{4})$/u.exec(value);\n if (m) {\n const month = Number(m[1]!);\n const day = Number(m[2]!);\n const year = Number(m[3]!);\n const ms = Date.UTC(year, month - 1, day);\n return Number.isFinite(ms) ? ms : null;\n }\n const direct = Date.parse(`${value}T00:00:00Z`);\n return Number.isFinite(direct) ? direct : null;\n}\n\nexport function computeSalesReportDates(\n options: SyncOptions,\n settings: AppStoreConnectSettings,\n): string[] {\n const now = Date.now();\n const endMs = now - SALES_REPORT_DELAY_HOURS * MS_PER_HOUR;\n let startMs: number;\n if (options.since) {\n const sinceMs = Date.parse(options.since);\n startMs = Number.isFinite(sinceMs) ? sinceMs : endMs - MS_PER_DAY;\n } else if (options.mode === 'latest') {\n startMs = endMs - 2 * MS_PER_DAY;\n } else {\n const days = settings.salesBackfillDays ?? DEFAULT_SALES_BACKFILL_DAYS;\n startMs = endMs - days * MS_PER_DAY;\n }\n if (startMs > endMs) {\n return [];\n }\n const dates: string[] = [];\n const start = new Date(Math.floor(startMs / MS_PER_DAY) * MS_PER_DAY);\n const end = new Date(Math.floor(endMs / MS_PER_DAY) * MS_PER_DAY);\n for (\n let d = new Date(start.getTime());\n d.getTime() <= end.getTime();\n d.setUTCDate(d.getUTCDate() + 1)\n ) {\n dates.push(toIsoDate(d));\n }\n return dates;\n}\n\nexport function parseSalesReportTsv(\n tsv: string,\n metricName: typeof APP_INSTALLS_METRIC | typeof APP_REVENUE_METRIC,\n): MetricSample[] {\n const lines = tsv.split(/\\r?\\n/u).filter((l) => l.length > 0);\n if (lines.length < 2) {\n return [];\n }\n const header = lines[0]!.split('\\t').map((h) => h.trim());\n const idx = (name: string): number => header.indexOf(name);\n\n const beginDateIdx = idx('Begin Date');\n const unitsIdx = idx('Units');\n const proceedsIdx = idx('Developer Proceeds');\n const countryIdx = idx('Country Code');\n const appleIdIdx = idx('Apple Identifier');\n const currencyIdx = idx('Currency of Proceeds');\n const productTypeIdx = idx('Product Type Identifier');\n\n if (\n beginDateIdx === -1 ||\n appleIdIdx === -1 ||\n countryIdx === -1 ||\n (metricName === APP_INSTALLS_METRIC && unitsIdx === -1) ||\n (metricName === APP_REVENUE_METRIC &&\n (proceedsIdx === -1 || currencyIdx === -1))\n ) {\n return [];\n }\n\n const samples: MetricSample[] = [];\n for (let i = 1; i < lines.length; i++) {\n const row = lines[i]!.split('\\t');\n const ts = parseSalesDate(row[beginDateIdx]?.trim() ?? '');\n if (ts === null) {\n continue;\n }\n const appId = row[appleIdIdx]?.trim() ?? '';\n if (appId === '') {\n continue;\n }\n const countryCode = row[countryIdx]?.trim() ?? '';\n const productType =\n productTypeIdx === -1 ? '' : (row[productTypeIdx]?.trim() ?? '');\n\n if (metricName === APP_INSTALLS_METRIC) {\n const raw = row[unitsIdx]?.trim() ?? '';\n const value = Number.parseFloat(raw);\n if (!Number.isFinite(value)) {\n continue;\n }\n const attributes: Record<string, JSONValue> = {\n appId,\n countryCode,\n productTypeIdentifier: productType,\n };\n samples.push({ name: metricName, ts, value, attributes });\n } else {\n const raw = row[proceedsIdx]?.trim() ?? '';\n const value = Number.parseFloat(raw);\n if (!Number.isFinite(value)) {\n continue;\n }\n const currency = row[currencyIdx]?.trim() ?? '';\n const attributes: Record<string, JSONValue> = {\n appId,\n countryCode,\n currency,\n productTypeIdentifier: productType,\n };\n samples.push({ name: metricName, ts, value, attributes });\n }\n }\n return samples;\n}\n\ninterface JwtHeader {\n alg: 'ES256';\n kid: string;\n typ: 'JWT';\n}\n\ninterface JwtPayload {\n iss: string;\n iat: number;\n exp: number;\n aud: string;\n}\n\nexport async function signES256Jwt({\n header,\n payload,\n privateKeyPem,\n}: {\n header: JwtHeader;\n payload: JwtPayload;\n privateKeyPem: string;\n}): Promise<string> {\n const encoder = new TextEncoder();\n const headerB64 = base64urlEncode(encoder.encode(JSON.stringify(header)));\n const payloadB64 = base64urlEncode(encoder.encode(JSON.stringify(payload)));\n const signingInput = `${headerB64}.${payloadB64}`;\n const key = await importEcPrivateKey(privateKeyPem);\n const signature = await globalThis.crypto.subtle.sign(\n { name: 'ECDSA', hash: 'SHA-256' },\n key,\n encoder.encode(signingInput),\n );\n return `${signingInput}.${base64urlEncode(new Uint8Array(signature))}`;\n}\n\nasync function importEcPrivateKey(pem: string): Promise<CryptoKey> {\n const trimmed = pem.trim();\n const body = trimmed\n .replace(/-----BEGIN PRIVATE KEY-----/u, '')\n .replace(/-----END PRIVATE KEY-----/u, '')\n .replace(/\\s+/gu, '');\n if (body.length === 0) {\n throw new AuthError(\n 'app-store-connect: privateKey is empty or not a PEM-encoded PKCS#8 key',\n );\n }\n const der = base64ToBytes(body);\n return globalThis.crypto.subtle.importKey(\n 'pkcs8',\n der,\n { name: 'ECDSA', namedCurve: 'P-256' },\n false,\n ['sign'],\n );\n}\n\nfunction base64ToBytes(b64: string): Uint8Array<ArrayBuffer> {\n return Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));\n}\n\nfunction base64urlEncode(bytes: Uint8Array): string {\n let binary = '';\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]!);\n }\n return btoa(binary)\n .replace(/\\+/gu, '-')\n .replace(/\\//gu, '_')\n .replace(/=+$/u, '');\n}\n","import { AppStoreConnectConnector } from './app-store-connect';\n\nexport {\n AppStoreConnectConnector,\n appStoreConnectResources as resources,\n configFields,\n cost,\n doc,\n id,\n} from './app-store-connect';\nexport type {\n AppStoreConnectResource,\n AppStoreConnectSettings,\n} from './app-store-connect';\nexport default AppStoreConnectConnector;\n"],"mappings":";AASO,IAAe,kBAAf,cAAuC,MAAM;EAEzC;EAET,YAAY,SAAiB,UAAyB;AACpD,UAAM,OAAO;AACb,SAAK,OAAO,WAAW;AACvB,SAAK,WAAW;EAClB;AACF;AAgBO,IAAM,YAAN,cAAwB,gBAAgB;EACpC,OAAO;AAClB;AEpCO,IAAM,sBAAsB;AAE5B,IAAM,qBAAqB,qBAAqB,mBAAmB;AAEnE,SAAS,mBAAmB,aAA6B;AAC9D,SAAO,qBAAqB,WAAW,IAAI,mBAAmB;AAChE;AICO,SAAS,mBACd,SACe;AACf,QAAM,EAAE,KAAK,MAAM,UAAU,WAAW,SAAS,IAAI;AACrD,MAAI,QAAQ,MAAM;AAChB,WAAO;EACT;AACA,MAAI;AACF,UAAM,IAAI,IAAI,IAAI,GAAG;AACrB,QAAI,EAAE,aAAa,YAAY,EAAE,SAAS,QAAQ,EAAE,aAAa,UAAU;AACzE,a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MAAM,mBAAmB,aAAa;AAClD,QAAM,YAAY,MAAM,WAAW,OAAO,OAAO;AAAA,IAC/C,EAAE,MAAM,SAAS,MAAM,UAAU;AAAA,IACjC;AAAA,IACA,QAAQ,OAAO,YAAY;AAAA,EAC7B;AACA,SAAO,GAAG,YAAY,IAAI,gBAAgB,IAAI,WAAW,SAAS,CAAC,CAAC;AACtE;AAEA,eAAe,mBAAmB,KAAiC;AACjE,QAAM,UAAU,IAAI,KAAK;AACzB,QAAM,OAAO,QACV,QAAQ,gCAAgC,EAAE,EAC1C,QAAQ,8BAA8B,EAAE,EACxC,QAAQ,SAAS,EAAE;AACtB,MAAI,KAAK,WAAW,GAAG;AACrB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,QAAM,MAAM,cAAc,IAAI;AAC9B,SAAO,WAAW,OAAO,OAAO;AAAA,IAC9B;AAAA,IACA;AAAA,IACA,EAAE,MAAM,SAAS,YAAY,QAAQ;AAAA,IACrC;AAAA,IACA,CAAC,MAAM;AAAA,EACT;AACF;AAEA,SAAS,cAAc,KAAsC;AAC3D,SAAO,WAAW,KAAK,KAAK,GAAG,GAAG,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;AAC1D;AAEA,SAAS,gBAAgB,OAA2B;AAClD,MAAI,SAAS;AACb,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,cAAU,OAAO,aAAa,MAAM,CAAC,CAAE;AAAA,EACzC;AACA,SAAO,KAAK,MAAM,EACf,QAAQ,QAAQ,GAAG,EACnB,QAAQ,QAAQ,GAAG,EACnB,QAAQ,QAAQ,EAAE;AACvB;;;ACh7BA,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/app-store-connect.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 AuthError,\n connectorUserAgent,\n sanitizeAllowedUrl,\n} from '@rawdash/connector-shared';\nimport {\n BaseConnector,\n type ChunkedSyncCursor,\n type ConnectorContext,\n type ConnectorCost,\n type ConnectorDoc,\n type CredentialsSchema,\n type FetchPageResult,\n type JSONValue,\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 issuerId: z.string().min(1).meta({\n label: 'Issuer ID',\n description:\n 'App Store Connect API issuer ID (UUID). Found at Users and Access -> Integrations -> App Store Connect API.',\n placeholder: '69a6de7f-...',\n }),\n keyId: z.string().min(1).meta({\n label: 'Key ID',\n description:\n 'App Store Connect API key ID (10 characters). Shown next to the key in Users and Access -> Integrations -> App Store Connect API.',\n placeholder: 'ABC1234DEF',\n }),\n privateKey: z.object({ $secret: z.string() }).meta({\n label: 'Private key (.p8)',\n description:\n 'Contents of the App Store Connect API private key file (.p8). PKCS#8 PEM, starting with -----BEGIN PRIVATE KEY-----. Apple only lets you download the key once on creation.',\n placeholder: '-----BEGIN PRIVATE KEY-----\\n...',\n secret: true,\n }),\n vendorNumber: z\n .string()\n .regex(/^\\d{8,9}$/u, 'Vendor number must be an 8-9 digit numeric string')\n .optional()\n .meta({\n label: 'Vendor number',\n description:\n 'Apple vendor number (8-9 digit numeric). Required to sync sales reports (app_installs and app_revenue). Found in App Store Connect -> Payments and Financial Reports -> top-left dropdown.',\n placeholder: '85912345',\n }),\n resources: z\n .array(z.enum(['apps', 'app_installs', 'app_revenue', 'app_ratings']))\n .nonempty()\n .optional()\n .meta({\n label: 'Resources',\n description:\n 'Which App Store Connect resources to sync. Omit to sync all resources. Sales-derived resources (app_installs, app_revenue) require vendorNumber and are silently skipped without it.',\n }),\n salesBackfillDays: z.number().int().positive().max(365).optional().meta({\n label: 'Sales backfill window (days)',\n description:\n 'How many days of daily sales reports to pull on a full sync. Defaults to 30. Apple keeps daily reports for the last 365 days.',\n placeholder: '30',\n }),\n reviewLimit: z.number().int().positive().max(2000).optional().meta({\n label: 'Review sample size',\n description:\n 'Most-recent customer reviews to fetch per app for the app_ratings metric. Defaults to 200 (one Apple page). Higher values smooth the rolling rating at the cost of more requests.',\n placeholder: '200',\n }),\n }),\n);\n\nexport const doc: ConnectorDoc = defineConnectorDoc({\n displayName: 'App Store Connect',\n category: 'mobile',\n brandColor: '#0D96F6',\n tagline:\n 'Sync your iOS / macOS apps, daily sales (downloads and proceeds), and customer review ratings from the App Store Connect API for mobile-team dashboards.',\n vendor: {\n name: 'Apple',\n domain: 'apple.com',\n apiDocs: 'https://developer.apple.com/documentation/appstoreconnectapi',\n website: 'https://appstoreconnect.apple.com',\n },\n auth: {\n summary:\n 'App Store Connect API uses an ES256-signed JWT minted per request from an issuer ID, key ID, and a PKCS#8 EC private key (.p8) downloaded from App Store Connect. The key only needs read access to Sales and Reports.',\n setup: [\n 'Open App Store Connect -> Users and Access -> Integrations -> App Store Connect API.',\n 'Generate a key with the \"Sales\" or \"Finance\" role (read-only is enough). Copy the key ID shown in the table; capture the issuer ID at the top of the page.',\n 'Download the .p8 file once on creation - Apple does not let you re-download it.',\n 'Store the .p8 contents as a secret (e.g. APPSTORECONNECT_P8) and reference it as `privateKey: secret(\"APPSTORECONNECT_P8\")`.',\n 'Set `vendorNumber` from App Store Connect -> Payments and Financial Reports (the top-left dropdown shows the 8-9 digit number). Only required for app_installs and app_revenue.',\n ],\n },\n rateLimit:\n 'App Store Connect enforces a 3,600 requests-per-hour quota per team. The shared HTTP client backs off on 429 using Retry-After. Sales report endpoints are billed in the same bucket and cost one request per (day, report) pair.',\n limitations: [\n 'app_crashes (per-build crash counts) is not implemented. Apple only exposes crash analytics via the asynchronous Analytics Reports flow (create report request -> poll for completion -> download gzipped CSV) which spans multiple syncs; a follow-up will add it.',\n 'app_ratings is sampled from the most recent N customer reviews per app (default 200, capped at 2,000). It is a rolling rating, not the lifetime average shown in the App Store, because Apple does not expose lifetime aggregates over the REST API.',\n 'Sales reports are pulled in DAILY frequency only; weekly, monthly, and yearly summaries are not synced.',\n 'Subscription, in-app-purchase, and refund line items in the SALES summary report are aggregated into `units` and `proceeds` rather than broken out by product type. Filter by `productTypeIdentifier` on the metric sample attributes if you need to separate them.',\n ],\n});\n\nexport const cost: ConnectorCost = {\n recommendedInterval: '6 hours',\n minInterval: '1 hour',\n warning:\n 'Daily sales reports are only finalized 24-48 hours after the day closes; syncing more often than the recommended interval will not bring fresher revenue data.',\n};\n\nexport interface AppStoreConnectSettings {\n resources?: readonly AppStoreConnectResource[];\n vendorNumber?: string;\n salesBackfillDays?: number;\n reviewLimit?: number;\n}\n\nconst appStoreConnectCredentials = {\n issuerId: {\n description: 'App Store Connect API issuer ID',\n auth: 'required' as const,\n },\n keyId: {\n description: 'App Store Connect API key ID',\n auth: 'required' as const,\n },\n privateKey: {\n description: 'App Store Connect API private key (.p8 PEM contents)',\n auth: 'required' as const,\n },\n} satisfies CredentialsSchema;\n\ntype AppStoreConnectCredentials = typeof appStoreConnectCredentials;\n\nconst PHASE_ORDER = [\n 'apps',\n 'app_installs',\n 'app_revenue',\n 'app_ratings',\n] as const;\n\ntype AppStoreConnectPhase = (typeof PHASE_ORDER)[number];\n\nexport type AppStoreConnectResource = AppStoreConnectPhase;\n\nconst isAppStoreConnectCursor = makeChunkedCursorGuard(PHASE_ORDER);\n\ntype AppStoreConnectCursor = ChunkedSyncCursor<AppStoreConnectPhase, string>;\n\nconst API_HOST = 'api.appstoreconnect.apple.com';\nconst API_BASE = `https://${API_HOST}`;\nconst APPS_PATH = '/v1/apps';\nconst SALES_REPORTS_PATH = '/v1/salesReports';\nconst PER_PAGE = 200;\nconst DEFAULT_SALES_BACKFILL_DAYS = 30;\nconst DEFAULT_REVIEW_LIMIT = 200;\nconst SALES_REPORT_DELAY_HOURS = 48;\nconst MS_PER_DAY = 86_400_000;\nconst MS_PER_HOUR = 3_600_000;\n\nconst APP_ENTITY = 'app_store_connect_app';\nconst APP_INSTALLS_METRIC = 'app_store_connect_app_installs';\nconst APP_REVENUE_METRIC = 'app_store_connect_app_revenue';\nconst APP_RATINGS_METRIC = 'app_store_connect_app_ratings';\n\ninterface AppRecord {\n id: string;\n attributes?: {\n name?: string | null;\n bundleId?: string | null;\n sku?: string | null;\n primaryLocale?: string | null;\n } | null;\n}\n\ninterface ReviewRecord {\n id: string;\n attributes?: {\n rating?: number | null;\n territory?: string | null;\n title?: string | null;\n reviewerNickname?: string | null;\n createdDate?: string | null;\n } | null;\n}\n\nconst appAttributesSchema = z.object({\n name: z.string().nullish(),\n bundleId: z.string().nullish(),\n sku: z.string().nullish(),\n primaryLocale: z.string().nullish(),\n});\n\nconst appSchema = z.object({\n id: z.string().min(1),\n type: z.string().optional(),\n attributes: appAttributesSchema.nullish(),\n});\n\nconst appsResponseSchema = z.object({\n data: z.array(appSchema),\n links: z\n .object({\n next: z.string().nullish(),\n })\n .nullish(),\n});\n\nconst reviewAttributesSchema = z.object({\n rating: z.number().int().min(1).max(5).nullish(),\n territory: z.string().nullish(),\n title: z.string().nullish(),\n reviewerNickname: z.string().nullish(),\n createdDate: z.string().nullish(),\n});\n\nconst reviewSchema = z.object({\n id: z.string().min(1),\n type: z.string().optional(),\n attributes: reviewAttributesSchema.nullish(),\n});\n\nconst reviewsResponseSchema = z.object({\n data: z.array(reviewSchema),\n links: z\n .object({\n next: z.string().nullish(),\n })\n .nullish(),\n});\n\nexport const appStoreConnectResources = defineResources({\n [APP_ENTITY]: {\n shape: 'entity',\n description:\n 'Apps registered in the team, with bundle id, SKU, and primary locale. Synced from /v1/apps.',\n endpoint: 'GET /v1/apps',\n filterable: [],\n fields: [\n { name: 'name', description: 'App display name.' },\n {\n name: 'bundleId',\n description: 'Bundle identifier, e.g. com.example.app.',\n },\n {\n name: 'sku',\n description: 'App SKU set when the app was registered.',\n },\n {\n name: 'primaryLocale',\n description: 'Primary App Store locale, e.g. en-US.',\n },\n ],\n responses: { apps: appsResponseSchema },\n },\n [APP_INSTALLS_METRIC]: {\n shape: 'metric',\n description:\n 'Daily installs (units sold or downloaded) aggregated from the SALES SUMMARY report by (date, app, country code, product type). One sample per (day, app, country, productTypeIdentifier).',\n endpoint: 'GET /v1/salesReports',\n granularity: 'daily',\n notes:\n 'Requires a vendor number. Apple delays daily reports by ~24-48 hours; the connector backs off two days from today to avoid empty / partial reports. Reports are gzipped TSV under the hood.',\n dimensions: [\n {\n name: 'appId',\n description:\n 'App Store Connect app id (Apple Identifier from the report).',\n },\n {\n name: 'countryCode',\n description: 'Two-letter ISO country code from the sale.',\n },\n {\n name: 'productTypeIdentifier',\n description:\n 'Apple product type, e.g. 1 (paid app), 1F (universal app), IA1 (in-app purchase).',\n },\n ],\n responses: { sales_installs_report: z.string() },\n },\n [APP_REVENUE_METRIC]: {\n shape: 'metric',\n description:\n 'Daily developer proceeds aggregated from the SALES SUMMARY report by (date, app, country code, product type). Values are summed across rows that share a currency; rows are emitted per currency.',\n endpoint: 'GET /v1/salesReports',\n unit: 'native currency (see currency attribute)',\n granularity: 'daily',\n notes:\n 'Proceeds are NOT FX-normalised; each sample carries its native currency in the `currency` attribute. Filter or convert downstream.',\n dimensions: [\n {\n name: 'appId',\n description: 'App Store Connect app id.',\n },\n {\n name: 'countryCode',\n description: 'Two-letter ISO country code from the sale.',\n },\n {\n name: 'currency',\n description:\n 'ISO 4217 currency of the proceeds, e.g. USD, EUR, JPY (matches Apple \"Currency of Proceeds\").',\n },\n {\n name: 'productTypeIdentifier',\n description: 'Apple product type code (same as app_installs).',\n },\n ],\n responses: { sales_revenue_report: z.string() },\n },\n [APP_RATINGS_METRIC]: {\n shape: 'metric',\n description:\n 'Rolling per-review ratings sampled from the most-recent N customer reviews per app (default 200). Each sample carries one review with the rating (1-5) as the value and the territory on the attribute.',\n endpoint: 'GET /v1/apps/{id}/customerReviews',\n notes:\n 'Apple does NOT expose the lifetime average rating over the REST API. Average over a time window downstream to get a rolling rating.',\n dimensions: [\n {\n name: 'appId',\n description: 'App Store Connect app id.',\n },\n {\n name: 'territory',\n description: 'Two-letter ISO country code where the review was filed.',\n },\n ],\n responses: { customer_reviews: reviewsResponseSchema },\n },\n});\n\nexport const id = 'app-store-connect';\n\nexport class AppStoreConnectConnector extends BaseConnector<\n AppStoreConnectSettings,\n AppStoreConnectCredentials\n> {\n static readonly id = id;\n\n static readonly resources = appStoreConnectResources;\n\n static readonly schemas = schemasFromResources(appStoreConnectResources);\n\n static readonly cost = cost;\n\n static create(\n input: unknown,\n ctx?: ConnectorContext,\n ): AppStoreConnectConnector {\n const parsed = configFields.parse(input);\n return new AppStoreConnectConnector(\n {\n resources: parsed.resources,\n vendorNumber: parsed.vendorNumber,\n salesBackfillDays: parsed.salesBackfillDays,\n reviewLimit: parsed.reviewLimit,\n },\n {\n issuerId: parsed.issuerId,\n keyId: parsed.keyId,\n privateKey: parsed.privateKey,\n },\n ctx,\n );\n }\n\n readonly id = id;\n override readonly credentials = appStoreConnectCredentials;\n\n private cachedJwt: { token: string; expiresAt: number } | null = null;\n private cachedAppIds: string[] | null = null;\n\n private async buildAuthHeader(): Promise<string> {\n const now = Math.floor(Date.now() / 1000);\n if (this.cachedJwt && this.cachedJwt.expiresAt > now + 60) {\n return `Bearer ${this.cachedJwt.token}`;\n }\n const { issuerId, keyId, privateKey } = this.creds;\n if (!issuerId || !keyId || !privateKey) {\n throw new AuthError(`${this.id}: missing App Store Connect credentials`);\n }\n const exp = now + 900;\n const jwt = await signES256Jwt({\n header: { alg: 'ES256', kid: keyId, typ: 'JWT' },\n payload: {\n iss: issuerId,\n iat: now,\n exp,\n aud: 'appstoreconnect-v1',\n },\n privateKeyPem: privateKey,\n });\n this.cachedJwt = { token: jwt, expiresAt: exp };\n return `Bearer ${jwt}`;\n }\n\n private async authHeaders(): Promise<Record<string, string>> {\n return {\n Authorization: await this.buildAuthHeader(),\n Accept: 'application/json',\n 'User-Agent': connectorUserAgent(this.id),\n };\n }\n\n private sanitizeListUrl(\n phase: AppStoreConnectPhase,\n pageUrl: string | null,\n ): string | null {\n const allowedPath = phase === 'apps' ? APPS_PATH : null;\n if (allowedPath === null) {\n return null;\n }\n return sanitizeAllowedUrl({\n url: pageUrl,\n host: API_HOST,\n pathname: allowedPath,\n });\n }\n\n private resolveCursor(cursor: unknown): AppStoreConnectCursor | undefined {\n if (!isAppStoreConnectCursor(cursor)) {\n return undefined;\n }\n if (cursor.phase === 'apps') {\n return {\n phase: cursor.phase,\n page: this.sanitizeListUrl(cursor.phase, cursor.page),\n };\n }\n return { phase: cursor.phase, page: null };\n }\n\n private async listApps(signal?: AbortSignal): Promise<string[]> {\n if (this.cachedAppIds !== null) {\n return this.cachedAppIds;\n }\n const ids: string[] = [];\n let url: string | null = `${API_BASE}${APPS_PATH}?limit=${PER_PAGE}`;\n while (url !== null) {\n if (signal?.aborted) {\n return ids;\n }\n const headers = await this.authHeaders();\n const res = await this.get<z.infer<typeof appsResponseSchema>>(url, {\n resource: 'apps',\n headers,\n signal,\n });\n for (const app of res.body.data ?? []) {\n ids.push(app.id);\n }\n const next = res.body.links?.next ?? null;\n url = this.sanitizeListUrl('apps', next);\n }\n this.cachedAppIds = ids;\n return ids;\n }\n\n private async fetchAppsPage(\n page: string | null,\n signal?: AbortSignal,\n ): Promise<FetchPageResult<string>> {\n const url = page ?? `${API_BASE}${APPS_PATH}?limit=${PER_PAGE}`;\n const headers = await this.authHeaders();\n const res = await this.get<z.infer<typeof appsResponseSchema>>(url, {\n resource: 'apps',\n headers,\n signal,\n });\n const items = res.body.data ?? [];\n if (this.cachedAppIds === null) {\n this.cachedAppIds = [];\n }\n for (const app of items) {\n if (!this.cachedAppIds.includes(app.id)) {\n this.cachedAppIds.push(app.id);\n }\n }\n const rawNext = res.body.links?.next ?? null;\n const next = this.sanitizeListUrl('apps', rawNext);\n return { items, next };\n }\n\n private buildSalesReportUrl(reportDate: string): string {\n const vendor = this.settings.vendorNumber;\n if (!vendor) {\n throw new Error(\n 'vendorNumber is required for app_installs / app_revenue resources',\n );\n }\n const params = new URLSearchParams();\n params.set('filter[frequency]', 'DAILY');\n params.set('filter[reportType]', 'SALES');\n params.set('filter[reportSubType]', 'SUMMARY');\n params.set('filter[vendorNumber]', vendor);\n params.set('filter[reportDate]', reportDate);\n return `${API_BASE}${SALES_REPORTS_PATH}?${params.toString()}`;\n }\n\n private async fetchSalesReportTsv(\n reportDate: string,\n signal?: AbortSignal,\n ): Promise<string | null> {\n const url = this.buildSalesReportUrl(reportDate);\n\n const res = await this.withRetry<Response>(\n async (sig) => {\n const headers = await this.authHeaders();\n headers['Accept'] = 'application/a-gzip';\n const response = await globalThis.fetch(url, {\n method: 'GET',\n headers,\n signal: sig,\n });\n if (response.status === 429) {\n const retryAfter = Number(response.headers.get('retry-after') ?? '');\n if (Number.isFinite(retryAfter) && retryAfter > 0) {\n await this.sleep(retryAfter * 1000, sig);\n }\n return { status: 'retry' };\n }\n return { status: 'done', value: response };\n },\n { signal },\n );\n if (res === null) {\n throw new Error(\n `App Store Connect sales report ${reportDate} failed: exhausted retries on HTTP 429`,\n );\n }\n if (res.status === 404) {\n return null;\n }\n if (!res.ok) {\n throw new Error(\n `App Store Connect sales report ${reportDate} failed: HTTP ${res.status}`,\n );\n }\n const body = res.body;\n if (!body) {\n return null;\n }\n const decompressed = body.pipeThrough(new DecompressionStream('gzip'));\n return await new Response(decompressed).text();\n }\n\n private async fetchReviewsForApp(\n appId: string,\n limit: number,\n signal?: AbortSignal,\n ): Promise<ReviewRecord[]> {\n const reviews: ReviewRecord[] = [];\n const reviewsBase = `/v1/apps/${encodeURIComponent(appId)}/customerReviews`;\n let url: string | null =\n `${API_BASE}${reviewsBase}?limit=${PER_PAGE}&sort=-createdDate`;\n while (url !== null && reviews.length < limit) {\n if (signal?.aborted) {\n return reviews;\n }\n const headers = await this.authHeaders();\n const res = await this.get<z.infer<typeof reviewsResponseSchema>>(url, {\n resource: 'customer_reviews',\n headers,\n signal,\n });\n for (const review of res.body.data ?? []) {\n reviews.push(review);\n if (reviews.length >= limit) {\n break;\n }\n }\n const rawNext = res.body.links?.next ?? null;\n url = sanitizeAllowedUrl({\n url: rawNext,\n host: API_HOST,\n pathname: reviewsBase,\n });\n }\n return reviews;\n }\n\n private async writeApps(\n storage: StorageHandle,\n items: AppRecord[],\n ): Promise<void> {\n const nowMs = Date.now();\n for (const app of items) {\n const attrs = app.attributes ?? {};\n await storage.entity({\n type: APP_ENTITY,\n id: app.id,\n attributes: {\n name: attrs.name ?? null,\n bundleId: attrs.bundleId ?? null,\n sku: attrs.sku ?? null,\n primaryLocale: attrs.primaryLocale ?? null,\n },\n updated_at: nowMs,\n });\n }\n }\n\n private async syncSalesReports(\n storage: StorageHandle,\n metricName: typeof APP_INSTALLS_METRIC | typeof APP_REVENUE_METRIC,\n options: SyncOptions,\n signal?: AbortSignal,\n ): Promise<void> {\n if (!this.settings.vendorNumber) {\n this.logger.info('skipping sales report (no vendorNumber configured)', {\n resource: metricName,\n });\n await storage.metrics([], { names: [metricName] });\n return;\n }\n const dates = computeSalesReportDates(options, this.settings);\n const samples: MetricSample[] = [];\n for (const reportDate of dates) {\n if (signal?.aborted) {\n return;\n }\n let tsv: string | null;\n try {\n tsv = await this.fetchSalesReportTsv(reportDate, signal);\n } catch (err) {\n this.logger.warn('sales report fetch failed', {\n reportDate,\n resource: metricName,\n error: err instanceof Error ? err.message : String(err),\n });\n continue;\n }\n if (tsv === null || tsv.length === 0) {\n continue;\n }\n for (const sample of parseSalesReportTsv(tsv, metricName)) {\n samples.push(sample);\n }\n }\n await storage.metrics(samples, { names: [metricName] });\n }\n\n private async syncAppRatings(\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<void> {\n const appIds = await this.listApps(signal);\n const limit = this.settings.reviewLimit ?? DEFAULT_REVIEW_LIMIT;\n const samples: MetricSample[] = [];\n for (const appId of appIds) {\n if (signal?.aborted) {\n return;\n }\n const reviews = await this.fetchReviewsForApp(appId, limit, signal);\n for (const review of reviews) {\n const attrs = review.attributes ?? {};\n if (typeof attrs.rating !== 'number') {\n continue;\n }\n const ts = isoToMs(attrs.createdDate);\n if (ts === null) {\n continue;\n }\n const attributes: Record<string, JSONValue> = {\n appId,\n reviewId: review.id,\n territory: attrs.territory ?? null,\n };\n samples.push({\n name: APP_RATINGS_METRIC,\n ts,\n value: attrs.rating,\n attributes,\n });\n }\n }\n await storage.metrics(samples, { names: [APP_RATINGS_METRIC] });\n }\n\n async sync(\n options: SyncOptions,\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<SyncResult> {\n this.cachedAppIds = null;\n const cursor = this.resolveCursor(options.cursor);\n const isFull = options.mode === 'full';\n const phases = selectActivePhases<\n AppStoreConnectResource,\n AppStoreConnectPhase\n >((r) => r, PHASE_ORDER, this.settings.resources);\n\n return paginateChunked<AppStoreConnectPhase, string>({\n phases,\n cursor,\n signal,\n logger: this.logger,\n fetchPage: async (phase, page, sig) => {\n if (phase === 'apps') {\n return this.fetchAppsPage(page, sig);\n }\n return { items: [{ phase }], next: null };\n },\n writeBatch: async (phase, items, page) => {\n if (phase === 'apps') {\n if (page === null && isFull) {\n await storage.entities([], { types: [APP_ENTITY] });\n }\n await this.writeApps(storage, items as AppRecord[]);\n return;\n }\n if (phase === 'app_installs') {\n await this.syncSalesReports(\n storage,\n APP_INSTALLS_METRIC,\n options,\n signal,\n );\n return;\n }\n if (phase === 'app_revenue') {\n await this.syncSalesReports(\n storage,\n APP_REVENUE_METRIC,\n options,\n signal,\n );\n return;\n }\n if (phase === 'app_ratings') {\n await this.syncAppRatings(storage, signal);\n return;\n }\n },\n });\n }\n}\n\nfunction isoToMs(value: string | null | undefined): number | null {\n if (!value) {\n return null;\n }\n const ms = Date.parse(value);\n return Number.isFinite(ms) ? ms : null;\n}\n\nfunction pad2(n: number): string {\n return n < 10 ? `0${n}` : String(n);\n}\n\nfunction toIsoDate(d: Date): string {\n return `${d.getUTCFullYear()}-${pad2(d.getUTCMonth() + 1)}-${pad2(\n d.getUTCDate(),\n )}`;\n}\n\nfunction parseSalesDate(value: string): number | null {\n const m = /^(\\d{2})\\/(\\d{2})\\/(\\d{4})$/u.exec(value);\n if (m) {\n const month = Number(m[1]!);\n const day = Number(m[2]!);\n const year = Number(m[3]!);\n const ms = Date.UTC(year, month - 1, day);\n return Number.isFinite(ms) ? ms : null;\n }\n const direct = Date.parse(`${value}T00:00:00Z`);\n return Number.isFinite(direct) ? direct : null;\n}\n\nexport function computeSalesReportDates(\n options: SyncOptions,\n settings: AppStoreConnectSettings,\n): string[] {\n const now = Date.now();\n const endMs = now - SALES_REPORT_DELAY_HOURS * MS_PER_HOUR;\n let startMs: number;\n if (options.since) {\n const sinceMs = Date.parse(options.since);\n startMs = Number.isFinite(sinceMs) ? sinceMs : endMs - MS_PER_DAY;\n } else if (options.mode === 'latest') {\n startMs = endMs - 2 * MS_PER_DAY;\n } else {\n const days = settings.salesBackfillDays ?? DEFAULT_SALES_BACKFILL_DAYS;\n startMs = endMs - days * MS_PER_DAY;\n }\n if (startMs > endMs) {\n return [];\n }\n const dates: string[] = [];\n const start = new Date(Math.floor(startMs / MS_PER_DAY) * MS_PER_DAY);\n const end = new Date(Math.floor(endMs / MS_PER_DAY) * MS_PER_DAY);\n for (\n let d = new Date(start.getTime());\n d.getTime() <= end.getTime();\n d.setUTCDate(d.getUTCDate() + 1)\n ) {\n dates.push(toIsoDate(d));\n }\n return dates;\n}\n\nexport function parseSalesReportTsv(\n tsv: string,\n metricName: typeof APP_INSTALLS_METRIC | typeof APP_REVENUE_METRIC,\n): MetricSample[] {\n const lines = tsv.split(/\\r?\\n/u).filter((l) => l.length > 0);\n if (lines.length < 2) {\n return [];\n }\n const header = lines[0]!.split('\\t').map((h) => h.trim());\n const idx = (name: string): number => header.indexOf(name);\n\n const beginDateIdx = idx('Begin Date');\n const unitsIdx = idx('Units');\n const proceedsIdx = idx('Developer Proceeds');\n const countryIdx = idx('Country Code');\n const appleIdIdx = idx('Apple Identifier');\n const currencyIdx = idx('Currency of Proceeds');\n const productTypeIdx = idx('Product Type Identifier');\n\n if (\n beginDateIdx === -1 ||\n appleIdIdx === -1 ||\n countryIdx === -1 ||\n (metricName === APP_INSTALLS_METRIC && unitsIdx === -1) ||\n (metricName === APP_REVENUE_METRIC &&\n (proceedsIdx === -1 || currencyIdx === -1))\n ) {\n return [];\n }\n\n const samples: MetricSample[] = [];\n for (let i = 1; i < lines.length; i++) {\n const row = lines[i]!.split('\\t');\n const ts = parseSalesDate(row[beginDateIdx]?.trim() ?? '');\n if (ts === null) {\n continue;\n }\n const appId = row[appleIdIdx]?.trim() ?? '';\n if (appId === '') {\n continue;\n }\n const countryCode = row[countryIdx]?.trim() ?? '';\n const productType =\n productTypeIdx === -1 ? '' : (row[productTypeIdx]?.trim() ?? '');\n\n if (metricName === APP_INSTALLS_METRIC) {\n const raw = row[unitsIdx]?.trim() ?? '';\n const value = Number.parseFloat(raw);\n if (!Number.isFinite(value)) {\n continue;\n }\n const attributes: Record<string, JSONValue> = {\n appId,\n countryCode,\n productTypeIdentifier: productType,\n };\n samples.push({ name: metricName, ts, value, attributes });\n } else {\n const raw = row[proceedsIdx]?.trim() ?? '';\n const value = Number.parseFloat(raw);\n if (!Number.isFinite(value)) {\n continue;\n }\n const currency = row[currencyIdx]?.trim() ?? '';\n const attributes: Record<string, JSONValue> = {\n appId,\n countryCode,\n currency,\n productTypeIdentifier: productType,\n };\n samples.push({ name: metricName, ts, value, attributes });\n }\n }\n return samples;\n}\n\ninterface JwtHeader {\n alg: 'ES256';\n kid: string;\n typ: 'JWT';\n}\n\ninterface JwtPayload {\n iss: string;\n iat: number;\n exp: number;\n aud: string;\n}\n\nexport async function signES256Jwt({\n header,\n payload,\n privateKeyPem,\n}: {\n header: JwtHeader;\n payload: JwtPayload;\n privateKeyPem: string;\n}): Promise<string> {\n const encoder = new TextEncoder();\n const headerB64 = base64urlEncode(encoder.encode(JSON.stringify(header)));\n const payloadB64 = base64urlEncode(encoder.encode(JSON.stringify(payload)));\n const signingInput = `${headerB64}.${payloadB64}`;\n const key = await importEcPrivateKey(privateKeyPem);\n const signature = await globalThis.crypto.subtle.sign(\n { name: 'ECDSA', hash: 'SHA-256' },\n key,\n encoder.encode(signingInput),\n );\n return `${signingInput}.${base64urlEncode(new Uint8Array(signature))}`;\n}\n\nasync function importEcPrivateKey(pem: string): Promise<CryptoKey> {\n const trimmed = pem.trim();\n const body = trimmed\n .replace(/-----BEGIN PRIVATE KEY-----/u, '')\n .replace(/-----END PRIVATE KEY-----/u, '')\n .replace(/\\s+/gu, '');\n if (body.length === 0) {\n throw new AuthError(\n 'app-store-connect: privateKey is empty or not a PEM-encoded PKCS#8 key',\n );\n }\n const der = base64ToBytes(body);\n return globalThis.crypto.subtle.importKey(\n 'pkcs8',\n der,\n { name: 'ECDSA', namedCurve: 'P-256' },\n false,\n ['sign'],\n );\n}\n\nfunction base64ToBytes(b64: string): Uint8Array<ArrayBuffer> {\n return Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));\n}\n\nfunction base64urlEncode(bytes: Uint8Array): string {\n let binary = '';\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]!);\n }\n return btoa(binary)\n .replace(/\\+/gu, '-')\n .replace(/\\//gu, '_')\n .replace(/=+$/u, '');\n}\n","import { AppStoreConnectConnector } from './app-store-connect';\n\nexport {\n AppStoreConnectConnector,\n appStoreConnectResources as resources,\n configFields,\n cost,\n doc,\n id,\n} from './app-store-connect';\nexport type {\n AppStoreConnectResource,\n AppStoreConnectSettings,\n} from './app-store-connect';\nexport default App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rC;AAAA,IACA,CAAC,MAAM;AAAA,EACT;AACF;AAEA,SAAS,cAAc,KAAsC;AAC3D,SAAO,WAAW,KAAK,KAAK,GAAG,GAAG,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;AAC1D;AAEA,SAAS,gBAAgB,OAA2B;AAClD,MAAI,SAAS;AACb,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,cAAU,OAAO,aAAa,MAAM,CAAC,CAAE;AAAA,EACzC;AACA,SAAO,KAAK,MAAM,EACf,QAAQ,QAAQ,GAAG,EACnB,QAAQ,QAAQ,GAAG,EACnB,QAAQ,QAAQ,EAAE;AACvB;;;ACl7BA,IAAO,gBAAQ;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rawdash/connector-app-store-connect",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.23.0",
|
|
4
4
|
"description": "Rawdash connector for App Store Connect — syncs apps, sales (units and proceeds), and customer review ratings from the App Store Connect API into the six-shape storage model",
|
|
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.23.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
|
+
}
|