@koda-sl/baker-cli 0.847.0 → 0.849.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.
Files changed (31) hide show
  1. package/README.md +5 -1
  2. package/dist/{accounts-S7CRQTBB.js → accounts-PVPBCV3W.js} +3 -3
  3. package/dist/{ads-2SBIPZJI.js → ads-NXIIU57V.js} +3 -3
  4. package/dist/{changes-JOJR4K4H.js → changes-SGLPIZL6.js} +3 -3
  5. package/dist/{chunk-3OZTT3XC.js → chunk-D4GVSSL3.js} +2 -2
  6. package/dist/{chunk-KR2OWPYB.js → chunk-HGEG5AJW.js} +73 -19
  7. package/dist/chunk-HGEG5AJW.js.map +1 -0
  8. package/dist/{chunk-52V3VGQI.js → chunk-MGHAKUDW.js} +38 -5
  9. package/dist/chunk-MGHAKUDW.js.map +1 -0
  10. package/dist/cli.js +1 -1
  11. package/dist/{currency-GMVPN52V.js → currency-L2VCDEKG.js} +3 -3
  12. package/dist/{google-BFBRJRZP.js → google-RRNBSRIF.js} +22 -13
  13. package/dist/google-RRNBSRIF.js.map +1 -0
  14. package/dist/{performance-GIUF4NDE.js → performance-3L7J4KQG.js} +4 -3
  15. package/dist/performance-3L7J4KQG.js.map +1 -0
  16. package/dist/{query-6UXOYBET.js → query-ZIV5EBKY.js} +4 -4
  17. package/dist/{search-terms-ZE364HEC.js → search-terms-32OOCXD7.js} +2 -2
  18. package/dist/{url-options-E6FNFBE3.js → url-options-HQWSPLSF.js} +3 -3
  19. package/package.json +1 -1
  20. package/dist/chunk-52V3VGQI.js.map +0 -1
  21. package/dist/chunk-KR2OWPYB.js.map +0 -1
  22. package/dist/google-BFBRJRZP.js.map +0 -1
  23. package/dist/performance-GIUF4NDE.js.map +0 -1
  24. /package/dist/{accounts-S7CRQTBB.js.map → accounts-PVPBCV3W.js.map} +0 -0
  25. /package/dist/{ads-2SBIPZJI.js.map → ads-NXIIU57V.js.map} +0 -0
  26. /package/dist/{changes-JOJR4K4H.js.map → changes-SGLPIZL6.js.map} +0 -0
  27. /package/dist/{chunk-3OZTT3XC.js.map → chunk-D4GVSSL3.js.map} +0 -0
  28. /package/dist/{currency-GMVPN52V.js.map → currency-L2VCDEKG.js.map} +0 -0
  29. /package/dist/{query-6UXOYBET.js.map → query-ZIV5EBKY.js.map} +0 -0
  30. /package/dist/{search-terms-ZE364HEC.js.map → search-terms-32OOCXD7.js.map} +0 -0
  31. /package/dist/{url-options-E6FNFBE3.js.map → url-options-HQWSPLSF.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/ads/google/query.ts","../src/commands/ads/google/preflight.ts","../src/commands/ads/google/conversion-mix.ts","../src/commands/ads/google/keyword-serving.ts","../src/commands/ads/google/money-units.ts","../src/commands/ads/google/stable-order.ts"],"sourcesContent":["import { appendFileSync, existsSync, readFileSync, renameSync, rmSync, writeFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { accountFundsWarnings, GOOGLE_ADS_QUERY_MAX_PAGE_SIZE } from \"@baker/api/ads-google\";\nimport {\n type ExpandedLevel,\n expandPreset,\n getPreset,\n isCampaignScoped,\n isInventoryPreset,\n isSearchable,\n PRESETS,\n SERVING_CHAINS,\n} from \"@baker/api/ads-google/presets\";\nimport { defineCommand } from \"citty\";\nimport { parse as parseCsv } from \"csv-parse/sync\";\nimport { quote as quoteShell } from \"shell-quote\";\nimport { ApiError, apiPost } from \"../../../client.ts\";\nimport { withWindowSpellings } from \"../../../date-window.ts\";\nimport { optionalTargetCompany } from \"../../../env.ts\";\nimport { maskEnvelope } from \"../../../field-mask.ts\";\nimport { registerSchema } from \"../../../schemas.ts\";\nimport { buildQueryCacheKey, cacheGet, cacheSet, getManagerIdForCustomer, getQueryTtl } from \"../cache.ts\";\nimport { getFieldDescriptions } from \"../field-descriptions.ts\";\nimport { resolveCustomerId, rowsFileHolds, toCsvRow, writeAdsJson, writeJsonEnvelope } from \"../output.ts\";\nimport { googlePresetSyncedHint } from \"../synced-first.ts\";\nimport type { AdsErrorEnvelope, AdsFileSummary, AdsSuccessEnvelope, AdsWarning, PartialRead } from \"../types.ts\";\nimport { parseCampaignIds } from \"./campaign-ids.ts\";\nimport { type ConvertingRows, conversionMixWarnings, foldConvertingRows } from \"./conversion-mix.ts\";\nimport { parseApiError } from \"./error-parser.ts\";\nimport {\n collectKeywordLimits,\n type KeywordLimits,\n type KeywordServingOptions,\n keywordServingWarnings,\n renderKeywordLimits,\n} from \"./keyword-serving.ts\";\nimport { type MoneyExample, moneyExample, moneyUnitWarnings } from \"./money-units.ts\";\nimport { blankQuotedValues, isSingleRowRead, validatePreflight } from \"./preflight.ts\";\nimport { masked, rowKeysOf, stableOrderQuery } from \"./stable-order.ts\";\n\nregisterSchema({\n command: \"ads.google.query\",\n routes: [\"POST /api/ads/google/query\"],\n effect: \"read_live\",\n description:\n \"Run a GAQL (Google Ads Query Language) query, one page at a time. Start here: `baker ads google query --preset campaign-performance` (--list-presets for all). Each read returns one page of --limit rows and, when the account holds more, `pagination.cursor` — pass it back with --cursor for the next page, or use --all --out <file> to read every page. A LIMIT in your own GAQL caps the whole read.\",\n args: {\n query: { type: \"positional\", description: \"GAQL SELECT statement (or pass it with --gaql)\", required: false },\n gaql: {\n type: \"string\",\n description:\n 'GAQL SELECT statement as a flag — same as the positional, for when quoting a positional is awkward: --gaql \"SELECT campaign.name FROM campaign\"',\n required: false,\n },\n \"customer-id\": {\n type: \"string\",\n description:\n \"Google Ads customer ID (10 digits; dashes are fine). Falls back to BAKER_GOOGLE_ADS_CUSTOMER_ID env var.\",\n required: false,\n },\n preset: {\n type: \"string\",\n description: `Named query preset (--list-presets shows each one's GAQL and page size): ${PRESETS.map((p) => p.name).join(\", \")}. Presets return only actually-serving entities (enabled campaign AND ad group AND ad) by default — pass --include-paused to include paused ones.`,\n required: false,\n },\n \"date-range\": {\n type: \"string\",\n description:\n \"Date range for presets: a Google date literal (TODAY, YESTERDAY, LAST_7_DAYS, LAST_14_DAYS, LAST_30_DAYS, THIS_MONTH, LAST_MONTH …) or BETWEEN 'YYYY-MM-DD' AND 'YYYY-MM-DD'. Google has no LAST_90_DAYS — use BETWEEN for any other window.\",\n required: false,\n },\n since: {\n type: \"string\",\n description:\n \"For a preset: first day, YYYY-MM-DD, with --until (also --start/--end, --start-date/--end-date) — the same window as --date-range \\\"BETWEEN 'since' AND 'until'\\\". Your own GAQL carries its window in its WHERE.\",\n required: false,\n },\n until: { type: \"string\", description: \"For a preset: last day, YYYY-MM-DD, with --since\", required: false },\n \"include-paused\": {\n type: \"boolean\",\n description:\n \"Include paused entities in preset results. Off by default: presets return only actually-serving entities. Google Ads has no single serving flag — an entity serves only when its whole chain (campaign, ad group, ad) is ENABLED, so recommendations should target serving entities unless the user asks about paused ones.\",\n required: false,\n },\n \"campaign-id\": {\n type: \"string\",\n description:\n \"For a preset: only these campaigns, comma-separated ids (--campaign-id 123,456), filtered in Google. Start here for any one-campaign question instead of reading the account and filtering the rows. --list-presets says which presets take it (campaignScoped).\",\n required: false,\n },\n search: {\n type: \"string\",\n description:\n \"For a keyword or search-term preset: only rows whose text contains any of these, comma-separated, case-insensitive (--search masia,paellero), filtered in Google. Start here for any question about a few terms (are they already negatives? what did AI Max match for them?) instead of reading every row and grepping. --list-presets says which presets take it (searchable).\",\n required: false,\n },\n limit: {\n type: \"number\",\n description: `Rows per page (default: the preset's page size, else 200; with --all, ${GOOGLE_ADS_QUERY_MAX_PAGE_SIZE}; a larger value is read at ${GOOGLE_ADS_QUERY_MAX_PAGE_SIZE}). A page size, not a cap: when more rows exist the read returns a cursor, and --all keeps paging.`,\n required: false,\n },\n \"list-presets\": { type: \"boolean\", description: \"List all available query presets\", required: false },\n cursor: {\n type: \"string\",\n description: \"Resume after a previous page: pass its pagination.cursor with the same query and --limit\",\n required: false,\n },\n all: {\n type: \"boolean\",\n description: `Follow every page until the account has no more rows (use with --out for large reads), ${GOOGLE_ADS_QUERY_MAX_PAGE_SIZE} rows per page unless --limit says otherwise. Needed for any read you will count or total. Only a LIMIT written in the GAQL itself can stop it early.`,\n required: false,\n },\n out: {\n type: \"string\",\n description:\n \"Write the rows alone to a file, not the envelope (format from extension: .csv, .jsonl, .json — a bare array of rows). The file appears only once the read is over; until then, and after a read that stopped part way, the rows are in <file>.partial.\",\n required: false,\n },\n append: {\n type: \"boolean\",\n description:\n \"Append to existing file (skip CSV headers). With --cursor, carries on a read that stopped in the <file>.partial it left (error.partial names the cursor).\",\n required: false,\n },\n output: {\n type: \"string\",\n description: \"Output format: json|csv|jsonl|md\",\n required: false,\n default: \"json\",\n enum: [\"json\", \"csv\", \"jsonl\", \"md\"],\n },\n fields: {\n type: \"string\",\n description:\n \"Only these columns, comma-separated, by their dotted names (--fields campaign.name,campaign.status); a resource name keeps all of its columns (--fields campaign). Every format; a column Google omitted still reads (omitted).\",\n required: false,\n },\n \"no-cache\": { type: \"boolean\", description: \"Skip cache, hit API directly\", required: false },\n full: {\n type: \"boolean\",\n description:\n \"Include the field description glossary in the JSON envelope. Off by default — rows already carry the data; only ask for this when you need a field's meaning explained.\",\n required: false,\n },\n },\n});\n\ninterface QueryApiResponse {\n rows: Array<Record<string, unknown>>;\n pageToken?: string;\n}\n\nfunction extractFields(rows: Array<Record<string, unknown>>): string[] {\n const keys = new Set<string>();\n foldObservedFields(rows, keys);\n return [...keys];\n}\n\n// The columns a table-shaped read renders: every SELECTed field, in SELECT order, whether or not any\n// row carried it. Deriving them from the rows is what dropped `campaign_conversion_goal.biddable` from\n// an md table: Google omits a false boolean, the first row was a non-biddable goal, and the column\n// that answered the question vanished with no warning. A submessage selected whole expands to the\n// leaves that came back, and a key nobody selected is kept at the end rather than lost.\nexport function resultColumns(gaql: string, rows: Array<Record<string, unknown>>): string[] {\n const observed = extractFields(rows);\n // A preset read in levels tags each row with its level: the column that tells its rows apart leads.\n const columns: string[] = observed.includes(\"level\") ? [\"level\"] : [];\n for (const field of parseSelectedFields(gaql)) {\n const leaves = observed.filter((key) => key.startsWith(`${field}.`));\n columns.push(...(leaves.length > 0 ? leaves : [field]));\n }\n for (const key of observed) columns.push(key);\n return [...new Set(columns)];\n}\n\nfunction isCsvPath(filePath: string): boolean {\n return filePath.split(\".\").pop()?.toLowerCase() === \"csv\";\n}\n\n// A CSV appended to keeps the header it has: a rerun whose SELECT gained a column (the ids a\n// conflict's steady order adds) would otherwise write rows wider than the header naming them.\nfunction fileColumnsFor(\n file: { partial: string; target: string },\n gaql: string,\n rows: Array<Record<string, unknown>>,\n append: boolean,\n): string[] {\n if (append && isCsvPath(file.target) && existsSync(file.partial)) {\n const [header] = parseCsv(readFileSync(file.partial, \"utf-8\"), {\n relax_column_count: true,\n skip_empty_lines: true,\n to_line: 1,\n }) as string[][];\n if (header && header.length > 0) return header;\n }\n return resultColumns(gaql, rows);\n}\n\n/** Writes rows to `filePath` in the format `target`'s extension names — the file it becomes. */\nfunction writeRowsToFile(\n filePath: string,\n target: string,\n rows: Array<Record<string, unknown>>,\n fields: string[],\n append: boolean,\n): void {\n if (isCsvPath(target)) {\n if (!append || !existsSync(filePath)) {\n writeFileSync(filePath, `${toCsvRow(fields)}\\n`, \"utf-8\");\n }\n const csvRows = rows.map((row) => toCsvRow(fields.map((f) => cellText(row[f]))));\n appendFileSync(filePath, `${csvRows.join(\"\\n\")}\\n`, \"utf-8\");\n } else if (target.split(\".\").pop()?.toLowerCase() === \"jsonl\") {\n const lines = rows.map((row) => JSON.stringify(row));\n if (append && existsSync(filePath)) {\n appendFileSync(filePath, `${lines.join(\"\\n\")}\\n`, \"utf-8\");\n } else {\n writeFileSync(filePath, `${lines.join(\"\\n\")}\\n`, \"utf-8\");\n }\n } else if (append && existsSync(filePath)) {\n const existing = JSON.parse(readFileSync(filePath, \"utf-8\")) as unknown[];\n writeFileSync(filePath, JSON.stringify([...existing, ...rows], null, 2), \"utf-8\");\n } else {\n writeFileSync(filePath, JSON.stringify(rows, null, 2), \"utf-8\");\n }\n}\n\n// The row cap in force for the whole read, or undefined when nothing caps it. --limit is only the\n// size of a page — the read hands back a cursor when the account holds more — so the one cap left is\n// a LIMIT the statement itself carries. Needed to tell \"this is all there is\" from \"this is as much\n// as the statement asked for\".\n//\n// A statement that returns one row by construction has no cap in force: its LIMIT 1 is the shape of\n// the answer, not a page size, and one row filling it is the whole data set.\nexport function effectiveRowLimit(finalQuery: string): number | undefined {\n if (isSingleRowRead(finalQuery)) return undefined;\n const match = blankQuotedValues(finalQuery).match(/\\bLIMIT\\s+(\\d+)/i);\n return match?.[1] ? Number(match[1]) : undefined;\n}\n\n// One notice per warning, shaped so it survives the format it travels in. The channel never names\n// a warning code: whatever the preflight or a row decoder produces flows through unchanged.\nexport function warningLines(warnings: AdsWarning[], format: string): string[] {\n return warnings.map((w) => {\n const message = w.message.replace(/\\s*\\n\\s*/g, \" \");\n if (format === \"jsonl\") return JSON.stringify({ _baker_warning: { code: w.code, message } });\n if (format === \"md\") return `> **${w.code}** — ${message}`;\n // csv and anything else: a leading # keeps a CSV parser from reading it as a header.\n return `# baker ${w.code}: ${message}`;\n });\n}\n\nexport interface ReadCompleteness {\n rowCount: number;\n /** The statement's own LIMIT — see `effectiveRowLimit`. Undefined when nothing caps the read. */\n effectiveLimit: number | undefined;\n /** The account handed back a next-page cursor that this run did not follow. */\n hasMore: boolean;\n}\n\n// A truncated read that looks complete is the whole failure this guard exists for: rows that stop\n// at a cap are indistinguishable from a data set that happens to be that size, and the agent reads\n// them as the universe. Two things can stop a read short — an unfollowed cursor, or the statement's\n// own LIMIT — and each has its own way on. A read that ran out of rows says nothing.\nexport function completenessWarnings(read: ReadCompleteness): AdsWarning[] {\n const cap = read.effectiveLimit;\n const filledTheCap = cap !== undefined && cap > 0 && read.rowCount >= cap;\n if (!read.hasMore && !filledTheCap) return [];\n const [cause, fix] = read.hasMore\n ? [\n \"More rows are waiting: the account returned a next-page cursor this run did not follow.\",\n \"Re-run with --all --out <file> to read every page, or pass --cursor <pagination.cursor> (same query, same --limit) for the next page.\",\n ]\n : [\n `The ${read.rowCount} rows returned exactly fill the LIMIT in the statement (${cap}).`,\n `Raise the LIMIT in the statement above ${cap}, or drop it — without a LIMIT, --all pages through every row.`,\n ];\n return [\n {\n code: \"TRUNCATED_RESULTS\",\n message: `INCOMPLETE READ — ${cause} These rows are a page, not the data set. Don't count, total or describe them as the whole picture. ${fix}`,\n },\n ];\n}\n\ninterface EnvelopeOptions {\n full: boolean;\n cached: boolean;\n nextCursor?: string;\n}\n\n// The field-description dictionary is a static glossary the agent almost never reads, so it is\n// opt-in via --full rather than a per-call token tax on every JSON envelope.\nexport function buildQueryEnvelope(\n rows: Array<Record<string, unknown>>,\n fieldDescs: Record<string, string>,\n warnings: AdsWarning[],\n options: EnvelopeOptions,\n): AdsSuccessEnvelope<Array<Record<string, unknown>>> {\n // Key order is load-bearing: a pretty-printed envelope of 500 rows read through `head` shows only\n // its first keys, so warnings and pagination go BEFORE data, and a one-line notice closes it for\n // whoever reads the tail.\n const notice = summariseWarnings(warnings);\n return {\n ok: true,\n ...(options.cached ? { cached: true as const } : {}),\n ...(warnings.length > 0 ? { warnings } : {}),\n ...(options.nextCursor ? { pagination: { hasMore: true, cursor: options.nextCursor } } : {}),\n data: rows,\n ...(options.full && Object.keys(fieldDescs).length > 0 ? { fields: fieldDescs } : {}),\n ...(notice ? { notice } : {}),\n };\n}\n\n// One line naming every warning code, so a reader who only sees the end of the output still knows\n// something was flagged. Code-agnostic: any warning the pipeline produces lands here.\nexport function summariseWarnings(warnings: AdsWarning[]): string | undefined {\n if (warnings.length === 0) return undefined;\n const codes = [...new Set(warnings.map((w) => w.code))].join(\", \");\n return `Read the \"warnings\" above before using these rows: ${codes}.`;\n}\n\nexport interface FileSummaryInput {\n file: string;\n rows: number;\n warnings: AdsWarning[];\n complete: boolean;\n}\n\n// The --out branch throws the rows away, so this envelope is the only thing the agent reads about\n// the pull. It carries every warning the read raised, not just the ones a row decoder produced.\nexport function buildFileSummary(input: FileSummaryInput): AdsFileSummary {\n const notice = summariseWarnings(input.warnings);\n return {\n ok: true,\n fields: {},\n file: input.file,\n holds: rowsFileHolds(input.file),\n rows: input.rows,\n complete: input.complete,\n ...(input.warnings.length > 0 ? { warnings: input.warnings } : {}),\n ...(notice ? { notice } : {}),\n };\n}\n\n// Repeating the notice at the tail costs two lines and buys the case that actually bit us: a long\n// CSV read whose output the agent inspects with `tail`. Short reads are visible whole, so once is enough.\nconst REPEAT_NOTICE_ABOVE_ROWS = 20;\n\n/** A repeated or nested message (policy topics, …) as its JSON, never \"[object Object]\". */\nfunction cellText(value: unknown): string {\n return typeof value === \"object\" && value !== null ? JSON.stringify(value) : String(value ?? \"\");\n}\n\nexport interface ReadContext {\n /** The statement that ran — its SELECT list, not the rows, decides a table's columns. */\n gaql: string;\n effectiveLimit: number | undefined;\n nextCursor?: string;\n}\n\nfunction writeLine(line: string): void {\n process.stdout.write(`${line}\\n`);\n}\n\ntype RowWriter = (rows: Array<Record<string, unknown>>, fields: string[], notices: string[]) => void;\n\n// The header stays the first line so a CSV reader still parses; the notice sits right under it,\n// where a `head` lands, and repeats at the tail, where a `tail` lands.\nconst writeCsvRows: RowWriter = (rows, fields, notices) => {\n writeLine(toCsvRow(fields));\n for (const line of notices) writeLine(line);\n for (const row of rows) writeLine(toCsvRow(fields.map((f) => cellText(row[f]))));\n};\n\nconst writeJsonlRows: RowWriter = (rows, _fields, notices) => {\n for (const line of notices) writeLine(line);\n for (const row of rows) writeLine(JSON.stringify(row));\n};\n\nconst OMITTED = \"(omitted)\";\nconst OMITTED_FALSE = `false ${OMITTED}`;\nconst OMITTED_LEGEND = `> ${OMITTED} = Google left this field off the row, which is how it sends false, 0 and \"not set\": the field WAS read. A field with no column here was not read.`;\n\n// A blank cell reads as \"no data\", which is the one thing an omitted field is not. Google omits a\n// false boolean, so in a column that carries a boolean anywhere the omission is spelled out as false.\nfunction mdCell(row: Record<string, unknown>, field: string, booleanColumns: ReadonlySet<string>): string {\n if (!(field in row)) return booleanColumns.has(field) ? OMITTED_FALSE : OMITTED;\n return cellText(row[field]).replace(/\\|/g, \"\\\\|\");\n}\n\n// A blockquote inside a markdown table would break it, so the notice brackets the table.\nconst writeMdRows: RowWriter = (rows, fields, notices) => {\n const booleanColumns = new Set(fields.filter((f) => rows.some((row) => typeof row[f] === \"boolean\")));\n for (const line of notices) writeLine(line);\n writeLine(`| ${fields.join(\" | \")} |`);\n writeLine(`| ${fields.map(() => \"---\").join(\" | \")} |`);\n for (const row of rows) writeLine(`| ${fields.map((f) => mdCell(row, f, booleanColumns)).join(\" | \")} |`);\n if (rows.some((row) => fields.some((f) => !(f in row)))) writeLine(OMITTED_LEGEND);\n};\n\nconst ROW_WRITERS: Record<string, RowWriter> = { csv: writeCsvRows, jsonl: writeJsonlRows, md: writeMdRows };\n\n// The warning a `| tail` must not miss: the rows stop before the account does, and its text says\n// how to read on. Every other warning is printed in full once, above the rows.\nconst REPEATED_IN_FULL = \"TRUNCATED_RESULTS\";\n\n// What a long read repeats at its tail: the truncation in full, then one line naming every other\n// code printed above. Repeating each in full made a third of a read warnings, and the agent\n// stripped them all with `grep -v '^>'`, the ones it was meant to carry included (BAKER-3808).\nfunction tailWarnings(warnings: AdsWarning[]): AdsWarning[] {\n const repeated = warnings.filter((w) => w.code === REPEATED_IN_FULL);\n const named = [...new Set(warnings.filter((w) => w.code !== REPEATED_IN_FULL).map((w) => w.code))];\n if (named.length === 0) return repeated;\n return [...repeated, { code: named.join(\", \"), message: \"printed in full at the start of this output.\" }];\n}\n\n// Each writer decides where a notice can sit without wrecking the format it travels in; the tail\n// repeat is common to all of them, because `| tail` is how a long read gets inspected.\nfunction writeRows(\n format: string,\n rows: Array<Record<string, unknown>>,\n columns: string[],\n warnings: AdsWarning[],\n): void {\n const write = ROW_WRITERS[format] ?? writeMdRows;\n write(rows, columns, warningLines(warnings, format));\n if (rows.length > REPEAT_NOTICE_ABOVE_ROWS) {\n for (const line of warningLines(tailWarnings(warnings), format)) writeLine(line);\n }\n}\n\n/** The columns `--fields` asked for, or null when it asked for none. */\nfunction requestedFields(args: Record<string, unknown>): string[] | null {\n if (typeof args.fields !== \"string\") return null;\n const fields = args.fields\n .split(\",\")\n .map((field) => field.trim())\n .filter((field) => field.length > 0);\n return fields.length > 0 ? fields : null;\n}\n\n/**\n * The result's columns `--fields` names, in the order it names them: a column by its dotted name, or\n * every column under a resource (`campaign`). Chosen from the SELECTed columns rather than the rows,\n * so a field Google omitted on every row keeps its column and still reads (omitted).\n */\nexport function chosenColumns(columns: string[], fields: string[]): { columns: string[]; unmatched: string[] } {\n const chosen: string[] = [];\n const unmatched: string[] = [];\n for (const field of fields) {\n const matched = columns.filter((column) => column === field || column.startsWith(`${field}.`));\n if (matched.length === 0) unmatched.push(field);\n chosen.push(...matched);\n }\n return { columns: [...new Set(chosen)], unmatched };\n}\n\n/** The envelope, masked by `--fields` when it named any. */\nfunction writeNarrowed(\n envelope: AdsSuccessEnvelope<Array<Record<string, unknown>>> | AdsFileSummary,\n fields: string[] | null,\n): void {\n if (fields) writeJsonEnvelope(maskEnvelope({ ...envelope }, fields));\n else writeAdsJson(envelope);\n}\n\nfunction pickColumns(row: Record<string, unknown>, columns: string[]): Record<string, unknown> {\n return Object.fromEntries(columns.filter((column) => column in row).map((column) => [column, row[column]]));\n}\n\nexport function outputResults(\n rows: Array<Record<string, unknown>>,\n fieldDescs: Record<string, string>,\n warnings: AdsWarning[],\n args: Record<string, unknown>,\n cached: boolean,\n read: ReadContext,\n): void {\n const format = (args.output as string) || \"json\";\n const allWarnings = [\n ...warnings,\n ...completenessWarnings({\n rowCount: rows.length,\n effectiveLimit: read.effectiveLimit,\n hasMore: Boolean(read.nextCursor),\n }),\n ];\n const fields = requestedFields(args);\n const columns = resultColumns(read.gaql, rows);\n const chosen = fields ? chosenColumns(columns, fields) : { columns, unmatched: [] };\n const unmatched: AdsWarning[] =\n chosen.unmatched.length > 0\n ? [\n {\n code: \"FIELDS_UNMATCHED\",\n message: `--fields matched no column for: ${chosen.unmatched.join(\", \")}. The columns are: ${columns.join(\", \")}.`,\n },\n ]\n : [];\n const narrowed = fields ? rows.map((row) => pickColumns(row, chosen.columns)) : rows;\n // Every format carries its warnings in-band, so stdout is their one channel: a stderr copy reached\n // the agent twice through `2>&1`, and in front of the JSON it made the capture unparseable.\n if (format === \"json\") {\n writeAdsJson(\n buildQueryEnvelope(narrowed, fieldDescs, [...unmatched, ...allWarnings], {\n full: Boolean(args.full),\n cached,\n nextCursor: read.nextCursor,\n }),\n );\n return;\n }\n writeRows(format, narrowed, chosen.columns, [...unmatched, ...allWarnings]);\n}\n\n/** The statement typed as the positional or as --gaql — never two different ones. */\nexport function resolveGaqlInput(\n args: Record<string, unknown>,\n): { ok: true; gaql: string } | { ok: false; message: string } {\n const positional = typeof args.query === \"string\" ? args.query.trim() : \"\";\n const flag = typeof args.gaql === \"string\" ? args.gaql.trim() : \"\";\n if (positional && flag && positional !== flag) {\n return { ok: false, message: \"Pass the GAQL statement once — as the positional or as --gaql, not both.\" };\n }\n return { ok: true, gaql: positional || flag };\n}\n\n/** `--search a,b` as its terms, split on commas; expandPreset drops the blank ones. */\nfunction searchTerms(value: unknown): string[] | undefined {\n return typeof value === \"string\" ? value.split(\",\") : undefined;\n}\n\n// Your own GAQL is sent as written, so a --campaign-id beside it would answer the account-wide question.\nfunction refuseCampaignIdOnGaql(value: unknown): void {\n const campaigns = parseCampaignIds(value);\n const ids = campaigns.ok && campaigns.ids ? campaigns.ids.join(\", \") : \"<id>\";\n writeAdsJson({\n ok: false,\n error: {\n code: \"VALIDATION_ERROR\",\n message: `--campaign-id narrows a --preset; your own GAQL is sent as written. Put the campaigns in its WHERE instead: campaign.id IN (${ids}).`,\n },\n });\n}\n\n/**\n * A preset's window: `--date-range` as typed, or a `--since`/`--until` pair (any of the shared\n * spellings) read as the BETWEEN range it is. `paired` says the window came as such a pair.\n */\nexport function presetDateRange(\n args: Record<string, unknown>,\n): { ok: true; dateRange?: string; paired: boolean } | { ok: false; message: string } {\n const range = typeof args[\"date-range\"] === \"string\" ? args[\"date-range\"] : undefined;\n const since = typeof args.since === \"string\" && args.since !== \"\" ? args.since : undefined;\n const until = typeof args.until === \"string\" && args.until !== \"\" ? args.until : undefined;\n if (since === undefined && until === undefined) return { ok: true, dateRange: range, paired: false };\n if (range !== undefined) {\n return { ok: false, message: \"Pass the window once — as --since/--until or as --date-range, not both.\" };\n }\n if (since === undefined || until === undefined) {\n return { ok: false, message: \"A date window needs both ends: --since YYYY-MM-DD --until YYYY-MM-DD.\" };\n }\n return { ok: true, dateRange: `BETWEEN '${since}' AND '${until}'`, paired: true };\n}\n\n// Your own GAQL is sent as written, so a --since/--until beside it would read whatever window it names.\nfunction refusedWindowOnGaql(args: Record<string, unknown>): boolean {\n const window = presetDateRange(args);\n if (window.ok && !window.paired) return false;\n writeAdsJson({\n ok: false,\n error: {\n code: \"VALIDATION_ERROR\",\n message: window.ok\n ? `A date window narrows a --preset; your own GAQL is sent as written. Put it in its WHERE instead: segments.date ${window.dateRange}.`\n : window.message,\n },\n });\n return true;\n}\n\n/** What a read sends: one statement, or a preset's levels read as one list (joined in `query`). */\ninterface ResolvedRead {\n query: string;\n levels?: ExpandedLevel[];\n}\n\n/** A preset expanded with the window, campaigns and paused rows the read asked for. */\nfunction resolvePresetRead(args: Record<string, unknown>): ResolvedRead | null {\n const preset = getPreset(args.preset as string);\n if (!preset) {\n const available = PRESETS.map((p) => p.name).join(\", \");\n writeAdsJson({\n ok: false,\n error: { code: \"VALIDATION_ERROR\", message: `Unknown preset: \"${args.preset}\". Available: ${available}` },\n });\n return null;\n }\n const campaigns = parseCampaignIds(args[\"campaign-id\"]);\n if (!campaigns.ok) {\n writeAdsJson({ ok: false, error: campaigns.error });\n return null;\n }\n const window = presetDateRange(args);\n if (!window.ok) {\n writeAdsJson({ ok: false, error: { code: \"VALIDATION_ERROR\", message: window.message } });\n return null;\n }\n const expanded = expandPreset(preset, {\n dateRange: window.dateRange,\n includePaused: Boolean(args[\"include-paused\"]),\n campaignIds: campaigns.ids,\n search: searchTerms(args.search),\n });\n if (expanded.error) {\n writeAdsJson({\n ok: false,\n error: { code: \"VALIDATION_ERROR\", message: expanded.error },\n });\n return null;\n }\n return { query: expanded.query, levels: expanded.levels };\n}\n\nfunction resolveGaql(args: Record<string, unknown>): ResolvedRead | null {\n if (args.preset) return resolvePresetRead(args);\n const input = resolveGaqlInput(args);\n if (input.ok && input.gaql && refusedWindowOnGaql(args)) return null;\n if (input.ok && input.gaql && args[\"campaign-id\"] !== undefined) {\n refuseCampaignIdOnGaql(args[\"campaign-id\"]);\n return null;\n }\n if (input.ok && input.gaql && typeof args.search === \"string\") {\n writeAdsJson({\n ok: false,\n error: {\n code: \"VALIDATION_ERROR\",\n message: `--search narrows a --preset; your own GAQL is sent as written. Put the terms in its WHERE instead: <text field> REGEXP_MATCH \"(?i).*(term1|term2).*\".`,\n },\n });\n return null;\n }\n if (!input.ok || !input.gaql) {\n writeAdsJson({\n ok: false,\n error: {\n code: \"VALIDATION_ERROR\",\n message: input.ok\n ? \"Provide a GAQL query (positional or --gaql) or use --preset. Run --list-presets to see options.\"\n : input.message,\n },\n });\n return null;\n }\n return { query: input.gaql };\n}\n\n// Resources whose rows only actually serve when their whole status chain is ENABLED, MINUS the\n// multi-rung ones preflight's SERVING_CHAINS already judges rung by rung. What is left is the\n// single-rung resources: they carry no ancestor to forget, so preflight exempts them by design and\n// this is the only place that says an unfiltered read of them returns paused rows. Two warnings for\n// one defect is how an agent learns to skim past both, so the populations must not overlap.\nconst SERVING_HIERARCHY_RESOURCES = [\n \"campaign\",\n \"ad_group\",\n \"ad_group_ad\",\n \"ad_group_criterion\",\n \"keyword_view\",\n \"search_term_view\",\n \"shopping_performance_view\",\n \"asset_group_asset\",\n].filter((resource) => !(resource in SERVING_CHAINS));\n\n// Extract the WHERE clause's predicates from an uppercased GAQL string — everything between\n// WHERE and the first trailing clause (ORDER BY / LIMIT / PARAMETERS). Returns \"\" when there is\n// no WHERE. Used to detect a real status *filter* rather than a status column in the SELECT list.\n// Keywords are found by word boundary, not by spaces, so a query written over several lines reads\n// the same as one written on a single line.\nfunction whereClause(upperQuery: string): string {\n const where = /\\bWHERE\\b/.exec(upperQuery);\n if (!where) return \"\";\n const rest = upperQuery.slice(where.index + where[0].length);\n const trailing = /\\b(?:ORDER\\s+BY|GROUP\\s+BY|LIMIT|PARAMETERS)\\b/.exec(rest);\n return trailing ? rest.slice(0, trailing.index) : rest;\n}\n\n// Nudge the agent toward serving-only analysis. Presets already default to the serving chain,\n// so this only fires for raw custom GAQL that targets a serving-hierarchy resource without any\n// status predicate — Google Ads has no single serving flag, so an unfiltered query returns\n// paused-parent entities that look live.\nexport function servingScopeWarnings(args: Record<string, unknown>, finalQuery: string): AdsWarning[] {\n // --include-paused only has an effect on presets (expandPreset consumes it). A preset without\n // the flag is serving-only by construction, so it needs no warning; with the flag we say so.\n if (args.preset) {\n // An inventory (`<thing> list`) lists paused entities on purpose: it is where ids to edit come from.\n // A preset with no serving chain has nothing for --include-paused to widen.\n const name = String(args.preset);\n if (!args[\"include-paused\"] || isInventoryPreset(name) || !getPreset(name)?.statusFields?.length) return [];\n return [\n {\n code: \"SERVING_SCOPE\",\n message:\n \"Paused entities are included (--include-paused). Only recommend changes for actually-serving entities (enabled campaign, ad group, and ad) unless the user asked about paused ones.\",\n },\n ];\n }\n\n // Raw GAQL: --include-paused is a no-op here, so don't claim paused rows were included. Warn\n // only when the query targets a serving-hierarchy resource with no status filter in its WHERE\n // (a status column in the SELECT list displays status but doesn't filter on it).\n const upper = finalQuery.toUpperCase();\n const fromMatch = upper.match(/\\bFROM\\s+([A-Z_]+)/);\n const resource = fromMatch?.[1]?.toLowerCase();\n const hierarchical = resource ? SERVING_HIERARCHY_RESOURCES.includes(resource) : false;\n const where = whereClause(upper);\n const filtersStatus = where.includes(\".STATUS\");\n // Entities named by id are the ones asked for, paused or not.\n const pinnedById = resource ? new RegExp(`\\\\b${resource.toUpperCase()}\\\\.ID\\\\s*(=|IN\\\\b)`).test(where) : false;\n if (hierarchical && !filtersStatus && !pinnedById) {\n return [\n {\n code: \"SERVING_SCOPE\",\n message:\n \"This query has no status filter, so it may return paused entities that aren't actually serving. Google Ads has no single serving flag — an entity serves only when its whole chain is ENABLED. Add campaign.status = 'ENABLED' AND ad_group.status = 'ENABLED' AND ad_group_ad.status = 'ENABLED' (as applicable), or use a --preset, unless you intend to include paused entities.\",\n },\n ];\n }\n return [];\n}\n\n// A performance preset Baker's synced copy also answers: say so, since that read has no rate limit.\nfunction syncedCopyWarnings(args: Record<string, unknown>): AdsWarning[] {\n const preset = typeof args.preset === \"string\" ? getPreset(args.preset) : undefined;\n const window = presetDateRange(args);\n if (preset === undefined || !window.ok) return [];\n const hint = googlePresetSyncedHint(preset.name, window.dateRange ?? preset.defaultDateRange);\n return hint ? [{ code: \"SYNCED_COPY\", message: hint }] : [];\n}\n\n// Parse the SELECT list out of a GAQL statement — of each statement, for a preset read in levels.\n// Case-insensitive, newline- and whitespace-tolerant. Returns [] when there is no parseable SELECT ... FROM.\nexport function parseSelectedFields(gaql: string): string[] {\n return [...new Set(selectStatements(gaql).flatMap((statement) => statement.fields))];\n}\n\n/**\n * Every `SELECT … FROM <resource>` in the text: one for a statement, one per level of a preset read in\n * levels. Quoted values are blanked first, so a filter that spells `SELECT … FROM` is no statement.\n */\nfunction selectStatements(gaql: string): Array<{ resource: string; fields: string[] }> {\n return [...masked(gaql).matchAll(/\\bSELECT\\b([\\s\\S]*?)\\bFROM\\b\\s*([A-Za-z_]*)/gi)].map((match) => ({\n resource: (match[2] ?? \"\").toLowerCase(),\n fields: (match[1] ?? \"\")\n .split(\",\")\n .map((field) => field.trim())\n .filter((field) => /^[A-Za-z_][A-Za-z0-9_]*(\\.[A-Za-z0-9_]+)*$/.test(field)),\n }));\n}\n\n// Which SELECTed fields appeared on NO returned row. Google Ads omits a field entirely from a\n// row when it has no value, so a key's absence is \"not observed\", never \"empty\" — and the union\n// across ALL rows is the only honest denominator (one arbitrary row proves nothing).\nfunction foldObservedFields(rows: Array<Record<string, unknown>>, observed: Set<string>): void {\n for (const row of rows) {\n for (const key of Object.keys(row)) observed.add(key);\n }\n}\n\nexport function unobservedSelectedFields(gaql: string, rows: Array<Record<string, unknown>>): string[] {\n const observed = new Set<string>();\n foldObservedFields(rows, observed);\n return unobservedFields(gaql, observed);\n}\n\n// Same verdict from a folded key set instead of the rows, so a read that streamed to disk can\n// still answer it.\nexport function unobservedFields(gaql: string, observed: Set<string>): string[] {\n const statements = selectStatements(gaql);\n // Of a read in levels, a level that had no row (no key of its own resource came back) observed\n // nothing, so its fields are not missing: there was nothing there to read.\n const answered =\n statements.length < 2\n ? statements\n : statements.filter((statement) => [...observed].some((key) => key.startsWith(`${statement.resource}.`)));\n const selected = [...new Set(answered.flatMap((statement) => statement.fields))];\n return selected.filter((field) => {\n // The backend strips resource_name from every row, so it is never observable.\n if (field.endsWith(\".resource_name\")) return false;\n if (observed.has(field)) return false;\n // One arm of a union is answered when the other came back: an unlimited budget has a type, no amount.\n if (unionPartners(field).some((partner) => observed.has(partner))) return false;\n // A submessage selected as a whole is observed when any of its flattened leaves came back.\n return ![...observed].some((key) => key.startsWith(`${field}.`));\n });\n}\n\n// Google fills one arm of a union field and omits the other: a spending limit is an amount or a type\n// (INFINITE), an end time a date or a type (FOREVER), a proposal's start a date or a type (NOW). Either\n// arm that came back answers the other. An approved INFINITE limit makes the adjusted one INFINITE too,\n// so it also answers the adjusted amount. An account budget's start is a plain date, not a union.\nconst UNION_ARMS: ReadonlyArray<readonly [string, string]> = [\n [\"spending_limit_micros\", \"spending_limit_type\"],\n [\"end_date_time\", \"end_time_type\"],\n];\nconst PROPOSAL_START_ARMS = [\n \"account_budget_proposal.proposed_start_date_time\",\n \"account_budget_proposal.proposed_start_time_type\",\n] as const;\n\nfunction unionPartners(field: string): string[] {\n const partners: string[] = [];\n for (const [a, b] of UNION_ARMS) {\n if (field.endsWith(a)) partners.push(`${field.slice(0, -a.length)}${b}`);\n if (field.endsWith(b)) partners.push(`${field.slice(0, -b.length)}${a}`);\n }\n const [startDate, startType] = PROPOSAL_START_ARMS;\n if (field === startDate) partners.push(startType);\n if (field === startType) partners.push(startDate);\n if (field === \"account_budget.adjusted_spending_limit_micros\")\n partners.push(\"account_budget.approved_spending_limit_type\");\n return partners;\n}\n\n// An absent field must never read as an empty one. Zero rows is a different, already-obvious\n// signal, so this only fires when the read actually returned data.\nexport function missingFieldWarnings(gaql: string, rows: Array<Record<string, unknown>>): AdsWarning[] {\n const observed = new Set<string>();\n foldObservedFields(rows, observed);\n return missingFieldWarningsFor(gaql, observed, rows.length);\n}\n\nexport function missingFieldWarningsFor(gaql: string, observed: Set<string>, rowCount: number): AdsWarning[] {\n if (rowCount === 0) return [];\n const missing = unobservedFields(gaql, observed);\n if (missing.length === 0) return [];\n return [\n {\n code: \"MISSING_FIELDS\",\n message: `These SELECTed fields came back on no row: ${missing.join(\", \")}. Google omits empty fields, so this does NOT mean the setting is empty: check the level that owns it.`,\n },\n ];\n}\n\n// A CSV header is fixed on the first page and cannot grow a column later, so a submessage selected\n// whole whose leaves first appear on a later page has nowhere to land in the file. Those values are\n// lost, and MISSING_FIELDS cannot see it (the leaves WERE observed), so the loss is named here.\n// A CSV appended to keeps its earlier header on purpose, so the row ids a conflict rerun adds to its\n// SELECT only to sort by have no column there, and that is no loss to re-read for.\nexport function unwrittenColumnWarnings(\n header: string[],\n observed: Set<string>,\n read?: { gaql: string; appended: boolean },\n): AdsWarning[] {\n const written = new Set([...header, ...(read?.appended ? rowKeysOf(read.gaql) : [])]);\n const unwritten = [...observed].filter((key) => !written.has(key));\n if (unwritten.length === 0) return [];\n return [\n {\n code: \"UNWRITTEN_COLUMNS\",\n message: `The file has no column for ${unwritten.join(\", \")}: the header was fixed on the first page, which carried none of them, so their values from later pages are NOT in the file. Do not read those columns as empty. SELECT these fields by name instead of their parent, or write to a .jsonl file, then re-run.`,\n },\n ];\n}\n\n// Google omits primary_status_reasons when a keyword has none, so the decoder can only tell\n// \"nothing to report\" from \"we never asked\" by looking at what the statement selected.\nexport function keywordServingOptions(gaql: string): KeywordServingOptions {\n return { statusReasonsSelected: parseSelectedFields(gaql).includes(\"ad_group_criterion.primary_status_reasons\") };\n}\n\n/** Where an --out read writes until it is over, and what that file held before this run wrote to it. */\ninterface OutFile {\n partial: string;\n target: string;\n /** Rows the partial file already held when this run started: the pages of the read it resumes, or the file it appends to. */\n rowsBefore: number;\n /** It carries on a read that stopped, so even a run that wrote nothing leaves that read to resume. */\n resumes: boolean;\n /** The file it appends to was moved into the partial file, and goes back if this run writes nothing. */\n movedTarget: boolean;\n /** Rows of the earlier file it appends to, first in the partial file: what a read from page 1 keeps. */\n base: number;\n}\n\n/** Beside a stopped read's partial file: how many of its rows are the earlier file it appends to, for its resume. */\nfunction baseFileOf(partial: string): string {\n return `${partial}.base`;\n}\n\n// An --out read writes beside its file and names the file only once the read is over. Written in\n// place, the file was valid at every page boundary: a reader with a file tool took a half-read\n// export, still running or already failed, for the finished one. A file already at the path, from\n// an earlier read, is taken away for the same reason: it would be read as this one.\nfunction startPartialFile(target: string, args: Record<string, unknown>): OutFile {\n const partial = `${target}.partial`;\n // `--cursor <it> --append` resumes a read that stopped, in the file it left.\n if (args.append && args.cursor && existsSync(partial)) {\n rmSync(target, { force: true });\n const baseFile = baseFileOf(partial);\n const base = existsSync(baseFile) ? Number(readFileSync(baseFile, \"utf-8\")) || 0 : 0;\n return { partial, target, rowsBefore: rowsInFile(partial, target), resumes: true, movedTarget: false, base };\n }\n rmSync(partial, { force: true });\n rmSync(baseFileOf(partial), { force: true });\n if (args.append && existsSync(target)) {\n // Counted before the move: a file that cannot be read stays where it was.\n const rowsBefore = rowsInFile(target, target);\n renameSync(target, partial);\n return { partial, target, rowsBefore, resumes: false, movedTarget: true, base: rowsBefore };\n }\n rmSync(target, { force: true });\n return { partial, target, rowsBefore: 0, resumes: false, movedTarget: false, base: 0 };\n}\n\n/** The file cut back to its first `rows` rows, read and written in the format its target names. */\nfunction keepFirstRows(file: string, target: string, rows: number): void {\n const text = readFileSync(file, \"utf-8\");\n if (isCsvPath(target)) {\n const records = parseCsv(text, { relax_column_count: true, skip_empty_lines: true }) as string[][];\n writeFileSync(\n file,\n records\n .map((record) => `${toCsvRow(record)}\\n`)\n .slice(0, rows + 1)\n .join(\"\"),\n \"utf-8\",\n );\n } else if (target.split(\".\").pop()?.toLowerCase() === \"jsonl\") {\n const lines = text.split(\"\\n\").filter((line) => line.trim());\n writeFileSync(file, `${lines.slice(0, rows).join(\"\\n\")}\\n`, \"utf-8\");\n } else {\n const all = JSON.parse(text) as unknown[];\n writeFileSync(file, JSON.stringify(all.slice(0, rows), null, 2), \"utf-8\");\n }\n}\n\n/** How many rows a file written by `writeRowsToFile` holds, read in the format its target names. */\nfunction rowsInFile(file: string, target: string): number {\n const text = readFileSync(file, \"utf-8\");\n if (isCsvPath(target)) {\n const records = parseCsv(text, { relax_column_count: true, skip_empty_lines: true }) as unknown[];\n return Math.max(records.length - 1, 0);\n }\n if (target.split(\".\").pop()?.toLowerCase() === \"jsonl\") return text.split(\"\\n\").filter((line) => line.trim()).length;\n const rows = JSON.parse(text) as unknown;\n return Array.isArray(rows) ? rows.length : 0;\n}\n\n/** A read that failed after it had read pages: the failure, and what it leaves. */\nclass StoppedRead extends Error {\n constructor(\n readonly failure: unknown,\n readonly partial: PartialRead,\n ) {\n super(failure instanceof Error ? failure.message : \"The read stopped\");\n }\n}\n\ntype PagesRead = {\n allRows: Array<Record<string, unknown>>;\n lastPageToken?: string;\n totalRowsWritten: number;\n /** Rows the statement's LIMIT covers: this run's, plus the pages of the read it resumes — not an earlier file it appends to. */\n rowsOfThisRead: number;\n convertingRows: ConvertingRows;\n keywordLimits: KeywordLimits;\n observedFields: Set<string>;\n fileColumns: string[];\n /** The `account_budget` rows of a --out read, kept for its ACCOUNT_FUNDS warning: a budget read is a few rows. */\n budgetRows: Array<Record<string, unknown>>;\n /** The first amount a --out read's rows carried, for its MONEY_IN_MICROS example. */\n moneySample: MoneyExample | undefined;\n};\n\n/** Where a read is, so a failure can say what it kept and where to resume from. */\ninterface ReadProgress {\n /** Rows this run read, written to the file or held for stdout. */\n rowsRead: number;\n /** The rows an --all read without --out holds until it prints them. */\n held: Array<Record<string, unknown>>;\n cursor: string | undefined;\n}\n\nasync function fetchAllPages(\n gaql: string,\n body: Record<string, unknown>,\n args: Record<string, unknown>,\n servingOptions: KeywordServingOptions,\n): Promise<PagesRead> {\n const target = args.out ? resolve(args.out as string) : undefined;\n const file = target ? startPartialFile(target, args) : undefined;\n const progress: ReadProgress = { rowsRead: 0, held: [], cursor: args.cursor as string | undefined };\n try {\n const read = await readPages(gaql, body, args, servingOptions, file, progress);\n if (file) {\n renameSync(file.partial, file.target);\n rmSync(baseFileOf(file.partial), { force: true });\n }\n return {\n ...read,\n totalRowsWritten: (file?.rowsBefore ?? 0) + read.totalRowsWritten,\n rowsOfThisRead: (file?.resumes ? file.rowsBefore : 0) + read.totalRowsWritten,\n };\n } catch (err) {\n throw readStopped(err, file, progress);\n }\n}\n\n/** What a failed read throws: a StoppedRead when it leaves rows to keep, else the failure itself. */\nfunction readStopped(err: unknown, file: OutFile | undefined, progress: ReadProgress): unknown {\n const cursor = progress.cursor ? { cursor: progress.cursor } : {};\n if (!file) {\n // A read to stdout keeps its rows in memory: printed with the failure, they are not lost with it.\n if (progress.rowsRead === 0) return err;\n return new StoppedRead(err, { data: progress.held, rows: progress.rowsRead, complete: false, ...cursor });\n }\n if (file.base > 0 && err instanceof ApiError && err.code === \"CONFLICT\") {\n // Rows that moved are read again from page 1, so none of this read's are kept: the file it\n // appends to goes back as it was, for that read to append to again.\n keepFirstRows(file.partial, file.target, file.base);\n renameSync(file.partial, file.target);\n rmSync(baseFileOf(file.partial), { force: true });\n return err;\n }\n if (file.resumes || progress.rowsRead > 0) {\n if (file.base > 0) writeFileSync(baseFileOf(file.partial), String(file.base), \"utf-8\");\n return new StoppedRead(err, {\n file: file.partial,\n rows: file.rowsBefore + progress.rowsRead,\n complete: false,\n ...cursor,\n });\n }\n // Nothing read: the file it appends to goes back as it was, and no partial file is left.\n if (file.movedTarget) renameSync(file.partial, file.target);\n else rmSync(file.partial, { force: true });\n return err;\n}\n\nfunction isBudgetRow(row: Record<string, unknown>): boolean {\n return Object.keys(row).some((key) => key.startsWith(\"account_budget.\"));\n}\n\nasync function readPages(\n gaql: string,\n body: Record<string, unknown>,\n args: Record<string, unknown>,\n servingOptions: KeywordServingOptions,\n file: OutFile | undefined,\n progress: ReadProgress,\n): Promise<PagesRead> {\n let pageToken: string | undefined = args.cursor as string | undefined;\n const convertingRows = foldConvertingRows([]);\n let keywordLimits: KeywordLimits | undefined;\n const observedFields = new Set<string>();\n // One header for the whole file: fixed on the first page, since a CSV cannot grow a column later.\n let fileColumns: string[] | undefined;\n let budgetRows: Array<Record<string, unknown>> = [];\n let moneySample: MoneyExample | undefined;\n\n do {\n const requestBody: Record<string, unknown> = { ...body };\n if (pageToken) requestBody.pageToken = pageToken;\n\n const response = await apiPost<QueryApiResponse>(\"/api/ads/google/query\", requestBody);\n const rows = response.rows ?? [];\n pageToken = response.pageToken;\n foldConvertingRows(rows, convertingRows);\n\n if (file) {\n const shouldAppend = (args.append as boolean) || progress.rowsRead > 0;\n fileColumns ??= fileColumnsFor(file, gaql, rows, shouldAppend);\n writeRowsToFile(file.partial, file.target, rows, fileColumns, shouldAppend);\n // The rows are gone after this — fold their verdicts now or the file summary has nothing\n // to say about the very pull this preset is sized for.\n keywordLimits = collectKeywordLimits(rows, servingOptions, keywordLimits);\n foldObservedFields(rows, observedFields);\n budgetRows = budgetRows.concat(rows.filter(isBudgetRow));\n moneySample ??= moneyExample(rows);\n } else {\n progress.held = progress.held.concat(rows);\n }\n progress.rowsRead += rows.length;\n progress.cursor = pageToken;\n\n if (!args.all) break;\n } while (pageToken);\n\n return {\n allRows: progress.held,\n lastPageToken: pageToken,\n totalRowsWritten: file ? progress.rowsRead : 0,\n rowsOfThisRead: file ? progress.rowsRead : 0,\n convertingRows,\n keywordLimits: keywordLimits ?? collectKeywordLimits([], servingOptions),\n observedFields,\n fileColumns: fileColumns ?? [],\n budgetRows,\n moneySample,\n };\n}\n\n/** One cached page: its rows and the cursor to the page after it, so a cache hit still says \"there is more\". */\ninterface CachedPage {\n rows: Array<Record<string, unknown>>;\n cursor?: string;\n}\n\n// A page is cached under the statement, its size and the cursor it starts at — any one of the three\n// changes which rows it holds. An --all read is many pages and never comes from (or goes to) this cache.\n// `cut=steady`: a page cached before the server cut pages in a steady order holds rows, and a\n// cursor, in Google's own order — served next to a page cut the new way, it repeats or skips rows.\nexport function pageCacheKey(customerId: string, query: string, pageSize: number, cursor: string | undefined): string {\n return buildQueryCacheKey(customerId, `${query}\\u0000page=${pageSize}\\u0000cursor=${cursor ?? \"\"}\\u0000cut=steady`);\n}\n\nasync function executeQuery(\n finalQuery: string,\n args: Record<string, unknown>,\n customerId: string,\n limit: number,\n warnings: AdsWarning[],\n useCache: boolean,\n cacheKey: string,\n levels: ExpandedLevel[] | undefined,\n): Promise<void> {\n const body: Record<string, unknown> = {\n customerId,\n ...(levels ? { levels } : { query: finalQuery }),\n pageSize: limit,\n };\n const managerId = getManagerIdForCustomer(customerId);\n if (managerId) body.managerId = managerId;\n if (!useCache) body.skipCache = true;\n\n const servingOptions = keywordServingOptions(finalQuery);\n const {\n allRows,\n lastPageToken,\n totalRowsWritten,\n rowsOfThisRead,\n convertingRows,\n keywordLimits,\n observedFields,\n fileColumns,\n budgetRows,\n moneySample,\n } = await fetchAllPages(finalQuery, body, args, servingOptions);\n // A read that started after a cursor, or left a page unread, cannot speak for the rows it skipped.\n const readWhole = !args.cursor && !lastPageToken;\n\n if (args.out) {\n const truncation = completenessWarnings({\n rowCount: rowsOfThisRead,\n effectiveLimit: effectiveRowLimit(finalQuery),\n hasMore: Boolean(lastPageToken),\n });\n const fileWarnings = [\n ...warnings,\n ...renderKeywordLimits(keywordLimits),\n ...missingFieldWarningsFor(finalQuery, observedFields, totalRowsWritten),\n // Only a CSV has a header to fall out of; json and jsonl files carry every row whole.\n ...(isCsvPath(args.out as string)\n ? unwrittenColumnWarnings(fileColumns, observedFields, { gaql: finalQuery, appended: args.append === true })\n : []),\n ...accountFundsWarnings(parseSelectedFields(finalQuery), budgetRows),\n ...conversionMixWarnings(finalQuery, readWhole ? convertingRows : undefined),\n ...moneyUnitWarnings(moneySample),\n ...truncation,\n ];\n const summary = buildFileSummary({\n file: resolve(args.out as string),\n rows: totalRowsWritten,\n warnings: fileWarnings,\n complete: truncation.length === 0,\n });\n // The file carries every column: said back, so a summary is not read as a narrowed file.\n writeNarrowed(summary, requestedFields(args));\n return;\n }\n\n if (useCache && !args.all && allRows.length > 0) {\n const page: CachedPage = { rows: allRows, ...(lastPageToken ? { cursor: lastPageToken } : {}) };\n cacheSet(\"queries\", cacheKey, page, getQueryTtl(finalQuery), getFieldDescriptions(extractFields(allRows)));\n }\n const fields = extractFields(allRows);\n outputResults(\n allRows,\n getFieldDescriptions(fields),\n [\n ...warnings,\n ...missingFieldWarnings(finalQuery, allRows),\n ...keywordServingWarnings(allRows, servingOptions),\n ...accountFundsWarnings(parseSelectedFields(finalQuery), allRows),\n ...conversionMixWarnings(finalQuery, readWhole ? convertingRows : undefined),\n ...moneyUnitWarnings(moneyExample(allRows)),\n ],\n args,\n false,\n {\n gaql: finalQuery,\n effectiveLimit: effectiveRowLimit(finalQuery),\n nextCursor: lastPageToken,\n },\n );\n}\n\n// A --out read must always produce the file. The --out branch never populates the cache, so a hit\n// there can only come from an earlier stdout read of the same statement — serving it would print\n// rows and leave the file stale or absent, which the next command reads as this pull.\nexport function shouldReadCache(args: Record<string, unknown>): boolean {\n return !args[\"no-cache\"] && !args.out && !args.all;\n}\n\ninterface ValidatedArgs {\n customerId: string;\n limit: number;\n finalQuery: string;\n levels?: ExpandedLevel[];\n warnings: AdsWarning[];\n useCache: boolean;\n cacheKey: string;\n}\n\nconst DEFAULT_QUERY_LIMIT = 200;\n\ntype ParsedQueryLimit = { ok: true; limit: number; clampedFrom?: number } | { ok: false; error: AdsErrorEnvelope };\n\n/**\n * `--limit` is the page size, and the server refuses a page above its cap. A larger one is read at\n * the cap rather than refused: it only sets how many rows one call carries, so the cursor and --all\n * still reach every row. Anything that is not a positive whole number is refused here, before any\n * request — sent on, the server's refusal reached the agent as an API_ERROR.\n */\nexport function parseQueryLimit(raw: unknown, fallback = DEFAULT_QUERY_LIMIT): ParsedQueryLimit {\n if (raw === undefined || raw === null || raw === \"\") return { ok: true, limit: fallback };\n const limit = Number(raw);\n if (Number.isInteger(limit) && limit > GOOGLE_ADS_QUERY_MAX_PAGE_SIZE) {\n return { ok: true, limit: GOOGLE_ADS_QUERY_MAX_PAGE_SIZE, clampedFrom: limit };\n }\n if (Number.isInteger(limit) && limit >= 1) return { ok: true, limit };\n return {\n ok: false,\n error: {\n ok: false,\n error: {\n code: \"VALIDATION_ERROR\",\n message: `--limit must be a whole number from 1 to ${GOOGLE_ADS_QUERY_MAX_PAGE_SIZE}, got '${String(raw)}'.`,\n fix: {\n action: \"retry_with_flag\",\n explanation: `--limit is the size of one page, at most ${GOOGLE_ADS_QUERY_MAX_PAGE_SIZE} rows. For more rows, add --all --out <file>: it reads every page.`,\n },\n retryable: false,\n },\n },\n };\n}\n\n/**\n * The page size: --limit when given; else, for --all, the largest page the route returns; else the\n * preset's own page size, else 200. The small defaults keep one printed page short — an --all read\n * goes through every page anyway, and each page is a round trip that re-reads Google's own page.\n */\nexport function queryPageSize(args: Record<string, unknown>): ParsedQueryLimit {\n if (args.all) return parseQueryLimit(args.limit, GOOGLE_ADS_QUERY_MAX_PAGE_SIZE);\n const preset = typeof args.preset === \"string\" ? getPreset(args.preset) : undefined;\n return parseQueryLimit(args.limit, preset?.defaultLimit ?? DEFAULT_QUERY_LIMIT);\n}\n\nfunction clampWarnings(parsed: { limit: number; clampedFrom?: number }): AdsWarning[] {\n if (parsed.clampedFrom === undefined) return [];\n return [\n {\n code: \"LIMIT_CLAMPED\",\n message: `--limit ${parsed.clampedFrom} is above the largest page (${GOOGLE_ADS_QUERY_MAX_PAGE_SIZE} rows), so pages were read at ${parsed.limit}. That changes only how many rows one call carries: --all still reads every page.`,\n },\n ];\n}\n\nasync function validateArgs(args: Record<string, unknown>): Promise<ValidatedArgs | null> {\n const parsedLimit = queryPageSize(args);\n if (!parsedLimit.ok) {\n writeAdsJson(parsedLimit.error);\n process.exit(1);\n }\n const { limit } = parsedLimit;\n const customerId = await resolveCustomerId(args);\n\n const read = resolveGaql(args);\n if (!read) {\n process.exit(1);\n }\n\n // A preset read in levels sends each level's statement, so each is checked as the one it is.\n const statements = read.levels?.map((part) => part.query) ?? [read.query];\n const preflights = statements.map((statement) => validatePreflight(statement, customerId));\n const refused = preflights.find((preflight) => !preflight.valid && preflight.error);\n if (refused?.error) {\n writeAdsJson(refused.error);\n process.exit(1);\n }\n\n const corrected = statements.map((statement, index) => preflights[index]?.correctedQuery ?? statement);\n const levels = read.levels?.map((part, index) => ({ ...part, query: corrected[index] ?? part.query }));\n const finalQuery = corrected.join(\"\\n\");\n return {\n customerId,\n limit,\n finalQuery,\n levels,\n warnings: [\n ...clampWarnings(parsedLimit),\n ...preflights.flatMap((preflight) => preflight.warnings),\n ...servingScopeWarnings(args, finalQuery),\n ...syncedCopyWarnings(args),\n ],\n useCache: !args[\"no-cache\"],\n // A level read once per campaign reads the campaigns its listing names: they are part of the read.\n cacheKey: pageCacheKey(\n customerId,\n [finalQuery, ...(levels ?? []).flatMap((part) => part.eachCampaignOf ?? [])].join(\"\\n\"),\n limit,\n args.cursor as string | undefined,\n ),\n };\n}\n\nfunction handleQueryError(\n thrown: unknown,\n finalQuery: string,\n levels: ExpandedLevel[] | undefined,\n customerId: string,\n limit: number,\n args: Record<string, unknown>,\n): void {\n const err = thrown instanceof StoppedRead ? thrown.failure : thrown;\n const envelope: AdsErrorEnvelope =\n err instanceof ApiError\n ? parseApiError(err.message, finalQuery, customerId, err.code)\n : {\n ok: false,\n error: {\n code: \"NETWORK_ERROR\",\n message: err instanceof Error ? err.message : \"Unexpected error\",\n fix: { action: \"wait_and_retry\", explanation: \"Network error — check connectivity and retry\" },\n retryable: true,\n },\n };\n envelope.error.gaqlExecuted = finalQuery;\n if (err instanceof ApiError && err.code === \"CONFLICT\") {\n envelope.error.fix = conflictFix(envelope.error.fix, finalQuery, levels, customerId, limit, args);\n }\n if (thrown instanceof StoppedRead) {\n const partial = partialReadFor(thrown.partial, err);\n envelope.error.partial = partial;\n envelope.error.fix.explanation += ` ${partialReadAdvice(partial)}`;\n if (partial.cursor) {\n const resume = \"file\" in partial ? [\"--append\", \"--out\", partial.file.replace(/\\.partial$/, \"\")] : [];\n envelope.error.fix.correctedCommand = rerunCommand(rerunRead(finalQuery, levels, args), customerId, limit, args, [\n \"--cursor\",\n partial.cursor,\n ...resume,\n ]);\n }\n }\n writeAdsJson(envelope);\n // Not process.exit: it cuts off a large envelope (the rows kept in error.partial.data) before stdout drains.\n process.exitCode = 1;\n}\n\n/**\n * The way past rows that moved between pages: from page 1, read fresh, ordered so no two rows tie —\n * the read that does not move again. A read that appended finds its earlier file back in place\n * (`readStopped`), so it appends again.\n */\nfunction conflictFix(\n fix: AdsErrorEnvelope[\"error\"][\"fix\"],\n finalQuery: string,\n levels: ExpandedLevel[] | undefined,\n customerId: string,\n limit: number,\n args: Record<string, unknown>,\n): AdsErrorEnvelope[\"error\"][\"fix\"] {\n const out = typeof args.out === \"string\" ? [...(args.append ? [\"--append\"] : []), \"--out\", args.out] : [];\n // Each level is its own statement, ordered on its own; a read in levels is rerun as its preset,\n // whose levels already order every row apart (stable-order.test.ts), so only the statement read is reordered.\n const stable = levels ? undefined : stableOrderQuery(finalQuery);\n const unorderable = levels\n ? [...new Set(levels.flatMap((level) => stableOrderQuery(level.query).unorderable))]\n : (stable?.unorderable ?? []);\n let explanation = fix.explanation;\n if (unorderable.length > 0) {\n explanation += ` Google cannot order by ${unorderable.join(\", \")}, so its rows can still move between pages: leave it out of the SELECT, or read a shorter date range per call.`;\n }\n if (args.append && typeof args.out === \"string\") {\n explanation += ` ${args.out} is back as it was before this read.`;\n }\n return {\n ...fix,\n explanation,\n correctedCommand: rerunCommand(rerunRead(stable?.query ?? finalQuery, levels, args), customerId, limit, args, [\n \"--no-cache\",\n ...out,\n ]),\n };\n}\n\n/**\n * What a rerun reads: the statement that ran (a preset already expanded) — a cursor only resumes the\n * statement it was cut from, so it is the one executed, never the one typed. A read in levels is\n * several statements no one request runs, and its `level:` cursor resumes only them: it is rerun as\n * the preset that expands to them.\n */\nfunction rerunRead(gaql: string, levels: ExpandedLevel[] | undefined, args: Record<string, unknown>): string[] {\n if (!levels) return [gaql];\n const words = [\"--preset\", String(args.preset)];\n if (args[\"campaign-id\"] !== undefined && args[\"campaign-id\"] !== \"\") {\n words.push(\"--campaign-id\", String(args[\"campaign-id\"]));\n }\n if (typeof args.search === \"string\" && args.search !== \"\") words.push(\"--search\", args.search);\n const window = presetDateRange(args);\n if (window.ok && window.dateRange !== undefined) words.push(\"--date-range\", window.dateRange);\n if (args[\"include-paused\"]) words.push(\"--include-paused\");\n return words;\n}\n\n/** The read as a command to run again: what it read (`rerunRead`), its account, page size, paging and output, plus `extra`. */\nfunction rerunCommand(\n read: string[],\n customerId: string,\n limit: number,\n args: Record<string, unknown>,\n extra: string[],\n): string {\n const words = [\"baker\", \"ads\", \"google\", \"query\", ...read, \"--customer-id\", customerId, \"--limit\", String(limit)];\n if (args.all) words.push(\"--all\");\n if (typeof args.output === \"string\" && args.output !== \"json\") words.push(\"--output\", args.output);\n // `--company` was taken off argv for this process only: without it, the rerun reads another company.\n const company = optionalTargetCompany();\n if (company) words.push(\"--company\", company);\n return quoteShell([...words, ...extra]);\n}\n\n// Rows that moved between pages cannot be resumed from where they stopped: only a read from page 1 can.\nfunction partialReadFor(partial: PartialRead, err: unknown): PartialRead {\n if (err instanceof ApiError && err.code === \"CONFLICT\") {\n const { cursor: _unresumable, ...rest } = partial;\n return rest;\n }\n return partial;\n}\n\nfunction partialReadAdvice(partial: PartialRead): string {\n if (!(\"file\" in partial)) {\n const kept = `The ${partial.rows} rows read before it stopped are in error.partial.data, which is NOT the whole read — never count or total from them.`;\n if (!partial.cursor) return `${kept} Read again from the first page.`;\n return `${kept} Read the rest with the same command plus --cursor \"${partial.cursor}\", or read everything again with --all --out <file>.`;\n }\n const kept = `${partial.file} holds the ${partial.rows} rows read before it stopped, which is NOT the whole read — never count or total from it.`;\n if (!partial.cursor) return `${kept} Read again from the first page.`;\n const out = quoteShell([partial.file.replace(/\\.partial$/, \"\")]);\n return `${kept} Resume with the same command plus --cursor \"${partial.cursor}\" --append --out ${out}: it carries on in that file and names it ${out} once the last page is in.`;\n}\n\n/**\n * One read, start to finish: validate, serve a cached page or fetch, then write the envelope. The\n * `query` command and every `<thing> list` command (which hand it a preset) run through here.\n */\nexport async function runQuery(args: Record<string, unknown>): Promise<void> {\n const validated = await validateArgs(args);\n if (!validated) return;\n const { customerId, limit, finalQuery, levels, warnings, useCache, cacheKey } = validated;\n\n if (shouldReadCache(args)) {\n const cached = cacheGet<CachedPage>(\"queries\", cacheKey);\n if (cached && Array.isArray(cached.data.rows)) {\n const rows = cached.data.rows;\n outputResults(\n rows,\n cached.fields ?? getFieldDescriptions(extractFields(rows)),\n [\n ...warnings,\n ...missingFieldWarnings(finalQuery, rows),\n ...keywordServingWarnings(rows, keywordServingOptions(finalQuery)),\n ...accountFundsWarnings(parseSelectedFields(finalQuery), rows),\n // A cached page is whole only when it starts at the first row and has no page after it.\n ...conversionMixWarnings(\n finalQuery,\n args.cursor || cached.data.cursor ? undefined : foldConvertingRows(rows),\n ),\n ...moneyUnitWarnings(moneyExample(rows)),\n ],\n args,\n true,\n { gaql: finalQuery, effectiveLimit: effectiveRowLimit(finalQuery), nextCursor: cached.data.cursor },\n );\n return;\n }\n }\n\n try {\n await executeQuery(finalQuery, args, customerId, limit, warnings, useCache, cacheKey, levels);\n } catch (err) {\n handleQueryError(err, finalQuery, levels, customerId, limit, args);\n }\n}\n\nexport const queryCommand = defineCommand({\n meta: {\n name: \"query\",\n description: `Run GAQL against Google Ads, one page at a time. Supports raw GAQL, presets, paging, file export, and caching.\n\nStart here:\n baker ads google query --list-presets\n baker ads google query --preset campaign-performance --customer-id 1234567890\n\nEach read returns one page (--limit rows; the preset's page size by default, else 200). When the\naccount holds more, the envelope carries pagination.cursor: pass it with --cursor for the next page,\nor read everything with --all --out <file>, which pages at 8192 rows. A LIMIT written in the GAQL\ncaps the whole read.\n\nAn --out file appears only once the read is over; until then the rows are in <file>.partial. A read\nthat stops part way exits with error.partial: the .partial file (or, without --out, the rows read)\nand the cursor to carry on from with --cursor <it> --append --out <same file>; error.fix.correctedCommand\nis that command. BUDGET_EXCEEDED and TIMEOUT (a page ran out of time or memory) and PAGINATION_CONFLICT\n(rows moved between pages; its command reads again from page 1 with a unique ORDER BY) are retryable.\n\nExamples:\n baker ads google query \"SELECT campaign.name, metrics.clicks FROM campaign WHERE segments.date DURING LAST_7_DAYS\" --customer-id 1234567890\n baker ads google query --gaql \"SELECT ad_group.name FROM ad_group WHERE ad_group.status = 'ENABLED'\" --customer-id 1234567890\n baker ads google query --preset search-terms --customer-id 1234567890 --date-range LAST_7_DAYS --all --out terms.csv\n baker ads google query --preset negative-keywords --customer-id 1234567890 --campaign-id 23886044838\n baker ads google query --preset negative-keywords --customer-id 1234567890 --search masia,paellero\n baker ads google query --preset ai-max-search-terms --customer-id 1234567890 --search birra,cerveza --all --out aimax.csv\n baker ads google query --preset keyword-serving --customer-id 1234567890 --cursor <pagination.cursor>`,\n },\n args: withWindowSpellings({\n query: { type: \"positional\", description: \"GAQL SELECT statement\", required: false },\n gaql: {\n type: \"string\",\n description: \"GAQL SELECT statement as a flag (instead of the positional)\",\n required: false,\n },\n \"customer-id\": {\n type: \"string\",\n description: \"Google Ads customer ID (10 digits; dashes are fine)\",\n required: false,\n },\n preset: { type: \"string\", description: \"Named query preset\", required: false },\n \"date-range\": { type: \"string\", description: \"Date range override for presets\", required: false },\n since: { type: \"string\", description: \"For a preset: first day, YYYY-MM-DD (with --until)\", required: false },\n until: { type: \"string\", description: \"For a preset: last day, YYYY-MM-DD (with --since)\", required: false },\n \"include-paused\": {\n type: \"boolean\",\n description: \"Include paused entities in preset results (default: serving entities only)\",\n required: false,\n },\n \"campaign-id\": {\n type: \"string\",\n description: \"For a preset: only these campaigns, comma-separated ids (--campaign-id 123,456)\",\n required: false,\n },\n search: {\n type: \"string\",\n description:\n \"For a keyword or search-term preset: only rows whose text contains any of these, comma-separated, case-insensitive (--search masia,paellero)\",\n required: false,\n },\n limit: {\n type: \"string\",\n description: \"Rows per page (default: the preset's page size, else 200; 8192 with --all)\",\n required: false,\n },\n \"list-presets\": { type: \"boolean\", description: \"List available presets\", required: false },\n cursor: { type: \"string\", description: \"pagination.cursor from the previous page\", required: false },\n all: { type: \"boolean\", description: \"Follow every page (use with --out for large reads)\", required: false },\n out: {\n type: \"string\",\n description:\n \"Write the rows alone to this file (not the envelope); it appears once the read is over, until then the rows are in <file>.partial\",\n required: false,\n },\n append: {\n type: \"boolean\",\n description: \"Append to file; with --cursor, carries on a stopped read in the <file>.partial it left\",\n required: false,\n },\n output: { type: \"string\", description: \"Format: json|csv|jsonl|md\", required: false, default: \"json\" },\n fields: {\n type: \"string\",\n description: \"Only these columns, comma-separated (--fields campaign.name,campaign.status); every format\",\n required: false,\n },\n \"no-cache\": { type: \"boolean\", description: \"Skip cache\", required: false },\n full: { type: \"boolean\", description: \"Include the field description glossary\", required: false },\n }),\n run: async ({ args }) => {\n if (args[\"list-presets\"]) {\n writeAdsJson({\n ok: true,\n data: PRESETS.map((p) => ({\n name: p.name,\n description: p.description,\n defaultDateRange: p.defaultDateRange,\n pageSize: p.defaultLimit,\n servingOnly: (p.statusFields?.length ?? 0) > 0,\n campaignScoped: isCampaignScoped(p),\n searchable: isSearchable(p),\n gaql: expandPreset(p, {}).query,\n })),\n });\n return;\n }\n\n await runQuery(args);\n },\n});\n","import { duringLiteralExplanation, equivalentBetween, isDuringLiteral } from \"@baker/api/ads-google/during-literals\";\nimport { SERVING_CHAINS } from \"@baker/api/ads-google/presets\";\nimport type { AdsErrorEnvelope, AdsWarning, PreflightResult } from \"../types.ts\";\nimport { NO_OR_EXPLANATION } from \"./correction-table.ts\";\nimport { LIST_FIELDS, listFieldGuidance } from \"./list-fields.ts\";\n\nfunction buildCommand(query: string, customerId: string): string {\n return `baker ads google query \"${query}\" --customer-id ${customerId}`;\n}\n\n// A rung is also settled when the query pins that level to one named entity: the caller looked at\n// that level and chose it, which is a different act from sweeping it silently.\nconst RUNG_PIN_FIELDS: Record<string, string[]> = {\n \"campaign.status\": [\"campaign.id\", \"campaign.resource_name\"],\n \"ad_group.status\": [\"ad_group.id\", \"ad_group.resource_name\"],\n \"ad_group_criterion.status\": [\"ad_group_criterion.criterion_id\", \"ad_group_criterion.resource_name\"],\n \"ad_group_ad.status\": [\"ad_group_ad.ad.id\", \"ad_group_ad.resource_name\"],\n \"asset_group.status\": [\"asset_group.id\", \"asset_group.resource_name\"],\n \"asset_group_asset.status\": [\"asset_group_asset.resource_name\"],\n \"campaign_asset.status\": [\"campaign_asset.resource_name\"],\n \"ad_group_asset.status\": [\"ad_group_asset.resource_name\"],\n};\n\n/**\n * The statement with every quoted value's contents blanked, keeping each character's position, so a\n * keyword inside a value (a --search term reading \"limit 1\") is never taken for the statement's own.\n */\nexport function blankQuotedValues(query: string): string {\n return query.replace(\n /'(?:\\\\.|[^'\\\\])*'|\"(?:\\\\.|[^\"\\\\])*\"/g,\n (value) => `${value[0]}${\" \".repeat(value.length - 2)}${value[0]}`,\n );\n}\n\n// WHERE clause only — a status column in the SELECT list displays status, it does not scope the rows.\n// The trailing clauses are found with quoted values blanked, then cut from the statement as written.\nfunction whereClause(query: string): string {\n const blanked = blankQuotedValues(query);\n const match = blanked.match(/\\bWHERE\\b([\\s\\S]*)$/i);\n if (match?.index === undefined || !match[1]) return \"\";\n const start = match.index + match[0].length - match[1].length;\n let end = blanked.length;\n for (const trailing of [/\\bORDER\\s+BY\\b/i, /\\bLIMIT\\b/i, /\\bPARAMETERS\\b/i]) {\n const idx = match[1].search(trailing);\n if (idx !== -1) end = Math.min(end, start + idx);\n }\n return query.slice(start, end);\n}\n\nfunction selectClause(query: string): string {\n return query.split(/\\bFROM\\b/i)[0] ?? \"\";\n}\n\nfunction mentions(clause: string, field: string): boolean {\n return new RegExp(`(?<![\\\\w.])${field.replace(/\\./g, \"\\\\.\")}\\\\b`, \"i\").test(clause);\n}\n\ninterface ChainAnalysis {\n chain: string[];\n /** Rungs the WHERE clause says nothing about — neither a status predicate nor an entity pin. */\n unscoped: string[];\n /** Rungs the WHERE clause pins to `= 'ENABLED'`, i.e. where the query claims \"this is live\". */\n assertsServing: boolean;\n}\n\nfunction analyzeServingChain(query: string): ChainAnalysis | null {\n const resource = fromResource(query);\n const chain = resource ? SERVING_CHAINS[resource] : undefined;\n if (!chain) return null;\n\n const where = whereClause(query);\n\n // A negative keyword never serves, so the serving chain is not a question anyone is asking of it.\n if (/ad_group_criterion\\.negative\\s*=\\s*TRUE/i.test(where)) return null;\n\n const unscoped = chain.filter((rung) => {\n if (mentions(where, rung)) return false;\n return !(RUNG_PIN_FIELDS[rung] ?? []).some((pin) => mentions(where, pin));\n });\n const assertsServing = chain.some((rung) =>\n new RegExp(`${rung.replace(/\\./g, \"\\\\.\")}\\\\s*=\\\\s*'ENABLED'`, \"i\").test(where),\n );\n\n return { chain, unscoped, assertsServing };\n}\n\n/**\n * REJECT a half-asserted chain. A query that pins one rung to ENABLED and leaves another silent\n * returns rows that read as \"these are live\" and are not — the shape that reported 486 serving\n * keywords when the account had 53. There is no reading of \"enabled criteria in ad groups I did\n * not look at\" that anyone means, so this is refused rather than warned: a warning on this path is\n * dropped by `--output csv` and swallowed by `2>/dev/null`, and no data at all is the only signal\n * that survives.\n */\nfunction rejectPartialChain(query: string, customerId: string, analysis: ChainAnalysis): AdsErrorEnvelope | null {\n if (!analysis.assertsServing || analysis.unscoped.length === 0) return null;\n\n const added = analysis.unscoped.map((rung) => `${rung} = 'ENABLED'`).join(\" AND \");\n // The rungs go into SELECT as well where the resource segments on them — on campaign_asset and\n // ad_group_asset a filtered-but-unselected ancestor is refused outright, so a corrected command\n // that only touched the WHERE clause was one the agent could not run either.\n const fixed = addRequiredAncestorFields(query.replace(/\\bWHERE\\b/i, `WHERE ${added} AND`)).query;\n return {\n ok: false,\n error: {\n code: \"INCOMPLETE_STATUS_CHAIN\",\n message: `This query filters on serving status but leaves ${analysis.unscoped.join(\", \")} unscoped. Google Ads has no single serving flag — a row is live only when its whole chain (${analysis.chain.join(\" → \")}) is ENABLED, so rows under a paused parent will come back looking live.`,\n fix: {\n action: \"retry_with_modified_query\",\n correctedCommand: buildCommand(fixed, customerId),\n explanation: `Add the missing rungs: ${added}. To look at paused entities on purpose, scope every rung explicitly instead (e.g. ${analysis.unscoped.map((rung) => `${rung} != 'REMOVED'`).join(\" AND \")}), or use --preset ... --include-paused.`,\n },\n retryable: false,\n },\n };\n}\n\n/**\n * ANNOTATE an unasserted chain. A sweep that claims nothing about serving is a legitimate read —\n * \"show me everything, paused included\" — so the rows are not changed. Every unscoped rung's status\n * column is added to SELECT instead, so the status travels with the data through a CSV, a `--out`\n * file and a `python3` pass. A banner does not survive that trip; a column name does.\n */\nfunction annotateUnscopedChain(query: string, analysis: ChainAnalysis): { query: string; warnings: AdsWarning[] } {\n if (analysis.assertsServing || analysis.unscoped.length === 0) return { query, warnings: [] };\n\n const select = selectClause(query);\n const missing = analysis.unscoped.filter((rung) => !mentions(select, rung));\n if (missing.length === 0) return { query, warnings: [] };\n\n return {\n query: query.replace(/SELECT\\s+/i, `SELECT ${missing.join(\", \")}, `),\n warnings: [\n {\n code: \"SERVING_STATUS_ADDED\",\n message: `Added ${missing.join(\", \")} to SELECT — this query does not scope ${analysis.unscoped.join(\", \")}, so it returns paused-parent rows that are not serving. Read those columns before calling any row live; filter every rung = 'ENABLED' to get serving rows only.`,\n },\n ],\n };\n}\n\n// Resources that return exactly one row per account, so no LIMIT can truncate them and no row can be\n// set against another. SELECTing a segment (segments.date, segments.device …) fans one back out into\n// many rows; filtering on a date range in WHERE does not — Google sums the range into the one row,\n// which is exactly what the account-summary preset reads.\nconst SINGLE_ROW_RESOURCES = [\"customer\"];\n\n// The resource named in the FROM clause, lowercased. Newline- and case-tolerant; null when the\n// statement has no FROM.\nexport function fromResource(query: string): string | null {\n const match = query.match(/\\bFROM\\s+([A-Za-z_][A-Za-z0-9_]*)/i);\n return match?.[1]?.toLowerCase() ?? null;\n}\n\n// A statement that returns one row by construction — decided from the statement, never from the rows.\nexport function isSingleRowRead(query: string): boolean {\n const resource = fromResource(query);\n if (!resource || !SINGLE_ROW_RESOURCES.includes(resource)) return false;\n return !/\\bsegments\\./i.test(selectClause(query));\n}\n\n// Resources whose ancestors SEGMENT them: one budget backs many campaigns, one asset is linked from\n// many campaigns/ad groups, so an ancestor field used in WHERE must appear in SELECT too or Google\n// refuses the whole statement with EXPECTED_REFERENCED_FIELD_IN_SELECT_CLAUSE. Verified live on v23:\n// FROM campaign/ad_group/ad_group_ad/ad_group_criterion/asset_group_asset filter their ancestors\n// freely; these three do not.\nconst SEGMENTING_ANCESTORS: Record<string, string[]> = {\n campaign_budget: [\"campaign\"],\n campaign_asset: [\"campaign\"],\n ad_group_asset: [\"campaign\", \"ad_group\"],\n};\n\n/** The ancestor fields a query filters on but does not select — empty unless the resource segments. */\nfunction missingRequiredSelectFields(query: string): string[] {\n const ancestors = SEGMENTING_ANCESTORS[fromResource(query) ?? \"\"];\n if (!ancestors) return [];\n\n const select = selectClause(query);\n // Everything after WHERE, ORDER BY included — an ancestor field is just as referenced there.\n const where = query.split(/\\bWHERE\\b/i)[1] ?? \"\";\n const filtered = ancestors.flatMap(\n (ancestor) => where.match(new RegExp(`(?<![\\\\w.])${ancestor}\\\\.[\\\\w.]+`, \"g\")) ?? [],\n );\n return [...new Set(filtered)].filter((field) => !mentions(select, field));\n}\n\nfunction addRequiredAncestorFields(query: string): { query: string; warnings: AdsWarning[] } {\n const missing = missingRequiredSelectFields(query);\n if (missing.length === 0) return { query, warnings: [] };\n\n return {\n query: query.replace(/SELECT\\s+/i, `SELECT ${missing.join(\", \")}, `),\n warnings: [\n {\n code: \"REQUIRED_FIELD_ADDED\",\n message: `Added ${missing.join(\", \")} to SELECT — ${fromResource(query)} queries must select the ancestor fields used in WHERE`,\n },\n ],\n };\n}\n\nfunction applyAutoFixes(query: string): { query: string; warnings: AdsWarning[] } {\n let corrected = query;\n const warnings: AdsWarning[] = [];\n\n // bare keyword.text → ad_group_criterion.keyword.text\n // Lookbehind skips fields already scoped to a resource (shared_criterion.keyword.text,\n // campaign_criterion.keyword.text, ad_group_criterion.keyword.text) so they pass through untouched.\n if (/(?<![\\w.])keyword\\.text\\b/.test(corrected)) {\n corrected = corrected.replace(/(?<![\\w.])keyword\\.text\\b/g, \"ad_group_criterion.keyword.text\");\n warnings.push({ code: \"FIELD_RENAMED\", message: \"keyword.text → ad_group_criterion.keyword.text\" });\n }\n\n // bare keyword.match_type → ad_group_criterion.keyword.match_type\n if (/(?<![\\w.])keyword\\.match_type\\b/.test(corrected)) {\n corrected = corrected.replace(/(?<![\\w.])keyword\\.match_type\\b/g, \"ad_group_criterion.keyword.match_type\");\n warnings.push({ code: \"FIELD_RENAMED\", message: \"keyword.match_type → ad_group_criterion.keyword.match_type\" });\n }\n\n // shopping_performance_view.product_* → segments.product_*\n if (/shopping_performance_view\\.product_\\w+/.test(corrected)) {\n corrected = corrected.replace(/shopping_performance_view\\.product_(\\w+)/g, \"segments.product_$1\");\n warnings.push({ code: \"FIELD_RENAMED\", message: \"shopping_performance_view.product_* → segments.product_*\" });\n }\n\n // asset.<type>_asset.final_urls → asset.final_urls (final URLs live on the asset itself;\n // the typed sub-message only carries type-specific fields like link_text/descriptions)\n if (/asset\\.\\w+_asset\\.final_(mobile_)?urls\\b/.test(corrected)) {\n corrected = corrected.replace(/asset\\.\\w+_asset\\.final_(mobile_)?urls\\b/g, \"asset.final_$1urls\");\n warnings.push({ code: \"FIELD_RENAMED\", message: \"asset.<type>_asset.final_urls → asset.final_urls\" });\n }\n\n const ancestorFix = addRequiredAncestorFields(corrected);\n corrected = ancestorFix.query;\n warnings.push(...ancestorFix.warnings);\n\n // campaign.status = 'ACTIVE' → 'ENABLED'\n if (/campaign\\.status\\s*=\\s*'ACTIVE'/i.test(corrected)) {\n corrected = corrected.replace(/campaign\\.status\\s*=\\s*'ACTIVE'/gi, \"campaign.status = 'ENABLED'\");\n warnings.push({ code: \"ENUM_CORRECTED\", message: \"campaign.status ACTIVE → ENABLED\" });\n }\n\n // ad_group.status = 'ACTIVE' → 'ENABLED'\n if (/ad_group\\.status\\s*=\\s*'ACTIVE'/i.test(corrected)) {\n corrected = corrected.replace(/ad_group\\.status\\s*=\\s*'ACTIVE'/gi, \"ad_group.status = 'ENABLED'\");\n warnings.push({ code: \"ENUM_CORRECTED\", message: \"ad_group.status ACTIVE → ENABLED\" });\n }\n\n return { query: corrected, warnings };\n}\n\nconst DURING_CLAUSE = /(?<=[a-z_]\\.[a-z_.]+\\s+)DURING\\s+([A-Za-z0-9_]+)/gi;\n\n/**\n * REJECT a DURING literal outside Google's set (LAST_90_DAYS, LAST_12_MONTHS …). Google refuses the\n * whole statement, so it is refused here with the same window spelled as a BETWEEN range.\n */\nfunction rejectUnsupportedDuring(query: string, customerId: string): AdsErrorEnvelope | null {\n const unsupported = [...query.matchAll(DURING_CLAUSE)]\n .map((match) => match[1] ?? \"\")\n .filter((literal) => !isDuringLiteral(literal));\n const literal = unsupported[0];\n if (literal === undefined) return null;\n const now = new Date();\n const between = equivalentBetween(literal, now);\n // Every unsupported clause is rewritten, so the corrected command runs as-is; one with no fixed\n // window leaves nothing runnable to offer.\n const fixed = unsupported.every((l) => equivalentBetween(l, now) !== null)\n ? query.replace(DURING_CLAUSE, (clause, l: string) =>\n isDuringLiteral(l) ? clause : (equivalentBetween(l, now) ?? clause),\n )\n : undefined;\n return {\n ok: false,\n error: {\n code: \"INVALID_DATE_RANGE\",\n message: `DURING ${literal} is not a Google Ads date range, so Google would refuse this query.`,\n fix: {\n action: \"narrow_date_range\",\n ...(fixed ? { correctedCommand: buildCommand(fixed, customerId) } : {}),\n explanation: duringLiteralExplanation(literal, between),\n },\n retryable: false,\n },\n };\n}\n\nconst WHERE_OPERATOR =\n /(?<![\\w.])([a-z_]+(?:\\.[a-z_]+)+)\\s*(CONTAINS\\s+(?:ALL|ANY|NONE)|IS\\s+NOT\\s+NULL|IS\\s+NULL|NOT\\s+LIKE|NOT\\s+IN|NOT\\s+REGEXP_MATCH|REGEXP_MATCH|LIKE|IN|BETWEEN|DURING|!=|<=|>=|=|<|>)/gi;\n\nfunction escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/** The statement without one null test on `field`, with `field` kept in SELECT so the rows still carry it. */\nfunction withoutNullTest(query: string, field: string): string {\n const test = `${escapeRegExp(field)}\\\\s+IS\\\\s+(?:NOT\\\\s+)?NULL\\\\b`;\n const dropped = query\n .replace(new RegExp(`\\\\bWHERE\\\\s+${test}\\\\s+AND\\\\s+`, \"i\"), \"WHERE \")\n .replace(new RegExp(`\\\\s+AND\\\\s+${test}`, \"i\"), \"\")\n .replace(new RegExp(`\\\\s*\\\\bWHERE\\\\s+${test}`, \"i\"), \"\");\n return mentions(selectClause(dropped), field) ? dropped : dropped.replace(/SELECT\\s+/i, `SELECT ${field}, `);\n}\n\n/** `field = 'x'` / `IN (…)` as CONTAINS ANY, `!=` / `NOT IN` as CONTAINS NONE — null when there is no list equivalent. */\nfunction asListCondition(query: string, field: string): string | null {\n const condition = new RegExp(\n `(?<![\\\\w.])${escapeRegExp(field)}\\\\s*(NOT\\\\s+IN\\\\b|IN\\\\b|!=|=)\\\\s*('[^']*'|\\\\([^)]*\\\\))`,\n \"i\",\n );\n const match = query.match(condition);\n if (!match) return null;\n const [, operator = \"\", value = \"\"] = match;\n const contains = /^(=|IN)$/i.test(operator.trim()) ? \"CONTAINS ANY\" : \"CONTAINS NONE\";\n const values = value.startsWith(\"(\") ? value : `(${value})`;\n return query.replace(condition, `${field} ${contains} ${values}`);\n}\n\n/**\n * REJECT an operator a list field does not take. Google filters a list field only with CONTAINS\n * ALL/ANY/NONE and refuses the whole statement otherwise. The corrected read rewrites =/IN/!=/NOT IN\n * to CONTAINS, and drops a null test — which has no list equivalent — keeping the field in SELECT for\n * the caller to filter. LIKE and the rest have no rewrite, so they get the explanation alone.\n */\nfunction rejectListFieldOperator(query: string, customerId: string): AdsErrorEnvelope | null {\n const where = whereClause(query).replace(/'(?:\\\\.|[^'\\\\])*'|\"(?:\\\\.|[^\"\\\\])*\"/g, \"''\");\n const refusals = [...where.matchAll(WHERE_OPERATOR)]\n .map(([, field = \"\", operator = \"\"]) => ({\n field: field.toLowerCase(),\n operator: operator.toUpperCase().replace(/\\s+/g, \" \"),\n }))\n .filter(({ field, operator }) => LIST_FIELDS.has(field) && !operator.startsWith(\"CONTAINS\"));\n const first = refusals[0];\n if (!first) return null;\n const fixed = refusals.reduce<string | null>(\n (corrected, { field, operator }) =>\n corrected === null\n ? null\n : operator.startsWith(\"IS \")\n ? withoutNullTest(corrected, field)\n : asListCondition(corrected, field),\n query,\n );\n return {\n ok: false,\n error: {\n code: \"INVALID_OPERATOR\",\n message: `${first.operator} cannot be used on ${first.field}: it is a list field, so Google would refuse this query.`,\n fix: {\n action: \"change_operator\",\n ...(fixed ? { correctedCommand: buildCommand(fixed, customerId) } : {}),\n explanation: listFieldGuidance(first.field),\n },\n retryable: false,\n },\n };\n}\n\n/** REJECT the function form CONTAINS(field, 'x'), which GAQL does not have — LIKE is the substring match. */\nfunction rejectContainsCall(query: string, customerId: string): AdsErrorEnvelope | null {\n const containsMatch = query.match(/CONTAINS\\s*\\(\\s*([^,]+),\\s*'([^']+)'\\s*\\)/i);\n if (!containsMatch) return null;\n const field = containsMatch[1]?.trim();\n const value = containsMatch[2] ?? \"\";\n const fixed = query.replace(/CONTAINS\\s*\\(\\s*[^,]+,\\s*'[^']+'\\s*\\)/i, `${field} LIKE '%${value}%'`);\n return {\n ok: false,\n error: {\n code: \"INVALID_OPERATOR\",\n message: \"GAQL does not support CONTAINS. Use LIKE with % wildcards.\",\n fix: {\n action: \"change_operator\",\n correctedCommand: buildCommand(fixed, customerId),\n explanation: \"GAQL uses LIKE '%value%' for substring matching, not CONTAINS()\",\n },\n retryable: false,\n },\n };\n}\n\n/**\n * REJECT an OR, or a parenthesised group of conditions, in WHERE. GAQL joins conditions with AND\n * only and Google refuses either shape, naming the token it choked on but not why. Quoted values\n * (single or double quotes, escapes included) are blanked first, and a parenthesis after IN / CONTAINS ANY|ALL|NONE is a value list, not a group.\n */\nfunction rejectOrCondition(query: string): AdsErrorEnvelope | null {\n const where = whereClause(query).replace(/'(?:\\\\.|[^'\\\\])*'|\"(?:\\\\.|[^\"\\\\])*\"/g, \"''\");\n const hasOr = /(?<![\\w.])OR(?![\\w.])/i.test(where);\n const hasGroup = /(?:^|\\bAND|\\bNOT)\\s*\\(/i.test(where);\n if (!hasOr && !hasGroup) return null;\n return {\n ok: false,\n error: {\n code: \"INVALID_SYNTAX\",\n message: `${hasOr ? \"OR\" : \"A parenthesised condition\"} in WHERE: Google would refuse this query.`,\n fix: { action: \"retry_with_modified_query\", explanation: NO_OR_EXPLANATION },\n retryable: false,\n },\n };\n}\n\nexport function validatePreflight(query: string, customerId: string): PreflightResult {\n const warnings: AdsWarning[] = [];\n const corrected = query;\n\n // REJECT: Non-SELECT queries\n const firstWord = corrected.trim().split(/\\s+/)[0]?.toUpperCase();\n if (firstWord && firstWord !== \"SELECT\") {\n return {\n valid: false,\n warnings: [],\n error: {\n ok: false,\n error: {\n code: \"READ_ONLY\",\n message: `Only SELECT queries are allowed. Got: ${firstWord}`,\n fix: {\n action: \"reject\",\n explanation: \"This CLI only supports GAQL SELECT queries for reading data\",\n },\n retryable: false,\n },\n },\n };\n }\n\n // REJECT: Open-ended date range\n const openDateMatch = corrected.match(/segments\\.date\\s*>=\\s*'(\\d{4}-\\d{2}-\\d{2})'/i);\n if (openDateMatch && !/BETWEEN/i.test(corrected)) {\n const startDate = openDateMatch[1] ?? \"\";\n const today = new Date().toISOString().slice(0, 10);\n const fixed = corrected.replace(\n /segments\\.date\\s*>=\\s*'(\\d{4}-\\d{2}-\\d{2})'/i,\n `segments.date BETWEEN '${startDate}' AND '${today}'`,\n );\n return {\n valid: false,\n warnings: [],\n error: {\n ok: false,\n error: {\n code: \"OPEN_ENDED_DATE\",\n message: \"Open-ended date ranges are not supported. Use BETWEEN or DURING.\",\n fix: {\n action: \"narrow_date_range\",\n correctedCommand: buildCommand(fixed, customerId),\n explanation: \"Use BETWEEN with explicit start and end dates\",\n },\n retryable: false,\n },\n },\n };\n }\n\n for (const reject of [rejectContainsCall, rejectOrCondition, rejectListFieldOperator, rejectUnsupportedDuring]) {\n const rejection = reject(corrected, customerId);\n if (rejection) return { valid: false, warnings: [], error: rejection };\n }\n\n // REJECT: conversion action segments are incompatible with cost metrics in GAQL.\n // Split conversion-action breakdowns from spend/cost queries and join by campaign in report code.\n if (/\\bsegments\\.conversion_action_name\\b/i.test(corrected) && /\\bmetrics\\.cost_micros\\b/i.test(corrected)) {\n return {\n valid: false,\n warnings: [],\n error: {\n ok: false,\n error: {\n code: \"INCOMPATIBLE_FIELDS\",\n message: \"segments.conversion_action_name cannot be selected with metrics.cost_micros in one GAQL query.\",\n fix: {\n action: \"split_query\",\n explanation:\n \"Run one campaign spend query with metrics.cost_micros and a separate conversion-action query without cost metrics, then join the results by campaign.\",\n },\n retryable: false,\n },\n },\n };\n }\n\n // WARN: ad_group_criterion without negative field — positives and negatives will be mixed\n if (/FROM\\s+ad_group_criterion\\b/i.test(corrected) && !/ad_group_criterion\\.negative/i.test(corrected)) {\n warnings.push({\n code: \"NEGATIVE_FIELD_MISSING\",\n message:\n \"ad_group_criterion returns BOTH positive and negative keywords. Add ad_group_criterion.negative to SELECT or filter with WHERE ad_group_criterion.negative = FALSE (positives) / TRUE (negatives). Use --preset positive-keywords or negative-keywords instead.\",\n });\n }\n\n const { query: autoFixed, warnings: autoFixWarnings } = applyAutoFixes(corrected);\n warnings.push(...autoFixWarnings);\n\n // Runs last, on the auto-fixed query, so ACTIVE → ENABLED is already normalised into the chain.\n const analysis = analyzeServingChain(autoFixed);\n if (!analysis) return { valid: true, correctedQuery: autoFixed, warnings };\n\n const rejection = rejectPartialChain(autoFixed, customerId, analysis);\n if (rejection) return { valid: false, warnings: [], error: rejection };\n\n const annotated = annotateUnscopedChain(autoFixed, analysis);\n warnings.push(...annotated.warnings);\n\n return { valid: true, correctedQuery: annotated.query, warnings };\n}\n","/**\n * Refusing to let one `metrics.conversions` column stand for several different events.\n *\n * `metrics.conversions` is not a metric, it is a sum: each campaign contributes whatever conversion\n * actions the account has marked primary for it, and in a real account those differ campaign by\n * campaign — a webinar registration here, a form fill there, a CRM-stage SQL somewhere else. So a\n * total across campaigns adds events that are not the same event, and a conversion rate from one\n * campaign is not comparable with another's.\n *\n * This was learned on a report that put \"our landings 4,6 % CVR vs theirs 3,2 %\" in front of the\n * client. The two sides were different campaign types counting different actions; the client caught\n * it, and the comparison had to be withdrawn. The read that produced it looked completely ordinary:\n * one `landing_page_view` pull with `metrics.conversions` and no campaign filter.\n *\n * The statement decides whether a read can blend actions at all. The rows can only clear it, and only\n * a read that started at the first page and reached the last: converting rows that all come from one\n * campaign leave nothing to total. A row of an account-wide resource is itself a total over every\n * campaign, so it never clears it. A read that skipped rows, or left some unread, is judged on the\n * statement alone.\n */\n\nimport type { AdsWarning } from \"../types.ts\";\nimport { fromResource } from \"./preflight.ts\";\n\n/** Metrics whose value is a sum, or a rate, over whichever conversion actions each campaign counts. */\nconst CONVERSION_METRICS = [\n \"METRICS.CONVERSIONS\",\n \"METRICS.ALL_CONVERSIONS\",\n \"METRICS.CONVERSIONS_VALUE\",\n \"METRICS.ALL_CONVERSIONS_VALUE\",\n \"METRICS.COST_PER_CONVERSION\",\n \"METRICS.COST_PER_ALL_CONVERSIONS\",\n \"METRICS.CONVERSIONS_FROM_INTERACTIONS_RATE\",\n \"METRICS.ALL_CONVERSIONS_FROM_INTERACTIONS_RATE\",\n \"METRICS.VALUE_PER_CONVERSION\",\n \"METRICS.VALUE_PER_ALL_CONVERSIONS\",\n];\n\n/** Segments that split the metric back into one row per action, which is what makes it readable. */\nconst CONVERSION_SEGMENTS = [\"SEGMENTS.CONVERSION_ACTION_NAME\", \"SEGMENTS.CONVERSION_ACTION=\"];\n\n// Selecting the action's name or its resource name splits the rows by action alike; the word\n// boundary keeps `segments.conversion_action_category` from passing for either.\nconst SELECTED_ACTION_SEGMENT = /\\bSEGMENTS\\.CONVERSION_ACTION(_NAME)?\\b/;\n\nfunction selectClause(upperQuery: string): string {\n const fromIdx = upperQuery.indexOf(\" FROM \");\n return fromIdx === -1 ? upperQuery : upperQuery.slice(0, fromIdx);\n}\n\n/** A campaign identity pinned by an equality predicate — the one shape that confines a read. */\nconst CAMPAIGN_EQUALITY = /\\bCAMPAIGN\\.(ID|NAME|RESOURCE_NAME)\\s*=/;\n\n// Everything between WHERE and the first trailing clause. A campaign column in the SELECT list\n// names a dimension the rows are broken down by; only a predicate confines the read to one.\nfunction whereClause(upperQuery: string): string {\n const whereIdx = upperQuery.indexOf(\" WHERE \");\n if (whereIdx === -1) return \"\";\n let rest = upperQuery.slice(whereIdx + 7);\n for (const trailing of [\" ORDER BY \", \" GROUP BY \", \" LIMIT \", \" PARAMETERS \"]) {\n const idx = rest.indexOf(trailing);\n if (idx !== -1) rest = rest.slice(0, idx);\n }\n return rest;\n}\n\n// The same prefix the statement check matches by, so `metrics.conversions_by_conversion_date` and\n// `metrics.conversions_value_per_cost` count on a row exactly as they do in the SELECT.\nfunction isConversionMetric(field: string): boolean {\n const upper = field.toUpperCase();\n return CONVERSION_METRICS.some((metric) => upper.startsWith(metric));\n}\n\n/**\n * Resources whose row is not one campaign's: Google sums every campaign into it — the account, a\n * page, a place, Shopping products, a portfolio strategy, a shared budget — unless the read selects\n * the campaign or ad group it is split by.\n */\nconst ACCOUNT_WIDE_RESOURCES = [\n \"customer\",\n \"landing_page_view\",\n \"expanded_landing_page_view\",\n \"geographic_view\",\n \"user_location_view\",\n \"shopping_performance_view\",\n \"bidding_strategy\",\n \"campaign_budget\",\n];\n\n/**\n * Where a read's converting rows come from. `campaigns` holds the campaigns and ad groups the rows\n * name by id (an ad group sits in one campaign); `byNameOnly` counts rows naming a campaign by name\n * alone, each counted apart since a removed campaign's name can be reused; `unnamed` counts rows\n * naming neither.\n */\nexport type ConvertingRows = { campaigns: Set<string>; byNameOnly: number; unnamed: number };\n\n// Google omits a zero metric, so an absent key counts as no conversions.\nfunction hasConversions(row: Record<string, unknown>): boolean {\n return Object.entries(row).some(\n ([field, value]) => isConversionMetric(field) && value !== undefined && value !== null && Number(value) !== 0,\n );\n}\n\n/** Folds one page into `into`, since the --out path keeps no rows to look at afterwards. */\nexport function foldConvertingRows(\n rows: Array<Record<string, unknown>>,\n into: ConvertingRows = { campaigns: new Set(), byNameOnly: 0, unnamed: 0 },\n): ConvertingRows {\n for (const row of rows) {\n if (!hasConversions(row)) continue;\n const campaign = row[\"campaign.id\"] ?? row[\"campaign.resource_name\"];\n const adGroup = row[\"ad_group.id\"] ?? row[\"ad_group.resource_name\"];\n if (campaign != null) into.campaigns.add(`campaign:${String(campaign)}`);\n else if (adGroup != null) into.campaigns.add(`ad_group:${String(adGroup)}`);\n else if (row[\"campaign.name\"] != null) into.byNameOnly += 1;\n else into.unnamed += 1;\n }\n return into;\n}\n\n/**\n * `converting`, only for a read that started at the first page and reached the last: rows from one\n * campaign leave nothing to total or set side by side. Any other read is judged on the statement.\n */\nexport function conversionMixWarnings(finalQuery: string, converting?: ConvertingRows): AdsWarning[] {\n const upper = ` ${finalQuery.toUpperCase().replace(/\\s+/g, \" \")} `;\n const readsConversions = CONVERSION_METRICS.some((metric) => upper.includes(metric));\n if (!readsConversions) return [];\n if (CONVERSION_SEGMENTS.some((segment) => upper.includes(segment))) return [];\n if (SELECTED_ACTION_SEGMENT.test(selectClause(upper))) return [];\n if (CAMPAIGN_EQUALITY.test(whereClause(upper))) return [];\n if (converting && clearedByRows(finalQuery, converting)) return [];\n\n return [\n {\n code: \"CONVERSION_MIX\",\n message:\n \"MIXED CONVERSION ACTIONS — each campaign counts its own primary actions, so totals across these rows add different events and conversion rates do not compare. Re-run by segments.conversion_action_name before comparing, and tell the user.\",\n },\n ];\n}\n\n// A row that names no campaign stands for one only when its resource belongs to one campaign.\nfunction clearedByRows(finalQuery: string, { campaigns, byNameOnly, unnamed }: ConvertingRows): boolean {\n if (unnamed > 0 && ACCOUNT_WIDE_RESOURCES.includes(fromResource(finalQuery) ?? \"\")) return false;\n return campaigns.size + byNameOnly + unnamed < 2;\n}\n","import type { AdsWarning } from \"../types.ts\";\n\n// Google Ads' UI renders \"Eligible (Limited) — Below first page bid (€3.63)\" from three separate\n// API fields: ad_group_criterion.primary_status_reasons, position_estimates.first_page_cpc_micros\n// and effective_cpc_bid_micros. Read raw, that is an enum name and two micro-integers — this\n// module turns them back into the sentence the column was showing, plus what fixes it.\n\nconst BELOW_FIRST_PAGE_BID = \"AD_GROUP_CRITERION_BELOW_FIRST_PAGE_BID\";\n\n// Reasons the keyword itself can act on. The parent-chain ones (CAMPAIGN_PAUSED, AD_GROUP_PAUSED,\n// AD_GROUP_CRITERION_PAUSED/REMOVED, …) restate a status the row already carries, so they are left\n// out rather than reported as a finding.\nconst ACTIONABLE_REASONS: Record<string, { label: string; advice: string }> = {\n [BELOW_FIRST_PAGE_BID]: {\n label: \"Below first page bid\",\n advice:\n \"raise the max CPC (keywords update --cpc-bid) to at least the first-page estimate, or move the ad group onto a smart bidding strategy that sets the bid itself\",\n },\n AD_GROUP_CRITERION_LOW_QUALITY: {\n label: \"Low quality score\",\n advice:\n \"a bid raise does not lift quality — tighten ad relevance to the keyword and the landing page it points at (ad_group_criterion.quality_info.* breaks the score into its three parts)\",\n },\n AD_GROUP_CRITERION_RARELY_SERVED: {\n label: \"Rarely served\",\n advice: \"too few people search this term — broaden the match type or drop it, don't bid it up\",\n },\n AD_GROUP_CRITERION_DISAPPROVED: {\n label: \"Disapproved\",\n advice: \"select ad_group_criterion.disapproval_reasons to see which policy blocked it\",\n },\n AD_GROUP_CRITERION_RESTRICTED: {\n label: \"Restricted\",\n advice: \"policy limits where and to whom this keyword may show\",\n },\n AD_GROUP_CRITERION_UNDER_REVIEW: {\n label: \"Under review\",\n advice: \"waiting on Google's review — nothing to change yet\",\n },\n AD_GROUP_CRITERION_PENDING_REVIEW: {\n label: \"Pending review\",\n advice: \"waiting on Google's review — nothing to change yet\",\n },\n AD_GROUP_CRITERION_PAUSED_DUE_TO_LOW_ACTIVITY: {\n label: \"Auto-paused for low activity\",\n advice: \"Google paused it after prolonged low serving — resume it only alongside a change that gives it traffic\",\n },\n};\n\nconst REASON_ORDER = Object.keys(ACTIONABLE_REASONS);\nconst MAX_NAMED_KEYWORDS = 5;\n\n// Google's REST transport serialises int64 as a JSON string, so a micros field arrives as\n// \"3630000\" from the API and as 3630000 from a hand-built fixture. Both have to read the same.\nfunction toMicros(value: unknown): number | null {\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n if (typeof value === \"string\" && value.trim() !== \"\" && Number.isFinite(Number(value))) return Number(value);\n return null;\n}\n\nfunction formatMoney(micros: number): string {\n return (micros / 1_000_000).toFixed(2);\n}\n\n// A keyword's criterion id is derived from its text + match type, so the same id and the same text\n// repeat in every ad group holding that keyword. Naming a copy without its ad group makes the\n// copies indistinguishable — and identical enough to be silently deduped out of the count.\nfunction keywordLabel(row: Record<string, unknown>): string {\n const text = row[\"ad_group_criterion.keyword.text\"];\n const id = row[\"ad_group_criterion.criterion_id\"];\n const name = typeof text === \"string\" && text !== \"\" ? text : id == null ? \"(unnamed keyword)\" : `criterion ${id}`;\n const adGroup = row[\"ad_group.name\"];\n return typeof adGroup === \"string\" && adGroup !== \"\" ? `${name} (ad group ${adGroup})` : name;\n}\n\n// What makes two rows the same keyword for counting. The ad group is half the identity, so it is\n// part of the key whenever the read selected it.\nfunction keywordKey(row: Record<string, unknown>): string {\n const adGroup = row[\"ad_group.id\"] ?? row[\"ad_group.name\"] ?? \"\";\n const criterion = row[\"ad_group_criterion.criterion_id\"] ?? row[\"ad_group_criterion.keyword.text\"] ?? \"\";\n return `${String(adGroup)}~${String(criterion)}` === \"~\" ? keywordLabel(row) : `${adGroup}~${criterion}`;\n}\n\nfunction reasonsOn(row: Record<string, unknown>): string[] | null {\n const raw = row[\"ad_group_criterion.primary_status_reasons\"];\n if (!Array.isArray(raw)) return null;\n return raw.filter((r): r is string => typeof r === \"string\");\n}\n\n// The bid gap the API states outright, for reads that selected the estimates without the status.\nfunction bidShortfall(row: Record<string, unknown>): string | null {\n const bid = toMicros(row[\"ad_group_criterion.effective_cpc_bid_micros\"] ?? row[\"ad_group_criterion.cpc_bid_micros\"]);\n const firstPage = toMicros(row[\"ad_group_criterion.position_estimates.first_page_cpc_micros\"]);\n if (bid == null || firstPage == null || bid >= firstPage) return null;\n return `bids ${formatMoney(bid)} against a ${formatMoney(firstPage)} first-page estimate`;\n}\n\n// The limits one row reports, each already phrased with the keyword it belongs to.\n//\n// Google omits primary_status_reasons entirely when a keyword has none, so an absent key means\n// two different things: \"nothing to report\" if the read selected the field, \"we never asked\" if it\n// didn't. Only the query knows which, hence statusReasonsSelected — without it, every healthy\n// keyword bidding under a stale estimate gets reported as starved.\nfunction limitsOn(\n row: Record<string, unknown>,\n options: KeywordServingOptions,\n): Array<{ reason: string; detail: string }> {\n const reasons = reasonsOn(row);\n const shortfall = bidShortfall(row);\n const label = keywordLabel(row);\n\n const applicable = reasons\n ? reasons.filter((reason) => reason in ACTIONABLE_REASONS)\n : options.statusReasonsSelected || shortfall === null\n ? []\n : [BELOW_FIRST_PAGE_BID];\n\n return applicable.map((reason) => ({\n reason,\n detail: reason === BELOW_FIRST_PAGE_BID && shortfall ? `\"${label}\" ${shortfall}` : `\"${label}\"`,\n }));\n}\n\nfunction describeLimit(reason: string, details: string[]): string {\n const named = details.slice(0, MAX_NAMED_KEYWORDS).join(\"; \");\n const rest = details.length > MAX_NAMED_KEYWORDS ? ` (+${details.length - MAX_NAMED_KEYWORDS} more)` : \"\";\n const { label, advice } = ACTIONABLE_REASONS[reason] as { label: string; advice: string };\n return `${label} — ${details.length}: ${named}${rest}. Fix: ${advice}.`;\n}\n\nexport interface KeywordServingOptions {\n /** Whether the executed query selected ad_group_criterion.primary_status_reasons. */\n statusReasonsSelected: boolean;\n}\n\n/** Limits found so far: the details to quote per reason, and which keywords they belong to. */\nexport interface KeywordLimits {\n detailsByReason: Map<string, string[]>;\n keywords: Set<string>;\n}\n\n/**\n * Fold one page of rows into the running limits. `--out` streams each page to disk and keeps no\n * rows, so the tally has to survive between pages rather than be recomputed at the end.\n */\nexport function collectKeywordLimits(\n rows: Array<Record<string, unknown>>,\n options: KeywordServingOptions,\n acc: KeywordLimits = { detailsByReason: new Map(), keywords: new Set() },\n): KeywordLimits {\n for (const row of rows) {\n const limits = limitsOn(row, options);\n if (limits.length === 0) continue;\n // Counted once per keyword, however many reasons it carries — Google reports below-first-page-\n // bid and low-quality together on the same keyword all the time.\n acc.keywords.add(keywordKey(row));\n for (const { reason, detail } of limits) {\n const bucket = acc.detailsByReason.get(reason);\n if (bucket) bucket.push(detail);\n else acc.detailsByReason.set(reason, [detail]);\n }\n }\n return acc;\n}\n\n/** Render accumulated limits as the single warning the agent reads. Empty when nothing is limited. */\nexport function renderKeywordLimits(limits: KeywordLimits): AdsWarning[] {\n if (limits.detailsByReason.size === 0) return [];\n\n const sentences = REASON_ORDER.filter((reason) => limits.detailsByReason.has(reason)).map((reason) =>\n describeLimit(reason, limits.detailsByReason.get(reason) ?? []),\n );\n const count = limits.keywords.size;\n\n return [\n {\n code: \"KEYWORD_SERVING_LIMITED\",\n message: `${count} ${count === 1 ? \"keyword is\" : \"keywords are\"} limited and not getting the traffic they could. ${sentences.join(\" \")} Amounts are in the account currency (baker ads google currency).`,\n },\n ];\n}\n\n/**\n * Turn the serving signals on a keyword read into one warning naming what is limited and what\n * fixes it. Silent when the rows carry no serving signal, or when every limit is just a paused\n * parent — a row that already says PAUSED needs no second telling.\n */\nexport function keywordServingWarnings(\n rows: Array<Record<string, unknown>>,\n options: KeywordServingOptions,\n): AdsWarning[] {\n return renderKeywordLimits(collectKeywordLimits(rows, options));\n}\n","/**\n * Google Ads reads keep money in micros (millionths of the account currency),\n * exactly as GAQL returns it, while every money flag (`--amount`, `--cpc-bid`,\n * `--target-cpa`, …) takes whole currency. An amount copied from one into the\n * other is a millionfold raise, so a read that carries a budget, bid or target\n * says so once, next to the rows.\n *\n * Only the settings a flag is set from count: cost metrics are read, not copied\n * into a write, and saying it on every performance read would teach the agent to\n * skip warnings. `*_fraction_micros` is a share, not money.\n */\n\nimport type { AdsWarning } from \"../types.ts\";\n\nfunction isSettingMicros(field: string): boolean {\n return field.endsWith(\"_micros\") && !field.startsWith(\"metrics.\") && !field.endsWith(\"_fraction_micros\");\n}\n\n/** A setting's amount as a row carried it, so the example the warning gives is one the read returned. */\nexport interface MoneyExample {\n field: string;\n micros: string;\n}\n\nexport function moneyExample(rows: ReadonlyArray<Record<string, unknown>>): MoneyExample | undefined {\n for (const row of rows) {\n for (const [field, value] of Object.entries(row)) {\n if (!isSettingMicros(field)) continue;\n if ((typeof value === \"string\" || typeof value === \"number\") && Number.isFinite(Number(value))) {\n return { field, micros: String(value) };\n }\n }\n }\n return undefined;\n}\n\nexport function moneyUnitWarnings(example: MoneyExample | undefined): AdsWarning[] {\n if (!example) return [];\n const units = Number(example.micros) / 1_000_000;\n return [\n {\n code: \"MONEY_IN_MICROS\",\n message: `Budgets and bids here are in micros (${example.field} ${example.micros} is ${units}); write flags take whole currency: --amount ${units}.`,\n },\n ];\n}\n","/**\n * A GAQL statement ordered so no two rows tie, for a read whose rows moved between pages.\n *\n * Google keeps a row order only for a unique ORDER BY, and orders only by selected, sortable fields\n * (`resource_name` is not one). So the statement's own ORDER BY is kept and the ids that name one row\n * of its resource are added last — to the SELECT too when missing, which cannot split a row, since a\n * row is already one of that resource — then every other selected id and segment, since a selected\n * segment (`segments.device`, `segments.conversion_action`) or segmenting resource (`campaign.id` on a\n * placement) splits one row of the resource into several. A segment Google will not order by leaves\n * those rows tied, and is named for the caller to drop or narrow.\n */\n\n/** The selected fields that tell one row of each resource apart, parent first. */\nconst ROW_KEYS: Readonly<Record<string, readonly string[]>> = {\n customer: [\"customer.id\"],\n campaign: [\"campaign.id\"],\n campaign_budget: [\"campaign_budget.id\"],\n campaign_criterion: [\"campaign.id\", \"campaign_criterion.criterion_id\"],\n ad_group: [\"ad_group.id\"],\n ad_group_ad: [\"ad_group.id\", \"ad_group_ad.ad.id\"],\n ad_group_criterion: [\"ad_group.id\", \"ad_group_criterion.criterion_id\"],\n keyword_view: [\"ad_group.id\", \"ad_group_criterion.criterion_id\"],\n search_term_view: [\"ad_group.id\", \"search_term_view.search_term\"],\n asset: [\"asset.id\"],\n asset_group: [\"asset_group.id\"],\n detail_placement_view: [\"ad_group.id\", \"detail_placement_view.placement\"],\n performance_max_placement_view: [\"performance_max_placement_view.placement\"],\n landing_page_view: [\"landing_page_view.unexpanded_final_url\"],\n campaign_asset: [\"campaign.id\", \"asset.id\", \"campaign_asset.field_type\"],\n asset_group_asset: [\"asset_group.id\", \"asset.id\", \"asset_group_asset.field_type\"],\n shared_criterion: [\"shared_set.id\", \"shared_criterion.criterion_id\"],\n campaign_shared_set: [\"campaign.id\", \"shared_set.id\"],\n};\n\n/** The segments GoogleAdsFieldService marks `sortable = false` (v21): selectable, never in an ORDER BY. */\nconst UNSORTABLE_SEGMENTS: ReadonlySet<string> = new Set([\n \"segments.ad_group\",\n \"segments.asset_group\",\n \"segments.campaign\",\n \"segments.experiment_arm\",\n \"segments.keyword.ad_group_criterion\",\n \"segments.search_subcategory\",\n \"segments.search_term\",\n \"segments.webpage\",\n]);\n\n/** A statement ordered as far as Google allows, and the selected segments that still leave rows tied. */\nexport interface StableOrder {\n query: string;\n /** Selected segments that split rows but cannot be ordered by: the order is unique only without them. */\n unorderable: string[];\n}\n\n/** The statement with every quoted value blanked to the same length, so clause offsets stay true. */\nexport function masked(gaql: string): string {\n return gaql.replace(/'(?:[^'\\\\]|\\\\.)*'|\"(?:[^\"\\\\]|\\\\.)*\"/g, (quoted) => \" \".repeat(quoted.length));\n}\n\nfunction listOf(clause: string): string[] {\n return clause\n .split(\",\")\n .map((term) => term.trim().split(/\\s+/)[0]?.toLowerCase() ?? \"\")\n .filter(Boolean);\n}\n\n/** The ids that name one row of the statement's resource — the ones a steady order adds to its SELECT. */\nexport function rowKeysOf(gaql: string): readonly string[] {\n const from = /\\bFROM\\s+([a-z_]+)/i.exec(masked(gaql));\n return ROW_KEYS[from?.[1]?.toLowerCase() ?? \"\"] ?? [];\n}\n\n/** The statement with its ORDER BY made unique as far as Google allows; unchanged when it already is, or holds nothing to add. */\nexport function stableOrderQuery(gaql: string): StableOrder {\n const plain = masked(gaql);\n const from = /\\bFROM\\s+([a-z_]+)/i.exec(plain);\n if (!from) return { query: gaql, unorderable: [] };\n const keys = ROW_KEYS[from[1]?.toLowerCase() ?? \"\"] ?? [];\n\n const selected = listOf(plain.slice(/\\bSELECT\\b/i.exec(plain)?.index ?? 0, from.index).replace(/^\\s*SELECT\\b/i, \"\"));\n const tail = /\\b(?:LIMIT|PARAMETERS)\\b/i.exec(plain);\n const end = tail ? tail.index : gaql.length;\n const orderBy = /\\bORDER\\s+BY\\b/i.exec(plain);\n const ordered = orderBy ? listOf(plain.slice(orderBy.index + orderBy[0].length, end)) : [];\n\n const ids = selected.filter((field) => /^[a-z_]+\\.id$/.test(field));\n const segments = selected.filter((field) => field.startsWith(\"segments.\"));\n const unorderable = segments.filter((field) => UNSORTABLE_SEGMENTS.has(field));\n const sortable = segments.filter((field) => !UNSORTABLE_SEGMENTS.has(field));\n const wanted = [...new Set([...keys, ...ids, ...sortable])];\n const missing = wanted.filter((field) => !ordered.includes(field));\n if (missing.length === 0) return { query: gaql, unorderable };\n\n const unselected = keys.filter((field) => !selected.includes(field));\n const head = gaql.slice(0, from.index).trimEnd();\n const select = unselected.length > 0 ? `${head}, ${unselected.join(\", \")} ` : gaql.slice(0, from.index);\n const body = gaql.slice(from.index, end).trimEnd();\n const order = orderBy ? `${body}, ${missing.join(\", \")}` : `${body} ORDER BY ${missing.join(\", \")}`;\n const rest = gaql.slice(end).trim();\n return { query: `${select}${order}${rest ? ` ${rest}` : \"\"}`, unorderable };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB,YAAY,cAAc,YAAY,QAAQ,qBAAqB;AAC5F,SAAS,eAAe;AAYxB,SAAS,qBAAqB;AAC9B,SAAS,SAAS,gBAAgB;AAClC,SAAS,SAAS,kBAAkB;;;ACTpC,SAAS,aAAa,OAAe,YAA4B;AAC/D,SAAO,2BAA2B,KAAK,mBAAmB,UAAU;AACtE;AAIA,IAAM,kBAA4C;AAAA,EAChD,mBAAmB,CAAC,eAAe,wBAAwB;AAAA,EAC3D,mBAAmB,CAAC,eAAe,wBAAwB;AAAA,EAC3D,6BAA6B,CAAC,mCAAmC,kCAAkC;AAAA,EACnG,sBAAsB,CAAC,qBAAqB,2BAA2B;AAAA,EACvE,sBAAsB,CAAC,kBAAkB,2BAA2B;AAAA,EACpE,4BAA4B,CAAC,iCAAiC;AAAA,EAC9D,yBAAyB,CAAC,8BAA8B;AAAA,EACxD,yBAAyB,CAAC,8BAA8B;AAC1D;AAMO,SAAS,kBAAkB,OAAuB;AACvD,SAAO,MAAM;AAAA,IACX;AAAA,IACA,CAAC,UAAU,GAAG,MAAM,CAAC,CAAC,GAAG,IAAI,OAAO,MAAM,SAAS,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC;AAAA,EAClE;AACF;AAIA,SAAS,YAAY,OAAuB;AAC1C,QAAM,UAAU,kBAAkB,KAAK;AACvC,QAAM,QAAQ,QAAQ,MAAM,sBAAsB;AAClD,MAAI,OAAO,UAAU,UAAa,CAAC,MAAM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