@aranova/tracking-react 0.27.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/index.ts
@@ -39,6 +49,7 @@ __export(src_exports, {
39
49
  createTrackingClientContext: () => createTrackingClientContext,
40
50
  createTrackingEventCreatePayload: () => createTrackingEventCreatePayload,
41
51
  createTrackingSessionUpsertPayload: () => createTrackingSessionUpsertPayload,
52
+ currencySchema: () => currencySchema,
42
53
  fetchServices: () => fetchServices,
43
54
  formatDateInTz: () => formatDateInTz,
44
55
  formatMoney: () => formatMoney,
@@ -126,7 +137,7 @@ function normalizeEmail(raw) {
126
137
  return EMAIL_SHAPE.test(cleaned) ? cleaned : null;
127
138
  }
128
139
  function stashUserData(data, country) {
129
- const email = normalizeEmail(data.email);
140
+ const email3 = normalizeEmail(data.email);
130
141
  let phoneNumber = null;
131
142
  if (typeof data.phone === "string" && data.phone.length > 0) {
132
143
  try {
@@ -136,7 +147,7 @@ function stashUserData(data, country) {
136
147
  }
137
148
  }
138
149
  stash = {
139
- email: email ?? stash.email,
150
+ email: email3 ?? stash.email,
140
151
  phoneNumber: phoneNumber ?? stash.phoneNumber
141
152
  };
142
153
  }
@@ -145,11 +156,11 @@ function clearStashedUserData() {
145
156
  }
146
157
  function applyUserDataForConversion(explicit, country) {
147
158
  if (typeof window === "undefined" || typeof window.gtag !== "function") return false;
148
- let email = stash.email;
159
+ let email3 = stash.email;
149
160
  let phoneNumber = stash.phoneNumber;
150
161
  if (explicit) {
151
162
  const normalizedEmail = normalizeEmail(explicit.email);
152
- if (normalizedEmail) email = normalizedEmail;
163
+ if (normalizedEmail) email3 = normalizedEmail;
153
164
  if (typeof explicit.phone === "string" && explicit.phone.length > 0) {
154
165
  try {
155
166
  phoneNumber = toE164(explicit.phone, country) ?? phoneNumber;
@@ -157,10 +168,10 @@ function applyUserDataForConversion(explicit, country) {
157
168
  }
158
169
  }
159
170
  }
160
- if (email === null && phoneNumber === null) return false;
171
+ if (email3 === null && phoneNumber === null) return false;
161
172
  try {
162
173
  window.gtag("set", "user_data", {
163
- ...email !== null ? { email } : {},
174
+ ...email3 !== null ? { email: email3 } : {},
164
175
  ...phoneNumber !== null ? { phone_number: phoneNumber } : {}
165
176
  });
166
177
  return true;
@@ -516,10 +527,10 @@ function readStoredRecord() {
516
527
  return null;
517
528
  }
518
529
  }
519
- function writeRecord(record) {
520
- memoryRecord = record;
530
+ function writeRecord(record3) {
531
+ memoryRecord = record3;
521
532
  try {
522
- window.localStorage.setItem(LANDING_STORAGE_KEY, JSON.stringify(record));
533
+ window.localStorage.setItem(LANDING_STORAGE_KEY, JSON.stringify(record3));
523
534
  } catch {
524
535
  }
525
536
  }
@@ -541,9 +552,9 @@ function getOrCaptureLandingParams(sessionId, url) {
541
552
  if (memoryRecord && memoryRecord.session_id === sessionId) {
542
553
  return memoryRecord.params;
543
554
  }
544
- const record = { session_id: sessionId, params: captureFromUrl(url) };
545
- writeRecord(record);
546
- return record.params;
555
+ const record3 = { session_id: sessionId, params: captureFromUrl(url) };
556
+ writeRecord(record3);
557
+ return record3.params;
547
558
  }
548
559
  function buildLandingPayloadFields(sessionId, override) {
549
560
  const params = override ?? (typeof window === "undefined" ? null : getOrCaptureLandingParams(sessionId));
@@ -920,9 +931,9 @@ function automaticThresholdMet(goal, eventType, metadata) {
920
931
  }
921
932
 
922
933
  // ../tracking-core/src/resources/intl/date.ts
923
- function formatDateInTz(iso, timeZone, opts, locale) {
924
- const date = new Date(iso);
925
- if (Number.isNaN(date.getTime())) return iso;
934
+ function formatDateInTz(iso3, timeZone, opts, locale) {
935
+ const date = new Date(iso3);
936
+ if (Number.isNaN(date.getTime())) return iso3;
926
937
  return new Intl.DateTimeFormat(locale, {
927
938
  year: "numeric",
928
939
  month: "short",
@@ -1334,29 +1345,6 @@ function getTrackingConfigRuntime(ref, fetchImpl) {
1334
1345
  return runtime;
1335
1346
  }
1336
1347
 
1337
- // ../tracking-core/src/session.ts
1338
- var SESSION_IDLE_MS = 30 * 60 * 1e3;
1339
-
1340
- // ../tracking-core/src/events/page-view.ts
1341
- var import_zod = require("zod");
1342
- var pageViewMetadataSchema = import_zod.z.object({
1343
- page: import_zod.z.object({
1344
- title: import_zod.z.string().nullable(),
1345
- path: import_zod.z.string(),
1346
- search: import_zod.z.string(),
1347
- hash: import_zod.z.string()
1348
- }).strict(),
1349
- referrer: import_zod.z.string().nullable(),
1350
- // `.nullable().optional()` — absent (undefined) OR explicit null OR a
1351
- // real viewport object. Mirrors Pydantic's `_Viewport | None = None`
1352
- // on the backend side so the drift test stays clean.
1353
- viewport: import_zod.z.object({
1354
- w: import_zod.z.number(),
1355
- h: import_zod.z.number()
1356
- }).strict().nullable().optional()
1357
- }).strict();
1358
- var pageViewConfigSchema = import_zod.z.object({}).strict();
1359
-
1360
1348
  // ../tracking-core/src/ingest.ts
1361
1349
  var API_KEY_HEADER = "X-Aranova-Api-Key";
1362
1350
  var SDK_VERSION_HEADER = "X-Aranova-Sdk-Version";
@@ -1364,187 +1352,6 @@ var SDK_PACKAGE_HEADER = "X-Aranova-Sdk-Package";
1364
1352
  var SDK_SURFACE_HEADER = "X-Aranova-Sdk-Surface";
1365
1353
  var SDK_ENVIRONMENT_HEADER = "X-Aranova-Sdk-Environment";
1366
1354
 
1367
- // ../tracking-core/src/events/cta-click.ts
1368
- var import_zod2 = require("zod");
1369
- var ctaClickMetadataSchema = import_zod2.z.object({
1370
- cta_name: import_zod2.z.string(),
1371
- page: import_zod2.z.object({
1372
- path: import_zod2.z.string()
1373
- }).strict(),
1374
- section: import_zod2.z.string().nullable().optional(),
1375
- destination_url: import_zod2.z.string().nullable().optional(),
1376
- // Set by auto-capture (and available to manual callers): the link target
1377
- // and a short element descriptor (tag#id) for tying clicks to specific UI.
1378
- href: import_zod2.z.string().nullable().optional(),
1379
- element: import_zod2.z.string().nullable().optional()
1380
- }).strict();
1381
- var ctaClickConfigSchema = import_zod2.z.object({
1382
- autoCapture: import_zod2.z.object({
1383
- selector: import_zod2.z.string().optional()
1384
- }).strict().optional()
1385
- }).strict();
1386
-
1387
- // ../tracking-core/src/events/sdk-heartbeat.ts
1388
- var import_zod3 = require("zod");
1389
- var sdkHeartbeatTriggersSchema = import_zod3.z.object({
1390
- automatic: import_zod3.z.array(import_zod3.z.string()),
1391
- manual: import_zod3.z.array(import_zod3.z.string())
1392
- }).strict();
1393
- var sdkHeartbeatMetadataSchema = import_zod3.z.object({
1394
- sdk_version: import_zod3.z.string(),
1395
- package_name: import_zod3.z.string().nullable(),
1396
- surface: import_zod3.z.enum(["next", "react", "script"]),
1397
- triggers: sdkHeartbeatTriggersSchema,
1398
- trigger_config: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.record(import_zod3.z.string(), import_zod3.z.unknown())).nullable().optional(),
1399
- configured_gtag_ids: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.string()).nullable().optional(),
1400
- // Site whose config object the SDK resolves; null on a legacy business ref.
1401
- config_site_id: import_zod3.z.string().uuid().nullable().optional()
1402
- }).strict();
1403
- var sdkHeartbeatConfigSchema = import_zod3.z.object({}).strict();
1404
-
1405
- // ../tracking-core/src/events/form-start.ts
1406
- var import_zod4 = require("zod");
1407
- var formStartMetadataSchema = import_zod4.z.object({
1408
- form: import_zod4.z.object({
1409
- id: import_zod4.z.string(),
1410
- action: import_zod4.z.string().nullable()
1411
- }).strict(),
1412
- page: import_zod4.z.object({
1413
- path: import_zod4.z.string()
1414
- }).strict()
1415
- }).strict();
1416
- var formStartConfigSchema = import_zod4.z.object({
1417
- selector: import_zod4.z.string().optional()
1418
- }).strict();
1419
-
1420
- // ../tracking-core/src/events/form-submit.ts
1421
- var import_zod5 = require("zod");
1422
- var jsonValueSchema = import_zod5.z.lazy(
1423
- () => import_zod5.z.union([
1424
- import_zod5.z.string(),
1425
- import_zod5.z.number().finite(),
1426
- import_zod5.z.boolean(),
1427
- import_zod5.z.null(),
1428
- import_zod5.z.array(jsonValueSchema),
1429
- import_zod5.z.record(jsonValueSchema)
1430
- ])
1431
- );
1432
- var formSubmitMetadataSchema = import_zod5.z.object({
1433
- form: import_zod5.z.object({
1434
- id: import_zod5.z.string(),
1435
- action: import_zod5.z.string().nullable(),
1436
- fields: import_zod5.z.array(
1437
- import_zod5.z.object({
1438
- name: import_zod5.z.string(),
1439
- type: import_zod5.z.string(),
1440
- label: import_zod5.z.string().nullable(),
1441
- value: jsonValueSchema
1442
- }).strict()
1443
- ).optional()
1444
- }).strict(),
1445
- page: import_zod5.z.object({
1446
- path: import_zod5.z.string()
1447
- }).strict()
1448
- }).strict();
1449
- var formSubmitConfigSchema = import_zod5.z.object({}).strict();
1450
-
1451
- // ../tracking-core/src/events/multi-page-session.ts
1452
- var import_zod6 = require("zod");
1453
- var multiPageSessionMetadataSchema = import_zod6.z.object({
1454
- page_count: import_zod6.z.number().int().min(2),
1455
- page: import_zod6.z.object({
1456
- path: import_zod6.z.string()
1457
- }).strict()
1458
- }).strict();
1459
- var multiPageSessionConfigSchema = import_zod6.z.object({
1460
- pageThreshold: import_zod6.z.number().int().min(2)
1461
- }).strict();
1462
-
1463
- // ../tracking-core/src/events/page-exit.ts
1464
- var import_zod7 = require("zod");
1465
- var pageExitMetadataSchema = import_zod7.z.object({
1466
- dwell_ms: import_zod7.z.number().int().min(0),
1467
- // null = left without any scroll signal; floor is 0 so a valid 0% is never
1468
- // rejected (a single bad field 422s the whole keepalive beacon batch).
1469
- max_scroll_percent: import_zod7.z.number().int().min(0).max(100).nullable(),
1470
- // The gating baseline: the fraction of the page visible at load with
1471
- // zero scrolling — or, for pages that grew after the post-paint snapshot
1472
- // (skeleton/streaming renders), the first-scroll position that
1473
- // established it. null = page had no scrollable range, or the segment
1474
- // ended before the snapshot. `.optional()` is load-bearing: SDK builds
1475
- // predating this field keep POSTing page_exit without the key —
1476
- // requiring it would 422 whole keepalive beacon batches.
1477
- scroll_baseline_percent: import_zod7.z.number().int().min(0).max(100).nullable().optional(),
1478
- page: import_zod7.z.object({
1479
- path: import_zod7.z.string()
1480
- }).strict()
1481
- }).strict();
1482
- var pageExitConfigSchema = import_zod7.z.object({}).strict();
1483
-
1484
- // ../tracking-core/src/events/phone-click.ts
1485
- var import_zod8 = require("zod");
1486
- var phoneClickMetadataSchema = import_zod8.z.object({
1487
- phone_number: import_zod8.z.string(),
1488
- page: import_zod8.z.object({
1489
- path: import_zod8.z.string()
1490
- }).strict(),
1491
- section: import_zod8.z.string().nullable().optional()
1492
- }).strict();
1493
- var phoneClickConfigSchema = import_zod8.z.object({
1494
- autoCapture: import_zod8.z.object({
1495
- selector: import_zod8.z.string().optional()
1496
- }).strict().optional()
1497
- }).strict();
1498
-
1499
- // ../tracking-core/src/events/scroll-depth.ts
1500
- var import_zod9 = require("zod");
1501
- var scrollDepthMetadataSchema = import_zod9.z.object({
1502
- depth_percent: import_zod9.z.number().int().min(1).max(100),
1503
- page: import_zod9.z.object({
1504
- path: import_zod9.z.string()
1505
- }).strict()
1506
- }).strict();
1507
- var scrollDepthConfigSchema = import_zod9.z.object({
1508
- thresholds: import_zod9.z.array(import_zod9.z.number().int().min(1).max(100)).min(1)
1509
- }).strict();
1510
-
1511
- // ../tracking-core/src/events/specific-page-visit.ts
1512
- var import_zod10 = require("zod");
1513
- var PAGE_IDENTITY_MAX_LENGTH = 64;
1514
- var PAGE_IDENTITY_PATTERN = /^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/;
1515
- var pageIdentitySchema = import_zod10.z.string().max(PAGE_IDENTITY_MAX_LENGTH).regex(PAGE_IDENTITY_PATTERN, {
1516
- message: "page identity must be lowercase snake_case, start with a letter, and contain at most 64 characters"
1517
- });
1518
- var specificPageNameSchema = pageIdentitySchema;
1519
- var specificPageVisitMetadataSchema = import_zod10.z.object({
1520
- page_name: specificPageNameSchema,
1521
- page: import_zod10.z.object({
1522
- path: import_zod10.z.string()
1523
- }).strict()
1524
- }).strict();
1525
- var specificPageVisitConfigSchema = import_zod10.z.object({
1526
- pages: import_zod10.z.array(
1527
- import_zod10.z.object({
1528
- name: specificPageNameSchema,
1529
- pathPattern: import_zod10.z.custom((value) => value instanceof RegExp, {
1530
- message: "pathPattern must be a RegExp"
1531
- })
1532
- }).strict()
1533
- ).min(1)
1534
- }).strict();
1535
-
1536
- // ../tracking-core/src/events/time-on-site.ts
1537
- var import_zod11 = require("zod");
1538
- var timeOnSiteMetadataSchema = import_zod11.z.object({
1539
- duration_ms: import_zod11.z.number().int().nonnegative(),
1540
- page: import_zod11.z.object({
1541
- path: import_zod11.z.string()
1542
- }).strict()
1543
- }).strict();
1544
- var timeOnSiteConfigSchema = import_zod11.z.object({
1545
- thresholdSeconds: import_zod11.z.number().int().positive()
1546
- }).strict();
1547
-
1548
1355
  // ../tracking-core/src/events/semantics.ts
1549
1356
  var EVENT_SEMANTICS = {
1550
1357
  page_view: {
@@ -1618,82 +1425,6 @@ function getEventSemantics(eventName) {
1618
1425
  return eventName in EVENT_SEMANTICS ? EVENT_SEMANTICS[eventName] : null;
1619
1426
  }
1620
1427
 
1621
- // ../tracking-core/src/events/registry.ts
1622
- var EVENT_REGISTRY = {
1623
- // --- automatic triggers ---
1624
- page_view: {
1625
- kind: "automatic",
1626
- semantics: EVENT_SEMANTICS.page_view,
1627
- metadataSchema: pageViewMetadataSchema,
1628
- configSchema: pageViewConfigSchema
1629
- },
1630
- time_on_site: {
1631
- kind: "automatic",
1632
- semantics: EVENT_SEMANTICS.time_on_site,
1633
- metadataSchema: timeOnSiteMetadataSchema,
1634
- configSchema: timeOnSiteConfigSchema
1635
- },
1636
- specific_page_visit: {
1637
- kind: "automatic",
1638
- semantics: EVENT_SEMANTICS.specific_page_visit,
1639
- metadataSchema: specificPageVisitMetadataSchema,
1640
- configSchema: specificPageVisitConfigSchema
1641
- },
1642
- scroll_depth: {
1643
- kind: "automatic",
1644
- semantics: EVENT_SEMANTICS.scroll_depth,
1645
- metadataSchema: scrollDepthMetadataSchema,
1646
- configSchema: scrollDepthConfigSchema
1647
- },
1648
- multi_page_session: {
1649
- kind: "automatic",
1650
- semantics: EVENT_SEMANTICS.multi_page_session,
1651
- metadataSchema: multiPageSessionMetadataSchema,
1652
- configSchema: multiPageSessionConfigSchema
1653
- },
1654
- form_start: {
1655
- kind: "automatic",
1656
- semantics: EVENT_SEMANTICS.form_start,
1657
- metadataSchema: formStartMetadataSchema,
1658
- configSchema: formStartConfigSchema
1659
- },
1660
- // --- SDK-internal automatic (not consumer-configurable) ---
1661
- sdk_heartbeat: {
1662
- kind: "automatic",
1663
- semantics: EVENT_SEMANTICS.sdk_heartbeat,
1664
- metadataSchema: sdkHeartbeatMetadataSchema,
1665
- configSchema: sdkHeartbeatConfigSchema
1666
- },
1667
- page_exit: {
1668
- kind: "automatic",
1669
- semantics: EVENT_SEMANTICS.page_exit,
1670
- metadataSchema: pageExitMetadataSchema,
1671
- configSchema: pageExitConfigSchema
1672
- },
1673
- // --- manual triggers ---
1674
- form_submit: {
1675
- kind: "manual",
1676
- semantics: EVENT_SEMANTICS.form_submit,
1677
- metadataSchema: formSubmitMetadataSchema,
1678
- configSchema: formSubmitConfigSchema
1679
- },
1680
- phone_click: {
1681
- kind: "manual",
1682
- semantics: EVENT_SEMANTICS.phone_click,
1683
- metadataSchema: phoneClickMetadataSchema,
1684
- configSchema: phoneClickConfigSchema
1685
- },
1686
- cta_click: {
1687
- kind: "manual",
1688
- semantics: EVENT_SEMANTICS.cta_click,
1689
- metadataSchema: ctaClickMetadataSchema,
1690
- configSchema: ctaClickConfigSchema
1691
- }
1692
- };
1693
- var ALL_AUTOMATIC_EVENT_NAMES = Object.entries(EVENT_REGISTRY).filter(([, def]) => def.kind === "automatic").map(([name]) => name);
1694
- var ALL_MANUAL_EVENT_NAMES = Object.entries(EVENT_REGISTRY).filter(([, def]) => def.kind === "manual").map(([name]) => name);
1695
- var ALL_LEAD_EVENT_NAMES = Object.entries(EVENT_REGISTRY).filter(([, def]) => def.semantics.outcomeRole === "lead").map(([name]) => name);
1696
-
1697
1428
  // ../tracking-core/src/resources/http/errors.ts
1698
1429
  var AranovaApiError = class extends Error {
1699
1430
  constructor(message, options) {
@@ -1731,9 +1462,9 @@ async function apiRequest(config, method, path, body, extraHeaders) {
1731
1462
  try {
1732
1463
  const parsed = await response.json();
1733
1464
  if (parsed && typeof parsed === "object") {
1734
- const record = parsed;
1735
- if (typeof record.detail === "string") detail = record.detail;
1736
- if (typeof record.code === "string") code = record.code;
1465
+ const record3 = parsed;
1466
+ if (typeof record3.detail === "string") detail = record3.detail;
1467
+ if (typeof record3.code === "string") code = record3.code;
1737
1468
  }
1738
1469
  } catch {
1739
1470
  }
@@ -1782,7 +1513,7 @@ function fireRecordedConversions(firing, input, recorded, sale, currency) {
1782
1513
  }
1783
1514
  function createSalesClient(config) {
1784
1515
  if (config.firing) registerCapability("conversion_goals_manual");
1785
- async function record(input) {
1516
+ async function record3(input) {
1786
1517
  const currency = input.currency ?? config.defaultCurrency;
1787
1518
  if (!currency) {
1788
1519
  throw new Error(
@@ -1808,9 +1539,9 @@ function createSalesClient(config) {
1808
1539
  return sale;
1809
1540
  }
1810
1541
  return {
1811
- record,
1542
+ record: record3,
1812
1543
  // recordSale is the intent-revealing alias — same behavior, clearer call site.
1813
- recordSale: record,
1544
+ recordSale: record3,
1814
1545
  trackConversion(key, options) {
1815
1546
  if (config.firing && "fireConversion" in config.firing) {
1816
1547
  if (options?.userData && getConsentState() !== "denied") stashUserData(options.userData);
@@ -1929,115 +1660,264 @@ function createSalesClient(config) {
1929
1660
  }
1930
1661
 
1931
1662
  // ../tracking-core/src/resources/sales/schema.ts
1932
- var import_zod12 = require("zod");
1933
- var SUPPORTED_CURRENCIES = ["USD", "CAD"];
1934
- var TRACKING_ENVIRONMENTS = ["production", "development"];
1935
- var currencySchema = import_zod12.z.enum(SUPPORTED_CURRENCIES);
1936
- var centsSchema = import_zod12.z.number().int().nonnegative();
1937
- var quantitySchema = import_zod12.z.string().regex(/^\d+(\.\d{1,3})?$/);
1938
- var metadataSchema = import_zod12.z.record(import_zod12.z.unknown());
1939
- var saleItemSchema = import_zod12.z.object({
1940
- external_item_id: import_zod12.z.string().nullable().optional(),
1941
- name: import_zod12.z.string().nullable().optional(),
1942
- category: import_zod12.z.string().nullable().optional(),
1943
- quantity: quantitySchema,
1944
- unit_price_cents: centsSchema,
1945
- // Non-negativity validated on the wire — same contract as the other cents
1946
- // fields — and backstopped by the DB CHECK.
1947
- unit_cost_cents: centsSchema.nullable().optional()
1948
- }).strict();
1949
- var saleServiceSchema = import_zod12.z.object({
1950
- service: import_zod12.z.string(),
1951
- amount_cents: centsSchema
1952
- }).strict();
1953
- var customerNameSchema = import_zod12.z.string().max(200);
1954
- var customerPhoneSchema = import_zod12.z.string().max(64);
1955
- var customerEmailSchema = import_zod12.z.string().max(320).email();
1663
+ var z2 = __toESM(require("zod/mini"));
1664
+
1665
+ // ../tracking-core/src/resources/sales/generated/zod.gen.ts
1666
+ var z = __toESM(require("zod/mini"));
1667
+ var zErrorCode = z.enum([
1668
+ "missing_credentials",
1669
+ "invalid_api_key",
1670
+ "not_authenticated",
1671
+ "wrong_key_type",
1672
+ "origin_missing",
1673
+ "origin_not_allowed",
1674
+ "capability_denied",
1675
+ "session_required",
1676
+ "operator_only",
1677
+ "cross_tenant",
1678
+ "business_id_required",
1679
+ "bad_request",
1680
+ "not_found",
1681
+ "conflict",
1682
+ "incompatible_payload",
1683
+ "repeat_confirmation_required",
1684
+ "idempotency_conflict",
1685
+ "validation_error",
1686
+ "unknown_service",
1687
+ "invalid_sale_properties",
1688
+ "invalid_cursor",
1689
+ "rate_limited",
1690
+ "internal_error"
1691
+ ]);
1692
+ var zSaleItemEntitySchema = z.object({
1693
+ category: z.nullable(z.string()),
1694
+ external_item_id: z.nullable(z.string()),
1695
+ id: z.uuid(),
1696
+ name: z.nullable(z.string()),
1697
+ quantity: z.string().check(z.regex(/^(?!^[-+.]*$)[+-]?0*\d*\.?\d*$/)),
1698
+ unit_cost_cents: z.nullable(z.int()),
1699
+ unit_price_cents: z.int()
1700
+ });
1701
+ var zSaleItemInputSchema = z.strictObject({
1702
+ category: z.nullish(z.string()),
1703
+ external_item_id: z.nullish(z.string()),
1704
+ name: z.nullish(z.string()),
1705
+ quantity: z.string().check(z.regex(/^\d+(\.\d{1,3})?$/)),
1706
+ unit_cost_cents: z.nullish(z.int().check(z.gte(0))),
1707
+ unit_price_cents: z.int().check(z.gte(0))
1708
+ });
1709
+ var zSaleServiceEntitySchema = z.object({
1710
+ amount_cents: z.int(),
1711
+ id: z.uuid(),
1712
+ mapped: z.nullable(z.boolean()),
1713
+ service_id: z.uuid(),
1714
+ service_key: z.string(),
1715
+ service_label: z.string()
1716
+ });
1717
+ var zSaleServiceInputSchema = z.strictObject({
1718
+ amount_cents: z.int().check(z.gte(0)),
1719
+ service: z.string()
1720
+ });
1721
+ var zSmsAutomationState = z.enum([
1722
+ "needs_check",
1723
+ "failed",
1724
+ "undelivered",
1725
+ "blocked_opted_out",
1726
+ "withheld",
1727
+ "queued",
1728
+ "sent",
1729
+ "delivered",
1730
+ "eligible",
1731
+ "not_applicable"
1732
+ ]);
1733
+ var zSmsWithheldReason = z.enum([
1734
+ "automation_disabled",
1735
+ "sms_disabled",
1736
+ "no_phone",
1737
+ "no_consent",
1738
+ "no_customer_identity",
1739
+ "missing_customer_name",
1740
+ "placeholder_customer_name",
1741
+ "opted_out",
1742
+ "already_messaged",
1743
+ "sender_not_ready",
1744
+ "missing_review_url",
1745
+ "no_handler",
1746
+ "dispatch_already_recorded"
1747
+ ]);
1748
+ var zSaleSmsStatusSchema = z.object({
1749
+ can_send_now: z._default(z.boolean(), false),
1750
+ last_message_at: z.nullable(z.iso.datetime({ offset: true })),
1751
+ reason_detail: z.nullable(z.string()),
1752
+ state: zSmsAutomationState,
1753
+ suppressed_by_other_sale: z._default(z.boolean(), false),
1754
+ withheld_reason: z.nullable(zSmsWithheldReason)
1755
+ });
1756
+ var zSupportedCurrency = z.enum(["USD", "CAD"]);
1757
+ var zTrackingEnvironment = z.enum(["production", "development"]);
1758
+ var zSaleCreateSchema = z.strictObject({
1759
+ amount_total_cents: z.nullish(z.int().check(z.gte(0))),
1760
+ currency: zSupportedCurrency,
1761
+ customer_email: z.nullish(z.email().check(z.maxLength(320))),
1762
+ customer_name: z.nullish(z.string().check(z.maxLength(200))),
1763
+ customer_phone: z.nullish(z.string().check(z.maxLength(64))),
1764
+ description: z.nullish(z.string()),
1765
+ environment: z._default(z.optional(zTrackingEnvironment), "production"),
1766
+ external_id: z.nullish(z.string()),
1767
+ items: z.optional(z.array(zSaleItemInputSchema)),
1768
+ metadata: z.nullish(z.record(z.string(), z.unknown())),
1769
+ occurred_at: z.iso.datetime({ offset: true }),
1770
+ service: z.nullish(z.string()),
1771
+ services: z.nullish(z.array(zSaleServiceInputSchema)),
1772
+ sms_consent: z.nullish(z.boolean())
1773
+ });
1774
+ var zValidationError = z.object({
1775
+ ctx: z.optional(z.record(z.string(), z.unknown())),
1776
+ input: z.optional(z.unknown()),
1777
+ loc: z.array(z.union([z.string(), z.int()])),
1778
+ msg: z.string(),
1779
+ type: z.string()
1780
+ });
1781
+ var zHttpValidationError = z.object({
1782
+ detail: z.optional(z.array(zValidationError))
1783
+ });
1784
+ var zValidationErrorItem = z.object({
1785
+ loc: z.array(z.union([z.string(), z.int()])),
1786
+ msg: z.string(),
1787
+ type: z.string()
1788
+ });
1789
+ var zApiErrorSchema = z.object({
1790
+ code: zErrorCode,
1791
+ context: z._default(z.nullish(z.record(z.string(), z.unknown())), null),
1792
+ detail: z.string(),
1793
+ errors: z._default(z.nullish(z.array(zValidationErrorItem)), null),
1794
+ request_id: z._default(z.nullish(z.string()), null)
1795
+ });
1796
+ var zWritebackEmailSource = z.enum(["NONE", "SALE", "CUSTOMER", "HARVESTED"]);
1797
+ var zWritebackEnrichmentStatus = z.enum(["NONE", "MATCHED", "AMBIGUOUS"]);
1798
+ var zWritebackSaleUploadCounts = z.object({
1799
+ failed: z._default(z.int(), 0),
1800
+ pending: z._default(z.int(), 0),
1801
+ skipped: z._default(z.int(), 0),
1802
+ submitted: z._default(z.int(), 0),
1803
+ total: z._default(z.int(), 0),
1804
+ uploaded: z._default(z.int(), 0)
1805
+ });
1806
+ var zSaleWritebackStatusSchema = z.object({
1807
+ blocked_reason: z.nullable(z.string()),
1808
+ can_dispatch: z._default(z.boolean(), false),
1809
+ email_source: z.nullable(zWritebackEmailSource),
1810
+ enrichment_status: z.nullable(zWritebackEnrichmentStatus),
1811
+ gclid_attached: z._default(z.boolean(), false),
1812
+ identifiers_sent: z.nullable(z.string()),
1813
+ mapped_service_ids: z.array(z.uuid()),
1814
+ matched_submit_count: z.nullable(z.int()),
1815
+ needs_force: z._default(z.boolean(), false),
1816
+ rollup: z.enum([
1817
+ "failed",
1818
+ "skipped",
1819
+ "pending",
1820
+ "submitted",
1821
+ "uploaded",
1822
+ "not_uploaded",
1823
+ "out_of_window",
1824
+ "blocked"
1825
+ ]),
1826
+ stale: z._default(z.boolean(), false),
1827
+ uncovered_service_ids: z.array(z.uuid()),
1828
+ uploads: zWritebackSaleUploadCounts
1829
+ });
1830
+ var zSaleEntitySchema = z.object({
1831
+ amount_total_cents: z.int(),
1832
+ business_id: z.uuid(),
1833
+ business_name: z.nullable(z.string()),
1834
+ created_at: z.iso.datetime({ offset: true }),
1835
+ currency: z.string(),
1836
+ customer_email: z.nullable(z.string()),
1837
+ customer_name: z.nullable(z.string()),
1838
+ customer_name_placeholder_confirmed: z._default(z.boolean(), false),
1839
+ customer_name_placeholder_confirmed_at: z.nullable(z.iso.datetime({ offset: true })),
1840
+ customer_phone: z.nullable(z.string()),
1841
+ description: z.nullable(z.string()),
1842
+ environment: zTrackingEnvironment,
1843
+ external_id: z.nullable(z.string()),
1844
+ id: z.uuid(),
1845
+ items: z.array(zSaleItemEntitySchema),
1846
+ metadata: z.nullable(z.record(z.string(), z.unknown())),
1847
+ occurred_at: z.iso.datetime({ offset: true }),
1848
+ service_id: z.nullable(z.uuid()),
1849
+ service_key: z.nullable(z.string()),
1850
+ service_label: z.nullable(z.string()),
1851
+ services: z.array(zSaleServiceEntitySchema),
1852
+ sms_automation: z.nullable(zSaleSmsStatusSchema),
1853
+ sms_consent: z._default(z.boolean(), false),
1854
+ sms_consent_granted_at: z.nullable(z.iso.datetime({ offset: true })),
1855
+ updated_at: z.iso.datetime({ offset: true }),
1856
+ writeback: z.nullable(zSaleWritebackStatusSchema)
1857
+ });
1858
+
1859
+ // ../tracking-core/src/resources/sales/schema.ts
1860
+ var saleItemSchema = zSaleItemInputSchema;
1861
+ var saleServiceSchema = zSaleServiceInputSchema;
1862
+ var currencySchema = zSupportedCurrency;
1863
+ var SUPPORTED_CURRENCIES = currencySchema.options;
1864
+ var centsSchema = z2.int().check(z2.gte(0));
1865
+ var metadataSchema = z2.record(z2.string(), z2.unknown());
1866
+ var customerNameSchema = z2.string().check(z2.maxLength(200));
1867
+ var customerPhoneSchema = z2.string().check(z2.maxLength(64));
1868
+ var customerEmailSchema = z2.email().check(z2.maxLength(320));
1869
+ function addIssue(ctx, path, message) {
1870
+ ctx.issues.push({ code: "custom", input: ctx.value, path, message });
1871
+ }
1956
1872
  function refineServiceXor(val, ctx, { requireAmount }) {
1957
1873
  if (val.services != null) {
1958
1874
  if (val.service != null) {
1959
- ctx.addIssue({
1960
- code: import_zod12.z.ZodIssueCode.custom,
1961
- message: "pass either `service` or `services`, not both",
1962
- path: ["services"]
1963
- });
1875
+ addIssue(ctx, ["services"], "pass either `service` or `services`, not both");
1964
1876
  }
1965
1877
  if (val.services.length === 0) {
1966
- ctx.addIssue({
1967
- code: import_zod12.z.ZodIssueCode.custom,
1968
- message: "`services` must not be empty",
1969
- path: ["services"]
1970
- });
1878
+ addIssue(ctx, ["services"], "`services` must not be empty");
1971
1879
  }
1972
1880
  const keys = val.services.map((s) => s.service);
1973
1881
  if (new Set(keys).size !== keys.length) {
1974
- ctx.addIssue({
1975
- code: import_zod12.z.ZodIssueCode.custom,
1976
- message: "`services` must not list the same service more than once",
1977
- path: ["services"]
1978
- });
1882
+ addIssue(ctx, ["services"], "`services` must not list the same service more than once");
1979
1883
  }
1980
1884
  if (val.amount_total_cents != null) {
1981
1885
  const sum = val.services.reduce((acc, s) => acc + s.amount_cents, 0);
1982
1886
  if (val.amount_total_cents !== sum) {
1983
- ctx.addIssue({
1984
- code: import_zod12.z.ZodIssueCode.custom,
1985
- message: "amount_total_cents must equal the sum of the services amounts (omit it to derive it automatically)",
1986
- path: ["amount_total_cents"]
1987
- });
1887
+ addIssue(
1888
+ ctx,
1889
+ ["amount_total_cents"],
1890
+ "amount_total_cents must equal the sum of the services amounts (omit it to derive it automatically)"
1891
+ );
1988
1892
  }
1989
1893
  }
1990
1894
  } else if (requireAmount && val.amount_total_cents == null) {
1991
- ctx.addIssue({
1992
- code: import_zod12.z.ZodIssueCode.custom,
1993
- message: "amount_total_cents is required unless `services` is provided",
1994
- path: ["amount_total_cents"]
1995
- });
1895
+ addIssue(
1896
+ ctx,
1897
+ ["amount_total_cents"],
1898
+ "amount_total_cents is required unless `services` is provided"
1899
+ );
1996
1900
  }
1997
1901
  }
1998
- var saleCreateSchema = import_zod12.z.object({
1999
- external_id: import_zod12.z.string().nullable().optional(),
2000
- description: import_zod12.z.string().nullable().optional(),
2001
- service: import_zod12.z.string().nullable().optional(),
2002
- services: import_zod12.z.array(saleServiceSchema).nullable().optional(),
2003
- currency: currencySchema,
2004
- // Optional only because the plural `services` form derives it from the sum
2005
- // (see refineServiceXor); the singular/serviceless path still requires it.
2006
- amount_total_cents: centsSchema.nullable().optional(),
2007
- occurred_at: import_zod12.z.string().datetime(),
2008
- environment: import_zod12.z.enum(TRACKING_ENVIRONMENTS).default("production"),
2009
- items: import_zod12.z.array(saleItemSchema).default([]),
2010
- metadata: metadataSchema.nullable().optional(),
2011
- customer_name: customerNameSchema.nullable().optional(),
2012
- customer_phone: customerPhoneSchema.nullable().optional(),
2013
- customer_email: customerEmailSchema.nullable().optional(),
2014
- // CASL consent attestation: the customer agreed to receive SMS. Recorded
2015
- // with a timestamp server-side; every SMS send path gates on it.
2016
- //
2017
- // Tri-state: omit it (or send null) to let the server apply the business's
2018
- // configured default-opt-in policy, honouring a returning customer's
2019
- // remembered preference. Send an explicit boolean to assert consent state
2020
- // yourself — `false` records a deliberate opt-out.
2021
- sms_consent: import_zod12.z.boolean().nullable().optional()
2022
- }).strict().superRefine((val, ctx) => refineServiceXor(val, ctx, { requireAmount: true }));
2023
- var saleUpdateSchema = import_zod12.z.object({
2024
- description: import_zod12.z.string().nullable().optional(),
2025
- service: import_zod12.z.string().nullable().optional(),
2026
- services: import_zod12.z.array(saleServiceSchema).nullable().optional(),
2027
- currency: currencySchema.optional(),
2028
- amount_total_cents: centsSchema.optional(),
2029
- occurred_at: import_zod12.z.string().datetime().optional(),
2030
- items: import_zod12.z.array(saleItemSchema).optional(),
2031
- metadata: metadataSchema.nullable().optional(),
2032
- customer_name: customerNameSchema.nullable().optional(),
1902
+ var saleCreateSchema = z2.extend(zSaleCreateSchema, { items: z2._default(z2.array(saleItemSchema), []) }).check((ctx) => refineServiceXor(ctx.value, ctx, { requireAmount: true }));
1903
+ var saleUpdateSchema = z2.strictObject({
1904
+ description: z2.nullish(z2.string()),
1905
+ service: z2.nullish(z2.string()),
1906
+ services: z2.nullish(z2.array(saleServiceSchema)),
1907
+ currency: z2.optional(currencySchema),
1908
+ amount_total_cents: z2.optional(centsSchema),
1909
+ occurred_at: z2.optional(z2.iso.datetime()),
1910
+ items: z2.optional(z2.array(saleItemSchema)),
1911
+ metadata: z2.nullish(metadataSchema),
1912
+ customer_name: z2.nullish(customerNameSchema),
2033
1913
  // Re-attest when changing a filler-looking name; the server clears the
2034
1914
  // prior attestation whenever `customer_name` changes.
2035
- customer_name_placeholder_confirmed: import_zod12.z.boolean().optional(),
2036
- customer_phone: customerPhoneSchema.nullable().optional(),
2037
- customer_email: customerEmailSchema.nullable().optional(),
1915
+ customer_name_placeholder_confirmed: z2.optional(z2.boolean()),
1916
+ customer_phone: z2.nullish(customerPhoneSchema),
1917
+ customer_email: z2.nullish(customerEmailSchema),
2038
1918
  // NOT NULL server-side: omit to leave unchanged (explicit null is rejected).
2039
- sms_consent: import_zod12.z.boolean().optional()
2040
- }).strict().superRefine((val, ctx) => refineServiceXor(val, ctx, { requireAmount: false }));
1919
+ sms_consent: z2.optional(z2.boolean())
1920
+ }).check((ctx) => refineServiceXor(ctx.value, ctx, { requireAmount: false }));
2041
1921
  var TRACKING_RANGES = ["24h", "7d", "30d"];
2042
1922
  var NAMED_RANGES = [
2043
1923
  "today",
@@ -2086,6 +1966,7 @@ var import_client2 = require("@aranova/tracking-react/client");
2086
1966
  createTrackingClientContext,
2087
1967
  createTrackingEventCreatePayload,
2088
1968
  createTrackingSessionUpsertPayload,
1969
+ currencySchema,
2089
1970
  fetchServices,
2090
1971
  formatDateInTz,
2091
1972
  formatMoney,