@putiikkipalvelu/storefront-sdk 0.1.0 → 0.2.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.d.cts CHANGED
@@ -1,270 +1,2382 @@
1
1
  /**
2
- * Store configuration types for the Storefront API
2
+ * Store Configuration Types
3
+ *
4
+ * Types for the store config endpoint response.
3
5
  */
6
+ /**
7
+ * Complete store configuration returned by the API.
8
+ * Includes business info, SEO settings, payments, campaigns, and feature flags.
9
+ */
10
+ interface StoreConfig {
11
+ store: StoreInfo;
12
+ seo: StoreSeo;
13
+ payments: PaymentConfig;
14
+ campaigns: Campaign[];
15
+ features: FeatureFlags;
16
+ }
4
17
  /**
5
18
  * Store business information
6
19
  */
7
20
  interface StoreInfo {
21
+ /** Unique store identifier */
8
22
  id: string;
23
+ /** Store display name */
9
24
  name: string;
25
+ /** Contact email */
10
26
  email: string;
27
+ /** Contact phone number */
11
28
  phone: string;
29
+ /** Street address */
12
30
  address: string;
31
+ /** City */
13
32
  city: string;
33
+ /** Postal/ZIP code */
14
34
  postalCode: string;
35
+ /** Country code (e.g., "FI") */
15
36
  country: string;
37
+ /** Currency code (e.g., "EUR") */
16
38
  currency: string;
39
+ /** Currency symbol (e.g., "€") */
17
40
  currencySymbol: string;
41
+ /** Default VAT rate as percentage (e.g., 25.5) */
18
42
  defaultVatRate: number;
43
+ /** Business/VAT ID */
19
44
  businessId: string;
45
+ /** Store logo URL */
20
46
  logoUrl: string | null;
21
47
  }
22
48
  /**
23
49
  * Store SEO and social media configuration
24
50
  */
25
51
  interface StoreSeo {
52
+ /** SEO meta title */
26
53
  seoTitle: string | null;
54
+ /** SEO meta description */
27
55
  seoDescription: string | null;
56
+ /** Store domain URL */
28
57
  domain: string | null;
58
+ /** Open Graph image URL */
29
59
  openGraphImageUrl: string | null;
60
+ /** Twitter card image URL */
30
61
  twitterImageUrl: string | null;
62
+ /** Instagram profile URL */
31
63
  instagramUrl: string | null;
64
+ /** Facebook page URL */
32
65
  facebookUrl: string | null;
66
+ /** Price range indicator (e.g., "€€") */
33
67
  priceRange: string | null;
68
+ /** Business type description */
34
69
  businessType: string | null;
35
70
  }
36
71
  /**
37
72
  * Payment configuration
38
73
  */
39
74
  interface PaymentConfig {
75
+ /** Available payment methods (e.g., ["stripe", "paytrail"]) */
40
76
  methods: string[];
77
+ /** Default VAT rate */
41
78
  defaultVatRate: number;
42
79
  }
43
80
  /**
44
81
  * Feature flags for the store
45
82
  */
46
83
  interface FeatureFlags {
84
+ /** Whether wishlist functionality is enabled */
47
85
  wishlistEnabled: boolean;
86
+ /** Whether guest checkout is allowed */
48
87
  guestCheckoutEnabled: boolean;
88
+ /** Whether newsletter signup is enabled */
49
89
  newsletterEnabled: boolean;
90
+ /** Whether product reviews are enabled */
50
91
  reviewsEnabled: boolean;
51
92
  }
93
+ /** Campaign type */
94
+ type CampaignType = "FREE_SHIPPING" | "BUY_X_PAY_Y";
52
95
  /**
53
- * Shipment method for free shipping campaigns
96
+ * Store campaign (promotion)
54
97
  */
55
- interface ShipmentMethod {
98
+ interface Campaign {
99
+ /** Unique campaign identifier */
56
100
  id: string;
101
+ /** Store ID this campaign belongs to */
57
102
  storeId: string;
103
+ /** Campaign display name */
58
104
  name: string;
105
+ /** Campaign description */
59
106
  description: string | null;
60
- price: number;
61
- active: boolean;
62
- min_estimate_delivery_days: number | null;
63
- max_estimate_delivery_days: number | null;
107
+ /** Type of campaign */
108
+ type: CampaignType;
109
+ /** Campaign start date (ISO 8601) */
110
+ startDate: string;
111
+ /** Campaign end date (ISO 8601), null = no end */
112
+ endDate: string | null;
113
+ /** Whether campaign is currently active */
114
+ isActive: boolean;
115
+ /** Creation timestamp (ISO 8601) */
116
+ createdAt: string;
117
+ /** Last update timestamp (ISO 8601) */
118
+ updatedAt: string;
119
+ /** Free shipping campaign details (if type is FREE_SHIPPING) */
120
+ FreeShippingCampaign: FreeShippingCampaign | null;
121
+ /** Buy X Pay Y campaign details (if type is BUY_X_PAY_Y) */
122
+ BuyXPayYCampaign: BuyXPayYCampaign | null;
64
123
  }
65
124
  /**
66
125
  * Free shipping campaign details
67
126
  */
68
127
  interface FreeShippingCampaign {
128
+ /** Unique identifier */
69
129
  id: string;
130
+ /** Parent campaign ID */
70
131
  campaignId: string;
132
+ /** Minimum spend in cents to qualify for free shipping */
71
133
  minimumSpend: number;
134
+ /** Shipping methods eligible for free shipping */
72
135
  shipmentMethods: ShipmentMethod[];
73
136
  }
74
137
  /**
75
- * Category reference for Buy X Pay Y campaigns
76
- */
77
- interface CategoryReference {
78
- id: string;
79
- name?: string;
80
- slug?: string;
81
- }
82
- /**
83
- * Buy X Pay Y campaign details
138
+ * Buy X Pay Y campaign details (e.g., "Buy 3, Pay 2")
84
139
  */
85
140
  interface BuyXPayYCampaign {
141
+ /** Unique identifier */
86
142
  id: string;
143
+ /** Parent campaign ID */
87
144
  campaignId: string;
145
+ /** Number of items customer must buy */
88
146
  buyQuantity: number;
147
+ /** Number of items customer pays for */
89
148
  payQuantity: number;
149
+ /** Categories this campaign applies to */
90
150
  applicableCategories: CategoryReference[];
91
151
  }
92
152
  /**
93
- * Campaign type enum
153
+ * Shipit shipping method details
154
+ * Represents a shipping service synced from the Shipit API
94
155
  */
95
- type CampaignType = "FREE_SHIPPING" | "BUY_X_PAY_Y";
156
+ interface ShipitShippingMethod {
157
+ /** Unique ID */
158
+ id: string;
159
+ /** Shipit service identifier */
160
+ serviceId: string;
161
+ /** Service name */
162
+ name: string;
163
+ /** Carrier name (e.g., "Posti", "Matkahuolto") */
164
+ carrier: string;
165
+ /** Carrier logo URL */
166
+ logo: string;
167
+ /** Whether pickup is included */
168
+ pickUpIncluded: boolean;
169
+ /** Whether home delivery is available */
170
+ homeDelivery: boolean;
171
+ /** Whether worldwide delivery is available */
172
+ worldwideDelivery: boolean;
173
+ /** Whether fragile handling is available */
174
+ fragile: boolean;
175
+ /** Whether domestic deliveries are available */
176
+ domesticDeliveries: boolean;
177
+ /** Additional information */
178
+ information: string | null;
179
+ /** Service description */
180
+ description: string;
181
+ /** Package height in cm */
182
+ height: number;
183
+ /** Package length in cm */
184
+ length: number;
185
+ /** Package width in cm */
186
+ width: number;
187
+ /** Package weight in kg */
188
+ weight: number;
189
+ /** Service type */
190
+ type: string;
191
+ /** Shipit price in cents */
192
+ price: number;
193
+ /** Whether pickup point selection is available */
194
+ pickupPoint: boolean;
195
+ /** Whether only parcel locker delivery is available */
196
+ onlyParchelLocker: boolean;
197
+ /** Reference to parent shipment method */
198
+ shipmentMethodId: string;
199
+ /** Created timestamp */
200
+ createdAt: string;
201
+ /** Updated timestamp */
202
+ updatedAt: string;
203
+ }
96
204
  /**
97
- * Store campaign
98
- * Note: Date fields can be Date objects (from Prisma) or strings (after JSON serialization)
205
+ * Shipping method
99
206
  */
100
- interface Campaign {
207
+ interface ShipmentMethod {
208
+ /** Unique identifier */
101
209
  id: string;
102
- storeId: string;
210
+ /** Shipping method name (e.g., "Posti - Paketti") */
103
211
  name: string;
212
+ /** Description */
104
213
  description: string | null;
105
- type: CampaignType;
106
- startDate: Date | string;
107
- endDate: Date | string | null;
108
- isActive: boolean;
109
- createdAt: Date | string;
110
- updatedAt: Date | string;
111
- FreeShippingCampaign?: FreeShippingCampaign | null;
112
- BuyXPayYCampaign?: BuyXPayYCampaign | null;
214
+ /** Price in cents */
215
+ price: number;
216
+ /** Whether this method is active */
217
+ active: boolean;
218
+ /** Minimum estimated delivery days */
219
+ min_estimate_delivery_days: number | null;
220
+ /** Maximum estimated delivery days */
221
+ max_estimate_delivery_days: number | null;
222
+ /** Associated Shipit method (if using Shipit integration) */
223
+ shipitMethod?: ShipitShippingMethod | null;
113
224
  }
114
225
  /**
115
- * Complete store configuration returned by store.getConfig()
226
+ * Category reference (lightweight, used in relationships)
116
227
  */
117
- interface StoreConfig {
118
- store: StoreInfo;
119
- seo: StoreSeo;
120
- payments: PaymentConfig;
121
- campaigns: Campaign[];
122
- features: FeatureFlags;
228
+ interface CategoryReference {
229
+ /** Unique identifier */
230
+ id: string;
231
+ /** Category name */
232
+ name: string;
233
+ /** URL-friendly slug */
234
+ slug: string;
235
+ /** Parent category ID (null if root category) */
236
+ parentId: string | null;
123
237
  }
124
238
 
125
239
  /**
126
- * SDK Configuration options
240
+ * Product Types
241
+ *
242
+ * Types for product-related API endpoints.
127
243
  */
128
- interface StorefrontClientConfig {
129
- /**
130
- * Your store's API key (required)
131
- */
132
- apiKey: string;
133
- /**
134
- * Base URL for the Storefront API
135
- */
136
- baseUrl: string;
137
- /**
138
- * Request timeout in milliseconds
139
- * @default 30000
140
- */
141
- timeout?: number;
244
+
245
+ /**
246
+ * Product variation option (e.g., Size: Large)
247
+ */
248
+ interface VariationOption {
249
+ /** Option value (e.g., "Large", "Red") */
250
+ value: string;
251
+ /** Option type information */
252
+ optionType: {
253
+ /** Option type name (e.g., "Size", "Color") */
254
+ name: string;
255
+ };
142
256
  }
143
257
  /**
144
- * Base options that can be passed to any API method.
145
- * Framework-agnostic - works with Next.js, Nuxt, or plain fetch.
258
+ * Product variation for listings (minimal fields)
146
259
  */
147
- interface FetchOptions {
148
- /**
149
- * AbortSignal for cancelling requests
150
- */
151
- signal?: AbortSignal;
152
- /**
153
- * Additional headers to send with the request
154
- */
155
- headers?: Record<string, string>;
156
- /**
157
- * Standard fetch cache mode
158
- */
159
- cache?: RequestCache;
160
- /**
161
- * Framework-specific options passthrough.
162
- * These are spread directly to the underlying fetch call.
163
- *
164
- * @example Next.js caching
165
- * ```typescript
166
- * await client.store.getConfig({
167
- * next: { revalidate: 60, tags: ['store-config'] }
168
- * });
169
- * ```
170
- *
171
- * @example Standard fetch
172
- * ```typescript
173
- * await client.store.getConfig({
174
- * cache: 'force-cache'
175
- * });
176
- * ```
177
- */
178
- [key: string]: unknown;
260
+ interface ProductVariationListing {
261
+ /** Unique variation identifier */
262
+ id: string;
263
+ /** Variation price in cents */
264
+ price: number;
265
+ /** Sale price in cents (null if not on sale) */
266
+ salePrice: number | null;
267
+ /** Sale discount percentage as string (null if not on sale) */
268
+ salePercent: string | null;
269
+ /** Sale start date (ISO 8601), null = immediate */
270
+ saleStartDate: string | null;
271
+ /** Sale end date (ISO 8601), null = no end */
272
+ saleEndDate: string | null;
273
+ }
274
+ /**
275
+ * Full product variation (for product detail page)
276
+ */
277
+ interface ProductVariation extends ProductVariationListing {
278
+ /** Available quantity (null = unlimited) */
279
+ quantity: number | null;
280
+ /** Stock keeping unit */
281
+ sku: string | null;
282
+ /** Variation-specific images */
283
+ images: string[];
284
+ /** Variation-specific description */
285
+ description: string | null;
286
+ /** Whether variation is visible on store */
287
+ showOnStore: boolean;
288
+ /** Variation options (size, color, etc.) */
289
+ options: VariationOption[];
290
+ }
291
+ /**
292
+ * Product for listing (cards, grids)
293
+ * Used by: /latest-products, /sorted-products, /filtered-products
294
+ */
295
+ interface Product {
296
+ /** Unique product identifier */
297
+ id: string;
298
+ /** Product display name */
299
+ name: string;
300
+ /** URL-friendly slug */
301
+ slug: string;
302
+ /** Product description */
303
+ description: string;
304
+ /** Base price in cents */
305
+ price: number;
306
+ /** Product images (URLs) */
307
+ images: string[];
308
+ /** Available quantity (null = unlimited) */
309
+ quantity: number | null;
310
+ /** Sale price in cents (null if not on sale) */
311
+ salePrice: number | null;
312
+ /** Sale discount percentage as string (null if not on sale) */
313
+ salePercent: string | null;
314
+ /** Sale start date (ISO 8601), null = immediate */
315
+ saleStartDate: string | null;
316
+ /** Sale end date (ISO 8601), null = no end */
317
+ saleEndDate: string | null;
318
+ /** Product variations (minimal fields for listing) */
319
+ variations: ProductVariationListing[];
320
+ }
321
+ /**
322
+ * Full product detail (single product page)
323
+ * Used by: /product/{slug}
324
+ */
325
+ interface ProductDetail extends Omit<Product, "variations"> {
326
+ /** Stock keeping unit */
327
+ sku: string | null;
328
+ /** SEO meta title */
329
+ metaTitle: string | null;
330
+ /** SEO meta description */
331
+ metaDescription: string | null;
332
+ /** Product categories */
333
+ categories: CategoryReference[];
334
+ /** Full product variations */
335
+ variations: ProductVariation[];
336
+ }
337
+ /**
338
+ * Response from /sorted-products and /filtered-products
339
+ */
340
+ interface ProductListResponse {
341
+ /** Category/collection name */
342
+ name: string;
343
+ /** Products in the list */
344
+ products: Product[];
345
+ /** Total count for pagination (only in sorted-products) */
346
+ totalCount?: number;
347
+ }
348
+ /**
349
+ * Response from /products-count
350
+ */
351
+ interface ProductCountResponse {
352
+ /** Number of products */
353
+ count: number;
354
+ }
355
+ /**
356
+ * Sort options for product listing
357
+ */
358
+ type ProductSortOption = "newest" | "price_asc" | "price_desc" | "popularity";
359
+ /**
360
+ * Parameters for sorted/filtered products
361
+ */
362
+ interface ProductListParams {
363
+ /** Category slugs to filter by (omit for all products) */
364
+ slugs?: string[];
365
+ /** Page number (1-based, default: 1) */
366
+ page?: number;
367
+ /** Products per page (default: 12, max: 100) */
368
+ pageSize?: number;
369
+ /** Sort order */
370
+ sort?: ProductSortOption;
179
371
  }
180
372
 
181
- interface FetcherConfig {
182
- apiKey: string;
183
- baseUrl: string;
184
- timeout?: number;
373
+ /**
374
+ * Category Types
375
+ *
376
+ * Types for category-related API endpoints.
377
+ */
378
+ /**
379
+ * Category with nested children.
380
+ * Used by: /categories, /categories/{slug}
381
+ */
382
+ interface Category {
383
+ /** Unique category identifier */
384
+ id: string;
385
+ /** Category display name */
386
+ name: string;
387
+ /** URL-friendly slug */
388
+ slug: string;
389
+ /** Store ID this category belongs to */
390
+ storeId: string;
391
+ /** Parent category ID (null if root category) */
392
+ parentId: string | null;
393
+ /** Creation timestamp (ISO 8601) */
394
+ createdAt: string;
395
+ /** Child categories (recursive) */
396
+ children: Category[];
185
397
  }
186
- interface RequestOptions extends FetchOptions {
187
- method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
188
- body?: unknown;
189
- params?: Record<string, string | number | boolean | undefined>;
398
+ /**
399
+ * Response from /categories/{slug}
400
+ */
401
+ interface CategoryResponse {
402
+ /** The category data */
403
+ category: Category;
190
404
  }
405
+
191
406
  /**
192
- * Fetcher instance type returned by createFetcher
407
+ * Cart Types
408
+ *
409
+ * Types for cart-related API endpoints.
193
410
  */
194
- type Fetcher = ReturnType<typeof createFetcher>;
411
+
195
412
  /**
196
- * Create a configured fetcher instance for making API requests
413
+ * A single item in the shopping cart
197
414
  */
198
- declare function createFetcher(config: FetcherConfig): {
199
- request: <T>(endpoint: string, options?: RequestOptions) => Promise<T>;
200
- };
415
+ interface CartItem {
416
+ /** Full product details */
417
+ product: ProductDetail;
418
+ /** Quantity of this item in the cart */
419
+ cartQuantity: number;
420
+ /** Selected variation (if product has variations) */
421
+ variation?: ProductVariation;
422
+ }
423
+ /**
424
+ * Response from GET /cart, POST /cart, PATCH /cart, DELETE /cart
425
+ */
426
+ interface CartResponse {
427
+ /** Items currently in the cart */
428
+ items: CartItem[];
429
+ /** Cart ID for guest users (undefined for logged-in users) */
430
+ cartId?: string;
431
+ }
432
+ /**
433
+ * Changes detected during cart validation
434
+ */
435
+ interface CartValidationChanges {
436
+ /** Number of items removed (product deleted or out of stock) */
437
+ removedItems: number;
438
+ /** Number of items with adjusted quantity (insufficient stock) */
439
+ quantityAdjusted: number;
440
+ /** Number of items with changed price */
441
+ priceChanged: number;
442
+ }
443
+ /**
444
+ * Response from GET /cart/validate
445
+ */
446
+ interface CartValidationResponse {
447
+ /** Validated cart items (with auto-fixed quantities/prices) */
448
+ items: CartItem[];
449
+ /** Whether any changes were made during validation */
450
+ hasChanges: boolean;
451
+ /** Details about what changed */
452
+ changes: CartValidationChanges;
453
+ }
454
+ /**
455
+ * Options for cart operations that require session context
456
+ */
457
+ interface CartSessionOptions {
458
+ /** Cart ID for guest users (from cookie or local storage) */
459
+ cartId?: string;
460
+ /** Session ID for logged-in users (from auth cookie) */
461
+ sessionId?: string;
462
+ }
463
+ /**
464
+ * Parameters for adding an item to cart
465
+ */
466
+ interface AddToCartParams extends CartSessionOptions {
467
+ /** Product ID to add */
468
+ productId: string;
469
+ /** Variation ID (required if product has variations) */
470
+ variationId?: string;
471
+ /** Quantity to add (default: 1) */
472
+ quantity?: number;
473
+ }
474
+ /**
475
+ * Parameters for updating cart item quantity
476
+ */
477
+ interface UpdateCartQuantityParams extends CartSessionOptions {
478
+ /** Product ID to update */
479
+ productId: string;
480
+ /** Variation ID (if applicable) */
481
+ variationId?: string;
482
+ /** Quantity change: positive to add, negative to subtract */
483
+ delta: number;
484
+ }
485
+ /**
486
+ * Parameters for removing an item from cart
487
+ */
488
+ interface RemoveFromCartParams extends CartSessionOptions {
489
+ /** Product ID to remove */
490
+ productId: string;
491
+ /** Variation ID (if applicable) */
492
+ variationId?: string;
493
+ }
494
+ /**
495
+ * Price information for a product or variation
496
+ */
497
+ interface PriceInfo {
498
+ /** Current effective price in cents (sale price if on sale, otherwise regular) */
499
+ effectivePrice: number;
500
+ /** Original/regular price in cents */
501
+ originalPrice: number;
502
+ /** Whether the item is currently on sale */
503
+ isOnSale: boolean;
504
+ /** Sale percentage (e.g., "-20%") if applicable */
505
+ salePercent: string | null;
506
+ }
507
+ /**
508
+ * A cart item with calculated paid and free quantities (for Buy X Pay Y campaigns)
509
+ */
510
+ interface CalculatedCartItem {
511
+ /** Original cart item */
512
+ item: CartItem;
513
+ /** Number of units the customer pays for */
514
+ paidQuantity: number;
515
+ /** Number of units that are free (from campaign) */
516
+ freeQuantity: number;
517
+ /** Total quantity in cart */
518
+ totalQuantity: number;
519
+ }
520
+ /**
521
+ * Free shipping eligibility status
522
+ */
523
+ interface FreeShippingStatus {
524
+ /** Whether the cart qualifies for free shipping */
525
+ isEligible: boolean;
526
+ /** Minimum spend required for free shipping (in cents) */
527
+ minimumSpend: number;
528
+ /** Amount remaining to qualify for free shipping (in cents) */
529
+ remainingAmount: number;
530
+ /** Name of the free shipping campaign */
531
+ campaignName?: string;
532
+ /** IDs of shipment methods eligible for free shipping (when isEligible is true) */
533
+ eligibleShipmentMethodIds?: string[];
534
+ }
535
+ /**
536
+ * Result of cart calculation with campaigns applied
537
+ */
538
+ interface CartCalculationResult {
539
+ /** Cart items with paid/free quantities calculated */
540
+ calculatedItems: CalculatedCartItem[];
541
+ /** Final cart total after discounts (in cents) */
542
+ cartTotal: number;
543
+ /** Original cart total before discounts (in cents) */
544
+ originalTotal: number;
545
+ /** Total savings from campaigns (in cents) */
546
+ totalSavings: number;
547
+ /** Free shipping eligibility status */
548
+ freeShipping: FreeShippingStatus;
549
+ }
201
550
 
202
551
  /**
203
- * Store resource for fetching store configuration
552
+ * Shipping Types
553
+ *
554
+ * Types for shipment methods and pickup locations.
555
+ * ShipmentMethod and ShipitShippingMethod are re-exported from storeconfig.
204
556
  */
205
- declare function createStoreResource(fetcher: Fetcher): {
206
- /**
207
- * Get the complete store configuration including settings, SEO, payments, campaigns, and features.
208
- *
209
- * @example Basic usage
210
- * ```typescript
211
- * const config = await client.store.getConfig();
212
- * console.log(config.store.name);
213
- * console.log(config.seo.seoTitle);
214
- * console.log(config.campaigns);
215
- * ```
216
- *
217
- * @example Next.js - with caching
218
- * ```typescript
219
- * const config = await client.store.getConfig({
220
- * next: { revalidate: 300, tags: ['store-config'] }
221
- * });
222
- * ```
223
- *
224
- * @example Nuxt - wrap with useAsyncData
225
- * ```typescript
226
- * const { data: config } = await useAsyncData(
227
- * 'store-config',
228
- * () => client.store.getConfig()
229
- * );
230
- * ```
231
- *
232
- * @example Standard fetch caching
233
- * ```typescript
234
- * const config = await client.store.getConfig({
235
- * cache: 'force-cache'
236
- * });
237
- * ```
238
- */
239
- getConfig(options?: FetchOptions): Promise<StoreConfig>;
240
- };
557
+
241
558
  /**
242
- * Type for the store resource
559
+ * Opening hours for a pickup location
243
560
  */
244
- type StoreResource = ReturnType<typeof createStoreResource>;
561
+ interface PickupLocationOpeningHours {
562
+ monday: string[];
563
+ tuesday: string[];
564
+ wednesday: string[];
565
+ thursday: string[];
566
+ friday: string[];
567
+ saturday: string[];
568
+ sunday: string[];
569
+ exceptions: string[];
570
+ }
571
+ /**
572
+ * A pickup location (parcel locker, pickup point, etc.)
573
+ * Returned from Shipit API with merchant pricing added
574
+ */
575
+ interface PickupLocation {
576
+ /** Unique location ID */
577
+ id: string;
578
+ /** Location name */
579
+ name: string;
580
+ /** Street address */
581
+ address1: string;
582
+ /** Postal code */
583
+ zipcode: string;
584
+ /** City */
585
+ city: string;
586
+ /** Country code (e.g., "FI") */
587
+ countryCode: string;
588
+ /** Shipit service ID */
589
+ serviceId: string;
590
+ /** Carrier name */
591
+ carrier: string;
592
+ /** Shipit price in cents (may be null) */
593
+ price: number | null;
594
+ /** Merchant's price in cents (from store settings) */
595
+ merchantPrice: number | null;
596
+ /** Carrier logo URL */
597
+ carrierLogo: string;
598
+ /** Structured opening hours */
599
+ openingHours: PickupLocationOpeningHours | null;
600
+ /** Raw opening hours string */
601
+ openingHoursRaw: string | null;
602
+ /** GPS latitude */
603
+ latitude: number;
604
+ /** GPS longitude */
605
+ longitude: number;
606
+ /** Distance from postal code in meters */
607
+ distanceInMeters: number;
608
+ /** Distance from postal code in kilometers */
609
+ distanceInKilometers: number;
610
+ /** Additional metadata */
611
+ metadata: unknown | null;
612
+ }
613
+ /**
614
+ * Response from GET /shipment-methods
615
+ */
616
+ interface ShipmentMethodsResponse {
617
+ /** Available shipment methods */
618
+ shipmentMethods: ShipmentMethod[];
619
+ }
620
+ /**
621
+ * Response from GET /shipment-methods/[postalCode]
622
+ * Includes pickup locations near the postal code
623
+ */
624
+ interface ShipmentMethodsWithLocationsResponse {
625
+ /** Available shipment methods */
626
+ shipmentMethods: ShipmentMethod[];
627
+ /** Pickup locations near the postal code with merchant pricing */
628
+ pricedLocations: PickupLocation[];
629
+ }
245
630
 
246
631
  /**
247
- * The Storefront API client
632
+ * Customer Types
633
+ *
634
+ * Types for customer authentication and account management API endpoints.
248
635
  */
249
- interface StorefrontClient {
250
- /**
251
- * The configured API key (masked for security)
252
- */
253
- readonly apiKey: string;
254
- /**
255
- * The base URL for API requests
256
- */
257
- readonly baseUrl: string;
258
- /**
259
- * Store configuration resource
260
- */
261
- readonly store: StoreResource;
636
+ /**
637
+ * Basic customer information returned from most customer endpoints
638
+ */
639
+ interface Customer {
640
+ /** Unique customer ID */
641
+ id: string;
642
+ /** Customer's first name */
643
+ firstName: string;
644
+ /** Customer's last name */
645
+ lastName: string;
646
+ /** Customer's email address */
647
+ email: string;
262
648
  }
263
649
  /**
264
- * Create a new Storefront API client
650
+ * Extended customer information returned after registration
651
+ */
652
+ interface CustomerWithVerification extends Customer {
653
+ /** Account creation timestamp */
654
+ createdAt: string;
655
+ /** Email verification token (for sending verification emails) */
656
+ emailVerificationToken: string;
657
+ /** Token expiration timestamp */
658
+ emailVerificationExpiresAt: string;
659
+ }
660
+ /**
661
+ * Customer information returned after login
662
+ */
663
+ interface CustomerWithEmailStatus extends Customer {
664
+ /** Email verification timestamp (null if not verified) */
665
+ emailVerified: string | null;
666
+ /** Account creation timestamp */
667
+ createdAt: string;
668
+ }
669
+ /**
670
+ * Data required to register a new customer account
671
+ */
672
+ interface RegisterData {
673
+ /** Customer's first name */
674
+ firstName: string;
675
+ /** Customer's last name */
676
+ lastName: string;
677
+ /** Customer's email address */
678
+ email: string;
679
+ /** Password (minimum 8 characters) */
680
+ password: string;
681
+ }
682
+ /**
683
+ * Options for the login method
684
+ */
685
+ interface LoginOptions {
686
+ /** Guest cart ID to merge into user's cart after login */
687
+ cartId?: string;
688
+ }
689
+ /**
690
+ * Response from successful registration
691
+ */
692
+ interface RegisterResponse {
693
+ /** Whether the operation was successful */
694
+ success: true;
695
+ /** Created customer with verification token */
696
+ customer: CustomerWithVerification;
697
+ /** Success message */
698
+ message: string;
699
+ }
700
+ /**
701
+ * Response from successful login
702
+ */
703
+ interface LoginResponse {
704
+ /** Whether the operation was successful */
705
+ success: true;
706
+ /** Authenticated customer data */
707
+ customer: CustomerWithEmailStatus;
708
+ /** Success message */
709
+ message: string;
710
+ /** Session token for authenticated requests */
711
+ sessionId: string;
712
+ /** Session expiration timestamp (ISO 8601) */
713
+ expiresAt: string;
714
+ }
715
+ /**
716
+ * Response when login fails due to unverified email
717
+ */
718
+ interface LoginVerificationRequiredResponse {
719
+ /** Error message */
720
+ error: string;
721
+ /** Indicates email verification is required */
722
+ requiresVerification: true;
723
+ /** Customer ID for resending verification email */
724
+ customerId: string;
725
+ }
726
+ /**
727
+ * Response from successful logout
728
+ */
729
+ interface LogoutResponse {
730
+ /** Whether the operation was successful */
731
+ success: true;
732
+ /** Success message */
733
+ message: string;
734
+ /** New guest cart ID (if user had items in cart) */
735
+ cartId?: string;
736
+ }
737
+ /**
738
+ * Response from get user endpoint
739
+ */
740
+ interface GetUserResponse {
741
+ /** Whether the operation was successful */
742
+ success: true;
743
+ /** Current authenticated customer */
744
+ customer: Customer;
745
+ }
746
+ /**
747
+ * Response from successful email verification
748
+ */
749
+ interface VerifyEmailResponse {
750
+ /** Whether the operation was successful */
751
+ success: true;
752
+ /** Success message */
753
+ message: string;
754
+ }
755
+ /**
756
+ * Response from resend verification email
757
+ */
758
+ interface ResendVerificationResponse {
759
+ /** Whether the operation was successful */
760
+ success: true;
761
+ /** Updated customer with new verification token */
762
+ customer: CustomerWithVerification;
763
+ /** Success message */
764
+ message: string;
765
+ }
766
+ /**
767
+ * Data for updating customer profile
768
+ */
769
+ interface UpdateProfileData {
770
+ /** Updated first name */
771
+ firstName?: string;
772
+ /** Updated last name */
773
+ lastName?: string;
774
+ /** Updated email address */
775
+ email?: string;
776
+ }
777
+ /**
778
+ * Extended customer info returned after profile update
779
+ */
780
+ interface CustomerWithCreatedAt extends Customer {
781
+ /** Account creation timestamp */
782
+ createdAt: string;
783
+ }
784
+ /**
785
+ * Response from updating profile
786
+ */
787
+ interface UpdateProfileResponse {
788
+ /** Success message */
789
+ message: string;
790
+ /** Updated customer data */
791
+ customer: CustomerWithCreatedAt;
792
+ }
793
+ /**
794
+ * Response from deleting account
795
+ */
796
+ interface DeleteAccountResponse {
797
+ /** Success message */
798
+ message: string;
799
+ }
800
+ /**
801
+ * Product information attached to order line item
802
+ */
803
+ interface OrderProductInfo {
804
+ /** Product or variation ID */
805
+ id: string;
806
+ /** Product name */
807
+ name: string;
808
+ /** Product images */
809
+ images: string[];
810
+ /** Product slug (null for shipping items) */
811
+ slug: string | null;
812
+ /** Variation ID if this is a variation */
813
+ variationId?: string;
814
+ /** Variation option name (e.g., "Size") */
815
+ optionName?: string;
816
+ /** Variation option value (e.g., "Large") */
817
+ optionValue?: string;
818
+ /** True if this is a shipping item */
819
+ isShipping?: boolean;
820
+ /** True if product is no longer available */
821
+ unavailable?: boolean;
822
+ }
823
+ /**
824
+ * A single line item in an order
825
+ */
826
+ interface OrderLineItem {
827
+ /** Line item ID */
828
+ id: string;
829
+ /** Item type: PRODUCT, VARIATION, or SHIPPING */
830
+ itemType: "PRODUCT" | "VARIATION" | "SHIPPING";
831
+ /** Quantity ordered */
832
+ quantity: number;
833
+ /** Price per unit in cents */
834
+ price: number;
835
+ /** Total amount in cents */
836
+ totalAmount: number;
837
+ /** Product or variation code (ID) */
838
+ productCode: string;
839
+ /** Item name */
840
+ name: string;
841
+ /** VAT rate percentage */
842
+ vatRate: number;
843
+ /** Product information */
844
+ product: OrderProductInfo;
845
+ }
846
+ /**
847
+ * Shipment method info attached to order
848
+ */
849
+ interface OrderShipmentMethod {
850
+ /** Shipment method name */
851
+ name: string;
852
+ /** Shipping price in cents */
853
+ price: number;
854
+ /** VAT rate percentage */
855
+ vatRate: number;
856
+ /** Carrier logo URL */
857
+ logo: string | null;
858
+ }
859
+ /**
860
+ * Order status values
861
+ */
862
+ type OrderStatus = "PENDING" | "PROCESSING" | "SHIPPED" | "DELIVERED" | "CANCELLED" | "REFUNDED";
863
+ /**
864
+ * A customer order
865
+ */
866
+ interface CustomerOrder {
867
+ /** Order ID */
868
+ id: string;
869
+ /** Human-readable order number */
870
+ orderNumber: string;
871
+ /** Total order amount in cents */
872
+ totalAmount: number;
873
+ /** Order status */
874
+ status: OrderStatus;
875
+ /** Order creation timestamp */
876
+ createdAt: string;
877
+ /** Order line items with product info */
878
+ OrderLineItems: OrderLineItem[];
879
+ /** Shipment method details */
880
+ orderShipmentMethod: OrderShipmentMethod | null;
881
+ }
882
+ /**
883
+ * Response from getting customer orders
884
+ */
885
+ interface GetOrdersResponse {
886
+ /** Whether the operation was successful */
887
+ success: true;
888
+ /** Customer's orders */
889
+ orders: CustomerOrder[];
890
+ }
891
+ /**
892
+ * Variation option in wishlist item
893
+ */
894
+ interface WishlistVariationOption {
895
+ /** Option ID */
896
+ id: string;
897
+ /** Option value (e.g., "Large", "Red") */
898
+ value: string;
899
+ /** Option type details */
900
+ optionType: {
901
+ /** Option type ID */
902
+ id: string;
903
+ /** Option type name (e.g., "Size", "Color") */
904
+ name: string;
905
+ };
906
+ }
907
+ /**
908
+ * Variation details in wishlist item
909
+ */
910
+ interface WishlistVariation {
911
+ /** Variation ID */
912
+ id: string;
913
+ /** Variation SKU */
914
+ sku: string | null;
915
+ /** Variation price in cents */
916
+ price: number;
917
+ /** Sale price in cents */
918
+ salePrice: number | null;
919
+ /** Quantity in stock */
920
+ quantity: number;
921
+ /** Variation images */
922
+ images: string[];
923
+ /** Variation options (size, color, etc.) */
924
+ options: WishlistVariationOption[];
925
+ }
926
+ /**
927
+ * Product details in wishlist item
928
+ */
929
+ interface WishlistProduct {
930
+ /** Product ID */
931
+ id: string;
932
+ /** Product name */
933
+ name: string;
934
+ /** Product slug */
935
+ slug: string;
936
+ /** Product description */
937
+ description: string | null;
938
+ /** Product images */
939
+ images: string[];
940
+ /** Product price in cents */
941
+ price: number;
942
+ /** Sale price in cents */
943
+ salePrice: number | null;
944
+ /** Sale percentage (e.g., "-20%") */
945
+ salePercent: string | null;
946
+ /** Sale start date */
947
+ saleStartDate: string | null;
948
+ /** Sale end date */
949
+ saleEndDate: string | null;
950
+ /** Quantity in stock */
951
+ quantity: number;
952
+ /** Product SKU */
953
+ sku: string | null;
954
+ /** Product status */
955
+ status: string;
956
+ }
957
+ /**
958
+ * A wishlist item with product and optional variation details
959
+ */
960
+ interface WishlistItem {
961
+ /** Wishlist item ID */
962
+ id: string;
963
+ /** Customer ID */
964
+ customerId: string;
965
+ /** Product ID */
966
+ productId: string;
967
+ /** Variation ID (if applicable) */
968
+ variationId: string | null;
969
+ /** When the item was added to wishlist */
970
+ createdAt: string;
971
+ /** Product details */
972
+ product: WishlistProduct;
973
+ /** Variation details (if applicable) */
974
+ variation: WishlistVariation | null;
975
+ }
976
+ /**
977
+ * Response from getting wishlist
978
+ */
979
+ interface WishlistResponse {
980
+ /** Wishlist items */
981
+ items: WishlistItem[];
982
+ }
983
+ /**
984
+ * Response from adding item to wishlist
985
+ */
986
+ interface AddToWishlistResponse {
987
+ /** Success message */
988
+ message: string;
989
+ }
990
+ /**
991
+ * Response from removing item from wishlist
992
+ */
993
+ interface RemoveFromWishlistResponse {
994
+ /** Success message */
995
+ message: string;
996
+ }
997
+
998
+ /**
999
+ * Order Types
1000
+ *
1001
+ * Types for fetching order details from the Storefront API.
1002
+ * These types represent the raw order data returned by GET /order/{id}.
1003
+ *
1004
+ * Note: These differ from CustomerOrder types in customer.ts which are
1005
+ * transformed for customer order history display.
1006
+ */
1007
+ /**
1008
+ * Item type for order line items
1009
+ */
1010
+ type ConfirmationItemType = "PRODUCT" | "VARIATION" | "SHIPPING";
1011
+ /**
1012
+ * A single line item in an order confirmation
1013
+ * Represents raw data as stored in the database
1014
+ */
1015
+ interface ConfirmationOrderLineItem {
1016
+ /** Unique line item ID */
1017
+ id: string;
1018
+ /** Parent order ID */
1019
+ orderId: string;
1020
+ /** Type of item: PRODUCT, VARIATION, or SHIPPING */
1021
+ itemType: ConfirmationItemType;
1022
+ /** Quantity ordered */
1023
+ quantity: number;
1024
+ /** Price per unit in cents */
1025
+ price: number;
1026
+ /** Total amount in cents (price * quantity) */
1027
+ totalAmount: number;
1028
+ /** Product or variation code (ID reference) */
1029
+ productCode: string;
1030
+ /** Display name of the item */
1031
+ name: string;
1032
+ /** VAT rate percentage */
1033
+ vatRate: number;
1034
+ /** Product images array */
1035
+ images: string[];
1036
+ }
1037
+ /**
1038
+ * Customer delivery information attached to an order
1039
+ */
1040
+ interface ConfirmationOrderCustomerData {
1041
+ /** Customer data record ID */
1042
+ id: string;
1043
+ /** Customer's first name */
1044
+ firstName: string;
1045
+ /** Customer's last name */
1046
+ lastName: string;
1047
+ /** Customer's email address */
1048
+ email: string;
1049
+ /** Customer's phone number */
1050
+ phone: string | null;
1051
+ /** Delivery street address */
1052
+ address: string;
1053
+ /** Delivery city */
1054
+ city: string;
1055
+ /** Delivery postal code */
1056
+ postalCode: string;
1057
+ }
1058
+ /**
1059
+ * Shipment method information attached to an order
1060
+ * Includes tracking information when available
1061
+ */
1062
+ interface ConfirmationOrderShipmentMethod {
1063
+ /** Shipment method record ID */
1064
+ id: string;
1065
+ /** Carrier service ID (for Shipit integration) */
1066
+ serviceId: string | null;
1067
+ /** Shipment method display name */
1068
+ name: string;
1069
+ /** Description of the shipment method */
1070
+ description: string | null;
1071
+ /** Carrier logo URL */
1072
+ logo: string | null;
1073
+ /** Shipping price in cents */
1074
+ price: number;
1075
+ /** Parent order ID */
1076
+ orderId: string;
1077
+ /** VAT rate percentage */
1078
+ vatRate: number | null;
1079
+ /** Tracking number (when shipped) */
1080
+ trackingNumber: string | null;
1081
+ /** Array of tracking URLs */
1082
+ trackingUrls: string[];
1083
+ /** Shipit shipment number */
1084
+ shipmentNumber: string | null;
1085
+ /** Freight document URLs */
1086
+ freightDoc: string[];
1087
+ }
1088
+ /**
1089
+ * Order status values
1090
+ */
1091
+ type ConfirmationOrderStatus = "PENDING" | "PAID" | "SHIPPED" | "DELIVERED" | "CANCELLED" | "REFUNDED";
1092
+ /**
1093
+ * Complete order information returned by GET /order/{id}
1094
+ * Used for order confirmation pages and order detail views
1095
+ */
1096
+ interface Order {
1097
+ /** Unique order ID */
1098
+ id: string;
1099
+ /** Store ID this order belongs to */
1100
+ storeId: string;
1101
+ /** Order creation timestamp */
1102
+ createdAt: string;
1103
+ /** Total order amount in cents */
1104
+ totalAmount: number;
1105
+ /** Current order status */
1106
+ status: ConfirmationOrderStatus;
1107
+ /** Human-readable order number */
1108
+ orderNumber: number;
1109
+ /** Order line items (products, variations, shipping) */
1110
+ OrderLineItems: ConfirmationOrderLineItem[];
1111
+ /** Customer delivery information */
1112
+ orderCustomerData: ConfirmationOrderCustomerData | null;
1113
+ /** Shipment method with tracking info */
1114
+ orderShipmentMethod: ConfirmationOrderShipmentMethod | null;
1115
+ }
1116
+
1117
+ /**
1118
+ * Checkout Types
1119
+ *
1120
+ * Types for payment checkout operations (Stripe and Paytrail)
1121
+ */
1122
+ /**
1123
+ * Customer data required for checkout
1124
+ */
1125
+ interface CheckoutCustomerData {
1126
+ /** Customer's first name */
1127
+ first_name: string;
1128
+ /** Customer's last name */
1129
+ last_name: string;
1130
+ /** Customer's email address */
1131
+ email: string;
1132
+ /** Street address */
1133
+ address: string;
1134
+ /** Postal code (5 digits for Finland) */
1135
+ postal_code: string;
1136
+ /** City name */
1137
+ city: string;
1138
+ /** Phone number */
1139
+ phone: string;
1140
+ }
1141
+ /**
1142
+ * Shipment method selection for checkout
1143
+ */
1144
+ interface CheckoutShipmentMethod {
1145
+ /** ID of the selected shipment method */
1146
+ shipmentMethodId: string;
1147
+ /** ID of pickup point (for pickup delivery methods) */
1148
+ pickupId: string | null;
1149
+ }
1150
+ /**
1151
+ * Parameters for creating a checkout session
1152
+ */
1153
+ interface CheckoutParams {
1154
+ /** Customer information */
1155
+ customerData: CheckoutCustomerData;
1156
+ /** Selected shipment method */
1157
+ shipmentMethod: CheckoutShipmentMethod | null;
1158
+ /** Unique order ID (generated by caller) */
1159
+ orderId: string;
1160
+ /** URL to redirect on successful payment */
1161
+ successUrl: string;
1162
+ /** URL to redirect on cancelled payment */
1163
+ cancelUrl: string;
1164
+ }
1165
+ /**
1166
+ * Response from Stripe checkout
1167
+ */
1168
+ interface StripeCheckoutResponse {
1169
+ /** URL to redirect user to Stripe checkout page */
1170
+ url: string;
1171
+ }
1172
+ /**
1173
+ * Payment provider from Paytrail
1174
+ */
1175
+ interface PaytrailProvider {
1176
+ /** Form submission URL for this provider */
1177
+ url: string;
1178
+ /** Provider icon URL */
1179
+ icon: string;
1180
+ /** Provider SVG icon */
1181
+ svg: string;
1182
+ /** Provider name (e.g., "Nordea", "OP") */
1183
+ name: string;
1184
+ /** Provider group (e.g., "bank", "mobile", "creditcard") */
1185
+ group: string;
1186
+ /** Provider ID */
1187
+ id: string;
1188
+ /** Form parameters to submit to provider */
1189
+ parameters: Array<{
1190
+ name: string;
1191
+ value: string;
1192
+ }>;
1193
+ }
1194
+ /**
1195
+ * Payment method group from Paytrail
1196
+ */
1197
+ interface PaytrailGroup {
1198
+ /** Group ID (e.g., "bank", "mobile", "creditcard") */
1199
+ id: string;
1200
+ /** Group name */
1201
+ name: string;
1202
+ /** Group icon URL */
1203
+ icon: string;
1204
+ /** Group SVG icon */
1205
+ svg: string;
1206
+ }
1207
+ /**
1208
+ * Response from Paytrail checkout
1209
+ */
1210
+ interface PaytrailCheckoutResponse {
1211
+ /** Paytrail transaction ID */
1212
+ transactionId: string;
1213
+ /** Direct payment URL */
1214
+ href: string;
1215
+ /** Payment reference */
1216
+ reference: string;
1217
+ /** Terms and conditions URL */
1218
+ terms: string;
1219
+ /** Payment method groups */
1220
+ groups: PaytrailGroup[];
1221
+ /** Available payment providers */
1222
+ providers: PaytrailProvider[];
1223
+ /** Custom providers (if configured) */
1224
+ customProviders: Record<string, unknown>;
1225
+ }
1226
+ /**
1227
+ * Checkout error codes
1228
+ */
1229
+ type CheckoutErrorCode = "EMPTY_CART" | "PRODUCT_NOT_FOUND" | "VARIATION_NOT_FOUND" | "INSUFFICIENT_INVENTORY" | "STORE_SETTINGS_NOT_FOUND" | "PAYMENT_FAILED";
1230
+ /**
1231
+ * Error details for checkout failures
1232
+ */
1233
+ interface CheckoutErrorDetails {
1234
+ /** ID of the problematic product */
1235
+ productId?: string;
1236
+ /** ID of the problematic variation */
1237
+ variationId?: string;
1238
+ /** Available quantity (for inventory errors) */
1239
+ availableQuantity?: number;
1240
+ /** Requested quantity (for inventory errors) */
1241
+ requestedQuantity?: number;
1242
+ /** Additional error details */
1243
+ [key: string]: unknown;
1244
+ }
1245
+
1246
+ /**
1247
+ * Putiikkipalvelu Storefront SDK Types
1248
+ *
1249
+ * These types define the shape of data returned by the Storefront API.
1250
+ * Keep in sync with API implementation when making changes.
1251
+ */
1252
+
1253
+ /**
1254
+ * SDK client configuration options
1255
+ */
1256
+ interface StorefrontClientConfig {
1257
+ /**
1258
+ * Your store's API key (required)
1259
+ * Get this from Dashboard > Settings > API Keys
1260
+ */
1261
+ apiKey: string;
1262
+ /**
1263
+ * Base URL for the Storefront API
1264
+ * @example "https://putiikkipalvelu.fi/api/storefront/v1"
1265
+ */
1266
+ baseUrl: string;
1267
+ /**
1268
+ * Request timeout in milliseconds
1269
+ * @default 30000
1270
+ */
1271
+ timeout?: number;
1272
+ }
1273
+ /**
1274
+ * Options that can be passed to any API method.
1275
+ * Framework-agnostic - works with Next.js, Nuxt, or plain fetch.
1276
+ */
1277
+ interface FetchOptions {
1278
+ /**
1279
+ * AbortSignal for cancelling requests
1280
+ */
1281
+ signal?: AbortSignal;
1282
+ /**
1283
+ * Additional headers to send with the request
1284
+ */
1285
+ headers?: Record<string, string>;
1286
+ /**
1287
+ * Standard fetch cache mode
1288
+ */
1289
+ cache?: RequestCache;
1290
+ /**
1291
+ * Framework-specific options passthrough.
1292
+ * These are spread directly to the underlying fetch call.
1293
+ *
1294
+ * @example Next.js caching
1295
+ * ```typescript
1296
+ * await client.store.getConfig({
1297
+ * next: { revalidate: 60, tags: ['store-config'] }
1298
+ * });
1299
+ * ```
1300
+ */
1301
+ [key: string]: unknown;
1302
+ }
1303
+
1304
+ interface FetcherConfig {
1305
+ apiKey: string;
1306
+ baseUrl: string;
1307
+ timeout?: number;
1308
+ }
1309
+ interface RequestOptions extends FetchOptions {
1310
+ method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
1311
+ body?: unknown;
1312
+ params?: Record<string, string | number | boolean | undefined>;
1313
+ }
1314
+ /**
1315
+ * Fetcher instance type returned by createFetcher
1316
+ */
1317
+ type Fetcher = ReturnType<typeof createFetcher>;
1318
+ /**
1319
+ * Create a configured fetcher instance for making API requests
1320
+ */
1321
+ declare function createFetcher(config: FetcherConfig): {
1322
+ request: <T>(endpoint: string, options?: RequestOptions) => Promise<T>;
1323
+ };
1324
+
1325
+ /**
1326
+ * Store resource for fetching store configuration
1327
+ */
1328
+ declare function createStoreResource(fetcher: Fetcher): {
1329
+ /**
1330
+ * Get the complete store configuration including settings, SEO, payments, campaigns, and features.
1331
+ *
1332
+ * @example Basic usage
1333
+ * ```typescript
1334
+ * const config = await client.store.getConfig();
1335
+ * console.log(config.store.name);
1336
+ * console.log(config.seo.seoTitle);
1337
+ * console.log(config.campaigns);
1338
+ * ```
1339
+ *
1340
+ * @example Next.js - with caching
1341
+ * ```typescript
1342
+ * const config = await client.store.getConfig({
1343
+ * next: { revalidate: 300, tags: ['store-config'] }
1344
+ * });
1345
+ * ```
1346
+ *
1347
+ * @example Nuxt - wrap with useAsyncData
1348
+ * ```typescript
1349
+ * const { data: config } = await useAsyncData(
1350
+ * 'store-config',
1351
+ * () => client.store.getConfig()
1352
+ * );
1353
+ * ```
1354
+ *
1355
+ * @example Standard fetch caching
1356
+ * ```typescript
1357
+ * const config = await client.store.getConfig({
1358
+ * cache: 'force-cache'
1359
+ * });
1360
+ * ```
1361
+ */
1362
+ getConfig(options?: FetchOptions): Promise<StoreConfig>;
1363
+ };
1364
+ /**
1365
+ * Type for the store resource
1366
+ */
1367
+ type StoreResource = ReturnType<typeof createStoreResource>;
1368
+
1369
+ /**
1370
+ * Products resource for fetching product data
1371
+ */
1372
+ declare function createProductsResource(fetcher: Fetcher): {
1373
+ /**
1374
+ * Get latest products ordered by creation date (newest first).
1375
+ *
1376
+ * @param take - Number of products to return (required, must be >= 1)
1377
+ * @param options - Fetch options (caching, headers, etc.)
1378
+ * @returns Array of products
1379
+ *
1380
+ * @example Basic usage
1381
+ * ```typescript
1382
+ * const products = await client.products.latest(6);
1383
+ * ```
1384
+ *
1385
+ * @example Next.js - with caching
1386
+ * ```typescript
1387
+ * const products = await client.products.latest(6, {
1388
+ * next: { revalidate: 3600, tags: ['products'] }
1389
+ * });
1390
+ * ```
1391
+ */
1392
+ latest(take: number, options?: FetchOptions): Promise<Product[]>;
1393
+ /**
1394
+ * Get a single product by its URL slug.
1395
+ *
1396
+ * @param slug - Product URL slug
1397
+ * @param options - Fetch options (caching, headers, etc.)
1398
+ * @returns Full product details including categories and variations
1399
+ * @throws NotFoundError if product doesn't exist or is not visible
1400
+ *
1401
+ * @example Basic usage
1402
+ * ```typescript
1403
+ * const product = await client.products.getBySlug('my-product');
1404
+ * console.log(product.name, product.categories);
1405
+ * ```
1406
+ *
1407
+ * @example Next.js - with caching
1408
+ * ```typescript
1409
+ * const product = await client.products.getBySlug('my-product', {
1410
+ * next: { revalidate: 3600, tags: ['product', 'my-product'] }
1411
+ * });
1412
+ * ```
1413
+ */
1414
+ getBySlug(slug: string, options?: FetchOptions): Promise<ProductDetail>;
1415
+ /**
1416
+ * Get total product count, optionally filtered by category.
1417
+ *
1418
+ * @param slugs - Optional category slugs to filter by
1419
+ * @param options - Fetch options (caching, headers, etc.)
1420
+ * @returns Object with count property
1421
+ *
1422
+ * @example Get total count
1423
+ * ```typescript
1424
+ * const { count } = await client.products.count();
1425
+ * console.log(`Total products: ${count}`);
1426
+ * ```
1427
+ *
1428
+ * @example Get count for specific category
1429
+ * ```typescript
1430
+ * const { count } = await client.products.count(['shoes']);
1431
+ * console.log(`Products in shoes: ${count}`);
1432
+ * ```
1433
+ */
1434
+ count(slugs?: string[], options?: FetchOptions): Promise<ProductCountResponse>;
1435
+ /**
1436
+ * Get sorted products with pagination.
1437
+ * Uses optimized sorting with pre-computed effective prices.
1438
+ *
1439
+ * @param params - Query parameters (slugs, page, pageSize, sort)
1440
+ * @param options - Fetch options (caching, headers, etc.)
1441
+ * @returns Products list with totalCount for pagination
1442
+ *
1443
+ * @example Basic usage
1444
+ * ```typescript
1445
+ * const { products, totalCount } = await client.products.sorted({
1446
+ * page: 1,
1447
+ * pageSize: 12,
1448
+ * sort: 'newest'
1449
+ * });
1450
+ * ```
1451
+ *
1452
+ * @example Filter by category
1453
+ * ```typescript
1454
+ * const { products, totalCount } = await client.products.sorted({
1455
+ * slugs: ['shoes', 'clothing'],
1456
+ * page: 1,
1457
+ * pageSize: 24,
1458
+ * sort: 'price_asc'
1459
+ * });
1460
+ * ```
1461
+ *
1462
+ * @example Real-time data (no cache)
1463
+ * ```typescript
1464
+ * const data = await client.products.sorted(
1465
+ * { page: 1, pageSize: 12 },
1466
+ * { cache: 'no-store' }
1467
+ * );
1468
+ * ```
1469
+ */
1470
+ sorted(params?: ProductListParams, options?: FetchOptions): Promise<ProductListResponse>;
1471
+ /**
1472
+ * Get filtered products with pagination.
1473
+ * Similar to sorted() but without totalCount in response.
1474
+ * Useful for sitemaps and bulk fetches.
1475
+ *
1476
+ * @param params - Query parameters (slugs, page, pageSize, sort)
1477
+ * @param options - Fetch options (caching, headers, etc.)
1478
+ * @returns Products list with category name
1479
+ *
1480
+ * @example Fetch all products for sitemap
1481
+ * ```typescript
1482
+ * const { products } = await client.products.filtered({
1483
+ * slugs: ['all-products'],
1484
+ * page: 1,
1485
+ * pageSize: 1000
1486
+ * });
1487
+ * ```
1488
+ */
1489
+ filtered(params?: ProductListParams, options?: FetchOptions): Promise<Omit<ProductListResponse, "totalCount">>;
1490
+ };
1491
+ /**
1492
+ * Type for the products resource
1493
+ */
1494
+ type ProductsResource = ReturnType<typeof createProductsResource>;
1495
+
1496
+ /**
1497
+ * Categories resource for fetching category data
1498
+ */
1499
+ declare function createCategoriesResource(fetcher: Fetcher): {
1500
+ /**
1501
+ * Get all top-level categories with nested children.
1502
+ * Returns a hierarchical tree of categories (up to 5 levels deep).
1503
+ *
1504
+ * @param options - Fetch options (caching, headers, etc.)
1505
+ * @returns Array of top-level categories with nested children
1506
+ *
1507
+ * @example Basic usage
1508
+ * ```typescript
1509
+ * const categories = await client.categories.list();
1510
+ * categories.forEach(cat => {
1511
+ * console.log(cat.name, cat.children.length);
1512
+ * });
1513
+ * ```
1514
+ *
1515
+ * @example Next.js - with caching
1516
+ * ```typescript
1517
+ * const categories = await client.categories.list({
1518
+ * next: { revalidate: 3600, tags: ['categories'] }
1519
+ * });
1520
+ * ```
1521
+ */
1522
+ list(options?: FetchOptions): Promise<Category[]>;
1523
+ /**
1524
+ * Get a single category by its URL slug.
1525
+ *
1526
+ * @param slug - Category URL slug
1527
+ * @param options - Fetch options (caching, headers, etc.)
1528
+ * @returns Category data
1529
+ * @throws NotFoundError if category doesn't exist
1530
+ *
1531
+ * @example Basic usage
1532
+ * ```typescript
1533
+ * const { category } = await client.categories.getBySlug('shoes');
1534
+ * console.log(category.name);
1535
+ * ```
1536
+ *
1537
+ * @example Next.js - with caching
1538
+ * ```typescript
1539
+ * const { category } = await client.categories.getBySlug('shoes', {
1540
+ * next: { revalidate: 86400, tags: ['category', 'shoes'] }
1541
+ * });
1542
+ * ```
1543
+ */
1544
+ getBySlug(slug: string, options?: FetchOptions): Promise<CategoryResponse>;
1545
+ };
1546
+ /**
1547
+ * Type for the categories resource
1548
+ */
1549
+ type CategoriesResource = ReturnType<typeof createCategoriesResource>;
1550
+
1551
+ /**
1552
+ * Cart Resource
1553
+ *
1554
+ * Methods for managing the shopping cart stored in Redis.
1555
+ * Supports both guest carts (via cartId) and authenticated user carts (via sessionId).
1556
+ */
1557
+
1558
+ /**
1559
+ * Cart resource for managing shopping cart
1560
+ */
1561
+ declare function createCartResource(fetcher: Fetcher): {
1562
+ /**
1563
+ * Fetch the current cart contents.
1564
+ *
1565
+ * @param options - Cart session options (cartId for guests, sessionId for logged-in users)
1566
+ * @param fetchOptions - Fetch options (caching, headers, etc.)
1567
+ * @returns Cart items and cartId (for guests)
1568
+ *
1569
+ * @example Guest user
1570
+ * ```typescript
1571
+ * const cartId = localStorage.getItem('cart-id');
1572
+ * const { items, cartId: newCartId } = await client.cart.get({ cartId });
1573
+ * ```
1574
+ *
1575
+ * @example Logged-in user
1576
+ * ```typescript
1577
+ * const { items } = await client.cart.get({ sessionId });
1578
+ * ```
1579
+ */
1580
+ get(options?: CartSessionOptions, fetchOptions?: FetchOptions): Promise<CartResponse>;
1581
+ /**
1582
+ * Add an item to the cart.
1583
+ * If the item already exists, quantity is incremented.
1584
+ *
1585
+ * @param params - Add to cart parameters
1586
+ * @param fetchOptions - Fetch options
1587
+ * @returns Updated cart with new cartId for guests
1588
+ * @throws ValidationError if quantity exceeds available stock
1589
+ *
1590
+ * @example Add product
1591
+ * ```typescript
1592
+ * const { items, cartId } = await client.cart.addItem({
1593
+ * cartId: existingCartId,
1594
+ * productId: 'prod_123',
1595
+ * quantity: 2
1596
+ * });
1597
+ * // Save cartId for future requests
1598
+ * localStorage.setItem('cart-id', cartId);
1599
+ * ```
1600
+ *
1601
+ * @example Add product with variation
1602
+ * ```typescript
1603
+ * const { items, cartId } = await client.cart.addItem({
1604
+ * cartId,
1605
+ * productId: 'prod_123',
1606
+ * variationId: 'var_456',
1607
+ * quantity: 1
1608
+ * });
1609
+ * ```
1610
+ */
1611
+ addItem(params: AddToCartParams, fetchOptions?: FetchOptions): Promise<CartResponse>;
1612
+ /**
1613
+ * Update item quantity by delta (atomic operation).
1614
+ * Use positive delta to increase, negative to decrease.
1615
+ * Minimum quantity is 1 (use removeItem to delete).
1616
+ *
1617
+ * @param params - Update quantity parameters
1618
+ * @param fetchOptions - Fetch options
1619
+ * @returns Updated cart
1620
+ * @throws NotFoundError if item not in cart or quantity would go below 1
1621
+ *
1622
+ * @example Increment quantity
1623
+ * ```typescript
1624
+ * const { items } = await client.cart.updateQuantity({
1625
+ * cartId,
1626
+ * productId: 'prod_123',
1627
+ * delta: 1
1628
+ * });
1629
+ * ```
1630
+ *
1631
+ * @example Decrement quantity
1632
+ * ```typescript
1633
+ * const { items } = await client.cart.updateQuantity({
1634
+ * cartId,
1635
+ * productId: 'prod_123',
1636
+ * variationId: 'var_456',
1637
+ * delta: -1
1638
+ * });
1639
+ * ```
1640
+ */
1641
+ updateQuantity(params: UpdateCartQuantityParams, fetchOptions?: FetchOptions): Promise<CartResponse>;
1642
+ /**
1643
+ * Remove an item from the cart.
1644
+ *
1645
+ * @param params - Remove from cart parameters
1646
+ * @param fetchOptions - Fetch options
1647
+ * @returns Updated cart
1648
+ *
1649
+ * @example Remove product
1650
+ * ```typescript
1651
+ * const { items } = await client.cart.removeItem({
1652
+ * cartId,
1653
+ * productId: 'prod_123'
1654
+ * });
1655
+ * ```
1656
+ *
1657
+ * @example Remove variation
1658
+ * ```typescript
1659
+ * const { items } = await client.cart.removeItem({
1660
+ * cartId,
1661
+ * productId: 'prod_123',
1662
+ * variationId: 'var_456'
1663
+ * });
1664
+ * ```
1665
+ */
1666
+ removeItem(params: RemoveFromCartParams, fetchOptions?: FetchOptions): Promise<CartResponse>;
1667
+ /**
1668
+ * Validate cart before checkout.
1669
+ * Checks product availability, stock levels, and prices.
1670
+ * Auto-fixes issues (removes unavailable items, adjusts quantities).
1671
+ *
1672
+ * @param options - Cart session options
1673
+ * @param fetchOptions - Fetch options
1674
+ * @returns Validated cart with change metadata
1675
+ *
1676
+ * @example Validate before checkout
1677
+ * ```typescript
1678
+ * const { items, hasChanges, changes } = await client.cart.validate({ cartId });
1679
+ *
1680
+ * if (hasChanges) {
1681
+ * if (changes.removedItems > 0) {
1682
+ * notify('Some items were removed (out of stock)');
1683
+ * }
1684
+ * if (changes.quantityAdjusted > 0) {
1685
+ * notify('Some quantities were adjusted');
1686
+ * }
1687
+ * if (changes.priceChanged > 0) {
1688
+ * notify('Some prices have changed');
1689
+ * }
1690
+ * }
1691
+ * ```
1692
+ */
1693
+ validate(options?: CartSessionOptions, fetchOptions?: FetchOptions): Promise<CartValidationResponse>;
1694
+ };
1695
+ /**
1696
+ * Type for the cart resource
1697
+ */
1698
+ type CartResource = ReturnType<typeof createCartResource>;
1699
+
1700
+ /**
1701
+ * Shipping Resource
1702
+ *
1703
+ * Methods for fetching shipment methods and pickup locations.
1704
+ */
1705
+
1706
+ /**
1707
+ * Shipping resource for fetching shipment methods and pickup locations
1708
+ */
1709
+ declare function createShippingResource(fetcher: Fetcher): {
1710
+ /**
1711
+ * Get all available shipment methods for the store.
1712
+ * Returns methods without pickup locations - use `getWithLocations` for postal code specific data.
1713
+ *
1714
+ * @param options - Fetch options (caching, headers, etc.)
1715
+ * @returns Available shipment methods
1716
+ *
1717
+ * @example
1718
+ * ```typescript
1719
+ * const { shipmentMethods } = await client.shipping.getMethods();
1720
+ *
1721
+ * shipmentMethods.forEach(method => {
1722
+ * console.log(`${method.name}: ${method.price / 100}€`);
1723
+ * });
1724
+ * ```
1725
+ */
1726
+ getMethods(options?: FetchOptions): Promise<ShipmentMethodsResponse>;
1727
+ /**
1728
+ * Get shipment methods with pickup locations for a specific postal code.
1729
+ * Calls the Shipit API to fetch nearby pickup points (parcel lockers, etc.)
1730
+ *
1731
+ * @param postalCode - Customer's postal code (e.g., "00100")
1732
+ * @param options - Fetch options (caching, headers, etc.)
1733
+ * @returns Shipment methods and nearby pickup locations with pricing
1734
+ *
1735
+ * @example
1736
+ * ```typescript
1737
+ * const { shipmentMethods, pricedLocations } = await client.shipping.getWithLocations("00100");
1738
+ *
1739
+ * // Show pickup locations
1740
+ * pricedLocations.forEach(location => {
1741
+ * console.log(`${location.name} - ${location.carrier}`);
1742
+ * console.log(` ${location.address1}, ${location.city}`);
1743
+ * console.log(` ${location.distanceInKilometers.toFixed(1)} km away`);
1744
+ * console.log(` Price: ${(location.merchantPrice ?? 0) / 100}€`);
1745
+ * });
1746
+ * ```
1747
+ *
1748
+ * @example Filter by carrier
1749
+ * ```typescript
1750
+ * const { pricedLocations } = await client.shipping.getWithLocations("00100");
1751
+ *
1752
+ * const postiLocations = pricedLocations.filter(
1753
+ * loc => loc.carrier === "Posti"
1754
+ * );
1755
+ * ```
1756
+ */
1757
+ getWithLocations(postalCode: string, options?: FetchOptions): Promise<ShipmentMethodsWithLocationsResponse>;
1758
+ };
1759
+ /**
1760
+ * Type for the shipping resource
1761
+ */
1762
+ type ShippingResource = ReturnType<typeof createShippingResource>;
1763
+
1764
+ /**
1765
+ * Customer Resource
1766
+ *
1767
+ * Methods for customer authentication and account management.
1768
+ * Supports session-based authentication with the x-session-id header.
1769
+ */
1770
+
1771
+ /**
1772
+ * Customer resource for authentication and account management
1773
+ */
1774
+ declare function createCustomerResource(fetcher: Fetcher): {
1775
+ /**
1776
+ * Register a new customer account.
1777
+ * After registration, the customer must verify their email before logging in.
1778
+ *
1779
+ * @param data - Registration data (firstName, lastName, email, password)
1780
+ * @param fetchOptions - Fetch options
1781
+ * @returns Created customer with verification token
1782
+ *
1783
+ * @example
1784
+ * ```typescript
1785
+ * const { customer, message } = await client.customer.register({
1786
+ * firstName: 'John',
1787
+ * lastName: 'Doe',
1788
+ * email: 'john@example.com',
1789
+ * password: 'securePassword123'
1790
+ * });
1791
+ *
1792
+ * // Send verification email using customer.emailVerificationToken
1793
+ * console.log('Account created:', message);
1794
+ * ```
1795
+ */
1796
+ register(data: RegisterData, fetchOptions?: FetchOptions): Promise<RegisterResponse>;
1797
+ /**
1798
+ * Log in an existing customer.
1799
+ * Returns a session ID that must be stored and passed to authenticated endpoints.
1800
+ *
1801
+ * @param email - Customer's email address
1802
+ * @param password - Customer's password
1803
+ * @param options - Login options (optional cartId for cart merging)
1804
+ * @param fetchOptions - Fetch options
1805
+ * @returns Session ID and customer data
1806
+ * @throws ValidationError if email is not verified (check error for requiresVerification)
1807
+ *
1808
+ * @example
1809
+ * ```typescript
1810
+ * try {
1811
+ * const { sessionId, customer, expiresAt } = await client.customer.login(
1812
+ * 'john@example.com',
1813
+ * 'securePassword123',
1814
+ * { cartId: guestCartId } // Optional: merge guest cart
1815
+ * );
1816
+ *
1817
+ * // Store sessionId in a cookie
1818
+ * cookies().set('session-id', sessionId, {
1819
+ * httpOnly: true,
1820
+ * expires: new Date(expiresAt)
1821
+ * });
1822
+ * } catch (error) {
1823
+ * if (error.requiresVerification) {
1824
+ * // Prompt user to verify email
1825
+ * await client.customer.resendVerification(error.customerId);
1826
+ * }
1827
+ * }
1828
+ * ```
1829
+ */
1830
+ login(email: string, password: string, options?: LoginOptions, fetchOptions?: FetchOptions): Promise<LoginResponse>;
1831
+ /**
1832
+ * Log out the current customer and invalidate their session.
1833
+ * If the customer had items in their cart, they are migrated to a new guest cart.
1834
+ *
1835
+ * @param sessionId - The customer's session ID
1836
+ * @param fetchOptions - Fetch options
1837
+ * @returns Logout confirmation with optional new guest cart ID
1838
+ *
1839
+ * @example
1840
+ * ```typescript
1841
+ * const { cartId } = await client.customer.logout(sessionId);
1842
+ *
1843
+ * // Clear session cookie
1844
+ * cookies().delete('session-id');
1845
+ *
1846
+ * // If cart was migrated, store the new guest cart ID
1847
+ * if (cartId) {
1848
+ * cookies().set('cart-id', cartId);
1849
+ * }
1850
+ * ```
1851
+ */
1852
+ logout(sessionId: string, fetchOptions?: FetchOptions): Promise<LogoutResponse>;
1853
+ /**
1854
+ * Get the currently authenticated customer's profile.
1855
+ *
1856
+ * @param sessionId - The customer's session ID
1857
+ * @param fetchOptions - Fetch options
1858
+ * @returns Current customer data
1859
+ * @throws AuthError if session is invalid or expired
1860
+ *
1861
+ * @example
1862
+ * ```typescript
1863
+ * const sessionId = cookies().get('session-id')?.value;
1864
+ * if (sessionId) {
1865
+ * const { customer } = await client.customer.getUser(sessionId);
1866
+ * console.log(`Welcome back, ${customer.firstName}!`);
1867
+ * }
1868
+ * ```
1869
+ */
1870
+ getUser(sessionId: string, fetchOptions?: FetchOptions): Promise<GetUserResponse>;
1871
+ /**
1872
+ * Verify a customer's email address using the token sent during registration.
1873
+ *
1874
+ * @param token - Email verification token
1875
+ * @param fetchOptions - Fetch options
1876
+ * @returns Verification confirmation
1877
+ * @throws ValidationError if token is invalid or expired
1878
+ *
1879
+ * @example
1880
+ * ```typescript
1881
+ * // Token comes from the verification email link
1882
+ * const token = searchParams.get('token');
1883
+ *
1884
+ * const { message } = await client.customer.verifyEmail(token);
1885
+ * console.log(message); // "Email verified successfully. You can now log in."
1886
+ * ```
1887
+ */
1888
+ verifyEmail(token: string, fetchOptions?: FetchOptions): Promise<VerifyEmailResponse>;
1889
+ /**
1890
+ * Resend the email verification token for an unverified customer.
1891
+ * Generates a new token valid for 24 hours.
1892
+ *
1893
+ * @param customerId - The customer's ID (from failed login response)
1894
+ * @param fetchOptions - Fetch options
1895
+ * @returns Updated customer with new verification token
1896
+ * @throws ValidationError if customer is already verified or not found
1897
+ *
1898
+ * @example
1899
+ * ```typescript
1900
+ * // After login fails with requiresVerification
1901
+ * const { customer } = await client.customer.resendVerification(customerId);
1902
+ *
1903
+ * // Send new verification email using customer.emailVerificationToken
1904
+ * await sendVerificationEmail(customer.email, customer.emailVerificationToken);
1905
+ * ```
1906
+ */
1907
+ resendVerification(customerId: string, fetchOptions?: FetchOptions): Promise<ResendVerificationResponse>;
1908
+ /**
1909
+ * Update the authenticated customer's profile.
1910
+ *
1911
+ * @param sessionId - The customer's session ID
1912
+ * @param data - Profile data to update (firstName, lastName, email)
1913
+ * @param fetchOptions - Fetch options
1914
+ * @returns Updated customer data
1915
+ * @throws AuthError if session is invalid
1916
+ * @throws ValidationError if email is already taken by another customer
1917
+ *
1918
+ * @example
1919
+ * ```typescript
1920
+ * const { customer } = await client.customer.updateProfile(sessionId, {
1921
+ * firstName: 'Jane',
1922
+ * lastName: 'Smith',
1923
+ * email: 'jane.smith@example.com'
1924
+ * });
1925
+ *
1926
+ * console.log('Profile updated:', customer.email);
1927
+ * ```
1928
+ */
1929
+ updateProfile(sessionId: string, data: UpdateProfileData, fetchOptions?: FetchOptions): Promise<UpdateProfileResponse>;
1930
+ /**
1931
+ * Delete the authenticated customer's account.
1932
+ * This action is permanent and cannot be undone.
1933
+ * All associated data (sessions, wishlist, etc.) will be deleted.
1934
+ *
1935
+ * @param sessionId - The customer's session ID
1936
+ * @param fetchOptions - Fetch options
1937
+ * @returns Deletion confirmation
1938
+ * @throws AuthError if session is invalid
1939
+ *
1940
+ * @example
1941
+ * ```typescript
1942
+ * // Confirm with user before calling
1943
+ * if (confirm('Are you sure you want to delete your account?')) {
1944
+ * await client.customer.deleteAccount(sessionId);
1945
+ *
1946
+ * // Clear session cookie
1947
+ * cookies().delete('session-id');
1948
+ *
1949
+ * // Redirect to home page
1950
+ * redirect('/');
1951
+ * }
1952
+ * ```
1953
+ */
1954
+ deleteAccount(sessionId: string, fetchOptions?: FetchOptions): Promise<DeleteAccountResponse>;
1955
+ /**
1956
+ * Get the customer's order history.
1957
+ * Returns all orders with line items and product details.
1958
+ *
1959
+ * @param sessionId - The customer's session ID
1960
+ * @param customerId - The customer's ID
1961
+ * @param fetchOptions - Fetch options
1962
+ * @returns List of customer orders
1963
+ *
1964
+ * @example
1965
+ * ```typescript
1966
+ * const { orders } = await client.customer.getOrders(sessionId, customerId);
1967
+ *
1968
+ * orders.forEach(order => {
1969
+ * console.log(`Order #${order.orderNumber}: ${order.status}`);
1970
+ * order.OrderLineItems.forEach(item => {
1971
+ * console.log(` - ${item.name} x${item.quantity}`);
1972
+ * });
1973
+ * });
1974
+ * ```
1975
+ */
1976
+ getOrders(sessionId: string, customerId: string, fetchOptions?: FetchOptions): Promise<GetOrdersResponse>;
1977
+ /**
1978
+ * Wishlist management methods.
1979
+ * Access via `client.customer.wishlist.get()`, `.add()`, `.remove()`.
1980
+ */
1981
+ wishlist: {
1982
+ /**
1983
+ * Get the customer's wishlist.
1984
+ * Returns all wishlist items with product and variation details.
1985
+ *
1986
+ * @param sessionId - The customer's session ID
1987
+ * @param fetchOptions - Fetch options
1988
+ * @returns Wishlist items with product details
1989
+ * @throws AuthError if session is invalid
1990
+ *
1991
+ * @example
1992
+ * ```typescript
1993
+ * const { items } = await client.customer.wishlist.get(sessionId);
1994
+ *
1995
+ * items.forEach(item => {
1996
+ * console.log(`${item.product.name} - $${item.product.price / 100}`);
1997
+ * if (item.variation) {
1998
+ * const options = item.variation.options
1999
+ * .map(o => `${o.optionType.name}: ${o.value}`)
2000
+ * .join(', ');
2001
+ * console.log(` Variant: ${options}`);
2002
+ * }
2003
+ * });
2004
+ * ```
2005
+ */
2006
+ get(sessionId: string, fetchOptions?: FetchOptions): Promise<WishlistResponse>;
2007
+ /**
2008
+ * Add a product to the customer's wishlist.
2009
+ *
2010
+ * @param sessionId - The customer's session ID
2011
+ * @param productId - The product ID to add
2012
+ * @param variationId - Optional variation ID (for products with variations)
2013
+ * @param fetchOptions - Fetch options
2014
+ * @returns Success message
2015
+ * @throws AuthError if session is invalid
2016
+ * @throws ValidationError if product already in wishlist
2017
+ *
2018
+ * @example
2019
+ * ```typescript
2020
+ * // Add a simple product
2021
+ * await client.customer.wishlist.add(sessionId, 'prod_123');
2022
+ *
2023
+ * // Add a product with a specific variation
2024
+ * await client.customer.wishlist.add(sessionId, 'prod_123', 'var_456');
2025
+ * ```
2026
+ */
2027
+ add(sessionId: string, productId: string, variationId?: string, fetchOptions?: FetchOptions): Promise<AddToWishlistResponse>;
2028
+ /**
2029
+ * Remove a product from the customer's wishlist.
2030
+ *
2031
+ * @param sessionId - The customer's session ID
2032
+ * @param productId - The product ID to remove
2033
+ * @param variationId - Optional variation ID (must match if item was added with variation)
2034
+ * @param fetchOptions - Fetch options
2035
+ * @returns Success message
2036
+ * @throws AuthError if session is invalid
2037
+ * @throws NotFoundError if item not in wishlist
2038
+ *
2039
+ * @example
2040
+ * ```typescript
2041
+ * // Remove a simple product
2042
+ * await client.customer.wishlist.remove(sessionId, 'prod_123');
2043
+ *
2044
+ * // Remove a specific variation
2045
+ * await client.customer.wishlist.remove(sessionId, 'prod_123', 'var_456');
2046
+ * ```
2047
+ */
2048
+ remove(sessionId: string, productId: string, variationId?: string, fetchOptions?: FetchOptions): Promise<RemoveFromWishlistResponse>;
2049
+ };
2050
+ };
2051
+ /**
2052
+ * Type for the customer resource
2053
+ */
2054
+ type CustomerResource = ReturnType<typeof createCustomerResource>;
2055
+
2056
+ /**
2057
+ * Order resource for fetching order details
2058
+ *
2059
+ * Used for order confirmation pages and viewing order details.
2060
+ * For customer order history, use the customer.getOrders() method instead.
2061
+ */
2062
+ declare function createOrderResource(fetcher: Fetcher): {
2063
+ /**
2064
+ * Get order details by ID.
2065
+ *
2066
+ * Retrieves complete order information including line items,
2067
+ * customer data, and shipment method with tracking info.
2068
+ *
2069
+ * @param orderId - The order ID to fetch
2070
+ * @param options - Fetch options (caching, headers, etc.)
2071
+ * @returns Complete order details
2072
+ * @throws NotFoundError if order doesn't exist or belongs to different store
2073
+ *
2074
+ * @example Basic usage (order confirmation page)
2075
+ * ```typescript
2076
+ * const order = await client.order.get(orderId);
2077
+ * console.log(`Order #${order.orderNumber} - ${order.status}`);
2078
+ * console.log(`Total: ${order.totalAmount / 100} EUR`);
2079
+ * ```
2080
+ *
2081
+ * @example Next.js - with caching
2082
+ * ```typescript
2083
+ * const order = await client.order.get(orderId, {
2084
+ * next: { revalidate: 60, tags: ['order', orderId] }
2085
+ * });
2086
+ * ```
2087
+ *
2088
+ * @example Display line items
2089
+ * ```typescript
2090
+ * const order = await client.order.get(orderId);
2091
+ * order.OrderLineItems.forEach(item => {
2092
+ * if (item.itemType !== 'SHIPPING') {
2093
+ * console.log(`${item.name} x${item.quantity} = ${item.totalAmount / 100} EUR`);
2094
+ * }
2095
+ * });
2096
+ * ```
2097
+ *
2098
+ * @example Show tracking info
2099
+ * ```typescript
2100
+ * const order = await client.order.get(orderId);
2101
+ * if (order.orderShipmentMethod?.trackingNumber) {
2102
+ * console.log(`Tracking: ${order.orderShipmentMethod.trackingNumber}`);
2103
+ * order.orderShipmentMethod.trackingUrls?.forEach(url => {
2104
+ * console.log(`Track at: ${url}`);
2105
+ * });
2106
+ * }
2107
+ * ```
2108
+ */
2109
+ get(orderId: string, options?: FetchOptions): Promise<Order>;
2110
+ };
2111
+ /**
2112
+ * Type for the order resource
2113
+ */
2114
+ type OrderResource = ReturnType<typeof createOrderResource>;
2115
+
2116
+ /**
2117
+ * Extended options for checkout requests
2118
+ *
2119
+ * Checkout requires cart and session context via headers.
2120
+ */
2121
+ interface CheckoutOptions extends FetchOptions {
2122
+ /**
2123
+ * Cart ID for guest checkout.
2124
+ * Pass this when the user is not logged in.
2125
+ */
2126
+ cartId?: string;
2127
+ /**
2128
+ * Session ID for authenticated checkout.
2129
+ * Pass this when the user is logged in.
2130
+ */
2131
+ sessionId?: string;
2132
+ }
2133
+ /**
2134
+ * Checkout resource for payment processing
2135
+ *
2136
+ * Handles both Stripe and Paytrail payment providers.
2137
+ */
2138
+ declare function createCheckoutResource(fetcher: Fetcher): {
2139
+ /**
2140
+ * Create a Stripe checkout session.
2141
+ *
2142
+ * Redirects the user to Stripe's hosted checkout page.
2143
+ * Cart items are validated and stock is reserved on the server.
2144
+ *
2145
+ * @param params - Checkout parameters (customer data, shipping, URLs)
2146
+ * @param options - Checkout options including cart/session context
2147
+ * @returns URL to redirect user to Stripe checkout
2148
+ * @throws ValidationError for invalid data or empty cart
2149
+ * @throws StorefrontError for inventory issues
2150
+ *
2151
+ * @example Basic usage with redirect
2152
+ * ```typescript
2153
+ * const { url } = await client.checkout.stripe({
2154
+ * customerData: {
2155
+ * first_name: "John",
2156
+ * last_name: "Doe",
2157
+ * email: "john@example.com",
2158
+ * address: "123 Main St",
2159
+ * postal_code: "00100",
2160
+ * city: "Helsinki",
2161
+ * phone: "+358401234567"
2162
+ * },
2163
+ * shipmentMethod: {
2164
+ * shipmentMethodId: "ship_123",
2165
+ * pickupId: null
2166
+ * },
2167
+ * orderId: "order_abc123",
2168
+ * successUrl: "https://mystore.com/success",
2169
+ * cancelUrl: "https://mystore.com/cancel"
2170
+ * }, {
2171
+ * cartId: "cart_xyz", // For guest users
2172
+ * sessionId: "sess_123" // For logged-in users
2173
+ * });
2174
+ *
2175
+ * // Redirect to Stripe
2176
+ * window.location.href = url;
2177
+ * ```
2178
+ */
2179
+ stripe(params: CheckoutParams, options?: CheckoutOptions): Promise<StripeCheckoutResponse>;
2180
+ /**
2181
+ * Create a Paytrail checkout session.
2182
+ *
2183
+ * Returns payment providers for Finnish payment methods.
2184
+ * Cart items are validated and stock is reserved on the server.
2185
+ *
2186
+ * @param params - Checkout parameters (customer data, shipping, URLs)
2187
+ * @param options - Checkout options including cart/session context
2188
+ * @returns Paytrail response with available payment providers
2189
+ * @throws ValidationError for invalid data or empty cart
2190
+ * @throws StorefrontError for inventory issues
2191
+ *
2192
+ * @example Display payment providers
2193
+ * ```typescript
2194
+ * const response = await client.checkout.paytrail({
2195
+ * customerData: {
2196
+ * first_name: "Matti",
2197
+ * last_name: "Meikäläinen",
2198
+ * email: "matti@example.fi",
2199
+ * address: "Mannerheimintie 1",
2200
+ * postal_code: "00100",
2201
+ * city: "Helsinki",
2202
+ * phone: "+358401234567"
2203
+ * },
2204
+ * shipmentMethod: {
2205
+ * shipmentMethodId: "ship_123",
2206
+ * pickupId: "pickup_456" // For pickup points
2207
+ * },
2208
+ * orderId: "order_abc123",
2209
+ * successUrl: "https://mystore.com/success",
2210
+ * cancelUrl: "https://mystore.com/cancel"
2211
+ * }, {
2212
+ * cartId: "cart_xyz"
2213
+ * });
2214
+ *
2215
+ * // Group providers by type
2216
+ * const banks = response.providers.filter(p => p.group === "bank");
2217
+ * const mobile = response.providers.filter(p => p.group === "mobile");
2218
+ * const cards = response.providers.filter(p => p.group === "creditcard");
2219
+ * ```
2220
+ *
2221
+ * @example Submit payment form
2222
+ * ```typescript
2223
+ * const provider = response.providers.find(p => p.id === "nordea");
2224
+ *
2225
+ * // Create and submit a form
2226
+ * const form = document.createElement("form");
2227
+ * form.method = "POST";
2228
+ * form.action = provider.url;
2229
+ *
2230
+ * provider.parameters.forEach(({ name, value }) => {
2231
+ * const input = document.createElement("input");
2232
+ * input.type = "hidden";
2233
+ * input.name = name;
2234
+ * input.value = value;
2235
+ * form.appendChild(input);
2236
+ * });
2237
+ *
2238
+ * document.body.appendChild(form);
2239
+ * form.submit();
2240
+ * ```
2241
+ */
2242
+ paytrail(params: CheckoutParams, options?: CheckoutOptions): Promise<PaytrailCheckoutResponse>;
2243
+ };
2244
+ /**
2245
+ * Type for the checkout resource
2246
+ */
2247
+ type CheckoutResource = ReturnType<typeof createCheckoutResource>;
2248
+
2249
+ /**
2250
+ * The Storefront API client
2251
+ */
2252
+ interface StorefrontClient {
2253
+ /**
2254
+ * The configured API key (masked for security)
2255
+ */
2256
+ readonly apiKey: string;
2257
+ /**
2258
+ * The base URL for API requests
2259
+ */
2260
+ readonly baseUrl: string;
2261
+ /**
2262
+ * Store configuration resource
2263
+ */
2264
+ readonly store: StoreResource;
2265
+ /**
2266
+ * Products resource
2267
+ */
2268
+ readonly products: ProductsResource;
2269
+ /**
2270
+ * Categories resource
2271
+ */
2272
+ readonly categories: CategoriesResource;
2273
+ /**
2274
+ * Cart resource
2275
+ */
2276
+ readonly cart: CartResource;
2277
+ /**
2278
+ * Shipping resource
2279
+ */
2280
+ readonly shipping: ShippingResource;
2281
+ /**
2282
+ * Customer authentication and account management resource
2283
+ */
2284
+ readonly customer: CustomerResource;
2285
+ /**
2286
+ * Order resource for fetching order details
2287
+ */
2288
+ readonly order: OrderResource;
2289
+ /**
2290
+ * Checkout resource for payment processing
2291
+ */
2292
+ readonly checkout: CheckoutResource;
2293
+ }
2294
+ /**
2295
+ * Create a new Storefront API client
265
2296
  */
266
2297
  declare function createStorefrontClient(config: StorefrontClientConfig): StorefrontClient;
267
2298
 
2299
+ /**
2300
+ * Pricing Utilities
2301
+ *
2302
+ * Helper functions for calculating prices with sale logic.
2303
+ */
2304
+
2305
+ /**
2306
+ * Check if a sale is currently active based on start and end dates.
2307
+ *
2308
+ * @param startDate - Sale start date (ISO string, Date, null, or undefined)
2309
+ * @param endDate - Sale end date (ISO string, Date, null, or undefined)
2310
+ * @returns true if the sale is currently active
2311
+ *
2312
+ * @example
2313
+ * ```typescript
2314
+ * // No dates = always active
2315
+ * isSaleActive(null, null); // true
2316
+ *
2317
+ * // Only start date = active if past start
2318
+ * isSaleActive("2024-01-01", null); // true if today >= Jan 1
2319
+ *
2320
+ * // Both dates = active if within range
2321
+ * isSaleActive("2024-01-01", "2024-12-31"); // true if within range
2322
+ * ```
2323
+ */
2324
+ declare function isSaleActive(startDate: Date | string | null | undefined, endDate: Date | string | null | undefined): boolean;
2325
+ /**
2326
+ * Get price information for a product or variation.
2327
+ * Returns the effective price (sale or regular) and sale status.
2328
+ * All prices are in cents.
2329
+ *
2330
+ * @param product - The product to get price info for
2331
+ * @param variation - Optional variation (takes precedence over product price)
2332
+ * @returns Price information with effective price, original price, and sale status
2333
+ *
2334
+ * @example
2335
+ * ```typescript
2336
+ * // Product without variation
2337
+ * const priceInfo = getPriceInfo(product);
2338
+ * console.log(priceInfo.effectivePrice); // 1990 (cents)
2339
+ * console.log(priceInfo.isOnSale); // true
2340
+ *
2341
+ * // Product with selected variation
2342
+ * const priceInfo = getPriceInfo(product, selectedVariation);
2343
+ * ```
2344
+ */
2345
+ declare function getPriceInfo(product: ProductDetail, variation?: ProductVariation): PriceInfo;
2346
+
2347
+ /**
2348
+ * Cart Calculation Utilities
2349
+ *
2350
+ * Functions for calculating cart totals with campaign discounts.
2351
+ */
2352
+
2353
+ /**
2354
+ * Calculate cart totals with campaign discounts applied.
2355
+ *
2356
+ * Supports two campaign types:
2357
+ * - **FREE_SHIPPING**: Free shipping when cart total exceeds minimum spend
2358
+ * - **BUY_X_PAY_Y**: Buy X items, pay for Y (e.g., Buy 3 Pay 2 = 1 free item)
2359
+ *
2360
+ * @param items - Cart items to calculate
2361
+ * @param campaigns - Active campaigns to apply
2362
+ * @returns Calculation result with totals, savings, and free shipping status
2363
+ *
2364
+ * @example
2365
+ * ```typescript
2366
+ * const result = calculateCartWithCampaigns(cartItems, activeCampaigns);
2367
+ *
2368
+ * console.log(result.cartTotal); // 4990 (cents)
2369
+ * console.log(result.totalSavings); // 1990 (cents)
2370
+ * console.log(result.freeShipping.isEligible); // true
2371
+ *
2372
+ * // Render calculated items
2373
+ * result.calculatedItems.forEach(({ item, paidQuantity, freeQuantity }) => {
2374
+ * console.log(`${item.product.name}: ${paidQuantity} paid, ${freeQuantity} free`);
2375
+ * });
2376
+ * ```
2377
+ */
2378
+ declare function calculateCartWithCampaigns(items: CartItem[], campaigns: Campaign[]): CartCalculationResult;
2379
+
268
2380
  /**
269
2381
  * Base error class for all Storefront API errors
270
2382
  */
@@ -299,4 +2411,4 @@ declare class ValidationError extends StorefrontError {
299
2411
  constructor(message?: string);
300
2412
  }
301
2413
 
302
- export { AuthError, type BuyXPayYCampaign, type Campaign, type CampaignType, type CategoryReference, type FeatureFlags, type FetchOptions, type FreeShippingCampaign, NotFoundError, type PaymentConfig, RateLimitError, type ShipmentMethod, type StoreConfig, type StoreInfo, type StoreSeo, type StorefrontClient, type StorefrontClientConfig, StorefrontError, ValidationError, createStorefrontClient };
2414
+ export { type AddToCartParams, type AddToWishlistResponse, AuthError, type BuyXPayYCampaign, type CalculatedCartItem, type Campaign, type CampaignType, type CartCalculationResult, type CartItem, type CartResponse, type CartSessionOptions, type CartValidationChanges, type CartValidationResponse, type Category, type CategoryReference, type CategoryResponse, type CheckoutCustomerData, type CheckoutErrorCode, type CheckoutErrorDetails, type CheckoutOptions, type CheckoutParams, type CheckoutShipmentMethod, type ConfirmationItemType, type ConfirmationOrderCustomerData, type ConfirmationOrderLineItem, type ConfirmationOrderShipmentMethod, type ConfirmationOrderStatus, type Customer, type CustomerOrder, type CustomerWithCreatedAt, type CustomerWithEmailStatus, type CustomerWithVerification, type DeleteAccountResponse, type FeatureFlags, type FetchOptions, type FreeShippingCampaign, type FreeShippingStatus, type GetOrdersResponse, type GetUserResponse, type LoginOptions, type LoginResponse, type LoginVerificationRequiredResponse, type LogoutResponse, NotFoundError, type Order, type OrderLineItem, type OrderProductInfo, type OrderShipmentMethod, type OrderStatus, type PaymentConfig, type PaytrailCheckoutResponse, type PaytrailGroup, type PaytrailProvider, type PickupLocation, type PickupLocationOpeningHours, type PriceInfo, type Product, type ProductCountResponse, type ProductDetail, type ProductListParams, type ProductListResponse, type ProductSortOption, type ProductVariation, type ProductVariationListing, RateLimitError, type RegisterData, type RegisterResponse, type RemoveFromCartParams, type RemoveFromWishlistResponse, type ResendVerificationResponse, type ShipitShippingMethod, type ShipmentMethod, type ShipmentMethodsResponse, type ShipmentMethodsWithLocationsResponse, type StoreConfig, type StoreInfo, type StoreSeo, type StorefrontClient, type StorefrontClientConfig, StorefrontError, type StripeCheckoutResponse, type UpdateCartQuantityParams, type UpdateProfileData, type UpdateProfileResponse, ValidationError, type VariationOption, type VerifyEmailResponse, type WishlistItem, type WishlistProduct, type WishlistResponse, type WishlistVariation, type WishlistVariationOption, calculateCartWithCampaigns, createStorefrontClient, getPriceInfo, isSaleActive };