@adport/provider-x 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 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.
@@ -0,0 +1,187 @@
1
+ import { z } from 'zod';
2
+ import { Account, AdProvider, StandardActions, WriteOperation, WriteGuard, WritePreview, WriteResult, NormalizedQuery, Report, AnyToolDefinition, CredentialStore, ProviderModule } from '@adport/core';
3
+
4
+ declare const X_ADS_API_BASE = "https://ads-api.x.com/12/";
5
+ interface XAdsCredentials {
6
+ consumerKey: string;
7
+ consumerSecret: string;
8
+ accessToken: string;
9
+ accessTokenSecret: string;
10
+ }
11
+ type XParams = Record<string, string | number | boolean>;
12
+ type XMethod = 'GET' | 'POST' | 'PUT';
13
+ declare class XAdsClient {
14
+ private readonly fetchImpl;
15
+ private readonly signer;
16
+ private readonly token;
17
+ constructor(credentials: XAdsCredentials, fetchImpl?: typeof fetch);
18
+ request<T>(method: XMethod, path: string, schema: z.ZodType<T>, params?: XParams): Promise<T>;
19
+ list<T extends {
20
+ id: string;
21
+ }>(path: string, item: z.ZodType<T>, params?: XParams): Promise<T[]>;
22
+ }
23
+
24
+ declare class XAdsEntities {
25
+ readonly client: XAdsClient;
26
+ constructor(client: XAdsClient);
27
+ listAccounts(): Promise<Account[]>;
28
+ getAccount(accountId: string): Promise<{
29
+ id: string;
30
+ name: string;
31
+ timezone: string;
32
+ approval_status: string;
33
+ deleted: boolean;
34
+ timezone_switch_at?: string | null | undefined;
35
+ }>;
36
+ listCampaigns(accountId: string): Promise<{
37
+ id: string;
38
+ name: string;
39
+ currency: string;
40
+ funding_instrument_id: string;
41
+ entity_status: string;
42
+ deleted: boolean;
43
+ budget_optimization: string;
44
+ daily_budget_amount_local_micro: number | null;
45
+ total_budget_amount_local_micro: number | null;
46
+ }[]>;
47
+ getCampaign(accountId: string, campaignId: string): Promise<{
48
+ id: string;
49
+ name: string;
50
+ currency: string;
51
+ funding_instrument_id: string;
52
+ entity_status: string;
53
+ deleted: boolean;
54
+ budget_optimization: string;
55
+ daily_budget_amount_local_micro: number | null;
56
+ total_budget_amount_local_micro: number | null;
57
+ }>;
58
+ listFundingInstruments(accountId: string): Promise<{
59
+ id: string;
60
+ account_id: string;
61
+ description: string;
62
+ currency: string;
63
+ type: string;
64
+ entity_status: string;
65
+ able_to_fund: boolean;
66
+ deleted: boolean;
67
+ }[]>;
68
+ getFundingInstrument(accountId: string, fundingId: string): Promise<{
69
+ id: string;
70
+ account_id: string;
71
+ description: string;
72
+ currency: string;
73
+ type: string;
74
+ entity_status: string;
75
+ able_to_fund: boolean;
76
+ deleted: boolean;
77
+ }>;
78
+ listLineItems(accountId: string): Promise<{
79
+ id: string;
80
+ name: string;
81
+ campaign_id: string;
82
+ currency: string;
83
+ entity_status: string;
84
+ deleted: boolean;
85
+ placements: string[];
86
+ product_type: string;
87
+ objective: string;
88
+ }[]>;
89
+ listPromotedTweets(accountId: string): Promise<{
90
+ id: string;
91
+ line_item_id: string;
92
+ tweet_id: string;
93
+ entity_status: string;
94
+ deleted: boolean;
95
+ }[]>;
96
+ listPromotedAccounts(accountId: string): Promise<{
97
+ id: string;
98
+ line_item_id: string;
99
+ user_id: string;
100
+ entity_status: string;
101
+ deleted: boolean;
102
+ }[]>;
103
+ listMediaCreatives(accountId: string): Promise<{
104
+ id: string;
105
+ line_item_id: string;
106
+ account_media_id: string;
107
+ entity_status: string;
108
+ deleted: boolean;
109
+ }[]>;
110
+ }
111
+
112
+ declare const statsSchema: z.ZodObject<{
113
+ data_type: z.ZodLiteral<"stats">;
114
+ time_series_length: z.ZodLiteral<1>;
115
+ data: z.ZodArray<z.ZodObject<{
116
+ id: z.ZodString;
117
+ id_data: z.ZodArray<z.ZodObject<{
118
+ segment: z.ZodNull;
119
+ metrics: z.ZodObject<{
120
+ billed_charge_local_micro: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodNullable<z.ZodNumber>>>>;
121
+ impressions: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodNullable<z.ZodNumber>>>>;
122
+ url_clicks: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodNullable<z.ZodNumber>>>>;
123
+ }, z.core.$strip>;
124
+ }, z.core.$strip>>;
125
+ }, z.core.$strip>>;
126
+ request: z.ZodObject<{
127
+ params: z.ZodObject<{
128
+ start_time: z.ZodString;
129
+ end_time: z.ZodString;
130
+ entity: z.ZodString;
131
+ entity_ids: z.ZodArray<z.ZodString>;
132
+ placement: z.ZodString;
133
+ granularity: z.ZodLiteral<"TOTAL">;
134
+ metric_groups: z.ZodArray<z.ZodString>;
135
+ }, z.core.$strip>;
136
+ }, z.core.$strip>;
137
+ }, z.core.$strip>;
138
+ type Stats = z.infer<typeof statsSchema>;
139
+ /** Report jobs are read computations, not advertising mutations. */
140
+ declare class XAdsAnalytics {
141
+ private readonly client;
142
+ private readonly fetchImpl;
143
+ private readonly pause;
144
+ private readonly jobs;
145
+ private readonly inflight;
146
+ constructor(client: XAdsClient, fetchImpl?: typeof fetch, pause?: (ms: number) => Promise<unknown>);
147
+ totals(accountId: string, params: XParams, asynchronous: boolean): Promise<Stats>;
148
+ private load;
149
+ private download;
150
+ }
151
+
152
+ declare class XAdsProvider extends XAdsEntities implements AdProvider {
153
+ readonly id = "x";
154
+ private readonly analytics;
155
+ constructor(client: XAdsClient, analytics?: XAdsAnalytics);
156
+ capabilities(): {
157
+ serverDryRun: boolean;
158
+ };
159
+ standardActions(): StandardActions;
160
+ previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview>;
161
+ applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult>;
162
+ report(query: NormalizedQuery): Promise<Report>;
163
+ private reportEntities;
164
+ }
165
+
166
+ declare function xTools(provider: XAdsProvider): AnyToolDefinition[];
167
+
168
+ type App = Pick<XAdsCredentials, 'consumerKey' | 'consumerSecret'>;
169
+ interface XUserTokens {
170
+ accessToken: string;
171
+ accessTokenSecret: string;
172
+ }
173
+ interface XRequestTokens {
174
+ requestToken: string;
175
+ requestTokenSecret: string;
176
+ }
177
+ declare function requestXToken(app: App, callback: string, fetchImpl?: typeof fetch): Promise<XRequestTokens>;
178
+ declare function buildXAuthorizationUrl(requestToken: string): string;
179
+ declare function exchangeXToken(app: App, request: XRequestTokens, verifier: string, fetchImpl?: typeof fetch): Promise<XUserTokens>;
180
+ declare function revokeXToken(credentials: XAdsCredentials, fetchImpl?: typeof fetch): Promise<void>;
181
+
182
+ declare function xCredentialsFromData(data: Record<string, string> | undefined): XAdsCredentials | undefined;
183
+ declare function xEnvironmentData(): Record<string, string>;
184
+ declare function resolveXCredentials(store: CredentialStore): Promise<XAdsCredentials | undefined>;
185
+ declare function createXModule(store: CredentialStore): Promise<ProviderModule | undefined>;
186
+
187
+ export { XAdsAnalytics, XAdsClient, type XAdsCredentials, XAdsEntities, XAdsProvider, type XParams, type XRequestTokens, type XUserTokens, X_ADS_API_BASE, buildXAuthorizationUrl, createXModule, exchangeXToken, requestXToken, resolveXCredentials, revokeXToken, xCredentialsFromData, xEnvironmentData, xTools };
package/dist/index.js ADDED
@@ -0,0 +1,702 @@
1
+ // src/client.ts
2
+ import { createHmac, randomBytes } from "crypto";
3
+ import OAuth from "oauth-1.0a";
4
+ import { z } from "zod";
5
+ import { AdportError } from "@adport/core";
6
+ var X_ADS_API_BASE = "https://ads-api.x.com/12/";
7
+ function createXSigner(credentials) {
8
+ const oauth = new OAuth({
9
+ consumer: { key: credentials.consumerKey, secret: credentials.consumerSecret },
10
+ signature_method: "HMAC-SHA1",
11
+ hash_function: (base, key) => createHmac("sha1", key).update(base).digest("base64")
12
+ });
13
+ oauth.getNonce = () => randomBytes(24).toString("hex");
14
+ return oauth;
15
+ }
16
+ var XAdsClient = class {
17
+ constructor(credentials, fetchImpl = fetch) {
18
+ this.fetchImpl = fetchImpl;
19
+ if (Object.values(credentials).some((value) => typeof value !== "string" || !value.trim()) || !credentials.consumerKey || !credentials.consumerSecret || !credentials.accessToken || !credentials.accessTokenSecret) {
20
+ throw new AdportError("INVALID_INPUT", "x: all four OAuth 1.0a credentials are required");
21
+ }
22
+ this.signer = createXSigner(credentials);
23
+ this.token = { key: credentials.accessToken, secret: credentials.accessTokenSecret };
24
+ }
25
+ fetchImpl;
26
+ signer;
27
+ token;
28
+ async request(method, path, schema, params = {}) {
29
+ if (!/^[a-z0-9_]+(?:\/[a-z0-9_]+)*$/.test(path)) throw new AdportError("INVALID_INPUT", "x: invalid API resource path");
30
+ const url = new URL(path, X_ADS_API_BASE);
31
+ for (const [key, value] of Object.entries(params)) {
32
+ if (!/^[a-z][a-z0-9_]*$/.test(key) || key.startsWith("oauth_") || typeof value === "number" && !Number.isFinite(value)) {
33
+ throw new AdportError("INVALID_INPUT", "x: invalid API parameter");
34
+ }
35
+ url.searchParams.set(key, String(value));
36
+ }
37
+ url.search = url.search.replace(/\+/g, "%20");
38
+ const headers = this.signer.toHeader(this.signer.authorize({ url: url.href, method }, this.token));
39
+ let response;
40
+ try {
41
+ response = await this.fetchImpl(url.href, { method, headers: { ...headers, accept: "application/json" }, redirect: "error", signal: AbortSignal.timeout(3e4) });
42
+ } catch {
43
+ throw new AdportError("PROVIDER_ERROR", `x: transport failed${method === "GET" ? "" : "; write outcome unknown, inspect the account before retrying"}`);
44
+ }
45
+ if (!response.ok) {
46
+ const guidance = response.status === 403 ? "Check Ads API app approval and this user\u2019s ad-account permissions; reconnecting alone may not help." : response.status === 401 ? "Check OAuth 1.0a credentials, token permissions and the local clock. Regenerate user tokens after Ads API approval." : response.status === 429 ? "Rate limit reached; wait for the provider reset before retrying." : "Provider request failed.";
47
+ throw new AdportError("PROVIDER_ERROR", `x: HTTP ${response.status}. ${guidance}${method === "GET" ? "" : " The write was not retried."}`);
48
+ }
49
+ let body;
50
+ try {
51
+ body = await response.json();
52
+ } catch {
53
+ throw new AdportError("PROVIDER_ERROR", "x: invalid JSON response");
54
+ }
55
+ if (body && typeof body === "object" && "errors" in body && Array.isArray(body.errors) && body.errors.length) {
56
+ throw new AdportError("PROVIDER_ERROR", "x: provider returned an error envelope");
57
+ }
58
+ const parsed = schema.safeParse(body);
59
+ if (!parsed.success) throw new AdportError("PROVIDER_ERROR", "x: unexpected API response schema");
60
+ return parsed.data;
61
+ }
62
+ async list(path, item, params = {}) {
63
+ const schema = z.object({ data: z.array(item), next_cursor: z.string().nullable().optional() });
64
+ const rows = [], ids = /* @__PURE__ */ new Set(), cursors = /* @__PURE__ */ new Set();
65
+ let cursor;
66
+ while (true) {
67
+ const page = await this.request("GET", path, schema, { ...params, count: 200, ...cursor ? { cursor } : {} });
68
+ for (const row of page.data) {
69
+ if (ids.has(row.id)) throw new AdportError("PROVIDER_ERROR", "x: pagination repeated an entity");
70
+ ids.add(row.id);
71
+ rows.push(row);
72
+ }
73
+ if (!page.next_cursor) return rows;
74
+ if (cursors.has(page.next_cursor) || cursors.size >= 1e3) throw new AdportError("PROVIDER_ERROR", "x: cursor pagination did not terminate");
75
+ cursors.add(page.next_cursor);
76
+ cursor = page.next_cursor;
77
+ }
78
+ }
79
+ };
80
+
81
+ // src/entities.ts
82
+ import { z as z3 } from "zod";
83
+ import { AdportError as AdportError2 } from "@adport/core";
84
+
85
+ // src/schemas.ts
86
+ import { z as z2 } from "zod";
87
+ var xId = z2.string().regex(/^[a-z0-9]+$/).min(1).max(64);
88
+ var micros = z2.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
89
+ var currency = z2.string().regex(/^[A-Z]{3}$/);
90
+ var accountSchema = z2.object({
91
+ id: xId,
92
+ name: z2.string(),
93
+ timezone: z2.string(),
94
+ timezone_switch_at: z2.string().nullable().optional(),
95
+ approval_status: z2.string(),
96
+ deleted: z2.boolean()
97
+ });
98
+ var fundingSchema = z2.object({
99
+ id: xId,
100
+ account_id: xId,
101
+ description: z2.string(),
102
+ currency,
103
+ type: z2.string(),
104
+ entity_status: z2.string(),
105
+ able_to_fund: z2.boolean(),
106
+ deleted: z2.boolean()
107
+ });
108
+ var campaignSchema = z2.object({
109
+ id: xId,
110
+ name: z2.string(),
111
+ currency,
112
+ funding_instrument_id: xId,
113
+ entity_status: z2.string(),
114
+ deleted: z2.boolean(),
115
+ budget_optimization: z2.string(),
116
+ daily_budget_amount_local_micro: micros.nullable(),
117
+ total_budget_amount_local_micro: micros.nullable()
118
+ });
119
+ var lineItemSchema = z2.object({
120
+ id: xId,
121
+ name: z2.string(),
122
+ campaign_id: xId,
123
+ currency,
124
+ entity_status: z2.string(),
125
+ deleted: z2.boolean(),
126
+ placements: z2.array(z2.string()),
127
+ product_type: z2.string(),
128
+ objective: z2.string()
129
+ });
130
+ var promotedTweetSchema = z2.object({
131
+ id: xId,
132
+ line_item_id: xId,
133
+ tweet_id: z2.string().regex(/^\d+$/),
134
+ entity_status: z2.string(),
135
+ deleted: z2.boolean()
136
+ });
137
+ var promotedAccountSchema = z2.object({ id: xId, line_item_id: xId, user_id: z2.string().regex(/^\d+$/), entity_status: z2.string(), deleted: z2.boolean() });
138
+ var mediaCreativeSchema = z2.object({ id: xId, line_item_id: xId, account_media_id: xId, entity_status: z2.string(), deleted: z2.boolean() });
139
+ var createCampaignSchema = z2.object({
140
+ name: z2.string().min(1).max(255),
141
+ funding_instrument_id: xId,
142
+ daily_budget_micros: micros.positive(),
143
+ total_budget_micros: micros.positive().optional(),
144
+ status: z2.enum(["ACTIVE", "PAUSED"]).default("PAUSED")
145
+ });
146
+ var setStatusSchema = z2.object({ campaign_id: xId, status: z2.enum(["ACTIVE", "PAUSED"]) });
147
+ var setBudgetSchema = z2.object({ campaign_id: xId, budget_type: z2.enum(["DAILY", "TOTAL"]), budget_micros: micros.positive() });
148
+
149
+ // src/entities.ts
150
+ var XAdsEntities = class {
151
+ constructor(client) {
152
+ this.client = client;
153
+ }
154
+ client;
155
+ async listAccounts() {
156
+ return (await this.client.list("accounts", accountSchema)).map((a) => ({ provider: "x", id: a.id, name: a.name, status: a.approval_status }));
157
+ }
158
+ async getAccount(accountId) {
159
+ const { data } = await this.client.request("GET", `accounts/${xId.parse(accountId)}`, z3.object({ data: accountSchema }));
160
+ if (data.id !== accountId) throw new AdportError2("PROVIDER_ERROR", "x: account ID mismatch");
161
+ return data;
162
+ }
163
+ listCampaigns(accountId) {
164
+ return this.client.list(`accounts/${xId.parse(accountId)}/campaigns`, campaignSchema, { with_deleted: true, with_draft: true });
165
+ }
166
+ async getCampaign(accountId, campaignId) {
167
+ const { data } = await this.client.request("GET", `accounts/${xId.parse(accountId)}/campaigns/${xId.parse(campaignId)}`, z3.object({ data: campaignSchema }));
168
+ if (data.id !== campaignId) throw new AdportError2("PROVIDER_ERROR", "x: campaign ID mismatch");
169
+ return data;
170
+ }
171
+ async listFundingInstruments(accountId) {
172
+ const data = await this.client.list(`accounts/${xId.parse(accountId)}/funding_instruments`, fundingSchema);
173
+ if (data.some((f) => f.account_id !== accountId)) throw new AdportError2("PROVIDER_ERROR", "x: funding instrument account mismatch");
174
+ return data;
175
+ }
176
+ async getFundingInstrument(accountId, fundingId) {
177
+ const { data } = await this.client.request("GET", `accounts/${xId.parse(accountId)}/funding_instruments/${xId.parse(fundingId)}`, z3.object({ data: fundingSchema }));
178
+ if (data.id !== fundingId || data.account_id !== accountId) throw new AdportError2("PROVIDER_ERROR", "x: funding instrument account/ID mismatch");
179
+ return data;
180
+ }
181
+ listLineItems(accountId) {
182
+ return this.client.list(`accounts/${xId.parse(accountId)}/line_items`, lineItemSchema, { with_deleted: true, with_draft: true });
183
+ }
184
+ listPromotedTweets(accountId) {
185
+ return this.client.list(`accounts/${xId.parse(accountId)}/promoted_tweets`, promotedTweetSchema, { with_deleted: true });
186
+ }
187
+ listPromotedAccounts(accountId) {
188
+ return this.client.list(`accounts/${xId.parse(accountId)}/promoted_accounts`, promotedAccountSchema, { with_deleted: true });
189
+ }
190
+ listMediaCreatives(accountId) {
191
+ return this.client.list(`accounts/${xId.parse(accountId)}/media_creatives`, mediaCreativeSchema, { with_deleted: true });
192
+ }
193
+ };
194
+
195
+ // src/provider.ts
196
+ import { z as z6 } from "zod";
197
+ import { AdportError as AdportError5, resolveDateRange } from "@adport/core";
198
+
199
+ // src/analytics.ts
200
+ import { gunzipSync } from "zlib";
201
+ import { setTimeout as delay } from "timers/promises";
202
+ import { z as z4 } from "zod";
203
+ import { AdportError as AdportError3 } from "@adport/core";
204
+ var X_PLACEMENTS = ["ALL_ON_TWITTER", "SPOTLIGHT", "TREND"];
205
+ var scalar = z4.array(z4.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).nullable()).length(1).nullable().optional();
206
+ var statsSchema = z4.object({
207
+ data_type: z4.literal("stats"),
208
+ time_series_length: z4.literal(1),
209
+ data: z4.array(z4.object({ id: xId, id_data: z4.array(z4.object({ segment: z4.null(), metrics: z4.object({
210
+ billed_charge_local_micro: scalar,
211
+ impressions: scalar,
212
+ url_clicks: scalar
213
+ }) })).length(1) })),
214
+ request: z4.object({ params: z4.object({
215
+ start_time: z4.string(),
216
+ end_time: z4.string(),
217
+ entity: z4.string(),
218
+ entity_ids: z4.array(xId),
219
+ placement: z4.string(),
220
+ granularity: z4.literal("TOTAL"),
221
+ metric_groups: z4.array(z4.string())
222
+ }) })
223
+ });
224
+ var jobSchema = z4.object({
225
+ id_str: z4.string().regex(/^\d+$/),
226
+ account_id: xId,
227
+ status: z4.enum(["PROCESSING", "SUCCESS", "FAILED"]),
228
+ url: z4.string().nullable(),
229
+ start_time: z4.string(),
230
+ end_time: z4.string(),
231
+ entity: z4.string(),
232
+ entity_ids: z4.array(xId),
233
+ placement: z4.string(),
234
+ granularity: z4.literal("TOTAL"),
235
+ metric_groups: z4.array(z4.string())
236
+ });
237
+ var MAX_FILE_BYTES = 20 * 1024 * 1024;
238
+ var XAdsAnalytics = class {
239
+ constructor(client, fetchImpl = fetch, pause = delay) {
240
+ this.client = client;
241
+ this.fetchImpl = fetchImpl;
242
+ this.pause = pause;
243
+ }
244
+ client;
245
+ fetchImpl;
246
+ pause;
247
+ jobs = /* @__PURE__ */ new Map();
248
+ inflight = /* @__PURE__ */ new Map();
249
+ async totals(accountId, params, asynchronous) {
250
+ const key = JSON.stringify([accountId, Object.entries(params).sort(), asynchronous]);
251
+ const active = this.inflight.get(key);
252
+ if (active) return active;
253
+ const promise = this.load(accountId, params, asynchronous, key);
254
+ this.inflight.set(key, promise);
255
+ try {
256
+ return await promise;
257
+ } finally {
258
+ this.inflight.delete(key);
259
+ }
260
+ }
261
+ async load(accountId, params, asynchronous, key) {
262
+ xId.parse(accountId);
263
+ if (!asynchronous) return validateStats(await this.client.request("GET", `stats/accounts/${accountId}`, statsSchema, params), params);
264
+ const path = `stats/jobs/accounts/${accountId}`;
265
+ let job = this.jobs.get(key) ?? (await this.client.request("POST", path, z4.object({ data: jobSchema }), params)).data;
266
+ validateJob(job, accountId, params);
267
+ this.jobs.set(key, job);
268
+ for (let attempt = 0; attempt <= 15; attempt++) {
269
+ if (job.status === "FAILED") {
270
+ this.jobs.delete(key);
271
+ throw new AdportError3("PROVIDER_ERROR", `x: analytics job ${job.id_str} failed`);
272
+ }
273
+ if (job.status === "SUCCESS") {
274
+ if (!job.url) throw new AdportError3("PROVIDER_ERROR", "x: successful analytics job has no download URL");
275
+ const result = validateStats(await this.download(job.url, job.id_str), params);
276
+ this.jobs.delete(key);
277
+ return result;
278
+ }
279
+ if (attempt === 15) break;
280
+ await this.pause(1e3);
281
+ const id = job.id_str;
282
+ const response = await this.client.request("GET", path, z4.object({ data: z4.array(jobSchema) }), { job_ids: id });
283
+ const match = response.data.filter((row) => row.id_str === id);
284
+ if (match.length !== 1 || response.data.length !== 1) throw new AdportError3("PROVIDER_ERROR", "x: analytics polling returned a different or duplicate job");
285
+ job = match[0];
286
+ validateJob(job, accountId, params);
287
+ this.jobs.set(key, job);
288
+ }
289
+ throw new AdportError3("PROVIDER_ERROR", `x: analytics job ${job.id_str} is still processing; retry this report to resume polling`);
290
+ }
291
+ async download(raw, id) {
292
+ let url;
293
+ try {
294
+ url = new URL(raw);
295
+ } catch {
296
+ throw new AdportError3("PROVIDER_ERROR", "x: invalid analytics download URL");
297
+ }
298
+ if (url.origin !== "https://ton.twimg.com" || url.username || url.password || url.hash || url.pathname !== `/advertiser-api-async-analytics/stats_job_${id}.json.gz`) {
299
+ throw new AdportError3("PROVIDER_ERROR", "x: untrusted analytics download URL");
300
+ }
301
+ let response;
302
+ try {
303
+ response = await this.fetchImpl(url.href, { redirect: "error", signal: AbortSignal.timeout(3e4) });
304
+ } catch {
305
+ throw new AdportError3("PROVIDER_ERROR", "x: analytics download transport failed");
306
+ }
307
+ if (!response.ok || !response.body) throw new AdportError3("PROVIDER_ERROR", "x: analytics download failed");
308
+ const reader = response.body.getReader(), chunks = [];
309
+ let size = 0;
310
+ try {
311
+ while (true) {
312
+ const { done, value } = await reader.read();
313
+ if (done) break;
314
+ size += value.byteLength;
315
+ if (size > MAX_FILE_BYTES) {
316
+ await reader.cancel();
317
+ throw new Error("size");
318
+ }
319
+ chunks.push(value);
320
+ }
321
+ const compressed = Buffer.concat(chunks);
322
+ const bytes = compressed[0] === 31 && compressed[1] === 139 ? gunzipSync(compressed, { maxOutputLength: MAX_FILE_BYTES }) : compressed;
323
+ const parsed = statsSchema.safeParse(JSON.parse(bytes.toString("utf8")));
324
+ if (!parsed.success) throw new Error("schema");
325
+ return parsed.data;
326
+ } catch {
327
+ throw new AdportError3("PROVIDER_ERROR", "x: invalid or oversized analytics download");
328
+ } finally {
329
+ reader.releaseLock();
330
+ }
331
+ }
332
+ };
333
+ function matches(data, params) {
334
+ return Date.parse(data.start_time) === Date.parse(String(params.start_time)) && Date.parse(data.end_time) === Date.parse(String(params.end_time)) && data.entity === params.entity && data.placement === params.placement && data.granularity === params.granularity && [...data.entity_ids].sort().join(",") === String(params.entity_ids).split(",").sort().join(",") && [...data.metric_groups].sort().join(",") === String(params.metric_groups).split(",").sort().join(",");
335
+ }
336
+ function validateJob(job, accountId, params) {
337
+ if (job.account_id !== accountId || !matches(job, params)) throw new AdportError3("PROVIDER_ERROR", "x: analytics job scope does not match the report");
338
+ }
339
+ function validateStats(data, params) {
340
+ const ids = String(params.entity_ids).split(","), returned = data.data.map((row) => row.id);
341
+ if (!matches(data.request.params, params) || new Set(returned).size !== returned.length || returned.some((id) => !ids.includes(id)) || ids.some((id) => !returned.includes(id))) {
342
+ throw new AdportError3("PROVIDER_ERROR", "x: analytics returned incomplete, duplicate or incorrectly scoped data");
343
+ }
344
+ return data;
345
+ }
346
+ function xAccountMidnight(date, timezone) {
347
+ z4.iso.date().parse(date);
348
+ const target = Date.parse(`${date}T00:00:00Z`);
349
+ let format;
350
+ try {
351
+ 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" });
352
+ } catch {
353
+ throw new AdportError3("PROVIDER_ERROR", "x: invalid account timezone");
354
+ }
355
+ let value = target;
356
+ for (let i = 0; i < 5; i++) {
357
+ const parts = Object.fromEntries(format.formatToParts(new Date(value)).map((p) => [p.type, p.value]));
358
+ const rendered = Date.parse(`${parts.year}-${parts.month}-${parts.day}T${parts.hour}:${parts.minute}:${parts.second}Z`);
359
+ if (rendered === target) {
360
+ if (value % 36e5 !== 0) throw new AdportError3("INVALID_INPUT", "x: account-local midnight is not a whole UTC hour; the API cannot represent this exact date boundary");
361
+ return value;
362
+ }
363
+ value += target - rendered;
364
+ }
365
+ throw new AdportError3("INVALID_INPUT", "x: no midnight exists for this account-local report date");
366
+ }
367
+
368
+ // src/writes.ts
369
+ import { z as z5 } from "zod";
370
+ import { AdportError as AdportError4 } from "@adport/core";
371
+ async function planXWrite(entities, op, guard) {
372
+ if (op.provider !== "x") throw new AdportError4("INVALID_INPUT", "x: provider mismatch");
373
+ const accountId = xId.parse(op.accountId), base = `accounts/${accountId}/campaigns`;
374
+ if (op.kind === "create" && op.tool === "x_create_campaign") {
375
+ const input = createCampaignSchema.parse(op.payload);
376
+ if (input.total_budget_micros !== void 0 && input.daily_budget_micros > input.total_budget_micros) throw new AdportError4("INVALID_INPUT", "x: daily budget cannot exceed total budget");
377
+ const funding = await entities.getFundingInstrument(accountId, input.funding_instrument_id);
378
+ if (funding.deleted || !funding.able_to_fund || funding.entity_status !== "ACTIVE") throw new AdportError4("INVALID_INPUT", "x: selected funding instrument cannot fund a campaign");
379
+ const status = guard.forcePausedCreation ? "PAUSED" : input.status;
380
+ const params = {
381
+ name: input.name,
382
+ funding_instrument_id: funding.id,
383
+ budget_optimization: "LINE_ITEM",
384
+ entity_status: status,
385
+ daily_budget_amount_local_micro: input.daily_budget_micros,
386
+ ...input.total_budget_micros !== void 0 ? { total_budget_amount_local_micro: input.total_budget_micros } : {}
387
+ };
388
+ return {
389
+ summary: `Create X campaign "${input.name}"`,
390
+ changes: [`+ ${JSON.stringify(params)} (${funding.currency})`, "Campaign only; serving also requires line items, targeting and creatives."],
391
+ coercions: status !== input.status ? ["status coerced to PAUSED by policy (paused_creation)"] : [],
392
+ budgetDeltas: [{ target: "new campaign daily budget", toMicros: input.daily_budget_micros }, ...input.total_budget_micros !== void 0 ? [{ target: "new campaign total budget", toMicros: input.total_budget_micros }] : []],
393
+ execute: async () => {
394
+ const { data } = await entities.client.request("POST", base, z5.object({ data: campaignSchema }), params);
395
+ if (data.name !== input.name || data.funding_instrument_id !== funding.id || data.currency !== funding.currency || data.entity_status !== status || data.deleted || data.budget_optimization !== "LINE_ITEM" || data.daily_budget_amount_local_micro !== input.daily_budget_micros || data.total_budget_amount_local_micro !== (input.total_budget_micros ?? null)) {
396
+ throw new AdportError4("PROVIDER_ERROR", "x: created campaign response does not match the approved plan; inspect the account before retrying");
397
+ }
398
+ return [data.id];
399
+ }
400
+ };
401
+ }
402
+ if (op.kind === "update" && ["x_set_campaign_status", "x_set_budget"].includes(op.tool)) {
403
+ const input = op.tool === "x_set_budget" ? setBudgetSchema.parse(op.payload) : setStatusSchema.parse(op.payload);
404
+ const current = await entities.getCampaign(accountId, input.campaign_id);
405
+ if (current.deleted || current.entity_status === "DRAFT") throw new AdportError4("INVALID_INPUT", "x: deleted and draft campaigns cannot be changed by this tool");
406
+ let params;
407
+ const budgetDeltas = [];
408
+ if ("budget_micros" in input) {
409
+ const field = input.budget_type === "DAILY" ? "daily_budget_amount_local_micro" : "total_budget_amount_local_micro";
410
+ const from = current[field];
411
+ if (from === null) throw new AdportError4("INVALID_INPUT", "x: no existing budget of this type; this tool does not change budget semantics");
412
+ if (current.budget_optimization !== "LINE_ITEM") throw new AdportError4("INVALID_INPUT", "x: unsupported campaign budget optimization");
413
+ const daily = input.budget_type === "DAILY" ? input.budget_micros : current.daily_budget_amount_local_micro;
414
+ const total = input.budget_type === "TOTAL" ? input.budget_micros : current.total_budget_amount_local_micro;
415
+ if (daily !== null && total !== null && daily > total) throw new AdportError4("INVALID_INPUT", "x: daily budget cannot exceed total budget");
416
+ params = { [field]: input.budget_micros };
417
+ budgetDeltas.push({ target: `campaign ${current.id} ${input.budget_type.toLowerCase()} budget`, fromMicros: from, toMicros: input.budget_micros });
418
+ } else params = { entity_status: input.status };
419
+ return {
420
+ summary: `Update X campaign "${current.name}"`,
421
+ changes: Object.entries(params).map(([key, value]) => `~ ${key}: ${current[key]} \u2192 ${value}`),
422
+ coercions: [],
423
+ budgetDeltas,
424
+ execute: async () => {
425
+ const { data } = await entities.client.request("PUT", `${base}/${current.id}`, z5.object({ data: campaignSchema }), params);
426
+ const expected = { ...current, ...params };
427
+ for (const key of ["id", "funding_instrument_id", "currency", "entity_status", "deleted", "budget_optimization", "daily_budget_amount_local_micro", "total_budget_amount_local_micro"]) {
428
+ if (data[key] !== expected[key]) throw new AdportError4("PROVIDER_ERROR", "x: updated campaign response does not match the approved plan; inspect the account before retrying");
429
+ }
430
+ return [data.id];
431
+ }
432
+ };
433
+ }
434
+ throw new AdportError4("INVALID_INPUT", `x: unsupported write ${op.tool}`);
435
+ }
436
+
437
+ // src/provider.ts
438
+ var DERIVED = { ctr: ["clicks", "impressions", 100], cpc: ["spend", "clicks", 1], cpm: ["spend", "impressions", 1e3] };
439
+ var DAY = 864e5;
440
+ var XAdsProvider = class extends XAdsEntities {
441
+ id = "x";
442
+ analytics;
443
+ constructor(client, analytics) {
444
+ super(client);
445
+ this.analytics = analytics ?? new XAdsAnalytics(client);
446
+ }
447
+ capabilities() {
448
+ return { serverDryRun: false };
449
+ }
450
+ standardActions() {
451
+ return { pauseCampaign: (accountId, campaignId) => ({ tool: "x_set_campaign_status", input: { account_id: accountId, campaign_id: campaignId, status: "PAUSED" } }) };
452
+ }
453
+ async previewWrite(op, guard) {
454
+ const { execute: _execute, ...preview } = await planXWrite(this, op, guard);
455
+ return { ...preview, serverValidated: false };
456
+ }
457
+ async applyWrite(op, guard) {
458
+ return { applied: true, resourceIds: await (await planXWrite(this, op, guard)).execute() };
459
+ }
460
+ async report(query) {
461
+ const range = resolveDateRange(query.dateRange);
462
+ z6.iso.date().parse(range.start);
463
+ z6.iso.date().parse(range.end);
464
+ if (range.end < range.start) throw new AdportError5("INVALID_INPUT", "x: report end precedes start");
465
+ const needed = /* @__PURE__ */ new Set();
466
+ for (const metric of query.metrics) {
467
+ if (["spend", "impressions", "clicks"].includes(metric)) needed.add(metric);
468
+ else if (metric in DERIVED) for (const dep of DERIVED[metric].slice(0, 2)) needed.add(dep);
469
+ }
470
+ if (!needed.size) throw new AdportError5("INVALID_INPUT", "x: supported normalized metrics are spend, impressions, link clicks, ctr, cpc and cpm; conversion normalization is not yet verified");
471
+ const limit = query.limit ?? 1e3;
472
+ if (!Number.isSafeInteger(limit) || limit < 1) throw new AdportError5("INVALID_INPUT", "x: report limit must be a positive integer");
473
+ const groups = [...needed.has("spend") ? ["BILLING"] : [], ...needed.has("clicks") || needed.has("impressions") ? ["ENGAGEMENT"] : []];
474
+ const rows = [];
475
+ const accounts = [...new Set(query.accountIds ?? (await this.listAccounts()).map((a) => a.id))];
476
+ for (const accountId of accounts) {
477
+ const account = await this.getAccount(accountId);
478
+ const start = xAccountMidnight(range.start, account.timezone);
479
+ const endDate = new Date(Date.parse(`${range.end}T00:00:00Z`) + DAY).toISOString().slice(0, 10);
480
+ const end = xAccountMidnight(endDate, account.timezone);
481
+ if (account.timezone_switch_at && (!Number.isFinite(Date.parse(account.timezone_switch_at)) || start < Date.parse(account.timezone_switch_at))) throw new AdportError5("INVALID_INPUT", "x: requested dates predate the account timezone switch; its previous reporting timezone is unknown");
482
+ let entities = await this.reportEntities(accountId, query.level);
483
+ if (query.level === "account" && new Set(entities.map((e) => e.currency)).size > 1) throw new AdportError5("PROVIDER_ERROR", "x: cannot aggregate campaigns with different currencies into one account total");
484
+ const truncated = query.level !== "account" && entities.length > limit - rows.length;
485
+ if (query.level !== "account") entities = entities.slice(0, Math.max(0, limit - rows.length));
486
+ const totals = /* @__PURE__ */ new Map();
487
+ const entityKey = (entity) => `${entity.type}:${entity.id}`;
488
+ for (const type of new Set(entities.map((e) => e.type))) {
489
+ const typed = entities.filter((e) => e.type === type);
490
+ for (let offset = 0; offset < typed.length; offset += 20) {
491
+ const batch = typed.slice(offset, offset + 20);
492
+ const accumulated = new Map(batch.map((e) => [e.id, void 0]));
493
+ for (let from = start; from < end; ) {
494
+ const asynchronous = end - start > 7 * DAY || end < Date.now() - 7 * DAY || type === "MEDIA_CREATIVE";
495
+ const to = Math.min(end, from + (asynchronous ? 30 : 7) * DAY);
496
+ for (const placement of X_PLACEMENTS) {
497
+ const stats = await this.analytics.totals(accountId, { entity: type, entity_ids: batch.map((e) => e.id).join(","), start_time: new Date(from).toISOString(), end_time: new Date(to).toISOString(), granularity: "TOTAL", placement, metric_groups: groups.join(",") }, asynchronous);
498
+ for (const row of stats.data) {
499
+ const source = row.id_data[0].metrics, metrics = {};
500
+ for (const [key, field, divisor] of [["spend", "billed_charge_local_micro", 1e6], ["impressions", "impressions", 1], ["clicks", "url_clicks", 1]]) {
501
+ const value = source[field];
502
+ if (value !== void 0 && needed.has(key)) metrics[key] = (value?.[0] ?? 0) / divisor;
503
+ }
504
+ accumulated.set(row.id, add(accumulated.get(row.id), metrics));
505
+ }
506
+ }
507
+ from = to;
508
+ }
509
+ for (const entity of batch) totals.set(entityKey(entity), accumulated.get(entity.id) ?? {});
510
+ }
511
+ }
512
+ if (query.level === "account") {
513
+ if (entities.length) {
514
+ let total;
515
+ for (const entity of entities) total = add(total, totals.get(entityKey(entity)));
516
+ rows.push({ provider: this.id, accountId, entity: { level: "account", id: accountId, name: account.name, status: account.approval_status }, metrics: normalize(total ?? {}, query.metrics) });
517
+ }
518
+ } else for (const entity of entities) rows.push({ provider: this.id, accountId, entity: { level: query.level, id: query.level === "ad" ? entityKey(entity) : entity.id, name: entity.name, status: entity.status }, metrics: normalize(totals.get(entityKey(entity)), query.metrics) });
519
+ if (truncated) return { rows, truncated: true };
520
+ if (rows.length >= limit) {
521
+ return { rows, ...accounts.indexOf(accountId) < accounts.length - 1 ? { truncated: true } : {} };
522
+ }
523
+ }
524
+ return { rows };
525
+ }
526
+ async reportEntities(accountId, level) {
527
+ if (level === "account" || level === "campaign") return (await this.listCampaigns(accountId)).filter((c) => c.entity_status !== "DRAFT").map((c) => ({ id: c.id, name: c.name, currency: c.currency, status: c.entity_status, type: "CAMPAIGN" }));
528
+ const allLines = await this.listLineItems(accountId);
529
+ const lines = allLines.filter((l) => l.entity_status !== "DRAFT");
530
+ if (level === "ad_group") return lines.map((l) => ({ id: l.id, name: l.name, currency: l.currency, status: l.entity_status, type: "LINE_ITEM" }));
531
+ const lookup = new Map(allLines.map((l) => [l.id, l]));
532
+ const tweets = await this.listPromotedTweets(accountId), media = await this.listMediaCreatives(accountId);
533
+ const promoted = lines.some((l) => l.product_type === "PROMOTED_ACCOUNT") ? await this.listPromotedAccounts(accountId) : [];
534
+ return [
535
+ ...tweets.map((t) => ({ ...t, type: "PROMOTED_TWEET", name: `Promoted post ${t.tweet_id}` })),
536
+ ...media.map((t) => ({ ...t, type: "MEDIA_CREATIVE", name: `Media creative ${t.account_media_id}` })),
537
+ ...promoted.map((t) => ({ ...t, type: "PROMOTED_ACCOUNT", name: `Promoted account ${t.user_id}` }))
538
+ ].filter((t) => {
539
+ if (!lookup.has(t.line_item_id)) throw new AdportError5("PROVIDER_ERROR", "x: ad references an unknown line item");
540
+ return lookup.get(t.line_item_id).entity_status !== "DRAFT";
541
+ }).map((t) => {
542
+ const parent = lookup.get(t.line_item_id);
543
+ if (!parent) throw new AdportError5("PROVIDER_ERROR", "x: ad references an unknown or draft line item");
544
+ return { id: t.id, name: t.name, status: t.entity_status, currency: parent.currency, type: t.type };
545
+ });
546
+ }
547
+ };
548
+ function add(previous, next) {
549
+ if (!previous) return { ...next };
550
+ const sum = {};
551
+ for (const key of ["spend", "impressions", "clicks"]) if (previous[key] !== void 0 && next[key] !== void 0) {
552
+ const value = previous[key] + next[key];
553
+ if (!Number.isFinite(value) || value > Number.MAX_SAFE_INTEGER) throw new AdportError5("PROVIDER_ERROR", "x: report total exceeds safe numeric range");
554
+ sum[key] = value;
555
+ }
556
+ return sum;
557
+ }
558
+ function normalize(values, requested) {
559
+ const all = { ...values };
560
+ for (const [metric, [numerator, denominator, factor]] of Object.entries(DERIVED)) if (values[numerator] !== void 0 && values[denominator] !== void 0) all[metric] = values[denominator] ? values[numerator] / values[denominator] * factor : 0;
561
+ return Object.fromEntries(requested.filter((m) => all[m] !== void 0).map((m) => [m, all[m]]));
562
+ }
563
+
564
+ // src/tools.ts
565
+ import { z as z7 } from "zod";
566
+ import { defineTool, guardedWriteTool } from "@adport/core";
567
+ function xTools(provider) {
568
+ return [
569
+ defineTool({ name: "x_list_campaigns", namespace: "x", description: "List X Ads campaigns including inactive, deleted and draft campaigns.", input: z7.object({ account_id: xId }), annotations: { readOnly: true }, handler: (input) => provider.listCampaigns(input.account_id) }),
570
+ defineTool({ name: "x_list_funding_instruments", namespace: "x", description: "List existing funding instruments for campaign creation; does not create or change billing.", input: z7.object({ account_id: xId }), annotations: { readOnly: true }, handler: (input) => provider.listFundingInstruments(input.account_id) }),
571
+ defineTool({ name: "x_list_line_items", namespace: "x", description: "List X Ads line items (ad groups).", input: z7.object({ account_id: xId }), annotations: { readOnly: true }, handler: (input) => provider.listLineItems(input.account_id) }),
572
+ guardedWriteTool({ name: "x_create_campaign", namespace: "x", provider: "x", kind: "create", description: "Create a paused X Ads campaign with an existing funding instrument and account-currency budgets in integer micros. Preview is local.", payload: createCampaignSchema }),
573
+ guardedWriteTool({ name: "x_set_campaign_status", namespace: "x", provider: "x", kind: "update", description: "Pause or activate an existing X Ads campaign.", payload: setStatusSchema }),
574
+ guardedWriteTool({ name: "x_set_budget", namespace: "x", provider: "x", kind: "update", description: "Change an existing X Ads daily or total campaign budget in integer micros, preserving the other cap.", payload: setBudgetSchema })
575
+ ];
576
+ }
577
+
578
+ // src/oauth.ts
579
+ import { AdportError as AdportError6 } from "@adport/core";
580
+ var REQUEST_TOKEN_URL = "https://api.x.com/oauth/request_token";
581
+ var ACCESS_TOKEN_URL = "https://api.x.com/oauth/access_token";
582
+ var INVALIDATE_TOKEN_URL = "https://api.x.com/1.1/oauth/invalidate_token.json";
583
+ var LIMIT = 16 * 1024;
584
+ function validToken(value) {
585
+ return typeof value === "string" && value.length > 0 && value.length <= 4096 && !/[\s\x00-\x1f\x7f]/.test(value);
586
+ }
587
+ function requireValues(...values) {
588
+ if (!values.every(validToken)) throw new AdportError6("INVALID_INPUT", "x: OAuth credentials or verifier are missing or malformed");
589
+ }
590
+ function failure(message) {
591
+ return new AdportError6("PROVIDER_ERROR", `x: ${message}`);
592
+ }
593
+ async function textBody(response) {
594
+ const reader = response.body?.getReader();
595
+ if (!reader) throw failure("empty OAuth response");
596
+ const chunks = [];
597
+ let length = 0;
598
+ try {
599
+ while (true) {
600
+ const { value, done } = await reader.read();
601
+ if (done) break;
602
+ length += value.byteLength;
603
+ if (length > LIMIT) {
604
+ await reader.cancel();
605
+ throw failure("OAuth response exceeded size limit");
606
+ }
607
+ chunks.push(value);
608
+ }
609
+ return new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks));
610
+ } catch {
611
+ throw failure("invalid or oversized OAuth response");
612
+ } finally {
613
+ reader.releaseLock();
614
+ }
615
+ }
616
+ async function signedPost(app, url, parameters, token, fetchImpl) {
617
+ requireValues(app.consumerKey, app.consumerSecret);
618
+ const signer = createXSigner(app);
619
+ const authorization = signer.authorize({ method: "POST", url, data: parameters }, token);
620
+ let response;
621
+ try {
622
+ response = await fetchImpl(url, { method: "POST", headers: { ...signer.toHeader({ ...authorization, ...parameters }) }, redirect: "error", signal: AbortSignal.timeout(3e4) });
623
+ } catch {
624
+ throw failure("OAuth transport failed; restart authorization rather than replaying the exchange");
625
+ }
626
+ if (response.status !== 200) throw failure(`OAuth request failed (HTTP ${response.status})`);
627
+ return response;
628
+ }
629
+ async function tokens(response) {
630
+ const values = new URLSearchParams(await textBody(response));
631
+ for (const key of ["oauth_token", "oauth_token_secret"]) {
632
+ if (values.getAll(key).length !== 1 || !validToken(values.get(key))) throw failure("malformed OAuth token response");
633
+ }
634
+ return values;
635
+ }
636
+ async function requestXToken(app, callback, fetchImpl = fetch) {
637
+ let url;
638
+ try {
639
+ url = new URL(callback);
640
+ } catch {
641
+ throw new AdportError6("INVALID_INPUT", "x: an exact registered HTTPS callback is required");
642
+ }
643
+ if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash) throw new AdportError6("INVALID_INPUT", "x: an exact registered HTTPS callback without query or fragment is required");
644
+ const values = await tokens(await signedPost(app, REQUEST_TOKEN_URL, { oauth_callback: url.href }, void 0, fetchImpl));
645
+ if (values.getAll("oauth_callback_confirmed").length !== 1 || values.get("oauth_callback_confirmed") !== "true") throw failure("OAuth callback was not confirmed");
646
+ return { requestToken: values.get("oauth_token"), requestTokenSecret: values.get("oauth_token_secret") };
647
+ }
648
+ function buildXAuthorizationUrl(requestToken) {
649
+ requireValues(requestToken);
650
+ return `https://api.x.com/oauth/authorize?${new URLSearchParams({ oauth_token: requestToken })}`;
651
+ }
652
+ async function exchangeXToken(app, request, verifier, fetchImpl = fetch) {
653
+ requireValues(request.requestToken, request.requestTokenSecret, verifier);
654
+ const values = await tokens(await signedPost(app, ACCESS_TOKEN_URL, { oauth_verifier: verifier }, { key: request.requestToken, secret: request.requestTokenSecret }, fetchImpl));
655
+ return { accessToken: values.get("oauth_token"), accessTokenSecret: values.get("oauth_token_secret") };
656
+ }
657
+ async function revokeXToken(credentials, fetchImpl = fetch) {
658
+ requireValues(credentials.accessToken, credentials.accessTokenSecret);
659
+ const response = await signedPost(credentials, INVALIDATE_TOKEN_URL, {}, { key: credentials.accessToken, secret: credentials.accessTokenSecret }, fetchImpl);
660
+ let value;
661
+ try {
662
+ value = JSON.parse(await textBody(response));
663
+ } catch {
664
+ throw failure("invalid OAuth revocation response");
665
+ }
666
+ if (!value || typeof value !== "object" || !("access_token" in value) || value.access_token !== credentials.accessToken) throw failure("OAuth revocation was not confirmed for this token");
667
+ }
668
+
669
+ // src/index.ts
670
+ function xCredentialsFromData(data) {
671
+ if (!data?.consumer_key?.trim() || !data.consumer_secret?.trim() || !data.access_token?.trim() || !data.access_token_secret?.trim()) return void 0;
672
+ return { consumerKey: data.consumer_key, consumerSecret: data.consumer_secret, accessToken: data.access_token, accessTokenSecret: data.access_token_secret };
673
+ }
674
+ function xEnvironmentData() {
675
+ return { consumer_key: process.env.X_CONSUMER_KEY ?? "", consumer_secret: process.env.X_CONSUMER_SECRET ?? "", access_token: process.env.X_ACCESS_TOKEN ?? "", access_token_secret: process.env.X_ACCESS_TOKEN_SECRET ?? "" };
676
+ }
677
+ async function resolveXCredentials(store) {
678
+ return xCredentialsFromData((await store.get("x"))?.data) ?? xCredentialsFromData(xEnvironmentData());
679
+ }
680
+ async function createXModule(store) {
681
+ const credentials = await resolveXCredentials(store);
682
+ if (!credentials) return void 0;
683
+ const provider = new XAdsProvider(new XAdsClient(credentials));
684
+ return { provider, tools: xTools(provider) };
685
+ }
686
+ export {
687
+ XAdsAnalytics,
688
+ XAdsClient,
689
+ XAdsEntities,
690
+ XAdsProvider,
691
+ X_ADS_API_BASE,
692
+ buildXAuthorizationUrl,
693
+ createXModule,
694
+ exchangeXToken,
695
+ requestXToken,
696
+ resolveXCredentials,
697
+ revokeXToken,
698
+ xCredentialsFromData,
699
+ xEnvironmentData,
700
+ xTools
701
+ };
702
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client.ts","../src/entities.ts","../src/schemas.ts","../src/provider.ts","../src/analytics.ts","../src/writes.ts","../src/tools.ts","../src/oauth.ts","../src/index.ts"],"sourcesContent":["import { createHmac, randomBytes } from 'node:crypto';\nimport OAuth from 'oauth-1.0a';\nimport { z } from 'zod';\nimport { AdportError } from '@adport/core';\n\nexport const X_ADS_API_BASE = 'https://ads-api.x.com/12/';\nexport interface XAdsCredentials {\n consumerKey: string;\n consumerSecret: string;\n accessToken: string;\n accessTokenSecret: string;\n}\nexport type XParams = Record<string, string | number | boolean>;\nexport type XMethod = 'GET' | 'POST' | 'PUT';\n\nexport function createXSigner(credentials: Pick<XAdsCredentials, 'consumerKey' | 'consumerSecret'>): OAuth {\n const oauth = new OAuth({\n consumer: { key: credentials.consumerKey, secret: credentials.consumerSecret },\n signature_method: 'HMAC-SHA1',\n hash_function: (base, key) => createHmac('sha1', key).update(base).digest('base64'),\n });\n // The library's default nonce uses Math.random. Use cryptographic entropy.\n oauth.getNonce = () => randomBytes(24).toString('hex');\n return oauth;\n}\n\nexport class XAdsClient {\n private readonly signer: OAuth;\n private readonly token: OAuth.Token;\n constructor(credentials: XAdsCredentials, private readonly fetchImpl: typeof fetch = fetch) {\n if (Object.values(credentials).some(value => typeof value !== 'string' || !value.trim()) ||\n !credentials.consumerKey || !credentials.consumerSecret || !credentials.accessToken || !credentials.accessTokenSecret) {\n throw new AdportError('INVALID_INPUT', 'x: all four OAuth 1.0a credentials are required');\n }\n this.signer = createXSigner(credentials);\n this.token = { key: credentials.accessToken, secret: credentials.accessTokenSecret };\n }\n\n async request<T>(method: XMethod, path: string, schema: z.ZodType<T>, params: XParams = {}): Promise<T> {\n if (!/^[a-z0-9_]+(?:\\/[a-z0-9_]+)*$/.test(path)) throw new AdportError('INVALID_INPUT', 'x: invalid API resource path');\n const url = new URL(path, X_ADS_API_BASE);\n for (const [key, value] of Object.entries(params)) {\n if (!/^[a-z][a-z0-9_]*$/.test(key) || key.startsWith('oauth_') || (typeof value === 'number' && !Number.isFinite(value))) {\n throw new AdportError('INVALID_INPUT', 'x: invalid API parameter');\n }\n url.searchParams.set(key, String(value));\n }\n // oauth-1.0a decodes percent escapes but not form-style '+' spaces.\n // Serialize spaces as %20 so the signed values match X's query parser.\n url.search = url.search.replace(/\\+/g, '%20');\n // X's endpoint reference specifies query parameters for POST and PUT too.\n // Sign the final encoded URL, and send exactly that URL without a JSON body.\n const headers = this.signer.toHeader(this.signer.authorize({ url: url.href, method }, this.token));\n let response: Response;\n try {\n response = await this.fetchImpl(url.href, { method, headers: { ...headers, accept: 'application/json' }, redirect: 'error', signal: AbortSignal.timeout(30_000) });\n } catch {\n throw new AdportError('PROVIDER_ERROR', `x: transport failed${method === 'GET' ? '' : '; write outcome unknown, inspect the account before retrying'}`);\n }\n if (!response.ok) {\n const guidance = response.status === 403 ? 'Check Ads API app approval and this user’s ad-account permissions; reconnecting alone may not help.'\n : response.status === 401 ? 'Check OAuth 1.0a credentials, token permissions and the local clock. Regenerate user tokens after Ads API approval.'\n : response.status === 429 ? 'Rate limit reached; wait for the provider reset before retrying.' : 'Provider request failed.';\n throw new AdportError('PROVIDER_ERROR', `x: HTTP ${response.status}. ${guidance}${method === 'GET' ? '' : ' The write was not retried.'}`);\n }\n let body: unknown;\n try { body = await response.json(); } catch { throw new AdportError('PROVIDER_ERROR', 'x: invalid JSON response'); }\n if (body && typeof body === 'object' && 'errors' in body && Array.isArray(body.errors) && body.errors.length) {\n throw new AdportError('PROVIDER_ERROR', 'x: provider returned an error envelope');\n }\n const parsed = schema.safeParse(body);\n if (!parsed.success) throw new AdportError('PROVIDER_ERROR', 'x: unexpected API response schema');\n return parsed.data;\n }\n\n async list<T extends { id: string }>(path: string, item: z.ZodType<T>, params: XParams = {}): Promise<T[]> {\n const schema = z.object({ data: z.array(item), next_cursor: z.string().nullable().optional() });\n const rows: T[] = [], ids = new Set<string>(), cursors = new Set<string>();\n let cursor: string | undefined;\n while (true) {\n const page = await this.request('GET', path, schema, { ...params, count: 200, ...(cursor ? { cursor } : {}) });\n for (const row of page.data) {\n if (ids.has(row.id)) throw new AdportError('PROVIDER_ERROR', 'x: pagination repeated an entity');\n ids.add(row.id); rows.push(row);\n }\n if (!page.next_cursor) return rows;\n if (cursors.has(page.next_cursor) || cursors.size >= 1000) throw new AdportError('PROVIDER_ERROR', 'x: cursor pagination did not terminate');\n cursors.add(page.next_cursor); cursor = page.next_cursor;\n }\n }\n}\n","import { z } from 'zod';\nimport { AdportError, type Account } from '@adport/core';\nimport { XAdsClient } from './client.js';\nimport { accountSchema, campaignSchema, fundingSchema, lineItemSchema, mediaCreativeSchema, promotedAccountSchema, promotedTweetSchema, xId } from './schemas.js';\n\nexport class XAdsEntities {\n constructor(readonly client: XAdsClient) {}\n async listAccounts(): Promise<Account[]> {\n // X's account response has no currency. It belongs to funding instruments\n // and campaigns; never infer USD or invent account currency here.\n return (await this.client.list('accounts', accountSchema)).map(a => ({ provider: 'x', id: a.id, name: a.name, status: a.approval_status }));\n }\n async getAccount(accountId: string) {\n const { data } = await this.client.request('GET', `accounts/${xId.parse(accountId)}`, z.object({ data: accountSchema }));\n if (data.id !== accountId) throw new AdportError('PROVIDER_ERROR', 'x: account ID mismatch');\n return data;\n }\n listCampaigns(accountId: string) {\n return this.client.list(`accounts/${xId.parse(accountId)}/campaigns`, campaignSchema, { with_deleted: true, with_draft: true });\n }\n async getCampaign(accountId: string, campaignId: string) {\n const { data } = await this.client.request('GET', `accounts/${xId.parse(accountId)}/campaigns/${xId.parse(campaignId)}`, z.object({ data: campaignSchema }));\n if (data.id !== campaignId) throw new AdportError('PROVIDER_ERROR', 'x: campaign ID mismatch');\n return data;\n }\n async listFundingInstruments(accountId: string) {\n const data = await this.client.list(`accounts/${xId.parse(accountId)}/funding_instruments`, fundingSchema);\n if (data.some(f => f.account_id !== accountId)) throw new AdportError('PROVIDER_ERROR', 'x: funding instrument account mismatch');\n return data;\n }\n async getFundingInstrument(accountId: string, fundingId: string) {\n const { data } = await this.client.request('GET', `accounts/${xId.parse(accountId)}/funding_instruments/${xId.parse(fundingId)}`, z.object({ data: fundingSchema }));\n if (data.id !== fundingId || data.account_id !== accountId) throw new AdportError('PROVIDER_ERROR', 'x: funding instrument account/ID mismatch');\n return data;\n }\n listLineItems(accountId: string) {\n return this.client.list(`accounts/${xId.parse(accountId)}/line_items`, lineItemSchema, { with_deleted: true, with_draft: true });\n }\n listPromotedTweets(accountId: string) {\n return this.client.list(`accounts/${xId.parse(accountId)}/promoted_tweets`, promotedTweetSchema, { with_deleted: true });\n }\n listPromotedAccounts(accountId: string) {\n return this.client.list(`accounts/${xId.parse(accountId)}/promoted_accounts`, promotedAccountSchema, { with_deleted: true });\n }\n listMediaCreatives(accountId: string) {\n return this.client.list(`accounts/${xId.parse(accountId)}/media_creatives`, mediaCreativeSchema, { with_deleted: true });\n }\n}\n","import { z } from 'zod';\n\nexport const xId = z.string().regex(/^[a-z0-9]+$/).min(1).max(64);\nconst micros = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);\nconst currency = z.string().regex(/^[A-Z]{3}$/);\nexport const accountSchema = z.object({\n id: xId, name: z.string(), timezone: z.string(), timezone_switch_at: z.string().nullable().optional(),\n approval_status: z.string(), deleted: z.boolean(),\n});\nexport const fundingSchema = z.object({\n id: xId, account_id: xId, description: z.string(), currency, type: z.string(),\n entity_status: z.string(), able_to_fund: z.boolean(), deleted: z.boolean(),\n});\nexport const campaignSchema = z.object({\n id: xId, name: z.string(), currency, funding_instrument_id: xId, entity_status: z.string(), deleted: z.boolean(),\n budget_optimization: z.string(), daily_budget_amount_local_micro: micros.nullable(), total_budget_amount_local_micro: micros.nullable(),\n});\nexport const lineItemSchema = z.object({\n id: xId, name: z.string(), campaign_id: xId, currency, entity_status: z.string(), deleted: z.boolean(),\n placements: z.array(z.string()), product_type: z.string(), objective: z.string(),\n});\nexport const promotedTweetSchema = z.object({\n id: xId, line_item_id: xId, tweet_id: z.string().regex(/^\\d+$/), entity_status: z.string(), deleted: z.boolean(),\n});\nexport const promotedAccountSchema = z.object({ id: xId, line_item_id: xId, user_id: z.string().regex(/^\\d+$/), entity_status: z.string(), deleted: z.boolean() });\nexport const mediaCreativeSchema = z.object({ id: xId, line_item_id: xId, account_media_id: xId, entity_status: z.string(), deleted: z.boolean() });\nexport const createCampaignSchema = z.object({\n name: z.string().min(1).max(255), funding_instrument_id: xId,\n daily_budget_micros: micros.positive(), total_budget_micros: micros.positive().optional(),\n status: z.enum(['ACTIVE', 'PAUSED']).default('PAUSED'),\n});\nexport const setStatusSchema = z.object({ campaign_id: xId, status: z.enum(['ACTIVE', 'PAUSED']) });\nexport const setBudgetSchema = z.object({ campaign_id: xId, budget_type: z.enum(['DAILY', 'TOTAL']), budget_micros: micros.positive() });\n","import { z } from 'zod';\nimport { AdportError, resolveDateRange, type AdProvider, type MetricName, type NormalizedQuery, type Report, type ReportRow, type StandardActions, type WriteGuard, type WriteOperation, type WritePreview, type WriteResult } from '@adport/core';\nimport { XAdsClient } from './client.js';\nimport { XAdsEntities } from './entities.js';\nimport { XAdsAnalytics, X_PLACEMENTS, xAccountMidnight } from './analytics.js';\nimport { planXWrite } from './writes.js';\n\ntype BaseMetric = 'spend' | 'impressions' | 'clicks';\ntype Metrics = Partial<Record<BaseMetric, number>>;\ninterface Entity { id: string; name: string; status: string; currency: string; type: string }\nconst DERIVED = { ctr: ['clicks', 'impressions', 100], cpc: ['spend', 'clicks', 1], cpm: ['spend', 'impressions', 1000] } as const;\nconst DAY = 86_400_000;\n\nexport class XAdsProvider extends XAdsEntities implements AdProvider {\n readonly id = 'x';\n private readonly analytics: XAdsAnalytics;\n constructor(client: XAdsClient, analytics?: XAdsAnalytics) { super(client); this.analytics = analytics ?? new XAdsAnalytics(client); }\n capabilities() { return { serverDryRun: false }; }\n standardActions(): StandardActions { return { pauseCampaign: (accountId, campaignId) => ({ tool: 'x_set_campaign_status', input: { account_id: accountId, campaign_id: campaignId, status: 'PAUSED' } }) }; }\n async previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview> {\n const { execute: _execute, ...preview } = await planXWrite(this, op, guard); return { ...preview, serverValidated: false };\n }\n async applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult> {\n return { applied: true, resourceIds: await (await planXWrite(this, op, guard)).execute() };\n }\n async report(query: NormalizedQuery): Promise<Report> {\n const range = resolveDateRange(query.dateRange);\n z.iso.date().parse(range.start); z.iso.date().parse(range.end);\n if (range.end < range.start) throw new AdportError('INVALID_INPUT', 'x: report end precedes start');\n const needed = new Set<BaseMetric>();\n for (const metric of query.metrics) {\n if (['spend', 'impressions', 'clicks'].includes(metric)) needed.add(metric as BaseMetric);\n else if (metric in DERIVED) for (const dep of DERIVED[metric as keyof typeof DERIVED].slice(0, 2)) needed.add(dep as BaseMetric);\n }\n if (!needed.size) throw new AdportError('INVALID_INPUT', 'x: supported normalized metrics are spend, impressions, link clicks, ctr, cpc and cpm; conversion normalization is not yet verified');\n const limit = query.limit ?? 1000;\n if (!Number.isSafeInteger(limit) || limit < 1) throw new AdportError('INVALID_INPUT', 'x: report limit must be a positive integer');\n const groups = [...(needed.has('spend') ? ['BILLING'] : []), ...(needed.has('clicks') || needed.has('impressions') ? ['ENGAGEMENT'] : [])];\n const rows: ReportRow[] = [];\n const accounts = [...new Set(query.accountIds ?? (await this.listAccounts()).map(a => a.id))];\n for (const accountId of accounts) {\n const account = await this.getAccount(accountId);\n const start = xAccountMidnight(range.start, account.timezone);\n const endDate = new Date(Date.parse(`${range.end}T00:00:00Z`) + DAY).toISOString().slice(0, 10);\n const end = xAccountMidnight(endDate, account.timezone);\n if (account.timezone_switch_at && (!Number.isFinite(Date.parse(account.timezone_switch_at)) || start < Date.parse(account.timezone_switch_at))) throw new AdportError('INVALID_INPUT', 'x: requested dates predate the account timezone switch; its previous reporting timezone is unknown');\n let entities = await this.reportEntities(accountId, query.level);\n if (query.level === 'account' && new Set(entities.map(e => e.currency)).size > 1) throw new AdportError('PROVIDER_ERROR', 'x: cannot aggregate campaigns with different currencies into one account total');\n const truncated = query.level !== 'account' && entities.length > limit - rows.length;\n if (query.level !== 'account') entities = entities.slice(0, Math.max(0, limit - rows.length));\n const totals = new Map<string, Metrics>();\n const entityKey = (entity: Entity) => `${entity.type}:${entity.id}`;\n for (const type of new Set(entities.map(e => e.type))) {\n const typed = entities.filter(e => e.type === type);\n for (let offset = 0; offset < typed.length; offset += 20) {\n const batch = typed.slice(offset, offset + 20);\n const accumulated = new Map(batch.map(e => [e.id, undefined as Metrics | undefined]));\n for (let from = start; from < end;) {\n const asynchronous = end - start > 7 * DAY || end < Date.now() - 7 * DAY || type === 'MEDIA_CREATIVE';\n const to = Math.min(end, from + (asynchronous ? 30 : 7) * DAY);\n for (const placement of X_PLACEMENTS) {\n const stats = await this.analytics.totals(accountId, { entity: type, entity_ids: batch.map(e => e.id).join(','), start_time: new Date(from).toISOString(), end_time: new Date(to).toISOString(), granularity: 'TOTAL', placement, metric_groups: groups.join(',') }, asynchronous);\n for (const row of stats.data) {\n const source = row.id_data[0]!.metrics, metrics: Metrics = {};\n for (const [key, field, divisor] of [['spend', 'billed_charge_local_micro', 1_000_000], ['impressions', 'impressions', 1], ['clicks', 'url_clicks', 1]] as const) {\n const value = source[field];\n if (value !== undefined && needed.has(key)) metrics[key] = (value?.[0] ?? 0) / divisor;\n }\n accumulated.set(row.id, add(accumulated.get(row.id), metrics));\n }\n }\n from = to;\n }\n for (const entity of batch) totals.set(entityKey(entity), accumulated.get(entity.id) ?? {});\n }\n }\n if (query.level === 'account') {\n if (entities.length) {\n let total: Metrics | undefined;\n for (const entity of entities) total = add(total, totals.get(entityKey(entity))!);\n rows.push({ provider: this.id, accountId, entity: { level: 'account', id: accountId, name: account.name, status: account.approval_status }, metrics: normalize(total ?? {}, query.metrics) });\n }\n } else for (const entity of entities) rows.push({ provider: this.id, accountId, entity: { level: query.level, id: query.level === 'ad' ? entityKey(entity) : entity.id, name: entity.name, status: entity.status }, metrics: normalize(totals.get(entityKey(entity))!, query.metrics) });\n if (truncated) return { rows, truncated: true };\n if (rows.length >= limit) {\n return { rows, ...(accounts.indexOf(accountId) < accounts.length - 1 ? { truncated: true } : {}) };\n }\n }\n return { rows };\n }\n private async reportEntities(accountId: string, level: NormalizedQuery['level']): Promise<Entity[]> {\n if (level === 'account' || level === 'campaign') return (await this.listCampaigns(accountId)).filter(c => c.entity_status !== 'DRAFT').map(c => ({ id: c.id, name: c.name, currency: c.currency, status: c.entity_status, type: 'CAMPAIGN' }));\n const allLines = await this.listLineItems(accountId);\n const lines = allLines.filter(l => l.entity_status !== 'DRAFT');\n if (level === 'ad_group') return lines.map(l => ({ id: l.id, name: l.name, currency: l.currency, status: l.entity_status, type: 'LINE_ITEM' }));\n const lookup = new Map(allLines.map(l => [l.id, l]));\n const tweets = await this.listPromotedTweets(accountId), media = await this.listMediaCreatives(accountId);\n const promoted = lines.some(l => l.product_type === 'PROMOTED_ACCOUNT') ? await this.listPromotedAccounts(accountId) : [];\n return [\n ...tweets.map(t => ({ ...t, type: 'PROMOTED_TWEET', name: `Promoted post ${t.tweet_id}` })),\n ...media.map(t => ({ ...t, type: 'MEDIA_CREATIVE', name: `Media creative ${t.account_media_id}` })),\n ...promoted.map(t => ({ ...t, type: 'PROMOTED_ACCOUNT', name: `Promoted account ${t.user_id}` })),\n ].filter(t => {\n if (!lookup.has(t.line_item_id)) throw new AdportError('PROVIDER_ERROR', 'x: ad references an unknown line item');\n return lookup.get(t.line_item_id)!.entity_status !== 'DRAFT';\n }).map(t => {\n const parent = lookup.get(t.line_item_id);\n if (!parent) throw new AdportError('PROVIDER_ERROR', 'x: ad references an unknown or draft line item');\n return { id: t.id, name: t.name, status: t.entity_status, currency: parent.currency, type: t.type };\n });\n }\n}\nfunction add(previous: Metrics | undefined, next: Metrics): Metrics {\n if (!previous) return { ...next };\n const sum: Metrics = {};\n for (const key of ['spend', 'impressions', 'clicks'] as const) if (previous[key] !== undefined && next[key] !== undefined) {\n const value = previous[key]! + next[key]!;\n if (!Number.isFinite(value) || value > Number.MAX_SAFE_INTEGER) throw new AdportError('PROVIDER_ERROR', 'x: report total exceeds safe numeric range');\n sum[key] = value;\n }\n return sum;\n}\nfunction normalize(values: Metrics, requested: MetricName[]) {\n const all: Partial<Record<MetricName, number>> = { ...values };\n for (const [metric, [numerator, denominator, factor]] of Object.entries(DERIVED)) if (values[numerator] !== undefined && values[denominator] !== undefined) all[metric as MetricName] = values[denominator] ? values[numerator]! / values[denominator]! * factor : 0;\n return Object.fromEntries(requested.filter(m => all[m] !== undefined).map(m => [m, all[m]]));\n}\n","import { gunzipSync } from 'node:zlib';\nimport { setTimeout as delay } from 'node:timers/promises';\nimport { z } from 'zod';\nimport { AdportError } from '@adport/core';\nimport { XAdsClient, type XParams } from './client.js';\nimport { xId } from './schemas.js';\n\nexport const X_PLACEMENTS = ['ALL_ON_TWITTER', 'SPOTLIGHT', 'TREND'] as const;\nconst scalar = z.array(z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).nullable()).length(1).nullable().optional();\nexport const statsSchema = z.object({\n data_type: z.literal('stats'), time_series_length: z.literal(1),\n data: z.array(z.object({ id: xId, id_data: z.array(z.object({ segment: z.null(), metrics: z.object({\n billed_charge_local_micro: scalar, impressions: scalar, url_clicks: scalar,\n }) })).length(1) })),\n request: z.object({ params: z.object({\n start_time: z.string(), end_time: z.string(), entity: z.string(), entity_ids: z.array(xId),\n placement: z.string(), granularity: z.literal('TOTAL'), metric_groups: z.array(z.string()),\n }) }),\n});\ntype Stats = z.infer<typeof statsSchema>;\nconst jobSchema = z.object({\n id_str: z.string().regex(/^\\d+$/), account_id: xId, status: z.enum(['PROCESSING', 'SUCCESS', 'FAILED']), url: z.string().nullable(),\n start_time: z.string(), end_time: z.string(), entity: z.string(), entity_ids: z.array(xId), placement: z.string(),\n granularity: z.literal('TOTAL'), metric_groups: z.array(z.string()),\n});\ntype Job = z.infer<typeof jobSchema>;\nconst MAX_FILE_BYTES = 20 * 1024 * 1024;\n\n/** Report jobs are read computations, not advertising mutations. */\nexport class XAdsAnalytics {\n private readonly jobs = new Map<string, Job>();\n private readonly inflight = new Map<string, Promise<Stats>>();\n constructor(private readonly client: XAdsClient, private readonly fetchImpl: typeof fetch = fetch, private readonly pause: (ms: number) => Promise<unknown> = delay) {}\n\n async totals(accountId: string, params: XParams, asynchronous: boolean): Promise<Stats> {\n const key = JSON.stringify([accountId, Object.entries(params).sort(), asynchronous]);\n const active = this.inflight.get(key);\n if (active) return active;\n const promise = this.load(accountId, params, asynchronous, key);\n this.inflight.set(key, promise);\n try { return await promise; } finally { this.inflight.delete(key); }\n }\n private async load(accountId: string, params: XParams, asynchronous: boolean, key: string): Promise<Stats> {\n xId.parse(accountId);\n if (!asynchronous) return validateStats(await this.client.request('GET', `stats/accounts/${accountId}`, statsSchema, params), params);\n const path = `stats/jobs/accounts/${accountId}`;\n let job: Job = this.jobs.get(key) ?? (await this.client.request('POST', path, z.object({ data: jobSchema }), params)).data;\n validateJob(job, accountId, params);\n this.jobs.set(key, job);\n for (let attempt = 0; attempt <= 15; attempt++) {\n if (job.status === 'FAILED') {\n this.jobs.delete(key);\n throw new AdportError('PROVIDER_ERROR', `x: analytics job ${job.id_str} failed`);\n }\n if (job.status === 'SUCCESS') {\n if (!job.url) throw new AdportError('PROVIDER_ERROR', 'x: successful analytics job has no download URL');\n const result = validateStats(await this.download(job.url, job.id_str), params);\n this.jobs.delete(key);\n return result;\n }\n if (attempt === 15) break;\n await this.pause(1000);\n const id = job.id_str;\n const response: { data: Job[] } = await this.client.request('GET', path, z.object({ data: z.array(jobSchema) }), { job_ids: id });\n const match = response.data.filter(row => row.id_str === id);\n if (match.length !== 1 || response.data.length !== 1) throw new AdportError('PROVIDER_ERROR', 'x: analytics polling returned a different or duplicate job');\n job = match[0]!; validateJob(job, accountId, params); this.jobs.set(key, job);\n }\n // Keep the handle: the next identical request on this client resumes it.\n throw new AdportError('PROVIDER_ERROR', `x: analytics job ${job.id_str} is still processing; retry this report to resume polling`);\n }\n private async download(raw: string, id: string): Promise<Stats> {\n let url: URL;\n try { url = new URL(raw); } catch { throw new AdportError('PROVIDER_ERROR', 'x: invalid analytics download URL'); }\n if (url.origin !== 'https://ton.twimg.com' || url.username || url.password || url.hash || url.pathname !== `/advertiser-api-async-analytics/stats_job_${id}.json.gz`) {\n throw new AdportError('PROVIDER_ERROR', 'x: untrusted analytics download URL');\n }\n let response: Response;\n try { response = await this.fetchImpl(url.href, { redirect: 'error', signal: AbortSignal.timeout(30_000) }); }\n catch { throw new AdportError('PROVIDER_ERROR', 'x: analytics download transport failed'); }\n if (!response.ok || !response.body) throw new AdportError('PROVIDER_ERROR', 'x: analytics download failed');\n const reader = response.body.getReader(), chunks: Uint8Array[] = []; let size = 0;\n try {\n while (true) {\n const { done, value } = await reader.read(); if (done) break;\n size += value.byteLength;\n if (size > MAX_FILE_BYTES) { await reader.cancel(); throw new Error('size'); }\n chunks.push(value);\n }\n const compressed = Buffer.concat(chunks);\n // fetch may already decompress HTTP Content-Encoding, unlike a raw .gz file.\n const bytes = compressed[0] === 0x1f && compressed[1] === 0x8b ? gunzipSync(compressed, { maxOutputLength: MAX_FILE_BYTES }) : compressed;\n const parsed = statsSchema.safeParse(JSON.parse(bytes.toString('utf8')));\n if (!parsed.success) throw new Error('schema');\n return parsed.data;\n } catch { throw new AdportError('PROVIDER_ERROR', 'x: invalid or oversized analytics download'); }\n finally { reader.releaseLock(); }\n }\n}\nfunction matches(data: Stats['request']['params'], params: XParams): boolean {\n return Date.parse(data.start_time) === Date.parse(String(params.start_time)) && Date.parse(data.end_time) === Date.parse(String(params.end_time)) &&\n data.entity === params.entity && data.placement === params.placement && data.granularity === params.granularity &&\n [...data.entity_ids].sort().join(',') === String(params.entity_ids).split(',').sort().join(',') &&\n [...data.metric_groups].sort().join(',') === String(params.metric_groups).split(',').sort().join(',');\n}\nfunction validateJob(job: Job, accountId: string, params: XParams) {\n if (job.account_id !== accountId || !matches(job, params)) throw new AdportError('PROVIDER_ERROR', 'x: analytics job scope does not match the report');\n}\nfunction validateStats(data: Stats, params: XParams): Stats {\n const ids = String(params.entity_ids).split(','), returned = data.data.map(row => row.id);\n if (!matches(data.request.params, params) || new Set(returned).size !== returned.length || returned.some(id => !ids.includes(id)) || ids.some(id => !returned.includes(id))) {\n throw new AdportError('PROVIDER_ERROR', 'x: analytics returned incomplete, duplicate or incorrectly scoped data');\n }\n return data;\n}\n\nexport function xAccountMidnight(date: string, timezone: string): number {\n z.iso.date().parse(date);\n const target = Date.parse(`${date}T00:00:00Z`);\n let format: Intl.DateTimeFormat;\n try { 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 catch { throw new AdportError('PROVIDER_ERROR', 'x: invalid account timezone'); }\n let value = target;\n for (let i = 0; i < 5; 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) {\n if (value % 3_600_000 !== 0) throw new AdportError('INVALID_INPUT', 'x: account-local midnight is not a whole UTC hour; the API cannot represent this exact date boundary');\n return value;\n }\n value += target - rendered;\n }\n throw new AdportError('INVALID_INPUT', 'x: no midnight exists for this account-local report date');\n}\n","import { z } from 'zod';\nimport { AdportError, type WriteGuard, type WriteOperation, type WritePreview } from '@adport/core';\nimport type { XParams } from './client.js';\nimport { XAdsEntities } from './entities.js';\nimport { campaignSchema, createCampaignSchema, setBudgetSchema, setStatusSchema, xId } from './schemas.js';\n\nexport interface XWritePlan extends Omit<WritePreview, 'serverValidated'> { execute: () => Promise<string[]> }\n\n/** Called by the provider on both policy preview and exact approved apply. */\nexport async function planXWrite(entities: XAdsEntities, op: WriteOperation, guard: WriteGuard): Promise<XWritePlan> {\n if (op.provider !== 'x') throw new AdportError('INVALID_INPUT', 'x: provider mismatch');\n const accountId = xId.parse(op.accountId), base = `accounts/${accountId}/campaigns`;\n if (op.kind === 'create' && op.tool === 'x_create_campaign') {\n const input = createCampaignSchema.parse(op.payload);\n if (input.total_budget_micros !== undefined && input.daily_budget_micros > input.total_budget_micros) throw new AdportError('INVALID_INPUT', 'x: daily budget cannot exceed total budget');\n const funding = await entities.getFundingInstrument(accountId, input.funding_instrument_id);\n if (funding.deleted || !funding.able_to_fund || funding.entity_status !== 'ACTIVE') throw new AdportError('INVALID_INPUT', 'x: selected funding instrument cannot fund a campaign');\n const status = guard.forcePausedCreation ? 'PAUSED' : input.status;\n const params: XParams = { name: input.name, funding_instrument_id: funding.id, budget_optimization: 'LINE_ITEM', entity_status: status, daily_budget_amount_local_micro: input.daily_budget_micros,\n ...(input.total_budget_micros !== undefined ? { total_budget_amount_local_micro: input.total_budget_micros } : {}) };\n return {\n summary: `Create X campaign \"${input.name}\"`, changes: [`+ ${JSON.stringify(params)} (${funding.currency})`, 'Campaign only; serving also requires line items, targeting and creatives.'],\n coercions: status !== input.status ? ['status coerced to PAUSED by policy (paused_creation)'] : [],\n budgetDeltas: [{ target: 'new campaign daily budget', toMicros: input.daily_budget_micros }, ...(input.total_budget_micros !== undefined ? [{ target: 'new campaign total budget', toMicros: input.total_budget_micros }] : [])],\n execute: async () => {\n const { data } = await entities.client.request('POST', base, z.object({ data: campaignSchema }), params);\n if (data.name !== input.name || data.funding_instrument_id !== funding.id || data.currency !== funding.currency || data.entity_status !== status || data.deleted || data.budget_optimization !== 'LINE_ITEM' || data.daily_budget_amount_local_micro !== input.daily_budget_micros || data.total_budget_amount_local_micro !== (input.total_budget_micros ?? null)) {\n throw new AdportError('PROVIDER_ERROR', 'x: created campaign response does not match the approved plan; inspect the account before retrying');\n }\n return [data.id];\n },\n };\n }\n if (op.kind === 'update' && ['x_set_campaign_status', 'x_set_budget'].includes(op.tool)) {\n const input = op.tool === 'x_set_budget' ? setBudgetSchema.parse(op.payload) : setStatusSchema.parse(op.payload);\n const current = await entities.getCampaign(accountId, input.campaign_id);\n if (current.deleted || current.entity_status === 'DRAFT') throw new AdportError('INVALID_INPUT', 'x: deleted and draft campaigns cannot be changed by this tool');\n let params: XParams;\n const budgetDeltas: XWritePlan['budgetDeltas'] = [];\n if ('budget_micros' in input) {\n const field = input.budget_type === 'DAILY' ? 'daily_budget_amount_local_micro' : 'total_budget_amount_local_micro';\n const from = current[field];\n if (from === null) throw new AdportError('INVALID_INPUT', 'x: no existing budget of this type; this tool does not change budget semantics');\n if (current.budget_optimization !== 'LINE_ITEM') throw new AdportError('INVALID_INPUT', 'x: unsupported campaign budget optimization');\n const daily = input.budget_type === 'DAILY' ? input.budget_micros : current.daily_budget_amount_local_micro;\n const total = input.budget_type === 'TOTAL' ? input.budget_micros : current.total_budget_amount_local_micro;\n if (daily !== null && total !== null && daily > total) throw new AdportError('INVALID_INPUT', 'x: daily budget cannot exceed total budget');\n params = { [field]: input.budget_micros };\n budgetDeltas.push({ target: `campaign ${current.id} ${input.budget_type.toLowerCase()} budget`, fromMicros: from, toMicros: input.budget_micros });\n } else params = { entity_status: input.status };\n return {\n summary: `Update X campaign \"${current.name}\"`, changes: Object.entries(params).map(([key, value]) => `~ ${key}: ${current[key as keyof typeof current]} → ${value}`), coercions: [], budgetDeltas,\n execute: async () => {\n const { data } = await entities.client.request('PUT', `${base}/${current.id}`, z.object({ data: campaignSchema }), params);\n const expected = { ...current, ...params };\n for (const key of ['id', 'funding_instrument_id', 'currency', 'entity_status', 'deleted', 'budget_optimization', 'daily_budget_amount_local_micro', 'total_budget_amount_local_micro'] as const) {\n if (data[key] !== expected[key]) throw new AdportError('PROVIDER_ERROR', 'x: updated campaign response does not match the approved plan; inspect the account before retrying');\n }\n return [data.id];\n },\n };\n }\n throw new AdportError('INVALID_INPUT', `x: unsupported write ${op.tool}`);\n}\n","import { z } from 'zod';\nimport { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport type { XAdsProvider } from './provider.js';\nimport { createCampaignSchema, setBudgetSchema, setStatusSchema, xId } from './schemas.js';\n\nexport function xTools(provider: XAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'x_list_campaigns', namespace: 'x', description: 'List X Ads campaigns including inactive, deleted and draft campaigns.', input: z.object({ account_id: xId }), annotations: { readOnly: true }, handler: input => provider.listCampaigns(input.account_id) }),\n defineTool({ name: 'x_list_funding_instruments', namespace: 'x', description: 'List existing funding instruments for campaign creation; does not create or change billing.', input: z.object({ account_id: xId }), annotations: { readOnly: true }, handler: input => provider.listFundingInstruments(input.account_id) }),\n defineTool({ name: 'x_list_line_items', namespace: 'x', description: 'List X Ads line items (ad groups).', input: z.object({ account_id: xId }), annotations: { readOnly: true }, handler: input => provider.listLineItems(input.account_id) }),\n guardedWriteTool({ name: 'x_create_campaign', namespace: 'x', provider: 'x', kind: 'create', description: 'Create a paused X Ads campaign with an existing funding instrument and account-currency budgets in integer micros. Preview is local.', payload: createCampaignSchema }),\n guardedWriteTool({ name: 'x_set_campaign_status', namespace: 'x', provider: 'x', kind: 'update', description: 'Pause or activate an existing X Ads campaign.', payload: setStatusSchema }),\n guardedWriteTool({ name: 'x_set_budget', namespace: 'x', provider: 'x', kind: 'update', description: 'Change an existing X Ads daily or total campaign budget in integer micros, preserving the other cap.', payload: setBudgetSchema }),\n ];\n}\n","import { AdportError } from '@adport/core';\nimport { createXSigner, type XAdsCredentials } from './client.js';\n\ntype App = Pick<XAdsCredentials, 'consumerKey' | 'consumerSecret'>;\nexport interface XUserTokens { accessToken: string; accessTokenSecret: string }\nexport interface XRequestTokens { requestToken: string; requestTokenSecret: string }\nconst REQUEST_TOKEN_URL = 'https://api.x.com/oauth/request_token';\nconst ACCESS_TOKEN_URL = 'https://api.x.com/oauth/access_token';\nconst INVALIDATE_TOKEN_URL = 'https://api.x.com/1.1/oauth/invalidate_token.json';\nconst LIMIT = 16 * 1024;\n\nfunction validToken(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0 && value.length <= 4096 && !/[\\s\\x00-\\x1f\\x7f]/.test(value);\n}\nfunction requireValues(...values: unknown[]): void {\n if (!values.every(validToken)) throw new AdportError('INVALID_INPUT', 'x: OAuth credentials or verifier are missing or malformed');\n}\nfunction failure(message: string): AdportError { return new AdportError('PROVIDER_ERROR', `x: ${message}`); }\n\nasync function textBody(response: Response): Promise<string> {\n const reader = response.body?.getReader();\n if (!reader) throw failure('empty OAuth response');\n const chunks: Uint8Array[] = []; let length = 0;\n try {\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n length += value.byteLength;\n if (length > LIMIT) { await reader.cancel(); throw failure('OAuth response exceeded size limit'); }\n chunks.push(value);\n }\n return new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks));\n } catch { throw failure('invalid or oversized OAuth response'); }\n finally { reader.releaseLock(); }\n}\n\nasync function signedPost(app: App, url: string, parameters: Record<string, string>, token: { key: string; secret: string } | undefined, fetchImpl: typeof fetch): Promise<Response> {\n requireValues(app.consumerKey, app.consumerSecret);\n const signer = createXSigner(app);\n // OAuth-specific parameters belong in the Authorization header. Include\n // them in the signature once, and send no query string or request body.\n const authorization = signer.authorize({ method: 'POST', url, data: parameters }, token);\n let response: Response;\n try {\n response = await fetchImpl(url, { method: 'POST', headers: { ...signer.toHeader({ ...authorization, ...parameters }) }, redirect: 'error', signal: AbortSignal.timeout(30_000) });\n } catch { throw failure('OAuth transport failed; restart authorization rather than replaying the exchange'); }\n if (response.status !== 200) throw failure(`OAuth request failed (HTTP ${response.status})`);\n return response;\n}\n\nasync function tokens(response: Response): Promise<URLSearchParams> {\n // The official examples return form-encoded tokens, not JSON, despite the\n // generic endpoint metadata saying JSON. Reject duplicate token fields.\n const values = new URLSearchParams(await textBody(response));\n for (const key of ['oauth_token', 'oauth_token_secret']) {\n if (values.getAll(key).length !== 1 || !validToken(values.get(key))) throw failure('malformed OAuth token response');\n }\n return values;\n}\n\nexport async function requestXToken(app: App, callback: string, fetchImpl: typeof fetch = fetch): Promise<XRequestTokens> {\n let url: URL;\n try { url = new URL(callback); } catch { throw new AdportError('INVALID_INPUT', 'x: an exact registered HTTPS callback is required'); }\n if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash) throw new AdportError('INVALID_INPUT', 'x: an exact registered HTTPS callback without query or fragment is required');\n const values = await tokens(await signedPost(app, REQUEST_TOKEN_URL, { oauth_callback: url.href }, undefined, fetchImpl));\n if (values.getAll('oauth_callback_confirmed').length !== 1 || values.get('oauth_callback_confirmed') !== 'true') throw failure('OAuth callback was not confirmed');\n return { requestToken: values.get('oauth_token')!, requestTokenSecret: values.get('oauth_token_secret')! };\n}\n\nexport function buildXAuthorizationUrl(requestToken: string): string {\n requireValues(requestToken);\n return `https://api.x.com/oauth/authorize?${new URLSearchParams({ oauth_token: requestToken })}`;\n}\n\nexport async function exchangeXToken(app: App, request: XRequestTokens, verifier: string, fetchImpl: typeof fetch = fetch): Promise<XUserTokens> {\n requireValues(request.requestToken, request.requestTokenSecret, verifier);\n const values = await tokens(await signedPost(app, ACCESS_TOKEN_URL, { oauth_verifier: verifier }, { key: request.requestToken, secret: request.requestTokenSecret }, fetchImpl));\n return { accessToken: values.get('oauth_token')!, accessTokenSecret: values.get('oauth_token_secret')! };\n}\n\nexport async function revokeXToken(credentials: XAdsCredentials, fetchImpl: typeof fetch = fetch): Promise<void> {\n requireValues(credentials.accessToken, credentials.accessTokenSecret);\n const response = await signedPost(credentials, INVALIDATE_TOKEN_URL, {}, { key: credentials.accessToken, secret: credentials.accessTokenSecret }, fetchImpl);\n let value: unknown;\n try { value = JSON.parse(await textBody(response)); } catch { throw failure('invalid OAuth revocation response'); }\n if (!value || typeof value !== 'object' || !('access_token' in value) || value.access_token !== credentials.accessToken) throw failure('OAuth revocation was not confirmed for this token');\n}\n","export { XAdsClient, X_ADS_API_BASE, type XAdsCredentials, type XParams } from './client.js';\nexport { XAdsEntities } from './entities.js';\nexport { XAdsProvider } from './provider.js';\nexport { XAdsAnalytics } from './analytics.js';\nexport { xTools } from './tools.js';\nexport { requestXToken, buildXAuthorizationUrl, exchangeXToken, revokeXToken, type XRequestTokens, type XUserTokens } from './oauth.js';\n\nimport { type CredentialStore, type ProviderModule } from '@adport/core';\nimport { XAdsClient, type XAdsCredentials } from './client.js';\nimport { XAdsProvider } from './provider.js';\nimport { xTools } from './tools.js';\n\nexport function xCredentialsFromData(data: Record<string, string> | undefined): XAdsCredentials | undefined {\n if (!data?.consumer_key?.trim() || !data.consumer_secret?.trim() || !data.access_token?.trim() || !data.access_token_secret?.trim()) return undefined;\n return { consumerKey: data.consumer_key, consumerSecret: data.consumer_secret, accessToken: data.access_token, accessTokenSecret: data.access_token_secret };\n}\nexport function xEnvironmentData(): Record<string, string> {\n return { consumer_key: process.env.X_CONSUMER_KEY ?? '', consumer_secret: process.env.X_CONSUMER_SECRET ?? '', access_token: process.env.X_ACCESS_TOKEN ?? '', access_token_secret: process.env.X_ACCESS_TOKEN_SECRET ?? '' };\n}\nexport async function resolveXCredentials(store: CredentialStore): Promise<XAdsCredentials | undefined> {\n return xCredentialsFromData((await store.get('x'))?.data) ?? xCredentialsFromData(xEnvironmentData());\n}\nexport async function createXModule(store: CredentialStore): Promise<ProviderModule | undefined> {\n const credentials = await resolveXCredentials(store);\n if (!credentials) return undefined;\n const provider = new XAdsProvider(new XAdsClient(credentials));\n return { provider, tools: xTools(provider) };\n}\n"],"mappings":";AAAA,SAAS,YAAY,mBAAmB;AACxC,OAAO,WAAW;AAClB,SAAS,SAAS;AAClB,SAAS,mBAAmB;AAErB,IAAM,iBAAiB;AAUvB,SAAS,cAAc,aAA6E;AACzG,QAAM,QAAQ,IAAI,MAAM;AAAA,IACtB,UAAU,EAAE,KAAK,YAAY,aAAa,QAAQ,YAAY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B,CAAC,GAAG,EAAE,KAAK,YAAY,aAAa,QAAQ,YAAY,kBAAkB,GAAG,SAAS;AAC3J,MAAI;AACJ,MAAI;AAAE,YAAQ,KAAK,MAAM,MAAM,SAAS,QAAQ,CAAC;AAAA,EAAG,QAAQ;AAAE,UAAM,QAAQ,mCAAmC;AAAA,EAAG;AAClH,MAAI,CAAC,SAAS,OAAO,UAAU,YAAY,EAAE,kBAAkB,UAAU,MAAM,iBAAiB,YAAY,YAAa,OAAM,QAAQ,mDAAmD;AAC5L;;;AC1EO,SAAS,qBAAqB,MAAuE;AAC1G,MAAI,CAAC,MAAM,cAAc,KAAK,KAAK,CAAC,KAAK,iBAAiB,KAAK,KAAK,CAAC,KAAK,cAAc,KAAK,KAAK,CAAC,KAAK,qBAAqB,KAAK,EAAG,QAAO;AAC5I,SAAO,EAAE,aAAa,KAAK,cAAc,gBAAgB,KAAK,iBAAiB,aAAa,KAAK,cAAc,mBAAmB,KAAK,oBAAoB;AAC7J;AACO,SAAS,mBAA2C;AACzD,SAAO,EAAE,cAAc,QAAQ,IAAI,kBAAkB,IAAI,iBAAiB,QAAQ,IAAI,qBAAqB,IAAI,cAAc,QAAQ,IAAI,kBAAkB,IAAI,qBAAqB,QAAQ,IAAI,yBAAyB,GAAG;AAC9N;AACA,eAAsB,oBAAoB,OAA8D;AACtG,SAAO,sBAAsB,MAAM,MAAM,IAAI,GAAG,IAAI,IAAI,KAAK,qBAAqB,iBAAiB,CAAC;AACtG;AACA,eAAsB,cAAc,OAA6D;AAC/F,QAAM,cAAc,MAAM,oBAAoB,KAAK;AACnD,MAAI,CAAC,YAAa,QAAO;AACzB,QAAM,WAAW,IAAI,aAAa,IAAI,WAAW,WAAW,CAAC;AAC7D,SAAO,EAAE,UAAU,OAAO,OAAO,QAAQ,EAAE;AAC7C;","names":["z","AdportError","z","z","AdportError","z","AdportError","z","AdportError","z","AdportError","z","AdportError","AdportError","z","z","AdportError","z","z","AdportError","AdportError"]}
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@adport/provider-x",
3
+ "version": "0.6.0",
4
+ "description": "X Ads 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
+ "oauth-1.0a": "^2.2.6",
20
+ "zod": "^4.4.3",
21
+ "@adport/core": "0.6.0"
22
+ },
23
+ "devDependencies": {
24
+ "@types/node": "^26.1.2",
25
+ "tsup": "^8.3.0",
26
+ "typescript": "^5.8.0",
27
+ "vitest": "^4.1.10"
28
+ },
29
+ "scripts": {
30
+ "build": "tsup src/index.ts --format esm --dts --sourcemap --clean",
31
+ "test": "vitest run",
32
+ "typecheck": "tsc --noEmit"
33
+ }
34
+ }