bitsnap-react 1.7.1 → 1.9.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/README.md +130 -0
- package/dist/CartProvider-XWTLBIZ5.js +2 -0
- package/dist/CartProvider-XWTLBIZ5.js.map +1 -0
- package/dist/CartProvider-ZURLJNBW.mjs +2 -0
- package/dist/analytics.d.mts +28 -0
- package/dist/analytics.d.ts +28 -0
- package/dist/analytics.js +2 -0
- package/dist/analytics.js.map +1 -0
- package/dist/analytics.mjs +2 -0
- package/dist/catalog.d.mts +14 -1
- package/dist/catalog.d.ts +14 -1
- package/dist/catalog.js +1 -1
- package/dist/catalog.js.map +1 -1
- package/dist/catalog.mjs +1 -1
- package/dist/chunk-3IMJALBX.js +2 -0
- package/dist/chunk-3IMJALBX.js.map +1 -0
- package/dist/chunk-3UHPJ6NK.js +2 -0
- package/dist/chunk-3UHPJ6NK.js.map +1 -0
- package/dist/chunk-CO2P4FR5.js +2 -0
- package/dist/chunk-CO2P4FR5.js.map +1 -0
- package/dist/chunk-E6QVQEGZ.mjs +2 -0
- package/dist/chunk-E6QVQEGZ.mjs.map +1 -0
- package/dist/chunk-FHDFLSPW.js +2 -0
- package/dist/chunk-FHDFLSPW.js.map +1 -0
- package/dist/{chunk-6KQBDN7M.mjs → chunk-GN63ITLA.mjs} +2 -2
- package/dist/chunk-HKVMSMDF.mjs +2 -0
- package/dist/chunk-HKVMSMDF.mjs.map +1 -0
- package/dist/chunk-JSDGZ4NY.js +2 -0
- package/dist/chunk-JSDGZ4NY.js.map +1 -0
- package/dist/chunk-KG6RU37U.js +4 -0
- package/dist/chunk-KG6RU37U.js.map +1 -0
- package/dist/chunk-KOVKUJAW.mjs +2 -0
- package/dist/chunk-KOVKUJAW.mjs.map +1 -0
- package/dist/chunk-KOYBZORL.js +2 -0
- package/dist/chunk-KOYBZORL.js.map +1 -0
- package/dist/chunk-LJWS6ZRJ.mjs +2 -0
- package/dist/chunk-LJWS6ZRJ.mjs.map +1 -0
- package/dist/chunk-LZE2E4TE.mjs +4 -0
- package/dist/chunk-LZE2E4TE.mjs.map +1 -0
- package/dist/chunk-QZJGNLCZ.js +2 -0
- package/dist/chunk-QZJGNLCZ.js.map +1 -0
- package/dist/chunk-RA452LXZ.mjs +2 -0
- package/dist/chunk-RA452LXZ.mjs.map +1 -0
- package/dist/chunk-SLLBTQTW.mjs +2 -0
- package/dist/chunk-SLLBTQTW.mjs.map +1 -0
- package/dist/chunk-SZ256RCC.mjs +2 -0
- package/dist/chunk-SZ256RCC.mjs.map +1 -0
- package/dist/chunk-V4U2PTKN.js +2 -0
- package/dist/chunk-V4U2PTKN.js.map +1 -0
- package/dist/chunk-VM6JEJFZ.js +2 -0
- package/dist/chunk-VM6JEJFZ.js.map +1 -0
- package/dist/chunk-VXB7LA4E.js +2 -0
- package/dist/chunk-VXB7LA4E.js.map +1 -0
- package/dist/chunk-XVQKEGPO.mjs +2 -0
- package/dist/chunk-XVQKEGPO.mjs.map +1 -0
- package/dist/consent.d.mts +158 -0
- package/dist/consent.d.ts +158 -0
- package/dist/consent.js +75 -0
- package/dist/consent.js.map +1 -0
- package/dist/consent.mjs +75 -0
- package/dist/consent.mjs.map +1 -0
- package/dist/course.d.mts +1882 -0
- package/dist/course.d.ts +1882 -0
- package/dist/course.js +2 -0
- package/dist/course.js.map +1 -0
- package/dist/course.mjs +2 -0
- package/dist/course.mjs.map +1 -0
- package/dist/embed/analytics.js +1 -0
- package/dist/embed/consent.js +74 -0
- package/dist/errors.js +1 -1
- package/dist/errors.js.map +1 -1
- package/dist/index.css +1 -1
- package/dist/index.css.map +1 -1
- package/dist/index.d.mts +56 -40
- package/dist/index.d.ts +56 -40
- package/dist/index.js +1 -3
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/instrument-C_abZLHk.d.mts +912 -0
- package/dist/instrument-C_abZLHk.d.ts +912 -0
- package/dist/internal.js +1 -1
- package/dist/internal.js.map +1 -1
- package/dist/methods-CYARZTYL.mjs +2 -0
- package/dist/methods-CYARZTYL.mjs.map +1 -0
- package/dist/methods-DAPEWVI6.js +2 -0
- package/dist/methods-DAPEWVI6.js.map +1 -0
- package/dist/models.js +1 -1
- package/dist/models.js.map +1 -1
- package/dist/returns.d.mts +14 -196
- package/dist/returns.d.ts +14 -196
- package/dist/returns.js +1 -1
- package/dist/returns.js.map +1 -1
- package/dist/returns.mjs +1 -1
- package/dist/texts-CIEFbJTN.d.ts +196 -0
- package/dist/texts-tQtAGJCT.d.mts +196 -0
- package/dist/types-BaqLJYuq.d.ts +53 -0
- package/dist/types-D_WnqwR_.d.mts +53 -0
- package/package.json +41 -5
- package/dist/CartProvider-F2VH7WFO.mjs +0 -2
- package/dist/chunk-3TENJTY4.mjs +0 -2
- package/dist/chunk-3TENJTY4.mjs.map +0 -1
- package/dist/chunk-4HOZFM6V.mjs +0 -2
- package/dist/chunk-4HOZFM6V.mjs.map +0 -1
- package/dist/chunk-FTYJTO6O.mjs +0 -2
- package/dist/chunk-FTYJTO6O.mjs.map +0 -1
- package/dist/chunk-RATFYRKZ.mjs +0 -4
- package/dist/chunk-RATFYRKZ.mjs.map +0 -1
- package/dist/methods-PFZSMZFU.mjs +0 -2
- /package/dist/{CartProvider-F2VH7WFO.mjs.map → CartProvider-ZURLJNBW.mjs.map} +0 -0
- /package/dist/{methods-PFZSMZFU.mjs.map → analytics.mjs.map} +0 -0
- /package/dist/{chunk-6KQBDN7M.mjs.map → chunk-GN63ITLA.mjs.map} +0 -0
package/README.md
CHANGED
|
@@ -1099,3 +1099,133 @@ The panel provides the following screens:
|
|
|
1099
1099
|
|
|
1100
1100
|
- Toggle all notifications
|
|
1101
1101
|
- Notification preferences
|
|
1102
|
+
|
|
1103
|
+
## Merchant analytics (`bitsnap-react/analytics`)
|
|
1104
|
+
|
|
1105
|
+
A small, cookieless tracker that sends buyer-behaviour events (page views, product views, cart and checkout steps) to Bitsnap, so your dashboard can show visits, sources and funnels. It never uses cookies, `localStorage`, `sessionStorage` or IndexedDB: events live in memory and the visitor is recognised on the server by a daily-rotating hash that is never stored.
|
|
1106
|
+
|
|
1107
|
+
What an event holds: the event name, a timestamp, the page host and path (no query string, no fragment), the referrer's host, `utm_*` and `ref` from the landing URL, ids of the product/variant/order involved, and a few numbers (price in minor units, quantity). It never holds names, emails, phone numbers, addresses, IPs, coupon codes, form values or free text.
|
|
1108
|
+
|
|
1109
|
+
Tracking stays off when `enabled` is `false`, when the browser sends Global Privacy Control (`navigator.globalPrivacyControl`), or when the browser is automated (`navigator.webdriver`). When [Bitsnap Consent](#cookie-consent-bitsnap-consent) is on the page and the visitor rejected analytics, the tracker stops and drops what it had queued. Without a stored choice it keeps going, because it stores nothing on the device.
|
|
1110
|
+
|
|
1111
|
+
### Script tag
|
|
1112
|
+
|
|
1113
|
+
```html
|
|
1114
|
+
<script src="https://bitsnap.pl/embed/v1/analytics.js" data-project="pk_…" defer></script>
|
|
1115
|
+
```
|
|
1116
|
+
|
|
1117
|
+
The standalone file is `dist/embed/analytics.js` (about 6 KB gzipped, no React). It sends a `page_view` on load and on every `history.pushState`/`replaceState`/back-forward navigation. Attributes: `data-project` (required), `data-env="live|test"`, `data-endpoint` (default `https://collect.bitsnap.pl`), `data-auto="on|off"` (default `on`), `data-page-type="shop|catalog|product|cart|checkout|…"`.
|
|
1118
|
+
|
|
1119
|
+
Bitsnap's own pages set three more: `data-source="script|storefront|dashboard"` (default `script`), `data-channel="embed|hosted|custom_domain"` (default `embed`) and `data-visitor-id`, a 22-character id that is only honoured with `data-source="dashboard"` (on any other source the collector computes the visitor id itself). With `data-source="dashboard"` the script sends `app_page_view` (with the route) instead of `page_view`. Unknown values fall back to the defaults.
|
|
1120
|
+
|
|
1121
|
+
```js
|
|
1122
|
+
window.bitsnap.track("product_view", { price_minor: 4900, currency: "PLN", availability: "in_stock" }, { product_id: "…" });
|
|
1123
|
+
window.bitsnap.page("product");
|
|
1124
|
+
|
|
1125
|
+
// Before the script has loaded, queue calls instead:
|
|
1126
|
+
(window.bitsnap = window.bitsnap || { q: [] }).q.push(["track", "variant_selected", {}, { product_id: "…" }]);
|
|
1127
|
+
```
|
|
1128
|
+
|
|
1129
|
+
### React
|
|
1130
|
+
|
|
1131
|
+
```tsx
|
|
1132
|
+
import { BitsnapAnalyticsProvider, useAnalytics } from "bitsnap-react/analytics";
|
|
1133
|
+
|
|
1134
|
+
<BitsnapAnalyticsProvider projectKey="pk_…" onEvent={(event) => myTool.track(event.event, event.props)}>
|
|
1135
|
+
<App />
|
|
1136
|
+
</BitsnapAnalyticsProvider>;
|
|
1137
|
+
|
|
1138
|
+
function Product({ id }: { id: string }) {
|
|
1139
|
+
const { track } = useAnalytics();
|
|
1140
|
+
// track("product_view", { price_minor, currency, availability }, { product_id: id })
|
|
1141
|
+
}
|
|
1142
|
+
```
|
|
1143
|
+
|
|
1144
|
+
`useAnalytics()` returns no-ops outside the provider and on the server. `onEvent` receives every event before it is sent, so you can forward it to your own tools after your own consent step; it is not called while tracking is off. The tracker is a per-page singleton: the first provider's `projectKey`, `env` and `endpoint` win.
|
|
1145
|
+
|
|
1146
|
+
Without React, use the core directly: `initTracker({ projectKey })` returns the page's tracker (`track`, `page`, `flush`, `setEnabled`, `onEvent`). Events are batched: sent every 5 seconds, at 20 events, and when the page is hidden (`navigator.sendBeacon`, with a `fetch` `keepalive` fallback). Failed sends are not retried.
|
|
1147
|
+
|
|
1148
|
+
### Automatic analytics in components
|
|
1149
|
+
|
|
1150
|
+
The Bitsnap components report their own events, so a project key is all you need. Each component takes an `analytics` prop:
|
|
1151
|
+
|
|
1152
|
+
```tsx
|
|
1153
|
+
<ProductList projectID="…" /> // tracks (default)
|
|
1154
|
+
<ProductList projectID="…" analytics={false} /> // opt out
|
|
1155
|
+
<ProductList projectID="…" analytics={{ onEvent: (e) => myTool.track(e.event, e.props), env: "test" }} />
|
|
1156
|
+
```
|
|
1157
|
+
|
|
1158
|
+
`onEvent` receives only the events of that component. `env: "test"` events are stored but never reach the merchant's stats. Parts inside a component inherit its setting; a surrounding `<BitsnapAnalyticsProvider>` owns the tracker and its `onEvent` still sees everything. Nothing is written to cookies or Storage, and events carry no personal data (no emails, names, order contents or free text).
|
|
1159
|
+
|
|
1160
|
+
| Component | Events |
|
|
1161
|
+
| --- | --- |
|
|
1162
|
+
| `ProductList` | `product_list_viewed`, `product_impression` (card ≥50% visible), `product_clicked`, `add_to_cart` |
|
|
1163
|
+
| `BitsnapCheckout` / `Bitsnap.addProductToCart` | `cart_opened`, `checkout_started`, `add_to_cart`, `remove_from_cart` |
|
|
1164
|
+
| `ApplePay` | `apple_pay_clicked`, `payment_method_selected`, `delivery_method_selected`, `payment_submitted`, `apple_pay_result` |
|
|
1165
|
+
| `GooglePay` | `payment_method_selected`, `payment_submitted` |
|
|
1166
|
+
| Notifications | `availability_signup` |
|
|
1167
|
+
| Panel | `panel_login`, `panel_order_viewed`, `panel_download` |
|
|
1168
|
+
| Returns | `return_started`, `return_submitted` |
|
|
1169
|
+
| Course | `course_opened`, `lesson_started`, `lesson_completed`, `video_progress` (25/50/75/100% of naturally played time), `test_submitted`, `lesson_rated` |
|
|
1170
|
+
|
|
1171
|
+
The components do not emit `page_view`, `product_view`, `checkout_step_completed`, `checkout_validation_error`, `coupon_applied` or `coupon_rejected` (the drawer hands over to the hosted checkout). Use `useAnalytics()` or the embed script for page views. Because the tracker is a per-page singleton, the first project key wins: use one project per page. The course sends nothing in creator preview.
|
|
1172
|
+
|
|
1173
|
+
For your own components, `useInstrument(projectKey, analytics)` returns the same `{ track }` helper and `<InstrumentProvider value={instrument}>` shares it with the parts below.
|
|
1174
|
+
|
|
1175
|
+
## Cookie consent (Bitsnap Consent)
|
|
1176
|
+
|
|
1177
|
+
An embeddable cookie banner with equal "Accept all" / "Reject all" buttons, per-category settings, light and dark themes, Polish and English texts, and Google Consent Mode v2. It renders in a Shadow DOM, stores only one first-party cookie (`bitsnap_consent`) and never uses `localStorage`.
|
|
1178
|
+
|
|
1179
|
+
### Script tag
|
|
1180
|
+
|
|
1181
|
+
```html
|
|
1182
|
+
<script src="https://bitsnap.pl/embed/v1/consent.js" data-project="pk_…" defer></script>
|
|
1183
|
+
```
|
|
1184
|
+
|
|
1185
|
+
The standalone file is `dist/embed/consent.js` (about 9 KB gzipped, no React). Attributes: `data-project`, `data-theme="auto|light|dark"`, `data-locale="auto|pl|en"`, `data-position="bottom|bottom-left|bottom-right"`, `data-privacy-url`, `data-scope="project"`, `data-api-host`, `data-collect-host`, `data-gcm="on|off"`, `data-categories="analytics,marketing"` (used when there is no remote config), `data-reload-on-withdraw="true"`.
|
|
1186
|
+
|
|
1187
|
+
For a live preview in a settings page, add `data-preview="on"`: the banner is shown on every load, nothing is read from or written to the cookie, and nothing is sent to the collect host. `data-title` and `data-description` replace the banner heading and text (the same options exist as `preview`, `title` and `description` in the core `ConsentOptions`).
|
|
1188
|
+
|
|
1189
|
+
With `data-project` the banner loads its config from `/api/consent/config` (3 s timeout, then defaults) and sends each choice to `<collect host>/consent`. Without it nothing leaves the page.
|
|
1190
|
+
|
|
1191
|
+
### React
|
|
1192
|
+
|
|
1193
|
+
```tsx
|
|
1194
|
+
import { BitsnapConsent, useConsent } from "bitsnap-react/consent";
|
|
1195
|
+
|
|
1196
|
+
<BitsnapConsent projectKey="pk_…" locale="pl" privacyPolicyUrl="/polityka-prywatnosci" />;
|
|
1197
|
+
|
|
1198
|
+
function CookieSettings() {
|
|
1199
|
+
const { consent, open } = useConsent();
|
|
1200
|
+
return <button onClick={open}>Cookie settings ({consent?.c.marketing ? "marketing on" : "marketing off"})</button>;
|
|
1201
|
+
}
|
|
1202
|
+
```
|
|
1203
|
+
|
|
1204
|
+
`<BitsnapConsent />` renders nothing on the server. A `config` prop (`ConsentConfig`, partial) overrides the project config.
|
|
1205
|
+
|
|
1206
|
+
### Loading scripts after consent
|
|
1207
|
+
|
|
1208
|
+
```html
|
|
1209
|
+
<script type="text/plain" data-bitsnap-consent="marketing" data-src="https://example.com/pixel.js"></script>
|
|
1210
|
+
<script type="text/plain" data-bitsnap-consent="analytics">/* inline code */</script>
|
|
1211
|
+
<iframe data-bitsnap-consent="marketing" data-src="https://www.youtube.com/embed/…"></iframe>
|
|
1212
|
+
```
|
|
1213
|
+
|
|
1214
|
+
After consent for the category the placeholder is replaced by a real script (attributes copied, `type` dropped, `data-src` becomes `src`), and an iframe gets its `src`. Categories are `analytics`, `marketing` and `preferences`.
|
|
1215
|
+
|
|
1216
|
+
### JavaScript API
|
|
1217
|
+
|
|
1218
|
+
```js
|
|
1219
|
+
BitsnapConsent.get(); // null or { id, ts, bv, c: { analytics, marketing, preferences } }
|
|
1220
|
+
BitsnapConsent.on("change", (d) => {}); // returns an unsubscribe function; d.action is accept_all | reject_all | custom | withdraw | reset
|
|
1221
|
+
BitsnapConsent.open(); // settings layer; any [data-bitsnap-consent-open] element does the same
|
|
1222
|
+
BitsnapConsent.acceptAll(); BitsnapConsent.rejectAll(); BitsnapConsent.accept({ analytics: true });
|
|
1223
|
+
BitsnapConsent.reset(); // clears the choice and asks again
|
|
1224
|
+
BitsnapConsent.ready; // Promise, resolves once config and the stored choice are applied
|
|
1225
|
+
```
|
|
1226
|
+
|
|
1227
|
+
`window` also receives `CustomEvent("bitsnap:consent", { detail })` on every choice. Categories missing from `accept()` are denied. When a visitor withdraws a category, the cookies listed in `services[].cookies` are deleted (best effort; a trailing `*` matches a prefix), and the page reloads if `reloadOnWithdraw` is set.
|
|
1228
|
+
|
|
1229
|
+
### Google Consent Mode v2
|
|
1230
|
+
|
|
1231
|
+
If `gtag` or `dataLayer` exists (or `data-gcm="on"`), the script sets `consent default` (everything denied except `security_storage`, `wait_for_update: 500`) before anything else, and `consent update` after each choice: analytics → `analytics_storage`, marketing → `ad_storage`, `ad_user_data`, `ad_personalization`, preferences → `functionality_storage`, `personalization_storage`.
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkKG6RU37Ujs = require('./chunk-KG6RU37U.js');require('./chunk-V4U2PTKN.js');require('./chunk-KOYBZORL.js');require('./chunk-3IMJALBX.js');require('./chunk-FHDFLSPW.js');var _chunkCO2P4FR5js = require('./chunk-CO2P4FR5.js');require('./chunk-QZJGNLCZ.js');require('./chunk-3UHPJ6NK.js');require('./chunk-JSDGZ4NY.js');exports.MARKETING_AGREEMENT_ID = _chunkKG6RU37Ujs.B; exports.bitsnapProjectID = _chunkKG6RU37Ujs.C; exports.default = _chunkKG6RU37Ujs.G; exports.getCheckoutMethods = _chunkKG6RU37Ujs.H; exports.getLocale = _chunkCO2P4FR5js.m; exports.getProjectID = _chunkKG6RU37Ujs.E; exports.setLocale = _chunkCO2P4FR5js.l; exports.setProjectID = _chunkKG6RU37Ujs.D; exports.useCartProvider = _chunkKG6RU37Ujs.F;
|
|
2
|
+
//# sourceMappingURL=CartProvider-XWTLBIZ5.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/consent-analytics/dist/CartProvider-XWTLBIZ5.js"],"names":[],"mappings":"AAAA,+HAAiF,+BAA4B,+BAA4B,+BAA4B,+BAA4B,sDAA+C,+BAA4B,+BAA4B,+BAA4B,8YAAsL","file":"/home/emems/.t3/worktrees/bitsnap-react/consent-analytics/dist/CartProvider-XWTLBIZ5.js"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{B as c,C as d,D as e,E as f,F as g,G as h,H as i}from"./chunk-LZE2E4TE.mjs";import"./chunk-SZ256RCC.mjs";import"./chunk-KOVKUJAW.mjs";import"./chunk-LJWS6ZRJ.mjs";import"./chunk-HKVMSMDF.mjs";import{l as a,m as b}from"./chunk-RA452LXZ.mjs";import"./chunk-XVQKEGPO.mjs";import"./chunk-E6QVQEGZ.mjs";import"./chunk-U6FLIRIV.mjs";export{c as MARKETING_AGREEMENT_ID,d as bitsnapProjectID,h as default,i as getCheckoutMethods,b as getLocale,f as getProjectID,a as setLocale,e as setProjectID,g as useCartProvider};
|
|
2
|
+
//# sourceMappingURL=CartProvider-ZURLJNBW.mjs.map
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { T as Tracker, a as TrackerOptions, C as ClientEvent } from './instrument-C_abZLHk.mjs';
|
|
2
|
+
export { A as AnalyticsOption, d as AppEventName, B as BrowserEventName, e as Channel, D as DEFAULT_ENDPOINT, E as Env, f as EventName, h as EventProps, l as Instrument, I as InstrumentProvider, P as PageType, S as Source, j as StorefrontEventName, b as TrackExtra, c as createTracker, g as getTracker, i as initTracker, n as noopInstrument, r as resetTracker, s as scoreBucket, u as useInstrument, k as useInstrumentContext } from './instrument-C_abZLHk.mjs';
|
|
3
|
+
import * as react from 'react';
|
|
4
|
+
import { ReactNode } from 'react';
|
|
5
|
+
|
|
6
|
+
type AnalyticsApi = Pick<Tracker, "track" | "page">;
|
|
7
|
+
type BitsnapAnalyticsProviderProps = {
|
|
8
|
+
/** Public project key (the `projectID` the rest of the SDK uses). */
|
|
9
|
+
projectKey: string;
|
|
10
|
+
env?: TrackerOptions["env"];
|
|
11
|
+
/** `false` turns tracking off. */
|
|
12
|
+
enabled?: boolean;
|
|
13
|
+
endpoint?: string;
|
|
14
|
+
/** Called with every event before it is sent, e.g. to forward it to the merchant's own tools. */
|
|
15
|
+
onEvent?: (event: ClientEvent) => void;
|
|
16
|
+
children?: ReactNode;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Starts the page's tracker and hands `track` and `page` to `useAnalytics()`.
|
|
20
|
+
* The tracker is a per-page singleton: the first valid `projectKey` wins, but
|
|
21
|
+
* `env`, `endpoint` and `enabled` of any provider update the running tracker.
|
|
22
|
+
* Nothing is tracked on the server, and nothing is stored on the visitor's device.
|
|
23
|
+
*/
|
|
24
|
+
declare function BitsnapAnalyticsProvider({ projectKey, env, enabled, endpoint, onEvent, children, }: BitsnapAnalyticsProviderProps): react.FunctionComponentElement<react.ProviderProps<AnalyticsApi>>;
|
|
25
|
+
/** `track` and `page`; no-ops outside a `<BitsnapAnalyticsProvider>`. */
|
|
26
|
+
declare function useAnalytics(): AnalyticsApi;
|
|
27
|
+
|
|
28
|
+
export { type AnalyticsApi, BitsnapAnalyticsProvider, type BitsnapAnalyticsProviderProps, ClientEvent, Tracker, TrackerOptions, useAnalytics };
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { T as Tracker, a as TrackerOptions, C as ClientEvent } from './instrument-C_abZLHk.js';
|
|
2
|
+
export { A as AnalyticsOption, d as AppEventName, B as BrowserEventName, e as Channel, D as DEFAULT_ENDPOINT, E as Env, f as EventName, h as EventProps, l as Instrument, I as InstrumentProvider, P as PageType, S as Source, j as StorefrontEventName, b as TrackExtra, c as createTracker, g as getTracker, i as initTracker, n as noopInstrument, r as resetTracker, s as scoreBucket, u as useInstrument, k as useInstrumentContext } from './instrument-C_abZLHk.js';
|
|
3
|
+
import * as react from 'react';
|
|
4
|
+
import { ReactNode } from 'react';
|
|
5
|
+
|
|
6
|
+
type AnalyticsApi = Pick<Tracker, "track" | "page">;
|
|
7
|
+
type BitsnapAnalyticsProviderProps = {
|
|
8
|
+
/** Public project key (the `projectID` the rest of the SDK uses). */
|
|
9
|
+
projectKey: string;
|
|
10
|
+
env?: TrackerOptions["env"];
|
|
11
|
+
/** `false` turns tracking off. */
|
|
12
|
+
enabled?: boolean;
|
|
13
|
+
endpoint?: string;
|
|
14
|
+
/** Called with every event before it is sent, e.g. to forward it to the merchant's own tools. */
|
|
15
|
+
onEvent?: (event: ClientEvent) => void;
|
|
16
|
+
children?: ReactNode;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Starts the page's tracker and hands `track` and `page` to `useAnalytics()`.
|
|
20
|
+
* The tracker is a per-page singleton: the first valid `projectKey` wins, but
|
|
21
|
+
* `env`, `endpoint` and `enabled` of any provider update the running tracker.
|
|
22
|
+
* Nothing is tracked on the server, and nothing is stored on the visitor's device.
|
|
23
|
+
*/
|
|
24
|
+
declare function BitsnapAnalyticsProvider({ projectKey, env, enabled, endpoint, onEvent, children, }: BitsnapAnalyticsProviderProps): react.FunctionComponentElement<react.ProviderProps<AnalyticsApi>>;
|
|
25
|
+
/** `track` and `page`; no-ops outside a `<BitsnapAnalyticsProvider>`. */
|
|
26
|
+
declare function useAnalytics(): AnalyticsApi;
|
|
27
|
+
|
|
28
|
+
export { type AnalyticsApi, BitsnapAnalyticsProvider, type BitsnapAnalyticsProviderProps, ClientEvent, Tracker, TrackerOptions, useAnalytics };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkQZJGNLCZjs = require('./chunk-QZJGNLCZ.js');require('./chunk-3UHPJ6NK.js');require('./chunk-JSDGZ4NY.js');exports.BitsnapAnalyticsProvider = _chunkQZJGNLCZjs.g; exports.DEFAULT_ENDPOINT = _chunkQZJGNLCZjs.b; exports.InstrumentProvider = _chunkQZJGNLCZjs.j; exports.createTracker = _chunkQZJGNLCZjs.c; exports.getTracker = _chunkQZJGNLCZjs.e; exports.initTracker = _chunkQZJGNLCZjs.d; exports.noopInstrument = _chunkQZJGNLCZjs.i; exports.resetTracker = _chunkQZJGNLCZjs.f; exports.scoreBucket = _chunkQZJGNLCZjs.p; exports.useAnalytics = _chunkQZJGNLCZjs.h; exports.useInstrument = _chunkQZJGNLCZjs.l; exports.useInstrumentContext = _chunkQZJGNLCZjs.k;
|
|
2
|
+
//# sourceMappingURL=analytics.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/consent-analytics/dist/analytics.js"],"names":[],"mappings":"AAAA,+HAAoH,+BAA4B,+BAA4B,iiBAA8P","file":"/home/emems/.t3/worktrees/bitsnap-react/consent-analytics/dist/analytics.js"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{b as e,c as r,d as t,e as n,f as o,g as a,h as p,i as s,j as c,k as i,l as m,p as u}from"./chunk-XVQKEGPO.mjs";import"./chunk-E6QVQEGZ.mjs";import"./chunk-U6FLIRIV.mjs";export{a as BitsnapAnalyticsProvider,e as DEFAULT_ENDPOINT,c as InstrumentProvider,r as createTracker,n as getTracker,t as initTracker,s as noopInstrument,o as resetTracker,u as scoreBucket,p as useAnalytics,m as useInstrument,i as useInstrumentContext};
|
|
2
|
+
//# sourceMappingURL=analytics.mjs.map
|
package/dist/catalog.d.mts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
2
|
import { ReactNode } from 'react';
|
|
3
|
+
import { A as AnalyticsOption } from './instrument-C_abZLHk.mjs';
|
|
3
4
|
import { S as SlotAppearance, A as AppearanceElements } from './appearance-core-Dt2grZdl.mjs';
|
|
4
5
|
import { BitsnapModels } from './models.mjs';
|
|
5
6
|
import 'zod';
|
|
@@ -168,6 +169,11 @@ type ProductListItemContext = {
|
|
|
168
169
|
locale: string;
|
|
169
170
|
/** Adds the product to the cart the way the built-in button does. */
|
|
170
171
|
addToCart: () => Promise<void>;
|
|
172
|
+
/**
|
|
173
|
+
* Reports a click on the product (`product_clicked`). Call it from the link
|
|
174
|
+
* a custom card renders; the built-in card does it itself.
|
|
175
|
+
*/
|
|
176
|
+
trackClick: () => void;
|
|
171
177
|
};
|
|
172
178
|
type ProductListProps = UseProductsOptions & {
|
|
173
179
|
/**
|
|
@@ -189,6 +195,13 @@ type ProductListProps = UseProductsOptions & {
|
|
|
189
195
|
/** Open the cart drawer after the default add to cart. Defaults to `true`. */
|
|
190
196
|
showCartOnAdd?: boolean;
|
|
191
197
|
className?: string;
|
|
198
|
+
/**
|
|
199
|
+
* Usage statistics for your Bitsnap dashboard (list views, impressions,
|
|
200
|
+
* clicks, add to cart). On by default; `false` turns it off. An object
|
|
201
|
+
* lets you forward every event: `{ onEvent }`. Nothing is stored on the
|
|
202
|
+
* visitor's device.
|
|
203
|
+
*/
|
|
204
|
+
analytics?: AnalyticsOption;
|
|
192
205
|
};
|
|
193
206
|
/**
|
|
194
207
|
* Responsive grid of the shop's products with pagination, loading, empty and
|
|
@@ -202,7 +215,7 @@ type ProductListProps = UseProductsOptions & {
|
|
|
202
215
|
* server) to have the products in the HTML; without it the server renders the
|
|
203
216
|
* loading skeleton and the browser fetches the first page.
|
|
204
217
|
*/
|
|
205
|
-
declare function ProductList({ productHref, appearance, texts, renderItem, onAddToCart, showCartOnAdd, className, ...options }: ProductListProps): react_jsx_runtime.JSX.Element;
|
|
218
|
+
declare function ProductList({ productHref, appearance, texts, renderItem, onAddToCart, showCartOnAdd, className, analytics, ...options }: ProductListProps): react_jsx_runtime.JSX.Element;
|
|
206
219
|
|
|
207
220
|
/**
|
|
208
221
|
* Formats a price in minor units (grosze, cents) for the locale, the same way
|
package/dist/catalog.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
2
|
import { ReactNode } from 'react';
|
|
3
|
+
import { A as AnalyticsOption } from './instrument-C_abZLHk.js';
|
|
3
4
|
import { S as SlotAppearance, A as AppearanceElements } from './appearance-core-Dt2grZdl.js';
|
|
4
5
|
import { BitsnapModels } from './models.js';
|
|
5
6
|
import 'zod';
|
|
@@ -168,6 +169,11 @@ type ProductListItemContext = {
|
|
|
168
169
|
locale: string;
|
|
169
170
|
/** Adds the product to the cart the way the built-in button does. */
|
|
170
171
|
addToCart: () => Promise<void>;
|
|
172
|
+
/**
|
|
173
|
+
* Reports a click on the product (`product_clicked`). Call it from the link
|
|
174
|
+
* a custom card renders; the built-in card does it itself.
|
|
175
|
+
*/
|
|
176
|
+
trackClick: () => void;
|
|
171
177
|
};
|
|
172
178
|
type ProductListProps = UseProductsOptions & {
|
|
173
179
|
/**
|
|
@@ -189,6 +195,13 @@ type ProductListProps = UseProductsOptions & {
|
|
|
189
195
|
/** Open the cart drawer after the default add to cart. Defaults to `true`. */
|
|
190
196
|
showCartOnAdd?: boolean;
|
|
191
197
|
className?: string;
|
|
198
|
+
/**
|
|
199
|
+
* Usage statistics for your Bitsnap dashboard (list views, impressions,
|
|
200
|
+
* clicks, add to cart). On by default; `false` turns it off. An object
|
|
201
|
+
* lets you forward every event: `{ onEvent }`. Nothing is stored on the
|
|
202
|
+
* visitor's device.
|
|
203
|
+
*/
|
|
204
|
+
analytics?: AnalyticsOption;
|
|
192
205
|
};
|
|
193
206
|
/**
|
|
194
207
|
* Responsive grid of the shop's products with pagination, loading, empty and
|
|
@@ -202,7 +215,7 @@ type ProductListProps = UseProductsOptions & {
|
|
|
202
215
|
* server) to have the products in the HTML; without it the server renders the
|
|
203
216
|
* loading skeleton and the browser fetches the first page.
|
|
204
217
|
*/
|
|
205
|
-
declare function ProductList({ productHref, appearance, texts, renderItem, onAddToCart, showCartOnAdd, className, ...options }: ProductListProps): react_jsx_runtime.JSX.Element;
|
|
218
|
+
declare function ProductList({ productHref, appearance, texts, renderItem, onAddToCart, showCartOnAdd, className, analytics, ...options }: ProductListProps): react_jsx_runtime.JSX.Element;
|
|
206
219
|
|
|
207
220
|
/**
|
|
208
221
|
* Formats a price in minor units (grosze, cents) for the locale, the same way
|
package/dist/catalog.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkVM6JEJFZjs = require('./chunk-VM6JEJFZ.js');require('./chunk-KOYBZORL.js');require('./chunk-CO2P4FR5.js');require('./chunk-QZJGNLCZ.js');require('./chunk-3UHPJ6NK.js');require('./chunk-JSDGZ4NY.js');exports.PRODUCT_LIST_SLOT_NAMES = _chunkVM6JEJFZjs.a; exports.ProductList = _chunkVM6JEJFZjs.d; exports.formatProductPrice = _chunkVM6JEJFZjs.b; exports.useProducts = _chunkVM6JEJFZjs.c;
|
|
2
2
|
//# sourceMappingURL=catalog.js.map
|
package/dist/catalog.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["
|
|
1
|
+
{"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/consent-analytics/dist/catalog.js"],"names":[],"mappings":"AAAA,+HAA4D,+BAA4B,+BAA4B,+BAA4B,+BAA4B,+BAA4B,0LAA+F","file":"/home/emems/.t3/worktrees/bitsnap-react/consent-analytics/dist/catalog.js"}
|
package/dist/catalog.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as o,b as r,c as e,d as f}from"./chunk-
|
|
1
|
+
import{a as o,b as r,c as e,d as f}from"./chunk-SLLBTQTW.mjs";import"./chunk-KOVKUJAW.mjs";import"./chunk-RA452LXZ.mjs";import"./chunk-XVQKEGPO.mjs";import"./chunk-E6QVQEGZ.mjs";import"./chunk-U6FLIRIV.mjs";export{o as PRODUCT_LIST_SLOT_NAMES,f as ProductList,r as formatProductPrice,e as useProducts};
|
|
2
2
|
//# sourceMappingURL=catalog.mjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var _chunkFHDFLSPWjs = require('./chunk-FHDFLSPW.js');var _chunkQZJGNLCZjs = require('./chunk-QZJGNLCZ.js');var t={projectID:void 0,loginURL:"/panel/login",theme:void 0,host:void 0,allowedReturnOrigins:[]},u=[];function w(e){t={...t,...e}}function s(){return t}function P(e){t.projectID=e}function v(e){t.theme=e}function C(e){t.loginURL=e}function R(e){t.host=e}function x(e){u=e,t={...t,allowedReturnOrigins:e}}function y(){return u}var _react = require('react');var _jsxruntime = require('react/jsx-runtime');var f=_react.createContext.call(void 0, s()),b= exports.i =({children:e,analytics:n})=>{let o=s(),i=_chunkQZJGNLCZjs.l.call(void 0, o.projectID,n,"panel");return _jsxruntime.jsx.call(void 0, _chunkFHDFLSPWjs.o,{children:_jsxruntime.jsx.call(void 0, f.Provider,{value:{...o},children:_jsxruntime.jsx.call(void 0, _chunkQZJGNLCZjs.j,{value:i,children:_jsxruntime.jsx.call(void 0, "div",{className:"bitsnap-react",children:e})})})})},L= exports.j =()=>_react.useContext.call(void 0, f);var l=(e,n)=>`bitsnap-panel-session:${encodeURIComponent(_nullishCoalesce(n, () => ("https://bitsnap.pl")))}:${encodeURIComponent(e)}`,a=(e,n)=>`bitsnap-panel-email:${encodeURIComponent(_nullishCoalesce(n, () => ("https://bitsnap.pl")))}:${encodeURIComponent(e)}`;function $(e,n){return typeof window>"u"||!e?void 0:_nullishCoalesce(window.localStorage.getItem(l(e,n)), () => (void 0))}function G(e,n,o,i){typeof window>"u"||!e||(window.localStorage.setItem(l(e,i),n),window.localStorage.setItem(a(e,i),o))}function k(e,n){return typeof window>"u"||!e?null:window.localStorage.getItem(a(e,n))}function E(e,n){typeof window>"u"||!e||(window.localStorage.removeItem(l(e,n)),window.localStorage.removeItem(a(e,n)))}exports.a = w; exports.b = s; exports.c = P; exports.d = v; exports.e = C; exports.f = R; exports.g = x; exports.h = y; exports.i = b; exports.j = L; exports.k = $; exports.l = G; exports.m = k; exports.n = E;
|
|
2
|
+
//# sourceMappingURL=chunk-3IMJALBX.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/consent-analytics/dist/chunk-3IMJALBX.js","../src/panel/config.ts","../src/panel/PanelProvider.tsx","../src/panel/session-storage.ts"],"names":["config","allowedReturnOrigins","setPanelConfig","newConfig","getPanelConfig","setProjectID","projectID","setTheme","theme","setLoginURL","loginURL","setHost","host","setAllowedReturnOrigins","origins","getAllowedReturnOrigins","PanelContext","createContext","PanelProvider","children","analytics","instrument","useInstrument","jsx","RpcProvider","InstrumentProvider","usePanelConfig","useContext","panelSessionKey"],"mappings":"AAAA,mOAAuC,sDAA+C,ICElFA,CAAAA,CAAsB,CACxB,SAAA,CAAW,KAAA,CAAA,CACX,QAAA,CAAU,cAAA,CACV,KAAA,CAAO,KAAA,CA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A,CACxC,QAAA,CAAAuB,6BAAAA,kBAACE,CAAA,CAAmB,KAAA,CAAOJ,CAAAA,CACzB,QAAA,CAAAE,6BAAAA,KAAC,CAAA,CAAI,SAAA,CAAU,eAAA,CAAiB,QAAA,CAAAJ,CAAAA,CAAS,CAAA,CAC3C,CAAA,CACF,CAAA,CACF,CAEJ,CAAA,CAEaO,CAAAA,aAAiB,CAAA,CAAA,EAAMC,+BAAAA,CAAuB,CAAA,CClC3D,IAAMC,CAAAA,CAAkB,CAACtB,CAAAA,CAAmBM,CAAAA,CAAAA,EAC1C,CAAA,sBAAA,EAAyB,kBAAA,kBAAmBA,CAAAA,SAAQ,sBAAoB,CAAC,CAAA,CAAA,EAAI,kBAAA,CAAmBN,CAAS,CAAC,CAAA,CAAA","file":"/home/emems/.t3/worktrees/bitsnap-react/consent-analytics/dist/chunk-3IMJALBX.js","sourcesContent":[null,"import type { GetThemeOutput } from \"./types\";\n\nlet config: PanelConfig = {\n projectID: undefined,\n loginURL: \"/panel/login\",\n theme: undefined,\n host: undefined,\n allowedReturnOrigins: [],\n};\n\nlet allowedReturnOrigins: string[] = [];\n\nexport interface PanelConfig {\n projectID?: string;\n loginURL?: string;\n theme?: GetThemeOutput;\n host?: string;\n allowedReturnOrigins: string[];\n}\n\nexport function setPanelConfig(newConfig: Partial<PanelConfig>): void {\n config = { ...config, ...newConfig };\n}\n\nexport function getPanelConfig(): PanelConfig {\n return config;\n}\n\nexport function setProjectID(projectID: string): void {\n config.projectID = projectID;\n}\n\nexport function setTheme(theme: GetThemeOutput): void {\n config.theme = theme;\n}\n\nexport function setLoginURL(loginURL: string): void {\n config.loginURL = loginURL;\n}\n\nexport function setHost(host: string): void {\n config.host = host;\n}\n\nexport function setAllowedReturnOrigins(origins: string[]): void {\n allowedReturnOrigins = origins;\n config = { ...config, allowedReturnOrigins: origins };\n}\n\nexport function getAllowedReturnOrigins(): string[] {\n return allowedReturnOrigins;\n}\n","import { createContext, useContext } from \"react\";\nimport {\n InstrumentProvider,\n useInstrument,\n type AnalyticsOption,\n} from \"../analytics/instrument\";\nimport { RpcProvider } from \"../rpc-provider\";\nimport { getPanelConfig, type PanelConfig } from \"./config\";\n\nconst PanelContext = createContext<PanelConfig>(getPanelConfig());\n\nexport const PanelProvider: React.FC<{\n children: React.ReactNode;\n /**\n * Usage statistics for your Bitsnap dashboard (panel logins, orders viewed,\n * downloads, course progress). On by default; `false` turns it off. An\n * object lets you forward every event: `{ onEvent }`. Nothing is stored on\n * the visitor's device.\n */\n analytics?: AnalyticsOption;\n}> = ({ children, analytics }) => {\n const config = getPanelConfig();\n const instrument = useInstrument(config.projectID, analytics, \"panel\");\n return (\n <RpcProvider>\n <PanelContext.Provider value={{ ...config }}>\n <InstrumentProvider value={instrument}>\n <div className=\"bitsnap-react\">{children}</div>\n </InstrumentProvider>\n </PanelContext.Provider>\n </RpcProvider>\n );\n};\n\nexport const usePanelConfig = () => useContext(PanelContext);\n","const panelSessionKey = (projectID: string, host?: string) =>\n `bitsnap-panel-session:${encodeURIComponent(host ?? \"https://bitsnap.pl\")}:${encodeURIComponent(projectID)}`;\n\nconst panelEmailKey = (projectID: string, host?: string) =>\n `bitsnap-panel-email:${encodeURIComponent(host ?? \"https://bitsnap.pl\")}:${encodeURIComponent(projectID)}`;\n\nexport function getPanelSession(projectID?: string, host?: string) {\n if (typeof window === \"undefined\" || !projectID) return undefined;\n const token = window.localStorage.getItem(panelSessionKey(projectID, host));\n return token ?? undefined;\n}\n\nexport function savePanelSession(projectID: string | undefined, token: string, email: string, host?: string) {\n if (typeof window === \"undefined\" || !projectID) return;\n window.localStorage.setItem(panelSessionKey(projectID, host), token);\n window.localStorage.setItem(panelEmailKey(projectID, host), email);\n}\n\nexport function getPanelEmail(projectID?: string, host?: string) {\n if (typeof window === \"undefined\" || !projectID) return null;\n return window.localStorage.getItem(panelEmailKey(projectID, host));\n}\n\nexport function clearPanelSession(projectID?: string, host?: string) {\n if (typeof window === \"undefined\" || !projectID) return;\n window.localStorage.removeItem(panelSessionKey(projectID, host));\n window.localStorage.removeItem(panelEmailKey(projectID, host));\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var r={maxBatchEvents:50,maxBodyBytes:65536,maxPropsChars:4096,maxPropString:200,maxPropArray:50,host:253,path:512,referrerHost:253,utm:100,refCode:64,id:64,sdk:64,pageId:32,region:64,osBrowser:32,tsSkewMs:864e5},w=["storefront_events","app_events","business_events"],C=["live","test"],N=["storefront","sdk_react","script","server","dashboard"],A=["hosted","custom_domain","embed","api","panel"],P=["shop","catalog","product","cart","checkout","payment","panel","course","custom_page","order","returns","app","other"];var T={storefront_events:["storefront","sdk_react","script"],app_events:["dashboard"],business_events:["server"]},u={value_minor:"number",currency:"string"},b={page_view:{landing:"boolean"},product_list_viewed:{list_id:"string?",item_count:"number"},product_impression:{list_id:"string?",product_ids:"string[]",positions:"number[]"},product_clicked:{list_id:"string?",position:"number?"},product_view:{price_minor:"number",currency:"string",availability:"enum:in_stock|out_of_stock|preorder"},variant_selected:{},add_to_cart:{qty:"number",...u},remove_from_cart:{qty:"number",...u},cart_opened:{item_count:"number",...u},checkout_started:{item_count:"number",checkout_type:"enum:single|cart|link",...u},checkout_step_completed:{step:"enum:contact|delivery|invoice|consents"},checkout_validation_error:{field:"string",rule:"string"},coupon_applied:{coupon_id:"string"},coupon_rejected:{coupon_id:"string?",reason:"string"},delivery_method_selected:{method:"string"},payment_method_selected:{gateway:"string",method:"string"},payment_submitted:{gateway:"string",method:"string"},apple_pay_clicked:{},apple_pay_result:{outcome:"enum:success|fail|cancel"},payment_returned:{gateway:"string",method:"string?",outcome:"enum:success|fail|cancel|pending",error_code:"string?"},availability_signup:{},panel_login:{},panel_order_viewed:{},panel_download:{},return_started:{},return_submitted:{reason_code:"string",item_count:"number"},course_opened:{course_id:"string"},lesson_started:{course_id:"string",lesson_id:"string",position:"number"},lesson_completed:{course_id:"string",lesson_id:"string",position:"number"},video_progress:{course_id:"string",lesson_id:"string",milestone:"number"},test_submitted:{course_id:"string",lesson_id:"string",score_bucket:"enum:0-24|25-49|50-74|75-99|100"},lesson_rated:{course_id:"string",lesson_id:"string",rating:"number"},consent_updated:{consent_id:"string",action:"enum:accept_all|reject_all|custom|withdraw",analytics:"boolean",marketing:"boolean",preferences:"boolean",banner_version:"number"}},h={app_page_view:{route:"string",previous_route:"string?"},insight_shown:{insight_type:"string",rank:"number",category:"string"},insight_clicked:{insight_type:"string",rank:"number",category:"string"},insight_dismissed:{insight_type:"string",rank:"number",category:"string"},checklist_step_viewed:{step:"string"},checklist_step_completed:{step:"string"},gateway_connect_started:{gateway:"string",step:"string?"},gateway_connect_completed:{gateway:"string",step:"string?"},gateway_connect_failed:{gateway:"string",step:"string?",error_code:"string?"},domain_connect_started:{},domain_connect_verified:{},domain_connect_failed:{error_code:"string?"},product_created:{product_type:"string?"},product_published:{product_type:"string?"},product_editor_section_opened:{section:"string"},feature_enabled:{feature:"string"},stats_viewed:{tab:"string"},stats_filter_changed:{tab:"string",filter:"string"},report_exported:{report:"string",format:"string?"},search_performed:{result_count:"number"},error_shown:{code:"string",route:"string"},help_opened:{topic:"string?"},ai_assistant_used:{topic:"string?"},member_invited:{role:"string"}},_={gateway:"string?",method:"string?",value_minor:"number?",currency:"string?"},a={subscription_id:"string?",value_minor:"number?",currency:"string?"},E={transaction_created:_,transaction_success:_,transaction_failure:{..._,error_code:"string?"},transaction_expired:_,transaction_charge:_,subscription_created:a,subscription_paused:a,subscription_resumed:a,subscription_updated:a,subscription_deleted:a,subscription_charge_paid:a,subscription_charge_failed:{...a,error_code:"string?"},subscription_past_due:a,subscription_canceled:a,access_expires_in_3_days:{},access_expired:{},cart_recovery:{value_minor:"number?",currency:"string?"},testimonial_email_send:{},testimonial_fulfilled:{},partner_commission_earned:{partner_id:"string",commission_minor:"number",currency:"string"},checkout_session_created:{item_count:"number",checkout_type:"enum:single|cart|link",gateway:"string?",...u},order_paid:{gateway:"string",method:"string?",item_count:"number?",visitor_day:"string?",items:"line_items?",...u},refund_issued:{gateway:"string?",reason:"string?",...u},return_requested:{item_count:"number",reason_code:"string?"},automation_run_completed:{automation_id:"string",status:"string",trigger:"string?"},notification_sent:{medium:"string",template:"string?"},notification_failed:{medium:"string",template:"string?",error_code:"string?"},recovery_email_sent:{step:"number?"},recovery_link_clicked:{},api_request:{endpoint:"string",client:"string?",status:"number",latency_bucket:"enum:lt_50|lt_200|lt_1000|gte_1000",sample_rate:"number"}};var R={...b,...h,...E},O={storefront_events:Object.keys(b),app_events:Object.keys(h),business_events:Object.keys(E)},v=Object.fromEntries(w.flatMap(t=>O[t].map(n=>[n,t])));function S(t){return typeof t=="string"&&Object.hasOwn(v,t)}var q=365*24*60*60;function Y(t){let n=t.startsWith("pk_")?t.slice(3):t;return/^[A-Za-z0-9]{1,32}$/.test(n)?n:null}var $=/^([a-z][a-z0-9-]{0,39})@(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]{1,20})?)$/;function x(t){if(!t||t.length>r.sdk)return null;let n=$.exec(t);return n?{package:n[1],version:n[2]}:null}var g=r.utm;function p(t,n){if(t==null)return null;let s=t.trim();return s.length===0||s.includes("@")?null:s.slice(0,n)}function I(t){let s=t.split("/").map(e=>e.includes("@")||e.includes("%40")?":email":/^[A-Za-z0-9_-]{24,}$/.test(e)?":token":e).join("/")||"/";return(s.startsWith("/")?s:`/${s}`).slice(0,r.path)}function F(t,n){let s;try{s=new URL(t,n)}catch (e2){return null}if(s.protocol!=="https:"&&s.protocol!=="http:")return null;let e=s.searchParams;return{host:s.hostname.toLowerCase().slice(0,r.host),path:I(s.pathname),utm_source:p(e.get("utm_source"),g),utm_medium:p(e.get("utm_medium"),g),utm_campaign:p(e.get("utm_campaign"),g),utm_content:p(e.get("utm_content"),g),utm_term:p(e.get("utm_term"),g),ref_code:p(e.get("ref"),r.refCode)}}var V=/^[A-Za-z0-9_-]{1,64}$/;function W(t){if(!t)return null;try{let n=new URL(t);return n.protocol!=="https:"&&n.protocol!=="http:"?null:n.hostname.toLowerCase().slice(0,r.referrerHost)}catch (e3){return null}}var Z=new TextEncoder;var U=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,M=/^[A-Za-z0-9_-]{8,32}$/,L=/[^\s@]+@[^\s@]+\.[A-Za-z]{2,}\b/;function d(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function j(t,n,s){let e=t[n];return e==null?null:typeof e!="string"?`bad_${n}`:e.length>s?`too_long_${n}`:null}function z(t,n){let e=t.endsWith("?")?t.slice(0,-1):t;if(e.startsWith("enum:"))return typeof n=="string"&&e.slice(5).split("|").includes(n);switch(e){case"string":return typeof n=="string"&&n.length<=r.maxPropString;case"number":return typeof n=="number"&&Number.isFinite(n);case"boolean":return typeof n=="boolean";case"string[]":return Array.isArray(n)&&n.length<=r.maxPropArray&&n.every(o=>typeof o=="string"&&o.length<=r.maxPropString);case"number[]":return Array.isArray(n)&&n.length<=r.maxPropArray&&n.every(o=>typeof o=="number"&&Number.isFinite(o));case"line_items":return Array.isArray(n)&&n.length<=r.maxPropArray&&n.every(o=>d(o)&&typeof o.product_id=="string"&&V.test(o.product_id)&&y(o.qty)&&y(o.value_minor));default:return!1}}function y(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0}function B(t){return x(t)!==null?!1:L.test(t)}function m(t){return typeof t=="string"?B(t):Array.isArray(t)?t.some(m):d(t)?Object.values(t).some(m):!1}function D(t,n){if(!S(t))return{ok:!1,reason:"unknown_event"};let s=R[t];if(!s)return{ok:!1,reason:"unknown_event"};if(!d(n))return{ok:!1,reason:"bad_props"};let e={};for(let[o,l]of Object.entries(s)){let i=n[o];if(i==null){if(!l.endsWith("?"))return{ok:!1,reason:`props_missing_${o}`};continue}if(!z(l,i))return{ok:!1,reason:`props_bad_${o}`};if(m(i))return{ok:!1,reason:`props_pii_${o}`};e[o]=l.startsWith("line_items")&&Array.isArray(i)?i.map(c=>({product_id:c.product_id,qty:c.qty,value_minor:c.value_minor})):i}return JSON.stringify(e).length>r.maxPropsChars?{ok:!1,reason:"props_too_large"}:{ok:!0,props:e}}function X(t,n={}){let s=_nullishCoalesce(n.from, () => ("browser")),e=c=>({ok:!1,reason:c});if(!d(t))return e("not_object");if(typeof t.event_id!="string"||!U.test(t.event_id))return e("bad_event_id");if(!S(t.event))return e("unknown_event");let o=v[t.event];if(s==="browser"){if(o==="business_events")return e("server_only_event");if(t.event==="consent_updated")return e("consent_via_consent_endpoint")}if(typeof t.ts!="number"||!Number.isInteger(t.ts)||t.ts<=0||t.ts>4e12)return e("bad_ts");if(t.schema_version!==1)return e("bad_schema_version");if(!C.includes(t.env))return e("bad_env");if(!N.includes(t.source))return e("bad_source");if(!T[o].includes(t.source))return e("source_not_allowed_for_event");if(!A.includes(t.channel))return e("bad_channel");if(t.sdk!=null&&(typeof t.sdk!="string"||x(t.sdk)===null))return e("bad_sdk");if(t.page_id!=null&&(typeof t.page_id!="string"||!M.test(t.page_id)))return e("bad_page_id");if(t.page_type!=null&&!P.includes(t.page_type))return e("bad_page_type");if(s==="browser"){if(typeof t.host!="string"||t.host.length===0)return e("bad_host");if(typeof t.path!="string"||!t.path.startsWith("/"))return e("bad_path")}if(typeof t.path=="string"&&t.path.includes("?"))return e("path_has_query");if(typeof t.path=="string"&&t.path.includes("#"))return e("path_has_fragment");let l=[["host",r.host],["path",r.path],["referrer_host",r.referrerHost],["utm_source",r.utm],["utm_medium",r.utm],["utm_campaign",r.utm],["utm_content",r.utm],["utm_term",r.utm],["ref_code",r.refCode],["product_id",r.id],["variant_id",r.id],["order_ref",r.id]];for(let[c,k]of l){let f=j(t,c,k);if(f)return e(f)}if(t.visitor_id!=null&&(typeof t.visitor_id!="string"||!/^[A-Za-z0-9_-]{22}$/.test(t.visitor_id)))return e("bad_visitor_id");let i=D(t.event,t.props);return i.ok?{ok:!0}:e(i.reason)}var _react = require('react');function Q(t,n){(typeof window<"u"?_react.useLayoutEffect:(0, _react.useEffect))(t,n)}exports.a = r; exports.b = Y; exports.c = I; exports.d = F; exports.e = W; exports.f = D; exports.g = X; exports.h = Q;
|
|
2
|
+
//# sourceMappingURL=chunk-3UHPJ6NK.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/analytics/contract.ts"],"names":["LIMITS","STREAMS","ENVS","SOURCES","CHANNELS","PAGE_TYPES","SOURCES_FOR_STREAM","MONEY","STOREFRONT_EVENT_SPEC","APP_EVENT_SPEC","TX","SUB","BUSINESS_EVENT_SPEC","EVENT_SPEC","EVENT_NAMES","STREAM_FOR_EVENT","stream","name","isEventName","CONSENT_COOKIE_MAX_AGE_SECONDS","normalizeProjectKey","key","bare","CLIENT_RE","parseClientHeader","value","m","MAX_QUERY_VALUE","cleanValue","v","max","t","sanitizePath","pathname","joined","seg"],"mappings":"AAgBO,iLAAMA,CAAAA,CAAS,CAEpB,cAAA,CAAgB,EAAA,CAEhB,YAAA,CAAc,KAAA,CAEd,aAAA,CAAe,IAAA,CACf,aAAA,CAAe,GAAA,CACf,YAAA,CAAc,EAAA,CACd,IAAA,CAAM,GAAA,CACN,IAAA,CAAM,GAAA,CACN,YAAA,CAAc,GAAA,CACd,GAAA,CAAK,GAAA,CACL,OAAA,CAAS,EAAA,CACT,EAAA,CAAI,EAAA,CACJ,GAAA,CAAK,EAAA,CACL,MAAA,CAAQ,EAAA,CACR,MAAA,CAAQ,EAAA,CACR,SAAA,CAAW,EAAA,CAEX,QAAA,CAAU,KACZ,CAAA,CAMaC,CAAAA,CAAU,CACrB,mBAAA,CACA,YAAA,CACA,iBACF,CAAA,CAGaC,CAAAA,CAAO,CAAC,MAAA,CAAQ,MAAM,CAAA,CAGtBC,CAAAA,CAAU,CACrB,YAAA,CACA,WAAA,CACA,QAAA,CACA,QAAA,CACA,WACF,CAAA,CAGaC,CAAAA,C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GAAA,CAAK,OAAO,IAAA,CAChD,IAAM0B,CAAAA,CAAIH,CAAAA,CAAU,IAAA,CAAKE,CAAK,CAAA,CAC9B,OAAOC,CAAAA,CAAI,CAAE,OAAA,CAASA,CAAAA,CAAE,CAAC,CAAA,CAAG,OAAA,CAASA,CAAAA,CAAE,CAAC,CAAE,CAAA,CAAI,IAChD,CAMA,IAAMC,CAAAA,CAAkB3B,CAAAA,CAAO,GAAA,CAOxB,SAAS4B,CAAAA,CAAWC,CAAAA,CAA8BC,CAAAA,CAA4B,CACnF,EAAA,CAAID,CAAAA,EAAK,IAAA,CAAM,OAAO,IAAA,CACtB,IAAME,CAAAA,CAAIF,CAAAA,CAAE,IAAA,CAAK,CAAA,CAEjB,OAAIE,CAAAA,CAAE,MAAA,GAAW,CAAA,EAAKA,CAAAA,CAAE,QAAA,CAAS,GAAG,CAAA,CAAU,IAAA,CACvCA,CAAAA,CAAE,KAAA,CAAM,CAAA,CAAGD,CAAG,CACvB,CAOO,SAASE,CAAAA,CAAaC,CAAAA,CAA0B,CAMrD,IAAMC,CAAAA,CALWD,CAAAA,CAAS,KAAA,CAAM,GAAG,CAAA,CAAE,GAAA,CAAKE,CAAAA,EACpCA,CAAAA,CAAI,QAAA,CAAS,GAAG,CAAA,EAAKA,CAAAA,CAAI,QAAA,CAAS,KAAK,CAAA,CAAU,QAAA,CACjD,sBAAA,CAAuB,IAAA,CAAKA,CAAG,CAAA,CAAU,QAAA,CACtCA,CACR,CAAA,CACuB,IAAA,CAAK,GAAG,CAAA,EAAK,GAAA,CACrC,MAAA,CAAQD,CAAAA,CAAO,UAAA,CAAW,GAAG,CAAA,CAAIA,CAAAA,CAAS,CAAA,CAAA,EAAIA,CAAM,CAAA,CAAA","file":"/home/emems/.t3/worktrees/bitsnap-react/consent-analytics/dist/chunk-3UHPJ6NK.js","sourcesContent":["/**\n * Bitsnap merchant analytics: the wire contract.\n *\n * SOURCE OF TRUTH: instapay `apps/collector/src/contract.ts` (prose version:\n * `docs/merchant-analytics-contract.md`). This file is a verbatim copy of it\n * (everything below the next comment block). Do not edit it here: change\n * instapay's file and copy it over. `computeVisitorId` is pure but needs the\n * server secret; the browser never calls it, so bundlers drop it.\n */\n\nexport const SCHEMA_VERSION = 1;\n\n// ---------------------------------------------------------------------------\n// Limits\n// ---------------------------------------------------------------------------\n\nexport const LIMITS = {\n /** Events in one POST /e. */\n maxBatchEvents: 50,\n /** Body of one POST /e or /consent, in bytes. */\n maxBodyBytes: 64 * 1024,\n /** `JSON.stringify(props)` of one event, in UTF-16 code units. */\n maxPropsChars: 4096,\n maxPropString: 200,\n maxPropArray: 50,\n host: 253,\n path: 512,\n referrerHost: 253,\n utm: 100,\n refCode: 64,\n id: 64,\n sdk: 64,\n pageId: 32,\n region: 64,\n osBrowser: 32,\n /** Collector replaces a client `ts` farther than this from `received_at`. */\n tsSkewMs: 24 * 60 * 60 * 1000,\n} as const;\n\n// ---------------------------------------------------------------------------\n// Enumerations\n// ---------------------------------------------------------------------------\n\nexport const STREAMS = [\n \"storefront_events\",\n \"app_events\",\n \"business_events\",\n] as const;\nexport type Stream = (typeof STREAMS)[number];\n\nexport const ENVS = [\"live\", \"test\"] as const;\nexport type Env = (typeof ENVS)[number];\n\nexport const SOURCES = [\n \"storefront\",\n \"sdk_react\",\n \"script\",\n \"server\",\n \"dashboard\",\n] as const;\nexport type Source = (typeof SOURCES)[number];\n\nexport const CHANNELS = [\n \"hosted\",\n \"custom_domain\",\n \"embed\",\n \"api\",\n \"panel\",\n] as const;\nexport type Channel = (typeof CHANNELS)[number];\n\nexport const PAGE_TYPES = [\n \"shop\",\n \"catalog\",\n \"product\",\n \"cart\",\n \"checkout\",\n \"payment\",\n \"panel\",\n \"course\",\n \"custom_page\",\n \"order\",\n \"returns\",\n \"app\",\n \"other\",\n] as const;\nexport type PageType = (typeof PAGE_TYPES)[number];\n\nexport const DEVICE_TYPES = [\"desktop\", \"mobile\", \"tablet\", \"other\"] as const;\nexport type DeviceType = (typeof DEVICE_TYPES)[number];\n\n/** Sources a browser may claim, per stream. `business_events` is server-only. */\nexport const SOURCES_FOR_STREAM: Record<Stream, readonly Source[]> = {\n storefront_events: [\"storefront\", \"sdk_react\", \"script\"],\n app_events: [\"dashboard\"],\n business_events: [\"server\"],\n};\n\n// ---------------------------------------------------------------------------\n// Event catalogue\n//\n// Each prop is `<type>[?]`: type is `string`, `number`, `boolean`, `string[]`,\n// `number[]` or `enum:a|b|c`; a trailing `?` makes the prop optional.\n// Money is always integer minor units (`*_minor`, grosze/cents) + `currency`\n// (ISO 4217, upper case). `product_id`, `variant_id` and `order_ref` live in\n// the envelope, never in props. Strings never hold PII (see the prose doc).\n// ---------------------------------------------------------------------------\n\nconst MONEY = { value_minor: \"number\", currency: \"string\" } as const;\n\n/** Browser events from hosted pages (H), bitsnap-react (R) and the script (S). */\nexport const STOREFRONT_EVENT_SPEC = {\n page_view: { landing: \"boolean\" },\n product_list_viewed: { list_id: \"string?\", item_count: \"number\" },\n product_impression: {\n list_id: \"string?\",\n product_ids: \"string[]\",\n positions: \"number[]\",\n },\n product_clicked: { list_id: \"string?\", position: \"number?\" },\n product_view: {\n price_minor: \"number\",\n currency: \"string\",\n availability: \"enum:in_stock|out_of_stock|preorder\",\n },\n variant_selected: {},\n add_to_cart: { qty: \"number\", ...MONEY },\n remove_from_cart: { qty: \"number\", ...MONEY },\n cart_opened: { item_count: \"number\", ...MONEY },\n checkout_started: {\n item_count: \"number\",\n checkout_type: \"enum:single|cart|link\",\n ...MONEY,\n },\n checkout_step_completed: {\n step: \"enum:contact|delivery|invoice|consents\",\n },\n checkout_validation_error: { field: \"string\", rule: \"string\" },\n coupon_applied: { coupon_id: \"string\" },\n coupon_rejected: { coupon_id: \"string?\", reason: \"string\" },\n delivery_method_selected: { method: \"string\" },\n payment_method_selected: { gateway: \"string\", method: \"string\" },\n payment_submitted: { gateway: \"string\", method: \"string\" },\n apple_pay_clicked: {},\n apple_pay_result: { outcome: \"enum:success|fail|cancel\" },\n payment_returned: {\n gateway: \"string\",\n method: \"string?\",\n outcome: \"enum:success|fail|cancel|pending\",\n error_code: \"string?\",\n },\n availability_signup: {},\n panel_login: {},\n panel_order_viewed: {},\n panel_download: {},\n return_started: {},\n return_submitted: { reason_code: \"string\", item_count: \"number\" },\n course_opened: { course_id: \"string\" },\n lesson_started: {\n course_id: \"string\",\n lesson_id: \"string\",\n position: \"number\",\n },\n lesson_completed: {\n course_id: \"string\",\n lesson_id: \"string\",\n position: \"number\",\n },\n video_progress: {\n course_id: \"string\",\n lesson_id: \"string\",\n /** 25, 50, 75 or 100. */\n milestone: \"number\",\n },\n test_submitted: {\n course_id: \"string\",\n lesson_id: \"string\",\n score_bucket: \"enum:0-24|25-49|50-74|75-99|100\",\n },\n lesson_rated: {\n course_id: \"string\",\n lesson_id: \"string\",\n /** 1..5. */\n rating: \"number\",\n },\n /** Written by the collector's POST /consent, never sent to POST /e. */\n consent_updated: {\n consent_id: \"string\",\n action: \"enum:accept_all|reject_all|custom|withdraw\",\n analytics: \"boolean\",\n marketing: \"boolean\",\n preferences: \"boolean\",\n banner_version: \"number\",\n },\n} as const;\n\n/** Merchant behaviour in /app, sent through the same tracker core. */\nexport const APP_EVENT_SPEC = {\n app_page_view: { route: \"string\", previous_route: \"string?\" },\n insight_shown: { insight_type: \"string\", rank: \"number\", category: \"string\" },\n insight_clicked: {\n insight_type: \"string\",\n rank: \"number\",\n category: \"string\",\n },\n insight_dismissed: {\n insight_type: \"string\",\n rank: \"number\",\n category: \"string\",\n },\n checklist_step_viewed: { step: \"string\" },\n checklist_step_completed: { step: \"string\" },\n gateway_connect_started: { gateway: \"string\", step: \"string?\" },\n gateway_connect_completed: { gateway: \"string\", step: \"string?\" },\n gateway_connect_failed: {\n gateway: \"string\",\n step: \"string?\",\n error_code: \"string?\",\n },\n domain_connect_started: {},\n domain_connect_verified: {},\n domain_connect_failed: { error_code: \"string?\" },\n product_created: { product_type: \"string?\" },\n product_published: { product_type: \"string?\" },\n product_editor_section_opened: { section: \"string\" },\n feature_enabled: { feature: \"string\" },\n stats_viewed: { tab: \"string\" },\n stats_filter_changed: { tab: \"string\", filter: \"string\" },\n report_exported: { report: \"string\", format: \"string?\" },\n search_performed: { result_count: \"number\" },\n error_shown: { code: \"string\", route: \"string\" },\n help_opened: { topic: \"string?\" },\n ai_assistant_used: { topic: \"string?\" },\n member_invited: { role: \"string\" },\n} as const;\n\nconst TX = {\n gateway: \"string?\",\n method: \"string?\",\n value_minor: \"number?\",\n currency: \"string?\",\n} as const;\nconst SUB = {\n subscription_id: \"string?\",\n value_minor: \"number?\",\n currency: \"string?\",\n} as const;\n\n/**\n * Emitted by instapay only. The lower-cased `EventType` of\n * server/event-system/event.list.ts maps 1:1 to the first group.\n */\nexport const BUSINESS_EVENT_SPEC = {\n // Mirror of the event bus (EventType.X -> x.toLowerCase()).\n transaction_created: TX,\n transaction_success: TX,\n transaction_failure: { ...TX, error_code: \"string?\" },\n transaction_expired: TX,\n transaction_charge: TX,\n subscription_created: SUB,\n subscription_paused: SUB,\n subscription_resumed: SUB,\n subscription_updated: SUB,\n subscription_deleted: SUB,\n subscription_charge_paid: SUB,\n subscription_charge_failed: { ...SUB, error_code: \"string?\" },\n subscription_past_due: SUB,\n subscription_canceled: SUB,\n access_expires_in_3_days: {},\n access_expired: {},\n cart_recovery: { value_minor: \"number?\", currency: \"string?\" },\n testimonial_email_send: {},\n testimonial_fulfilled: {},\n partner_commission_earned: {\n partner_id: \"string\",\n commission_minor: \"number\",\n currency: \"string\",\n },\n // Added by the analytics work.\n checkout_session_created: {\n item_count: \"number\",\n checkout_type: \"enum:single|cart|link\",\n gateway: \"string?\",\n ...MONEY,\n },\n order_paid: {\n gateway: \"string\",\n method: \"string?\",\n item_count: \"number?\",\n /** UTC date (`YYYY-MM-DD`) the envelope `visitor_id` was computed for. */\n visitor_day: \"string?\",\n /** Every line of the order (public hashed product ids), at most 50. */\n items: \"line_items?\",\n ...MONEY,\n },\n refund_issued: {\n gateway: \"string?\",\n reason: \"string?\",\n ...MONEY,\n },\n return_requested: { item_count: \"number\", reason_code: \"string?\" },\n automation_run_completed: {\n automation_id: \"string\",\n status: \"string\",\n trigger: \"string?\",\n },\n notification_sent: { medium: \"string\", template: \"string?\" },\n notification_failed: {\n medium: \"string\",\n template: \"string?\",\n error_code: \"string?\",\n },\n recovery_email_sent: { step: \"number?\" },\n recovery_link_clicked: {},\n api_request: {\n /** Route template without ids or query, e.g. `/api/rpc/public.v1.PublicApiService/ListProducts`. */\n endpoint: \"string\",\n /** `X-Bitsnap-Client` value, absent when the caller sent none. */\n client: \"string?\",\n status: \"number\",\n latency_bucket: \"enum:lt_50|lt_200|lt_1000|gte_1000\",\n /** 1 for errors, <1 for sampled successes; rollups divide counts by it. */\n sample_rate: \"number\",\n },\n} as const;\n\nexport const EVENT_SPEC_BY_STREAM = {\n storefront_events: STOREFRONT_EVENT_SPEC,\n app_events: APP_EVENT_SPEC,\n business_events: BUSINESS_EVENT_SPEC,\n} as const;\n\nexport const EVENT_SPEC = {\n ...STOREFRONT_EVENT_SPEC,\n ...APP_EVENT_SPEC,\n ...BUSINESS_EVENT_SPEC,\n} as const;\n\nexport type StorefrontEventName = keyof typeof STOREFRONT_EVENT_SPEC;\nexport type AppEventName = keyof typeof APP_EVENT_SPEC;\nexport type BusinessEventName = keyof typeof BUSINESS_EVENT_SPEC;\nexport type EventName = StorefrontEventName | AppEventName | BusinessEventName;\n\nexport const EVENT_NAMES = {\n storefront_events: Object.keys(STOREFRONT_EVENT_SPEC) as StorefrontEventName[],\n app_events: Object.keys(APP_EVENT_SPEC) as AppEventName[],\n business_events: Object.keys(BUSINESS_EVENT_SPEC) as BusinessEventName[],\n} as const;\n\nexport const STREAM_FOR_EVENT: Record<EventName, Stream> = Object.fromEntries(\n STREAMS.flatMap((stream) =>\n (EVENT_NAMES[stream] as string[]).map((name) => [name, stream] as const),\n ),\n) as Record<EventName, Stream>;\n\n/** True for a catalogue event name; own keys only (`constructor`, `toString` are not events). */\nexport function isEventName(name: unknown): name is EventName {\n return typeof name === \"string\" && Object.hasOwn(STREAM_FOR_EVENT, name);\n}\n\n// -- props types, derived from the spec ------------------------------------\n\ntype PropPrimitives = {\n string: string;\n number: number;\n boolean: boolean;\n \"string[]\": string[];\n \"number[]\": number[];\n line_items: Array<{ product_id: string; qty: number; value_minor: number }>;\n};\ntype SplitEnum<S extends string> = S extends `${infer H}|${infer R}`\n ? H | SplitEnum<R>\n : S;\ntype StripOpt<S extends string> = S extends `${infer B}?` ? B : S;\ntype ResolveProp<S extends string> =\n StripOpt<S> extends `enum:${infer E}`\n ? SplitEnum<E>\n : StripOpt<S> extends keyof PropPrimitives\n ? PropPrimitives[StripOpt<S>]\n : never;\ntype PropsFromSpec<S extends Record<string, string>> = {\n [K in keyof S as S[K] extends `${string}?` ? never : K]: ResolveProp<S[K]>;\n} & {\n [K in keyof S as S[K] extends `${string}?` ? K : never]?: ResolveProp<S[K]>;\n};\n\nexport type EventProps<E extends EventName> = PropsFromSpec<\n (typeof EVENT_SPEC)[E]\n>;\n\n// ---------------------------------------------------------------------------\n// Envelope\n// ---------------------------------------------------------------------------\n\n/** Fields the emitter fills in. Everything else is derived by the collector. */\nexport interface ClientEvent<E extends EventName = EventName> {\n /** UUIDv7, generated by the emitter. Dedupe key. */\n event_id: string;\n event: E;\n /** Client clock, unix ms. */\n ts: number;\n schema_version: typeof SCHEMA_VERSION;\n env: Env;\n source: Source;\n channel: Channel;\n /** `<package>@<version>`, e.g. `bitsnap-react@1.9.0`. */\n sdk?: string | null;\n /** Random per page load, in memory only. */\n page_id?: string | null;\n page_type?: PageType | null;\n host?: string | null;\n /** Path without query string and fragment, already run through `sanitizePath`. */\n path?: string | null;\n referrer_host?: string | null;\n utm_source?: string | null;\n utm_medium?: string | null;\n utm_campaign?: string | null;\n utm_content?: string | null;\n utm_term?: string | null;\n ref_code?: string | null;\n product_id?: string | null;\n variant_id?: string | null;\n order_ref?: string | null;\n /** Object on the wire; the collector stores `JSON.stringify(props)`. */\n props: EventProps<E>;\n /**\n * Only honoured for `source: \"dashboard\"`: the hashed Clerk user id computed\n * by instapay and handed to the dashboard tracker. Ignored for every other\n * source (the collector computes `visitor_id` itself).\n */\n visitor_id?: string | null;\n}\n\n/** One row as stored in Basin (all three streams share this shape). */\nexport interface StoredEvent {\n event_id: string;\n event: EventName;\n /** Unix ms, client clock after `clampTs`. */\n ts: number;\n /** Unix ms, collector clock. */\n received_at: number;\n schema_version: number;\n /** Numeric database id. Resolved by the collector, never taken from the client. */\n project_id: number;\n env: Env;\n source: Source;\n channel: Channel;\n sdk: string | null;\n visitor_id: string | null;\n page_id: string | null;\n page_type: PageType | null;\n host: string | null;\n path: string | null;\n referrer_host: string | null;\n utm_source: string | null;\n utm_medium: string | null;\n utm_campaign: string | null;\n utm_content: string | null;\n utm_term: string | null;\n ref_code: string | null;\n country: string | null;\n region: string | null;\n device_type: DeviceType | null;\n os: string | null;\n browser: string | null;\n product_id: string | null;\n variant_id: string | null;\n order_ref: string | null;\n /** `JSON.stringify` of the props object. */\n props: string;\n}\n\n/** POST /e body. */\nexport interface IngestBody {\n /** Project key, see `normalizeProjectKey`. */\n k: string;\n events: ClientEvent[];\n}\n\n// ---------------------------------------------------------------------------\n// Consent shapes\n// ---------------------------------------------------------------------------\n\nexport const CONSENT_TEXT_KEYS = [\n \"title\",\n \"description\",\n \"acceptAll\",\n \"rejectAll\",\n \"settings\",\n \"save\",\n \"close\",\n \"necessaryTitle\",\n \"necessaryDescription\",\n \"analyticsTitle\",\n \"analyticsDescription\",\n \"marketingTitle\",\n \"marketingDescription\",\n \"preferencesTitle\",\n \"preferencesDescription\",\n \"poweredBy\",\n] as const;\nexport type ConsentTextKey = (typeof CONSENT_TEXT_KEYS)[number];\nexport type ConsentTexts = Record<ConsentTextKey, string>;\n\nexport type ConsentCategory = \"analytics\" | \"marketing\" | \"preferences\";\nexport type ConsentChoice = Record<ConsentCategory, boolean>;\n\nexport type ConsentConfig = {\n version: number;\n theme: \"auto\" | \"light\" | \"dark\";\n accentColor?: string;\n position: \"bottom\" | \"bottom-left\" | \"bottom-right\";\n privacyPolicyUrl?: string;\n categories: { analytics: boolean; marketing: boolean; preferences: boolean };\n services: Array<{\n name: string;\n category: \"analytics\" | \"marketing\" | \"preferences\";\n cookies?: string[];\n }>;\n texts?: Partial<Record<\"pl\" | \"en\", Partial<ConsentTexts>>>;\n poweredBy: true;\n};\n\n/** Value of the consent cookie, JSON then base64url. */\nexport interface ConsentCookie {\n v: 1;\n /** Random consent id (also sent to POST /consent). */\n id: string;\n /** Unix seconds. */\n ts: number;\n /** Banner version (`ConsentConfig.version`) the visitor answered. */\n bv: number;\n c: ConsentChoice;\n}\n\nexport const CONSENT_COOKIE_NAME = \"bitsnap_consent\";\nexport const CONSENT_COOKIE_MAX_AGE_SECONDS = 365 * 24 * 60 * 60;\nexport const CONSENT_ACTIONS = [\n \"accept_all\",\n \"reject_all\",\n \"custom\",\n \"withdraw\",\n] as const;\nexport type ConsentAction = (typeof CONSENT_ACTIONS)[number];\n\n/** POST /consent body. */\nexport interface ConsentLogBody {\n k: string;\n /** Same random id as `ConsentCookie.id`. 16 to 64 chars of `[A-Za-z0-9_-]`. */\n consent_id: string;\n action: ConsentAction;\n c: ConsentChoice;\n /** Banner version. */\n bv: number;\n /** Hostname the banner ran on. Collector overwrites it with the Origin host. */\n host: string;\n /** Unix SECONDS (like the cookie), not ms. */\n ts: number;\n}\n\n/** `bitsnap_consent`, or `bitsnap_consent_<projectKey>` for `data-scope=\"project\"`. */\nexport function consentCookieName(scope: \"site\" | \"project\", projectKey?: string): string {\n if (scope === \"project\") {\n if (!projectKey) throw new Error(\"projectKey required for project scope\");\n return `${CONSENT_COOKIE_NAME}_${normalizeProjectKey(projectKey)}`;\n }\n return CONSENT_COOKIE_NAME;\n}\n\n// ---------------------------------------------------------------------------\n// Project key\n// ---------------------------------------------------------------------------\n\n/**\n * The project key is the existing public hashed project id\n * (`hashId(projectId)` in apps/bitsnap/queries/hashids.ts, the `projectID`\n * of bitsnap-react). A leading `pk_` is accepted and dropped so the\n * documented `pk_…` snippets work too. Returns null when it is not a plausible\n * key (hashids default alphabet).\n */\nexport function normalizeProjectKey(key: string): string | null {\n const bare = key.startsWith(\"pk_\") ? key.slice(3) : key;\n return /^[A-Za-z0-9]{1,32}$/.test(bare) ? bare : null;\n}\n\n// ---------------------------------------------------------------------------\n// X-Bitsnap-Client\n// ---------------------------------------------------------------------------\n\nconst CLIENT_RE = /^([a-z][a-z0-9-]{0,39})@(\\d+\\.\\d+\\.\\d+(?:[-+][0-9A-Za-z.+-]{1,20})?)$/;\n\n/** `<package>@<version>`, e.g. `bitsnap-react@1.9.0`. Also the shape of `sdk`. */\nexport function parseClientHeader(\n value: string | null | undefined,\n): { package: string; version: string } | null {\n if (!value || value.length > LIMITS.sdk) return null;\n const m = CLIENT_RE.exec(value);\n return m ? { package: m[1], version: m[2] } : null;\n}\n\n// ---------------------------------------------------------------------------\n// URL stripping\n// ---------------------------------------------------------------------------\n\nconst MAX_QUERY_VALUE = LIMITS.utm;\n\n/**\n * Campaign/ref value: trimmed, capped, null when empty or when it holds an \"@\"\n * (someone put an email in a tag). The collector runs every client-supplied\n * `utm_*` and `ref_code` through it again.\n */\nexport function cleanValue(v: string | null | undefined, max: number): string | null {\n if (v == null) return null;\n const t = v.trim();\n // An \"@\" means someone put an email in a campaign tag: drop the value.\n if (t.length === 0 || t.includes(\"@\")) return null;\n return t.slice(0, max);\n}\n\n/**\n * Path sanitiser: no query, no fragment, capped. Opaque segments (24+ chars of\n * `[A-Za-z0-9_-]`, i.e. tokens in order/panel links) become `:token` and\n * segments containing `@` become `:email`.\n */\nexport function sanitizePath(pathname: string): string {\n const segments = pathname.split(\"/\").map((seg) => {\n if (seg.includes(\"@\") || seg.includes(\"%40\")) return \":email\";\n if (/^[A-Za-z0-9_-]{24,}$/.test(seg)) return \":token\";\n return seg;\n });\n const joined = segments.join(\"/\") || \"/\";\n return (joined.startsWith(\"/\") ? joined : `/${joined}`).slice(0, LIMITS.path);\n}\n\nexport interface UrlParts {\n host: string;\n /** Sanitised path, no query. */\n path: string;\n utm_source: string | null;\n utm_medium: string | null;\n utm_campaign: string | null;\n utm_content: string | null;\n utm_term: string | null;\n /** The `ref` query parameter. */\n ref_code: string | null;\n}\n\n/**\n * Parses a URL and keeps only what may leave the browser: host, sanitised path\n * and the `utm_*` and `ref` query parameters. Returns null for non-http(s) or\n * unparseable input. `base` resolves relative URLs.\n */\nexport function parseUrl(url: string, base?: string): UrlParts | null {\n let u: URL;\n try {\n u = new URL(url, base);\n } catch {\n return null;\n }\n if (u.protocol !== \"https:\" && u.protocol !== \"http:\") return null;\n const q = u.searchParams;\n return {\n host: u.hostname.toLowerCase().slice(0, LIMITS.host),\n path: sanitizePath(u.pathname),\n utm_source: cleanValue(q.get(\"utm_source\"), MAX_QUERY_VALUE),\n utm_medium: cleanValue(q.get(\"utm_medium\"), MAX_QUERY_VALUE),\n utm_campaign: cleanValue(q.get(\"utm_campaign\"), MAX_QUERY_VALUE),\n utm_content: cleanValue(q.get(\"utm_content\"), MAX_QUERY_VALUE),\n utm_term: cleanValue(q.get(\"utm_term\"), MAX_QUERY_VALUE),\n ref_code: cleanValue(q.get(\"ref\"), LIMITS.refCode),\n };\n}\n\n/**\n * Returns the URL with userinfo, fragment and every query parameter removed\n * except `utm_*` and `ref`. Null when `url` is not a usable http(s) URL.\n */\nexport function stripUrl(url: string, base?: string): string | null {\n let u: URL;\n try {\n u = new URL(url, base);\n } catch {\n return null;\n }\n if (u.protocol !== \"https:\" && u.protocol !== \"http:\") return null;\n const keep = new URLSearchParams();\n for (const [key, value] of u.searchParams) {\n if (key !== \"ref\" && !key.startsWith(\"utm_\")) continue;\n const cleaned = cleanValue(value, MAX_QUERY_VALUE);\n if (cleaned != null) keep.append(key, cleaned);\n }\n const qs = keep.toString();\n return `${u.protocol}//${u.host}${sanitizePath(u.pathname)}${qs ? `?${qs}` : \"\"}`;\n}\n\nconst HOSTNAME_RE = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/;\n\n/** A plain DNS hostname (lower-cased), or null: no scheme, port, path, userinfo or \"@\". */\nexport function cleanHostname(\n v: string | null | undefined,\n max: number = LIMITS.referrerHost,\n): string | null {\n if (typeof v !== \"string\") return null;\n const h = v.trim().toLowerCase();\n return h.length > 0 && h.length <= max && HOSTNAME_RE.test(h) ? h : null;\n}\n\n/** Public hashed ids (`product_id`, `variant_id`, `order_ref`): URL-safe, at most `LIMITS.id`. */\nexport const ID_RE = /^[A-Za-z0-9_-]{1,64}$/;\n\nexport function cleanId(v: string | null | undefined): string | null {\n return typeof v === \"string\" && ID_RE.test(v) ? v : null;\n}\n\n/** Host of a referrer URL, or null (also null for non-http(s) referrers). */\nexport function referrerHost(referrer: string | null | undefined): string | null {\n if (!referrer) return null;\n try {\n const u = new URL(referrer);\n if (u.protocol !== \"https:\" && u.protocol !== \"http:\") return null;\n return u.hostname.toLowerCase().slice(0, LIMITS.referrerHost);\n } catch {\n return null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Bot rule\n// ---------------------------------------------------------------------------\n\nconst BOT_UA =\n /bot\\b|crawl|spider|slurp|facebookexternalhit|bingpreview|headless|phantomjs|lighthouse|pagespeed|gtmetrix|pingdom|uptime|statuscake|monitor|preview|scrapy|curl\\/|wget|python-|go-http-client|java\\/|okhttp|axios|node-fetch|undici|libwww|httpclient|aiohttp|postman|insomnia/i;\n\n/** True when the User-Agent is empty or looks automated. Such events are dropped. */\nexport function isBotUserAgent(ua: string | null | undefined): boolean {\n if (!ua || ua.trim().length === 0) return true;\n return BOT_UA.test(ua);\n}\n\n// ---------------------------------------------------------------------------\n// visitor_id\n// ---------------------------------------------------------------------------\n\nconst encoder = new TextEncoder();\n\nasync function hmacSha256(\n key: Uint8Array,\n message: string,\n): Promise<Uint8Array> {\n const cryptoKey = await crypto.subtle.importKey(\n \"raw\",\n key,\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n return new Uint8Array(\n await crypto.subtle.sign(\"HMAC\", cryptoKey, encoder.encode(message)),\n );\n}\n\nfunction base64url(bytes: Uint8Array): string {\n let bin = \"\";\n for (const b of bytes) bin += String.fromCharCode(b);\n return btoa(bin).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/** `YYYY-MM-DD` of a unix-ms timestamp in UTC. */\nexport function utcDate(ms: number): string {\n return new Date(ms).toISOString().slice(0, 10);\n}\n\n/**\n * IP as hashed: lower-case; IPv4 unchanged; IPv4-mapped IPv6 (`::ffff:1.2.3.4`\n * or `::ffff:102:304`) becomes plain IPv4; any other IPv6, including one with\n * an embedded dotted quad (`64:ff9b::1.2.3.4`), is cut to its /64 (first four\n * hextets, canonical form `a:b:c:d::`). Both the Worker and the instapay\n * server MUST call this on the client IP before `computeVisitorId`.\n */\nexport function normalizeIp(ip: string): string {\n let s = ip.trim().toLowerCase();\n const zone = s.indexOf(\"%\");\n if (zone >= 0) s = s.slice(0, zone);\n if (!s.includes(\":\")) return s; // plain IPv4 (or not an IP at all)\n\n // Embedded dotted quad in the last 32 bits: turn it into two hextets.\n const quad = /^(.*:)(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/.exec(s);\n if (quad) {\n const o = [quad[2], quad[3], quad[4], quad[5]].map(Number);\n if (o.some((n) => n > 255)) return s;\n const hex = (hi: number, lo: number) => (hi * 256 + lo).toString(16);\n s = `${quad[1]}${hex(o[0], o[1])}:${hex(o[2], o[3])}`;\n }\n\n const [head, tail] = s.split(\"::\");\n const headParts = head ? head.split(\":\") : [];\n const tailParts = tail !== undefined && tail !== \"\" ? tail.split(\":\") : [];\n const fill =\n tail === undefined ? 0 : Math.max(0, 8 - headParts.length - tailParts.length);\n const groups = [...headParts, ...Array<string>(fill).fill(\"0\"), ...tailParts];\n if (groups.length !== 8) return s;\n const h = groups.map((g) => Number.parseInt(g, 16) || 0);\n\n // ::ffff:a.b.c.d in hex form.\n if (h.slice(0, 5).every((x) => x === 0) && h[5] === 0xffff) {\n return `${h[6] >> 8}.${h[6] & 255}.${h[7] >> 8}.${h[7] & 255}`;\n }\n return `${h\n .slice(0, 4)\n .map((g) => g.toString(16))\n .join(\":\")}::`;\n}\n\n/**\n * Cookieless visitor id, identical in the Worker and the instapay server.\n *\n * day_secret = HMAC-SHA256(key = utf8(masterSecret), msg = utf8(\"YYYY-MM-DD\")) // 32 raw bytes\n * visitor_id = base64url(HMAC-SHA256(key = day_secret, msg = utf8(ip + \"\\n\" + ua + \"\\n\" + projectId))).slice(0, 22)\n *\n * `dateUtc` is the UTC date of the request; `ip` is `normalizeIp(<client IP>)`;\n * `ua` is the raw `User-Agent` request header; `projectId` is the decimal\n * numeric project id.\n */\nexport async function computeVisitorId(\n masterSecret: string,\n dateUtc: string,\n ip: string,\n ua: string,\n projectId: number | string,\n): Promise<string> {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(dateUtc)) {\n throw new Error(`dateUtc must be YYYY-MM-DD, got ${dateUtc}`);\n }\n const daySecret = await hmacSha256(encoder.encode(masterSecret), dateUtc);\n const mac = await hmacSha256(daySecret, `${ip}\\n${ua}\\n${projectId}`);\n return base64url(mac).slice(0, 22);\n}\n\n// ---------------------------------------------------------------------------\n// Validation\n// ---------------------------------------------------------------------------\n\nexport type ValidationResult = { ok: true } | { ok: false; reason: string };\n\nconst UUID_V7 =\n /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\nconst PAGE_ID_RE = /^[A-Za-z0-9_-]{8,32}$/;\n/** A letter TLD is required: `bitsnap-react@1.9.0` and `v@1.2` are not addresses. */\nconst EMAIL_LIKE = /[^\\s@]+@[^\\s@]+\\.[A-Za-z]{2,}\\b/;\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\nfunction nullableString(\n e: Record<string, unknown>,\n key: string,\n max: number,\n): string | null {\n const v = e[key];\n if (v === undefined || v === null) return null;\n if (typeof v !== \"string\") return `bad_${key}`;\n return v.length > max ? `too_long_${key}` : null;\n}\n\nfunction checkPropValue(spec: string, value: unknown): boolean {\n const optional = spec.endsWith(\"?\");\n const type = optional ? spec.slice(0, -1) : spec;\n if (type.startsWith(\"enum:\")) {\n return typeof value === \"string\" && type.slice(5).split(\"|\").includes(value);\n }\n switch (type) {\n case \"string\":\n return typeof value === \"string\" && value.length <= LIMITS.maxPropString;\n case \"number\":\n return typeof value === \"number\" && Number.isFinite(value);\n case \"boolean\":\n return typeof value === \"boolean\";\n case \"string[]\":\n return (\n Array.isArray(value) &&\n value.length <= LIMITS.maxPropArray &&\n value.every((x) => typeof x === \"string\" && x.length <= LIMITS.maxPropString)\n );\n case \"number[]\":\n return (\n Array.isArray(value) &&\n value.length <= LIMITS.maxPropArray &&\n value.every((x) => typeof x === \"number\" && Number.isFinite(x))\n );\n case \"line_items\":\n return (\n Array.isArray(value) &&\n value.length <= LIMITS.maxPropArray &&\n value.every(\n (x) =>\n isRecord(x) &&\n typeof x.product_id === \"string\" &&\n ID_RE.test(x.product_id) &&\n isNonNegativeSafeInteger(x.qty) &&\n isNonNegativeSafeInteger(x.value_minor),\n )\n );\n default:\n return false;\n }\n}\n\nfunction isNonNegativeSafeInteger(value: unknown): boolean {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0;\n}\n\n/** True when `value` looks like an email address (also exported for the collector's re-checks). */\nexport function looksLikeEmail(value: string): boolean {\n // A well-formed `<package>@<version>` client id is never an address.\n if (parseClientHeader(value) !== null) return false;\n return EMAIL_LIKE.test(value);\n}\n\nfunction hasEmailLike(value: unknown): boolean {\n if (typeof value === \"string\") return looksLikeEmail(value);\n if (Array.isArray(value)) return value.some(hasEmailLike);\n if (isRecord(value)) return Object.values(value).some(hasEmailLike);\n return false;\n}\n\n/**\n * Validates `props` against the catalogue and returns a copy without keys the\n * catalogue does not know (forward compatibility: a newer SDK adding an\n * optional prop must not get its events dropped by an older collector).\n * Fails on missing required props, wrong types, bad enum values, oversize\n * props and string values that look like an email address.\n */\nexport function sanitizeProps(\n event: string,\n props: unknown,\n): { ok: true; props: Record<string, unknown> } | { ok: false; reason: string } {\n if (!isEventName(event)) return { ok: false, reason: \"unknown_event\" };\n const spec = (EVENT_SPEC as Record<string, Record<string, string>>)[event];\n if (!spec) return { ok: false, reason: \"unknown_event\" };\n if (!isRecord(props)) return { ok: false, reason: \"bad_props\" };\n const out: Record<string, unknown> = {};\n for (const [key, type] of Object.entries(spec)) {\n const value = props[key];\n if (value === undefined || value === null) {\n if (!type.endsWith(\"?\")) return { ok: false, reason: `props_missing_${key}` };\n continue;\n }\n if (!checkPropValue(type, value)) return { ok: false, reason: `props_bad_${key}` };\n if (hasEmailLike(value)) return { ok: false, reason: `props_pii_${key}` };\n out[key] =\n type.startsWith(\"line_items\") && Array.isArray(value)\n ? value.map((x) => ({ product_id: x.product_id, qty: x.qty, value_minor: x.value_minor }))\n : value;\n }\n if (JSON.stringify(out).length > LIMITS.maxPropsChars) {\n return { ok: false, reason: \"props_too_large\" };\n }\n return { ok: true, props: out };\n}\n\nexport interface ValidateOptions {\n /**\n * Who sent it. `browser` (default) is POST /e: the event must belong to\n * `storefront_events` or `app_events`, `consent_updated` is refused (only\n * POST /consent writes it) and `source` must fit the stream. `server` is the\n * instapay emitter: any stream, `source` must fit the stream.\n */\n from?: \"browser\" | \"server\";\n}\n\n/**\n * Validates the emitter-controlled part of an event: names, types, enums,\n * lengths, the event/source/stream pairing and `props`. It does not check\n * that `ts` is plausible (use `clampTs`), origins or project keys.\n */\nexport function validateEnvelope(\n e: unknown,\n options: ValidateOptions = {},\n): ValidationResult {\n const from = options.from ?? \"browser\";\n const fail = (reason: string): ValidationResult => ({ ok: false, reason });\n if (!isRecord(e)) return fail(\"not_object\");\n\n if (typeof e.event_id !== \"string\" || !UUID_V7.test(e.event_id)) {\n return fail(\"bad_event_id\");\n }\n if (!isEventName(e.event)) return fail(\"unknown_event\");\n const stream = STREAM_FOR_EVENT[e.event as EventName];\n if (from === \"browser\") {\n if (stream === \"business_events\") return fail(\"server_only_event\");\n if (e.event === \"consent_updated\") return fail(\"consent_via_consent_endpoint\");\n }\n if (\n typeof e.ts !== \"number\" ||\n !Number.isInteger(e.ts) ||\n e.ts <= 0 ||\n e.ts > 4e12\n ) {\n return fail(\"bad_ts\");\n }\n if (e.schema_version !== SCHEMA_VERSION) return fail(\"bad_schema_version\");\n if (!ENVS.includes(e.env as Env)) return fail(\"bad_env\");\n if (!SOURCES.includes(e.source as Source)) return fail(\"bad_source\");\n if (!SOURCES_FOR_STREAM[stream].includes(e.source as Source)) {\n return fail(\"source_not_allowed_for_event\");\n }\n if (!CHANNELS.includes(e.channel as Channel)) return fail(\"bad_channel\");\n\n if (e.sdk != null) {\n if (typeof e.sdk !== \"string\" || parseClientHeader(e.sdk) === null) {\n return fail(\"bad_sdk\");\n }\n }\n if (e.page_id != null) {\n if (typeof e.page_id !== \"string\" || !PAGE_ID_RE.test(e.page_id)) {\n return fail(\"bad_page_id\");\n }\n }\n if (e.page_type != null && !PAGE_TYPES.includes(e.page_type as PageType)) {\n return fail(\"bad_page_type\");\n }\n if (from === \"browser\") {\n if (typeof e.host !== \"string\" || e.host.length === 0) return fail(\"bad_host\");\n if (typeof e.path !== \"string\" || !e.path.startsWith(\"/\")) return fail(\"bad_path\");\n }\n if (typeof e.path === \"string\" && e.path.includes(\"?\")) return fail(\"path_has_query\");\n if (typeof e.path === \"string\" && e.path.includes(\"#\")) return fail(\"path_has_fragment\");\n\n const lengths: Array<[string, number]> = [\n [\"host\", LIMITS.host],\n [\"path\", LIMITS.path],\n [\"referrer_host\", LIMITS.referrerHost],\n [\"utm_source\", LIMITS.utm],\n [\"utm_medium\", LIMITS.utm],\n [\"utm_campaign\", LIMITS.utm],\n [\"utm_content\", LIMITS.utm],\n [\"utm_term\", LIMITS.utm],\n [\"ref_code\", LIMITS.refCode],\n [\"product_id\", LIMITS.id],\n [\"variant_id\", LIMITS.id],\n [\"order_ref\", LIMITS.id],\n ];\n for (const [key, max] of lengths) {\n const problem = nullableString(e, key, max);\n if (problem) return fail(problem);\n }\n if (e.visitor_id != null) {\n if (typeof e.visitor_id !== \"string\" || !/^[A-Za-z0-9_-]{22}$/.test(e.visitor_id)) {\n return fail(\"bad_visitor_id\");\n }\n }\n\n const props = sanitizeProps(e.event, e.props);\n if (!props.ok) return fail(props.reason);\n return { ok: true };\n}\n\n/** Client `ts` as stored: replaced by `receivedAt` when more than 24 h away from it. */\nexport function clampTs(ts: number, receivedAt: number): number {\n return Math.abs(ts - receivedAt) > LIMITS.tsSkewMs ? receivedAt : ts;\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkQZJGNLCZjs = require('./chunk-QZJGNLCZ.js');var p="X-Bitsnap-Client",a=`bitsnap-react@${_chunkQZJGNLCZjs.a}`,T="bs_client",L= exports.a ={[p]:a},E= exports.b =e=>t=>(t.header.set(p,a),e(t));function h(e){let t=e.indexOf("#"),o=t===-1?e:e.slice(0,t),s=t===-1?"":e.slice(t),n=o.includes("?")?/[?&]$/.test(o)?"":"&":"?";return`${o}${n}${T}=${encodeURIComponent(a)}${s}`}var y="https://bitsnap.pl",g= exports.f =y;function v(e){console.log("setCustomHost",e),g= exports.f =e}function d(e,t){return t.toLowerCase().startsWith("en")?e.en:e.pl}function f(e,t){let o={...e};if(t!=null)for(let[s,n]of Object.entries(t))n!=null&&(o[s]=n);return o}function u(e,t,o){return f(d(e,t),o)}function x(e,t){return _nullishCoalesce(e[t], () => (t))}var C={en:{cart:"Cart",emptyCart:"Your cart is empty.",total:"Total:",delivery:"+ delivery",chooseCountry:"Choose a country",nextStep:"Next step",unavailableProducts:"Not all products are available."},pl:{cart:"Koszyk",emptyCart:"Brak produkt\xF3w w koszyku.",total:"Suma:",delivery:"+ dostawa",chooseCountry:"Wybierz kraj",nextStep:"Nast\u0119pny krok",unavailableProducts:"Nie wszystkie produkty s\u0105 dost\u0119pne w magazynie."}};function m(e,t){return u(C,e,t)}function A(e,t,o){return x(m(t,o),e)}var i="pl-PL",l="bitsnap-locale",r;function w(e){let t=_optionalChain([e, 'optionalAccess', _ => _.trim, 'call', _2 => _2()]);r=t?t.toLowerCase()==="en"?"en-US":t.toLowerCase()==="pl"?i:t:void 0,typeof localStorage<"u"&&(r==null?localStorage.removeItem(l):localStorage.setItem(l,r))}function H(){return _nullishCoalesce(r, () => ((typeof localStorage<"u"?_nullishCoalesce(localStorage.getItem(l), () => (i)):i)))}var _clsx = require('clsx');var _tailwindmerge = require('tailwind-merge');function $(...e){return _tailwindmerge.twMerge.call(void 0, _clsx.clsx.call(void 0, e))}exports.a = L; exports.b = E; exports.c = h; exports.d = $; exports.e = y; exports.f = g; exports.g = v; exports.h = d; exports.i = u; exports.j = A; exports.k = i; exports.l = w; exports.m = H;
|
|
2
|
+
//# sourceMappingURL=chunk-CO2P4FR5.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/consent-analytics/dist/chunk-CO2P4FR5.js","../src/lib/client-header.ts"],"names":["CLIENT_HEADER_NAME","CLIENT_HEADER_VALUE","SDK_VERSION"],"mappings":"AAAA,uuBAAuC,ICG1BA,CAAAA,CAAqB,kBAAA,CACrBC,CAAAA,CAAsB,CAAA,cAAA,EAAiBC,kBAAW,CAAA,CAAA","file":"/home/emems/.t3/worktrees/bitsnap-react/consent-analytics/dist/chunk-CO2P4FR5.js","sourcesContent":[null,"import type { Interceptor } from \"@connectrpc/connect\";\nimport { SDK_VERSION } from \"../version\";\n\nexport const CLIENT_HEADER_NAME = \"X-Bitsnap-Client\";\nexport const CLIENT_HEADER_VALUE = `bitsnap-react@${SDK_VERSION}`;\n\nexport const CLIENT_QUERY_PARAM = \"bs_client\";\n\n/**\n * Spread into the `headers` of a fetch that already triggers a CORS preflight\n * (JSON POST, Connect RPC). Never use it on a simple cross-origin GET: the\n * custom header would force a preflight that older servers and merchant\n * proxies do not allow. Use `withClientParam` there.\n */\nexport const clientHeaders: Record<string, string> = {\n [CLIENT_HEADER_NAME]: CLIENT_HEADER_VALUE,\n};\n\n/** Connect interceptor adding the client header to every RPC. */\nexport const clientHeaderInterceptor: Interceptor = (next) => (req) => {\n req.header.set(CLIENT_HEADER_NAME, CLIENT_HEADER_VALUE);\n return next(req);\n};\n\n/** Adds `bs_client=<pkg>@<ver>` to a URL, for simple GETs that must stay preflight-free. */\nexport function withClientParam(url: string): string {\n const hash = url.indexOf(\"#\");\n const base = hash === -1 ? url : url.slice(0, hash);\n const fragment = hash === -1 ? \"\" : url.slice(hash);\n const separator = base.includes(\"?\") ? (/[?&]$/.test(base) ? \"\" : \"&\") : \"?\";\n return `${base}${separator}${CLIENT_QUERY_PARAM}=${encodeURIComponent(CLIENT_HEADER_VALUE)}${fragment}`;\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var r={maxBatchEvents:50,maxBodyBytes:65536,maxPropsChars:4096,maxPropString:200,maxPropArray:50,host:253,path:512,referrerHost:253,utm:100,refCode:64,id:64,sdk:64,pageId:32,region:64,osBrowser:32,tsSkewMs:864e5},w=["storefront_events","app_events","business_events"],C=["live","test"],N=["storefront","sdk_react","script","server","dashboard"],A=["hosted","custom_domain","embed","api","panel"],P=["shop","catalog","product","cart","checkout","payment","panel","course","custom_page","order","returns","app","other"];var T={storefront_events:["storefront","sdk_react","script"],app_events:["dashboard"],business_events:["server"]},u={value_minor:"number",currency:"string"},b={page_view:{landing:"boolean"},product_list_viewed:{list_id:"string?",item_count:"number"},product_impression:{list_id:"string?",product_ids:"string[]",positions:"number[]"},product_clicked:{list_id:"string?",position:"number?"},product_view:{price_minor:"number",currency:"string",availability:"enum:in_stock|out_of_stock|preorder"},variant_selected:{},add_to_cart:{qty:"number",...u},remove_from_cart:{qty:"number",...u},cart_opened:{item_count:"number",...u},checkout_started:{item_count:"number",checkout_type:"enum:single|cart|link",...u},checkout_step_completed:{step:"enum:contact|delivery|invoice|consents"},checkout_validation_error:{field:"string",rule:"string"},coupon_applied:{coupon_id:"string"},coupon_rejected:{coupon_id:"string?",reason:"string"},delivery_method_selected:{method:"string"},payment_method_selected:{gateway:"string",method:"string"},payment_submitted:{gateway:"string",method:"string"},apple_pay_clicked:{},apple_pay_result:{outcome:"enum:success|fail|cancel"},payment_returned:{gateway:"string",method:"string?",outcome:"enum:success|fail|cancel|pending",error_code:"string?"},availability_signup:{},panel_login:{},panel_order_viewed:{},panel_download:{},return_started:{},return_submitted:{reason_code:"string",item_count:"number"},course_opened:{course_id:"string"},lesson_started:{course_id:"string",lesson_id:"string",position:"number"},lesson_completed:{course_id:"string",lesson_id:"string",position:"number"},video_progress:{course_id:"string",lesson_id:"string",milestone:"number"},test_submitted:{course_id:"string",lesson_id:"string",score_bucket:"enum:0-24|25-49|50-74|75-99|100"},lesson_rated:{course_id:"string",lesson_id:"string",rating:"number"},consent_updated:{consent_id:"string",action:"enum:accept_all|reject_all|custom|withdraw",analytics:"boolean",marketing:"boolean",preferences:"boolean",banner_version:"number"}},h={app_page_view:{route:"string",previous_route:"string?"},insight_shown:{insight_type:"string",rank:"number",category:"string"},insight_clicked:{insight_type:"string",rank:"number",category:"string"},insight_dismissed:{insight_type:"string",rank:"number",category:"string"},checklist_step_viewed:{step:"string"},checklist_step_completed:{step:"string"},gateway_connect_started:{gateway:"string",step:"string?"},gateway_connect_completed:{gateway:"string",step:"string?"},gateway_connect_failed:{gateway:"string",step:"string?",error_code:"string?"},domain_connect_started:{},domain_connect_verified:{},domain_connect_failed:{error_code:"string?"},product_created:{product_type:"string?"},product_published:{product_type:"string?"},product_editor_section_opened:{section:"string"},feature_enabled:{feature:"string"},stats_viewed:{tab:"string"},stats_filter_changed:{tab:"string",filter:"string"},report_exported:{report:"string",format:"string?"},search_performed:{result_count:"number"},error_shown:{code:"string",route:"string"},help_opened:{topic:"string?"},ai_assistant_used:{topic:"string?"},member_invited:{role:"string"}},_={gateway:"string?",method:"string?",value_minor:"number?",currency:"string?"},a={subscription_id:"string?",value_minor:"number?",currency:"string?"},E={transaction_created:_,transaction_success:_,transaction_failure:{..._,error_code:"string?"},transaction_expired:_,transaction_charge:_,subscription_created:a,subscription_paused:a,subscription_resumed:a,subscription_updated:a,subscription_deleted:a,subscription_charge_paid:a,subscription_charge_failed:{...a,error_code:"string?"},subscription_past_due:a,subscription_canceled:a,access_expires_in_3_days:{},access_expired:{},cart_recovery:{value_minor:"number?",currency:"string?"},testimonial_email_send:{},testimonial_fulfilled:{},partner_commission_earned:{partner_id:"string",commission_minor:"number",currency:"string"},checkout_session_created:{item_count:"number",checkout_type:"enum:single|cart|link",gateway:"string?",...u},order_paid:{gateway:"string",method:"string?",item_count:"number?",visitor_day:"string?",items:"line_items?",...u},refund_issued:{gateway:"string?",reason:"string?",...u},return_requested:{item_count:"number",reason_code:"string?"},automation_run_completed:{automation_id:"string",status:"string",trigger:"string?"},notification_sent:{medium:"string",template:"string?"},notification_failed:{medium:"string",template:"string?",error_code:"string?"},recovery_email_sent:{step:"number?"},recovery_link_clicked:{},api_request:{endpoint:"string",client:"string?",status:"number",latency_bucket:"enum:lt_50|lt_200|lt_1000|gte_1000",sample_rate:"number"}};var R={...b,...h,...E},O={storefront_events:Object.keys(b),app_events:Object.keys(h),business_events:Object.keys(E)},v=Object.fromEntries(w.flatMap(t=>O[t].map(n=>[n,t])));function S(t){return typeof t=="string"&&Object.hasOwn(v,t)}var q=365*24*60*60;function Y(t){let n=t.startsWith("pk_")?t.slice(3):t;return/^[A-Za-z0-9]{1,32}$/.test(n)?n:null}var $=/^([a-z][a-z0-9-]{0,39})@(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]{1,20})?)$/;function x(t){if(!t||t.length>r.sdk)return null;let n=$.exec(t);return n?{package:n[1],version:n[2]}:null}var g=r.utm;function p(t,n){if(t==null)return null;let s=t.trim();return s.length===0||s.includes("@")?null:s.slice(0,n)}function I(t){let s=t.split("/").map(e=>e.includes("@")||e.includes("%40")?":email":/^[A-Za-z0-9_-]{24,}$/.test(e)?":token":e).join("/")||"/";return(s.startsWith("/")?s:`/${s}`).slice(0,r.path)}function F(t,n){let s;try{s=new URL(t,n)}catch{return null}if(s.protocol!=="https:"&&s.protocol!=="http:")return null;let e=s.searchParams;return{host:s.hostname.toLowerCase().slice(0,r.host),path:I(s.pathname),utm_source:p(e.get("utm_source"),g),utm_medium:p(e.get("utm_medium"),g),utm_campaign:p(e.get("utm_campaign"),g),utm_content:p(e.get("utm_content"),g),utm_term:p(e.get("utm_term"),g),ref_code:p(e.get("ref"),r.refCode)}}var V=/^[A-Za-z0-9_-]{1,64}$/;function W(t){if(!t)return null;try{let n=new URL(t);return n.protocol!=="https:"&&n.protocol!=="http:"?null:n.hostname.toLowerCase().slice(0,r.referrerHost)}catch{return null}}var Z=new TextEncoder;var U=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,M=/^[A-Za-z0-9_-]{8,32}$/,L=/[^\s@]+@[^\s@]+\.[A-Za-z]{2,}\b/;function d(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function j(t,n,s){let e=t[n];return e==null?null:typeof e!="string"?`bad_${n}`:e.length>s?`too_long_${n}`:null}function z(t,n){let e=t.endsWith("?")?t.slice(0,-1):t;if(e.startsWith("enum:"))return typeof n=="string"&&e.slice(5).split("|").includes(n);switch(e){case"string":return typeof n=="string"&&n.length<=r.maxPropString;case"number":return typeof n=="number"&&Number.isFinite(n);case"boolean":return typeof n=="boolean";case"string[]":return Array.isArray(n)&&n.length<=r.maxPropArray&&n.every(o=>typeof o=="string"&&o.length<=r.maxPropString);case"number[]":return Array.isArray(n)&&n.length<=r.maxPropArray&&n.every(o=>typeof o=="number"&&Number.isFinite(o));case"line_items":return Array.isArray(n)&&n.length<=r.maxPropArray&&n.every(o=>d(o)&&typeof o.product_id=="string"&&V.test(o.product_id)&&y(o.qty)&&y(o.value_minor));default:return!1}}function y(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0}function B(t){return x(t)!==null?!1:L.test(t)}function m(t){return typeof t=="string"?B(t):Array.isArray(t)?t.some(m):d(t)?Object.values(t).some(m):!1}function D(t,n){if(!S(t))return{ok:!1,reason:"unknown_event"};let s=R[t];if(!s)return{ok:!1,reason:"unknown_event"};if(!d(n))return{ok:!1,reason:"bad_props"};let e={};for(let[o,l]of Object.entries(s)){let i=n[o];if(i==null){if(!l.endsWith("?"))return{ok:!1,reason:`props_missing_${o}`};continue}if(!z(l,i))return{ok:!1,reason:`props_bad_${o}`};if(m(i))return{ok:!1,reason:`props_pii_${o}`};e[o]=l.startsWith("line_items")&&Array.isArray(i)?i.map(c=>({product_id:c.product_id,qty:c.qty,value_minor:c.value_minor})):i}return JSON.stringify(e).length>r.maxPropsChars?{ok:!1,reason:"props_too_large"}:{ok:!0,props:e}}function X(t,n={}){let s=n.from??"browser",e=c=>({ok:!1,reason:c});if(!d(t))return e("not_object");if(typeof t.event_id!="string"||!U.test(t.event_id))return e("bad_event_id");if(!S(t.event))return e("unknown_event");let o=v[t.event];if(s==="browser"){if(o==="business_events")return e("server_only_event");if(t.event==="consent_updated")return e("consent_via_consent_endpoint")}if(typeof t.ts!="number"||!Number.isInteger(t.ts)||t.ts<=0||t.ts>4e12)return e("bad_ts");if(t.schema_version!==1)return e("bad_schema_version");if(!C.includes(t.env))return e("bad_env");if(!N.includes(t.source))return e("bad_source");if(!T[o].includes(t.source))return e("source_not_allowed_for_event");if(!A.includes(t.channel))return e("bad_channel");if(t.sdk!=null&&(typeof t.sdk!="string"||x(t.sdk)===null))return e("bad_sdk");if(t.page_id!=null&&(typeof t.page_id!="string"||!M.test(t.page_id)))return e("bad_page_id");if(t.page_type!=null&&!P.includes(t.page_type))return e("bad_page_type");if(s==="browser"){if(typeof t.host!="string"||t.host.length===0)return e("bad_host");if(typeof t.path!="string"||!t.path.startsWith("/"))return e("bad_path")}if(typeof t.path=="string"&&t.path.includes("?"))return e("path_has_query");if(typeof t.path=="string"&&t.path.includes("#"))return e("path_has_fragment");let l=[["host",r.host],["path",r.path],["referrer_host",r.referrerHost],["utm_source",r.utm],["utm_medium",r.utm],["utm_campaign",r.utm],["utm_content",r.utm],["utm_term",r.utm],["ref_code",r.refCode],["product_id",r.id],["variant_id",r.id],["order_ref",r.id]];for(let[c,k]of l){let f=j(t,c,k);if(f)return e(f)}if(t.visitor_id!=null&&(typeof t.visitor_id!="string"||!/^[A-Za-z0-9_-]{22}$/.test(t.visitor_id)))return e("bad_visitor_id");let i=D(t.event,t.props);return i.ok?{ok:!0}:e(i.reason)}import{useEffect as H,useLayoutEffect as K}from"react";function Q(t,n){(typeof window<"u"?K:H)(t,n)}export{r as a,Y as b,I as c,F as d,W as e,D as f,X as g,Q as h};
|
|
2
|
+
//# sourceMappingURL=chunk-E6QVQEGZ.mjs.map
|