@adport/provider-snapchat 0.6.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 +201 -0
- package/dist/index.d.ts +96 -0
- package/dist/index.js +465 -0
- package/dist/index.js.map +1 -0
- package/package.json +33 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Yannick Westermann
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { AdProvider, StandardActions, Account, NormalizedQuery, Report, WriteOperation, WriteGuard, WritePreview, WriteResult, AnyToolDefinition, CredentialStore, ProviderModule } from '@adport/core';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
|
|
4
|
+
declare const SNAPCHAT_API_BASE = "https://adsapi.snapchat.com/v1/";
|
|
5
|
+
declare const SNAPCHAT_TOKEN_URL = "https://accounts.snapchat.com/login/oauth2/access_token";
|
|
6
|
+
declare const SNAPCHAT_SCOPE = "snapchat-marketing-api";
|
|
7
|
+
declare function buildSnapchatAuthUrl(clientId: string, redirectUri: string, state: string): string;
|
|
8
|
+
declare function exchangeSnapchatCode(input: {
|
|
9
|
+
clientId: string;
|
|
10
|
+
clientSecret: string;
|
|
11
|
+
code: string;
|
|
12
|
+
redirectUri: string;
|
|
13
|
+
}, fetchImpl?: typeof fetch): Promise<string>;
|
|
14
|
+
interface SnapchatCredentials {
|
|
15
|
+
clientId: string;
|
|
16
|
+
clientSecret: string;
|
|
17
|
+
refreshToken: string;
|
|
18
|
+
onRefreshToken?: (refreshToken: string) => Promise<void>;
|
|
19
|
+
}
|
|
20
|
+
declare class SnapchatAdsClient {
|
|
21
|
+
private readonly credentials;
|
|
22
|
+
private readonly fetchImpl;
|
|
23
|
+
private token?;
|
|
24
|
+
private refreshToken;
|
|
25
|
+
private refreshing?;
|
|
26
|
+
constructor(credentials: SnapchatCredentials, fetchImpl?: typeof fetch);
|
|
27
|
+
collection<T>(path: string, plural: string, singular: string, schema: z.ZodType<T>, params?: Record<string, string>): Promise<T[]>;
|
|
28
|
+
mutate<T>(path: string, method: 'POST' | 'PATCH', body: unknown, plural: string, singular: string, schema: z.ZodType<T>): Promise<T[]>;
|
|
29
|
+
private items;
|
|
30
|
+
private url;
|
|
31
|
+
private send;
|
|
32
|
+
private accessToken;
|
|
33
|
+
private refresh;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
declare class SnapchatAdsProvider implements AdProvider {
|
|
37
|
+
private readonly client;
|
|
38
|
+
readonly id = "snapchat";
|
|
39
|
+
constructor(client: SnapchatAdsClient);
|
|
40
|
+
capabilities(): {
|
|
41
|
+
serverDryRun: boolean;
|
|
42
|
+
};
|
|
43
|
+
standardActions(): StandardActions;
|
|
44
|
+
listAccounts(): Promise<Account[]>;
|
|
45
|
+
listCampaigns(accountId: string): Promise<{
|
|
46
|
+
[x: string]: unknown;
|
|
47
|
+
id: string;
|
|
48
|
+
ad_account_id: string;
|
|
49
|
+
name: string;
|
|
50
|
+
status: string;
|
|
51
|
+
daily_budget_micro?: number | undefined;
|
|
52
|
+
lifetime_spend_cap_micro?: number | undefined;
|
|
53
|
+
}[]>;
|
|
54
|
+
report(query: NormalizedQuery): Promise<Report>;
|
|
55
|
+
previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview>;
|
|
56
|
+
applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult>;
|
|
57
|
+
private plan;
|
|
58
|
+
}
|
|
59
|
+
/** Snap TOTAL stats require account-local day boundaries, including DST changes. */
|
|
60
|
+
declare function accountMidnight(date: string, timezone: string): string;
|
|
61
|
+
|
|
62
|
+
declare function snapchatTools(provider: SnapchatAdsProvider): AnyToolDefinition[];
|
|
63
|
+
|
|
64
|
+
declare const organizationSchema: z.ZodObject<{
|
|
65
|
+
id: z.ZodString;
|
|
66
|
+
name: z.ZodString;
|
|
67
|
+
}, z.core.$loose>;
|
|
68
|
+
declare const accountSchema: z.ZodObject<{
|
|
69
|
+
id: z.ZodString;
|
|
70
|
+
name: z.ZodString;
|
|
71
|
+
currency: z.ZodString;
|
|
72
|
+
timezone: z.ZodString;
|
|
73
|
+
status: z.ZodString;
|
|
74
|
+
}, z.core.$loose>;
|
|
75
|
+
declare const campaignSchema: z.ZodObject<{
|
|
76
|
+
id: z.ZodString;
|
|
77
|
+
ad_account_id: z.ZodString;
|
|
78
|
+
name: z.ZodString;
|
|
79
|
+
status: z.ZodString;
|
|
80
|
+
daily_budget_micro: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
|
|
81
|
+
lifetime_spend_cap_micro: z.ZodOptional<z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
|
|
82
|
+
}, z.core.$loose>;
|
|
83
|
+
type SnapchatCampaign = z.infer<typeof campaignSchema>;
|
|
84
|
+
declare const statSchema: z.ZodObject<{
|
|
85
|
+
id: z.ZodString;
|
|
86
|
+
stats: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>>;
|
|
87
|
+
breakdown_stats: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodArray<z.ZodObject<{
|
|
88
|
+
id: z.ZodString;
|
|
89
|
+
stats: z.ZodRecord<z.ZodString, z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>, z.ZodNumber>>;
|
|
90
|
+
}, z.core.$loose>>>>;
|
|
91
|
+
}, z.core.$loose>;
|
|
92
|
+
|
|
93
|
+
declare function resolveSnapchatCredentials(store: CredentialStore): Promise<SnapchatCredentials | undefined>;
|
|
94
|
+
declare function createSnapchatModule(store: CredentialStore): Promise<ProviderModule | undefined>;
|
|
95
|
+
|
|
96
|
+
export { SNAPCHAT_API_BASE, SNAPCHAT_SCOPE, SNAPCHAT_TOKEN_URL, SnapchatAdsClient, SnapchatAdsProvider, type SnapchatCampaign, type SnapchatCredentials, accountMidnight, accountSchema, buildSnapchatAuthUrl, campaignSchema, createSnapchatModule, exchangeSnapchatCode, organizationSchema, resolveSnapchatCredentials, snapchatTools, statSchema };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,465 @@
|
|
|
1
|
+
// src/client.ts
|
|
2
|
+
import { AdportError } from "@adport/core";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
var SNAPCHAT_API_BASE = "https://adsapi.snapchat.com/v1/";
|
|
5
|
+
var SNAPCHAT_TOKEN_URL = "https://accounts.snapchat.com/login/oauth2/access_token";
|
|
6
|
+
var SNAPCHAT_SCOPE = "snapchat-marketing-api";
|
|
7
|
+
function buildSnapchatAuthUrl(clientId, redirectUri, state) {
|
|
8
|
+
return `https://accounts.snapchat.com/login/oauth2/authorize?${new URLSearchParams({
|
|
9
|
+
client_id: clientId,
|
|
10
|
+
redirect_uri: redirectUri,
|
|
11
|
+
response_type: "code",
|
|
12
|
+
scope: SNAPCHAT_SCOPE,
|
|
13
|
+
state
|
|
14
|
+
})}`;
|
|
15
|
+
}
|
|
16
|
+
async function exchangeSnapchatCode(input, fetchImpl = fetch) {
|
|
17
|
+
const response = await fetchImpl(SNAPCHAT_TOKEN_URL, {
|
|
18
|
+
method: "POST",
|
|
19
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
20
|
+
body: new URLSearchParams({ grant_type: "authorization_code", client_id: input.clientId, client_secret: input.clientSecret, code: input.code, redirect_uri: input.redirectUri }),
|
|
21
|
+
redirect: "error",
|
|
22
|
+
signal: AbortSignal.timeout(3e4)
|
|
23
|
+
});
|
|
24
|
+
if (!response.ok) throw new AdportError("PROVIDER_ERROR", `snapchat: OAuth exchange failed (HTTP ${response.status})`);
|
|
25
|
+
const parsed = tokenSchema.safeParse(await response.json());
|
|
26
|
+
if (!parsed.success || !parsed.data.refresh_token) throw new AdportError("PROVIDER_ERROR", "snapchat: OAuth response did not include a valid refresh token");
|
|
27
|
+
return parsed.data.refresh_token;
|
|
28
|
+
}
|
|
29
|
+
var envelopeSchema = z.looseObject({
|
|
30
|
+
request_status: z.string(),
|
|
31
|
+
request_id: z.string().optional(),
|
|
32
|
+
paging: z.object({ next_link: z.string().optional() }).optional()
|
|
33
|
+
});
|
|
34
|
+
var success = (status) => status.toUpperCase() === "SUCCESS";
|
|
35
|
+
var tokenSchema = z.object({
|
|
36
|
+
access_token: z.string().min(1),
|
|
37
|
+
expires_in: z.number().positive(),
|
|
38
|
+
refresh_token: z.string().min(1).optional()
|
|
39
|
+
});
|
|
40
|
+
var SnapchatAdsClient = class {
|
|
41
|
+
constructor(credentials, fetchImpl = fetch) {
|
|
42
|
+
this.credentials = credentials;
|
|
43
|
+
this.fetchImpl = fetchImpl;
|
|
44
|
+
this.refreshToken = credentials.refreshToken;
|
|
45
|
+
}
|
|
46
|
+
credentials;
|
|
47
|
+
fetchImpl;
|
|
48
|
+
token;
|
|
49
|
+
refreshToken;
|
|
50
|
+
refreshing;
|
|
51
|
+
async collection(path, plural, singular, schema, params = {}) {
|
|
52
|
+
let url = this.url(path, params);
|
|
53
|
+
const resourcePath = url.pathname;
|
|
54
|
+
const visited = /* @__PURE__ */ new Set();
|
|
55
|
+
const rows = [];
|
|
56
|
+
while (true) {
|
|
57
|
+
if (visited.has(url.href) || visited.size >= 1e3) {
|
|
58
|
+
throw new AdportError("PROVIDER_ERROR", "snapchat: pagination did not terminate; refusing incomplete results");
|
|
59
|
+
}
|
|
60
|
+
visited.add(url.href);
|
|
61
|
+
const data = await this.send(url, "GET");
|
|
62
|
+
rows.push(...this.items(data, plural, singular, schema));
|
|
63
|
+
const next = data.paging?.next_link;
|
|
64
|
+
if (!next) return rows;
|
|
65
|
+
url = this.url(next);
|
|
66
|
+
if (url.pathname !== resourcePath) throw new AdportError("PROVIDER_ERROR", "snapchat: pagination changed resource scope");
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
async mutate(path, method, body, plural, singular, schema) {
|
|
70
|
+
const data = await this.send(this.url(path), method, body);
|
|
71
|
+
return this.items(data, plural, singular, schema);
|
|
72
|
+
}
|
|
73
|
+
items(data, plural, singular, schema) {
|
|
74
|
+
const items = z.array(z.looseObject({ sub_request_status: z.string() })).safeParse(data[plural]);
|
|
75
|
+
if (!items.success) throw new AdportError("PROVIDER_ERROR", `snapchat: malformed ${plural} response`);
|
|
76
|
+
return items.data.map((item) => {
|
|
77
|
+
if (!success(item.sub_request_status)) {
|
|
78
|
+
throw new AdportError("PROVIDER_ERROR", `snapchat: ${singular} sub-request failed`, { requestId: data.request_id });
|
|
79
|
+
}
|
|
80
|
+
const parsed = schema.safeParse(item[singular]);
|
|
81
|
+
if (!parsed.success) throw new AdportError("PROVIDER_ERROR", `snapchat: malformed ${singular} response`);
|
|
82
|
+
return parsed.data;
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
url(path, params = {}) {
|
|
86
|
+
const url = new URL(path, SNAPCHAT_API_BASE);
|
|
87
|
+
if (url.origin !== "https://adsapi.snapchat.com" || !url.pathname.startsWith("/v1/") || url.username || url.password || url.hash) {
|
|
88
|
+
throw new AdportError("INVALID_INPUT", "snapchat: invalid API URL");
|
|
89
|
+
}
|
|
90
|
+
for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);
|
|
91
|
+
return url;
|
|
92
|
+
}
|
|
93
|
+
async send(url, method, body, retry = true) {
|
|
94
|
+
const token = await this.accessToken();
|
|
95
|
+
const response = await this.fetchImpl(url.href, {
|
|
96
|
+
method,
|
|
97
|
+
headers: {
|
|
98
|
+
authorization: `Bearer ${token}`,
|
|
99
|
+
...body !== void 0 ? { "content-type": method === "PATCH" ? "application/json-patch+json" : "application/json" } : {}
|
|
100
|
+
},
|
|
101
|
+
...body !== void 0 ? { body: JSON.stringify(body) } : {},
|
|
102
|
+
redirect: "error",
|
|
103
|
+
signal: AbortSignal.timeout(3e4)
|
|
104
|
+
});
|
|
105
|
+
if (response.status === 401 && method === "GET" && retry) {
|
|
106
|
+
if (this.token?.value === token) this.token = void 0;
|
|
107
|
+
return this.send(url, method, body, false);
|
|
108
|
+
}
|
|
109
|
+
if (!response.ok) {
|
|
110
|
+
const advice = response.status === 403 ? " Check app approval and the user\u2019s ad-account permissions; reconnecting alone may not resolve this." : "";
|
|
111
|
+
throw new AdportError("PROVIDER_ERROR", `snapchat: HTTP ${response.status}.${advice}`);
|
|
112
|
+
}
|
|
113
|
+
const parsed = envelopeSchema.safeParse(await response.json());
|
|
114
|
+
if (!parsed.success) throw new AdportError("PROVIDER_ERROR", "snapchat: malformed API envelope");
|
|
115
|
+
if (!success(parsed.data.request_status)) {
|
|
116
|
+
throw new AdportError("PROVIDER_ERROR", "snapchat: API request failed", { requestId: parsed.data.request_id });
|
|
117
|
+
}
|
|
118
|
+
return parsed.data;
|
|
119
|
+
}
|
|
120
|
+
async accessToken() {
|
|
121
|
+
if (this.token && this.token.expiresAt > Date.now() + 6e4) return this.token.value;
|
|
122
|
+
if (!this.refreshing) this.refreshing = this.refresh().finally(() => {
|
|
123
|
+
this.refreshing = void 0;
|
|
124
|
+
});
|
|
125
|
+
return this.refreshing;
|
|
126
|
+
}
|
|
127
|
+
async refresh() {
|
|
128
|
+
const response = await this.fetchImpl(SNAPCHAT_TOKEN_URL, {
|
|
129
|
+
method: "POST",
|
|
130
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
131
|
+
body: new URLSearchParams({
|
|
132
|
+
grant_type: "refresh_token",
|
|
133
|
+
client_id: this.credentials.clientId,
|
|
134
|
+
client_secret: this.credentials.clientSecret,
|
|
135
|
+
refresh_token: this.refreshToken
|
|
136
|
+
}),
|
|
137
|
+
redirect: "error",
|
|
138
|
+
signal: AbortSignal.timeout(3e4)
|
|
139
|
+
});
|
|
140
|
+
if (!response.ok) throw new AdportError("PROVIDER_ERROR", `snapchat: OAuth refresh failed (HTTP ${response.status}); re-authorize if the grant was revoked or expired`);
|
|
141
|
+
const parsed = tokenSchema.safeParse(await response.json());
|
|
142
|
+
if (!parsed.success) throw new AdportError("PROVIDER_ERROR", "snapchat: malformed OAuth response");
|
|
143
|
+
const token = parsed.data;
|
|
144
|
+
if (token.refresh_token && token.refresh_token !== this.refreshToken) {
|
|
145
|
+
this.refreshToken = token.refresh_token;
|
|
146
|
+
await this.credentials.onRefreshToken?.(token.refresh_token);
|
|
147
|
+
}
|
|
148
|
+
this.token = { value: token.access_token, expiresAt: Date.now() + token.expires_in * 1e3 };
|
|
149
|
+
return token.access_token;
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
// src/provider.ts
|
|
154
|
+
import {
|
|
155
|
+
AdportError as AdportError2,
|
|
156
|
+
resolveDateRange
|
|
157
|
+
} from "@adport/core";
|
|
158
|
+
|
|
159
|
+
// src/schemas.ts
|
|
160
|
+
import { z as z2 } from "zod";
|
|
161
|
+
var snapchatId = z2.string().regex(/^[A-Za-z0-9_-]+$/);
|
|
162
|
+
var snapchatStatus = z2.enum(["ACTIVE", "PAUSED"]);
|
|
163
|
+
var snapchatMicros = z2.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
|
164
|
+
var wireNumber = z2.union([z2.number(), z2.string().regex(/^\d+(?:\.\d+)?$/)]).transform(Number).pipe(z2.number().finite().nonnegative().max(Number.MAX_SAFE_INTEGER));
|
|
165
|
+
var organizationSchema = z2.looseObject({ id: snapchatId, name: z2.string() });
|
|
166
|
+
var accountSchema = z2.looseObject({
|
|
167
|
+
id: snapchatId,
|
|
168
|
+
name: z2.string(),
|
|
169
|
+
currency: z2.string(),
|
|
170
|
+
timezone: z2.string(),
|
|
171
|
+
status: z2.string()
|
|
172
|
+
});
|
|
173
|
+
var campaignSchema = z2.looseObject({
|
|
174
|
+
id: snapchatId,
|
|
175
|
+
ad_account_id: snapchatId,
|
|
176
|
+
name: z2.string(),
|
|
177
|
+
status: z2.string(),
|
|
178
|
+
daily_budget_micro: wireNumber.optional(),
|
|
179
|
+
lifetime_spend_cap_micro: wireNumber.optional()
|
|
180
|
+
});
|
|
181
|
+
var statSchema = z2.looseObject({
|
|
182
|
+
id: snapchatId,
|
|
183
|
+
stats: z2.record(z2.string(), wireNumber).optional(),
|
|
184
|
+
breakdown_stats: z2.record(z2.string(), z2.array(z2.looseObject({
|
|
185
|
+
id: snapchatId,
|
|
186
|
+
stats: z2.record(z2.string(), wireNumber)
|
|
187
|
+
}))).optional()
|
|
188
|
+
});
|
|
189
|
+
var createCampaignSchema = z2.object({
|
|
190
|
+
name: z2.string().min(1).max(375),
|
|
191
|
+
start_time: z2.iso.datetime({ offset: true }),
|
|
192
|
+
end_time: z2.iso.datetime({ offset: true }).optional(),
|
|
193
|
+
objective: z2.string().min(1).default("BRAND_AWARENESS"),
|
|
194
|
+
status: snapchatStatus.default("PAUSED"),
|
|
195
|
+
daily_budget_micro: snapchatMicros.positive().optional(),
|
|
196
|
+
lifetime_spend_cap_micro: snapchatMicros.positive().optional(),
|
|
197
|
+
measurement_spec: z2.object({ ios_app_id: z2.string().optional(), android_app_url: z2.string().optional() }).optional(),
|
|
198
|
+
regulations: z2.object({ restricted_delivery_signals: z2.boolean() }).optional()
|
|
199
|
+
});
|
|
200
|
+
var setStatusSchema = z2.object({ campaign_id: snapchatId, status: snapchatStatus });
|
|
201
|
+
var setBudgetSchema = z2.object({
|
|
202
|
+
campaign_id: snapchatId,
|
|
203
|
+
field: z2.enum(["daily_budget_micro", "lifetime_spend_cap_micro"]).default("daily_budget_micro"),
|
|
204
|
+
budget_micros: snapchatMicros.positive()
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
// src/provider.ts
|
|
208
|
+
var MICROS = 1e6;
|
|
209
|
+
var FIELDS = "spend,impressions,swipes,conversion_purchases,conversion_purchases_value";
|
|
210
|
+
var BREAKDOWN = { account: "campaign", campaign: "campaign", ad_group: "adsquad", ad: "ad" };
|
|
211
|
+
var SnapchatAdsProvider = class {
|
|
212
|
+
constructor(client) {
|
|
213
|
+
this.client = client;
|
|
214
|
+
}
|
|
215
|
+
client;
|
|
216
|
+
id = "snapchat";
|
|
217
|
+
capabilities() {
|
|
218
|
+
return { serverDryRun: false };
|
|
219
|
+
}
|
|
220
|
+
standardActions() {
|
|
221
|
+
return { pauseCampaign: (accountId, campaignId) => ({
|
|
222
|
+
tool: "snapchat_set_campaign_status",
|
|
223
|
+
input: { account_id: accountId, campaign_id: campaignId, status: "PAUSED" }
|
|
224
|
+
}) };
|
|
225
|
+
}
|
|
226
|
+
async listAccounts() {
|
|
227
|
+
const organizations = await this.client.collection("me/organizations", "organizations", "organization", organizationSchema);
|
|
228
|
+
const accounts = /* @__PURE__ */ new Map();
|
|
229
|
+
for (const organization of organizations) {
|
|
230
|
+
const rows = await this.client.collection(`organizations/${organization.id}/adaccounts`, "adaccounts", "adaccount", accountSchema);
|
|
231
|
+
for (const account of rows) accounts.set(account.id, {
|
|
232
|
+
provider: this.id,
|
|
233
|
+
id: account.id,
|
|
234
|
+
name: account.name,
|
|
235
|
+
currency: account.currency,
|
|
236
|
+
status: account.status
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
return [...accounts.values()];
|
|
240
|
+
}
|
|
241
|
+
async listCampaigns(accountId) {
|
|
242
|
+
return this.client.collection(`adaccounts/${snapchatId.parse(accountId)}/campaigns`, "campaigns", "campaign", campaignSchema, { limit: "1000" });
|
|
243
|
+
}
|
|
244
|
+
async report(query) {
|
|
245
|
+
const range = resolveDateRange(query.dateRange);
|
|
246
|
+
const accountIds = query.accountIds ?? (await this.listAccounts()).map((a) => a.id);
|
|
247
|
+
const rows = [];
|
|
248
|
+
const limit = query.limit ?? 1e3;
|
|
249
|
+
if (!Number.isSafeInteger(limit) || limit < 1) throw new AdportError2("INVALID_INPUT", "snapchat: report limit must be a positive integer");
|
|
250
|
+
for (const id of accountIds) {
|
|
251
|
+
const accountId = snapchatId.parse(id);
|
|
252
|
+
const accounts = await this.client.collection(`adaccounts/${accountId}`, "adaccounts", "adaccount", accountSchema);
|
|
253
|
+
const account = accounts.find((a) => a.id === accountId);
|
|
254
|
+
if (!account) throw new AdportError2("PROVIDER_ERROR", "snapchat: requested account missing from response");
|
|
255
|
+
const breakdown = BREAKDOWN[query.level];
|
|
256
|
+
const totals = await this.client.collection(`adaccounts/${accountId}/stats`, "total_stats", "total_stat", statSchema, {
|
|
257
|
+
granularity: "TOTAL",
|
|
258
|
+
breakdown,
|
|
259
|
+
fields: FIELDS,
|
|
260
|
+
start_time: accountMidnight(range.start, account.timezone),
|
|
261
|
+
end_time: accountMidnight(nextDate(range.end), account.timezone),
|
|
262
|
+
swipe_up_attribution_window: "28_DAY",
|
|
263
|
+
view_attribution_window: "1_DAY"
|
|
264
|
+
});
|
|
265
|
+
const stats = totals.flatMap((total) => {
|
|
266
|
+
if (total.id !== accountId || !total.breakdown_stats || !Array.isArray(total.breakdown_stats[breakdown])) {
|
|
267
|
+
throw new AdportError2("PROVIDER_ERROR", "snapchat: malformed or incorrectly scoped report breakdown");
|
|
268
|
+
}
|
|
269
|
+
return total.breakdown_stats[breakdown];
|
|
270
|
+
});
|
|
271
|
+
if (query.level === "account") {
|
|
272
|
+
const sums = {};
|
|
273
|
+
for (const field of FIELDS.split(",")) {
|
|
274
|
+
if (stats.every((row) => row.stats[field] !== void 0)) sums[field] = stats.reduce((sum, row) => sum + row.stats[field], 0);
|
|
275
|
+
}
|
|
276
|
+
rows.push({ provider: this.id, accountId, entity: { level: "account", id: accountId, name: account.name, status: account.status }, metrics: normalize(sums, query.metrics) });
|
|
277
|
+
} else {
|
|
278
|
+
for (const stat of stats) rows.push({
|
|
279
|
+
provider: this.id,
|
|
280
|
+
accountId,
|
|
281
|
+
entity: { level: query.level, id: stat.id, name: stat.id },
|
|
282
|
+
metrics: normalize(stat.stats, query.metrics)
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
return { rows: rows.slice(0, limit), ...rows.length > limit ? { truncated: true } : {} };
|
|
287
|
+
}
|
|
288
|
+
async previewWrite(op, guard) {
|
|
289
|
+
const { execute: _execute, ...preview } = await this.plan(op, guard);
|
|
290
|
+
return { ...preview, serverValidated: false };
|
|
291
|
+
}
|
|
292
|
+
async applyWrite(op, guard) {
|
|
293
|
+
return { applied: true, resourceIds: await (await this.plan(op, guard)).execute() };
|
|
294
|
+
}
|
|
295
|
+
async plan(op, guard) {
|
|
296
|
+
const accountId = snapchatId.parse(op.accountId);
|
|
297
|
+
if (op.provider !== this.id) throw new AdportError2("INVALID_INPUT", "snapchat: provider mismatch");
|
|
298
|
+
if (op.tool === "snapchat_create_campaign" && op.kind === "create") {
|
|
299
|
+
const input2 = createCampaignSchema.parse(op.payload);
|
|
300
|
+
if (input2.end_time && Date.parse(input2.end_time) <= Date.parse(input2.start_time)) {
|
|
301
|
+
throw new AdportError2("INVALID_INPUT", "snapchat: end_time must be after start_time");
|
|
302
|
+
}
|
|
303
|
+
const status = guard.forcePausedCreation ? "PAUSED" : input2.status;
|
|
304
|
+
const body = { campaigns: [{ ...input2, ad_account_id: accountId, status, buy_model: "AUCTION" }] };
|
|
305
|
+
return {
|
|
306
|
+
summary: `Create Snapchat campaign "${input2.name}"`,
|
|
307
|
+
changes: [`+ ${JSON.stringify(body)}`],
|
|
308
|
+
coercions: status !== input2.status ? ["status coerced to PAUSED by policy (paused_creation)"] : [],
|
|
309
|
+
budgetDeltas: ["daily_budget_micro", "lifetime_spend_cap_micro"].flatMap((field2) => {
|
|
310
|
+
const value2 = input2[field2];
|
|
311
|
+
return value2 === void 0 ? [] : [{ target: `new campaign ${field2}`, toMicros: value2 }];
|
|
312
|
+
}),
|
|
313
|
+
execute: async () => (await this.client.mutate(`adaccounts/${accountId}/campaigns`, "POST", body, "campaigns", "campaign", campaignSchema)).map((c) => c.id)
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
if (op.kind !== "update" || !["snapchat_set_campaign_status", "snapchat_set_budget"].includes(op.tool)) {
|
|
317
|
+
throw new AdportError2("INVALID_INPUT", `snapchat: unsupported write ${op.tool}`);
|
|
318
|
+
}
|
|
319
|
+
const input = op.tool === "snapchat_set_budget" ? setBudgetSchema.parse(op.payload) : setStatusSchema.parse(op.payload);
|
|
320
|
+
const campaigns = await this.client.collection(`campaigns/${input.campaign_id}`, "campaigns", "campaign", campaignSchema);
|
|
321
|
+
const current = campaigns.find((c) => c.id === input.campaign_id);
|
|
322
|
+
if (!current || current.ad_account_id !== accountId) {
|
|
323
|
+
throw new AdportError2("INVALID_INPUT", "snapchat: campaign does not belong to selected account");
|
|
324
|
+
}
|
|
325
|
+
const field = "budget_micros" in input ? input.field : "status";
|
|
326
|
+
const value = "budget_micros" in input ? input.budget_micros : input.status;
|
|
327
|
+
const previous = current[field];
|
|
328
|
+
const patch = [{ op: previous === void 0 ? "add" : "replace", path: `/${field}`, value }];
|
|
329
|
+
return {
|
|
330
|
+
summary: `Change Snapchat campaign "${current.name}" ${field}`,
|
|
331
|
+
changes: [`~ ${current.id} ${field}: ${previous ?? "unset"} \u2192 ${value}`],
|
|
332
|
+
coercions: [],
|
|
333
|
+
budgetDeltas: typeof value === "number" ? [{ target: `campaign ${current.id} ${field}`, ...typeof previous === "number" ? { fromMicros: previous } : {}, toMicros: value }] : [],
|
|
334
|
+
execute: async () => (await this.client.mutate(
|
|
335
|
+
`adaccounts/${accountId}/campaigns/${current.id}`,
|
|
336
|
+
"PATCH",
|
|
337
|
+
patch,
|
|
338
|
+
"campaigns",
|
|
339
|
+
"campaign",
|
|
340
|
+
campaignSchema
|
|
341
|
+
)).map((c) => c.id)
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
};
|
|
345
|
+
function normalize(raw, metrics) {
|
|
346
|
+
const mapped = {};
|
|
347
|
+
const fields = { spend: ["spend", MICROS], impressions: ["impressions", 1], clicks: ["swipes", 1], conversions: ["conversion_purchases", 1], conversion_value: ["conversion_purchases_value", MICROS] };
|
|
348
|
+
for (const [metric, [field, divisor]] of Object.entries(fields)) {
|
|
349
|
+
if (raw[field] !== void 0) mapped[metric] = raw[field] / divisor;
|
|
350
|
+
}
|
|
351
|
+
for (const [metric, numerator, denominator, factor] of [
|
|
352
|
+
["ctr", "clicks", "impressions", 100],
|
|
353
|
+
["cpc", "spend", "clicks", 1],
|
|
354
|
+
["cpm", "spend", "impressions", 1e3],
|
|
355
|
+
["cpa", "spend", "conversions", 1],
|
|
356
|
+
["roas", "conversion_value", "spend", 1]
|
|
357
|
+
]) {
|
|
358
|
+
if (mapped[numerator] !== void 0 && mapped[denominator] !== void 0) {
|
|
359
|
+
mapped[metric] = mapped[denominator] ? mapped[numerator] / mapped[denominator] * factor : 0;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
return Object.fromEntries(metrics.filter((metric) => mapped[metric] !== void 0).map((metric) => [metric, mapped[metric]]));
|
|
363
|
+
}
|
|
364
|
+
function nextDate(date) {
|
|
365
|
+
return new Date(Date.parse(`${date}T00:00:00Z`) + 864e5).toISOString().slice(0, 10);
|
|
366
|
+
}
|
|
367
|
+
function accountMidnight(date, timezone) {
|
|
368
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) throw new AdportError2("INVALID_INPUT", "snapchat: invalid report date");
|
|
369
|
+
const target = Date.parse(`${date}T00:00:00Z`);
|
|
370
|
+
if (!Number.isFinite(target) || new Date(target).toISOString().slice(0, 10) !== date) throw new AdportError2("INVALID_INPUT", "snapchat: invalid report date");
|
|
371
|
+
const format = new Intl.DateTimeFormat("en-GB", { timeZone: timezone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23" });
|
|
372
|
+
let value = target;
|
|
373
|
+
for (let i = 0; i < 4; i++) {
|
|
374
|
+
const parts = Object.fromEntries(format.formatToParts(new Date(value)).map((p) => [p.type, p.value]));
|
|
375
|
+
const rendered = Date.parse(`${parts.year}-${parts.month}-${parts.day}T${parts.hour}:${parts.minute}:${parts.second}Z`);
|
|
376
|
+
if (rendered === target) return new Date(value).toISOString();
|
|
377
|
+
value += target - rendered;
|
|
378
|
+
}
|
|
379
|
+
throw new AdportError2("INVALID_INPUT", "snapchat: account timezone has no midnight for this report date");
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
// src/tools.ts
|
|
383
|
+
import { z as z3 } from "zod";
|
|
384
|
+
import { defineTool, guardedWriteTool } from "@adport/core";
|
|
385
|
+
function snapchatTools(provider) {
|
|
386
|
+
return [
|
|
387
|
+
defineTool({
|
|
388
|
+
name: "snapchat_list_campaigns",
|
|
389
|
+
namespace: "snapchat",
|
|
390
|
+
description: "List Snapchat campaigns in the selected ad account.",
|
|
391
|
+
input: z3.object({ account_id: snapchatId }),
|
|
392
|
+
annotations: { readOnly: true },
|
|
393
|
+
handler: (input) => provider.listCampaigns(input.account_id)
|
|
394
|
+
}),
|
|
395
|
+
guardedWriteTool({
|
|
396
|
+
name: "snapchat_create_campaign",
|
|
397
|
+
namespace: "snapchat",
|
|
398
|
+
provider: "snapchat",
|
|
399
|
+
kind: "create",
|
|
400
|
+
description: "Create a Snapchat campaign, paused by default. Budget fields use integer micro-currency. Preview is local, not server validation.",
|
|
401
|
+
payload: createCampaignSchema
|
|
402
|
+
}),
|
|
403
|
+
guardedWriteTool({
|
|
404
|
+
name: "snapchat_set_campaign_status",
|
|
405
|
+
namespace: "snapchat",
|
|
406
|
+
provider: "snapchat",
|
|
407
|
+
kind: "update",
|
|
408
|
+
description: "Pause or activate a Snapchat campaign after verifying account ownership.",
|
|
409
|
+
payload: setStatusSchema
|
|
410
|
+
}),
|
|
411
|
+
guardedWriteTool({
|
|
412
|
+
name: "snapchat_set_budget",
|
|
413
|
+
namespace: "snapchat",
|
|
414
|
+
provider: "snapchat",
|
|
415
|
+
kind: "update",
|
|
416
|
+
description: "Set a Snapchat campaign daily budget or lifetime cap in integer micros; reads the existing value for policy checks.",
|
|
417
|
+
payload: setBudgetSchema
|
|
418
|
+
})
|
|
419
|
+
];
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
// src/index.ts
|
|
423
|
+
async function resolveSnapchatCredentials(store) {
|
|
424
|
+
const record = await store.get("snapchat");
|
|
425
|
+
const data = record?.data;
|
|
426
|
+
if (data?.client_id && data.client_secret && data.refresh_token) return {
|
|
427
|
+
clientId: data.client_id,
|
|
428
|
+
clientSecret: data.client_secret,
|
|
429
|
+
refreshToken: data.refresh_token,
|
|
430
|
+
onRefreshToken: async (refreshToken) => {
|
|
431
|
+
const latest = await store.get("snapchat");
|
|
432
|
+
if (latest) await store.set({ provider: "snapchat", source: latest.source, data: { ...latest.data, refresh_token: refreshToken } });
|
|
433
|
+
}
|
|
434
|
+
};
|
|
435
|
+
if (process.env.SNAPCHAT_CLIENT_ID && process.env.SNAPCHAT_CLIENT_SECRET && process.env.SNAPCHAT_REFRESH_TOKEN) return {
|
|
436
|
+
clientId: process.env.SNAPCHAT_CLIENT_ID,
|
|
437
|
+
clientSecret: process.env.SNAPCHAT_CLIENT_SECRET,
|
|
438
|
+
refreshToken: process.env.SNAPCHAT_REFRESH_TOKEN
|
|
439
|
+
};
|
|
440
|
+
return void 0;
|
|
441
|
+
}
|
|
442
|
+
async function createSnapchatModule(store) {
|
|
443
|
+
const credentials = await resolveSnapchatCredentials(store);
|
|
444
|
+
if (!credentials) return void 0;
|
|
445
|
+
const provider = new SnapchatAdsProvider(new SnapchatAdsClient(credentials));
|
|
446
|
+
return { provider, tools: snapchatTools(provider) };
|
|
447
|
+
}
|
|
448
|
+
export {
|
|
449
|
+
SNAPCHAT_API_BASE,
|
|
450
|
+
SNAPCHAT_SCOPE,
|
|
451
|
+
SNAPCHAT_TOKEN_URL,
|
|
452
|
+
SnapchatAdsClient,
|
|
453
|
+
SnapchatAdsProvider,
|
|
454
|
+
accountMidnight,
|
|
455
|
+
accountSchema,
|
|
456
|
+
buildSnapchatAuthUrl,
|
|
457
|
+
campaignSchema,
|
|
458
|
+
createSnapchatModule,
|
|
459
|
+
exchangeSnapchatCode,
|
|
460
|
+
organizationSchema,
|
|
461
|
+
resolveSnapchatCredentials,
|
|
462
|
+
snapchatTools,
|
|
463
|
+
statSchema
|
|
464
|
+
};
|
|
465
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client.ts","../src/provider.ts","../src/schemas.ts","../src/tools.ts","../src/index.ts"],"sourcesContent":["import { AdportError } from '@adport/core';\nimport { z } from 'zod';\n\nexport const SNAPCHAT_API_BASE = 'https://adsapi.snapchat.com/v1/';\nexport const SNAPCHAT_TOKEN_URL = 'https://accounts.snapchat.com/login/oauth2/access_token';\nexport const SNAPCHAT_SCOPE = 'snapchat-marketing-api';\n\nexport function buildSnapchatAuthUrl(clientId: string, redirectUri: string, state: string): string {\n return `https://accounts.snapchat.com/login/oauth2/authorize?${new URLSearchParams({\n client_id: clientId, redirect_uri: redirectUri, response_type: 'code', scope: SNAPCHAT_SCOPE, state,\n })}`;\n}\n\nexport async function exchangeSnapchatCode(input: { clientId: string; clientSecret: string; code: string; redirectUri: string }, fetchImpl: typeof fetch = fetch): Promise<string> {\n const response = await fetchImpl(SNAPCHAT_TOKEN_URL, {\n method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({ grant_type: 'authorization_code', client_id: input.clientId, client_secret: input.clientSecret, code: input.code, redirect_uri: input.redirectUri }),\n redirect: 'error', signal: AbortSignal.timeout(30_000),\n });\n if (!response.ok) throw new AdportError('PROVIDER_ERROR', `snapchat: OAuth exchange failed (HTTP ${response.status})`);\n const parsed = tokenSchema.safeParse(await response.json());\n if (!parsed.success || !parsed.data.refresh_token) throw new AdportError('PROVIDER_ERROR', 'snapchat: OAuth response did not include a valid refresh token');\n return parsed.data.refresh_token;\n}\n\nexport interface SnapchatCredentials {\n clientId: string;\n clientSecret: string;\n refreshToken: string;\n onRefreshToken?: (refreshToken: string) => Promise<void>;\n}\n\nconst envelopeSchema = z.looseObject({\n request_status: z.string(),\n request_id: z.string().optional(),\n paging: z.object({ next_link: z.string().optional() }).optional(),\n});\nconst success = (status: string) => status.toUpperCase() === 'SUCCESS';\nconst tokenSchema = z.object({\n access_token: z.string().min(1), expires_in: z.number().positive(), refresh_token: z.string().min(1).optional(),\n});\n\nexport class SnapchatAdsClient {\n private token?: { value: string; expiresAt: number };\n private refreshToken: string;\n private refreshing?: Promise<string>;\n\n constructor(private readonly credentials: SnapchatCredentials, private readonly fetchImpl: typeof fetch = fetch) {\n this.refreshToken = credentials.refreshToken;\n }\n\n async collection<T>(path: string, plural: string, singular: string, schema: z.ZodType<T>, params: Record<string, string> = {}): Promise<T[]> {\n let url = this.url(path, params);\n const resourcePath = url.pathname;\n const visited = new Set<string>();\n const rows: T[] = [];\n while (true) {\n if (visited.has(url.href) || visited.size >= 1000) {\n throw new AdportError('PROVIDER_ERROR', 'snapchat: pagination did not terminate; refusing incomplete results');\n }\n visited.add(url.href);\n const data = await this.send(url, 'GET');\n rows.push(...this.items(data, plural, singular, schema));\n const next = data.paging?.next_link;\n if (!next) return rows;\n url = this.url(next);\n if (url.pathname !== resourcePath) throw new AdportError('PROVIDER_ERROR', 'snapchat: pagination changed resource scope');\n }\n }\n\n async mutate<T>(path: string, method: 'POST' | 'PATCH', body: unknown, plural: string, singular: string, schema: z.ZodType<T>): Promise<T[]> {\n const data = await this.send(this.url(path), method, body);\n return this.items(data, plural, singular, schema);\n }\n\n private items<T>(data: z.infer<typeof envelopeSchema>, plural: string, singular: string, schema: z.ZodType<T>): T[] {\n const items = z.array(z.looseObject({ sub_request_status: z.string() })).safeParse(data[plural]);\n if (!items.success) throw new AdportError('PROVIDER_ERROR', `snapchat: malformed ${plural} response`);\n return items.data.map(item => {\n if (!success(item.sub_request_status)) {\n throw new AdportError('PROVIDER_ERROR', `snapchat: ${singular} sub-request failed`, { requestId: data.request_id });\n }\n const parsed = schema.safeParse(item[singular]);\n if (!parsed.success) throw new AdportError('PROVIDER_ERROR', `snapchat: malformed ${singular} response`);\n return parsed.data;\n });\n }\n\n private url(path: string, params: Record<string, string> = {}): URL {\n // Pagination must never forward an access token to another origin or API.\n const url = new URL(path, SNAPCHAT_API_BASE);\n if (url.origin !== 'https://adsapi.snapchat.com' || !url.pathname.startsWith('/v1/') || url.username || url.password || url.hash) {\n throw new AdportError('INVALID_INPUT', 'snapchat: invalid API URL');\n }\n for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);\n return url;\n }\n\n private async send(url: URL, method: 'GET' | 'POST' | 'PATCH', body?: unknown, retry = true): Promise<z.infer<typeof envelopeSchema>> {\n const token = await this.accessToken();\n const response = await this.fetchImpl(url.href, {\n method,\n headers: {\n authorization: `Bearer ${token}`,\n ...(body !== undefined ? { 'content-type': method === 'PATCH' ? 'application/json-patch+json' : 'application/json' } : {}),\n },\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n redirect: 'error', signal: AbortSignal.timeout(30_000),\n });\n if (response.status === 401 && method === 'GET' && retry) {\n if (this.token?.value === token) this.token = undefined;\n return this.send(url, method, body, false);\n }\n if (!response.ok) {\n const advice = response.status === 403 ? ' Check app approval and the user’s ad-account permissions; reconnecting alone may not resolve this.' : '';\n throw new AdportError('PROVIDER_ERROR', `snapchat: HTTP ${response.status}.${advice}`);\n }\n const parsed = envelopeSchema.safeParse(await response.json());\n if (!parsed.success) throw new AdportError('PROVIDER_ERROR', 'snapchat: malformed API envelope');\n if (!success(parsed.data.request_status)) {\n throw new AdportError('PROVIDER_ERROR', 'snapchat: API request failed', { requestId: parsed.data.request_id });\n }\n return parsed.data;\n }\n\n private async accessToken(): Promise<string> {\n if (this.token && this.token.expiresAt > Date.now() + 60_000) return this.token.value;\n if (!this.refreshing) this.refreshing = this.refresh().finally(() => { this.refreshing = undefined; });\n return this.refreshing;\n }\n\n private async refresh(): Promise<string> {\n const response = await this.fetchImpl(SNAPCHAT_TOKEN_URL, {\n method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'refresh_token', client_id: this.credentials.clientId,\n client_secret: this.credentials.clientSecret, refresh_token: this.refreshToken,\n }),\n redirect: 'error', signal: AbortSignal.timeout(30_000),\n });\n if (!response.ok) throw new AdportError('PROVIDER_ERROR', `snapchat: OAuth refresh failed (HTTP ${response.status}); re-authorize if the grant was revoked or expired`);\n const parsed = tokenSchema.safeParse(await response.json());\n if (!parsed.success) throw new AdportError('PROVIDER_ERROR', 'snapchat: malformed OAuth response');\n const token = parsed.data;\n if (token.refresh_token && token.refresh_token !== this.refreshToken) {\n this.refreshToken = token.refresh_token;\n await this.credentials.onRefreshToken?.(token.refresh_token);\n }\n this.token = { value: token.access_token, expiresAt: Date.now() + token.expires_in * 1000 };\n return token.access_token;\n }\n}\n","import {\n AdportError, resolveDateRange, type Account, type AdProvider, type MetricName,\n type NormalizedQuery, type Report, type ReportRow, type StandardActions,\n type WriteGuard, type WriteOperation, type WritePreview, type WriteResult,\n} from '@adport/core';\nimport { SnapchatAdsClient } from './client.js';\nimport {\n accountSchema, campaignSchema, createCampaignSchema, organizationSchema,\n setBudgetSchema, setStatusSchema, snapchatId, statSchema,\n} from './schemas.js';\n\ninterface Plan extends Omit<WritePreview, 'serverValidated'> { execute: () => Promise<string[]> }\nconst MICROS = 1_000_000;\nconst FIELDS = 'spend,impressions,swipes,conversion_purchases,conversion_purchases_value';\nconst BREAKDOWN = { account: 'campaign', campaign: 'campaign', ad_group: 'adsquad', ad: 'ad' } as const;\n\nexport class SnapchatAdsProvider implements AdProvider {\n readonly id = 'snapchat';\n constructor(private readonly client: SnapchatAdsClient) {}\n capabilities() { return { serverDryRun: false }; }\n standardActions(): StandardActions {\n return { pauseCampaign: (accountId, campaignId) => ({\n tool: 'snapchat_set_campaign_status', input: { account_id: accountId, campaign_id: campaignId, status: 'PAUSED' },\n }) };\n }\n\n async listAccounts(): Promise<Account[]> {\n const organizations = await this.client.collection('me/organizations', 'organizations', 'organization', organizationSchema);\n const accounts = new Map<string, Account>();\n for (const organization of organizations) {\n const rows = await this.client.collection(`organizations/${organization.id}/adaccounts`, 'adaccounts', 'adaccount', accountSchema);\n for (const account of rows) accounts.set(account.id, {\n provider: this.id, id: account.id, name: account.name, currency: account.currency, status: account.status,\n });\n }\n return [...accounts.values()];\n }\n\n async listCampaigns(accountId: string) {\n return this.client.collection(`adaccounts/${snapchatId.parse(accountId)}/campaigns`, 'campaigns', 'campaign', campaignSchema, { limit: '1000' });\n }\n\n async report(query: NormalizedQuery): Promise<Report> {\n const range = resolveDateRange(query.dateRange);\n const accountIds = query.accountIds ?? (await this.listAccounts()).map(a => a.id);\n const rows: ReportRow[] = [];\n const limit = query.limit ?? 1000;\n if (!Number.isSafeInteger(limit) || limit < 1) throw new AdportError('INVALID_INPUT', 'snapchat: report limit must be a positive integer');\n for (const id of accountIds) {\n const accountId = snapchatId.parse(id);\n const accounts = await this.client.collection(`adaccounts/${accountId}`, 'adaccounts', 'adaccount', accountSchema);\n const account = accounts.find(a => a.id === accountId);\n if (!account) throw new AdportError('PROVIDER_ERROR', 'snapchat: requested account missing from response');\n const breakdown = BREAKDOWN[query.level];\n // Account-level /stats only supports spend. Aggregate the campaign\n // breakdown for complete account metrics; never sum already-derived ratios.\n const totals = await this.client.collection(`adaccounts/${accountId}/stats`, 'total_stats', 'total_stat', statSchema, {\n granularity: 'TOTAL', breakdown, fields: FIELDS,\n start_time: accountMidnight(range.start, account.timezone),\n end_time: accountMidnight(nextDate(range.end), account.timezone),\n swipe_up_attribution_window: '28_DAY', view_attribution_window: '1_DAY',\n });\n const stats = totals.flatMap(total => {\n if (total.id !== accountId || !total.breakdown_stats || !Array.isArray(total.breakdown_stats[breakdown])) {\n throw new AdportError('PROVIDER_ERROR', 'snapchat: malformed or incorrectly scoped report breakdown');\n }\n return total.breakdown_stats[breakdown]!;\n });\n if (query.level === 'account') {\n const sums: Record<string, number> = {};\n for (const field of FIELDS.split(',')) {\n if (stats.every(row => row.stats[field] !== undefined)) sums[field] = stats.reduce((sum, row) => sum + row.stats[field]!, 0);\n }\n rows.push({ provider: this.id, accountId, entity: { level: 'account', id: accountId, name: account.name, status: account.status }, metrics: normalize(sums, query.metrics) });\n } else {\n for (const stat of stats) rows.push({\n provider: this.id, accountId, entity: { level: query.level, id: stat.id, name: stat.id }, metrics: normalize(stat.stats, query.metrics),\n });\n }\n }\n return { rows: rows.slice(0, limit), ...(rows.length > limit ? { truncated: true } : {}) };\n }\n\n async previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview> {\n const { execute: _execute, ...preview } = await this.plan(op, guard);\n return { ...preview, serverValidated: false };\n }\n async applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult> {\n return { applied: true, resourceIds: await (await this.plan(op, guard)).execute() };\n }\n\n private async plan(op: WriteOperation, guard: WriteGuard): Promise<Plan> {\n const accountId = snapchatId.parse(op.accountId);\n if (op.provider !== this.id) throw new AdportError('INVALID_INPUT', 'snapchat: provider mismatch');\n if (op.tool === 'snapchat_create_campaign' && op.kind === 'create') {\n const input = createCampaignSchema.parse(op.payload);\n if (input.end_time && Date.parse(input.end_time) <= Date.parse(input.start_time)) {\n throw new AdportError('INVALID_INPUT', 'snapchat: end_time must be after start_time');\n }\n const status = guard.forcePausedCreation ? 'PAUSED' : input.status;\n const body = { campaigns: [{ ...input, ad_account_id: accountId, status, buy_model: 'AUCTION' }] };\n return {\n summary: `Create Snapchat campaign \"${input.name}\"`,\n changes: [`+ ${JSON.stringify(body)}`],\n coercions: status !== input.status ? ['status coerced to PAUSED by policy (paused_creation)'] : [],\n budgetDeltas: ['daily_budget_micro', 'lifetime_spend_cap_micro'].flatMap(field => {\n const value = input[field as 'daily_budget_micro' | 'lifetime_spend_cap_micro'];\n return value === undefined ? [] : [{ target: `new campaign ${field}`, toMicros: value }];\n }),\n execute: async () => (await this.client.mutate(`adaccounts/${accountId}/campaigns`, 'POST', body, 'campaigns', 'campaign', campaignSchema)).map(c => c.id),\n };\n }\n if (op.kind !== 'update' || !['snapchat_set_campaign_status', 'snapchat_set_budget'].includes(op.tool)) {\n throw new AdportError('INVALID_INPUT', `snapchat: unsupported write ${op.tool}`);\n }\n const input = op.tool === 'snapchat_set_budget' ? setBudgetSchema.parse(op.payload) : setStatusSchema.parse(op.payload);\n const campaigns = await this.client.collection(`campaigns/${input.campaign_id}`, 'campaigns', 'campaign', campaignSchema);\n const current = campaigns.find(c => c.id === input.campaign_id);\n if (!current || current.ad_account_id !== accountId) {\n throw new AdportError('INVALID_INPUT', 'snapchat: campaign does not belong to selected account');\n }\n const field = 'budget_micros' in input ? input.field : 'status';\n const value = 'budget_micros' in input ? input.budget_micros : input.status;\n const previous = current[field];\n const patch = [{ op: previous === undefined ? 'add' : 'replace', path: `/${field}`, value }];\n return {\n summary: `Change Snapchat campaign \"${current.name}\" ${field}`,\n changes: [`~ ${current.id} ${field}: ${previous ?? 'unset'} → ${value}`], coercions: [],\n budgetDeltas: typeof value === 'number' ? [{ target: `campaign ${current.id} ${field}`, ...(typeof previous === 'number' ? { fromMicros: previous } : {}), toMicros: value }] : [],\n execute: async () => (await this.client.mutate(\n `adaccounts/${accountId}/campaigns/${current.id}`, 'PATCH', patch, 'campaigns', 'campaign', campaignSchema,\n )).map(c => c.id),\n };\n }\n}\n\nfunction normalize(raw: Record<string, number>, metrics: MetricName[]): Partial<Record<MetricName, number>> {\n const mapped: Partial<Record<MetricName, number>> = {};\n const fields = { spend: ['spend', MICROS], impressions: ['impressions', 1], clicks: ['swipes', 1], conversions: ['conversion_purchases', 1], conversion_value: ['conversion_purchases_value', MICROS] } as const;\n for (const [metric, [field, divisor]] of Object.entries(fields)) {\n if (raw[field] !== undefined) mapped[metric as MetricName] = raw[field]! / divisor;\n }\n for (const [metric, numerator, denominator, factor] of [\n ['ctr', 'clicks', 'impressions', 100], ['cpc', 'spend', 'clicks', 1], ['cpm', 'spend', 'impressions', 1000],\n ['cpa', 'spend', 'conversions', 1], ['roas', 'conversion_value', 'spend', 1],\n ] as const) {\n if (mapped[numerator] !== undefined && mapped[denominator] !== undefined) {\n mapped[metric] = mapped[denominator] ? mapped[numerator]! / mapped[denominator]! * factor : 0;\n }\n }\n return Object.fromEntries(metrics.filter(metric => mapped[metric] !== undefined).map(metric => [metric, mapped[metric]]));\n}\n\nfunction nextDate(date: string): string {\n return new Date(Date.parse(`${date}T00:00:00Z`) + 86_400_000).toISOString().slice(0, 10);\n}\n\n/** Snap TOTAL stats require account-local day boundaries, including DST changes. */\nexport function accountMidnight(date: string, timezone: string): string {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(date)) throw new AdportError('INVALID_INPUT', 'snapchat: invalid report date');\n const target = Date.parse(`${date}T00:00:00Z`);\n if (!Number.isFinite(target) || new Date(target).toISOString().slice(0, 10) !== date) throw new AdportError('INVALID_INPUT', 'snapchat: invalid report date');\n const format = new Intl.DateTimeFormat('en-GB', { timeZone: timezone, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23' });\n let value = target;\n for (let i = 0; i < 4; i++) {\n const parts = Object.fromEntries(format.formatToParts(new Date(value)).map(p => [p.type, p.value]));\n const rendered = Date.parse(`${parts.year}-${parts.month}-${parts.day}T${parts.hour}:${parts.minute}:${parts.second}Z`);\n if (rendered === target) return new Date(value).toISOString();\n value += target - rendered;\n }\n throw new AdportError('INVALID_INPUT', 'snapchat: account timezone has no midnight for this report date');\n}\n","import { z } from 'zod';\n\n// Official Snap Marketing API v1 contracts, reviewed 2026-08-31.\n// Source URLs and normalization decisions: docs/providers/snapchat.md.\nexport const snapchatId = z.string().regex(/^[A-Za-z0-9_-]+$/);\nexport const snapchatStatus = z.enum(['ACTIVE', 'PAUSED']);\nexport const snapchatMicros = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);\nconst wireNumber = z.union([z.number(), z.string().regex(/^\\d+(?:\\.\\d+)?$/)])\n .transform(Number).pipe(z.number().finite().nonnegative().max(Number.MAX_SAFE_INTEGER));\n\nexport const organizationSchema = z.looseObject({ id: snapchatId, name: z.string() });\nexport const accountSchema = z.looseObject({\n id: snapchatId, name: z.string(), currency: z.string(), timezone: z.string(), status: z.string(),\n});\nexport const campaignSchema = z.looseObject({\n id: snapchatId, ad_account_id: snapchatId, name: z.string(), status: z.string(),\n daily_budget_micro: wireNumber.optional(), lifetime_spend_cap_micro: wireNumber.optional(),\n});\nexport type SnapchatCampaign = z.infer<typeof campaignSchema>;\nexport const statSchema = z.looseObject({\n id: snapchatId,\n stats: z.record(z.string(), wireNumber).optional(),\n breakdown_stats: z.record(z.string(), z.array(z.looseObject({\n id: snapchatId, stats: z.record(z.string(), wireNumber),\n }))).optional(),\n});\n\nexport const createCampaignSchema = z.object({\n name: z.string().min(1).max(375),\n start_time: z.iso.datetime({ offset: true }),\n end_time: z.iso.datetime({ offset: true }).optional(),\n objective: z.string().min(1).default('BRAND_AWARENESS'),\n status: snapchatStatus.default('PAUSED'),\n daily_budget_micro: snapchatMicros.positive().optional(),\n lifetime_spend_cap_micro: snapchatMicros.positive().optional(),\n measurement_spec: z.object({ ios_app_id: z.string().optional(), android_app_url: z.string().optional() }).optional(),\n regulations: z.object({ restricted_delivery_signals: z.boolean() }).optional(),\n});\nexport const setStatusSchema = z.object({ campaign_id: snapchatId, status: snapchatStatus });\nexport const setBudgetSchema = z.object({\n campaign_id: snapchatId,\n field: z.enum(['daily_budget_micro', 'lifetime_spend_cap_micro']).default('daily_budget_micro'),\n budget_micros: snapchatMicros.positive(),\n});\n","import { z } from 'zod';\nimport { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { createCampaignSchema, setBudgetSchema, setStatusSchema, snapchatId } from './schemas.js';\nimport type { SnapchatAdsProvider } from './provider.js';\n\nexport function snapchatTools(provider: SnapchatAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'snapchat_list_campaigns', namespace: 'snapchat', description: 'List Snapchat campaigns in the selected ad account.',\n input: z.object({ account_id: snapchatId }), annotations: { readOnly: true }, handler: input => provider.listCampaigns(input.account_id) }),\n guardedWriteTool({ name: 'snapchat_create_campaign', namespace: 'snapchat', provider: 'snapchat', kind: 'create',\n description: 'Create a Snapchat campaign, paused by default. Budget fields use integer micro-currency. Preview is local, not server validation.', payload: createCampaignSchema }),\n guardedWriteTool({ name: 'snapchat_set_campaign_status', namespace: 'snapchat', provider: 'snapchat', kind: 'update',\n description: 'Pause or activate a Snapchat campaign after verifying account ownership.', payload: setStatusSchema }),\n guardedWriteTool({ name: 'snapchat_set_budget', namespace: 'snapchat', provider: 'snapchat', kind: 'update',\n description: 'Set a Snapchat campaign daily budget or lifetime cap in integer micros; reads the existing value for policy checks.', payload: setBudgetSchema }),\n ];\n}\n","import type { CredentialStore, ProviderModule } from '@adport/core';\nimport { SnapchatAdsClient, type SnapchatCredentials } from './client.js';\nimport { SnapchatAdsProvider } from './provider.js';\nimport { snapchatTools } from './tools.js';\nexport { SnapchatAdsClient, SNAPCHAT_API_BASE, SNAPCHAT_TOKEN_URL, SNAPCHAT_SCOPE, buildSnapchatAuthUrl, exchangeSnapchatCode, type SnapchatCredentials } from './client.js';\nexport { SnapchatAdsProvider, accountMidnight } from './provider.js';\nexport { snapchatTools } from './tools.js';\nexport { accountSchema, campaignSchema, organizationSchema, statSchema, type SnapchatCampaign } from './schemas.js';\n\nexport async function resolveSnapchatCredentials(store: CredentialStore): Promise<SnapchatCredentials | undefined> {\n const record = await store.get('snapchat');\n const data = record?.data;\n if (data?.client_id && data.client_secret && data.refresh_token) return {\n clientId: data.client_id, clientSecret: data.client_secret, refreshToken: data.refresh_token,\n onRefreshToken: async refreshToken => {\n const latest = await store.get('snapchat');\n if (latest) await store.set({ provider: 'snapchat', source: latest.source, data: { ...latest.data, refresh_token: refreshToken } });\n },\n };\n if (process.env.SNAPCHAT_CLIENT_ID && process.env.SNAPCHAT_CLIENT_SECRET && process.env.SNAPCHAT_REFRESH_TOKEN) return {\n clientId: process.env.SNAPCHAT_CLIENT_ID, clientSecret: process.env.SNAPCHAT_CLIENT_SECRET, refreshToken: process.env.SNAPCHAT_REFRESH_TOKEN,\n };\n return undefined;\n}\n\nexport async function createSnapchatModule(store: CredentialStore): Promise<ProviderModule | undefined> {\n const credentials = await resolveSnapchatCredentials(store);\n if (!credentials) return undefined;\n const provider = new SnapchatAdsProvider(new SnapchatAdsClient(credentials));\n return { provider, tools: snapchatTools(provider) };\n}\n"],"mappings":";AAAA,SAAS,mBAAmB;AAC5B,SAAS,SAAS;AAEX,IAAM,oBAAoB;AAC1B,IAAM,qBAAqB;AAC3B,IAAM,iBAAiB;AAEvB,SAAS,qBAAqB,UAAkB,aAAqB,OAAuB;AACjG,SAAO,wDAAwD,IAAI,gBAAgB;AAAA,IACjF,WAAW;AAAA,IAAU,cAAc;AAAA,IAAa,eAAe;AAAA,IAAQ,OAAO;AAAA,IAAgB;AAAA,EAChG,CAAC,CAAC;AACJ;AAEA,eAAsB,qBAAqB,OAAsF,YAA0B,OAAwB;AACjL,QAAM,WAAW,MAAM,UAAU,oBAAoB;AAAA,IACnD,QAAQ;AAAA,IAAQ,SAAS,EAAE,gBAAgB,oCAAoC;AAAA,IAC/E,MAAM,IAAI,gBAAgB,EAAE,YAAY,sBAAsB,WAAW,MAAM,UAAU,eAAe,MAAM,cAAc,MAAM,MAAM,MAAM,cAAc,MAAM,YAAY,CAAC;AAAA,IAC/K,UAAU;AAAA,IAAS,QAAQ,YAAY,QAAQ,GAAM;AAAA,EACvD,CAAC;AACD,MAAI,CAAC,SAAS,GAAI,OAAM,IAAI,YAAY,kBAAkB,yCAAyC,SAAS,MAAM,GAAG;AACrH,QAAM,SAAS,Y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,MAAM,EAAE,GAAG,OAAO,MAAM,eAAe,aAAa,EAAE,CAAC;AAAA,IACpI;AAAA,EACF;AACA,MAAI,QAAQ,IAAI,sBAAsB,QAAQ,IAAI,0BAA0B,QAAQ,IAAI,uBAAwB,QAAO;AAAA,IACrH,UAAU,QAAQ,IAAI;AAAA,IAAoB,cAAc,QAAQ,IAAI;AAAA,IAAwB,cAAc,QAAQ,IAAI;AAAA,EACxH;AACA,SAAO;AACT;AAEA,eAAsB,qBAAqB,OAA6D;AACtG,QAAM,cAAc,MAAM,2BAA2B,KAAK;AAC1D,MAAI,CAAC,YAAa,QAAO;AACzB,QAAM,WAAW,IAAI,oBAAoB,IAAI,kBAAkB,WAAW,CAAC;AAC3E,SAAO,EAAE,UAAU,OAAO,cAAc,QAAQ,EAAE;AACpD;","names":["AdportError","z","AdportError","input","field","value","z","z"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@adport/provider-snapchat",
|
|
3
|
+
"version": "0.6.0",
|
|
4
|
+
"description": "Snapchat Marketing API provider for adport",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist"
|
|
17
|
+
],
|
|
18
|
+
"dependencies": {
|
|
19
|
+
"zod": "^4.4.3",
|
|
20
|
+
"@adport/core": "0.6.0"
|
|
21
|
+
},
|
|
22
|
+
"devDependencies": {
|
|
23
|
+
"@types/node": "^26.1.2",
|
|
24
|
+
"tsup": "^8.3.0",
|
|
25
|
+
"typescript": "^5.8.0",
|
|
26
|
+
"vitest": "^4.1.10"
|
|
27
|
+
},
|
|
28
|
+
"scripts": {
|
|
29
|
+
"build": "tsup src/index.ts --format esm --dts --sourcemap --clean",
|
|
30
|
+
"test": "vitest run",
|
|
31
|
+
"typecheck": "tsc --noEmit"
|
|
32
|
+
}
|
|
33
|
+
}
|