@shware/analytics 16.5.0 → 16.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_virtual/_rolldown/runtime.cjs +0 -2
- package/dist/ads/google.d.cts +13 -0
- package/dist/ads/google.d.cts.map +1 -1
- package/dist/ads/google.d.mts +13 -0
- package/dist/ads/google.d.mts.map +1 -1
- package/dist/ads/index.cjs +1 -1
- package/dist/ads/index.d.cts +1 -1
- package/dist/ads/index.d.mts +1 -1
- package/dist/ads/index.mjs +1 -1
- package/dist/ads/meta.cjs.map +1 -1
- package/dist/ads/meta.mjs.map +1 -1
- package/dist/ads/types.d.cts +1 -0
- package/dist/ads/types.d.cts.map +1 -1
- package/dist/attribution/index.cjs +1 -1
- package/dist/attribution/index.d.cts +1 -1
- package/dist/attribution/index.d.mts +1 -1
- package/dist/attribution/index.mjs +1 -1
- package/dist/click-id/index.cjs.map +1 -1
- package/dist/hooks/use-app-analytics.cjs +1 -1
- package/dist/hooks/use-app-analytics.cjs.map +1 -1
- package/dist/hooks/use-app-analytics.mjs +1 -1
- package/dist/hooks/use-outbound-click-analytics.cjs.map +1 -1
- package/dist/hooks/use-report-web-vitals.cjs.map +1 -1
- package/dist/hooks/use-track-impression.cjs.map +1 -1
- package/dist/hooks/use-uet-id-sync.cjs.map +1 -1
- package/dist/hooks/use-uet-id-sync.mjs.map +1 -1
- package/dist/hooks/use-web-analytics.cjs +2 -2
- package/dist/hooks/use-web-analytics.cjs.map +1 -1
- package/dist/hooks/use-web-analytics.mjs +2 -2
- package/dist/index.d.cts +7 -7
- package/dist/index.d.mts +7 -7
- package/dist/link/index.cjs.map +1 -1
- package/dist/link/index.d.cts +12 -1
- package/dist/link/index.d.cts.map +1 -1
- package/dist/link/index.d.mts +12 -1
- package/dist/link/index.d.mts.map +1 -1
- package/dist/link/index.mjs.map +1 -1
- package/dist/native/deep-link.cjs.map +1 -1
- package/dist/native/fbsdk.cjs +1 -1
- package/dist/native/fbsdk.cjs.map +1 -1
- package/dist/native/fbsdk.d.cts +1 -1
- package/dist/native/fbsdk.d.mts +1 -1
- package/dist/native/fbsdk.mjs +1 -1
- package/dist/native/firebase.cjs.map +1 -1
- package/dist/native/firebase.d.cts +1 -1
- package/dist/native/firebase.d.mts +1 -1
- package/dist/native/index.cjs +2 -2
- package/dist/native/index.d.cts +2 -2
- package/dist/native/index.d.mts +2 -2
- package/dist/native/index.mjs +2 -2
- package/dist/native/setup.cjs +1 -1
- package/dist/native/setup.cjs.map +1 -1
- package/dist/native/setup.d.cts +1 -2
- package/dist/native/setup.d.cts.map +1 -1
- package/dist/native/setup.d.mts +1 -1
- package/dist/native/setup.mjs +1 -1
- package/dist/next/index.cjs +2 -2
- package/dist/next/index.cjs.map +1 -1
- package/dist/next/index.mjs +2 -2
- package/dist/node_modules/.pnpm/bowser@2.15.0/node_modules/bowser/bowser.cjs +2157 -0
- package/dist/node_modules/.pnpm/bowser@2.15.0/node_modules/bowser/bowser.cjs.map +1 -0
- package/dist/node_modules/.pnpm/bowser@2.15.0/node_modules/bowser/bowser.mjs +2152 -0
- package/dist/node_modules/.pnpm/bowser@2.15.0/node_modules/bowser/bowser.mjs.map +1 -0
- package/dist/react/index.cjs +2 -2
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.mjs +2 -2
- package/dist/react/posthog-error-boundary.cjs.map +1 -1
- package/dist/react/posthog-error-boundary.mjs.map +1 -1
- package/dist/server/conversions-api-error.cjs.map +1 -1
- package/dist/server/conversions-api-error.mjs.map +1 -1
- package/dist/server/index.cjs +4 -4
- package/dist/server/index.d.cts +6 -6
- package/dist/server/index.d.mts +6 -6
- package/dist/server/index.mjs +4 -4
- package/dist/server/linkedin-conversions-api.d.cts +1 -1
- package/dist/server/linkedin-conversions-api.d.mts +1 -1
- package/dist/server/meta-capi.cjs +1 -1
- package/dist/server/meta-capi.d.cts +1 -1
- package/dist/server/meta-capi.d.mts +1 -1
- package/dist/server/meta-capi.mjs +1 -1
- package/dist/server/microsoft-conversions-api.cjs +3 -3
- package/dist/server/microsoft-conversions-api.d.cts +1 -1
- package/dist/server/microsoft-conversions-api.d.mts +1 -1
- package/dist/server/microsoft-conversions-api.mjs +3 -3
- package/dist/server/openai-conversions-api.cjs +2 -2
- package/dist/server/openai-conversions-api.d.cts +2 -2
- package/dist/server/openai-conversions-api.d.mts +2 -2
- package/dist/server/openai-conversions-api.mjs +2 -2
- package/dist/server/reddit-conversions-api.cjs +3 -3
- package/dist/server/reddit-conversions-api.d.cts +2 -2
- package/dist/server/reddit-conversions-api.d.mts +2 -2
- package/dist/server/reddit-conversions-api.mjs +3 -3
- package/dist/setup/index.d.cts +1 -1
- package/dist/setup/index.d.mts +1 -1
- package/dist/setup/session.cjs +1 -1
- package/dist/setup/session.cjs.map +1 -1
- package/dist/setup/session.mjs +1 -1
- package/dist/test/setup.cjs +1 -1
- package/dist/test/setup.cjs.map +1 -1
- package/dist/test/setup.mjs +1 -1
- package/dist/test/setup.mjs.map +1 -1
- package/dist/third-parties/google-analytics.d.cts +1 -1
- package/dist/third-parties/google-analytics.d.mts +1 -1
- package/dist/third-parties/index.cjs +3 -3
- package/dist/third-parties/index.d.cts +5 -5
- package/dist/third-parties/index.d.mts +5 -5
- package/dist/third-parties/index.mjs +3 -3
- package/dist/third-parties/linkedin-insight-tag.d.cts +2 -2
- package/dist/third-parties/linkedin-insight-tag.d.mts +2 -2
- package/dist/third-parties/meta-pixel.cjs +1 -1
- package/dist/third-parties/meta-pixel.d.cts +2 -2
- package/dist/third-parties/meta-pixel.d.mts +2 -2
- package/dist/third-parties/meta-pixel.mjs +1 -1
- package/dist/third-parties/microsoft-uet.cjs +1 -1
- package/dist/third-parties/microsoft-uet.cjs.map +1 -1
- package/dist/third-parties/microsoft-uet.d.cts +2 -2
- package/dist/third-parties/microsoft-uet.d.mts +2 -2
- package/dist/third-parties/microsoft-uet.mjs +1 -1
- package/dist/third-parties/microsoft-uet.mjs.map +1 -1
- package/dist/third-parties/openai-pixel.cjs +1 -1
- package/dist/third-parties/openai-pixel.d.cts +2 -2
- package/dist/third-parties/openai-pixel.d.mts +2 -2
- package/dist/third-parties/openai-pixel.mjs +1 -1
- package/dist/third-parties/posthog.d.cts +1 -1
- package/dist/third-parties/posthog.d.mts +1 -1
- package/dist/third-parties/reddit-pixel.cjs +1 -1
- package/dist/third-parties/reddit-pixel.d.cts +2 -2
- package/dist/third-parties/reddit-pixel.d.mts +2 -2
- package/dist/third-parties/reddit-pixel.mjs +1 -1
- package/dist/track/index.cjs.map +1 -1
- package/dist/track/index.mjs.map +1 -1
- package/dist/track/once.cjs.map +1 -1
- package/dist/track/once.d.cts +1 -1
- package/dist/track/once.d.mts +1 -1
- package/dist/visitor/id.cjs +1 -1
- package/dist/visitor/id.cjs.map +1 -1
- package/dist/visitor/id.mjs +1 -1
- package/dist/visitor/index.cjs +2 -2
- package/dist/visitor/index.cjs.map +1 -1
- package/dist/visitor/index.mjs +2 -2
- package/dist/web/index.cjs +3 -5
- package/dist/web/index.cjs.map +1 -1
- package/dist/web/index.d.cts +1 -1
- package/dist/web/index.d.mts +1 -1
- package/dist/web/index.mjs +3 -5
- package/dist/web/index.mjs.map +1 -1
- package/package.json +11 -11
- package/dist/_virtual/_rolldown/runtime.mjs +0 -23
- package/dist/node_modules/.pnpm/bowser@2.14.1/node_modules/bowser/es5.cjs +0 -1724
- package/dist/node_modules/.pnpm/bowser@2.14.1/node_modules/bowser/es5.cjs.map +0 -1
- package/dist/node_modules/.pnpm/bowser@2.14.1/node_modules/bowser/es5.mjs +0 -1721
- package/dist/node_modules/.pnpm/bowser@2.14.1/node_modules/bowser/es5.mjs.map +0 -1
|
@@ -5,7 +5,6 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
|
5
5
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
6
|
var __getProtoOf = Object.getPrototypeOf;
|
|
7
7
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
-
var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod, mod.exports), cb = null), mod.exports);
|
|
9
8
|
var __copyProps = (to, from, except, desc) => {
|
|
10
9
|
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
11
10
|
key = keys[i];
|
|
@@ -20,5 +19,4 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
20
19
|
value: mod,
|
|
21
20
|
enumerable: true
|
|
22
21
|
}) : target, mod));
|
|
23
|
-
exports.__commonJSMin = __commonJSMin;
|
|
24
22
|
exports.__toESM = __toESM;
|
package/dist/ads/google.d.cts
CHANGED
|
@@ -1,3 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Google Ads delivery pushed by a Google Ads script: the script runs inside the ad account on
|
|
3
|
+
* Google's schedule, reads the hourly report with `AdsApp.search` and posts it to the host, which
|
|
4
|
+
* turns it into `AdPerformanceRow`s here. No developer token, manager account or OAuth client is
|
|
5
|
+
* needed — the script runs as the account's own user. The script is in the README.
|
|
6
|
+
*
|
|
7
|
+
* Google reports hours down to the ad group, not the ad (`segments.hour` is incompatible with
|
|
8
|
+
* `ad_group_ad`), and Performance Max campaigns have no ad groups at all; so a row is an ad group's
|
|
9
|
+
* hour, or a Performance Max campaign's, and `ad_id` holds that ad group or campaign id.
|
|
10
|
+
*
|
|
11
|
+
* https://developers.google.com/google-ads/scripts/docs/features/reports
|
|
12
|
+
* https://developers.google.com/google-ads/api/fields/v21/ad_group
|
|
13
|
+
*/
|
|
1
14
|
import { AdPerformanceRow } from "./types.cjs";
|
|
2
15
|
import { infer as __Infer } from "zod/mini";
|
|
3
16
|
declare const reportSchema: import("zod/mini").ZodMiniObject<{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"google.d.cts","names":["Infer"],"sources":["../../src/ads/google.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"google.d.cts","names":["Infer"],"sources":["../../src/ads/google.ts"],"mappings":";;;;;;;;;;;;;;;cAoDM,iCAAY;;;;;;;;;;;;;;;;;yBAOhB;;YAGU,wBAAwBA,eAAa;;qBAGpC,6BAA6B;EACxC,YAAY;;;;;;;;;;;;;;;wBA0CE,2BAA2B,gBAAgB"}
|
package/dist/ads/google.d.mts
CHANGED
|
@@ -1,3 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Google Ads delivery pushed by a Google Ads script: the script runs inside the ad account on
|
|
3
|
+
* Google's schedule, reads the hourly report with `AdsApp.search` and posts it to the host, which
|
|
4
|
+
* turns it into `AdPerformanceRow`s here. No developer token, manager account or OAuth client is
|
|
5
|
+
* needed — the script runs as the account's own user. The script is in the README.
|
|
6
|
+
*
|
|
7
|
+
* Google reports hours down to the ad group, not the ad (`segments.hour` is incompatible with
|
|
8
|
+
* `ad_group_ad`), and Performance Max campaigns have no ad groups at all; so a row is an ad group's
|
|
9
|
+
* hour, or a Performance Max campaign's, and `ad_id` holds that ad group or campaign id.
|
|
10
|
+
*
|
|
11
|
+
* https://developers.google.com/google-ads/scripts/docs/features/reports
|
|
12
|
+
* https://developers.google.com/google-ads/api/fields/v21/ad_group
|
|
13
|
+
*/
|
|
1
14
|
import { AdPerformanceRow } from "./types.mjs";
|
|
2
15
|
import { infer as __Infer } from "zod/mini";
|
|
3
16
|
declare const reportSchema: import("zod/mini").ZodMiniObject<{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"google.d.mts","names":["Infer"],"sources":["../../src/ads/google.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"google.d.mts","names":["Infer"],"sources":["../../src/ads/google.ts"],"mappings":";;;;;;;;;;;;;;;cAoDM,iCAAY;;;;;;;;;;;;;;;;;yBAOhB;;YAGU,wBAAwBA,eAAa;;qBAGpC,6BAA6B;EACxC,YAAY;;;;;;;;;;;;;;;wBA0CE,2BAA2B,gBAAgB"}
|
package/dist/ads/index.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_ads_time = require("./time.cjs");
|
|
3
2
|
const require_ads_google = require("./google.cjs");
|
|
4
3
|
const require_ads_meta = require("./meta.cjs");
|
|
4
|
+
const require_ads_time = require("./time.cjs");
|
|
5
5
|
exports.GoogleAdsReportError = require_ads_google.GoogleAdsReportError;
|
|
6
6
|
exports.MetaAdsApiError = require_ads_meta.MetaAdsApiError;
|
|
7
7
|
exports.addDays = require_ads_time.addDays;
|
package/dist/ads/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { AdPerformanceRow, AdPlatform, ReportDate } from "./types.cjs";
|
|
2
1
|
import { GoogleAdsReportError, GoogleAdsScriptReport, parseGoogleAdsScriptReport } from "./google.cjs";
|
|
3
2
|
import { MetaAdPerformanceOptions, MetaAdsApiError, fetchMetaAdPerformance, fetchMetaAdPerformanceHistory, spread } from "./meta.cjs";
|
|
4
3
|
import { addDays, addMonths, todayIn, zonedHourToUtc } from "./time.cjs";
|
|
4
|
+
import { AdPerformanceRow, AdPlatform, ReportDate } from "./types.cjs";
|
|
5
5
|
export { type AdPerformanceRow, type AdPlatform, GoogleAdsReportError, GoogleAdsScriptReport, MetaAdPerformanceOptions, MetaAdsApiError, type ReportDate, addDays, addMonths, fetchMetaAdPerformance, fetchMetaAdPerformanceHistory, parseGoogleAdsScriptReport, spread, todayIn, zonedHourToUtc };
|
package/dist/ads/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { AdPerformanceRow, AdPlatform, ReportDate } from "./types.mjs";
|
|
2
1
|
import { GoogleAdsReportError, GoogleAdsScriptReport, parseGoogleAdsScriptReport } from "./google.mjs";
|
|
3
2
|
import { MetaAdPerformanceOptions, MetaAdsApiError, fetchMetaAdPerformance, fetchMetaAdPerformanceHistory, spread } from "./meta.mjs";
|
|
4
3
|
import { addDays, addMonths, todayIn, zonedHourToUtc } from "./time.mjs";
|
|
4
|
+
import { AdPerformanceRow, AdPlatform, ReportDate } from "./types.mjs";
|
|
5
5
|
export { type AdPerformanceRow, type AdPlatform, GoogleAdsReportError, GoogleAdsScriptReport, MetaAdPerformanceOptions, MetaAdsApiError, type ReportDate, addDays, addMonths, fetchMetaAdPerformance, fetchMetaAdPerformanceHistory, parseGoogleAdsScriptReport, spread, todayIn, zonedHourToUtc };
|
package/dist/ads/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { addDays, addMonths, todayIn, zonedHourToUtc } from "./time.mjs";
|
|
2
1
|
import { GoogleAdsReportError, parseGoogleAdsScriptReport } from "./google.mjs";
|
|
3
2
|
import { MetaAdsApiError, fetchMetaAdPerformance, fetchMetaAdPerformanceHistory, spread } from "./meta.mjs";
|
|
3
|
+
import { addDays, addMonths, todayIn, zonedHourToUtc } from "./time.mjs";
|
|
4
4
|
export { GoogleAdsReportError, MetaAdsApiError, addDays, addMonths, fetchMetaAdPerformance, fetchMetaAdPerformanceHistory, parseGoogleAdsScriptReport, spread, todayIn, zonedHourToUtc };
|
package/dist/ads/meta.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"meta.cjs","names":["object","string","optional","array","number","createHmac","fetch","safeParse","channelGroupOf","zonedHourToUtc","addDays","addMonths","todayIn"],"sources":["../../src/ads/meta.ts"],"sourcesContent":["/**\n * Meta ad delivery through the Marketing API's Insights endpoint, over plain `fetch`: one row per\n * ad and hour, in the attribution vocabulary (see `AdPerformanceRow`).\n *\n * The token needs `ads_read` on the ad account — a system user token with the account assigned\n * at \"View performance\". It is sent in the `Authorization` header and never put in a URL: paging\n * follows the `after` cursor rather than Meta's `paging.next`, which embeds the token.\n *\n * https://developers.facebook.com/docs/marketing-api/insights\n * https://developers.facebook.com/docs/marketing-api/insights/breakdowns\n */\nimport { createHmac } from 'node:crypto';\nimport { fetch } from '@shware/utils';\nimport {\n type infer as Infer,\n type ZodMiniType,\n array,\n number,\n object,\n optional,\n safeParse,\n string,\n} from 'zod/mini';\nimport { channelGroupOf } from '../attribution';\nimport { addDays, addMonths, todayIn, zonedHourToUtc } from './time';\nimport type { AdPerformanceRow, ReportDate } from './types';\n\n/** Same Graph API version as the Conversions API sender. */\nconst API_VERSION = 'v24.0';\nconst GRAPH = `https://graph.facebook.com/${API_VERSION}`;\n\n/** What an ad click is in the attribution vocabulary: `meta / cpc`, a paid social touch. */\nconst CHANNEL = 'meta';\nconst MEDIUM = 'cpc';\n\n/**\n * The click window of the click-through columns. Meta's longest since 2021, and the click part of\n * its default setting (7-day click, 1-day view).\n */\nconst CLICK_WINDOW = '7d_click';\nconst VIEW_WINDOW = '1d_view';\n\nconst HOURLY = 'hourly_stats_aggregated_by_advertiser_time_zone';\n\n/**\n * How far back Meta answers the hourly breakdown, in months. Past it Meta does not fail — it\n * returns no rows — so a backfill would silently store a gap.\n * https://developers.facebook.com/docs/marketing-api/insights/best-practices\n */\nconst HOURLY_RETENTION_MONTHS = 13;\n\n/** How far back Meta answers Insights without the hourly breakdown, in months. */\nconst DAILY_RETENTION_MONTHS = 37;\n\n/**\n * Days per Insights request. A synchronous request over a long range of ad rows times out on\n * Meta's side (`code 1, subcode 99`, \"An unknown error occurred\", as a 500): 17 months of daily\n * ad rows did. A range is split into windows this long, each paged on its own.\n */\nconst CHUNK_DAYS = 7;\n\n/** Days per request for daily rows: 24 times fewer rows than hourly ones per day. */\nconst DAILY_CHUNK_DAYS = 30;\n\n/** Decimal places of a day's numbers spread over its hours. */\nconst SPREAD_SCALE = 1e6;\n\nconst FIELDS = [\n 'ad_id',\n 'ad_name',\n 'adset_id',\n 'adset_name',\n 'campaign_id',\n 'campaign_name',\n 'spend',\n 'impressions',\n 'inline_link_clicks',\n 'actions',\n 'action_values',\n];\n\nexport interface MetaAdPerformanceOptions {\n /** A token with `ads_read` on the account. */\n accessToken: string;\n /** The ad account id, with or without its `act_` prefix. */\n accountId: string;\n /** First day, in the ad account's time zone. */\n since: ReportDate;\n /** Last day, inclusive, in the ad account's time zone. */\n until: ReportDate;\n /**\n * The `action_type` counted as the conversion, default `purchase` (Meta's total of the pixel,\n * Conversions API and in-app purchases of an event, deduplicated).\n */\n conversionActionType?: string;\n /**\n * The app secret, when the app requires `appsecret_proof` (App settings → Advanced → \"Require\n * app secret\"). The proof is computed here; the secret itself is never sent.\n */\n appSecret?: string;\n}\n\n/** A Graph API error, with Meta's code, for a caller deciding whether to retry. */\nexport class MetaAdsApiError extends Error {\n constructor(\n message: string,\n readonly status: number,\n readonly code: number | undefined,\n readonly subcode: number | undefined,\n readonly fbtraceId: string | undefined\n ) {\n super(message);\n this.name = 'MetaAdsApiError';\n }\n}\n\nconst actionSchema = object({\n action_type: string(),\n /**\n * The count under the ad's own attribution setting. Absent when the setting does not count any\n * of it — a view-only conversion of an ad set to 1-day click — which only shows in the windows.\n */\n value: optional(string()),\n [CLICK_WINDOW]: optional(string()),\n [VIEW_WINDOW]: optional(string()),\n});\n\nconst insightSchema = object({\n ad_id: string(),\n ad_name: optional(string()),\n adset_id: optional(string()),\n adset_name: optional(string()),\n campaign_id: string(),\n campaign_name: optional(string()),\n spend: optional(string()),\n impressions: optional(string()),\n inline_link_clicks: optional(string()),\n actions: optional(array(actionSchema)),\n action_values: optional(array(actionSchema)),\n date_start: string(),\n [HOURLY]: optional(string()),\n});\n\nconst pageSchema = object({\n data: array(insightSchema),\n paging: optional(\n object({ cursors: optional(object({ after: optional(string()) })), next: optional(string()) })\n ),\n});\n\nconst accountSchema = object({ currency: string(), timezone_name: string() });\n\nconst errorSchema = object({\n error: object({\n message: string(),\n code: optional(number()),\n error_subcode: optional(number()),\n fbtrace_id: optional(string()),\n }),\n});\n\ntype Insight = Infer<typeof insightSchema>;\ntype Action = Infer<typeof actionSchema>;\n\nasync function graphGet<T>(\n path: string,\n params: Record<string, string>,\n options: MetaAdPerformanceOptions,\n parse: (body: unknown) => T\n): Promise<T> {\n const query = new URLSearchParams(params);\n if (options.appSecret) {\n query.set(\n 'appsecret_proof',\n createHmac('sha256', options.appSecret).update(options.accessToken).digest('hex')\n );\n }\n const response = await fetch(`${GRAPH}/${path}?${query}`, {\n headers: { authorization: `Bearer ${options.accessToken}` },\n });\n const body: unknown = await response.json().catch(() => null);\n if (!response.ok) {\n const parsed = safeParse(errorSchema, body);\n const error = parsed.success ? parsed.data.error : undefined;\n throw new MetaAdsApiError(\n error?.message ?? `Meta Graph API responded ${response.status}`,\n response.status,\n error?.code,\n error?.error_subcode,\n error?.fbtrace_id\n );\n }\n return parse(body);\n}\n\nfunction parseWith<T>(schema: ZodMiniType<T>, what: string) {\n return (body: unknown): T => {\n const parsed = safeParse(schema, body);\n if (!parsed.success) {\n const issues = parsed.error.issues;\n const first = issues\n .slice(0, 3)\n .map((issue) => `${issue.path.join('.')}: ${issue.message}`)\n .join('; ');\n throw new Error(\n `Unexpected Meta ${what} response (${issues.length} issues): ${first}${issues.length > 3 ? '; …' : ''}`\n );\n }\n return parsed.data;\n };\n}\n\nfunction count(value: string | undefined): number {\n return value === undefined ? 0 : Number(value);\n}\n\n/** The action's total and its click-through part; nulls when Meta reported no such action. */\nfunction conversion(actions: Action[] | undefined, actionType: string) {\n const action = actions?.find((a) => a.action_type === actionType);\n if (!action) return { total: null, click: null };\n return { total: Number(action.value ?? 0), click: Number(action[CLICK_WINDOW] ?? 0) };\n}\n\n/** `\"13:00:00 - 13:59:59\"` → 13. */\nfunction hourOf(bucket: string | undefined): number {\n const hour = Number(bucket?.slice(0, 2));\n if (!Number.isInteger(hour) || hour < 0 || hour > 23) {\n throw new Error(`Unexpected Meta hourly bucket: ${bucket}`);\n }\n return hour;\n}\n\n/** A row for one hour: what Meta reports of an ad, its numbers as given. */\nfunction toRow(\n insight: Insight,\n hourStart: Date,\n accountId: string,\n currency: string,\n actionType: string\n): AdPerformanceRow {\n const conversions = conversion(insight.actions, actionType);\n const values = conversion(insight.action_values, actionType);\n return {\n platform: 'meta',\n account_id: accountId,\n campaign_id: insight.campaign_id,\n campaign_name: insight.campaign_name ?? null,\n ad_group_id: insight.adset_id ?? null,\n ad_group_name: insight.adset_name ?? null,\n ad_id: insight.ad_id,\n ad_name: insight.ad_name ?? null,\n channel: CHANNEL,\n medium: MEDIUM,\n channel_group: channelGroupOf(CHANNEL, MEDIUM),\n hour_start: hourStart.toISOString(),\n currency,\n spend: Number(insight.spend ?? 0),\n impressions: count(insight.impressions),\n clicks: count(insight.inline_link_clicks),\n conversions: conversions.total,\n conversion_value: values.total,\n click_conversions: conversions.click,\n click_conversion_value: values.click,\n };\n}\n\n/**\n * `value` in `parts` equal shares rounded to `SPREAD_SCALE`, the rounding left in the last share\n * so that the shares add back to `value` exactly as Meta reported it.\n */\nexport function spread(value: number, parts: number): number[] {\n const share = Math.round((value / parts) * SPREAD_SCALE) / SPREAD_SCALE;\n const last = Math.round((value - share * (parts - 1)) * SPREAD_SCALE) / SPREAD_SCALE;\n return [...Array.from({ length: parts - 1 }, () => share), last];\n}\n\n/**\n * A day row as one row per hour of the account's calendar day — 24, or 23 / 25 across a\n * daylight-saving change — each number spread evenly (nulls stay null).\n */\nfunction spreadDay(day: AdPerformanceRow, date: string, timeZone: string): AdPerformanceRow[] {\n const start = zonedHourToUtc(date, 0, timeZone).getTime();\n const end = zonedHourToUtc(addDays(date, 1), 0, timeZone).getTime();\n const hours = Math.round((end - start) / 3_600_000);\n const shares = (value: number | null) => (value === null ? null : spread(value, hours));\n const spend = spread(day.spend, hours);\n const impressions = spread(day.impressions, hours);\n const clicks = spread(day.clicks, hours);\n const conversions = shares(day.conversions);\n const conversionValue = shares(day.conversion_value);\n const clickConversions = shares(day.click_conversions);\n const clickConversionValue = shares(day.click_conversion_value);\n return Array.from({ length: hours }, (_, hour) => ({\n ...day,\n hour_start: new Date(start + hour * 3_600_000).toISOString(),\n spend: spend[hour],\n impressions: impressions[hour],\n clicks: clicks[hour],\n conversions: conversions?.[hour] ?? null,\n conversion_value: conversionValue?.[hour] ?? null,\n click_conversions: clickConversions?.[hour] ?? null,\n click_conversion_value: clickConversionValue?.[hour] ?? null,\n }));\n}\n\ninterface Account {\n id: string;\n currency: string;\n timezone_name: string;\n}\n\nasync function accountOf(options: MetaAdPerformanceOptions): Promise<Account> {\n const id = options.accountId.replace(/^act_/, '');\n const account = await graphGet(\n `act_${id}`,\n { fields: 'currency,timezone_name' },\n options,\n parseWith(accountSchema, 'ad account')\n );\n return { id, ...account };\n}\n\n/** Every ad row of the account between `since` and `until`, one request per window of `chunkDays`. */\nasync function insights(\n options: MetaAdPerformanceOptions,\n accountId: string,\n since: string,\n until: string,\n { chunkDays, hourly }: { chunkDays: number; hourly: boolean }\n): Promise<Insight[]> {\n const rows: Insight[] = [];\n for (let from = since; from <= until; from = addDays(from, chunkDays)) {\n const last = addDays(from, chunkDays - 1);\n const to = last < until ? last : until;\n let after: string | undefined;\n do {\n const params: Record<string, string> = {\n level: 'ad',\n fields: FIELDS.join(','),\n time_range: JSON.stringify({ since: from, until: to }),\n // One row per day. Without it the hourly breakdown folds the whole range into 24\n // hour-of-day buckets, all dated `since`, and a daily request returns the range's total.\n time_increment: '1',\n action_attribution_windows: JSON.stringify([CLICK_WINDOW, VIEW_WINDOW]),\n use_unified_attribution_setting: 'true',\n limit: '500',\n };\n if (hourly) params.breakdowns = HOURLY;\n if (after) params.after = after;\n const page = await graphGet(\n `act_${accountId}/insights`,\n params,\n options,\n parseWith(pageSchema, 'insights')\n );\n rows.push(...page.data);\n // `next` is absent on the last page; the cursor alone is not a signal, Meta returns it there too.\n after = page.paging?.next ? page.paging.cursors?.after : undefined;\n } while (after);\n }\n return rows;\n}\n\n/**\n * Hourly delivery of every ad of the account that ran between `since` and `until` — deleted and\n * archived ads included — one row per ad and hour (hours without delivery are absent). The hours\n * are Meta's, in the account's time zone, turned into UTC instants. Conversions are those of each\n * ad's attribution setting (`use_unified_attribution_setting`), their click-through part from the\n * 7-day click window.\n *\n * Meta restates past hours as late conversions arrive — a purchase is credited to the hour of the\n * click, up to 7 days after it — and corrects spend for invalid traffic: re-fetch the last 8 days\n * daily (the 7-day window plus a day of time zone slack) and upsert on (`platform`, `account_id`,\n * `ad_id`, `hour_start`).\n *\n * @throws RangeError when `since` is more than 13 months back, where Meta keeps no hourly\n * breakdown and would answer with no rows rather than an error.\n */\nexport async function fetchMetaAdPerformance(\n options: MetaAdPerformanceOptions\n): Promise<AdPerformanceRow[]> {\n const actionType = options.conversionActionType ?? 'purchase';\n const account = await accountOf(options);\n\n // Normalized, so `2025-9-8` compares as `2025-09-08`.\n const since = addDays(options.since, 0);\n const until = addDays(options.until, 0);\n const earliest = addMonths(todayIn(account.timezone_name), -HOURLY_RETENTION_MONTHS);\n if (since < earliest) {\n throw new RangeError(\n `Meta keeps hourly insights for ${HOURLY_RETENTION_MONTHS} months: since ${since} is before ${earliest}`\n );\n }\n\n const rows = await insights(options, account.id, since, until, {\n chunkDays: CHUNK_DAYS,\n hourly: true,\n });\n return rows.map((insight) =>\n toRow(\n insight,\n zonedHourToUtc(insight.date_start, hourOf(insight[HOURLY]), account.timezone_name),\n account.id,\n account.currency,\n actionType\n )\n );\n}\n\n/**\n * The delivery older than Meta's 13 months of hourly data, as hourly rows: Meta's daily ad rows,\n * each spread evenly over the hours of the account's day (`spread`), so that one table stays\n * hourly from end to end. Sums over whole days are Meta's exactly; the hours within a day are an\n * even split, not when the ads actually ran.\n *\n * Only for days the hourly data no longer covers, and only once: a day stored this way must\n * never also get hourly rows (an hour without delivery is not reported hourly, so its spread\n * share would stay and count twice). Fetch up to the day before the first hourly day stored.\n * These days are final; they need no re-fetch.\n *\n * @throws RangeError when `until` is within the 13 months of hourly data (use\n * `fetchMetaAdPerformance`), or `since` is past the 37 months Meta keeps at all.\n */\nexport async function fetchMetaAdPerformanceHistory(\n options: MetaAdPerformanceOptions\n): Promise<AdPerformanceRow[]> {\n const actionType = options.conversionActionType ?? 'purchase';\n const account = await accountOf(options);\n\n const since = addDays(options.since, 0);\n const until = addDays(options.until, 0);\n const today = todayIn(account.timezone_name);\n const hourlyFrom = addMonths(today, -HOURLY_RETENTION_MONTHS);\n const earliest = addMonths(today, -DAILY_RETENTION_MONTHS);\n if (until >= hourlyFrom) {\n throw new RangeError(\n `Meta has hourly insights from ${hourlyFrom}: until ${until} must be before it, fetch those days with fetchMetaAdPerformance`\n );\n }\n if (since < earliest) {\n throw new RangeError(\n `Meta keeps insights for ${DAILY_RETENTION_MONTHS} months: since ${since} is before ${earliest}`\n );\n }\n\n const days = await insights(options, account.id, since, until, {\n chunkDays: DAILY_CHUNK_DAYS,\n hourly: false,\n });\n return days.flatMap((insight) => {\n const day = toRow(\n insight,\n zonedHourToUtc(insight.date_start, 0, account.timezone_name),\n account.id,\n account.currency,\n actionType\n );\n return spreadDay(day, insight.date_start, account.timezone_name);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA6BA,MAAM,QAAQ;;AAGd,MAAM,UAAU;AAChB,MAAM,SAAS;;;;;AAMf,MAAM,eAAe;AACrB,MAAM,cAAc;AAEpB,MAAM,SAAS;;;;;;AAOf,MAAM,0BAA0B;;AAGhC,MAAM,yBAAyB;;;;;;AAO/B,MAAM,aAAa;;AAGnB,MAAM,mBAAmB;;AAGzB,MAAM,eAAe;AAErB,MAAM,SAAS;CACb;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAwBA,IAAa,kBAAb,cAAqC,MAAM;CACzC,YACE,SACA,QACA,MACA,SACA,WACA;EACA,MAAM,OAAO;EALJ,KAAA,SAAA;EACA,KAAA,OAAA;EACA,KAAA,UAAA;EACA,KAAA,YAAA;EAGT,KAAK,OAAO;CACd;AACF;AAEA,MAAM,gBAAA,GAAeA,SAAAA,OAAAA,CAAO;CAC1B,cAAA,GAAaC,SAAAA,OAAAA,CAAO;;;;;CAKpB,QAAA,GAAOC,SAAAA,SAAAA,EAAAA,GAASD,SAAAA,OAAAA,CAAO,CAAC;EACvB,gBAAA,GAAeC,SAAAA,SAAAA,EAAAA,GAASD,SAAAA,OAAA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UAAU,OAAO,GAAuB;CACzD,IAAI,SAAS,YACX,MAAM,IAAI,WACR,iCAAiC,WAAW,UAAU,MAAM,iEAC9D;CAEF,IAAI,QAAQ,UACV,MAAM,IAAI,WACR,2BAA2B,uBAAuB,iBAAiB,MAAM,aAAa,UACxF;CAOF,QAAO,MAJY,SAAS,SAAS,QAAQ,IAAI,OAAO,OAAO;EAC7D,WAAW;EACX,QAAQ;CACV,CAAC,EAAA,CACW,SAAS,YAAY;EAQ/B,OAAO,UAPK,MACV,SACAF,iBAAAA,eAAe,QAAQ,YAAY,GAAG,QAAQ,aAAa,GAC3D,QAAQ,IACR,QAAQ,UACR,UAEiB,GAAG,QAAQ,YAAY,QAAQ,aAAa;CACjE,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"meta.cjs","names":["object","string","optional","array","number","createHmac","fetch","safeParse","channelGroupOf","zonedHourToUtc","addDays","addMonths","todayIn"],"sources":["../../src/ads/meta.ts"],"sourcesContent":["/**\n * Meta ad delivery through the Marketing API's Insights endpoint, over plain `fetch`: one row per\n * ad and hour, in the attribution vocabulary (see `AdPerformanceRow`).\n *\n * The token needs `ads_read` on the ad account — a system user token with the account assigned\n * at \"View performance\". It is sent in the `Authorization` header and never put in a URL: paging\n * follows the `after` cursor rather than Meta's `paging.next`, which embeds the token.\n *\n * https://developers.facebook.com/docs/marketing-api/insights\n * https://developers.facebook.com/docs/marketing-api/insights/breakdowns\n */\nimport { createHmac } from 'node:crypto';\nimport { fetch } from '@shware/utils';\nimport {\n type infer as Infer,\n type ZodMiniType,\n array,\n number,\n object,\n optional,\n safeParse,\n string,\n} from 'zod/mini';\nimport { channelGroupOf } from '../attribution';\nimport { addDays, addMonths, todayIn, zonedHourToUtc } from './time';\nimport type { AdPerformanceRow, ReportDate } from './types';\n\n/** Same Graph API version as the Conversions API sender. */\nconst API_VERSION = 'v24.0';\nconst GRAPH = `https://graph.facebook.com/${API_VERSION}`;\n\n/** What an ad click is in the attribution vocabulary: `meta / cpc`, a paid social touch. */\nconst CHANNEL = 'meta';\nconst MEDIUM = 'cpc';\n\n/**\n * The click window of the click-through columns. Meta's longest since 2021, and the click part of\n * its default setting (7-day click, 1-day view).\n */\nconst CLICK_WINDOW = '7d_click';\nconst VIEW_WINDOW = '1d_view';\n\nconst HOURLY = 'hourly_stats_aggregated_by_advertiser_time_zone';\n\n/**\n * How far back Meta answers the hourly breakdown, in months. Past it Meta does not fail — it\n * returns no rows — so a backfill would silently store a gap.\n * https://developers.facebook.com/docs/marketing-api/insights/best-practices\n */\nconst HOURLY_RETENTION_MONTHS = 13;\n\n/** How far back Meta answers Insights without the hourly breakdown, in months. */\nconst DAILY_RETENTION_MONTHS = 37;\n\n/**\n * Days per Insights request. A synchronous request over a long range of ad rows times out on\n * Meta's side (`code 1, subcode 99`, \"An unknown error occurred\", as a 500): 17 months of daily\n * ad rows did. A range is split into windows this long, each paged on its own.\n */\nconst CHUNK_DAYS = 7;\n\n/** Days per request for daily rows: 24 times fewer rows than hourly ones per day. */\nconst DAILY_CHUNK_DAYS = 30;\n\n/** Decimal places of a day's numbers spread over its hours. */\nconst SPREAD_SCALE = 1e6;\n\nconst FIELDS = [\n 'ad_id',\n 'ad_name',\n 'adset_id',\n 'adset_name',\n 'campaign_id',\n 'campaign_name',\n 'spend',\n 'impressions',\n 'inline_link_clicks',\n 'actions',\n 'action_values',\n];\n\nexport interface MetaAdPerformanceOptions {\n /** A token with `ads_read` on the account. */\n accessToken: string;\n /** The ad account id, with or without its `act_` prefix. */\n accountId: string;\n /** First day, in the ad account's time zone. */\n since: ReportDate;\n /** Last day, inclusive, in the ad account's time zone. */\n until: ReportDate;\n /**\n * The `action_type` counted as the conversion, default `purchase` (Meta's total of the pixel,\n * Conversions API and in-app purchases of an event, deduplicated).\n */\n conversionActionType?: string;\n /**\n * The app secret, when the app requires `appsecret_proof` (App settings → Advanced → \"Require\n * app secret\"). The proof is computed here; the secret itself is never sent.\n */\n appSecret?: string;\n}\n\n/** A Graph API error, with Meta's code, for a caller deciding whether to retry. */\nexport class MetaAdsApiError extends Error {\n constructor(\n message: string,\n readonly status: number,\n readonly code: number | undefined,\n readonly subcode: number | undefined,\n readonly fbtraceId: string | undefined\n ) {\n super(message);\n this.name = 'MetaAdsApiError';\n }\n}\n\nconst actionSchema = object({\n action_type: string(),\n /**\n * The count under the ad's own attribution setting. Absent when the setting does not count any\n * of it — a view-only conversion of an ad set to 1-day click — which only shows in the windows.\n */\n value: optional(string()),\n [CLICK_WINDOW]: optional(string()),\n [VIEW_WINDOW]: optional(string()),\n});\n\nconst insightSchema = object({\n ad_id: string(),\n ad_name: optional(string()),\n adset_id: optional(string()),\n adset_name: optional(string()),\n campaign_id: string(),\n campaign_name: optional(string()),\n spend: optional(string()),\n impressions: optional(string()),\n inline_link_clicks: optional(string()),\n actions: optional(array(actionSchema)),\n action_values: optional(array(actionSchema)),\n date_start: string(),\n [HOURLY]: optional(string()),\n});\n\nconst pageSchema = object({\n data: array(insightSchema),\n paging: optional(\n object({ cursors: optional(object({ after: optional(string()) })), next: optional(string()) })\n ),\n});\n\nconst accountSchema = object({ currency: string(), timezone_name: string() });\n\nconst errorSchema = object({\n error: object({\n message: string(),\n code: optional(number()),\n error_subcode: optional(number()),\n fbtrace_id: optional(string()),\n }),\n});\n\ntype Insight = Infer<typeof insightSchema>;\ntype Action = Infer<typeof actionSchema>;\n\nasync function graphGet<T>(\n path: string,\n params: Record<string, string>,\n options: MetaAdPerformanceOptions,\n parse: (body: unknown) => T\n): Promise<T> {\n const query = new URLSearchParams(params);\n if (options.appSecret) {\n query.set(\n 'appsecret_proof',\n createHmac('sha256', options.appSecret).update(options.accessToken).digest('hex')\n );\n }\n const response = await fetch(`${GRAPH}/${path}?${query}`, {\n headers: { authorization: `Bearer ${options.accessToken}` },\n });\n const body: unknown = await response.json().catch(() => null);\n if (!response.ok) {\n const parsed = safeParse(errorSchema, body);\n const error = parsed.success ? parsed.data.error : undefined;\n throw new MetaAdsApiError(\n error?.message ?? `Meta Graph API responded ${response.status}`,\n response.status,\n error?.code,\n error?.error_subcode,\n error?.fbtrace_id\n );\n }\n return parse(body);\n}\n\nfunction parseWith<T>(schema: ZodMiniType<T>, what: string) {\n return (body: unknown): T => {\n const parsed = safeParse(schema, body);\n if (!parsed.success) {\n const issues = parsed.error.issues;\n const first = issues\n .slice(0, 3)\n .map((issue) => `${issue.path.join('.')}: ${issue.message}`)\n .join('; ');\n throw new Error(\n `Unexpected Meta ${what} response (${issues.length} issues): ${first}${issues.length > 3 ? '; …' : ''}`\n );\n }\n return parsed.data;\n };\n}\n\nfunction count(value: string | undefined): number {\n return value === undefined ? 0 : Number(value);\n}\n\n/** The action's total and its click-through part; nulls when Meta reported no such action. */\nfunction conversion(actions: Action[] | undefined, actionType: string) {\n const action = actions?.find((a) => a.action_type === actionType);\n if (!action) return { total: null, click: null };\n return { total: Number(action.value ?? 0), click: Number(action[CLICK_WINDOW] ?? 0) };\n}\n\n/** `\"13:00:00 - 13:59:59\"` → 13. */\nfunction hourOf(bucket: string | undefined): number {\n const hour = Number(bucket?.slice(0, 2));\n if (!Number.isInteger(hour) || hour < 0 || hour > 23) {\n throw new Error(`Unexpected Meta hourly bucket: ${bucket}`);\n }\n return hour;\n}\n\n/** A row for one hour: what Meta reports of an ad, its numbers as given. */\nfunction toRow(\n insight: Insight,\n hourStart: Date,\n accountId: string,\n currency: string,\n actionType: string\n): AdPerformanceRow {\n const conversions = conversion(insight.actions, actionType);\n const values = conversion(insight.action_values, actionType);\n return {\n platform: 'meta',\n account_id: accountId,\n campaign_id: insight.campaign_id,\n campaign_name: insight.campaign_name ?? null,\n ad_group_id: insight.adset_id ?? null,\n ad_group_name: insight.adset_name ?? null,\n ad_id: insight.ad_id,\n ad_name: insight.ad_name ?? null,\n channel: CHANNEL,\n medium: MEDIUM,\n channel_group: channelGroupOf(CHANNEL, MEDIUM),\n hour_start: hourStart.toISOString(),\n currency,\n spend: Number(insight.spend ?? 0),\n impressions: count(insight.impressions),\n clicks: count(insight.inline_link_clicks),\n conversions: conversions.total,\n conversion_value: values.total,\n click_conversions: conversions.click,\n click_conversion_value: values.click,\n };\n}\n\n/**\n * `value` in `parts` equal shares rounded to `SPREAD_SCALE`, the rounding left in the last share\n * so that the shares add back to `value` exactly as Meta reported it.\n */\nexport function spread(value: number, parts: number): number[] {\n const share = Math.round((value / parts) * SPREAD_SCALE) / SPREAD_SCALE;\n const last = Math.round((value - share * (parts - 1)) * SPREAD_SCALE) / SPREAD_SCALE;\n return [...Array.from({ length: parts - 1 }, () => share), last];\n}\n\n/**\n * A day row as one row per hour of the account's calendar day — 24, or 23 / 25 across a\n * daylight-saving change — each number spread evenly (nulls stay null).\n */\nfunction spreadDay(day: AdPerformanceRow, date: string, timeZone: string): AdPerformanceRow[] {\n const start = zonedHourToUtc(date, 0, timeZone).getTime();\n const end = zonedHourToUtc(addDays(date, 1), 0, timeZone).getTime();\n const hours = Math.round((end - start) / 3_600_000);\n const shares = (value: number | null) => (value === null ? null : spread(value, hours));\n const spend = spread(day.spend, hours);\n const impressions = spread(day.impressions, hours);\n const clicks = spread(day.clicks, hours);\n const conversions = shares(day.conversions);\n const conversionValue = shares(day.conversion_value);\n const clickConversions = shares(day.click_conversions);\n const clickConversionValue = shares(day.click_conversion_value);\n return Array.from({ length: hours }, (_, hour) => ({\n ...day,\n hour_start: new Date(start + hour * 3_600_000).toISOString(),\n spend: spend[hour],\n impressions: impressions[hour],\n clicks: clicks[hour],\n conversions: conversions?.[hour] ?? null,\n conversion_value: conversionValue?.[hour] ?? null,\n click_conversions: clickConversions?.[hour] ?? null,\n click_conversion_value: clickConversionValue?.[hour] ?? null,\n }));\n}\n\ninterface Account {\n id: string;\n currency: string;\n timezone_name: string;\n}\n\nasync function accountOf(options: MetaAdPerformanceOptions): Promise<Account> {\n const id = options.accountId.replace(/^act_/, '');\n const account = await graphGet(\n `act_${id}`,\n { fields: 'currency,timezone_name' },\n options,\n parseWith(accountSchema, 'ad account')\n );\n return { id, ...account };\n}\n\n/** Every ad row of the account between `since` and `until`, one request per window of `chunkDays`. */\nasync function insights(\n options: MetaAdPerformanceOptions,\n accountId: string,\n since: string,\n until: string,\n { chunkDays, hourly }: { chunkDays: number; hourly: boolean }\n): Promise<Insight[]> {\n const rows: Insight[] = [];\n for (let from = since; from <= until; from = addDays(from, chunkDays)) {\n const last = addDays(from, chunkDays - 1);\n const to = last < until ? last : until;\n let after: string | undefined;\n do {\n const params: Record<string, string> = {\n level: 'ad',\n fields: FIELDS.join(','),\n time_range: JSON.stringify({ since: from, until: to }),\n // One row per day. Without it the hourly breakdown folds the whole range into 24\n // hour-of-day buckets, all dated `since`, and a daily request returns the range's total.\n time_increment: '1',\n action_attribution_windows: JSON.stringify([CLICK_WINDOW, VIEW_WINDOW]),\n use_unified_attribution_setting: 'true',\n limit: '500',\n };\n if (hourly) params.breakdowns = HOURLY;\n if (after) params.after = after;\n const page = await graphGet(\n `act_${accountId}/insights`,\n params,\n options,\n parseWith(pageSchema, 'insights')\n );\n rows.push(...page.data);\n // `next` is absent on the last page; the cursor alone is not a signal, Meta returns it there too.\n after = page.paging?.next ? page.paging.cursors?.after : undefined;\n } while (after);\n }\n return rows;\n}\n\n/**\n * Hourly delivery of every ad of the account that ran between `since` and `until` — deleted and\n * archived ads included — one row per ad and hour (hours without delivery are absent). The hours\n * are Meta's, in the account's time zone, turned into UTC instants. Conversions are those of each\n * ad's attribution setting (`use_unified_attribution_setting`), their click-through part from the\n * 7-day click window.\n *\n * Meta restates past hours as late conversions arrive — a purchase is credited to the hour of the\n * click, up to 7 days after it — and corrects spend for invalid traffic: re-fetch the last 8 days\n * daily (the 7-day window plus a day of time zone slack) and upsert on (`platform`, `account_id`,\n * `ad_id`, `hour_start`).\n *\n * @throws RangeError when `since` is more than 13 months back, where Meta keeps no hourly\n * breakdown and would answer with no rows rather than an error.\n */\nexport async function fetchMetaAdPerformance(\n options: MetaAdPerformanceOptions\n): Promise<AdPerformanceRow[]> {\n const actionType = options.conversionActionType ?? 'purchase';\n const account = await accountOf(options);\n\n // Normalized, so `2025-9-8` compares as `2025-09-08`.\n const since = addDays(options.since, 0);\n const until = addDays(options.until, 0);\n const earliest = addMonths(todayIn(account.timezone_name), -HOURLY_RETENTION_MONTHS);\n if (since < earliest) {\n throw new RangeError(\n `Meta keeps hourly insights for ${HOURLY_RETENTION_MONTHS} months: since ${since} is before ${earliest}`\n );\n }\n\n const rows = await insights(options, account.id, since, until, {\n chunkDays: CHUNK_DAYS,\n hourly: true,\n });\n return rows.map((insight) =>\n toRow(\n insight,\n zonedHourToUtc(insight.date_start, hourOf(insight[HOURLY]), account.timezone_name),\n account.id,\n account.currency,\n actionType\n )\n );\n}\n\n/**\n * The delivery older than Meta's 13 months of hourly data, as hourly rows: Meta's daily ad rows,\n * each spread evenly over the hours of the account's day (`spread`), so that one table stays\n * hourly from end to end. Sums over whole days are Meta's exactly; the hours within a day are an\n * even split, not when the ads actually ran.\n *\n * Only for days the hourly data no longer covers, and only once: a day stored this way must\n * never also get hourly rows (an hour without delivery is not reported hourly, so its spread\n * share would stay and count twice). Fetch up to the day before the first hourly day stored.\n * These days are final; they need no re-fetch.\n *\n * @throws RangeError when `until` is within the 13 months of hourly data (use\n * `fetchMetaAdPerformance`), or `since` is past the 37 months Meta keeps at all.\n */\nexport async function fetchMetaAdPerformanceHistory(\n options: MetaAdPerformanceOptions\n): Promise<AdPerformanceRow[]> {\n const actionType = options.conversionActionType ?? 'purchase';\n const account = await accountOf(options);\n\n const since = addDays(options.since, 0);\n const until = addDays(options.until, 0);\n const today = todayIn(account.timezone_name);\n const hourlyFrom = addMonths(today, -HOURLY_RETENTION_MONTHS);\n const earliest = addMonths(today, -DAILY_RETENTION_MONTHS);\n if (until >= hourlyFrom) {\n throw new RangeError(\n `Meta has hourly insights from ${hourlyFrom}: until ${until} must be before it, fetch those days with fetchMetaAdPerformance`\n );\n }\n if (since < earliest) {\n throw new RangeError(\n `Meta keeps insights for ${DAILY_RETENTION_MONTHS} months: since ${since} is before ${earliest}`\n );\n }\n\n const days = await insights(options, account.id, since, until, {\n chunkDays: DAILY_CHUNK_DAYS,\n hourly: false,\n });\n return days.flatMap((insight) => {\n const day = toRow(\n insight,\n zonedHourToUtc(insight.date_start, 0, account.timezone_name),\n account.id,\n account.currency,\n actionType\n );\n return spreadDay(day, insight.date_start, account.timezone_name);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA6BA,MAAM,QAAQ;;AAGd,MAAM,UAAU;AAChB,MAAM,SAAS;;;;;AAMf,MAAM,eAAe;AACrB,MAAM,cAAc;AAEpB,MAAM,SAAS;;;;;;AAOf,MAAM,0BAA0B;;AAGhC,MAAM,yBAAyB;;;;;;AAO/B,MAAM,aAAa;;AAGnB,MAAM,mBAAmB;;AAGzB,MAAM,eAAe;AAErB,MAAM,SAAS;CACb;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAwBA,IAAa,kBAAb,cAAqC,MAAM;CACzC,YACE,SACS,QACA,MACA,SACA,WACT;EACA,MAAM,OAAO;EALJ,KAAA,SAAA;EACA,KAAA,OAAA;EACA,KAAA,UAAA;EACA,KAAA,YAAA;EAGT,KAAK,OAAO;CACd;AACF;AAEA,MAAM,gBAAA,GAAeA,SAAAA,OAAAA,CAAO;CAC1B,cAAA,GAAaC,SAAAA,OAAAA,CAAO;;;;;CAKpB,QAAA,GAAOC,SAAAA,SAAAA,EAAAA,GAASD,SAAAA,OAAAA,CAAO,CAAC;EACvB,gBAAA,GAAeC,SAAAA,SAAAA,EAAAA,GAASD,SAAAA,OAAAA,CAAO,CAAC;EAChC,eAAA,GAAcC,SAAAA,SAAAA,EAAAA,GAASD,SAAAA,OAAAA,CAAO,CAAC;AAClC,CAAC;AAED,MAAM,iBAAA,GAAgBD,SAAAA,OAAAA,CAAO;CAC3B,QAAA,GAAOC,SAAAA,OAAAA,CAAO;CACd,UAAA,GAASC,SAAAA,SAAAA,EAAAA,GAASD,SAAAA,OAAAA,CAAO,CAAC;CAC1B,WAAA,GAA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CACW,SAAS,YAAY;EAQ/B,OAAO,UAPK,MACV,SACAF,iBAAAA,eAAe,QAAQ,YAAY,GAAG,QAAQ,aAAa,GAC3D,QAAQ,IACR,QAAQ,UACR,UAEiB,GAAG,QAAQ,YAAY,QAAQ,aAAa;CACjE,CAAC;AACH"}
|
package/dist/ads/meta.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"meta.mjs","names":[],"sources":["../../src/ads/meta.ts"],"sourcesContent":["/**\n * Meta ad delivery through the Marketing API's Insights endpoint, over plain `fetch`: one row per\n * ad and hour, in the attribution vocabulary (see `AdPerformanceRow`).\n *\n * The token needs `ads_read` on the ad account — a system user token with the account assigned\n * at \"View performance\". It is sent in the `Authorization` header and never put in a URL: paging\n * follows the `after` cursor rather than Meta's `paging.next`, which embeds the token.\n *\n * https://developers.facebook.com/docs/marketing-api/insights\n * https://developers.facebook.com/docs/marketing-api/insights/breakdowns\n */\nimport { createHmac } from 'node:crypto';\nimport { fetch } from '@shware/utils';\nimport {\n type infer as Infer,\n type ZodMiniType,\n array,\n number,\n object,\n optional,\n safeParse,\n string,\n} from 'zod/mini';\nimport { channelGroupOf } from '../attribution';\nimport { addDays, addMonths, todayIn, zonedHourToUtc } from './time';\nimport type { AdPerformanceRow, ReportDate } from './types';\n\n/** Same Graph API version as the Conversions API sender. */\nconst API_VERSION = 'v24.0';\nconst GRAPH = `https://graph.facebook.com/${API_VERSION}`;\n\n/** What an ad click is in the attribution vocabulary: `meta / cpc`, a paid social touch. */\nconst CHANNEL = 'meta';\nconst MEDIUM = 'cpc';\n\n/**\n * The click window of the click-through columns. Meta's longest since 2021, and the click part of\n * its default setting (7-day click, 1-day view).\n */\nconst CLICK_WINDOW = '7d_click';\nconst VIEW_WINDOW = '1d_view';\n\nconst HOURLY = 'hourly_stats_aggregated_by_advertiser_time_zone';\n\n/**\n * How far back Meta answers the hourly breakdown, in months. Past it Meta does not fail — it\n * returns no rows — so a backfill would silently store a gap.\n * https://developers.facebook.com/docs/marketing-api/insights/best-practices\n */\nconst HOURLY_RETENTION_MONTHS = 13;\n\n/** How far back Meta answers Insights without the hourly breakdown, in months. */\nconst DAILY_RETENTION_MONTHS = 37;\n\n/**\n * Days per Insights request. A synchronous request over a long range of ad rows times out on\n * Meta's side (`code 1, subcode 99`, \"An unknown error occurred\", as a 500): 17 months of daily\n * ad rows did. A range is split into windows this long, each paged on its own.\n */\nconst CHUNK_DAYS = 7;\n\n/** Days per request for daily rows: 24 times fewer rows than hourly ones per day. */\nconst DAILY_CHUNK_DAYS = 30;\n\n/** Decimal places of a day's numbers spread over its hours. */\nconst SPREAD_SCALE = 1e6;\n\nconst FIELDS = [\n 'ad_id',\n 'ad_name',\n 'adset_id',\n 'adset_name',\n 'campaign_id',\n 'campaign_name',\n 'spend',\n 'impressions',\n 'inline_link_clicks',\n 'actions',\n 'action_values',\n];\n\nexport interface MetaAdPerformanceOptions {\n /** A token with `ads_read` on the account. */\n accessToken: string;\n /** The ad account id, with or without its `act_` prefix. */\n accountId: string;\n /** First day, in the ad account's time zone. */\n since: ReportDate;\n /** Last day, inclusive, in the ad account's time zone. */\n until: ReportDate;\n /**\n * The `action_type` counted as the conversion, default `purchase` (Meta's total of the pixel,\n * Conversions API and in-app purchases of an event, deduplicated).\n */\n conversionActionType?: string;\n /**\n * The app secret, when the app requires `appsecret_proof` (App settings → Advanced → \"Require\n * app secret\"). The proof is computed here; the secret itself is never sent.\n */\n appSecret?: string;\n}\n\n/** A Graph API error, with Meta's code, for a caller deciding whether to retry. */\nexport class MetaAdsApiError extends Error {\n constructor(\n message: string,\n readonly status: number,\n readonly code: number | undefined,\n readonly subcode: number | undefined,\n readonly fbtraceId: string | undefined\n ) {\n super(message);\n this.name = 'MetaAdsApiError';\n }\n}\n\nconst actionSchema = object({\n action_type: string(),\n /**\n * The count under the ad's own attribution setting. Absent when the setting does not count any\n * of it — a view-only conversion of an ad set to 1-day click — which only shows in the windows.\n */\n value: optional(string()),\n [CLICK_WINDOW]: optional(string()),\n [VIEW_WINDOW]: optional(string()),\n});\n\nconst insightSchema = object({\n ad_id: string(),\n ad_name: optional(string()),\n adset_id: optional(string()),\n adset_name: optional(string()),\n campaign_id: string(),\n campaign_name: optional(string()),\n spend: optional(string()),\n impressions: optional(string()),\n inline_link_clicks: optional(string()),\n actions: optional(array(actionSchema)),\n action_values: optional(array(actionSchema)),\n date_start: string(),\n [HOURLY]: optional(string()),\n});\n\nconst pageSchema = object({\n data: array(insightSchema),\n paging: optional(\n object({ cursors: optional(object({ after: optional(string()) })), next: optional(string()) })\n ),\n});\n\nconst accountSchema = object({ currency: string(), timezone_name: string() });\n\nconst errorSchema = object({\n error: object({\n message: string(),\n code: optional(number()),\n error_subcode: optional(number()),\n fbtrace_id: optional(string()),\n }),\n});\n\ntype Insight = Infer<typeof insightSchema>;\ntype Action = Infer<typeof actionSchema>;\n\nasync function graphGet<T>(\n path: string,\n params: Record<string, string>,\n options: MetaAdPerformanceOptions,\n parse: (body: unknown) => T\n): Promise<T> {\n const query = new URLSearchParams(params);\n if (options.appSecret) {\n query.set(\n 'appsecret_proof',\n createHmac('sha256', options.appSecret).update(options.accessToken).digest('hex')\n );\n }\n const response = await fetch(`${GRAPH}/${path}?${query}`, {\n headers: { authorization: `Bearer ${options.accessToken}` },\n });\n const body: unknown = await response.json().catch(() => null);\n if (!response.ok) {\n const parsed = safeParse(errorSchema, body);\n const error = parsed.success ? parsed.data.error : undefined;\n throw new MetaAdsApiError(\n error?.message ?? `Meta Graph API responded ${response.status}`,\n response.status,\n error?.code,\n error?.error_subcode,\n error?.fbtrace_id\n );\n }\n return parse(body);\n}\n\nfunction parseWith<T>(schema: ZodMiniType<T>, what: string) {\n return (body: unknown): T => {\n const parsed = safeParse(schema, body);\n if (!parsed.success) {\n const issues = parsed.error.issues;\n const first = issues\n .slice(0, 3)\n .map((issue) => `${issue.path.join('.')}: ${issue.message}`)\n .join('; ');\n throw new Error(\n `Unexpected Meta ${what} response (${issues.length} issues): ${first}${issues.length > 3 ? '; …' : ''}`\n );\n }\n return parsed.data;\n };\n}\n\nfunction count(value: string | undefined): number {\n return value === undefined ? 0 : Number(value);\n}\n\n/** The action's total and its click-through part; nulls when Meta reported no such action. */\nfunction conversion(actions: Action[] | undefined, actionType: string) {\n const action = actions?.find((a) => a.action_type === actionType);\n if (!action) return { total: null, click: null };\n return { total: Number(action.value ?? 0), click: Number(action[CLICK_WINDOW] ?? 0) };\n}\n\n/** `\"13:00:00 - 13:59:59\"` → 13. */\nfunction hourOf(bucket: string | undefined): number {\n const hour = Number(bucket?.slice(0, 2));\n if (!Number.isInteger(hour) || hour < 0 || hour > 23) {\n throw new Error(`Unexpected Meta hourly bucket: ${bucket}`);\n }\n return hour;\n}\n\n/** A row for one hour: what Meta reports of an ad, its numbers as given. */\nfunction toRow(\n insight: Insight,\n hourStart: Date,\n accountId: string,\n currency: string,\n actionType: string\n): AdPerformanceRow {\n const conversions = conversion(insight.actions, actionType);\n const values = conversion(insight.action_values, actionType);\n return {\n platform: 'meta',\n account_id: accountId,\n campaign_id: insight.campaign_id,\n campaign_name: insight.campaign_name ?? null,\n ad_group_id: insight.adset_id ?? null,\n ad_group_name: insight.adset_name ?? null,\n ad_id: insight.ad_id,\n ad_name: insight.ad_name ?? null,\n channel: CHANNEL,\n medium: MEDIUM,\n channel_group: channelGroupOf(CHANNEL, MEDIUM),\n hour_start: hourStart.toISOString(),\n currency,\n spend: Number(insight.spend ?? 0),\n impressions: count(insight.impressions),\n clicks: count(insight.inline_link_clicks),\n conversions: conversions.total,\n conversion_value: values.total,\n click_conversions: conversions.click,\n click_conversion_value: values.click,\n };\n}\n\n/**\n * `value` in `parts` equal shares rounded to `SPREAD_SCALE`, the rounding left in the last share\n * so that the shares add back to `value` exactly as Meta reported it.\n */\nexport function spread(value: number, parts: number): number[] {\n const share = Math.round((value / parts) * SPREAD_SCALE) / SPREAD_SCALE;\n const last = Math.round((value - share * (parts - 1)) * SPREAD_SCALE) / SPREAD_SCALE;\n return [...Array.from({ length: parts - 1 }, () => share), last];\n}\n\n/**\n * A day row as one row per hour of the account's calendar day — 24, or 23 / 25 across a\n * daylight-saving change — each number spread evenly (nulls stay null).\n */\nfunction spreadDay(day: AdPerformanceRow, date: string, timeZone: string): AdPerformanceRow[] {\n const start = zonedHourToUtc(date, 0, timeZone).getTime();\n const end = zonedHourToUtc(addDays(date, 1), 0, timeZone).getTime();\n const hours = Math.round((end - start) / 3_600_000);\n const shares = (value: number | null) => (value === null ? null : spread(value, hours));\n const spend = spread(day.spend, hours);\n const impressions = spread(day.impressions, hours);\n const clicks = spread(day.clicks, hours);\n const conversions = shares(day.conversions);\n const conversionValue = shares(day.conversion_value);\n const clickConversions = shares(day.click_conversions);\n const clickConversionValue = shares(day.click_conversion_value);\n return Array.from({ length: hours }, (_, hour) => ({\n ...day,\n hour_start: new Date(start + hour * 3_600_000).toISOString(),\n spend: spend[hour],\n impressions: impressions[hour],\n clicks: clicks[hour],\n conversions: conversions?.[hour] ?? null,\n conversion_value: conversionValue?.[hour] ?? null,\n click_conversions: clickConversions?.[hour] ?? null,\n click_conversion_value: clickConversionValue?.[hour] ?? null,\n }));\n}\n\ninterface Account {\n id: string;\n currency: string;\n timezone_name: string;\n}\n\nasync function accountOf(options: MetaAdPerformanceOptions): Promise<Account> {\n const id = options.accountId.replace(/^act_/, '');\n const account = await graphGet(\n `act_${id}`,\n { fields: 'currency,timezone_name' },\n options,\n parseWith(accountSchema, 'ad account')\n );\n return { id, ...account };\n}\n\n/** Every ad row of the account between `since` and `until`, one request per window of `chunkDays`. */\nasync function insights(\n options: MetaAdPerformanceOptions,\n accountId: string,\n since: string,\n until: string,\n { chunkDays, hourly }: { chunkDays: number; hourly: boolean }\n): Promise<Insight[]> {\n const rows: Insight[] = [];\n for (let from = since; from <= until; from = addDays(from, chunkDays)) {\n const last = addDays(from, chunkDays - 1);\n const to = last < until ? last : until;\n let after: string | undefined;\n do {\n const params: Record<string, string> = {\n level: 'ad',\n fields: FIELDS.join(','),\n time_range: JSON.stringify({ since: from, until: to }),\n // One row per day. Without it the hourly breakdown folds the whole range into 24\n // hour-of-day buckets, all dated `since`, and a daily request returns the range's total.\n time_increment: '1',\n action_attribution_windows: JSON.stringify([CLICK_WINDOW, VIEW_WINDOW]),\n use_unified_attribution_setting: 'true',\n limit: '500',\n };\n if (hourly) params.breakdowns = HOURLY;\n if (after) params.after = after;\n const page = await graphGet(\n `act_${accountId}/insights`,\n params,\n options,\n parseWith(pageSchema, 'insights')\n );\n rows.push(...page.data);\n // `next` is absent on the last page; the cursor alone is not a signal, Meta returns it there too.\n after = page.paging?.next ? page.paging.cursors?.after : undefined;\n } while (after);\n }\n return rows;\n}\n\n/**\n * Hourly delivery of every ad of the account that ran between `since` and `until` — deleted and\n * archived ads included — one row per ad and hour (hours without delivery are absent). The hours\n * are Meta's, in the account's time zone, turned into UTC instants. Conversions are those of each\n * ad's attribution setting (`use_unified_attribution_setting`), their click-through part from the\n * 7-day click window.\n *\n * Meta restates past hours as late conversions arrive — a purchase is credited to the hour of the\n * click, up to 7 days after it — and corrects spend for invalid traffic: re-fetch the last 8 days\n * daily (the 7-day window plus a day of time zone slack) and upsert on (`platform`, `account_id`,\n * `ad_id`, `hour_start`).\n *\n * @throws RangeError when `since` is more than 13 months back, where Meta keeps no hourly\n * breakdown and would answer with no rows rather than an error.\n */\nexport async function fetchMetaAdPerformance(\n options: MetaAdPerformanceOptions\n): Promise<AdPerformanceRow[]> {\n const actionType = options.conversionActionType ?? 'purchase';\n const account = await accountOf(options);\n\n // Normalized, so `2025-9-8` compares as `2025-09-08`.\n const since = addDays(options.since, 0);\n const until = addDays(options.until, 0);\n const earliest = addMonths(todayIn(account.timezone_name), -HOURLY_RETENTION_MONTHS);\n if (since < earliest) {\n throw new RangeError(\n `Meta keeps hourly insights for ${HOURLY_RETENTION_MONTHS} months: since ${since} is before ${earliest}`\n );\n }\n\n const rows = await insights(options, account.id, since, until, {\n chunkDays: CHUNK_DAYS,\n hourly: true,\n });\n return rows.map((insight) =>\n toRow(\n insight,\n zonedHourToUtc(insight.date_start, hourOf(insight[HOURLY]), account.timezone_name),\n account.id,\n account.currency,\n actionType\n )\n );\n}\n\n/**\n * The delivery older than Meta's 13 months of hourly data, as hourly rows: Meta's daily ad rows,\n * each spread evenly over the hours of the account's day (`spread`), so that one table stays\n * hourly from end to end. Sums over whole days are Meta's exactly; the hours within a day are an\n * even split, not when the ads actually ran.\n *\n * Only for days the hourly data no longer covers, and only once: a day stored this way must\n * never also get hourly rows (an hour without delivery is not reported hourly, so its spread\n * share would stay and count twice). Fetch up to the day before the first hourly day stored.\n * These days are final; they need no re-fetch.\n *\n * @throws RangeError when `until` is within the 13 months of hourly data (use\n * `fetchMetaAdPerformance`), or `since` is past the 37 months Meta keeps at all.\n */\nexport async function fetchMetaAdPerformanceHistory(\n options: MetaAdPerformanceOptions\n): Promise<AdPerformanceRow[]> {\n const actionType = options.conversionActionType ?? 'purchase';\n const account = await accountOf(options);\n\n const since = addDays(options.since, 0);\n const until = addDays(options.until, 0);\n const today = todayIn(account.timezone_name);\n const hourlyFrom = addMonths(today, -HOURLY_RETENTION_MONTHS);\n const earliest = addMonths(today, -DAILY_RETENTION_MONTHS);\n if (until >= hourlyFrom) {\n throw new RangeError(\n `Meta has hourly insights from ${hourlyFrom}: until ${until} must be before it, fetch those days with fetchMetaAdPerformance`\n );\n }\n if (since < earliest) {\n throw new RangeError(\n `Meta keeps insights for ${DAILY_RETENTION_MONTHS} months: since ${since} is before ${earliest}`\n );\n }\n\n const days = await insights(options, account.id, since, until, {\n chunkDays: DAILY_CHUNK_DAYS,\n hourly: false,\n });\n return days.flatMap((insight) => {\n const day = toRow(\n insight,\n zonedHourToUtc(insight.date_start, 0, account.timezone_name),\n account.id,\n account.currency,\n actionType\n );\n return spreadDay(day, insight.date_start, account.timezone_name);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA6BA,MAAM,QAAQ;;AAGd,MAAM,UAAU;AAChB,MAAM,SAAS;;;;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I,OAAO,OAAO;EAC7D,WAAW;EACX,QAAQ;CACV,CAAC,EAAA,CACW,KAAK,YACf,MACE,SACA,eAAe,QAAQ,YAAY,OAAO,QAAQ,OAAO,GAAG,QAAQ,aAAa,GACjF,QAAQ,IACR,QAAQ,UACR,UACF,CACF;AACF;;;;;;;;;;;;;;;AAgBA,eAAsB,8BACpB,SAC6B;CAC7B,MAAM,aAAa,QAAQ,wBAAwB;CACnD,MAAM,UAAU,MAAM,UAAU,OAAO;CAEvC,MAAM,QAAQ,QAAQ,QAAQ,OAAO,CAAC;CACtC,MAAM,QAAQ,QAAQ,QAAQ,OAAO,CAAC;CACtC,MAAM,QAAQ,QAAQ,QAAQ,aAAa;CAC3C,MAAM,aAAa,UAAU,OAAO,GAAwB;CAC5D,MAAM,WAAW,UAAU,OAAO,GAAuB;CACzD,IAAI,SAAS,YACX,MAAM,IAAI,WACR,iCAAiC,WAAW,UAAU,MAAM,iEAC9D;CAEF,IAAI,QAAQ,UACV,MAAM,IAAI,WACR,2BAA2B,uBAAuB,iBAAiB,MAAM,aAAa,UACxF;CAOF,QAAO,MAJY,SAAS,SAAS,QAAQ,IAAI,OAAO,OAAO;EAC7D,WAAW;EACX,QAAQ;CACV,CAAC,EAAA,CACW,SAAS,YAAY;EAQ/B,OAAO,UAPK,MACV,SACA,eAAe,QAAQ,YAAY,GAAG,QAAQ,aAAa,GAC3D,QAAQ,IACR,QAAQ,UACR,UAEiB,GAAG,QAAQ,YAAY,QAAQ,aAAa;CACjE,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"meta.mjs","names":[],"sources":["../../src/ads/meta.ts"],"sourcesContent":["/**\n * Meta ad delivery through the Marketing API's Insights endpoint, over plain `fetch`: one row per\n * ad and hour, in the attribution vocabulary (see `AdPerformanceRow`).\n *\n * The token needs `ads_read` on the ad account — a system user token with the account assigned\n * at \"View performance\". It is sent in the `Authorization` header and never put in a URL: paging\n * follows the `after` cursor rather than Meta's `paging.next`, which embeds the token.\n *\n * https://developers.facebook.com/docs/marketing-api/insights\n * https://developers.facebook.com/docs/marketing-api/insights/breakdowns\n */\nimport { createHmac } from 'node:crypto';\nimport { fetch } from '@shware/utils';\nimport {\n type infer as Infer,\n type ZodMiniType,\n array,\n number,\n object,\n optional,\n safeParse,\n string,\n} from 'zod/mini';\nimport { channelGroupOf } from '../attribution';\nimport { addDays, addMonths, todayIn, zonedHourToUtc } from './time';\nimport type { AdPerformanceRow, ReportDate } from './types';\n\n/** Same Graph API version as the Conversions API sender. */\nconst API_VERSION = 'v24.0';\nconst GRAPH = `https://graph.facebook.com/${API_VERSION}`;\n\n/** What an ad click is in the attribution vocabulary: `meta / cpc`, a paid social touch. */\nconst CHANNEL = 'meta';\nconst MEDIUM = 'cpc';\n\n/**\n * The click window of the click-through columns. Meta's longest since 2021, and the click part of\n * its default setting (7-day click, 1-day view).\n */\nconst CLICK_WINDOW = '7d_click';\nconst VIEW_WINDOW = '1d_view';\n\nconst HOURLY = 'hourly_stats_aggregated_by_advertiser_time_zone';\n\n/**\n * How far back Meta answers the hourly breakdown, in months. Past it Meta does not fail — it\n * returns no rows — so a backfill would silently store a gap.\n * https://developers.facebook.com/docs/marketing-api/insights/best-practices\n */\nconst HOURLY_RETENTION_MONTHS = 13;\n\n/** How far back Meta answers Insights without the hourly breakdown, in months. */\nconst DAILY_RETENTION_MONTHS = 37;\n\n/**\n * Days per Insights request. A synchronous request over a long range of ad rows times out on\n * Meta's side (`code 1, subcode 99`, \"An unknown error occurred\", as a 500): 17 months of daily\n * ad rows did. A range is split into windows this long, each paged on its own.\n */\nconst CHUNK_DAYS = 7;\n\n/** Days per request for daily rows: 24 times fewer rows than hourly ones per day. */\nconst DAILY_CHUNK_DAYS = 30;\n\n/** Decimal places of a day's numbers spread over its hours. */\nconst SPREAD_SCALE = 1e6;\n\nconst FIELDS = [\n 'ad_id',\n 'ad_name',\n 'adset_id',\n 'adset_name',\n 'campaign_id',\n 'campaign_name',\n 'spend',\n 'impressions',\n 'inline_link_clicks',\n 'actions',\n 'action_values',\n];\n\nexport interface MetaAdPerformanceOptions {\n /** A token with `ads_read` on the account. */\n accessToken: string;\n /** The ad account id, with or without its `act_` prefix. */\n accountId: string;\n /** First day, in the ad account's time zone. */\n since: ReportDate;\n /** Last day, inclusive, in the ad account's time zone. */\n until: ReportDate;\n /**\n * The `action_type` counted as the conversion, default `purchase` (Meta's total of the pixel,\n * Conversions API and in-app purchases of an event, deduplicated).\n */\n conversionActionType?: string;\n /**\n * The app secret, when the app requires `appsecret_proof` (App settings → Advanced → \"Require\n * app secret\"). The proof is computed here; the secret itself is never sent.\n */\n appSecret?: string;\n}\n\n/** A Graph API error, with Meta's code, for a caller deciding whether to retry. */\nexport class MetaAdsApiError extends Error {\n constructor(\n message: string,\n readonly status: number,\n readonly code: number | undefined,\n readonly subcode: number | undefined,\n readonly fbtraceId: string | undefined\n ) {\n super(message);\n this.name = 'MetaAdsApiError';\n }\n}\n\nconst actionSchema = object({\n action_type: string(),\n /**\n * The count under the ad's own attribution setting. Absent when the setting does not count any\n * of it — a view-only conversion of an ad set to 1-day click — which only shows in the windows.\n */\n value: optional(string()),\n [CLICK_WINDOW]: optional(string()),\n [VIEW_WINDOW]: optional(string()),\n});\n\nconst insightSchema = object({\n ad_id: string(),\n ad_name: optional(string()),\n adset_id: optional(string()),\n adset_name: optional(string()),\n campaign_id: string(),\n campaign_name: optional(string()),\n spend: optional(string()),\n impressions: optional(string()),\n inline_link_clicks: optional(string()),\n actions: optional(array(actionSchema)),\n action_values: optional(array(actionSchema)),\n date_start: string(),\n [HOURLY]: optional(string()),\n});\n\nconst pageSchema = object({\n data: array(insightSchema),\n paging: optional(\n object({ cursors: optional(object({ after: optional(string()) })), next: optional(string()) })\n ),\n});\n\nconst accountSchema = object({ currency: string(), timezone_name: string() });\n\nconst errorSchema = object({\n error: object({\n message: string(),\n code: optional(number()),\n error_subcode: optional(number()),\n fbtrace_id: optional(string()),\n }),\n});\n\ntype Insight = Infer<typeof insightSchema>;\ntype Action = Infer<typeof actionSchema>;\n\nasync function graphGet<T>(\n path: string,\n params: Record<string, string>,\n options: MetaAdPerformanceOptions,\n parse: (body: unknown) => T\n): Promise<T> {\n const query = new URLSearchParams(params);\n if (options.appSecret) {\n query.set(\n 'appsecret_proof',\n createHmac('sha256', options.appSecret).update(options.accessToken).digest('hex')\n );\n }\n const response = await fetch(`${GRAPH}/${path}?${query}`, {\n headers: { authorization: `Bearer ${options.accessToken}` },\n });\n const body: unknown = await response.json().catch(() => null);\n if (!response.ok) {\n const parsed = safeParse(errorSchema, body);\n const error = parsed.success ? parsed.data.error : undefined;\n throw new MetaAdsApiError(\n error?.message ?? `Meta Graph API responded ${response.status}`,\n response.status,\n error?.code,\n error?.error_subcode,\n error?.fbtrace_id\n );\n }\n return parse(body);\n}\n\nfunction parseWith<T>(schema: ZodMiniType<T>, what: string) {\n return (body: unknown): T => {\n const parsed = safeParse(schema, body);\n if (!parsed.success) {\n const issues = parsed.error.issues;\n const first = issues\n .slice(0, 3)\n .map((issue) => `${issue.path.join('.')}: ${issue.message}`)\n .join('; ');\n throw new Error(\n `Unexpected Meta ${what} response (${issues.length} issues): ${first}${issues.length > 3 ? '; …' : ''}`\n );\n }\n return parsed.data;\n };\n}\n\nfunction count(value: string | undefined): number {\n return value === undefined ? 0 : Number(value);\n}\n\n/** The action's total and its click-through part; nulls when Meta reported no such action. */\nfunction conversion(actions: Action[] | undefined, actionType: string) {\n const action = actions?.find((a) => a.action_type === actionType);\n if (!action) return { total: null, click: null };\n return { total: Number(action.value ?? 0), click: Number(action[CLICK_WINDOW] ?? 0) };\n}\n\n/** `\"13:00:00 - 13:59:59\"` → 13. */\nfunction hourOf(bucket: string | undefined): number {\n const hour = Number(bucket?.slice(0, 2));\n if (!Number.isInteger(hour) || hour < 0 || hour > 23) {\n throw new Error(`Unexpected Meta hourly bucket: ${bucket}`);\n }\n return hour;\n}\n\n/** A row for one hour: what Meta reports of an ad, its numbers as given. */\nfunction toRow(\n insight: Insight,\n hourStart: Date,\n accountId: string,\n currency: string,\n actionType: string\n): AdPerformanceRow {\n const conversions = conversion(insight.actions, actionType);\n const values = conversion(insight.action_values, actionType);\n return {\n platform: 'meta',\n account_id: accountId,\n campaign_id: insight.campaign_id,\n campaign_name: insight.campaign_name ?? null,\n ad_group_id: insight.adset_id ?? null,\n ad_group_name: insight.adset_name ?? null,\n ad_id: insight.ad_id,\n ad_name: insight.ad_name ?? null,\n channel: CHANNEL,\n medium: MEDIUM,\n channel_group: channelGroupOf(CHANNEL, MEDIUM),\n hour_start: hourStart.toISOString(),\n currency,\n spend: Number(insight.spend ?? 0),\n impressions: count(insight.impressions),\n clicks: count(insight.inline_link_clicks),\n conversions: conversions.total,\n conversion_value: values.total,\n click_conversions: conversions.click,\n click_conversion_value: values.click,\n };\n}\n\n/**\n * `value` in `parts` equal shares rounded to `SPREAD_SCALE`, the rounding left in the last share\n * so that the shares add back to `value` exactly as Meta reported it.\n */\nexport function spread(value: number, parts: number): number[] {\n const share = Math.round((value / parts) * SPREAD_SCALE) / SPREAD_SCALE;\n const last = Math.round((value - share * (parts - 1)) * SPREAD_SCALE) / SPREAD_SCALE;\n return [...Array.from({ length: parts - 1 }, () => share), last];\n}\n\n/**\n * A day row as one row per hour of the account's calendar day — 24, or 23 / 25 across a\n * daylight-saving change — each number spread evenly (nulls stay null).\n */\nfunction spreadDay(day: AdPerformanceRow, date: string, timeZone: string): AdPerformanceRow[] {\n const start = zonedHourToUtc(date, 0, timeZone).getTime();\n const end = zonedHourToUtc(addDays(date, 1), 0, timeZone).getTime();\n const hours = Math.round((end - start) / 3_600_000);\n const shares = (value: number | null) => (value === null ? null : spread(value, hours));\n const spend = spread(day.spend, hours);\n const impressions = spread(day.impressions, hours);\n const clicks = spread(day.clicks, hours);\n const conversions = shares(day.conversions);\n const conversionValue = shares(day.conversion_value);\n const clickConversions = shares(day.click_conversions);\n const clickConversionValue = shares(day.click_conversion_value);\n return Array.from({ length: hours }, (_, hour) => ({\n ...day,\n hour_start: new Date(start + hour * 3_600_000).toISOString(),\n spend: spend[hour],\n impressions: impressions[hour],\n clicks: clicks[hour],\n conversions: conversions?.[hour] ?? null,\n conversion_value: conversionValue?.[hour] ?? null,\n click_conversions: clickConversions?.[hour] ?? null,\n click_conversion_value: clickConversionValue?.[hour] ?? null,\n }));\n}\n\ninterface Account {\n id: string;\n currency: string;\n timezone_name: string;\n}\n\nasync function accountOf(options: MetaAdPerformanceOptions): Promise<Account> {\n const id = options.accountId.replace(/^act_/, '');\n const account = await graphGet(\n `act_${id}`,\n { fields: 'currency,timezone_name' },\n options,\n parseWith(accountSchema, 'ad account')\n );\n return { id, ...account };\n}\n\n/** Every ad row of the account between `since` and `until`, one request per window of `chunkDays`. */\nasync function insights(\n options: MetaAdPerformanceOptions,\n accountId: string,\n since: string,\n until: string,\n { chunkDays, hourly }: { chunkDays: number; hourly: boolean }\n): Promise<Insight[]> {\n const rows: Insight[] = [];\n for (let from = since; from <= until; from = addDays(from, chunkDays)) {\n const last = addDays(from, chunkDays - 1);\n const to = last < until ? last : until;\n let after: string | undefined;\n do {\n const params: Record<string, string> = {\n level: 'ad',\n fields: FIELDS.join(','),\n time_range: JSON.stringify({ since: from, until: to }),\n // One row per day. Without it the hourly breakdown folds the whole range into 24\n // hour-of-day buckets, all dated `since`, and a daily request returns the range's total.\n time_increment: '1',\n action_attribution_windows: JSON.stringify([CLICK_WINDOW, VIEW_WINDOW]),\n use_unified_attribution_setting: 'true',\n limit: '500',\n };\n if (hourly) params.breakdowns = HOURLY;\n if (after) params.after = after;\n const page = await graphGet(\n `act_${accountId}/insights`,\n params,\n options,\n parseWith(pageSchema, 'insights')\n );\n rows.push(...page.data);\n // `next` is absent on the last page; the cursor alone is not a signal, Meta returns it there too.\n after = page.paging?.next ? page.paging.cursors?.after : undefined;\n } while (after);\n }\n return rows;\n}\n\n/**\n * Hourly delivery of every ad of the account that ran between `since` and `until` — deleted and\n * archived ads included — one row per ad and hour (hours without delivery are absent). The hours\n * are Meta's, in the account's time zone, turned into UTC instants. Conversions are those of each\n * ad's attribution setting (`use_unified_attribution_setting`), their click-through part from the\n * 7-day click window.\n *\n * Meta restates past hours as late conversions arrive — a purchase is credited to the hour of the\n * click, up to 7 days after it — and corrects spend for invalid traffic: re-fetch the last 8 days\n * daily (the 7-day window plus a day of time zone slack) and upsert on (`platform`, `account_id`,\n * `ad_id`, `hour_start`).\n *\n * @throws RangeError when `since` is more than 13 months back, where Meta keeps no hourly\n * breakdown and would answer with no rows rather than an error.\n */\nexport async function fetchMetaAdPerformance(\n options: MetaAdPerformanceOptions\n): Promise<AdPerformanceRow[]> {\n const actionType = options.conversionActionType ?? 'purchase';\n const account = await accountOf(options);\n\n // Normalized, so `2025-9-8` compares as `2025-09-08`.\n const since = addDays(options.since, 0);\n const until = addDays(options.until, 0);\n const earliest = addMonths(todayIn(account.timezone_name), -HOURLY_RETENTION_MONTHS);\n if (since < earliest) {\n throw new RangeError(\n `Meta keeps hourly insights for ${HOURLY_RETENTION_MONTHS} months: since ${since} is before ${earliest}`\n );\n }\n\n const rows = await insights(options, account.id, since, until, {\n chunkDays: CHUNK_DAYS,\n hourly: true,\n });\n return rows.map((insight) =>\n toRow(\n insight,\n zonedHourToUtc(insight.date_start, hourOf(insight[HOURLY]), account.timezone_name),\n account.id,\n account.currency,\n actionType\n )\n );\n}\n\n/**\n * The delivery older than Meta's 13 months of hourly data, as hourly rows: Meta's daily ad rows,\n * each spread evenly over the hours of the account's day (`spread`), so that one table stays\n * hourly from end to end. Sums over whole days are Meta's exactly; the hours within a day are an\n * even split, not when the ads actually ran.\n *\n * Only for days the hourly data no longer covers, and only once: a day stored this way must\n * never also get hourly rows (an hour without delivery is not reported hourly, so its spread\n * share would stay and count twice). Fetch up to the day before the first hourly day stored.\n * These days are final; they need no re-fetch.\n *\n * @throws RangeError when `until` is within the 13 months of hourly data (use\n * `fetchMetaAdPerformance`), or `since` is past the 37 months Meta keeps at all.\n */\nexport async function fetchMetaAdPerformanceHistory(\n options: MetaAdPerformanceOptions\n): Promise<AdPerformanceRow[]> {\n const actionType = options.conversionActionType ?? 'purchase';\n const account = await accountOf(options);\n\n const since = addDays(options.since, 0);\n const until = addDays(options.until, 0);\n const today = todayIn(account.timezone_name);\n const hourlyFrom = addMonths(today, -HOURLY_RETENTION_MONTHS);\n const earliest = addMonths(today, -DAILY_RETENTION_MONTHS);\n if (until >= hourlyFrom) {\n throw new RangeError(\n `Meta has hourly insights from ${hourlyFrom}: until ${until} must be before it, fetch those days with fetchMetaAdPerformance`\n );\n }\n if (since < earliest) {\n throw new RangeError(\n `Meta keeps insights for ${DAILY_RETENTION_MONTHS} months: since ${since} is before ${earliest}`\n );\n }\n\n const days = await insights(options, account.id, since, until, {\n chunkDays: DAILY_CHUNK_DAYS,\n hourly: false,\n });\n return days.flatMap((insight) => {\n const day = toRow(\n insight,\n zonedHourToUtc(insight.date_start, 0, account.timezone_name),\n account.id,\n account.currency,\n actionType\n );\n return spreadDay(day, insight.date_start, account.timezone_name);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA6BA,MAAM,QAAQ;;AAGd,MAAM,UAAU;AAChB,MAAM,SAAS;;;;;AAMf,MAAM,eAAe;AACrB,MAAM,cAAc;AAEpB,MAAM,SAAS;;;;;;AAOf,MAAM,0BAA0B;;AAGhC,MAAM,yBAAyB;;;;;;AAO/B,MAAM,aAAa;;AAGnB,MAAM,mBAAmB;;AAGzB,MAAM,eAAe;AAErB,MAAM,SAAS;CACb;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAwBA,IAAa,kBAAb,cAAqC,MAAM;CACzC,YACE,SACS,QACA,MACA,SACA,WACT;EACA,MAAM,OAAO;EALJ,KAAA,SAAA;EACA,KAAA,OAAA;EACA,KAAA,UAAA;EACA,KAAA,YAAA;EAGT,KAAK,OAAO;CACd;AACF;AAEA,MAAM,eAAe,OAAO;CAC1B,aAAa,OAAO;;;;;CAKpB,OAAO,SAAS,OAAO,CAAC;EACvB,eAAe,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AS,YACX,MAAM,IAAI,WACR,iCAAiC,WAAW,UAAU,MAAM,iEAC9D;CAEF,IAAI,QAAQ,UACV,MAAM,IAAI,WACR,2BAA2B,uBAAuB,iBAAiB,MAAM,aAAa,UACxF;CAOF,QAAO,MAJY,SAAS,SAAS,QAAQ,IAAI,OAAO,OAAO;EAC7D,WAAW;EACX,QAAQ;CACV,CAAC,EAAA,CACW,SAAS,YAAY;EAQ/B,OAAO,UAPK,MACV,SACA,eAAe,QAAQ,YAAY,GAAG,QAAQ,aAAa,GAC3D,QAAQ,IACR,QAAQ,UACR,UAEiB,GAAG,QAAQ,YAAY,QAAQ,aAAa;CACjE,CAAC;AACH"}
|
package/dist/ads/types.d.cts
CHANGED
package/dist/ads/types.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.cts","names":[],"sources":["../../src/ads/types.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"types.d.cts","names":[],"sources":["../../src/ads/types.ts"],"mappings":";;;YAGY;;;;;;;;;;;;;;iBAeK;;EAEf,UAAU;;EAEV;EACA;EACA;;EAEA;EACA;;;;;EAKA;EACA;EACA;EACA;EACA,eAAe;;EAEf;;EAEA;EACA;EACA;;;;;EAKA;;;;;EAKA;EACA;;EAEA;EACA;;;YAIU"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_attribution_vocabulary = require("./vocabulary.cjs");
|
|
3
2
|
const require_attribution_classify = require("./classify.cjs");
|
|
3
|
+
const require_attribution_vocabulary = require("./vocabulary.cjs");
|
|
4
4
|
exports.AD_LANDING_PAGE = require_attribution_vocabulary.AD_LANDING_PAGE;
|
|
5
5
|
exports.ANDROID_APP_HOSTS = require_attribution_vocabulary.ANDROID_APP_HOSTS;
|
|
6
6
|
exports.CHANNELS = require_attribution_vocabulary.CHANNELS;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { AD_LANDING_PAGE, ANDROID_APP_HOSTS, CHANNELS, CHANNEL_GROUPS, CLICK_ID_CHANNELS, Channel, ChannelGroup, DIRECT_CHANNEL, DISPLAY_MEDIUMS, EMAIL_MEDIUM, EMAIL_MEDIUMS, MEDIUM_NOT_SET, META_PLACEMENTS, NO_MEDIUM, PAID_MEDIUM, PUSH_MEDIUM, REFERRERS_NOT_A_TOUCH, REFERRER_SITES, REPORTED_TOUCH_KINDS, REPORTED_TOUCH_PRIORITY, ReferrerMedium, ReportedTouchKind, SOURCE_ALIASES, TOUCH_PRIORITY, TOUCH_SOURCES, TouchSource } from "./vocabulary.cjs";
|
|
2
1
|
import { ClassifyOptions, ProductTouch, Touch, TouchRule, channelGroupOf, classifyTouch } from "./classify.cjs";
|
|
2
|
+
import { AD_LANDING_PAGE, ANDROID_APP_HOSTS, CHANNELS, CHANNEL_GROUPS, CLICK_ID_CHANNELS, Channel, ChannelGroup, DIRECT_CHANNEL, DISPLAY_MEDIUMS, EMAIL_MEDIUM, EMAIL_MEDIUMS, MEDIUM_NOT_SET, META_PLACEMENTS, NO_MEDIUM, PAID_MEDIUM, PUSH_MEDIUM, REFERRERS_NOT_A_TOUCH, REFERRER_SITES, REPORTED_TOUCH_KINDS, REPORTED_TOUCH_PRIORITY, ReferrerMedium, ReportedTouchKind, SOURCE_ALIASES, TOUCH_PRIORITY, TOUCH_SOURCES, TouchSource } from "./vocabulary.cjs";
|
|
3
3
|
export { AD_LANDING_PAGE, ANDROID_APP_HOSTS, CHANNELS, CHANNEL_GROUPS, CLICK_ID_CHANNELS, Channel, ChannelGroup, ClassifyOptions, DIRECT_CHANNEL, DISPLAY_MEDIUMS, EMAIL_MEDIUM, EMAIL_MEDIUMS, MEDIUM_NOT_SET, META_PLACEMENTS, NO_MEDIUM, PAID_MEDIUM, PUSH_MEDIUM, ProductTouch, REFERRERS_NOT_A_TOUCH, REFERRER_SITES, REPORTED_TOUCH_KINDS, REPORTED_TOUCH_PRIORITY, ReferrerMedium, ReportedTouchKind, SOURCE_ALIASES, TOUCH_PRIORITY, TOUCH_SOURCES, Touch, TouchRule, TouchSource, channelGroupOf, classifyTouch };
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { AD_LANDING_PAGE, ANDROID_APP_HOSTS, CHANNELS, CHANNEL_GROUPS, CLICK_ID_CHANNELS, Channel, ChannelGroup, DIRECT_CHANNEL, DISPLAY_MEDIUMS, EMAIL_MEDIUM, EMAIL_MEDIUMS, MEDIUM_NOT_SET, META_PLACEMENTS, NO_MEDIUM, PAID_MEDIUM, PUSH_MEDIUM, REFERRERS_NOT_A_TOUCH, REFERRER_SITES, REPORTED_TOUCH_KINDS, REPORTED_TOUCH_PRIORITY, ReferrerMedium, ReportedTouchKind, SOURCE_ALIASES, TOUCH_PRIORITY, TOUCH_SOURCES, TouchSource } from "./vocabulary.mjs";
|
|
2
1
|
import { ClassifyOptions, ProductTouch, Touch, TouchRule, channelGroupOf, classifyTouch } from "./classify.mjs";
|
|
2
|
+
import { AD_LANDING_PAGE, ANDROID_APP_HOSTS, CHANNELS, CHANNEL_GROUPS, CLICK_ID_CHANNELS, Channel, ChannelGroup, DIRECT_CHANNEL, DISPLAY_MEDIUMS, EMAIL_MEDIUM, EMAIL_MEDIUMS, MEDIUM_NOT_SET, META_PLACEMENTS, NO_MEDIUM, PAID_MEDIUM, PUSH_MEDIUM, REFERRERS_NOT_A_TOUCH, REFERRER_SITES, REPORTED_TOUCH_KINDS, REPORTED_TOUCH_PRIORITY, ReferrerMedium, ReportedTouchKind, SOURCE_ALIASES, TOUCH_PRIORITY, TOUCH_SOURCES, TouchSource } from "./vocabulary.mjs";
|
|
3
3
|
export { AD_LANDING_PAGE, ANDROID_APP_HOSTS, CHANNELS, CHANNEL_GROUPS, CLICK_ID_CHANNELS, Channel, ChannelGroup, ClassifyOptions, DIRECT_CHANNEL, DISPLAY_MEDIUMS, EMAIL_MEDIUM, EMAIL_MEDIUMS, MEDIUM_NOT_SET, META_PLACEMENTS, NO_MEDIUM, PAID_MEDIUM, PUSH_MEDIUM, ProductTouch, REFERRERS_NOT_A_TOUCH, REFERRER_SITES, REPORTED_TOUCH_KINDS, REPORTED_TOUCH_PRIORITY, ReferrerMedium, ReportedTouchKind, SOURCE_ALIASES, TOUCH_PRIORITY, TOUCH_SOURCES, Touch, TouchRule, TouchSource, channelGroupOf, classifyTouch };
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { AD_LANDING_PAGE, ANDROID_APP_HOSTS, CHANNELS, CHANNEL_GROUPS, CLICK_ID_CHANNELS, DIRECT_CHANNEL, DISPLAY_MEDIUMS, EMAIL_MEDIUM, EMAIL_MEDIUMS, MEDIUM_NOT_SET, META_PLACEMENTS, NO_MEDIUM, PAID_MEDIUM, PUSH_MEDIUM, REFERRERS_NOT_A_TOUCH, REFERRER_SITES, REPORTED_TOUCH_KINDS, REPORTED_TOUCH_PRIORITY, SOURCE_ALIASES, TOUCH_PRIORITY, TOUCH_SOURCES } from "./vocabulary.mjs";
|
|
2
1
|
import { channelGroupOf, classifyTouch } from "./classify.mjs";
|
|
2
|
+
import { AD_LANDING_PAGE, ANDROID_APP_HOSTS, CHANNELS, CHANNEL_GROUPS, CLICK_ID_CHANNELS, DIRECT_CHANNEL, DISPLAY_MEDIUMS, EMAIL_MEDIUM, EMAIL_MEDIUMS, MEDIUM_NOT_SET, META_PLACEMENTS, NO_MEDIUM, PAID_MEDIUM, PUSH_MEDIUM, REFERRERS_NOT_A_TOUCH, REFERRER_SITES, REPORTED_TOUCH_KINDS, REPORTED_TOUCH_PRIORITY, SOURCE_ALIASES, TOUCH_PRIORITY, TOUCH_SOURCES } from "./vocabulary.mjs";
|
|
3
3
|
export { AD_LANDING_PAGE, ANDROID_APP_HOSTS, CHANNELS, CHANNEL_GROUPS, CLICK_ID_CHANNELS, DIRECT_CHANNEL, DISPLAY_MEDIUMS, EMAIL_MEDIUM, EMAIL_MEDIUMS, MEDIUM_NOT_SET, META_PLACEMENTS, NO_MEDIUM, PAID_MEDIUM, PUSH_MEDIUM, REFERRERS_NOT_A_TOUCH, REFERRER_SITES, REPORTED_TOUCH_KINDS, REPORTED_TOUCH_PRIORITY, SOURCE_ALIASES, TOUCH_PRIORITY, TOUCH_SOURCES, channelGroupOf, classifyTouch };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["parseCookie","stringifySetCookie","cookie"],"sources":["../../src/click-id/index.ts"],"sourcesContent":["import { type SetCookie, parseCookie, stringifySetCookie } from 'cookie';\n\n/**\n * Server-side resolution of ad-click-id cookies (`_fbc`, `_gcl_aw`/`_gcl_gb`, `_rdt_cid`,\n * `_uetmsclkid`) from the incoming request.\n *\n * This is the framework-agnostic core meant to run on the *document* response (e.g. TanStack Start\n * server middleware, Next middleware). Setting `_fbc` via an HTTP `Set-Cookie` header on the top\n * document — rather than `document.cookie` on the client — is what Meta officially recommends and is\n * the only reliable way to keep the cookie alive for 90 days in Safari: ITP caps JavaScript-set\n * cookies on a fbclid-decorated landing page to 24 hours, and the document response is never\n * classified as CNAME/IP cloaking (it is the reference the browser measures cloaking against).\n *\n * The Google pair follows the same architecture Google itself ships for server containers —\n * sGTM's Conversion Linker sets FPGCLAW via Set-Cookie for 90 days — and the sGTM ecosystem\n * productized for gtag's own cookies (stape Cookie Keeper re-issues `_gcl_*` over HTTP; vendor\n * case studies report 5–20% of Google Ads conversions recovered, up to +44% on the Safari\n * slice). One deployment caveat from WebKit's rules: the HTTP-cookie exemption holds only for\n * responses from the site's own infrastructure — a CNAME or third-party-IP host (a tagging\n * subdomain on someone else's cloud) gets its Set-Cookie silently capped to 7 days. This module\n * runs on the host's own document response, which is exactly the exempt case.\n *\n * references:\n * - https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/fbp-and-fbc\n * - https://webkit.org/tracking-prevention/ (7d JS cookies, 24h on ad-decorated landings,\n * CNAME/third-party-IP HTTP cookies capped to 7d, same-origin HTTP cookies exempt)\n * - https://www.simoahava.com/analytics/google-ads-server-side-tagging-google-tag-manager/\n * (Conversion Linker → FPGCLAW via Set-Cookie, Google's own server-side equivalent)\n * - https://stape.io/helpdesk/documentation/cookie-keeper-power-up (the productized re-issue)\n */\n\n// Meta's recommended _fbc cookie expiry. Events Manager warns (\"Server sending expired fbclid\")\n// when the embedded creationTime is older than 90 days and match quality/attribution may degrade;\n// no hard drop is documented.\nconst FBC_TTL_MS = 90 * 24 * 60 * 60 * 1000;\n// Reddit's pixel.js rewrites `_rdt_cid` and `_rdt_uuid` for 90 days on every page load.\nconst RDT_CID_TTL_MS = 90 * 24 * 60 * 60 * 1000;\nconst RDT_UUID_TTL_MS = 90 * 24 * 60 * 60 * 1000;\n// Meta's pixel rewrites `_fbp` for 90 days on every page load.\nconst FBP_TTL_MS = 90 * 24 * 60 * 60 * 1000;\n// OpenAI's oaiq: `__oppref` for 30 days (`720*60*60` s), `__obref` for 365 days.\nconst OPPREF_TTL_MS = 30 * 24 * 60 * 60 * 1000;\nconst OBREF_TTL_MS = 365 * 24 * 60 * 60 * 1000;\n// bat.js's own expiry for _uetmsclkid (`msClkIdExpirationTime`), the Microsoft Ads click window.\nconst MSCLKID_TTL_MS = 90 * 24 * 60 * 60 * 1000;\n// gtag's own expiry for _gcl_* — 90 days, the length of a Google Ads click's upload window.\nconst GCL_TTL_MS = 90 * 24 * 60 * 60 * 1000;\n// Tolerate a little clock skew when validating a creationTime against \"now\".\nconst CLOCK_SKEW_MS = 24 * 60 * 60 * 1000;\n\nexport const FBC_COOKIE = '_fbc';\nexport const RDT_CID_COOKIE = '_rdt_cid';\nexport const GCL_AW_COOKIE = '_gcl_aw';\nexport const GCL_GB_COOKIE = '_gcl_gb';\nexport const UET_MSCLKID_COOKIE = '_uetmsclkid';\nexport const RDT_UUID_COOKIE = '_rdt_uuid';\nexport const FBP_COOKIE = '_fbp';\nexport const OPPREF_COOKIE = '__oppref';\nexport const OBREF_COOKIE = '__obref';\n/** OpenAI's consent cookie; `false` is the visitor's opt-out, on which oaiq deletes its cookies. */\nexport const OAIQ_CONSENT_COOKIE = '__oaiq_consent';\n\nexport type ParsedFbc = { raw: string; creationTime: number; fbclid: string };\n\n/**\n * Parse `fb.<subdomainIndex>.<creationTime>.<fbclid>[.<appendix>]`. The appendix is what Meta's\n * Parameter Builder adds to the values it writes (\"an appendix field at the end of each\n * parameter\"); it is not part of the click id, so `fbclid` is the fourth segment alone and the\n * value is passed on as `raw`, unchanged. Returns undefined for anything malformed.\n * ref: https://developers.facebook.com/docs/marketing-api/conversions-api/parameter-builder-library\n */\nexport function parseFbc(\n raw: string | undefined | null,\n now: number = Date.now()\n): ParsedFbc | undefined {\n if (!raw) return undefined;\n const parts = raw.split('.');\n if (parts.length < 4 || parts.length > 5 || parts[0] !== 'fb') return undefined;\n if (parts.length === 5 && !parts[4]) return undefined;\n\n const creationTime = Number(parts[2]);\n const fbclid = parts[3];\n if (!fbclid) return undefined;\n // creationTime is UNIX ms; reject seconds-precision or future-dated values as malformed.\n if (!Number.isFinite(creationTime)) return undefined;\n if (creationTime < 1e12 || creationTime > now + CLOCK_SKEW_MS) return undefined;\n\n return { raw, creationTime, fbclid };\n}\n\n/**\n * Build a fresh `_fbc` value. subdomainIndex is the cookie's domain level (com=0, example.com=1,\n * www.example.com=2); 1 is correct for an apex-hosted cookie.\n */\nexport function formatFbc(fbclid: string, now: number, subdomainIndex = 1): string {\n return `fb.${subdomainIndex}.${now}.${fbclid}`;\n}\n\nexport type ParsedGcl = { raw: string; creationTime: number; clickId: string };\n\n/**\n * Whether a URL's `gclid` is a Google Ads click, by its `gclsrc` — gtag's own gating: absent or\n * `aw.ds` is Google Ads; `ds` / `3p.ds` are Search Ads 360's (a click on another engine, or on\n * Google with auto-tagging off), which gtag keeps in `_gcl_dc` and not `_gcl_aw`.\n * ref: https://support.google.com/sa360/answer/7342044\n */\nexport function isGoogleAdsGclid(gclsrc: string | null | undefined): boolean {\n return !gclsrc || gclsrc === 'aw.ds';\n}\n\n// gtag's own value validator, extracted from the live gtag.js bundle (2026-09): its parser\n// accepts version \"GCL\" or \"1\", a /^\\d+$/ seconds timestamp, and a click id matching this.\n// Re-verify against gtag.js before changing anything here — the format is gtag's, not ours.\nconst GCL_CLICK_ID = /^[\\w-]+$/;\n\n/**\n * Parse a `_gcl_aw`/`_gcl_gb` value: `GCL.<seconds>.<clickId>[.<labels…>]` — note the timestamp\n * is in SECONDS, unlike `_fbc`'s milliseconds. gtag's parser accepts version `GCL` or `1` and\n * validates the segments exactly this way (`/^\\d+$/` timestamp, `/^[\\w-]+$/` click id); any\n * labels tail is preserved through `raw` so a re-issue stays byte-identical.\n */\nexport function parseGcl(\n raw: string | undefined | null,\n now: number = Date.now()\n): ParsedGcl | undefined {\n if (!raw) return undefined;\n const parts = raw.split('.');\n if (parts.length < 3) return undefined;\n if (parts[0] !== 'GCL' && parts[0] !== '1') return undefined;\n const seconds = parts[1];\n const clickId = parts[2];\n if (!/^\\d+$/.test(seconds)) return undefined;\n if (!GCL_CLICK_ID.test(clickId)) return undefined;\n const creationTime = Number(seconds) * 1000;\n // Reject millisecond-precision or future-dated values as malformed.\n if (creationTime >= 1e15 || creationTime > now + CLOCK_SKEW_MS) return undefined;\n return { raw, creationTime, clickId };\n}\n\n/** Build a fresh `_gcl_aw`/`_gcl_gb` value in gtag's own format. */\nexport function formatGcl(clickId: string, now: number): string {\n return `GCL.${Math.floor(now / 1000)}.${clickId}`;\n}\n\n// bat.js writes the click id as `_uet<msclkid>` and reads it back only when what follows the\n// prefix is at most 32 characters (`msClkIdCookieValuePrefix`, `lengthMsClkId`); a msclkid is a\n// 32-hex-digit UUID without dashes. Re-verify against bat.js before changing anything here —\n// the format is UET's, not ours.\nconst UET_MSCLKID_PREFIX = '_uet';\nconst MSCLKID = /^[0-9a-f]{32}$/i;\n\n/** Whether a value has the shape of a Microsoft click id: 32 hex digits, no dashes. */\nexport function isMsclkid(value: string | null | undefined): value is string {\n return !!value && MSCLKID.test(value);\n}\n\n/**\n * Parse a `_uetmsclkid` value: `_uet<32 hex>`. Returns the click id, lowercased, or undefined\n * for anything bat.js itself would not read back.\n */\nexport function parseUetMsclkid(raw: string | undefined | null): string | undefined {\n if (!raw || !raw.startsWith(UET_MSCLKID_PREFIX)) return undefined;\n const clickId = raw.slice(UET_MSCLKID_PREFIX.length);\n return MSCLKID.test(clickId) ? clickId.toLowerCase() : undefined;\n}\n\n/** Build a `_uetmsclkid` value in bat.js's own format. */\nexport function formatUetMsclkid(clickId: string): string {\n return `${UET_MSCLKID_PREFIX}${clickId.toLowerCase()}`;\n}\n\n/**\n * The click id as the Conversions API wants it: a dashed, lowercase UUID. The URL and the cookie\n * carry the 32-hex form; a value in any other shape is returned untouched for the API to judge.\n */\nexport function formatMsclkid(clickId: string): string {\n const id = clickId.trim().toLowerCase();\n if (!MSCLKID.test(id)) return id;\n return `${id.slice(0, 8)}-${id.slice(8, 12)}-${id.slice(12, 16)}-${id.slice(16, 20)}-${id.slice(20)}`;\n}\n\nexport type ResolveClickIdCookiesInput = {\n /** The absolute request URL (must include the query string). */\n url: string;\n /** The raw `Cookie` request header, if any. */\n cookieHeader?: string | null;\n /** Overridable clock, primarily for tests. Defaults to `Date.now()`. */\n now?: number;\n /**\n * `Domain` attribute for the emitted cookies: the site's registrable domain, e.g.\n * `.shware.io`, where the pixels write theirs. Required in production: a host-only cookie is a\n * second cookie of the same name next to the pixel's, which the pixel then reads — or deletes,\n * as Reddit's does at every subdomain level before writing its own. `null` for a host-only\n * cookie, which only a local `localhost` setup should ask for.\n */\n domain: string | null;\n /** `Secure` attribute, default true. Set false only for local http testing. */\n secure?: boolean;\n /** subdomainIndex for a freshly built `_fbc` (see {@link formatFbc}). Default 1. */\n subdomainIndex?: number;\n /**\n * Re-issue the stored click and browser ids on every call. On by default, as an ITP self-heal:\n * cookies follow last-writer-wins, so when a pixel has rewritten one through `document.cookie`\n * (Safari caps JS-written cookies at 7 days, 24h on an ad-decorated landing), re-issuing the\n * long-lived HTTP cookie on the next navigation restores it — the same continuous-re-issue\n * mitigation the sGTM ecosystem uses (stape Cookie Keeper, Cookie Monster). `_fbc` and\n * `_gcl_*` are re-issued byte-for-byte at their *remaining* lifetime, so their window never\n * slides (Meta warns on a moved fbclid); the others at the lifetime their pixel itself gives\n * them on every page load (see each below).\n *\n * Set false to strictly follow Meta's documented conditional-write rule (\"only set the cookie if\n * it doesn't exist or the fbclid changed\") — e.g. to keep pages CDN-cacheable, since the\n * re-issue attaches a per-user `Set-Cookie` (forcing `no-store`) to every response carrying an\n * `_fbc`.\n */\n refresh?: boolean;\n};\n\nexport type ResolveClickIdCookiesResult = {\n /**\n * Cookies to emit on the response, ready for `Set-Cookie`. Empty when nothing needs to change.\n * A `value: ''`, `maxAge: 0` entry is a deletion (an expired or malformed leftover).\n */\n cookies: SetCookie[];\n /** The resolved `_fbc` value, for immediate server-side use (e.g. Conversions API). */\n fbc?: string;\n /** The resolved `_rdt_cid` value. */\n rdt_cid?: string;\n /** The resolved Google Ads click id (from the URL or a still-valid `_gcl_aw`). */\n gclid?: string;\n /** The resolved iOS web-to-app click id (from the URL or a still-valid `_gcl_gb`). */\n wbraid?: string;\n /** The resolved Microsoft Ads click id (from the URL or `_uetmsclkid`), 32-hex form. */\n msclkid?: string;\n};\n\nfunction searchParams(url: string): URLSearchParams {\n try {\n return new URL(url).searchParams;\n } catch {\n // Fall back to a manual split so a relative or slightly malformed URL still yields the query.\n const q = url.indexOf('?');\n return new URLSearchParams(q !== -1 ? url.slice(q + 1) : '');\n }\n}\n\n/**\n * Resolve the click-id cookies to set on the current document response.\n *\n * `_fbc` follows Meta's documented conditional-write rule value-wise: a new fbclid (or an absent\n * cookie) opens a fresh 90-day window; a same-fbclid cookie keeps its original value and\n * `creationTime`. Expired (>90d) or malformed values are cleared instead of forwarded. By default,\n * ({@link ResolveClickIdCookiesInput.refresh}) a still-valid cookie is re-issued unchanged at its\n * *remaining* lifetime — never `now + 90d` — so a returning visitor's window cannot slide forward\n * (which is what makes Meta flag an expired fbclid).\n */\nexport function resolveClickIdCookies(\n input: ResolveClickIdCookiesInput\n): ResolveClickIdCookiesResult {\n const { url, cookieHeader, domain, secure = true, subdomainIndex = 1, refresh = true } = input;\n const now = input.now ?? Date.now();\n\n const params = searchParams(url);\n const jar = parseCookie(cookieHeader ?? '');\n const cookies: SetCookie[] = [];\n const result: ResolveClickIdCookiesResult = { cookies };\n\n const base = { path: '/', secure, sameSite: 'lax', domain: domain ?? undefined } as const;\n const set = (name: string, value: string, ttlMs: number) =>\n cookies.push({ name, value, maxAge: Math.floor(ttlMs / 1000), ...base });\n const del = (name: string) => cookies.push({ name, value: '', maxAge: 0, ...base });\n\n // --- Meta _fbc ---\n const urlFbclid = params.get('fbclid') || undefined;\n const existingFbc = parseFbc(jar[FBC_COOKIE], now);\n\n if (urlFbclid && urlFbclid !== existingFbc?.fbclid) {\n // A new click always wins and opens a fresh 90-day window.\n const raw = formatFbc(urlFbclid, now, subdomainIndex);\n set(FBC_COOKIE, raw, FBC_TTL_MS);\n result.fbc = raw;\n } else if (existingFbc) {\n const remainingMs = existingFbc.creationTime + FBC_TTL_MS - now;\n if (remainingMs <= 0) {\n del(FBC_COOKIE);\n } else {\n // Same fbclid: the value and creationTime are preserved (Meta's rule); refresh (default)\n // re-issues it unchanged at its remaining lifetime as an ITP self-heal.\n result.fbc = existingFbc.raw;\n if (refresh) set(FBC_COOKIE, existingFbc.raw, remainingMs);\n }\n } else if (jar[FBC_COOKIE]) {\n // Malformed leftover — clear it rather than forwarding it to Meta.\n del(FBC_COOKIE);\n }\n\n // --- Google Ads _gcl_aw / _gcl_gb ---\n // The same first-party HTTP persistence Google's own server-side Conversion Linker performs\n // (it sets FPGCLAW via Set-Cookie for 90 days), applied to gtag's cookies the way the sGTM\n // ecosystem does (stape Cookie Keeper re-issues _gcl_* over HTTP). Ownership is shared with\n // gtag, so the rules are stricter than for _fbc: a value this module cannot parse is left\n // untouched — never rewritten, never deleted — and a re-issue is byte-identical (labels tail\n // included) at the window's REMAINING lifetime, so the 90-day click window never slides.\n const gclsrc = params.get('gclsrc') || undefined;\n const google = [\n {\n cookie: GCL_AW_COOKIE,\n // gtag's own gating (`isGoogleAdsGclid`): a gclid enters _gcl_aw only when gclsrc is\n // absent or 'aw.ds' — 'ds'/'3p.ds' clicks are Search Ads 360's and belong to _gcl_dc.\n urlClickId: isGoogleAdsGclid(gclsrc) ? params.get('gclid') || undefined : undefined,\n assign: (value: string) => (result.gclid = value),\n },\n {\n cookie: GCL_GB_COOKIE,\n urlClickId: params.get('wbraid') || undefined,\n assign: (value: string) => (result.wbraid = value),\n },\n ];\n for (const { cookie, urlClickId, assign } of google) {\n const existing = parseGcl(jar[cookie], now);\n if (urlClickId && GCL_CLICK_ID.test(urlClickId) && urlClickId !== existing?.clickId) {\n // A new click always wins and opens a fresh 90-day window, in gtag's exact format.\n set(cookie, formatGcl(urlClickId, now), GCL_TTL_MS);\n assign(urlClickId);\n } else if (existing) {\n const remainingMs = existing.creationTime + GCL_TTL_MS - now;\n if (remainingMs > 0) {\n assign(existing.clickId);\n if (refresh) set(cookie, existing.raw, remainingMs);\n }\n // Expired: not returned and not re-issued, but gtag owns the deletion.\n }\n }\n\n // --- Reddit _rdt_cid / _rdt_uuid ---\n // Reddit's pixel.js rewrites both on every page load through `document.cookie` — the click id\n // from the URL, else the stored one, and the browser id — each for a fresh 90 days. So Reddit\n // slides the window itself, and the re-issue (default on, see `refresh`) does the same over\n // HTTP: without it the pixel's JS copy, capped at 7 days in Safari, is the only one left.\n const urlRdtCid = params.get('rdt_cid') || undefined;\n const existingRdtCid = jar[RDT_CID_COOKIE] || undefined;\n if (urlRdtCid && urlRdtCid !== existingRdtCid) {\n set(RDT_CID_COOKIE, urlRdtCid, RDT_CID_TTL_MS);\n result.rdt_cid = urlRdtCid;\n } else if (existingRdtCid) {\n result.rdt_cid = existingRdtCid;\n if (refresh) set(RDT_CID_COOKIE, existingRdtCid, RDT_CID_TTL_MS);\n }\n const existingRdtUuid = jar[RDT_UUID_COOKIE] || undefined;\n if (existingRdtUuid && refresh) set(RDT_UUID_COOKIE, existingRdtUuid, RDT_UUID_TTL_MS);\n\n // --- Meta _fbp ---\n // The pixel's browser id: created by the pixel, which rewrites it for 90 days on every page\n // load, as Reddit's does its own. Re-issued as it is, never created here.\n const existingFbp = jar[FBP_COOKIE] || undefined;\n if (existingFbp && refresh) set(FBP_COOKIE, existingFbp, FBP_TTL_MS);\n\n // --- OpenAI __oppref / __obref ---\n // oaiq writes `__oppref` only when the URL carries `oppref` (30 days), and `__obref` — its\n // browser reference — only when there is none (365 days); otherwise it reads them, through\n // `document.cookie`, so in Safari each is gone after 7 days and the browser starts over with a\n // new reference. The first is captured here from the URL as well, and both are re-issued as\n // they are, `__obref` never created. Unlike oaiq, the re-issue restarts their windows: their\n // values carry no creation time to count a remaining lifetime from, and OpenAI applies its own\n // attribution window to the click whatever the cookie's age. Nothing is written once the\n // visitor has opted out of oaiq, which deletes both cookies then.\n if (jar[OAIQ_CONSENT_COOKIE] !== 'false') {\n const urlOppref = params.get('oppref') || undefined;\n const existingOppref = jar[OPPREF_COOKIE] || undefined;\n if (urlOppref) set(OPPREF_COOKIE, urlOppref, OPPREF_TTL_MS);\n else if (existingOppref && refresh) set(OPPREF_COOKIE, existingOppref, OPPREF_TTL_MS);\n const existingObref = jar[OBREF_COOKIE] || undefined;\n if (existingObref && refresh) set(OBREF_COOKIE, existingObref, OBREF_TTL_MS);\n }\n\n // --- Microsoft Ads _uetmsclkid ---\n // The UET tag's own cookie, in its own format, so the tag and this module read each other's\n // writes. Microsoft's ITP answer is this first-party cookie (plus a localStorage backup), but\n // bat.js writes it through `document.cookie`, which Safari caps at 7 days — 24 hours on a\n // landing page decorated by a classified domain, and a bing.com ad click is exactly that.\n // Persisting it here over HTTP on the document response restores the 90-day window.\n //\n // The re-issue (default on, see `refresh`) is the same self-heal as for `_fbc`, and it matters\n // more here: bat.js rewrites this cookie on EVERY page load, so without the re-issue the HTTP\n // copy is downgraded to a JS cookie on the very next page. There is no embedded timestamp to\n // compute a remaining lifetime from, so it is re-issued at a fresh 90 days — which is exactly\n // what bat.js itself does on each page (`msClkIdExpirationTime` from now), so the window\n // slides no more than the tag already slides it. A value this module cannot parse belongs to\n // the tag: never rewritten, never deleted.\n const urlMsclkid = params.get('msclkid')?.trim();\n const existingMsclkid = parseUetMsclkid(jar[UET_MSCLKID_COOKIE]);\n if (urlMsclkid && MSCLKID.test(urlMsclkid) && urlMsclkid.toLowerCase() !== existingMsclkid) {\n set(UET_MSCLKID_COOKIE, formatUetMsclkid(urlMsclkid), MSCLKID_TTL_MS);\n result.msclkid = urlMsclkid.toLowerCase();\n } else if (existingMsclkid) {\n result.msclkid = existingMsclkid;\n if (refresh) set(UET_MSCLKID_COOKIE, formatUetMsclkid(existingMsclkid), MSCLKID_TTL_MS);\n }\n\n return result;\n}\n\n/** Serialize the resolved cookies into `Set-Cookie` header values. */\nexport function toSetCookieHeaders(cookies: SetCookie[]): string[] {\n return cookies.map((cookie) => stringifySetCookie(cookie));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAM,aAAa;AAEnB,MAAM,iBAAiB;AACvB,MAAM,kBAAkB;AAExB,MAAM,aAAa;AAEnB,MAAM,gBAAgB;AACtB,MAAM,eAAe;AAErB,MAAM,iBAAiB;AAEvB,MAAM,aAAa;AAEnB,MAAM,gBAAgB;AAEtB,MAAa,aAAa;AAC1B,MAAa,iBAAiB;AAC9B,MAAa,gBAAgB;AAC7B,MAAa,gBAAgB;AAC7B,MAAa,qBAAqB;AAClC,MAAa,kBAAkB;AAC/B,MAAa,aAAa;AAC1B,MAAa,gBAAgB;AAC7B,MAAa,eAAe;;AAE5B,MAAa,sBAAsB;;;;;;;;AAWnC,SAAgB,SACd,KACA,MAAc,KAAK,IAAI,GACA;CACvB,IAAI,CAAC,KAAK,OAAO,KAAA;CACjB,MAAM,QAAQ,IAAI,MAAM,GAAG;CAC3B,IAAI,MAAM,SAAS,KAAK,MAAM,SAAS,KAAK,MAAM,OAAO,MA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SAAS,IAAI,oBAAoB,iBAAiB,eAAe,GAAG,cAAc;CACxF;CAEA,OAAO;AACT;;AAGA,SAAgB,mBAAmB,SAAgC;CACjE,OAAO,QAAQ,KAAK,cAAA,GAAWC,OAAAA,mBAAAA,CAAmBC,QAAM,CAAC;AAC3D"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["parseCookie","cookie","stringifySetCookie"],"sources":["../../src/click-id/index.ts"],"sourcesContent":["import { type SetCookie, parseCookie, stringifySetCookie } from 'cookie';\n\n/**\n * Server-side resolution of ad-click-id cookies (`_fbc`, `_gcl_aw`/`_gcl_gb`, `_rdt_cid`,\n * `_uetmsclkid`) from the incoming request.\n *\n * This is the framework-agnostic core meant to run on the *document* response (e.g. TanStack Start\n * server middleware, Next middleware). Setting `_fbc` via an HTTP `Set-Cookie` header on the top\n * document — rather than `document.cookie` on the client — is what Meta officially recommends and is\n * the only reliable way to keep the cookie alive for 90 days in Safari: ITP caps JavaScript-set\n * cookies on a fbclid-decorated landing page to 24 hours, and the document response is never\n * classified as CNAME/IP cloaking (it is the reference the browser measures cloaking against).\n *\n * The Google pair follows the same architecture Google itself ships for server containers —\n * sGTM's Conversion Linker sets FPGCLAW via Set-Cookie for 90 days — and the sGTM ecosystem\n * productized for gtag's own cookies (stape Cookie Keeper re-issues `_gcl_*` over HTTP; vendor\n * case studies report 5–20% of Google Ads conversions recovered, up to +44% on the Safari\n * slice). One deployment caveat from WebKit's rules: the HTTP-cookie exemption holds only for\n * responses from the site's own infrastructure — a CNAME or third-party-IP host (a tagging\n * subdomain on someone else's cloud) gets its Set-Cookie silently capped to 7 days. This module\n * runs on the host's own document response, which is exactly the exempt case.\n *\n * references:\n * - https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/fbp-and-fbc\n * - https://webkit.org/tracking-prevention/ (7d JS cookies, 24h on ad-decorated landings,\n * CNAME/third-party-IP HTTP cookies capped to 7d, same-origin HTTP cookies exempt)\n * - https://www.simoahava.com/analytics/google-ads-server-side-tagging-google-tag-manager/\n * (Conversion Linker → FPGCLAW via Set-Cookie, Google's own server-side equivalent)\n * - https://stape.io/helpdesk/documentation/cookie-keeper-power-up (the productized re-issue)\n */\n\n// Meta's recommended _fbc cookie expiry. Events Manager warns (\"Server sending expired fbclid\")\n// when the embedded creationTime is older than 90 days and match quality/attribution may degrade;\n// no hard drop is documented.\nconst FBC_TTL_MS = 90 * 24 * 60 * 60 * 1000;\n// Reddit's pixel.js rewrites `_rdt_cid` and `_rdt_uuid` for 90 days on every page load.\nconst RDT_CID_TTL_MS = 90 * 24 * 60 * 60 * 1000;\nconst RDT_UUID_TTL_MS = 90 * 24 * 60 * 60 * 1000;\n// Meta's pixel rewrites `_fbp` for 90 days on every page load.\nconst FBP_TTL_MS = 90 * 24 * 60 * 60 * 1000;\n// OpenAI's oaiq: `__oppref` for 30 days (`720*60*60` s), `__obref` for 365 days.\nconst OPPREF_TTL_MS = 30 * 24 * 60 * 60 * 1000;\nconst OBREF_TTL_MS = 365 * 24 * 60 * 60 * 1000;\n// bat.js's own expiry for _uetmsclkid (`msClkIdExpirationTime`), the Microsoft Ads click window.\nconst MSCLKID_TTL_MS = 90 * 24 * 60 * 60 * 1000;\n// gtag's own expiry for _gcl_* — 90 days, the length of a Google Ads click's upload window.\nconst GCL_TTL_MS = 90 * 24 * 60 * 60 * 1000;\n// Tolerate a little clock skew when validating a creationTime against \"now\".\nconst CLOCK_SKEW_MS = 24 * 60 * 60 * 1000;\n\nexport const FBC_COOKIE = '_fbc';\nexport const RDT_CID_COOKIE = '_rdt_cid';\nexport const GCL_AW_COOKIE = '_gcl_aw';\nexport const GCL_GB_COOKIE = '_gcl_gb';\nexport const UET_MSCLKID_COOKIE = '_uetmsclkid';\nexport const RDT_UUID_COOKIE = '_rdt_uuid';\nexport const FBP_COOKIE = '_fbp';\nexport const OPPREF_COOKIE = '__oppref';\nexport const OBREF_COOKIE = '__obref';\n/** OpenAI's consent cookie; `false` is the visitor's opt-out, on which oaiq deletes its cookies. */\nexport const OAIQ_CONSENT_COOKIE = '__oaiq_consent';\n\nexport type ParsedFbc = { raw: string; creationTime: number; fbclid: string };\n\n/**\n * Parse `fb.<subdomainIndex>.<creationTime>.<fbclid>[.<appendix>]`. The appendix is what Meta's\n * Parameter Builder adds to the values it writes (\"an appendix field at the end of each\n * parameter\"); it is not part of the click id, so `fbclid` is the fourth segment alone and the\n * value is passed on as `raw`, unchanged. Returns undefined for anything malformed.\n * ref: https://developers.facebook.com/docs/marketing-api/conversions-api/parameter-builder-library\n */\nexport function parseFbc(\n raw: string | undefined | null,\n now: number = Date.now()\n): ParsedFbc | undefined {\n if (!raw) return undefined;\n const parts = raw.split('.');\n if (parts.length < 4 || parts.length > 5 || parts[0] !== 'fb') return undefined;\n if (parts.length === 5 && !parts[4]) return undefined;\n\n const creationTime = Number(parts[2]);\n const fbclid = parts[3];\n if (!fbclid) return undefined;\n // creationTime is UNIX ms; reject seconds-precision or future-dated values as malformed.\n if (!Number.isFinite(creationTime)) return undefined;\n if (creationTime < 1e12 || creationTime > now + CLOCK_SKEW_MS) return undefined;\n\n return { raw, creationTime, fbclid };\n}\n\n/**\n * Build a fresh `_fbc` value. subdomainIndex is the cookie's domain level (com=0, example.com=1,\n * www.example.com=2); 1 is correct for an apex-hosted cookie.\n */\nexport function formatFbc(fbclid: string, now: number, subdomainIndex = 1): string {\n return `fb.${subdomainIndex}.${now}.${fbclid}`;\n}\n\nexport type ParsedGcl = { raw: string; creationTime: number; clickId: string };\n\n/**\n * Whether a URL's `gclid` is a Google Ads click, by its `gclsrc` — gtag's own gating: absent or\n * `aw.ds` is Google Ads; `ds` / `3p.ds` are Search Ads 360's (a click on another engine, or on\n * Google with auto-tagging off), which gtag keeps in `_gcl_dc` and not `_gcl_aw`.\n * ref: https://support.google.com/sa360/answer/7342044\n */\nexport function isGoogleAdsGclid(gclsrc: string | null | undefined): boolean {\n return !gclsrc || gclsrc === 'aw.ds';\n}\n\n// gtag's own value validator, extracted from the live gtag.js bundle (2026-09): its parser\n// accepts version \"GCL\" or \"1\", a /^\\d+$/ seconds timestamp, and a click id matching this.\n// Re-verify against gtag.js before changing anything here — the format is gtag's, not ours.\nconst GCL_CLICK_ID = /^[\\w-]+$/;\n\n/**\n * Parse a `_gcl_aw`/`_gcl_gb` value: `GCL.<seconds>.<clickId>[.<labels…>]` — note the timestamp\n * is in SECONDS, unlike `_fbc`'s milliseconds. gtag's parser accepts version `GCL` or `1` and\n * validates the segments exactly this way (`/^\\d+$/` timestamp, `/^[\\w-]+$/` click id); any\n * labels tail is preserved through `raw` so a re-issue stays byte-identical.\n */\nexport function parseGcl(\n raw: string | undefined | null,\n now: number = Date.now()\n): ParsedGcl | undefined {\n if (!raw) return undefined;\n const parts = raw.split('.');\n if (parts.length < 3) return undefined;\n if (parts[0] !== 'GCL' && parts[0] !== '1') return undefined;\n const seconds = parts[1];\n const clickId = parts[2];\n if (!/^\\d+$/.test(seconds)) return undefined;\n if (!GCL_CLICK_ID.test(clickId)) return undefined;\n const creationTime = Number(seconds) * 1000;\n // Reject millisecond-precision or future-dated values as malformed.\n if (creationTime >= 1e15 || creationTime > now + CLOCK_SKEW_MS) return undefined;\n return { raw, creationTime, clickId };\n}\n\n/** Build a fresh `_gcl_aw`/`_gcl_gb` value in gtag's own format. */\nexport function formatGcl(clickId: string, now: number): string {\n return `GCL.${Math.floor(now / 1000)}.${clickId}`;\n}\n\n// bat.js writes the click id as `_uet<msclkid>` and reads it back only when what follows the\n// prefix is at most 32 characters (`msClkIdCookieValuePrefix`, `lengthMsClkId`); a msclkid is a\n// 32-hex-digit UUID without dashes. Re-verify against bat.js before changing anything here —\n// the format is UET's, not ours.\nconst UET_MSCLKID_PREFIX = '_uet';\nconst MSCLKID = /^[0-9a-f]{32}$/i;\n\n/** Whether a value has the shape of a Microsoft click id: 32 hex digits, no dashes. */\nexport function isMsclkid(value: string | null | undefined): value is string {\n return !!value && MSCLKID.test(value);\n}\n\n/**\n * Parse a `_uetmsclkid` value: `_uet<32 hex>`. Returns the click id, lowercased, or undefined\n * for anything bat.js itself would not read back.\n */\nexport function parseUetMsclkid(raw: string | undefined | null): string | undefined {\n if (!raw || !raw.startsWith(UET_MSCLKID_PREFIX)) return undefined;\n const clickId = raw.slice(UET_MSCLKID_PREFIX.length);\n return MSCLKID.test(clickId) ? clickId.toLowerCase() : undefined;\n}\n\n/** Build a `_uetmsclkid` value in bat.js's own format. */\nexport function formatUetMsclkid(clickId: string): string {\n return `${UET_MSCLKID_PREFIX}${clickId.toLowerCase()}`;\n}\n\n/**\n * The click id as the Conversions API wants it: a dashed, lowercase UUID. The URL and the cookie\n * carry the 32-hex form; a value in any other shape is returned untouched for the API to judge.\n */\nexport function formatMsclkid(clickId: string): string {\n const id = clickId.trim().toLowerCase();\n if (!MSCLKID.test(id)) return id;\n return `${id.slice(0, 8)}-${id.slice(8, 12)}-${id.slice(12, 16)}-${id.slice(16, 20)}-${id.slice(20)}`;\n}\n\nexport type ResolveClickIdCookiesInput = {\n /** The absolute request URL (must include the query string). */\n url: string;\n /** The raw `Cookie` request header, if any. */\n cookieHeader?: string | null;\n /** Overridable clock, primarily for tests. Defaults to `Date.now()`. */\n now?: number;\n /**\n * `Domain` attribute for the emitted cookies: the site's registrable domain, e.g.\n * `.shware.io`, where the pixels write theirs. Required in production: a host-only cookie is a\n * second cookie of the same name next to the pixel's, which the pixel then reads — or deletes,\n * as Reddit's does at every subdomain level before writing its own. `null` for a host-only\n * cookie, which only a local `localhost` setup should ask for.\n */\n domain: string | null;\n /** `Secure` attribute, default true. Set false only for local http testing. */\n secure?: boolean;\n /** subdomainIndex for a freshly built `_fbc` (see {@link formatFbc}). Default 1. */\n subdomainIndex?: number;\n /**\n * Re-issue the stored click and browser ids on every call. On by default, as an ITP self-heal:\n * cookies follow last-writer-wins, so when a pixel has rewritten one through `document.cookie`\n * (Safari caps JS-written cookies at 7 days, 24h on an ad-decorated landing), re-issuing the\n * long-lived HTTP cookie on the next navigation restores it — the same continuous-re-issue\n * mitigation the sGTM ecosystem uses (stape Cookie Keeper, Cookie Monster). `_fbc` and\n * `_gcl_*` are re-issued byte-for-byte at their *remaining* lifetime, so their window never\n * slides (Meta warns on a moved fbclid); the others at the lifetime their pixel itself gives\n * them on every page load (see each below).\n *\n * Set false to strictly follow Meta's documented conditional-write rule (\"only set the cookie if\n * it doesn't exist or the fbclid changed\") — e.g. to keep pages CDN-cacheable, since the\n * re-issue attaches a per-user `Set-Cookie` (forcing `no-store`) to every response carrying an\n * `_fbc`.\n */\n refresh?: boolean;\n};\n\nexport type ResolveClickIdCookiesResult = {\n /**\n * Cookies to emit on the response, ready for `Set-Cookie`. Empty when nothing needs to change.\n * A `value: ''`, `maxAge: 0` entry is a deletion (an expired or malformed leftover).\n */\n cookies: SetCookie[];\n /** The resolved `_fbc` value, for immediate server-side use (e.g. Conversions API). */\n fbc?: string;\n /** The resolved `_rdt_cid` value. */\n rdt_cid?: string;\n /** The resolved Google Ads click id (from the URL or a still-valid `_gcl_aw`). */\n gclid?: string;\n /** The resolved iOS web-to-app click id (from the URL or a still-valid `_gcl_gb`). */\n wbraid?: string;\n /** The resolved Microsoft Ads click id (from the URL or `_uetmsclkid`), 32-hex form. */\n msclkid?: string;\n};\n\nfunction searchParams(url: string): URLSearchParams {\n try {\n return new URL(url).searchParams;\n } catch {\n // Fall back to a manual split so a relative or slightly malformed URL still yields the query.\n const q = url.indexOf('?');\n return new URLSearchParams(q !== -1 ? url.slice(q + 1) : '');\n }\n}\n\n/**\n * Resolve the click-id cookies to set on the current document response.\n *\n * `_fbc` follows Meta's documented conditional-write rule value-wise: a new fbclid (or an absent\n * cookie) opens a fresh 90-day window; a same-fbclid cookie keeps its original value and\n * `creationTime`. Expired (>90d) or malformed values are cleared instead of forwarded. By default,\n * ({@link ResolveClickIdCookiesInput.refresh}) a still-valid cookie is re-issued unchanged at its\n * *remaining* lifetime — never `now + 90d` — so a returning visitor's window cannot slide forward\n * (which is what makes Meta flag an expired fbclid).\n */\nexport function resolveClickIdCookies(\n input: ResolveClickIdCookiesInput\n): ResolveClickIdCookiesResult {\n const { url, cookieHeader, domain, secure = true, subdomainIndex = 1, refresh = true } = input;\n const now = input.now ?? Date.now();\n\n const params = searchParams(url);\n const jar = parseCookie(cookieHeader ?? '');\n const cookies: SetCookie[] = [];\n const result: ResolveClickIdCookiesResult = { cookies };\n\n const base = { path: '/', secure, sameSite: 'lax', domain: domain ?? undefined } as const;\n const set = (name: string, value: string, ttlMs: number) =>\n cookies.push({ name, value, maxAge: Math.floor(ttlMs / 1000), ...base });\n const del = (name: string) => cookies.push({ name, value: '', maxAge: 0, ...base });\n\n // --- Meta _fbc ---\n const urlFbclid = params.get('fbclid') || undefined;\n const existingFbc = parseFbc(jar[FBC_COOKIE], now);\n\n if (urlFbclid && urlFbclid !== existingFbc?.fbclid) {\n // A new click always wins and opens a fresh 90-day window.\n const raw = formatFbc(urlFbclid, now, subdomainIndex);\n set(FBC_COOKIE, raw, FBC_TTL_MS);\n result.fbc = raw;\n } else if (existingFbc) {\n const remainingMs = existingFbc.creationTime + FBC_TTL_MS - now;\n if (remainingMs <= 0) {\n del(FBC_COOKIE);\n } else {\n // Same fbclid: the value and creationTime are preserved (Meta's rule); refresh (default)\n // re-issues it unchanged at its remaining lifetime as an ITP self-heal.\n result.fbc = existingFbc.raw;\n if (refresh) set(FBC_COOKIE, existingFbc.raw, remainingMs);\n }\n } else if (jar[FBC_COOKIE]) {\n // Malformed leftover — clear it rather than forwarding it to Meta.\n del(FBC_COOKIE);\n }\n\n // --- Google Ads _gcl_aw / _gcl_gb ---\n // The same first-party HTTP persistence Google's own server-side Conversion Linker performs\n // (it sets FPGCLAW via Set-Cookie for 90 days), applied to gtag's cookies the way the sGTM\n // ecosystem does (stape Cookie Keeper re-issues _gcl_* over HTTP). Ownership is shared with\n // gtag, so the rules are stricter than for _fbc: a value this module cannot parse is left\n // untouched — never rewritten, never deleted — and a re-issue is byte-identical (labels tail\n // included) at the window's REMAINING lifetime, so the 90-day click window never slides.\n const gclsrc = params.get('gclsrc') || undefined;\n const google = [\n {\n cookie: GCL_AW_COOKIE,\n // gtag's own gating (`isGoogleAdsGclid`): a gclid enters _gcl_aw only when gclsrc is\n // absent or 'aw.ds' — 'ds'/'3p.ds' clicks are Search Ads 360's and belong to _gcl_dc.\n urlClickId: isGoogleAdsGclid(gclsrc) ? params.get('gclid') || undefined : undefined,\n assign: (value: string) => (result.gclid = value),\n },\n {\n cookie: GCL_GB_COOKIE,\n urlClickId: params.get('wbraid') || undefined,\n assign: (value: string) => (result.wbraid = value),\n },\n ];\n for (const { cookie, urlClickId, assign } of google) {\n const existing = parseGcl(jar[cookie], now);\n if (urlClickId && GCL_CLICK_ID.test(urlClickId) && urlClickId !== existing?.clickId) {\n // A new click always wins and opens a fresh 90-day window, in gtag's exact format.\n set(cookie, formatGcl(urlClickId, now), GCL_TTL_MS);\n assign(urlClickId);\n } else if (existing) {\n const remainingMs = existing.creationTime + GCL_TTL_MS - now;\n if (remainingMs > 0) {\n assign(existing.clickId);\n if (refresh) set(cookie, existing.raw, remainingMs);\n }\n // Expired: not returned and not re-issued, but gtag owns the deletion.\n }\n }\n\n // --- Reddit _rdt_cid / _rdt_uuid ---\n // Reddit's pixel.js rewrites both on every page load through `document.cookie` — the click id\n // from the URL, else the stored one, and the browser id — each for a fresh 90 days. So Reddit\n // slides the window itself, and the re-issue (default on, see `refresh`) does the same over\n // HTTP: without it the pixel's JS copy, capped at 7 days in Safari, is the only one left.\n const urlRdtCid = params.get('rdt_cid') || undefined;\n const existingRdtCid = jar[RDT_CID_COOKIE] || undefined;\n if (urlRdtCid && urlRdtCid !== existingRdtCid) {\n set(RDT_CID_COOKIE, urlRdtCid, RDT_CID_TTL_MS);\n result.rdt_cid = urlRdtCid;\n } else if (existingRdtCid) {\n result.rdt_cid = existingRdtCid;\n if (refresh) set(RDT_CID_COOKIE, existingRdtCid, RDT_CID_TTL_MS);\n }\n const existingRdtUuid = jar[RDT_UUID_COOKIE] || undefined;\n if (existingRdtUuid && refresh) set(RDT_UUID_COOKIE, existingRdtUuid, RDT_UUID_TTL_MS);\n\n // --- Meta _fbp ---\n // The pixel's browser id: created by the pixel, which rewrites it for 90 days on every page\n // load, as Reddit's does its own. Re-issued as it is, never created here.\n const existingFbp = jar[FBP_COOKIE] || undefined;\n if (existingFbp && refresh) set(FBP_COOKIE, existingFbp, FBP_TTL_MS);\n\n // --- OpenAI __oppref / __obref ---\n // oaiq writes `__oppref` only when the URL carries `oppref` (30 days), and `__obref` — its\n // browser reference — only when there is none (365 days); otherwise it reads them, through\n // `document.cookie`, so in Safari each is gone after 7 days and the browser starts over with a\n // new reference. The first is captured here from the URL as well, and both are re-issued as\n // they are, `__obref` never created. Unlike oaiq, the re-issue restarts their windows: their\n // values carry no creation time to count a remaining lifetime from, and OpenAI applies its own\n // attribution window to the click whatever the cookie's age. Nothing is written once the\n // visitor has opted out of oaiq, which deletes both cookies then.\n if (jar[OAIQ_CONSENT_COOKIE] !== 'false') {\n const urlOppref = params.get('oppref') || undefined;\n const existingOppref = jar[OPPREF_COOKIE] || undefined;\n if (urlOppref) set(OPPREF_COOKIE, urlOppref, OPPREF_TTL_MS);\n else if (existingOppref && refresh) set(OPPREF_COOKIE, existingOppref, OPPREF_TTL_MS);\n const existingObref = jar[OBREF_COOKIE] || undefined;\n if (existingObref && refresh) set(OBREF_COOKIE, existingObref, OBREF_TTL_MS);\n }\n\n // --- Microsoft Ads _uetmsclkid ---\n // The UET tag's own cookie, in its own format, so the tag and this module read each other's\n // writes. Microsoft's ITP answer is this first-party cookie (plus a localStorage backup), but\n // bat.js writes it through `document.cookie`, which Safari caps at 7 days — 24 hours on a\n // landing page decorated by a classified domain, and a bing.com ad click is exactly that.\n // Persisting it here over HTTP on the document response restores the 90-day window.\n //\n // The re-issue (default on, see `refresh`) is the same self-heal as for `_fbc`, and it matters\n // more here: bat.js rewrites this cookie on EVERY page load, so without the re-issue the HTTP\n // copy is downgraded to a JS cookie on the very next page. There is no embedded timestamp to\n // compute a remaining lifetime from, so it is re-issued at a fresh 90 days — which is exactly\n // what bat.js itself does on each page (`msClkIdExpirationTime` from now), so the window\n // slides no more than the tag already slides it. A value this module cannot parse belongs to\n // the tag: never rewritten, never deleted.\n const urlMsclkid = params.get('msclkid')?.trim();\n const existingMsclkid = parseUetMsclkid(jar[UET_MSCLKID_COOKIE]);\n if (urlMsclkid && MSCLKID.test(urlMsclkid) && urlMsclkid.toLowerCase() !== existingMsclkid) {\n set(UET_MSCLKID_COOKIE, formatUetMsclkid(urlMsclkid), MSCLKID_TTL_MS);\n result.msclkid = urlMsclkid.toLowerCase();\n } else if (existingMsclkid) {\n result.msclkid = existingMsclkid;\n if (refresh) set(UET_MSCLKID_COOKIE, formatUetMsclkid(existingMsclkid), MSCLKID_TTL_MS);\n }\n\n return result;\n}\n\n/** Serialize the resolved cookies into `Set-Cookie` header values. */\nexport function toSetCookieHeaders(cookies: SetCookie[]): string[] {\n return cookies.map((cookie) => stringifySetCookie(cookie));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAM,aAAa;AAEnB,MAAM,iBAAiB;AACvB,MAAM,kBAAkB;AAExB,MAAM,aAAa;AAEnB,MAAM,gBAAgB;AACtB,MAAM,eAAe;AAErB,MAAM,iBAAiB;AAEvB,MAAM,aAAa;AAEnB,MAAM,gBAAgB;AAEtB,MAAa,aAAa;AAC1B,MAAa,iBAAiB;AAC9B,MAAa,gBAAgB;AAC7B,MAAa,gBAAgB;AAC7B,MAAa,qBAAqB;AAClC,MAAa,kBAAkB;AAC/B,MAAa,aAAa;AAC1B,MAAa,gBAAgB;AAC7B,MAAa,eAAe;;AAE5B,MAAa,sBAAsB;;;;;;;;AAWnC,SAAgB,SACd,KACA,MAAc,KAAK,IAAI,GACA;CACvB,IAAI,CAAC,KAAK,OAAO,KAAA;CACjB,MAAM,QAAQ,IAAI,MAAM,GAAG;CAC3B,IAAI,MAAM,SAAS,KAAK,MAAM,SAAS,KAAK,MAAM,OAAO,MAAM,OAA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AAI,oBAAoB,iBAAiB,eAAe,GAAG,cAAc;CACxF;CAEA,OAAO;AACT;;AAGA,SAAgB,mBAAmB,SAAgC;CACjE,OAAO,QAAQ,KAAKC,cAAAA,GAAWC,OAAAA,mBAAAA,CAAmBD,QAAM,CAAC;AAC3D"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_setup_index = require("../setup/index.cjs");
|
|
3
2
|
const require_constants_storage = require("../constants/storage.cjs");
|
|
3
|
+
const require_setup_index = require("../setup/index.cjs");
|
|
4
4
|
const require_setup_session = require("../setup/session.cjs");
|
|
5
5
|
const require_track_index = require("../track/index.cjs");
|
|
6
6
|
let react = require("react");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-app-analytics.cjs","names":["config","keys","getSession","useRef","AppState"],"sources":["../../src/hooks/use-app-analytics.ts"],"sourcesContent":["import { useEffect, useRef } from 'react';\nimport { AppState } from 'react-native';\nimport { keys } from '../constants/storage';\nimport { config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { sendPendingEvents, track } from '../track/index';\n\nfunction sendFirstOpen(pathname: string) {\n if (config.storage.getItem(keys.first_open_time)) return;\n track('first_open', { screen_name: pathname, screen_class: pathname });\n config.storage.setItem(keys.first_open_time, new Date().toISOString());\n}\n\nfunction sendUserEngagement() {\n const engagement_time_msec = getSession().flush();\n if (engagement_time_msec <= 0) return;\n track('user_engagement', { engagement_time_msec, trigger: 'background' });\n}\n\nexport function useAppAnalytics(pathname: string) {\n const lastScreenPath = useRef<string | undefined>(undefined);\n\n useEffect(() => {\n const session = getSession();\n\n sendFirstOpen(pathname);\n\n const subscription = AppState.addEventListener('change', (state) => {\n session.updateAccumulator();\n // when returning to the foreground from the background\n if (state === 'active' && !session.isActive()) {\n session.updateActive(true);\n }\n // when entering the background\n else if (state !== 'active' && session.isActive()) {\n session.updateActive(false);\n sendUserEngagement();\n // The app may be suspended or killed soon after going to the background: send the queue\n // now rather than after the batch delay — a new session's session_start may be in it.\n // React Native has no beacon, so this is the usual send, started at once.\n sendPendingEvents();\n }\n });\n\n return () => subscription.remove();\n }, []);\n\n // when the screen is switched, the engagement time of the previous screen is recorded\n useEffect(() => {\n const prevPathname = lastScreenPath.current;\n track('screen_view', {\n screen_name: pathname,\n screen_class: pathname,\n previous_screen_class: prevPathname ?? undefined,\n engagement_time_msec: prevPathname ? getSession().flush() : undefined,\n });\n // Keep the history across Activity effect cleanup and restoration.\n lastScreenPath.current = pathname;\n }, [pathname]);\n}\n"],"mappings":";;;;;;;;AAOA,SAAS,cAAc,UAAkB;CACvC,IAAIA,oBAAAA,OAAO,QAAQ,QAAQC,0BAAAA,KAAK,eAAe,GAAG;
|
|
1
|
+
{"version":3,"file":"use-app-analytics.cjs","names":["config","keys","track","getSession","useRef","useEffect","AppState","sendPendingEvents"],"sources":["../../src/hooks/use-app-analytics.ts"],"sourcesContent":["import { useEffect, useRef } from 'react';\nimport { AppState } from 'react-native';\nimport { keys } from '../constants/storage';\nimport { config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { sendPendingEvents, track } from '../track/index';\n\nfunction sendFirstOpen(pathname: string) {\n if (config.storage.getItem(keys.first_open_time)) return;\n track('first_open', { screen_name: pathname, screen_class: pathname });\n config.storage.setItem(keys.first_open_time, new Date().toISOString());\n}\n\nfunction sendUserEngagement() {\n const engagement_time_msec = getSession().flush();\n if (engagement_time_msec <= 0) return;\n track('user_engagement', { engagement_time_msec, trigger: 'background' });\n}\n\nexport function useAppAnalytics(pathname: string) {\n const lastScreenPath = useRef<string | undefined>(undefined);\n\n useEffect(() => {\n const session = getSession();\n\n sendFirstOpen(pathname);\n\n const subscription = AppState.addEventListener('change', (state) => {\n session.updateAccumulator();\n // when returning to the foreground from the background\n if (state === 'active' && !session.isActive()) {\n session.updateActive(true);\n }\n // when entering the background\n else if (state !== 'active' && session.isActive()) {\n session.updateActive(false);\n sendUserEngagement();\n // The app may be suspended or killed soon after going to the background: send the queue\n // now rather than after the batch delay — a new session's session_start may be in it.\n // React Native has no beacon, so this is the usual send, started at once.\n sendPendingEvents();\n }\n });\n\n return () => subscription.remove();\n }, []);\n\n // when the screen is switched, the engagement time of the previous screen is recorded\n useEffect(() => {\n const prevPathname = lastScreenPath.current;\n track('screen_view', {\n screen_name: pathname,\n screen_class: pathname,\n previous_screen_class: prevPathname ?? undefined,\n engagement_time_msec: prevPathname ? getSession().flush() : undefined,\n });\n // Keep the history across Activity effect cleanup and restoration.\n lastScreenPath.current = pathname;\n }, [pathname]);\n}\n"],"mappings":";;;;;;;;AAOA,SAAS,cAAc,UAAkB;CACvC,IAAIA,oBAAAA,OAAO,QAAQ,QAAQC,0BAAAA,KAAK,eAAe,GAAG;CAClDC,oBAAAA,MAAM,cAAc;EAAE,aAAa;EAAU,cAAc;CAAS,CAAC;CACrEF,oBAAAA,OAAO,QAAQ,QAAQC,0BAAAA,KAAK,kCAAiB,IAAI,KAAK,EAAA,CAAE,YAAY,CAAC;AACvE;AAEA,SAAS,qBAAqB;CAC5B,MAAM,uBAAuBE,sBAAAA,WAAW,CAAC,CAAC,MAAM;CAChD,IAAI,wBAAwB,GAAG;CAC/BD,oBAAAA,MAAM,mBAAmB;EAAE;EAAsB,SAAS;CAAa,CAAC;AAC1E;AAEA,SAAgB,gBAAgB,UAAkB;CAChD,MAAM,kBAAA,GAAiBE,MAAAA,OAAAA,CAA2B,KAAA,CAAS;CAE3DC,CAAAA,GAAAA,MAAAA,UAAAA,OAAgB;EACd,MAAM,UAAUF,sBAAAA,WAAW;EAE3B,cAAc,QAAQ;EAEtB,MAAM,eAAeG,aAAAA,SAAS,iBAAiB,WAAW,UAAU;GAClE,QAAQ,kBAAkB;GAE1B,IAAI,UAAU,YAAY,CAAC,QAAQ,SAAS,GAC1C,QAAQ,aAAa,IAAI;QAGtB,IAAI,UAAU,YAAY,QAAQ,SAAS,GAAG;IACjD,QAAQ,aAAa,KAAK;IAC1B,mBAAmB;IAInBC,oBAAAA,kBAAkB;GACpB;EACF,CAAC;EAED,aAAa,aAAa,OAAO;CACnC,GAAG,CAAC,CAAC;CAGLF,CAAAA,GAAAA,MAAAA,UAAAA,OAAgB;EACd,MAAM,eAAe,eAAe;EACpCH,oBAAAA,MAAM,eAAe;GACnB,aAAa;GACb,cAAc;GACd,uBAAuB,gBAAgB,KAAA;GACvC,sBAAsB,eAAeC,sBAAAA,WAAW,CAAC,CAAC,MAAM,IAAI,KAAA;EAC9D,CAAC;EAED,eAAe,UAAU;CAC3B,GAAG,CAAC,QAAQ,CAAC;AACf"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { config } from "../setup/index.mjs";
|
|
2
1
|
import { keys } from "../constants/storage.mjs";
|
|
2
|
+
import { config } from "../setup/index.mjs";
|
|
3
3
|
import { getSession } from "../setup/session.mjs";
|
|
4
4
|
import { sendPendingEvents, track } from "../track/index.mjs";
|
|
5
5
|
import { useEffect, useRef } from "react";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-outbound-click-analytics.cjs","names":[],"sources":["../../src/hooks/use-outbound-click-analytics.ts"],"sourcesContent":["import { useEffect } from 'react';\nimport { track } from '../track/index';\n\n/**\n * The registrable domain (eTLD+1) of `hostname`, found the way gtag's `cookie_domain: 'auto'`\n * finds it: a cookie is tried on each suffix from the shortest up, and the first one the browser\n * accepts is the domain — browsers refuse public suffixes (`com`, `co.uk`), so no suffix list is\n * needed (gtag's `cookie_domain: 'auto'` walks the same list). A hostname without dots\n * (`localhost`) or one no suffix accepts (an IP address) is its own domain, as a host-only cookie\n * would be. `probe` tries one suffix and says whether the cookie stuck.\n */\nexport function registrableDomain(\n hostname: string,\n probe: (domain: string) => boolean = canSetCookieOn\n): string {\n const labels = hostname.split('.');\n if (labels.length < 2 || /^[\\d.]+$/.test(hostname)) return hostname;\n for (let i = labels.length - 2; i >= 0; i -= 1) {\n const candidate = labels.slice(i).join('.');\n if (probe(candidate)) return candidate;\n }\n return hostname;\n}\n\n/**\n * Whether the browser accepts a cookie for `domain`, read back by a value made for this one probe:\n * a cookie of the same name the site already holds can then neither pass the check for a refused\n * suffix nor hide the probe (gtag writes its real cookie this way and keeps it; this one is a\n * throwaway, deleted at once).\n */\nfunction canSetCookieOn(domain: string): boolean {\n const name = '_sa_d';\n const value = Math.random().toString(36).slice(2);\n try {\n document.cookie = `${name}=${value}; domain=${domain}; path=/; SameSite=Lax`;\n const stuck = document.cookie.split('; ').includes(`${name}=${value}`);\n if (stuck) document.cookie = `${name}=; domain=${domain}; path=/; max-age=0; SameSite=Lax`;\n return stuck;\n } catch {\n return false;\n }\n}\n\n/**\n * Whether a link leads away from the site, by GA4's definition of an outbound click: an http(s)\n * link to a host that is not the site's registrable domain or a subdomain of it. `mailto:`,\n * `tel:` and the like are not outbound clicks (GA4 never counts them), and `www.` → `app.` is\n * not leaving the site.\n */\nexport function isOutboundLink(url: URL, siteDomain: string): boolean {\n if (url.protocol !== 'http:' && url.protocol !== 'https:') return false;\n const host = url.hostname;\n return host !== siteDomain && !host.endsWith(`.${siteDomain}`);\n}\n\n/**\n * Tracks outbound link clicks - when a user clicks a link that leads away from the site to\n * another website (see `isOutboundLink`).\n */\nexport function useOutboundClickAnalytics() {\n useEffect(() => {\n const siteDomain = registrableDomain(window.location.hostname);\n const onClick = (event: MouseEvent) => {\n // Find the closest anchor element from the clicked target\n const target = event.target as HTMLElement;\n const anchor = target.closest('a');\n if (!anchor?.href) return;\n\n try {\n const url = new URL(anchor.href, window.location.origin);\n if (!isOutboundLink(url, siteDomain)) return;\n track('click', {\n outbound: true,\n link_id: anchor.id || '',\n link_url: anchor.href,\n // An anchor can wrap a whole card, so its text runs to kilobytes of markup content\n // that no report ever looks at. GA4 keeps 100 characters of a text event parameter;\n // 512 leaves room for the whole label of a long button while staying well under the\n // transport limit.\n link_text: anchor.textContent.trim().slice(0, 512),\n link_domain: url.hostname,\n link_classes: anchor.className || '',\n });\n } catch {\n // Invalid URL, ignore\n }\n };\n\n document.addEventListener('click', onClick, { passive: true, capture: true });\n return () => document.removeEventListener('click', onClick, { capture: true });\n }, []);\n}\n"],"mappings":";;;;;;;;;;;;AAWA,SAAgB,kBACd,UACA,QAAqC,gBAC7B;CACR,MAAM,SAAS,SAAS,MAAM,GAAG;CACjC,IAAI,OAAO,SAAS,KAAK,WAAW,KAAK,QAAQ,GAAG,OAAO;CAC3D,KAAK,IAAI,IAAI,OAAO,SAAS,GAAG,KAAK,GAAG,KAAK,GAAG;EAC9C,MAAM,YAAY,OAAO,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG;EAC1C,IAAI,MAAM,SAAS,GAAG,OAAO;CAC/B;CACA,OAAO;AACT;;;;;;;AAQA,SAAS,eAAe,QAAyB;CAC/C,MAAM,OAAO;CACb,MAAM,QAAQ,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,CAAC;CAChD,IAAI;EACF,SAAS,SAAS,GAAG,KAAK,GAAG,MAAM,WAAW,OAAO;EACrD,MAAM,QAAQ,SAAS,OAAO,MAAM,IAAI,CAAC,CAAC,SAAS,GAAG,KAAK,GAAG,OAAO;EACrE,IAAI,OAAO,SAAS,SAAS,GAAG,KAAK,YAAY,OAAO;EACxD,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;AAQA,SAAgB,eAAe,KAAU,YAA6B;CACpE,IAAI,IAAI,aAAa,WAAW,IAAI,aAAa,UAAU,OAAO;CAClE,MAAM,OAAO,IAAI;CACjB,OAAO,SAAS,cAAc,CAAC,KAAK,SAAS,IAAI,YAAY;AAC/D;;;;;AAMA,SAAgB,4BAA4B;
|
|
1
|
+
{"version":3,"file":"use-outbound-click-analytics.cjs","names":["useEffect","track"],"sources":["../../src/hooks/use-outbound-click-analytics.ts"],"sourcesContent":["import { useEffect } from 'react';\nimport { track } from '../track/index';\n\n/**\n * The registrable domain (eTLD+1) of `hostname`, found the way gtag's `cookie_domain: 'auto'`\n * finds it: a cookie is tried on each suffix from the shortest up, and the first one the browser\n * accepts is the domain — browsers refuse public suffixes (`com`, `co.uk`), so no suffix list is\n * needed (gtag's `cookie_domain: 'auto'` walks the same list). A hostname without dots\n * (`localhost`) or one no suffix accepts (an IP address) is its own domain, as a host-only cookie\n * would be. `probe` tries one suffix and says whether the cookie stuck.\n */\nexport function registrableDomain(\n hostname: string,\n probe: (domain: string) => boolean = canSetCookieOn\n): string {\n const labels = hostname.split('.');\n if (labels.length < 2 || /^[\\d.]+$/.test(hostname)) return hostname;\n for (let i = labels.length - 2; i >= 0; i -= 1) {\n const candidate = labels.slice(i).join('.');\n if (probe(candidate)) return candidate;\n }\n return hostname;\n}\n\n/**\n * Whether the browser accepts a cookie for `domain`, read back by a value made for this one probe:\n * a cookie of the same name the site already holds can then neither pass the check for a refused\n * suffix nor hide the probe (gtag writes its real cookie this way and keeps it; this one is a\n * throwaway, deleted at once).\n */\nfunction canSetCookieOn(domain: string): boolean {\n const name = '_sa_d';\n const value = Math.random().toString(36).slice(2);\n try {\n document.cookie = `${name}=${value}; domain=${domain}; path=/; SameSite=Lax`;\n const stuck = document.cookie.split('; ').includes(`${name}=${value}`);\n if (stuck) document.cookie = `${name}=; domain=${domain}; path=/; max-age=0; SameSite=Lax`;\n return stuck;\n } catch {\n return false;\n }\n}\n\n/**\n * Whether a link leads away from the site, by GA4's definition of an outbound click: an http(s)\n * link to a host that is not the site's registrable domain or a subdomain of it. `mailto:`,\n * `tel:` and the like are not outbound clicks (GA4 never counts them), and `www.` → `app.` is\n * not leaving the site.\n */\nexport function isOutboundLink(url: URL, siteDomain: string): boolean {\n if (url.protocol !== 'http:' && url.protocol !== 'https:') return false;\n const host = url.hostname;\n return host !== siteDomain && !host.endsWith(`.${siteDomain}`);\n}\n\n/**\n * Tracks outbound link clicks - when a user clicks a link that leads away from the site to\n * another website (see `isOutboundLink`).\n */\nexport function useOutboundClickAnalytics() {\n useEffect(() => {\n const siteDomain = registrableDomain(window.location.hostname);\n const onClick = (event: MouseEvent) => {\n // Find the closest anchor element from the clicked target\n const target = event.target as HTMLElement;\n const anchor = target.closest('a');\n if (!anchor?.href) return;\n\n try {\n const url = new URL(anchor.href, window.location.origin);\n if (!isOutboundLink(url, siteDomain)) return;\n track('click', {\n outbound: true,\n link_id: anchor.id || '',\n link_url: anchor.href,\n // An anchor can wrap a whole card, so its text runs to kilobytes of markup content\n // that no report ever looks at. GA4 keeps 100 characters of a text event parameter;\n // 512 leaves room for the whole label of a long button while staying well under the\n // transport limit.\n link_text: anchor.textContent.trim().slice(0, 512),\n link_domain: url.hostname,\n link_classes: anchor.className || '',\n });\n } catch {\n // Invalid URL, ignore\n }\n };\n\n document.addEventListener('click', onClick, { passive: true, capture: true });\n return () => document.removeEventListener('click', onClick, { capture: true });\n }, []);\n}\n"],"mappings":";;;;;;;;;;;;AAWA,SAAgB,kBACd,UACA,QAAqC,gBAC7B;CACR,MAAM,SAAS,SAAS,MAAM,GAAG;CACjC,IAAI,OAAO,SAAS,KAAK,WAAW,KAAK,QAAQ,GAAG,OAAO;CAC3D,KAAK,IAAI,IAAI,OAAO,SAAS,GAAG,KAAK,GAAG,KAAK,GAAG;EAC9C,MAAM,YAAY,OAAO,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG;EAC1C,IAAI,MAAM,SAAS,GAAG,OAAO;CAC/B;CACA,OAAO;AACT;;;;;;;AAQA,SAAS,eAAe,QAAyB;CAC/C,MAAM,OAAO;CACb,MAAM,QAAQ,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,CAAC;CAChD,IAAI;EACF,SAAS,SAAS,GAAG,KAAK,GAAG,MAAM,WAAW,OAAO;EACrD,MAAM,QAAQ,SAAS,OAAO,MAAM,IAAI,CAAC,CAAC,SAAS,GAAG,KAAK,GAAG,OAAO;EACrE,IAAI,OAAO,SAAS,SAAS,GAAG,KAAK,YAAY,OAAO;EACxD,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;AAQA,SAAgB,eAA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