@adport/provider-linkedin 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,117 @@
1
+ import { AdProvider, StandardActions, Account, NormalizedQuery, Report, WriteOperation, WriteGuard, WritePreview, WriteResult, AnyToolDefinition, CredentialStore, ProviderModule } from '@adport/core';
2
+ import { z } from 'zod';
3
+
4
+ declare const LINKEDIN_API_BASE = "https://api.linkedin.com/rest/";
5
+ declare const LINKEDIN_API_VERSION = "202608";
6
+ declare const LINKEDIN_TOKEN_URL = "https://www.linkedin.com/oauth/v2/accessToken";
7
+ interface LinkedInTokens {
8
+ accessToken: string;
9
+ expiresAt?: number;
10
+ refreshToken?: string;
11
+ refreshExpiresAt?: number;
12
+ }
13
+ interface LinkedInCredentials extends Partial<LinkedInTokens> {
14
+ clientId?: string;
15
+ clientSecret?: string;
16
+ onTokens?: (tokens: LinkedInTokens) => Promise<void>;
17
+ }
18
+ declare function buildLinkedInAuthUrl(clientId: string, redirectUri: string, state: string): string;
19
+ declare function exchangeLinkedInCode(input: {
20
+ clientId: string;
21
+ clientSecret: string;
22
+ code: string;
23
+ redirectUri: string;
24
+ }, fetchImpl?: typeof fetch): Promise<LinkedInTokens>;
25
+ type RestliValue = string | number | RestliValue[] | {
26
+ [key: string]: RestliValue;
27
+ };
28
+ declare function restli(value: RestliValue): string;
29
+ declare class LinkedInAdsClient {
30
+ private readonly credentials;
31
+ private readonly fetchImpl;
32
+ private tokens;
33
+ private refreshing?;
34
+ constructor(credentials: LinkedInCredentials, fetchImpl?: typeof fetch);
35
+ get<T>(path: string, schema: z.ZodType<T>, params?: Record<string, RestliValue>): Promise<T>;
36
+ create(path: string, body: unknown): Promise<string>;
37
+ update(path: string, fields: Record<string, unknown>): Promise<void>;
38
+ private request;
39
+ private canRefresh;
40
+ private accessToken;
41
+ private refresh;
42
+ }
43
+
44
+ declare class LinkedInAdsProvider implements AdProvider {
45
+ private readonly client;
46
+ readonly id = "linkedin";
47
+ constructor(client: LinkedInAdsClient);
48
+ capabilities(): {
49
+ serverDryRun: boolean;
50
+ };
51
+ standardActions(): StandardActions;
52
+ private search;
53
+ listAccounts(): Promise<Account[]>;
54
+ getAccount(accountId: string): Promise<{
55
+ [x: string]: unknown;
56
+ id: number;
57
+ name: string;
58
+ currency: string;
59
+ status: string;
60
+ test?: boolean | undefined;
61
+ }>;
62
+ listCampaigns(accountId: string): Promise<{
63
+ [x: string]: unknown;
64
+ id: number;
65
+ name: string;
66
+ account: string;
67
+ status: string;
68
+ dailyBudget?: {
69
+ amount: string;
70
+ currencyCode: string;
71
+ } | undefined;
72
+ totalBudget?: {
73
+ amount: string;
74
+ currencyCode: string;
75
+ } | undefined;
76
+ campaignGroup?: string | undefined;
77
+ }[]>;
78
+ listCampaignGroups(accountId: string): Promise<{
79
+ [x: string]: unknown;
80
+ id: number;
81
+ name: string;
82
+ account: string;
83
+ status: string;
84
+ budgetOptimization?: {
85
+ [x: string]: unknown;
86
+ budgetOptimizationStrategy?: string | undefined;
87
+ } | undefined;
88
+ }[]>;
89
+ getCampaign(accountId: string, campaignId: string): Promise<{
90
+ [x: string]: unknown;
91
+ id: number;
92
+ name: string;
93
+ account: string;
94
+ status: string;
95
+ dailyBudget?: {
96
+ amount: string;
97
+ currencyCode: string;
98
+ } | undefined;
99
+ totalBudget?: {
100
+ amount: string;
101
+ currencyCode: string;
102
+ } | undefined;
103
+ campaignGroup?: string | undefined;
104
+ }>;
105
+ report(query: NormalizedQuery): Promise<Report>;
106
+ previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview>;
107
+ applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult>;
108
+ private plan;
109
+ }
110
+
111
+ declare function linkedinTools(provider: LinkedInAdsProvider): AnyToolDefinition[];
112
+
113
+ declare function linkedInTokensData(tokens: LinkedInTokens): Record<string, string>;
114
+ declare function resolveLinkedInCredentials(store: CredentialStore): Promise<LinkedInCredentials | undefined>;
115
+ declare function createLinkedInModule(store: CredentialStore): Promise<ProviderModule | undefined>;
116
+
117
+ export { LINKEDIN_API_BASE, LINKEDIN_API_VERSION, LINKEDIN_TOKEN_URL, LinkedInAdsClient, LinkedInAdsProvider, type LinkedInCredentials, type LinkedInTokens, buildLinkedInAuthUrl, createLinkedInModule, exchangeLinkedInCode, linkedInTokensData, linkedinTools, resolveLinkedInCredentials, restli };
package/dist/index.js ADDED
@@ -0,0 +1,445 @@
1
+ // src/index.ts
2
+ import { AdportError as AdportError3 } from "@adport/core";
3
+
4
+ // src/client.ts
5
+ import { AdportError } from "@adport/core";
6
+ import { z } from "zod";
7
+ var LINKEDIN_API_BASE = "https://api.linkedin.com/rest/";
8
+ var LINKEDIN_API_VERSION = "202608";
9
+ var LINKEDIN_TOKEN_URL = "https://www.linkedin.com/oauth/v2/accessToken";
10
+ var tokenSchema = z.object({ access_token: z.string().min(1), expires_in: z.number().positive(), refresh_token: z.string().min(1).optional(), refresh_token_expires_in: z.number().nonnegative().optional() });
11
+ function buildLinkedInAuthUrl(clientId, redirectUri, state) {
12
+ const redirect = new URL(redirectUri);
13
+ if (redirect.protocol !== "https:" || redirect.hash || redirect.username || redirect.password || redirect.search) throw new AdportError("INVALID_INPUT", "linkedin: register an exact HTTPS callback on your own app");
14
+ return `https://www.linkedin.com/oauth/v2/authorization?${new URLSearchParams({ response_type: "code", client_id: clientId, redirect_uri: redirectUri, state, scope: "rw_ads r_ads_reporting" })}`;
15
+ }
16
+ async function tokenRequest(body, fetchImpl) {
17
+ const response = await fetchImpl(LINKEDIN_TOKEN_URL, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body, redirect: "error", signal: AbortSignal.timeout(3e4) });
18
+ if (!response.ok) throw new AdportError("PROVIDER_ERROR", `linkedin: OAuth ${body.get("grant_type")} failed (HTTP ${response.status}); reauthorize your own app if the grant expired`);
19
+ const result = tokenSchema.safeParse(await response.json());
20
+ if (!result.success) throw new AdportError("PROVIDER_ERROR", "linkedin: malformed OAuth response");
21
+ const token = result.data, now = Date.now();
22
+ return {
23
+ accessToken: token.access_token,
24
+ expiresAt: now + token.expires_in * 1e3,
25
+ ...token.refresh_token ? { refreshToken: token.refresh_token } : {},
26
+ ...token.refresh_token_expires_in !== void 0 ? { refreshExpiresAt: now + token.refresh_token_expires_in * 1e3 } : {}
27
+ };
28
+ }
29
+ async function exchangeLinkedInCode(input, fetchImpl = fetch) {
30
+ buildLinkedInAuthUrl(input.clientId, input.redirectUri, "validation");
31
+ return tokenRequest(new URLSearchParams({ grant_type: "authorization_code", code: input.code, redirect_uri: input.redirectUri, client_id: input.clientId, client_secret: input.clientSecret }), fetchImpl);
32
+ }
33
+ function restli(value) {
34
+ if (Array.isArray(value)) return `List(${value.map(restli).join(",")})`;
35
+ if (typeof value === "object") return `(${Object.entries(value).map(([key, child]) => `${encodeURIComponent(key)}:${restli(child)}`).join(",")})`;
36
+ return encodeURIComponent(String(value)).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
37
+ }
38
+ var LinkedInAdsClient = class {
39
+ constructor(credentials, fetchImpl = fetch) {
40
+ this.credentials = credentials;
41
+ this.fetchImpl = fetchImpl;
42
+ this.tokens = { accessToken: credentials.accessToken, expiresAt: credentials.expiresAt, refreshToken: credentials.refreshToken, refreshExpiresAt: credentials.refreshExpiresAt };
43
+ }
44
+ credentials;
45
+ fetchImpl;
46
+ tokens;
47
+ refreshing;
48
+ async get(path, schema, params = {}) {
49
+ const response = await this.request(path, "GET", params);
50
+ const parsed = schema.safeParse(await response.json());
51
+ if (!parsed.success) throw new AdportError("PROVIDER_ERROR", "linkedin: malformed API response");
52
+ return parsed.data;
53
+ }
54
+ async create(path, body) {
55
+ const response = await this.request(path, "POST", {}, body);
56
+ const id = response.headers.get("x-restli-id");
57
+ if (response.status !== 201 || !id || !/^[1-9]\d*$/.test(id)) throw new AdportError("PROVIDER_ERROR", "linkedin: create did not return 201 and x-restli-id; inspect the account before retrying");
58
+ return id;
59
+ }
60
+ async update(path, fields) {
61
+ const response = await this.request(path, "POST", {}, { patch: { $set: fields } }, true);
62
+ if (response.status !== 204) throw new AdportError("PROVIDER_ERROR", "linkedin: partial update did not return 204; inspect the account before retrying");
63
+ }
64
+ async request(path, method, params, body, partial = false, retry = true) {
65
+ if (!/^[a-zA-Z]+(?:\/[a-zA-Z0-9]+)*$/.test(path)) throw new AdportError("INVALID_INPUT", "linkedin: invalid API resource path");
66
+ const query = Object.entries(params).map(([key, value]) => `${encodeURIComponent(key)}=${key === "fields" && typeof value === "string" ? value.split(",").map(restli).join(",") : restli(value)}`).join("&");
67
+ const url = new URL(path, LINKEDIN_API_BASE);
68
+ url.search = query;
69
+ const token = await this.accessToken();
70
+ const response = await this.fetchImpl(url.href, {
71
+ method,
72
+ headers: {
73
+ authorization: `Bearer ${token}`,
74
+ "Linkedin-Version": LINKEDIN_API_VERSION,
75
+ "X-Restli-Protocol-Version": "2.0.0",
76
+ ...body !== void 0 ? { "content-type": "application/json" } : {},
77
+ ...partial ? { "X-RestLi-Method": "PARTIAL_UPDATE" } : {}
78
+ },
79
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {},
80
+ redirect: "error",
81
+ signal: AbortSignal.timeout(3e4)
82
+ });
83
+ if (response.status === 401 && method === "GET" && retry && this.canRefresh()) {
84
+ if (this.tokens.accessToken === token) this.tokens.expiresAt = 0;
85
+ return this.request(path, method, params, body, partial, false);
86
+ }
87
+ if (!response.ok) {
88
+ const advice = response.status === 403 ? " Check Advertising API approval, r_ads_reporting/rw_ads scopes and account roles; reauthorization alone may not help." : response.status === 401 ? " Reauthorize your own LinkedIn app; a non-refreshable token must be replaced." : "";
89
+ throw new AdportError("PROVIDER_ERROR", `linkedin: HTTP ${response.status}.${advice}`);
90
+ }
91
+ return response;
92
+ }
93
+ canRefresh() {
94
+ return Boolean(this.tokens.refreshToken && this.credentials.clientId && this.credentials.clientSecret && (this.tokens.refreshExpiresAt === void 0 || this.tokens.refreshExpiresAt > Date.now()));
95
+ }
96
+ async accessToken() {
97
+ if (this.tokens.accessToken && (this.tokens.expiresAt === void 0 || this.tokens.expiresAt > Date.now() + 6e4)) return this.tokens.accessToken;
98
+ if (!this.canRefresh()) throw new AdportError("NOT_CONNECTED", "linkedin: access token expired or missing; run adport connect linkedin with a fresh authorized token");
99
+ if (!this.refreshing) this.refreshing = this.refresh().finally(() => {
100
+ this.refreshing = void 0;
101
+ });
102
+ return this.refreshing;
103
+ }
104
+ async refresh() {
105
+ const updated = await tokenRequest(new URLSearchParams({ grant_type: "refresh_token", refresh_token: this.tokens.refreshToken, client_id: this.credentials.clientId, client_secret: this.credentials.clientSecret }), this.fetchImpl);
106
+ const tokens = { ...this.tokens, ...updated };
107
+ if (this.tokens.refreshExpiresAt !== void 0 && tokens.refreshExpiresAt !== void 0) tokens.refreshExpiresAt = Math.min(tokens.refreshExpiresAt, this.tokens.refreshExpiresAt);
108
+ await this.credentials.onTokens?.(tokens);
109
+ this.tokens = tokens;
110
+ return tokens.accessToken;
111
+ }
112
+ };
113
+
114
+ // src/provider.ts
115
+ import { z as z3 } from "zod";
116
+ import { AdportError as AdportError2, resolveDateRange } from "@adport/core";
117
+
118
+ // src/schemas.ts
119
+ import { z as z2 } from "zod";
120
+ var linkedinId = z2.string().regex(/^[1-9]\d*$/);
121
+ var numericId = z2.number().int().positive().safe();
122
+ var accountUrn = z2.string().regex(/^urn:li:sponsoredAccount:[1-9]\d*$/);
123
+ var decimal = z2.string().regex(/^\d+(?:\.\d+)?$/);
124
+ var moneySchema = z2.object({ amount: decimal, currencyCode: z2.string().regex(/^[A-Z]{3}$/) });
125
+ var accountSchema = z2.looseObject({ id: numericId, name: z2.string(), currency: z2.string().regex(/^[A-Z]{3}$/), status: z2.string(), test: z2.boolean().optional() });
126
+ var campaignSchema = z2.looseObject({ id: numericId, name: z2.string(), account: accountUrn, status: z2.string(), dailyBudget: moneySchema.optional(), totalBudget: moneySchema.optional(), campaignGroup: z2.string().regex(/^urn:li:sponsoredCampaignGroup:[1-9]\d*$/).optional() });
127
+ var groupSchema = z2.looseObject({ id: numericId, name: z2.string(), account: accountUrn, status: z2.string(), budgetOptimization: z2.looseObject({ budgetOptimizationStrategy: z2.string().optional() }).optional() });
128
+ var date = z2.object({ year: z2.number().int(), month: z2.number().int().min(1).max(12), day: z2.number().int().min(1).max(31) });
129
+ var reportRowSchema = z2.looseObject({
130
+ pivotValues: z2.array(z2.string()).length(1),
131
+ dateRange: z2.object({ start: date, end: date }),
132
+ costInLocalCurrency: decimal.optional(),
133
+ conversionValueInLocalCurrency: decimal.optional(),
134
+ impressions: z2.number().int().nonnegative().safe().optional(),
135
+ clicks: z2.number().int().nonnegative().safe().optional(),
136
+ externalWebsiteConversions: z2.number().int().nonnegative().safe().optional()
137
+ });
138
+ var NON_DISCRIMINATION_NOTICE = "LinkedIn tools may not be used to discriminate based on personal characteristics such as gender, age, race, or ethnicity. Learn more: https://www.linkedin.com/legal/ads-policy";
139
+ var NON_POLITICAL_CONSENT = "I confirm this is not political advertising. None of my ads qualify as political advertising under the law of the targeted countries, including EU law for ads targeted to the EU.";
140
+ var facets = z2.record(z2.string().regex(/^urn:li:adTargetingFacet:[a-zA-Z]+$/), z2.array(z2.string().regex(/^urn:li:[a-zA-Z]+:[a-zA-Z0-9_()-]+$/)).min(1));
141
+ var targetingSchema = z2.object({ include: z2.object({ and: z2.array(z2.object({ or: facets })).min(1) }), exclude: z2.object({ or: facets }).optional() });
142
+ var micros = z2.number().int().positive().safe();
143
+ var createCampaignSchema = z2.object({
144
+ name: z2.string().trim().min(1).max(200),
145
+ campaign_group_id: linkedinId,
146
+ type: z2.enum(["TEXT_AD", "SPONSORED_UPDATES", "SPONSORED_INMAILS", "DYNAMIC"]),
147
+ objective_type: z2.enum(["BRAND_AWARENESS", "ENGAGEMENT", "JOB_APPLICANTS", "LEAD_GENERATION", "WEBSITE_CONVERSIONS", "WEBSITE_VISITS", "VIDEO_VIEWS"]),
148
+ cost_type: z2.enum(["CPM", "CPC", "CPV"]),
149
+ unit_cost_micros: micros,
150
+ daily_budget_micros: micros.optional(),
151
+ total_budget_micros: micros.optional(),
152
+ locale: z2.object({ country: z2.string().regex(/^[A-Z]{2}$/), language: z2.string().regex(/^[a-z]{2}$/) }),
153
+ targeting_criteria: targetingSchema,
154
+ associated_entity: z2.string().regex(/^urn:li:(organization|person):[a-zA-Z0-9_-]+$/).optional(),
155
+ format: z2.string().regex(/^[A-Z_]+$/).optional(),
156
+ start_time: z2.number().int().positive().safe().optional(),
157
+ end_time: z2.number().int().positive().safe().optional(),
158
+ status: z2.enum(["PAUSED", "ACTIVE"]).default("PAUSED"),
159
+ non_political_consent: z2.literal(true).describe(`Explicit advertiser confirmation required: ${NON_POLITICAL_CONSENT}`)
160
+ });
161
+ var setStatusSchema = z2.object({ campaign_id: linkedinId, status: z2.enum(["PAUSED", "ACTIVE"]), non_political_consent: z2.literal(true).optional().describe(`Required when activating: ${NON_POLITICAL_CONSENT}`) });
162
+ var setBudgetSchema = z2.object({ campaign_id: linkedinId, budget_type: z2.enum(["DAILY", "TOTAL"]), budget_micros: micros });
163
+
164
+ // src/provider.ts
165
+ var FIELDS = { spend: "costInLocalCurrency", impressions: "impressions", clicks: "clicks", conversions: "externalWebsiteConversions", conversion_value: "conversionValueInLocalCurrency" };
166
+ var DERIVED = { ctr: ["clicks", "impressions", 100], cpc: ["spend", "clicks", 1], cpm: ["spend", "impressions", 1e3], cpa: ["spend", "conversions", 1], roas: ["conversion_value", "spend", 1] };
167
+ var STATUS = ["ACTIVE", "PAUSED", "ARCHIVED", "COMPLETED", "CANCELED", "DRAFT", "PENDING_DELETION", "REMOVED"];
168
+ var ACCOUNT_URN = (id) => `urn:li:sponsoredAccount:${linkedinId.parse(id)}`;
169
+ function decimalToMicros(amount) {
170
+ if (!/^\d+(?:\.\d+)?$/.test(amount)) throw new AdportError2("PROVIDER_ERROR", "linkedin: invalid money amount");
171
+ const [whole, fraction = ""] = amount.split(".");
172
+ if (fraction.slice(6).replace(/0/g, "")) throw new AdportError2("PROVIDER_ERROR", "linkedin: budget precision exceeds integer micros");
173
+ const value = BigInt(whole) * 1000000n + BigInt(fraction.slice(0, 6).padEnd(6, "0"));
174
+ if (value > BigInt(Number.MAX_SAFE_INTEGER)) throw new AdportError2("PROVIDER_ERROR", "linkedin: budget exceeds safe integer micros");
175
+ return Number(value);
176
+ }
177
+ function microsToDecimal(value) {
178
+ if (!Number.isSafeInteger(value) || value < 0) throw new AdportError2("INVALID_INPUT", "linkedin: budget must be integer micros");
179
+ const number = BigInt(value);
180
+ return `${number / 1000000n}.${String(number % 1000000n).padStart(6, "0")}`;
181
+ }
182
+ var LinkedInAdsProvider = class {
183
+ constructor(client) {
184
+ this.client = client;
185
+ }
186
+ client;
187
+ id = "linkedin";
188
+ capabilities() {
189
+ return { serverDryRun: false };
190
+ }
191
+ standardActions() {
192
+ return { pauseCampaign: (accountId, campaignId) => ({ tool: "linkedin_set_campaign_status", input: { account_id: accountId, campaign_id: campaignId, status: "PAUSED" } }) };
193
+ }
194
+ async search(path, schema, search) {
195
+ const params = { q: "search", pageSize: 100, ...search ? { search } : {} };
196
+ const pageSchema = z3.object({ elements: z3.array(schema), metadata: z3.object({ nextPageToken: z3.string().optional() }).optional() });
197
+ const rows = [], tokens = /* @__PURE__ */ new Set(), seen = /* @__PURE__ */ new Set();
198
+ while (true) {
199
+ const page = await this.client.get(path, pageSchema, params);
200
+ for (const row of page.elements) {
201
+ if (seen.has(row.id)) throw new AdportError2("PROVIDER_ERROR", "linkedin: search repeated an entity");
202
+ seen.add(row.id);
203
+ rows.push(row);
204
+ }
205
+ const next = page.metadata?.nextPageToken;
206
+ if (!next) return rows;
207
+ if (tokens.has(next) || tokens.size >= 1e3) throw new AdportError2("PROVIDER_ERROR", "linkedin: cursor pagination did not terminate");
208
+ tokens.add(next);
209
+ params.pageToken = next;
210
+ }
211
+ }
212
+ async listAccounts() {
213
+ return (await this.search("adAccounts", accountSchema)).map((a) => ({ provider: this.id, id: String(a.id), name: a.name, currency: a.currency, status: a.status }));
214
+ }
215
+ async getAccount(accountId) {
216
+ const data = await this.client.get(`adAccounts/${linkedinId.parse(accountId)}`, accountSchema);
217
+ if (String(data.id) !== accountId) throw new AdportError2("PROVIDER_ERROR", "linkedin: account ID mismatch");
218
+ return data;
219
+ }
220
+ async listCampaigns(accountId) {
221
+ const rows = await this.search(`adAccounts/${linkedinId.parse(accountId)}/adCampaigns`, campaignSchema, { status: { values: STATUS } });
222
+ if (rows.some((r) => r.account !== ACCOUNT_URN(accountId))) throw new AdportError2("PROVIDER_ERROR", "linkedin: campaign account mismatch");
223
+ return rows;
224
+ }
225
+ async listCampaignGroups(accountId) {
226
+ const rows = await this.search(`adAccounts/${linkedinId.parse(accountId)}/adCampaignGroups`, groupSchema, { status: { values: ["ACTIVE", "PAUSED", "ARCHIVED", "DRAFT", "PENDING_DELETION", "REMOVED"] } });
227
+ if (rows.some((r) => r.account !== ACCOUNT_URN(accountId))) throw new AdportError2("PROVIDER_ERROR", "linkedin: campaign group account mismatch");
228
+ return rows;
229
+ }
230
+ async getCampaign(accountId, campaignId) {
231
+ const data = await this.client.get(`adAccounts/${linkedinId.parse(accountId)}/adCampaigns/${linkedinId.parse(campaignId)}`, campaignSchema);
232
+ if (String(data.id) !== campaignId || data.account !== ACCOUNT_URN(accountId)) throw new AdportError2("PROVIDER_ERROR", "linkedin: campaign account/ID mismatch");
233
+ return data;
234
+ }
235
+ async report(query) {
236
+ if (query.level === "ad_group") throw new AdportError2("INVALID_INPUT", "linkedin: no native ad-group level; use campaign (LinkedIn campaign) or ad (creative). Campaign groups are listed separately.");
237
+ const range = resolveDateRange(query.dateRange), start = z3.iso.date().parse(range.start), end = z3.iso.date().parse(range.end);
238
+ if (end < start) throw new AdportError2("INVALID_INPUT", "linkedin: report end must be on/after start");
239
+ const dateObject = (iso) => {
240
+ const [year, month, day] = iso.split("-").map(Number);
241
+ return { year, month, day };
242
+ };
243
+ const dateRange = { start: dateObject(start), end: dateObject(end) };
244
+ const limit = query.limit ?? 1e3;
245
+ if (!Number.isSafeInteger(limit) || limit < 1) throw new AdportError2("INVALID_INPUT", "linkedin: report limit must be a positive integer");
246
+ const fields = /* @__PURE__ */ new Set(["pivotValues", "dateRange"]);
247
+ for (const metric of query.metrics) {
248
+ if (metric in FIELDS) fields.add(FIELDS[metric]);
249
+ else if (metric in DERIVED) for (const dependency of DERIVED[metric].slice(0, 2)) fields.add(FIELDS[dependency]);
250
+ }
251
+ if (fields.size === 2) throw new AdportError2("INVALID_INPUT", "linkedin: at least one supported metric is required");
252
+ const pivot = { account: "ACCOUNT", campaign: "CAMPAIGN", ad: "CREATIVE" }[query.level];
253
+ const urnType = { account: "sponsoredAccount", campaign: "sponsoredCampaign", ad: "sponsoredCreative" }[query.level];
254
+ const rows = [];
255
+ let capped = false;
256
+ for (const id of [...new Set(query.accountIds ?? (await this.listAccounts()).map((a) => a.id))]) {
257
+ const accountId = linkedinId.parse(id), account = await this.getAccount(accountId);
258
+ const campaigns = query.level === "campaign" ? new Map((await this.listCampaigns(accountId)).map((c) => [String(c.id), c])) : void 0;
259
+ const data = await this.client.get("adAnalytics", z3.object({ elements: z3.array(reportRowSchema), paging: z3.object({ links: z3.array(z3.object({ rel: z3.string() })).optional() }).optional() }), {
260
+ q: "analytics",
261
+ pivot,
262
+ timeGranularity: "ALL",
263
+ dateRange,
264
+ accounts: [ACCOUNT_URN(accountId)],
265
+ fields: [...fields].join(",")
266
+ });
267
+ if (data.paging?.links?.some((link) => link.rel === "next")) throw new AdportError2("PROVIDER_ERROR", "linkedin: unexpected analytics pagination; refusing incomplete data");
268
+ capped ||= data.elements.length >= 15e3;
269
+ const seen = /* @__PURE__ */ new Set();
270
+ for (const row of data.elements) {
271
+ const urn = row.pivotValues[0], match = urn.match(new RegExp(`^urn:li:${urnType}:([1-9]\\d*)$`));
272
+ if (!match) throw new AdportError2("PROVIDER_ERROR", "linkedin: unexpected analytics pivot");
273
+ const entityId = match[1];
274
+ if (seen.has(entityId) || query.level === "account" && entityId !== accountId || campaigns && !campaigns.has(entityId)) throw new AdportError2("PROVIDER_ERROR", "linkedin: incorrectly scoped or duplicate analytics row");
275
+ seen.add(entityId);
276
+ if (["start", "end"].some((bound) => ["year", "month", "day"].some((part) => row.dateRange[bound][part] !== dateRange[bound][part]))) {
277
+ throw new AdportError2("PROVIDER_ERROR", "linkedin: provider changed the reporting date range (older queries may round to months); request the returned month boundaries explicitly");
278
+ }
279
+ const campaign = campaigns?.get(entityId);
280
+ rows.push({ provider: this.id, accountId, entity: { level: query.level, id: entityId, name: query.level === "account" ? account.name : campaign?.name ?? entityId, ...query.level === "account" ? { status: account.status } : campaign ? { status: campaign.status } : {} }, metrics: normalize(row, query.metrics) });
281
+ if (rows.length > limit) return { rows: rows.slice(0, limit), truncated: true };
282
+ }
283
+ }
284
+ return { rows, ...capped ? { truncated: true } : {} };
285
+ }
286
+ async previewWrite(op, guard) {
287
+ const { execute: _execute, ...preview } = await this.plan(op, guard);
288
+ return { ...preview, serverValidated: false };
289
+ }
290
+ async applyWrite(op, guard) {
291
+ return { applied: true, resourceIds: await (await this.plan(op, guard)).execute() };
292
+ }
293
+ async plan(op, guard) {
294
+ const accountId = linkedinId.parse(op.accountId), base = `adAccounts/${accountId}/adCampaigns`;
295
+ if (op.provider !== this.id) throw new AdportError2("INVALID_INPUT", "linkedin: provider mismatch");
296
+ if (op.tool === "linkedin_create_campaign" && op.kind === "create") {
297
+ const input = createCampaignSchema.parse(op.payload);
298
+ if (!input.daily_budget_micros && !input.total_budget_micros) throw new AdportError2("INVALID_INPUT", "linkedin: a daily or total campaign budget is required");
299
+ if (input.type === "DYNAMIC" && (!input.daily_budget_micros || !input.total_budget_micros || !input.format)) throw new AdportError2("INVALID_INPUT", "linkedin: dynamic campaigns require daily and total budgets and a format");
300
+ if ((input.type === "SPONSORED_UPDATES" || input.type === "DYNAMIC" || input.objective_type === "LEAD_GENERATION") && !input.associated_entity) throw new AdportError2("INVALID_INPUT", "linkedin: sponsored content, dynamic and lead-generation campaigns require an associated entity");
301
+ if (input.total_budget_micros && !input.end_time) throw new AdportError2("INVALID_INPUT", "linkedin: lifetime campaign budgets require an end time");
302
+ if (input.end_time && (!input.start_time || input.end_time <= input.start_time)) throw new AdportError2("INVALID_INPUT", "linkedin: scheduled end requires an earlier start time");
303
+ const keys = input.targeting_criteria.include.and.flatMap((clause) => Object.keys(clause.or));
304
+ if (input.targeting_criteria.include.and.some((clause) => !Object.keys(clause.or).length)) throw new AdportError2("INVALID_INPUT", "linkedin: targeting include clauses cannot be empty");
305
+ if (!keys.includes("urn:li:adTargetingFacet:locations") && !keys.includes("urn:li:adTargetingFacet:profileLocations")) throw new AdportError2("INVALID_INPUT", "linkedin: targeting must include modern geo locations");
306
+ if (keys.includes("urn:li:adTargetingFacet:locations") && keys.includes("urn:li:adTargetingFacet:profileLocations")) throw new AdportError2("INVALID_INPUT", "linkedin: choose locations or profileLocations, not both");
307
+ for (const clause of input.targeting_criteria.include.and) for (const [facet, values] of Object.entries(clause.or)) {
308
+ if (["urn:li:adTargetingFacet:locations", "urn:li:adTargetingFacet:profileLocations"].includes(facet) && values.some((value) => !/^urn:li:geo:[1-9]\d*$/.test(value))) throw new AdportError2("INVALID_INPUT", "linkedin: use modern urn:li:geo location identifiers; legacy geo is no longer supported");
309
+ }
310
+ const account = await this.getAccount(accountId);
311
+ const group = await this.client.get(`adAccounts/${accountId}/adCampaignGroups/${input.campaign_group_id}`, groupSchema);
312
+ if (group.account !== ACCOUNT_URN(accountId) || String(group.id) !== input.campaign_group_id) throw new AdportError2("PROVIDER_ERROR", "linkedin: campaign group account/ID mismatch");
313
+ if (group.budgetOptimization?.budgetOptimizationStrategy === "DYNAMIC") throw new AdportError2("INVALID_INPUT", "linkedin: this group shares a dynamic budget; ordinary campaign budget creation is not supported for it");
314
+ const status = guard.forcePausedCreation ? "PAUSED" : input.status;
315
+ const money = (amount) => ({ amount: microsToDecimal(amount), currencyCode: account.currency });
316
+ const body = {
317
+ account: ACCOUNT_URN(accountId),
318
+ campaignGroup: `urn:li:sponsoredCampaignGroup:${input.campaign_group_id}`,
319
+ name: input.name,
320
+ type: input.type,
321
+ objectiveType: input.objective_type,
322
+ costType: input.cost_type,
323
+ unitCost: money(input.unit_cost_micros),
324
+ locale: input.locale,
325
+ targetingCriteria: input.targeting_criteria,
326
+ status,
327
+ politicalIntent: "NOT_POLITICAL",
328
+ offsiteDeliveryEnabled: false,
329
+ audienceExpansionEnabled: false,
330
+ ...input.associated_entity ? { associatedEntity: input.associated_entity } : {},
331
+ ...input.format ? { format: input.format } : {},
332
+ ...input.daily_budget_micros ? { dailyBudget: money(input.daily_budget_micros) } : {},
333
+ ...input.total_budget_micros ? { totalBudget: money(input.total_budget_micros), pacingStrategy: "LIFETIME" } : {},
334
+ ...input.start_time ? { runSchedule: { start: input.start_time, ...input.end_time ? { end: input.end_time } : {} } } : {}
335
+ };
336
+ return {
337
+ summary: `Create LinkedIn campaign "${input.name}"`,
338
+ changes: [NON_DISCRIMINATION_NOTICE, `Advertiser confirmation: ${NON_POLITICAL_CONSENT}`, `+ ${JSON.stringify(body)}`],
339
+ coercions: input.status !== status ? ["status coerced to PAUSED by policy (paused_creation)"] : [],
340
+ budgetDeltas: [...input.daily_budget_micros ? [{ target: "new campaign daily budget", toMicros: input.daily_budget_micros }] : [], ...input.total_budget_micros ? [{ target: "new campaign total budget", toMicros: input.total_budget_micros }] : []],
341
+ execute: async () => [await this.client.create(base, body)]
342
+ };
343
+ }
344
+ if (op.kind === "update" && ["linkedin_set_campaign_status", "linkedin_set_budget"].includes(op.tool)) {
345
+ const input = op.tool === "linkedin_set_budget" ? setBudgetSchema.parse(op.payload) : setStatusSchema.parse(op.payload);
346
+ if ("status" in input && input.status === "ACTIVE" && !input.non_political_consent) throw new AdportError2("INVALID_INPUT", `linkedin: activation requires explicit advertiser consent: ${NON_POLITICAL_CONSENT}`);
347
+ const current = await this.getCampaign(accountId, input.campaign_id);
348
+ if ("budget_micros" in input) {
349
+ const field = input.budget_type === "DAILY" ? "dailyBudget" : "totalBudget", budget = current[field];
350
+ if (!budget) throw new AdportError2("INVALID_INPUT", `linkedin: campaign has no existing ${field}; this tool changes existing budget types only`);
351
+ const fromMicros = decimalToMicros(budget.amount);
352
+ return {
353
+ summary: `Change LinkedIn campaign "${current.name}" budget`,
354
+ changes: [`~ ${field}: ${budget.amount} \u2192 ${microsToDecimal(input.budget_micros)} ${budget.currencyCode}`],
355
+ coercions: [],
356
+ budgetDeltas: [{ target: `campaign ${current.id} ${field}`, fromMicros, toMicros: input.budget_micros }],
357
+ execute: async () => {
358
+ await this.client.update(`${base}/${current.id}`, { [field]: { amount: microsToDecimal(input.budget_micros), currencyCode: budget.currencyCode } });
359
+ return [String(current.id)];
360
+ }
361
+ };
362
+ }
363
+ return {
364
+ summary: `Change LinkedIn campaign "${current.name}" status`,
365
+ changes: [`~ status: ${current.status} \u2192 ${input.status}`, ...input.status === "ACTIVE" ? [NON_DISCRIMINATION_NOTICE, `Advertiser confirmation: ${NON_POLITICAL_CONSENT}`] : []],
366
+ coercions: [],
367
+ budgetDeltas: [],
368
+ execute: async () => {
369
+ await this.client.update(`${base}/${current.id}`, { status: input.status, ...input.status === "ACTIVE" ? { politicalIntent: "NOT_POLITICAL" } : {} });
370
+ return [String(current.id)];
371
+ }
372
+ };
373
+ }
374
+ throw new AdportError2("INVALID_INPUT", `linkedin: unsupported write ${op.tool}`);
375
+ }
376
+ };
377
+ function normalize(row, requested) {
378
+ const mapped = {};
379
+ for (const [metric, field] of Object.entries(FIELDS)) {
380
+ const value = row[field];
381
+ if (value === void 0) continue;
382
+ const number = Number(value);
383
+ if (!Number.isFinite(number) || number < 0) throw new AdportError2("PROVIDER_ERROR", `linkedin: invalid ${field} metric`);
384
+ mapped[metric] = number;
385
+ }
386
+ for (const [metric, [numerator, denominator, factor]] of Object.entries(DERIVED)) if (mapped[numerator] !== void 0 && mapped[denominator] !== void 0) mapped[metric] = mapped[denominator] ? mapped[numerator] / mapped[denominator] * factor : 0;
387
+ return Object.fromEntries(requested.filter((metric) => mapped[metric] !== void 0).map((metric) => [metric, mapped[metric]]));
388
+ }
389
+
390
+ // src/tools.ts
391
+ import { z as z4 } from "zod";
392
+ import { defineTool, guardedWriteTool } from "@adport/core";
393
+ function linkedinTools(provider) {
394
+ return [
395
+ defineTool({ name: "linkedin_list_campaigns", namespace: "linkedin", description: "List LinkedIn campaigns, including inactive campaigns.", input: z4.object({ account_id: linkedinId }), annotations: { readOnly: true }, handler: (input) => provider.listCampaigns(input.account_id) }),
396
+ defineTool({ name: "linkedin_list_campaign_groups", namespace: "linkedin", description: "List LinkedIn campaign groups to select a parent for campaign creation.", input: z4.object({ account_id: linkedinId }), annotations: { readOnly: true }, handler: (input) => provider.listCampaignGroups(input.account_id) }),
397
+ guardedWriteTool({ name: "linkedin_create_campaign", namespace: "linkedin", provider: "linkedin", kind: "create", description: `Create a paused LinkedIn campaign with account-currency budgets in micros. Explicit non-political advertiser consent required. Preview is local. ${NON_DISCRIMINATION_NOTICE}`, payload: createCampaignSchema }),
398
+ guardedWriteTool({ name: "linkedin_set_campaign_status", namespace: "linkedin", provider: "linkedin", kind: "update", description: "Pause or activate a LinkedIn campaign. Activation requires explicit non-political advertiser consent.", payload: setStatusSchema }),
399
+ guardedWriteTool({ name: "linkedin_set_budget", namespace: "linkedin", provider: "linkedin", kind: "update", description: "Change an existing daily or total LinkedIn campaign budget in integer micros, preserving currency and other budget fields.", payload: setBudgetSchema })
400
+ ];
401
+ }
402
+
403
+ // src/index.ts
404
+ function timestamp(value) {
405
+ if (value === void 0) return void 0;
406
+ const parsed = Number(value);
407
+ if (!Number.isSafeInteger(parsed) || parsed < 0) throw new AdportError3("INVALID_INPUT", "linkedin: token expiration must be Unix milliseconds");
408
+ return parsed;
409
+ }
410
+ function linkedInTokensData(tokens) {
411
+ return { access_token: tokens.accessToken, ...tokens.expiresAt !== void 0 ? { expires_at: String(tokens.expiresAt) } : {}, ...tokens.refreshToken ? { refresh_token: tokens.refreshToken } : {}, ...tokens.refreshExpiresAt !== void 0 ? { refresh_expires_at: String(tokens.refreshExpiresAt) } : {} };
412
+ }
413
+ async function resolveLinkedInCredentials(store) {
414
+ const saved = await store.get("linkedin"), data = saved?.data;
415
+ const complete = (d) => Boolean(d?.access_token || d?.refresh_token && d.client_id && d.client_secret);
416
+ const source = complete(data) ? data : { access_token: process.env.LINKEDIN_ACCESS_TOKEN ?? "", refresh_token: process.env.LINKEDIN_REFRESH_TOKEN ?? "", client_id: process.env.LINKEDIN_CLIENT_ID ?? "", client_secret: process.env.LINKEDIN_CLIENT_SECRET ?? "", ...process.env.LINKEDIN_EXPIRES_AT ? { expires_at: process.env.LINKEDIN_EXPIRES_AT } : {}, ...process.env.LINKEDIN_REFRESH_EXPIRES_AT ? { refresh_expires_at: process.env.LINKEDIN_REFRESH_EXPIRES_AT } : {} };
417
+ if (!complete(source)) return void 0;
418
+ const credentials = { accessToken: source?.access_token || void 0, expiresAt: timestamp(source?.expires_at), refreshToken: source?.refresh_token || void 0, refreshExpiresAt: timestamp(source?.refresh_expires_at), clientId: source?.client_id || void 0, clientSecret: source?.client_secret || void 0 };
419
+ if (source === data) credentials.onTokens = async (tokens) => {
420
+ const latest = await store.get("linkedin");
421
+ if (latest) await store.set({ provider: "linkedin", source: latest.source, data: { ...latest.data, ...linkedInTokensData(tokens) } });
422
+ };
423
+ return credentials;
424
+ }
425
+ async function createLinkedInModule(store) {
426
+ const credentials = await resolveLinkedInCredentials(store);
427
+ if (!credentials) return void 0;
428
+ const provider = new LinkedInAdsProvider(new LinkedInAdsClient(credentials));
429
+ return { provider, tools: linkedinTools(provider) };
430
+ }
431
+ export {
432
+ LINKEDIN_API_BASE,
433
+ LINKEDIN_API_VERSION,
434
+ LINKEDIN_TOKEN_URL,
435
+ LinkedInAdsClient,
436
+ LinkedInAdsProvider,
437
+ buildLinkedInAuthUrl,
438
+ createLinkedInModule,
439
+ exchangeLinkedInCode,
440
+ linkedInTokensData,
441
+ linkedinTools,
442
+ resolveLinkedInCredentials,
443
+ restli
444
+ };
445
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/client.ts","../src/provider.ts","../src/schemas.ts","../src/tools.ts"],"sourcesContent":["import { AdportError, type CredentialStore, type ProviderModule } from '@adport/core';\nimport { LinkedInAdsClient, type LinkedInCredentials, type LinkedInTokens } from './client.js';\nimport { LinkedInAdsProvider } from './provider.js';\nimport { linkedinTools } from './tools.js';\nexport { LinkedInAdsClient, LINKEDIN_API_BASE, LINKEDIN_API_VERSION, LINKEDIN_TOKEN_URL, buildLinkedInAuthUrl, exchangeLinkedInCode, restli, type LinkedInCredentials, type LinkedInTokens } from './client.js';\nexport { LinkedInAdsProvider } from './provider.js';\nexport { linkedinTools } from './tools.js';\n\nfunction timestamp(value: string | undefined): number | undefined {\n if (value === undefined) return undefined;\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed < 0) throw new AdportError('INVALID_INPUT', 'linkedin: token expiration must be Unix milliseconds');\n return parsed;\n}\nexport function linkedInTokensData(tokens: LinkedInTokens): Record<string, string> {\n return { access_token: tokens.accessToken, ...(tokens.expiresAt !== undefined ? { expires_at: String(tokens.expiresAt) } : {}), ...(tokens.refreshToken ? { refresh_token: tokens.refreshToken } : {}), ...(tokens.refreshExpiresAt !== undefined ? { refresh_expires_at: String(tokens.refreshExpiresAt) } : {}) };\n}\nexport async function resolveLinkedInCredentials(store: CredentialStore): Promise<LinkedInCredentials | undefined> {\n const saved = await store.get('linkedin'), data = saved?.data;\n const complete = (d: Record<string, string> | undefined) => Boolean(d?.access_token || (d?.refresh_token && d.client_id && d.client_secret));\n const source = complete(data) ? data : { access_token: process.env.LINKEDIN_ACCESS_TOKEN ?? '', refresh_token: process.env.LINKEDIN_REFRESH_TOKEN ?? '', client_id: process.env.LINKEDIN_CLIENT_ID ?? '', client_secret: process.env.LINKEDIN_CLIENT_SECRET ?? '', ...(process.env.LINKEDIN_EXPIRES_AT ? { expires_at: process.env.LINKEDIN_EXPIRES_AT } : {}), ...(process.env.LINKEDIN_REFRESH_EXPIRES_AT ? { refresh_expires_at: process.env.LINKEDIN_REFRESH_EXPIRES_AT } : {}) };\n if (!complete(source)) return undefined;\n const credentials: LinkedInCredentials = { accessToken: source?.access_token || undefined, expiresAt: timestamp(source?.expires_at), refreshToken: source?.refresh_token || undefined, refreshExpiresAt: timestamp(source?.refresh_expires_at), clientId: source?.client_id || undefined, clientSecret: source?.client_secret || undefined };\n if (source === data) credentials.onTokens = async tokens => { const latest = await store.get('linkedin'); if (latest) await store.set({ provider: 'linkedin', source: latest.source, data: { ...latest.data, ...linkedInTokensData(tokens) } }); };\n return credentials;\n}\nexport async function createLinkedInModule(store: CredentialStore): Promise<ProviderModule | undefined> {\n const credentials = await resolveLinkedInCredentials(store);\n if (!credentials) return undefined;\n const provider = new LinkedInAdsProvider(new LinkedInAdsClient(credentials));\n return { provider, tools: linkedinTools(provider) };\n}\n","import { AdportError } from '@adport/core';\nimport { z } from 'zod';\n\nexport const LINKEDIN_API_BASE = 'https://api.linkedin.com/rest/';\nexport const LINKEDIN_API_VERSION = '202608';\nexport const LINKEDIN_TOKEN_URL = 'https://www.linkedin.com/oauth/v2/accessToken';\nexport interface LinkedInTokens {\n accessToken: string;\n expiresAt?: number;\n refreshToken?: string;\n refreshExpiresAt?: number;\n}\nexport interface LinkedInCredentials extends Partial<LinkedInTokens> {\n clientId?: string;\n clientSecret?: string;\n onTokens?: (tokens: LinkedInTokens) => Promise<void>;\n}\nconst tokenSchema = z.object({ access_token: z.string().min(1), expires_in: z.number().positive(), refresh_token: z.string().min(1).optional(), refresh_token_expires_in: z.number().nonnegative().optional() });\n\nexport function buildLinkedInAuthUrl(clientId: string, redirectUri: string, state: string): string {\n const redirect = new URL(redirectUri);\n if (redirect.protocol !== 'https:' || redirect.hash || redirect.username || redirect.password || redirect.search) throw new AdportError('INVALID_INPUT', 'linkedin: register an exact HTTPS callback on your own app');\n return `https://www.linkedin.com/oauth/v2/authorization?${new URLSearchParams({ response_type: 'code', client_id: clientId, redirect_uri: redirectUri, state, scope: 'rw_ads r_ads_reporting' })}`;\n}\nasync function tokenRequest(body: URLSearchParams, fetchImpl: typeof fetch): Promise<LinkedInTokens> {\n const response = await fetchImpl(LINKEDIN_TOKEN_URL, { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body, redirect: 'error', signal: AbortSignal.timeout(30_000) });\n if (!response.ok) throw new AdportError('PROVIDER_ERROR', `linkedin: OAuth ${body.get('grant_type')} failed (HTTP ${response.status}); reauthorize your own app if the grant expired`);\n const result = tokenSchema.safeParse(await response.json());\n if (!result.success) throw new AdportError('PROVIDER_ERROR', 'linkedin: malformed OAuth response');\n const token = result.data, now = Date.now();\n return { accessToken: token.access_token, expiresAt: now + token.expires_in * 1000,\n ...(token.refresh_token ? { refreshToken: token.refresh_token } : {}),\n ...(token.refresh_token_expires_in !== undefined ? { refreshExpiresAt: now + token.refresh_token_expires_in * 1000 } : {}),\n };\n}\nexport async function exchangeLinkedInCode(input: { clientId: string; clientSecret: string; code: string; redirectUri: string }, fetchImpl: typeof fetch = fetch) {\n buildLinkedInAuthUrl(input.clientId, input.redirectUri, 'validation');\n return tokenRequest(new URLSearchParams({ grant_type: 'authorization_code', code: input.code, redirect_uri: input.redirectUri, client_id: input.clientId, client_secret: input.clientSecret }), fetchImpl);\n}\n\n// Rest.li encodes leaf values, not List/record punctuation. URLSearchParams\n// would incorrectly encode the structural parentheses and commas as well.\nexport type RestliValue = string | number | RestliValue[] | { [key: string]: RestliValue };\nexport function restli(value: RestliValue): string {\n if (Array.isArray(value)) return `List(${value.map(restli).join(',')})`;\n if (typeof value === 'object') return `(${Object.entries(value).map(([key, child]) => `${encodeURIComponent(key)}:${restli(child)}`).join(',')})`;\n return encodeURIComponent(String(value)).replace(/[!'()*]/g, c => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);\n}\n\nexport class LinkedInAdsClient {\n private tokens: Partial<LinkedInTokens>;\n private refreshing?: Promise<string>;\n constructor(private readonly credentials: LinkedInCredentials, private readonly fetchImpl: typeof fetch = fetch) {\n this.tokens = { accessToken: credentials.accessToken, expiresAt: credentials.expiresAt, refreshToken: credentials.refreshToken, refreshExpiresAt: credentials.refreshExpiresAt };\n }\n async get<T>(path: string, schema: z.ZodType<T>, params: Record<string, RestliValue> = {}): Promise<T> {\n const response = await this.request(path, 'GET', params);\n const parsed = schema.safeParse(await response.json());\n if (!parsed.success) throw new AdportError('PROVIDER_ERROR', 'linkedin: malformed API response');\n return parsed.data;\n }\n async create(path: string, body: unknown): Promise<string> {\n const response = await this.request(path, 'POST', {}, body);\n const id = response.headers.get('x-restli-id');\n if (response.status !== 201 || !id || !/^[1-9]\\d*$/.test(id)) throw new AdportError('PROVIDER_ERROR', 'linkedin: create did not return 201 and x-restli-id; inspect the account before retrying');\n return id;\n }\n async update(path: string, fields: Record<string, unknown>): Promise<void> {\n const response = await this.request(path, 'POST', {}, { patch: { $set: fields } }, true);\n if (response.status !== 204) throw new AdportError('PROVIDER_ERROR', 'linkedin: partial update did not return 204; inspect the account before retrying');\n }\n private async request(path: string, method: 'GET' | 'POST', params: Record<string, RestliValue>, body?: unknown, partial = false, retry = true): Promise<Response> {\n if (!/^[a-zA-Z]+(?:\\/[a-zA-Z0-9]+)*$/.test(path)) throw new AdportError('INVALID_INPUT', 'linkedin: invalid API resource path');\n const query = Object.entries(params).map(([key, value]) => `${encodeURIComponent(key)}=${key === 'fields' && typeof value === 'string' ? value.split(',').map(restli).join(',') : restli(value)}`).join('&');\n const url = new URL(path, LINKEDIN_API_BASE); url.search = query;\n const token = await this.accessToken();\n const response = await this.fetchImpl(url.href, {\n method, headers: { authorization: `Bearer ${token}`, 'Linkedin-Version': LINKEDIN_API_VERSION, 'X-Restli-Protocol-Version': '2.0.0',\n ...(body !== undefined ? { 'content-type': 'application/json' } : {}), ...(partial ? { 'X-RestLi-Method': 'PARTIAL_UPDATE' } : {}) },\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}), redirect: 'error', signal: AbortSignal.timeout(30_000),\n });\n if (response.status === 401 && method === 'GET' && retry && this.canRefresh()) {\n if (this.tokens.accessToken === token) this.tokens.expiresAt = 0;\n return this.request(path, method, params, body, partial, false);\n }\n if (!response.ok) {\n const advice = response.status === 403 ? ' Check Advertising API approval, r_ads_reporting/rw_ads scopes and account roles; reauthorization alone may not help.' : response.status === 401 ? ' Reauthorize your own LinkedIn app; a non-refreshable token must be replaced.' : '';\n throw new AdportError('PROVIDER_ERROR', `linkedin: HTTP ${response.status}.${advice}`);\n }\n return response;\n }\n private canRefresh() { return Boolean(this.tokens.refreshToken && this.credentials.clientId && this.credentials.clientSecret && (this.tokens.refreshExpiresAt === undefined || this.tokens.refreshExpiresAt > Date.now())); }\n private async accessToken(): Promise<string> {\n if (this.tokens.accessToken && (this.tokens.expiresAt === undefined || this.tokens.expiresAt > Date.now() + 60_000)) return this.tokens.accessToken;\n if (!this.canRefresh()) throw new AdportError('NOT_CONNECTED', 'linkedin: access token expired or missing; run adport connect linkedin with a fresh authorized token');\n if (!this.refreshing) this.refreshing = this.refresh().finally(() => { this.refreshing = undefined; });\n return this.refreshing;\n }\n private async refresh(): Promise<string> {\n const updated = await tokenRequest(new URLSearchParams({ grant_type: 'refresh_token', refresh_token: this.tokens.refreshToken!, client_id: this.credentials.clientId!, client_secret: this.credentials.clientSecret! }), this.fetchImpl);\n const tokens = { ...this.tokens, ...updated } as LinkedInTokens;\n // The refresh grant has a fixed lifetime. Missing TTL is not a renewal.\n if (this.tokens.refreshExpiresAt !== undefined && tokens.refreshExpiresAt !== undefined) tokens.refreshExpiresAt = Math.min(tokens.refreshExpiresAt, this.tokens.refreshExpiresAt);\n await this.credentials.onTokens?.(tokens);\n this.tokens = tokens;\n return tokens.accessToken;\n }\n}\n","import { z } from 'zod';\nimport { AdportError, resolveDateRange, type Account, type AdProvider, type MetricName, type NormalizedQuery, type Report, type ReportRow, type StandardActions, type WriteGuard, type WriteOperation, type WritePreview, type WriteResult } from '@adport/core';\nimport { LinkedInAdsClient, type RestliValue } from './client.js';\nimport { accountSchema, campaignSchema, createCampaignSchema, groupSchema, linkedinId, NON_DISCRIMINATION_NOTICE, NON_POLITICAL_CONSENT, reportRowSchema, setBudgetSchema, setStatusSchema } from './schemas.js';\n\ninterface Plan extends Omit<WritePreview, 'serverValidated'> { execute: () => Promise<string[]> }\nconst FIELDS = { spend: 'costInLocalCurrency', impressions: 'impressions', clicks: 'clicks', conversions: 'externalWebsiteConversions', conversion_value: 'conversionValueInLocalCurrency' } as const;\nconst DERIVED = { ctr: ['clicks', 'impressions', 100], cpc: ['spend', 'clicks', 1], cpm: ['spend', 'impressions', 1000], cpa: ['spend', 'conversions', 1], roas: ['conversion_value', 'spend', 1] } as const;\nconst STATUS = ['ACTIVE', 'PAUSED', 'ARCHIVED', 'COMPLETED', 'CANCELED', 'DRAFT', 'PENDING_DELETION', 'REMOVED'];\nconst ACCOUNT_URN = (id: string) => `urn:li:sponsoredAccount:${linkedinId.parse(id)}`;\n\nexport function decimalToMicros(amount: string): number {\n if (!/^\\d+(?:\\.\\d+)?$/.test(amount)) throw new AdportError('PROVIDER_ERROR', 'linkedin: invalid money amount');\n const [whole, fraction = ''] = amount.split('.');\n if (fraction.slice(6).replace(/0/g, '')) throw new AdportError('PROVIDER_ERROR', 'linkedin: budget precision exceeds integer micros');\n const value = BigInt(whole!) * 1_000_000n + BigInt(fraction.slice(0, 6).padEnd(6, '0'));\n if (value > BigInt(Number.MAX_SAFE_INTEGER)) throw new AdportError('PROVIDER_ERROR', 'linkedin: budget exceeds safe integer micros');\n return Number(value);\n}\nexport function microsToDecimal(value: number): string {\n if (!Number.isSafeInteger(value) || value < 0) throw new AdportError('INVALID_INPUT', 'linkedin: budget must be integer micros');\n const number = BigInt(value);\n return `${number / 1_000_000n}.${String(number % 1_000_000n).padStart(6, '0')}`;\n}\n\nexport class LinkedInAdsProvider implements AdProvider {\n readonly id = 'linkedin';\n constructor(private readonly client: LinkedInAdsClient) {}\n capabilities() { return { serverDryRun: false }; }\n standardActions(): StandardActions { return { pauseCampaign: (accountId, campaignId) => ({ tool: 'linkedin_set_campaign_status', input: { account_id: accountId, campaign_id: campaignId, status: 'PAUSED' } }) }; }\n private async search<T extends { id: number }>(path: string, schema: z.ZodType<T>, search?: RestliValue): Promise<T[]> {\n const params: Record<string, RestliValue> = { q: 'search', pageSize: 100, ...(search ? { search } : {}) };\n const pageSchema = z.object({ elements: z.array(schema), metadata: z.object({ nextPageToken: z.string().optional() }).optional() });\n const rows: T[] = [], tokens = new Set<string>(), seen = new Set<number>();\n while (true) {\n const page = await this.client.get(path, pageSchema, params);\n for (const row of page.elements) {\n if (seen.has(row.id)) throw new AdportError('PROVIDER_ERROR', 'linkedin: search repeated an entity');\n seen.add(row.id); rows.push(row);\n }\n const next = page.metadata?.nextPageToken;\n if (!next) return rows;\n if (tokens.has(next) || tokens.size >= 1000) throw new AdportError('PROVIDER_ERROR', 'linkedin: cursor pagination did not terminate');\n tokens.add(next); params.pageToken = next;\n }\n }\n async listAccounts(): Promise<Account[]> {\n return (await this.search('adAccounts', accountSchema)).map(a => ({ provider: this.id, id: String(a.id), name: a.name, currency: a.currency, status: a.status }));\n }\n async getAccount(accountId: string) {\n const data = await this.client.get(`adAccounts/${linkedinId.parse(accountId)}`, accountSchema);\n if (String(data.id) !== accountId) throw new AdportError('PROVIDER_ERROR', 'linkedin: account ID mismatch');\n return data;\n }\n async listCampaigns(accountId: string) {\n const rows = await this.search(`adAccounts/${linkedinId.parse(accountId)}/adCampaigns`, campaignSchema, { status: { values: STATUS } });\n if (rows.some(r => r.account !== ACCOUNT_URN(accountId))) throw new AdportError('PROVIDER_ERROR', 'linkedin: campaign account mismatch');\n return rows;\n }\n async listCampaignGroups(accountId: string) {\n const rows = await this.search(`adAccounts/${linkedinId.parse(accountId)}/adCampaignGroups`, groupSchema, { status: { values: ['ACTIVE', 'PAUSED', 'ARCHIVED', 'DRAFT', 'PENDING_DELETION', 'REMOVED'] } });\n if (rows.some(r => r.account !== ACCOUNT_URN(accountId))) throw new AdportError('PROVIDER_ERROR', 'linkedin: campaign group account mismatch');\n return rows;\n }\n async getCampaign(accountId: string, campaignId: string) {\n const data = await this.client.get(`adAccounts/${linkedinId.parse(accountId)}/adCampaigns/${linkedinId.parse(campaignId)}`, campaignSchema);\n if (String(data.id) !== campaignId || data.account !== ACCOUNT_URN(accountId)) throw new AdportError('PROVIDER_ERROR', 'linkedin: campaign account/ID mismatch');\n return data;\n }\n async report(query: NormalizedQuery): Promise<Report> {\n if (query.level === 'ad_group') throw new AdportError('INVALID_INPUT', 'linkedin: no native ad-group level; use campaign (LinkedIn campaign) or ad (creative). Campaign groups are listed separately.');\n const range = resolveDateRange(query.dateRange), start = z.iso.date().parse(range.start), end = z.iso.date().parse(range.end);\n if (end < start) throw new AdportError('INVALID_INPUT', 'linkedin: report end must be on/after start');\n const dateObject = (iso: string) => { const [year, month, day] = iso.split('-').map(Number); return { year: year!, month: month!, day: day! }; };\n const dateRange = { start: dateObject(start), end: dateObject(end) };\n const limit = query.limit ?? 1000;\n if (!Number.isSafeInteger(limit) || limit < 1) throw new AdportError('INVALID_INPUT', 'linkedin: report limit must be a positive integer');\n const fields = new Set<string>(['pivotValues', 'dateRange']);\n for (const metric of query.metrics) {\n if (metric in FIELDS) fields.add(FIELDS[metric as keyof typeof FIELDS]);\n else if (metric in DERIVED) for (const dependency of DERIVED[metric as keyof typeof DERIVED].slice(0, 2)) fields.add(FIELDS[dependency as keyof typeof FIELDS]);\n }\n if (fields.size === 2) throw new AdportError('INVALID_INPUT', 'linkedin: at least one supported metric is required');\n const pivot = { account: 'ACCOUNT', campaign: 'CAMPAIGN', ad: 'CREATIVE' }[query.level];\n const urnType = { account: 'sponsoredAccount', campaign: 'sponsoredCampaign', ad: 'sponsoredCreative' }[query.level];\n const rows: ReportRow[] = []; let capped = false;\n for (const id of [...new Set(query.accountIds ?? (await this.listAccounts()).map(a => a.id))]) {\n const accountId = linkedinId.parse(id), account = await this.getAccount(accountId);\n const campaigns = query.level === 'campaign' ? new Map((await this.listCampaigns(accountId)).map(c => [String(c.id), c])) : undefined;\n const data = await this.client.get('adAnalytics', z.object({ elements: z.array(reportRowSchema), paging: z.object({ links: z.array(z.object({ rel: z.string() })).optional() }).optional() }), {\n q: 'analytics', pivot, timeGranularity: 'ALL', dateRange, accounts: [ACCOUNT_URN(accountId)], fields: [...fields].join(','),\n });\n if (data.paging?.links?.some(link => link.rel === 'next')) throw new AdportError('PROVIDER_ERROR', 'linkedin: unexpected analytics pagination; refusing incomplete data');\n capped ||= data.elements.length >= 15_000;\n const seen = new Set<string>();\n for (const row of data.elements) {\n const urn = row.pivotValues[0]!, match = urn.match(new RegExp(`^urn:li:${urnType}:([1-9]\\\\d*)$`));\n if (!match) throw new AdportError('PROVIDER_ERROR', 'linkedin: unexpected analytics pivot');\n const entityId = match[1]!;\n if (seen.has(entityId) || (query.level === 'account' && entityId !== accountId) || (campaigns && !campaigns.has(entityId))) throw new AdportError('PROVIDER_ERROR', 'linkedin: incorrectly scoped or duplicate analytics row');\n seen.add(entityId);\n // Older ALL queries can be rounded to full months. Never label those\n // expanded dates as the narrower period the caller requested.\n if (['start', 'end'].some(bound => ['year', 'month', 'day'].some(part => row.dateRange[bound as 'start' | 'end'][part as 'year' | 'month' | 'day'] !== dateRange[bound as 'start' | 'end'][part as 'year' | 'month' | 'day']))) {\n throw new AdportError('PROVIDER_ERROR', 'linkedin: provider changed the reporting date range (older queries may round to months); request the returned month boundaries explicitly');\n }\n const campaign = campaigns?.get(entityId);\n rows.push({ provider: this.id, accountId, entity: { level: query.level, id: entityId, name: query.level === 'account' ? account.name : campaign?.name ?? entityId, ...(query.level === 'account' ? { status: account.status } : campaign ? { status: campaign.status } : {}) }, metrics: normalize(row, query.metrics) });\n if (rows.length > limit) return { rows: rows.slice(0, limit), truncated: true };\n }\n }\n return { rows, ...(capped ? { truncated: true } : {}) };\n }\n async previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview> {\n const { execute: _execute, ...preview } = await this.plan(op, guard); return { ...preview, serverValidated: false };\n }\n async applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult> { return { applied: true, resourceIds: await (await this.plan(op, guard)).execute() }; }\n private async plan(op: WriteOperation, guard: WriteGuard): Promise<Plan> {\n const accountId = linkedinId.parse(op.accountId), base = `adAccounts/${accountId}/adCampaigns`;\n if (op.provider !== this.id) throw new AdportError('INVALID_INPUT', 'linkedin: provider mismatch');\n if (op.tool === 'linkedin_create_campaign' && op.kind === 'create') {\n const input = createCampaignSchema.parse(op.payload);\n if (!input.daily_budget_micros && !input.total_budget_micros) throw new AdportError('INVALID_INPUT', 'linkedin: a daily or total campaign budget is required');\n if (input.type === 'DYNAMIC' && (!input.daily_budget_micros || !input.total_budget_micros || !input.format)) throw new AdportError('INVALID_INPUT', 'linkedin: dynamic campaigns require daily and total budgets and a format');\n if ((input.type === 'SPONSORED_UPDATES' || input.type === 'DYNAMIC' || input.objective_type === 'LEAD_GENERATION') && !input.associated_entity) throw new AdportError('INVALID_INPUT', 'linkedin: sponsored content, dynamic and lead-generation campaigns require an associated entity');\n if (input.total_budget_micros && !input.end_time) throw new AdportError('INVALID_INPUT', 'linkedin: lifetime campaign budgets require an end time');\n if (input.end_time && (!input.start_time || input.end_time <= input.start_time)) throw new AdportError('INVALID_INPUT', 'linkedin: scheduled end requires an earlier start time');\n const keys = input.targeting_criteria.include.and.flatMap(clause => Object.keys(clause.or));\n if (input.targeting_criteria.include.and.some(clause => !Object.keys(clause.or).length)) throw new AdportError('INVALID_INPUT', 'linkedin: targeting include clauses cannot be empty');\n if (!keys.includes('urn:li:adTargetingFacet:locations') && !keys.includes('urn:li:adTargetingFacet:profileLocations')) throw new AdportError('INVALID_INPUT', 'linkedin: targeting must include modern geo locations');\n if (keys.includes('urn:li:adTargetingFacet:locations') && keys.includes('urn:li:adTargetingFacet:profileLocations')) throw new AdportError('INVALID_INPUT', 'linkedin: choose locations or profileLocations, not both');\n for (const clause of input.targeting_criteria.include.and) for (const [facet, values] of Object.entries(clause.or)) {\n if (['urn:li:adTargetingFacet:locations', 'urn:li:adTargetingFacet:profileLocations'].includes(facet) && values.some(value => !/^urn:li:geo:[1-9]\\d*$/.test(value))) throw new AdportError('INVALID_INPUT', 'linkedin: use modern urn:li:geo location identifiers; legacy geo is no longer supported');\n }\n const account = await this.getAccount(accountId);\n const group = await this.client.get(`adAccounts/${accountId}/adCampaignGroups/${input.campaign_group_id}`, groupSchema);\n if (group.account !== ACCOUNT_URN(accountId) || String(group.id) !== input.campaign_group_id) throw new AdportError('PROVIDER_ERROR', 'linkedin: campaign group account/ID mismatch');\n if (group.budgetOptimization?.budgetOptimizationStrategy === 'DYNAMIC') throw new AdportError('INVALID_INPUT', 'linkedin: this group shares a dynamic budget; ordinary campaign budget creation is not supported for it');\n const status = guard.forcePausedCreation ? 'PAUSED' : input.status;\n const money = (amount: number) => ({ amount: microsToDecimal(amount), currencyCode: account.currency });\n const body = {\n account: ACCOUNT_URN(accountId), campaignGroup: `urn:li:sponsoredCampaignGroup:${input.campaign_group_id}`, name: input.name,\n type: input.type, objectiveType: input.objective_type, costType: input.cost_type, unitCost: money(input.unit_cost_micros), locale: input.locale,\n targetingCriteria: input.targeting_criteria, status, politicalIntent: 'NOT_POLITICAL', offsiteDeliveryEnabled: false, audienceExpansionEnabled: false,\n ...(input.associated_entity ? { associatedEntity: input.associated_entity } : {}), ...(input.format ? { format: input.format } : {}),\n ...(input.daily_budget_micros ? { dailyBudget: money(input.daily_budget_micros) } : {}),\n ...(input.total_budget_micros ? { totalBudget: money(input.total_budget_micros), pacingStrategy: 'LIFETIME' } : {}),\n ...(input.start_time ? { runSchedule: { start: input.start_time, ...(input.end_time ? { end: input.end_time } : {}) } } : {}),\n };\n return {\n summary: `Create LinkedIn campaign \"${input.name}\"`, changes: [NON_DISCRIMINATION_NOTICE, `Advertiser confirmation: ${NON_POLITICAL_CONSENT}`, `+ ${JSON.stringify(body)}`],\n coercions: input.status !== status ? ['status coerced to PAUSED by policy (paused_creation)'] : [],\n budgetDeltas: [ ...(input.daily_budget_micros ? [{ target: 'new campaign daily budget', toMicros: input.daily_budget_micros }] : []), ...(input.total_budget_micros ? [{ target: 'new campaign total budget', toMicros: input.total_budget_micros }] : []) ],\n execute: async () => [await this.client.create(base, body)],\n };\n }\n if (op.kind === 'update' && ['linkedin_set_campaign_status', 'linkedin_set_budget'].includes(op.tool)) {\n const input = op.tool === 'linkedin_set_budget' ? setBudgetSchema.parse(op.payload) : setStatusSchema.parse(op.payload);\n if ('status' in input && input.status === 'ACTIVE' && !input.non_political_consent) throw new AdportError('INVALID_INPUT', `linkedin: activation requires explicit advertiser consent: ${NON_POLITICAL_CONSENT}`);\n const current = await this.getCampaign(accountId, input.campaign_id);\n if ('budget_micros' in input) {\n const field = input.budget_type === 'DAILY' ? 'dailyBudget' : 'totalBudget', budget = current[field];\n if (!budget) throw new AdportError('INVALID_INPUT', `linkedin: campaign has no existing ${field}; this tool changes existing budget types only`);\n const fromMicros = decimalToMicros(budget.amount);\n return { summary: `Change LinkedIn campaign \"${current.name}\" budget`, changes: [`~ ${field}: ${budget.amount} → ${microsToDecimal(input.budget_micros)} ${budget.currencyCode}`], coercions: [],\n budgetDeltas: [{ target: `campaign ${current.id} ${field}`, fromMicros, toMicros: input.budget_micros }],\n execute: async () => { await this.client.update(`${base}/${current.id}`, { [field]: { amount: microsToDecimal(input.budget_micros), currencyCode: budget.currencyCode } }); return [String(current.id)]; },\n };\n }\n return { summary: `Change LinkedIn campaign \"${current.name}\" status`, changes: [`~ status: ${current.status} → ${input.status}`, ...(input.status === 'ACTIVE' ? [NON_DISCRIMINATION_NOTICE, `Advertiser confirmation: ${NON_POLITICAL_CONSENT}`] : [])], coercions: [], budgetDeltas: [],\n execute: async () => { await this.client.update(`${base}/${current.id}`, { status: input.status, ...(input.status === 'ACTIVE' ? { politicalIntent: 'NOT_POLITICAL' } : {}) }); return [String(current.id)]; },\n };\n }\n throw new AdportError('INVALID_INPUT', `linkedin: unsupported write ${op.tool}`);\n }\n}\n\nfunction normalize(row: z.infer<typeof reportRowSchema>, requested: MetricName[]) {\n const mapped: Partial<Record<MetricName, number>> = {};\n for (const [metric, field] of Object.entries(FIELDS)) {\n const value = row[field];\n if (value === undefined) continue;\n const number = Number(value);\n if (!Number.isFinite(number) || number < 0) throw new AdportError('PROVIDER_ERROR', `linkedin: invalid ${field} metric`);\n mapped[metric as MetricName] = number;\n }\n for (const [metric, [numerator, denominator, factor]] of Object.entries(DERIVED)) if (mapped[numerator] !== undefined && mapped[denominator] !== undefined) mapped[metric as MetricName] = mapped[denominator] ? mapped[numerator]! / mapped[denominator]! * factor : 0;\n return Object.fromEntries(requested.filter(metric => mapped[metric] !== undefined).map(metric => [metric, mapped[metric]]));\n}\n","import { z } from 'zod';\n\nexport const linkedinId = z.string().regex(/^[1-9]\\d*$/);\nconst numericId = z.number().int().positive().safe();\nexport const accountUrn = z.string().regex(/^urn:li:sponsoredAccount:[1-9]\\d*$/);\nconst decimal = z.string().regex(/^\\d+(?:\\.\\d+)?$/);\nexport const moneySchema = z.object({ amount: decimal, currencyCode: z.string().regex(/^[A-Z]{3}$/) });\nexport const accountSchema = z.looseObject({ id: numericId, name: z.string(), currency: z.string().regex(/^[A-Z]{3}$/), status: z.string(), test: z.boolean().optional() });\nexport const campaignSchema = z.looseObject({ id: numericId, name: z.string(), account: accountUrn, status: z.string(), dailyBudget: moneySchema.optional(), totalBudget: moneySchema.optional(), campaignGroup: z.string().regex(/^urn:li:sponsoredCampaignGroup:[1-9]\\d*$/).optional() });\nexport const groupSchema = z.looseObject({ id: numericId, name: z.string(), account: accountUrn, status: z.string(), budgetOptimization: z.looseObject({ budgetOptimizationStrategy: z.string().optional() }).optional() });\nconst date = z.object({ year: z.number().int(), month: z.number().int().min(1).max(12), day: z.number().int().min(1).max(31) });\nexport const reportRowSchema = z.looseObject({\n pivotValues: z.array(z.string()).length(1), dateRange: z.object({ start: date, end: date }),\n costInLocalCurrency: decimal.optional(), conversionValueInLocalCurrency: decimal.optional(),\n impressions: z.number().int().nonnegative().safe().optional(), clicks: z.number().int().nonnegative().safe().optional(), externalWebsiteConversions: z.number().int().nonnegative().safe().optional(),\n});\nexport const NON_DISCRIMINATION_NOTICE = 'LinkedIn tools may not be used to discriminate based on personal characteristics such as gender, age, race, or ethnicity. Learn more: https://www.linkedin.com/legal/ads-policy';\nexport const NON_POLITICAL_CONSENT = 'I confirm this is not political advertising. None of my ads qualify as political advertising under the law of the targeted countries, including EU law for ads targeted to the EU.';\nconst facets = z.record(z.string().regex(/^urn:li:adTargetingFacet:[a-zA-Z]+$/), z.array(z.string().regex(/^urn:li:[a-zA-Z]+:[a-zA-Z0-9_()-]+$/)).min(1));\nexport const targetingSchema = z.object({ include: z.object({ and: z.array(z.object({ or: facets })).min(1) }), exclude: z.object({ or: facets }).optional() });\nconst micros = z.number().int().positive().safe();\nexport const createCampaignSchema = z.object({\n name: z.string().trim().min(1).max(200), campaign_group_id: linkedinId,\n type: z.enum(['TEXT_AD', 'SPONSORED_UPDATES', 'SPONSORED_INMAILS', 'DYNAMIC']),\n objective_type: z.enum(['BRAND_AWARENESS', 'ENGAGEMENT', 'JOB_APPLICANTS', 'LEAD_GENERATION', 'WEBSITE_CONVERSIONS', 'WEBSITE_VISITS', 'VIDEO_VIEWS']),\n cost_type: z.enum(['CPM', 'CPC', 'CPV']), unit_cost_micros: micros,\n daily_budget_micros: micros.optional(), total_budget_micros: micros.optional(),\n locale: z.object({ country: z.string().regex(/^[A-Z]{2}$/), language: z.string().regex(/^[a-z]{2}$/) }),\n targeting_criteria: targetingSchema,\n associated_entity: z.string().regex(/^urn:li:(organization|person):[a-zA-Z0-9_-]+$/).optional(),\n format: z.string().regex(/^[A-Z_]+$/).optional(),\n start_time: z.number().int().positive().safe().optional(), end_time: z.number().int().positive().safe().optional(),\n status: z.enum(['PAUSED', 'ACTIVE']).default('PAUSED'),\n non_political_consent: z.literal(true).describe(`Explicit advertiser confirmation required: ${NON_POLITICAL_CONSENT}`),\n});\nexport const setStatusSchema = z.object({ campaign_id: linkedinId, status: z.enum(['PAUSED', 'ACTIVE']), non_political_consent: z.literal(true).optional().describe(`Required when activating: ${NON_POLITICAL_CONSENT}`) });\nexport const setBudgetSchema = z.object({ campaign_id: linkedinId, budget_type: z.enum(['DAILY', 'TOTAL']), budget_micros: micros });\n","import { z } from 'zod';\nimport { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport type { LinkedInAdsProvider } from './provider.js';\nimport { createCampaignSchema, linkedinId, NON_DISCRIMINATION_NOTICE, setBudgetSchema, setStatusSchema } from './schemas.js';\n\nexport function linkedinTools(provider: LinkedInAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'linkedin_list_campaigns', namespace: 'linkedin', description: 'List LinkedIn campaigns, including inactive campaigns.', input: z.object({ account_id: linkedinId }), annotations: { readOnly: true }, handler: input => provider.listCampaigns(input.account_id) }),\n defineTool({ name: 'linkedin_list_campaign_groups', namespace: 'linkedin', description: 'List LinkedIn campaign groups to select a parent for campaign creation.', input: z.object({ account_id: linkedinId }), annotations: { readOnly: true }, handler: input => provider.listCampaignGroups(input.account_id) }),\n guardedWriteTool({ name: 'linkedin_create_campaign', namespace: 'linkedin', provider: 'linkedin', kind: 'create', description: `Create a paused LinkedIn campaign with account-currency budgets in micros. Explicit non-political advertiser consent required. Preview is local. ${NON_DISCRIMINATION_NOTICE}`, payload: createCampaignSchema }),\n guardedWriteTool({ name: 'linkedin_set_campaign_status', namespace: 'linkedin', provider: 'linkedin', kind: 'update', description: 'Pause or activate a LinkedIn campaign. Activation requires explicit non-political advertiser consent.', payload: setStatusSchema }),\n guardedWriteTool({ name: 'linkedin_set_budget', namespace: 'linkedin', provider: 'linkedin', kind: 'update', description: 'Change an existing daily or total LinkedI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B,WAAW,CAAC;AAC3E,SAAO,EAAE,UAAU,OAAO,cAAc,QAAQ,EAAE;AACpD;","names":["AdportError","z","AdportError","z","AdportError","z","z","z","AdportError"]}
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@adport/provider-linkedin",
3
+ "version": "0.6.0",
4
+ "description": "LinkedIn 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
+ "zod": "^4.4.3",
20
+ "@adport/core": "0.6.0"
21
+ },
22
+ "devDependencies": {
23
+ "@types/node": "^26.1.2",
24
+ "tsup": "^8.3.0",
25
+ "typescript": "^5.8.0",
26
+ "vitest": "^4.1.10"
27
+ },
28
+ "scripts": {
29
+ "build": "tsup src/index.ts --format esm --dts --sourcemap --clean",
30
+ "test": "vitest run",
31
+ "typecheck": "tsc --noEmit"
32
+ }
33
+ }