@koda-sl/baker-cli 0.379.0-dev.600795410 → 0.379.0-dev.bfd923423

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.
@@ -1,6 +1,4 @@
1
1
  import {
2
- cacheGet,
3
- cacheSet,
4
2
  handleConnectionError,
5
3
  needsConnectionFix,
6
4
  writeAdsJson
@@ -49,20 +47,11 @@ function handleMetaError(err) {
49
47
  process.exit(1);
50
48
  }
51
49
  var ACCOUNT_ID_RE = /^(act_)?[0-9]+$/;
52
- var META_ACCOUNTS_CACHE = { category: "meta-accounts", key: "accounts:scoped", ttlMs: 60 * 60 * 1e3 };
53
50
  function withActPrefix(id) {
54
51
  return id.startsWith("act_") ? id : `act_${id}`;
55
52
  }
56
- async function fetchConnectedAccounts(useCache) {
57
- if (useCache) {
58
- const cached = cacheGet(META_ACCOUNTS_CACHE.category, META_ACCOUNTS_CACHE.key);
59
- if (cached) return cached.data;
60
- }
61
- const data = await apiGet("/api/ads/meta/accounts", useCache ? {} : { "skip-cache": "true" });
62
- if (useCache) {
63
- cacheSet(META_ACCOUNTS_CACHE.category, META_ACCOUNTS_CACHE.key, data, META_ACCOUNTS_CACHE.ttlMs);
64
- }
65
- return data;
53
+ function fetchConnectedAccounts() {
54
+ return apiGet("/api/ads/meta/accounts", { "skip-cache": "true" });
66
55
  }
67
56
  function connectedAccountId(account) {
68
57
  const id = account.externalId ?? account.id ?? account.account_id;
@@ -86,7 +75,7 @@ async function resolveAccountIdArg(args) {
86
75
  }
87
76
  let accounts;
88
77
  try {
89
- accounts = await fetchConnectedAccounts(!args["no-cache"]);
78
+ accounts = await fetchConnectedAccounts();
90
79
  } catch (err) {
91
80
  if (err instanceof ApiError && needsConnectionFix(err.code, err.message)) {
92
81
  handleConnectionError("meta_ads", err.message);
@@ -111,7 +100,14 @@ async function resolveAccountIdArg(args) {
111
100
  return single.id;
112
101
  }
113
102
  if (connected.length === 0) {
114
- handleConnectionError("meta_ads");
103
+ writeAdsJson({
104
+ ok: false,
105
+ error: {
106
+ code: "MISSING_ACCOUNT_ID",
107
+ message: "Meta is connected, but no ad account is picked for this company. Pass --account-id or set BAKER_META_AD_ACCOUNT_ID. Run `baker ads meta accounts --include-all` to find IDs."
108
+ }
109
+ });
110
+ process.exit(1);
115
111
  }
116
112
  const list = connected.map((account) => ` ${account.id}${account.name ? ` ${account.name}` : ""}`).join("\n");
117
113
  writeAdsJson({
@@ -169,7 +165,6 @@ function statusFilterHints(rows, effectiveStatus, noun) {
169
165
  export {
170
166
  metaForbiddenFix,
171
167
  handleMetaError,
172
- META_ACCOUNTS_CACHE,
173
168
  resolveAccountIdArg,
174
169
  getDateRange,
175
170
  todayIso,
@@ -179,4 +174,4 @@ export {
179
174
  resolveEffectiveStatus,
180
175
  statusFilterHints
181
176
  };
182
- //# sourceMappingURL=chunk-MK4AIHRF.js.map
177
+ //# sourceMappingURL=chunk-KAOU6QLP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/ads/meta/shared.ts"],"sourcesContent":["import { ApiError, apiGet } from \"../../../client.ts\";\nimport { getEnv } from \"../../../env.ts\";\nimport { handleConnectionError, needsConnectionFix } from \"../../../error-handler.ts\";\nimport { writeAdsJson } from \"../output.ts\";\nimport type { AdsErrorEnvelope, QueryFix } from \"../types.ts\";\n\nconst DAY_MS = 86_400_000;\n\n/**\n * Meta answers a permission refusal (Graph codes 200/10/294) with a bare\n * \"Permissions error\" that covers two causes needing opposite remedies: a\n * consent grant the connection never got — nothing validates Meta's granted\n * scopes after connect, unlike HubSpot's `requireCapability` — or a role the\n * user lacks on one asset, since a Pixel/Dataset, Page or catalog lives in a\n * Business and is assigned separately from the ad account. Only the blast radius\n * separates them, so hand the agent that test rather than a verdict: guessing\n * \"reconnect\" wastes the user's time on an unassigned asset, and ruling it out\n * strands a connection that really is short a scope.\n */\nexport function metaForbiddenFix(message: string): QueryFix {\n return {\n action: \"reject\",\n explanation: [\n message,\n \"This is a permission refusal, not a dead connection, and Meta returns the same code for two causes with opposite remedies. Tell them apart by how much else works before you answer.\",\n \"If other reads on this account are ALSO refused (campaigns, ad sets, insights), the connection is short a permission it was never granted. Only the user can widen it, by reconnecting Meta from the dashboard.\",\n \"If those reads work and only this object is refused, the asset (pixel/dataset, Page, or catalog) belongs to a Business the connected user holds no role in. Ad-account access does not carry asset access and reconnecting cannot grant it — the client assigns that asset to the connected user or partner in Meta Business settings, under the asset's own section (Data sources → Datasets for a pixel).\",\n \"Either way do not retry the same call, and do not abort the wider job. Continue with what you can read, and state in your answer that this specific check could not run and why — never present the task as verified when this step was skipped.\",\n ].join(\"\\n\\n\"),\n };\n}\n\nexport function handleMetaError(err: unknown): never {\n if (err instanceof ApiError) {\n if (needsConnectionFix(err.code, err.message)) {\n handleConnectionError(\"meta_ads\", err.message);\n }\n const envelope: AdsErrorEnvelope = {\n ok: false,\n error: {\n code: err.code,\n message: err.message,\n fix: err.code === \"FORBIDDEN\" ? metaForbiddenFix(err.message) : { action: \"reject\", explanation: err.message },\n retryable: err.code === \"RATE_LIMITED\" || err.code === \"UNAVAILABLE\" || err.code === \"INTERNAL_ERROR\",\n },\n };\n writeAdsJson(envelope);\n process.exit(1);\n }\n const message = err instanceof Error ? err.message : \"Unexpected error\";\n writeAdsJson({ ok: false, error: { code: \"NETWORK_ERROR\", message } });\n process.exit(1);\n}\n\nconst ACCOUNT_ID_RE = /^(act_)?[0-9]+$/;\n\n/** A row of `/api/ads/meta/accounts` — the company's picked accounts, as `baker ads meta accounts` prints them. */\ninterface ConnectedMetaAccount {\n externalId?: string;\n id?: string;\n account_id?: string;\n name?: string;\n}\n\nfunction withActPrefix(id: string): string {\n return id.startsWith(\"act_\") ? id : `act_${id}`;\n}\n\n/**\n * Read past both caches — the CLI's disk cache and the backend's hour-long one:\n * an account picked since the last listing must turn a sole-account default\n * into a refusal at once, not an hour later.\n */\nfunction fetchConnectedAccounts(): Promise<ConnectedMetaAccount[]> {\n return apiGet<ConnectedMetaAccount[]>(\"/api/ads/meta/accounts\", { \"skip-cache\": \"true\" });\n}\n\nfunction connectedAccountId(account: ConnectedMetaAccount): string | undefined {\n const id = account.externalId ?? account.id ?? account.account_id;\n return id && ACCOUNT_ID_RE.test(id) ? withActPrefix(id) : undefined;\n}\n\n/**\n * The Meta ad account a command works on: `--account-id`, else\n * `BAKER_META_AD_ACCOUNT_ID`, else the company's only connected account — the\n * default `baker ads meta accounts` promises. With several connected, nothing\n * is picked for the agent: the refusal lists them so the next call can name one.\n */\nexport async function resolveAccountIdArg(args: Record<string, unknown>): Promise<string> {\n const fromArgs = args[\"account-id\"] as string | undefined;\n const id = fromArgs || getEnv().BAKER_META_AD_ACCOUNT_ID;\n if (id) {\n if (!ACCOUNT_ID_RE.test(id)) {\n writeAdsJson({\n ok: false,\n error: {\n code: \"INVALID_ACCOUNT_ID\",\n message: `Invalid account ID \"${id}\". Expected numeric ID, optionally prefixed with \"act_\".`,\n },\n });\n process.exit(1);\n }\n return withActPrefix(id);\n }\n\n let accounts: ConnectedMetaAccount[];\n try {\n accounts = await fetchConnectedAccounts();\n } catch (err) {\n if (err instanceof ApiError && needsConnectionFix(err.code, err.message)) {\n handleConnectionError(\"meta_ads\", err.message);\n }\n writeAdsJson({\n ok: false,\n error: {\n code: \"MISSING_ACCOUNT_ID\",\n message:\n \"Could not look up this company's Meta ad accounts. Pass --account-id or set BAKER_META_AD_ACCOUNT_ID. Run `baker ads meta accounts` to find IDs.\",\n },\n });\n process.exit(1);\n }\n\n const connected = accounts.flatMap((account) => {\n const accountId = connectedAccountId(account);\n return accountId ? [{ id: accountId, name: account.name }] : [];\n });\n const [single] = connected;\n if (connected.length === 1 && single) {\n process.stderr.write(`Using Meta ad account ${single.name ? `\"${single.name}\" ` : \"\"}(${single.id})\\n`);\n return single.id;\n }\n if (connected.length === 0) {\n writeAdsJson({\n ok: false,\n error: {\n code: \"MISSING_ACCOUNT_ID\",\n message:\n \"Meta is connected, but no ad account is picked for this company. Pass --account-id or set BAKER_META_AD_ACCOUNT_ID. Run `baker ads meta accounts --include-all` to find IDs.\",\n },\n });\n process.exit(1);\n }\n const list = connected.map((account) => ` ${account.id}${account.name ? ` ${account.name}` : \"\"}`).join(\"\\n\");\n writeAdsJson({\n ok: false,\n error: {\n code: \"MULTIPLE_ACCOUNTS\",\n message: `This company connected ${connected.length} Meta ad accounts. Pass --account-id or set BAKER_META_AD_ACCOUNT_ID:\\n${list}`,\n },\n });\n process.exit(1);\n}\n\nexport function getDateRange(args: Record<string, unknown>): { datePreset?: string; since?: string; until?: string } {\n const datePreset = args[\"date-preset\"] as string | undefined;\n const since = args.since as string | undefined;\n const until = args.until as string | undefined;\n if (since && until) return { since, until };\n return { datePreset: datePreset ?? \"last_7d\" };\n}\n\nexport function todayIso(): string {\n return new Date().toISOString().slice(0, 10);\n}\n\nexport function daysAgoIso(days: number): string {\n return new Date(Date.now() - days * DAY_MS).toISOString().slice(0, 10);\n}\n\nexport function csvOrJson(args: Record<string, unknown>): string {\n return (args.output as string | undefined) ?? \"json\";\n}\n\n/**\n * Matched by Meta itself, so finding one entity by name reads only the rows that\n * match instead of the whole account.\n */\nexport const NAME_CONTAINS_ARG = {\n type: \"string\",\n description:\n \"Only rows whose name contains this text, matched by Meta before anything is returned. Start here to find one entity by name: --name-contains octubre --all-statuses\",\n} as const;\n\n/**\n * Default to ACTIVE-only on listings — that's almost always what an AI agent or\n * a human glance wants. Pass `--effective-status ACTIVE,PAUSED` to override, or\n * `--all-statuses` to drop the filter entirely.\n */\nexport function resolveEffectiveStatus(args: Record<string, unknown>): string | undefined {\n if (args[\"all-statuses\"]) {\n return undefined;\n }\n const explicit = args[\"effective-status\"] as string | undefined;\n if (explicit) {\n return explicit;\n }\n return \"ACTIVE\";\n}\n\n/**\n * An empty listing under a status filter reads exactly like \"nothing exists\":\n * a paused campaign's ad sets are CAMPAIGN_PAUSED, so the ACTIVE default hides\n * every one of them. Say which filter produced the empty list and how to widen it.\n */\nexport function statusFilterHints(\n rows: ReadonlyArray<unknown>,\n effectiveStatus: string | undefined,\n noun: string,\n): string[] {\n if (rows.length > 0 || effectiveStatus === undefined) return [];\n if (effectiveStatus === \"ACTIVE\") {\n return [\n `No ACTIVE ${noun}. The ACTIVE filter hides paused, archived and in-review ones (under a paused campaign or ad set that is all of them), so this does NOT mean none exist. Re-run with --all-statuses before concluding there are none.`,\n ];\n }\n return [\n `No ${noun} with effective_status ${effectiveStatus}. Re-run with --all-statuses to see every status before concluding there are none.`,\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;AAMA,IAAM,SAAS;AAaR,SAAS,iBAAiB,SAA2B;AAC1D,SAAO;AAAA,IACL,QAAQ;AAAA,IACR,aAAa;AAAA,MACX;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,EAAE,KAAK,MAAM;AAAA,EACf;AACF;AAEO,SAAS,gBAAgB,KAAqB;AACnD,MAAI,eAAe,UAAU;AAC3B,QAAI,mBAAmB,IAAI,MAAM,IAAI,OAAO,GAAG;AAC7C,4BAAsB,YAAY,IAAI,OAAO;AAAA,IAC/C;AACA,UAAM,WAA6B;AAAA,MACjC,IAAI;AAAA,MACJ,OAAO;AAAA,QACL,MAAM,IAAI;AAAA,QACV,SAAS,IAAI;AAAA,QACb,KAAK,IAAI,SAAS,cAAc,iBAAiB,IAAI,OAAO,IAAI,EAAE,QAAQ,UAAU,aAAa,IAAI,QAAQ;AAAA,QAC7G,WAAW,IAAI,SAAS,kBAAkB,IAAI,SAAS,iBAAiB,IAAI,SAAS;AAAA,MACvF;AAAA,IACF;AACA,iBAAa,QAAQ;AACrB,YAAQ,KAAK,CAAC;AAAA,EAChB;AACA,QAAM,UAAU,eAAe,QAAQ,IAAI,UAAU;AACrD,eAAa,EAAE,IAAI,OAAO,OAAO,EAAE,MAAM,iBAAiB,QAAQ,EAAE,CAAC;AACrE,UAAQ,KAAK,CAAC;AAChB;AAEA,IAAM,gBAAgB;AAUtB,SAAS,cAAc,IAAoB;AACzC,SAAO,GA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ACxC,MAAI,UAAU;AACZ,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAOO,SAAS,kBACd,MACA,iBACA,MACU;AACV,MAAI,KAAK,SAAS,KAAK,oBAAoB,OAAW,QAAO,CAAC;AAC9D,MAAI,oBAAoB,UAAU;AAChC,WAAO;AAAA,MACL,aAAa,IAAI;AAAA,IACnB;AAAA,EACF;AACA,SAAO;AAAA,IACL,MAAM,IAAI,0BAA0B,eAAe;AAAA,EACrD;AACF;","names":[]}
package/dist/cli.js CHANGED
@@ -72,7 +72,6 @@ import {
72
72
  ytDlpBlockSignal
73
73
  } from "./chunk-CHJOTJTZ.js";
74
74
  import {
75
- META_ACCOUNTS_CACHE,
76
75
  NAME_CONTAINS_ARG,
77
76
  csvOrJson,
78
77
  daysAgoIso,
@@ -82,7 +81,7 @@ import {
82
81
  resolveEffectiveStatus,
83
82
  statusFilterHints,
84
83
  todayIso
85
- } from "./chunk-MK4AIHRF.js";
84
+ } from "./chunk-KAOU6QLP.js";
86
85
  import {
87
86
  buildQueryCacheKey,
88
87
  cacheGet,
@@ -24349,9 +24348,9 @@ Examples:
24349
24348
  run: async ({ args: args5 }) => {
24350
24349
  const includeAll = args5["include-all"] === true;
24351
24350
  const useCache = !args5["no-cache"];
24352
- const cacheKey = includeAll ? "accounts:all" : META_ACCOUNTS_CACHE.key;
24351
+ const cacheKey = `accounts:${includeAll ? "all" : "scoped"}`;
24353
24352
  if (useCache) {
24354
- const cached = cacheGet(META_ACCOUNTS_CACHE.category, cacheKey);
24353
+ const cached = cacheGet("meta-accounts", cacheKey);
24355
24354
  if (cached) {
24356
24355
  writeJsonEnvelope({
24357
24356
  ok: true,
@@ -24368,7 +24367,7 @@ Examples:
24368
24367
  if (!useCache) params["skip-cache"] = "true";
24369
24368
  const data = await apiGet("/api/ads/meta/accounts", params);
24370
24369
  if (useCache) {
24371
- cacheSet(META_ACCOUNTS_CACHE.category, cacheKey, data, META_ACCOUNTS_CACHE.ttlMs);
24370
+ cacheSet("meta-accounts", cacheKey, data, 60 * 60 * 1e3);
24372
24371
  }
24373
24372
  const fmt = csvOrJson(args5);
24374
24373
  if (fmt !== "json") {
@@ -26840,7 +26839,7 @@ Example: baker ads meta ads retag 120252158038400247 --url-tags "utm_source={{si
26840
26839
  const { apiPost: apiPost2 } = await import("./client-GR6YL3YX.js");
26841
26840
  const { requireChatId: requireChatId2 } = await import("./env-4P5HOGNA.js");
26842
26841
  const { writeJsonEnvelope: writeJsonEnvelope2 } = await import("./output-NMQXZF3Z.js");
26843
- const { handleMetaError: handleMetaError2 } = await import("./shared-DDBXEUL4.js");
26842
+ const { handleMetaError: handleMetaError2 } = await import("./shared-TD76Z3W2.js");
26844
26843
  try {
26845
26844
  const accountId = await bareAccountId2(args5);
26846
26845
  const urlTags = typeof args5["url-tags"] === "string" ? args5["url-tags"] : void 0;
@@ -26988,7 +26987,7 @@ function duplicateCommand2(entity, label) {
26988
26987
  const { apiPost: apiPost2 } = await import("./client-GR6YL3YX.js");
26989
26988
  const { requireChatId: requireChatId2 } = await import("./env-4P5HOGNA.js");
26990
26989
  const { writeJsonEnvelope: writeJsonEnvelope2 } = await import("./output-NMQXZF3Z.js");
26991
- const { handleMetaError: handleMetaError2 } = await import("./shared-DDBXEUL4.js");
26990
+ const { handleMetaError: handleMetaError2 } = await import("./shared-TD76Z3W2.js");
26992
26991
  try {
26993
26992
  const accountId = await bareAccountId2(args5);
26994
26993
  const chatId = requireChatId2();