@adport/provider-tiktok 0.9.0 → 0.11.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/dist/index.d.ts +65 -24
- package/dist/index.js +384 -266
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -72,7 +72,8 @@ var TikTokClient = class {
|
|
|
72
72
|
}
|
|
73
73
|
const envelope = JSON.parse(raw);
|
|
74
74
|
if (envelope.code !== 0) {
|
|
75
|
-
const
|
|
75
|
+
const pixelPermission = ["pixel/list", "pixel/event/stats"].includes(path2?.replace(/^\/|\/$/g, "") ?? "") && envelope.code === 40001;
|
|
76
|
+
const hint = pixelPermission ? "Pixel access was denied. Check the developer app\u2019s Pixel/measurement permission and this advertiser\u2019s grant. After the app gains approval, reconnect TikTok in Adport Cloud (or run `adport connect tiktok`) and select the same advertiser. Reconnecting alone cannot add an unapproved app permission." : CODE_HINTS[envelope.code];
|
|
76
77
|
throw new AdportError(
|
|
77
78
|
"PROVIDER_ERROR",
|
|
78
79
|
`TikTok API error ${envelope.code}: ${envelope.message}${hint ? `
|
|
@@ -86,7 +87,7 @@ var TikTokClient = class {
|
|
|
86
87
|
|
|
87
88
|
// src/provider.ts
|
|
88
89
|
import {
|
|
89
|
-
AdportError as
|
|
90
|
+
AdportError as AdportError22,
|
|
90
91
|
LocalMediaResolver,
|
|
91
92
|
resolveDateRange
|
|
92
93
|
} from "@adport/core";
|
|
@@ -1333,21 +1334,21 @@ function tiktokAutomatedRuleTools(provider) {
|
|
|
1333
1334
|
}
|
|
1334
1335
|
|
|
1335
1336
|
// src/catalogs.ts
|
|
1336
|
-
import { createHash as
|
|
1337
|
-
import { AdportError as
|
|
1338
|
-
import { z as
|
|
1337
|
+
import { createHash as createHash14 } from "crypto";
|
|
1338
|
+
import { AdportError as AdportError20 } from "@adport/core";
|
|
1339
|
+
import { z as z22 } from "zod";
|
|
1339
1340
|
|
|
1340
1341
|
// src/catalog-tools.ts
|
|
1341
1342
|
import { creativesOutput, defineTool as defineTool4, guardedWriteTool as guardedWriteTool3 } from "@adport/core";
|
|
1342
|
-
import { z as
|
|
1343
|
+
import { z as z21 } from "zod";
|
|
1343
1344
|
|
|
1344
1345
|
// src/catalog-schema.ts
|
|
1345
1346
|
import { z as z9 } from "zod";
|
|
1346
1347
|
var catalogId = z9.string().regex(/^\d{1,30}$/);
|
|
1347
1348
|
var catalogInput = z9.object({ account_id: catalogId, bc_id: catalogId, catalog_id: catalogId }).strict();
|
|
1348
|
-
var catalogPermissionSelection = z9.object({ account_id: catalogId, bc_id: catalogId, catalog_id: catalogId.optional(), resource_kind: z9.enum(["catalog", "catalog_creation"]).optional() }).strict();
|
|
1349
|
-
var validCatalogPermission = (input) => input.resource_kind === "catalog_creation" ? !input.catalog_id && (!input.mode || ["none", "create"].includes(input.mode)) : !!input.catalog_id && input.mode
|
|
1350
|
-
var catalogPermissionSnapshot = catalogPermissionSelection.refine(validCatalogPermission, "Choose an exact catalog or creation delegation without a catalog ID");
|
|
1349
|
+
var catalogPermissionSelection = z9.object({ account_id: catalogId, bc_id: catalogId, catalog_id: catalogId.optional(), resource_kind: z9.enum(["catalog", "catalog_creation", "catalog_migration"]).optional() }).strict();
|
|
1350
|
+
var validCatalogPermission = (input) => input.resource_kind === "catalog_creation" ? !input.catalog_id && (!input.mode || ["none", "create"].includes(input.mode)) : input.resource_kind === "catalog_migration" ? !!input.catalog_id && (!input.mode || input.mode === "none" || input.mode === "migrate" && input.acknowledge_source_ownership === true && input.acknowledge_shared_effects === true) : !!input.catalog_id && (!input.mode || ["none", "read", "write"].includes(input.mode));
|
|
1351
|
+
var catalogPermissionSnapshot = catalogPermissionSelection.refine(validCatalogPermission, "Choose an exact catalog/transfer, or creation delegation without a catalog ID");
|
|
1351
1352
|
|
|
1352
1353
|
// src/catalog-product-sets.ts
|
|
1353
1354
|
import { createHash as createHash6 } from "crypto";
|
|
@@ -1561,14 +1562,14 @@ var TikTokCatalogProductSets = class {
|
|
|
1561
1562
|
await this.authorizeParent(scope, true);
|
|
1562
1563
|
const current = (await this.native(scope, input.product_set_id))[0];
|
|
1563
1564
|
if (hash4(scope, current) !== input.expected_configuration_hash) throw new AdportError10("INVALID_INPUT", "Product-set configuration changed. Read and preview it again.");
|
|
1564
|
-
const
|
|
1565
|
+
const notes7 = ["The set may be reused by other ads or accounts. Only its name changes; filter conditions are preserved.", "Preview is local. TikTok checks native eligibility on apply. No ads are activated or tracking events sent.", "An uncertain result retains the known set ID. Inspect it before another write; never replay automatically."];
|
|
1565
1566
|
return {
|
|
1566
1567
|
summary: `Rename TikTok product set ${current.product_set_name}`,
|
|
1567
1568
|
changes: [`~ Product-set name ${JSON.stringify(current.product_set_name)} \u2192 ${JSON.stringify(input.product_set_name)}`],
|
|
1568
1569
|
coercions: [],
|
|
1569
1570
|
budgetDeltas: [],
|
|
1570
|
-
notes:
|
|
1571
|
-
review: { provider: "tiktok", accountId: scope.account_id, kind: "update", title: "Rename product set", subject: current.product_set_name, fields: [{ label: "Name", before: current.product_set_name, after: input.product_set_name }, { label: "Catalog", after: input.catalog_id }, { label: "Product set", after: input.product_set_id }], notices:
|
|
1571
|
+
notes: notes7,
|
|
1572
|
+
review: { provider: "tiktok", accountId: scope.account_id, kind: "update", title: "Rename product set", subject: current.product_set_name, fields: [{ label: "Name", before: current.product_set_name, after: input.product_set_name }, { label: "Catalog", after: input.catalog_id }, { label: "Product set", after: input.product_set_id }], notices: notes7 },
|
|
1572
1573
|
execute: async () => {
|
|
1573
1574
|
await this.authorizeParent(scope, true);
|
|
1574
1575
|
try {
|
|
@@ -1606,14 +1607,14 @@ var TikTokCatalogProductSets = class {
|
|
|
1606
1607
|
return { file, count: skus.size };
|
|
1607
1608
|
};
|
|
1608
1609
|
const prepared = await prepare();
|
|
1609
|
-
const
|
|
1610
|
+
const notes7 = ["Creates an E-commerce set from the exact approved CSV; no ads are activated or budgets changed.", "Adport caps the template at 5,000 SKU rows. TikTok checks SKU eligibility and membership on apply; independent readback confirms the set ID/name, not full membership or ingestion.", "No automatic retry. Reconcile an uncertain creation by its known ID or unique name before another upload."];
|
|
1610
1611
|
return {
|
|
1611
1612
|
summary: `Create TikTok product set ${input.product_set_name} from CSV`,
|
|
1612
1613
|
changes: [`+ Product set ${JSON.stringify(input.product_set_name)} from ${prepared.count} SKU rows`, `+ File ${JSON.stringify(prepared.file.name)}; ${prepared.file.bytes.byteLength} bytes; SHA-256 ${prepared.file.sha256}`],
|
|
1613
1614
|
coercions: [],
|
|
1614
1615
|
budgetDeltas: [],
|
|
1615
|
-
notes:
|
|
1616
|
-
review: { provider: "tiktok", accountId: scope.account_id, kind: "create", title: "Upload product set", subject: input.product_set_name, fields: [{ label: "Catalog", after: input.catalog_id }, { label: "File", after: prepared.file.name }, { label: "SKU rows", after: String(prepared.count) }, { label: "SHA-256", after: prepared.file.sha256 }], notices:
|
|
1616
|
+
notes: notes7,
|
|
1617
|
+
review: { provider: "tiktok", accountId: scope.account_id, kind: "create", title: "Upload product set", subject: input.product_set_name, fields: [{ label: "Catalog", after: input.catalog_id }, { label: "File", after: prepared.file.name }, { label: "SKU rows", after: String(prepared.count) }, { label: "SHA-256", after: prepared.file.sha256 }], notices: notes7 },
|
|
1617
1618
|
execute: async () => {
|
|
1618
1619
|
const { file } = await prepare();
|
|
1619
1620
|
const form = new FormData();
|
|
@@ -1643,14 +1644,14 @@ var TikTokCatalogProductSets = class {
|
|
|
1643
1644
|
if (parent.configuration_hash !== input.expected_catalog_hash) throw new AdportError10("INVALID_INPUT", "Catalog configuration changed. Read the catalog and review creation again.");
|
|
1644
1645
|
};
|
|
1645
1646
|
await verifyParent();
|
|
1646
|
-
const
|
|
1647
|
+
const notes7 = ["Creates a filter-defined set in the selected catalog; it does not create or activate an ad.", "Field names and catalog-specific values are checked by TikTok on apply; this is a local preview. Adport allows up to 1,024 combined values.", "No automatic retry. An unknown creation outcome must be reconciled before another create."];
|
|
1647
1648
|
return {
|
|
1648
1649
|
summary: `Create TikTok product set ${input.product_set_name}`,
|
|
1649
1650
|
changes: [`+ Product set ${JSON.stringify(input.product_set_name)}`, `+ Product selection ${canonical6(input.conditions)}`],
|
|
1650
1651
|
coercions: [],
|
|
1651
1652
|
budgetDeltas: [],
|
|
1652
|
-
notes:
|
|
1653
|
-
review: { provider: "tiktok", accountId: scope.account_id, kind: "create", title: "Create product set", subject: input.product_set_name, fields: [{ label: "Catalog", after: input.catalog_id }, { label: "Product selection", after: describeProductSetConditions(input.conditions), format: "text" }], notices:
|
|
1653
|
+
notes: notes7,
|
|
1654
|
+
review: { provider: "tiktok", accountId: scope.account_id, kind: "create", title: "Create product set", subject: input.product_set_name, fields: [{ label: "Catalog", after: input.catalog_id }, { label: "Product selection", after: describeProductSetConditions(input.conditions), format: "text" }], notices: notes7 },
|
|
1654
1655
|
execute: async () => {
|
|
1655
1656
|
await verifyParent();
|
|
1656
1657
|
let createdId;
|
|
@@ -1671,14 +1672,14 @@ var TikTokCatalogProductSets = class {
|
|
|
1671
1672
|
await this.authorizeParent(scope, true);
|
|
1672
1673
|
const current = (await this.native(scope, input.product_set_id))[0];
|
|
1673
1674
|
if (hash4(scope, current) !== input.expected_configuration_hash) throw new AdportError10("INVALID_INPUT", "Product-set configuration changed. Read and review it again.");
|
|
1674
|
-
const
|
|
1675
|
+
const notes7 = ["Replaces the complete filter definition. Existing ads using this shared set may select different products after apply.", "The name is preserved. No ad is activated and no budget or tracking event is changed.", "Catalog-specific fields and values are checked by TikTok on apply; preview is local. No automatic retry after an uncertain result."];
|
|
1675
1676
|
return {
|
|
1676
1677
|
summary: `Change TikTok product selection for ${current.product_set_name}`,
|
|
1677
1678
|
changes: [`~ Product selection ${canonical6(current.conditions)} \u2192 ${canonical6(input.conditions)}`],
|
|
1678
1679
|
coercions: [],
|
|
1679
1680
|
budgetDeltas: [],
|
|
1680
|
-
notes:
|
|
1681
|
-
review: { provider: "tiktok", accountId: scope.account_id, kind: "update", title: "Change product selection", subject: current.product_set_name, fields: [{ label: "Product selection", before: describeProductSetConditions(current.conditions), after: describeProductSetConditions(input.conditions), format: "text" }, { label: "Catalog", after: input.catalog_id }, { label: "Product set", after: input.product_set_id }], notices:
|
|
1681
|
+
notes: notes7,
|
|
1682
|
+
review: { provider: "tiktok", accountId: scope.account_id, kind: "update", title: "Change product selection", subject: current.product_set_name, fields: [{ label: "Product selection", before: describeProductSetConditions(current.conditions), after: describeProductSetConditions(input.conditions), format: "text" }, { label: "Catalog", after: input.catalog_id }, { label: "Product set", after: input.product_set_id }], notices: notes7 },
|
|
1682
1683
|
execute: async () => {
|
|
1683
1684
|
await this.authorizeParent(scope, true);
|
|
1684
1685
|
try {
|
|
@@ -1703,14 +1704,14 @@ var TikTokCatalogProductSets = class {
|
|
|
1703
1704
|
current.push(row3);
|
|
1704
1705
|
}
|
|
1705
1706
|
const ids2 = current.map((row3) => row3.product_set_id);
|
|
1706
|
-
const
|
|
1707
|
+
const notes7 = ["Permanently deletes the selected shared set definitions. Existing ads may reference them; there is no automatic restoration.", "The full selected set list and each configuration hash are checked before apply. TikTok checks native dependencies and eligibility.", "No automatic retry after a partial or uncertain result. Reconcile every known ID before another delete."];
|
|
1707
1708
|
return {
|
|
1708
1709
|
summary: `Delete ${current.length} TikTok product set${current.length === 1 ? "" : "s"}`,
|
|
1709
1710
|
changes: current.map((row3) => `- Product set ${row3.product_set_id}: ${JSON.stringify(row3.product_set_name)}`),
|
|
1710
1711
|
coercions: [],
|
|
1711
1712
|
budgetDeltas: [],
|
|
1712
|
-
notes:
|
|
1713
|
-
review: { provider: "tiktok", accountId: scope.account_id, kind: "remove", title: "Delete product sets", subject: current.length === 1 ? current[0].product_set_name : `${current.length} product sets`, fields: current.map((row3) => ({ label: `Product set ${row3.product_set_id}`, before: row3.product_set_name, after: "Permanently deleted" })), notices:
|
|
1713
|
+
notes: notes7,
|
|
1714
|
+
review: { provider: "tiktok", accountId: scope.account_id, kind: "remove", title: "Delete product sets", subject: current.length === 1 ? current[0].product_set_name : `${current.length} product sets`, fields: current.map((row3) => ({ label: `Product set ${row3.product_set_id}`, before: row3.product_set_name, after: "Permanently deleted" })), notices: notes7 },
|
|
1714
1715
|
execute: async () => {
|
|
1715
1716
|
await this.authorizeParent(scope, true);
|
|
1716
1717
|
try {
|
|
@@ -1729,7 +1730,7 @@ var TikTokCatalogProductSets = class {
|
|
|
1729
1730
|
|
|
1730
1731
|
// src/catalog-feeds.ts
|
|
1731
1732
|
import { createHash as createHash7 } from "crypto";
|
|
1732
|
-
import { AdportError as AdportError11 } from "@adport/core";
|
|
1733
|
+
import { AdportError as AdportError11, hostedFeedUrl } from "@adport/core";
|
|
1733
1734
|
import { z as z12 } from "zod";
|
|
1734
1735
|
var hash5 = z12.string().regex(/^[a-f0-9]{64}$/);
|
|
1735
1736
|
var nativeId5 = z12.union([catalogId, z12.number().int().positive().safe()]).transform(String);
|
|
@@ -1787,6 +1788,9 @@ var catalogFeedUpdate = payload.extend({
|
|
|
1787
1788
|
acknowledge_shared_effects: z12.literal(true),
|
|
1788
1789
|
acknowledge_automatic_processing: z12.literal(true)
|
|
1789
1790
|
}).strict();
|
|
1791
|
+
var hostedSchedule = schedule.safeExtend({ source: z12.strictObject({ uri: hostedFeedUrl }) });
|
|
1792
|
+
var hostedCatalogFeedCreate = catalogFeedCreate.extend({ schedule_param: hostedSchedule.optional() });
|
|
1793
|
+
var hostedCatalogFeedUpdate = catalogFeedUpdate.extend({ schedule_param: hostedSchedule.optional() });
|
|
1790
1794
|
var catalogFeedSwitch = payload.extend({ feed_id: catalogId, status: z12.enum(["ON", "OFF"]), expected_configuration_hash: hash5, acknowledge_shared_effects: z12.literal(true), acknowledge_automatic_processing: z12.literal(true) }).strict();
|
|
1791
1795
|
var catalogFeedDelete = payload.extend({ feed_id: catalogId, expected_configuration_hash: hash5, acknowledge_shared_effects: z12.literal(true) }).strict();
|
|
1792
1796
|
var nativeSchedule = z12.looseObject({
|
|
@@ -1916,15 +1920,15 @@ var TikTokCatalogFeeds = class {
|
|
|
1916
1920
|
if (op.provider !== "tiktok" || !Object.hasOwn(kinds, op.tool) || op.kind !== kinds[op.tool]) throw new AdportError11("INVALID_INPUT", "TikTok feed operation/provider kind mismatch.");
|
|
1917
1921
|
const create = op.tool === "tiktok_create_catalog_feed", input = create ? catalogFeedCreate.parse(op.payload) : op.tool === "tiktok_update_catalog_feed" ? catalogFeedUpdate.parse(op.payload) : op.tool === "tiktok_set_catalog_feed_schedule_status" ? catalogFeedSwitch.parse(op.payload) : catalogFeedDelete.parse(op.payload);
|
|
1918
1922
|
const scope = catalogInput.parse({ account_id: op.accountId, bc_id: input.bc_id, catalog_id: input.catalog_id }), parent = await this.authorizeParent(scope, true);
|
|
1919
|
-
const review = (title2, subject, fields2,
|
|
1923
|
+
const review = (title2, subject, fields2, notes8) => ({ provider: "tiktok", accountId: scope.account_id, kind: op.kind, title: title2, subject, fields: [{ label: "Catalog", after: input.catalog_id }, ...fields2], notices: notes8 });
|
|
1920
1924
|
if ("expected_catalog_hash" in input) {
|
|
1921
1925
|
if (input.expected_catalog_hash !== parent.configuration_hash) throw new AdportError11("INVALID_INPUT", "Catalog configuration changed. Read and review feed creation again.");
|
|
1922
1926
|
if (input.feed_type === "COUNTRY_FEED" && parent.catalog_conf.is_multi_country !== true) throw new AdportError11("INVALID_INPUT", "A country feed requires a verified multi-country catalog. Native existing-product eligibility is checked on apply.");
|
|
1923
1927
|
const sourceSecrets = input.schedule_param ? [input.schedule_param.source.uri, input.schedule_param.source.username, input.schedule_param.source.password].filter((item) => typeof item === "string" && item.length > 0) : [];
|
|
1924
1928
|
const displayName = sourceSecrets.reduce((name4, secret) => name4.replaceAll(secret, "[redacted]"), input.feed_name);
|
|
1925
1929
|
const fields2 = [{ label: "Name", after: displayName }, { label: "Update mode", after: input.update_mode }, ...input.feed_type ? [{ label: "Feed type", after: input.feed_type }] : [], ...scheduleFields(input.schedule_param)];
|
|
1926
|
-
const
|
|
1927
|
-
return { summary: `Create TikTok catalog feed ${displayName}`, changes: fields2.map((field) => `+ ${field.label}: ${JSON.stringify(field.after)}`), coercions: [], budgetDeltas: [], notes:
|
|
1930
|
+
const notes8 = [input.schedule_param ? "Supplying a source schedule can start automatic native product processing immediately. OVERWRITE can remove products missing from the source." : "No source schedule is supplied. The created feed must remain OFF with no source URI.", "Country feeds also require existing products; native eligibility is checked on apply.", ...commonNotes];
|
|
1931
|
+
return { summary: `Create TikTok catalog feed ${displayName}`, changes: fields2.map((field) => `+ ${field.label}: ${JSON.stringify(field.after)}`), coercions: [], budgetDeltas: [], notes: notes8, review: review("Create catalog feed", displayName, fields2, notes8), execute: async () => {
|
|
1928
1932
|
const fresh = await this.authorizeParent(scope, true);
|
|
1929
1933
|
if (fresh.configuration_hash !== input.expected_catalog_hash) throw new AdportError11("INVALID_INPUT", "Catalog changed before creating the feed. Review again.");
|
|
1930
1934
|
let createdId;
|
|
@@ -1942,12 +1946,12 @@ var TikTokCatalogFeeds = class {
|
|
|
1942
1946
|
}
|
|
1943
1947
|
const current = (await this.native(scope, input.feed_id))[0], name3 = publicText(current.feed_name, current);
|
|
1944
1948
|
if (input.expected_configuration_hash !== configurationHash(scope, current)) throw new AdportError11("INVALID_INPUT", "Feed configuration changed. Read and review it again.");
|
|
1945
|
-
let path2, body, expected = config(current), fields,
|
|
1949
|
+
let path2, body, expected = config(current), fields, notes7;
|
|
1946
1950
|
if (op.tool === "tiktok_delete_catalog_feed") {
|
|
1947
1951
|
path2 = "catalog/feed/delete";
|
|
1948
1952
|
body = { bc_id: input.bc_id, catalog_id: input.catalog_id, feed_id: input.feed_id };
|
|
1949
1953
|
fields = [{ label: "Feed", before: name3, after: "Permanently deleted" }];
|
|
1950
|
-
|
|
1954
|
+
notes7 = ["Permanently removes this shared feed. Review dependent catalog products and ads; no restoration or compensating write is automatic.", ...commonNotes];
|
|
1951
1955
|
} else if (op.tool === "tiktok_set_catalog_feed_schedule_status") {
|
|
1952
1956
|
const targetStatus = catalogFeedSwitch.parse(input).status;
|
|
1953
1957
|
if (!current.status || current.status === targetStatus) throw new AdportError11("INVALID_INPUT", "Schedule status must be known and change to the opposite ON/OFF value.");
|
|
@@ -1957,7 +1961,7 @@ var TikTokCatalogFeeds = class {
|
|
|
1957
1961
|
body = { bc_id: input.bc_id, catalog_id: input.catalog_id, feed_id: input.feed_id, status: targetStatus };
|
|
1958
1962
|
expected = { ...expected, status: targetStatus };
|
|
1959
1963
|
fields = [{ label: "Automatic processing", before: current.status, after: targetStatus }, { label: "Source", after: { origin: origin(source2?.uri), fingerprint: source2?.uri ? digest5(source2.uri) : "Not configured" } }];
|
|
1960
|
-
|
|
1964
|
+
notes7 = ["ON resumes automatic product processing and may change products selected by existing ads. OFF stops future scheduled runs; it does not undo previous imports.", ...commonNotes];
|
|
1961
1965
|
} else {
|
|
1962
1966
|
const update = catalogFeedUpdate.parse(input);
|
|
1963
1967
|
path2 = "catalog/feed/update";
|
|
@@ -1965,10 +1969,10 @@ var TikTokCatalogFeeds = class {
|
|
|
1965
1969
|
expected = { ...expected, schedule: { ...expected.schedule, update_mode: update.update_mode } };
|
|
1966
1970
|
if (update.schedule_param) expected.schedule = { ...expected.schedule, ...scheduleConfig({ ...update.schedule_param, uri: update.schedule_param.source.uri, update_mode: update.update_mode }) };
|
|
1967
1971
|
fields = [{ label: "Update mode", before: current.last_update_param?.update_mode ?? "Not reported", after: update.update_mode }, ...scheduleFields(update.schedule_param, current)];
|
|
1968
|
-
|
|
1972
|
+
notes7 = ["Replaces the supplied source/schedule configuration. Existing automatic runs can use it immediately; OVERWRITE can remove products missing from the source.", "Supply any required source authentication explicitly when replacing the schedule. Native credential values are unavailable for preservation/readback.", ...commonNotes];
|
|
1969
1973
|
}
|
|
1970
1974
|
const remove = op.kind === "remove", title = remove ? "Delete catalog feed" : "status" in input ? "Change feed schedule status" : "Update catalog feed";
|
|
1971
|
-
return { summary: `${title} ${name3}`, changes: fields.map((field) => `${remove ? "-" : "~"} ${field.label}: ${JSON.stringify(field.after)}`), coercions: [], budgetDeltas: [], notes:
|
|
1975
|
+
return { summary: `${title} ${name3}`, changes: fields.map((field) => `${remove ? "-" : "~"} ${field.label}: ${JSON.stringify(field.after)}`), coercions: [], budgetDeltas: [], notes: notes7, review: review(title, name3, fields, notes7), execute: async () => {
|
|
1972
1976
|
await this.authorizeParent(scope, true);
|
|
1973
1977
|
try {
|
|
1974
1978
|
const raw = await this.client.post(path2, body);
|
|
@@ -2207,14 +2211,14 @@ var TikTokCatalogProducts = class {
|
|
|
2207
2211
|
return { parent, feed: feed2, file, rowCount, columns: header.length };
|
|
2208
2212
|
};
|
|
2209
2213
|
const initial = await prepare();
|
|
2210
|
-
const
|
|
2214
|
+
const notes7 = ["Submits a one-time asynchronous import into this existing feed. Native processing validates catalog-specific columns, feed ownership and product eligibility; local CSV validation does not certify the provider template.", input.update_mode === "OVERWRITE" ? "OVERWRITE removes existing feed products missing from this file and can change ads using them." : "INCREMENTAL adds products and updates matching products; products omitted from the CSV remain.", "This request does not change the feed\u2019s saved update mode or activate ads. Feed scheduling is managed separately; read fresh feed state before changing automation.", "The result is an accepted task ID, not completed ingestion. Read tiktok_catalog_product_log until terminal and inspect item errors. Never automatically replay an uncertain import."];
|
|
2211
2215
|
return {
|
|
2212
2216
|
summary: `Import ${initial.rowCount} product rows into TikTok feed ${input.feed_id}`,
|
|
2213
2217
|
changes: [`~ One-time ${input.update_mode} product import into ${initial.feed.feed_type} ${input.feed_id}`, `+ CSV ${JSON.stringify(initial.file.name)}; ${initial.file.bytes.byteLength} bytes; SHA-256 ${initial.file.sha256}`],
|
|
2214
2218
|
coercions: [],
|
|
2215
2219
|
budgetDeltas: [],
|
|
2216
|
-
notes:
|
|
2217
|
-
review: { provider: "tiktok", accountId: scope.account_id, kind: "update", title: "Import catalog file", subject: initial.file.name, fields: [{ label: "Catalog", after: input.catalog_id }, { label: "Feed", after: input.feed_id }, { label: "Feed type", after: initial.feed.feed_type }, { label: "Feed schedule", after: initial.feed.status }, { label: "Import mode", after: input.update_mode }, { label: "Product rows", after: String(initial.rowCount) }, { label: "CSV columns", after: String(initial.columns) }, { label: "SHA-256", after: initial.file.sha256 }], notices:
|
|
2220
|
+
notes: notes7,
|
|
2221
|
+
review: { provider: "tiktok", accountId: scope.account_id, kind: "update", title: "Import catalog file", subject: initial.file.name, fields: [{ label: "Catalog", after: input.catalog_id }, { label: "Feed", after: input.feed_id }, { label: "Feed type", after: initial.feed.feed_type }, { label: "Feed schedule", after: initial.feed.status }, { label: "Import mode", after: input.update_mode }, { label: "Product rows", after: String(initial.rowCount) }, { label: "CSV columns", after: String(initial.columns) }, { label: "SHA-256", after: initial.file.sha256 }], notices: notes7 },
|
|
2218
2222
|
execute: async () => {
|
|
2219
2223
|
await prepare();
|
|
2220
2224
|
const grant = await providerUrl(input, { maxBytes: MAX_PROJECT_MEDIA_BYTES2, contentTypes: ["text/csv"] });
|
|
@@ -2552,14 +2556,14 @@ var TikTokCatalogProductAuthoring = class {
|
|
|
2552
2556
|
}
|
|
2553
2557
|
}
|
|
2554
2558
|
if (assets.length) reviewFields.push({ label: "Adport media", after: assets });
|
|
2555
|
-
const
|
|
2559
|
+
const notes7 = ["Local preview only. TikTok validates native permissions, product fields and feed membership during asynchronous processing.", "Shared catalog changes can change existing ads wherever products or product sets are used; no ad status or budget is changed.", "Acceptance is not completed processing, product audit approval or ad eligibility. Inspect the exact native job, then read product context.", "TikTok permits one active product operation per catalog. Wait for prior jobs; busy/uncertain submissions are never automatically retried.", ...assets.length ? ["Media bytes/checksums are verified at preview and apply. Private download grants are minted only at apply; the payload hash binds logical media references, not an expiring URL.", "Images require at least 500\xD7500 pixels. Native media fetching/audit and any ongoing URL refetch behavior remain unverified; grants expire."] : [], ...upload ? ["Incremental upsert: uploading an existing external identity may replace its product data. Existing configuration was not inspected by this upsert preview."] : remove ? ["Removal cannot be undone through this operation; historical reporting may remain."] : ["Only supplied top-level fields are sent. Nested-object merge behavior remains native; no unverified preservation is promised."], ...reviewTruncated ? [`Review is limited to 20 products and 40 editable fields from ${count5} products; the full submitted payload is bound by its SHA-256 and identical-argument approval.`] : []];
|
|
2556
2560
|
return {
|
|
2557
2561
|
summary: `${title} \xB7 ${count5} ${type}`,
|
|
2558
2562
|
changes: [`${remove ? "-" : "~"} ${count5} selected ${type} products in catalog ${input.catalog_id}, feed ${input.feed_id}.`, `Approved native payload SHA-256 ${digest6(body)}.`],
|
|
2559
2563
|
coercions: [],
|
|
2560
2564
|
budgetDeltas: [],
|
|
2561
|
-
notes:
|
|
2562
|
-
review: { provider: "tiktok", accountId: scope.account_id, kind: op.kind, title, subject: `${count5} products`, fields: reviewFields, notices:
|
|
2565
|
+
notes: notes7,
|
|
2566
|
+
review: { provider: "tiktok", accountId: scope.account_id, kind: op.kind, title, subject: `${count5} products`, fields: reviewFields, notices: notes7 },
|
|
2563
2567
|
execute: async () => {
|
|
2564
2568
|
await this.authorizeParent(scope, true);
|
|
2565
2569
|
let nativeBody = body;
|
|
@@ -2600,12 +2604,12 @@ import { constants, promises as fs } from "fs";
|
|
|
2600
2604
|
import path from "path";
|
|
2601
2605
|
import { AdportError as AdportError15, adportHome } from "@adport/core";
|
|
2602
2606
|
import { z as z16 } from "zod";
|
|
2603
|
-
var catalogScope = z16.object({ accountId: z16.string().regex(/^\d{1,30}$/), businessId: z16.string().regex(/^\d{1,30}$/), resourceId: z16.string().regex(/^\d{1,30}$/), kind: z16.enum(["catalog", "catalog_creation"]) }).strict();
|
|
2604
|
-
var catalogAccessMode = z16.enum(["none", "read", "write", "create"]);
|
|
2607
|
+
var catalogScope = z16.object({ accountId: z16.string().regex(/^\d{1,30}$/), businessId: z16.string().regex(/^\d{1,30}$/), resourceId: z16.string().regex(/^\d{1,30}$/), kind: z16.enum(["catalog", "catalog_creation", "catalog_migration"]) }).strict();
|
|
2608
|
+
var catalogAccessMode = z16.enum(["none", "read", "write", "create", "migrate"]);
|
|
2605
2609
|
function catalogGrant(scope, mode2 = "none", revision = 0) {
|
|
2606
2610
|
const parsed = catalogScope.parse(scope);
|
|
2607
2611
|
catalogAccessMode.parse(mode2);
|
|
2608
|
-
if (!Number.isSafeInteger(revision) || revision < 0 || parsed.kind === "catalog_creation" && (parsed.resourceId !== parsed.businessId || !["none", "create"].includes(mode2)) || parsed.kind === "catalog" && mode2 === "
|
|
2612
|
+
if (!Number.isSafeInteger(revision) || revision < 0 || parsed.kind === "catalog_creation" && (parsed.resourceId !== parsed.businessId || !["none", "create"].includes(mode2)) || parsed.kind === "catalog" && !["none", "read", "write"].includes(mode2) || parsed.kind === "catalog_migration" && !["none", "migrate"].includes(mode2)) throw new AdportError15("INVALID_INPUT", "Invalid TikTok catalog access configuration.");
|
|
2609
2613
|
return { scope: parsed, mode: mode2, revision, hash: createHash9("sha256").update(JSON.stringify([parsed.accountId, parsed.businessId, parsed.kind, parsed.resourceId, mode2, revision])).digest("hex") };
|
|
2610
2614
|
}
|
|
2611
2615
|
function catalogScopeKey(scope) {
|
|
@@ -2620,6 +2624,13 @@ async function requireCatalogAccess(store, scope, write = false) {
|
|
|
2620
2624
|
return grant;
|
|
2621
2625
|
}
|
|
2622
2626
|
var creationScope = (accountId, businessId) => catalogScope.parse({ accountId, businessId, resourceId: businessId, kind: "catalog_creation" });
|
|
2627
|
+
var migrationScope = (accountId, businessId, resourceId) => catalogScope.parse({ accountId, businessId, resourceId, kind: "catalog_migration" });
|
|
2628
|
+
async function requireCatalogMigrationAccess(store, scope, write = false) {
|
|
2629
|
+
if (!store || scope.kind !== "catalog_migration" || write && !store.canWrite) throw new AdportError15("POLICY_VIOLATION", "Catalog migration requires a separate exact owner delegation and a writable connection.");
|
|
2630
|
+
const grant = await store.authorize(scope, write);
|
|
2631
|
+
if (catalogScopeKey(grant.scope) !== catalogScopeKey(scope) || grant.mode !== "migrate") throw new AdportError15("POLICY_VIOLATION", "An owner must attest source ownership and delegate this exact catalog transfer to this Business Center. Creation and catalog read/write grants do not authorize transfers.");
|
|
2632
|
+
return grant;
|
|
2633
|
+
}
|
|
2623
2634
|
async function requireCatalogCreationAccess(store, scope, write = false) {
|
|
2624
2635
|
if (!store || scope.kind !== "catalog_creation" || scope.resourceId !== scope.businessId || write && !store.canWrite) throw new AdportError15("POLICY_VIOLATION", "Catalog creation requires owner-delegated creation access and a writable connection.");
|
|
2625
2636
|
const grant = await store.authorize(scope, write);
|
|
@@ -2811,14 +2822,14 @@ var TikTokCatalogLifecycle = class {
|
|
|
2811
2822
|
if (requested.some((code2) => !current.available_region_codes.includes(code2))) throw new AdportError16("INVALID_INPUT", "A selected region is not available in this Business Center.");
|
|
2812
2823
|
};
|
|
2813
2824
|
await prepare();
|
|
2814
|
-
const c = input.catalog_conf,
|
|
2825
|
+
const c = input.catalog_conf, notes7 = ["Local preview only. Native creation eligibility, allowlists and supported type/currency/region combinations are checked on apply.", "Creates an empty Business Center catalog. No products, ads, budgets, tracking or events are created.", "The owner delegated read/write management of this successfully created, independently verified catalog ID only. Existing catalogs are not adopted or enumerated.", "Type, region, currency, channel and additional targeting configuration cannot be edited later. Uncertain creation or access adoption retains known IDs; reconcile before another create."];
|
|
2815
2826
|
return {
|
|
2816
2827
|
summary: `Create TikTok catalog "${input.name}"`,
|
|
2817
2828
|
changes: [`+ ${input.catalog_type} catalog ${input.name} in Business Center ${input.bc_id}`, `+ Immutable catalog configuration ${canonical9(c)}`, "+ Project read/write grant for the independently verified new catalog ID only"],
|
|
2818
2829
|
coercions: [],
|
|
2819
2830
|
budgetDeltas: [],
|
|
2820
|
-
notes:
|
|
2821
|
-
review: { provider: "tiktok", accountId: op.accountId, kind: "create", title: "Create catalog", subject: input.name, fields: [{ label: "Business Center", after: input.bc_id }, { label: "Catalog type", after: input.catalog_type }, { label: "Primary region", after: c.region_code ?? "Multi-country" }, { label: "Currency", after: c.currency }, { label: "Multi-country", after: c.is_multi_country ?? false }, { label: "Channel", after: c.channel ?? "Native default" }, { label: "Additional regions", after: c.additional_config_list?.map((row3) => row3.region_code + ":" + row3.currency).join(", ") || "None" }, { label: "New catalog project access", after: "Read and write" }], notices:
|
|
2831
|
+
notes: notes7,
|
|
2832
|
+
review: { provider: "tiktok", accountId: op.accountId, kind: "create", title: "Create catalog", subject: input.name, fields: [{ label: "Business Center", after: input.bc_id }, { label: "Catalog type", after: input.catalog_type }, { label: "Primary region", after: c.region_code ?? "Multi-country" }, { label: "Currency", after: c.currency }, { label: "Multi-country", after: c.is_multi_country ?? false }, { label: "Channel", after: c.channel ?? "Native default" }, { label: "Additional regions", after: c.additional_config_list?.map((row3) => row3.region_code + ":" + row3.currency).join(", ") || "None" }, { label: "New catalog project access", after: "Read and write" }], notices: notes7 },
|
|
2822
2833
|
execute: async () => {
|
|
2823
2834
|
await prepare();
|
|
2824
2835
|
let id6;
|
|
@@ -2844,14 +2855,14 @@ var TikTokCatalogLifecycle = class {
|
|
|
2844
2855
|
if (current2.configuration_hash !== input.expected_configuration_hash || current2.catalog_name !== input.confirm_catalog_name) throw new AdportError16("PENDING_MISMATCH", "Catalog configuration/name changed. Read it and request a fresh deletion preview.");
|
|
2845
2856
|
return current2;
|
|
2846
2857
|
};
|
|
2847
|
-
const current = await prepare(),
|
|
2858
|
+
const current = await prepare(), notes7 = ["Permanently deletes the entire shared catalog, including its current products and feeds. Existing ads or other accounts may be affected. No restore endpoint or global/atomic usage guarantee is available.", "Dependent contents are not enumerated or frozen by this configuration snapshot. Deletion applies to the entire catalog and its contents at apply time.", "Native deletion receipt and filtered catalog absence are checked independently. Provider errors are not absence; uncertain results are never replayed.", "Adport access grants remain separate owner settings; revocation is available without native catalog access."];
|
|
2848
2859
|
return {
|
|
2849
2860
|
summary: `Permanently delete TikTok catalog "${current.catalog_name}"`,
|
|
2850
2861
|
changes: [`- Entire catalog ${input.catalog_id} and its current products/feeds`, "- Catalog availability to existing shared consumers"],
|
|
2851
2862
|
coercions: [],
|
|
2852
2863
|
budgetDeltas: [],
|
|
2853
|
-
notes:
|
|
2854
|
-
review: { provider: "tiktok", accountId: op.accountId, kind: "remove", title: "Delete catalog permanently", subject: current.catalog_name, fields: [{ label: "Catalog", after: input.catalog_id }, { label: "Business Center", after: input.bc_id }, { label: "Catalog type", after: current.catalog_type }, { label: "Contents affected", after: "All current products and feeds; not enumerated or frozen" }], notices:
|
|
2864
|
+
notes: notes7,
|
|
2865
|
+
review: { provider: "tiktok", accountId: op.accountId, kind: "remove", title: "Delete catalog permanently", subject: current.catalog_name, fields: [{ label: "Catalog", after: input.catalog_id }, { label: "Business Center", after: input.bc_id }, { label: "Catalog type", after: current.catalog_type }, { label: "Contents affected", after: "All current products and feeds; not enumerated or frozen" }], notices: notes7 },
|
|
2855
2866
|
execute: async () => {
|
|
2856
2867
|
await prepare();
|
|
2857
2868
|
try {
|
|
@@ -2870,43 +2881,140 @@ var TikTokCatalogLifecycle = class {
|
|
|
2870
2881
|
}
|
|
2871
2882
|
};
|
|
2872
2883
|
|
|
2873
|
-
// src/catalog-
|
|
2884
|
+
// src/catalog-migration.ts
|
|
2874
2885
|
import { createHash as createHash11 } from "crypto";
|
|
2875
2886
|
import { AdportError as AdportError17 } from "@adport/core";
|
|
2876
2887
|
import { z as z18 } from "zod";
|
|
2877
2888
|
var hash9 = z18.string().regex(/^[a-f0-9]{64}$/);
|
|
2878
|
-
var
|
|
2879
|
-
|
|
2880
|
-
|
|
2889
|
+
var catalogMigration = catalogInput.omit({ account_id: true }).extend({
|
|
2890
|
+
expected_migration_access_hash: hash9,
|
|
2891
|
+
expected_destination_hash: hash9,
|
|
2892
|
+
confirm_catalog_id: z18.string(),
|
|
2893
|
+
acknowledge_shared_effects: z18.literal(true),
|
|
2894
|
+
acknowledge_source_ownership_not_independently_verified: z18.literal(true)
|
|
2895
|
+
}).strict().refine((input) => input.confirm_catalog_id === input.catalog_id, "Confirm the exact source catalog ID");
|
|
2896
|
+
var notes6 = [
|
|
2897
|
+
"Source ownership is attested by the project owner, not independently verified by an Adport source lookup. TikTok enforces source-advertiser ownership when applying the transfer.",
|
|
2898
|
+
"The destination Business Center Admin role is read from TikTok at preview and apply. The source catalog must not already be present there.",
|
|
2899
|
+
"Transfers the entire catalog, including its products, product sets and video templates. Existing users, ads and shared consumers may be affected; dependent contents are not enumerated or frozen.",
|
|
2900
|
+
"No ads are activated and no budgets or tracking events are changed. Native ownership transfer has no automatic retry or rollback.",
|
|
2901
|
+
"After transfer, the owner must separately grant read/write access to the exact destination catalog. Existing project grants are not expanded."
|
|
2902
|
+
];
|
|
2903
|
+
var TikTokCatalogMigration = class {
|
|
2904
|
+
constructor(client, store, lookup) {
|
|
2905
|
+
this.client = client;
|
|
2906
|
+
this.store = store;
|
|
2907
|
+
this.lookup = lookup;
|
|
2908
|
+
}
|
|
2909
|
+
client;
|
|
2910
|
+
store;
|
|
2911
|
+
lookup;
|
|
2912
|
+
async destination(bcId) {
|
|
2913
|
+
let response2;
|
|
2914
|
+
try {
|
|
2915
|
+
response2 = await this.client.get("bc/get", { bc_id: bcId, page: 1, page_size: 1 });
|
|
2916
|
+
} catch {
|
|
2917
|
+
throw new AdportError17("PROVIDER_ERROR", "TikTok destination Business Center lookup failed. Check the current token\u2019s Business Center permission and exact ID. No transfer was submitted.");
|
|
2918
|
+
}
|
|
2919
|
+
const parsed = z18.looseObject({
|
|
2920
|
+
list: z18.array(z18.looseObject({ bc_info: z18.looseObject({ bc_id: z18.string(), name: z18.string().optional() }), user_role: z18.string() })).length(1),
|
|
2921
|
+
page_info: z18.looseObject({ page: z18.literal(1), total_page: z18.number().int().min(0).max(1), total_number: z18.number().int().min(0).max(1).optional() }).optional()
|
|
2922
|
+
}).safeParse(response2);
|
|
2923
|
+
if (!parsed.success || parsed.data.list[0].bc_info.bc_id !== bcId || parsed.data.list[0].user_role !== "ADMIN" || parsed.data.page_info?.total_number === 0) throw new AdportError17("POLICY_VIOLATION", "The exact destination Business Center and native Admin role could not be verified.");
|
|
2924
|
+
const selected5 = parsed.data.list[0];
|
|
2925
|
+
return { bc_id: bcId, name: selected5.bc_info.name ?? bcId, user_role: selected5.user_role };
|
|
2926
|
+
}
|
|
2927
|
+
async context(raw) {
|
|
2928
|
+
const input = catalogInput.parse(raw), grant = await requireCatalogMigrationAccess(this.store, migrationScope(input.account_id, input.bc_id, input.catalog_id));
|
|
2929
|
+
const destination = await this.destination(input.bc_id);
|
|
2930
|
+
if (await this.lookup(input)) throw new AdportError17("INVALID_INPUT", "This catalog is already in the destination Business Center. Do not transfer it again; review its exact catalog access separately.");
|
|
2931
|
+
return {
|
|
2932
|
+
expected_migration_access_hash: grant.hash,
|
|
2933
|
+
expected_destination_hash: createHash11("sha256").update(JSON.stringify({ ...input, destination })).digest("hex"),
|
|
2934
|
+
source_ownership: "OWNER_ATTESTED_NOT_INDEPENDENTLY_VERIFIED",
|
|
2935
|
+
destination,
|
|
2936
|
+
records: [{ id: input.catalog_id, name: "Catalog transfer", source_advertiser_id: input.account_id, destination_business_center_id: input.bc_id, source_ownership: "Owner attested", destination_role: destination.user_role }],
|
|
2937
|
+
notes: [...notes6]
|
|
2938
|
+
};
|
|
2939
|
+
}
|
|
2940
|
+
async plan(op) {
|
|
2941
|
+
if (op.provider !== "tiktok" || op.tool !== "tiktok_migrate_catalog" || op.kind !== "update") throw new AdportError17("INVALID_INPUT", "Unsupported catalog migration operation.");
|
|
2942
|
+
const input = catalogMigration.parse(op.payload), selection = { account_id: op.accountId, bc_id: input.bc_id, catalog_id: input.catalog_id };
|
|
2943
|
+
const prepare = async () => {
|
|
2944
|
+
await requireCatalogMigrationAccess(this.store, migrationScope(op.accountId, input.bc_id, input.catalog_id), true);
|
|
2945
|
+
const current2 = await this.context(selection);
|
|
2946
|
+
if (current2.expected_migration_access_hash !== input.expected_migration_access_hash || current2.expected_destination_hash !== input.expected_destination_hash) throw new AdportError17("PENDING_MISMATCH", "Transfer delegation or destination changed. Read migration context and review a new preview.");
|
|
2947
|
+
return current2;
|
|
2948
|
+
};
|
|
2949
|
+
const current = await prepare();
|
|
2950
|
+
return {
|
|
2951
|
+
summary: `Transfer TikTok catalog ${input.catalog_id} to ${current.destination.name}`,
|
|
2952
|
+
changes: [`~ Entire catalog ${input.catalog_id}: advertiser ${op.accountId} \u2192 Business Center ${input.bc_id}`],
|
|
2953
|
+
coercions: [],
|
|
2954
|
+
budgetDeltas: [],
|
|
2955
|
+
notes: [...notes6],
|
|
2956
|
+
review: { provider: "tiktok", accountId: op.accountId, kind: "update", title: "Transfer catalog ownership", subject: input.catalog_id, fields: [
|
|
2957
|
+
{ label: "Source advertiser", after: op.accountId },
|
|
2958
|
+
{ label: "Catalog", after: input.catalog_id },
|
|
2959
|
+
{ label: "Destination Business Center", after: input.bc_id },
|
|
2960
|
+
{ label: "Source ownership verification", after: "Owner attestation; native check at apply" },
|
|
2961
|
+
{ label: "Destination role", after: "ADMIN" },
|
|
2962
|
+
{ label: "Contents affected", after: "Entire catalog and its current products, product sets and video templates" },
|
|
2963
|
+
{ label: "Project read/write grants", after: "Unchanged" }
|
|
2964
|
+
], notices: [...notes6] },
|
|
2965
|
+
execute: async () => {
|
|
2966
|
+
await prepare();
|
|
2967
|
+
try {
|
|
2968
|
+
await this.client.post("catalog/capitalize", { advertiser_id: op.accountId, bc_id: input.bc_id, catalog_id: input.catalog_id });
|
|
2969
|
+
await requireCatalogMigrationAccess(this.store, migrationScope(op.accountId, input.bc_id, input.catalog_id), true);
|
|
2970
|
+
if (!await this.lookup(selection)) throw new Error("Destination catalog was not found");
|
|
2971
|
+
return [input.catalog_id];
|
|
2972
|
+
} catch (error) {
|
|
2973
|
+
const details = error instanceof AdportError17 && error.details && typeof error.details === "object" ? error.details : {};
|
|
2974
|
+
throw new AdportError17("PROVIDER_ERROR", "Catalog transfer or destination readback is unconfirmed. Inspect the exact destination catalog before another transfer; no request was retried.", { resource_ids: [input.catalog_id], ...Number.isInteger(details.code) ? { provider_code: details.code } : {} });
|
|
2975
|
+
}
|
|
2976
|
+
}
|
|
2977
|
+
};
|
|
2978
|
+
}
|
|
2979
|
+
};
|
|
2980
|
+
|
|
2981
|
+
// src/catalog-event-sources.ts
|
|
2982
|
+
import { createHash as createHash12 } from "crypto";
|
|
2983
|
+
import { AdportError as AdportError18 } from "@adport/core";
|
|
2984
|
+
import { z as z19 } from "zod";
|
|
2985
|
+
var hash10 = z19.string().regex(/^[a-f0-9]{64}$/);
|
|
2986
|
+
var nativeId8 = z19.union([catalogId, z19.number().int().positive().safe()]).transform(String);
|
|
2987
|
+
var code = z19.string().min(1).max(256).regex(/^[^\u0000-\u0020\u007f]+$/);
|
|
2988
|
+
var text3 = z19.string().max(4e3);
|
|
2881
2989
|
var selectedFields = { app_id: catalogId.optional(), pixel_code: code.optional() };
|
|
2882
2990
|
var hasSource = (value) => !!(value.app_id || value.pixel_code);
|
|
2883
|
-
var paging2 = { cursor:
|
|
2991
|
+
var paging2 = { cursor: z19.string().min(1).max(512).optional(), page_size: z19.number().int().min(1).max(100).default(30) };
|
|
2884
2992
|
var catalogEventList = catalogInput.extend(paging2).strict();
|
|
2885
|
-
var catalogEventApps = catalogInput.extend({ ...paging2, app_platform_ids:
|
|
2886
|
-
var catalogEventContext = catalogInput.extend({ ...selectedFields, purpose:
|
|
2887
|
-
var catalogEventChange = catalogInput.omit({ account_id: true }).extend({ ...selectedFields, expected_catalog_hash:
|
|
2993
|
+
var catalogEventApps = catalogInput.extend({ ...paging2, app_platform_ids: z19.array(z19.string().min(1).max(1e3)).min(1).max(100).refine((ids2) => new Set(ids2).size === ids2.length, "Platform IDs must be unique").optional() }).strict();
|
|
2994
|
+
var catalogEventContext = catalogInput.extend({ ...selectedFields, purpose: z19.enum(["bind", "unbind"]).default("bind") }).strict().refine(hasSource, "Select an app_id, pixel_code or both");
|
|
2995
|
+
var catalogEventChange = catalogInput.omit({ account_id: true }).extend({ ...selectedFields, expected_catalog_hash: hash10, expected_bindings_hash: hash10, expected_sources_hash: hash10, acknowledge_shared_effects: z19.literal(true), acknowledge_measurement_effects: z19.literal(true) }).strict().refine(hasSource, "Select an app_id, pixel_code or both; an empty selector cannot unbind all sources");
|
|
2888
2996
|
var canonical10 = (value) => JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
|
|
2889
|
-
var digest8 = (value) =>
|
|
2997
|
+
var digest8 = (value) => createHash12("sha256").update(canonical10(value)).digest("hex");
|
|
2890
2998
|
var key = (value) => value.type + ":" + value.id;
|
|
2891
2999
|
var identities = (rows) => rows.map(({ type, id: id6 }) => ({ type, id: id6 })).sort((a, b) => key(a).localeCompare(key(b)));
|
|
2892
|
-
var invalid7 = () => new
|
|
3000
|
+
var invalid7 = () => new AdportError18("PROVIDER_ERROR", "TikTok catalog event-source scope, identifiers or response shape could not be verified.");
|
|
2893
3001
|
var failure3 = (error, message, ids2) => {
|
|
2894
|
-
const details = error instanceof
|
|
2895
|
-
return new
|
|
3002
|
+
const details = error instanceof AdportError18 && error.details && typeof error.details === "object" ? error.details : {};
|
|
3003
|
+
return new AdportError18("PROVIDER_ERROR", message + " Provider bodies stay hidden; no request was retried.", { ...Number.isSafeInteger(details.code) ? { provider_code: details.code } : {}, ...typeof details.request_id === "string" && /^[a-zA-Z0-9_-]{1,128}$/.test(details.request_id) ? { request_id: details.request_id } : {}, ...ids2 ? { resourceIds: ids2 } : {} });
|
|
2896
3004
|
};
|
|
2897
|
-
var nativeApp =
|
|
2898
|
-
var matching2 =
|
|
2899
|
-
var nativePixel =
|
|
3005
|
+
var nativeApp = z19.object({ advertiser_id: nativeId8, app_id: nativeId8, app_name: text3, app_platform_id: z19.string().min(1).max(1e3), platform: z19.enum(["ANDROID", "IOS"]).optional(), package_name: text3.optional(), self_attribution_enabled: z19.boolean().optional(), skan_allowed: z19.enum(["ALLOWED", "NOT_ALLOWED"]).optional(), advanced_dedicated_campaign_allowed: z19.boolean().optional(), is_attribution_flex_enable: z19.boolean().optional() });
|
|
3006
|
+
var matching2 = z19.object({ email: z19.boolean().optional(), phone_number: z19.boolean().optional(), name: z19.boolean().optional(), address: z19.boolean().optional(), external_id: z19.boolean().optional() });
|
|
3007
|
+
var nativePixel = z19.object({ pixel_id: nativeId8, pixel_code: code, pixel_name: text3, advertiser_id: nativeId8.optional(), asset_ownership: z19.object({ asset_relation_status: z19.string().nullable().optional(), ownership_status: z19.boolean().optional(), owner_bc_id: nativeId8.nullable().optional() }).optional(), advanced_matching_fields: matching2.optional(), automatic_advanced_matching_fields: matching2.optional(), enable_first_party_cookies: z19.boolean().optional(), enable_expanded_data_sharing: z19.boolean().optional() });
|
|
2900
3008
|
function page(scope, rows, cursor, size) {
|
|
2901
3009
|
const snapshot3 = digest8({ scope, rows });
|
|
2902
3010
|
let index = 0;
|
|
2903
3011
|
if (cursor) {
|
|
2904
3012
|
try {
|
|
2905
|
-
const parsed =
|
|
3013
|
+
const parsed = z19.object({ h: hash10, i: z19.number().int().positive().safe() }).strict().parse(JSON.parse(Buffer.from(cursor, "base64url").toString("utf8")));
|
|
2906
3014
|
if (parsed.h !== snapshot3 || parsed.i >= rows.length) throw new Error();
|
|
2907
3015
|
index = parsed.i;
|
|
2908
3016
|
} catch {
|
|
2909
|
-
throw new
|
|
3017
|
+
throw new AdportError18("INVALID_INPUT", "The source inventory, selection or cursor changed. Read the first page again.");
|
|
2910
3018
|
}
|
|
2911
3019
|
}
|
|
2912
3020
|
const selected5 = rows.slice(index, index + size), next = index + selected5.length;
|
|
@@ -2927,7 +3035,7 @@ var TikTokCatalogEventSources = class {
|
|
|
2927
3035
|
}
|
|
2928
3036
|
}
|
|
2929
3037
|
async bindings(scope) {
|
|
2930
|
-
const response2 =
|
|
3038
|
+
const response2 = z19.object({ catalog_id: nativeId8, bc_id: nativeId8.optional(), event_sources: z19.array(z19.object({ event_source_name: text3.nullable().optional(), app_id: nativeId8.nullable().optional(), pixel_code: code.nullable().optional() }).refine(hasSource)).max(5e3) }).safeParse(await this.get("catalog/eventsource_bind/get", { bc_id: scope.bc_id, catalog_id: scope.catalog_id }));
|
|
2931
3039
|
if (!response2.success || response2.data.catalog_id !== scope.catalog_id || response2.data.bc_id !== void 0 && response2.data.bc_id !== scope.bc_id) throw invalid7();
|
|
2932
3040
|
const rows = response2.data.event_sources.flatMap((row3) => [...row3.app_id ? [{ type: "APP", id: row3.app_id, name: row3.event_source_name ?? "App event source" }] : [], ...row3.pixel_code ? [{ type: "PIXEL", id: row3.pixel_code, name: row3.event_source_name ?? "Web Pixel" }] : []]);
|
|
2933
3041
|
if (rows.length > 5e3 || new Set(rows.map(key)).size !== rows.length) throw invalid7();
|
|
@@ -2941,7 +3049,7 @@ var TikTokCatalogEventSources = class {
|
|
|
2941
3049
|
async apps(value) {
|
|
2942
3050
|
const input = catalogEventApps.parse(value), scope = catalogInput.parse({ account_id: input.account_id, bc_id: input.bc_id, catalog_id: input.catalog_id });
|
|
2943
3051
|
await this.parent(scope);
|
|
2944
|
-
const response2 =
|
|
3052
|
+
const response2 = z19.object({ apps: z19.array(nativeApp).max(5e3) }).safeParse(await this.get("app/list", { advertiser_id: scope.account_id, ...input.app_platform_ids ? { app_platform_ids: input.app_platform_ids } : {} }));
|
|
2945
3053
|
if (!response2.success || response2.data.apps.some((row3) => row3.advertiser_id !== scope.account_id || input.app_platform_ids && !input.app_platform_ids.includes(row3.app_platform_id)) || new Set(response2.data.apps.map((row3) => row3.app_id)).size !== response2.data.apps.length) throw invalid7();
|
|
2946
3054
|
const rows = response2.data.apps.sort((a, b) => a.app_id.localeCompare(b.app_id)), result = page({ ...scope, kind: "apps", app_platform_ids: input.app_platform_ids ?? null }, rows, input.cursor, input.page_size);
|
|
2947
3055
|
return { apps: result.selected, records: result.selected.map((row3) => ({ id: row3.app_id, name: row3.app_name, platform: row3.platform ?? "Not reported", app_platform_id: row3.app_platform_id, skan_allowed: row3.skan_allowed ?? "Not reported" })), total_in_response: rows.length, complete: result.complete, truncated: result.truncated, ..."next_cursor" in result ? { next_cursor: result.next_cursor } : {}, notes: ["Advertiser app discovery, not a guarantee of catalog binding eligibility. Use the native app_id for event-source binding; app_platform_id and tiktok_app_id are different identifiers.", "Native endpoint is unpaged; Adport snapshot-pages at most 5,000 apps, up to 100 per local page. Tracking URLs, partner tokens, raw icons and other private fields are omitted."] };
|
|
@@ -2949,13 +3057,13 @@ var TikTokCatalogEventSources = class {
|
|
|
2949
3057
|
async selected(scope, input, purpose) {
|
|
2950
3058
|
const sources = [];
|
|
2951
3059
|
if (input.app_id) {
|
|
2952
|
-
const response2 =
|
|
3060
|
+
const response2 = z19.object({ app: nativeApp }).safeParse(await this.get("app/info", { advertiser_id: scope.account_id, app_id: input.app_id }));
|
|
2953
3061
|
if (!response2.success || response2.data.app.advertiser_id !== scope.account_id || response2.data.app.app_id !== input.app_id) throw invalid7();
|
|
2954
3062
|
const app = response2.data.app;
|
|
2955
3063
|
sources.push({ type: "APP", id: app.app_id, name: app.app_name, ...app });
|
|
2956
3064
|
}
|
|
2957
3065
|
if (input.pixel_code) {
|
|
2958
|
-
const response2 =
|
|
3066
|
+
const response2 = z19.object({ pixels: z19.array(nativePixel).max(20), page_info: z19.object({ page: z19.literal(1), page_size: z19.literal(20), total_page: z19.number().int().nonnegative().safe().optional(), total_number: z19.number().int().nonnegative().safe().optional() }).optional() }).safeParse(await this.get("pixel/list", { advertiser_id: scope.account_id, code: input.pixel_code, page: 1, page_size: 20, ...purpose === "bind" ? { filtering: { available_for_catalog_only: true } } : {} }));
|
|
2959
3067
|
if (!response2.success || response2.data.pixels.length !== 1 || (response2.data.page_info?.total_page ?? 1) !== 1 || response2.data.page_info?.total_number !== void 0 && response2.data.page_info.total_number !== 1) throw invalid7();
|
|
2960
3068
|
const pixel = response2.data.pixels[0];
|
|
2961
3069
|
if (pixel.pixel_code !== input.pixel_code || pixel.advertiser_id !== void 0 && pixel.advertiser_id !== scope.account_id || pixel.asset_ownership?.asset_relation_status === "UNBOUND") throw invalid7();
|
|
@@ -2966,7 +3074,7 @@ var TikTokCatalogEventSources = class {
|
|
|
2966
3074
|
async contextFor(scope, input, purpose, write = false) {
|
|
2967
3075
|
const parent = await this.parent(scope, write), bindings = await this.bindings(scope), selected5 = await this.selected(scope, input, purpose);
|
|
2968
3076
|
const keys = new Set(bindings.rows.map(key));
|
|
2969
|
-
if (selected5.sources.some((row3) => purpose === "bind" ? keys.has(key(row3)) : !keys.has(key(row3)))) throw new
|
|
3077
|
+
if (selected5.sources.some((row3) => purpose === "bind" ? keys.has(key(row3)) : !keys.has(key(row3)))) throw new AdportError18("INVALID_INPUT", purpose === "bind" ? "A selected source is already bound. Select only new bindings, or split the change." : "Every selected source must already be bound. No unbind-all operation is inferred.");
|
|
2970
3078
|
return { parent, bindings, selected: selected5 };
|
|
2971
3079
|
}
|
|
2972
3080
|
async context(value) {
|
|
@@ -2975,22 +3083,22 @@ var TikTokCatalogEventSources = class {
|
|
|
2975
3083
|
}
|
|
2976
3084
|
async plan(op) {
|
|
2977
3085
|
const bind = op.tool === "tiktok_bind_catalog_event_sources";
|
|
2978
|
-
if (op.provider !== "tiktok" || !(bind && op.kind === "update" || op.tool === "tiktok_unbind_catalog_event_sources" && op.kind === "remove")) throw new
|
|
3086
|
+
if (op.provider !== "tiktok" || !(bind && op.kind === "update" || op.tool === "tiktok_unbind_catalog_event_sources" && op.kind === "remove")) throw new AdportError18("INVALID_INPUT", "Unsupported catalog event-source operation or kind.");
|
|
2979
3087
|
const input = catalogEventChange.parse(op.payload), scope = catalogInput.parse({ account_id: op.accountId, bc_id: input.bc_id, catalog_id: input.catalog_id }), purpose = bind ? "bind" : "unbind";
|
|
2980
3088
|
const prepare = async () => {
|
|
2981
3089
|
const current2 = await this.contextFor(scope, input, purpose, true);
|
|
2982
|
-
if (current2.parent.configuration_hash !== input.expected_catalog_hash || current2.bindings.hash !== input.expected_bindings_hash || current2.selected.hash !== input.expected_sources_hash) throw new
|
|
3090
|
+
if (current2.parent.configuration_hash !== input.expected_catalog_hash || current2.bindings.hash !== input.expected_bindings_hash || current2.selected.hash !== input.expected_sources_hash) throw new AdportError18("PENDING_MISMATCH", "Catalog, bindings or selected sources changed. Read context and request a new preview.");
|
|
2983
3091
|
return current2;
|
|
2984
3092
|
};
|
|
2985
3093
|
const current = await prepare(), selected5 = current.selected.sources, title = bind ? "Bind catalog event sources" : "Unbind catalog event sources";
|
|
2986
|
-
const
|
|
3094
|
+
const notes7 = ["Local preview only. Changes shared catalog product/event matching and may affect measurement, retargeting and existing ads.", "No tracking installation, event ingestion, budget or ad-status change. Source access and native catalog eligibility remain authoritative.", "All unselected binding identities are checked after the write. There is no atomic cross-resource guarantee; uncertain or partial results are never replayed."];
|
|
2987
3095
|
return {
|
|
2988
3096
|
summary: title + " \xB7 catalog " + input.catalog_id,
|
|
2989
3097
|
changes: selected5.map((row3) => `${bind ? "+" : "-"} ${row3.type} ${row3.name} (${row3.id})`),
|
|
2990
3098
|
coercions: [],
|
|
2991
3099
|
budgetDeltas: [],
|
|
2992
|
-
notes:
|
|
2993
|
-
review: { provider: "tiktok", accountId: scope.account_id, kind: bind ? "update" : "remove", title, subject: input.catalog_id, fields: [{ label: "Catalog", after: input.catalog_id }, ...selected5.map((row3) => ({ label: row3.type === "APP" ? "App event source" : "Web Pixel", before: bind ? "Not bound" : row3.name + " (" + row3.id + ")", after: bind ? row3.name + " (" + row3.id + ")" : "Unbound" })), { label: "Other bindings preserved", after: String(current.bindings.rows.length - (bind ? 0 : selected5.length)) }], notices:
|
|
3100
|
+
notes: notes7,
|
|
3101
|
+
review: { provider: "tiktok", accountId: scope.account_id, kind: bind ? "update" : "remove", title, subject: input.catalog_id, fields: [{ label: "Catalog", after: input.catalog_id }, ...selected5.map((row3) => ({ label: row3.type === "APP" ? "App event source" : "Web Pixel", before: bind ? "Not bound" : row3.name + " (" + row3.id + ")", after: bind ? row3.name + " (" + row3.id + ")" : "Unbound" })), { label: "Other bindings preserved", after: String(current.bindings.rows.length - (bind ? 0 : selected5.length)) }], notices: notes7 },
|
|
2994
3102
|
execute: async () => {
|
|
2995
3103
|
const fresh = await prepare(), selectedKeys = new Set(selected5.map(key)), expected = bind ? [...fresh.bindings.rows, ...selected5] : fresh.bindings.rows.filter((row3) => !selectedKeys.has(key(row3)));
|
|
2996
3104
|
try {
|
|
@@ -3009,41 +3117,41 @@ var TikTokCatalogEventSources = class {
|
|
|
3009
3117
|
};
|
|
3010
3118
|
|
|
3011
3119
|
// src/catalog-videos.ts
|
|
3012
|
-
import { createHash as
|
|
3013
|
-
import { AdportError as
|
|
3014
|
-
import { z as
|
|
3015
|
-
var
|
|
3016
|
-
var count4 =
|
|
3017
|
-
var nativeId9 =
|
|
3018
|
-
var videoId =
|
|
3019
|
-
var time =
|
|
3020
|
-
var text4 =
|
|
3120
|
+
import { createHash as createHash13 } from "crypto";
|
|
3121
|
+
import { AdportError as AdportError19, csvRows as csvRows4, MAX_PROJECT_MEDIA_BYTES as MAX_PROJECT_MEDIA_BYTES4, verifyMedia as verifyMedia4 } from "@adport/core";
|
|
3122
|
+
import { z as z20 } from "zod";
|
|
3123
|
+
var hash11 = z20.string().regex(/^[a-f0-9]{64}$/);
|
|
3124
|
+
var count4 = z20.number().int().nonnegative().safe();
|
|
3125
|
+
var nativeId9 = z20.union([catalogId, z20.number().int().positive().safe()]).transform(String);
|
|
3126
|
+
var videoId = z20.string().min(1).max(1024).regex(/^[^\u0000-\u0020\u007f]+$/);
|
|
3127
|
+
var time = z20.string().max(40).regex(/^[0-9TZ :.+-]*$/);
|
|
3128
|
+
var text4 = z20.string().max(256 * 1024).nullable().optional();
|
|
3021
3129
|
var metadata = { category: text4, brand: text4, creator: text4, video_type: text4, description: text4, landing_page_url: text4, custom_label_0: text4, custom_label_1: text4, custom_label_2: text4, custom_label_3: text4, custom_label_4: text4 };
|
|
3022
3130
|
var metadataKeys = Object.keys(metadata);
|
|
3023
|
-
var nativeVideo =
|
|
3131
|
+
var nativeVideo = z20.object({
|
|
3024
3132
|
...metadata,
|
|
3025
3133
|
catalog_video_id: videoId,
|
|
3026
|
-
video_name:
|
|
3027
|
-
video_link:
|
|
3028
|
-
sku_id_list:
|
|
3134
|
+
video_name: z20.string().max(4e3),
|
|
3135
|
+
video_link: z20.string().max(256 * 1024).optional(),
|
|
3136
|
+
sku_id_list: z20.array(z20.string().max(100)).max(20).optional(),
|
|
3029
3137
|
video_id: videoId.nullable().optional(),
|
|
3030
|
-
video_signature:
|
|
3031
|
-
status:
|
|
3032
|
-
active_status:
|
|
3138
|
+
video_signature: z20.string().max(128).nullable().optional(),
|
|
3139
|
+
status: z20.enum(["PENDING", "SUCCESS", "FAILED"]),
|
|
3140
|
+
active_status: z20.enum(["ACTIVATED", "DEACTIVATED"]).optional(),
|
|
3033
3141
|
create_time: time.optional(),
|
|
3034
|
-
preview_url:
|
|
3142
|
+
preview_url: z20.string().max(16384).nullable().optional(),
|
|
3035
3143
|
catalog_id: nativeId9.optional(),
|
|
3036
3144
|
bc_id: nativeId9.optional()
|
|
3037
3145
|
});
|
|
3038
3146
|
var displayMetadata = (row3) => Object.fromEntries(metadataKeys.filter((key2) => key2 !== "landing_page_url" && row3[key2] !== void 0).map((key2) => [key2, typeof row3[key2] === "string" ? row3[key2].slice(0, 1e3) : row3[key2]]));
|
|
3039
|
-
var source = catalogInput.extend({ media_id:
|
|
3147
|
+
var source = catalogInput.extend({ media_id: z20.string().uuid(), expected_sha256: hash11 }).strict();
|
|
3040
3148
|
var catalogVideoImportContext = source;
|
|
3041
|
-
var catalogVideoList = catalogInput.extend({ catalog_video_ids:
|
|
3149
|
+
var catalogVideoList = catalogInput.extend({ catalog_video_ids: z20.array(videoId).min(1).max(50).refine((ids2) => new Set(ids2).size === ids2.length, "Video IDs must be unique").optional(), page: z20.number().int().positive().safe().default(1), page_size: z20.number().int().min(1).max(50).default(20) }).strict();
|
|
3042
3150
|
var catalogVideoLog = catalogInput.extend({ feed_log_id: catalogId }).strict();
|
|
3043
|
-
var catalogVideoUpload = source.omit({ account_id: true }).extend({ expected_catalog_hash:
|
|
3044
|
-
var catalogVideoDelete = catalogInput.omit({ account_id: true }).extend({ catalog_video_id: videoId, expected_configuration_hash:
|
|
3151
|
+
var catalogVideoUpload = source.omit({ account_id: true }).extend({ expected_catalog_hash: hash11, expected_associations_hash: hash11, sync_to_selected_account: z20.boolean().default(false), acknowledge_account_copy: z20.literal(true).optional(), acknowledge_shared_effects: z20.literal(true), acknowledge_possible_delivery: z20.literal(true), acknowledge_async_processing: z20.literal(true) }).strict().refine((value) => !value.sync_to_selected_account || value.acknowledge_account_copy === true, "Syncing creates separate advertiser-library copies; acknowledge_account_copy is required");
|
|
3152
|
+
var catalogVideoDelete = catalogInput.omit({ account_id: true }).extend({ catalog_video_id: videoId, expected_configuration_hash: hash11, acknowledge_shared_effects: z20.literal(true) }).strict();
|
|
3045
3153
|
var canonical11 = (value) => JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
|
|
3046
|
-
var digest9 = (value) =>
|
|
3154
|
+
var digest9 = (value) => createHash13("sha256").update(canonical11(value)).digest("hex");
|
|
3047
3155
|
var object3 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
3048
3156
|
var safeUrl2 = (value, httpsOnly = true) => {
|
|
3049
3157
|
if (typeof value !== "string" || /[\u0000-\u0020\u007f]/.test(value)) return;
|
|
@@ -3064,10 +3172,10 @@ var sourceInfo = (value) => {
|
|
|
3064
3172
|
};
|
|
3065
3173
|
var config2 = (row3) => ({ ...Object.fromEntries(metadataKeys.filter((key2) => row3[key2] !== void 0).map((key2) => [key2, row3[key2]])), catalog_video_id: row3.catalog_video_id, video_name: row3.video_name, video_link: row3.video_link, sku_id_list: row3.sku_id_list, active_status: row3.active_status });
|
|
3066
3174
|
var configurationHash2 = (scope, row3) => digest9({ ...scope, configuration: config2(row3) });
|
|
3067
|
-
var invalid8 = () => new
|
|
3175
|
+
var invalid8 = () => new AdportError19("PROVIDER_ERROR", "TikTok returned an unexpected catalog-video scope, identifier or shape. No request was retried.");
|
|
3068
3176
|
var failure4 = (error, message, ids2) => {
|
|
3069
|
-
const details = object3(error instanceof
|
|
3070
|
-
return new
|
|
3177
|
+
const details = object3(error instanceof AdportError19 ? error.details : void 0);
|
|
3178
|
+
return new AdportError19("PROVIDER_ERROR", `${message} Provider bodies and source URLs stay hidden; no request was retried.`, { ...Number.isSafeInteger(details.code) ? { provider_code: details.code } : {}, ...typeof details.request_id === "string" && /^[a-zA-Z0-9_-]{1,128}$/.test(details.request_id) ? { request_id: details.request_id } : {}, ...ids2 ? { resourceIds: ids2 } : {} });
|
|
3071
3179
|
};
|
|
3072
3180
|
var columns = ["video_name", "video_link", "sku_id_list", "category", "brand", "creator", "video_type", "description", "landing_page_url", "custom_label_0", "custom_label_1", "custom_label_2", "custom_label_3", "custom_label_4"];
|
|
3073
3181
|
var TikTokCatalogVideos = class {
|
|
@@ -3081,7 +3189,7 @@ var TikTokCatalogVideos = class {
|
|
|
3081
3189
|
media;
|
|
3082
3190
|
async parent(scope, write = false) {
|
|
3083
3191
|
const parent = await this.authorizeParent(scope, write);
|
|
3084
|
-
if (parent.catalog_type !== "ECOM" || parent.catalog_conf.is_multi_country === true) throw new
|
|
3192
|
+
if (parent.catalog_type !== "ECOM" || parent.catalog_conf.is_multi_country === true) throw new AdportError19("INVALID_INPUT", "Catalog videos require a single-country E-commerce catalog.");
|
|
3085
3193
|
return parent;
|
|
3086
3194
|
}
|
|
3087
3195
|
async request(path2, args) {
|
|
@@ -3092,9 +3200,9 @@ var TikTokCatalogVideos = class {
|
|
|
3092
3200
|
}
|
|
3093
3201
|
}
|
|
3094
3202
|
async native(scope, ids2, page3 = 1, size = 20) {
|
|
3095
|
-
const result =
|
|
3203
|
+
const result = z20.object({ videos: z20.array(nativeVideo).max(ids2 ? ids2.length : size), page_info: z20.unknown().optional() }).safeParse(await this.request("catalog/video/get", { bc_id: scope.bc_id, catalog_id: scope.catalog_id, ...ids2 ? { catalog_video_ids: ids2 } : { page: page3, page_size: size } }));
|
|
3096
3204
|
if (!result.success) throw invalid8();
|
|
3097
|
-
const pageInfo7 = ids2 || result.data.page_info === void 0 ? void 0 :
|
|
3205
|
+
const pageInfo7 = ids2 || result.data.page_info === void 0 ? void 0 : z20.object({ page: z20.number().int().positive().safe(), page_size: z20.number().int().positive().max(50), total_page: count4.optional(), total_number: count4.optional() }).safeParse(result.data.page_info);
|
|
3098
3206
|
if (pageInfo7 && !pageInfo7.success) throw invalid8();
|
|
3099
3207
|
const rows = result.data.videos, info = pageInfo7?.data;
|
|
3100
3208
|
if (new Set(rows.map((row3) => row3.catalog_video_id)).size !== rows.length || rows.some((row3) => ids2 && !ids2.includes(row3.catalog_video_id) || row3.catalog_id !== void 0 && row3.catalog_id !== scope.catalog_id || row3.bc_id !== void 0 && row3.bc_id !== scope.bc_id) || !ids2 && info && (info.page !== page3 || info.page_size !== size)) throw invalid8();
|
|
@@ -3145,10 +3253,10 @@ var TikTokCatalogVideos = class {
|
|
|
3145
3253
|
async log(value) {
|
|
3146
3254
|
const input = catalogVideoLog.parse(value), scope = catalogInput.parse({ account_id: input.account_id, bc_id: input.bc_id, catalog_id: input.catalog_id });
|
|
3147
3255
|
await this.parent(scope);
|
|
3148
|
-
const issue =
|
|
3149
|
-
const result =
|
|
3150
|
-
video_feed_log:
|
|
3151
|
-
feed_log_data:
|
|
3256
|
+
const issue = z20.object({ field: z20.string().max(256 * 1024).optional(), affected_video_count: count4 });
|
|
3257
|
+
const result = z20.object({
|
|
3258
|
+
video_feed_log: z20.object({ catalog_id: nativeId9, bc_id: nativeId9.optional(), feed_log_id: nativeId9.optional(), feed_id: nativeId9.optional(), add_count: count4.optional(), update_count: count4.optional(), delete_count: count4.optional(), error_count: count4.optional(), warn_count: count4.optional(), process_status: z20.enum(["PROCESSING", "SUCCESS", "FAILED", "WAITING"]), start_time: time.optional(), end_time: time.optional() }),
|
|
3259
|
+
feed_log_data: z20.object({ error_affected_videos: z20.array(issue).max(1e3).nullable().optional(), warn_affected_videos: z20.array(issue).max(1e3).nullable().optional() }).nullable().optional()
|
|
3152
3260
|
}).safeParse(await this.request("catalog/video/log", { bc_id: input.bc_id, catalog_id: input.catalog_id, feed_log_id: input.feed_log_id, language: "en" }));
|
|
3153
3261
|
if (!result.success) throw invalid8();
|
|
3154
3262
|
const row3 = result.data.video_feed_log;
|
|
@@ -3167,43 +3275,43 @@ var TikTokCatalogVideos = class {
|
|
|
3167
3275
|
}
|
|
3168
3276
|
async source(scope, mediaId, sha, write = false) {
|
|
3169
3277
|
const parent = await this.parent(scope, write), media = this.media;
|
|
3170
|
-
if (!media) throw new
|
|
3278
|
+
if (!media) throw new AdportError19("NOT_CONNECTED", "Catalog-video imports require a CSV staged through Adport agent, widget, dashboard or cloud CLI media tools.");
|
|
3171
3279
|
let raw;
|
|
3172
3280
|
try {
|
|
3173
3281
|
raw = await media.read({ media_id: mediaId, expected_sha256: sha }, { maxBytes: MAX_PROJECT_MEDIA_BYTES4, contentTypes: ["text/csv"] });
|
|
3174
3282
|
} catch {
|
|
3175
|
-
throw new
|
|
3283
|
+
throw new AdportError19("INVALID_INPUT", "Catalog-video CSV bytes/checksum could not be verified. Refresh the immutable media reference.");
|
|
3176
3284
|
}
|
|
3177
3285
|
const file = verifyMedia4(raw.bytes, raw.name, sha, { maxBytes: MAX_PROJECT_MEDIA_BYTES4, contentTypes: ["text/csv"] }), rows = csvRows4(file.bytes, { maxRows: 5001, maxColumns: columns.length }), first = rows.next();
|
|
3178
|
-
if (first.done || new Set(first.value).size !== first.value.length || first.value.some((key2) => !columns.includes(key2)) || columns.slice(0, 3).some((key2) => !first.value.includes(key2))) throw new
|
|
3286
|
+
if (first.done || new Set(first.value).size !== first.value.length || first.value.some((key2) => !columns.includes(key2)) || columns.slice(0, 3).some((key2) => !first.value.includes(key2))) throw new AdportError19("INVALID_INPUT", "Use the documented catalog-video CSV headers: video_name, video_link, sku_id_list and optional native metadata columns.");
|
|
3179
3287
|
const previews = [], allSkus = /* @__PURE__ */ new Set();
|
|
3180
3288
|
let rowCount = 0;
|
|
3181
3289
|
for (const fields of rows) {
|
|
3182
3290
|
const row3 = Object.fromEntries(first.value.map((key2, i) => [key2, fields[i]]));
|
|
3183
|
-
if (!row3.video_name?.trim() || row3.video_name.length > 500 || !safeUrl2(row3.video_link, false) || row3.landing_page_url && !safeUrl2(row3.landing_page_url, false) || ["category", "brand", "creator", "video_type", "description"].some((key2) => (row3[key2]?.length ?? 0) > 500)) throw new
|
|
3291
|
+
if (!row3.video_name?.trim() || row3.video_name.length > 500 || !safeUrl2(row3.video_link, false) || row3.landing_page_url && !safeUrl2(row3.landing_page_url, false) || ["category", "brand", "creator", "video_type", "description"].some((key2) => (row3[key2]?.length ?? 0) > 500)) throw new AdportError19("INVALID_INPUT", "Each catalog-video row needs a nonempty name up to 500 characters and a valid HTTP(S) video URL. Optional metadata up to 500 characters; native would null longer values.");
|
|
3184
3292
|
const skus = row3.sku_id_list.split(",");
|
|
3185
|
-
if (!skus.length || skus.length > 20 || skus.some((sku) => !sku || sku !== sku.trim() || sku.length > 100 || /[\u0000-\u001f\u007f]/.test(sku)) || new Set(skus).size !== skus.length) throw new
|
|
3293
|
+
if (!skus.length || skus.length > 20 || skus.some((sku) => !sku || sku !== sku.trim() || sku.length > 100 || /[\u0000-\u001f\u007f]/.test(sku)) || new Set(skus).size !== skus.length) throw new AdportError19("INVALID_INPUT", "Each video needs 1\u201320 distinct exact SKU IDs, comma-separated without surrounding whitespace. Quote the CSV field when it contains commas.");
|
|
3186
3294
|
for (const sku of skus) allSkus.add(sku);
|
|
3187
|
-
if (allSkus.size > 5e3) throw new
|
|
3295
|
+
if (allSkus.size > 5e3) throw new AdportError19("INVALID_INPUT", "Adport verifies at most 5,000 distinct SKU associations per import. Use smaller CSV batches.");
|
|
3188
3296
|
if (previews.length < 20) previews.push({ row: rowCount + 2, name: row3.video_name, sku_ids: skus, source: sourceInfo(row3.video_link) });
|
|
3189
3297
|
rowCount++;
|
|
3190
3298
|
}
|
|
3191
|
-
if (!rowCount) throw new
|
|
3299
|
+
if (!rowCount) throw new AdportError19("INVALID_INPUT", "The catalog-video CSV needs at least one data row.");
|
|
3192
3300
|
const skuIds = [...allSkus].sort(), found = /* @__PURE__ */ new Map();
|
|
3193
3301
|
for (let start = 0; start < skuIds.length; start += 1e3) {
|
|
3194
3302
|
const selected5 = skuIds.slice(start, start + 1e3);
|
|
3195
3303
|
for (let page3 = 1; page3 <= 2; page3++) {
|
|
3196
|
-
const result =
|
|
3304
|
+
const result = z20.object({ list: z20.array(z20.object({ sku_id: z20.string().min(1).max(100), product_id: nativeId9, ad_creation_eligible: z20.string(), catalog_id: nativeId9.optional(), bc_id: nativeId9.optional() })).max(500), page_info: z20.object({ page: z20.number().int().positive(), page_size: z20.number().int().positive(), total_page: count4.optional(), total_number: count4.optional() }).optional() }).safeParse(await this.request("catalog/product/get", { bc_id: scope.bc_id, catalog_id: scope.catalog_id, sku_ids: selected5, page: page3, page_size: 500 }));
|
|
3197
3305
|
if (!result.success || result.data.page_info && (result.data.page_info.page !== page3 || result.data.page_info.page_size !== 500)) throw invalid8();
|
|
3198
3306
|
for (const row3 of result.data.list) {
|
|
3199
3307
|
if (!selected5.includes(row3.sku_id) || found.has(row3.sku_id) || row3.catalog_id !== void 0 && row3.catalog_id !== scope.catalog_id || row3.bc_id !== void 0 && row3.bc_id !== scope.bc_id) throw invalid8();
|
|
3200
|
-
if (row3.ad_creation_eligible !== "AVAILABLE") throw new
|
|
3308
|
+
if (row3.ad_creation_eligible !== "AVAILABLE") throw new AdportError19("INVALID_INPUT", "Every associated SKU must be natively AVAILABLE for ad creation. No import was submitted.");
|
|
3201
3309
|
found.set(row3.sku_id, { sku_id: row3.sku_id, product_id: row3.product_id, ad_creation_eligible: row3.ad_creation_eligible });
|
|
3202
3310
|
}
|
|
3203
3311
|
if (selected5.every((sku) => found.has(sku))) break;
|
|
3204
3312
|
if (!result.data.list.length || !result.data.page_info || result.data.page_info.total_page === void 0 || page3 >= result.data.page_info.total_page) break;
|
|
3205
3313
|
}
|
|
3206
|
-
if (!selected5.every((sku) => found.has(sku))) throw new
|
|
3314
|
+
if (!selected5.every((sku) => found.has(sku))) throw new AdportError19("INVALID_INPUT", "Not every selected SKU association could be verified in the catalog. No import was submitted.");
|
|
3207
3315
|
}
|
|
3208
3316
|
const associations = [...found.values()].sort((a, b) => a.sku_id.localeCompare(b.sku_id));
|
|
3209
3317
|
return { parent, file, rowCount, skuCount: skuIds.length, previews, associations_hash: digest9({ ...scope, sha256: file.sha256, associations }) };
|
|
@@ -3224,35 +3332,35 @@ var TikTokCatalogVideos = class {
|
|
|
3224
3332
|
};
|
|
3225
3333
|
}
|
|
3226
3334
|
async plan(op) {
|
|
3227
|
-
if (op.provider !== "tiktok") throw new
|
|
3335
|
+
if (op.provider !== "tiktok") throw new AdportError19("INVALID_INPUT", "TikTok catalog-video provider differs.");
|
|
3228
3336
|
if (op.tool === "tiktok_upload_catalog_videos" && op.kind === "create") {
|
|
3229
3337
|
const input = catalogVideoUpload.parse(op.payload), scope = catalogInput.parse({ account_id: op.accountId, bc_id: input.bc_id, catalog_id: input.catalog_id }), media = this.media, providerUrl = media?.providerUrl?.bind(media);
|
|
3230
|
-
if (!providerUrl) throw new
|
|
3338
|
+
if (!providerUrl) throw new AdportError19("NOT_CONNECTED", "Catalog-video CSV imports require the hosted project media library to create a private download grant.");
|
|
3231
3339
|
const prepare = async () => {
|
|
3232
3340
|
const result = await this.source(scope, input.media_id, input.expected_sha256, true);
|
|
3233
|
-
if (result.parent.configuration_hash !== input.expected_catalog_hash || result.associations_hash !== input.expected_associations_hash) throw new
|
|
3341
|
+
if (result.parent.configuration_hash !== input.expected_catalog_hash || result.associations_hash !== input.expected_associations_hash) throw new AdportError19("PENDING_MISMATCH", "Catalog configuration or SKU associations changed. Read import context and request a fresh preview.");
|
|
3234
3342
|
return result;
|
|
3235
3343
|
};
|
|
3236
|
-
const initial = await prepare(),
|
|
3344
|
+
const initial = await prepare(), notes7 = ["Local preview only. This adds catalog videos asynchronously and may make them available to existing Video Shopping Ads using the associated products. Ad statuses and budgets are not changed.", "Only one catalog-video file task can run at a time. Wait for prior tasks; uncertain/failed submissions are never automatically retried.", "Native video extraction, media eligibility and any advertiser-library sync remain separate from task acceptance.", input.sync_to_selected_account ? `Requests a separate video copy in the selected advertiser ${scope.account_id}. TikTok ignores ineligible accounts; this request does not confirm sync. Catalog deletion does not delete advertiser copies.` : "No advertiser-library sync is requested."];
|
|
3237
3345
|
return {
|
|
3238
3346
|
summary: `Upload ${initial.rowCount} catalog videos`,
|
|
3239
3347
|
changes: [`+ ${initial.rowCount} video rows and ${initial.skuCount} distinct SKU associations in catalog ${input.catalog_id}.`, `CSV SHA-256 ${input.expected_sha256}; selected advertiser sync requested: ${input.sync_to_selected_account}.`],
|
|
3240
3348
|
coercions: [],
|
|
3241
3349
|
budgetDeltas: [],
|
|
3242
|
-
notes:
|
|
3243
|
-
review: { provider: "tiktok", accountId: scope.account_id, kind: "create", title: "Upload catalog videos", subject: initial.file.name, fields: [{ label: "Catalog", after: input.catalog_id }, { label: "Video rows", after: initial.rowCount }, { label: "Associated SKUs", after: initial.skuCount }, { label: "Ad-account copy requested", after: input.sync_to_selected_account ? scope.account_id : "No" }, { label: "CSV SHA-256", after: input.expected_sha256 }, { label: "SKU association snapshot", after: input.expected_associations_hash }], notices:
|
|
3350
|
+
notes: notes7,
|
|
3351
|
+
review: { provider: "tiktok", accountId: scope.account_id, kind: "create", title: "Upload catalog videos", subject: initial.file.name, fields: [{ label: "Catalog", after: input.catalog_id }, { label: "Video rows", after: initial.rowCount }, { label: "Associated SKUs", after: initial.skuCount }, { label: "Ad-account copy requested", after: input.sync_to_selected_account ? scope.account_id : "No" }, { label: "CSV SHA-256", after: input.expected_sha256 }, { label: "SKU association snapshot", after: input.expected_associations_hash }], notices: notes7 },
|
|
3244
3352
|
execute: async () => {
|
|
3245
3353
|
await prepare();
|
|
3246
3354
|
let grant;
|
|
3247
3355
|
try {
|
|
3248
3356
|
grant = await providerUrl({ media_id: input.media_id, expected_sha256: input.expected_sha256 }, { maxBytes: MAX_PROJECT_MEDIA_BYTES4, contentTypes: ["text/csv"] });
|
|
3249
3357
|
} catch {
|
|
3250
|
-
throw new
|
|
3358
|
+
throw new AdportError19("PROVIDER_ERROR", "Private CSV staging failed. No native catalog-video upload was submitted.");
|
|
3251
3359
|
}
|
|
3252
|
-
if (grant.sha256 !== input.expected_sha256 || !safeUrl2(grant.url) || !(Date.parse(grant.expires_at) > Date.now() + 10 * 6e4)) throw new
|
|
3360
|
+
if (grant.sha256 !== input.expected_sha256 || !safeUrl2(grant.url) || !(Date.parse(grant.expires_at) > Date.now() + 10 * 6e4)) throw new AdportError19("PROVIDER_ERROR", "The private CSV grant could not be verified. No catalog-video upload was submitted.");
|
|
3253
3361
|
let job;
|
|
3254
3362
|
try {
|
|
3255
|
-
const result =
|
|
3363
|
+
const result = z20.object({ feed_log_id: nativeId9 }).parse(await this.client.post("catalog/video/file", { bc_id: input.bc_id, catalog_id: input.catalog_id, file_url: grant.url, ...input.sync_to_selected_account ? { advertiser_ids: [scope.account_id] } : {} }));
|
|
3256
3364
|
job = result.feed_log_id;
|
|
3257
3365
|
const actual = await this.log({ ...scope, feed_log_id: job });
|
|
3258
3366
|
if (actual.log.process_status === "FAILED" || (actual.log.error_count ?? 0) > 0) throw new Error("Native task failed or has item errors");
|
|
@@ -3268,19 +3376,19 @@ var TikTokCatalogVideos = class {
|
|
|
3268
3376
|
const prepare = async () => {
|
|
3269
3377
|
await this.parent(scope, true);
|
|
3270
3378
|
const result = await this.native(scope, [input.catalog_video_id]);
|
|
3271
|
-
if (result.rows.length !== 1) throw new
|
|
3379
|
+
if (result.rows.length !== 1) throw new AdportError19("INVALID_INPUT", "The exact catalog video could not be verified. Refresh the gallery.");
|
|
3272
3380
|
const row3 = result.rows[0];
|
|
3273
|
-
if (configurationHash2(scope, row3) !== input.expected_configuration_hash) throw new
|
|
3381
|
+
if (configurationHash2(scope, row3) !== input.expected_configuration_hash) throw new AdportError19("PENDING_MISMATCH", "The catalog video changed. Read its configuration and request a fresh preview.");
|
|
3274
3382
|
return row3;
|
|
3275
3383
|
};
|
|
3276
|
-
const current = await prepare(),
|
|
3384
|
+
const current = await prepare(), notes7 = ["Local preview only. Removes one catalog video and its product associations; existing catalog ads may be affected.", "Video copies already synced into advertiser creative libraries are not removed. No global/atomic usage guarantee or restore endpoint is available."];
|
|
3277
3385
|
return {
|
|
3278
3386
|
summary: `Remove catalog video "${current.video_name}"`,
|
|
3279
3387
|
changes: [`- Catalog video ${input.catalog_video_id} and its catalog SKU associations.`, "Advertiser-library copies may remain."],
|
|
3280
3388
|
coercions: [],
|
|
3281
3389
|
budgetDeltas: [],
|
|
3282
|
-
notes:
|
|
3283
|
-
review: { provider: "tiktok", accountId: scope.account_id, kind: "remove", title: "Remove from catalog", subject: current.video_name, fields: [{ label: "Catalog video", after: input.catalog_video_id }, { label: "Associated SKUs", after: current.sku_id_list ?? "Not reported" }, { label: "Extraction", after: current.status }, { label: "Activation", after: current.active_status ?? "Not reported" }], notices:
|
|
3390
|
+
notes: notes7,
|
|
3391
|
+
review: { provider: "tiktok", accountId: scope.account_id, kind: "remove", title: "Remove from catalog", subject: current.video_name, fields: [{ label: "Catalog video", after: input.catalog_video_id }, { label: "Associated SKUs", after: current.sku_id_list ?? "Not reported" }, { label: "Extraction", after: current.status }, { label: "Activation", after: current.active_status ?? "Not reported" }], notices: notes7 },
|
|
3284
3392
|
execute: async () => {
|
|
3285
3393
|
await prepare();
|
|
3286
3394
|
try {
|
|
@@ -3294,17 +3402,19 @@ var TikTokCatalogVideos = class {
|
|
|
3294
3402
|
}
|
|
3295
3403
|
};
|
|
3296
3404
|
}
|
|
3297
|
-
throw new
|
|
3405
|
+
throw new AdportError19("INVALID_INPUT", "Unsupported TikTok catalog-video operation or kind.");
|
|
3298
3406
|
}
|
|
3299
3407
|
};
|
|
3300
3408
|
|
|
3301
3409
|
// src/catalog-tools.ts
|
|
3302
|
-
var
|
|
3303
|
-
var catalogRename = catalogInput.omit({ account_id: true }).extend({ name:
|
|
3304
|
-
var catalogAccessChange = catalogPermissionSelection.omit({ account_id: true }).extend({ mode:
|
|
3410
|
+
var hash12 = z21.string().regex(/^[a-f0-9]{64}$/);
|
|
3411
|
+
var catalogRename = catalogInput.omit({ account_id: true }).extend({ name: z21.string().trim().min(1).max(128), expected_configuration_hash: hash12, acknowledge_shared_effects: z21.literal(true) }).strict();
|
|
3412
|
+
var catalogAccessChange = catalogPermissionSelection.omit({ account_id: true }).extend({ mode: z21.enum(["none", "read", "write", "create", "migrate"]), expected_access_hash: hash12, acknowledge_source_ownership: z21.literal(true).optional(), acknowledge_shared_effects: z21.literal(true).optional() }).strict().refine(validCatalogPermission, "Choose exact catalog read/write access, creation without a catalog ID, or an exact transfer with owner and shared-effects acknowledgements");
|
|
3305
3413
|
function tiktokCatalogTools(provider, accessManagement = false) {
|
|
3306
|
-
const read = { namespace: "tiktok", annotations: { readOnly: true }, presentation: "records", output:
|
|
3414
|
+
const read = { namespace: "tiktok", annotations: { readOnly: true }, presentation: "records", output: z21.looseObject({ records: z21.array(z21.record(z21.string(), z21.unknown())) }) };
|
|
3307
3415
|
return [
|
|
3416
|
+
defineTool4({ ...read, name: "tiktok_catalog_migration_context", catalog: { category: "administration", exposure: "specialist" }, description: "Read a separate owner-attested exact transfer grant, verify destination Business Center Admin and absence of the source catalog there. Source ownership is not independently verified; TikTok enforces it at apply. Returns hashes for a guarded transfer.", input: catalogInput, handler: (input) => provider.catalogs.migration.context(input) }),
|
|
3417
|
+
guardedWriteTool3({ name: "tiktok_migrate_catalog", namespace: "tiktok", provider: "tiktok", catalog: { category: "administration", exposure: "specialist" }, kind: "update", destructive: true, description: "Transfer an exact advertiser-owned catalog to a Business Center using separate owner-attested delegation and destination hashes. Whole-catalog/shared effects; native ownership check at apply and exact destination readback. No project grant expansion, rollback or automatic retry.", payload: catalogMigration }),
|
|
3308
3418
|
defineTool4({ ...read, name: "tiktok_catalog_creation_context", catalog: { category: "creatives", exposure: "specialist" }, description: "Read an owner-delegated creation grant hash and available regions for one advertiser/Business Center. Covers all ten catalog types; native allowlists and currency combinations remain authoritative. No existing catalogs are enumerated or granted.", input: catalogCreationInput, handler: (input) => provider.catalogs.lifecycle.context(input) }),
|
|
3309
3419
|
guardedWriteTool3({ name: "tiktok_create_catalog", namespace: "tiktok", provider: "tiktok", catalog: { category: "creatives", exposure: "specialist" }, kind: "create", destructive: false, description: "Create an empty catalog using creation-delegation/region hashes and explicit immutable configuration. Independently verifies the native ID/configuration, then adopts only that new ID for project read/write access under owner delegation. No ads, products or spend; no automatic replay.", payload: catalogCreate }),
|
|
3310
3420
|
guardedWriteTool3({ name: "tiktok_delete_catalog", namespace: "tiktok", provider: "tiktok", catalog: { category: "creatives", exposure: "specialist" }, kind: "remove", destructive: true, description: "Permanently delete one writable catalog with fresh configuration_hash, exact name confirmation and contents/shared-effects acknowledgement. Deletes current products/feeds; contents are not enumerated/frozen. Verifies native receipt and filtered absence; errors are not absence. No restore or replay.", payload: catalogDelete }),
|
|
@@ -3313,25 +3423,25 @@ function tiktokCatalogTools(provider, accessManagement = false) {
|
|
|
3313
3423
|
defineTool4({ ...read, name: "tiktok_catalog_event_source_context", catalog: { category: "measurement", exposure: "specialist" }, description: "Verify one app_id, pixel_code or both under the selected advertiser and read catalog/binding/source hashes for bind or unbind. Bind checks Pixel catalog availability; unbind checks existing membership. No events or writes.", input: catalogEventContext, handler: (input) => provider.catalogs.eventSources.context(input) }),
|
|
3314
3424
|
guardedWriteTool3({ name: "tiktok_bind_catalog_event_sources", namespace: "tiktok", provider: "tiktok", catalog: { category: "measurement", exposure: "specialist" }, kind: "update", destructive: true, description: "Bind selected advertiser app/Pixel sources to a writable catalog using fresh context hashes and shared/measurement-effects acknowledgement. Can affect existing catalog matching/ads. Rechecks sources and all bindings; no tracking installation, event sending or automatic replay.", payload: catalogEventChange }),
|
|
3315
3425
|
guardedWriteTool3({ name: "tiktok_unbind_catalog_event_sources", namespace: "tiktok", provider: "tiktok", catalog: { category: "measurement", exposure: "specialist" }, kind: "remove", destructive: true, description: "Unbind explicit selected advertiser app/Pixel sources using fresh context hashes. Requires existing membership and shared/measurement-effects acknowledgement. Verifies absence and preservation of unselected binding identities. No unbind-all inference or replay; no events sent.", payload: catalogEventChange }),
|
|
3316
|
-
defineTool4({ ...read, name: "tiktok_catalog_videos", catalog: { category: "creatives", exposure: "specialist" }, description: "
|
|
3426
|
+
defineTool4({ ...read, name: "tiktok_catalog_videos", catalog: { category: "creatives", exposure: "specialist" }, description: "List videos in the selected TikTok catalog with SKU links, processing status and six-hour previews. Read-only. If permitted, the gallery links to the separately listed tiktok_delete_catalog_video tool for preview and approval.", input: catalogVideoList, output: creativesOutput.extend({ videos: z21.array(z21.record(z21.string(), z21.unknown())), complete: z21.boolean().nullable(), next_page: z21.number().int().positive().optional(), notes: z21.array(z21.string()), page_info: z21.record(z21.string(), z21.unknown()).optional(), missing_ids: z21.array(z21.string()).optional() }), presentation: "creatives", pagination: { cursorInput: "page", cursorOutput: "next_page" }, handler: (input) => provider.catalogs.videos.list(input) }),
|
|
3317
3427
|
defineTool4({ ...read, name: "tiktok_catalog_video_log", catalog: { category: "creatives", exposure: "specialist" }, description: "Read one catalog-video handling task with exact catalog binding. Preserves native processing states/counts and bounded diagnostic field counts. Does not certify video extraction, ad eligibility or advertiser sync; source links/downloads and free-form diagnostics stay hidden.", input: catalogVideoLog, handler: (input) => provider.catalogs.videos.log(input) }),
|
|
3318
3428
|
defineTool4({ ...read, name: "tiktok_catalog_video_import_context", catalog: { category: "creatives", exposure: "specialist" }, description: "Inspect a checksum-bound project CSV for catalog videos and verify every referenced SKU is AVAILABLE for ad creation. Returns catalog/association hashes for upload. Up to 5,000 rows/distinct SKUs and 20 SKUs/video; source URLs stay private. No upload or media-eligibility claim.", input: catalogVideoImportContext, handler: (input) => provider.catalogs.videos.importContext(input) }),
|
|
3319
3429
|
guardedWriteTool3({ name: "tiktok_upload_catalog_videos", namespace: "tiktok", provider: "tiktok", catalog: { category: "creatives", exposure: "specialist" }, kind: "create", destructive: true, description: "Submit a checksum-bound library CSV to the native catalog-video file API, using fresh import-context hashes. May feed existing catalog ads; explicit delivery/shared/async acknowledgement required. Optional sync targets only the selected advertiser and requires copy acknowledgement. Returns an accepted job, not ingestion/sync success; no replay.", payload: catalogVideoUpload }),
|
|
3320
3430
|
guardedWriteTool3({ name: "tiktok_delete_catalog_video", namespace: "tiktok", provider: "tiktok", catalog: { category: "creatives", exposure: "specialist" }, kind: "remove", destructive: true, description: "Remove one composite catalog-video ID with its fresh configuration_hash and shared-effects acknowledgement. Rechecks native state, issues one delete and verifies filtered-view absence. Existing catalog ads may be affected; synced advertiser-library copies remain separate. No automatic replay or restore.", payload: catalogVideoDelete }),
|
|
3321
|
-
defineTool4({ ...read, name: "tiktok_catalog_product_schema", catalog: { category: "creatives", exposure: "specialist" }, presentation: void 0, output:
|
|
3431
|
+
defineTool4({ ...read, name: "tiktok_catalog_product_schema", catalog: { category: "creatives", exposure: "specialist" }, presentation: void 0, output: z21.looseObject({ schema: z21.record(z21.string(), z21.unknown()) }), description: "Read the official structural product schema for this granted catalog\u2019s native type and upload/update operation. Covers all ten catalog types. Native semantic requirements still apply; no products or ads are changed.", input: catalogProductSchema, handler: (input) => provider.catalogs.productAuthoring.schema(input) }),
|
|
3322
3432
|
defineTool4({ ...read, name: "tiktok_catalog_product_context", catalog: { category: "creatives", exposure: "specialist" }, description: "Read exact native product IDs, safe editable configuration and products_hash for JSON edits/removal. Verifies catalog/feed and every selected ID; URL origins/fingerprints only. This is selected configuration, not complete catalog inventory or proof of feed membership.", input: catalogProductContext, handler: (input) => provider.catalogs.productAuthoring.context(input) }),
|
|
3323
3433
|
guardedWriteTool3({ name: "tiktok_upsert_catalog_products", namespace: "tiktok", provider: "tiktok", catalog: { category: "creatives", exposure: "specialist" }, kind: "update", destructive: true, description: "Upload up to5,000 native JSON products using the catalog-type schema. Can replace existing external identities; fresh catalog/feed hashes and explicit replacement/shared/async acknowledgements required. Returns an accepted task, not completed ingestion. No automatic replay.", payload: catalogProductUpsert, sensitiveInputs: ["products"] }),
|
|
3324
3434
|
guardedWriteTool3({ name: "tiktok_update_catalog_products", namespace: "tiktok", provider: "tiktok", catalog: { category: "creatives", exposure: "specialist" }, kind: "update", destructive: true, description: "Patch product fields selected by verified native product IDs and products_hash. External identities are derived from native context and cannot be edited. Fresh catalog/feed hashes required; asynchronous task and shared-effects acknowledgements. Read the schema first; no automatic replay.", payload: catalogProductUpdate, sensitiveInputs: ["updates"] }),
|
|
3325
3435
|
guardedWriteTool3({ name: "tiktok_delete_catalog_products", namespace: "tiktok", provider: "tiktok", catalog: { category: "creatives", exposure: "specialist" }, kind: "remove", destructive: true, description: "Remove verified native product IDs using products_hash and fresh catalog/feed hashes. Maps native external IDs to documented deletion selectors; Entertainment removal is undocumented and refused. Requires removal/shared/async acknowledgements. Returns accepted task; never replays.", payload: catalogProductDelete }),
|
|
3326
|
-
defineTool4({ ...read, name: "tiktok_catalog_access", catalog: { category: "administration", exposure: "specialist" }, description: "List only this project/account\u2019s explicit Business Center catalog grants. Advertiser access alone grants no catalog access. No native Business Center inventory is enumerated.", input:
|
|
3436
|
+
defineTool4({ ...read, name: "tiktok_catalog_access", catalog: { category: "administration", exposure: "specialist" }, description: "List only this project/account\u2019s explicit Business Center catalog grants. Advertiser access alone grants no catalog access. No native Business Center inventory is enumerated.", input: z21.object({ account_id: catalogId }).strict(), handler: (input) => provider.catalogs.access(input.account_id) }),
|
|
3327
3437
|
defineTool4({ ...read, name: "tiktok_get_catalog", description: "Read one explicitly granted Business Center catalog, native eligibility and configuration_hash. Verifies exact catalog and Business Center IDs; does not enumerate unrelated catalogs.", input: catalogInput, handler: (input) => provider.catalogs.get(input) }),
|
|
3328
|
-
defineTool4({ ...read, name: "tiktok_catalog_products", catalog: { category: "creatives", exposure: "specialist" }, description: "Browse product/media summaries in an explicitly granted catalog. Native product-ID or ECOM SKU filters, exact string IDs and page navigation. At most100/page and10,000 accessible matches; missing pagination stays unknown. Compact view, not full editable configuration.", input: catalogProductList, output: creativesOutput.extend({ products:
|
|
3438
|
+
defineTool4({ ...read, name: "tiktok_catalog_products", catalog: { category: "creatives", exposure: "specialist" }, description: "Browse product/media summaries in an explicitly granted catalog. Native product-ID or ECOM SKU filters, exact string IDs and page navigation. At most100/page and10,000 accessible matches; missing pagination stays unknown. Compact view, not full editable configuration.", input: catalogProductList, output: creativesOutput.extend({ products: z21.array(z21.record(z21.string(), z21.unknown())), complete: z21.boolean().nullable(), next_page: z21.number().int().positive().optional(), native_access_limit: z21.literal(1e4), native_limit_reached: z21.boolean(), notes: z21.array(z21.string()), page_info: z21.record(z21.string(), z21.unknown()).optional() }), presentation: "creatives", pagination: { cursorInput: "page", cursorOutput: "next_page" }, handler: (input) => provider.catalogs.products.list(input) }),
|
|
3329
3439
|
defineTool4({ ...read, name: "tiktok_catalog_product_log", catalog: { category: "creatives", exposure: "specialist" }, description: "Read one product import task after verifying its catalog/feed. Native processing state, counts and bounded diagnostic field counts; no free-form error text or download capabilities. SUCCESS is not ad eligibility. Requires the feed_log_id returned on import.", input: catalogProductLog, handler: (input) => provider.catalogs.products.log(input) }),
|
|
3330
3440
|
guardedWriteTool3({ name: "tiktok_import_catalog_file", namespace: "tiktok", provider: "tiktok", catalog: { category: "creatives", exposure: "specialist" }, kind: "update", destructive: true, description: "Submit a checksum-bound project CSV as a one-time catalog feed import. Fresh catalog/feed hashes, explicit mode and asynchronous/shared-effects acknowledgement; OVERWRITE also requires deletion acknowledgement. Returns an accepted native job, not completed ingestion. Never automatically replay.", payload: catalogFileImport }),
|
|
3331
3441
|
defineTool4({ ...read, name: "tiktok_catalog_feeds", catalog: { category: "creatives", exposure: "specialist" }, description: "Browse feeds in one explicitly granted catalog, with safe source fingerprints and configuration_hash. Native lists are unpaged; Adport bounds to 5,000 and snapshot-pages locally. Credentials, source paths and query values stay hidden.", input: catalogFeedList, pagination: { cursorInput: "cursor" }, handler: (input) => provider.catalogs.feeds.list(input) }),
|
|
3332
3442
|
defineTool4({ ...read, name: "tiktok_catalog_feed_log", catalog: { category: "creatives", exposure: "specialist" }, description: "Read the latest 10 native processing operations for an exact verified feed. Shows status, counts and timestamps only; not full history or proof of catalog ad eligibility.", input: catalogFeedLog, handler: (input) => provider.catalogs.feeds.log(input) }),
|
|
3333
|
-
guardedWriteTool3({ name: "tiktok_create_catalog_feed", namespace: "tiktok", provider: "tiktok", catalog: { category: "creatives", exposure: "specialist" }, kind: "create", destructive: true, description: "Create a feed using its catalog hash. Optional source/schedule can start product processing; OVERWRITE can remove products. Native config readback required. Source arguments stay private; use the agent to apply when supplied.", payload: catalogFeedCreate, sensitiveInputs: ["schedule_param.source"] }),
|
|
3334
|
-
guardedWriteTool3({ name: "tiktok_update_catalog_feed", namespace: "tiktok", provider: "tiktok", catalog: { category: "creatives", exposure: "specialist" }, kind: "update", destructive: true, description: "Update feed mode/source/schedule using its configuration_hash. OVERWRITE can remove products; explicit automatic-processing acknowledgement required. Native auth cannot be read back. Source arguments stay out of widget approvals.", payload: catalogFeedUpdate, sensitiveInputs: ["schedule_param.source"] }),
|
|
3443
|
+
guardedWriteTool3({ name: "tiktok_create_catalog_feed", namespace: "tiktok", provider: "tiktok", catalog: { category: "creatives", exposure: "specialist" }, kind: "create", destructive: true, description: "Create a feed using its catalog hash. Optional source/schedule can start product processing; OVERWRITE can remove products. Native config readback required. Source arguments stay private; use the agent to apply when supplied.", payload: catalogFeedCreate, hosted: { payload: hostedCatalogFeedCreate, description: "Create a feed in an authorized TikTok catalog. An optional public HTTPS source and schedule can start processing. OVERWRITE can remove products. Requires acknowledgment of processing and effects on existing products and ads." }, sensitiveInputs: ["schedule_param.source"] }),
|
|
3444
|
+
guardedWriteTool3({ name: "tiktok_update_catalog_feed", namespace: "tiktok", provider: "tiktok", catalog: { category: "creatives", exposure: "specialist" }, kind: "update", destructive: true, description: "Update feed mode/source/schedule using its configuration_hash. OVERWRITE can remove products; explicit automatic-processing acknowledgement required. Native auth cannot be read back. Source arguments stay out of widget approvals.", payload: catalogFeedUpdate, hosted: { payload: hostedCatalogFeedUpdate, description: "Update a selected TikTok feed using its current configuration hash. A replacement source must be a public HTTPS URL. OVERWRITE can remove products. Requires acknowledgment of processing and effects on existing products and ads." }, sensitiveInputs: ["schedule_param.source"] }),
|
|
3335
3445
|
guardedWriteTool3({ name: "tiktok_set_catalog_feed_schedule_status", namespace: "tiktok", provider: "tiktok", catalog: { category: "creatives", exposure: "specialist" }, kind: "update", destructive: true, description: "Switch a verified feed ON/OFF with a fresh configuration_hash. ON can resume automatic product changes; requires an existing source, interval and timezone. Opposite state only; independent preservation readback and no replay.", payload: catalogFeedSwitch }),
|
|
3336
3446
|
guardedWriteTool3({ name: "tiktok_delete_catalog_feed", namespace: "tiktok", provider: "tiktok", catalog: { category: "creatives", exposure: "specialist" }, kind: "remove", destructive: true, description: "Permanently delete one verified shared feed using its configuration_hash. Exact native receipt and complete catalog feed absence check required. Dependent products/ads must be reviewed; uncertain results are never replayed.", payload: catalogFeedDelete }),
|
|
3337
3447
|
defineTool4({ ...read, name: "tiktok_product_sets", catalog: { category: "creatives", exposure: "specialist" }, description: "Browse one granted catalog\u2019s product sets or an exact set, with configuration hashes. Snapshot-bound local paging; native endpoint returns all sets, bounded to 5,000. Product counts default off to avoid native timeouts.", input: productSetList, pagination: { cursorInput: "cursor" }, handler: (input) => provider.catalogs.productSets.list(input) }),
|
|
@@ -3350,15 +3460,15 @@ function tiktokCatalogTools(provider, accessManagement = false) {
|
|
|
3350
3460
|
}
|
|
3351
3461
|
|
|
3352
3462
|
// src/catalogs.ts
|
|
3353
|
-
var id4 =
|
|
3354
|
-
var nativeCatalog =
|
|
3463
|
+
var id4 = z22.string().regex(/^\d{1,30}$/);
|
|
3464
|
+
var nativeCatalog = z22.looseObject({ catalog_id: id4, catalog_name: z22.string(), catalog_type: z22.string(), bc_info: z22.looseObject({ bc_id: id4, bc_name: z22.string().optional() }), catalog_conf: z22.record(z22.string(), z22.unknown()) });
|
|
3355
3465
|
var canonical12 = (value) => JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
|
|
3356
3466
|
var config3 = (value) => ({ catalog_id: value.catalog_id, catalog_name: value.catalog_name, catalog_type: value.catalog_type, bc_id: value.bc_info.bc_id, catalog_conf: value.catalog_conf });
|
|
3357
|
-
var configurationHash3 = (account, value) =>
|
|
3467
|
+
var configurationHash3 = (account, value) => createHash14("sha256").update(canonical12({ account_id: account, ...config3(value) })).digest("hex");
|
|
3358
3468
|
var scopeOf = (input) => ({ accountId: input.account_id, businessId: input.bc_id, resourceId: input.catalog_id, kind: "catalog" });
|
|
3359
3469
|
var nativeError = (error) => {
|
|
3360
|
-
const details = error instanceof
|
|
3361
|
-
return new
|
|
3470
|
+
const details = error instanceof AdportError20 && error.details && typeof error.details === "object" ? error.details : {};
|
|
3471
|
+
return new AdportError20("PROVIDER_ERROR", "TikTok catalog request failed. Check the token\u2019s Business Center/catalog permissions and native API eligibility. No request was retried.", { ...Number.isInteger(details.code) ? { provider_code: details.code } : {}, ...typeof details.request_id === "string" && /^[a-zA-Z0-9_-]{1,128}$/.test(details.request_id) ? { request_id: details.request_id } : {} });
|
|
3362
3472
|
};
|
|
3363
3473
|
var TikTokCatalogService = class {
|
|
3364
3474
|
constructor(client, store, media) {
|
|
@@ -3375,6 +3485,7 @@ var TikTokCatalogService = class {
|
|
|
3375
3485
|
this.productAuthoring = new TikTokCatalogProductAuthoring(client, authorizeParent, this.feeds, this.products, media);
|
|
3376
3486
|
this.videos = new TikTokCatalogVideos(client, authorizeParent, media);
|
|
3377
3487
|
this.eventSources = new TikTokCatalogEventSources(client, authorizeParent);
|
|
3488
|
+
this.migration = new TikTokCatalogMigration(client, store, (input) => this.native(input, true));
|
|
3378
3489
|
this.lifecycle = new TikTokCatalogLifecycle(client, store, authorizeParent, (input) => this.native(input, true));
|
|
3379
3490
|
}
|
|
3380
3491
|
client;
|
|
@@ -3386,8 +3497,9 @@ var TikTokCatalogService = class {
|
|
|
3386
3497
|
videos;
|
|
3387
3498
|
eventSources;
|
|
3388
3499
|
lifecycle;
|
|
3500
|
+
migration;
|
|
3389
3501
|
manager() {
|
|
3390
|
-
if (!this.store?.canManage) throw new
|
|
3502
|
+
if (!this.store?.canManage) throw new AdportError20("POLICY_VIOLATION", "Only the local owner or a signed-in project owner/admin in Accounts can change catalog access.");
|
|
3391
3503
|
return this.store;
|
|
3392
3504
|
}
|
|
3393
3505
|
async native(input, allowAbsent = false) {
|
|
@@ -3395,21 +3507,21 @@ var TikTokCatalogService = class {
|
|
|
3395
3507
|
try {
|
|
3396
3508
|
data = await this.client.get("catalog/get", { bc_id: input.bc_id, catalog_id: input.catalog_id, page: 1, page_size: 1e3 });
|
|
3397
3509
|
} catch (error) {
|
|
3398
|
-
if (error instanceof
|
|
3510
|
+
if (error instanceof AdportError20 && ["POLICY_VIOLATION", "NOT_CONNECTED"].includes(error.code)) throw error;
|
|
3399
3511
|
throw nativeError(error);
|
|
3400
3512
|
}
|
|
3401
|
-
const result =
|
|
3402
|
-
if (!result.success || result.data.list.some((row3) => row3.catalog_id !== input.catalog_id || row3.bc_info.bc_id !== input.bc_id) || result.data.page_info && (result.data.page_info.page !== 1 || result.data.page_info.total_page > 1 || !result.data.list.length && typeof result.data.page_info.total_number === "number" && result.data.page_info.total_number !== 0)) throw new
|
|
3513
|
+
const result = z22.looseObject({ list: allowAbsent ? z22.array(nativeCatalog).max(1) : z22.array(nativeCatalog).length(1), page_info: z22.looseObject({ page: z22.number().int().positive(), total_page: z22.number().int().nonnegative() }).optional() }).safeParse(data);
|
|
3514
|
+
if (!result.success || result.data.list.some((row3) => row3.catalog_id !== input.catalog_id || row3.bc_info.bc_id !== input.bc_id) || result.data.page_info && (result.data.page_info.page !== 1 || result.data.page_info.total_page > 1 || !result.data.list.length && typeof result.data.page_info.total_number === "number" && result.data.page_info.total_number !== 0)) throw new AdportError20("PROVIDER_ERROR", "TikTok returned an unexpected catalog/Business Center scope or incomplete exact-ID response.");
|
|
3403
3515
|
return result.data.list[0];
|
|
3404
3516
|
}
|
|
3405
3517
|
async access(accountId) {
|
|
3406
3518
|
id4.parse(accountId);
|
|
3407
3519
|
const grants = await this.store?.list(accountId) ?? [];
|
|
3408
|
-
if (grants.some((value) => value.scope.accountId !== accountId)) throw new
|
|
3520
|
+
if (grants.some((value) => value.scope.accountId !== accountId)) throw new AdportError20("POLICY_VIOLATION", "Catalog grants do not match the selected advertiser.");
|
|
3409
3521
|
return { grants, records: grants.map((value) => ({ id: value.scope.resourceId, name: value.scope.kind === "catalog" ? "Catalog " + value.scope.resourceId : "Catalog creation", business_center_id: value.scope.businessId, access: value.mode })), notes: ["Only explicit project grants are returned. An advertiser account does not implicitly authorize other Business Center assets."] };
|
|
3410
3522
|
}
|
|
3411
3523
|
async accessSnapshot(value) {
|
|
3412
|
-
const input = catalogPermissionSnapshot.parse(value), scope = input.resource_kind === "catalog_creation" ? creationScope(input.account_id, input.bc_id) : scopeOf({ ...input, catalog_id: input.catalog_id }), grant = await this.manager().get(scope);
|
|
3524
|
+
const input = catalogPermissionSnapshot.parse(value), scope = input.resource_kind === "catalog_migration" ? migrationScope(input.account_id, input.bc_id, input.catalog_id) : input.resource_kind === "catalog_creation" ? creationScope(input.account_id, input.bc_id) : scopeOf({ ...input, catalog_id: input.catalog_id }), grant = await this.manager().get(scope);
|
|
3413
3525
|
return { grant, records: [{ id: scope.resourceId, name: scope.kind === "catalog_creation" ? "Creation delegation" : "Catalog access", business_center_id: input.bc_id, access: grant.mode }] };
|
|
3414
3526
|
}
|
|
3415
3527
|
async get(value) {
|
|
@@ -3419,6 +3531,7 @@ var TikTokCatalogService = class {
|
|
|
3419
3531
|
return { catalog: data, records: [{ id: catalog.catalog_id, name: catalog.catalog_name, native_ad_eligibility: catalog.ad_creation_eligible ?? "Not reported", type: catalog.catalog_type, business_center: catalog.bc_info.bc_name ?? input.bc_id, currency: catalog.catalog_conf.currency ?? "Not reported", country: catalog.catalog_conf.country ?? "Not reported" }] };
|
|
3420
3532
|
}
|
|
3421
3533
|
async plan(op) {
|
|
3534
|
+
if (op.tool === "tiktok_migrate_catalog") return this.migration.plan(op);
|
|
3422
3535
|
if (["tiktok_create_catalog", "tiktok_delete_catalog"].includes(op.tool)) return this.lifecycle.plan(op);
|
|
3423
3536
|
if (["tiktok_bind_catalog_event_sources", "tiktok_unbind_catalog_event_sources"].includes(op.tool)) return this.eventSources.plan(op);
|
|
3424
3537
|
if (["tiktok_upload_catalog_videos", "tiktok_delete_catalog_video"].includes(op.tool)) return this.videos.plan(op);
|
|
@@ -3426,52 +3539,53 @@ var TikTokCatalogService = class {
|
|
|
3426
3539
|
if (op.tool === "tiktok_import_catalog_file") return this.products.plan(op);
|
|
3427
3540
|
if (["tiktok_create_catalog_feed", "tiktok_update_catalog_feed", "tiktok_set_catalog_feed_schedule_status", "tiktok_delete_catalog_feed"].includes(op.tool)) return this.feeds.plan(op);
|
|
3428
3541
|
if (["tiktok_create_product_set", "tiktok_upload_product_set", "tiktok_update_product_set_conditions", "tiktok_delete_product_sets", "tiktok_rename_product_set"].includes(op.tool)) return this.productSets.plan(op);
|
|
3429
|
-
if (op.provider !== "tiktok" || op.kind !== "update") throw new
|
|
3542
|
+
if (op.provider !== "tiktok" || op.kind !== "update") throw new AdportError20("INVALID_INPUT", "TikTok catalog provider/operation kind mismatch.");
|
|
3430
3543
|
const account = id4.parse(op.accountId);
|
|
3431
3544
|
if (op.tool === "tiktok_set_catalog_access") {
|
|
3432
|
-
const store = this.manager(), input2 = catalogAccessChange.parse(op.payload), scope2 = input2.resource_kind === "catalog_creation" ? creationScope(account, input2.bc_id) : scopeOf({ ...input2, account_id: account, catalog_id: input2.catalog_id }), current2 = await store.get(scope2);
|
|
3433
|
-
if (current2.hash !== input2.expected_access_hash) throw new
|
|
3434
|
-
const creation = scope2.kind === "catalog_creation";
|
|
3545
|
+
const store = this.manager(), input2 = catalogAccessChange.parse(op.payload), scope2 = input2.resource_kind === "catalog_migration" ? migrationScope(account, input2.bc_id, input2.catalog_id) : input2.resource_kind === "catalog_creation" ? creationScope(account, input2.bc_id) : scopeOf({ ...input2, account_id: account, catalog_id: input2.catalog_id }), current2 = await store.get(scope2);
|
|
3546
|
+
if (current2.hash !== input2.expected_access_hash) throw new AdportError20("POLICY_VIOLATION", "Catalog access changed. Read and review it again.");
|
|
3547
|
+
const creation = scope2.kind === "catalog_creation", migration = scope2.kind === "catalog_migration";
|
|
3548
|
+
if (migration && input2.mode !== "none") await this.migration.destination(input2.bc_id);
|
|
3435
3549
|
if (creation && input2.mode !== "none") await this.lifecycle.availableCountries(input2.bc_id);
|
|
3436
|
-
const catalog = creation || input2.mode === "none" ? void 0 : await this.native({ account_id: account, bc_id: input2.bc_id, catalog_id: input2.catalog_id });
|
|
3437
|
-
const title = input2.mode === "none" ? "Revoke catalog access" : creation ? "Delegate catalog creation" : "Grant catalog access",
|
|
3550
|
+
const catalog = creation || migration || input2.mode === "none" ? void 0 : await this.native({ account_id: account, bc_id: input2.bc_id, catalog_id: input2.catalog_id });
|
|
3551
|
+
const title = input2.mode === "none" ? "Revoke catalog access" : creation ? "Delegate catalog creation" : migration ? "Delegate owner-attested catalog transfer" : "Grant catalog access", notes8 = ["This changes Adport project access, not TikTok\u2019s native user permissions.", "Write access covers this Business Center catalog wherever it is reused. Agents cannot expand their own hosted access.", ...migration ? ["The owner attests ownership of this exact source-advertiser catalog and authorizes moving it to this exact Business Center. Source ownership is not independently verified by Adport; TikTok checks it at apply.", "This permits only the reviewed ownership transfer. Catalog creation and ongoing read/write management require separate grants. The whole shared catalog and its consumers may be affected."] : [], ...creation ? ["Delegates creation in this exact Business Center and read/write management of verified new catalog IDs only. Existing catalogs are excluded.", "Revoking creation delegation does not revoke independent grants already issued for new catalogs. Native eligibility remains authoritative."] : []];
|
|
3438
3552
|
return {
|
|
3439
3553
|
summary: `${title} \xB7 ${catalog?.catalog_name ?? (creation ? "Business Center " + input2.bc_id : input2.catalog_id)}`,
|
|
3440
3554
|
changes: [`~ Project access ${current2.mode} \u2192 ${input2.mode} for Business Center ${input2.bc_id}, ${creation ? "new catalogs only" : "catalog " + input2.catalog_id}`],
|
|
3441
3555
|
coercions: [],
|
|
3442
3556
|
budgetDeltas: [],
|
|
3443
|
-
notes:
|
|
3444
|
-
review: { provider: "tiktok", accountId: account, kind: "update", title, subject: catalog?.catalog_name ?? (creation ? "Business Center " + input2.bc_id : input2.catalog_id), fields: [{ label: "Business Center", after: catalog?.bc_info.bc_name ?? input2.bc_id }, { label: creation ? "Resource" : "Catalog", after: creation ? "New catalogs created through this project" : input2.catalog_id }, { label: "Project access", before: current2.mode, after: input2.mode === "create" ? "Create and manage verified new catalogs" : input2.mode }], notices:
|
|
3557
|
+
notes: notes8,
|
|
3558
|
+
review: { provider: "tiktok", accountId: account, kind: "update", title, subject: catalog?.catalog_name ?? (creation ? "Business Center " + input2.bc_id : input2.catalog_id), fields: [{ label: "Business Center", after: catalog?.bc_info.bc_name ?? input2.bc_id }, { label: creation ? "Resource" : "Catalog", after: creation ? "New catalogs created through this project" : input2.catalog_id }, { label: "Project access", before: current2.mode, after: input2.mode === "create" ? "Create and manage verified new catalogs" : input2.mode === "migrate" ? "Transfer this owner-attested source catalog only" : input2.mode }], notices: notes8 },
|
|
3445
3559
|
execute: async () => {
|
|
3446
3560
|
const result = await store.compareAndSet(scope2, input2.expected_access_hash, input2.mode), actual = await store.get(scope2);
|
|
3447
|
-
if (catalogScopeKey(result.scope) !== catalogScopeKey(scope2) || result.mode !== input2.mode || actual.hash !== result.hash) throw new
|
|
3561
|
+
if (catalogScopeKey(result.scope) !== catalogScopeKey(scope2) || result.mode !== input2.mode || actual.hash !== result.hash) throw new AdportError20("POLICY_VIOLATION", "Catalog access receipt is unconfirmed. Inspect access before retrying.");
|
|
3448
3562
|
return [scope2.resourceId];
|
|
3449
3563
|
}
|
|
3450
3564
|
};
|
|
3451
3565
|
}
|
|
3452
|
-
if (op.tool !== "tiktok_update_catalog") throw new
|
|
3566
|
+
if (op.tool !== "tiktok_update_catalog") throw new AdportError20("INVALID_INPUT", "Unsupported TikTok catalog mutation.");
|
|
3453
3567
|
const input = catalogRename.parse(op.payload), source2 = { account_id: account, bc_id: input.bc_id, catalog_id: input.catalog_id }, scope = scopeOf(source2);
|
|
3454
3568
|
await requireCatalogAccess(this.store, scope, true);
|
|
3455
3569
|
const current = await this.native(source2);
|
|
3456
|
-
if (configurationHash3(account, current) !== input.expected_configuration_hash) throw new
|
|
3457
|
-
const
|
|
3570
|
+
if (configurationHash3(account, current) !== input.expected_configuration_hash) throw new AdportError20("INVALID_INPUT", "Catalog configuration changed. Read and preview it again.");
|
|
3571
|
+
const notes7 = ["Local preview only; TikTok checks native permissions and eligibility on apply.", "The catalog may be reused by other ads or accounts. This operation updates its name and does not activate ads or change a budget.", "No automatic retry. Inspect the exact catalog after an uncertain result."];
|
|
3458
3572
|
return {
|
|
3459
3573
|
summary: `Rename TikTok catalog ${current.catalog_name}`,
|
|
3460
3574
|
changes: [`~ Catalog name ${JSON.stringify(current.catalog_name)} \u2192 ${JSON.stringify(input.name)}`],
|
|
3461
3575
|
coercions: [],
|
|
3462
3576
|
budgetDeltas: [],
|
|
3463
|
-
notes:
|
|
3464
|
-
review: { provider: "tiktok", accountId: account, kind: "update", title: "Rename catalog", subject: current.catalog_name, fields: [{ label: "Name", before: current.catalog_name, after: input.name }, { label: "Business Center", after: current.bc_info.bc_name ?? input.bc_id }], notices:
|
|
3577
|
+
notes: notes7,
|
|
3578
|
+
review: { provider: "tiktok", accountId: account, kind: "update", title: "Rename catalog", subject: current.catalog_name, fields: [{ label: "Name", before: current.catalog_name, after: input.name }, { label: "Business Center", after: current.bc_info.bc_name ?? input.bc_id }], notices: notes7 },
|
|
3465
3579
|
execute: async () => {
|
|
3466
3580
|
await requireCatalogAccess(this.store, scope, true);
|
|
3467
3581
|
try {
|
|
3468
|
-
const result =
|
|
3582
|
+
const result = z22.object({ catalog_id: id4 }).parse(await this.client.post("catalog/update", { bc_id: input.bc_id, catalog_id: input.catalog_id, name: input.name }));
|
|
3469
3583
|
if (result.catalog_id !== input.catalog_id) throw new Error("ID differs");
|
|
3470
3584
|
const actual = await this.native(source2);
|
|
3471
3585
|
if (canonical12(config3(actual)) !== canonical12({ ...config3(current), catalog_name: input.name })) throw new Error("Configuration differs");
|
|
3472
3586
|
return [input.catalog_id];
|
|
3473
3587
|
} catch {
|
|
3474
|
-
throw new
|
|
3588
|
+
throw new AdportError20("PROVIDER_ERROR", "TikTok catalog rename outcome is unconfirmed. Read the known catalog before another write; do not replay automatically.", { resource_ids: [input.catalog_id] });
|
|
3475
3589
|
}
|
|
3476
3590
|
}
|
|
3477
3591
|
};
|
|
@@ -3479,29 +3593,29 @@ var TikTokCatalogService = class {
|
|
|
3479
3593
|
};
|
|
3480
3594
|
|
|
3481
3595
|
// src/audience-sharing.ts
|
|
3482
|
-
import { createHash as
|
|
3483
|
-
import { AdportError as
|
|
3484
|
-
import { z as
|
|
3596
|
+
import { createHash as createHash15 } from "crypto";
|
|
3597
|
+
import { AdportError as AdportError21 } from "@adport/core";
|
|
3598
|
+
import { z as z24 } from "zod";
|
|
3485
3599
|
|
|
3486
3600
|
// src/audience-sharing-schemas.ts
|
|
3487
|
-
import { z as
|
|
3488
|
-
var selectedIds =
|
|
3489
|
-
var sharingSelection =
|
|
3601
|
+
import { z as z23 } from "zod";
|
|
3602
|
+
var selectedIds = z23.array(audienceId).min(1).max(10).refine((values) => new Set(values).size === values.length, "Use unique IDs");
|
|
3603
|
+
var sharingSelection = z23.object({ custom_audience_ids: selectedIds, shared_advertiser_ids: selectedIds }).strict();
|
|
3490
3604
|
var audienceSharesRead = sharingSelection.safeExtend({ account_id: audienceId });
|
|
3491
|
-
var audienceSharingContext = audienceSharesRead.safeExtend({ bc_id: audienceId, action:
|
|
3492
|
-
var shareAudiences = sharingSelection.safeExtend({ bc_id: audienceId, expected_context_hash:
|
|
3493
|
-
var unshareAudience =
|
|
3605
|
+
var audienceSharingContext = audienceSharesRead.safeExtend({ bc_id: audienceId, action: z23.enum(["SHARE", "UNSHARE"]).default("SHARE") }).refine((value) => value.action !== "UNSHARE" || value.custom_audience_ids.length === 1 && value.shared_advertiser_ids.length === 1, "Cancellation selects one audience/recipient pair");
|
|
3606
|
+
var shareAudiences = sharingSelection.safeExtend({ bc_id: audienceId, expected_context_hash: z23.string().regex(/^[a-f0-9]{64}$/), acknowledge_recipient_access: z23.literal(true) });
|
|
3607
|
+
var unshareAudience = z23.object({ bc_id: audienceId, custom_audience_id: audienceId, shared_advertiser_id: audienceId, expected_context_hash: z23.string().regex(/^[a-f0-9]{64}$/), acknowledge_shared_effects: z23.literal(true) }).strict();
|
|
3494
3608
|
var audienceSharingWrites = /* @__PURE__ */ new Set(["tiktok_share_custom_audiences", "tiktok_unshare_custom_audience"]);
|
|
3495
3609
|
|
|
3496
3610
|
// src/audience-sharing.ts
|
|
3497
3611
|
var canonical13 = (value) => JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
|
|
3498
|
-
var
|
|
3499
|
-
var nativeShare =
|
|
3500
|
-
var asset =
|
|
3501
|
-
var pageInfo6 =
|
|
3612
|
+
var hash13 = (value) => createHash15("sha256").update(canonical13(value)).digest("hex");
|
|
3613
|
+
var nativeShare = z24.object({ custom_audience_id: audienceNativeId, shared_advertiser_id: audienceNativeId, shared_advertiser_name: z24.string().max(4096), status: z24.string().max(128) });
|
|
3614
|
+
var asset = z24.object({ asset_id: audienceNativeId, asset_type: z24.literal("ADVERTISER"), asset_name: z24.string().max(4096), advertiser_role: z24.string().max(128) });
|
|
3615
|
+
var pageInfo6 = z24.object({ page: z24.number().int().positive().safe(), page_size: z24.number().int().min(1).max(50), total_page: z24.number().int().nonnegative().safe().optional(), total_number: z24.number().int().nonnegative().safe().optional() });
|
|
3502
3616
|
var supported = /* @__PURE__ */ new Set(["Customer File Audience", "Engagement Audience", "App Activity Audience", "Website Audience", "Lookalike Audience"]);
|
|
3503
3617
|
var notices = ["This changes audience access for the selected destination advertisers. Revocation can affect ads already targeting a shared audience. No ad, budget or delivery status is changed.", "Business Center membership and source role are checked from the authorized user\u2019s native asset view. Native eligibility, account ownership requirements, quotas and concurrent operations remain authoritative.", "Sharing-log presence and native audience status are separate from matching, targetability or delivery. No conditional-write, atomic batch or automatic replay is available."];
|
|
3504
|
-
var invalid9 = () => new
|
|
3618
|
+
var invalid9 = () => new AdportError21("PROVIDER_ERROR", "TikTok sharing scope, native representation or inventory completeness could not be verified.");
|
|
3505
3619
|
var preserved = (row3) => {
|
|
3506
3620
|
const { shared: _shared, ...configuration4 } = configuration(row3);
|
|
3507
3621
|
return configuration4;
|
|
@@ -3519,16 +3633,16 @@ var TikTokAudienceSharing = class {
|
|
|
3519
3633
|
try {
|
|
3520
3634
|
return await this.client.get(path2, input);
|
|
3521
3635
|
} catch (error) {
|
|
3522
|
-
const details = error instanceof
|
|
3523
|
-
throw new
|
|
3636
|
+
const details = error instanceof AdportError21 && error.details && typeof error.details === "object" ? error.details : {};
|
|
3637
|
+
throw new AdportError21("PROVIDER_ERROR", "TikTok audience sharing read failed. Check existing native permissions; no access was changed.", { ...Number.isSafeInteger(details.code) ? { native_code: details.code } : {} });
|
|
3524
3638
|
}
|
|
3525
3639
|
}
|
|
3526
3640
|
owned(account, row3, share) {
|
|
3527
|
-
if (row3.is_creator !== true || row3.owner_id !== account) throw new
|
|
3528
|
-
if (share && (!supported.has(row3.type.trim()) || row3.is_valid !== true || row3.is_expiring !== false || row3.native_error_reported)) throw new
|
|
3641
|
+
if (row3.is_creator !== true || row3.owner_id !== account) throw new AdportError21("POLICY_VIOLATION", "Audience sharing requires explicit selected-advertiser ownership; recipient access is insufficient.");
|
|
3642
|
+
if (share && (!supported.has(row3.type.trim()) || row3.is_valid !== true || row3.is_expiring !== false || row3.native_error_reported)) throw new AdportError21("INVALID_INPUT", "Only a documented shareable, available, non-expiring audience without a native error can be shared.");
|
|
3529
3643
|
}
|
|
3530
3644
|
async log(account, audience) {
|
|
3531
|
-
const parsed =
|
|
3645
|
+
const parsed = z24.object({ list: z24.array(nativeShare).max(5e3) }).safeParse(await this.get("dmp/custom_audience/share/log", { advertiser_id: account, custom_audience_id: audience }));
|
|
3532
3646
|
if (!parsed.success || parsed.data.list.some((row3) => row3.custom_audience_id !== audience) || new Set(parsed.data.list.map((row3) => row3.shared_advertiser_id)).size !== parsed.data.list.length) throw invalid9();
|
|
3533
3647
|
return parsed.data.list.sort((a, b) => a.shared_advertiser_id.localeCompare(b.shared_advertiser_id));
|
|
3534
3648
|
}
|
|
@@ -3538,7 +3652,7 @@ var TikTokAudienceSharing = class {
|
|
|
3538
3652
|
return rows;
|
|
3539
3653
|
}
|
|
3540
3654
|
selection(account, targets) {
|
|
3541
|
-
if (targets.includes(account)) throw new
|
|
3655
|
+
if (targets.includes(account)) throw new AdportError21("INVALID_INPUT", "Choose destination advertisers other than the source.");
|
|
3542
3656
|
}
|
|
3543
3657
|
view(logs, targets) {
|
|
3544
3658
|
return [...logs.values()].flat().filter((row3) => targets.includes(row3.shared_advertiser_id));
|
|
@@ -3556,7 +3670,7 @@ var TikTokAudienceSharing = class {
|
|
|
3556
3670
|
const wanted = /* @__PURE__ */ new Set([source2, ...targets]), found = /* @__PURE__ */ new Map(), seen = /* @__PURE__ */ new Set();
|
|
3557
3671
|
let complete = false;
|
|
3558
3672
|
for (let page3 = 1; page3 <= 100; page3++) {
|
|
3559
|
-
const parsed =
|
|
3673
|
+
const parsed = z24.object({ list: z24.array(asset).max(50), page_info: pageInfo6.optional() }).safeParse(await this.get("bc/asset/get", { bc_id: bc, asset_type: "ADVERTISER", page: page3, page_size: 50 }));
|
|
3560
3674
|
if (!parsed.success || parsed.data.page_info && (parsed.data.page_info.page !== page3 || parsed.data.page_info.page_size !== 50)) throw invalid9();
|
|
3561
3675
|
const info = parsed.data.page_info;
|
|
3562
3676
|
if (info && (info.total_page !== void 0 && info.total_page < page3 && parsed.data.list.length > 0 || info.total_number !== void 0 && (parsed.data.list.length !== Math.max(0, Math.min(50, info.total_number - (page3 - 1) * 50)) || info.total_page !== void 0 && (info.total_number === 0 ? info.total_page > 1 : info.total_page !== Math.ceil(info.total_number / 50))))) throw invalid9();
|
|
@@ -3572,8 +3686,8 @@ var TikTokAudienceSharing = class {
|
|
|
3572
3686
|
break;
|
|
3573
3687
|
}
|
|
3574
3688
|
}
|
|
3575
|
-
if (found.size !== wanted.size) throw new
|
|
3576
|
-
if (!["ADMIN", "OPERATOR"].includes(found.get(source2).advertiser_role)) throw new
|
|
3689
|
+
if (found.size !== wanted.size) throw new AdportError21("INVALID_INPUT", complete ? "Selected source/destination accounts are not all accessible in this Business Center." : "Business Center membership is unconfirmed; inventory is incomplete.");
|
|
3690
|
+
if (!["ADMIN", "OPERATOR"].includes(found.get(source2).advertiser_role)) throw new AdportError21("POLICY_VIOLATION", "Audience sharing requires the authorized user to be Admin or Operator on the source advertiser.");
|
|
3577
3691
|
return [...found.values()].sort((a, b) => a.asset_id.localeCompare(b.asset_id));
|
|
3578
3692
|
}
|
|
3579
3693
|
async prepare(value) {
|
|
@@ -3584,7 +3698,7 @@ var TikTokAudienceSharing = class {
|
|
|
3584
3698
|
audiences.forEach((row3) => this.owned(input.account_id, row3, input.action === "SHARE"));
|
|
3585
3699
|
const logs = await this.logs(input.account_id, input.custom_audience_ids);
|
|
3586
3700
|
const fingerprint = { input, accounts, audiences: audiences.map((row3) => ({ snapshot_hash: row3.snapshot_hash, configuration: preserved(row3) })), logs: [...logs].map(([id6, rows]) => [id6, rows.map(({ shared_advertiser_name: _name, ...row3 }) => row3)]) };
|
|
3587
|
-
return { input, accounts, audiences, logs, context_hash:
|
|
3701
|
+
return { input, accounts, audiences, logs, context_hash: hash13(fingerprint) };
|
|
3588
3702
|
}
|
|
3589
3703
|
async context(value) {
|
|
3590
3704
|
const current = await this.prepare(value), selected5 = this.view(current.logs, current.input.shared_advertiser_ids);
|
|
@@ -3592,14 +3706,14 @@ var TikTokAudienceSharing = class {
|
|
|
3592
3706
|
}
|
|
3593
3707
|
async plan(op) {
|
|
3594
3708
|
const share = op.tool === "tiktok_share_custom_audiences";
|
|
3595
|
-
if (op.provider !== "tiktok" || op.kind !== "update" || !share && op.tool !== "tiktok_unshare_custom_audience") throw new
|
|
3709
|
+
if (op.provider !== "tiktok" || op.kind !== "update" || !share && op.tool !== "tiktok_unshare_custom_audience") throw new AdportError21("INVALID_INPUT", "Unsupported audience-sharing operation/provider kind.");
|
|
3596
3710
|
const selected5 = share ? shareAudiences.parse(op.payload) : unshareAudience.parse(op.payload), input = share ? { account_id: op.accountId, ...shareAudiences.parse(selected5), action: "SHARE" } : { account_id: op.accountId, bc_id: selected5.bc_id, custom_audience_ids: [unshareAudience.parse(selected5).custom_audience_id], shared_advertiser_ids: [unshareAudience.parse(selected5).shared_advertiser_id], action: "UNSHARE" };
|
|
3597
3711
|
const selection = audienceSharingContext.parse(Object.fromEntries(Object.entries(input).filter(([key2]) => !["expected_context_hash", "acknowledge_recipient_access"].includes(key2))));
|
|
3598
|
-
if (canonical13([...new Set(op.affectedAccountIds ?? [])].sort()) !== canonical13([...selection.shared_advertiser_ids].sort())) throw new
|
|
3712
|
+
if (canonical13([...new Set(op.affectedAccountIds ?? [])].sort()) !== canonical13([...selection.shared_advertiser_ids].sort())) throw new AdportError21("POLICY_VIOLATION", "All destination accounts must be bound to the shared policy operation.");
|
|
3599
3713
|
const current = await this.prepare(selection);
|
|
3600
|
-
if (current.context_hash !== selected5.expected_context_hash) throw new
|
|
3714
|
+
if (current.context_hash !== selected5.expected_context_hash) throw new AdportError21("PENDING_MISMATCH", "Audience sharing, source configuration or account authority changed; read and preview again.");
|
|
3601
3715
|
const existing = this.view(current.logs, selection.shared_advertiser_ids);
|
|
3602
|
-
if (share ? existing.length > 0 : existing.length !== 1) throw new
|
|
3716
|
+
if (share ? existing.length > 0 : existing.length !== 1) throw new AdportError21("INVALID_INPUT", share ? "A selected audience/recipient pair already appears in the sharing log. Reconcile partial outcomes and select only intended new pairs; do not replay sharing." : "The exact audience/recipient pair is not present in the current explicit sharing log.");
|
|
3603
3717
|
const title = share ? "Share custom audiences" : "Revoke audience sharing";
|
|
3604
3718
|
return { summary: title, changes: current.audiences.map((row3) => `${share ? "+" : "-"} ${row3.name} \xB7 ${selection.shared_advertiser_ids.length} recipient(s)`), coercions: [], budgetDeltas: [], notes: notices, review: { provider: "tiktok", accountId: op.accountId, kind: "update", title, fields: [{ label: "Business Center", after: selection.bc_id }, { label: "Owned audiences", after: current.audiences.map((row3) => ({ id: row3.audience_id, name: row3.name, type: row3.type })) }, { label: "Recipient accounts", after: current.accounts.filter((row3) => row3.asset_id !== op.accountId).map((row3) => ({ id: row3.asset_id, name: row3.asset_name })) }, { label: "Audience access", before: share ? "Not shared with selected recipients" : "Shared with selected recipient", after: share ? "Grant selected recipients access" : "Revoke selected recipient access" }], notices }, execute: async () => {
|
|
3605
3719
|
const outcomes = [];
|
|
@@ -3617,8 +3731,8 @@ var TikTokAudienceSharing = class {
|
|
|
3617
3731
|
if (after.some((row3) => canonical13(preserved(row3)) !== canonical13(preserved(current.audiences.find((before) => before.audience_id === row3.audience_id))))) throw invalid9();
|
|
3618
3732
|
return { applied: true, resourceIds: selection.custom_audience_ids, details: { state: share ? "RECIPIENT_PAIRS_OBSERVED" : "RECIPIENT_PAIR_ABSENT", outcomes, audience_configuration_preserved: true, audience_availability_verified: false, ads_changed: false, next_tool: "tiktok_custom_audience_shares", next_arguments: { account_id: op.accountId, custom_audience_ids: selection.custom_audience_ids, shared_advertiser_ids: selection.shared_advertiser_ids } }, ...share ? { warnings: ["Recipient pairs are present in the native sharing log. Audience targeting availability remains unverified; inspect native status before use."] } : {} };
|
|
3619
3733
|
} catch (error) {
|
|
3620
|
-
const details = error instanceof
|
|
3621
|
-
throw new
|
|
3734
|
+
const details = error instanceof AdportError21 && error.details && typeof error.details === "object" ? error.details : {};
|
|
3735
|
+
throw new AdportError21("PROVIDER_ERROR", "Audience sharing outcome is unconfirmed. Reconcile every selected pair in the sharing log before a new preview. No mutation was retried.", { resourceIds: selection.custom_audience_ids, observed_pairs: outcomes, ...Number.isSafeInteger(details.code) ? { native_code: details.code } : {} });
|
|
3622
3736
|
}
|
|
3623
3737
|
} };
|
|
3624
3738
|
}
|
|
@@ -3644,7 +3758,7 @@ var TikTokAdsProvider = class {
|
|
|
3644
3758
|
this.app = app;
|
|
3645
3759
|
const authorizeAccounts = async (ids2) => {
|
|
3646
3760
|
const authorized = await client.get("oauth2/advertiser/get", { app_id: this.appId(), secret: this.secret() });
|
|
3647
|
-
if (!Array.isArray(authorized.list) || authorized.list.some((row3) => typeof row3.advertiser_id !== "string") || ids2.some((id6) => !authorized.list.some((row3) => row3.advertiser_id === id6))) throw new
|
|
3761
|
+
if (!Array.isArray(authorized.list) || authorized.list.some((row3) => typeof row3.advertiser_id !== "string") || ids2.some((id6) => !authorized.list.some((row3) => row3.advertiser_id === id6))) throw new AdportError22("POLICY_VIOLATION", "Every selected advertiser must be in the current native authorization.");
|
|
3648
3762
|
};
|
|
3649
3763
|
this.creatives = new TikTokCreativeService(client, media);
|
|
3650
3764
|
this.audiences = new TikTokAudienceService(client);
|
|
@@ -3800,6 +3914,7 @@ var TikTokAdsProvider = class {
|
|
|
3800
3914
|
const resourceIds2 = await plan.execute();
|
|
3801
3915
|
if (!Array.isArray(resourceIds2)) return resourceIds2;
|
|
3802
3916
|
if (op.tool === "tiktok_create_catalog") return { applied: true, resourceIds: resourceIds2, details: { configuration_readback: "VERIFIED", project_catalog_access: "write", products_created: false, ads_created: false } };
|
|
3917
|
+
if (op.tool === "tiktok_migrate_catalog") return { applied: true, resourceIds: resourceIds2, details: { destination_catalog_readback: "VERIFIED", source_ownership: "OWNER_ATTESTED_NATIVE_ENFORCED", project_catalog_access: "UNCHANGED" } };
|
|
3803
3918
|
if (op.tool === "tiktok_delete_catalog") return { applied: true, resourceIds: resourceIds2, details: { deletion_readback: "ABSENT_FROM_FILTERED_CATALOG_VIEW", resource_grant_retained: true } };
|
|
3804
3919
|
if (op.tool === "tiktok_upload_catalog_videos") {
|
|
3805
3920
|
const payload3 = op.payload;
|
|
@@ -3826,6 +3941,7 @@ var TikTokAdsProvider = class {
|
|
|
3826
3941
|
if (["tiktok_upload_audience_file", "tiktok_create_customer_audience", "tiktok_update_customer_audience_users", "tiktok_rename_custom_audience", "tiktok_delete_custom_audiences"].includes(op.tool)) return this.customAudiences.plan(op);
|
|
3827
3942
|
const payload3 = op.payload;
|
|
3828
3943
|
switch (op.tool) {
|
|
3944
|
+
case "tiktok_migrate_catalog":
|
|
3829
3945
|
case "tiktok_create_catalog":
|
|
3830
3946
|
case "tiktok_delete_catalog":
|
|
3831
3947
|
case "tiktok_bind_catalog_event_sources":
|
|
@@ -3878,7 +3994,7 @@ var TikTokAdsProvider = class {
|
|
|
3878
3994
|
case "tiktok_api_delete":
|
|
3879
3995
|
return this.planApiDelete(op.accountId, payload3);
|
|
3880
3996
|
default:
|
|
3881
|
-
throw new
|
|
3997
|
+
throw new AdportError22("PROVIDER_ERROR", `tiktok: unsupported write tool ${op.tool}`);
|
|
3882
3998
|
}
|
|
3883
3999
|
}
|
|
3884
4000
|
async planApiCreate(accountId, payload3, guard) {
|
|
@@ -3910,7 +4026,7 @@ var TikTokAdsProvider = class {
|
|
|
3910
4026
|
async planApiUpdate(accountId, payload3) {
|
|
3911
4027
|
const path2 = validateTikTokMutationPath(payload3.path, "update");
|
|
3912
4028
|
if (containsTikTokBudget(payload3.body)) {
|
|
3913
|
-
throw new
|
|
4029
|
+
throw new AdportError22("INVALID_INPUT", "tiktok: budget updates require a typed budget tool for policy checks");
|
|
3914
4030
|
}
|
|
3915
4031
|
const body = { ...payload3.body, advertiser_id: accountId };
|
|
3916
4032
|
return {
|
|
@@ -3940,7 +4056,7 @@ var TikTokAdsProvider = class {
|
|
|
3940
4056
|
coercions.push("operation_status coerced to DISABLE (paused) by policy (paused_creation)");
|
|
3941
4057
|
}
|
|
3942
4058
|
if (payload3.budget_mode !== "BUDGET_MODE_INFINITE" && !payload3.budget) {
|
|
3943
|
-
throw new
|
|
4059
|
+
throw new AdportError22("INVALID_INPUT", `tiktok: budget is required for ${payload3.budget_mode}`);
|
|
3944
4060
|
}
|
|
3945
4061
|
const budgetDeltas = [];
|
|
3946
4062
|
if (payload3.budget) {
|
|
@@ -3971,7 +4087,7 @@ var TikTokAdsProvider = class {
|
|
|
3971
4087
|
}
|
|
3972
4088
|
async planSetStatus(accountId, payload3) {
|
|
3973
4089
|
const campaigns = await this.listCampaigns(accountId, payload3.campaign_ids);
|
|
3974
|
-
if (payload3.campaign_ids.some((id6) => !campaigns.some((campaign) => campaign.campaign_id === id6 && (campaign.advertiser_id === void 0 || campaign.advertiser_id === accountId)))) throw new
|
|
4090
|
+
if (payload3.campaign_ids.some((id6) => !campaigns.some((campaign) => campaign.campaign_id === id6 && (campaign.advertiser_id === void 0 || campaign.advertiser_id === accountId)))) throw new AdportError22("INVALID_INPUT", "tiktok: campaign was not found in the selected advertiser");
|
|
3975
4091
|
const changes = payload3.campaign_ids.map((id6) => {
|
|
3976
4092
|
const campaign = campaigns.find((c) => c.campaign_id === id6);
|
|
3977
4093
|
return `~ campaign ${id6} ("${campaign?.campaign_name ?? "?"}") operation_status ${campaign?.operation_status ?? "?"} \u2192 ${payload3.operation_status}`;
|
|
@@ -3995,10 +4111,10 @@ var TikTokAdsProvider = class {
|
|
|
3995
4111
|
const campaigns = await this.listCampaigns(accountId, [payload3.campaign_id]);
|
|
3996
4112
|
const campaign = campaigns.find((campaign2) => campaign2.campaign_id === payload3.campaign_id);
|
|
3997
4113
|
if (!campaign || campaign.advertiser_id !== void 0 && campaign.advertiser_id !== accountId) {
|
|
3998
|
-
throw new
|
|
4114
|
+
throw new AdportError22("PROVIDER_ERROR", `tiktok: campaign ${payload3.campaign_id} not found in advertiser ${accountId}`);
|
|
3999
4115
|
}
|
|
4000
4116
|
if (campaign.budget_mode === "BUDGET_MODE_INFINITE") {
|
|
4001
|
-
throw new
|
|
4117
|
+
throw new AdportError22("PROVIDER_ERROR", `tiktok: campaign "${campaign.campaign_name}" has no budget (BUDGET_MODE_INFINITE)`);
|
|
4002
4118
|
}
|
|
4003
4119
|
return {
|
|
4004
4120
|
summary: `Change TikTok campaign "${campaign.campaign_name}" budget ${campaign.budget} \u2192 ${payload3.budget} (${campaign.budget_mode})`,
|
|
@@ -4037,17 +4153,17 @@ function round2(n) {
|
|
|
4037
4153
|
function validateTikTokPath(path2) {
|
|
4038
4154
|
const normalized = path2.replace(/^\/+|\/+$/g, "").trim();
|
|
4039
4155
|
if (!/^[a-z0-9_/-]{3,160}$/.test(normalized) || normalized.includes("..") || normalized.includes("//")) {
|
|
4040
|
-
throw new
|
|
4156
|
+
throw new AdportError22("INVALID_INPUT", `tiktok: invalid Business API path "${path2}"`);
|
|
4041
4157
|
}
|
|
4042
4158
|
return normalized;
|
|
4043
4159
|
}
|
|
4044
4160
|
function validateTikTokMutationPath(path2, kind2) {
|
|
4045
4161
|
const normalized = validateTikTokPath(path2);
|
|
4046
4162
|
if (normalized.startsWith("optimizer/rule/")) {
|
|
4047
|
-
throw new
|
|
4163
|
+
throw new AdportError22("INVALID_INPUT", "tiktok: automated-rule mutations require a verified direct-advertiser workflow with scheduled-action budget and account checks; raw dispatch cannot enforce these limits");
|
|
4048
4164
|
}
|
|
4049
4165
|
if (!normalized.endsWith(`/${kind2}`)) {
|
|
4050
|
-
throw new
|
|
4166
|
+
throw new AdportError22("INVALID_INPUT", `tiktok: ${kind2} tool requires an endpoint ending in /${kind2}`);
|
|
4051
4167
|
}
|
|
4052
4168
|
return normalized;
|
|
4053
4169
|
}
|
|
@@ -4108,41 +4224,41 @@ function extractTikTokIds(value) {
|
|
|
4108
4224
|
|
|
4109
4225
|
// src/tools.ts
|
|
4110
4226
|
import { defineTool as defineTool9, guardedWriteTool as guardedWriteTool8 } from "@adport/core";
|
|
4111
|
-
import { z as
|
|
4227
|
+
import { z as z28 } from "zod";
|
|
4112
4228
|
|
|
4113
4229
|
// src/creative-tools.ts
|
|
4114
4230
|
import { creativesOutput as creativesOutput2, defineTool as defineTool5, guardedWriteTool as guardedWriteTool4, mediaSourceFields as mediaSourceFields3 } from "@adport/core";
|
|
4115
|
-
import { z as
|
|
4116
|
-
var id5 =
|
|
4117
|
-
var status2 =
|
|
4118
|
-
var page2 = { page:
|
|
4119
|
-
var url =
|
|
4231
|
+
import { z as z25 } from "zod";
|
|
4232
|
+
var id5 = z25.string().regex(/^\d+$/);
|
|
4233
|
+
var status2 = z25.enum(["ENABLE", "DISABLE"]);
|
|
4234
|
+
var page2 = { page: z25.number().int().positive().default(1), page_size: z25.number().int().positive().max(1e3).default(100) };
|
|
4235
|
+
var url = z25.string().url().refine((value) => {
|
|
4120
4236
|
const u = new URL(value);
|
|
4121
4237
|
return ["https:", "http:"].includes(u.protocol) && !u.username && !u.password;
|
|
4122
4238
|
});
|
|
4123
|
-
var strings2 =
|
|
4124
|
-
var targetingShape = { location_ids: strings2.optional(), zipcode_ids: strings2.optional(), age_groups: strings2.optional(), gender:
|
|
4125
|
-
var targeting =
|
|
4126
|
-
var groupPayload =
|
|
4127
|
-
var creative =
|
|
4239
|
+
var strings2 = z25.array(z25.string().min(1));
|
|
4240
|
+
var targetingShape = { location_ids: strings2.optional(), zipcode_ids: strings2.optional(), age_groups: strings2.optional(), gender: z25.string().min(1).optional(), languages: strings2.optional(), operating_systems: strings2.optional(), interest_category_ids: strings2.optional(), interest_keyword_ids: strings2.optional(), audience_ids: strings2.optional(), excluded_audience_ids: strings2.optional(), network_types: strings2.optional(), device_model_ids: strings2.optional(), dayparting: z25.string().regex(/^[01]{336}$/).optional(), smart_audience_enabled: z25.boolean().optional(), smart_interest_behavior_enabled: z25.boolean().optional() };
|
|
4241
|
+
var targeting = z25.object(targetingShape).strict();
|
|
4242
|
+
var groupPayload = z25.object({ campaign_id: id5, adgroup_name: z25.string().trim().min(1).max(512), promotion_type: z25.string().min(1), placement_type: z25.enum(["PLACEMENT_TYPE_AUTOMATIC", "PLACEMENT_TYPE_NORMAL"]), placements: strings2.min(1).optional(), budget_mode: z25.enum(["BUDGET_MODE_DAY", "BUDGET_MODE_TOTAL"]), budget: z25.number().positive(), optimization_goal: z25.string().min(1), billing_event: z25.string().min(1), bid_type: z25.enum(["BID_TYPE_CUSTOM", "BID_TYPE_NO_BID"]), bid_price: z25.number().positive().optional(), conversion_bid_price: z25.number().positive().optional(), pacing: z25.enum(["PACING_MODE_SMOOTH", "PACING_MODE_FAST"]), schedule_type: z25.enum(["SCHEDULE_FROM_NOW", "SCHEDULE_START_END"]), schedule_start_time: z25.string().regex(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/), schedule_end_time: z25.string().regex(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/).optional(), pixel_id: id5.optional(), optimization_event: z25.string().min(1).optional(), app_id: z25.string().min(1).optional(), targeting, operation_status: status2.default("DISABLE") }).refine((value) => value.placement_type !== "PLACEMENT_TYPE_NORMAL" || Boolean(value.placements?.length), "Manual placement requires placements").refine((value) => value.schedule_type !== "SCHEDULE_START_END" || Boolean(value.schedule_end_time && value.schedule_end_time > value.schedule_start_time), "Scheduled end must be after start");
|
|
4243
|
+
var creative = z25.object({ ad_name: z25.string().trim().min(1).max(512), ad_format: z25.enum(["SINGLE_VIDEO", "SINGLE_IMAGE", "CAROUSEL_ADS"]), ad_text: z25.string().min(1).max(100).optional(), identity_type: z25.string().min(1), identity_id: z25.string().min(1), identity_authorized_bc_id: id5.optional(), video_id: z25.string().min(1).optional(), image_ids: strings2.min(1).optional(), tiktok_item_id: id5.optional(), landing_page_url: url.optional(), call_to_action: z25.string().min(1).optional(), display_name: z25.string().min(1).optional(), operation_status: status2.default("DISABLE") }).refine((value) => value.ad_format !== "SINGLE_VIDEO" || Boolean(value.video_id || value.tiktok_item_id), "Video ads require video_id or an authorized tiktok_item_id").refine((value) => value.ad_format === "SINGLE_VIDEO" || Boolean(value.image_ids?.length), "Image/carousel ads require image_ids").refine((value) => !(value.video_id && value.tiktok_item_id), "Choose video_id or tiktok_item_id").refine((value) => Boolean(value.tiktok_item_id || value.ad_text), "Non-Spark ads require ad_text");
|
|
4128
4244
|
function tiktokCreativeTools(provider) {
|
|
4129
4245
|
const read = (name3, description, input, handler) => defineTool5({ name: name3, namespace: "tiktok", description, input, annotations: { readOnly: true }, handler });
|
|
4130
4246
|
const write = (name3, description, payload3, kind2 = "update") => guardedWriteTool4({ name: name3, namespace: "tiktok", provider: "tiktok", description, payload: payload3, kind: kind2 });
|
|
4131
4247
|
return [
|
|
4132
|
-
read("tiktok_ad_groups", "Read native ad-group targeting, budgets, bidding, schedules and statuses with pagination.",
|
|
4133
|
-
defineTool5({ name: "tiktok_ads", namespace: "tiktok", description: "Read native TikTok ad configuration and copy with guarded text/status edit actions. Media previews use URLs returned by TikTok.", input:
|
|
4134
|
-
read("tiktok_videos", "Search the advertiser video library with native filtering and pagination.",
|
|
4135
|
-
read("tiktok_image_info", "Read advertiser image IDs, dimensions and returned preview URLs.",
|
|
4136
|
-
read("tiktok_video_info", "Read advertiser video IDs, processing metadata and returned playback/cover URLs.",
|
|
4137
|
-
read("tiktok_search_targeting", "Search location/zip targeting tags using TikTok\u2019s read-only POST endpoint. Targeting eligibility depends on objective, placement and promotion type.",
|
|
4248
|
+
read("tiktok_ad_groups", "Read native ad-group targeting, budgets, bidding, schedules and statuses with pagination.", z25.object({ account_id: id5, campaign_ids: z25.array(id5).optional(), ad_group_ids: z25.array(id5).optional(), ...page2 }), (input) => provider.creatives.groups(input)),
|
|
4249
|
+
defineTool5({ name: "tiktok_ads", namespace: "tiktok", description: "Read native TikTok ad configuration and copy with guarded text/status edit actions. Media previews use URLs returned by TikTok.", input: z25.object({ account_id: id5, ad_group_ids: z25.array(id5).optional(), ad_ids: z25.array(id5).optional(), ...page2 }), output: creativesOutput2.extend({ ads: z25.array(z25.record(z25.string(), z25.unknown())), page_info: z25.unknown().optional() }), presentation: "creatives", annotations: { readOnly: true }, handler: (input) => provider.creatives.ads(input) }),
|
|
4250
|
+
read("tiktok_videos", "Search the advertiser video library with native filtering and pagination.", z25.object({ account_id: id5, filtering: z25.record(z25.string(), z25.unknown()).optional(), ...page2 }), (input) => provider.creatives.read("file/video/ad/search", input)),
|
|
4251
|
+
read("tiktok_image_info", "Read advertiser image IDs, dimensions and returned preview URLs.", z25.object({ account_id: id5, image_ids: strings2.min(1).max(100) }), (input) => provider.creatives.read("file/image/ad/info", input)),
|
|
4252
|
+
read("tiktok_video_info", "Read advertiser video IDs, processing metadata and returned playback/cover URLs.", z25.object({ account_id: id5, video_ids: strings2.min(1).max(100) }), (input) => provider.creatives.read("file/video/ad/info", input)),
|
|
4253
|
+
read("tiktok_search_targeting", "Search location/zip targeting tags using TikTok\u2019s read-only POST endpoint. Targeting eligibility depends on objective, placement and promotion type.", z25.object({ account_id: id5, keywords: strings2.min(1).max(1e3), search_type: z25.enum(["FUZZY_SEARCH", "BATCH_REGION_SEARCH", "BATCH_ZIPCODE_SEARCH"]).default("FUZZY_SEARCH"), objective_type: z25.string().min(1), promotion_type: z25.string().min(1).optional(), placements: strings2.min(1), region_codes: strings2.optional(), geo_types: strings2.optional() }).refine((value) => value.search_type !== "FUZZY_SEARCH" || value.keywords.length === 1, "Fuzzy search takes one keyword"), (input) => provider.creatives.read("tool/targeting/search", input, true)),
|
|
4138
4254
|
write("tiktok_create_ad_group", "Create an advertiser-owned ad group with explicit objective-dependent settings. Budgets/bids are whole currency units; schedules use advertiser time. Policy may force DISABLE.", groupPayload, "create"),
|
|
4139
|
-
write("tiktok_create_ads", "Create up to 20 standard or Spark ads in an account-owned ad group. Use existing authorized identity and media IDs. Policy may force every creative to DISABLE.",
|
|
4140
|
-
...["ad_group", "ad"].map((entity) => write(`tiktok_set_${entity}_status`, "Enable or pause verified advertiser-owned child entities. Parent serving settings remain independent.",
|
|
4141
|
-
write("tiktok_update_ad", "Patch supplied ad text/name, landing page or media IDs in its verified ad group. Uses patch_update=true; serving status and omitted creative fields are preserved.",
|
|
4142
|
-
write("tiktok_update_targeting", "Replace only supplied ad-group targeting dimensions. Omitted targeting and serving settings remain unchanged; supplied arrays replace existing lists.",
|
|
4143
|
-
write("tiktok_set_ad_group_budget", "Change a verified ad-group budget in whole account-currency units. Current/proposed amounts are policy-checked; TikTok also enforces spend-based minimums.",
|
|
4144
|
-
write("tiktok_set_ad_group_bidding", "Edit supplied ad-group bids and target ROAS. Monetary bids use whole account-currency units and current-value policy checks. Serving status remains unchanged.",
|
|
4145
|
-
...["image", "video"].map((type) => write(`tiktok_upload_${type}`, `Upload advertiser ${type} bytes with SHA-256-bound approval and TikTok MD5 signature. Hosted calls require media_id; file_path is local-only. Adport limits: images10MiB, videos100MiB.`,
|
|
4255
|
+
write("tiktok_create_ads", "Create up to 20 standard or Spark ads in an account-owned ad group. Use existing authorized identity and media IDs. Policy may force every creative to DISABLE.", z25.object({ ad_group_id: id5, creatives: z25.array(creative).min(1).max(20) }), "create"),
|
|
4256
|
+
...["ad_group", "ad"].map((entity) => write(`tiktok_set_${entity}_status`, "Enable or pause verified advertiser-owned child entities. Parent serving settings remain independent.", z25.object({ [entity === "ad_group" ? "ad_group_ids" : "ad_ids"]: z25.array(id5).min(1).max(20).refine((value) => new Set(value).size === value.length, "IDs must be unique"), operation_status: status2 }))),
|
|
4257
|
+
write("tiktok_update_ad", "Patch supplied ad text/name, landing page or media IDs in its verified ad group. Uses patch_update=true; serving status and omitted creative fields are preserved.", z25.object({ ad_group_id: id5, ad_id: id5, ad_name: z25.string().min(1).max(512).optional(), ad_text: z25.string().min(1).max(100).optional(), landing_page_url: url.optional(), video_id: z25.string().min(1).optional(), image_ids: strings2.min(1).optional() }).refine((value) => ["ad_name", "ad_text", "landing_page_url", "video_id", "image_ids"].some((key2) => value[key2] !== void 0), "Provide a creative field")),
|
|
4258
|
+
write("tiktok_update_targeting", "Replace only supplied ad-group targeting dimensions. Omitted targeting and serving settings remain unchanged; supplied arrays replace existing lists.", z25.object({ ad_group_id: id5, targeting: targeting.refine((value) => Object.keys(value).length > 0, "Provide a targeting dimension") })),
|
|
4259
|
+
write("tiktok_set_ad_group_budget", "Change a verified ad-group budget in whole account-currency units. Current/proposed amounts are policy-checked; TikTok also enforces spend-based minimums.", z25.object({ ad_group_id: id5, budget: z25.number().positive() })),
|
|
4260
|
+
write("tiktok_set_ad_group_bidding", "Edit supplied ad-group bids and target ROAS. Monetary bids use whole account-currency units and current-value policy checks. Serving status remains unchanged.", z25.object({ ad_group_id: id5, bid_price: z25.number().positive().optional(), conversion_bid_price: z25.number().positive().optional(), roas_bid: z25.number().positive().optional() }).refine((value) => ["bid_price", "conversion_bid_price", "roas_bid"].some((key2) => value[key2] !== void 0), "Provide a bid field")),
|
|
4261
|
+
...["image", "video"].map((type) => write(`tiktok_upload_${type}`, `Upload advertiser ${type} bytes with SHA-256-bound approval and TikTok MD5 signature. Hosted calls require media_id; file_path is local-only. Adport limits: images10MiB, videos100MiB.`, z25.object({ ...mediaSourceFields3 }).refine((value) => Number(Boolean(value.file_path)) + Number(Boolean(value.media_id)) === 1, "Choose media_id or file_path"), "create"))
|
|
4146
4262
|
];
|
|
4147
4263
|
}
|
|
4148
4264
|
|
|
@@ -4162,10 +4278,10 @@ function tiktokCustomAudienceTools(provider) {
|
|
|
4162
4278
|
}
|
|
4163
4279
|
|
|
4164
4280
|
// src/audience-authoring-tools.ts
|
|
4165
|
-
import { z as
|
|
4281
|
+
import { z as z26 } from "zod";
|
|
4166
4282
|
import { defineTool as defineTool7, guardedWriteTool as guardedWriteTool6 } from "@adport/core";
|
|
4167
4283
|
function tiktokAudienceAuthoringTools(provider) {
|
|
4168
|
-
const catalog = { category: "audiences", exposure: "specialist" }, read = { namespace: "tiktok", catalog, presentation: "records", annotations: { readOnly: true }, output:
|
|
4284
|
+
const catalog = { category: "audiences", exposure: "specialist" }, read = { namespace: "tiktok", catalog, presentation: "records", annotations: { readOnly: true }, output: z26.looseObject({ records: z26.array(z26.record(z26.string(), z26.unknown())) }) }, write = { namespace: "tiktok", provider: "tiktok", catalog };
|
|
4169
4285
|
return [
|
|
4170
4286
|
defineTool7({ ...read, name: "tiktok_identities", description: "Page identities already linked to the advertiser. Preserves native identity/BC references and availability; BC queries may include other linked identities. Creates no identity or permissions. Exact video source use rechecks identity/info.", input: audienceIdentityList, pagination: { cursorInput: "page", cursorOutput: "next_page" }, handler: (input) => provider.audienceSources.identities(input) }),
|
|
4171
4287
|
defineTool7({ ...read, name: "tiktok_audience_sources", description: "Discover advertiser-scoped event sources for all nine rule-audience families. Pages apps, pixels, ad groups, stores, offline sets and exact-identity videos. Source filters and cursors stay bound; organic history has a native 500-post window.", input: audienceSourceList, pagination: { cursorInput: "cursor" }, handler: (input) => provider.audienceSources.list(input) }),
|
|
@@ -4178,9 +4294,9 @@ function tiktokAudienceAuthoringTools(provider) {
|
|
|
4178
4294
|
|
|
4179
4295
|
// src/audience-sharing-tools.ts
|
|
4180
4296
|
import { defineTool as defineTool8, guardedWriteTool as guardedWriteTool7 } from "@adport/core";
|
|
4181
|
-
import { z as
|
|
4297
|
+
import { z as z27 } from "zod";
|
|
4182
4298
|
function tiktokAudienceSharingTools(provider) {
|
|
4183
|
-
const shared = { namespace: "tiktok", catalog: { category: "audiences", exposure: "specialist" } }, read = { ...shared, output:
|
|
4299
|
+
const shared = { namespace: "tiktok", catalog: { category: "audiences", exposure: "specialist" } }, read = { ...shared, output: z27.looseObject({ records: z27.array(z27.record(z27.string(), z27.unknown())) }), presentation: "records", annotations: { readOnly: true }, additionalAccountInputs: ["shared_advertiser_ids"] }, write = { ...shared, provider: "tiktok", kind: "update", destructive: true };
|
|
4184
4300
|
return [
|
|
4185
4301
|
defineTool8({ ...read, name: "tiktok_custom_audience_shares", description: "Read owned audience sharing logs for explicit destination accounts. Hosted scope requires source and destinations enabled in this project. Other recipient names/IDs stay hidden. Native status is preserved; missing list data does not prove absence.", input: audienceSharesRead, handler: (input) => provider.audienceSharing.read(input) }),
|
|
4186
4302
|
defineTool8({ ...read, name: "tiktok_audience_sharing_context", description: "Check selected owned audiences, native authorization, source Admin/Operator role and selected accounts in one Business Center. Returns context_hash for SHARE or singular UNSHARE, with exact existing pairs. No access is changed.", input: audienceSharingContext, handler: (input) => provider.audienceSharing.context(input) }),
|
|
@@ -4200,7 +4316,7 @@ var OBJECTIVES = [
|
|
|
4200
4316
|
"WEB_CONVERSIONS",
|
|
4201
4317
|
"PRODUCT_SALES"
|
|
4202
4318
|
];
|
|
4203
|
-
var operationStatusSchema =
|
|
4319
|
+
var operationStatusSchema = z28.enum(["ENABLE", "DISABLE"]);
|
|
4204
4320
|
function tiktokTools(provider, options = {}) {
|
|
4205
4321
|
return [
|
|
4206
4322
|
...tiktokCreativeTools(provider),
|
|
@@ -4215,10 +4331,10 @@ function tiktokTools(provider, options = {}) {
|
|
|
4215
4331
|
name: "tiktok_api_read",
|
|
4216
4332
|
namespace: "tiktok",
|
|
4217
4333
|
description: "Call any documented TikTok Business API v1.3 GET endpoint with advertiser scoping and API-shaped parameters.",
|
|
4218
|
-
input:
|
|
4219
|
-
account_id:
|
|
4220
|
-
path:
|
|
4221
|
-
params:
|
|
4334
|
+
input: z28.object({
|
|
4335
|
+
account_id: z28.string(),
|
|
4336
|
+
path: z28.string().min(3).describe("Relative endpoint, e.g. adgroup/get, ad/get, creative/report/get"),
|
|
4337
|
+
params: z28.record(z28.string(), z28.unknown()).optional()
|
|
4222
4338
|
}),
|
|
4223
4339
|
annotations: { readOnly: true },
|
|
4224
4340
|
async handler(input) {
|
|
@@ -4229,9 +4345,9 @@ function tiktokTools(provider, options = {}) {
|
|
|
4229
4345
|
name: "tiktok_campaigns",
|
|
4230
4346
|
namespace: "tiktok",
|
|
4231
4347
|
description: "List TikTok campaigns (id, name, operation_status ENABLE/DISABLE, budget, budget_mode, objective).",
|
|
4232
|
-
input:
|
|
4233
|
-
account_id:
|
|
4234
|
-
campaign_ids:
|
|
4348
|
+
input: z28.object({
|
|
4349
|
+
account_id: z28.string().describe("Advertiser id"),
|
|
4350
|
+
campaign_ids: z28.array(z28.string()).optional()
|
|
4235
4351
|
}),
|
|
4236
4352
|
annotations: { readOnly: true },
|
|
4237
4353
|
async handler(input) {
|
|
@@ -4243,14 +4359,14 @@ function tiktokTools(provider, options = {}) {
|
|
|
4243
4359
|
name: "tiktok_report",
|
|
4244
4360
|
namespace: "tiktok",
|
|
4245
4361
|
description: "Raw TikTok synchronous reporting (report/integrated). Metric values come back as strings; note total_complete_payment_rate is total purchase VALUE (misleading name), complete_payment_roas is purchase ROAS.",
|
|
4246
|
-
input:
|
|
4247
|
-
account_id:
|
|
4248
|
-
data_level:
|
|
4249
|
-
dimensions:
|
|
4250
|
-
metrics:
|
|
4251
|
-
start_date:
|
|
4252
|
-
end_date:
|
|
4253
|
-
page_size:
|
|
4362
|
+
input: z28.object({
|
|
4363
|
+
account_id: z28.string(),
|
|
4364
|
+
data_level: z28.enum(["AUCTION_ADVERTISER", "AUCTION_CAMPAIGN", "AUCTION_ADGROUP", "AUCTION_AD"]).default("AUCTION_CAMPAIGN"),
|
|
4365
|
+
dimensions: z28.array(z28.string()).min(1).default(["campaign_id"]),
|
|
4366
|
+
metrics: z28.array(z28.string()).min(1).default(["spend", "impressions", "clicks", "conversion"]),
|
|
4367
|
+
start_date: z28.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
|
4368
|
+
end_date: z28.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
|
4369
|
+
page_size: z28.number().int().positive().max(1e3).default(200)
|
|
4254
4370
|
}),
|
|
4255
4371
|
annotations: { readOnly: true },
|
|
4256
4372
|
async handler(input) {
|
|
@@ -4264,11 +4380,11 @@ function tiktokTools(provider, options = {}) {
|
|
|
4264
4380
|
description: "Create a TikTok campaign. Budget is a float in whole account-currency units (min ~20 USD-equivalent for DAY/TOTAL modes). TikTok has no server-side dry run \u2014 the preview is a client-side diff.",
|
|
4265
4381
|
provider: "tiktok",
|
|
4266
4382
|
kind: "create",
|
|
4267
|
-
payload:
|
|
4268
|
-
campaign_name:
|
|
4269
|
-
objective_type:
|
|
4270
|
-
budget_mode:
|
|
4271
|
-
budget:
|
|
4383
|
+
payload: z28.object({
|
|
4384
|
+
campaign_name: z28.string().min(1).max(512),
|
|
4385
|
+
objective_type: z28.enum(OBJECTIVES).default("TRAFFIC"),
|
|
4386
|
+
budget_mode: z28.enum(["BUDGET_MODE_DAY", "BUDGET_MODE_TOTAL", "BUDGET_MODE_INFINITE"]).default("BUDGET_MODE_DAY"),
|
|
4387
|
+
budget: z28.number().positive().optional().describe("Whole currency units (float), required unless BUDGET_MODE_INFINITE"),
|
|
4272
4388
|
operation_status: operationStatusSchema.optional()
|
|
4273
4389
|
})
|
|
4274
4390
|
}),
|
|
@@ -4278,8 +4394,8 @@ function tiktokTools(provider, options = {}) {
|
|
|
4278
4394
|
description: "Enable or pause (DISABLE) up to 20 TikTok campaigns.",
|
|
4279
4395
|
provider: "tiktok",
|
|
4280
4396
|
kind: "update",
|
|
4281
|
-
payload:
|
|
4282
|
-
campaign_ids:
|
|
4397
|
+
payload: z28.object({
|
|
4398
|
+
campaign_ids: z28.array(z28.string()).min(1).max(20),
|
|
4283
4399
|
operation_status: operationStatusSchema
|
|
4284
4400
|
})
|
|
4285
4401
|
}),
|
|
@@ -4289,9 +4405,9 @@ function tiktokTools(provider, options = {}) {
|
|
|
4289
4405
|
description: "Change a TikTok campaign's budget (whole currency units). TikTok rejects new budgets below 105% of current spend.",
|
|
4290
4406
|
provider: "tiktok",
|
|
4291
4407
|
kind: "update",
|
|
4292
|
-
payload:
|
|
4293
|
-
campaign_id:
|
|
4294
|
-
budget:
|
|
4408
|
+
payload: z28.object({
|
|
4409
|
+
campaign_id: z28.string(),
|
|
4410
|
+
budget: z28.number().positive()
|
|
4295
4411
|
})
|
|
4296
4412
|
}),
|
|
4297
4413
|
guardedWriteTool8({
|
|
@@ -4300,7 +4416,7 @@ function tiktokTools(provider, options = {}) {
|
|
|
4300
4416
|
description: "Create through any documented TikTok Business API v1.3 /create endpoint. The advertiser is forced to account_id, campaign creation is paused, and budget fields are policy-checked.",
|
|
4301
4417
|
provider: "tiktok",
|
|
4302
4418
|
kind: "create",
|
|
4303
|
-
payload:
|
|
4419
|
+
payload: z28.object({ path: z28.string().min(3), body: z28.record(z28.string(), z28.unknown()) })
|
|
4304
4420
|
}),
|
|
4305
4421
|
guardedWriteTool8({
|
|
4306
4422
|
name: "tiktok_api_update",
|
|
@@ -4308,7 +4424,7 @@ function tiktokTools(provider, options = {}) {
|
|
|
4308
4424
|
description: "Update non-budget/non-bid fields through any documented TikTok Business API v1.3 /update endpoint. Monetary and target-ROAS edits require typed tools.",
|
|
4309
4425
|
provider: "tiktok",
|
|
4310
4426
|
kind: "update",
|
|
4311
|
-
payload:
|
|
4427
|
+
payload: z28.object({ path: z28.string().min(3), body: z28.record(z28.string(), z28.unknown()) })
|
|
4312
4428
|
}),
|
|
4313
4429
|
guardedWriteTool8({
|
|
4314
4430
|
name: "tiktok_api_delete",
|
|
@@ -4317,7 +4433,7 @@ function tiktokTools(provider, options = {}) {
|
|
|
4317
4433
|
provider: "tiktok",
|
|
4318
4434
|
kind: "remove",
|
|
4319
4435
|
destructive: true,
|
|
4320
|
-
payload:
|
|
4436
|
+
payload: z28.object({ path: z28.string().min(3), body: z28.record(z28.string(), z28.unknown()) })
|
|
4321
4437
|
})
|
|
4322
4438
|
];
|
|
4323
4439
|
}
|
|
@@ -4366,8 +4482,10 @@ export {
|
|
|
4366
4482
|
catalogScopeKey,
|
|
4367
4483
|
createTikTokModule,
|
|
4368
4484
|
creationScope,
|
|
4485
|
+
migrationScope,
|
|
4369
4486
|
requireCatalogAccess,
|
|
4370
4487
|
requireCatalogCreationAccess,
|
|
4488
|
+
requireCatalogMigrationAccess,
|
|
4371
4489
|
resolveTikTokCredentials,
|
|
4372
4490
|
tiktokCatalogTools,
|
|
4373
4491
|
tiktokTools
|