@growth-labs/store 0.1.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 (117) hide show
  1. package/README.md +41 -0
  2. package/dist/api.d.ts +30 -0
  3. package/dist/api.d.ts.map +1 -0
  4. package/dist/api.js +126 -0
  5. package/dist/api.js.map +1 -0
  6. package/dist/availability.d.ts +30 -0
  7. package/dist/availability.d.ts.map +1 -0
  8. package/dist/availability.js +47 -0
  9. package/dist/availability.js.map +1 -0
  10. package/dist/cache.d.ts +34 -0
  11. package/dist/cache.d.ts.map +1 -0
  12. package/dist/cache.js +80 -0
  13. package/dist/cache.js.map +1 -0
  14. package/dist/cart-client.d.ts +54 -0
  15. package/dist/cart-client.d.ts.map +1 -0
  16. package/dist/cart-client.js +347 -0
  17. package/dist/cart-client.js.map +1 -0
  18. package/dist/checkout-client.d.ts +20 -0
  19. package/dist/checkout-client.d.ts.map +1 -0
  20. package/dist/checkout-client.js +33 -0
  21. package/dist/checkout-client.js.map +1 -0
  22. package/dist/checkout-url.d.ts +25 -0
  23. package/dist/checkout-url.d.ts.map +1 -0
  24. package/dist/checkout-url.js +36 -0
  25. package/dist/checkout-url.js.map +1 -0
  26. package/dist/client.d.ts +459 -0
  27. package/dist/client.d.ts.map +1 -0
  28. package/dist/client.js +139 -0
  29. package/dist/client.js.map +1 -0
  30. package/dist/collections.d.ts +27 -0
  31. package/dist/collections.d.ts.map +1 -0
  32. package/dist/collections.js +24 -0
  33. package/dist/collections.js.map +1 -0
  34. package/dist/health.d.ts +17 -0
  35. package/dist/health.d.ts.map +1 -0
  36. package/dist/health.js +38 -0
  37. package/dist/health.js.map +1 -0
  38. package/dist/image.d.ts +25 -0
  39. package/dist/image.d.ts.map +1 -0
  40. package/dist/image.js +43 -0
  41. package/dist/image.js.map +1 -0
  42. package/dist/index.d.ts +21 -0
  43. package/dist/index.d.ts.map +1 -0
  44. package/dist/index.js +48 -0
  45. package/dist/index.js.map +1 -0
  46. package/dist/options.d.ts +174 -0
  47. package/dist/options.d.ts.map +1 -0
  48. package/dist/options.js +59 -0
  49. package/dist/options.js.map +1 -0
  50. package/dist/product-card-variant.d.ts +13 -0
  51. package/dist/product-card-variant.d.ts.map +1 -0
  52. package/dist/product-card-variant.js +33 -0
  53. package/dist/product-card-variant.js.map +1 -0
  54. package/dist/routes/cart-bootstrap.d.ts +3 -0
  55. package/dist/routes/cart-bootstrap.d.ts.map +1 -0
  56. package/dist/routes/cart-bootstrap.js +5 -0
  57. package/dist/routes/cart-bootstrap.js.map +1 -0
  58. package/dist/routes/checkout.d.ts +4 -0
  59. package/dist/routes/checkout.d.ts.map +1 -0
  60. package/dist/routes/checkout.js +14 -0
  61. package/dist/routes/checkout.js.map +1 -0
  62. package/dist/routes/webhook.d.ts +4 -0
  63. package/dist/routes/webhook.d.ts.map +1 -0
  64. package/dist/routes/webhook.js +12 -0
  65. package/dist/routes/webhook.js.map +1 -0
  66. package/dist/state.d.ts +5 -0
  67. package/dist/state.d.ts.map +1 -0
  68. package/dist/state.js +14 -0
  69. package/dist/state.js.map +1 -0
  70. package/dist/types.d.ts +5111 -0
  71. package/dist/types.d.ts.map +1 -0
  72. package/dist/types.js +167 -0
  73. package/dist/types.js.map +1 -0
  74. package/dist/variant.d.ts +59 -0
  75. package/dist/variant.d.ts.map +1 -0
  76. package/dist/variant.js +81 -0
  77. package/dist/variant.js.map +1 -0
  78. package/dist/vite-plugin.d.ts +4 -0
  79. package/dist/vite-plugin.d.ts.map +1 -0
  80. package/dist/vite-plugin.js +24 -0
  81. package/dist/vite-plugin.js.map +1 -0
  82. package/package.json +59 -0
  83. package/src/analytics-window.d.ts +15 -0
  84. package/src/api.ts +184 -0
  85. package/src/availability.ts +65 -0
  86. package/src/cache.ts +118 -0
  87. package/src/cart-client.ts +423 -0
  88. package/src/checkout-client.ts +49 -0
  89. package/src/checkout-url.ts +52 -0
  90. package/src/client.ts +216 -0
  91. package/src/cloudflare-workers.d.ts +3 -0
  92. package/src/collections.ts +63 -0
  93. package/src/components/AddToCartButton.astro +146 -0
  94. package/src/components/CartDrawer.astro +276 -0
  95. package/src/components/CartIcon.astro +96 -0
  96. package/src/components/CollectionCard.astro +81 -0
  97. package/src/components/CurrencySelector.astro +73 -0
  98. package/src/components/Price.astro +34 -0
  99. package/src/components/ProductCard.astro +225 -0
  100. package/src/components/StoreCartPage.astro +219 -0
  101. package/src/components/StoreCollectionPage.astro +166 -0
  102. package/src/components/StoreIndexPage.astro +193 -0
  103. package/src/components/StoreProductPage.astro +296 -0
  104. package/src/components/VariantPicker.astro +190 -0
  105. package/src/health.ts +54 -0
  106. package/src/image.ts +58 -0
  107. package/src/index.ts +75 -0
  108. package/src/options.ts +74 -0
  109. package/src/product-card-variant.ts +47 -0
  110. package/src/routes/cart-bootstrap.ts +6 -0
  111. package/src/routes/checkout.ts +16 -0
  112. package/src/routes/webhook.ts +14 -0
  113. package/src/state.ts +20 -0
  114. package/src/types.ts +196 -0
  115. package/src/variant.ts +119 -0
  116. package/src/virtual.d.ts +6 -0
  117. package/src/vite-plugin.ts +27 -0
@@ -0,0 +1,65 @@
1
+ import { z } from 'zod'
2
+
3
+ export const FourthwallStockSchema = z.discriminatedUnion('type', [
4
+ z.object({ type: z.literal('UNLIMITED') }).passthrough(),
5
+ z
6
+ .object({
7
+ type: z.literal('LIMITED'),
8
+ inStock: z.number().int().nonnegative(),
9
+ })
10
+ .passthrough(),
11
+ ])
12
+
13
+ export type FourthwallAvailabilityStatus = 'available' | 'unavailable' | 'unknown'
14
+
15
+ export interface FourthwallAvailability {
16
+ status: FourthwallAvailabilityStatus
17
+ purchasable: boolean
18
+ offerAvailability: 'https://schema.org/InStock' | 'https://schema.org/OutOfStock' | null
19
+ }
20
+
21
+ interface FourthwallVariantStockInput {
22
+ id?: unknown
23
+ stock?: unknown
24
+ }
25
+
26
+ const available: FourthwallAvailability = Object.freeze({
27
+ status: 'available',
28
+ purchasable: true,
29
+ offerAvailability: 'https://schema.org/InStock',
30
+ })
31
+ const unavailable: FourthwallAvailability = Object.freeze({
32
+ status: 'unavailable',
33
+ purchasable: false,
34
+ offerAvailability: 'https://schema.org/OutOfStock',
35
+ })
36
+ const unknown: FourthwallAvailability = Object.freeze({
37
+ status: 'unknown',
38
+ purchasable: false,
39
+ offerAvailability: null,
40
+ })
41
+
42
+ export function resolveFourthwallAvailability(
43
+ variant: FourthwallVariantStockInput,
44
+ ): FourthwallAvailability {
45
+ const parsed = FourthwallStockSchema.safeParse(variant.stock)
46
+ if (!parsed.success) {
47
+ const stock =
48
+ variant.stock && typeof variant.stock === 'object'
49
+ ? (variant.stock as Record<string, unknown>)
50
+ : null
51
+ console.error({
52
+ event: 'fourthwall_contract_violation',
53
+ variantId: typeof variant.id === 'string' ? variant.id : null,
54
+ stockType: typeof stock?.type === 'string' ? stock.type : null,
55
+ issues: parsed.error.issues.map((issue) => ({
56
+ code: issue.code,
57
+ path: issue.path.join('.'),
58
+ })),
59
+ })
60
+ return unknown
61
+ }
62
+
63
+ if (parsed.data.type === 'UNLIMITED') return available
64
+ return parsed.data.inStock > 0 ? available : unavailable
65
+ }
package/src/cache.ts ADDED
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Wrapper around the Workers Cache API (`caches.default`) for Fourthwall
3
+ * Storefront API responses.
4
+ *
5
+ * Key shape: `https://i.cache/fw/{path}?{sortedQuery}` — synthetic URL so the
6
+ * regional cache keys are stable across incoming request origins.
7
+ *
8
+ * We cache JSON, not upstream `Response` bodies, because Fourthwall response
9
+ * headers aren't cache-friendly. Each entry is stored as a fresh Response
10
+ * with `Cache-Control: public, s-maxage={ttl}` so Workers Cache expires it
11
+ * server-side.
12
+ */
13
+
14
+ const CACHE_HOST = 'https://i.cache'
15
+
16
+ type CacheFetcher<T> = () => Promise<T>
17
+
18
+ /** Deterministic cache-key builder. Null/undefined query values are dropped. */
19
+ export function buildCacheKey(
20
+ pathSegment: string,
21
+ query: Record<string, string | number | undefined | null> = {},
22
+ ): string {
23
+ const normalized = pathSegment.startsWith('/') ? pathSegment : `/${pathSegment}`
24
+ const params = new URLSearchParams()
25
+ for (const key of Object.keys(query).sort()) {
26
+ const v = query[key]
27
+ if (v === undefined || v === null || v === '') continue
28
+ params.set(key, String(v))
29
+ }
30
+ const qs = params.toString()
31
+ return `${CACHE_HOST}/fw${normalized}${qs ? `?${qs}` : ''}`
32
+ }
33
+
34
+ interface CachedJsonOpts<T> {
35
+ pathSegment: string
36
+ query?: Record<string, string | number | undefined | null>
37
+ ttlSeconds: number
38
+ fetcher: CacheFetcher<T>
39
+ /** If provided, this Cache instance is used instead of `caches.default`. */
40
+ cache?: Cache
41
+ }
42
+
43
+ /**
44
+ * Read-through JSON cache. On miss, calls `fetcher`, stores the JSON under
45
+ * the computed key with s-maxage TTL, and returns the freshly-fetched value.
46
+ */
47
+ export async function cachedJson<T>(opts: CachedJsonOpts<T>): Promise<T> {
48
+ const key = buildCacheKey(opts.pathSegment, opts.query)
49
+ const cache = opts.cache ?? getDefaultCache()
50
+ if (!cache) {
51
+ return opts.fetcher()
52
+ }
53
+
54
+ const keyRequest = new Request(key)
55
+ const hit = await cache.match(keyRequest)
56
+ if (hit) {
57
+ try {
58
+ return (await hit.json()) as T
59
+ } catch {
60
+ // Corrupted entry — fall through to a live fetch.
61
+ }
62
+ }
63
+
64
+ const value = await opts.fetcher()
65
+ const body = JSON.stringify(value)
66
+ const response = new Response(body, {
67
+ status: 200,
68
+ headers: {
69
+ 'Content-Type': 'application/json',
70
+ 'Cache-Control': `public, s-maxage=${opts.ttlSeconds}`,
71
+ },
72
+ })
73
+ await cache.put(keyRequest, response)
74
+ return value
75
+ }
76
+
77
+ /** Remove one product entry across all cached currencies. Best-effort. */
78
+ export async function purgeProductCache(
79
+ slug: string,
80
+ currencies: string[] = ['USD'],
81
+ cache?: Cache,
82
+ ): Promise<void> {
83
+ const c = cache ?? getDefaultCache()
84
+ if (!c) return
85
+ await Promise.all(
86
+ currencies.map((cur) =>
87
+ c.delete(new Request(buildCacheKey(`/products/${encodeURIComponent(slug)}`, { cur }))),
88
+ ),
89
+ )
90
+ }
91
+
92
+ /** Remove one collection entry across all cached currencies. Best-effort. */
93
+ export async function purgeCollectionCache(
94
+ handle: string,
95
+ currencies: string[] = ['USD'],
96
+ cache?: Cache,
97
+ ): Promise<void> {
98
+ const c = cache ?? getDefaultCache()
99
+ if (!c) return
100
+ await Promise.all(
101
+ currencies.map((cur) =>
102
+ c.delete(
103
+ new Request(buildCacheKey(`/collections/${encodeURIComponent(handle)}/products`, { cur })),
104
+ ),
105
+ ),
106
+ )
107
+ }
108
+
109
+ interface CloudflareCacheStorage {
110
+ default: Cache
111
+ }
112
+
113
+ function getDefaultCache(): Cache | null {
114
+ const c = (globalThis as { caches?: CloudflareCacheStorage | CacheStorage }).caches
115
+ if (!c) return null
116
+ const asCf = c as Partial<CloudflareCacheStorage>
117
+ return asCf.default ?? null
118
+ }
@@ -0,0 +1,423 @@
1
+ /**
2
+ * Browser-side Fourthwall cart store.
3
+ *
4
+ * Owns `cartId` in localStorage, fetches the cart from Fourthwall's Storefront
5
+ * API directly (public token in a data attribute), and dispatches
6
+ * `fw:cart-updated` on `document` so UI components (drawer, icon badge) can
7
+ * stay in sync without framework state.
8
+ *
9
+ * Bootstrap by calling `cart.init(config)` once. Subsequent imports reuse the
10
+ * same singleton.
11
+ */
12
+
13
+ export interface CartClientConfig {
14
+ token: string
15
+ currency: string
16
+ }
17
+
18
+ export interface CartLineMeta {
19
+ productId?: string
20
+ productName?: string
21
+ sku?: string
22
+ variantName?: string
23
+ }
24
+
25
+ export interface CartSnapshotItem extends CartLineMeta {
26
+ lineId: string
27
+ variantId: string
28
+ name: string
29
+ priceValue: number
30
+ priceCurrency: string
31
+ quantity: number
32
+ imageUrl: string | null
33
+ }
34
+
35
+ export interface CartSnapshot {
36
+ cartId: string | null
37
+ items: CartSnapshotItem[]
38
+ totalCents: number
39
+ currency: string
40
+ count: number
41
+ }
42
+
43
+ const EVENT_NAME = 'fw:cart-updated'
44
+ const STORAGE_KEY = 'fw_cart_id'
45
+ const SNAPSHOT_KEY = 'fw_cart_snapshot'
46
+ const SNAPSHOT_TTL_MS = 60 * 60 * 1000 // 1h — stale-while-revalidate before forced refetch
47
+ const CART_TTL_MS = 7 * 24 * 60 * 60 * 1000 // 7d — drop persisted cart so stale items don't reappear
48
+ const API_BASE = 'https://storefront-api.fourthwall.com'
49
+
50
+ interface CartResponseItem {
51
+ id?: string
52
+ quantity: number
53
+ variant: {
54
+ id: string
55
+ name?: string
56
+ unitPrice: { value: number; currency: string }
57
+ images?: Array<{ url: string }>
58
+ }
59
+ }
60
+
61
+ interface CartResponse {
62
+ id: string
63
+ items: CartResponseItem[]
64
+ }
65
+
66
+ // Fourthwall returns `{"code":"CART_NOT_FOUND",...}` when a persisted cartId
67
+ // has expired server-side. Without this, add-to-cart against a stale cartId
68
+ // throws forever until the visitor manually clears localStorage — the
69
+ // "expired cart" bug fixed on sideprojects (#263) and missing on the other
70
+ // five sites.
71
+ class FourthwallRequestError extends Error {
72
+ readonly status: number
73
+ readonly code: string | null
74
+
75
+ constructor(status: number, body: string) {
76
+ super(`Fourthwall ${status}: ${body}`)
77
+ this.name = 'FourthwallRequestError'
78
+ this.status = status
79
+ this.code = null
80
+ try {
81
+ const parsed = JSON.parse(body) as { code?: unknown } | null
82
+ if (typeof parsed?.code === 'string') this.code = parsed.code
83
+ } catch {
84
+ // Keep unstructured provider errors on the existing failure path.
85
+ }
86
+ }
87
+ }
88
+
89
+ let state: CartSnapshot = {
90
+ cartId: null,
91
+ items: [],
92
+ totalCents: 0,
93
+ currency: 'USD',
94
+ count: 0,
95
+ }
96
+
97
+ let config: CartClientConfig | null = null
98
+
99
+ interface PersistedCartId {
100
+ id: string
101
+ expiresAt: number
102
+ }
103
+
104
+ function persistCartId(id: string | null): void {
105
+ try {
106
+ if (id) {
107
+ const payload: PersistedCartId = { id, expiresAt: Date.now() + CART_TTL_MS }
108
+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify(payload))
109
+ } else {
110
+ window.localStorage.removeItem(STORAGE_KEY)
111
+ window.localStorage.removeItem(SNAPSHOT_KEY)
112
+ }
113
+ } catch {
114
+ // localStorage blocked — cart becomes session-scoped. Acceptable.
115
+ }
116
+ }
117
+
118
+ function readCartId(): string | null {
119
+ try {
120
+ const raw = window.localStorage.getItem(STORAGE_KEY)
121
+ if (!raw) return null
122
+ // Legacy entries are a bare cartId string. Migrate them to the new
123
+ // shape with a fresh TTL so existing carts aren't dropped abruptly.
124
+ if (!raw.startsWith('{')) {
125
+ persistCartId(raw)
126
+ return raw
127
+ }
128
+ const parsed = JSON.parse(raw) as Partial<PersistedCartId>
129
+ if (
130
+ typeof parsed.id !== 'string' ||
131
+ typeof parsed.expiresAt !== 'number' ||
132
+ Date.now() > parsed.expiresAt
133
+ ) {
134
+ window.localStorage.removeItem(STORAGE_KEY)
135
+ window.localStorage.removeItem(SNAPSHOT_KEY)
136
+ return null
137
+ }
138
+ return parsed.id
139
+ } catch {
140
+ return null
141
+ }
142
+ }
143
+
144
+ function persistSnapshot(snap: CartSnapshot): void {
145
+ try {
146
+ if (snap.cartId) {
147
+ window.localStorage.setItem(SNAPSHOT_KEY, JSON.stringify({ ...snap, _ts: Date.now() }))
148
+ } else {
149
+ window.localStorage.removeItem(SNAPSHOT_KEY)
150
+ }
151
+ } catch {
152
+ /* noop */
153
+ }
154
+ }
155
+
156
+ function readCachedSnapshot(fallbackCurrency: string): CartSnapshot | null {
157
+ try {
158
+ const raw = window.localStorage.getItem(SNAPSHOT_KEY)
159
+ if (!raw) return null
160
+ const data = JSON.parse(raw) as Partial<CartSnapshot> & { _ts?: number }
161
+ if (!data._ts || Date.now() - data._ts > SNAPSHOT_TTL_MS) return null
162
+ return {
163
+ cartId: data.cartId ?? null,
164
+ items: Array.isArray(data.items) ? (data.items as CartSnapshotItem[]) : [],
165
+ totalCents: typeof data.totalCents === 'number' ? data.totalCents : 0,
166
+ currency: typeof data.currency === 'string' ? data.currency : fallbackCurrency,
167
+ count: typeof data.count === 'number' ? data.count : 0,
168
+ }
169
+ } catch {
170
+ return null
171
+ }
172
+ }
173
+
174
+ // Fourthwall's cart API doesn't return product-level metadata (productId,
175
+ // sku, etc.) on cart lines, so we persist the values supplied to cart.add()
176
+ // in a variantId → meta map and merge them onto each snapshot. Storefront
177
+ // analytics emits (store_remove_from_cart, in particular) need productId at
178
+ // remove time, after the original product page context is gone.
179
+ const META_KEY = 'fw_cart_line_meta'
180
+ const metaIndex: Record<string, CartLineMeta> = (() => {
181
+ try {
182
+ const raw = window?.localStorage?.getItem(META_KEY)
183
+ return raw ? (JSON.parse(raw) as Record<string, CartLineMeta>) : {}
184
+ } catch {
185
+ return {}
186
+ }
187
+ })()
188
+
189
+ function persistMetaIndex(): void {
190
+ try {
191
+ window.localStorage.setItem(META_KEY, JSON.stringify(metaIndex))
192
+ } catch {
193
+ /* noop */
194
+ }
195
+ }
196
+
197
+ function recordMeta(variantId: string, meta: CartLineMeta | undefined): void {
198
+ if (!meta) return
199
+ const { sku: _persistedSku, ...persistedMeta } = metaIndex[variantId] ?? {}
200
+ const { sku, ...currentMeta } = meta
201
+ const normalizedSku = sku?.trim()
202
+ metaIndex[variantId] = {
203
+ ...persistedMeta,
204
+ ...currentMeta,
205
+ ...(normalizedSku ? { sku: normalizedSku } : {}),
206
+ }
207
+ persistMetaIndex()
208
+ }
209
+
210
+ function toSnapshot(resp: CartResponse, currency: string): CartSnapshot {
211
+ const items: CartSnapshotItem[] = resp.items.map((it, idx) => ({
212
+ lineId: it.id ?? `${it.variant.id}:${idx}`,
213
+ variantId: it.variant.id,
214
+ name: it.variant.name ?? '',
215
+ priceValue: it.variant.unitPrice.value,
216
+ priceCurrency: it.variant.unitPrice.currency,
217
+ quantity: it.quantity,
218
+ imageUrl: it.variant.images?.[0]?.url ?? null,
219
+ ...(metaIndex[it.variant.id] ?? {}),
220
+ }))
221
+ const totalCents = items.reduce(
222
+ (acc, it) => acc + Math.round(it.priceValue * 100) * it.quantity,
223
+ 0,
224
+ )
225
+ const count = items.reduce((acc, it) => acc + it.quantity, 0)
226
+ return { cartId: resp.id, items, totalCents, currency, count }
227
+ }
228
+
229
+ function emit(): void {
230
+ state = { ...state }
231
+ persistSnapshot(state)
232
+ document.dispatchEvent(new CustomEvent<CartSnapshot>(EVENT_NAME, { detail: state }))
233
+ }
234
+
235
+ function resetCartState(): void {
236
+ persistCartId(null)
237
+ state = {
238
+ cartId: null,
239
+ items: [],
240
+ totalCents: 0,
241
+ currency: config?.currency ?? state.currency,
242
+ count: 0,
243
+ }
244
+ emit()
245
+ }
246
+
247
+ async function request(
248
+ path: string,
249
+ init: RequestInit & { method?: string } = {},
250
+ ): Promise<CartResponse> {
251
+ if (!config) throw new Error('cart-client: call cart.init() first')
252
+ const url = new URL(path, API_BASE)
253
+ url.searchParams.set('storefront_token', config.token)
254
+ url.searchParams.set('currency', config.currency)
255
+
256
+ const response = await fetch(url.toString(), {
257
+ ...init,
258
+ cache: 'no-store',
259
+ headers: {
260
+ 'Content-Type': 'application/json',
261
+ Accept: 'application/json',
262
+ ...(init.headers ?? {}),
263
+ },
264
+ })
265
+ if (!response.ok) {
266
+ const text = await response.text().catch(() => '')
267
+ throw new FourthwallRequestError(response.status, text)
268
+ }
269
+ return (await response.json()) as CartResponse
270
+ }
271
+
272
+ async function ensureCart(): Promise<string> {
273
+ const existing = state.cartId ?? readCartId()
274
+ if (existing) {
275
+ state.cartId = existing
276
+ return existing
277
+ }
278
+ const created = await request('/v1/carts', {
279
+ method: 'POST',
280
+ body: JSON.stringify({ items: [] }),
281
+ })
282
+ state.cartId = created.id
283
+ persistCartId(created.id)
284
+ return created.id
285
+ }
286
+
287
+ export const cart = {
288
+ init(nextConfig: CartClientConfig): void {
289
+ config = nextConfig
290
+ const cached = readCachedSnapshot(nextConfig.currency)
291
+ if (cached) {
292
+ // Hydrate count/items from localStorage so the badge paints
293
+ // instantly without a network round-trip on every page.
294
+ state = cached
295
+ emit()
296
+ return
297
+ }
298
+
299
+ // No fresh snapshot, but the cartId in localStorage may still point
300
+ // at a server-side cart with items. Paint an empty badge first, then
301
+ // kick off a background refresh so the badge corrects itself instead
302
+ // of silently showing 0 until the user opens the drawer.
303
+ state = {
304
+ cartId: readCartId(),
305
+ items: [],
306
+ totalCents: 0,
307
+ currency: nextConfig.currency,
308
+ count: 0,
309
+ }
310
+ emit()
311
+ if (state.cartId) {
312
+ this.refresh().catch(() => {
313
+ // refresh() already resets state on a non-recoverable error.
314
+ })
315
+ }
316
+ },
317
+
318
+ getSnapshot(): CartSnapshot {
319
+ return { ...state }
320
+ },
321
+
322
+ on(handler: (snap: CartSnapshot) => void): () => void {
323
+ const listener = (e: Event) => {
324
+ const detail = (e as CustomEvent<CartSnapshot>).detail
325
+ handler(detail ?? state)
326
+ }
327
+ document.addEventListener(EVENT_NAME, listener)
328
+ // Emit the current state right away so subscribers render immediately.
329
+ handler(state)
330
+ return () => document.removeEventListener(EVENT_NAME, listener)
331
+ },
332
+
333
+ async refresh(): Promise<CartSnapshot> {
334
+ if (!state.cartId && !readCartId()) {
335
+ emit()
336
+ return state
337
+ }
338
+ const id = state.cartId ?? readCartId()
339
+ if (!id) {
340
+ emit()
341
+ return state
342
+ }
343
+ try {
344
+ const resp = await request(`/v1/carts/${encodeURIComponent(id)}`)
345
+ state = toSnapshot(resp, config?.currency ?? state.currency)
346
+ emit()
347
+ return state
348
+ } catch (err) {
349
+ // Cart may have expired server-side. Clear and reset.
350
+ resetCartState()
351
+ throw err
352
+ }
353
+ },
354
+
355
+ async add(variantId: string, quantity = 1, meta?: CartLineMeta): Promise<CartSnapshot> {
356
+ const id = await ensureCart()
357
+ recordMeta(variantId, meta)
358
+ const addToCart = (cartId: string) =>
359
+ request(`/v1/carts/${encodeURIComponent(cartId)}/add`, {
360
+ method: 'POST',
361
+ body: JSON.stringify({ items: [{ variantId, quantity }] }),
362
+ })
363
+ let resp: CartResponse
364
+ try {
365
+ resp = await addToCart(id)
366
+ } catch (error) {
367
+ if (!(error instanceof FourthwallRequestError) || error.code !== 'CART_NOT_FOUND') {
368
+ throw error
369
+ }
370
+ // The persisted cart expired server-side between page load and this
371
+ // add — recover by minting a fresh cart and retrying once, instead
372
+ // of surfacing a broken "add to cart" button to the visitor.
373
+ resetCartState()
374
+ const replacementId = await ensureCart()
375
+ resp = await addToCart(replacementId)
376
+ }
377
+ state = toSnapshot(resp, config?.currency ?? state.currency)
378
+ emit()
379
+ return state
380
+ },
381
+
382
+ async update(lineId: string, quantity: number): Promise<CartSnapshot> {
383
+ const id = await ensureCart()
384
+ const item = state.items.find((it) => it.lineId === lineId)
385
+ if (!item) return state
386
+ const resp = await request(`/v1/carts/${encodeURIComponent(id)}/change`, {
387
+ method: 'POST',
388
+ body: JSON.stringify({ items: [{ variantId: item.variantId, quantity }] }),
389
+ })
390
+ state = toSnapshot(resp, config?.currency ?? state.currency)
391
+ emit()
392
+ return state
393
+ },
394
+
395
+ async remove(lineId: string): Promise<CartSnapshot> {
396
+ const id = await ensureCart()
397
+ const item = state.items.find((it) => it.lineId === lineId)
398
+ if (!item) return state
399
+ const resp = await request(`/v1/carts/${encodeURIComponent(id)}/remove`, {
400
+ method: 'POST',
401
+ body: JSON.stringify({ items: [{ variantId: item.variantId, quantity: item.quantity }] }),
402
+ })
403
+ state = toSnapshot(resp, config?.currency ?? state.currency)
404
+ emit()
405
+ return state
406
+ },
407
+
408
+ clear(): void {
409
+ resetCartState()
410
+ },
411
+ }
412
+
413
+ export type CartClient = typeof cart
414
+
415
+ declare global {
416
+ interface Window {
417
+ fwCart?: typeof cart
418
+ }
419
+ }
420
+
421
+ if (typeof window !== 'undefined') {
422
+ window.fwCart = cart
423
+ }
@@ -0,0 +1,49 @@
1
+ import { type CartSnapshot, cart } from './cart-client.js'
2
+
3
+ export interface InitiateCheckoutOptions {
4
+ /** Where the checkout call originated — feeds `store_checkout_initiated.source`. */
5
+ source: 'cart-page' | 'cart-drawer' | 'buy-now'
6
+ checkoutPath: string
7
+ /** Called with the redirect target before navigation, e.g. to disable a button. */
8
+ onRedirect?: (url: string) => void
9
+ }
10
+
11
+ /**
12
+ * Shared checkout call used by the cart page, the cart drawer, AND the
13
+ * buy-now button — the drawer used to be the only call site that fired
14
+ * `store_checkout_initiated`, silently undercounting checkout starts from
15
+ * the standalone cart page.
16
+ */
17
+ export async function initiateCheckout(
18
+ snapshot: CartSnapshot,
19
+ opts: InitiateCheckoutOptions,
20
+ ): Promise<void> {
21
+ if (!snapshot.cartId) return
22
+
23
+ const res = await fetch(opts.checkoutPath, {
24
+ method: 'POST',
25
+ headers: { 'Content-Type': 'application/json' },
26
+ body: JSON.stringify({ cartId: snapshot.cartId }),
27
+ })
28
+ if (!res.ok) throw new Error(`checkout ${res.status}`)
29
+ const { url } = (await res.json()) as { url: string }
30
+
31
+ window.glAnalytics?.track('store_checkout_initiated', {
32
+ cartTotal: snapshot.totalCents / 100,
33
+ currency: snapshot.currency,
34
+ itemCount: snapshot.count,
35
+ source: opts.source,
36
+ })
37
+
38
+ opts.onRedirect?.(url)
39
+ window.location.href = url
40
+ }
41
+
42
+ /** Add a variant to the cart and go straight to checkout in one action. */
43
+ export async function buyNow(
44
+ variantId: string,
45
+ opts: InitiateCheckoutOptions & { quantity?: number },
46
+ ): Promise<void> {
47
+ const snapshot = await cart.add(variantId, opts.quantity ?? 1)
48
+ await initiateCheckout(snapshot, opts)
49
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Build the Fourthwall-hosted checkout redirect URL.
3
+ *
4
+ * Docs:
5
+ * https://docs.fourthwall.com/storefront/checkout
6
+ * https://docs.fourthwall.com/shop-apis/cart-checkout-endpoint
7
+ */
8
+
9
+ export interface CheckoutUrlInput {
10
+ /** Fully-qualified `https://<something>.fourthwall.com` or custom checkout subdomain, without trailing slash. */
11
+ checkoutDomain: string
12
+ cartId: string
13
+ currency: string
14
+ coupon?: string | null
15
+ utm?: {
16
+ source?: string
17
+ medium?: string
18
+ campaign?: string
19
+ term?: string
20
+ content?: string
21
+ }
22
+ /** Origin marker recognized by Fourthwall analytics — the site's `cartOrigin` option. */
23
+ cartOrigin: string
24
+ }
25
+
26
+ export function buildCheckoutUrl(input: CheckoutUrlInput): string {
27
+ if (!input.checkoutDomain) {
28
+ throw new Error('checkoutDomain is required')
29
+ }
30
+ if (!input.cartId) {
31
+ throw new Error('cartId is required')
32
+ }
33
+
34
+ const domain = input.checkoutDomain.replace(/^https?:\/\//, '').replace(/\/+$/, '')
35
+ const url = new URL(`https://${domain}/checkout/`)
36
+
37
+ url.searchParams.set('cartId', input.cartId)
38
+ url.searchParams.set('cartCurrency', input.currency)
39
+ if (input.coupon) {
40
+ url.searchParams.set('coupon', input.coupon)
41
+ }
42
+ url.searchParams.set('cart_origin', input.cartOrigin)
43
+
44
+ const utm = input.utm ?? {}
45
+ if (utm.source) url.searchParams.set('utm_source', utm.source)
46
+ if (utm.medium) url.searchParams.set('utm_medium', utm.medium)
47
+ if (utm.campaign) url.searchParams.set('utm_campaign', utm.campaign)
48
+ if (utm.term) url.searchParams.set('utm_term', utm.term)
49
+ if (utm.content) url.searchParams.set('utm_content', utm.content)
50
+
51
+ return url.toString()
52
+ }