@misiki/gocommerce-connector 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.
@@ -1,2352 +1,2571 @@
1
1
  'use strict';
2
2
 
3
- // src/services/base.ts
4
- var API_PROXY_PREFIX = "/proxy/gocommerce";
3
+ // src/errors.ts
5
4
  var GoCommerceError = class extends Error {
5
+ status;
6
6
  code;
7
7
  details;
8
- status;
9
- constructor(message, code = "internal_error", status = 0, details) {
8
+ constructor(message, status, code, details) {
10
9
  super(message);
11
10
  this.name = "GoCommerceError";
12
- this.code = code;
13
11
  this.status = status;
12
+ this.code = code;
14
13
  this.details = details;
15
14
  }
16
15
  };
17
- var BaseService = class _BaseService {
18
- _fetch;
19
- static _credentials = {};
20
- static _languageCode;
21
- constructor(fetchFn) {
22
- this._fetch = fetchFn || ((...args) => globalThis.fetch(...args));
16
+ var NotSupportedError = class extends Error {
17
+ service;
18
+ method;
19
+ constructor(service, method, detail) {
20
+ super(`${service}.${method}() is not supported by GoCommerce${detail ? `: ${detail}` : "."}`);
21
+ this.name = "NotSupportedError";
22
+ this.service = service;
23
+ this.method = method;
23
24
  }
24
- setFetch(fetchFn) {
25
- this._fetch = fetchFn;
26
- return this;
25
+ };
26
+
27
+ // src/rest-guard.ts
28
+ var COLLECTION_SEGMENTS = /* @__PURE__ */ new Set([
29
+ "all",
30
+ "list",
31
+ "list-by-parent",
32
+ "list-public",
33
+ "latest",
34
+ "search",
35
+ "public",
36
+ "public-details",
37
+ "me",
38
+ "multiple"
39
+ ]);
40
+ var emptyResult = () => ({ data: [], count: 0, pageSize: 0, noOfPage: 0, page: 1 });
41
+ var addressesOneRecord = (url) => {
42
+ const segments = url.split("?")[0].split("/").filter(Boolean);
43
+ if (segments.length < 3) return false;
44
+ return !COLLECTION_SEGMENTS.has(segments[segments.length - 1].toLowerCase());
45
+ };
46
+ var reported = /* @__PURE__ */ new Set();
47
+ var report = (method, url) => {
48
+ const key = `${method} ${url.split("?")[0]}`;
49
+ if (reported.has(key)) return;
50
+ reported.add(key);
51
+ console.warn(
52
+ `[gocommerce] no native implementation for \`${key}\` \u2014 that is a Litekart REST path, and it was not called.`
53
+ );
54
+ };
55
+ var localResolver;
56
+ var resolveRestLocally = async (method, url) => {
57
+ if (method === "get") {
58
+ const local = await localResolver?.(url);
59
+ if (local !== void 0) return local;
60
+ }
61
+ report(method, url);
62
+ if (method !== "get" || addressesOneRecord(url)) {
63
+ throw new Error(`This feature is not available on this store (gocommerce).`);
64
+ }
65
+ return emptyResult();
66
+ };
67
+
68
+ // src/browser.ts
69
+ var inBrowser = () => typeof window !== "undefined" && typeof document !== "undefined";
70
+ function readLocal(key) {
71
+ if (!inBrowser()) return null;
72
+ try {
73
+ return window.localStorage.getItem(key);
74
+ } catch {
75
+ return null;
27
76
  }
28
- getFetch() {
29
- return this._fetch;
77
+ }
78
+ function writeLocal(key, value) {
79
+ if (!inBrowser()) return;
80
+ try {
81
+ window.localStorage.setItem(key, value);
82
+ } catch {
30
83
  }
31
- /**
32
- * The fetch a GoCommerce call actually goes out on.
33
- *
34
- * In the browser it is whatever was handed in, against this storefront's own origin. On the
35
- * server it is deliberately the platform's, not SvelteKit's: a universal `+page.ts` load is
36
- * given a `fetch` that simulates a browser's CORS check, and GoCommerce sends no
37
- * `Access-Control-Allow-Origin`, so the same product page that renders from a `+page.server.ts`
38
- * would throw from a `+page.ts`. Nothing is lost by stepping around it — SvelteKit's fetch adds
39
- * cookie forwarding and internal routing, and both are about this storefront's own origin, not
40
- * a separate API host.
41
- */
42
- transport() {
43
- return _BaseService.isBrowser() ? this._fetch : (...args) => globalThis.fetch(...args);
84
+ }
85
+ function removeLocal(key) {
86
+ if (!inBrowser()) return;
87
+ try {
88
+ window.localStorage.removeItem(key);
89
+ } catch {
90
+ }
91
+ }
92
+ function readJSON(key) {
93
+ const raw = readLocal(key);
94
+ if (!raw) return null;
95
+ try {
96
+ return JSON.parse(raw);
97
+ } catch {
98
+ return null;
99
+ }
100
+ }
101
+ var YEAR = 60 * 60 * 24 * 365;
102
+ function setCookie(name, value, maxAge = YEAR) {
103
+ if (!inBrowser()) return;
104
+ document.cookie = `${name}=${value}; path=/; max-age=${maxAge}; samesite=lax`;
105
+ }
106
+ function clearCookie(name) {
107
+ if (!inBrowser()) return;
108
+ document.cookie = `${name}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
109
+ }
110
+ function readCookie(name) {
111
+ if (!inBrowser()) return null;
112
+ for (const pair of document.cookie.split(";")) {
113
+ const at = pair.indexOf("=");
114
+ if (at < 0) continue;
115
+ if (pair.slice(0, at).trim() === name) return pair.slice(at + 1).trim();
116
+ }
117
+ return null;
118
+ }
119
+ var TOKEN = "gocommerce_token";
120
+ var sessionToken = () => readLocal(TOKEN);
121
+ function toMe(c) {
122
+ const [firstName, ...rest] = (c.name ?? "").trim().split(/\s+/);
123
+ return {
124
+ id: String(c.id),
125
+ userId: String(c.id),
126
+ email: c.email,
127
+ phone: c.phone || null,
128
+ firstName: firstName || "",
129
+ lastName: rest.join(" "),
130
+ name: c.name ?? "",
131
+ fullName: c.name ?? "",
132
+ avatar: null,
133
+ role: "USER",
134
+ emailVerified: c.email_verified,
135
+ storeId: null
136
+ };
137
+ }
138
+ function startSession(auth) {
139
+ writeLocal(TOKEN, auth.token);
140
+ const me = toMe(auth.record);
141
+ const expires = Math.max(60, Math.floor((Date.parse(auth.expires_at) - Date.now()) / 1e3)) || YEAR;
142
+ setCookie("me", encodeURIComponent(JSON.stringify(me)), expires);
143
+ setCookie("connect.sid", "gocommerce", expires);
144
+ return me;
145
+ }
146
+ function updateMe(c) {
147
+ const me = toMe(c);
148
+ setCookie("me", encodeURIComponent(JSON.stringify(me)));
149
+ return me;
150
+ }
151
+ function endSession() {
152
+ removeLocal(TOKEN);
153
+ clearCookie("me");
154
+ clearCookie("connect.sid");
155
+ }
156
+ function currentMe() {
157
+ const raw = readCookie("me");
158
+ if (!raw) return null;
159
+ try {
160
+ return JSON.parse(decodeURIComponent(raw));
161
+ } catch {
162
+ return null;
163
+ }
164
+ }
165
+ function storedCartId() {
166
+ const v = readLocal("cart_id");
167
+ if (!v || v === "undefined" || v === "null") return null;
168
+ return v;
169
+ }
170
+ var rememberCartId = (id) => writeLocal("cart_id", id);
171
+ var extrasKey = (cartId) => `gocommerce_cart_${cartId}`;
172
+ var cartExtras = (cartId) => readJSON(extrasKey(cartId)) ?? {};
173
+ function saveCartExtras(cartId, patch) {
174
+ const next = { ...cartExtras(cartId), ...patch };
175
+ writeLocal(extrasKey(cartId), JSON.stringify(next));
176
+ return next;
177
+ }
178
+ var forgetCartExtras = (cartId) => removeLocal(extrasKey(cartId));
179
+ var ORDERS = "gocommerce_orders";
180
+ var placedOrders = () => readJSON(ORDERS) ?? [];
181
+ function rememberOrder(o) {
182
+ const kept = placedOrders().filter((p) => p.number !== o.number);
183
+ writeLocal(ORDERS, JSON.stringify([o, ...kept].slice(0, 50)));
184
+ }
185
+ var placedOrder = (number) => placedOrders().find((p) => p.number === number);
186
+ var placedOrderForCart = (cartId) => placedOrders().find((p) => p.cartId === cartId);
187
+ var placedOrderByReference = (reference) => placedOrders().find((p) => p.reference === reference);
188
+ var WISHLIST = "gocommerce_wishlist";
189
+ var wishlistToken = () => readLocal(WISHLIST);
190
+ var rememberWishlistToken = (token) => writeLocal(WISHLIST, token);
191
+ var forgetWishlistToken = () => removeLocal(WISHLIST);
192
+
193
+ // src/services/base.service.ts
194
+ var BaseService = class _BaseService {
195
+ static _credentials = { apiUrl: "" };
196
+ _fetch;
197
+ constructor(fetchFn) {
198
+ this._fetch = fetchFn ?? ((input, init) => globalThis.fetch(input, init));
44
199
  }
45
- /**
46
- * The hook the storefront's `src/lib/core/connectors/init.ts` calls with `PUBLIC_GOCOMMERCE_*`. Merges, so a
47
- * later call with a subset never erases the base url an earlier one established.
48
- */
49
200
  static setCredentials(creds) {
50
201
  _BaseService._credentials = { ..._BaseService._credentials, ...creds };
51
202
  }
52
203
  static getCredentials() {
53
204
  return _BaseService._credentials;
54
205
  }
55
- static setBaseUrl(url) {
56
- if (url) _BaseService._credentials.apiUrl = url;
57
- }
58
- /** Trailing slashes stripped so `${base}/api/products` never doubles up. */
59
- static getBaseUrl() {
60
- return (_BaseService._credentials.apiUrl || "").replace(/\/+$/, "");
61
- }
62
- static setLanguageCode(code) {
63
- _BaseService._languageCode = code;
64
- }
65
- static getLanguageCode() {
66
- return _BaseService._languageCode;
67
- }
68
- setBaseUrl(url) {
69
- _BaseService.setBaseUrl(url);
70
- return this;
71
- }
72
- getBaseUrl() {
73
- return _BaseService.getBaseUrl();
206
+ get creds() {
207
+ return _BaseService._credentials;
74
208
  }
75
209
  /**
76
- * Where a request for `path` actually goes.
77
- *
78
- * GoCommerce sends no CORS headers and answers a preflight with 405, so a browser cannot reach
79
- * it cross-origin at all — and neither can a universal `+page.ts` load, because SvelteKit
80
- * simulates the same CORS check server-side for consistency. So anything the browser issues goes
81
- * through this storefront's own origin (`src/routes/proxy/gocommerce/[...path]`), which is
82
- * same-origin and needs no headers from the API.
83
- *
84
- * On the server there is no such rule, and the extra hop through the storefront's own handler
85
- * would be a request the process makes to itself, so it calls the API directly.
210
+ * The engine's base URL from wherever this code runs. In the browser a
211
+ * configured proxy path wins, because the engine answers no CORS preflight.
86
212
  */
87
- static apiUrl(path) {
88
- if (/^https?:\/\//i.test(path)) return path;
89
- const suffix = path.startsWith("/") ? path : `/${path}`;
90
- if (_BaseService.isBrowser()) return `${API_PROXY_PREFIX}${suffix}`;
91
- const base = _BaseService.getBaseUrl();
92
- if (!base) {
93
- throw new GoCommerceError("PUBLIC_GOCOMMERCE_API_URL is not configured \u2014 add it to .env (see docs/GOCOMMERCE.md).", "not_ready");
213
+ engineBase() {
214
+ const { apiUrl, proxyPath } = this.creds;
215
+ if (proxyPath && typeof window !== "undefined" && window.location) {
216
+ return new URL(proxyPath, window.location.origin).href.replace(/\/+$/, "");
94
217
  }
95
- return `${base}${suffix}`;
96
- }
97
- /**
98
- * Where an `<img>` points.
99
- *
100
- * Media urls come back site-relative for files this store holds (`/media/42.jpg`). Unlike an API
101
- * call, the consumer is always the browser — a server-rendered `<img src>` is still fetched by
102
- * it — so this always resolves through the proxy, and the picture loads wherever the API happens
103
- * to be reachable from. A url that is already absolute belongs to someone else's host and is
104
- * left exactly as it is.
105
- */
106
- static mediaUrl(path) {
107
- if (/^https?:\/\//i.test(path)) return path;
108
- return `${API_PROXY_PREFIX}${path.startsWith("/") ? path : `/${path}`}`;
218
+ const url = (apiUrl ?? "").trim();
219
+ if (!url) {
220
+ throw new GoCommerceError(
221
+ "PUBLIC_GOCOMMERCE_API_URL is not set, so this storefront does not know where its commerce engine is. Point it at a running GoCommerce, e.g. http://127.0.0.1:8080.",
222
+ 0
223
+ );
224
+ }
225
+ return url.replace(/\/+$/, "");
109
226
  }
110
- static isBrowser() {
111
- return typeof window !== "undefined" && typeof window.document !== "undefined";
227
+ /** An absolute engine URL for a path and query, without sending anything. */
228
+ engineURL(path, query) {
229
+ return this.engineBase() + path + qs(query);
112
230
  }
113
231
  /**
114
- * One request against the GoCommerce API.
232
+ * One request to the engine, envelope and all.
115
233
  *
116
- * Unwraps `{ data, meta }` and turns `{ error: { code, message } }` into a thrown
117
- * GoCommerceError carrying the server's own wording — a 409 at checkout says which line went
118
- * stale, and that sentence is what the shopper needs to see.
234
+ * The body is read as text first, so a proxy's HTML error page is reported
235
+ * as what it is rather than as a JSON parse error three frames away.
119
236
  */
120
- async api(method, path, body, headers = {}) {
121
- const url = _BaseService.apiUrl(path);
122
- const lang = _BaseService.getLanguageCode();
237
+ async engine(path, req = {}) {
238
+ const url = this.engineURL(path, req.query);
239
+ const headers = { Accept: "application/json", ...req.headers };
240
+ if (req.body !== void 0) headers["Content-Type"] = "application/json";
241
+ if (this.creds.store) headers["X-Store"] = this.creds.store;
242
+ if (req.auth) {
243
+ const token = sessionToken();
244
+ if (!token) throw new GoCommerceError("Please sign in to continue.", 401, "unauthorized");
245
+ headers.Authorization = `Bearer ${token}`;
246
+ }
247
+ const init = {
248
+ method: req.method ?? "GET",
249
+ headers,
250
+ body: req.body === void 0 ? void 0 : JSON.stringify(req.body)
251
+ };
123
252
  let res;
124
253
  try {
125
- res = await this.transport()(url, {
126
- method,
127
- headers: {
128
- Accept: "application/json",
129
- ...body === void 0 ? {} : { "Content-Type": "application/json" },
130
- ...lang ? { "Accept-Language": lang } : {},
131
- ...headers
132
- },
133
- ...body === void 0 ? {} : { body: JSON.stringify(body) }
134
- });
254
+ res = await this._fetch.call(globalThis, url, init);
135
255
  } catch (cause) {
136
- const reason = cause?.cause?.code ?? cause?.message ?? "unknown error";
137
- throw new GoCommerceError(
138
- `Could not reach the GoCommerce server at ${_BaseService.getBaseUrl() || url} \u2014 ${reason}. Is it running?`,
139
- "not_ready",
140
- 0,
141
- cause
142
- );
256
+ if (typeof window === "undefined" && /CORS/i.test(String(cause?.message))) {
257
+ try {
258
+ res = await globalThis.fetch(url, init);
259
+ } catch (again) {
260
+ throw unreachable(this.engineBase(), again);
261
+ }
262
+ } else {
263
+ throw unreachable(this.engineBase(), cause);
264
+ }
143
265
  }
266
+ return this.unwrap(res);
267
+ }
268
+ /** The envelope opened: the payload, or the engine's error as a GoCommerceError. */
269
+ async unwrap(res) {
144
270
  const text = await res.text();
145
- let parsed = void 0;
271
+ let parsed = null;
146
272
  if (text) {
147
273
  try {
148
274
  parsed = JSON.parse(text);
149
275
  } catch {
150
- throw new GoCommerceError(`GoCommerce returned a non-JSON response for ${method} ${path} (${res.status}).`, "internal_error", res.status);
276
+ throw new GoCommerceError(
277
+ `The commerce engine answered ${res.status} with something that is not JSON: ${text.slice(0, 120)}`,
278
+ res.status
279
+ );
151
280
  }
152
281
  }
153
- const envelope = parsed ?? {};
154
- if (!res.ok || envelope.error) {
155
- const error = envelope.error;
282
+ if (!res.ok) {
283
+ const err = parsed?.error ?? {};
156
284
  throw new GoCommerceError(
157
- error?.message || envelope.message || `GoCommerce request failed: ${method} ${path} (${res.status}).`,
158
- error?.code || "internal_error",
285
+ err.message ?? `The commerce engine answered ${res.status}.`,
159
286
  res.status,
160
- error?.details
287
+ err.code,
288
+ err.details
161
289
  );
162
290
  }
163
- return { data: envelope.data, meta: envelope.meta };
291
+ return parsed ?? { data: null };
292
+ }
293
+ /** The bare payload, for the many callers that never look at `meta`. */
294
+ async data(path, req = {}) {
295
+ return (await this.engine(path, req)).data;
164
296
  }
165
297
  /**
166
- * Litekart-era raw-url reads. Deliberately not routed to GoCommerce: a bare `/api/...` here means
167
- * a path from the storefront's own REST API, which rest-guard.ts answers from local data or
168
- * reports. Absolute urls pass straight through.
298
+ * Prices a cart at the signed-in shopper's customer-group prices. The
299
+ * engine does this only for an account whose email is confirmed (403
300
+ * otherwise), and the cart stays the shopper's either way — so a refusal
301
+ * is not an error, and neither is a build without ext/identity.
169
302
  */
170
- async get(url) {
171
- const res = await this._fetch(url, { headers: { Accept: "application/json" } });
172
- return await res.json();
303
+ async claimCartForAccount(cartId) {
304
+ try {
305
+ await this.engine("/x/identity/me/carts", { method: "POST", body: { cart_id: cartId }, auth: true });
306
+ } catch {
307
+ }
173
308
  }
174
- async post(url, data) {
175
- const res = await this._fetch(url, {
176
- method: "POST",
177
- headers: { "Content-Type": "application/json", Accept: "application/json" },
178
- body: JSON.stringify(data)
179
- });
180
- return await res.json();
309
+ // ------------------------------------------------------------ Litekart verbs
310
+ /**
311
+ * The family's path-addressed verbs. An absolute URL is fetched as-is; a
312
+ * relative one is a Litekart REST path, answered from the storefront's own
313
+ * data where it has some and refused otherwise (rest-guard.ts).
314
+ */
315
+ get(path) {
316
+ return this.raw("get", path);
181
317
  }
182
- async put(url, data) {
183
- const res = await this._fetch(url, {
184
- method: "PUT",
185
- headers: { "Content-Type": "application/json", Accept: "application/json" },
186
- body: JSON.stringify(data)
187
- });
188
- return await res.json();
318
+ post(path, data) {
319
+ return this.raw("post", path, data);
189
320
  }
190
- async patch(url, data) {
191
- const res = await this._fetch(url, {
192
- method: "PATCH",
193
- headers: { "Content-Type": "application/json", Accept: "application/json" },
194
- body: JSON.stringify(data)
195
- });
196
- return await res.json();
321
+ put(path, data) {
322
+ return this.raw("put", path, data);
197
323
  }
198
- async delete(url) {
199
- const res = await this._fetch(url, { method: "DELETE", headers: { Accept: "application/json" } });
200
- return await res.json();
324
+ patch(path, data) {
325
+ return this.raw("patch", path, data);
201
326
  }
202
- };
203
-
204
- // src/services/static-store.ts
205
- var provider;
206
- var setStaticStore = (fn) => {
207
- provider = fn;
208
- };
209
- var hasStaticStore = () => Boolean(provider);
210
- var IMPOSSIBLE_FEATURES = {
211
- accounts: { active: false },
212
- isDiscountCoupons: { active: false },
213
- isWishlist: { active: false },
214
- isProductReviewsAndRatings: { active: false },
215
- isMultiVendor: { active: false }
216
- };
217
- var readStaticStore = async () => {
218
- if (!provider) return void 0;
219
- const store = await provider();
220
- if (!store) return store;
327
+ delete(path) {
328
+ return this.raw("delete", path);
329
+ }
330
+ async raw(method, path, data) {
331
+ if (!/^https?:\/\//i.test(path)) return await resolveRestLocally(method, path);
332
+ const res = await this._fetch.call(globalThis, path, {
333
+ method: method.toUpperCase(),
334
+ headers: { Accept: "application/json", ...data === void 0 ? {} : { "Content-Type": "application/json" } },
335
+ body: data === void 0 ? void 0 : JSON.stringify(data)
336
+ });
337
+ const body = await res.json().catch(() => ({}));
338
+ if (!res.ok)
339
+ throw new GoCommerceError(body?.error?.message ?? `Request failed with status ${res.status}`, res.status);
340
+ return body;
341
+ }
342
+ };
343
+ var unreachable = (base, cause) => new GoCommerceError(`Could not reach the commerce engine at ${base}: ${cause?.message ?? cause}`, 0);
344
+ function qs(query) {
345
+ if (!query) return "";
346
+ const sp = new URLSearchParams();
347
+ for (const [key, value] of Object.entries(query)) {
348
+ if (value === void 0 || value === null || value === "") continue;
349
+ if (Array.isArray(value)) for (const v of value) sp.append(key, String(v));
350
+ else sp.append(key, String(value));
351
+ }
352
+ const s = sp.toString();
353
+ return s ? `?${s}` : "";
354
+ }
355
+ function toPage(env, map) {
356
+ const rows = env.data ?? [];
357
+ const meta = env.meta;
221
358
  return {
222
- ...store,
223
- plugins: { ...store.plugins ?? {}, ...IMPOSSIBLE_FEATURES }
359
+ data: rows.map(map),
360
+ count: meta?.total ?? rows.length,
361
+ pageSize: meta?.limit ?? rows.length,
362
+ noOfPage: meta?.total_pages ?? 1,
363
+ page: meta?.page ?? 1
224
364
  };
225
- };
226
- var readStaticStoreDetails = readStaticStore;
365
+ }
366
+ var emptyPage = () => ({ data: [], count: 0, pageSize: 0, noOfPage: 0, page: 1 });
227
367
 
228
- // src/services/money.ts
229
- var DEFAULT_FRACTION_DIGITS = 2;
230
- var fractionDigitsCache = /* @__PURE__ */ new Map();
231
- var currencyFractionDigits = (currencyCode) => {
232
- if (!currencyCode) return DEFAULT_FRACTION_DIGITS;
233
- const code = currencyCode.toUpperCase();
234
- const cached = fractionDigitsCache.get(code);
235
- if (cached !== void 0) return cached;
236
- let digits = DEFAULT_FRACTION_DIGITS;
237
- try {
238
- const resolved = new Intl.NumberFormat("en", { style: "currency", currency: code }).resolvedOptions().maximumFractionDigits;
239
- if (typeof resolved === "number") digits = resolved;
240
- } catch {
241
- }
242
- fractionDigitsCache.set(code, digits);
243
- return digits;
244
- };
245
- var fromMoney = (money) => {
246
- if (!money || typeof money.amount_minor !== "number" || !Number.isFinite(money.amount_minor)) return 0;
247
- const digits = currencyFractionDigits(money.currency);
248
- return digits === 0 ? money.amount_minor : money.amount_minor / 10 ** digits;
249
- };
368
+ // src/money.ts
369
+ var ZERO_DECIMAL = /* @__PURE__ */ new Set([
370
+ "BIF",
371
+ "CLP",
372
+ "DJF",
373
+ "GNF",
374
+ "ISK",
375
+ "JPY",
376
+ "KMF",
377
+ "KRW",
378
+ "PYG",
379
+ "RWF",
380
+ "UGX",
381
+ "VND",
382
+ "VUV",
383
+ "XAF",
384
+ "XOF",
385
+ "XPF"
386
+ ]);
387
+ var THREE_DECIMAL = /* @__PURE__ */ new Set(["BHD", "IQD", "JOD", "KWD", "LYD", "OMR", "TND"]);
388
+ function currencyExponent(code) {
389
+ const c = (code ?? "").toUpperCase();
390
+ if (ZERO_DECIMAL.has(c)) return 0;
391
+ if (THREE_DECIMAL.has(c)) return 3;
392
+ return 2;
393
+ }
394
+ function toMajor(money) {
395
+ if (!money) return 0;
396
+ return minorToMajor(money.amount_minor, money.currency);
397
+ }
398
+ function minorToMajor(minor, currency) {
399
+ if (minor === null || minor === void 0 || !Number.isFinite(minor)) return 0;
400
+ const exp = currencyExponent(currency);
401
+ if (exp === 0) return minor;
402
+ return Number((minor / 10 ** exp).toFixed(exp));
403
+ }
404
+ function toMinor(amount, currency) {
405
+ const exp = currencyExponent(currency);
406
+ return Math.round(amount * 10 ** exp);
407
+ }
250
408
 
251
- // src/services/mappers.ts
252
- var PAGE_SIZE = 20;
253
- var MAX_LIMIT = 200;
254
- var UNTRACKED_STOCK = 999;
255
- var paginated = (data, count, page = 1, pageSize = PAGE_SIZE) => ({
256
- data,
257
- count,
258
- pageSize,
259
- noOfPage: Math.ceil(count / pageSize) || (count ? 1 : 0),
260
- page
261
- });
262
- var emptyPage = (page = 1, pageSize = PAGE_SIZE) => ({
263
- data: [],
264
- count: 0,
265
- pageSize,
266
- noOfPage: 0,
267
- page
268
- });
269
- var fromListMeta = (data, meta, fallbackPage = 1) => {
270
- const count = meta?.total ?? data.length;
271
- const pageSize = meta?.limit || data.length || PAGE_SIZE;
272
- return {
273
- data,
274
- count,
275
- pageSize,
276
- noOfPage: meta?.total_pages ?? (Math.ceil(count / pageSize) || (count ? 1 : 0)),
277
- page: meta?.page ?? fallbackPage
409
+ // src/map.ts
410
+ var str = (v) => v === null || v === void 0 ? "" : String(v);
411
+ var arr = (v) => v ?? [];
412
+ var liveVariants = (p) => arr(p.variants).filter((v) => v.active);
413
+ function variantImages(v) {
414
+ const out = [];
415
+ for (const img of [v.image, ...arr(v.images)]) {
416
+ if (img?.url && (img.kind ?? "image") === "image" && !out.includes(img.url)) out.push(img.url);
417
+ }
418
+ return out;
419
+ }
420
+ function productImages(p) {
421
+ const out = [];
422
+ const push = (url) => {
423
+ if (url && !out.includes(url)) out.push(url);
278
424
  };
279
- };
280
- var absoluteMedia = (url) => url ? BaseService.mediaUrl(url) : null;
281
- var activeVariants = (product) => (product?.variants || []).filter((v) => v?.active !== false);
282
- var primaryVariant = (product) => activeVariants(product)[0] || (product?.variants || [])[0];
283
- var variantStock = (variant) => {
284
- if (!variant) return 0;
285
- if (variant.track_inventory === false) return UNTRACKED_STOCK;
286
- const available = Math.max(0, variant.available ?? 0);
287
- return available === 0 && variant.continue_selling ? UNTRACKED_STOCK : available;
288
- };
289
- var productImages = (product) => {
290
- const seen = /* @__PURE__ */ new Set();
291
- const featured = absoluteMedia(product?.image_url);
292
- if (featured) seen.add(featured);
293
- for (const variant of product?.variants || []) {
294
- const url = absoluteMedia(variant?.image?.url);
295
- if (url) seen.add(url);
296
- }
297
- return [...seen];
298
- };
299
- var flattenMetadata = (metadata) => {
300
- if (!metadata || typeof metadata !== "object") return null;
301
- const out = {};
302
- const printable = (value) => {
303
- if (value === null || value === void 0 || value === "") return void 0;
304
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return String(value);
305
- if (Array.isArray(value)) {
306
- const items = value.map(printable).filter(Boolean);
307
- return items.length ? items.join(", ") : void 0;
308
- }
309
- return void 0;
310
- };
311
- const walk = (node, namespace = "") => {
312
- for (const [key, value] of Object.entries(node)) {
313
- const text = printable(value);
314
- if (text !== void 0) {
315
- out[key in out && namespace ? `${namespace} ${key}` : key] = text;
316
- continue;
317
- }
318
- if (value && typeof value === "object" && !Array.isArray(value)) walk(value, key);
319
- }
320
- };
321
- walk(metadata);
322
- return Object.keys(out).length ? out : null;
323
- };
324
- var optionValueId = (product, optionIndex, value) => product?.options?.[optionIndex]?.values?.find((v) => v.value === value)?.id ?? `${optionIndex}-${value}`;
325
- var mapVariant = (product, variant) => {
326
- const price = fromMoney(variant.price);
327
- const compareAt = fromMoney(variant.compare_at_price);
328
- const image = absoluteMedia(variant.image?.url) || absoluteMedia(product.image_url);
425
+ push(p.image_url);
426
+ for (const v of arr(p.variants)) for (const url of variantImages(v)) push(url);
427
+ return out;
428
+ }
429
+ function toVariant(v, p, optionless) {
430
+ const images = variantImages(v);
431
+ const options = arr(p.options);
329
432
  return {
330
- id: variant.id,
331
- // The PDP prints this as the heading whenever it is not 'default'. GoCommerce labels a variant
332
- // by its options ("M / Black") and leaves that empty for a product that has none — where the
333
- // product's own title is the right heading, and the SKU would be a code shown to a shopper.
334
- title: variant.label || (variant.options || []).join(" / ") || product.title || "default",
335
- productId: product.id,
336
- sku: variant.sku || null,
337
- barcode: variant.barcode || null,
338
- batchNo: null,
339
- stock: variantStock(variant),
340
- allowBackorder: Boolean(variant.continue_selling),
341
- manageInventory: variant.track_inventory !== false,
342
- hsCode: variant.hs_code || null,
343
- originCountry: variant.origin_country || null,
344
- midCode: null,
345
- material: null,
346
- weight: variant.weight ?? null,
347
- length: null,
348
- height: null,
349
- width: null,
350
- price,
351
- costPerItem: 0,
352
- mfgDate: null,
353
- expiryDate: null,
354
- returnAllowed: false,
355
- replaceAllowed: false,
356
- // No compare-at price recorded means nothing is on sale; mrp equals price so the components
357
- // print one number instead of a struck-through duplicate.
358
- mrp: compareAt > price ? compareAt : price,
359
- img: image,
360
- description: null,
361
- storeId: null,
362
- len: null,
363
- rank: variant.position ?? 0,
364
- shippingWeight: null,
365
- shippingHeight: null,
366
- shippingLen: null,
367
- shippingWidth: null,
368
- shippingCost: null,
369
- metadata: variant.metadata ?? null,
370
- variantRank: variant.position ?? 0,
371
- // A variant's `options` are the VALUES, positionally aligned with the product's option list.
372
- options: (variant.options || []).map((value, index) => ({
373
- id: optionValueId(product, index, value),
374
- optionId: product.options?.[index]?.id ?? index,
375
- value,
376
- variantId: variant.id
377
- }))
433
+ id: str(v.id),
434
+ productId: str(v.product_id),
435
+ // The storefront picks the default variant of an optionless product by
436
+ // this exact title, and hides the variant name when it sees it.
437
+ title: optionless ? "default" : v.label || v.sku,
438
+ sku: v.sku,
439
+ barcode: v.barcode ?? null,
440
+ price: toMajor(v.price),
441
+ mrp: toMajor(v.compare_at_price ?? v.price),
442
+ // The engine's own vocabulary, unchanged: `available` is on hand minus
443
+ // reserved; an untracked variant is never managed, so its count is moot.
444
+ stock: v.active ? v.available : 0,
445
+ manageInventory: v.active ? v.track_inventory : true,
446
+ allowBackorder: v.active && v.continue_selling,
447
+ active: v.active,
448
+ weight: v.weight_grams ?? null,
449
+ length: v.dimensions?.length_mm ?? null,
450
+ width: v.dimensions?.width_mm ?? null,
451
+ height: v.dimensions?.height_mm ?? null,
452
+ images: images.join(","),
453
+ img: images[0] ?? null,
454
+ image: images[0] ?? null,
455
+ thumbnail: images[0] ?? null,
456
+ // Values in option order — `options[i]` answers `p.options[i]`.
457
+ options: arr(v.options).map((value, i) => ({ optionId: str(options[i]?.id), value })),
458
+ metadata: v.metadata ?? null
378
459
  };
379
- };
380
- var mapProduct = (product) => {
381
- if (!product) return null;
382
- const variants = activeVariants(product);
383
- const priced = variants.length ? variants : product.variants || [];
384
- const prices = priced.map((v) => fromMoney(v.price)).filter((n) => Number.isFinite(n));
385
- const price = prices.length ? Math.min(...prices) : 0;
386
- const compareAtPrices = priced.map((v) => fromMoney(v.compare_at_price)).filter((n) => n > 0);
387
- const mrp = compareAtPrices.length ? Math.max(...compareAtPrices) : price;
388
- const images = productImages(product);
389
- const featured = images[0] || null;
390
- const first = primaryVariant(product);
460
+ }
461
+ function toProduct(p, extra = {}) {
462
+ const live = liveVariants(p);
463
+ const lead = live[0] ?? arr(p.variants)[0];
464
+ const optionless = arr(p.options).length === 0;
465
+ const images = productImages(p);
466
+ const prices = live.map((v) => toMajor(v.price));
467
+ const tracked = live.filter((v) => v.track_inventory);
468
+ const category = p.category;
469
+ const tags = arr(p.tags);
391
470
  return {
392
- id: product.id,
393
- title: product.title,
394
- slug: product.slug,
395
- description: product.description || "",
396
- price,
397
- mrp,
398
- featuredImage: featured,
399
- active: product.status === "active",
400
- status: product.status === "active" ? "published" : product.status || "draft",
401
- type: "physical",
402
- vendorId: product.vendor || "",
403
- categoryId: product.category?.id ?? null,
404
- currency: product.currency || null,
405
- instructions: null,
406
- hsnCode: first?.hs_code || null,
407
- // The components read this as a comma-joined list, the way Litekart serves it.
471
+ id: str(p.id),
472
+ slug: p.slug,
473
+ title: p.title,
474
+ name: p.title,
475
+ subtitle: null,
476
+ description: p.description ?? "",
477
+ status: p.status === "active" ? "published" : p.status,
478
+ active: p.status === "active",
479
+ type: p.product_type ?? "",
480
+ currency: p.currency,
481
+ currencyCode: p.currency,
482
+ price: lead ? toMajor(lead.price) : 0,
483
+ mrp: lead ? toMajor(lead.compare_at_price ?? lead.price) : 0,
484
+ minPrice: prices.length ? Math.min(...prices) : 0,
485
+ maxPrice: prices.length ? Math.max(...prices) : 0,
486
+ sku: lead?.sku ?? null,
487
+ barcode: lead?.barcode ?? null,
488
+ weight: lead?.weight_grams ?? null,
489
+ originCountry: lead?.origin_country ?? null,
490
+ thumbnail: images[0] ?? null,
491
+ image_url: images[0] ?? null,
408
492
  images: images.join(","),
409
- thumbnail: featured,
410
- keywords: (product.tags || []).join(",") || null,
411
- link: null,
412
- metaTitle: product.seo_title || null,
413
- metaDescription: product.seo_description || null,
414
- subtitle: product.product_type || null,
415
- popularity: 0,
416
- rank: 0,
417
- expiryDate: null,
418
- weight: first?.weight ?? null,
419
- mfgDate: null,
420
- costPerItem: 0,
421
- sku: first?.sku || null,
422
- stock: priced.reduce((sum, v) => sum + variantStock(v), 0),
423
- allowBackorder: Boolean(first?.continue_selling),
424
- manageInventory: first?.track_inventory !== false,
425
- shippingWeight: null,
426
- shippingHeight: null,
427
- shippingLen: null,
428
- shippingWidth: null,
429
- height: null,
430
- width: null,
431
- len: null,
432
- barcode: first?.barcode || null,
433
- shippingCost: null,
434
- returnAllowed: false,
435
- replaceAllowed: false,
436
- originCountry: first?.origin_country || null,
437
- weightUnit: first?.weight_unit || "g",
438
- dimensionUnit: "cm",
439
- metadata: flattenMetadata(product.metadata),
440
- collectionId: product.collections?.[0]?.id ?? null,
441
- tags: product.tags || [],
442
- vendor: product.vendor || null,
443
- categories: product.category ? [{ category: { id: product.category.id, name: product.category.title, slug: product.category.slug } }] : [],
444
- createdAt: product.created_at || null,
445
- updatedAt: product.updated_at || null,
446
- options: (product.options || []).map((option) => ({
447
- id: option.id,
448
- title: option.name,
449
- type: "radio",
450
- values: (option.values || []).map((v) => ({ id: v.id, value: v.value }))
493
+ imageList: images,
494
+ // Product-level stock is what a card shows before a variant is picked:
495
+ // buyable when any live variant is, counted only where counting means
496
+ // something.
497
+ manageInventory: live.length > 0 && tracked.length === live.length,
498
+ allowBackorder: live.some((v) => v.continue_selling),
499
+ stock: tracked.reduce((n, v) => n + Math.max(0, v.available), 0),
500
+ hasStock: live.some((v) => !v.track_inventory || v.continue_selling || v.available > 0),
501
+ categoryId: category ? str(category.id) : null,
502
+ category: category ? { id: str(category.id), name: category.title, slug: category.slug } : null,
503
+ categories: category ? [{ category: { id: str(category.id), name: category.title, slug: category.slug } }] : [],
504
+ categoryHierarchy: extra.categoryHierarchy ?? (category ? [{ name: category.title, slug: category.slug }] : []),
505
+ collections: arr(p.collections).map((c) => ({ id: str(c.id), name: c.title, slug: c.slug })),
506
+ // Free text on the engine's product, not a vendor record.
507
+ vendor: p.vendor ? { businessName: p.vendor } : null,
508
+ productTags: tags.join(","),
509
+ keywords: tags.join(","),
510
+ metaTitle: p.seo_title || p.title,
511
+ metaDescription: p.seo_description || null,
512
+ link: `/products/${p.slug}`,
513
+ options: arr(p.options).map((o) => ({
514
+ id: str(o.id),
515
+ title: o.name,
516
+ name: o.name,
517
+ type: "text",
518
+ values: arr(o.values).map((val) => ({ id: str(val.id), value: val.value }))
451
519
  })),
452
- variants: priced.map((variant) => mapVariant(product, variant))
520
+ variants: live.map((v) => toVariant(v, p, optionless)),
521
+ // Filled by the product page from ext/reviews when it is installed.
522
+ ratings: [],
523
+ rating: null,
524
+ ratingCount: 0,
525
+ reviewCount: 0,
526
+ attributes: [],
527
+ metadata: p.metadata ?? null,
528
+ createdAt: p.created_at,
529
+ updatedAt: p.updated_at
453
530
  };
454
- };
455
- var mapCategory = (category) => {
456
- if (!category) return null;
531
+ }
532
+ function fromSearchDoc(d) {
533
+ const price = minorToMajor(d.price_minor, d.currency);
534
+ return {
535
+ id: str(d.id),
536
+ slug: d.slug,
537
+ title: d.title,
538
+ name: d.title,
539
+ description: d.description,
540
+ currency: d.currency,
541
+ price,
542
+ mrp: price,
543
+ minPrice: price,
544
+ maxPrice: minorToMajor(d.price_max_minor, d.currency),
545
+ thumbnail: d.image ?? null,
546
+ image_url: d.image ?? null,
547
+ images: d.image ?? "",
548
+ stock: d.in_stock ? 1 : 0,
549
+ hasStock: d.in_stock,
550
+ // The index cannot say how much is left, only whether any is; a card
551
+ // built from it must not claim to count.
552
+ manageInventory: false,
553
+ allowBackorder: false,
554
+ productTags: arr(d.tags).join(","),
555
+ category: d.category ? { name: d.category.split(" / ").pop() ?? d.category, slug: "" } : null,
556
+ vendor: d.vendor ? { businessName: d.vendor } : null,
557
+ variants: [],
558
+ options: [],
559
+ ratings: [],
560
+ link: `/products/${d.slug}`,
561
+ updatedAt: new Date(d.updated_at * 1e3).toISOString()
562
+ };
563
+ }
564
+ function toCategory(c) {
457
565
  return {
458
- id: category.id,
566
+ id: str(c.id),
567
+ name: c.title,
568
+ title: c.title,
569
+ slug: c.slug,
570
+ link: `/${c.slug}`,
571
+ parentCategoryId: c.parent_id === null || c.parent_id === void 0 ? null : str(c.parent_id),
572
+ path: c.full_name,
573
+ level: c.depth,
574
+ rank: c.position,
575
+ childCount: c.child_count,
576
+ thumbnail: c.metadata?.image ?? null,
577
+ description: c.metadata?.description ?? null,
459
578
  isActive: true,
460
- isInternal: false,
461
- isMegamenu: false,
462
- thumbnail: null,
463
- path: category.full_name || null,
464
- level: category.depth ?? 0,
465
- description: null,
466
579
  isFeatured: false,
467
- keywords: null,
468
- rank: category.position ?? 0,
469
- link: null,
470
- metaDescription: null,
471
- metaKeywords: null,
472
- metaTitle: null,
473
- name: category.title,
474
- // The storefront's filter composable rebuilds the tree from this field.
475
- parentCategoryId: category.parent_id ?? null,
476
- store: null,
477
- slug: category.slug,
478
- userId: "",
479
- activeProducts: 0,
480
- inactiveProducts: 0,
481
- createdAt: category.created_at || null,
482
- updatedAt: category.updated_at || null
580
+ isMegamenu: false,
581
+ metaTitle: c.title,
582
+ children: arr(c.children).map(toCategory),
583
+ createdAt: c.created_at,
584
+ updatedAt: c.updated_at
483
585
  };
484
- };
485
- var mapCollection = (collection) => {
486
- if (!collection) return null;
487
- const products = collection.products || [];
586
+ }
587
+ function toCollection(c) {
488
588
  return {
489
- id: collection.id,
490
- name: collection.title,
491
- slug: collection.slug,
492
- description: collection.description || null,
589
+ id: str(c.id),
590
+ name: c.title,
591
+ title: c.title,
592
+ slug: c.slug,
593
+ description: c.description || null,
594
+ subTitle: null,
595
+ rank: str(c.position),
596
+ thumbnail: c.metadata?.image ?? null,
493
597
  isActive: true,
494
- isFeatured: false,
495
- userId: "",
496
- thumbnail: productImages(products[0])[0] || null,
497
- metaTitle: null,
498
- metaDescription: null,
499
- rank: collection.position ?? 0,
500
- collectionvalues: products.map((product) => {
501
- const mapped = mapProduct(product);
502
- return {
503
- products: {
504
- id: product.id,
505
- name: product.title,
506
- title: product.title,
507
- slug: product.slug,
508
- thumbnail: mapped?.thumbnail || null,
509
- price: mapped?.price ?? 0,
510
- mrp: mapped?.mrp ?? 0
511
- }
512
- };
513
- }),
514
- productCount: products.length,
515
- createdAt: collection.created_at || null,
516
- updatedAt: collection.updated_at || null
598
+ metaTitle: c.title,
599
+ metaDescription: c.description || null,
600
+ createdAt: c.created_at,
601
+ updatedAt: c.updated_at
517
602
  };
518
- };
519
- var lineProduct = (index, productId) => productId == null ? void 0 : index?.get(productId);
520
- var mapCartLine = (line, index) => {
521
- const product = lineProduct(index, line.product_id);
522
- const mapped = product ? mapProduct(product) : null;
523
- const variant = product?.variants?.find((v) => v.id === line.variant_id);
524
- const price = fromMoney(line.unit_price);
525
- const compareAt = fromMoney(variant?.compare_at_price);
526
- const thumbnail = absoluteMedia(variant?.image?.url) || mapped?.thumbnail || null;
603
+ }
604
+ function fromEngineAddress(a, email) {
605
+ if (!a) return null;
606
+ const [firstName, ...rest] = (a.name ?? "").trim().split(/\s+/);
527
607
  return {
528
- id: line.id,
529
- productId: line.product_id,
530
- variantId: line.variant_id,
531
- qty: line.quantity,
532
- subtotal: fromMoney(line.total),
533
- discount: 0,
534
- tax: 0,
535
- shippingCharges: 0,
536
- total: fromMoney(line.total),
537
- price,
538
- mrp: compareAt > price ? compareAt : price,
539
- title: line.title || mapped?.title || "",
540
- slug: mapped?.slug || "",
541
- sku: line.sku || "",
542
- description: null,
543
- thumbnail,
544
- metadata: null,
545
- vendorId: null,
546
- weight: null,
547
- dimensionUnit: "cm",
548
- height: null,
549
- width: null,
550
- len: null,
551
- shippingWeight: null,
552
- shippingHeight: null,
553
- shippingLen: null,
554
- shippingWidth: null,
608
+ firstName: firstName || "",
609
+ lastName: rest.join(" "),
610
+ email: email ?? null,
611
+ phone: a.phone ?? null,
612
+ address_1: a.line1,
613
+ address_2: a.line2 ?? "",
614
+ city: a.city,
615
+ state: a.state ?? "",
616
+ zip: a.postal_code,
617
+ country: a.country,
618
+ countryCode: a.country
619
+ };
620
+ }
621
+ function toEngineAddress(a) {
622
+ const name = [a.firstName, a.lastName].filter(Boolean).join(" ").trim();
623
+ return {
624
+ ...name ? { name } : {},
625
+ ...a.phone ? { phone: String(a.phone) } : {},
626
+ line1: String(a.address_1 ?? "").trim(),
627
+ ...a.address_2 || a.locality ? { line2: [a.address_2, a.locality].filter(Boolean).join(", ") } : {},
628
+ city: String(a.city ?? "").trim(),
629
+ ...a.state ? { state: String(a.state) } : {},
630
+ postal_code: String(a.zip ?? "").trim(),
631
+ country: String(a.countryCode || a.country || "").trim().toUpperCase()
632
+ };
633
+ }
634
+ function fromIdentityAddress(a, email) {
635
+ const [firstName, ...rest] = (a.name ?? "").trim().split(/\s+/);
636
+ return {
637
+ id: str(a.id),
638
+ firstName: firstName || "",
639
+ lastName: rest.join(" "),
640
+ email: email ?? null,
641
+ phone: a.phone || null,
642
+ address_1: a.line1,
643
+ address_2: a.line2,
644
+ city: a.city,
645
+ state: a.state,
646
+ zip: a.postal_code,
647
+ country: a.country,
648
+ countryCode: a.country,
649
+ label: a.label,
650
+ isPrimary: a.is_default,
651
+ createdAt: a.created_at,
652
+ updatedAt: a.updated_at
653
+ };
654
+ }
655
+ function toIdentityAddress(a) {
656
+ const e = toEngineAddress(a);
657
+ return {
658
+ name: e.name ?? "",
659
+ phone: e.phone ?? "",
660
+ line1: e.line1,
661
+ line2: e.line2 ?? "",
662
+ city: e.city,
663
+ state: e.state ?? "",
664
+ postal_code: e.postal_code,
665
+ country: e.country,
666
+ ...a.label ? { label: String(a.label) } : {},
667
+ ...a.isPrimary ? { is_default: true } : {}
668
+ };
669
+ }
670
+ function toCartLine(l, extra = {}) {
671
+ return {
672
+ id: str(l.id),
673
+ productId: str(l.product_id),
674
+ variantId: str(l.variant_id),
675
+ sku: l.sku,
676
+ title: l.title,
677
+ name: l.title,
678
+ slug: extra.slug ?? "",
679
+ thumbnail: extra.thumbnail ?? null,
680
+ variantTitle: l.variant_label ?? "",
681
+ qty: l.quantity,
682
+ price: toMajor(l.unit_price),
683
+ mrp: toMajor(l.unit_price),
684
+ subtotal: toMajor(l.total),
685
+ total: toMajor(l.total),
686
+ inStock: l.in_stock,
687
+ priceChanged: l.price_changed,
688
+ currentPrice: toMajor(l.current_price),
689
+ // The storefront's review step lists only lines marked for checkout. The
690
+ // engine checks a cart out whole, so every line is.
555
691
  isSelectedForCheckout: true,
556
- // Surfaced so the cart can warn, instead of letting checkout refuse the whole order later.
557
- priceChanged: Boolean(line.price_changed),
558
- inStock: line.in_stock !== false,
559
- createdAt: null,
560
- product: {
561
- id: line.product_id,
562
- title: line.title || mapped?.title || "",
563
- thumbnail,
564
- slug: mapped?.slug || "",
565
- sku: line.sku || "",
566
- categories: mapped?.categories || []
567
- },
568
692
  variant: {
569
- id: line.variant_id,
570
- price,
571
- mrp: compareAt > price ? compareAt : price,
572
- weight: null,
573
- height: null,
574
- width: null,
575
- len: null,
576
- shippingWeight: null,
577
- shippingHeight: null,
578
- shippingLen: null,
579
- shippingWidth: null,
580
- sku: line.sku || "",
581
- title: line.variant_label || variant?.label || "default",
582
- options: variant && product ? mapVariant(product, variant).options : []
583
- }
693
+ id: str(l.variant_id),
694
+ options: l.variant_label ? l.variant_label.split(" / ").map((value) => ({ option: { title: "" }, value })) : []
695
+ },
696
+ product: { id: str(l.product_id), categories: [] }
584
697
  };
585
- };
586
- var mapCart = (cart, details = {}, index, store) => {
587
- if (!cart) return {};
588
- const currency = cart.currency || store?.currency?.code || "USD";
589
- const lines = cart.line_items || [];
590
- const subtotal = fromMoney(cart.subtotal);
591
- const shippingAddress = details.shippingAddress || null;
592
- const billingAddress = details.billingAddress || shippingAddress;
698
+ }
699
+ function toCart(c, extras = {}, lineExtra = () => ({})) {
700
+ const lines = c.status === "converted" ? [] : arr(c.line_items);
701
+ const currency = c.currency;
702
+ const subtotalMinor = lines.reduce((n, l) => n + l.total.amount_minor, 0);
703
+ const discountMinor = extras.discount && !extras.discount.free_shipping ? extras.discount.amount_minor : 0;
704
+ const shippingMinor = extras.discount?.free_shipping ? 0 : extras.shippingRate?.minor ?? 0;
705
+ const totalMinor = Math.max(0, subtotalMinor - discountMinor) + shippingMinor;
706
+ const money = (minor) => minorToMajor(minor, currency);
707
+ const ship = extras.shippingAddress ?? null;
593
708
  return {
594
- id: cart.id,
595
- email: cart.email || details.email || null,
596
- phone: details.phone || shippingAddress?.phone || null,
597
- name: details.name || null,
598
- // The payment step gates on an id as well as the address itself. There is no address record
599
- // in GoCommerce to have an id of its own, so the cart it belongs to names it.
600
- billingAddressId: billingAddress ? `${cart.id}-billing` : null,
601
- shippingAddressId: shippingAddress ? `${cart.id}-shipping` : null,
602
- regionId: null,
603
- userId: null,
604
- couponCode: null,
709
+ id: c.id,
710
+ status: c.status,
711
+ email: c.email ?? ship?.email ?? null,
712
+ phone: extras.phone ?? ship?.phone ?? null,
713
+ name: ship ? [ship.firstName, ship.lastName].filter(Boolean).join(" ") : null,
714
+ lineItems: lines.map((l) => toCartLine(l, lineExtra(l))),
715
+ qty: lines.reduce((n, l) => n + l.quantity, 0),
716
+ currencyCode: currency,
717
+ currency,
718
+ subtotal: money(subtotalMinor),
719
+ discountAmount: money(discountMinor),
720
+ savingAmount: money(discountMinor),
721
+ couponCode: extras.discount?.code ?? null,
722
+ discount: extras.discount ?? null,
723
+ shippingCharges: money(shippingMinor),
724
+ shippingRateId: extras.shippingRateId ?? null,
725
+ shippingMethod: extras.shippingRate?.name ?? null,
726
+ tax: 0,
727
+ taxIncluded: false,
728
+ codCharges: 0,
729
+ total: money(totalMinor),
730
+ shippingAddress: ship,
731
+ shippingAddressId: ship ? ship.id && ship.id !== "new" ? String(ship.id) : "cart" : null,
732
+ billingAddress: extras.billingAddress ?? ship,
733
+ billingAddressId: extras.billingAddress ? extras.billingAddress.id && extras.billingAddress.id !== "new" ? String(extras.billingAddress.id) : "cart-billing" : ship ? ship.id && ship.id !== "new" ? String(ship.id) : "cart" : null,
734
+ paymentMethod: null,
735
+ needAddress: lines.length > 0,
736
+ completedAt: c.status === "converted" ? c.updated_at : null,
737
+ createdAt: c.created_at,
738
+ updatedAt: c.updated_at,
739
+ expiresAt: c.expires_at
740
+ };
741
+ }
742
+ function emptyCart(currency = "USD") {
743
+ return {
744
+ id: "",
745
+ status: "open",
746
+ email: null,
747
+ phone: null,
748
+ lineItems: [],
749
+ qty: 0,
750
+ currencyCode: currency,
751
+ subtotal: 0,
605
752
  discountAmount: 0,
606
- couponAppliedDate: null,
607
- needAddress: !shippingAddress,
608
- isCodAvailable: true,
609
- paymentId: null,
610
- type: null,
611
- completedAt: cart.status === "converted" ? cart.updated_at || null : null,
612
- paymentAuthorizedAt: null,
613
- idempotencyKey: null,
614
- salesChannelId: null,
615
- qty: cart.item_count ?? lines.reduce((sum, l) => sum + (l.quantity || 0), 0),
616
- // GoCommerce prices shipping at checkout, not on the cart, so there is nothing honest to put
617
- // here yet — and a fabricated number is the one the shopper would check the total against.
753
+ savingAmount: 0,
754
+ couponCode: null,
618
755
  shippingCharges: 0,
619
- paymentMethod: null,
620
- shippingMethod: null,
621
- subtotal,
622
- codCharges: 0,
623
756
  tax: 0,
624
- total: subtotal,
625
- savingAmount: 0,
626
- userAuthToken: null,
757
+ total: 0,
758
+ shippingAddress: null,
759
+ shippingAddressId: null,
760
+ billingAddress: null,
761
+ billingAddressId: null
762
+ };
763
+ }
764
+ var STATUS = {
765
+ pending: "Pending",
766
+ confirmed: "Confirmed",
767
+ partial: "Partially shipped",
768
+ shipped: "Shipped",
769
+ delivered: "Delivered",
770
+ cancelled: "Cancelled"
771
+ };
772
+ var PAYMENT_STATUS = {
773
+ pending: "Pending",
774
+ paid: "Paid",
775
+ failed: "Failed",
776
+ refunded: "Refunded"
777
+ };
778
+ function toOrderLine(l, currency) {
779
+ return {
780
+ id: str(l.id),
781
+ productId: str(l.product_id),
782
+ variantId: str(l.variant_id),
783
+ sku: l.sku,
784
+ title: l.title,
785
+ name: l.title,
786
+ slug: "",
787
+ thumbnail: l.image_url ?? null,
788
+ img: l.image_url ?? null,
789
+ variantTitle: l.variant_label ?? "",
790
+ qty: l.quantity,
791
+ shippedQty: l.shipped_quantity,
792
+ price: toMajor(l.unit_price),
793
+ mrp: toMajor(l.unit_price),
794
+ subtotal: toMajor(l.total),
795
+ total: toMajor(l.total),
627
796
  currencyCode: currency,
628
- currencySymbol: store?.currency?.symbol || "",
629
- shippingRateId: null,
630
- currencyDecimalDigits: currencyFractionDigits(currency),
631
- storeId: store?.id ?? null,
632
- status: cart.status || "open",
633
- createdAt: cart.created_at || null,
634
- updatedAt: cart.updated_at || null,
635
- deletedAt: null,
636
- lineItems: lines.map((line) => mapCartLine(line, index)),
637
- shippingAddress,
638
- billingAddress
797
+ status: l.shipped_quantity >= l.quantity ? "Shipped" : "Pending",
798
+ files: [],
799
+ usedOptions: []
639
800
  };
640
- };
641
- var splitName = (name) => {
642
- const parts = (name || "").trim().split(/\s+/).filter(Boolean);
643
- return { firstName: parts[0] || "", lastName: parts.slice(1).join(" ") };
644
- };
645
- var toStorefrontAddress = (address, email, phone) => {
646
- if (!address) return null;
647
- const { firstName, lastName } = splitName(address.name);
801
+ }
802
+ function toOrder(o) {
803
+ const address = fromEngineAddress(o.address, o.email);
804
+ const code = (o.discounts ?? []).find((d) => d.code)?.code;
648
805
  return {
649
- id: null,
650
- firstName,
651
- lastName,
652
- email: email || null,
653
- phone: address.phone || phone || "",
654
- address_1: address.line1 || "",
655
- address_2: address.line2 || "",
656
- city: address.city || "",
657
- state: address.state || "",
658
- zip: address.postal_code || "",
659
- country: address.country || "",
660
- countryCode: address.country || "",
661
- isPrimary: false,
662
- isResidential: true,
663
- deliveryInstructions: null
806
+ id: str(o.id),
807
+ orderNo: o.number,
808
+ orderNumber: o.number,
809
+ number: o.number,
810
+ // The storefront links an order by this; the engine has no sub-orders,
811
+ // so an order is its own parent.
812
+ parentOrderNo: o.number,
813
+ status: STATUS[o.status] ?? o.status,
814
+ engineStatus: o.status,
815
+ paymentStatus: PAYMENT_STATUS[o.payment_status] ?? o.payment_status,
816
+ paymentMethod: o.payment_provider.toUpperCase(),
817
+ currencyCode: o.currency,
818
+ subtotal: toMajor(o.subtotal),
819
+ shippingCharges: toMajor(o.shipping),
820
+ discount: toMajor(o.discount),
821
+ tax: toMajor(o.tax),
822
+ taxIncluded: o.tax_inclusive,
823
+ total: toMajor(o.total),
824
+ refunded: toMajor(o.refunded),
825
+ codCharges: 0,
826
+ coupon: code ? { code } : null,
827
+ userEmail: o.email,
828
+ email: o.email,
829
+ phone: o.phone ?? null,
830
+ shippingAddress: address,
831
+ billingAddress: address,
832
+ shippingMethod: o.shipping_method ?? null,
833
+ shippingRate: o.shipping_method ? { name: o.shipping_method } : null,
834
+ lineItems: arr(o.line_items).map((l) => toOrderLine(l, o.currency)),
835
+ fulfillments: arr(o.fulfillments).map((f) => ({
836
+ id: str(f.id),
837
+ status: f.status,
838
+ carrier: f.carrier_name || f.carrier || f.provider,
839
+ trackingNumber: f.tracking ?? null,
840
+ trackingUrl: f.tracking_url ?? null,
841
+ lineItems: arr(f.lines).map((l) => ({ id: str(l.order_line_id), title: l.title, qty: l.quantity })),
842
+ createdAt: f.created_at
843
+ })),
844
+ tracking: [],
845
+ orderHistory: [],
846
+ isReplaceOrReturn: false,
847
+ createdAt: o.created_at,
848
+ updatedAt: o.updated_at
664
849
  };
665
- };
666
- var toGoCommerceAddress = (address, fallbackPhone) => {
667
- if (!address) return null;
668
- const name = [address.firstName, address.lastName].filter(Boolean).join(" ").trim() || address.name || "";
669
- const line1 = address.address_1 || address.line1 || "";
670
- const city = address.city || "";
671
- const postal = address.zip || address.postal_code || "";
672
- const country = address.countryCode || address.country_code || address.country || "";
673
- if (!line1 || !city || !postal || !country) return null;
850
+ }
851
+ function toRating(r) {
674
852
  return {
675
- name,
676
- phone: address.phone || fallbackPhone || "",
677
- line1,
678
- line2: address.address_2 || address.line2 || "",
679
- city,
680
- state: address.state || "",
681
- postal_code: postal,
682
- // GoCommerce wants ISO 3166-1 alpha-2; the form may hold a full country name alongside it.
683
- country: String(country).length === 2 ? String(country).toUpperCase() : String(country)
853
+ id: str(r.id),
854
+ rating: r.rating,
855
+ name: r.name,
856
+ title: r.title ?? "",
857
+ review: r.body,
858
+ message: r.body,
859
+ reply: r.reply ?? null,
860
+ verified: r.verified,
861
+ img: "",
862
+ createdAt: r.created_at
684
863
  };
685
- };
686
- var mapOrder = (order, index) => {
687
- if (!order) return null;
688
- const shippingAddress = toStorefrontAddress(order.address, order.email, order.phone);
864
+ }
865
+ function toCmsPage(p) {
689
866
  return {
690
- id: order.id,
691
- orderNo: order.number,
692
- order_no: order.number,
693
- // The orders list links a detail page by parentOrderNo; the number is the handle here.
694
- parentOrderNo: order.number,
695
- status: order.status || "pending",
696
- paymentStatus: order.payment_status || "pending",
697
- paymentMethod: order.payment_provider || null,
698
- createdAt: order.created_at || null,
699
- updatedAt: order.updated_at || null,
700
- userEmail: order.email || "",
701
- phone: order.phone || "",
702
- subtotal: fromMoney(order.subtotal),
703
- shippingCharges: fromMoney(order.shipping),
704
- discount: fromMoney(order.discount),
705
- total: fromMoney(order.total),
706
- currencyCode: order.currency,
707
- currencyDecimalDigits: currencyFractionDigits(order.currency),
708
- shippingRate: null,
709
- fulfillments: (order.fulfillments || []).map((f) => ({
710
- id: f.id,
711
- status: f.status || "",
712
- provider: f.provider || "",
713
- trackingNumber: f.tracking || "",
714
- labelUrl: f.label_url || "",
715
- createdAt: f.created_at || null
716
- })),
717
- shippingAddress,
718
- billingAddress: shippingAddress,
719
- lineItems: (order.line_items || []).map((line) => {
720
- const product = lineProduct(index, line.product_id);
721
- const mapped = product ? mapProduct(product) : null;
722
- const variant = product?.variants?.find((v) => v.id === line.variant_id);
723
- return {
724
- id: line.id,
725
- productId: line.product_id,
726
- variantId: line.variant_id,
727
- title: line.title || mapped?.title || "",
728
- variantTitle: line.variant_label || line.sku || "",
729
- slug: mapped?.slug || "",
730
- sku: line.sku || "",
731
- thumbnail: absoluteMedia(variant?.image?.url) || mapped?.thumbnail || null,
732
- qty: line.quantity,
733
- price: fromMoney(line.unit_price),
734
- // The orders list prints `total`; the confirmation page prints `subtotal`.
735
- subtotal: fromMoney(line.total),
736
- total: fromMoney(line.total)
737
- };
738
- })
867
+ id: str(p.id),
868
+ slug: p.slug,
869
+ name: p.title,
870
+ title: p.title,
871
+ content: p.body,
872
+ excerpt: p.excerpt ?? null,
873
+ layouts: [],
874
+ language: p.language,
875
+ metaTitle: p.seo?.title || p.title,
876
+ metaDescription: p.seo?.description || p.excerpt || null,
877
+ metaKeywords: p.seo?.keywords || null,
878
+ publishedAt: p.published_at ?? null,
879
+ createdAt: p.created_at,
880
+ updatedAt: p.updated_at
739
881
  };
740
- };
741
-
742
- // src/services/checkout-details.ts
743
- var DETAILS_PREFIX = "gocommerce_checkout_";
744
- var ORDER_TOKENS_KEY = "gocommerce_order_tokens";
745
- var storage = () => {
746
- try {
747
- return typeof window !== "undefined" && window.localStorage ? window.localStorage : void 0;
748
- } catch {
749
- return void 0;
750
- }
751
- };
752
- var readJson = (key) => {
753
- const store = storage();
754
- if (!store) return void 0;
755
- try {
756
- const raw = store.getItem(key);
757
- return raw ? JSON.parse(raw) : void 0;
758
- } catch {
759
- return void 0;
760
- }
761
- };
762
- var writeJson = (key, value) => {
763
- const store = storage();
764
- if (!store) return;
765
- try {
766
- store.setItem(key, JSON.stringify(value));
767
- } catch {
768
- }
769
- };
770
- var readCheckoutDetails = (cartId) => {
771
- if (!cartId) return {};
772
- return readJson(`${DETAILS_PREFIX}${cartId}`) ?? {};
773
- };
774
- var writeCheckoutDetails = (cartId, patch) => {
775
- if (!cartId) return patch;
776
- const merged = { ...readCheckoutDetails(cartId), ...patch };
777
- writeJson(`${DETAILS_PREFIX}${cartId}`, merged);
778
- return merged;
779
- };
780
- var clearCheckoutDetails = (cartId) => {
781
- const store = storage();
782
- if (!store || !cartId) return;
783
- try {
784
- store.removeItem(`${DETAILS_PREFIX}${cartId}`);
785
- } catch {
786
- }
787
- };
788
- var rememberOrderToken = (orderNumber, token) => {
789
- if (!orderNumber || !token) return;
790
- const tokens = readJson(ORDER_TOKENS_KEY) ?? {};
791
- tokens[orderNumber] = token;
792
- writeJson(ORDER_TOKENS_KEY, tokens);
793
- };
794
- var readOrderToken = (orderNumber) => {
795
- if (!orderNumber) return void 0;
796
- return (readJson(ORDER_TOKENS_KEY) ?? {})[orderNumber];
797
- };
798
- var readOrderNumbers = () => Object.keys(readJson(ORDER_TOKENS_KEY) ?? {});
882
+ }
883
+ function toVendor(v) {
884
+ return {
885
+ id: str(v.id),
886
+ slug: v.slug,
887
+ name: v.name,
888
+ businessName: v.name,
889
+ about: v.about,
890
+ description: v.about,
891
+ website: v.website,
892
+ address: v.address,
893
+ banners: [],
894
+ rating: null
895
+ };
896
+ }
897
+ function toUser(c) {
898
+ const [firstName, ...rest] = (c.name ?? "").trim().split(/\s+/);
899
+ return {
900
+ id: str(c.id),
901
+ userId: str(c.id),
902
+ email: c.email,
903
+ emailVerified: c.email_verified,
904
+ phone: c.phone || null,
905
+ firstName: firstName || "",
906
+ lastName: rest.join(" "),
907
+ name: c.name,
908
+ fullName: c.name,
909
+ avatar: null,
910
+ role: "USER",
911
+ createdAt: c.created_at,
912
+ updatedAt: c.updated_at
913
+ };
914
+ }
799
915
 
800
- // src/services/address-book.ts
801
- var ADDRESSES_KEY = "gocommerce_addresses";
802
- var storage2 = () => {
803
- try {
804
- return typeof window !== "undefined" && window.localStorage ? window.localStorage : void 0;
805
- } catch {
806
- return void 0;
807
- }
808
- };
809
- var readAll = () => {
810
- const store = storage2();
811
- if (!store) return [];
812
- try {
813
- const raw = store.getItem(ADDRESSES_KEY);
814
- const parsed = raw ? JSON.parse(raw) : [];
815
- return Array.isArray(parsed) ? parsed : [];
816
- } catch {
817
- return [];
818
- }
819
- };
820
- var writeAll = (addresses) => {
821
- const store = storage2();
822
- if (!store) return;
823
- try {
824
- store.setItem(ADDRESSES_KEY, JSON.stringify(addresses));
825
- } catch {
826
- }
827
- };
828
- var isSavedId = (id) => typeof id === "string" && id.length > 0 && id !== "new";
829
- var newId = () => `addr_${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36)}`;
830
- var listAddresses = () => readAll();
831
- var findAddress = (id) => readAll().find((a) => a.id === id);
832
- var putAddress = (address) => {
833
- const addresses = readAll();
834
- const id = isSavedId(address.id) ? address.id : newId();
835
- const saved = { ...address, id };
836
- const index = addresses.findIndex((a) => a.id === id);
837
- if (index >= 0) addresses[index] = saved;
838
- else addresses.push(saved);
839
- writeAll(addresses);
840
- return saved;
841
- };
842
- var patchAddress = (id, patch) => {
843
- const existing = findAddress(id);
844
- if (!existing) return void 0;
845
- return putAddress({ ...existing, ...patch, id });
846
- };
847
- var removeAddress = (id) => {
848
- writeAll(readAll().filter((a) => a.id !== id));
849
- };
850
- var SESSION_COOKIES = ["connect.sid", "me"];
851
- var clearPhantomSession = () => {
852
- if (typeof document === "undefined") return;
853
- for (const name of SESSION_COOKIES) {
854
- document.cookie = `${name}=; Max-Age=0; path=/`;
855
- document.cookie = `${name}=; Max-Age=0`;
856
- }
857
- };
858
- var hasPhantomSession = () => typeof document !== "undefined" && SESSION_COOKIES.some((name) => new RegExp(`(^|;\\s*)${name.replace(".", "\\.")}=`).test(document.cookie));
916
+ // src/cache.ts
917
+ var TTL_MS = 6e4;
918
+ var entries = /* @__PURE__ */ new Map();
919
+ function remember(key, load, ttl = TTL_MS) {
920
+ const hit = entries.get(key);
921
+ if (hit && Date.now() - hit.at < ttl) return hit.value;
922
+ const value = load();
923
+ entries.set(key, { at: Date.now(), value });
924
+ value.catch(() => {
925
+ if (entries.get(key)?.value === value) entries.delete(key);
926
+ });
927
+ return value;
928
+ }
859
929
 
860
- // src/services/catalog.ts
861
- var productCache = /* @__PURE__ */ new Map();
862
- var categorySlugById = /* @__PURE__ */ new Map();
863
- var remember = (products) => {
864
- for (const product of products) {
865
- if (product?.id != null) productCache.set(product.id, product);
866
- if (product?.category?.id != null && product.category.slug) categorySlugById.set(product.category.id, product.category.slug);
867
- }
868
- return products;
869
- };
870
- var rememberCategories = (categories) => {
871
- for (const category of categories) {
872
- if (category?.id != null && category.slug) categorySlugById.set(category.id, category.slug);
873
- if (category?.children?.length) rememberCategories(category.children);
930
+ // src/services/facts.ts
931
+ var StoreFacts = class extends BaseService {
932
+ key(name) {
933
+ return `${this.engineBase()}|${this.creds.store ?? ""}|${name}`;
934
+ }
935
+ /** Enabled plugins by key. A module that is not installed has no key here. */
936
+ plugins() {
937
+ return remember(this.key("plugins"), async () => {
938
+ const list = await this.data("/api/plugins") ?? [];
939
+ return new Map(list.map((p) => [p.key, p]));
940
+ });
874
941
  }
875
- return categories;
876
- };
877
- var query = (params) => {
878
- const search = new URLSearchParams();
879
- for (const [key, value] of Object.entries(params)) {
880
- if (value === void 0 || value === "") continue;
881
- search.set(key, String(value));
882
- }
883
- const qs = search.toString();
884
- return qs ? `?${qs}` : "";
885
- };
886
- var ProductService = class _ProductService extends BaseService {
887
- static instance;
888
- static getInstance() {
889
- if (!_ProductService.instance) _ProductService.instance = new _ProductService();
890
- return _ProductService.instance;
891
- }
892
- /** One window of the catalogue, raw. Everything else in this file is built on it. */
893
- async fetchProducts({ q, page = 1, limit = PAGE_SIZE } = {}) {
894
- const res = await this.api("GET", `/api/products${query({ q, page, limit })}`);
895
- return { products: remember(res.data || []), meta: res.meta };
896
- }
897
- /** A product by its numeric id — how a cart line names what is in it. */
898
- async fetchProductById(id) {
899
- const cached = productCache.get(id);
900
- if (cached) return cached;
942
+ async pluginOn(key) {
901
943
  try {
902
- const res = await this.api("GET", `/api/products/${id}`);
903
- if (res.data) remember([res.data]);
904
- return res.data ?? null;
944
+ return (await this.plugins()).has(key);
905
945
  } catch {
906
- return null;
907
- }
908
- }
909
- async fetchProductBySlug(slug) {
910
- const res = await this.api("GET", `/api/products/slug/${encodeURIComponent(slug)}`);
911
- if (res.data) remember([res.data]);
912
- return res.data ?? null;
913
- }
914
- async list({ page = 1, search = "", sort = "" } = {}) {
915
- if (sortNeedsWholeCatalogue(sort)) {
916
- const { products: products2, meta: meta2 } = await this.fetchProducts({ q: search, page: 1, limit: MAX_LIMIT });
917
- const sorted = sortProducts(products2, sort);
918
- const start = (page - 1) * PAGE_SIZE;
919
- return paginated(sorted.slice(start, start + PAGE_SIZE).map(mapProduct), meta2?.total ?? sorted.length, page);
946
+ return false;
920
947
  }
921
- const { products, meta } = await this.fetchProducts({ q: search, page, limit: PAGE_SIZE });
922
- return fromListMeta(products.map(mapProduct), meta, page);
923
948
  }
924
- // GoCommerce records no "featured" or "trending" flag, and inventing one would rank the catalogue
925
- // by nothing. Newest first is the honest reading of both, and it is what the homepage asks for.
926
- async listFeaturedProducts({ page = 1, sort = "-createdAt" } = {}) {
927
- return this.list({ page, sort });
949
+ /** The store's settlement currency and default language. */
950
+ ready() {
951
+ return remember(this.key("ready"), () => this.data("/health/ready"));
928
952
  }
929
- async listTrendingProducts({ page = 1, search = "", sort = "-createdAt" } = {}) {
930
- return this.list({ page, search, sort });
953
+ checkoutOptions() {
954
+ return remember(this.key("checkout"), () => this.data("/api/checkout"));
931
955
  }
932
- /** The "you may also like" rail: the rest of the product's own category. */
933
- async listRelatedProducts({ page = 1, categoryId = "" } = {}) {
934
- const slug = await resolveCategorySlug(categoryId);
935
- if (!slug) return emptyPage(page);
936
- const { products, meta } = await categoryService.fetchCategoryPage(slug, { limit: MAX_LIMIT });
937
- const start = (page - 1) * PAGE_SIZE;
938
- return paginated(products.slice(start, start + PAGE_SIZE).map(mapProduct), meta?.total ?? products.length, page);
939
- }
940
- async getOne(slug) {
941
- return mapProduct(await this.fetchProductBySlug(slug));
942
- }
943
- /** A product's variants, for a PDP that wants them without re-reading the product. */
944
- async listVariants(productId) {
945
- const res = await this.api("GET", `/api/variants${query({ product_id: productId, limit: MAX_LIMIT })}`);
946
- return fromListMeta(res.data || [], res.meta);
947
- }
948
- // GoCommerce ships no review API, and a silent success would tell the shopper their review was
949
- // saved when nothing left the browser.
950
- async addReview(_params) {
951
- throw new Error("Product reviews are not available on this store.");
956
+ /**
957
+ * The whole tree, flat and depth-first. Past 500 categories the engine
958
+ * answers a truncated list; the tree then serves what it has, and a
959
+ * breadcrumb for a category outside it falls back to the category alone.
960
+ */
961
+ categories() {
962
+ return remember(
963
+ this.key("categories"),
964
+ async () => await this.data("/api/categories", { query: { flat: 1 } }) ?? []
965
+ );
952
966
  }
953
- async fetchReels() {
954
- return { data: [], count: 0 };
967
+ /** Root → `slug`, by walking parents in the flat tree. */
968
+ async hierarchy(slug) {
969
+ const all = await this.categories().catch(() => []);
970
+ const byId = new Map(all.map((c2) => [c2.id, c2]));
971
+ const out = [];
972
+ let c = all.find((x) => x.slug === slug);
973
+ while (c) {
974
+ out.unshift({ name: c.title, slug: c.slug });
975
+ c = c.parent_id === null ? void 0 : byId.get(c.parent_id);
976
+ }
977
+ return out;
978
+ }
979
+ /** `slug` and every category under it — what a category page sells. */
980
+ async subtree(slug) {
981
+ const all = await this.categories();
982
+ const root = all.find((c) => c.slug === slug);
983
+ if (!root) return [];
984
+ const ids = /* @__PURE__ */ new Set([root.id]);
985
+ const out = [root];
986
+ for (const c of all) {
987
+ if (c.parent_id !== null && ids.has(c.parent_id) && !ids.has(c.id)) {
988
+ ids.add(c.id);
989
+ out.push(c);
990
+ }
991
+ }
992
+ return out;
955
993
  }
956
994
  };
957
- var productService = ProductService.getInstance();
958
- var CategoryService = class _CategoryService extends BaseService {
959
- static instance;
960
- static getInstance() {
961
- if (!_CategoryService.instance) _CategoryService.instance = new _CategoryService();
962
- return _CategoryService.instance;
963
- }
964
- /**
965
- * `use-category-filters` in @misiki/kitcommerce-core fetches the tree by raw Litekart REST path
966
- * rather than a typed method. On a GoCommerce store that url resolves against the storefront's
967
- * own origin, so route that one path to the real tree; `fetchAllCategories` already returns the
968
- * `{ data }` shape it reads.
969
- */
970
- async get(url) {
971
- if (typeof url === "string" && url.startsWith("/api/categories/all")) {
972
- return await this.fetchAllCategories();
995
+
996
+ // src/services/catalog.ts
997
+ var PAGE_SIZE = 24;
998
+ function indexSort(sort) {
999
+ if (!sort) return void 0;
1000
+ const s = sort.trim();
1001
+ const [field, dir] = s.startsWith("-") ? [s.slice(1), "desc"] : s.includes(":") ? s.split(":") : [s, "asc"];
1002
+ const d = dir === "desc" ? "desc" : "asc";
1003
+ switch (field) {
1004
+ case "price":
1005
+ return `price_minor:${d}`;
1006
+ case "updatedAt":
1007
+ case "updated_at":
1008
+ case "createdAt":
1009
+ case "created_at":
1010
+ return `updated_at:${d}`;
1011
+ case "title":
1012
+ case "name":
1013
+ return `title:${d}`;
1014
+ default:
1015
+ return void 0;
1016
+ }
1017
+ }
1018
+ var NATURAL = /* @__PURE__ */ new Set([
1019
+ "-createdAt",
1020
+ "createdAt:desc",
1021
+ "-updatedAt",
1022
+ "updatedAt:desc",
1023
+ "-popularity",
1024
+ "popularity:desc"
1025
+ ]);
1026
+ var quote = (s) => `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
1027
+ var CatalogService = class extends BaseService {
1028
+ facts = new StoreFacts(this._fetch);
1029
+ async queryCatalog(q) {
1030
+ const page = Math.max(1, Number(q.page) || 1);
1031
+ const limit = Math.min(100, Math.max(1, Number(q.limit) || PAGE_SIZE));
1032
+ const search = q.search?.trim() || void 0;
1033
+ const wantsRange = Number.isFinite(q.priceFrom) || Number.isFinite(q.priceTo);
1034
+ const sortKey = q.sort && !NATURAL.has(q.sort) ? indexSort(q.sort) : void 0;
1035
+ const hierarchy = q.category ? await this.facts.hierarchy(q.category) : [];
1036
+ if ((sortKey || wantsRange) && await this.facts.pluginOn("meilisearch")) {
1037
+ const filters = [];
1038
+ if (q.category) {
1039
+ const names = (await this.facts.subtree(q.category).catch(() => [])).map(
1040
+ (c) => quote(c.full_name)
1041
+ );
1042
+ if (!names.length) return { ...emptyCatalog(limit), categoryHierarchy: hierarchy, sorted: true };
1043
+ filters.push(`category IN [${names.join(", ")}]`);
1044
+ }
1045
+ if (wantsRange) {
1046
+ const { currency } = await this.facts.ready();
1047
+ if (Number.isFinite(q.priceFrom)) filters.push(`price_minor >= ${toMinor(q.priceFrom, currency)}`);
1048
+ if (Number.isFinite(q.priceTo)) filters.push(`price_minor <= ${toMinor(q.priceTo, currency)}`);
1049
+ }
1050
+ const res = await this.data("/x/meilisearch/search", {
1051
+ query: {
1052
+ q: search ?? "",
1053
+ limit,
1054
+ offset: (page - 1) * limit,
1055
+ filter: filters.join(" AND ") || void 0,
1056
+ sort: sortKey
1057
+ }
1058
+ });
1059
+ const total = res.total ?? 0;
1060
+ return {
1061
+ data: (res.hits ?? []).map(fromSearchDoc),
1062
+ count: total,
1063
+ pageSize: limit,
1064
+ noOfPage: Math.max(1, Math.ceil(total / limit)),
1065
+ page,
1066
+ categoryHierarchy: hierarchy,
1067
+ sorted: true
1068
+ };
1069
+ }
1070
+ const sorted = !sortKey && !wantsRange;
1071
+ if (q.category && !search) {
1072
+ const env2 = await this.engine(
1073
+ `/api/categories/${encodeURIComponent(q.category)}`,
1074
+ { query: { page, limit } }
1075
+ );
1076
+ const products = env2.data?.products ?? [];
1077
+ return {
1078
+ ...toPage({ data: products, meta: env2.meta }, (p) => toProduct(p)),
1079
+ categoryHierarchy: hierarchy,
1080
+ sorted
1081
+ };
973
1082
  }
974
- return super.get(url);
1083
+ const env = await this.engine("/api/products", {
1084
+ query: { q: search, page, limit, channel: this.creds.channel }
1085
+ });
1086
+ return { ...toPage(env, (p) => toProduct(p)), categoryHierarchy: hierarchy, sorted };
975
1087
  }
1088
+ };
1089
+ function emptyCatalog(limit = PAGE_SIZE) {
1090
+ return { data: [], count: 0, pageSize: limit, noOfPage: 0, page: 1 };
1091
+ }
1092
+
1093
+ // src/services/product-service.ts
1094
+ var ProductService = class extends CatalogService {
976
1095
  /**
977
- * The taxonomy, flattened.
1096
+ * A product page. `slug` may also be a numeric id or a variant SKU, which is
1097
+ * how an old link or a search hit sometimes arrives.
978
1098
  *
979
- * `GET /api/categories` answers with one fixed window and ignores `limit`/`page`, so this is
980
- * every category the storefront can see — roots plus what fits beneath them. A store that has
981
- * imported a full retail taxonomy has far more nodes than that; the ones a shopper reaches are
982
- * still reachable, because a listing page looks its category up by slug directly.
1099
+ * Reviews ride along when ext/reviews is installed and switched on; a review
1100
+ * failure never costs the shopper the product page.
983
1101
  */
984
- async fetchAllCategories() {
985
- const res = await this.api("GET", `/api/categories${query({ flat: "true" })}`);
986
- const categories = rememberCategories(res.data || []);
987
- return paginated(categories.map(mapCategory), categories.length, 1, categories.length || PAGE_SIZE);
988
- }
989
- /** A category and the active products filed under it or anything beneath it. */
990
- async fetchCategoryPage(slug, { limit = MAX_LIMIT, offset = 0 } = {}) {
991
- const res = await this.api("GET", `/api/categories/${encodeURIComponent(slug)}${query({ limit, offset })}`);
992
- const category = res.data;
993
- if (category) rememberCategories([category]);
994
- const products = remember(category?.products || []);
995
- return { category, products, meta: res.meta };
996
- }
997
- async fetchCategory(slugOrId) {
998
- const { category } = await this.fetchCategoryPage(String(slugOrId), { limit: 1 });
999
- return mapCategory(category);
1000
- }
1001
- async fetchFooterCategories({ page = 1, q = "" } = {}) {
1002
- const all = await this.fetchAllCategories();
1003
- const filtered = q ? all.data.filter((c) => c?.name?.toLowerCase().includes(q.toLowerCase())) : all.data;
1004
- const start = (page - 1) * PAGE_SIZE;
1005
- return paginated(filtered.slice(start, start + PAGE_SIZE), filtered.length, page);
1006
- }
1007
- /** The homepage grid: the roots of the taxonomy, which is what a shopper navigates from. */
1008
- async fetchFeaturedCategories({ limit = 18 } = {}) {
1009
- const all = await this.fetchAllCategories();
1010
- const roots = all.data.filter((c) => c && c.parentCategoryId == null);
1011
- const picked = (roots.length ? roots : all.data).slice(0, limit);
1012
- return paginated(picked, picked.length, 1, limit);
1013
- }
1014
- async fetchAllProductsOfCategories(slugOrId) {
1015
- const slug = await resolveCategorySlug(slugOrId) || String(slugOrId);
1016
- const { products, meta } = await this.fetchCategoryPage(slug);
1017
- return fromListMeta(products.map(mapProduct), meta);
1102
+ async getOne(slug) {
1103
+ const p = await this.findProduct(String(slug));
1104
+ const product = toProduct(p, {
1105
+ categoryHierarchy: p.category ? await this.facts.hierarchy(p.category.slug) : []
1106
+ });
1107
+ if (await this.facts.pluginOn("product-reviews")) {
1108
+ try {
1109
+ const res = await this.data("/x/reviews", { query: { product_id: p.id, limit: 50 } });
1110
+ product.ratings = (res.reviews ?? []).map(toRating);
1111
+ product.rating = res.summary?.count ? res.summary.average : null;
1112
+ product.ratingCount = res.summary?.count ?? 0;
1113
+ product.reviewCount = res.summary?.count ?? 0;
1114
+ } catch {
1115
+ }
1116
+ }
1117
+ return product;
1018
1118
  }
1019
- async getMegamenu() {
1020
- return this.fetchFeaturedCategories({ limit: 50 });
1119
+ async findProduct(slug) {
1120
+ try {
1121
+ return await this.data(`/api/products/slug/${encodeURIComponent(slug)}`);
1122
+ } catch (err) {
1123
+ if (!(err instanceof GoCommerceError) || err.status !== 404) throw err;
1124
+ const fallback = /^\d+$/.test(slug) ? `/api/products/${slug}` : `/api/products/sku/${encodeURIComponent(slug)}`;
1125
+ try {
1126
+ return await this.data(fallback);
1127
+ } catch {
1128
+ throw err;
1129
+ }
1130
+ }
1021
1131
  }
1022
- };
1023
- var categoryService = CategoryService.getInstance();
1024
- var resolveCategorySlug = async (categoryId) => {
1025
- if (categoryId === void 0 || categoryId === null || categoryId === "") return void 0;
1026
- const asNumber = Number(categoryId);
1027
- if (!Number.isFinite(asNumber)) return String(categoryId);
1028
- const known = categorySlugById.get(asNumber);
1029
- if (known) return known;
1030
- await categoryService.fetchAllCategories();
1031
- return categorySlugById.get(asNumber);
1032
- };
1033
- var CollectionService = class _CollectionService extends BaseService {
1034
- static instance;
1035
- static getInstance() {
1036
- if (!_CollectionService.instance) _CollectionService.instance = new _CollectionService();
1037
- return _CollectionService.instance;
1038
- }
1039
- async list({ page = 1, q = "" } = {}) {
1040
- const res = await this.api("GET", `/api/collections${query({ page, limit: PAGE_SIZE })}`);
1041
- const items = res.data || [];
1042
- const filtered = q ? items.filter((c) => c.title?.toLowerCase().includes(q.toLowerCase())) : items;
1043
- return fromListMeta(
1044
- filtered.map((c) => mapCollection(c)),
1045
- res.meta,
1046
- page
1047
- );
1132
+ /** The shop's listing: `{ page, search, sort }`, newest first unless the index can reorder it. */
1133
+ async list({
1134
+ page = 1,
1135
+ search,
1136
+ q,
1137
+ sort,
1138
+ limit,
1139
+ categories
1140
+ } = {}) {
1141
+ const res = await this.queryCatalog({ page, search: search ?? q, sort, limit, category: categories || void 0 });
1142
+ return { data: res.data, count: res.count, pageSize: res.pageSize, noOfPage: res.noOfPage, page: res.page };
1143
+ }
1144
+ async listFeaturedProducts({ page = 1, sort, limit } = {}) {
1145
+ return this.shelf("featured", { page, sort, limit });
1146
+ }
1147
+ async listTrendingProducts({ page = 1, limit } = {}) {
1148
+ return this.shelf("trending", { page, limit });
1149
+ }
1150
+ /** More from this product's category. */
1151
+ async listRelatedProducts({
1152
+ page = 1,
1153
+ categoryId,
1154
+ limit
1155
+ } = {}) {
1156
+ if (!categoryId) return this.list({ page, limit });
1157
+ const category = (await this.facts.categories()).find((c) => String(c.id) === String(categoryId));
1158
+ if (!category) return this.list({ page, limit });
1159
+ return this.list({ page, limit, categories: category.slug });
1160
+ }
1161
+ async shelf(slug, { page, sort, limit }) {
1162
+ const size = Math.min(100, Math.max(1, Number(limit) || PAGE_SIZE));
1163
+ try {
1164
+ const env = await this.engine(`/api/collections/${slug}`, {
1165
+ query: { page, limit: size }
1166
+ });
1167
+ const rows = env.data?.products ?? [];
1168
+ return {
1169
+ data: rows.map((p) => toProduct(p)),
1170
+ count: env.meta?.total ?? rows.length,
1171
+ pageSize: env.meta?.limit ?? size,
1172
+ noOfPage: env.meta?.total_pages ?? 1,
1173
+ page: env.meta?.page ?? page
1174
+ };
1175
+ } catch (err) {
1176
+ if (!(err instanceof GoCommerceError) || err.status !== 404) throw err;
1177
+ return this.list({ page, sort, limit: size });
1178
+ }
1048
1179
  }
1049
1180
  /**
1050
- * A collection with its products. GoCommerce is keyed on slug; the storefront sometimes has only
1051
- * an id, and there is no id lookup, so that case reads the list and matches there.
1181
+ * A review, through ext/reviews. The engine asks for a name and an email
1182
+ * with every review, so a signed-out shopper is asked to sign in rather
1183
+ * than having one made up for them. Uploaded photos have nowhere to go: the
1184
+ * module stores text.
1052
1185
  */
1053
- async getOne(idOrSlug) {
1054
- const looksLikeId = /^[0-9]+$/.test(String(idOrSlug));
1055
- let slug = String(idOrSlug);
1056
- if (looksLikeId) {
1057
- const res2 = await this.api("GET", `/api/collections${query({ limit: MAX_LIMIT })}`);
1058
- const match = (res2.data || []).find((c) => String(c.id) === String(idOrSlug));
1059
- if (!match) throw new Error(`Collection ${idOrSlug} not found`);
1060
- slug = match.slug;
1061
- }
1062
- const res = await this.api("GET", `/api/collections/${encodeURIComponent(slug)}${query({ limit: MAX_LIMIT })}`);
1063
- if (!res.data) throw new Error(`Collection ${idOrSlug} not found`);
1064
- remember(res.data.products || []);
1065
- return mapCollection(res.data);
1186
+ async addReview({
1187
+ productId,
1188
+ rating,
1189
+ review,
1190
+ title
1191
+ }) {
1192
+ const me = currentMe();
1193
+ if (!me?.email) throw new GoCommerceError("Please sign in to write a review.", 401, "unauthorized");
1194
+ const name = [me.firstName, me.lastName].filter(Boolean).join(" ") || me.email.split("@")[0];
1195
+ return this.data("/x/reviews", {
1196
+ method: "POST",
1197
+ body: {
1198
+ product_id: Number(productId),
1199
+ name,
1200
+ email: me.email,
1201
+ rating: Math.round(Number(rating)),
1202
+ ...title ? { title } : {},
1203
+ body: String(review ?? "")
1204
+ }
1205
+ });
1066
1206
  }
1067
- // GoCommerce records no ratings, so there is no "all ratings" collection to serve.
1068
- async getAllRatings() {
1069
- return {
1070
- id: null,
1071
- name: "All Ratings",
1072
- slug: "all-ratings",
1073
- description: null,
1074
- isActive: true,
1075
- isFeatured: false,
1076
- userId: "",
1077
- productCount: 0,
1078
- thumbnail: null,
1079
- metaTitle: null,
1080
- metaDescription: null,
1081
- collectionvalues: [],
1082
- createdAt: null,
1083
- updatedAt: null
1084
- };
1207
+ async fetchReels() {
1208
+ throw new NotSupportedError("ProductService", "fetchReels", "the engine has no reels");
1085
1209
  }
1086
1210
  };
1087
- var collectionService = CollectionService.getInstance();
1088
- var sortNeedsWholeCatalogue = (sort) => {
1089
- if (!sort) return false;
1090
- const key = sort.replace(/^-/, "").split(":")[0];
1091
- return key === "price" || key === "updatedAt" || key === "createdAt";
1092
- };
1093
- var sortProducts = (products, sort) => {
1094
- if (!sortNeedsWholeCatalogue(sort)) return products;
1095
- const leadingMinus = sort.startsWith("-");
1096
- const [rawKey, rawDirection] = sort.replace(/^-/, "").split(":");
1097
- const descending = leadingMinus || rawDirection === "desc";
1098
- const value = (product) => {
1099
- if (rawKey === "price") {
1100
- const prices = (product.variants || []).filter((v) => v.active !== false).map((v) => v.price?.amount_minor ?? 0);
1101
- return prices.length ? Math.min(...prices) : 0;
1102
- }
1103
- const stamp = rawKey === "createdAt" ? product.created_at : product.updated_at;
1104
- return stamp ? Date.parse(stamp) : 0;
1105
- };
1106
- return [...products].sort((a, b) => descending ? value(b) - value(a) : value(a) - value(b));
1107
- };
1108
- var productPrice = (product) => {
1109
- const prices = (product.variants || []).filter((v) => v.active !== false).map((v) => v.price?.amount_minor ?? 0);
1110
- return prices.length ? Math.min(...prices) : 0;
1111
- };
1112
- var countBy = (items, key) => {
1113
- const counts = /* @__PURE__ */ new Map();
1114
- for (const item of items) {
1115
- const entry = key(item);
1116
- if (!entry?.name) continue;
1117
- const id = entry.slug || entry.name;
1118
- const existing = counts.get(id);
1119
- if (existing) existing.count += 1;
1120
- else counts.set(id, { ...entry, count: 1 });
1121
- }
1122
- return [...counts.values()].sort((a, b) => b.count - a.count);
1211
+ var productService = new ProductService();
1212
+
1213
+ // src/services/search-service.ts
1214
+ var num = (v) => {
1215
+ if (v === null || v.trim() === "") return void 0;
1216
+ const n = Number(v);
1217
+ return Number.isFinite(n) ? n : void 0;
1123
1218
  };
1124
- var SearchService = class _SearchService extends BaseService {
1125
- static instance;
1126
- static getInstance() {
1127
- if (!_SearchService.instance) _SearchService.instance = new _SearchService();
1128
- return _SearchService.instance;
1129
- }
1219
+ var SearchService = class extends CatalogService {
1130
1220
  emptyResult() {
1131
1221
  return {
1132
1222
  data: [],
1133
1223
  count: 0,
1134
1224
  totalPages: 0,
1135
1225
  categoryHierarchy: [],
1136
- facets: { priceStat: { min: void 0, max: void 0 }, categories: [], tags: [], allFilters: {} }
1226
+ facets: { priceStat: {}, categories: [], tags: [], allFilters: {} }
1137
1227
  };
1138
1228
  }
1139
- /**
1140
- * The listing page: `/products`, `/[slug]` for a category, and every filter the sidebar sets.
1141
- *
1142
- * Term and category are pushed to the API. Tags, the price range and the sort control are
1143
- * applied here, because GoCommerce has no parameter for them — so when any of those is active
1144
- * the request asks for the whole window rather than one page, and the result is paged locally.
1145
- */
1146
1229
  async searchWithUrl(url, slug) {
1147
1230
  try {
1148
- const params = new URLSearchParams(url.search);
1149
- const term = params.get("search") || params.get("q") || "";
1150
- const page = Math.max(1, Number(params.get("page") || 1) || 1);
1151
- const sort = params.get("sort") || "";
1152
- const tags = (params.get("tags") || "").split(",").map((t) => decodeURIComponent(t).trim().toLowerCase()).filter(Boolean);
1153
- const priceFrom = params.get("priceFrom") ? Number(params.get("priceFrom")) : void 0;
1154
- const priceTo = params.get("priceTo") ? Number(params.get("priceTo")) : void 0;
1155
- const categorySlug = slug && slug !== "products" ? slug : params.get("categories") || void 0;
1156
- const localFilters = tags.length > 0 || priceFrom !== void 0 || priceTo !== void 0;
1157
- const needsWholeWindow = localFilters || sortNeedsWholeCatalogue(sort) || Boolean(categorySlug);
1158
- let products = [];
1159
- let meta;
1160
- let category;
1161
- if (categorySlug) {
1162
- const res = await categoryService.fetchCategoryPage(categorySlug, { limit: MAX_LIMIT });
1163
- products = res.products;
1164
- meta = res.meta;
1165
- category = res.category;
1166
- if (term) {
1167
- const needle = term.toLowerCase();
1168
- products = products.filter((p) => `${p.title} ${p.description || ""}`.toLowerCase().includes(needle));
1169
- }
1170
- } else {
1171
- const res = await productService.fetchProducts({
1172
- q: term,
1173
- page: needsWholeWindow ? 1 : page,
1174
- limit: needsWholeWindow ? MAX_LIMIT : PAGE_SIZE
1175
- });
1176
- products = res.products;
1177
- meta = res.meta;
1178
- }
1179
- const facetSource = products;
1180
- const priceMinor = facetSource.map(productPrice).filter((n) => Number.isFinite(n));
1181
- const currency = facetSource[0]?.variants?.[0]?.price?.currency || facetSource[0]?.currency;
1182
- const digits = currency ? 10 ** currencyFractionDigits(currency) : 100;
1183
- let filtered = products;
1184
- if (tags.length) {
1185
- filtered = filtered.filter((p) => (p.tags || []).some((tag) => tags.includes(tag.toLowerCase())));
1186
- }
1187
- if (priceFrom !== void 0) filtered = filtered.filter((p) => productPrice(p) / digits >= priceFrom);
1188
- if (priceTo !== void 0) filtered = filtered.filter((p) => productPrice(p) / digits <= priceTo);
1189
- filtered = sortProducts(filtered, sort);
1190
- const paged = needsWholeWindow ? filtered.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE) : filtered;
1191
- const count = needsWholeWindow ? filtered.length : meta?.total ?? filtered.length;
1231
+ const u = typeof url === "string" ? new URL(url, "http://localhost") : url;
1232
+ const p = u.searchParams;
1233
+ const [from, to] = (p.get("price") ?? "").split(/[,-]/);
1234
+ const res = await this.queryCatalog({
1235
+ page: num(p.get("page")),
1236
+ search: p.get("search") ?? p.get("q") ?? void 0,
1237
+ sort: p.get("sort") ?? void 0,
1238
+ category: slug || p.get("categories")?.split(",")[0] || void 0,
1239
+ priceFrom: num(p.get("priceFrom")) ?? num(from ?? null),
1240
+ priceTo: num(p.get("priceTo")) ?? num(to ?? null)
1241
+ });
1192
1242
  return {
1193
- data: paged.map(mapProduct),
1194
- count,
1195
- totalPages: Math.ceil(count / PAGE_SIZE) || (count ? 1 : 0),
1196
- // Only the category itself: its ancestors are named in `full_name` but their slugs are
1197
- // not served to a storefront, and a breadcrumb link with no destination is worse than
1198
- // no crumb.
1199
- categoryHierarchy: category ? [{ name: category.title, slug: category.slug }] : [],
1200
- facets: {
1201
- priceStat: priceMinor.length ? { min: Math.min(...priceMinor) / digits, max: Math.max(...priceMinor) / digits } : { min: void 0, max: void 0 },
1202
- categories: countBy(facetSource, (p) => p.category ? { name: p.category.title, slug: p.category.slug } : void 0),
1203
- tags: countBy(
1204
- facetSource.flatMap((p) => (p.tags || []).map((tag) => ({ tag }))),
1205
- ({ tag }) => ({ name: tag, slug: tag })
1206
- ),
1207
- allFilters: {}
1208
- }
1243
+ data: res.data,
1244
+ count: res.count,
1245
+ totalPages: res.noOfPage,
1246
+ page: res.page,
1247
+ categoryHierarchy: res.categoryHierarchy,
1248
+ facets: { priceStat: {}, categories: [], tags: [], allFilters: {} }
1209
1249
  };
1210
- } catch (error) {
1211
- if (error?.code !== "not_found") console.error("[gocommerce] search failed", error);
1212
- return this.emptyResult();
1250
+ } catch (err) {
1251
+ if (err?.status === 404) return this.emptyResult();
1252
+ throw err;
1213
1253
  }
1214
1254
  }
1215
- async searchWithQuery(queryString) {
1216
- const url = new URL("https://storefront.local/products");
1217
- if (queryString) url.searchParams.set("search", queryString);
1218
- return this.searchWithUrl(url);
1219
- }
1220
1255
  };
1221
- var searchService = SearchService.getInstance();
1222
- var MeilisearchService = class _MeilisearchService extends BaseService {
1223
- static instance;
1224
- static getInstance() {
1225
- if (!_MeilisearchService.instance) _MeilisearchService.instance = new _MeilisearchService();
1226
- return _MeilisearchService.instance;
1227
- }
1228
- async search(params = {}) {
1229
- const page = Math.max(1, Number(params.page || 1) || 1);
1230
- const { products, meta } = await productService.fetchProducts({
1231
- q: params.q || "",
1232
- page,
1233
- limit: params.limit || PAGE_SIZE
1234
- });
1235
- const hits = products.map(mapProduct);
1256
+ var searchService = new SearchService();
1257
+
1258
+ // src/services/meilisearch-service.ts
1259
+ var MeilisearchService = class extends CatalogService {
1260
+ /** `{ query, categories, page }` → a Meilisearch-shaped answer: `hits`, `totalHits`, `totalPages`. */
1261
+ async search({
1262
+ query,
1263
+ search,
1264
+ categories,
1265
+ page = 1,
1266
+ limit
1267
+ } = {}) {
1268
+ const res = await this.queryCatalog({ page, limit, search: query ?? search, category: categories || void 0 });
1236
1269
  return {
1237
- hits,
1238
- data: hits,
1239
- estimatedTotalHits: meta?.total ?? hits.length,
1240
- count: meta?.total ?? hits.length,
1241
- page,
1242
- totalPages: meta?.total_pages ?? 1,
1243
- hitsPerPage: meta?.limit ?? PAGE_SIZE,
1244
- facetDistribution: {},
1245
- processingTimeMs: 0,
1246
- query: params.q || ""
1270
+ hits: res.data,
1271
+ totalHits: res.count,
1272
+ estimatedTotalHits: res.count,
1273
+ totalPages: res.noOfPage,
1274
+ page: res.page,
1275
+ categories: res.categoryHierarchy,
1276
+ facetDistribution: {}
1247
1277
  };
1248
1278
  }
1249
- async searchAutoComplete(params = {}) {
1250
- const { products } = await productService.fetchProducts({ q: params.q || "", page: 1, limit: params.limit || 8 });
1251
- const hits = products.map((product) => ({
1252
- id: product.id,
1253
- name: product.title,
1254
- title: product.title,
1255
- slug: product.slug,
1256
- thumbnail: mapProduct(product)?.thumbnail || null
1257
- }));
1258
- return { hits, data: hits, count: hits.length, query: params.q || "" };
1259
- }
1260
- };
1261
- var meilisearchService = MeilisearchService.getInstance();
1262
- var AutocompleteService = class _AutocompleteService extends BaseService {
1263
- static instance;
1264
- static getInstance() {
1265
- if (!_AutocompleteService.instance) _AutocompleteService.instance = new _AutocompleteService();
1266
- return _AutocompleteService.instance;
1267
- }
1268
- async list({ page = 1, q = "" } = {}) {
1269
- const { products, meta } = await productService.fetchProducts({ q, page, limit: 10 });
1270
- return fromListMeta(
1271
- products.map((product) => ({ id: product.id, name: product.title, slug: product.slug })),
1272
- meta,
1273
- page
1274
- );
1279
+ /** The header's type-ahead: `{ data: [{ slug, title, thumbnail, price }] }`. */
1280
+ async searchAutoComplete({ query, search, limit = 8 } = {}) {
1281
+ const q = (query ?? search ?? "").trim();
1282
+ if (!q) return { data: [] };
1283
+ if (await this.facts.pluginOn("meilisearch")) {
1284
+ const res = await this.data("/x/meilisearch/search", { query: { q, limit } });
1285
+ return { data: (res.hits ?? []).map(fromSearchDoc) };
1286
+ }
1287
+ const rows = await this.data("/api/products", { query: { q, limit, channel: this.creds.channel } }) ?? [];
1288
+ return { data: rows.map((p) => toProduct(p)) };
1275
1289
  }
1276
1290
  };
1277
- var autocompleteService = AutocompleteService.getInstance();
1278
- var resolveProductIndex = async (ids, fetchFn) => {
1279
- const wanted = [...new Set(ids.filter((id) => typeof id === "number"))];
1280
- const service = fetchFn ? new ProductService(fetchFn) : productService;
1281
- await Promise.all(wanted.filter((id) => !productCache.has(id)).map((id) => service.fetchProductById(id)));
1282
- const index = /* @__PURE__ */ new Map();
1283
- for (const id of wanted) {
1284
- const product = productCache.get(id);
1285
- if (product) index.set(id, product);
1286
- }
1287
- return index;
1288
- };
1291
+ var meilisearchService = new MeilisearchService();
1289
1292
 
1290
- // src/services/cart.ts
1291
- var REMOVE_LINE = -9999999;
1292
- var CART_ID_KEY = "cart_id";
1293
- var readStoredCartId = () => {
1294
- try {
1295
- return typeof window !== "undefined" ? window.localStorage?.getItem(CART_ID_KEY) || null : null;
1296
- } catch {
1297
- return null;
1298
- }
1299
- };
1300
- var storeCartId = (cartId) => {
1301
- if (!cartId) return;
1302
- try {
1303
- window?.localStorage?.setItem(CART_ID_KEY, cartId);
1304
- } catch {
1293
+ // src/services/category-service.ts
1294
+ var asList = (rows) => ({
1295
+ data: rows,
1296
+ count: rows.length,
1297
+ pageSize: rows.length,
1298
+ noOfPage: 1,
1299
+ page: 1
1300
+ });
1301
+ var CategoryService = class extends BaseService {
1302
+ facts = new StoreFacts(this._fetch);
1303
+ /** Every category, flat, each naming its parent. The storefront builds the tree. */
1304
+ async fetchAllCategories(_args = {}) {
1305
+ const all = await this.facts.categories();
1306
+ return asList(all.map(flat));
1305
1307
  }
1306
- };
1307
- var forgetCartId = () => {
1308
- try {
1309
- window?.localStorage?.removeItem(CART_ID_KEY);
1310
- } catch {
1308
+ async fetchFeaturedCategories({ limit = 18 } = {}) {
1309
+ const roots = (await this.facts.categories()).filter((c) => c.parent_id === null);
1310
+ return asList(roots.slice(0, Math.max(0, Number(limit) || 18)).map(flat));
1311
1311
  }
1312
- };
1313
- var usableId = (cartId) => cartId && cartId !== "undefined" && cartId !== "null" ? cartId : null;
1314
- var CartService = class _CartService extends BaseService {
1315
- static instance;
1316
- static getInstance() {
1317
- if (!_CartService.instance) _CartService.instance = new _CartService();
1318
- return _CartService.instance;
1319
- }
1320
- /** Turns a GoCommerce cart into the shape the storefront's cart, drawer and checkout read. */
1321
- async present(cart) {
1322
- if (!cart) return {};
1323
- storeCartId(cart.id);
1324
- const [index, store] = await Promise.all([
1325
- // Cart lines name a product by id only, so slug and image are filled in from the catalogue.
1326
- resolveProductIndex(
1327
- (cart.line_items || []).map((line) => line.product_id),
1328
- this.getFetch()
1329
- ),
1330
- readStaticStore()
1331
- ]);
1332
- return mapCart(cart, readCheckoutDetails(cart.id), index, store);
1312
+ async fetchFooterCategories(args = {}) {
1313
+ return this.fetchFeaturedCategories(args);
1333
1314
  }
1334
- /** Opens a cart. The email is optional here and is the only field `POST /api/carts` accepts. */
1335
- async openCart(email) {
1336
- const res = await this.api("POST", "/api/carts", email ? { email } : {});
1337
- storeCartId(res.data?.id);
1338
- return res.data;
1315
+ /** The nested tree, roots first. */
1316
+ async getMegamenu(_args = {}) {
1317
+ const tree = await this.data("/api/categories") ?? [];
1318
+ return tree.map(toCategory);
1339
1319
  }
1340
- async readCart(cartId) {
1341
- let cart = null;
1342
- try {
1343
- const res = await this.api("GET", `/api/carts/${encodeURIComponent(cartId)}`);
1344
- cart = res.data ?? null;
1345
- } catch {
1346
- return null;
1347
- }
1348
- if (cart && cart.status && cart.status !== "open") {
1349
- forgetCartId();
1350
- return null;
1351
- }
1352
- return cart;
1320
+ async fetchCategory(slug) {
1321
+ const c = await this.data(`/api/categories/${encodeURIComponent(slug)}`, { query: { limit: 1 } });
1322
+ return toCategory(c);
1353
1323
  }
1354
1324
  /**
1355
- * Is the cart behind this token gone for good — expired, unknown, or already checked out?
1356
- *
1357
- * Asked by re-reading the cart rather than by matching the failure's wording, because the API
1358
- * reports several unrelated things the same way: a dead cart and an unknown payment code are both
1359
- * `404 not_found`. The status is the fact; the message is prose.
1325
+ * kitcommerce-core's category filter asks for `/api/categories/all` by path,
1326
+ * through the family's raw `get`. That is a Litekart path the rest-guard
1327
+ * would swallow, so it is answered here, from the engine's tree.
1360
1328
  */
1361
- async cartIsSpent(cartId) {
1362
- try {
1363
- const res = await this.api("GET", `/api/carts/${encodeURIComponent(cartId)}`);
1364
- return !res.data || Boolean(res.data.status) && res.data.status !== "open";
1365
- } catch {
1366
- return true;
1367
- }
1329
+ async get(path) {
1330
+ if (path.split("?")[0] === "/api/categories/all") return await this.fetchAllCategories();
1331
+ return super.get(path);
1368
1332
  }
1369
- /** One line-item write against a cart that exists. Returns the cart the write left behind. */
1370
- async writeLine(cartId, { variantId, qty, lineId, removing }) {
1371
- const cart = encodeURIComponent(cartId);
1372
- if (lineId) {
1373
- const line = encodeURIComponent(String(lineId));
1374
- const res2 = removing ? await this.api("DELETE", `/api/carts/${cart}/line-items/${line}`) : await this.api("PATCH", `/api/carts/${cart}/line-items/${line}`, { quantity: qty });
1375
- return res2.data ?? null;
1376
- }
1377
- if (removing) return this.readCart(cartId);
1378
- const res = await this.api("POST", `/api/carts/${cart}/line-items`, {
1379
- variant_id: Number(variantId),
1380
- quantity: qty
1381
- });
1382
- return res.data ?? null;
1333
+ };
1334
+ var flat = (c) => ({ ...toCategory(c), children: [] });
1335
+ var categoryService = new CategoryService();
1336
+
1337
+ // src/services/collection-service.ts
1338
+ var CollectionService = class extends BaseService {
1339
+ async list({ page = 1, limit = 24 } = {}) {
1340
+ const env = await this.engine("/api/collections", { query: { page, limit } });
1341
+ return toPage(env, toCollection);
1342
+ }
1343
+ /** A collection page: the collection, and its products in the merchant's order. */
1344
+ async getOne(slug, { page = 1, limit = 48 } = {}) {
1345
+ const env = await this.engine(
1346
+ `/api/collections/${encodeURIComponent(slug)}`,
1347
+ { query: { page, limit } }
1348
+ );
1349
+ const products = (env.data.products ?? []).map((p) => toProduct(p));
1350
+ return {
1351
+ ...toCollection(env.data),
1352
+ products,
1353
+ // The family's shape for a collection's members.
1354
+ collectionvalues: products.map((p) => ({ products: p })),
1355
+ count: env.meta?.total ?? products.length,
1356
+ noOfPage: env.meta?.total_pages ?? 1,
1357
+ page: env.meta?.page ?? page
1358
+ };
1359
+ }
1360
+ /** Collection-level ratings are a Litekart aggregate; the engine has none to report. */
1361
+ async getAllRatings() {
1362
+ return { data: [] };
1383
1363
  }
1364
+ };
1365
+ var collectionService = new CollectionService();
1366
+
1367
+ // src/services/cart-service.ts
1368
+ var REMOVE = -9999999;
1369
+ var CartService = class extends BaseService {
1370
+ facts = new StoreFacts(this._fetch);
1384
1371
  async getCartByCartId(cartId) {
1385
- const id = usableId(cartId) || readStoredCartId();
1386
- if (!id) return {};
1387
- return this.present(await this.readCart(id));
1372
+ const id = clean(cartId);
1373
+ if (!id) return emptyCart(await this.currency());
1374
+ try {
1375
+ return await this.present(await this.data(`/api/carts/${encodeURIComponent(id)}`));
1376
+ } catch (err) {
1377
+ if (err instanceof GoCommerceError && err.status === 404) return emptyCart(await this.currency());
1378
+ throw err;
1379
+ }
1388
1380
  }
1389
- async fetchCartData() {
1390
- const id = readStoredCartId();
1391
- if (!id) return {};
1392
- return this.present(await this.readCart(id));
1381
+ async fetchCartData(cartId) {
1382
+ return this.getCartByCartId(cartId ?? storedCartId());
1393
1383
  }
1384
+ /**
1385
+ * The cart after an order: the engine marks it `converted` and keeps its
1386
+ * lines, and this answers it with none — which is how the storefront knows
1387
+ * to clear the bag on the success page.
1388
+ */
1394
1389
  async refereshCart() {
1395
- return this.fetchCartData();
1390
+ const id = storedCartId();
1391
+ const cart = await this.getCartByCartId(id);
1392
+ if (id && cart.status === "converted") forgetCartExtras(id);
1393
+ return cart;
1396
1394
  }
1397
1395
  /**
1398
- * Add, change or remove a line.
1399
- *
1400
- * `qty` is the line's new quantity, not a delta — which is how the shared cart store calls it
1401
- * (its stepper sends `qty ± 1`), and what `PATCH .../line-items/{lineId}` takes. A quantity of
1402
- * zero removes the line, and so does the store's `REMOVE_LINE` sentinel.
1403
- *
1404
- * A cart token in this browser can be dead — expired, wiped server-side, or already checked out —
1405
- * and the API then answers "cart not found", which is what the shopper was shown when they
1406
- * clicked Add to bag. That is a token this storefront is holding, not anything they did, so a
1407
- * dead one is dropped and the item is added to a fresh cart instead of reporting it.
1396
+ * `qty` is a change, not a total: +1 from a product page, −1 from a card's
1397
+ * minus button. With no cart yet, one is opened and remembered.
1408
1398
  */
1409
1399
  async addToCart({
1410
- variantId,
1411
- qty,
1412
1400
  cartId,
1413
- lineId
1401
+ lineId,
1402
+ qty = 1,
1403
+ variantId
1414
1404
  }) {
1415
- const removing = qty === REMOVE_LINE || qty <= 0;
1416
- if (!removing && !variantId) throw new Error("A variant is required to add an item to the cart.");
1417
- let id = usableId(cartId) || readStoredCartId();
1418
- if (id) {
1419
- let cart = null;
1420
- let spent = false;
1421
- try {
1422
- cart = await this.writeLine(id, { variantId, qty, lineId, removing });
1423
- } catch (error) {
1424
- if (!await this.cartIsSpent(id)) throw error;
1425
- spent = true;
1405
+ let id = clean(cartId) ?? storedCartId();
1406
+ if (lineId && id) {
1407
+ const cart = await this.data(`/api/carts/${encodeURIComponent(id)}`);
1408
+ const line = (cart.line_items ?? []).find((l) => String(l.id) === String(lineId));
1409
+ if (line) {
1410
+ const next = qty === REMOVE ? 0 : line.quantity + Number(qty);
1411
+ return this.setQuantity(id, line.id, next);
1426
1412
  }
1427
- if (!spent) return this.present(cart);
1428
- forgetCartId();
1429
- id = null;
1430
1413
  }
1431
- if (removing) return {};
1432
- const opened = await this.openCart(readCheckoutDetails(null).email);
1433
- if (!opened?.id) throw new Error("Could not open a cart on this store.");
1434
- return this.present(await this.writeLine(opened.id, { variantId, qty, lineId: null, removing: false }));
1414
+ if (qty === REMOVE || Number(qty) <= 0) return this.getCartByCartId(id);
1415
+ if (!variantId) throw new GoCommerceError("Please choose an option before adding this to your bag.", 400);
1416
+ if (!id) id = await this.open();
1417
+ try {
1418
+ return await this.present(
1419
+ await this.data(`/api/carts/${encodeURIComponent(id)}/line-items`, {
1420
+ method: "POST",
1421
+ body: { variant_id: Number(variantId), quantity: Number(qty) }
1422
+ })
1423
+ );
1424
+ } catch (err) {
1425
+ if (err instanceof GoCommerceError && (err.status === 404 || /checked out/.test(err.message))) {
1426
+ const fresh = await this.open();
1427
+ return this.present(
1428
+ await this.data(`/api/carts/${encodeURIComponent(fresh)}/line-items`, {
1429
+ method: "POST",
1430
+ body: { variant_id: Number(variantId), quantity: Number(qty) }
1431
+ })
1432
+ );
1433
+ }
1434
+ throw err;
1435
+ }
1435
1436
  }
1437
+ /** `qty` is the new total; 0 takes the line out. */
1436
1438
  async updateCart({
1437
- qty,
1438
1439
  cartId,
1439
- lineId = null,
1440
- productId,
1441
- variantId
1440
+ lineId,
1441
+ qty
1442
1442
  }) {
1443
- return this.addToCart({ productId, variantId, qty, cartId, lineId });
1444
- }
1445
- async removeCart({ cartId, lineId = null }) {
1446
- return this.addToCart({ qty: REMOVE_LINE, cartId, lineId });
1443
+ const id = clean(cartId) ?? storedCartId();
1444
+ if (!id) return emptyCart(await this.currency());
1445
+ return this.setQuantity(id, lineId, Number(qty));
1446
+ }
1447
+ async removeCart({ cartId, lineId }) {
1448
+ const id = clean(cartId) ?? storedCartId();
1449
+ if (!id) return emptyCart(await this.currency());
1450
+ return this.present(
1451
+ await this.data(`/api/carts/${encodeURIComponent(id)}/line-items/${encodeURIComponent(String(lineId))}`, {
1452
+ method: "DELETE"
1453
+ })
1454
+ );
1447
1455
  }
1448
1456
  /**
1449
- * The address step's write.
1450
- *
1451
- * GoCommerce has no endpoint that changes a cart after it is opened, and no address on it: these
1452
- * fields are arguments to checkout. They are kept against this cart id in the browser and sent
1453
- * when the order is placed — see checkout-details.ts. The email additionally seeds a cart that
1454
- * has not been opened yet, which is the one moment GoCommerce does accept it.
1457
+ * Contact details and addresses, from the checkout's address step. The
1458
+ * email goes to the engine — it is how an abandoned cart is followed up —
1459
+ * and the rest is kept for the checkout request.
1455
1460
  */
1456
- async updateCart2({
1457
- cartId,
1458
- email,
1459
- phone,
1460
- billingAddress,
1461
- shippingAddress,
1462
- isBillingAddressSameAsShipping
1463
- }) {
1464
- let id = usableId(cartId) || readStoredCartId();
1465
- let cart = id ? await this.readCart(id) : null;
1466
- if (!cart) {
1467
- cart = await this.openCart(email);
1468
- id = cart?.id ?? null;
1461
+ async updateCart2(args) {
1462
+ const id = clean(args.cartId) ?? storedCartId();
1463
+ if (!id) return emptyCart(await this.currency());
1464
+ const patch = {};
1465
+ if (args.phone !== void 0) patch.phone = args.phone || void 0;
1466
+ if (args.shippingAddress !== void 0) {
1467
+ patch.shippingAddress = args.shippingAddress;
1468
+ if (args.shippingAddress?.phone && !patch.phone) patch.phone = String(args.shippingAddress.phone);
1469
1469
  }
1470
- if (!id) throw new Error("Could not open a cart on this store.");
1471
- const name = [shippingAddress?.firstName, shippingAddress?.lastName].filter(Boolean).join(" ").trim() || [billingAddress?.firstName, billingAddress?.lastName].filter(Boolean).join(" ").trim() || void 0;
1472
- writeCheckoutDetails(id, {
1473
- ...email ? { email } : {},
1474
- ...phone || shippingAddress?.phone ? { phone: phone || shippingAddress?.phone } : {},
1475
- ...name ? { name } : {},
1476
- ...shippingAddress ? { shippingAddress } : {},
1477
- ...billingAddress && !isBillingAddressSameAsShipping ? { billingAddress } : shippingAddress ? { billingAddress: shippingAddress } : {}
1470
+ if (args.billingAddress !== void 0 || args.isBillingAddressSameAsShipping) {
1471
+ patch.billingAddress = args.isBillingAddressSameAsShipping ? null : args.billingAddress ?? null;
1472
+ }
1473
+ const before = cartExtras(id);
1474
+ const country = (a) => String(a?.countryCode || a?.country || "").toUpperCase();
1475
+ if (args.shippingAddress !== void 0 && country(args.shippingAddress) !== country(before.shippingAddress)) {
1476
+ patch.shippingRateId = null;
1477
+ patch.shippingRate = null;
1478
+ }
1479
+ saveCartExtras(id, patch);
1480
+ const email = args.email ?? (args.shippingAddress?.email ? String(args.shippingAddress.email) : void 0);
1481
+ if (email !== void 0) {
1482
+ return this.present(
1483
+ await this.data(`/api/carts/${encodeURIComponent(id)}/email`, { method: "PUT", body: { email } })
1484
+ );
1485
+ }
1486
+ return this.getCartByCartId(id);
1487
+ }
1488
+ /**
1489
+ * A discount code. The engine prices it against the basket now and decides
1490
+ * it again at checkout; what it answers is kept so the bag can show it,
1491
+ * because the cart itself does not carry the code.
1492
+ */
1493
+ async applyCoupon({ cartId, couponCode }) {
1494
+ const id = clean(cartId) ?? storedCartId();
1495
+ if (!id) throw new GoCommerceError("Add something to your bag before applying a code.", 400);
1496
+ const cart = await this.data(`/api/carts/${encodeURIComponent(id)}`);
1497
+ const discount = await this.data(`/api/carts/${encodeURIComponent(id)}/discount`, {
1498
+ method: "PUT",
1499
+ body: { code: String(couponCode ?? "").trim(), ...cart.email ? { email: cart.email } : {} }
1478
1500
  });
1501
+ saveCartExtras(id, { discount: { ...discount, code: discount.code || String(couponCode).trim() } });
1479
1502
  return this.present(cart);
1480
1503
  }
1481
- /** Nothing to reserve ahead of payment: `POST /api/checkout/{code}` is one transaction. */
1482
- async completeCart(cartId) {
1483
- return this.getCartByCartId(cartId);
1484
- }
1485
- /** Remembered so the payment step can re-select it; GoCommerce takes the code at checkout. */
1486
- async updateCartPaymentMethod({ cartId, paymentMethod }) {
1487
- const id = usableId(cartId) || readStoredCartId();
1488
- if (!id) return {};
1489
- const cart = await this.readCart(id);
1490
- const presented = await this.present(cart);
1491
- if (presented && paymentMethod) presented.paymentMethod = paymentMethod;
1492
- return presented;
1493
- }
1494
- // GoCommerce has no discount engine, so there is no code to accept. Saying so beats a silent
1495
- // no-op that leaves the shopper waiting for a discount that is never coming.
1496
- async applyCoupon(_params) {
1497
- throw new Error("Discount codes are not available on this store.");
1504
+ async removeCoupon(cartId) {
1505
+ const id = clean(cartId) ?? storedCartId();
1506
+ if (!id) return emptyCart(await this.currency());
1507
+ await this.engine(`/api/carts/${encodeURIComponent(id)}/discount`, { method: "DELETE" });
1508
+ saveCartExtras(id, { discount: null });
1509
+ return this.getCartByCartId(id);
1510
+ }
1511
+ /** The delivery option the shopper picked, priced from the engine's own quote. */
1512
+ async updateShippingRate({ cartId, shippingRateId }) {
1513
+ const id = clean(cartId) ?? storedCartId();
1514
+ if (!id) return emptyCart(await this.currency());
1515
+ const ship = cartExtras(id).shippingAddress;
1516
+ const country = String(ship?.countryCode || ship?.country || "").toUpperCase();
1517
+ if (!country) throw new GoCommerceError("Add a delivery address first.", 400);
1518
+ const quote2 = await this.data("/api/checkout/rates", { query: { cart: id, country, state: ship?.state ? String(ship.state) : void 0 } });
1519
+ const rate = (quote2.rates ?? []).find((r) => String(r.rate_id) === String(shippingRateId));
1520
+ if (!rate) throw new GoCommerceError("That delivery option is not available for this address any more.", 409);
1521
+ saveCartExtras(id, {
1522
+ shippingRateId: String(rate.rate_id),
1523
+ shippingRate: {
1524
+ id: String(rate.rate_id),
1525
+ name: rate.name,
1526
+ minor: rate.price.amount_minor,
1527
+ currency: rate.price.currency
1528
+ }
1529
+ });
1530
+ return this.getCartByCartId(id);
1531
+ }
1532
+ /** The payment method is chosen at checkout, by which checkout route is called. */
1533
+ async updateCartPaymentMethod({ cartId }) {
1534
+ return this.getCartByCartId(clean(cartId) ?? storedCartId());
1535
+ }
1536
+ async completeCart() {
1537
+ throw new NotSupportedError("CartService", "completeCart", "an order is placed through checkoutService");
1538
+ }
1539
+ // ------------------------------------------------------------ internals
1540
+ async setQuantity(cartId, lineId, qty) {
1541
+ const path = `/api/carts/${encodeURIComponent(cartId)}/line-items/${encodeURIComponent(String(lineId))}`;
1542
+ if (qty <= 0) return this.present(await this.data(path, { method: "DELETE" }));
1543
+ return this.present(await this.data(path, { method: "PATCH", body: { quantity: qty } }));
1544
+ }
1545
+ /** A new cart, remembered — and priced for the signed-in shopper's group when the engine allows it. */
1546
+ async open() {
1547
+ const channel = this.creds.channel;
1548
+ const cart = await this.data("/api/carts", { method: "POST", ...channel ? { body: { channel } } : {} });
1549
+ rememberCartId(cart.id);
1550
+ if (sessionToken()) await this.claimCartForAccount(cart.id);
1551
+ return cart.id;
1552
+ }
1553
+ async currency() {
1554
+ try {
1555
+ return (await this.facts.ready()).currency;
1556
+ } catch {
1557
+ return "USD";
1558
+ }
1498
1559
  }
1499
- async removeCoupon() {
1500
- return this.fetchCartData();
1560
+ /** The engine's cart with the browser-held extras and each line's picture and link. */
1561
+ async present(cart) {
1562
+ const ids = [...new Set((cart.line_items ?? []).map((l) => l.product_id))];
1563
+ const products = /* @__PURE__ */ new Map();
1564
+ await Promise.all(
1565
+ ids.map(async (pid) => {
1566
+ products.set(pid, await this.productFor(pid));
1567
+ })
1568
+ );
1569
+ return toCart(cart, cartExtras(cart.id), (l) => {
1570
+ const p = products.get(l.product_id);
1571
+ if (!p) return {};
1572
+ const v = (p.variants ?? []).find((x) => x.id === l.variant_id);
1573
+ return { slug: p.slug, thumbnail: v?.image?.url ?? p.image_url ?? null };
1574
+ });
1501
1575
  }
1502
- /** Shipping is priced by the store at checkout; there are no rates for a shopper to choose. */
1503
- async updateShippingRate({ cartId }) {
1504
- return this.getCartByCartId(cartId || "");
1576
+ productFor(id) {
1577
+ return remember(
1578
+ `${this.engineBase()}|product|${id}`,
1579
+ () => this.data(`/api/products/${id}`).catch(() => null)
1580
+ );
1505
1581
  }
1506
1582
  };
1507
- var cartService = CartService.getInstance();
1583
+ var clean = (id) => id && id !== "undefined" && id !== "null" ? id : null;
1584
+ var cartService = new CartService();
1508
1585
 
1509
- // src/services/checkout.ts
1510
- var CART_ID_KEY2 = "cart_id";
1511
- var readStoredCartId2 = () => {
1512
- try {
1513
- return typeof window !== "undefined" ? window.localStorage?.getItem(CART_ID_KEY2) || null : null;
1514
- } catch {
1515
- return null;
1516
- }
1517
- };
1518
- var METHOD_NAMES = {
1519
- cod: "Cash on delivery",
1520
- stripe: "Card",
1521
- razorpay: "Razorpay",
1522
- cashfree: "Cashfree",
1523
- paypal: "PayPal",
1524
- phonepe: "PhonePe",
1525
- manual: "Manual payment"
1526
- };
1527
- var installedCodes = [];
1528
- var goCommerceCode = (storefrontCode) => {
1529
- const match = installedCodes.find((code) => code.toLowerCase() === storefrontCode.toLowerCase());
1530
- return match || storefrontCode.toLowerCase();
1531
- };
1532
- var titleCase = (code) => code.charAt(0).toUpperCase() + code.slice(1);
1533
- var PaymentMethodService = class _PaymentMethodService extends BaseService {
1534
- static instance;
1535
- static getInstance() {
1536
- if (!_PaymentMethodService.instance) _PaymentMethodService.instance = new _PaymentMethodService();
1537
- return _PaymentMethodService.instance;
1538
- }
1539
- /**
1540
- * What this store accepts, from `GET /api/checkout`.
1541
- *
1542
- * The storefront branches on an uppercase code (`COD`, `STRIPE`, …) while GoCommerce installs
1543
- * them lowercase, so the code is uppercased for the UI and the original kept for the API call.
1544
- */
1545
- async list(_params = {}) {
1546
- const res = await this.api("GET", "/api/checkout");
1547
- const codes = res.data?.payment_methods || [];
1548
- installedCodes = codes;
1549
- const data = codes.map((code, index) => ({
1550
- id: code,
1551
- code: code.toUpperCase(),
1552
- name: METHOD_NAMES[code.toLowerCase()] || titleCase(code),
1553
- description: "",
1554
- active: true,
1555
- isTest: false,
1556
- img: null,
1557
- rank: index,
1558
- currency: res.data?.currency || null
1559
- }));
1560
- return { data, count: data.length, pageSize: data.length, noOfPage: data.length ? 1 : 0, page: 1 };
1586
+ // src/services/checkout-service.ts
1587
+ var CheckoutService = class extends BaseService {
1588
+ /** Delivery options for the address on the cart: `{ data: [{ id, name, base_rate }] }`. */
1589
+ async getShippingRates({ cartId } = {}) {
1590
+ const id = cartId || storedCartId();
1591
+ const ship = id ? cartExtras(id).shippingAddress : null;
1592
+ const country = String(ship?.countryCode || ship?.country || "").toUpperCase();
1593
+ if (!id || !country) return { data: [] };
1594
+ const quote2 = await this.data("/api/checkout/rates", { query: { cart: id, country, state: ship?.state ? String(ship.state) : void 0 } });
1595
+ return {
1596
+ data: (quote2.rates ?? []).map((r) => ({
1597
+ id: String(r.rate_id),
1598
+ name: r.name,
1599
+ description: null,
1600
+ base_rate: minorToMajor(r.price.amount_minor, r.price.currency),
1601
+ price: minorToMajor(r.price.amount_minor, r.price.currency),
1602
+ currencyCode: r.price.currency,
1603
+ // The engine's rates carry no delivery estimate; none is made up.
1604
+ estimated_min_days: null,
1605
+ estimated_max_days: null
1606
+ }))
1607
+ };
1561
1608
  }
1562
- };
1563
- var paymentMethodService = PaymentMethodService.getInstance();
1564
- var CheckoutService = class _CheckoutService extends BaseService {
1565
- static instance;
1566
- static getInstance() {
1567
- if (!_CheckoutService.instance) _CheckoutService.instance = new _CheckoutService();
1568
- return _CheckoutService.instance;
1609
+ /** Cash on delivery: the order is confirmed at once and paid on the doorstep. */
1610
+ async checkoutCOD({ cartId } = {}) {
1611
+ const result = await this.place("cod", cartId);
1612
+ return {
1613
+ order_no: result.order.number,
1614
+ orderNo: result.order.number,
1615
+ id: String(result.order.id),
1616
+ status: result.order.status
1617
+ };
1569
1618
  }
1570
1619
  /**
1571
- * Places the order.
1572
- *
1573
- * Everything the API requires and the cart cannot hold — email, name, phone, delivery address —
1574
- * comes from what the address step recorded against this cart. Missing pieces are named in the
1575
- * error rather than sent as blanks, because GoCommerce's own validation message ("address.line1
1576
- * is required") does not tell a shopper which screen to go back to.
1620
+ * Razorpay's modal. The engine has already created the Razorpay order; this
1621
+ * hands the storefront what the modal needs. A store running Razorpay's
1622
+ * hosted (redirect) mode cannot be driven from this storefront's modal flow,
1623
+ * and says so rather than opening a modal on an order it cannot pay.
1577
1624
  */
1578
- async place(storefrontCode, { cartId, origin, returnUrl }) {
1579
- const id = cartId && cartId !== "undefined" ? cartId : readStoredCartId2();
1580
- if (!id) throw new Error("There is no cart to check out.");
1581
- const details = readCheckoutDetails(id);
1582
- const address = toGoCommerceAddress(details.shippingAddress, details.phone);
1583
- if (!details.email) throw new Error("An email address is required to place this order \u2014 add one at the address step.");
1584
- if (!address) throw new Error("A complete delivery address is required to place this order \u2014 add one at the address step.");
1585
- const code = goCommerceCode(storefrontCode);
1586
- let res;
1587
- try {
1588
- res = await this.api(
1589
- "POST",
1590
- `/api/checkout/${encodeURIComponent(code)}`,
1591
- {
1592
- cart_id: id,
1593
- email: details.email,
1594
- ...details.name ? { name: details.name } : {},
1595
- ...details.phone ? { phone: details.phone } : {},
1596
- address,
1597
- ...returnUrl || origin ? { return_url: returnUrl || `${origin}/checkout/process` } : {}
1598
- },
1599
- // A double-submitted Place Order must not become two orders and two inventory holds.
1600
- { "Idempotency-Key": `${id}:${code}` }
1625
+ async checkoutRazorpay({ cartId } = {}) {
1626
+ const result = await this.place("razorpay", cartId);
1627
+ const data = result.payment.client_data ?? {};
1628
+ if (result.payment.kind !== "client_action" || !data.razorpay_order_id) {
1629
+ throw new GoCommerceError(
1630
+ "This store takes Razorpay payments on Razorpay\u2019s own page, which this storefront does not support yet.",
1631
+ 0
1601
1632
  );
1602
- } catch (error) {
1603
- if (await cartService.cartIsSpent(id)) {
1604
- throw new Error("This cart is no longer available \u2014 it has expired or was already checked out. Add the items to a new bag and try again.");
1605
- }
1606
- throw error;
1607
1633
  }
1608
- const order = res.data?.order;
1609
- const payment = res.data?.payment;
1610
- rememberOrderToken(order?.number, order?.access_token);
1611
- clearCheckoutDetails(id);
1612
- const index = await resolveProductIndex(
1613
- (order?.line_items || []).map((line) => line.product_id),
1614
- this.getFetch()
1615
- );
1616
1634
  return {
1617
- ...mapOrder(order, index) ?? {},
1618
- // The order number, under every name the storefront's payment step reads it by.
1619
- order_no: order?.number,
1620
- orderNo: order?.number,
1621
- code: order?.number,
1622
- payment: payment ?? null,
1623
- paymentKind: payment?.kind ?? "none",
1624
- // A gateway's own fields (a Razorpay order id, a Stripe client secret, a redirect url)
1625
- // ride on `client_data`; spreading them is what lets the storefront's per-gateway
1626
- // branches find what they look for without this connector naming each gateway.
1627
- ...payment?.client_data ?? {}
1635
+ order_no: result.order.number,
1636
+ id: data.razorpay_order_id,
1637
+ key_id: data.key_id,
1638
+ amount: Number(data.amount),
1639
+ currency: data.currency
1628
1640
  };
1629
1641
  }
1630
- async checkoutCOD({ cartId, origin }) {
1631
- return this.place("cod", { cartId, origin });
1632
- }
1633
- async checkoutPOS({ cartId, origin }) {
1634
- return this.place("pos", { cartId, origin });
1635
- }
1636
- async checkoutRazorpay({ cartId, origin }) {
1637
- return this.place("razorpay", { cartId, origin });
1638
- }
1639
- async checkoutStripe({ cartId, origin }) {
1640
- return this.place("stripe", { cartId, origin });
1641
- }
1642
- async checkoutCashfree({ cartId, origin }) {
1643
- return this.place("cashfree", { cartId, origin });
1642
+ /** The modal closed with a payment. The engine learns of it from Razorpay itself. */
1643
+ async captureRazorpayPayment({ razorpay_order_id }) {
1644
+ const order = placedOrderByReference(razorpay_order_id);
1645
+ if (!order) throw new GoCommerceError("That payment does not belong to an order placed from this browser.", 404);
1646
+ return { order_no: order.number, status: "processing" };
1647
+ }
1648
+ // The family's other gateways. GoCommerce's Stripe is a Payment Element
1649
+ // (a client secret, not a hosted page), and PayPal, Cashfree, PhonePe and
1650
+ // Affirm are not engine gateways at all; paymentMethodService never lists
1651
+ // them, so these are reached only by a storefront that hard-codes one.
1652
+ async checkoutStripe() {
1653
+ throw unsupported(
1654
+ "checkoutStripe",
1655
+ "GoCommerce\u2019s Stripe gateway uses the Payment Element, not a hosted checkout page"
1656
+ );
1644
1657
  }
1645
- async checkoutPaypal({ cartId, origin, return_url }) {
1646
- return this.place("paypal", { cartId, origin, returnUrl: return_url });
1658
+ async checkoutStripeCapture() {
1659
+ throw unsupported("checkoutStripeCapture", "Stripe confirms payments to the engine by webhook");
1647
1660
  }
1648
- async checkoutPhonepe({ cartId, origin }) {
1649
- return this.place("phonepe", { cartId, origin });
1661
+ async checkoutPaypal() {
1662
+ throw unsupported("checkoutPaypal", "the engine has no PayPal gateway");
1650
1663
  }
1651
- async createAffirmPayOrder({
1652
- cartId,
1653
- origin
1654
- }) {
1655
- return this.place("affirm", { cartId, origin });
1664
+ async capturePaypalPayment() {
1665
+ throw unsupported("capturePaypalPayment", "the engine has no PayPal gateway");
1656
1666
  }
1657
- // GoCommerce reconciles a payment through `POST /api/checkout/{code}/webhook`, which the gateway
1658
- // calls server to server. There is nothing for the browser to capture afterwards, so these keep
1659
- // the storefront's redirect moving with the order number it already has rather than pretending
1660
- // to perform a capture that this API does not offer.
1661
- settled(orderNo) {
1662
- return { order_no: orderNo || "", orderNo: orderNo || "", captured: false };
1667
+ async checkoutCashfree() {
1668
+ throw unsupported("checkoutCashfree", "the engine has no Cashfree gateway");
1663
1669
  }
1664
- async captureRazorpayPayment({ razorpay_order_id }) {
1665
- return this.settled(razorpay_order_id);
1670
+ async captureCashfreePayment() {
1671
+ throw unsupported("captureCashfreePayment", "the engine has no Cashfree gateway");
1666
1672
  }
1667
- async capturePhonepePayment({ phonepe_order_id }) {
1668
- return this.settled(phonepe_order_id);
1673
+ async checkoutPhonepe() {
1674
+ throw unsupported("checkoutPhonepe", "the engine has no PhonePe gateway");
1669
1675
  }
1670
- async captureCashfreePayment({ order_no }) {
1671
- return this.settled(order_no);
1676
+ async createAffirmPayOrder() {
1677
+ throw unsupported("createAffirmPayOrder", "the engine has no Affirm gateway");
1672
1678
  }
1673
- async checkoutStripeCapture({ order_no }) {
1674
- return this.settled(order_no);
1679
+ async confirmAffirmOrder() {
1680
+ throw unsupported("confirmAffirmOrder", "the engine has no Affirm gateway");
1675
1681
  }
1676
- async confirmAffirmOrder({ orderId }) {
1677
- return this.settled(orderId);
1682
+ async cancelAffirmOrder() {
1683
+ throw unsupported("cancelAffirmOrder", "the engine has no Affirm gateway");
1678
1684
  }
1679
- async cancelAffirmOrder({ orderId }) {
1680
- throw new Error(`Cancelling order ${orderId || ""} is not available on this store.`);
1685
+ async checkoutPOS() {
1686
+ throw unsupported("checkoutPOS", "point-of-sale orders are placed from the admin panel");
1681
1687
  }
1682
1688
  /**
1683
- * GoCommerce prices shipping when it creates the order — there is no rate list for a shopper to
1684
- * choose from. An empty list is the accurate answer, and the payment step renders no rate picker
1685
- * for it rather than an empty one.
1689
+ * One checkout attempt.
1690
+ *
1691
+ * The Idempotency-Key is kept with the cart and reused while the request is
1692
+ * the same, because a payment gateway that fails after the engine has
1693
+ * created the order leaves the cart converted: only a retry under the same
1694
+ * key resumes that order, and without one the shopper is stuck. A changed
1695
+ * request — a different address, a different method — gets a new key, since
1696
+ * the engine refuses a key replayed with a different body.
1686
1697
  */
1687
- async getShippingRates(_params) {
1688
- return { message: "This store does not offer selectable shipping rates", success: true, error: null, data: [] };
1698
+ async place(code, cartId) {
1699
+ const id = cartId || storedCartId();
1700
+ if (!id) throw new GoCommerceError("Your bag is empty.", 400);
1701
+ const extras = cartExtras(id);
1702
+ const ship = extras.shippingAddress;
1703
+ if (!ship) throw new GoCommerceError("Add a delivery address first.", 400);
1704
+ const cart = await this.data(`/api/carts/${encodeURIComponent(id)}`);
1705
+ const email = cart.email || (ship.email ? String(ship.email) : "");
1706
+ if (!email) throw new GoCommerceError("Add an email address so we can send your receipt.", 400);
1707
+ const address = toEngineAddress(ship);
1708
+ const body = {
1709
+ cart_id: id,
1710
+ email,
1711
+ ...extras.phone || address.phone ? { phone: String(extras.phone || address.phone) } : {},
1712
+ ...address.name ? { name: address.name } : {},
1713
+ address,
1714
+ ...extras.shippingRateId ? { shipping_rate_id: Number(extras.shippingRateId) } : {}
1715
+ };
1716
+ const serialised = JSON.stringify(body);
1717
+ const key = extras.attempt?.body === `${code}:${serialised}` ? extras.attempt.key : newKey();
1718
+ saveCartExtras(id, { attempt: { key, body: `${code}:${serialised}` } });
1719
+ const result = await this.data(`/api/checkout/${encodeURIComponent(code)}`, {
1720
+ method: "POST",
1721
+ body,
1722
+ headers: { "Idempotency-Key": key }
1723
+ });
1724
+ if (result.order.access_token) {
1725
+ rememberOrder({
1726
+ number: result.order.number,
1727
+ token: result.order.access_token,
1728
+ cartId: id,
1729
+ reference: result.payment.client_data?.razorpay_order_id ?? result.payment.reference
1730
+ });
1731
+ if (sessionToken()) {
1732
+ await this.engine("/x/identity/me/orders", {
1733
+ method: "POST",
1734
+ body: { number: result.order.number, token: result.order.access_token },
1735
+ auth: true
1736
+ }).catch(() => void 0);
1737
+ }
1738
+ }
1739
+ saveCartExtras(id, { attempt: null });
1740
+ return result;
1689
1741
  }
1690
1742
  };
1691
- var checkoutService = CheckoutService.getInstance();
1743
+ var unsupported = (method, why) => new NotSupportedError("CheckoutService", method, why);
1744
+ function newKey() {
1745
+ const c = globalThis.crypto;
1746
+ if (c?.randomUUID) return c.randomUUID();
1747
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;
1748
+ }
1749
+ var checkoutService = new CheckoutService();
1692
1750
 
1693
- // src/services/orders.ts
1694
- var usable = (value) => value && value !== "undefined" && value !== "null" ? value : null;
1695
- var OrderService = class _OrderService extends BaseService {
1696
- static instance;
1697
- static getInstance() {
1698
- if (!_OrderService.instance) _OrderService.instance = new _OrderService();
1699
- return _OrderService.instance;
1700
- }
1701
- async readOrder(orderNumber, token) {
1702
- try {
1703
- const res = await this.api("GET", `/api/orders/${encodeURIComponent(orderNumber)}?token=${encodeURIComponent(token)}`);
1704
- return res.data ?? null;
1705
- } catch {
1706
- return null;
1707
- }
1751
+ // src/services/payment-method-service.ts
1752
+ var DRIVABLE = {
1753
+ cod: { code: "COD", img: "/payment/cod.svg" },
1754
+ razorpay: { code: "RAZORPAY" }
1755
+ };
1756
+ var reported2 = /* @__PURE__ */ new Set();
1757
+ var PaymentMethodService = class extends BaseService {
1758
+ facts = new StoreFacts(this._fetch);
1759
+ async list(_args = {}) {
1760
+ const options = await this.facts.checkoutOptions();
1761
+ const methods = options.methods ?? [];
1762
+ const data = methods.filter((m) => {
1763
+ if (DRIVABLE[m.code]) return true;
1764
+ if (!reported2.has(m.code)) {
1765
+ reported2.add(m.code);
1766
+ console.warn(
1767
+ `[gocommerce] payment method "${m.code}" is switched on but this storefront cannot drive its flow, so it is not offered.`
1768
+ );
1769
+ }
1770
+ return false;
1771
+ }).map((m, i) => ({
1772
+ id: m.code,
1773
+ code: DRIVABLE[m.code].code,
1774
+ engineCode: m.code,
1775
+ name: m.name,
1776
+ title: m.name,
1777
+ description: "",
1778
+ img: DRIVABLE[m.code].img ?? null,
1779
+ rank: i,
1780
+ active: true,
1781
+ isActive: true
1782
+ }));
1783
+ return { data, count: data.length, pageSize: data.length, noOfPage: 1, page: 1 };
1708
1784
  }
1709
- async present(order) {
1710
- if (!order) return null;
1711
- const index = await resolveProductIndex(
1712
- (order.line_items || []).map((line) => line.product_id),
1713
- this.getFetch()
1714
- );
1715
- return mapOrder(order, index);
1785
+ };
1786
+ var paymentMethodService = new PaymentMethodService();
1787
+
1788
+ // src/services/coupon-service.ts
1789
+ var CouponService = class extends BaseService {
1790
+ async listCoupons(_args = {}) {
1791
+ return emptyPage();
1716
1792
  }
1793
+ };
1794
+ var couponService = new CouponService();
1795
+
1796
+ // src/services/order-service.ts
1797
+ var OrderService = class extends BaseService {
1717
1798
  /**
1718
- * The confirmation view, rebuilt from the cart that became the order.
1799
+ * The order-success page's lookup, by the number and cart in its URL.
1719
1800
  *
1720
- * Everything a receipt needs is on the converted cart except the address, which was never stored
1721
- * on it — so that block is simply absent rather than invented.
1801
+ * It runs on the server, where neither the token nor the session exists —
1802
+ * they live in the shopper's browser — so there it answers nothing and the
1803
+ * page says the details are not available yet. In the browser it answers
1804
+ * the order. Inventing a server-side credential from the cart token in the
1805
+ * URL would make that URL, which lands in history and referrers, a key to
1806
+ * the shopper's address.
1722
1807
  */
1723
- async orderFromCart(cartId, orderNumber) {
1724
- let cart = null;
1808
+ async listOrdersByParent({ orderNo, cartId } = {}) {
1809
+ const number = clean2(orderNo) ?? (clean2(cartId) ? placedOrderForCart(clean2(cartId))?.number : void 0);
1810
+ if (!number) return { data: [] };
1725
1811
  try {
1726
- const res = await this.api("GET", `/api/carts/${encodeURIComponent(cartId)}`);
1727
- cart = res.data ?? null;
1728
- } catch {
1729
- return null;
1812
+ return { data: [await this.getOrder(number)] };
1813
+ } catch (err) {
1814
+ if (err instanceof GoCommerceError && (err.status === 404 || err.status === 401)) return { data: [] };
1815
+ throw err;
1730
1816
  }
1731
- if (!cart) return null;
1732
- const lines = cart.line_items || [];
1733
- const index = await resolveProductIndex(
1734
- lines.map((line) => line.product_id),
1735
- this.getFetch()
1736
- );
1737
- const subtotal = fromMoney(cart.subtotal);
1738
- return {
1739
- id: null,
1740
- orderNo: orderNumber,
1741
- order_no: orderNumber,
1742
- parentOrderNo: orderNumber,
1743
- status: cart.status === "converted" ? "confirmed" : "pending",
1744
- paymentStatus: "pending",
1745
- paymentMethod: null,
1746
- createdAt: cart.updated_at || cart.created_at || null,
1747
- updatedAt: cart.updated_at || null,
1748
- userEmail: cart.email || "",
1749
- phone: "",
1750
- subtotal,
1751
- shippingCharges: 0,
1752
- discount: 0,
1753
- total: subtotal,
1754
- currencyCode: cart.currency,
1755
- shippingRate: null,
1756
- fulfillments: [],
1757
- shippingAddress: null,
1758
- billingAddress: null,
1759
- lineItems: lines.map((line) => {
1760
- const product = line.product_id == null ? void 0 : index.get(line.product_id);
1761
- const mapped = product ? mapProduct(product) : null;
1762
- const variant = product?.variants?.find((v) => v.id === line.variant_id);
1763
- return {
1764
- id: line.id,
1765
- productId: line.product_id,
1766
- variantId: line.variant_id,
1767
- title: line.title || mapped?.title || "",
1768
- variantTitle: line.variant_label || line.sku || "",
1769
- slug: mapped?.slug || "",
1770
- sku: line.sku || "",
1771
- thumbnail: absoluteMedia(variant?.image?.url) || mapped?.thumbnail || null,
1772
- qty: line.quantity,
1773
- price: fromMoney(line.unit_price),
1774
- subtotal: fromMoney(line.total),
1775
- total: fromMoney(line.total)
1776
- };
1777
- })
1778
- };
1779
1817
  }
1780
- /**
1781
- * The shopper's orders. Without an account there is no server-side list to ask for, so this is
1782
- * every order placed from this browser, newest first — which is exactly what it can know.
1783
- */
1784
- async list({ page = 1 } = {}) {
1785
- const numbers = readOrderNumbers().reverse();
1786
- if (!numbers.length) return emptyPage(page);
1787
- const start = (page - 1) * PAGE_SIZE;
1788
- const window2 = numbers.slice(start, start + PAGE_SIZE);
1789
- const orders = await Promise.all(
1790
- window2.map(async (number) => {
1791
- const token = readOrderToken(number);
1792
- return token ? this.present(await this.readOrder(number, token)) : null;
1793
- })
1794
- );
1795
- return paginated(orders.filter(Boolean), numbers.length, page);
1796
- }
1797
- /** What the confirmation page loads with, server-side, straight after checkout. */
1798
- async listOrdersByParent({ orderNo, cartId }) {
1799
- const number = usable(orderNo);
1800
- if (!number) return emptyPage();
1801
- const token = readOrderToken(number);
1802
- if (token) {
1803
- const order = await this.present(await this.readOrder(number, token));
1804
- if (order) return paginated([order], 1, 1, 1);
1818
+ /** The signed-in shopper's orders, newest claim first. */
1819
+ async list({ page = 1, limit = 20 } = {}) {
1820
+ const env = await this.engine("/x/identity/me/orders", { query: { page, limit }, auth: true });
1821
+ return toPage(env, toOrder);
1822
+ }
1823
+ /** One order by number: the account's when signed in, otherwise one this browser placed. */
1824
+ async getOrder(number) {
1825
+ const kept = placedOrder(number);
1826
+ if (kept) {
1827
+ return toOrder(
1828
+ await this.data(`/api/orders/${encodeURIComponent(number)}`, { query: { token: kept.token } })
1829
+ );
1805
1830
  }
1806
- const cart = usable(cartId);
1807
- if (cart) {
1808
- const reconstructed = await this.orderFromCart(cart, number);
1809
- if (reconstructed) return paginated([reconstructed], 1, 1, 1);
1831
+ if (sessionToken()) {
1832
+ return toOrder(await this.data(`/x/identity/me/orders/${encodeURIComponent(number)}`, { auth: true }));
1810
1833
  }
1811
- return emptyPage();
1834
+ throw new GoCommerceError(
1835
+ inBrowser() ? "Sign in to see this order, or open it from the browser that placed it." : "order not found",
1836
+ 404,
1837
+ "not_found"
1838
+ );
1812
1839
  }
1813
- async getOrder(orderNo) {
1814
- const number = usable(orderNo);
1815
- if (!number) return {};
1816
- const token = readOrderToken(number);
1817
- if (!token) return {};
1818
- return await this.present(await this.readOrder(number, token)) ?? {};
1840
+ /** Everything the signed-in shopper has bought, once each, most recent first. */
1841
+ async buyAgain() {
1842
+ const orders = await this.data("/x/identity/me/orders", { query: { limit: 20 }, auth: true }) ?? [];
1843
+ const seen = /* @__PURE__ */ new Set();
1844
+ const lines = [];
1845
+ for (const o of orders) {
1846
+ for (const l of o.line_items ?? []) {
1847
+ if (!l.product_id || !l.variant_id || seen.has(l.variant_id)) continue;
1848
+ seen.add(l.variant_id);
1849
+ lines.push({
1850
+ productId: l.product_id,
1851
+ variantId: l.variant_id,
1852
+ title: l.title,
1853
+ img: l.image_url ?? null,
1854
+ price: toMajor(l.unit_price),
1855
+ qty: l.quantity
1856
+ });
1857
+ }
1858
+ }
1859
+ const live = await Promise.all(
1860
+ lines.map((l) => this.data(`/api/products/${l.productId}`).catch(() => null))
1861
+ );
1862
+ return lines.flatMap((l, i) => {
1863
+ const p = live[i];
1864
+ if (!p) return [];
1865
+ return [{ ...l, productId: String(l.productId), variantId: String(l.variantId), slug: p.slug }];
1866
+ });
1819
1867
  }
1820
- async fetchOrder(id) {
1821
- return this.getOrder(id);
1868
+ /** The "someone just bought" popup would publish other shoppers' purchases; the engine offers none. */
1869
+ async listPublic(_args = {}) {
1870
+ return emptyPage();
1822
1871
  }
1823
- async fetchTrackOrder(id) {
1824
- return this.listOrdersByParent({ orderNo: id, cartId: null });
1872
+ async getOrderByEmailAndOTP() {
1873
+ throw new NotSupportedError(
1874
+ "OrderService",
1875
+ "getOrderByEmailAndOTP",
1876
+ "the engine sends no one-time codes; a guest reads an order with its access token"
1877
+ );
1825
1878
  }
1826
- async paySuccessPageHit(orderId) {
1827
- return this.getOrder(orderId);
1879
+ };
1880
+ var clean2 = (v) => v && v !== "undefined" && v !== "null" ? v : void 0;
1881
+ var orderService = new OrderService();
1882
+
1883
+ // src/services/user-service.ts
1884
+ var UserService = class extends BaseService {
1885
+ /** Email and password. The answer is the user object the storefront keeps in its `me` cookie. */
1886
+ async login({ email, password }) {
1887
+ const auth = await this.account("/x/identity/login", {
1888
+ method: "POST",
1889
+ body: { email: String(email ?? "").trim(), password: String(password ?? "") }
1890
+ });
1891
+ return this.signedIn(auth);
1828
1892
  }
1829
- // GoCommerce has no email+OTP lookup: an order is reached by its number and access token.
1830
- async getOrderByEmailAndOTP(_params) {
1831
- return emptyPage();
1893
+ async signup({
1894
+ email,
1895
+ password,
1896
+ firstName,
1897
+ lastName,
1898
+ phone
1899
+ }) {
1900
+ const name = [firstName, lastName].filter(Boolean).join(" ").trim();
1901
+ const auth = await this.account("/x/identity/register", {
1902
+ method: "POST",
1903
+ body: {
1904
+ email: String(email ?? "").trim(),
1905
+ password: String(password ?? ""),
1906
+ ...name ? { name } : {},
1907
+ ...phone ? { phone: String(phone) } : {}
1908
+ }
1909
+ });
1910
+ return this.signedIn(auth);
1832
1911
  }
1833
- // No server-side order feed exists to reorder from; `list()` is the shopper's own history.
1834
- async buyAgain() {
1835
- return emptyPage();
1912
+ /** Signs out here and on the engine. The storefront assigns the answer to its user: `null`. */
1913
+ async logout() {
1914
+ await this.engine("/x/identity/logout", { method: "POST", auth: true }).catch(() => void 0);
1915
+ endSession();
1916
+ return null;
1836
1917
  }
1837
- async listPublic() {
1838
- return emptyPage();
1918
+ async getMe() {
1919
+ return toUser(await this.account("/x/identity/me", { auth: true }));
1839
1920
  }
1840
- async submitReview(_params) {
1841
- throw new Error("Product reviews are not available on this store.");
1921
+ async updateProfile(user) {
1922
+ const name = user.name ?? [user.firstName, user.lastName].filter((v) => v !== void 0).join(" ").trim();
1923
+ const c = await this.account("/x/identity/me", {
1924
+ method: "PATCH",
1925
+ auth: true,
1926
+ body: {
1927
+ ...name !== void 0 ? { name } : {},
1928
+ ...user.email ? { email: String(user.email).trim() } : {},
1929
+ ...user.phone !== void 0 && user.phone !== null ? { phone: String(user.phone) } : {}
1930
+ }
1931
+ });
1932
+ updateMe(c);
1933
+ return toUser(c);
1842
1934
  }
1843
- // Checkout runs through CheckoutService here; these Litekart-era entry points have no equivalent
1844
- // and must not fall back to an API a GoCommerce store does not run.
1845
- async codCheckout(_params) {
1846
- throw new Error("Use checkoutService.checkoutCOD() on GoCommerce.");
1935
+ /**
1936
+ * A password change ends every session the account had, this one included,
1937
+ * and the engine answers a fresh one — which is kept, so the shopper stays
1938
+ * signed in here and nowhere else.
1939
+ */
1940
+ async changePassword({ old, oldPassword, password }) {
1941
+ const auth = await this.account("/x/identity/me/password", {
1942
+ method: "PUT",
1943
+ auth: true,
1944
+ body: { current_password: String(old ?? oldPassword ?? ""), password: String(password ?? "") }
1945
+ });
1946
+ startSession(auth);
1947
+ return toUser(auth.record);
1847
1948
  }
1848
- async razorpayCheckout(_params) {
1849
- throw new Error("Use checkoutService.checkoutRazorpay() on GoCommerce.");
1949
+ async deleteUser() {
1950
+ throw new NotSupportedError("UserService", "deleteUser", "an account is closed by the store, on request");
1850
1951
  }
1851
- async stripeCheckout(_params) {
1852
- throw new Error("Use checkoutService.checkoutStripe() on GoCommerce.");
1952
+ async checkEmail() {
1953
+ throw new NotSupportedError("UserService", "checkEmail", "the engine does not say which addresses have accounts");
1853
1954
  }
1854
- async cashfreeCheckout(_params) {
1855
- throw new Error("Use checkoutService.checkoutCashfree() on GoCommerce.");
1955
+ async joinAsVendor() {
1956
+ throw new NotSupportedError("UserService", "joinAsVendor", "sellers are invited by the store");
1856
1957
  }
1857
- async razorCapture(_params) {
1858
- throw new Error("Use checkoutService.captureRazorpayPayment() on GoCommerce.");
1958
+ async signedIn(auth) {
1959
+ const me = startSession(auth);
1960
+ const cartId = storedCartId();
1961
+ if (cartId) await this.claimCartForAccount(cartId);
1962
+ return me;
1859
1963
  }
1860
- };
1861
- var orderService = OrderService.getInstance();
1862
-
1863
- // src/services/store.ts
1864
- var listOf = (items) => paginated(items, items.length, 1, items.length || PAGE_SIZE);
1865
- var StoreService = class _StoreService extends BaseService {
1866
- static instance;
1867
- static getInstance() {
1868
- if (!_StoreService.instance) _StoreService.instance = new _StoreService();
1869
- return _StoreService.instance;
1870
- }
1871
- async getStoreByIdOrDomain(_params = {}) {
1872
- const store = await readStaticStoreDetails();
1873
- if (!store) {
1874
- throw new Error("No store configuration is registered \u2014 check kitcommerce.config.ts (see docs/GOCOMMERCE.md).");
1964
+ /** An identity call, with a 404 from a build without the module said in words. */
1965
+ async account(path, req = {}) {
1966
+ try {
1967
+ return await this.data(path, req);
1968
+ } catch (err) {
1969
+ if (err instanceof GoCommerceError && err.status === 404 && /no route/i.test(err.message)) {
1970
+ throw new GoCommerceError("Accounts are not available on this store.", 404, "not_found");
1971
+ }
1972
+ if (err instanceof GoCommerceError && err.status === 401 && req.auth) endSession();
1973
+ throw err;
1875
1974
  }
1876
- return store;
1877
- }
1878
- /** The settings store asks for the record by id; there is only ever the configured one. */
1879
- async getStore(_storeId) {
1880
- return this.getStoreByIdOrDomain({});
1881
1975
  }
1882
1976
  };
1883
- var storeService = StoreService.getInstance();
1884
- var MenuService = class _MenuService extends BaseService {
1885
- static instance;
1886
- static getInstance() {
1887
- if (!_MenuService.instance) _MenuService.instance = new _MenuService();
1888
- return _MenuService.instance;
1889
- }
1890
- /** The nav reads `response.data` and filters it on `menuId`, the way the Litekart API served it. */
1891
- async list() {
1892
- const store = await readStaticStore();
1893
- return { data: store?.menu ?? [] };
1977
+ var AuthService = class extends UserService {
1978
+ async forgotPassword({ email }) {
1979
+ return this.account("/x/identity/password-reset", {
1980
+ method: "POST",
1981
+ body: { email: String(email ?? "").trim() }
1982
+ });
1894
1983
  }
1895
- };
1896
- var menuService = MenuService.getInstance();
1897
- var StateService = class _StateService extends BaseService {
1898
- static instance;
1899
- static getInstance() {
1900
- if (!_StateService.instance) _StateService.instance = new _StateService();
1901
- return _StateService.instance;
1984
+ /** The token arrives in the link the engine emailed (`GOCOMMERCE_IDENTITY_RESET_URL`). */
1985
+ async resetPassword({ token, password }) {
1986
+ const auth = await this.account("/x/identity/password-reset/confirm", {
1987
+ method: "POST",
1988
+ body: { token: String(token ?? ""), password: String(password ?? "") }
1989
+ });
1990
+ return startSession(auth);
1902
1991
  }
1903
- // No state list ships with the store record, and GoCommerce takes the state as free text.
1904
- async list() {
1905
- return listOf([]);
1992
+ /** Answers `{ errorCode, message }` on failure rather than throwing: that is how the page reads it. */
1993
+ async verifyEmail(_email, token) {
1994
+ try {
1995
+ const c = await this.account("/x/identity/email-verification/confirm", {
1996
+ method: "POST",
1997
+ body: { token: String(token ?? "") }
1998
+ });
1999
+ return { ...toUser(c), message: "Your email address is confirmed." };
2000
+ } catch (err) {
2001
+ return { errorCode: err.code ?? "invalid_token", message: err.message };
2002
+ }
1906
2003
  }
1907
- };
1908
- var stateService = StateService.getInstance();
1909
- var CurrencyService = class _CurrencyService extends BaseService {
1910
- static instance;
1911
- static getInstance() {
1912
- if (!_CurrencyService.instance) _CurrencyService.instance = new _CurrencyService();
1913
- return _CurrencyService.instance;
1914
- }
1915
- /** One currency: GoCommerce prices a store in the currency its catalogue is recorded in. */
1916
- async listCurrencies() {
1917
- const store = await readStaticStore();
1918
- return listOf(store?.currency ? [store.currency] : []);
2004
+ async getOtp() {
2005
+ throw new NotSupportedError("AuthService", "getOtp", "sign in with an email and password");
1919
2006
  }
1920
- };
1921
- var currencyService = CurrencyService.getInstance();
1922
- var RegionService = class _RegionService extends BaseService {
1923
- static instance;
1924
- static getInstance() {
1925
- if (!_RegionService.instance) _RegionService.instance = new _RegionService();
1926
- return _RegionService.instance;
2007
+ async verifyOtp() {
2008
+ throw new NotSupportedError("AuthService", "verifyOtp", "sign in with an email and password");
1927
2009
  }
1928
- // GoCommerce has no regions; one store, one currency, one price list.
1929
- async getRegionByRegionId(_id) {
1930
- return {};
2010
+ async joinAsAdmin() {
2011
+ throw new NotSupportedError("AuthService", "joinAsAdmin", "operators are invited from the admin panel");
1931
2012
  }
1932
2013
  };
1933
- var regionService = RegionService.getInstance();
1934
- var PluginService = class _PluginService extends BaseService {
1935
- static instance;
1936
- static getInstance() {
1937
- if (!_PluginService.instance) _PluginService.instance = new _PluginService();
1938
- return _PluginService.instance;
2014
+ var ProfileService = class extends UserService {
2015
+ async getOne() {
2016
+ return this.getMe();
1939
2017
  }
1940
- async list(_params = {}) {
1941
- const store = await readStaticStore();
1942
- return listOf(store?.plugins ?? []);
2018
+ async save(profile) {
2019
+ return this.updateProfile(profile);
1943
2020
  }
1944
2021
  };
1945
- var pluginService = PluginService.getInstance();
1946
- var pluginsService = pluginService;
1947
- var SettingService = class _SettingService extends BaseService {
1948
- static instance;
1949
- static getInstance() {
1950
- if (!_SettingService.instance) _SettingService.instance = new _SettingService();
1951
- return _SettingService.instance;
1952
- }
1953
- async fetchSetting() {
1954
- const store = await readStaticStore();
1955
- return store ? [store] : [];
2022
+ var userService = new UserService();
2023
+ var authService = new AuthService();
2024
+ var profileService = new ProfileService();
2025
+
2026
+ // src/services/address-service.ts
2027
+ var AddressService = class extends BaseService {
2028
+ async list({
2029
+ page = 1,
2030
+ limit = 20
2031
+ } = {}) {
2032
+ const env = await this.engine("/x/identity/me/addresses", {
2033
+ query: { page, limit },
2034
+ auth: true
2035
+ });
2036
+ const email = currentMe()?.email;
2037
+ const rows = env.data ?? [];
2038
+ return {
2039
+ data: rows.map((a) => fromIdentityAddress(a, email)),
2040
+ count: env.meta?.total ?? rows.length,
2041
+ pageSize: env.meta?.limit ?? limit,
2042
+ noOfPage: env.meta?.total_pages ?? 1,
2043
+ page: env.meta?.page ?? page
2044
+ };
1956
2045
  }
1957
- // Settings are the storefront's own configuration; a storefront must not write them back.
1958
- async saveSettings(_setting) {
1959
- throw new Error("Store settings are configured in kitcommerce.config.ts, not from the storefront.");
2046
+ async fetchAddress(id) {
2047
+ return fromIdentityAddress(
2048
+ await this.data(`/x/identity/me/addresses/${enc(id)}`, { auth: true }),
2049
+ currentMe()?.email
2050
+ );
1960
2051
  }
1961
- async updateSettings(_id, _setting) {
1962
- throw new Error("Store settings are configured in kitcommerce.config.ts, not from the storefront.");
2052
+ /** New when it has no id (or the form's `'new'`), an edit when it has one — the storefront saves both here. */
2053
+ async saveAddress(address) {
2054
+ const id = address?.id && address.id !== "new" ? String(address.id) : null;
2055
+ if (id) return this.editAddress(id, address);
2056
+ const a = await this.data("/x/identity/me/addresses", {
2057
+ method: "POST",
2058
+ auth: true,
2059
+ body: toIdentityAddress(address)
2060
+ });
2061
+ return fromIdentityAddress(a, currentMe()?.email);
1963
2062
  }
1964
- };
1965
- var settingService = SettingService.getInstance();
1966
- var settingsService = settingService;
1967
- var InitService = class _InitService extends BaseService {
1968
- static instance;
1969
- static getInstance() {
1970
- if (!_InitService.instance) _InitService.instance = new _InitService();
1971
- return _InitService.instance;
2063
+ async editAddress(id, address) {
2064
+ const a = await this.data(`/x/identity/me/addresses/${enc(id)}`, {
2065
+ method: "PATCH",
2066
+ auth: true,
2067
+ body: toIdentityAddress(address)
2068
+ });
2069
+ return fromIdentityAddress(a, currentMe()?.email);
1972
2070
  }
1973
- async fetchInit() {
1974
- const store = await readStaticStore();
1975
- return store ? [store] : [];
2071
+ async deleteAddress(id) {
2072
+ await this.engine(`/x/identity/me/addresses/${enc(id)}`, { method: "DELETE", auth: true });
2073
+ return { id: String(id), deleted: true };
1976
2074
  }
1977
2075
  };
1978
- var initService = InitService.getInstance();
1979
- var HomeService = class _HomeService extends BaseService {
1980
- static instance;
1981
- static getInstance() {
1982
- if (!_HomeService.instance) _HomeService.instance = new _HomeService();
1983
- return _HomeService.instance;
1984
- }
1985
- // The homepage is composed from the storefront's own blocks; GoCommerce stores no page layouts.
1986
- async getHome() {
1987
- return [];
2076
+ var enc = (id) => encodeURIComponent(String(id));
2077
+ var addressService = new AddressService();
2078
+
2079
+ // src/services/wishlist-service.ts
2080
+ var WishlistService = class extends BaseService {
2081
+ async fetchWishlist(_args = {}) {
2082
+ const list = await this.current();
2083
+ if (!list) return { data: [], count: 0 };
2084
+ const items = (list.items ?? []).filter((i) => !i.deleted);
2085
+ const products = await Promise.all(
2086
+ items.map((i) => this.data(`/api/products/${i.product_id}`).catch(() => null))
2087
+ );
2088
+ const data = items.flatMap((item, n) => {
2089
+ const p = products[n];
2090
+ if (!p) return [];
2091
+ return [
2092
+ {
2093
+ id: String(item.id),
2094
+ productId: String(item.product_id),
2095
+ variantId: item.variant_id ? String(item.variant_id) : null,
2096
+ product: toProduct(p),
2097
+ variant: { id: item.variant_id ? String(item.variant_id) : null },
2098
+ createdAt: item.created_at
2099
+ }
2100
+ ];
2101
+ });
2102
+ return { data, count: data.length };
2103
+ }
2104
+ /** Saved → removed, removed → saved. `{ active }` is the state after the click. */
2105
+ async toggleWishlist({ productId, variantId }) {
2106
+ const list = await this.current() ?? await this.create();
2107
+ const item = (list.items ?? []).find((i) => String(i.product_id) === String(productId));
2108
+ if (item) {
2109
+ await this.data(`/x/wishlist/${enc2(list.token)}/items/${item.id}`, { method: "DELETE" });
2110
+ return { active: false, id: String(item.id) };
2111
+ }
2112
+ const next = await this.data(`/x/wishlist/${enc2(list.token)}/items`, {
2113
+ method: "POST",
2114
+ body: { product_id: Number(productId), ...variantId ? { variant_id: Number(variantId) } : {} }
2115
+ });
2116
+ const added = (next.items ?? []).find((i) => String(i.product_id) === String(productId));
2117
+ return { active: true, id: added ? String(added.id) : null };
1988
2118
  }
1989
- };
1990
- var homeService = HomeService.getInstance();
1991
- var PopularSearchService = class _PopularSearchService extends BaseService {
1992
- static instance;
1993
- static getInstance() {
1994
- if (!_PopularSearchService.instance) _PopularSearchService.instance = new _PopularSearchService();
1995
- return _PopularSearchService.instance;
2119
+ async checkWishlist({ productId }) {
2120
+ const list = await this.current();
2121
+ return !!list && (list.items ?? []).some((i) => String(i.product_id) === String(productId));
1996
2122
  }
1997
- // GoCommerce records no search analytics, so there are no popular searches to report.
1998
- async listPopularSearch(_params = {}) {
1999
- return listOf([]);
2123
+ async checkWishlistInBulk(pairs) {
2124
+ const list = await this.current();
2125
+ const saved = new Set((list?.items ?? []).map((i) => String(i.product_id)));
2126
+ return (pairs ?? []).map((p) => ({ ...p, exists: saved.has(String(p.productId)) }));
2000
2127
  }
2001
- };
2002
- var popularSearchService = PopularSearchService.getInstance();
2003
- var PopularityService = class _PopularityService extends BaseService {
2004
- static instance;
2005
- static getInstance() {
2006
- if (!_PopularityService.instance) _PopularityService.instance = new _PopularityService();
2007
- return _PopularityService.instance;
2128
+ async current() {
2129
+ const token = wishlistToken();
2130
+ if (!token) return null;
2131
+ try {
2132
+ return { ...await this.data(`/x/wishlist/${enc2(token)}`), token };
2133
+ } catch (err) {
2134
+ if (err instanceof GoCommerceError && err.status === 404 && !/no wishlist|no route/i.test(err.message)) {
2135
+ forgetWishlistToken();
2136
+ return null;
2137
+ }
2138
+ throw err;
2139
+ }
2008
2140
  }
2009
- /** Nothing to record against: a view counter is not part of this API. Accepted and dropped. */
2010
- async updatePopularity(_params = {}) {
2011
- return { success: true };
2141
+ async create() {
2142
+ const email = currentMe()?.email;
2143
+ const list = await this.data("/x/wishlist", { method: "POST", ...email ? { body: { email } } : {} });
2144
+ if (!list.token) throw new GoCommerceError("The store did not return a wishlist token.", 500);
2145
+ rememberWishlistToken(list.token);
2146
+ return { ...list, token: list.token };
2012
2147
  }
2013
2148
  };
2014
- var popularityService = PopularityService.getInstance();
2149
+ var enc2 = (s) => encodeURIComponent(s);
2150
+ var wishlistService = new WishlistService();
2015
2151
 
2016
- // src/services/unsupported.ts
2017
- var unavailable = (what) => new Error(`${what} is not available on this store.`);
2018
- var singleton = (Ctor) => {
2019
- let instance;
2020
- return () => instance ??= new Ctor();
2021
- };
2022
- var NO_ACCOUNTS = "Accounts are not available on this store \u2014 checkout does not need one";
2023
- var UserService = class _UserService extends BaseService {
2024
- static getInstance = singleton(_UserService);
2025
- /** No session to report. `null` is what the header and guards check for. */
2026
- async getMe() {
2027
- return null;
2028
- }
2029
- async getUser(_id) {
2030
- return null;
2031
- }
2032
- async login(_params) {
2033
- throw new Error(`${NO_ACCOUNTS}.`);
2152
+ // src/services/review-service.ts
2153
+ var ReviewService = class extends BaseService {
2154
+ async fetchReviews({
2155
+ productId,
2156
+ currentPage = 1,
2157
+ page,
2158
+ limit = 20
2159
+ } = {}) {
2160
+ if (!productId) return { data: [], count: 0, pageSize: limit, noOfPage: 0, page: 1 };
2161
+ const p = Math.max(1, Number(page ?? currentPage) || 1);
2162
+ const res = await this.data("/x/reviews", { query: { product_id: productId, page: p, limit } });
2163
+ const total = res.meta?.total ?? res.summary?.count ?? 0;
2164
+ return {
2165
+ data: (res.reviews ?? []).map(toRating),
2166
+ count: total,
2167
+ pageSize: limit,
2168
+ noOfPage: Math.max(1, Math.ceil(total / limit)),
2169
+ page: p,
2170
+ summary: res.summary ?? null
2171
+ };
2034
2172
  }
2035
- async signup(_params) {
2036
- throw new Error(`${NO_ACCOUNTS}.`);
2173
+ async allReviews(args = {}) {
2174
+ return this.fetchReviews(args);
2037
2175
  }
2038
- async joinAsVendor(_params) {
2039
- throw unavailable("Vendor signup");
2176
+ };
2177
+ var reviewService = new ReviewService();
2178
+
2179
+ // src/services/menu-service.ts
2180
+ function linkFor(item) {
2181
+ const t = item.target ?? "";
2182
+ switch (item.kind) {
2183
+ case "home":
2184
+ return "/";
2185
+ case "product":
2186
+ return t ? `/products/${t}` : item.url;
2187
+ case "collection":
2188
+ return t ? `/collections/${t}` : item.url;
2189
+ case "category":
2190
+ return t ? `/${t}` : item.url;
2191
+ case "page":
2192
+ return t ? `/p/${t}` : item.url;
2193
+ default:
2194
+ return item.url;
2195
+ }
2196
+ }
2197
+ var toItem = (item, i) => ({
2198
+ id: String(item.id ?? i),
2199
+ name: item.title,
2200
+ link: linkFor(item),
2201
+ items: (item.children ?? []).map(toItem)
2202
+ });
2203
+ var MenuService = class extends BaseService {
2204
+ facts = new StoreFacts(this._fetch);
2205
+ async list(_args = {}) {
2206
+ const menus = await this.engineMenus();
2207
+ if (menus) return { data: menus };
2208
+ return resolveRestLocally("get", "/api/menu");
2209
+ }
2210
+ /** The header and footer menus, or `null` when the module is not there. Cached: a menu is store-level. */
2211
+ async engineMenus() {
2212
+ if (!await this.facts.pluginOn("navigation")) return null;
2213
+ return remember(`${this.engineBase()}|${this.creds.store ?? ""}|menus`, async () => {
2214
+ const out = [];
2215
+ for (const handle of ["header", "footer"]) {
2216
+ try {
2217
+ const m = await this.data(`/x/navigation/menus/${handle}`);
2218
+ out.push({ menuId: handle, name: m.title, items: (m.items ?? []).map(toItem) });
2219
+ } catch {
2220
+ }
2221
+ }
2222
+ return out;
2223
+ }).catch(() => null);
2040
2224
  }
2041
- async forgotPassword(_params) {
2042
- throw new Error(`${NO_ACCOUNTS}.`);
2225
+ };
2226
+ var menuService = new MenuService();
2227
+ var readStaticStore = async () => {
2228
+ return {};
2229
+ };
2230
+
2231
+ // src/services/store-service.ts
2232
+ function symbolFor(code) {
2233
+ try {
2234
+ const part = new Intl.NumberFormat("en", { style: "currency", currency: code }).formatToParts(0).find((p) => p.type === "currency");
2235
+ return part?.value ?? code;
2236
+ } catch {
2237
+ return code;
2043
2238
  }
2044
- async resetPassword(_params) {
2045
- throw new Error(`${NO_ACCOUNTS}.`);
2239
+ }
2240
+ var StoreService = class extends BaseService {
2241
+ facts = new StoreFacts(this._fetch);
2242
+ async getStoreByIdOrDomain(_args = {}) {
2243
+ const base = await readStaticStore();
2244
+ const live = await this.live().catch(() => ({}));
2245
+ return { ...base, ...live, id: base.id || "gocommerce" };
2046
2246
  }
2047
- async changePassword(_params) {
2048
- throw new Error(`${NO_ACCOUNTS}.`);
2247
+ async getStore(storeId) {
2248
+ return this.getStoreByIdOrDomain({ storeId });
2049
2249
  }
2050
- async getOtp(_params) {
2051
- throw new Error(`${NO_ACCOUNTS}.`);
2250
+ /**
2251
+ * The storefront's sitemap route asks for `/api/stores/<id>` and serves the
2252
+ * `sitemap` path it gets back from `PUBLIC_SITEMAP_URL`. With ext/sitemaps
2253
+ * installed, `/sitemaps/sitemap.xml` under `PUBLIC_SITEMAP_URL=<engine>/x`
2254
+ * is the engine's own sitemap; without it, an empty path is the route's
2255
+ * clean 404 rather than a crash.
2256
+ */
2257
+ async get(path) {
2258
+ if (path.split("?")[0].startsWith("/api/stores/")) {
2259
+ const on = await this.facts.pluginOn("sitemap");
2260
+ return { sitemap: on ? "/sitemaps/sitemap.xml" : "" };
2261
+ }
2262
+ return super.get(path);
2052
2263
  }
2053
- async verifyOtp(_params) {
2054
- throw new Error(`${NO_ACCOUNTS}.`);
2264
+ async live() {
2265
+ const [ready, plugins, menus, base] = await Promise.all([
2266
+ this.facts.ready(),
2267
+ this.facts.plugins().catch(() => /* @__PURE__ */ new Map()),
2268
+ new MenuService(this._fetch).engineMenus(),
2269
+ readStaticStore()
2270
+ ]);
2271
+ const code = ready.currency;
2272
+ const sameCurrency = (base.currency?.code ?? base.currencyCode) === code;
2273
+ const flag = (on) => ({ ...on ? { active: true } : { active: false } });
2274
+ const basePlugins = base.plugins ?? {};
2275
+ return {
2276
+ currencyCode: code,
2277
+ currencySymbol: sameCurrency ? base.currencySymbol ?? symbolFor(code) : symbolFor(code),
2278
+ currency: {
2279
+ ...base.currency ?? {},
2280
+ code,
2281
+ symbol: sameCurrency ? base.currency?.symbol ?? symbolFor(code) : symbolFor(code)
2282
+ },
2283
+ language: ready.language,
2284
+ plugins: {
2285
+ ...basePlugins,
2286
+ // Features this connector serves from a module: on exactly when the
2287
+ // module is installed and switched on, whatever the static record says.
2288
+ isWishlist: { ...basePlugins.isWishlist, ...flag(plugins.has("wishlist")) },
2289
+ isProductReviewsAndRatings: {
2290
+ ...basePlugins.isProductReviewsAndRatings,
2291
+ ...flag(plugins.has("product-reviews"))
2292
+ }
2293
+ },
2294
+ ...menus?.length ? { menu: menus } : {}
2295
+ };
2055
2296
  }
2056
- async updateProfile(_params) {
2057
- throw new Error(`${NO_ACCOUNTS}.`);
2297
+ };
2298
+ var storeService = new StoreService();
2299
+
2300
+ // src/services/page-service.ts
2301
+ var PageService = class extends BaseService {
2302
+ async getOne(slug) {
2303
+ return toCmsPage(await this.data(`/x/cms/pages/${encodeURIComponent(String(slug))}`));
2304
+ }
2305
+ async list({ page = 1, limit = 50 } = {}) {
2306
+ const env = await this.engine("/x/cms/pages", { query: { page, limit } });
2307
+ return toPage(env, toCmsPage);
2308
+ }
2309
+ };
2310
+ var FaqService = class extends BaseService {
2311
+ async listFaqs(_args = {}) {
2312
+ const faq = await this.data("/x/faq");
2313
+ const data = (faq.sections ?? []).flatMap(
2314
+ (s) => (s.entries ?? []).map((e) => ({
2315
+ id: String(e.id),
2316
+ question: e.question,
2317
+ answer: e.answer,
2318
+ category: s.section || null
2319
+ }))
2320
+ );
2321
+ return { data, count: data.length, heading: faq.heading, blurb: faq.blurb };
2058
2322
  }
2059
- async checkEmail(_email) {
2060
- return { exists: false };
2323
+ async list(args = {}) {
2324
+ return this.listFaqs(args);
2061
2325
  }
2062
- async deleteUser(_id) {
2063
- throw new Error(`${NO_ACCOUNTS}.`);
2326
+ };
2327
+ var pageService = new PageService();
2328
+ var faqService = new FaqService();
2329
+
2330
+ // src/services/vendor-service.ts
2331
+ var VendorService = class extends BaseService {
2332
+ async list({
2333
+ page = 1,
2334
+ limit = 24,
2335
+ q,
2336
+ search
2337
+ } = {}) {
2338
+ const env = await this.engine("/api/vendors", { query: { page, limit, q: q ?? search } });
2339
+ return toPage(env, toVendor);
2340
+ }
2341
+ async getVendor(slug) {
2342
+ return toVendor(await this.data(`/api/vendors/${encodeURIComponent(String(slug))}`));
2064
2343
  }
2065
2344
  /**
2066
- * Clears the session this storefront thinks it has.
2067
- *
2068
- * There is no session on GoCommerce to end, so it would be easy to make this a no-op — and that
2069
- * is a trap. The shared user store decides who is signed in by reading the `connect.sid` and `me`
2070
- * cookies straight from `document.cookie`, not by asking a service. A pair left behind by running
2071
- * this storefront against a backend that does have accounts therefore makes GoCommerce look
2072
- * signed-in, which sends the checkout down the saved-address path instead of the guest one. The
2073
- * checkout page already knows to call `logout()` and retry when that happens — so this has to
2074
- * actually clear them, or that recovery does nothing.
2345
+ * A seller's shelf. The engine's vendors sell through offers on the shop's
2346
+ * own variants and the public API lists no products by seller, so the shelf
2347
+ * is empty — the seller's page still renders, with their details.
2075
2348
  */
2076
- async logout() {
2077
- clearPhantomSession();
2078
- return { success: true };
2349
+ async fetchProductsOfVendor(_vendorId) {
2350
+ return emptyPage();
2079
2351
  }
2080
2352
  };
2081
- var userService = UserService.getInstance();
2082
- var AuthService = class _AuthService extends UserService {
2083
- static getInstance = singleton(_AuthService);
2084
- async verifyEmail(_email, _token) {
2085
- throw new Error(`${NO_ACCOUNTS}, so there is no address to verify.`);
2086
- }
2087
- async joinAsAdmin(_params) {
2088
- throw unavailable("Admin signup");
2353
+ var vendorService = new VendorService();
2354
+
2355
+ // src/services/misc-services.ts
2356
+ var refuse = (service, method, why) => new NotSupportedError(service, method, why);
2357
+ var ContactService = class extends BaseService {
2358
+ async submitContactUsForm({
2359
+ name,
2360
+ email,
2361
+ phone,
2362
+ message,
2363
+ subject
2364
+ }) {
2365
+ return this.data("/x/contact/messages", {
2366
+ method: "POST",
2367
+ body: {
2368
+ name: String(name ?? ""),
2369
+ email: String(email ?? ""),
2370
+ ...phone ? { phone: String(phone) } : {},
2371
+ ...subject ? { subject: String(subject) } : {},
2372
+ body: String(message ?? "")
2373
+ }
2374
+ });
2089
2375
  }
2090
2376
  };
2091
- var authService = AuthService.getInstance();
2092
- var ProfileService = class _ProfileService extends BaseService {
2093
- static getInstance = singleton(_ProfileService);
2094
- async getOne() {
2095
- return null;
2096
- }
2097
- async save(_profile) {
2098
- throw new Error(`${NO_ACCOUNTS}.`);
2377
+ var EnquiryService = class extends ContactService {
2378
+ async create({
2379
+ name,
2380
+ email,
2381
+ phone,
2382
+ message,
2383
+ productId
2384
+ }) {
2385
+ return this.submitContactUsForm({
2386
+ name,
2387
+ email,
2388
+ phone,
2389
+ subject: productId ? `Enquiry about product ${productId}` : "Enquiry",
2390
+ message
2391
+ });
2099
2392
  }
2100
2393
  };
2101
- var profileService = ProfileService.getInstance();
2102
- var AddressService = class _AddressService extends BaseService {
2103
- static getInstance = singleton(_AddressService);
2104
- async list(params = {}) {
2105
- const addresses = listAddresses();
2106
- const page = Math.max(1, Number(params.page || 1) || 1);
2107
- const start = (page - 1) * PAGE_SIZE;
2108
- return paginated(addresses.slice(start, start + PAGE_SIZE), addresses.length, page);
2109
- }
2110
- async fetchAddress(id) {
2111
- const address = findAddress(id);
2112
- if (!address) throw new Error("That address is no longer saved on this device.");
2113
- return address;
2114
- }
2115
- async saveAddress(address) {
2116
- return putAddress(address);
2117
- }
2118
- async editAddress(id, address) {
2119
- const saved = patchAddress(id, address);
2120
- if (!saved) throw new Error("That address is no longer saved on this device.");
2121
- return saved;
2122
- }
2123
- async deleteAddress(id) {
2124
- removeAddress(id);
2394
+ var PluginService = class extends BaseService {
2395
+ facts = new StoreFacts(this._fetch);
2396
+ async list(_args = {}) {
2397
+ const data = [...(await this.facts.plugins()).values()];
2398
+ return { data, count: data.length, pageSize: data.length, noOfPage: 1, page: 1 };
2125
2399
  }
2126
2400
  };
2127
- var addressService = AddressService.getInstance();
2128
- var WishlistService = class _WishlistService extends BaseService {
2129
- static getInstance = singleton(_WishlistService);
2130
- async fetchWishlist(_params = {}) {
2131
- return emptyPage();
2132
- }
2133
- async checkWishlist(_params = {}) {
2134
- return { data: false };
2135
- }
2136
- /** The product grid asks about many ids at once; nothing is on a list that cannot exist. */
2137
- async checkWishlistInBulk(_ids) {
2138
- return { data: [] };
2401
+ var SettingService = class extends BaseService {
2402
+ async fetchSettings(_args = {}) {
2403
+ return new StoreService(this._fetch).getStoreByIdOrDomain();
2139
2404
  }
2140
- async toggleWishlist(_params) {
2141
- throw unavailable("Wishlists");
2405
+ async list(args = {}) {
2406
+ return this.fetchSettings(args);
2142
2407
  }
2143
2408
  };
2144
- var wishlistService = WishlistService.getInstance();
2145
- var CouponService = class _CouponService extends BaseService {
2146
- static getInstance = singleton(_CouponService);
2147
- // No discount engine, so the payment step renders no coupon box rather than an empty one.
2148
- async listCoupons(_params = {}) {
2149
- return emptyPage();
2150
- }
2151
- async searchCoupons(_params = {}) {
2152
- return emptyPage();
2409
+ var InitService = class extends SettingService {
2410
+ async fetchInit(_args = {}) {
2411
+ const store = await this.fetchSettings();
2412
+ return { storeOne: store, store, settings: store };
2153
2413
  }
2154
- async getCoupon(_id) {
2155
- throw unavailable("Discount codes");
2414
+ };
2415
+ var HomeService = class extends BaseService {
2416
+ /** A homepage is assembled by the storefront from shelves; the engine has no page of its own for it. */
2417
+ async getHome(_args = {}) {
2418
+ return { banners: [], groupByBanner: [], categories: [], products: [] };
2156
2419
  }
2157
- async createCoupon(_coupon) {
2158
- throw unavailable("Discount codes");
2420
+ };
2421
+ var CountryService = class extends BaseService {
2422
+ async list(_args = {}) {
2423
+ return resolveRestLocally("get", "/api/countries");
2159
2424
  }
2160
- async patchCoupon(_id, _coupon) {
2161
- throw unavailable("Discount codes");
2425
+ };
2426
+ var CurrencyService = class extends BaseService {
2427
+ facts = new StoreFacts(this._fetch);
2428
+ async listCurrencies(_args = {}) {
2429
+ const { currency } = await this.facts.ready();
2430
+ const data = [{ code: currency, name: currency, isDefault: true }];
2431
+ return { data, count: 1, pageSize: 1, noOfPage: 1, page: 1 };
2162
2432
  }
2163
- async deleteCoupon(_id) {
2164
- throw unavailable("Discount codes");
2433
+ async list(args = {}) {
2434
+ return this.listCurrencies(args);
2165
2435
  }
2166
2436
  };
2167
- var couponService = CouponService.getInstance();
2168
- var DealService = class _DealService extends BaseService {
2169
- static getInstance = singleton(_DealService);
2170
- async fetchDeals() {
2437
+ var StateService = class extends BaseService {
2438
+ async list(_args = {}) {
2171
2439
  return emptyPage();
2172
2440
  }
2173
2441
  };
2174
- var dealService = DealService.getInstance();
2175
- var ReviewService = class _ReviewService extends BaseService {
2176
- static getInstance = singleton(_ReviewService);
2177
- async fetchReviews(_params = {}) {
2178
- return emptyPage();
2179
- }
2180
- async allReviews(_params = {}) {
2181
- return emptyPage();
2182
- }
2183
- async fetchProducrReviews(_productId) {
2442
+ var RegionService = class extends BaseService {
2443
+ async list(_args = {}) {
2184
2444
  return emptyPage();
2185
2445
  }
2186
- async saveReview(_review) {
2187
- throw unavailable("Product reviews");
2188
- }
2189
2446
  };
2190
- var reviewService = ReviewService.getInstance();
2191
- var PageService = class _PageService extends BaseService {
2192
- static getInstance = singleton(_PageService);
2193
- async list(_params = {}) {
2194
- return emptyPage();
2447
+ var AutocompleteService = class extends MeilisearchService {
2448
+ async list({ q, search } = {}) {
2449
+ return this.searchAutoComplete({ query: q ?? search });
2195
2450
  }
2196
- async listLatestPages(_params = {}) {
2451
+ };
2452
+ var PopularSearchService = class extends BaseService {
2453
+ async list(_args = {}) {
2197
2454
  return emptyPage();
2198
2455
  }
2199
- /**
2200
- * Every caller asks for a fixed, optional slug — `products`, `about-us`, `privacy-policy` — to
2201
- * dress a page the storefront already renders. So an absent page is the normal state, not a dead
2202
- * link: answer empty and let the route show its own content, rather than log a failure on every
2203
- * request for something that was never required.
2204
- */
2205
- async getOne(_id) {
2206
- return {};
2456
+ };
2457
+ var PopularityService = class extends BaseService {
2458
+ async updatePopularity(_args = {}) {
2459
+ return void 0;
2207
2460
  }
2208
2461
  };
2209
- var pageService = PageService.getInstance();
2210
- var BlogService = class _BlogService extends BaseService {
2211
- static getInstance = singleton(_BlogService);
2212
- async list(_params = {}) {
2462
+ var BlogService = class extends BaseService {
2463
+ async list(_args = {}) {
2213
2464
  return emptyPage();
2214
2465
  }
2215
- async getOne(id) {
2216
- throw new Error(`The post "${id}" does not exist on this store.`);
2466
+ async getOne(_slug) {
2467
+ throw refuse("BlogService", "getOne", "the engine has no blog; publish articles as pages");
2217
2468
  }
2218
2469
  };
2219
- var blogService = BlogService.getInstance();
2220
- var BannerService = class _BannerService extends BaseService {
2221
- static getInstance = singleton(_BannerService);
2222
- async list() {
2470
+ var BannerService = class extends BaseService {
2471
+ async list(_args = {}) {
2223
2472
  return emptyPage();
2224
2473
  }
2225
- async fetchBannersGroup() {
2226
- return emptyPage();
2474
+ async listBanners(args = {}) {
2475
+ return this.list(args);
2227
2476
  }
2228
- };
2229
- var bannerService = BannerService.getInstance();
2230
- var GalleryService = class _GalleryService extends BaseService {
2231
- static getInstance = singleton(_GalleryService);
2232
- async fetchGallery() {
2233
- return [];
2477
+ async fetchBanners(args = {}) {
2478
+ return this.list(args);
2234
2479
  }
2235
2480
  };
2236
- var galleryService = GalleryService.getInstance();
2237
- var ReelsService = class _ReelsService extends BaseService {
2238
- static getInstance = singleton(_ReelsService);
2239
- async list() {
2481
+ var ReelsService = class extends BaseService {
2482
+ async list(_args = {}) {
2240
2483
  return emptyPage();
2241
2484
  }
2242
2485
  };
2243
- var reelsService = ReelsService.getInstance();
2244
- var FaqService = class _FaqService extends BaseService {
2245
- static getInstance = singleton(_FaqService);
2246
- async listFaqs(_params = {}) {
2486
+ var DealService = class extends BaseService {
2487
+ async fetchDeals(_args = {}) {
2247
2488
  return emptyPage();
2248
2489
  }
2249
2490
  };
2250
- var faqService = FaqService.getInstance();
2251
- var FeedbackService = class _FeedbackService extends BaseService {
2252
- static getInstance = singleton(_FeedbackService);
2253
- async listFeedbacks(_params = {}) {
2491
+ var GalleryService = class extends BaseService {
2492
+ async list(_args = {}) {
2254
2493
  return emptyPage();
2255
2494
  }
2256
2495
  };
2257
- var feedbackService = FeedbackService.getInstance();
2258
- var ContactService = class _ContactService extends BaseService {
2259
- static getInstance = singleton(_ContactService);
2260
- async submitContactUsForm(_params) {
2261
- throw unavailable("The contact form");
2262
- }
2263
- };
2264
- var contactService = ContactService.getInstance();
2265
- var EnquiryService = class _EnquiryService extends BaseService {
2266
- static getInstance = singleton(_EnquiryService);
2267
- async create(_params) {
2268
- throw unavailable("Product enquiries");
2269
- }
2270
- };
2271
- var enquiryService = EnquiryService.getInstance();
2272
- var ChatService = class _ChatService extends BaseService {
2273
- static getInstance = singleton(_ChatService);
2274
- async list() {
2275
- return [];
2496
+ var ChatService = class extends BaseService {
2497
+ async list(_args = {}) {
2498
+ return emptyPage();
2276
2499
  }
2277
2500
  async chats() {
2278
- return [];
2501
+ throw refuse("ChatService", "chats", "the engine has no shopper chat");
2279
2502
  }
2280
- async save(_message) {
2281
- throw unavailable("Messaging");
2503
+ async save() {
2504
+ throw refuse("ChatService", "save", "the engine has no shopper chat");
2282
2505
  }
2283
2506
  };
2284
- var chatService = ChatService.getInstance();
2285
- var UploadService = class _UploadService extends BaseService {
2286
- static getInstance = singleton(_UploadService);
2287
- // Media in GoCommerce is an operator's, uploaded through the admin API. A storefront holds no
2288
- // admin credential and must not act as though it does.
2289
- async uploadToS3(_params) {
2290
- throw unavailable("File uploads");
2291
- }
2292
- async uploadMultipleToS3(_params) {
2293
- throw unavailable("File uploads");
2294
- }
2295
- async deleteFromS3(_params) {
2296
- throw unavailable("File uploads");
2507
+ var FeedbackService = class extends BaseService {
2508
+ async save() {
2509
+ throw refuse("FeedbackService", "save", "use the contact form");
2297
2510
  }
2298
2511
  };
2299
- var uploadService = UploadService.getInstance();
2300
- var VendorService = class _VendorService extends BaseService {
2301
- static getInstance = singleton(_VendorService);
2302
- async list(_params = {}) {
2303
- return emptyPage();
2304
- }
2305
- async getVendor(_id) {
2306
- throw unavailable("Vendor pages");
2307
- }
2308
- async fetchMyVendorDetails() {
2309
- throw unavailable("Vendor accounts");
2310
- }
2311
- async fetchDashboard() {
2312
- throw unavailable("Vendor accounts");
2313
- }
2314
- async fetchProductsOfVendor(_vendorId) {
2315
- return [];
2316
- }
2317
- async getAllVendorRatings(_vendorId) {
2318
- return [];
2512
+ var DemoRequestService = class extends BaseService {
2513
+ async save() {
2514
+ throw refuse("DemoRequestService", "save", "use the contact form");
2319
2515
  }
2320
- async save(_data) {
2321
- throw unavailable("Vendor accounts");
2516
+ };
2517
+ var UploadService = class extends BaseService {
2518
+ async uploadMultipleToS3() {
2519
+ throw refuse("UploadService", "uploadMultipleToS3", "shoppers cannot upload files to the engine");
2322
2520
  }
2323
- async update(_data) {
2324
- throw unavailable("Vendor accounts");
2521
+ async upload() {
2522
+ throw refuse("UploadService", "upload", "shoppers cannot upload files to the engine");
2325
2523
  }
2326
2524
  };
2327
- var vendorService = VendorService.getInstance();
2328
- var VarniCustomDesignService = class _VarniCustomDesignService extends BaseService {
2329
- static getInstance = singleton(_VarniCustomDesignService);
2330
- async submitForm(_formDetails) {
2331
- throw unavailable("Custom design requests");
2525
+ var WarrantyService = class extends BaseService {
2526
+ async submitWarrantyRegistration() {
2527
+ throw refuse("WarrantyService", "submitWarrantyRegistration", "the engine has no warranty registrations");
2332
2528
  }
2333
2529
  };
2334
- var varniCustomDesignService = VarniCustomDesignService.getInstance();
2335
- var VarniCustomProductService = class _VarniCustomProductService extends BaseService {
2336
- static getInstance = singleton(_VarniCustomProductService);
2337
- async checkForCombinationWith(_args) {
2338
- return { data: [], count: 0, pageSize: PAGE_SIZE, noOfPage: 0, page: 1 };
2339
- }
2340
- async createCustomOrderChat(_productId) {
2341
- throw unavailable("Custom product chat");
2530
+ var VarniCustomDesignService = class extends BaseService {
2531
+ async submitForm() {
2532
+ throw refuse("VarniCustomDesignService", "submitForm", "custom design requests are a Litekart feature");
2342
2533
  }
2343
- async sendMessageToCustomOrderChat(_chatId, _vendor, _message) {
2344
- throw unavailable("Custom product chat");
2534
+ };
2535
+ var VarniCustomProductService = class extends BaseService {
2536
+ async list(_args = {}) {
2537
+ return emptyPage();
2345
2538
  }
2346
2539
  };
2347
- var varniCustomProductService = VarniCustomProductService.getInstance();
2540
+ var staticStore = () => readStaticStore();
2541
+ var contactService = new ContactService();
2542
+ var enquiryService = new EnquiryService();
2543
+ var pluginService = new PluginService();
2544
+ var settingService = new SettingService();
2545
+ var initService = new InitService();
2546
+ var homeService = new HomeService();
2547
+ var countryService = new CountryService();
2548
+ var currencyService = new CurrencyService();
2549
+ var stateService = new StateService();
2550
+ var regionService = new RegionService();
2551
+ var autocompleteService = new AutocompleteService();
2552
+ var popularSearchService = new PopularSearchService();
2553
+ var popularityService = new PopularityService();
2554
+ var blogService = new BlogService();
2555
+ var bannerService = new BannerService();
2556
+ var reelsService = new ReelsService();
2557
+ var dealService = new DealService();
2558
+ var galleryService = new GalleryService();
2559
+ var chatService = new ChatService();
2560
+ var feedbackService = new FeedbackService();
2561
+ var demoRequestService = new DemoRequestService();
2562
+ var uploadService = new UploadService();
2563
+ var warrantyService = new WarrantyService();
2564
+ var varniCustomDesignService = new VarniCustomDesignService();
2565
+ var varniCustomProductService = new VarniCustomProductService();
2566
+ var pluginsService = pluginService;
2567
+ var settingsService = settingService;
2348
2568
 
2349
- exports.API_PROXY_PREFIX = API_PROXY_PREFIX;
2350
2569
  exports.AddressService = AddressService;
2351
2570
  exports.AuthService = AuthService;
2352
2571
  exports.AutocompleteService = AutocompleteService;
@@ -2354,26 +2573,26 @@ exports.BannerService = BannerService;
2354
2573
  exports.BaseService = BaseService;
2355
2574
  exports.BlogService = BlogService;
2356
2575
  exports.CartService = CartService;
2576
+ exports.CatalogService = CatalogService;
2357
2577
  exports.CategoryService = CategoryService;
2358
2578
  exports.ChatService = ChatService;
2359
2579
  exports.CheckoutService = CheckoutService;
2360
2580
  exports.CollectionService = CollectionService;
2361
2581
  exports.ContactService = ContactService;
2582
+ exports.CountryService = CountryService;
2362
2583
  exports.CouponService = CouponService;
2363
2584
  exports.CurrencyService = CurrencyService;
2364
2585
  exports.DealService = DealService;
2586
+ exports.DemoRequestService = DemoRequestService;
2365
2587
  exports.EnquiryService = EnquiryService;
2366
2588
  exports.FaqService = FaqService;
2367
2589
  exports.FeedbackService = FeedbackService;
2368
2590
  exports.GalleryService = GalleryService;
2369
- exports.GoCommerceError = GoCommerceError;
2370
2591
  exports.HomeService = HomeService;
2371
2592
  exports.InitService = InitService;
2372
- exports.MAX_LIMIT = MAX_LIMIT;
2373
2593
  exports.MeilisearchService = MeilisearchService;
2374
2594
  exports.MenuService = MenuService;
2375
2595
  exports.OrderService = OrderService;
2376
- exports.PAGE_SIZE = PAGE_SIZE;
2377
2596
  exports.PageService = PageService;
2378
2597
  exports.PaymentMethodService = PaymentMethodService;
2379
2598
  exports.PluginService = PluginService;
@@ -2395,8 +2614,8 @@ exports.UserService = UserService;
2395
2614
  exports.VarniCustomDesignService = VarniCustomDesignService;
2396
2615
  exports.VarniCustomProductService = VarniCustomProductService;
2397
2616
  exports.VendorService = VendorService;
2617
+ exports.WarrantyService = WarrantyService;
2398
2618
  exports.WishlistService = WishlistService;
2399
- exports.absoluteMedia = absoluteMedia;
2400
2619
  exports.addressService = addressService;
2401
2620
  exports.authService = authService;
2402
2621
  exports.autocompleteService = autocompleteService;
@@ -2406,72 +2625,48 @@ exports.cartService = cartService;
2406
2625
  exports.categoryService = categoryService;
2407
2626
  exports.chatService = chatService;
2408
2627
  exports.checkoutService = checkoutService;
2409
- exports.clearCheckoutDetails = clearCheckoutDetails;
2410
- exports.clearPhantomSession = clearPhantomSession;
2411
2628
  exports.collectionService = collectionService;
2412
2629
  exports.contactService = contactService;
2630
+ exports.countryService = countryService;
2413
2631
  exports.couponService = couponService;
2414
- exports.currencyFractionDigits = currencyFractionDigits;
2415
2632
  exports.currencyService = currencyService;
2416
2633
  exports.dealService = dealService;
2634
+ exports.demoRequestService = demoRequestService;
2417
2635
  exports.emptyPage = emptyPage;
2418
2636
  exports.enquiryService = enquiryService;
2419
2637
  exports.faqService = faqService;
2420
2638
  exports.feedbackService = feedbackService;
2421
- exports.findAddress = findAddress;
2422
- exports.flattenMetadata = flattenMetadata;
2423
- exports.fromMoney = fromMoney;
2424
2639
  exports.galleryService = galleryService;
2425
- exports.hasPhantomSession = hasPhantomSession;
2426
- exports.hasStaticStore = hasStaticStore;
2427
2640
  exports.homeService = homeService;
2428
2641
  exports.initService = initService;
2429
- exports.listAddresses = listAddresses;
2430
- exports.mapCart = mapCart;
2431
- exports.mapCategory = mapCategory;
2432
- exports.mapCollection = mapCollection;
2433
- exports.mapOrder = mapOrder;
2434
- exports.mapProduct = mapProduct;
2435
2642
  exports.meilisearchService = meilisearchService;
2436
2643
  exports.menuService = menuService;
2437
2644
  exports.orderService = orderService;
2438
2645
  exports.pageService = pageService;
2439
- exports.paginated = paginated;
2440
- exports.patchAddress = patchAddress;
2441
2646
  exports.paymentMethodService = paymentMethodService;
2442
2647
  exports.pluginService = pluginService;
2443
2648
  exports.pluginsService = pluginsService;
2444
2649
  exports.popularSearchService = popularSearchService;
2445
2650
  exports.popularityService = popularityService;
2446
- exports.productImages = productImages;
2447
2651
  exports.productService = productService;
2448
2652
  exports.profileService = profileService;
2449
- exports.putAddress = putAddress;
2450
- exports.readCheckoutDetails = readCheckoutDetails;
2451
- exports.readOrderNumbers = readOrderNumbers;
2452
- exports.readOrderToken = readOrderToken;
2453
- exports.readStaticStore = readStaticStore;
2454
- exports.readStaticStoreDetails = readStaticStoreDetails;
2653
+ exports.qs = qs;
2455
2654
  exports.reelsService = reelsService;
2456
2655
  exports.regionService = regionService;
2457
- exports.rememberOrderToken = rememberOrderToken;
2458
- exports.removeAddress = removeAddress;
2459
- exports.resolveProductIndex = resolveProductIndex;
2460
2656
  exports.reviewService = reviewService;
2461
2657
  exports.searchService = searchService;
2462
- exports.setStaticStore = setStaticStore;
2463
2658
  exports.settingService = settingService;
2464
2659
  exports.settingsService = settingsService;
2465
2660
  exports.stateService = stateService;
2661
+ exports.staticStore = staticStore;
2466
2662
  exports.storeService = storeService;
2467
- exports.toGoCommerceAddress = toGoCommerceAddress;
2468
- exports.toStorefrontAddress = toStorefrontAddress;
2663
+ exports.toPage = toPage;
2469
2664
  exports.uploadService = uploadService;
2470
2665
  exports.userService = userService;
2471
2666
  exports.varniCustomDesignService = varniCustomDesignService;
2472
2667
  exports.varniCustomProductService = varniCustomProductService;
2473
2668
  exports.vendorService = vendorService;
2669
+ exports.warrantyService = warrantyService;
2474
2670
  exports.wishlistService = wishlistService;
2475
- exports.writeCheckoutDetails = writeCheckoutDetails;
2476
2671
  //# sourceMappingURL=index.cjs.map
2477
2672
  //# sourceMappingURL=index.cjs.map