@shware/analytics 7.1.1 → 7.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/click-id/index.cjs.map +1 -1
- package/dist/click-id/index.d.cts +1 -1
- package/dist/click-id/index.d.mts +1 -1
- package/dist/click-id/index.mjs.map +1 -1
- package/dist/constants/storage.cjs +2 -1
- package/dist/constants/storage.cjs.map +1 -1
- package/dist/constants/storage.d.cts +1 -0
- package/dist/constants/storage.d.cts.map +1 -1
- package/dist/constants/storage.d.mts +1 -0
- package/dist/constants/storage.d.mts.map +1 -1
- package/dist/constants/storage.mjs +2 -1
- package/dist/constants/storage.mjs.map +1 -1
- package/dist/hooks/use-app-analytics.cjs +1 -2
- package/dist/hooks/use-app-analytics.cjs.map +1 -1
- package/dist/hooks/use-app-analytics.mjs +1 -2
- package/dist/hooks/use-app-analytics.mjs.map +1 -1
- package/dist/hooks/use-outbound-click-analytics.cjs +1 -1
- package/dist/hooks/use-outbound-click-analytics.cjs.map +1 -1
- package/dist/hooks/use-outbound-click-analytics.mjs +1 -1
- package/dist/hooks/use-outbound-click-analytics.mjs.map +1 -1
- package/dist/hooks/use-web-analytics.cjs +1 -2
- package/dist/hooks/use-web-analytics.cjs.map +1 -1
- package/dist/hooks/use-web-analytics.mjs +1 -2
- package/dist/hooks/use-web-analytics.mjs.map +1 -1
- package/dist/next/index.cjs +1 -1
- package/dist/next/index.mjs +1 -1
- package/dist/react-router/index.cjs +1 -1
- package/dist/react-router/index.mjs +1 -1
- package/dist/schema/index.cjs +4 -2
- package/dist/schema/index.cjs.map +1 -1
- package/dist/schema/index.d.cts.map +1 -1
- package/dist/schema/index.d.mts.map +1 -1
- package/dist/schema/index.mjs +4 -2
- package/dist/schema/index.mjs.map +1 -1
- package/dist/setup/session.cjs +61 -14
- package/dist/setup/session.cjs.map +1 -1
- package/dist/setup/session.d.cts +24 -6
- package/dist/setup/session.d.cts.map +1 -1
- package/dist/setup/session.d.mts +24 -6
- package/dist/setup/session.d.mts.map +1 -1
- package/dist/setup/session.mjs +61 -14
- package/dist/setup/session.mjs.map +1 -1
- package/dist/tanstack/middleware.cjs.map +1 -1
- package/dist/tanstack/middleware.d.cts +1 -1
- package/dist/tanstack/middleware.d.mts +1 -1
- package/dist/tanstack/middleware.mjs.map +1 -1
- package/dist/track/index.cjs +17 -18
- package/dist/track/index.cjs.map +1 -1
- package/dist/track/index.d.cts.map +1 -1
- package/dist/track/index.d.mts.map +1 -1
- package/dist/track/index.mjs +17 -18
- package/dist/track/index.mjs.map +1 -1
- package/package.json +14 -14
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":[],"sources":["../../src/schema/index.ts"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../../src/schema/index.ts"],"mappings":";;cAyEa;cAUA;cAEA,YAAU,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqErB,EAAA,KAAA;cAEW,kBAAgB,EAAA,gBAAA,EAAA,YAAA,EAAA,cAAA,EAAA,uBAAA,EAAA,uBAAA,EAAA,YAAA,EAAA,uBAAA,EAAA,mCAAA,EAAA,uBAAA,EAAA,yBAAA,EAAA,aAAA,EAAA,aAAA,EAAA,YAAA,EAAA,cAAA,EAAA,uBAAA,EAAA,uBAAA,EAAA,YAAA,EAAA,uBAAA,EAAA,mCAAA,EAAA,uBAAA,EAAA,yBAAA,EAAA,gBAAA,EAAA,iBAAA,kDAAA,wDAAA,EAAA,iBAAA,2CAAA,4DAAA,2CAAA;cAehB,wBAAsB,EAAA,aAAA,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAWE,EAAA,KAAA;cAExB,qBAAmB,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAM9B,EAAA,KAAA;;;;;;;;;;;cA6BW,wBAAsB,EAAA;;;;;;;;;;;;;;;;;;;;GAIjC,EAAA,KAAA;cAEW,qBAAmB,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAM9B,EAAA,KAAA;cAEW,sBAAoB,EAAA;;;;GAI/B,EAAA,KAAA;;;;;cAWW,kBAAgB,EAAA;;;;;;;;;;;GA+C3B,EAAA,KAAA;KAEU,sBAAsB,EAAE,cAAc;KACtC,oBAAoB,EAAE,cAAc;KACpC,gBAAgB,EAAE,cAAc;KAChC,mBAAmB,EAAE,cAAc;KACnC,sBAAsB,EAAE,cAAc;KACtC,mBAAmB,EAAE,cAAc"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/schema/index.ts"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/schema/index.ts"],"mappings":";;cAyEa;cAUA;cAEA,YAAU,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqErB,EAAA,KAAA;cAEW,kBAAgB,EAAA,gBAAA,EAAA,YAAA,EAAA,cAAA,EAAA,uBAAA,EAAA,uBAAA,EAAA,YAAA,EAAA,uBAAA,EAAA,mCAAA,EAAA,uBAAA,EAAA,yBAAA,EAAA,aAAA,EAAA,aAAA,EAAA,YAAA,EAAA,cAAA,EAAA,uBAAA,EAAA,uBAAA,EAAA,YAAA,EAAA,uBAAA,EAAA,mCAAA,EAAA,uBAAA,EAAA,yBAAA,EAAA,gBAAA,EAAA,iBAAA,kDAAA,wDAAA,EAAA,iBAAA,2CAAA,4DAAA,2CAAA;cAehB,wBAAsB,EAAA,aAAA,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAWE,EAAA,KAAA;cAExB,qBAAmB,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAM9B,EAAA,KAAA;;;;;;;;;;;cA6BW,wBAAsB,EAAA;;;;;;;;;;;;;;;;;;;;GAIjC,EAAA,KAAA;cAEW,qBAAmB,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAM9B,EAAA,KAAA;cAEW,sBAAoB,EAAA;;;;GAI/B,EAAA,KAAA;;;;;cAWW,kBAAgB,EAAA;;;;;;;;;;;GA+C3B,EAAA,KAAA;KAEU,sBAAsB,EAAE,cAAc;KACtC,oBAAoB,EAAE,cAAc;KACpC,gBAAgB,EAAE,cAAc;KAChC,mBAAmB,EAAE,cAAc;KACnC,sBAAsB,EAAE,cAAc;KACtC,mBAAmB,EAAE,cAAc"}
|
package/dist/schema/index.mjs
CHANGED
|
@@ -5,7 +5,7 @@ const MAX_VALUE_LENGTH = 512;
|
|
|
5
5
|
const MAX_PROPERTIES = 64;
|
|
6
6
|
/**
|
|
7
7
|
* Truncated rather than rejected. These schemas validate a whole batch at once, so refusing one
|
|
8
|
-
* oversized value costs every event that
|
|
8
|
+
* oversized value costs every event that traveled with it — and the values that overrun are the
|
|
9
9
|
* ones derived from the page (a link's text, a URL carrying a long query), which no client can
|
|
10
10
|
* bound in advance. A shortened value is worth more than a lost batch.
|
|
11
11
|
*/
|
|
@@ -22,11 +22,13 @@ const propertyText = pipe(string(), transform((value) => value.slice(0, MAX_VALU
|
|
|
22
22
|
*/
|
|
23
23
|
function takeProperties(data) {
|
|
24
24
|
const result = {};
|
|
25
|
+
let count = 0;
|
|
25
26
|
for (const [rawKey, value] of Object.entries(data)) {
|
|
27
|
+
if (count >= MAX_PROPERTIES) break;
|
|
26
28
|
const key = rawKey.trim();
|
|
27
29
|
if (!key || key.length > MAX_KEY_LENGTH) continue;
|
|
28
|
-
if (Object.keys(result).length >= MAX_PROPERTIES) break;
|
|
29
30
|
result[key] = value;
|
|
31
|
+
count++;
|
|
30
32
|
}
|
|
31
33
|
return result;
|
|
32
34
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["_null","_enum"],"sources":["../../src/schema/index.ts"],"sourcesContent":["import {\n enum as _enum,\n null as _null,\n array,\n boolean,\n e164,\n email,\n iso,\n maxLength,\n minLength,\n number,\n object,\n optional,\n pipe,\n record,\n refine,\n regex,\n string,\n toLowerCase,\n toUpperCase,\n transform,\n trim,\n union,\n url,\n uuid,\n type z,\n} from 'zod/mini';\nimport type { Environment, Platform } from '../track/types';\n\nconst MAX_KEY_LENGTH = 128;\nconst MAX_VALUE_LENGTH = 512;\nconst MAX_PROPERTIES = 64;\n\n/**\n * Truncated rather than rejected. These schemas validate a whole batch at once, so refusing one\n * oversized value costs every event that travelled with it — and the values that overrun are the\n * ones derived from the page (a link's text, a URL carrying a long query), which no client can\n * bound in advance. A shortened value is worth more than a lost batch.\n */\nconst propertyText = pipe(\n string(),\n transform((value) => value.slice(0, MAX_VALUE_LENGTH))\n);\n\n/**\n * Keys are written by hand in instrumentation code, so an unusable one is a mistake in the host\n * rather than something the visitor typed. It is still dropped rather than rejected, for the same\n * reason: the mistake should cost that property, not the batch it happens to be in. Truncating a\n * key is not an option — two long keys would silently become one field.\n *\n * The key schema below is deliberately permissive so that this transform is reached at all; the\n * trimming it used to do happens here instead. `MAX_PROPERTIES` keeps the first N in insertion\n * order.\n */\nfunction takeProperties<T>(data: Record<string, T>): Record<string, T> {\n const result: Record<string, T> = {};\n for (const [rawKey, value] of Object.entries(data)) {\n const key = rawKey.trim();\n if (!key || key.length > MAX_KEY_LENGTH) continue;\n if (Object.keys(result).length >= MAX_PROPERTIES) break;\n result[key] = value;\n }\n return result;\n}\n\nconst items = array(\n pipe(\n record(string(), union([propertyText, number(), boolean(), _null()])),\n transform(takeProperties)\n )\n);\n\nexport const ALL_PLATFORMS = [\n 'ios',\n 'android',\n 'web',\n 'macos',\n 'windows',\n 'linux',\n 'unknown',\n] as const satisfies Platform[];\n\nexport const ALL_ENVIRONMENTS = ['development', 'production'] as const satisfies Environment[];\n\nexport const tagsSchema = object({\n os: optional(string()),\n os_name: optional(string()),\n os_version: optional(string()),\n browser: optional(string()),\n browser_name: optional(string()),\n browser_version: optional(string()),\n device: optional(string()),\n device_id: optional(string().check(trim(), minLength(1), maxLength(36))),\n device_type: optional(string()),\n device_vendor: optional(string()),\n device_pixel_ratio: optional(number()),\n screen_width: optional(number()),\n screen_height: optional(number()),\n screen_resolution: optional(\n pipe(\n string().check(regex(/^\\d+x\\d+$/)),\n transform((v) => v as `${number}x${number}`)\n )\n ),\n release: optional(string()),\n language: optional(string()),\n time_zone: optional(string()),\n page_location: optional(string()),\n page_referrer: optional(string()),\n page_title: optional(string()),\n // app info\n advertising_id: optional(string()),\n install_referrer: optional(string()),\n // Meta Ads\n fbc: optional(string()),\n fbp: optional(string()),\n fbclid: optional(string()),\n ad_id: optional(string()),\n ad_name: optional(string()),\n adset_id: optional(string()),\n adset_name: optional(string()),\n campaign_id: optional(string()),\n campaign_name: optional(string()),\n placement: optional(string()),\n site_source_name: optional(string()),\n // Google Ads\n gclid: optional(string()),\n gclsrc: optional(string()),\n gad_source: optional(string()),\n gad_campaignid: optional(string()),\n // Reddit ads\n rdt_cid: optional(string()),\n rdt_uuid: optional(string()),\n // click ids\n dclid: optional(string()),\n ko_click_id: optional(string()),\n li_fat_id: optional(string()),\n msclkid: optional(string()),\n sccid: optional(string()),\n ttclid: optional(string()),\n twclid: optional(string()),\n wbraid: optional(string()),\n yclid: optional(string()),\n // utm params\n utm_source: optional(string()),\n utm_medium: optional(string()),\n utm_campaign: optional(string()),\n utm_term: optional(string()),\n utm_content: optional(string()),\n utm_id: optional(string()),\n utm_source_platform: optional(string()),\n utm_creative_format: optional(string()),\n utm_marketing_tactic: optional(string()),\n});\n\nexport const propertiesSchema = optional(\n pipe(\n record(string(), union([propertyText, number(), boolean(), _null(), items])),\n transform(takeProperties)\n )\n);\n\n/** Visitor properties differ from event properties only in taking no nested item lists. */\nconst visitorPropertiesSchema = optional(\n pipe(\n record(string(), union([propertyText, number(), boolean(), _null()])),\n transform(takeProperties)\n )\n);\n\nexport const createTrackEventSchema = array(\n object({\n name: string().check(trim(), minLength(1), maxLength(64)),\n visitor_id: uuid(),\n session_id: uuid(),\n platform: _enum(ALL_PLATFORMS),\n environment: _enum(ALL_ENVIRONMENTS),\n timestamp: iso.datetime(),\n tags: tagsSchema,\n properties: propertiesSchema,\n })\n).check(minLength(1), maxLength(100));\n\nexport const createVisitorSchema = object({\n device_id: string().check(trim(), minLength(1), maxLength(36)),\n platform: _enum(ALL_PLATFORMS),\n environment: _enum(ALL_ENVIRONMENTS),\n tags: tagsSchema,\n properties: visitorPropertiesSchema,\n});\n\nconst emailValue = pipe(string().check(trim(), toLowerCase(), maxLength(320)), email());\n\n/** E.164: a plus sign (+) prefix, country code, then digits only, no dashes/parens/spaces. */\nconst phoneValue = pipe(string().check(trim()), e164());\n\nconst addressValue = object({\n first_name: optional(string().check(trim(), maxLength(128))),\n last_name: optional(string().check(trim(), maxLength(128))),\n street: optional(string().check(trim(), maxLength(256))),\n city: optional(string().check(trim(), maxLength(128))),\n /** User province, state, or region. Example: `Hampshire` */\n region: optional(string().check(trim(), maxLength(128))),\n postal_code: optional(string().check(trim(), maxLength(32))),\n /** 2-letter country code, per the ISO 3166-1 alpha-2 standard. Example: `UK` */\n country: optional(string().check(trim(), toUpperCase(), regex(/^[A-Z]{2}$/))),\n});\n\n/**\n * User-provided data (UPD) used for enhanced conversions, Customer Match, and demographics.\n * Values are sent unhashed; Google normalizes and hashes them before they reach its servers.\n *\n * Multiple values may be sent to increase the match rate: up to 3 emails, 3 phone numbers, and\n * 2 addresses.\n *\n * @see https://support.google.com/analytics/answer/14078702\n * @see https://support.google.com/google-ads/answer/13258081\n */\nexport const userProvidedDataSchema = object({\n email: optional(union([emailValue, array(emailValue).check(minLength(1), maxLength(3))])),\n phone_number: optional(union([phoneValue, array(phoneValue).check(minLength(1), maxLength(3))])),\n address: optional(union([addressValue, array(addressValue).check(minLength(1), maxLength(2))])),\n});\n\nexport const updateVisitorSchema = object({\n user_id: optional(uuid()),\n user_data: optional(userProvidedDataSchema),\n distinct_id: optional(string().check(trim(), minLength(1), maxLength(36))),\n tags: tagsSchema,\n properties: visitorPropertiesSchema,\n});\n\nexport const createFeedbackSchema = object({\n name: string().check(minLength(1), maxLength(256)),\n email: email().check(maxLength(320)),\n message: string().check(minLength(1), maxLength(65536)),\n});\n\nconst noEmptyString = pipe(\n string().check(maxLength(256)),\n transform((v) => (v ? v : undefined))\n);\n\n/**\n * The schema for creating a link.\n * @see https://support.google.com/analytics/answer/10917952\n * */\nexport const createLinkSchema = object({\n /** The URL that the user is redirected to. */\n url: url().check(minLength(1), maxLength(1024)), // required\n\n /**\n * Campaign ID. Used to identify a specific campaign or promotion. This is a required key for GA4\n * data import. Use the same IDs that you use when uploading campaign cost data.\n */\n utm_id: optional(noEmptyString),\n\n /** Referrer, for example: google, newsletter4, billboard */\n utm_source: string().check(minLength(1), maxLength(256)), // required\n\n /** Marketing medium, for example: cpc, banner, email */\n utm_medium: string().check(minLength(1), maxLength(256)), // required\n\n /** Product, slogan, promo code, for example, spring_sale */\n utm_campaign: string().check(minLength(1), maxLength(256)), // required\n\n /** Paid keyword */\n utm_term: optional(noEmptyString),\n\n /**\n * Use to differentiate creatives. For example, if you have two call-to-action links within the\n * same email message, you can use utm_content and set different values for each so you can tell\n * which version is more effective.\n */\n utm_content: optional(noEmptyString),\n\n /**\n * The platform responsible for directing traffic to a given Analytics property (such as a buying\n * platform that sets budgets and targeting criteria or a platform that manages organic traffic\n * data). For example, Search Ads 360 or Display & Video 360.\n */\n utm_source_platform: optional(noEmptyString),\n\n /**\n * Type of creative, for example, display, native, video, search, utm_creative_format is not\n * currently reported in Google Analytics 4 properties.\n */\n utm_creative_format: optional(noEmptyString),\n\n /**\n * Targeting criteria applied to a campaign, for example, remarketing, prospecting,\n * utm_marketing_tactic is not currently reported in Google Analytics 4 properties.\n * */\n utm_marketing_tactic: optional(noEmptyString),\n});\n\nexport type CreateTrackEventDTO = z.output<typeof createTrackEventSchema>;\nexport type CreateFeedbackDTO = z.output<typeof createFeedbackSchema>;\nexport type CreateLinkDTO = z.output<typeof createLinkSchema>;\nexport type CreateVisitorDTO = z.output<typeof createVisitorSchema>;\nexport type UserProvidedDataDTO = z.output<typeof userProvidedDataSchema>;\nexport type UpdateVisitorDTO = z.output<typeof updateVisitorSchema>;\n"],"mappings":";;AA6BA,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;;;;;;;AAQvB,MAAM,eAAe,KACnB,OAAO,GACP,WAAW,UAAU,MAAM,MAAM,GAAG,gBAAgB,CAAC,CACvD;;;;;;;;;;;AAYA,SAAS,eAAkB,MAA4C;CACrE,MAAM,SAA4B,CAAC;CACnC,KAAK,MAAM,CAAC,QAAQ,UAAU,OAAO,QAAQ,IAAI,GAAG;EAClD,MAAM,MAAM,OAAO,KAAK;EACxB,IAAI,CAAC,OAAO,IAAI,SAAS,gBAAgB;EACzC,IAAI,OAAO,KAAK,MAAM,CAAC,CAAC,UAAU,gBAAgB;EAClD,OAAO,OAAO;CAChB;CACA,OAAO;AACT;AAEA,MAAM,QAAQ,MACZ,KACE,OAAO,OAAO,GAAG,MAAM;CAAC;CAAc,OAAO;CAAG,QAAQ;CAAGA,OAAM;AAAC,CAAC,CAAC,GACpE,UAAU,cAAc,CAC1B,CACF;AAEA,MAAa,gBAAgB;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAa,mBAAmB,CAAC,eAAe,YAAY;AAE5D,MAAa,aAAa,OAAO;CAC/B,IAAI,SAAS,OAAO,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;;;;;CAOnC,qBAAqB,SAAS,aAAa;;;;;CAM3C,qBAAqB,SAAS,aAAa;;;;;CAM3C,sBAAsB,SAAS,aAAa;AAC9C,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["_null","_enum"],"sources":["../../src/schema/index.ts"],"sourcesContent":["import {\n enum as _enum,\n null as _null,\n array,\n boolean,\n e164,\n email,\n iso,\n maxLength,\n minLength,\n number,\n object,\n optional,\n pipe,\n record,\n regex,\n string,\n toLowerCase,\n toUpperCase,\n transform,\n trim,\n union,\n url,\n uuid,\n type z,\n} from 'zod/mini';\nimport type { Environment, Platform } from '../track/types';\n\nconst MAX_KEY_LENGTH = 128;\nconst MAX_VALUE_LENGTH = 512;\nconst MAX_PROPERTIES = 64;\n\n/**\n * Truncated rather than rejected. These schemas validate a whole batch at once, so refusing one\n * oversized value costs every event that traveled with it — and the values that overrun are the\n * ones derived from the page (a link's text, a URL carrying a long query), which no client can\n * bound in advance. A shortened value is worth more than a lost batch.\n */\nconst propertyText = pipe(\n string(),\n transform((value) => value.slice(0, MAX_VALUE_LENGTH))\n);\n\n/**\n * Keys are written by hand in instrumentation code, so an unusable one is a mistake in the host\n * rather than something the visitor typed. It is still dropped rather than rejected, for the same\n * reason: the mistake should cost that property, not the batch it happens to be in. Truncating a\n * key is not an option — two long keys would silently become one field.\n *\n * The key schema below is deliberately permissive so that this transform is reached at all; the\n * trimming it used to do happens here instead. `MAX_PROPERTIES` keeps the first N in insertion\n * order.\n */\nfunction takeProperties<T>(data: Record<string, T>): Record<string, T> {\n const result: Record<string, T> = {};\n let count = 0;\n for (const [rawKey, value] of Object.entries(data)) {\n if (count >= MAX_PROPERTIES) break;\n const key = rawKey.trim();\n if (!key || key.length > MAX_KEY_LENGTH) continue;\n result[key] = value;\n count++;\n }\n return result;\n}\n\nconst items = array(\n pipe(\n record(string(), union([propertyText, number(), boolean(), _null()])),\n transform(takeProperties)\n )\n);\n\nexport const ALL_PLATFORMS = [\n 'ios',\n 'android',\n 'web',\n 'macos',\n 'windows',\n 'linux',\n 'unknown',\n] as const satisfies Platform[];\n\nexport const ALL_ENVIRONMENTS = ['development', 'production'] as const satisfies Environment[];\n\nexport const tagsSchema = object({\n os: optional(string()),\n os_name: optional(string()),\n os_version: optional(string()),\n browser: optional(string()),\n browser_name: optional(string()),\n browser_version: optional(string()),\n device: optional(string()),\n device_id: optional(string().check(trim(), minLength(1), maxLength(36))),\n device_type: optional(string()),\n device_vendor: optional(string()),\n device_pixel_ratio: optional(number()),\n screen_width: optional(number()),\n screen_height: optional(number()),\n screen_resolution: optional(\n pipe(\n string().check(regex(/^\\d+x\\d+$/)),\n transform((v) => v as `${number}x${number}`)\n )\n ),\n release: optional(string()),\n language: optional(string()),\n time_zone: optional(string()),\n page_location: optional(string()),\n page_referrer: optional(string()),\n page_title: optional(string()),\n // app info\n advertising_id: optional(string()),\n install_referrer: optional(string()),\n // Meta Ads\n fbc: optional(string()),\n fbp: optional(string()),\n fbclid: optional(string()),\n ad_id: optional(string()),\n ad_name: optional(string()),\n adset_id: optional(string()),\n adset_name: optional(string()),\n campaign_id: optional(string()),\n campaign_name: optional(string()),\n placement: optional(string()),\n site_source_name: optional(string()),\n // Google Ads\n gclid: optional(string()),\n gclsrc: optional(string()),\n gad_source: optional(string()),\n gad_campaignid: optional(string()),\n // Reddit ads\n rdt_cid: optional(string()),\n rdt_uuid: optional(string()),\n // click ids\n dclid: optional(string()),\n ko_click_id: optional(string()),\n li_fat_id: optional(string()),\n msclkid: optional(string()),\n sccid: optional(string()),\n ttclid: optional(string()),\n twclid: optional(string()),\n wbraid: optional(string()),\n yclid: optional(string()),\n // utm params\n utm_source: optional(string()),\n utm_medium: optional(string()),\n utm_campaign: optional(string()),\n utm_term: optional(string()),\n utm_content: optional(string()),\n utm_id: optional(string()),\n utm_source_platform: optional(string()),\n utm_creative_format: optional(string()),\n utm_marketing_tactic: optional(string()),\n});\n\nexport const propertiesSchema = optional(\n pipe(\n record(string(), union([propertyText, number(), boolean(), _null(), items])),\n transform(takeProperties)\n )\n);\n\n/** Visitor properties differ from event properties only in taking no nested item lists. */\nconst visitorPropertiesSchema = optional(\n pipe(\n record(string(), union([propertyText, number(), boolean(), _null()])),\n transform(takeProperties)\n )\n);\n\nexport const createTrackEventSchema = array(\n object({\n name: string().check(trim(), minLength(1), maxLength(64)),\n visitor_id: uuid(),\n session_id: uuid(),\n platform: _enum(ALL_PLATFORMS),\n environment: _enum(ALL_ENVIRONMENTS),\n timestamp: iso.datetime(),\n tags: tagsSchema,\n properties: propertiesSchema,\n })\n).check(minLength(1), maxLength(100));\n\nexport const createVisitorSchema = object({\n device_id: string().check(trim(), minLength(1), maxLength(36)),\n platform: _enum(ALL_PLATFORMS),\n environment: _enum(ALL_ENVIRONMENTS),\n tags: tagsSchema,\n properties: visitorPropertiesSchema,\n});\n\nconst emailValue = pipe(string().check(trim(), toLowerCase(), maxLength(320)), email());\n\n/** E.164: a plus sign (+) prefix, country code, then digits only, no dashes/parens/spaces. */\nconst phoneValue = pipe(string().check(trim()), e164());\n\nconst addressValue = object({\n first_name: optional(string().check(trim(), maxLength(128))),\n last_name: optional(string().check(trim(), maxLength(128))),\n street: optional(string().check(trim(), maxLength(256))),\n city: optional(string().check(trim(), maxLength(128))),\n /** User province, state, or region. Example: `Hampshire` */\n region: optional(string().check(trim(), maxLength(128))),\n postal_code: optional(string().check(trim(), maxLength(32))),\n /** 2-letter country code, per the ISO 3166-1 alpha-2 standard. Example: `UK` */\n country: optional(string().check(trim(), toUpperCase(), regex(/^[A-Z]{2}$/))),\n});\n\n/**\n * User-provided data (UPD) used for enhanced conversions, Customer Match, and demographics.\n * Values are sent unhashed; Google normalizes and hashes them before they reach its servers.\n *\n * Multiple values may be sent to increase the match rate: up to 3 emails, 3 phone numbers, and\n * 2 addresses.\n *\n * @see https://support.google.com/analytics/answer/14078702\n * @see https://support.google.com/google-ads/answer/13258081\n */\nexport const userProvidedDataSchema = object({\n email: optional(union([emailValue, array(emailValue).check(minLength(1), maxLength(3))])),\n phone_number: optional(union([phoneValue, array(phoneValue).check(minLength(1), maxLength(3))])),\n address: optional(union([addressValue, array(addressValue).check(minLength(1), maxLength(2))])),\n});\n\nexport const updateVisitorSchema = object({\n user_id: optional(uuid()),\n user_data: optional(userProvidedDataSchema),\n distinct_id: optional(string().check(trim(), minLength(1), maxLength(36))),\n tags: tagsSchema,\n properties: visitorPropertiesSchema,\n});\n\nexport const createFeedbackSchema = object({\n name: string().check(minLength(1), maxLength(256)),\n email: email().check(maxLength(320)),\n message: string().check(minLength(1), maxLength(65536)),\n});\n\nconst noEmptyString = pipe(\n string().check(maxLength(256)),\n transform((v) => (v ? v : undefined))\n);\n\n/**\n * The schema for creating a link.\n * @see https://support.google.com/analytics/answer/10917952\n * */\nexport const createLinkSchema = object({\n /** The URL that the user is redirected to. */\n url: url().check(minLength(1), maxLength(1024)), // required\n\n /**\n * Campaign ID. Used to identify a specific campaign or promotion. This is a required key for GA4\n * data import. Use the same IDs that you use when uploading campaign cost data.\n */\n utm_id: optional(noEmptyString),\n\n /** Referrer, for example: google, newsletter4, billboard */\n utm_source: string().check(minLength(1), maxLength(256)), // required\n\n /** Marketing medium, for example: cpc, banner, email */\n utm_medium: string().check(minLength(1), maxLength(256)), // required\n\n /** Product, slogan, promo code, for example, spring_sale */\n utm_campaign: string().check(minLength(1), maxLength(256)), // required\n\n /** Paid keyword */\n utm_term: optional(noEmptyString),\n\n /**\n * Use to differentiate creatives. For example, if you have two call-to-action links within the\n * same email message, you can use utm_content and set different values for each so you can tell\n * which version is more effective.\n */\n utm_content: optional(noEmptyString),\n\n /**\n * The platform responsible for directing traffic to a given Analytics property (such as a buying\n * platform that sets budgets and targeting criteria or a platform that manages organic traffic\n * data). For example, Search Ads 360 or Display & Video 360.\n */\n utm_source_platform: optional(noEmptyString),\n\n /**\n * Type of creative, for example, display, native, video, search, utm_creative_format is not\n * currently reported in Google Analytics 4 properties.\n */\n utm_creative_format: optional(noEmptyString),\n\n /**\n * Targeting criteria applied to a campaign, for example, remarketing, prospecting,\n * utm_marketing_tactic is not currently reported in Google Analytics 4 properties.\n * */\n utm_marketing_tactic: optional(noEmptyString),\n});\n\nexport type CreateTrackEventDTO = z.output<typeof createTrackEventSchema>;\nexport type CreateFeedbackDTO = z.output<typeof createFeedbackSchema>;\nexport type CreateLinkDTO = z.output<typeof createLinkSchema>;\nexport type CreateVisitorDTO = z.output<typeof createVisitorSchema>;\nexport type UserProvidedDataDTO = z.output<typeof userProvidedDataSchema>;\nexport type UpdateVisitorDTO = z.output<typeof updateVisitorSchema>;\n"],"mappings":";;AA4BA,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;;;;;;;AAQvB,MAAM,eAAe,KACnB,OAAO,GACP,WAAW,UAAU,MAAM,MAAM,GAAG,gBAAgB,CAAC,CACvD;;;;;;;;;;;AAYA,SAAS,eAAkB,MAA4C;CACrE,MAAM,SAA4B,CAAC;CACnC,IAAI,QAAQ;CACZ,KAAK,MAAM,CAAC,QAAQ,UAAU,OAAO,QAAQ,IAAI,GAAG;EAClD,IAAI,SAAS,gBAAgB;EAC7B,MAAM,MAAM,OAAO,KAAK;EACxB,IAAI,CAAC,OAAO,IAAI,SAAS,gBAAgB;EACzC,OAAO,OAAO;EACd;CACF;CACA,OAAO;AACT;AAEA,MAAM,QAAQ,MACZ,KACE,OAAO,OAAO,GAAG,MAAM;CAAC;CAAc,OAAO;CAAG,QAAQ;CAAGA,OAAM;AAAC,CAAC,CAAC,GACpE,UAAU,cAAc,CAC1B,CACF;AAEA,MAAa,gBAAgB;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAa,mBAAmB,CAAC,eAAe,YAAY;AAE5D,MAAa,aAAa,OAAO;CAC/B,IAAI,SAAS,OAAO,CAAC;CACrB,SAAS,SAAS,OAAO,CAAC;CAC1B,YAAY,SAAS,OAAO,CAAC;CAC7B,SAAS,SAAS,OAAO,CAAC;CAC1B,cAAc,SAAS,OAAO,CA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session.cjs
CHANGED
|
@@ -1,24 +1,76 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_setup_index = require("./index.cjs");
|
|
3
|
+
const require_constants_storage = require("../constants/storage.cjs");
|
|
2
4
|
let uuid = require("uuid");
|
|
3
5
|
//#region src/setup/session.ts
|
|
4
6
|
const SESSION_TIMEOUT = 1800 * 1e3;
|
|
7
|
+
/**
|
|
8
|
+
* `<version>.<id>.<lastEventTime>`, compact and cookie-safe rather than JSON: `{`, `"`
|
|
9
|
+
* and `,` all have to be percent-encoded in a cookie, and a host that wants one session across
|
|
10
|
+
* its subdomains will hand `setupAnalytics` a cookie-backed `storage`, where this has to survive
|
|
11
|
+
* unchanged. A uuidv7 contains no dots, so the record splits cleanly.
|
|
12
|
+
*
|
|
13
|
+
* The version guards a change the parser could not otherwise survive. A field appended to the end
|
|
14
|
+
* does not need one — a short record simply leaves it undefined.
|
|
15
|
+
*/
|
|
16
|
+
const VERSION = "1";
|
|
17
|
+
function readSession() {
|
|
18
|
+
const raw = require_setup_index.config.storage.getItem(require_constants_storage.keys.session);
|
|
19
|
+
if (!raw) return void 0;
|
|
20
|
+
const [version, id, lastEventTime] = raw.split(".");
|
|
21
|
+
if (version !== VERSION || !id) return void 0;
|
|
22
|
+
const parsed = {
|
|
23
|
+
id,
|
|
24
|
+
lastEventTime: Number(lastEventTime)
|
|
25
|
+
};
|
|
26
|
+
if (!Number.isFinite(parsed.lastEventTime)) return void 0;
|
|
27
|
+
return parsed;
|
|
28
|
+
}
|
|
29
|
+
function writeSession({ id, lastEventTime }) {
|
|
30
|
+
require_setup_index.config.storage.setItem(require_constants_storage.keys.session, `${VERSION}.${id}.${lastEventTime}`);
|
|
31
|
+
}
|
|
5
32
|
var Session = class {
|
|
6
33
|
constructor() {
|
|
7
|
-
this.
|
|
34
|
+
this.touch = (eventTime, lastEventTime = eventTime) => {
|
|
35
|
+
const stored = readSession();
|
|
36
|
+
if (stored && eventTime - stored.lastEventTime <= 18e5) {
|
|
37
|
+
writeSession({
|
|
38
|
+
...stored,
|
|
39
|
+
lastEventTime: Math.max(stored.lastEventTime, lastEventTime)
|
|
40
|
+
});
|
|
41
|
+
return {
|
|
42
|
+
id: stored.id,
|
|
43
|
+
started: false
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
this.accumulatedTime = 0;
|
|
47
|
+
this.startTime = Date.now();
|
|
48
|
+
const session = {
|
|
49
|
+
id: (0, uuid.v7)(),
|
|
50
|
+
lastEventTime
|
|
51
|
+
};
|
|
52
|
+
writeSession(session);
|
|
53
|
+
return {
|
|
54
|
+
id: session.id,
|
|
55
|
+
started: true
|
|
56
|
+
};
|
|
57
|
+
};
|
|
58
|
+
this.extend = () => {
|
|
59
|
+
const stored = readSession();
|
|
60
|
+
if (!stored) return this.touch(Date.now()).id;
|
|
61
|
+
const now = Date.now();
|
|
62
|
+
if (now - stored.lastEventTime <= 18e5) writeSession({
|
|
63
|
+
...stored,
|
|
64
|
+
lastEventTime: now
|
|
65
|
+
});
|
|
66
|
+
return stored.id;
|
|
67
|
+
};
|
|
8
68
|
this.isActive = () => this.active;
|
|
9
69
|
this.isVisible = () => this.visible;
|
|
10
70
|
this.isFocused = () => this.focused;
|
|
11
|
-
this.isExpired = () => Date.now() - this.lastActiveTime > SESSION_TIMEOUT;
|
|
12
|
-
this.updateLastActiveTime = () => {
|
|
13
|
-
this.lastActiveTime = Date.now();
|
|
14
|
-
};
|
|
15
71
|
this.updateActive = (active) => {
|
|
16
72
|
this.active = active;
|
|
17
73
|
};
|
|
18
|
-
this.refresh = () => {
|
|
19
|
-
this.id = (0, uuid.v7)();
|
|
20
|
-
this.lastActiveTime = Date.now();
|
|
21
|
-
};
|
|
22
74
|
this.updateAccumulator = () => {
|
|
23
75
|
const now = Date.now();
|
|
24
76
|
if (this.focused && this.visible && this.active) {
|
|
@@ -29,7 +81,6 @@ var Session = class {
|
|
|
29
81
|
};
|
|
30
82
|
this.focus = () => {
|
|
31
83
|
this.updateAccumulator();
|
|
32
|
-
this.updateLastActiveTime();
|
|
33
84
|
this.focused = true;
|
|
34
85
|
};
|
|
35
86
|
this.blur = () => {
|
|
@@ -38,7 +89,6 @@ var Session = class {
|
|
|
38
89
|
};
|
|
39
90
|
this.pageshow = () => {
|
|
40
91
|
this.updateAccumulator();
|
|
41
|
-
this.updateLastActiveTime();
|
|
42
92
|
this.active = true;
|
|
43
93
|
};
|
|
44
94
|
this.pagehide = () => {
|
|
@@ -47,7 +97,6 @@ var Session = class {
|
|
|
47
97
|
};
|
|
48
98
|
this.visibilitychange = (state) => {
|
|
49
99
|
this.updateAccumulator();
|
|
50
|
-
if (state === "visible") this.updateLastActiveTime();
|
|
51
100
|
this.visible = state === "visible";
|
|
52
101
|
};
|
|
53
102
|
this.flush = () => {
|
|
@@ -56,9 +105,7 @@ var Session = class {
|
|
|
56
105
|
this.accumulatedTime = 0;
|
|
57
106
|
return engagementTime;
|
|
58
107
|
};
|
|
59
|
-
this.id = (0, uuid.v7)();
|
|
60
108
|
this.startTime = Date.now();
|
|
61
|
-
this.lastActiveTime = Date.now();
|
|
62
109
|
this.accumulatedTime = 0;
|
|
63
110
|
this.active = true;
|
|
64
111
|
this.visible = typeof document !== "undefined" ? document.visibilityState === "visible" : true;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.cjs","names":[],"sources":["../../src/setup/session.ts"],"sourcesContent":["import { v7 as uuidv7 } from 'uuid';\n\nexport const SESSION_TIMEOUT = 30 * 60 * 1000;\n\
|
|
1
|
+
{"version":3,"file":"session.cjs","names":["config","keys"],"sources":["../../src/setup/session.ts"],"sourcesContent":["import { v7 as uuidv7 } from 'uuid';\nimport { keys } from '../constants/storage';\nimport { config } from './index';\n\nexport const SESSION_TIMEOUT = 30 * 60 * 1000;\n\n/**\n * The part of a session that outlives the page: its identity, and the clock the timeout is\n * measured against. GA4 keeps these in its `_ga_<container>` cookie — alongside the engaged flag,\n * which arrives with `session_engaged` later — and rereads them for every event, which is what\n * makes a session survive a reload, span a whole multipage visit, and stay shared between two\n * tabs of the same site. Holding them in memory instead, as this did, starts a new session on\n * every full navigation and gives every tab one of its own.\n */\ninterface StoredSession {\n id: string;\n /** When the last event was sent. The timeout is measured from here, and only from here. */\n lastEventTime: number;\n}\n\n/** The session an event belongs to, and whether that event is the one that started it. */\ninterface SessionForEvent {\n id: string;\n started: boolean;\n}\n\n/**\n * `<version>.<id>.<lastEventTime>`, compact and cookie-safe rather than JSON: `{`, `\"`\n * and `,` all have to be percent-encoded in a cookie, and a host that wants one session across\n * its subdomains will hand `setupAnalytics` a cookie-backed `storage`, where this has to survive\n * unchanged. A uuidv7 contains no dots, so the record splits cleanly.\n *\n * The version guards a change the parser could not otherwise survive. A field appended to the end\n * does not need one — a short record simply leaves it undefined.\n */\nconst VERSION = '1';\n\nfunction readSession(): StoredSession | undefined {\n const raw = config.storage.getItem(keys.session);\n if (!raw) return undefined;\n\n const [version, id, lastEventTime] = raw.split('.');\n if (version !== VERSION || !id) return undefined;\n\n const parsed = { id, lastEventTime: Number(lastEventTime) };\n if (!Number.isFinite(parsed.lastEventTime)) return undefined;\n return parsed;\n}\n\nfunction writeSession({ id, lastEventTime }: StoredSession) {\n config.storage.setItem(keys.session, `${VERSION}.${id}.${lastEventTime}`);\n}\n\nclass Session {\n /**\n * Engagement is deliberately not stored: it is the time this page has accrued and not yet\n * reported, so it belongs to the page, not to the session. GA4 draws the same line — its cookie\n * carries the session, while the engagement timer lives and dies with the document.\n */\n private startTime: number;\n private accumulatedTime: number;\n\n private active: boolean;\n private visible: boolean;\n private focused: boolean;\n\n constructor() {\n this.startTime = Date.now();\n this.accumulatedTime = 0;\n\n this.active = true;\n this.visible = typeof document !== 'undefined' ? document.visibilityState === 'visible' : true;\n this.focused = typeof document !== 'undefined' ? document.hasFocus() : true;\n }\n\n /**\n * The session a batch of events belongs to: read the stored one, start a new one if it has\n * timed out or there is none, stamp it with when those events happened and write it back. Every\n * event goes through here, exactly as GA4 rereads and rewrites its cookie per event — caching\n * the session in memory would put the tabs back out of step with each other.\n */\n touch = (eventTime: number, lastEventTime = eventTime): SessionForEvent => {\n const stored = readSession();\n\n if (stored && eventTime - stored.lastEventTime <= SESSION_TIMEOUT) {\n // `Math.max`, because a batch that waited in a frozen tab can be older than what another\n // tab has since written, and a session must never be shortened by a late arrival.\n writeSession({ ...stored, lastEventTime: Math.max(stored.lastEventTime, lastEventTime) });\n return { id: stored.id, started: false };\n }\n\n // Engagement the previous session accrued but never reported dies with it rather than being\n // handed to its successor. GA4 does the same on `session_start`.\n this.accumulatedTime = 0;\n // Wall clock, not `eventTime`: this anchors the engagement timer for the page in front of the\n // visitor now, which a batch describing something that happened an hour ago says nothing about.\n this.startTime = Date.now();\n\n const session: StoredSession = { id: uuidv7(), lastEventTime };\n writeSession(session);\n return { id: session.id, started: true };\n };\n\n /**\n * The id for an event that must not start a session — the `pagehide` beacon, which reports what\n * the session now ending accrued. A live session is extended, as any event extends it; one\n * already past its timeout still owns that engagement, so its id comes back without being\n * revived into a session no `session_start` ever announced.\n */\n extend = (): string => {\n const stored = readSession();\n if (!stored) return this.touch(Date.now()).id;\n\n const now = Date.now();\n if (now - stored.lastEventTime <= SESSION_TIMEOUT) {\n writeSession({ ...stored, lastEventTime: now });\n }\n return stored.id;\n };\n\n isActive = () => this.active;\n isVisible = () => this.visible;\n isFocused = () => this.focused;\n\n updateActive = (active: boolean) => {\n this.active = active;\n };\n\n updateAccumulator = () => {\n const now = Date.now();\n if (this.focused && this.visible && this.active) {\n const delta = now - this.startTime;\n if (delta > 0 && delta < SESSION_TIMEOUT) {\n this.accumulatedTime += delta;\n }\n }\n this.startTime = now;\n };\n\n focus = () => {\n this.updateAccumulator();\n this.focused = true;\n };\n\n blur = () => {\n this.updateAccumulator();\n this.focused = false;\n };\n\n pageshow = () => {\n this.updateAccumulator();\n this.active = true;\n };\n\n pagehide = () => {\n this.updateAccumulator();\n this.active = false;\n };\n\n visibilitychange = (state: DocumentVisibilityState) => {\n this.updateAccumulator();\n this.visible = state === 'visible';\n };\n\n flush = () => {\n this.updateAccumulator();\n const engagementTime = this.accumulatedTime;\n this.accumulatedTime = 0;\n return engagementTime;\n };\n}\n\nlet session: Session | undefined;\n\n/**\n * The session, built the first time something asks for it.\n *\n * Deliberately not a module-scope `new Session()`. The constructor calls\n * `uuidv7()`, `uuid` draws its bytes from `crypto.getRandomValues`, and\n * Cloudflare Workers reject that outside a request handler:\n *\n * Disallowed operation called within global scope. Asynchronous I/O\n * (ex: fetch() or connect()), setting a timeout, and generating random\n * values are not allowed within global scope.\n *\n * Module scope in a Worker is evaluated once when the isolate boots and is\n * then shared by every request that isolate serves, so a random value drawn\n * there would be the same for all of them — which is why the runtime refuses\n * to produce one. A host that server-renders on Workers reaches this module\n * through `track()` on the server as well, and the throw happened as the\n * isolate booted, taking down every route before a component rendered.\n *\n * Everything here is per-visitor browser or app state, so deferring the\n * construction costs nothing and buys two things: the server bundle can be\n * evaluated, and `startTime` marks when the session actually began rather\n * than when the isolate happened to start.\n */\nexport function getSession() {\n return (session ??= new Session());\n}\n"],"mappings":";;;;;AAIA,MAAa,kBAAkB,OAAU;;;;;;;;;;AA+BzC,MAAM,UAAU;AAEhB,SAAS,cAAyC;CAChD,MAAM,MAAMA,oBAAAA,OAAO,QAAQ,QAAQC,0BAAAA,KAAK,OAAO;CAC/C,IAAI,CAAC,KAAK,OAAO,KAAA;CAEjB,MAAM,CAAC,SAAS,IAAI,iBAAiB,IAAI,MAAM,GAAG;CAClD,IAAI,YAAY,WAAW,CAAC,IAAI,OAAO,KAAA;CAEvC,MAAM,SAAS;EAAE;EAAI,eAAe,OAAO,aAAa;CAAE;CAC1D,IAAI,CAAC,OAAO,SAAS,OAAO,aAAa,GAAG,OAAO,KAAA;CACnD,OAAO;AACT;AAEA,SAAS,aAAa,EAAE,IAAI,iBAAgC;CAC1D,oBAAA,OAAO,QAAQ,QAAQA,0BAAAA,KAAK,SAAS,GAAG,QAAQ,GAA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AA,iBAAA;GACf,KAAK,kBAAkB;GACvB,KAAK,SAAS;EAChB;EAEiB,KAAA,iBAAA;GACf,KAAK,kBAAkB;GACvB,KAAK,SAAS;EAChB;EAEoB,KAAA,oBAAA,UAAmC;GACrD,KAAK,kBAAkB;GACvB,KAAK,UAAU,UAAU;EAC3B;EAEc,KAAA,cAAA;GACZ,KAAK,kBAAkB;GACvB,MAAM,iBAAiB,KAAK;GAC5B,KAAK,kBAAkB;GACvB,OAAO;EACT;EAtGE,KAAK,YAAY,KAAK,IAAI;EAC1B,KAAK,kBAAkB;EAEvB,KAAK,SAAS;EACd,KAAK,UAAU,OAAO,aAAa,cAAc,SAAS,oBAAoB,YAAY;EAC1F,KAAK,UAAU,OAAO,aAAa,cAAc,SAAS,SAAS,IAAI;CACzE;AAiGF;AAEA,IAAI;;;;;;;;;;;;;;;;;;;;;;;;AAyBJ,SAAgB,aAAa;CAC3B,OAAQ,YAAY,IAAI,QAAQ;AAClC"}
|
package/dist/setup/session.d.cts
CHANGED
|
@@ -1,22 +1,40 @@
|
|
|
1
1
|
//#region src/setup/session.d.ts
|
|
2
2
|
declare const SESSION_TIMEOUT: number;
|
|
3
|
+
/** The session an event belongs to, and whether that event is the one that started it. */
|
|
4
|
+
interface SessionForEvent {
|
|
5
|
+
id: string;
|
|
6
|
+
started: boolean;
|
|
7
|
+
}
|
|
3
8
|
declare class Session {
|
|
4
|
-
|
|
9
|
+
/**
|
|
10
|
+
* Engagement is deliberately not stored: it is the time this page has accrued and not yet
|
|
11
|
+
* reported, so it belongs to the page, not to the session. GA4 draws the same line — its cookie
|
|
12
|
+
* carries the session, while the engagement timer lives and dies with the document.
|
|
13
|
+
*/
|
|
5
14
|
private startTime;
|
|
6
|
-
private lastActiveTime;
|
|
7
15
|
private accumulatedTime;
|
|
8
16
|
private active;
|
|
9
17
|
private visible;
|
|
10
18
|
private focused;
|
|
11
19
|
constructor();
|
|
12
|
-
|
|
20
|
+
/**
|
|
21
|
+
* The session a batch of events belongs to: read the stored one, start a new one if it has
|
|
22
|
+
* timed out or there is none, stamp it with when those events happened and write it back. Every
|
|
23
|
+
* event goes through here, exactly as GA4 rereads and rewrites its cookie per event — caching
|
|
24
|
+
* the session in memory would put the tabs back out of step with each other.
|
|
25
|
+
*/
|
|
26
|
+
touch: (eventTime: number, lastEventTime?: number) => SessionForEvent;
|
|
27
|
+
/**
|
|
28
|
+
* The id for an event that must not start a session — the `pagehide` beacon, which reports what
|
|
29
|
+
* the session now ending accrued. A live session is extended, as any event extends it; one
|
|
30
|
+
* already past its timeout still owns that engagement, so its id comes back without being
|
|
31
|
+
* revived into a session no `session_start` ever announced.
|
|
32
|
+
*/
|
|
33
|
+
extend: () => string;
|
|
13
34
|
isActive: () => boolean;
|
|
14
35
|
isVisible: () => boolean;
|
|
15
36
|
isFocused: () => boolean;
|
|
16
|
-
isExpired: () => boolean;
|
|
17
|
-
updateLastActiveTime: () => void;
|
|
18
37
|
updateActive: (active: boolean) => void;
|
|
19
|
-
refresh: () => void;
|
|
20
38
|
updateAccumulator: () => void;
|
|
21
39
|
focus: () => void;
|
|
22
40
|
blur: () => void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.d.cts","names":[],"sources":["../../src/setup/session.ts"],"mappings":";
|
|
1
|
+
{"version":3,"file":"session.d.cts","names":[],"sources":["../../src/setup/session.ts"],"mappings":";cAIa;;UAiBH;EACR;EACA;;cA8BI;;;;;;UAMI;UACA;UAEA;UACA;UACA;EAER;;;;;;;EAeA,QAAK,mBAAqB,2BAA8B;;;;;;;EA4BxD;EAWA;EACA;EACA;EAEA,eAAY;EAIZ;EAWA;EAKA;EAKA;EAKA;EAKA,mBAAgB,OAAW;EAK3B;;;;;;;;;;;;;;;;;;;;;;;;;iBAiCc,cAAU"}
|
package/dist/setup/session.d.mts
CHANGED
|
@@ -1,22 +1,40 @@
|
|
|
1
1
|
//#region src/setup/session.d.ts
|
|
2
2
|
declare const SESSION_TIMEOUT: number;
|
|
3
|
+
/** The session an event belongs to, and whether that event is the one that started it. */
|
|
4
|
+
interface SessionForEvent {
|
|
5
|
+
id: string;
|
|
6
|
+
started: boolean;
|
|
7
|
+
}
|
|
3
8
|
declare class Session {
|
|
4
|
-
|
|
9
|
+
/**
|
|
10
|
+
* Engagement is deliberately not stored: it is the time this page has accrued and not yet
|
|
11
|
+
* reported, so it belongs to the page, not to the session. GA4 draws the same line — its cookie
|
|
12
|
+
* carries the session, while the engagement timer lives and dies with the document.
|
|
13
|
+
*/
|
|
5
14
|
private startTime;
|
|
6
|
-
private lastActiveTime;
|
|
7
15
|
private accumulatedTime;
|
|
8
16
|
private active;
|
|
9
17
|
private visible;
|
|
10
18
|
private focused;
|
|
11
19
|
constructor();
|
|
12
|
-
|
|
20
|
+
/**
|
|
21
|
+
* The session a batch of events belongs to: read the stored one, start a new one if it has
|
|
22
|
+
* timed out or there is none, stamp it with when those events happened and write it back. Every
|
|
23
|
+
* event goes through here, exactly as GA4 rereads and rewrites its cookie per event — caching
|
|
24
|
+
* the session in memory would put the tabs back out of step with each other.
|
|
25
|
+
*/
|
|
26
|
+
touch: (eventTime: number, lastEventTime?: number) => SessionForEvent;
|
|
27
|
+
/**
|
|
28
|
+
* The id for an event that must not start a session — the `pagehide` beacon, which reports what
|
|
29
|
+
* the session now ending accrued. A live session is extended, as any event extends it; one
|
|
30
|
+
* already past its timeout still owns that engagement, so its id comes back without being
|
|
31
|
+
* revived into a session no `session_start` ever announced.
|
|
32
|
+
*/
|
|
33
|
+
extend: () => string;
|
|
13
34
|
isActive: () => boolean;
|
|
14
35
|
isVisible: () => boolean;
|
|
15
36
|
isFocused: () => boolean;
|
|
16
|
-
isExpired: () => boolean;
|
|
17
|
-
updateLastActiveTime: () => void;
|
|
18
37
|
updateActive: (active: boolean) => void;
|
|
19
|
-
refresh: () => void;
|
|
20
38
|
updateAccumulator: () => void;
|
|
21
39
|
focus: () => void;
|
|
22
40
|
blur: () => void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.d.mts","names":[],"sources":["../../src/setup/session.ts"],"mappings":";
|
|
1
|
+
{"version":3,"file":"session.d.mts","names":[],"sources":["../../src/setup/session.ts"],"mappings":";cAIa;;UAiBH;EACR;EACA;;cA8BI;;;;;;UAMI;UACA;UAEA;UACA;UACA;EAER;;;;;;;EAeA,QAAK,mBAAqB,2BAA8B;;;;;;;EA4BxD;EAWA;EACA;EACA;EAEA,eAAY;EAIZ;EAWA;EAKA;EAKA;EAKA;EAKA,mBAAgB,OAAW;EAK3B;;;;;;;;;;;;;;;;;;;;;;;;;iBAiCc,cAAU"}
|
package/dist/setup/session.mjs
CHANGED
|
@@ -1,23 +1,75 @@
|
|
|
1
|
+
import { config } from "./index.mjs";
|
|
2
|
+
import { keys } from "../constants/storage.mjs";
|
|
1
3
|
import { v7 } from "uuid";
|
|
2
4
|
//#region src/setup/session.ts
|
|
3
5
|
const SESSION_TIMEOUT = 1800 * 1e3;
|
|
6
|
+
/**
|
|
7
|
+
* `<version>.<id>.<lastEventTime>`, compact and cookie-safe rather than JSON: `{`, `"`
|
|
8
|
+
* and `,` all have to be percent-encoded in a cookie, and a host that wants one session across
|
|
9
|
+
* its subdomains will hand `setupAnalytics` a cookie-backed `storage`, where this has to survive
|
|
10
|
+
* unchanged. A uuidv7 contains no dots, so the record splits cleanly.
|
|
11
|
+
*
|
|
12
|
+
* The version guards a change the parser could not otherwise survive. A field appended to the end
|
|
13
|
+
* does not need one — a short record simply leaves it undefined.
|
|
14
|
+
*/
|
|
15
|
+
const VERSION = "1";
|
|
16
|
+
function readSession() {
|
|
17
|
+
const raw = config.storage.getItem(keys.session);
|
|
18
|
+
if (!raw) return void 0;
|
|
19
|
+
const [version, id, lastEventTime] = raw.split(".");
|
|
20
|
+
if (version !== VERSION || !id) return void 0;
|
|
21
|
+
const parsed = {
|
|
22
|
+
id,
|
|
23
|
+
lastEventTime: Number(lastEventTime)
|
|
24
|
+
};
|
|
25
|
+
if (!Number.isFinite(parsed.lastEventTime)) return void 0;
|
|
26
|
+
return parsed;
|
|
27
|
+
}
|
|
28
|
+
function writeSession({ id, lastEventTime }) {
|
|
29
|
+
config.storage.setItem(keys.session, `${VERSION}.${id}.${lastEventTime}`);
|
|
30
|
+
}
|
|
4
31
|
var Session = class {
|
|
5
32
|
constructor() {
|
|
6
|
-
this.
|
|
33
|
+
this.touch = (eventTime, lastEventTime = eventTime) => {
|
|
34
|
+
const stored = readSession();
|
|
35
|
+
if (stored && eventTime - stored.lastEventTime <= 18e5) {
|
|
36
|
+
writeSession({
|
|
37
|
+
...stored,
|
|
38
|
+
lastEventTime: Math.max(stored.lastEventTime, lastEventTime)
|
|
39
|
+
});
|
|
40
|
+
return {
|
|
41
|
+
id: stored.id,
|
|
42
|
+
started: false
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
this.accumulatedTime = 0;
|
|
46
|
+
this.startTime = Date.now();
|
|
47
|
+
const session = {
|
|
48
|
+
id: v7(),
|
|
49
|
+
lastEventTime
|
|
50
|
+
};
|
|
51
|
+
writeSession(session);
|
|
52
|
+
return {
|
|
53
|
+
id: session.id,
|
|
54
|
+
started: true
|
|
55
|
+
};
|
|
56
|
+
};
|
|
57
|
+
this.extend = () => {
|
|
58
|
+
const stored = readSession();
|
|
59
|
+
if (!stored) return this.touch(Date.now()).id;
|
|
60
|
+
const now = Date.now();
|
|
61
|
+
if (now - stored.lastEventTime <= 18e5) writeSession({
|
|
62
|
+
...stored,
|
|
63
|
+
lastEventTime: now
|
|
64
|
+
});
|
|
65
|
+
return stored.id;
|
|
66
|
+
};
|
|
7
67
|
this.isActive = () => this.active;
|
|
8
68
|
this.isVisible = () => this.visible;
|
|
9
69
|
this.isFocused = () => this.focused;
|
|
10
|
-
this.isExpired = () => Date.now() - this.lastActiveTime > SESSION_TIMEOUT;
|
|
11
|
-
this.updateLastActiveTime = () => {
|
|
12
|
-
this.lastActiveTime = Date.now();
|
|
13
|
-
};
|
|
14
70
|
this.updateActive = (active) => {
|
|
15
71
|
this.active = active;
|
|
16
72
|
};
|
|
17
|
-
this.refresh = () => {
|
|
18
|
-
this.id = v7();
|
|
19
|
-
this.lastActiveTime = Date.now();
|
|
20
|
-
};
|
|
21
73
|
this.updateAccumulator = () => {
|
|
22
74
|
const now = Date.now();
|
|
23
75
|
if (this.focused && this.visible && this.active) {
|
|
@@ -28,7 +80,6 @@ var Session = class {
|
|
|
28
80
|
};
|
|
29
81
|
this.focus = () => {
|
|
30
82
|
this.updateAccumulator();
|
|
31
|
-
this.updateLastActiveTime();
|
|
32
83
|
this.focused = true;
|
|
33
84
|
};
|
|
34
85
|
this.blur = () => {
|
|
@@ -37,7 +88,6 @@ var Session = class {
|
|
|
37
88
|
};
|
|
38
89
|
this.pageshow = () => {
|
|
39
90
|
this.updateAccumulator();
|
|
40
|
-
this.updateLastActiveTime();
|
|
41
91
|
this.active = true;
|
|
42
92
|
};
|
|
43
93
|
this.pagehide = () => {
|
|
@@ -46,7 +96,6 @@ var Session = class {
|
|
|
46
96
|
};
|
|
47
97
|
this.visibilitychange = (state) => {
|
|
48
98
|
this.updateAccumulator();
|
|
49
|
-
if (state === "visible") this.updateLastActiveTime();
|
|
50
99
|
this.visible = state === "visible";
|
|
51
100
|
};
|
|
52
101
|
this.flush = () => {
|
|
@@ -55,9 +104,7 @@ var Session = class {
|
|
|
55
104
|
this.accumulatedTime = 0;
|
|
56
105
|
return engagementTime;
|
|
57
106
|
};
|
|
58
|
-
this.id = v7();
|
|
59
107
|
this.startTime = Date.now();
|
|
60
|
-
this.lastActiveTime = Date.now();
|
|
61
108
|
this.accumulatedTime = 0;
|
|
62
109
|
this.active = true;
|
|
63
110
|
this.visible = typeof document !== "undefined" ? document.visibilityState === "visible" : true;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.mjs","names":["uuidv7"],"sources":["../../src/setup/session.ts"],"sourcesContent":["import { v7 as uuidv7 } from 'uuid';\n\nexport const SESSION_TIMEOUT = 30 * 60 * 1000;\n\
|
|
1
|
+
{"version":3,"file":"session.mjs","names":["uuidv7"],"sources":["../../src/setup/session.ts"],"sourcesContent":["import { v7 as uuidv7 } from 'uuid';\nimport { keys } from '../constants/storage';\nimport { config } from './index';\n\nexport const SESSION_TIMEOUT = 30 * 60 * 1000;\n\n/**\n * The part of a session that outlives the page: its identity, and the clock the timeout is\n * measured against. GA4 keeps these in its `_ga_<container>` cookie — alongside the engaged flag,\n * which arrives with `session_engaged` later — and rereads them for every event, which is what\n * makes a session survive a reload, span a whole multipage visit, and stay shared between two\n * tabs of the same site. Holding them in memory instead, as this did, starts a new session on\n * every full navigation and gives every tab one of its own.\n */\ninterface StoredSession {\n id: string;\n /** When the last event was sent. The timeout is measured from here, and only from here. */\n lastEventTime: number;\n}\n\n/** The session an event belongs to, and whether that event is the one that started it. */\ninterface SessionForEvent {\n id: string;\n started: boolean;\n}\n\n/**\n * `<version>.<id>.<lastEventTime>`, compact and cookie-safe rather than JSON: `{`, `\"`\n * and `,` all have to be percent-encoded in a cookie, and a host that wants one session across\n * its subdomains will hand `setupAnalytics` a cookie-backed `storage`, where this has to survive\n * unchanged. A uuidv7 contains no dots, so the record splits cleanly.\n *\n * The version guards a change the parser could not otherwise survive. A field appended to the end\n * does not need one — a short record simply leaves it undefined.\n */\nconst VERSION = '1';\n\nfunction readSession(): StoredSession | undefined {\n const raw = config.storage.getItem(keys.session);\n if (!raw) return undefined;\n\n const [version, id, lastEventTime] = raw.split('.');\n if (version !== VERSION || !id) return undefined;\n\n const parsed = { id, lastEventTime: Number(lastEventTime) };\n if (!Number.isFinite(parsed.lastEventTime)) return undefined;\n return parsed;\n}\n\nfunction writeSession({ id, lastEventTime }: StoredSession) {\n config.storage.setItem(keys.session, `${VERSION}.${id}.${lastEventTime}`);\n}\n\nclass Session {\n /**\n * Engagement is deliberately not stored: it is the time this page has accrued and not yet\n * reported, so it belongs to the page, not to the session. GA4 draws the same line — its cookie\n * carries the session, while the engagement timer lives and dies with the document.\n */\n private startTime: number;\n private accumulatedTime: number;\n\n private active: boolean;\n private visible: boolean;\n private focused: boolean;\n\n constructor() {\n this.startTime = Date.now();\n this.accumulatedTime = 0;\n\n this.active = true;\n this.visible = typeof document !== 'undefined' ? document.visibilityState === 'visible' : true;\n this.focused = typeof document !== 'undefined' ? document.hasFocus() : true;\n }\n\n /**\n * The session a batch of events belongs to: read the stored one, start a new one if it has\n * timed out or there is none, stamp it with when those events happened and write it back. Every\n * event goes through here, exactly as GA4 rereads and rewrites its cookie per event — caching\n * the session in memory would put the tabs back out of step with each other.\n */\n touch = (eventTime: number, lastEventTime = eventTime): SessionForEvent => {\n const stored = readSession();\n\n if (stored && eventTime - stored.lastEventTime <= SESSION_TIMEOUT) {\n // `Math.max`, because a batch that waited in a frozen tab can be older than what another\n // tab has since written, and a session must never be shortened by a late arrival.\n writeSession({ ...stored, lastEventTime: Math.max(stored.lastEventTime, lastEventTime) });\n return { id: stored.id, started: false };\n }\n\n // Engagement the previous session accrued but never reported dies with it rather than being\n // handed to its successor. GA4 does the same on `session_start`.\n this.accumulatedTime = 0;\n // Wall clock, not `eventTime`: this anchors the engagement timer for the page in front of the\n // visitor now, which a batch describing something that happened an hour ago says nothing about.\n this.startTime = Date.now();\n\n const session: StoredSession = { id: uuidv7(), lastEventTime };\n writeSession(session);\n return { id: session.id, started: true };\n };\n\n /**\n * The id for an event that must not start a session — the `pagehide` beacon, which reports what\n * the session now ending accrued. A live session is extended, as any event extends it; one\n * already past its timeout still owns that engagement, so its id comes back without being\n * revived into a session no `session_start` ever announced.\n */\n extend = (): string => {\n const stored = readSession();\n if (!stored) return this.touch(Date.now()).id;\n\n const now = Date.now();\n if (now - stored.lastEventTime <= SESSION_TIMEOUT) {\n writeSession({ ...stored, lastEventTime: now });\n }\n return stored.id;\n };\n\n isActive = () => this.active;\n isVisible = () => this.visible;\n isFocused = () => this.focused;\n\n updateActive = (active: boolean) => {\n this.active = active;\n };\n\n updateAccumulator = () => {\n const now = Date.now();\n if (this.focused && this.visible && this.active) {\n const delta = now - this.startTime;\n if (delta > 0 && delta < SESSION_TIMEOUT) {\n this.accumulatedTime += delta;\n }\n }\n this.startTime = now;\n };\n\n focus = () => {\n this.updateAccumulator();\n this.focused = true;\n };\n\n blur = () => {\n this.updateAccumulator();\n this.focused = false;\n };\n\n pageshow = () => {\n this.updateAccumulator();\n this.active = true;\n };\n\n pagehide = () => {\n this.updateAccumulator();\n this.active = false;\n };\n\n visibilitychange = (state: DocumentVisibilityState) => {\n this.updateAccumulator();\n this.visible = state === 'visible';\n };\n\n flush = () => {\n this.updateAccumulator();\n const engagementTime = this.accumulatedTime;\n this.accumulatedTime = 0;\n return engagementTime;\n };\n}\n\nlet session: Session | undefined;\n\n/**\n * The session, built the first time something asks for it.\n *\n * Deliberately not a module-scope `new Session()`. The constructor calls\n * `uuidv7()`, `uuid` draws its bytes from `crypto.getRandomValues`, and\n * Cloudflare Workers reject that outside a request handler:\n *\n * Disallowed operation called within global scope. Asynchronous I/O\n * (ex: fetch() or connect()), setting a timeout, and generating random\n * values are not allowed within global scope.\n *\n * Module scope in a Worker is evaluated once when the isolate boots and is\n * then shared by every request that isolate serves, so a random value drawn\n * there would be the same for all of them — which is why the runtime refuses\n * to produce one. A host that server-renders on Workers reaches this module\n * through `track()` on the server as well, and the throw happened as the\n * isolate booted, taking down every route before a component rendered.\n *\n * Everything here is per-visitor browser or app state, so deferring the\n * construction costs nothing and buys two things: the server bundle can be\n * evaluated, and `startTime` marks when the session actually began rather\n * than when the isolate happened to start.\n */\nexport function getSession() {\n return (session ??= new Session());\n}\n"],"mappings":";;;;AAIA,MAAa,kBAAkB,OAAU;;;;;;;;;;AA+BzC,MAAM,UAAU;AAEhB,SAAS,cAAyC;CAChD,MAAM,MAAM,OAAO,QAAQ,QAAQ,KAAK,OAAO;CAC/C,IAAI,CAAC,KAAK,OAAO,KAAA;CAEjB,MAAM,CAAC,SAAS,IAAI,iBAAiB,IAAI,MAAM,GAAG;CAClD,IAAI,YAAY,WAAW,CAAC,IAAI,OAAO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AAK;IACzB,IAAI,QAAQ,KAAK,QAAA,MACf,KAAK,mBAAmB;GAE5B;GACA,KAAK,YAAY;EACnB;EAEc,KAAA,cAAA;GACZ,KAAK,kBAAkB;GACvB,KAAK,UAAU;EACjB;EAEa,KAAA,aAAA;GACX,KAAK,kBAAkB;GACvB,KAAK,UAAU;EACjB;EAEiB,KAAA,iBAAA;GACf,KAAK,kBAAkB;GACvB,KAAK,SAAS;EAChB;EAEiB,KAAA,iBAAA;GACf,KAAK,kBAAkB;GACvB,KAAK,SAAS;EAChB;EAEoB,KAAA,oBAAA,UAAmC;GACrD,KAAK,kBAAkB;GACvB,KAAK,UAAU,UAAU;EAC3B;EAEc,KAAA,cAAA;GACZ,KAAK,kBAAkB;GACvB,MAAM,iBAAiB,KAAK;GAC5B,KAAK,kBAAkB;GACvB,OAAO;EACT;EAtGE,KAAK,YAAY,KAAK,IAAI;EAC1B,KAAK,kBAAkB;EAEvB,KAAK,SAAS;EACd,KAAK,UAAU,OAAO,aAAa,cAAc,SAAS,oBAAoB,YAAY;EAC1F,KAAK,UAAU,OAAO,aAAa,cAAc,SAAS,SAAS,IAAI;CACzE;AAiGF;AAEA,IAAI;;;;;;;;;;;;;;;;;;;;;;;;AAyBJ,SAAgB,aAAa;CAC3B,OAAQ,YAAY,IAAI,QAAQ;AAClC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middleware.cjs","names":["resolveClickIdCookies","toSetCookieHeaders"],"sources":["../../src/tanstack/middleware.ts"],"sourcesContent":["import { createMiddleware } from '@tanstack/react-start';\nimport { resolveClickIdCookies, toSetCookieHeaders } from '../click-id/index';\n\nexport interface ClickIdMiddlewareOptions {\n /** `Domain` attribute for the cookies, e.g. `.
|
|
1
|
+
{"version":3,"file":"middleware.cjs","names":["resolveClickIdCookies","toSetCookieHeaders"],"sources":["../../src/tanstack/middleware.ts"],"sourcesContent":["import { createMiddleware } from '@tanstack/react-start';\nimport { resolveClickIdCookies, toSetCookieHeaders } from '../click-id/index';\n\nexport interface ClickIdMiddlewareOptions {\n /** `Domain` attribute for the cookies, e.g. `.shware.io`. Omit for a host-only cookie. */\n domain?: string;\n /** `Secure` attribute, default true. Set false only for local http testing. */\n secure?: boolean;\n /** subdomainIndex for a freshly built `_fbc` (com=0, example.com=1, www.example.com=2). Default 1. */\n subdomainIndex?: number;\n /**\n * Re-issue a still-valid `_fbc` on every request as an ITP self-heal (restores the long-lived\n * HTTP cookie if the Meta Pixel's `document.cookie` write re-capped it to 24h in Safari). On by\n * default. Note it attaches a per-user `Set-Cookie` — and thus `no-store` — to every page\n * response carrying an `_fbc`, defeating CDN caching of those pages; set false to strictly follow\n * Meta's conditional-write rule and keep them cacheable. See {@link resolveClickIdCookies}.\n */\n refresh?: boolean;\n /**\n * Override the `Cache-Control` of a response we attach cookies to (default `private, no-store`).\n * A per-user `Set-Cookie` must never end up on a shared-cache entry, or one visitor's `_fbc` would\n * be served to everyone. Only set this false if you guarantee these responses are never cached.\n */\n cacheControl?: string | false;\n /**\n * Consent gate. Return false to skip setting cookies for this request (e.g. before the visitor has\n * granted consent where required). Runs per request with the incoming `Request`.\n */\n shouldPersist?: (request: Request) => boolean;\n}\n\n/**\n * TanStack Start request middleware that persists ad click-id cookies (`_fbc`, `_rdt_cid`) on the\n * document response.\n *\n * Setting `_fbc` here — on the top document via an HTTP `Set-Cookie` header, before any client JS\n * runs — is what Meta officially recommends and the only reliable way to keep the cookie alive for\n * 90 days in Safari: ITP caps JavaScript-set cookies on a fbclid-decorated landing page to 24\n * hours, and a document response is never classified as CNAME/IP cloaking (it is the reference the\n * browser measures cloaking against).\n *\n * Register it as a global request middleware:\n * ```ts\n * // start.ts\n * import { createStart } from '@tanstack/react-start'\n * import { clickIdMiddleware } from '@shware/analytics/tanstack'\n * export const startInstance = createStart(() => ({ requestMiddleware: [clickIdMiddleware] }))\n * ```\n *\n * reference: https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/fbp-and-fbc\n */\nexport function createClickIdMiddleware(options: ClickIdMiddlewareOptions = {}) {\n const { cacheControl = 'private, no-store' } = options;\n\n return createMiddleware({ type: 'request' }).server(async ({ request, next, handlerType }) => {\n const result = await next();\n\n // Skip serverFn RPC responses. 'router' covers SSR document requests *and* custom server\n // routes (API endpoints) — those also get cookies when the URL carries a click id.\n if (handlerType !== 'router') return result;\n if (options.shouldPersist && !options.shouldPersist(request)) return result;\n\n const { cookies } = resolveClickIdCookies({\n url: request.url,\n cookieHeader: request.headers.get('cookie'),\n domain: options.domain,\n secure: options.secure,\n subdomainIndex: options.subdomainIndex,\n refresh: options.refresh ?? true,\n });\n\n if (cookies.length > 0) {\n for (const header of toSetCookieHeaders(cookies)) {\n result.response.headers.append('set-cookie', header);\n }\n if (cacheControl !== false) {\n result.response.headers.set('cache-control', cacheControl);\n }\n }\n\n return result;\n });\n}\n\n/** Ready-to-register middleware with default options. */\nexport const clickIdMiddleware = createClickIdMiddleware();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAmDA,SAAgB,wBAAwB,UAAoC,CAAC,GAAG;CAC9E,MAAM,EAAE,eAAe,wBAAwB;CAE/C,QAAA,GAAA,sBAAA,iBAAA,CAAwB,EAAE,MAAM,UAAU,CAAC,CAAC,CAAC,OAAO,OAAO,EAAE,SAAS,MAAM,kBAAkB;EAC5F,MAAM,SAAS,MAAM,KAAK;EAI1B,IAAI,gBAAgB,UAAU,OAAO;EACrC,IAAI,QAAQ,iBAAiB,CAAC,QAAQ,cAAc,OAAO,GAAG,OAAO;EAErE,MAAM,EAAE,YAAYA,uBAAAA,sBAAsB;GACxC,KAAK,QAAQ;GACb,cAAc,QAAQ,QAAQ,IAAI,QAAQ;GAC1C,QAAQ,QAAQ;GAChB,QAAQ,QAAQ;GAChB,gBAAgB,QAAQ;GACxB,SAAS,QAAQ,WAAW;EAC9B,CAAC;EAED,IAAI,QAAQ,SAAS,GAAG;GACtB,KAAK,MAAM,UAAUC,uBAAAA,mBAAmB,OAAO,GAC7C,OAAO,SAAS,QAAQ,OAAO,cAAc,MAAM;GAErD,IAAI,iBAAiB,OACnB,OAAO,SAAS,QAAQ,IAAI,iBAAiB,YAAY;EAE7D;EAEA,OAAO;CACT,CAAC;AACH;;AAGA,MAAa,oBAAoB,wBAAwB"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
//#region src/tanstack/middleware.d.ts
|
|
2
2
|
interface ClickIdMiddlewareOptions {
|
|
3
|
-
/** `Domain` attribute for the cookies, e.g. `.
|
|
3
|
+
/** `Domain` attribute for the cookies, e.g. `.shware.io`. Omit for a host-only cookie. */
|
|
4
4
|
domain?: string;
|
|
5
5
|
/** `Secure` attribute, default true. Set false only for local http testing. */
|
|
6
6
|
secure?: boolean;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
//#region src/tanstack/middleware.d.ts
|
|
2
2
|
interface ClickIdMiddlewareOptions {
|
|
3
|
-
/** `Domain` attribute for the cookies, e.g. `.
|
|
3
|
+
/** `Domain` attribute for the cookies, e.g. `.shware.io`. Omit for a host-only cookie. */
|
|
4
4
|
domain?: string;
|
|
5
5
|
/** `Secure` attribute, default true. Set false only for local http testing. */
|
|
6
6
|
secure?: boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middleware.mjs","names":[],"sources":["../../src/tanstack/middleware.ts"],"sourcesContent":["import { createMiddleware } from '@tanstack/react-start';\nimport { resolveClickIdCookies, toSetCookieHeaders } from '../click-id/index';\n\nexport interface ClickIdMiddlewareOptions {\n /** `Domain` attribute for the cookies, e.g. `.
|
|
1
|
+
{"version":3,"file":"middleware.mjs","names":[],"sources":["../../src/tanstack/middleware.ts"],"sourcesContent":["import { createMiddleware } from '@tanstack/react-start';\nimport { resolveClickIdCookies, toSetCookieHeaders } from '../click-id/index';\n\nexport interface ClickIdMiddlewareOptions {\n /** `Domain` attribute for the cookies, e.g. `.shware.io`. Omit for a host-only cookie. */\n domain?: string;\n /** `Secure` attribute, default true. Set false only for local http testing. */\n secure?: boolean;\n /** subdomainIndex for a freshly built `_fbc` (com=0, example.com=1, www.example.com=2). Default 1. */\n subdomainIndex?: number;\n /**\n * Re-issue a still-valid `_fbc` on every request as an ITP self-heal (restores the long-lived\n * HTTP cookie if the Meta Pixel's `document.cookie` write re-capped it to 24h in Safari). On by\n * default. Note it attaches a per-user `Set-Cookie` — and thus `no-store` — to every page\n * response carrying an `_fbc`, defeating CDN caching of those pages; set false to strictly follow\n * Meta's conditional-write rule and keep them cacheable. See {@link resolveClickIdCookies}.\n */\n refresh?: boolean;\n /**\n * Override the `Cache-Control` of a response we attach cookies to (default `private, no-store`).\n * A per-user `Set-Cookie` must never end up on a shared-cache entry, or one visitor's `_fbc` would\n * be served to everyone. Only set this false if you guarantee these responses are never cached.\n */\n cacheControl?: string | false;\n /**\n * Consent gate. Return false to skip setting cookies for this request (e.g. before the visitor has\n * granted consent where required). Runs per request with the incoming `Request`.\n */\n shouldPersist?: (request: Request) => boolean;\n}\n\n/**\n * TanStack Start request middleware that persists ad click-id cookies (`_fbc`, `_rdt_cid`) on the\n * document response.\n *\n * Setting `_fbc` here — on the top document via an HTTP `Set-Cookie` header, before any client JS\n * runs — is what Meta officially recommends and the only reliable way to keep the cookie alive for\n * 90 days in Safari: ITP caps JavaScript-set cookies on a fbclid-decorated landing page to 24\n * hours, and a document response is never classified as CNAME/IP cloaking (it is the reference the\n * browser measures cloaking against).\n *\n * Register it as a global request middleware:\n * ```ts\n * // start.ts\n * import { createStart } from '@tanstack/react-start'\n * import { clickIdMiddleware } from '@shware/analytics/tanstack'\n * export const startInstance = createStart(() => ({ requestMiddleware: [clickIdMiddleware] }))\n * ```\n *\n * reference: https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/fbp-and-fbc\n */\nexport function createClickIdMiddleware(options: ClickIdMiddlewareOptions = {}) {\n const { cacheControl = 'private, no-store' } = options;\n\n return createMiddleware({ type: 'request' }).server(async ({ request, next, handlerType }) => {\n const result = await next();\n\n // Skip serverFn RPC responses. 'router' covers SSR document requests *and* custom server\n // routes (API endpoints) — those also get cookies when the URL carries a click id.\n if (handlerType !== 'router') return result;\n if (options.shouldPersist && !options.shouldPersist(request)) return result;\n\n const { cookies } = resolveClickIdCookies({\n url: request.url,\n cookieHeader: request.headers.get('cookie'),\n domain: options.domain,\n secure: options.secure,\n subdomainIndex: options.subdomainIndex,\n refresh: options.refresh ?? true,\n });\n\n if (cookies.length > 0) {\n for (const header of toSetCookieHeaders(cookies)) {\n result.response.headers.append('set-cookie', header);\n }\n if (cacheControl !== false) {\n result.response.headers.set('cache-control', cacheControl);\n }\n }\n\n return result;\n });\n}\n\n/** Ready-to-register middleware with default options. */\nexport const clickIdMiddleware = createClickIdMiddleware();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAmDA,SAAgB,wBAAwB,UAAoC,CAAC,GAAG;CAC9E,MAAM,EAAE,eAAe,wBAAwB;CAE/C,OAAO,iBAAiB,EAAE,MAAM,UAAU,CAAC,CAAC,CAAC,OAAO,OAAO,EAAE,SAAS,MAAM,kBAAkB;EAC5F,MAAM,SAAS,MAAM,KAAK;EAI1B,IAAI,gBAAgB,UAAU,OAAO;EACrC,IAAI,QAAQ,iBAAiB,CAAC,QAAQ,cAAc,OAAO,GAAG,OAAO;EAErE,MAAM,EAAE,YAAY,sBAAsB;GACxC,KAAK,QAAQ;GACb,cAAc,QAAQ,QAAQ,IAAI,QAAQ;GAC1C,QAAQ,QAAQ;GAChB,QAAQ,QAAQ;GAChB,gBAAgB,QAAQ;GACxB,SAAS,QAAQ,WAAW;EAC9B,CAAC;EAED,IAAI,QAAQ,SAAS,GAAG;GACtB,KAAK,MAAM,UAAU,mBAAmB,OAAO,GAC7C,OAAO,SAAS,QAAQ,OAAO,cAAc,MAAM;GAErD,IAAI,iBAAiB,OACnB,OAAO,SAAS,QAAQ,IAAI,iBAAiB,YAAY;EAE7D;EAEA,OAAO;CACT,CAAC;AACH;;AAGA,MAAa,oBAAoB,wBAAwB"}
|