@growth-labs/store 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/api.js +1 -1
  3. package/dist/api.js.map +1 -1
  4. package/dist/cart-client.d.ts.map +1 -1
  5. package/dist/cart-client.js +2 -0
  6. package/dist/cart-client.js.map +1 -1
  7. package/dist/checkout-client.d.ts +2 -0
  8. package/dist/checkout-client.d.ts.map +1 -1
  9. package/dist/checkout-client.js +7 -1
  10. package/dist/checkout-client.js.map +1 -1
  11. package/dist/coupon.d.ts +30 -0
  12. package/dist/coupon.d.ts.map +1 -0
  13. package/dist/coupon.js +79 -0
  14. package/dist/coupon.js.map +1 -0
  15. package/dist/featured.d.ts +36 -0
  16. package/dist/featured.d.ts.map +1 -0
  17. package/dist/featured.js +127 -0
  18. package/dist/featured.js.map +1 -0
  19. package/dist/holiday-banner.d.ts +3 -0
  20. package/dist/holiday-banner.d.ts.map +1 -0
  21. package/dist/holiday-banner.js +3 -0
  22. package/dist/holiday-banner.js.map +1 -0
  23. package/dist/index.d.ts +5 -0
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +3 -0
  26. package/dist/index.js.map +1 -1
  27. package/dist/orders.d.ts +2 -0
  28. package/dist/orders.d.ts.map +1 -1
  29. package/dist/orders.js +27 -10
  30. package/dist/orders.js.map +1 -1
  31. package/dist/types.d.ts +9 -9
  32. package/dist/types.d.ts.map +1 -1
  33. package/dist/types.js +8 -7
  34. package/dist/types.js.map +1 -1
  35. package/package.json +1 -1
  36. package/src/api.ts +1 -1
  37. package/src/cart-client.ts +3 -0
  38. package/src/checkout-client.ts +10 -1
  39. package/src/components/AddToCartButton.astro +3 -0
  40. package/src/components/CartDrawer.astro +9 -0
  41. package/src/components/HolidayShippingBanner.astro +21 -0
  42. package/src/components/StoreCartPage.astro +6 -0
  43. package/src/components/StoreCollectionPage.astro +4 -0
  44. package/src/components/StoreIndexPage.astro +96 -4
  45. package/src/components/StoreProductPage.astro +3 -0
  46. package/src/coupon.ts +91 -0
  47. package/src/featured.ts +162 -0
  48. package/src/holiday-banner.ts +3 -0
  49. package/src/index.ts +20 -0
  50. package/src/orders.ts +28 -9
  51. package/src/types.ts +8 -7
@@ -0,0 +1,162 @@
1
+ import { FourthwallStockSchema } from './availability.js'
2
+ import type { FwProduct, FwVariant } from './types.js'
3
+ import { isStoreVariantAvailable, normalizeStoreVariantSku } from './variant.js'
4
+
5
+ /** SKU of the DTU $99 Official Signed Script that gets prominent placement whenever in stock. */
6
+ export const DTU_SIGNED_SCRIPT_SKU = 'Y52G-AZX0000'
7
+
8
+ const SIGNED_PATTERN = /\bsigned\b/i
9
+
10
+ export interface SelectFeaturedProductsOptions {
11
+ /** Maximum number of cards in the featured grid (excluding a dedicated spotlight item). Default 6. */
12
+ limit?: number
13
+ /** SKUs eligible for top spotlight placement when in stock. Defaults to `[DTU_SIGNED_SCRIPT_SKU]`. */
14
+ spotlightSkus?: readonly string[]
15
+ }
16
+
17
+ export interface FeaturedProductsSelection {
18
+ /** Prominent spotlight product (e.g. DTU Official Signed Script) when in stock, else null. */
19
+ spotlight: FwProduct | null
20
+ /** The specific in-stock variant matching the spotlight SKU, if `spotlight` is set. */
21
+ spotlightVariant: FwVariant | null
22
+ /** Remaining ranked featured products for the grid (excluding `spotlight`). */
23
+ items: FwProduct[]
24
+ /** All selected featured products in rank order (`[spotlight, ...items]` or `items`). */
25
+ all: FwProduct[]
26
+ }
27
+
28
+ export function isInStockLimitedVariant(variant: FwVariant): boolean {
29
+ const parsed = FourthwallStockSchema.safeParse(variant.stock)
30
+ return parsed.success && parsed.data.type === 'LIMITED' && parsed.data.inStock > 0
31
+ }
32
+
33
+ export function isSignedProduct(product: FwProduct): boolean {
34
+ if (SIGNED_PATTERN.test(product.name) || SIGNED_PATTERN.test(product.slug)) {
35
+ return true
36
+ }
37
+ return product.variants.some((variant) =>
38
+ typeof variant.name === 'string' ? SIGNED_PATTERN.test(variant.name) : false,
39
+ )
40
+ }
41
+
42
+ function buildSpotlightSkuSet(skus: readonly string[] | undefined): Set<string> {
43
+ const source = skus ?? [DTU_SIGNED_SCRIPT_SKU]
44
+ const set = new Set<string>()
45
+ for (const sku of source) {
46
+ const normalized = normalizeStoreVariantSku(sku)?.toUpperCase()
47
+ if (normalized) set.add(normalized)
48
+ }
49
+ return set
50
+ }
51
+
52
+ export function findInStockSpotlightVariant(
53
+ product: FwProduct,
54
+ spotlightSkus: readonly string[] = [DTU_SIGNED_SCRIPT_SKU],
55
+ ): FwVariant | null {
56
+ const skuSet = buildSpotlightSkuSet(spotlightSkus)
57
+ if (skuSet.size === 0) return null
58
+ for (const variant of product.variants) {
59
+ const sku = normalizeStoreVariantSku(variant.sku)?.toUpperCase()
60
+ if (sku && skuSet.has(sku) && isStoreVariantAvailable(variant)) {
61
+ return variant
62
+ }
63
+ }
64
+ return null
65
+ }
66
+
67
+ function productHasInStockVariant(product: FwProduct): boolean {
68
+ return product.variants.some((variant) => isStoreVariantAvailable(variant))
69
+ }
70
+
71
+ function productHasInStockLimitedVariant(product: FwProduct): boolean {
72
+ return product.variants.some((variant) => isInStockLimitedVariant(variant))
73
+ }
74
+
75
+ function featuredTier(product: FwProduct, skuSet: ReadonlySet<string>): number {
76
+ const isSpotlight = product.variants.some((variant) => {
77
+ const sku = normalizeStoreVariantSku(variant.sku)?.toUpperCase()
78
+ return Boolean(sku && skuSet.has(sku) && isStoreVariantAvailable(variant))
79
+ })
80
+ if (isSpotlight) return 0
81
+
82
+ const limited = productHasInStockLimitedVariant(product)
83
+ const signed = isSignedProduct(product)
84
+ if (limited && signed) return 1
85
+ if (limited) return 2
86
+ if (signed) return 3
87
+ return 4
88
+ }
89
+
90
+ function createdAtMs(product: FwProduct): number {
91
+ if (!product.createdAt) return 0
92
+ const parsed = Date.parse(product.createdAt)
93
+ return Number.isNaN(parsed) ? 0 : parsed
94
+ }
95
+
96
+ /**
97
+ * Ranks in-stock products for the Featured / Bestsellers section:
98
+ * 0. In-stock spotlight SKU (DTU $99 Official Signed Script, Y52G-AZX0000)
99
+ * 1. In-stock LIMITED + signed products
100
+ * 2. In-stock LIMITED products
101
+ * 3. In-stock signed products
102
+ * 4. Other in-stock products
103
+ *
104
+ * Out-of-stock products are excluded. Ties break by newest `createdAt`, then
105
+ * original input order.
106
+ */
107
+ export function rankFeaturedProducts(
108
+ products: readonly FwProduct[],
109
+ options: Pick<SelectFeaturedProductsOptions, 'spotlightSkus'> = {},
110
+ ): FwProduct[] {
111
+ const skuSet = buildSpotlightSkuSet(options.spotlightSkus)
112
+ return products
113
+ .map((product, index) => ({
114
+ product,
115
+ index,
116
+ inStock: productHasInStockVariant(product),
117
+ }))
118
+ .filter((entry) => entry.inStock)
119
+ .map((entry) => ({
120
+ ...entry,
121
+ tier: featuredTier(entry.product, skuSet),
122
+ created: createdAtMs(entry.product),
123
+ }))
124
+ .sort((a, b) => {
125
+ if (a.tier !== b.tier) return a.tier - b.tier
126
+ if (a.created !== b.created) return b.created - a.created
127
+ return a.index - b.index
128
+ })
129
+ .map((entry) => entry.product)
130
+ }
131
+
132
+ export function selectFeaturedProducts(
133
+ products: readonly FwProduct[],
134
+ options: SelectFeaturedProductsOptions = {},
135
+ ): FeaturedProductsSelection {
136
+ const limit = options.limit ?? 6
137
+ const spotlightSkus = options.spotlightSkus ?? [DTU_SIGNED_SCRIPT_SKU]
138
+ const ranked = rankFeaturedProducts(products, { spotlightSkus })
139
+ if (ranked.length === 0) {
140
+ return { spotlight: null, spotlightVariant: null, items: [], all: [] }
141
+ }
142
+
143
+ const first = ranked[0]!
144
+ const spotlightVariant = findInStockSpotlightVariant(first, spotlightSkus)
145
+ if (spotlightVariant) {
146
+ const items = ranked.slice(1, 1 + Math.max(0, limit))
147
+ return {
148
+ spotlight: first,
149
+ spotlightVariant,
150
+ items,
151
+ all: [first, ...items],
152
+ }
153
+ }
154
+
155
+ const items = ranked.slice(0, Math.max(0, limit))
156
+ return {
157
+ spotlight: null,
158
+ spotlightVariant: null,
159
+ items,
160
+ all: items,
161
+ }
162
+ }
@@ -0,0 +1,3 @@
1
+ /** Exact holiday shipping cutoff copy displayed across storefront pages. */
2
+ export const HOLIDAY_SHIPPING_BANNER_TEXT =
3
+ 'Holiday delivery (US): order by Wed, Dec 9 for standard shipping or Tue, Dec 15 for expedited shipping.'
package/src/index.ts CHANGED
@@ -79,8 +79,28 @@ export {
79
79
  resolveProductKind,
80
80
  resolveShopCollections,
81
81
  } from './collections.js'
82
+ export type { CouponStorage } from './coupon.js'
83
+ export {
84
+ captureSessionCoupon,
85
+ getSessionCoupon,
86
+ normalizeCouponCode,
87
+ SESSION_COUPON_STORAGE_KEY,
88
+ } from './coupon.js'
89
+ export type {
90
+ FeaturedProductsSelection,
91
+ SelectFeaturedProductsOptions,
92
+ } from './featured.js'
93
+ export {
94
+ DTU_SIGNED_SCRIPT_SKU,
95
+ findInStockSpotlightVariant,
96
+ isInStockLimitedVariant,
97
+ isSignedProduct,
98
+ rankFeaturedProducts,
99
+ selectFeaturedProducts,
100
+ } from './featured.js'
82
101
  export type { StoreHealthCheckOptions } from './health.js'
83
102
  export { createStoreHealthCheck } from './health.js'
103
+ export { HOLIDAY_SHIPPING_BANNER_TEXT } from './holiday-banner.js'
84
104
  export { hasProductImages, optimizeFwImage } from './image.js'
85
105
  export type { ResolvedStoreOptions, StoreOptions } from './options.js'
86
106
  export { storeOptionsSchema } from './options.js'
package/src/orders.ts CHANGED
@@ -63,13 +63,25 @@ function buildItemsJson(event: FwOrderPlacedEvent): string {
63
63
  )
64
64
  }
65
65
 
66
+ const EMAIL_SHAPED_PATTERN = /[^\s@]+@[^\s@]+\.[^\s@]+/
67
+
68
+ function isEmailShaped(value: string): boolean {
69
+ return EMAIL_SHAPED_PATTERN.test(value)
70
+ }
71
+
72
+ function sanitizeAnalyticsBlob(value: string | null | undefined): string {
73
+ if (!value) return ''
74
+ return isEmailShaped(value) ? '' : value
75
+ }
76
+
66
77
  function cartOriginFor(event: FwOrderPlacedEvent, fallback: string): string {
67
78
  const metadata = event.data.metadata
68
79
  const fromMetadata =
69
80
  metadata && typeof metadata.cart_origin === 'string'
70
81
  ? (metadata.cart_origin as string)
71
82
  : undefined
72
- return fromMetadata ?? fallback
83
+ if (fromMetadata && !isEmailShaped(fromMetadata)) return fromMetadata
84
+ return sanitizeAnalyticsBlob(fallback)
73
85
  }
74
86
 
75
87
  /**
@@ -77,6 +89,8 @@ function cartOriginFor(event: FwOrderPlacedEvent, fallback: string): string {
77
89
  * (packages don't import each other — PLATFORM_PATTERNS.md — so this
78
90
  * replicates the slot mapping from `buildWAEDataPoint`/`buildStorefrontWAEParams`
79
91
  * rather than calling into that package).
92
+ *
93
+ * Privacy: never emit customer email or any email-shaped value to WAE.
80
94
  */
81
95
  export function buildStoreOrderWAEDataPoint(
82
96
  options: OrderTelemetryOptions,
@@ -89,26 +103,25 @@ export function buildStoreOrderWAEDataPoint(
89
103
  rawPayloadHash,
90
104
  itemCount: orderItemCount(event),
91
105
  }
92
- if (event.data.email) labelExtras.customerEmail = event.data.email
93
106
 
94
107
  return {
95
108
  blobs: [
96
109
  'store_order_placed', // blob1 eventName
97
- options.siteId, // blob2 siteId
110
+ sanitizeAnalyticsBlob(options.siteId), // blob2 siteId
98
111
  '', // blob3 visitorId
99
112
  '', // blob4 sessionId
100
113
  '', // blob5 pageUrl
101
114
  '', // blob6 pagePath
102
115
  '', // blob7 referrer
103
- utm.utm_source ?? '', // blob8 utmSource
104
- utm.utm_medium ?? '', // blob9 utmMedium
105
- utm.utm_campaign ?? '', // blob10 utmCampaign
116
+ sanitizeAnalyticsBlob(utm.utm_source), // blob8 utmSource
117
+ sanitizeAnalyticsBlob(utm.utm_medium), // blob9 utmMedium
118
+ sanitizeAnalyticsBlob(utm.utm_campaign), // blob10 utmCampaign
106
119
  '', // blob11 derivedSource
107
120
  '', // blob12 country
108
121
  '', // blob13 deviceType
109
122
  '', // blob14 browserName
110
123
  '', // blob15 osName
111
- event.data.id, // blob16 contentSlug = orderId
124
+ sanitizeAnalyticsBlob(event.data.id), // blob16 contentSlug = orderId
112
125
  'order', // blob17 contentType
113
126
  'storefront', // blob18 eventCategory
114
127
  JSON.stringify(labelExtras), // blob19 eventLabel
@@ -164,6 +177,7 @@ export function createD1OrderHandler(options: OrderTelemetryOptions): OrderPlace
164
177
 
165
178
  const rawPayloadHash = await sha256Hex(JSON.stringify(event))
166
179
 
180
+ let duplicateOrder = false
167
181
  const db = env[options.d1Binding] as D1LikeDatabase | undefined
168
182
  if (!db) {
169
183
  console.error('store.order_telemetry.d1_binding_missing', {
@@ -172,7 +186,7 @@ export function createD1OrderHandler(options: OrderTelemetryOptions): OrderPlace
172
186
  })
173
187
  } else {
174
188
  try {
175
- await db
189
+ const result = (await db
176
190
  .prepare(
177
191
  `INSERT OR IGNORE INTO gl_store_orders
178
192
  (id, shop_id, site_id, amount, currency, items_json, cart_origin, utm_source, utm_medium, utm_campaign, utm_term, utm_content, raw_payload_hash, received_at)
@@ -194,7 +208,10 @@ export function createD1OrderHandler(options: OrderTelemetryOptions): OrderPlace
194
208
  rawPayloadHash,
195
209
  Date.now(),
196
210
  )
197
- .run()
211
+ .run()) as { meta?: { changes?: number } } | undefined
212
+ if (result?.meta?.changes === 0) {
213
+ duplicateOrder = true
214
+ }
198
215
  } catch (error) {
199
216
  console.error('store.order_telemetry.d1_write_failed', {
200
217
  orderId: event.data.id,
@@ -203,6 +220,8 @@ export function createD1OrderHandler(options: OrderTelemetryOptions): OrderPlace
203
220
  }
204
221
  }
205
222
 
223
+ if (duplicateOrder) return
224
+
206
225
  const wae = env[options.waeBinding] as WaeLikeBinding | undefined
207
226
  if (!wae?.writeDataPoint) {
208
227
  console.error('store.order_telemetry.wae_binding_missing', {
package/src/types.ts CHANGED
@@ -167,15 +167,16 @@ export const FwOrderPlacedEventSchema = z
167
167
  offers: z.array(FwOrderOfferSchema).default([]),
168
168
  trackingParams: z
169
169
  .object({
170
- utm_source: z.string().optional(),
171
- utm_medium: z.string().optional(),
172
- utm_campaign: z.string().optional(),
173
- utm_content: z.string().optional(),
174
- utm_term: z.string().optional(),
175
- fbc: z.string().optional(),
176
- fbp: z.string().optional(),
170
+ utm_source: z.string().nullable().optional(),
171
+ utm_medium: z.string().nullable().optional(),
172
+ utm_campaign: z.string().nullable().optional(),
173
+ utm_content: z.string().nullable().optional(),
174
+ utm_term: z.string().nullable().optional(),
175
+ fbc: z.string().nullable().optional(),
176
+ fbp: z.string().nullable().optional(),
177
177
  })
178
178
  .passthrough()
179
+ .nullable()
179
180
  .optional(),
180
181
  })
181
182
  .passthrough(),