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