@viu/emporix-sdk 4.6.6 → 4.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/availability.cjs.map +1 -1
  3. package/dist/availability.js +2 -2
  4. package/dist/cart.cjs +3 -0
  5. package/dist/cart.cjs.map +1 -1
  6. package/dist/cart.js +2 -2
  7. package/dist/checkout.cjs.map +1 -1
  8. package/dist/checkout.js +2 -2
  9. package/dist/{chunk-J2AN2FMK.js → chunk-3JO2O4BY.js} +25 -14
  10. package/dist/chunk-3JO2O4BY.js.map +1 -0
  11. package/dist/{chunk-UWGGF4MC.js → chunk-4Q76UV4J.js} +6 -3
  12. package/dist/chunk-4Q76UV4J.js.map +1 -0
  13. package/dist/{chunk-RYQVMR26.js → chunk-BHNYGUSD.js} +3 -3
  14. package/dist/{chunk-RYQVMR26.js.map → chunk-BHNYGUSD.js.map} +1 -1
  15. package/dist/{chunk-IYNT5BQW.js → chunk-CXTVY4SI.js} +8 -4
  16. package/dist/chunk-CXTVY4SI.js.map +1 -0
  17. package/dist/{chunk-K4KXT6NX.js → chunk-ENMMDGUB.js} +3 -3
  18. package/dist/{chunk-K4KXT6NX.js.map → chunk-ENMMDGUB.js.map} +1 -1
  19. package/dist/{chunk-UA4BM6OP.js → chunk-EQE5WGME.js} +4 -4
  20. package/dist/{chunk-UA4BM6OP.js.map → chunk-EQE5WGME.js.map} +1 -1
  21. package/dist/{chunk-4VRUMCS2.js → chunk-PK4DQHJO.js} +4 -4
  22. package/dist/{chunk-4VRUMCS2.js.map → chunk-PK4DQHJO.js.map} +1 -1
  23. package/dist/{chunk-NFSO7WUA.js → chunk-SIGXBN4F.js} +3 -3
  24. package/dist/{chunk-NFSO7WUA.js.map → chunk-SIGXBN4F.js.map} +1 -1
  25. package/dist/{chunk-N2CE3J4M.js → chunk-U3ZIJZYH.js} +3 -3
  26. package/dist/{chunk-N2CE3J4M.js.map → chunk-U3ZIJZYH.js.map} +1 -1
  27. package/dist/{chunk-S2ERKGYL.js → chunk-ZLGLI4KC.js} +3 -3
  28. package/dist/{chunk-S2ERKGYL.js.map → chunk-ZLGLI4KC.js.map} +1 -1
  29. package/dist/{chunk-3BDDYX3V.js → chunk-ZVIEFW3X.js} +3 -3
  30. package/dist/{chunk-3BDDYX3V.js.map → chunk-ZVIEFW3X.js.map} +1 -1
  31. package/dist/{chunk-XQAOHHXL.js → chunk-ZZ3X3DDL.js} +3 -3
  32. package/dist/{chunk-XQAOHHXL.js.map → chunk-ZZ3X3DDL.js.map} +1 -1
  33. package/dist/customer.cjs.map +1 -1
  34. package/dist/customer.js +3 -3
  35. package/dist/index.cjs +62 -29
  36. package/dist/index.cjs.map +1 -1
  37. package/dist/index.d.cts +114 -34
  38. package/dist/index.d.ts +114 -34
  39. package/dist/index.js +52 -38
  40. package/dist/index.js.map +1 -1
  41. package/dist/media.cjs +3 -0
  42. package/dist/media.cjs.map +1 -1
  43. package/dist/media.js +2 -2
  44. package/dist/orders.cjs +6 -2
  45. package/dist/orders.cjs.map +1 -1
  46. package/dist/orders.d.cts +6 -2
  47. package/dist/orders.d.ts +6 -2
  48. package/dist/orders.js +1 -1
  49. package/dist/payment.cjs.map +1 -1
  50. package/dist/payment.js +3 -3
  51. package/dist/price.cjs.map +1 -1
  52. package/dist/price.js +2 -2
  53. package/dist/product.cjs +23 -12
  54. package/dist/product.cjs.map +1 -1
  55. package/dist/product.d.cts +193 -12
  56. package/dist/product.d.ts +193 -12
  57. package/dist/product.js +1 -1
  58. package/dist/segment.cjs.map +1 -1
  59. package/dist/segment.js +3 -3
  60. package/package.json +1 -1
  61. package/dist/chunk-IYNT5BQW.js.map +0 -1
  62. package/dist/chunk-J2AN2FMK.js.map +0 -1
  63. package/dist/chunk-UWGGF4MC.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/errors.ts","../src/core/auth.ts","../src/core/require-customer.ts","../src/services/payment.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E,GAAI,KAAA,KAAU,MAAA,GAAY,EAAC,GAAI,EAAE,MAAM,KAAA,EAAM;AAAA,MAC7C,IAAA,EAAM;AAAA,KACP,CAAA;AAAA;AAAA,IAGH,MAAA,EAAQ,OAAO,aAAA,EAAuB,OAAA,GAAuB,YAC3D,IAAA,CAAK,GAAA,CAAI,KAAK,OAAA,CAA6B;AAAA,MACzC,MAAA,EAAQ,MAAA;AAAA,MACR,MAAM,CAAA,iBAAA,EAAoB,IAAA,CAAK,GAAA,CAAI,MAAM,YAAY,aAAa,CAAA,OAAA,CAAA;AAAA,MAClE,IAAA,EAAM;AAAA,KACP;AAAA,GACL;AACF","file":"payment.cjs","sourcesContent":["/** Keys whose values are stripped from any serialised error body. */\nconst REDACTED_BODY_KEYS = new Set([\n \"access_token\", \"refresh_token\", \"token\", \"customertoken\", \"saastoken\",\n \"secret\", \"client_secret\", \"authorization\", \"password\",\n]);\n\nfunction scrub(body: unknown): unknown {\n if (Array.isArray(body)) return body.map(scrub);\n if (body && typeof body === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(body as Record<string, unknown>)) {\n out[k] = REDACTED_BODY_KEYS.has(k.toLowerCase()) ? \"***redacted***\" : scrub(v);\n }\n return out;\n }\n return body;\n}\n\n/** Base class for every error thrown by the SDK. */\nexport class EmporixError extends Error {\n readonly status: number | undefined;\n readonly body: unknown;\n constructor(message: string, status?: number, body?: unknown) {\n super(message);\n this.name = new.target.name;\n this.status = status;\n this.body = body;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n /** Safe serialisation — token-like body fields are redacted. */\n toJSON(): Record<string, unknown> {\n return { name: this.name, message: this.message, status: this.status, body: scrub(this.body) };\n }\n}\n\n/** 401 — authentication failed or token expired. */\nexport class EmporixAuthError extends EmporixError {}\n/** 403 — authenticated but not permitted. */\nexport class EmporixForbiddenError extends EmporixError {}\n/** 404 — resource not found. */\nexport class EmporixNotFoundError extends EmporixError {}\n/** 400/422 — request validation failed. */\nexport class EmporixValidationError extends EmporixError {}\n/** 5xx — server-side failure. */\nexport class EmporixServerError extends EmporixError {}\n/** Request aborted by the configured connect/read timeout. No HTTP status. */\nexport class EmporixTimeoutError extends EmporixError {}\n/** DNS/TLS/connection-level failure before or during the exchange. No HTTP status. */\nexport class EmporixNetworkError extends EmporixError {}\n\n/**\n * 403 with a `missing scope: <name>` hint in the body's `details` array.\n * Subclasses {@link EmporixForbiddenError} so existing 403 catches still work.\n */\nexport class EmporixInsufficientScopeError extends EmporixForbiddenError {\n readonly requiredScope: string | undefined;\n constructor(message: string, status: number, body: unknown, requiredScope?: string) {\n super(message, status, body);\n this.requiredScope = requiredScope;\n }\n}\n\nconst SCOPE_HINT_RE = /missing scope[: ]+([a-z0-9._-]+)/i;\n\nfunction extractRequiredScope(body: unknown): string | undefined {\n if (body && typeof body === \"object\" && \"details\" in body) {\n const details = (body as { details?: unknown }).details;\n if (Array.isArray(details)) {\n for (const d of details) {\n if (typeof d === \"string\") {\n const m = d.match(SCOPE_HINT_RE);\n if (m) return m[1];\n }\n }\n }\n }\n return undefined;\n}\n\n/** Maps an HTTP status to the matching {@link EmporixError} subclass. */\nexport function errorFromResponse(status: number, message: string, body: unknown): EmporixError {\n if (status === 401) return new EmporixAuthError(message, status, body);\n if (status === 403) {\n const scope = extractRequiredScope(body);\n if (scope) return new EmporixInsufficientScopeError(message, status, body, scope);\n return new EmporixForbiddenError(message, status, body);\n }\n if (status === 404) return new EmporixNotFoundError(message, status, body);\n if (status === 400 || status === 422) return new EmporixValidationError(message, status, body);\n if (status >= 500) return new EmporixServerError(message, status, body);\n return new EmporixError(message, status, body);\n}\n","import type { ResolvedConfig, ServiceCredentials } from \"./config\";\nimport { EmporixAuthError, EmporixTimeoutError, EmporixNetworkError } from \"./errors\";\n\n/** Which token a call should use. */\nexport type AuthKind = \"service\" | \"customer\" | \"anonymous\" | \"raw\";\n\n/** Caller-supplied, per-call auth selector. Never stored on the client. */\nexport type AuthContext =\n | { kind: \"service\"; credentials?: string }\n | { kind: \"anonymous\" }\n | { kind: \"customer\"; token: string }\n | { kind: \"raw\"; token: string };\n\n/**\n * Supplies a fresh customer token when a `customer`-kind request 401s. The host\n * (e.g. EmporixProvider) implements this; the SDK never refreshes the\n * caller-owned customer token unless a refresher is registered.\n */\nexport interface CustomerTokenRefresher {\n /**\n * Called on a `customer`-kind 401. Receives the token that just failed;\n * returns a fresh customer token to retry with, or `null` to give up (the\n * 401 then propagates as EmporixAuthError).\n */\n refresh(expiredToken: string): Promise<string | null>;\n}\n\n/** An obtained anonymous storefront session. */\nexport interface AnonymousSession {\n accessToken: string;\n refreshToken: string;\n sessionId: string;\n expiresIn: number;\n}\n\n/**\n * An anonymous session as it survives outside the client instance.\n *\n * `accessToken` and `expiresAt` are optional, and a store is free to drop them:\n * they turn a *server* round trip into zero token calls, because a server client\n * lives for one request and would otherwise refresh on every single one. A\n * long-lived browser client keeps the token in memory anyway, so the React\n * storage adapters deliberately persist only the two required fields — a token\n * readable by JavaScript buys nothing there.\n *\n * A store that returns `accessToken` without a future `expiresAt` gets treated as\n * having no token at all; see {@link DefaultTokenProvider.attachAnonymousStore}.\n */\nexport interface StoredAnonymousSession {\n refreshToken: string;\n sessionId: string;\n /** The access token itself, so a fresh client need not spend a refresh call for it. */\n accessToken?: string;\n /** Epoch ms after which `accessToken` is stale. The expiry buffer is already applied. */\n expiresAt?: number;\n}\n\n/**\n * Persistence callback for anonymous sessions. `read` is called once on the\n * first need for an anonymous token to bootstrap a possibly-existing session;\n * `write` is called after every successful login or refresh. `write(null)`\n * means the SDK is invalidating the stored session.\n */\nexport interface AnonymousSessionStore {\n read(): StoredAnonymousSession | null;\n write(session: StoredAnonymousSession | null): void;\n}\n\n/** Supplies SDK-managed tokens (service/custom + anonymous). May be user-injected. */\nexport interface TokenProvider {\n /** Service/custom client-credentials token for the named credential set. */\n getToken(credentialSet: string): Promise<string>;\n /** Cached anonymous storefront session (preserves sessionId across refreshes). */\n getAnonymousToken(): Promise<AnonymousSession>;\n /** Refresh the anonymous session, preserving sessionId. */\n refreshAnonymous?(): Promise<AnonymousSession>;\n /** Invalidate a cached SDK-managed token so the next call re-auths. */\n invalidate?(credentialSet: string): void;\n /** Invalidate the cached anonymous session entirely (next call re-logs in). */\n invalidateAnonymous?(): void;\n /**\n * Mark the anonymous access token stale but keep the refresh token, so the\n * next {@link getAnonymousToken} refreshes (preserving sessionId) rather\n * than starting a brand-new session.\n */\n expireAnonymous?(): void;\n /**\n * Install a persistence adapter for the anonymous session. The host (e.g.\n * `EmporixProvider`) calls this at construction so the SDK can bootstrap\n * an existing session and persist refreshes. Idempotent: a later call\n * replaces the previous adapter.\n */\n attachAnonymousStore?(store: AnonymousSessionStore): void;\n /**\n * Override the storefront context (currency/site/country) used for the next\n * anonymous login, then invalidate the current anonymous session so it\n * re-mints with the new context. No-op for providers without anon support.\n */\n setAnonymousContext?(ctx: {\n currency?: string;\n siteCode?: string;\n targetLocation?: string;\n }): void;\n /**\n * Subscribe to token-refresh events. Optional — implementations may no-op.\n * Returns an unsubscribe function. `DefaultTokenProvider` emits for the\n * anonymous-login / anonymous-refresh paths.\n */\n onRefresh?(\n listener: (event: { kind: \"anonymous\" | \"customer\"; success: boolean }) => void,\n ): () => void;\n}\n\n/** Tiny constructors for {@link AuthContext}. */\nexport const auth = {\n /** Service/custom credential set (default `backend`). */\n service: (credentials?: string): AuthContext =>\n credentials === undefined ? { kind: \"service\" } : { kind: \"service\", credentials },\n /** Cached anonymous storefront token. */\n anonymous: (): AuthContext => ({ kind: \"anonymous\" }),\n /** Caller-owned customer bearer token. */\n customer: (token: string): AuthContext => ({ kind: \"customer\", token }),\n /** Exact token, no transformation (SSO / token-exchange). */\n raw: (token: string): AuthContext => ({ kind: \"raw\", token }),\n};\n\n/** Resolves an {@link AuthContext} to a concrete bearer token. */\nexport async function resolveToken(ctx: AuthContext, provider: TokenProvider): Promise<string> {\n switch (ctx.kind) {\n case \"service\":\n return provider.getToken(ctx.credentials ?? \"backend\");\n case \"anonymous\":\n return (await provider.getAnonymousToken()).accessToken;\n case \"customer\":\n case \"raw\":\n return ctx.token;\n }\n}\n\n/**\n * Late-bindable, single-flight holder for an optional\n * {@link CustomerTokenRefresher}. Single-flight is required because Emporix\n * rotates the refresh token on each refresh — concurrent refreshes would\n * invalidate each other. Off (returns `null`) until a refresher is set.\n */\nexport class CustomerRefreshRegistry {\n private refresher: CustomerTokenRefresher | null = null;\n private inflight: Promise<string | null> | null = null;\n\n set(refresher: CustomerTokenRefresher | null): void {\n this.refresher = refresher;\n }\n\n get enabled(): boolean {\n return this.refresher !== null;\n }\n\n /** Concurrent callers share one in-flight refresh. */\n refresh(expiredToken: string): Promise<string | null> {\n if (!this.refresher) return Promise.resolve(null);\n if (this.inflight) return this.inflight;\n const p = Promise.resolve(this.refresher.refresh(expiredToken)).finally(() => {\n this.inflight = null;\n });\n this.inflight = p;\n return p;\n }\n}\n\ninterface CacheEntry {\n token: string;\n expiresAt: number;\n obtainedAt: number;\n}\n\n/** SDK-owned token provider: client-credentials service tokens + anonymous session. */\nexport class DefaultTokenProvider implements TokenProvider {\n private readonly serviceCache = new Map<string, CacheEntry>();\n private readonly serviceLocks = new Map<string, Promise<string>>();\n private anon: (AnonymousSession & { expiresAt: number }) | undefined;\n private anonLock: Promise<AnonymousSession> | undefined;\n private anonStore?: AnonymousSessionStore;\n private contextOverride:\n | { currency?: string; siteCode?: string; targetLocation?: string }\n | undefined;\n private readonly refreshListeners = new Set<\n (event: { kind: \"anonymous\" | \"customer\"; success: boolean }) => void\n >();\n\n constructor(private readonly cfg: ResolvedConfig) {}\n\n onRefresh(\n listener: (event: { kind: \"anonymous\" | \"customer\"; success: boolean }) => void,\n ): () => void {\n this.refreshListeners.add(listener);\n return () => {\n this.refreshListeners.delete(listener);\n };\n }\n\n private notifyRefresh(kind: \"anonymous\" | \"customer\", success: boolean): void {\n for (const l of this.refreshListeners) {\n try {\n l({ kind, success });\n } catch {\n // Never let a telemetry listener break the auth path.\n }\n }\n }\n\n attachAnonymousStore(store: AnonymousSessionStore): void {\n this.anonStore = store;\n // Bootstrap `this.anon` from the store if we don't have it yet.\n //\n // A persisted access token that is still inside its lifetime is adopted as\n // is, and that is the point on a server: a client that lives for one request\n // would otherwise spend one `/anonymous/refresh` per request for a token it\n // already holds. Without a token — or past its expiry — `expiresAt` stays 0\n // and the next getAnonymousToken refreshes, which preserves the sessionId,\n // so the guest's cart survives either way.\n //\n // `expiresAt` counts only when there is a token to go with it. A store that\n // returns one without the other would otherwise make `anonFresh()` true and\n // hand out an empty bearer token.\n //\n // Trusting a stored expiry means trusting the writer's clock. A token\n // revoked early, or an expiry that a skewed clock made look valid, comes\n // back as a 401 — which `HttpClient` answers with `expireAnonymous()` plus\n // one retry, so the failure mode is a refresh, not an error.\n if (!this.anon) {\n const persisted = store.read();\n if (persisted) {\n const token = persisted.accessToken ?? \"\";\n this.anon = {\n accessToken: token,\n refreshToken: persisted.refreshToken,\n sessionId: persisted.sessionId,\n expiresIn: 0,\n expiresAt: token === \"\" ? 0 : (persisted.expiresAt ?? 0),\n };\n }\n }\n }\n\n private creds(set: string): ServiceCredentials {\n if (set === \"backend\") {\n const b = this.cfg.credentials.backend;\n if (!b?.clientId || !b.secret) {\n throw new EmporixAuthError(\n \"A 'service' AuthContext was used but credentials.backend is not configured\",\n );\n }\n return b;\n }\n const c = this.cfg.credentials.custom?.[set];\n if (!c) throw new Error(`Unknown credential set \"${set}\"`);\n return c;\n }\n\n private fresh(e: CacheEntry | undefined): boolean {\n if (!e) return false;\n const now = Date.now();\n if (now - e.obtainedAt >= this.cfg.cache.maxLifetimeSeconds * 1000) return false;\n return now < e.expiresAt;\n }\n\n async getToken(set: string): Promise<string> {\n // Surface an unknown credential set before entering the cache/lock path.\n this.creds(set);\n const cached = this.serviceCache.get(set);\n if (this.fresh(cached)) return cached!.token;\n const inflight = this.serviceLocks.get(set);\n if (inflight) return inflight;\n const p = this.requestServiceToken(set).finally(() => this.serviceLocks.delete(set));\n this.serviceLocks.set(set, p);\n return p;\n }\n\n /**\n * fetch with the configured read timeout. Token endpoints sit in front of\n * single-flight locks — one hung call would otherwise block every request\n * on this credential set forever.\n */\n private async boundedFetch(url: string | URL, init: RequestInit = {}): Promise<Response> {\n const ms = this.cfg.timeouts?.readMs ?? 60_000;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), ms);\n try {\n return await fetch(url, { ...init, signal: controller.signal });\n } catch (err) {\n if ((err as Error).name === \"AbortError\") {\n throw new EmporixTimeoutError(`token request timed out after ${ms}ms`);\n }\n throw new EmporixNetworkError(`token request network failure: ${(err as Error).message}`);\n } finally {\n clearTimeout(timer);\n }\n }\n\n private async requestServiceToken(set: string): Promise<string> {\n const c = this.creds(set);\n const body = new URLSearchParams({\n grant_type: \"client_credentials\",\n client_id: c.clientId,\n client_secret: c.secret,\n });\n if (c.scope) body.set(\"scope\", c.scope);\n const res = await this.boundedFetch(`${this.cfg.host}/oauth/token`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body,\n });\n const json = (await res.json().catch(() => ({}))) as Record<string, unknown>;\n if (!res.ok) {\n throw new EmporixAuthError(`Token request failed for \"${set}\"`, res.status, json);\n }\n const obtainedAt = Date.now();\n const ttl = Number((json.expires_in as number | undefined) ?? 3600);\n this.serviceCache.set(set, {\n token: json.access_token as string,\n obtainedAt,\n expiresAt: obtainedAt + (ttl - this.cfg.cache.expirationBufferSeconds) * 1000,\n });\n return this.serviceCache.get(set)!.token;\n }\n\n invalidate(set: string): void {\n this.serviceCache.delete(set);\n }\n\n private anonFresh(): boolean {\n return !!this.anon && Date.now() < this.anon.expiresAt;\n }\n\n async getAnonymousToken(): Promise<AnonymousSession> {\n if (this.anonFresh()) return this.stripExpiry(this.anon!);\n if (this.anonLock) return this.anonLock;\n // Token expired but a refresh token survives → refresh to keep the same\n // sessionId; only fall back to a brand-new login if the refresh fails.\n const canRefresh = !!this.anon?.refreshToken;\n const obtain = canRefresh\n ? this.fetchAnonymous(\"refresh\").catch(() => this.fetchAnonymous(\"login\"))\n : this.fetchAnonymous(\"login\");\n const p = obtain.finally(() => {\n this.anonLock = undefined;\n });\n this.anonLock = p;\n return p;\n }\n\n /** Refreshes the anonymous session, preserving its sessionId. */\n async refreshAnonymous(): Promise<AnonymousSession> {\n if (!this.anon) return this.getAnonymousToken();\n return this.fetchAnonymous(\"refresh\");\n }\n\n invalidateAnonymous(): void {\n this.anon = undefined;\n this.anonStore?.write(null);\n }\n\n setAnonymousContext(ctx: {\n currency?: string;\n siteCode?: string;\n targetLocation?: string;\n }): void {\n const base = this.contextOverride ?? this.cfg.credentials.storefront?.context ?? {};\n this.contextOverride = { ...base, ...ctx };\n this.invalidateAnonymous();\n }\n\n /** Force a stale access token while keeping the refresh token + sessionId. */\n expireAnonymous(): void {\n if (this.anon) this.anon = { ...this.anon, expiresAt: 0 };\n }\n\n private stripExpiry(s: AnonymousSession & { expiresAt: number }): AnonymousSession {\n const { expiresAt: _expiresAt, ...rest } = s;\n return rest;\n }\n\n private async fetchAnonymous(mode: \"login\" | \"refresh\"): Promise<AnonymousSession> {\n const sf = this.cfg.credentials.storefront;\n if (!sf?.clientId) {\n throw new Error(\"credentials.storefront.clientId is required for anonymous tokens\");\n }\n const url = new URL(`${this.cfg.host}/customerlogin/auth/anonymous/${mode}`);\n url.searchParams.set(\"tenant\", this.cfg.tenant);\n url.searchParams.set(\"client_id\", sf.clientId);\n // Context is the runtime override (set via setAnonymousContext) if present,\n // else the config-fixed context.\n const c = this.contextOverride ?? sf.context;\n if (c?.currency) url.searchParams.set(\"currency\", c.currency);\n if (c?.siteCode) url.searchParams.set(\"siteCode\", c.siteCode);\n if (c?.targetLocation) url.searchParams.set(\"targetLocation\", c.targetLocation);\n if (mode === \"refresh\" && this.anon) {\n url.searchParams.set(\"refresh_token\", this.anon.refreshToken);\n }\n try {\n const res = await this.boundedFetch(url, { method: \"GET\" });\n const json = (await res.json().catch(() => ({}))) as Record<string, unknown>;\n if (!res.ok) {\n this.notifyRefresh(\"anonymous\", false);\n throw new EmporixAuthError(`Anonymous token ${mode} failed`, res.status, json);\n }\n const obtainedAt = Date.now();\n this.anon = {\n accessToken: json.access_token as string,\n refreshToken: json.refresh_token as string,\n sessionId: json.sessionId as string,\n expiresIn: json.expires_in as number,\n expiresAt:\n obtainedAt +\n ((json.expires_in as number) - this.cfg.cache.expirationBufferSeconds) * 1000,\n };\n // The access token and its expiry go out too, so a store that keeps them\n // (a server one) can hand the next request a usable token instead of\n // another refresh. A store that only wants the refresh token drops them.\n this.anonStore?.write({\n refreshToken: this.anon.refreshToken,\n sessionId: this.anon.sessionId,\n accessToken: this.anon.accessToken,\n expiresAt: this.anon.expiresAt,\n });\n this.notifyRefresh(\"anonymous\", true);\n return this.stripExpiry(this.anon);\n } catch (err) {\n // Re-throw EmporixAuthError as-is; for non-Emporix errors (network), also notify.\n if (!(err instanceof EmporixAuthError)) {\n this.notifyRefresh(\"anonymous\", false);\n }\n throw err;\n }\n }\n}\n// Customer-token refreshes happen via client.customers.refresh() and don't\n// route through this TokenProvider — only the anonymous flow notifies.\n// React-side useCustomerSession.refresh emits its own telemetry event in a\n// follow-up if needed.\n","import type { AuthContext } from \"./auth\";\nimport { EmporixAuthError } from \"./errors\";\n\n/**\n * Enforces a caller-owned customer or raw token. Throws `EmporixAuthError`\n * for any other `AuthContext` kind (or when `auth` is missing). Shared by\n * services whose endpoints require a customer scope (`/me`, payments,\n * customer-segments…).\n */\nexport function requireCustomer(auth: AuthContext | undefined): AuthContext {\n if (auth && (auth.kind === \"customer\" || auth.kind === \"raw\")) return auth;\n throw new EmporixAuthError(\"This operation requires a customer or raw AuthContext\");\n}\n","import type { ClientContext } from \"../core/context\";\nimport { auth, type AuthContext } from \"../core/auth\";\nimport { requireCustomer } from \"../core/require-customer\";\nimport type {\n PaymentModeFrontendResponse,\n AuthorizePaymentRequest,\n InitializePaymentRequest,\n InitializePaymentResponse,\n PaymentModeResponse,\n PaymentModeRequest,\n PaymentMethodUpdateRequest,\n PaymentTransactionResponse,\n AuthorizePaymentResponse,\n CaptureRequest,\n RefundRequest,\n CommonPaymentResponse,\n} from \"../generated/payment\";\n\nconst ANON: AuthContext = auth.anonymous();\nconst SERVICE: AuthContext = auth.service();\n\n/** A frontend payment mode (generated). */\nexport type PaymentMode = PaymentModeFrontendResponse;\n\n/** Post-checkout authorize request (generated; caller sends the exact wire shape). */\nexport type AuthorizePaymentInput = AuthorizePaymentRequest;\n\n/** Frontend payment-initialize request (generated). */\nexport type InitializePaymentInput = InitializePaymentRequest;\n\n/** Frontend payment-initialize response (generated). */\nexport type InitializePaymentResult = InitializePaymentResponse;\n\n/** Post-checkout authorize result. */\nexport interface AuthorizePaymentResult {\n successful: boolean;\n paymentTransactionId?: string;\n authorizationToken?: string;\n requiresExternalPayment?: boolean;\n externalPaymentRedirectURL?: string;\n externalPaymentHttpMethod?: string;\n [k: string]: unknown;\n}\n\n/** A configured payment mode (admin view, `/paymentmodes/config`). */\nexport type PaymentModeConfig = PaymentModeResponse;\n\n/** Body for creating a payment-mode configuration. */\nexport type PaymentModeCreateInput = PaymentModeRequest;\n\n/** Body for updating a payment-mode configuration. */\nexport type PaymentModeUpdateInput = PaymentMethodUpdateRequest;\n\n/** A payment transaction (generated). */\nexport type PaymentTransaction = PaymentTransactionResponse;\n\n/** Result of a backend payment authorization. */\nexport type PaymentAuthorizeResult = AuthorizePaymentResponse;\n\n/** Body for capturing an authorized payment. */\nexport type PaymentCaptureInput = CaptureRequest;\n\n/** Body for refunding a captured payment. */\nexport type PaymentRefundInput = RefundRequest;\n\n/**\n * Result of a refund/cancel operation. Business failures are reported in the\n * body (`successful: false` + `message`), not via HTTP status.\n */\nexport type PaymentActionResult = CommonPaymentResponse;\n\n/** Result of a capture — like {@link PaymentActionResult} plus the provider's capture id. */\nexport type PaymentCaptureResult = {\n successful?: boolean;\n message?: string;\n captureId?: string;\n};\n\n/** Payment-Gateway: list frontend payment modes, authorize deferred payments. */\nexport class PaymentGatewayService {\n static readonly channel = \"payment\" as const;\n constructor(private readonly ctx: ClientContext) {}\n\n /**\n * Lists configured frontend payment modes. The endpoint requires a bearer\n * token but no customer scope (\"No scope required\"), so it defaults to an\n * anonymous context and works for guests and logged-in customers alike.\n */\n async listPaymentModes(authCtx: AuthContext = ANON): Promise<PaymentMode[]> {\n return this.ctx.http.request<PaymentMode[]>({\n method: \"GET\",\n path: `/payment-gateway/${this.ctx.tenant}/paymentmodes/frontend`,\n auth: authCtx,\n });\n }\n\n /** Authorizes a post-checkout (deferred) payment for an existing order. */\n async authorize(\n input: AuthorizePaymentInput,\n authCtx?: AuthContext,\n ): Promise<AuthorizePaymentResult> {\n return this.ctx.http.request<AuthorizePaymentResult>({\n method: \"POST\",\n path: `/payment-gateway/${this.ctx.tenant}/payment/frontend/authorize`,\n auth: requireCustomer(authCtx),\n body: input,\n });\n }\n\n /** Retrieves a single frontend payment mode by id. Defaults to anonymous (no scope required). */\n async getMode(id: string, authCtx: AuthContext = ANON): Promise<PaymentMode> {\n return this.ctx.http.request<PaymentMode>({\n method: \"GET\",\n path: `/payment-gateway/${this.ctx.tenant}/paymentmodes/frontend/${id}`,\n auth: authCtx,\n });\n }\n\n /** Initializes a payment from the frontend. Defaults to anonymous (no scope required). */\n async initialize(\n input: InitializePaymentInput,\n authCtx: AuthContext = ANON,\n ): Promise<InitializePaymentResult> {\n return this.ctx.http.request<InitializePaymentResult>({\n method: \"POST\",\n path: `/payment-gateway/${this.ctx.tenant}/payment/frontend/initialize`,\n auth: authCtx,\n body: input,\n });\n }\n\n /**\n * Payment-mode **configuration** (`/paymentmodes/config`) — the admin view.\n * For the storefront view use {@link listPaymentModes} / {@link getMode}.\n * Defaults to service auth.\n */\n readonly modes = {\n /** Lists all configured payment modes. The endpoint takes no query parameters. */\n list: async (authCtx: AuthContext = SERVICE): Promise<PaymentModeConfig[]> =>\n this.ctx.http.request<PaymentModeConfig[]>({\n method: \"GET\",\n path: `/payment-gateway/${this.ctx.tenant}/paymentmodes/config`,\n auth: authCtx,\n }),\n\n /** Retrieves one payment-mode configuration by id. */\n get: async (id: string, authCtx: AuthContext = SERVICE): Promise<PaymentModeConfig> =>\n this.ctx.http.request<PaymentModeConfig>({\n method: \"GET\",\n path: `/payment-gateway/${this.ctx.tenant}/paymentmodes/config/${id}`,\n auth: authCtx,\n }),\n\n /** Creates a payment-mode configuration. Responds 200 with the created mode. */\n create: async (\n input: PaymentModeCreateInput,\n authCtx: AuthContext = SERVICE,\n ): Promise<PaymentModeConfig> =>\n this.ctx.http.request<PaymentModeConfig>({\n method: \"POST\",\n path: `/payment-gateway/${this.ctx.tenant}/paymentmodes/config`,\n body: input,\n auth: authCtx,\n }),\n\n /** Updates a payment-mode configuration (PUT). Responds 200 with the updated mode. */\n update: async (\n id: string,\n input: PaymentModeUpdateInput,\n authCtx: AuthContext = SERVICE,\n ): Promise<PaymentModeConfig> =>\n this.ctx.http.request<PaymentModeConfig>({\n method: \"PUT\",\n path: `/payment-gateway/${this.ctx.tenant}/paymentmodes/config/${id}`,\n body: input,\n auth: authCtx,\n }),\n\n /** Deletes a payment-mode configuration. */\n delete: async (id: string, authCtx: AuthContext = SERVICE): Promise<void> => {\n await this.ctx.http.request<void>({\n method: \"DELETE\",\n path: `/payment-gateway/${this.ctx.tenant}/paymentmodes/config/${id}`,\n auth: authCtx,\n });\n },\n };\n\n /**\n * Backend transaction lifecycle and reads. `authorize` creates the transaction\n * that `capture`/`refund`/`cancel` then act on. Business failures are reported\n * in the response body (`successful: false`), not as HTTP errors — always check\n * `successful`. Defaults to service auth.\n */\n readonly transactions = {\n /** One page of payment transactions. */\n list: async (\n params: { pageNumber?: number; pageSize?: number; sort?: string } = {},\n authCtx: AuthContext = SERVICE,\n ): Promise<PaymentTransaction[]> => {\n const query = {\n ...(params.pageNumber === undefined ? {} : { pageNumber: params.pageNumber }),\n ...(params.pageSize === undefined ? {} : { pageSize: params.pageSize }),\n ...(params.sort === undefined ? {} : { sort: params.sort }),\n };\n return this.ctx.http.request<PaymentTransaction[]>({\n method: \"GET\",\n path: `/payment-gateway/${this.ctx.tenant}/transactions`,\n ...(Object.keys(query).length > 0 ? { query } : {}),\n auth: authCtx,\n });\n },\n\n /** Retrieves one payment transaction by id. */\n get: async (transactionId: string, authCtx: AuthContext = SERVICE): Promise<PaymentTransaction> =>\n this.ctx.http.request<PaymentTransaction>({\n method: \"GET\",\n path: `/payment-gateway/${this.ctx.tenant}/transactions/${transactionId}`,\n auth: authCtx,\n }),\n\n /**\n * Authorizes a payment as a backend caller (`POST /payment/authorize`). The\n * storefront equivalent is {@link PaymentGatewayService.authorize}, which\n * targets `/payment/frontend/authorize` with a customer token.\n */\n authorize: async (\n input: AuthorizePaymentInput,\n authCtx: AuthContext = SERVICE,\n ): Promise<PaymentAuthorizeResult> =>\n this.ctx.http.request<PaymentAuthorizeResult>({\n method: \"POST\",\n path: `/payment-gateway/${this.ctx.tenant}/payment/authorize`,\n body: input,\n auth: authCtx,\n }),\n\n /**\n * Captures an authorized payment. Omit `input` to capture the full\n * authorized amount. Returns the provider's `captureId` on success.\n */\n capture: async (\n transactionId: string,\n input?: PaymentCaptureInput,\n authCtx: AuthContext = SERVICE,\n ): Promise<PaymentCaptureResult> =>\n this.ctx.http.request<PaymentCaptureResult>({\n method: \"POST\",\n path: `/payment-gateway/${this.ctx.tenant}/payment/${transactionId}/capture`,\n ...(input === undefined ? {} : { body: input }),\n auth: authCtx,\n }),\n\n /**\n * Refunds a captured payment. Omit `input` to refund the full captured\n * amount; pass `captureId` when several captures exist for the payment.\n */\n refund: async (\n transactionId: string,\n input?: PaymentRefundInput,\n authCtx: AuthContext = SERVICE,\n ): Promise<PaymentActionResult> =>\n this.ctx.http.request<PaymentActionResult>({\n method: \"POST\",\n path: `/payment-gateway/${this.ctx.tenant}/payment/${transactionId}/refund`,\n ...(input === undefined ? {} : { body: input }),\n auth: authCtx,\n }),\n\n /** Cancels an authorized payment. Takes no body. */\n cancel: async (transactionId: string, authCtx: AuthContext = SERVICE): Promise<PaymentActionResult> =>\n this.ctx.http.request<PaymentActionResult>({\n method: \"POST\",\n path: `/payment-gateway/${this.ctx.tenant}/payment/${transactionId}/cancel`,\n auth: authCtx,\n }),\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/core/errors.ts","../src/core/auth.ts","../src/core/require-customer.ts","../src/services/payment.ts"],"names":["auth"],"mappings":";;;AACA,IAAM,kBAAA,uBAAyB,GAAA,CAAI;AAAA,EACjC,cAAA;AAAA,EAAgB,eAAA;AAAA,EAAiB,OAAA;AAAA,EAAS,eAAA;AAAA,EAAiB,WAAA;AAAA,EAC3D,QAAA;AAAA,EAAU,eAAA;AAAA,EAAiB,eAAA;AAAA,EAAiB;AAC9C,CAAC,CAAA;AAED,SAAS,MAAM,IAAA,EAAwB;AACrC,EAAA,IAAI,MAAM,OAAA,CAAQ,IAAI,GAAG,OAAO,IAAA,CAAK,IAAI,KAAK,CAAA;AAC9C,EAAA,IAAI,IAAA,IAAQ,OAAO,IAAA,KAAS,QAAA,EAAU;AACpC,IAAA,MAAM,MAA+B,EAAC;AACtC,IAAA,KAAA,MAAW,CAAC,CAAA,EAAG,CAAC,KAAK,MAAA,CAAO,OAAA,CAAQ,IAA+B,CAAA,EAAG;AACpE,MAAA,GAAA,CAAI,CAAC,CAAA,GAAI,kBAAA,CAAmB,GAAA,CAAI,CAAA,CAAE,aAAa,CAAA,GAAI,gBAAA,GAAmB,KAAA,CAAM,CAAC,CAAA;AAAA,IAC/E;AACA,IAAA,OAAO,GAAA;AAAA,EACT;AACA,EAAA,OAAO,IAAA;AACT;AAGO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA,EAC7B,MAAA;AAAA,EACA,IAAA;AAAA,EACT,WAAA,CAAY,OAAA,EAAiB,MAAA,EAAiB,IAAA,EAAgB;AAC5D,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,OAAO,GAAA,CAAA,MAAA,CAAW,IAAA;AACvB,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;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AAA,CAAK,GAAA,CAAI,IAAA,CAAK,OAAA,CAA6B;AAAA,MACzC,MAAA,EAAQ,MAAA;AAAA,MACR,MAAM,CAAA,iBAAA,EAAoB,IAAA,CAAK,GAAA,CAAI,MAAM,YAAY,aAAa,CAAA,OAAA,CAAA;AAAA,MAClE,GAAI,KAAA,KAAU,MAAA,GAAY,EAAC,GAAI,EAAE,MAAM,KAAA,EAAM;AAAA,MAC7C,IAAA,EAAM;AAAA,KACP,CAAA;AAAA;AAAA,IAGH,MAAA,EAAQ,OAAO,aAAA,EAAuB,OAAA,GAAuB,YAC3D,IAAA,CAAK,GAAA,CAAI,KAAK,OAAA,CAA6B;AAAA,MACzC,MAAA,EAAQ,MAAA;AAAA,MACR,MAAM,CAAA,iBAAA,EAAoB,IAAA,CAAK,GAAA,CAAI,MAAM,YAAY,aAAa,CAAA,OAAA,CAAA;AAAA,MAClE,IAAA,EAAM;AAAA,KACP;AAAA,GACL;AACF","file":"payment.cjs","sourcesContent":["/** Keys whose values are stripped from any serialised error body. */\nconst REDACTED_BODY_KEYS = new Set([\n \"access_token\", \"refresh_token\", \"token\", \"customertoken\", \"saastoken\",\n \"secret\", \"client_secret\", \"authorization\", \"password\",\n]);\n\nfunction scrub(body: unknown): unknown {\n if (Array.isArray(body)) return body.map(scrub);\n if (body && typeof body === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(body as Record<string, unknown>)) {\n out[k] = REDACTED_BODY_KEYS.has(k.toLowerCase()) ? \"***redacted***\" : scrub(v);\n }\n return out;\n }\n return body;\n}\n\n/** Base class for every error thrown by the SDK. */\nexport class EmporixError extends Error {\n readonly status: number | undefined;\n readonly body: unknown;\n constructor(message: string, status?: number, body?: unknown) {\n super(message);\n this.name = new.target.name;\n this.status = status;\n this.body = body;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n /** Safe serialisation — token-like body fields are redacted. */\n toJSON(): Record<string, unknown> {\n return { name: this.name, message: this.message, status: this.status, body: scrub(this.body) };\n }\n}\n\n/** 401 — authentication failed or token expired. */\nexport class EmporixAuthError extends EmporixError {}\n/** 403 — authenticated but not permitted. */\nexport class EmporixForbiddenError extends EmporixError {}\n/** 404 — resource not found. */\nexport class EmporixNotFoundError extends EmporixError {}\n/** 400/422 — request validation failed. */\nexport class EmporixValidationError extends EmporixError {}\n/** 409 — conflict: a stale `metadata.version`, or an id that already exists. */\nexport class EmporixConflictError extends EmporixError {}\n/** 5xx — server-side failure. */\nexport class EmporixServerError extends EmporixError {}\n/** Request aborted by the configured connect/read timeout. No HTTP status. */\nexport class EmporixTimeoutError extends EmporixError {}\n/** DNS/TLS/connection-level failure before or during the exchange. No HTTP status. */\nexport class EmporixNetworkError extends EmporixError {}\n\n/**\n * 403 with a `missing scope: <name>` hint in the body's `details` array.\n * Subclasses {@link EmporixForbiddenError} so existing 403 catches still work.\n */\nexport class EmporixInsufficientScopeError extends EmporixForbiddenError {\n readonly requiredScope: string | undefined;\n constructor(message: string, status: number, body: unknown, requiredScope?: string) {\n super(message, status, body);\n this.requiredScope = requiredScope;\n }\n}\n\nconst SCOPE_HINT_RE = /missing scope[: ]+([a-z0-9._-]+)/i;\n\nfunction extractRequiredScope(body: unknown): string | undefined {\n if (body && typeof body === \"object\" && \"details\" in body) {\n const details = (body as { details?: unknown }).details;\n if (Array.isArray(details)) {\n for (const d of details) {\n if (typeof d === \"string\") {\n const m = d.match(SCOPE_HINT_RE);\n if (m) return m[1];\n }\n }\n }\n }\n return undefined;\n}\n\n/** Maps an HTTP status to the matching {@link EmporixError} subclass. */\nexport function errorFromResponse(status: number, message: string, body: unknown): EmporixError {\n if (status === 401) return new EmporixAuthError(message, status, body);\n if (status === 403) {\n const scope = extractRequiredScope(body);\n if (scope) return new EmporixInsufficientScopeError(message, status, body, scope);\n return new EmporixForbiddenError(message, status, body);\n }\n if (status === 404) return new EmporixNotFoundError(message, status, body);\n if (status === 400 || status === 422) return new EmporixValidationError(message, status, body);\n if (status === 409) return new EmporixConflictError(message, status, body);\n if (status >= 500) return new EmporixServerError(message, status, body);\n return new EmporixError(message, status, body);\n}\n","import type { ResolvedConfig, ServiceCredentials } from \"./config\";\nimport { EmporixAuthError, EmporixTimeoutError, EmporixNetworkError } from \"./errors\";\n\n/** Which token a call should use. */\nexport type AuthKind = \"service\" | \"customer\" | \"anonymous\" | \"raw\";\n\n/** Caller-supplied, per-call auth selector. Never stored on the client. */\nexport type AuthContext =\n | { kind: \"service\"; credentials?: string }\n | { kind: \"anonymous\" }\n | { kind: \"customer\"; token: string }\n | { kind: \"raw\"; token: string };\n\n/**\n * Supplies a fresh customer token when a `customer`-kind request 401s. The host\n * (e.g. EmporixProvider) implements this; the SDK never refreshes the\n * caller-owned customer token unless a refresher is registered.\n */\nexport interface CustomerTokenRefresher {\n /**\n * Called on a `customer`-kind 401. Receives the token that just failed;\n * returns a fresh customer token to retry with, or `null` to give up (the\n * 401 then propagates as EmporixAuthError).\n */\n refresh(expiredToken: string): Promise<string | null>;\n}\n\n/** An obtained anonymous storefront session. */\nexport interface AnonymousSession {\n accessToken: string;\n refreshToken: string;\n sessionId: string;\n expiresIn: number;\n}\n\n/**\n * An anonymous session as it survives outside the client instance.\n *\n * `accessToken` and `expiresAt` are optional, and a store is free to drop them:\n * they turn a *server* round trip into zero token calls, because a server client\n * lives for one request and would otherwise refresh on every single one. A\n * long-lived browser client keeps the token in memory anyway, so the React\n * storage adapters deliberately persist only the two required fields — a token\n * readable by JavaScript buys nothing there.\n *\n * A store that returns `accessToken` without a future `expiresAt` gets treated as\n * having no token at all; see {@link DefaultTokenProvider.attachAnonymousStore}.\n */\nexport interface StoredAnonymousSession {\n refreshToken: string;\n sessionId: string;\n /** The access token itself, so a fresh client need not spend a refresh call for it. */\n accessToken?: string;\n /** Epoch ms after which `accessToken` is stale. The expiry buffer is already applied. */\n expiresAt?: number;\n}\n\n/**\n * Persistence callback for anonymous sessions. `read` is called once on the\n * first need for an anonymous token to bootstrap a possibly-existing session;\n * `write` is called after every successful login or refresh. `write(null)`\n * means the SDK is invalidating the stored session.\n */\nexport interface AnonymousSessionStore {\n read(): StoredAnonymousSession | null;\n write(session: StoredAnonymousSession | null): void;\n}\n\n/** Supplies SDK-managed tokens (service/custom + anonymous). May be user-injected. */\nexport interface TokenProvider {\n /** Service/custom client-credentials token for the named credential set. */\n getToken(credentialSet: string): Promise<string>;\n /** Cached anonymous storefront session (preserves sessionId across refreshes). */\n getAnonymousToken(): Promise<AnonymousSession>;\n /** Refresh the anonymous session, preserving sessionId. */\n refreshAnonymous?(): Promise<AnonymousSession>;\n /** Invalidate a cached SDK-managed token so the next call re-auths. */\n invalidate?(credentialSet: string): void;\n /** Invalidate the cached anonymous session entirely (next call re-logs in). */\n invalidateAnonymous?(): void;\n /**\n * Mark the anonymous access token stale but keep the refresh token, so the\n * next {@link getAnonymousToken} refreshes (preserving sessionId) rather\n * than starting a brand-new session.\n */\n expireAnonymous?(): void;\n /**\n * Install a persistence adapter for the anonymous session. The host (e.g.\n * `EmporixProvider`) calls this at construction so the SDK can bootstrap\n * an existing session and persist refreshes. Idempotent: a later call\n * replaces the previous adapter.\n */\n attachAnonymousStore?(store: AnonymousSessionStore): void;\n /**\n * Override the storefront context (currency/site/country) used for the next\n * anonymous login, then invalidate the current anonymous session so it\n * re-mints with the new context. No-op for providers without anon support.\n */\n setAnonymousContext?(ctx: {\n currency?: string;\n siteCode?: string;\n targetLocation?: string;\n }): void;\n /**\n * Subscribe to token-refresh events. Optional — implementations may no-op.\n * Returns an unsubscribe function. `DefaultTokenProvider` emits for the\n * anonymous-login / anonymous-refresh paths.\n */\n onRefresh?(\n listener: (event: { kind: \"anonymous\" | \"customer\"; success: boolean }) => void,\n ): () => void;\n}\n\n/** Tiny constructors for {@link AuthContext}. */\nexport const auth = {\n /** Service/custom credential set (default `backend`). */\n service: (credentials?: string): AuthContext =>\n credentials === undefined ? { kind: \"service\" } : { kind: \"service\", credentials },\n /** Cached anonymous storefront token. */\n anonymous: (): AuthContext => ({ kind: \"anonymous\" }),\n /** Caller-owned customer bearer token. */\n customer: (token: string): AuthContext => ({ kind: \"customer\", token }),\n /** Exact token, no transformation (SSO / token-exchange). */\n raw: (token: string): AuthContext => ({ kind: \"raw\", token }),\n};\n\n/** Resolves an {@link AuthContext} to a concrete bearer token. */\nexport async function resolveToken(ctx: AuthContext, provider: TokenProvider): Promise<string> {\n switch (ctx.kind) {\n case \"service\":\n return provider.getToken(ctx.credentials ?? \"backend\");\n case \"anonymous\":\n return (await provider.getAnonymousToken()).accessToken;\n case \"customer\":\n case \"raw\":\n return ctx.token;\n }\n}\n\n/**\n * Late-bindable, single-flight holder for an optional\n * {@link CustomerTokenRefresher}. Single-flight is required because Emporix\n * rotates the refresh token on each refresh — concurrent refreshes would\n * invalidate each other. Off (returns `null`) until a refresher is set.\n */\nexport class CustomerRefreshRegistry {\n private refresher: CustomerTokenRefresher | null = null;\n private inflight: Promise<string | null> | null = null;\n\n set(refresher: CustomerTokenRefresher | null): void {\n this.refresher = refresher;\n }\n\n get enabled(): boolean {\n return this.refresher !== null;\n }\n\n /** Concurrent callers share one in-flight refresh. */\n refresh(expiredToken: string): Promise<string | null> {\n if (!this.refresher) return Promise.resolve(null);\n if (this.inflight) return this.inflight;\n const p = Promise.resolve(this.refresher.refresh(expiredToken)).finally(() => {\n this.inflight = null;\n });\n this.inflight = p;\n return p;\n }\n}\n\ninterface CacheEntry {\n token: string;\n expiresAt: number;\n obtainedAt: number;\n}\n\n/** SDK-owned token provider: client-credentials service tokens + anonymous session. */\nexport class DefaultTokenProvider implements TokenProvider {\n private readonly serviceCache = new Map<string, CacheEntry>();\n private readonly serviceLocks = new Map<string, Promise<string>>();\n private anon: (AnonymousSession & { expiresAt: number }) | undefined;\n private anonLock: Promise<AnonymousSession> | undefined;\n private anonStore?: AnonymousSessionStore;\n private contextOverride:\n | { currency?: string; siteCode?: string; targetLocation?: string }\n | undefined;\n private readonly refreshListeners = new Set<\n (event: { kind: \"anonymous\" | \"customer\"; success: boolean }) => void\n >();\n\n constructor(private readonly cfg: ResolvedConfig) {}\n\n onRefresh(\n listener: (event: { kind: \"anonymous\" | \"customer\"; success: boolean }) => void,\n ): () => void {\n this.refreshListeners.add(listener);\n return () => {\n this.refreshListeners.delete(listener);\n };\n }\n\n private notifyRefresh(kind: \"anonymous\" | \"customer\", success: boolean): void {\n for (const l of this.refreshListeners) {\n try {\n l({ kind, success });\n } catch {\n // Never let a telemetry listener break the auth path.\n }\n }\n }\n\n attachAnonymousStore(store: AnonymousSessionStore): void {\n this.anonStore = store;\n // Bootstrap `this.anon` from the store if we don't have it yet.\n //\n // A persisted access token that is still inside its lifetime is adopted as\n // is, and that is the point on a server: a client that lives for one request\n // would otherwise spend one `/anonymous/refresh` per request for a token it\n // already holds. Without a token — or past its expiry — `expiresAt` stays 0\n // and the next getAnonymousToken refreshes, which preserves the sessionId,\n // so the guest's cart survives either way.\n //\n // `expiresAt` counts only when there is a token to go with it. A store that\n // returns one without the other would otherwise make `anonFresh()` true and\n // hand out an empty bearer token.\n //\n // Trusting a stored expiry means trusting the writer's clock. A token\n // revoked early, or an expiry that a skewed clock made look valid, comes\n // back as a 401 — which `HttpClient` answers with `expireAnonymous()` plus\n // one retry, so the failure mode is a refresh, not an error.\n if (!this.anon) {\n const persisted = store.read();\n if (persisted) {\n const token = persisted.accessToken ?? \"\";\n this.anon = {\n accessToken: token,\n refreshToken: persisted.refreshToken,\n sessionId: persisted.sessionId,\n expiresIn: 0,\n expiresAt: token === \"\" ? 0 : (persisted.expiresAt ?? 0),\n };\n }\n }\n }\n\n private creds(set: string): ServiceCredentials {\n if (set === \"backend\") {\n const b = this.cfg.credentials.backend;\n if (!b?.clientId || !b.secret) {\n throw new EmporixAuthError(\n \"A 'service' AuthContext was used but credentials.backend is not configured\",\n );\n }\n return b;\n }\n const c = this.cfg.credentials.custom?.[set];\n if (!c) throw new Error(`Unknown credential set \"${set}\"`);\n return c;\n }\n\n private fresh(e: CacheEntry | undefined): boolean {\n if (!e) return false;\n const now = Date.now();\n if (now - e.obtainedAt >= this.cfg.cache.maxLifetimeSeconds * 1000) return false;\n return now < e.expiresAt;\n }\n\n async getToken(set: string): Promise<string> {\n // Surface an unknown credential set before entering the cache/lock path.\n this.creds(set);\n const cached = this.serviceCache.get(set);\n if (this.fresh(cached)) return cached!.token;\n const inflight = this.serviceLocks.get(set);\n if (inflight) return inflight;\n const p = this.requestServiceToken(set).finally(() => this.serviceLocks.delete(set));\n this.serviceLocks.set(set, p);\n return p;\n }\n\n /**\n * fetch with the configured read timeout. Token endpoints sit in front of\n * single-flight locks — one hung call would otherwise block every request\n * on this credential set forever.\n */\n private async boundedFetch(url: string | URL, init: RequestInit = {}): Promise<Response> {\n const ms = this.cfg.timeouts?.readMs ?? 60_000;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), ms);\n try {\n return await fetch(url, { ...init, signal: controller.signal });\n } catch (err) {\n if ((err as Error).name === \"AbortError\") {\n throw new EmporixTimeoutError(`token request timed out after ${ms}ms`);\n }\n throw new EmporixNetworkError(`token request network failure: ${(err as Error).message}`);\n } finally {\n clearTimeout(timer);\n }\n }\n\n private async requestServiceToken(set: string): Promise<string> {\n const c = this.creds(set);\n const body = new URLSearchParams({\n grant_type: \"client_credentials\",\n client_id: c.clientId,\n client_secret: c.secret,\n });\n if (c.scope) body.set(\"scope\", c.scope);\n const res = await this.boundedFetch(`${this.cfg.host}/oauth/token`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body,\n });\n const json = (await res.json().catch(() => ({}))) as Record<string, unknown>;\n if (!res.ok) {\n throw new EmporixAuthError(`Token request failed for \"${set}\"`, res.status, json);\n }\n const obtainedAt = Date.now();\n const ttl = Number((json.expires_in as number | undefined) ?? 3600);\n this.serviceCache.set(set, {\n token: json.access_token as string,\n obtainedAt,\n expiresAt: obtainedAt + (ttl - this.cfg.cache.expirationBufferSeconds) * 1000,\n });\n return this.serviceCache.get(set)!.token;\n }\n\n invalidate(set: string): void {\n this.serviceCache.delete(set);\n }\n\n private anonFresh(): boolean {\n return !!this.anon && Date.now() < this.anon.expiresAt;\n }\n\n async getAnonymousToken(): Promise<AnonymousSession> {\n if (this.anonFresh()) return this.stripExpiry(this.anon!);\n if (this.anonLock) return this.anonLock;\n // Token expired but a refresh token survives → refresh to keep the same\n // sessionId; only fall back to a brand-new login if the refresh fails.\n const canRefresh = !!this.anon?.refreshToken;\n const obtain = canRefresh\n ? this.fetchAnonymous(\"refresh\").catch(() => this.fetchAnonymous(\"login\"))\n : this.fetchAnonymous(\"login\");\n const p = obtain.finally(() => {\n this.anonLock = undefined;\n });\n this.anonLock = p;\n return p;\n }\n\n /** Refreshes the anonymous session, preserving its sessionId. */\n async refreshAnonymous(): Promise<AnonymousSession> {\n if (!this.anon) return this.getAnonymousToken();\n return this.fetchAnonymous(\"refresh\");\n }\n\n invalidateAnonymous(): void {\n this.anon = undefined;\n this.anonStore?.write(null);\n }\n\n setAnonymousContext(ctx: {\n currency?: string;\n siteCode?: string;\n targetLocation?: string;\n }): void {\n const base = this.contextOverride ?? this.cfg.credentials.storefront?.context ?? {};\n this.contextOverride = { ...base, ...ctx };\n this.invalidateAnonymous();\n }\n\n /** Force a stale access token while keeping the refresh token + sessionId. */\n expireAnonymous(): void {\n if (this.anon) this.anon = { ...this.anon, expiresAt: 0 };\n }\n\n private stripExpiry(s: AnonymousSession & { expiresAt: number }): AnonymousSession {\n const { expiresAt: _expiresAt, ...rest } = s;\n return rest;\n }\n\n private async fetchAnonymous(mode: \"login\" | \"refresh\"): Promise<AnonymousSession> {\n const sf = this.cfg.credentials.storefront;\n if (!sf?.clientId) {\n throw new Error(\"credentials.storefront.clientId is required for anonymous tokens\");\n }\n const url = new URL(`${this.cfg.host}/customerlogin/auth/anonymous/${mode}`);\n url.searchParams.set(\"tenant\", this.cfg.tenant);\n url.searchParams.set(\"client_id\", sf.clientId);\n // Context is the runtime override (set via setAnonymousContext) if present,\n // else the config-fixed context.\n const c = this.contextOverride ?? sf.context;\n if (c?.currency) url.searchParams.set(\"currency\", c.currency);\n if (c?.siteCode) url.searchParams.set(\"siteCode\", c.siteCode);\n if (c?.targetLocation) url.searchParams.set(\"targetLocation\", c.targetLocation);\n if (mode === \"refresh\" && this.anon) {\n url.searchParams.set(\"refresh_token\", this.anon.refreshToken);\n }\n try {\n const res = await this.boundedFetch(url, { method: \"GET\" });\n const json = (await res.json().catch(() => ({}))) as Record<string, unknown>;\n if (!res.ok) {\n this.notifyRefresh(\"anonymous\", false);\n throw new EmporixAuthError(`Anonymous token ${mode} failed`, res.status, json);\n }\n const obtainedAt = Date.now();\n this.anon = {\n accessToken: json.access_token as string,\n refreshToken: json.refresh_token as string,\n sessionId: json.sessionId as string,\n expiresIn: json.expires_in as number,\n expiresAt:\n obtainedAt +\n ((json.expires_in as number) - this.cfg.cache.expirationBufferSeconds) * 1000,\n };\n // The access token and its expiry go out too, so a store that keeps them\n // (a server one) can hand the next request a usable token instead of\n // another refresh. A store that only wants the refresh token drops them.\n this.anonStore?.write({\n refreshToken: this.anon.refreshToken,\n sessionId: this.anon.sessionId,\n accessToken: this.anon.accessToken,\n expiresAt: this.anon.expiresAt,\n });\n this.notifyRefresh(\"anonymous\", true);\n return this.stripExpiry(this.anon);\n } catch (err) {\n // Re-throw EmporixAuthError as-is; for non-Emporix errors (network), also notify.\n if (!(err instanceof EmporixAuthError)) {\n this.notifyRefresh(\"anonymous\", false);\n }\n throw err;\n }\n }\n}\n// Customer-token refreshes happen via client.customers.refresh() and don't\n// route through this TokenProvider — only the anonymous flow notifies.\n// React-side useCustomerSession.refresh emits its own telemetry event in a\n// follow-up if needed.\n","import type { AuthContext } from \"./auth\";\nimport { EmporixAuthError } from \"./errors\";\n\n/**\n * Enforces a caller-owned customer or raw token. Throws `EmporixAuthError`\n * for any other `AuthContext` kind (or when `auth` is missing). Shared by\n * services whose endpoints require a customer scope (`/me`, payments,\n * customer-segments…).\n */\nexport function requireCustomer(auth: AuthContext | undefined): AuthContext {\n if (auth && (auth.kind === \"customer\" || auth.kind === \"raw\")) return auth;\n throw new EmporixAuthError(\"This operation requires a customer or raw AuthContext\");\n}\n","import type { ClientContext } from \"../core/context\";\nimport { auth, type AuthContext } from \"../core/auth\";\nimport { requireCustomer } from \"../core/require-customer\";\nimport type {\n PaymentModeFrontendResponse,\n AuthorizePaymentRequest,\n InitializePaymentRequest,\n InitializePaymentResponse,\n PaymentModeResponse,\n PaymentModeRequest,\n PaymentMethodUpdateRequest,\n PaymentTransactionResponse,\n AuthorizePaymentResponse,\n CaptureRequest,\n RefundRequest,\n CommonPaymentResponse,\n} from \"../generated/payment\";\n\nconst ANON: AuthContext = auth.anonymous();\nconst SERVICE: AuthContext = auth.service();\n\n/** A frontend payment mode (generated). */\nexport type PaymentMode = PaymentModeFrontendResponse;\n\n/** Post-checkout authorize request (generated; caller sends the exact wire shape). */\nexport type AuthorizePaymentInput = AuthorizePaymentRequest;\n\n/** Frontend payment-initialize request (generated). */\nexport type InitializePaymentInput = InitializePaymentRequest;\n\n/** Frontend payment-initialize response (generated). */\nexport type InitializePaymentResult = InitializePaymentResponse;\n\n/** Post-checkout authorize result. */\nexport interface AuthorizePaymentResult {\n successful: boolean;\n paymentTransactionId?: string;\n authorizationToken?: string;\n requiresExternalPayment?: boolean;\n externalPaymentRedirectURL?: string;\n externalPaymentHttpMethod?: string;\n [k: string]: unknown;\n}\n\n/** A configured payment mode (admin view, `/paymentmodes/config`). */\nexport type PaymentModeConfig = PaymentModeResponse;\n\n/** Body for creating a payment-mode configuration. */\nexport type PaymentModeCreateInput = PaymentModeRequest;\n\n/** Body for updating a payment-mode configuration. */\nexport type PaymentModeUpdateInput = PaymentMethodUpdateRequest;\n\n/** A payment transaction (generated). */\nexport type PaymentTransaction = PaymentTransactionResponse;\n\n/** Result of a backend payment authorization. */\nexport type PaymentAuthorizeResult = AuthorizePaymentResponse;\n\n/** Body for capturing an authorized payment. */\nexport type PaymentCaptureInput = CaptureRequest;\n\n/** Body for refunding a captured payment. */\nexport type PaymentRefundInput = RefundRequest;\n\n/**\n * Result of a refund/cancel operation. Business failures are reported in the\n * body (`successful: false` + `message`), not via HTTP status.\n */\nexport type PaymentActionResult = CommonPaymentResponse;\n\n/** Result of a capture — like {@link PaymentActionResult} plus the provider's capture id. */\nexport type PaymentCaptureResult = {\n successful?: boolean;\n message?: string;\n captureId?: string;\n};\n\n/** Payment-Gateway: list frontend payment modes, authorize deferred payments. */\nexport class PaymentGatewayService {\n static readonly channel = \"payment\" as const;\n constructor(private readonly ctx: ClientContext) {}\n\n /**\n * Lists configured frontend payment modes. The endpoint requires a bearer\n * token but no customer scope (\"No scope required\"), so it defaults to an\n * anonymous context and works for guests and logged-in customers alike.\n */\n async listPaymentModes(authCtx: AuthContext = ANON): Promise<PaymentMode[]> {\n return this.ctx.http.request<PaymentMode[]>({\n method: \"GET\",\n path: `/payment-gateway/${this.ctx.tenant}/paymentmodes/frontend`,\n auth: authCtx,\n });\n }\n\n /** Authorizes a post-checkout (deferred) payment for an existing order. */\n async authorize(\n input: AuthorizePaymentInput,\n authCtx?: AuthContext,\n ): Promise<AuthorizePaymentResult> {\n return this.ctx.http.request<AuthorizePaymentResult>({\n method: \"POST\",\n path: `/payment-gateway/${this.ctx.tenant}/payment/frontend/authorize`,\n auth: requireCustomer(authCtx),\n body: input,\n });\n }\n\n /** Retrieves a single frontend payment mode by id. Defaults to anonymous (no scope required). */\n async getMode(id: string, authCtx: AuthContext = ANON): Promise<PaymentMode> {\n return this.ctx.http.request<PaymentMode>({\n method: \"GET\",\n path: `/payment-gateway/${this.ctx.tenant}/paymentmodes/frontend/${id}`,\n auth: authCtx,\n });\n }\n\n /** Initializes a payment from the frontend. Defaults to anonymous (no scope required). */\n async initialize(\n input: InitializePaymentInput,\n authCtx: AuthContext = ANON,\n ): Promise<InitializePaymentResult> {\n return this.ctx.http.request<InitializePaymentResult>({\n method: \"POST\",\n path: `/payment-gateway/${this.ctx.tenant}/payment/frontend/initialize`,\n auth: authCtx,\n body: input,\n });\n }\n\n /**\n * Payment-mode **configuration** (`/paymentmodes/config`) — the admin view.\n * For the storefront view use {@link listPaymentModes} / {@link getMode}.\n * Defaults to service auth.\n */\n readonly modes = {\n /** Lists all configured payment modes. The endpoint takes no query parameters. */\n list: async (authCtx: AuthContext = SERVICE): Promise<PaymentModeConfig[]> =>\n this.ctx.http.request<PaymentModeConfig[]>({\n method: \"GET\",\n path: `/payment-gateway/${this.ctx.tenant}/paymentmodes/config`,\n auth: authCtx,\n }),\n\n /** Retrieves one payment-mode configuration by id. */\n get: async (id: string, authCtx: AuthContext = SERVICE): Promise<PaymentModeConfig> =>\n this.ctx.http.request<PaymentModeConfig>({\n method: \"GET\",\n path: `/payment-gateway/${this.ctx.tenant}/paymentmodes/config/${id}`,\n auth: authCtx,\n }),\n\n /** Creates a payment-mode configuration. Responds 200 with the created mode. */\n create: async (\n input: PaymentModeCreateInput,\n authCtx: AuthContext = SERVICE,\n ): Promise<PaymentModeConfig> =>\n this.ctx.http.request<PaymentModeConfig>({\n method: \"POST\",\n path: `/payment-gateway/${this.ctx.tenant}/paymentmodes/config`,\n body: input,\n auth: authCtx,\n }),\n\n /** Updates a payment-mode configuration (PUT). Responds 200 with the updated mode. */\n update: async (\n id: string,\n input: PaymentModeUpdateInput,\n authCtx: AuthContext = SERVICE,\n ): Promise<PaymentModeConfig> =>\n this.ctx.http.request<PaymentModeConfig>({\n method: \"PUT\",\n path: `/payment-gateway/${this.ctx.tenant}/paymentmodes/config/${id}`,\n body: input,\n auth: authCtx,\n }),\n\n /** Deletes a payment-mode configuration. */\n delete: async (id: string, authCtx: AuthContext = SERVICE): Promise<void> => {\n await this.ctx.http.request<void>({\n method: \"DELETE\",\n path: `/payment-gateway/${this.ctx.tenant}/paymentmodes/config/${id}`,\n auth: authCtx,\n });\n },\n };\n\n /**\n * Backend transaction lifecycle and reads. `authorize` creates the transaction\n * that `capture`/`refund`/`cancel` then act on. Business failures are reported\n * in the response body (`successful: false`), not as HTTP errors — always check\n * `successful`. Defaults to service auth.\n */\n readonly transactions = {\n /** One page of payment transactions. */\n list: async (\n params: { pageNumber?: number; pageSize?: number; sort?: string } = {},\n authCtx: AuthContext = SERVICE,\n ): Promise<PaymentTransaction[]> => {\n const query = {\n ...(params.pageNumber === undefined ? {} : { pageNumber: params.pageNumber }),\n ...(params.pageSize === undefined ? {} : { pageSize: params.pageSize }),\n ...(params.sort === undefined ? {} : { sort: params.sort }),\n };\n return this.ctx.http.request<PaymentTransaction[]>({\n method: \"GET\",\n path: `/payment-gateway/${this.ctx.tenant}/transactions`,\n ...(Object.keys(query).length > 0 ? { query } : {}),\n auth: authCtx,\n });\n },\n\n /** Retrieves one payment transaction by id. */\n get: async (transactionId: string, authCtx: AuthContext = SERVICE): Promise<PaymentTransaction> =>\n this.ctx.http.request<PaymentTransaction>({\n method: \"GET\",\n path: `/payment-gateway/${this.ctx.tenant}/transactions/${transactionId}`,\n auth: authCtx,\n }),\n\n /**\n * Authorizes a payment as a backend caller (`POST /payment/authorize`). The\n * storefront equivalent is {@link PaymentGatewayService.authorize}, which\n * targets `/payment/frontend/authorize` with a customer token.\n */\n authorize: async (\n input: AuthorizePaymentInput,\n authCtx: AuthContext = SERVICE,\n ): Promise<PaymentAuthorizeResult> =>\n this.ctx.http.request<PaymentAuthorizeResult>({\n method: \"POST\",\n path: `/payment-gateway/${this.ctx.tenant}/payment/authorize`,\n body: input,\n auth: authCtx,\n }),\n\n /**\n * Captures an authorized payment. Omit `input` to capture the full\n * authorized amount. Returns the provider's `captureId` on success.\n */\n capture: async (\n transactionId: string,\n input?: PaymentCaptureInput,\n authCtx: AuthContext = SERVICE,\n ): Promise<PaymentCaptureResult> =>\n this.ctx.http.request<PaymentCaptureResult>({\n method: \"POST\",\n path: `/payment-gateway/${this.ctx.tenant}/payment/${transactionId}/capture`,\n ...(input === undefined ? {} : { body: input }),\n auth: authCtx,\n }),\n\n /**\n * Refunds a captured payment. Omit `input` to refund the full captured\n * amount; pass `captureId` when several captures exist for the payment.\n */\n refund: async (\n transactionId: string,\n input?: PaymentRefundInput,\n authCtx: AuthContext = SERVICE,\n ): Promise<PaymentActionResult> =>\n this.ctx.http.request<PaymentActionResult>({\n method: \"POST\",\n path: `/payment-gateway/${this.ctx.tenant}/payment/${transactionId}/refund`,\n ...(input === undefined ? {} : { body: input }),\n auth: authCtx,\n }),\n\n /** Cancels an authorized payment. Takes no body. */\n cancel: async (transactionId: string, authCtx: AuthContext = SERVICE): Promise<PaymentActionResult> =>\n this.ctx.http.request<PaymentActionResult>({\n method: \"POST\",\n path: `/payment-gateway/${this.ctx.tenant}/payment/${transactionId}/cancel`,\n auth: authCtx,\n }),\n };\n}\n"]}
package/dist/payment.js CHANGED
@@ -1,5 +1,5 @@
1
- export { PaymentGatewayService } from './chunk-4VRUMCS2.js';
2
- import './chunk-3BDDYX3V.js';
3
- import './chunk-UWGGF4MC.js';
1
+ export { PaymentGatewayService } from './chunk-PK4DQHJO.js';
2
+ import './chunk-ZVIEFW3X.js';
3
+ import './chunk-4Q76UV4J.js';
4
4
  //# sourceMappingURL=payment.js.map
5
5
  //# sourceMappingURL=payment.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/errors.ts","../src/core/search.ts","../src/services/price.ts"],"names":[],"mappings":";;;AACA,IAAM,kBAAA,uBAAyB,GAAA,CAAI;AAAA,EACjC,cAAA;AAAA,EAAgB,eAAA;AAAA,EAAiB,OAAA;AAAA,EAAS,eAAA;AAAA,EAAiB,WAAA;AAAA,EAC3D,QAAA;AAAA,EAAU,eAAA;AAAA,EAAiB,eAAA;AAAA,EAAiB;AAC9C,CAAC,CAAA;AAED,SAAS,MAAM,IAAA,EAAwB;AACrC,EAAA,IAAI,MAAM,OAAA,CAAQ,IAAI,GAAG,OAAO,IAAA,CAAK,IAAI,KAAK,CAAA;AAC9C,EAAA,IAAI,IAAA,IAAQ,OAAO,IAAA,KAAS,QAAA,EAAU;AACpC,IAAA,MAAM,MAA+B,EAAC;AACtC,IAAA,KAAA,MAAW,CAAC,CAAA,EA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AI,MAAM,gBAAgB,MAAM,CAAA,YAAA,CAAA;AAAA,MACrD,IAAA,EAAM,OAAA;AAAA,MACN,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,IACH,gBAAA,EAAkB,OAChB,MAAA,EACA,MAAA,EACA,UAAuB,OAAA,KAEvB,IAAA,CAAK,GAAA,CAAI,IAAA,CAAK,OAAA,CAA2B;AAAA,MACvC,MAAA,EAAQ,KAAA;AAAA,MACR,MAAM,CAAA,OAAA,EAAU,IAAA,CAAK,GAAA,CAAI,MAAM,gBAAgB,MAAM,CAAA,YAAA,CAAA;AAAA,MACrD,IAAA,EAAM,OAAA;AAAA,MACN,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,IACH,gBAAA,EAAkB,OAChB,MAAA,EACA,IAAA,EACA,UAAuB,OAAA,KAEvB,IAAA,CAAK,GAAA,CAAI,IAAA,CAAK,OAAA,CAA2B;AAAA,MACvC,MAAA,EAAQ,QAAA;AAAA,MACR,MAAM,CAAA,OAAA,EAAU,IAAA,CAAK,GAAA,CAAI,MAAM,gBAAgB,MAAM,CAAA,YAAA,CAAA;AAAA,MACrD,IAAA,EAAM,OAAA;AAAA,MACN;AAAA,KACD;AAAA,GACL;AACF","file":"price.cjs","sourcesContent":["/** Keys whose values are stripped from any serialised error body. */\nconst REDACTED_BODY_KEYS = new Set([\n \"access_token\", \"refresh_token\", \"token\", \"customertoken\", \"saastoken\",\n \"secret\", \"client_secret\", \"authorization\", \"password\",\n]);\n\nfunction scrub(body: unknown): unknown {\n if (Array.isArray(body)) return body.map(scrub);\n if (body && typeof body === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(body as Record<string, unknown>)) {\n out[k] = REDACTED_BODY_KEYS.has(k.toLowerCase()) ? \"***redacted***\" : scrub(v);\n }\n return out;\n }\n return body;\n}\n\n/** Base class for every error thrown by the SDK. */\nexport class EmporixError extends Error {\n readonly status: number | undefined;\n readonly body: unknown;\n constructor(message: string, status?: number, body?: unknown) {\n super(message);\n this.name = new.target.name;\n this.status = status;\n this.body = body;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n /** Safe serialisation — token-like body fields are redacted. */\n toJSON(): Record<string, unknown> {\n return { name: this.name, message: this.message, status: this.status, body: scrub(this.body) };\n }\n}\n\n/** 401 — authentication failed or token expired. */\nexport class EmporixAuthError extends EmporixError {}\n/** 403 — authenticated but not permitted. */\nexport class EmporixForbiddenError extends EmporixError {}\n/** 404 — resource not found. */\nexport class EmporixNotFoundError extends EmporixError {}\n/** 400/422 — request validation failed. */\nexport class EmporixValidationError extends EmporixError {}\n/** 5xx — server-side failure. */\nexport class EmporixServerError extends EmporixError {}\n/** Request aborted by the configured connect/read timeout. No HTTP status. */\nexport class EmporixTimeoutError extends EmporixError {}\n/** DNS/TLS/connection-level failure before or during the exchange. No HTTP status. */\nexport class EmporixNetworkError extends EmporixError {}\n\n/**\n * 403 with a `missing scope: <name>` hint in the body's `details` array.\n * Subclasses {@link EmporixForbiddenError} so existing 403 catches still work.\n */\nexport class EmporixInsufficientScopeError extends EmporixForbiddenError {\n readonly requiredScope: string | undefined;\n constructor(message: string, status: number, body: unknown, requiredScope?: string) {\n super(message, status, body);\n this.requiredScope = requiredScope;\n }\n}\n\nconst SCOPE_HINT_RE = /missing scope[: ]+([a-z0-9._-]+)/i;\n\nfunction extractRequiredScope(body: unknown): string | undefined {\n if (body && typeof body === \"object\" && \"details\" in body) {\n const details = (body as { details?: unknown }).details;\n if (Array.isArray(details)) {\n for (const d of details) {\n if (typeof d === \"string\") {\n const m = d.match(SCOPE_HINT_RE);\n if (m) return m[1];\n }\n }\n }\n }\n return undefined;\n}\n\n/** Maps an HTTP status to the matching {@link EmporixError} subclass. */\nexport function errorFromResponse(status: number, message: string, body: unknown): EmporixError {\n if (status === 401) return new EmporixAuthError(message, status, body);\n if (status === 403) {\n const scope = extractRequiredScope(body);\n if (scope) return new EmporixInsufficientScopeError(message, status, body, scope);\n return new EmporixForbiddenError(message, status, body);\n }\n if (status === 404) return new EmporixNotFoundError(message, status, body);\n if (status === 400 || status === 422) return new EmporixValidationError(message, status, body);\n if (status >= 500) return new EmporixServerError(message, status, body);\n return new EmporixError(message, status, body);\n}\n","/**\n * Paging, sort and field selection for a `POST …/search` endpoint. Emporix reads\n * them from the query string, not the body, so the SDK sends them there. Without\n * them a search returns only the server's first page.\n */\nexport interface SearchPaging {\n pageNumber?: number;\n pageSize?: number;\n /** Properties to sort by, in Emporix sort syntax. */\n sort?: string;\n /** Comma-separated fields to return. */\n fields?: string;\n}\n\n/** The {@link SearchPaging} keys, for {@link splitQuery}. */\nexport const SEARCH_PAGING = [\"pageNumber\", \"pageSize\", \"sort\", \"fields\"] as const;\n\n/**\n * Splits a request input: the named keys go to the query string, everything\n * else stays in the body. A `POST …/search` declares its paging, sort and similar\n * parameters in the query and ignores them in the body — sent there, the search\n * silently returns the first page.\n */\nexport function splitQuery(\n input: object,\n queryKeys: readonly string[],\n): { body: Record<string, unknown>; query: Record<string, string | number | boolean | undefined> } {\n const body: Record<string, unknown> = {};\n const query: Record<string, string | number | boolean | undefined> = {};\n for (const [key, value] of Object.entries(input)) {\n if (queryKeys.includes(key)) query[key] = value as string | number | boolean | undefined;\n else body[key] = value;\n }\n return { body, query };\n}\n","import type { ClientContext } from \"../core/context\";\nimport type { AuthContext } from \"../core/auth\";\nimport { EmporixAuthError } from \"../core/errors\";\nimport { splitQuery, type SearchPaging } from \"../core/search\";\nimport type {\n Match,\n MatchByContext,\n MatchResponse,\n CreatePrice,\n GetPrice,\n PriceModelDefinitionCreation,\n PriceModelRetrieval,\n PriceListCreation,\n PriceListUpdate,\n PriceList as GenPriceList,\n PriceListPriceCreation,\n PriceListPriceUpdate,\n PriceListPrice as GenPriceListPrice,\n PriceBulkResponseEntry,\n} from \"../generated/price\";\n\n/** Session-context match request body (generated). */\nexport type PriceMatchByContextInput = MatchByContext;\n\n/** Explicit-context match request body (generated). */\nexport type PriceMatchInput = Match;\n\n/** Item (product or price) a price was matched for. */\nexport interface PriceMatchItemRef {\n itemType?: string;\n id?: string;\n /** Localized (or plain) product name — present on the live API, absent from the OpenAPI doc. */\n name?: Record<string, string> | string;\n}\n\n/**\n * A resolved price. Superset of the generated match-response schema: the\n * deployed API returns the matched item under `itemId` (with a localized\n * `name`), while the OpenAPI doc/codegen call it `itemRef`.\n */\nexport type PriceMatch = Omit<MatchResponse, \"itemRef\"> & {\n /** Item the price was matched for, as returned by the API. */\n itemId?: PriceMatchItemRef;\n /**\n * @deprecated The OpenAPI doc names this `itemRef`, but the deployed API\n * returns `itemId`. Mirrored from `itemId` for back-compat — prefer `itemId`.\n */\n itemRef?: PriceMatchItemRef;\n};\n\n/**\n * Normalizes a raw match row: the deployed API returns `itemId`, while the\n * codegen type calls it `itemRef`. Expose `itemId` canonically and mirror it\n * to the deprecated `itemRef` so existing consumers keep working.\n */\nfunction normalizeMatch(raw: MatchResponse): PriceMatch {\n const itemId = (raw as MatchResponse & { itemId?: PriceMatchItemRef }).itemId ?? raw.itemRef;\n const base = raw as PriceMatch;\n if (!itemId) return base;\n // Mirror only id/type into the deprecated itemRef (drop name); build without\n // explicit `undefined` for exactOptionalPropertyTypes.\n const itemRef: PriceMatchItemRef = {\n ...(itemId.itemType !== undefined ? { itemType: itemId.itemType } : {}),\n ...(itemId.id !== undefined ? { id: itemId.id } : {}),\n };\n return { ...base, itemId, itemRef };\n}\n\n/** Options for {@link PriceService.matchByContextChunked}. */\nexport interface MatchByContextChunkedOptions {\n /** Items per request. Default 50. Must be >= 1. */\n chunkSize?: number;\n /** Maximum number of requests in flight at once. Default 4. Must be >= 1. */\n concurrency?: number;\n /** Invoked once per failed chunk (default mode only — not when throwing). */\n onChunkError?: (err: unknown, chunkIndex: number) => void;\n /** When true, the first failing chunk rejects the whole call. Default false. */\n throwOnAnyChunkError?: boolean;\n}\n\n/** A resolved/stored price (generated read shape). */\nexport type Price = GetPrice;\n/** Create/upsert body for a flat price (generated). */\nexport type PriceCreateInput = CreatePrice;\n/** A price model (read). */\nexport type PriceModel = PriceModelRetrieval;\n/** Create/upsert body for a price model (generated). */\nexport type PriceModelInput = PriceModelDefinitionCreation;\n/** A price list (read). */\nexport type PriceList = GenPriceList;\n/** Create body for a price list (generated). */\nexport type PriceListInput = PriceListCreation;\n/** Upsert body for a price list (generated). */\nexport type PriceListUpdateInput = PriceListUpdate;\n/** A price inside a price list (read). */\nexport type PriceListPrice = GenPriceListPrice;\n/** Add body for a price-list price (generated). */\nexport type PriceListPriceInput = PriceListPriceCreation;\n/** Upsert body for a price-list price (generated). */\nexport type PriceListPriceUpdateInput = PriceListPriceUpdate;\n/** Per-entry result of a bulk price operation (generated). */\nexport type PriceBulkResult = PriceBulkResponseEntry;\n\nconst ANON: AuthContext = { kind: \"anonymous\" };\nconst SERVICE: AuthContext = { kind: \"service\" };\n\nfunction requireContextAuth(auth: AuthContext | undefined): AuthContext {\n const a = auth ?? ANON;\n if (a.kind === \"anonymous\" || a.kind === \"customer\" || a.kind === \"raw\") return a;\n throw new EmporixAuthError(\n \"match-prices-by-context requires an anonymous, customer, or raw AuthContext\",\n );\n}\n\n/**\n * Price matching. The Cart service does not resolve prices — call this\n * explicitly before rendering money and again right before placing an order.\n * The SDK is stateless: it never caches or revalidates prices.\n */\nexport class PriceService {\n static readonly channel = \"price\" as const;\n constructor(private readonly ctx: ClientContext) {}\n\n /**\n * Resolves prices using the session context bound to the bearer token\n * (currency/site/country were set at anonymous-login time). Default auth:\n * anonymous; pass a customer/raw context for personalized pricing.\n */\n async matchByContext(\n input: PriceMatchByContextInput,\n auth?: AuthContext,\n ): Promise<PriceMatch[]> {\n const rows = await this.ctx.http.request<MatchResponse[]>({\n method: \"POST\",\n path: `/price/${this.ctx.tenant}/match-prices-by-context`,\n auth: requireContextAuth(auth),\n body: input,\n idempotent: true, // pure read over POST — safe to replay on 5xx/429\n });\n return rows.map(normalizeMatch);\n }\n\n /**\n * Resolves prices from an explicit context. Default auth: service\n * (requires `price.price_read` / `price.price_manage`).\n */\n async match(input: PriceMatchInput, auth: AuthContext = SERVICE): Promise<PriceMatch[]> {\n const rows = await this.ctx.http.request<MatchResponse[]>({\n method: \"POST\",\n path: `/price/${this.ctx.tenant}/match-prices`,\n auth,\n body: input,\n idempotent: true, // pure read over POST — safe to replay on 5xx/429\n });\n return rows.map(normalizeMatch);\n }\n\n /**\n * Chunked variant of {@link matchByContext} for large `items` arrays. The\n * Emporix backend handles only a limited number of items per request\n * (production limit ~50), so this splits `input.items` into chunks and runs\n * `matchByContext` with bounded concurrency.\n *\n * By default a failing chunk is skipped (its items are absent from the\n * result) and `opts.onChunkError` is called once for it; pass\n * `throwOnAnyChunkError: true` to reject on the first failure instead.\n *\n * **Result order is not guaranteed** — match entries back to your items by\n * `priceId` / `itemId.id`.\n */\n async matchByContextChunked(\n input: PriceMatchByContextInput,\n opts: MatchByContextChunkedOptions = {},\n auth?: AuthContext,\n ): Promise<PriceMatch[]> {\n const chunkSize = opts.chunkSize ?? 50;\n const concurrency = opts.concurrency ?? 4;\n if (chunkSize < 1) throw new Error(\"chunkSize must be >= 1\");\n if (concurrency < 1) throw new Error(\"concurrency must be >= 1\");\n\n const items = input.items ?? [];\n if (items.length === 0) return [];\n\n const chunks: PriceMatchByContextInput[] = [];\n for (let i = 0; i < items.length; i += chunkSize) {\n chunks.push({ ...input, items: items.slice(i, i + chunkSize) });\n }\n\n const results: PriceMatch[][] = new Array(chunks.length);\n let cursor = 0;\n\n const worker = async (): Promise<void> => {\n for (;;) {\n const idx = cursor++;\n const chunk = chunks[idx];\n if (chunk === undefined) return; // past the end\n try {\n results[idx] = await this.matchByContext(chunk, auth);\n } catch (err) {\n if (opts.throwOnAnyChunkError) throw err;\n results[idx] = [];\n opts.onChunkError?.(err, idx);\n }\n }\n };\n\n const workerCount = Math.min(concurrency, chunks.length);\n await Promise.all(Array.from({ length: workerCount }, () => worker()));\n\n return results.flat();\n }\n\n // --- Admin CRUD (flat prices). Default auth: service. ---\n\n /** Creates a flat price. Default auth: service. */\n async create(input: PriceCreateInput, authCtx: AuthContext = SERVICE): Promise<Price> {\n return this.ctx.http.request<Price>({\n method: \"POST\",\n path: `/price/${this.ctx.tenant}/prices`,\n auth: authCtx,\n body: input,\n });\n }\n\n /** Lists flat prices. Default auth: service. */\n async list(\n query?: Record<string, string | number>,\n authCtx: AuthContext = SERVICE,\n ): Promise<Price[]> {\n return this.ctx.http.request<Price[]>({\n method: \"GET\",\n path: `/price/${this.ctx.tenant}/prices`,\n auth: authCtx,\n ...(query ? { query } : {}),\n });\n }\n\n /** Retrieves one flat price by id. Default auth: service. */\n async get(priceId: string, authCtx: AuthContext = SERVICE): Promise<Price> {\n return this.ctx.http.request<Price>({\n method: \"GET\",\n path: `/price/${this.ctx.tenant}/prices/${priceId}`,\n auth: authCtx,\n });\n }\n\n /** Upserts a flat price by id (PUT). Default auth: service. */\n async upsert(priceId: string, input: PriceCreateInput, authCtx: AuthContext = SERVICE): Promise<Price> {\n return this.ctx.http.request<Price>({\n method: \"PUT\",\n path: `/price/${this.ctx.tenant}/prices/${priceId}`,\n auth: authCtx,\n body: input,\n });\n }\n\n /** Deletes a flat price by id. Default auth: service. */\n async delete(priceId: string, authCtx: AuthContext = SERVICE): Promise<void> {\n await this.ctx.http.request<void>({\n method: \"DELETE\",\n path: `/price/${this.ctx.tenant}/prices/${priceId}`,\n auth: authCtx,\n });\n }\n\n /**\n * Searches flat prices: the criteria go in the body, `expand` in the query\n * string. Default auth: service.\n */\n async search(query: Record<string, unknown> & { expand?: string }, authCtx: AuthContext = SERVICE): Promise<Price[]> {\n return this.ctx.http.request<Price[]>({\n method: \"POST\",\n path: `/price/${this.ctx.tenant}/prices/search`,\n auth: authCtx,\n ...splitQuery(query, [\"expand\"]),\n });\n }\n\n /** Creates multiple flat prices in one request. Default auth: service. */\n async bulkCreate(inputs: PriceCreateInput[], authCtx: AuthContext = SERVICE): Promise<PriceBulkResult[]> {\n return this.ctx.http.request<PriceBulkResult[]>({\n method: \"POST\",\n path: `/price/${this.ctx.tenant}/prices/bulk`,\n auth: authCtx,\n body: inputs,\n });\n }\n\n /** Upserts multiple flat prices in one request (PUT). Default auth: service. */\n async bulkUpsert(inputs: PriceCreateInput[], authCtx: AuthContext = SERVICE): Promise<PriceBulkResult[]> {\n return this.ctx.http.request<PriceBulkResult[]>({\n method: \"PUT\",\n path: `/price/${this.ctx.tenant}/prices/bulk`,\n auth: authCtx,\n body: inputs,\n });\n }\n\n /** Price-model admin CRUD (`/priceModels`). Default auth: service. */\n readonly models = {\n list: async (\n query?: Record<string, string | number>,\n authCtx: AuthContext = SERVICE,\n ): Promise<PriceModel[]> =>\n this.ctx.http.request<PriceModel[]>({\n method: \"GET\",\n path: `/price/${this.ctx.tenant}/priceModels`,\n auth: authCtx,\n ...(query ? { query } : {}),\n }),\n create: async (input: PriceModelInput, authCtx: AuthContext = SERVICE): Promise<PriceModel> =>\n this.ctx.http.request<PriceModel>({\n method: \"POST\",\n path: `/price/${this.ctx.tenant}/priceModels`,\n auth: authCtx,\n body: input,\n }),\n get: async (modelId: string, authCtx: AuthContext = SERVICE): Promise<PriceModel> =>\n this.ctx.http.request<PriceModel>({\n method: \"GET\",\n path: `/price/${this.ctx.tenant}/priceModels/${modelId}`,\n auth: authCtx,\n }),\n upsert: async (\n modelId: string,\n input: PriceModelInput,\n authCtx: AuthContext = SERVICE,\n ): Promise<PriceModel> =>\n this.ctx.http.request<PriceModel>({\n method: \"PUT\",\n path: `/price/${this.ctx.tenant}/priceModels/${modelId}`,\n auth: authCtx,\n body: input,\n }),\n delete: async (modelId: string, authCtx: AuthContext = SERVICE): Promise<void> => {\n await this.ctx.http.request<void>({\n method: \"DELETE\",\n path: `/price/${this.ctx.tenant}/priceModels/${modelId}`,\n auth: authCtx,\n });\n },\n };\n\n /** Price-list admin CRUD (`/price-lists`) + nested price management. Default auth: service. */\n readonly lists = {\n list: async (\n query?: Record<string, string | number>,\n authCtx: AuthContext = SERVICE,\n ): Promise<PriceList[]> =>\n this.ctx.http.request<PriceList[]>({\n method: \"GET\",\n path: `/price/${this.ctx.tenant}/price-lists`,\n auth: authCtx,\n ...(query ? { query } : {}),\n }),\n create: async (input: PriceListInput, authCtx: AuthContext = SERVICE): Promise<PriceList> =>\n this.ctx.http.request<PriceList>({\n method: \"POST\",\n path: `/price/${this.ctx.tenant}/price-lists`,\n auth: authCtx,\n body: input,\n }),\n /** `q` in the body; `pageNumber`, `pageSize` and `sort` in the query string. */\n search: async (\n query: Record<string, unknown> & Omit<SearchPaging, \"fields\">,\n authCtx: AuthContext = SERVICE,\n ): Promise<PriceList[]> =>\n this.ctx.http.request<PriceList[]>({\n method: \"POST\",\n path: `/price/${this.ctx.tenant}/price-lists/search`,\n auth: authCtx,\n ...splitQuery(query, [\"pageNumber\", \"pageSize\", \"sort\"]),\n }),\n get: async (listId: string, authCtx: AuthContext = SERVICE): Promise<PriceList> =>\n this.ctx.http.request<PriceList>({\n method: \"GET\",\n path: `/price/${this.ctx.tenant}/price-lists/${listId}`,\n auth: authCtx,\n }),\n upsert: async (\n listId: string,\n input: PriceListUpdateInput,\n authCtx: AuthContext = SERVICE,\n ): Promise<PriceList> =>\n this.ctx.http.request<PriceList>({\n method: \"PUT\",\n path: `/price/${this.ctx.tenant}/price-lists/${listId}`,\n auth: authCtx,\n body: input,\n }),\n delete: async (listId: string, authCtx: AuthContext = SERVICE): Promise<void> => {\n await this.ctx.http.request<void>({\n method: \"DELETE\",\n path: `/price/${this.ctx.tenant}/price-lists/${listId}`,\n auth: authCtx,\n });\n },\n listPrices: async (\n listId: string,\n query?: Record<string, string | number>,\n authCtx: AuthContext = SERVICE,\n ): Promise<PriceListPrice[]> =>\n this.ctx.http.request<PriceListPrice[]>({\n method: \"GET\",\n path: `/price/${this.ctx.tenant}/price-lists/${listId}/prices`,\n auth: authCtx,\n ...(query ? { query } : {}),\n }),\n addPrice: async (\n listId: string,\n input: PriceListPriceInput,\n authCtx: AuthContext = SERVICE,\n ): Promise<PriceListPrice> =>\n this.ctx.http.request<PriceListPrice>({\n method: \"POST\",\n path: `/price/${this.ctx.tenant}/price-lists/${listId}/prices`,\n auth: authCtx,\n body: input,\n }),\n getPrice: async (\n listId: string,\n priceId: string,\n authCtx: AuthContext = SERVICE,\n ): Promise<PriceListPrice> =>\n this.ctx.http.request<PriceListPrice>({\n method: \"GET\",\n path: `/price/${this.ctx.tenant}/price-lists/${listId}/prices/${priceId}`,\n auth: authCtx,\n }),\n upsertPrice: async (\n listId: string,\n priceId: string,\n input: PriceListPriceUpdateInput,\n authCtx: AuthContext = SERVICE,\n ): Promise<PriceListPrice> =>\n this.ctx.http.request<PriceListPrice>({\n method: \"PUT\",\n path: `/price/${this.ctx.tenant}/price-lists/${listId}/prices/${priceId}`,\n auth: authCtx,\n body: input,\n }),\n deletePrice: async (\n listId: string,\n priceId: string,\n authCtx: AuthContext = SERVICE,\n ): Promise<void> => {\n await this.ctx.http.request<void>({\n method: \"DELETE\",\n path: `/price/${this.ctx.tenant}/price-lists/${listId}/prices/${priceId}`,\n auth: authCtx,\n });\n },\n /** `q` in the body; `pageNumber`, `pageSize` and `sort` in the query string. */\n searchPrices: async (\n listId: string,\n query: Record<string, unknown> & Omit<SearchPaging, \"fields\">,\n authCtx: AuthContext = SERVICE,\n ): Promise<PriceListPrice[]> =>\n this.ctx.http.request<PriceListPrice[]>({\n method: \"POST\",\n path: `/price/${this.ctx.tenant}/price-lists/${listId}/prices/search`,\n auth: authCtx,\n ...splitQuery(query, [\"pageNumber\", \"pageSize\", \"sort\"]),\n }),\n bulkCreatePrices: async (\n listId: string,\n inputs: PriceListPriceInput[],\n authCtx: AuthContext = SERVICE,\n ): Promise<PriceBulkResult[]> =>\n this.ctx.http.request<PriceBulkResult[]>({\n method: \"POST\",\n path: `/price/${this.ctx.tenant}/price-lists/${listId}/prices/bulk`,\n auth: authCtx,\n body: inputs,\n }),\n bulkUpsertPrices: async (\n listId: string,\n inputs: PriceListPriceInput[],\n authCtx: AuthContext = SERVICE,\n ): Promise<PriceBulkResult[]> =>\n this.ctx.http.request<PriceBulkResult[]>({\n method: \"PUT\",\n path: `/price/${this.ctx.tenant}/price-lists/${listId}/prices/bulk`,\n auth: authCtx,\n body: inputs,\n }),\n bulkDeletePrices: async (\n listId: string,\n body: Record<string, unknown>,\n authCtx: AuthContext = SERVICE,\n ): Promise<PriceBulkResult[]> =>\n this.ctx.http.request<PriceBulkResult[]>({\n method: \"DELETE\",\n path: `/price/${this.ctx.tenant}/price-lists/${listId}/prices/bulk`,\n auth: authCtx,\n body,\n }),\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/core/errors.ts","../src/core/search.ts","../src/services/price.ts"],"names":[],"mappings":";;;AACA,IAAM,kBAAA,uBAAyB,GAAA,CAAI;AAAA,EACjC,cAAA;AAAA,EAAgB,eAAA;AAAA,EAAiB,OAAA;AAAA,EAAS,eAAA;AAAA,EAAiB,WAAA;AAAA,EAC3D,QAAA;AAAA,EAAU,eAAA;AAAA,EAAiB,eAAA;AAAA,EAAiB;AAC9C,CAAC,CAAA;AAED,SAAS,MAAM,IAAA,EAAwB;AACrC,EAAA,IAAI,MAAM,OAAA,CAAQ,IAAI,GAAG,OAAO,IAAA,CAAK,IAAI,KAAK,CAAA;AAC9C,EAAA,IAAI,IAAA,IAAQ,OAAO,IAAA,KAAS,QAAA,EAAU;AACpC,IAAA,MAAM,MAA+B,EAAC;AACtC,IAAA,KAAA,MAAW,CAAC,CAAA,EAAG,CAAC,KAAK,MAAA,CAAO,OAAA,CAAQ,IAA+B,CAAA,EAAG;AACpE,MAAA,GAAA,CAAI,CAAC,CAAA,GAAI,kBAAA,CAAmB,GAAA,CAAI,CAAA,CAAE,aAAa,CAAA,GAAI,gBAAA,GAAmB,KAAA,CAAM,CAAC,CAAA;AAAA,IAC/E;AACA,IAAA,OAAO,GAAA;AAAA,EACT;AACA,EAAA,OAAO,IAAA;AACT;AAGO,IAAM,YAAA,GAAN,cAA2B,KAAA,CAAM;AAAA,EAC7B,MAAA;AAAA,EACA,IAAA;AAAA,EACT,WAAA,CAAY,OAA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AA,EAAM,OAAA;AAAA,MACN,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,IACH,gBAAA,EAAkB,OAChB,MAAA,EACA,IAAA,EACA,UAAuB,OAAA,KAEvB,IAAA,CAAK,GAAA,CAAI,IAAA,CAAK,OAAA,CAA2B;AAAA,MACvC,MAAA,EAAQ,QAAA;AAAA,MACR,MAAM,CAAA,OAAA,EAAU,IAAA,CAAK,GAAA,CAAI,MAAM,gBAAgB,MAAM,CAAA,YAAA,CAAA;AAAA,MACrD,IAAA,EAAM,OAAA;AAAA,MACN;AAAA,KACD;AAAA,GACL;AACF","file":"price.cjs","sourcesContent":["/** Keys whose values are stripped from any serialised error body. */\nconst REDACTED_BODY_KEYS = new Set([\n \"access_token\", \"refresh_token\", \"token\", \"customertoken\", \"saastoken\",\n \"secret\", \"client_secret\", \"authorization\", \"password\",\n]);\n\nfunction scrub(body: unknown): unknown {\n if (Array.isArray(body)) return body.map(scrub);\n if (body && typeof body === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(body as Record<string, unknown>)) {\n out[k] = REDACTED_BODY_KEYS.has(k.toLowerCase()) ? \"***redacted***\" : scrub(v);\n }\n return out;\n }\n return body;\n}\n\n/** Base class for every error thrown by the SDK. */\nexport class EmporixError extends Error {\n readonly status: number | undefined;\n readonly body: unknown;\n constructor(message: string, status?: number, body?: unknown) {\n super(message);\n this.name = new.target.name;\n this.status = status;\n this.body = body;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n /** Safe serialisation — token-like body fields are redacted. */\n toJSON(): Record<string, unknown> {\n return { name: this.name, message: this.message, status: this.status, body: scrub(this.body) };\n }\n}\n\n/** 401 — authentication failed or token expired. */\nexport class EmporixAuthError extends EmporixError {}\n/** 403 — authenticated but not permitted. */\nexport class EmporixForbiddenError extends EmporixError {}\n/** 404 — resource not found. */\nexport class EmporixNotFoundError extends EmporixError {}\n/** 400/422 — request validation failed. */\nexport class EmporixValidationError extends EmporixError {}\n/** 409 — conflict: a stale `metadata.version`, or an id that already exists. */\nexport class EmporixConflictError extends EmporixError {}\n/** 5xx — server-side failure. */\nexport class EmporixServerError extends EmporixError {}\n/** Request aborted by the configured connect/read timeout. No HTTP status. */\nexport class EmporixTimeoutError extends EmporixError {}\n/** DNS/TLS/connection-level failure before or during the exchange. No HTTP status. */\nexport class EmporixNetworkError extends EmporixError {}\n\n/**\n * 403 with a `missing scope: <name>` hint in the body's `details` array.\n * Subclasses {@link EmporixForbiddenError} so existing 403 catches still work.\n */\nexport class EmporixInsufficientScopeError extends EmporixForbiddenError {\n readonly requiredScope: string | undefined;\n constructor(message: string, status: number, body: unknown, requiredScope?: string) {\n super(message, status, body);\n this.requiredScope = requiredScope;\n }\n}\n\nconst SCOPE_HINT_RE = /missing scope[: ]+([a-z0-9._-]+)/i;\n\nfunction extractRequiredScope(body: unknown): string | undefined {\n if (body && typeof body === \"object\" && \"details\" in body) {\n const details = (body as { details?: unknown }).details;\n if (Array.isArray(details)) {\n for (const d of details) {\n if (typeof d === \"string\") {\n const m = d.match(SCOPE_HINT_RE);\n if (m) return m[1];\n }\n }\n }\n }\n return undefined;\n}\n\n/** Maps an HTTP status to the matching {@link EmporixError} subclass. */\nexport function errorFromResponse(status: number, message: string, body: unknown): EmporixError {\n if (status === 401) return new EmporixAuthError(message, status, body);\n if (status === 403) {\n const scope = extractRequiredScope(body);\n if (scope) return new EmporixInsufficientScopeError(message, status, body, scope);\n return new EmporixForbiddenError(message, status, body);\n }\n if (status === 404) return new EmporixNotFoundError(message, status, body);\n if (status === 400 || status === 422) return new EmporixValidationError(message, status, body);\n if (status === 409) return new EmporixConflictError(message, status, body);\n if (status >= 500) return new EmporixServerError(message, status, body);\n return new EmporixError(message, status, body);\n}\n","/**\n * Paging, sort and field selection for a `POST …/search` endpoint. Emporix reads\n * them from the query string, not the body, so the SDK sends them there. Without\n * them a search returns only the server's first page.\n */\nexport interface SearchPaging {\n pageNumber?: number;\n pageSize?: number;\n /** Properties to sort by, in Emporix sort syntax. */\n sort?: string;\n /** Comma-separated fields to return. */\n fields?: string;\n}\n\n/** The {@link SearchPaging} keys, for {@link splitQuery}. */\nexport const SEARCH_PAGING = [\"pageNumber\", \"pageSize\", \"sort\", \"fields\"] as const;\n\n/**\n * Splits a request input: the named keys go to the query string, everything\n * else stays in the body. A `POST …/search` declares its paging, sort and similar\n * parameters in the query and ignores them in the body — sent there, the search\n * silently returns the first page.\n */\nexport function splitQuery(\n input: object,\n queryKeys: readonly string[],\n): { body: Record<string, unknown>; query: Record<string, string | number | boolean | undefined> } {\n const body: Record<string, unknown> = {};\n const query: Record<string, string | number | boolean | undefined> = {};\n for (const [key, value] of Object.entries(input)) {\n if (queryKeys.includes(key)) query[key] = value as string | number | boolean | undefined;\n else body[key] = value;\n }\n return { body, query };\n}\n","import type { ClientContext } from \"../core/context\";\nimport type { AuthContext } from \"../core/auth\";\nimport { EmporixAuthError } from \"../core/errors\";\nimport { splitQuery, type SearchPaging } from \"../core/search\";\nimport type {\n Match,\n MatchByContext,\n MatchResponse,\n CreatePrice,\n GetPrice,\n PriceModelDefinitionCreation,\n PriceModelRetrieval,\n PriceListCreation,\n PriceListUpdate,\n PriceList as GenPriceList,\n PriceListPriceCreation,\n PriceListPriceUpdate,\n PriceListPrice as GenPriceListPrice,\n PriceBulkResponseEntry,\n} from \"../generated/price\";\n\n/** Session-context match request body (generated). */\nexport type PriceMatchByContextInput = MatchByContext;\n\n/** Explicit-context match request body (generated). */\nexport type PriceMatchInput = Match;\n\n/** Item (product or price) a price was matched for. */\nexport interface PriceMatchItemRef {\n itemType?: string;\n id?: string;\n /** Localized (or plain) product name — present on the live API, absent from the OpenAPI doc. */\n name?: Record<string, string> | string;\n}\n\n/**\n * A resolved price. Superset of the generated match-response schema: the\n * deployed API returns the matched item under `itemId` (with a localized\n * `name`), while the OpenAPI doc/codegen call it `itemRef`.\n */\nexport type PriceMatch = Omit<MatchResponse, \"itemRef\"> & {\n /** Item the price was matched for, as returned by the API. */\n itemId?: PriceMatchItemRef;\n /**\n * @deprecated The OpenAPI doc names this `itemRef`, but the deployed API\n * returns `itemId`. Mirrored from `itemId` for back-compat — prefer `itemId`.\n */\n itemRef?: PriceMatchItemRef;\n};\n\n/**\n * Normalizes a raw match row: the deployed API returns `itemId`, while the\n * codegen type calls it `itemRef`. Expose `itemId` canonically and mirror it\n * to the deprecated `itemRef` so existing consumers keep working.\n */\nfunction normalizeMatch(raw: MatchResponse): PriceMatch {\n const itemId = (raw as MatchResponse & { itemId?: PriceMatchItemRef }).itemId ?? raw.itemRef;\n const base = raw as PriceMatch;\n if (!itemId) return base;\n // Mirror only id/type into the deprecated itemRef (drop name); build without\n // explicit `undefined` for exactOptionalPropertyTypes.\n const itemRef: PriceMatchItemRef = {\n ...(itemId.itemType !== undefined ? { itemType: itemId.itemType } : {}),\n ...(itemId.id !== undefined ? { id: itemId.id } : {}),\n };\n return { ...base, itemId, itemRef };\n}\n\n/** Options for {@link PriceService.matchByContextChunked}. */\nexport interface MatchByContextChunkedOptions {\n /** Items per request. Default 50. Must be >= 1. */\n chunkSize?: number;\n /** Maximum number of requests in flight at once. Default 4. Must be >= 1. */\n concurrency?: number;\n /** Invoked once per failed chunk (default mode only — not when throwing). */\n onChunkError?: (err: unknown, chunkIndex: number) => void;\n /** When true, the first failing chunk rejects the whole call. Default false. */\n throwOnAnyChunkError?: boolean;\n}\n\n/** A resolved/stored price (generated read shape). */\nexport type Price = GetPrice;\n/** Create/upsert body for a flat price (generated). */\nexport type PriceCreateInput = CreatePrice;\n/** A price model (read). */\nexport type PriceModel = PriceModelRetrieval;\n/** Create/upsert body for a price model (generated). */\nexport type PriceModelInput = PriceModelDefinitionCreation;\n/** A price list (read). */\nexport type PriceList = GenPriceList;\n/** Create body for a price list (generated). */\nexport type PriceListInput = PriceListCreation;\n/** Upsert body for a price list (generated). */\nexport type PriceListUpdateInput = PriceListUpdate;\n/** A price inside a price list (read). */\nexport type PriceListPrice = GenPriceListPrice;\n/** Add body for a price-list price (generated). */\nexport type PriceListPriceInput = PriceListPriceCreation;\n/** Upsert body for a price-list price (generated). */\nexport type PriceListPriceUpdateInput = PriceListPriceUpdate;\n/** Per-entry result of a bulk price operation (generated). */\nexport type PriceBulkResult = PriceBulkResponseEntry;\n\nconst ANON: AuthContext = { kind: \"anonymous\" };\nconst SERVICE: AuthContext = { kind: \"service\" };\n\nfunction requireContextAuth(auth: AuthContext | undefined): AuthContext {\n const a = auth ?? ANON;\n if (a.kind === \"anonymous\" || a.kind === \"customer\" || a.kind === \"raw\") return a;\n throw new EmporixAuthError(\n \"match-prices-by-context requires an anonymous, customer, or raw AuthContext\",\n );\n}\n\n/**\n * Price matching. The Cart service does not resolve prices — call this\n * explicitly before rendering money and again right before placing an order.\n * The SDK is stateless: it never caches or revalidates prices.\n */\nexport class PriceService {\n static readonly channel = \"price\" as const;\n constructor(private readonly ctx: ClientContext) {}\n\n /**\n * Resolves prices using the session context bound to the bearer token\n * (currency/site/country were set at anonymous-login time). Default auth:\n * anonymous; pass a customer/raw context for personalized pricing.\n */\n async matchByContext(\n input: PriceMatchByContextInput,\n auth?: AuthContext,\n ): Promise<PriceMatch[]> {\n const rows = await this.ctx.http.request<MatchResponse[]>({\n method: \"POST\",\n path: `/price/${this.ctx.tenant}/match-prices-by-context`,\n auth: requireContextAuth(auth),\n body: input,\n idempotent: true, // pure read over POST — safe to replay on 5xx/429\n });\n return rows.map(normalizeMatch);\n }\n\n /**\n * Resolves prices from an explicit context. Default auth: service\n * (requires `price.price_read` / `price.price_manage`).\n */\n async match(input: PriceMatchInput, auth: AuthContext = SERVICE): Promise<PriceMatch[]> {\n const rows = await this.ctx.http.request<MatchResponse[]>({\n method: \"POST\",\n path: `/price/${this.ctx.tenant}/match-prices`,\n auth,\n body: input,\n idempotent: true, // pure read over POST — safe to replay on 5xx/429\n });\n return rows.map(normalizeMatch);\n }\n\n /**\n * Chunked variant of {@link matchByContext} for large `items` arrays. The\n * Emporix backend handles only a limited number of items per request\n * (production limit ~50), so this splits `input.items` into chunks and runs\n * `matchByContext` with bounded concurrency.\n *\n * By default a failing chunk is skipped (its items are absent from the\n * result) and `opts.onChunkError` is called once for it; pass\n * `throwOnAnyChunkError: true` to reject on the first failure instead.\n *\n * **Result order is not guaranteed** — match entries back to your items by\n * `priceId` / `itemId.id`.\n */\n async matchByContextChunked(\n input: PriceMatchByContextInput,\n opts: MatchByContextChunkedOptions = {},\n auth?: AuthContext,\n ): Promise<PriceMatch[]> {\n const chunkSize = opts.chunkSize ?? 50;\n const concurrency = opts.concurrency ?? 4;\n if (chunkSize < 1) throw new Error(\"chunkSize must be >= 1\");\n if (concurrency < 1) throw new Error(\"concurrency must be >= 1\");\n\n const items = input.items ?? [];\n if (items.length === 0) return [];\n\n const chunks: PriceMatchByContextInput[] = [];\n for (let i = 0; i < items.length; i += chunkSize) {\n chunks.push({ ...input, items: items.slice(i, i + chunkSize) });\n }\n\n const results: PriceMatch[][] = new Array(chunks.length);\n let cursor = 0;\n\n const worker = async (): Promise<void> => {\n for (;;) {\n const idx = cursor++;\n const chunk = chunks[idx];\n if (chunk === undefined) return; // past the end\n try {\n results[idx] = await this.matchByContext(chunk, auth);\n } catch (err) {\n if (opts.throwOnAnyChunkError) throw err;\n results[idx] = [];\n opts.onChunkError?.(err, idx);\n }\n }\n };\n\n const workerCount = Math.min(concurrency, chunks.length);\n await Promise.all(Array.from({ length: workerCount }, () => worker()));\n\n return results.flat();\n }\n\n // --- Admin CRUD (flat prices). Default auth: service. ---\n\n /** Creates a flat price. Default auth: service. */\n async create(input: PriceCreateInput, authCtx: AuthContext = SERVICE): Promise<Price> {\n return this.ctx.http.request<Price>({\n method: \"POST\",\n path: `/price/${this.ctx.tenant}/prices`,\n auth: authCtx,\n body: input,\n });\n }\n\n /** Lists flat prices. Default auth: service. */\n async list(\n query?: Record<string, string | number>,\n authCtx: AuthContext = SERVICE,\n ): Promise<Price[]> {\n return this.ctx.http.request<Price[]>({\n method: \"GET\",\n path: `/price/${this.ctx.tenant}/prices`,\n auth: authCtx,\n ...(query ? { query } : {}),\n });\n }\n\n /** Retrieves one flat price by id. Default auth: service. */\n async get(priceId: string, authCtx: AuthContext = SERVICE): Promise<Price> {\n return this.ctx.http.request<Price>({\n method: \"GET\",\n path: `/price/${this.ctx.tenant}/prices/${priceId}`,\n auth: authCtx,\n });\n }\n\n /** Upserts a flat price by id (PUT). Default auth: service. */\n async upsert(priceId: string, input: PriceCreateInput, authCtx: AuthContext = SERVICE): Promise<Price> {\n return this.ctx.http.request<Price>({\n method: \"PUT\",\n path: `/price/${this.ctx.tenant}/prices/${priceId}`,\n auth: authCtx,\n body: input,\n });\n }\n\n /** Deletes a flat price by id. Default auth: service. */\n async delete(priceId: string, authCtx: AuthContext = SERVICE): Promise<void> {\n await this.ctx.http.request<void>({\n method: \"DELETE\",\n path: `/price/${this.ctx.tenant}/prices/${priceId}`,\n auth: authCtx,\n });\n }\n\n /**\n * Searches flat prices: the criteria go in the body, `expand` in the query\n * string. Default auth: service.\n */\n async search(query: Record<string, unknown> & { expand?: string }, authCtx: AuthContext = SERVICE): Promise<Price[]> {\n return this.ctx.http.request<Price[]>({\n method: \"POST\",\n path: `/price/${this.ctx.tenant}/prices/search`,\n auth: authCtx,\n ...splitQuery(query, [\"expand\"]),\n });\n }\n\n /** Creates multiple flat prices in one request. Default auth: service. */\n async bulkCreate(inputs: PriceCreateInput[], authCtx: AuthContext = SERVICE): Promise<PriceBulkResult[]> {\n return this.ctx.http.request<PriceBulkResult[]>({\n method: \"POST\",\n path: `/price/${this.ctx.tenant}/prices/bulk`,\n auth: authCtx,\n body: inputs,\n });\n }\n\n /** Upserts multiple flat prices in one request (PUT). Default auth: service. */\n async bulkUpsert(inputs: PriceCreateInput[], authCtx: AuthContext = SERVICE): Promise<PriceBulkResult[]> {\n return this.ctx.http.request<PriceBulkResult[]>({\n method: \"PUT\",\n path: `/price/${this.ctx.tenant}/prices/bulk`,\n auth: authCtx,\n body: inputs,\n });\n }\n\n /** Price-model admin CRUD (`/priceModels`). Default auth: service. */\n readonly models = {\n list: async (\n query?: Record<string, string | number>,\n authCtx: AuthContext = SERVICE,\n ): Promise<PriceModel[]> =>\n this.ctx.http.request<PriceModel[]>({\n method: \"GET\",\n path: `/price/${this.ctx.tenant}/priceModels`,\n auth: authCtx,\n ...(query ? { query } : {}),\n }),\n create: async (input: PriceModelInput, authCtx: AuthContext = SERVICE): Promise<PriceModel> =>\n this.ctx.http.request<PriceModel>({\n method: \"POST\",\n path: `/price/${this.ctx.tenant}/priceModels`,\n auth: authCtx,\n body: input,\n }),\n get: async (modelId: string, authCtx: AuthContext = SERVICE): Promise<PriceModel> =>\n this.ctx.http.request<PriceModel>({\n method: \"GET\",\n path: `/price/${this.ctx.tenant}/priceModels/${modelId}`,\n auth: authCtx,\n }),\n upsert: async (\n modelId: string,\n input: PriceModelInput,\n authCtx: AuthContext = SERVICE,\n ): Promise<PriceModel> =>\n this.ctx.http.request<PriceModel>({\n method: \"PUT\",\n path: `/price/${this.ctx.tenant}/priceModels/${modelId}`,\n auth: authCtx,\n body: input,\n }),\n delete: async (modelId: string, authCtx: AuthContext = SERVICE): Promise<void> => {\n await this.ctx.http.request<void>({\n method: \"DELETE\",\n path: `/price/${this.ctx.tenant}/priceModels/${modelId}`,\n auth: authCtx,\n });\n },\n };\n\n /** Price-list admin CRUD (`/price-lists`) + nested price management. Default auth: service. */\n readonly lists = {\n list: async (\n query?: Record<string, string | number>,\n authCtx: AuthContext = SERVICE,\n ): Promise<PriceList[]> =>\n this.ctx.http.request<PriceList[]>({\n method: \"GET\",\n path: `/price/${this.ctx.tenant}/price-lists`,\n auth: authCtx,\n ...(query ? { query } : {}),\n }),\n create: async (input: PriceListInput, authCtx: AuthContext = SERVICE): Promise<PriceList> =>\n this.ctx.http.request<PriceList>({\n method: \"POST\",\n path: `/price/${this.ctx.tenant}/price-lists`,\n auth: authCtx,\n body: input,\n }),\n /** `q` in the body; `pageNumber`, `pageSize` and `sort` in the query string. */\n search: async (\n query: Record<string, unknown> & Omit<SearchPaging, \"fields\">,\n authCtx: AuthContext = SERVICE,\n ): Promise<PriceList[]> =>\n this.ctx.http.request<PriceList[]>({\n method: \"POST\",\n path: `/price/${this.ctx.tenant}/price-lists/search`,\n auth: authCtx,\n ...splitQuery(query, [\"pageNumber\", \"pageSize\", \"sort\"]),\n }),\n get: async (listId: string, authCtx: AuthContext = SERVICE): Promise<PriceList> =>\n this.ctx.http.request<PriceList>({\n method: \"GET\",\n path: `/price/${this.ctx.tenant}/price-lists/${listId}`,\n auth: authCtx,\n }),\n upsert: async (\n listId: string,\n input: PriceListUpdateInput,\n authCtx: AuthContext = SERVICE,\n ): Promise<PriceList> =>\n this.ctx.http.request<PriceList>({\n method: \"PUT\",\n path: `/price/${this.ctx.tenant}/price-lists/${listId}`,\n auth: authCtx,\n body: input,\n }),\n delete: async (listId: string, authCtx: AuthContext = SERVICE): Promise<void> => {\n await this.ctx.http.request<void>({\n method: \"DELETE\",\n path: `/price/${this.ctx.tenant}/price-lists/${listId}`,\n auth: authCtx,\n });\n },\n listPrices: async (\n listId: string,\n query?: Record<string, string | number>,\n authCtx: AuthContext = SERVICE,\n ): Promise<PriceListPrice[]> =>\n this.ctx.http.request<PriceListPrice[]>({\n method: \"GET\",\n path: `/price/${this.ctx.tenant}/price-lists/${listId}/prices`,\n auth: authCtx,\n ...(query ? { query } : {}),\n }),\n addPrice: async (\n listId: string,\n input: PriceListPriceInput,\n authCtx: AuthContext = SERVICE,\n ): Promise<PriceListPrice> =>\n this.ctx.http.request<PriceListPrice>({\n method: \"POST\",\n path: `/price/${this.ctx.tenant}/price-lists/${listId}/prices`,\n auth: authCtx,\n body: input,\n }),\n getPrice: async (\n listId: string,\n priceId: string,\n authCtx: AuthContext = SERVICE,\n ): Promise<PriceListPrice> =>\n this.ctx.http.request<PriceListPrice>({\n method: \"GET\",\n path: `/price/${this.ctx.tenant}/price-lists/${listId}/prices/${priceId}`,\n auth: authCtx,\n }),\n upsertPrice: async (\n listId: string,\n priceId: string,\n input: PriceListPriceUpdateInput,\n authCtx: AuthContext = SERVICE,\n ): Promise<PriceListPrice> =>\n this.ctx.http.request<PriceListPrice>({\n method: \"PUT\",\n path: `/price/${this.ctx.tenant}/price-lists/${listId}/prices/${priceId}`,\n auth: authCtx,\n body: input,\n }),\n deletePrice: async (\n listId: string,\n priceId: string,\n authCtx: AuthContext = SERVICE,\n ): Promise<void> => {\n await this.ctx.http.request<void>({\n method: \"DELETE\",\n path: `/price/${this.ctx.tenant}/price-lists/${listId}/prices/${priceId}`,\n auth: authCtx,\n });\n },\n /** `q` in the body; `pageNumber`, `pageSize` and `sort` in the query string. */\n searchPrices: async (\n listId: string,\n query: Record<string, unknown> & Omit<SearchPaging, \"fields\">,\n authCtx: AuthContext = SERVICE,\n ): Promise<PriceListPrice[]> =>\n this.ctx.http.request<PriceListPrice[]>({\n method: \"POST\",\n path: `/price/${this.ctx.tenant}/price-lists/${listId}/prices/search`,\n auth: authCtx,\n ...splitQuery(query, [\"pageNumber\", \"pageSize\", \"sort\"]),\n }),\n bulkCreatePrices: async (\n listId: string,\n inputs: PriceListPriceInput[],\n authCtx: AuthContext = SERVICE,\n ): Promise<PriceBulkResult[]> =>\n this.ctx.http.request<PriceBulkResult[]>({\n method: \"POST\",\n path: `/price/${this.ctx.tenant}/price-lists/${listId}/prices/bulk`,\n auth: authCtx,\n body: inputs,\n }),\n bulkUpsertPrices: async (\n listId: string,\n inputs: PriceListPriceInput[],\n authCtx: AuthContext = SERVICE,\n ): Promise<PriceBulkResult[]> =>\n this.ctx.http.request<PriceBulkResult[]>({\n method: \"PUT\",\n path: `/price/${this.ctx.tenant}/price-lists/${listId}/prices/bulk`,\n auth: authCtx,\n body: inputs,\n }),\n bulkDeletePrices: async (\n listId: string,\n body: Record<string, unknown>,\n authCtx: AuthContext = SERVICE,\n ): Promise<PriceBulkResult[]> =>\n this.ctx.http.request<PriceBulkResult[]>({\n method: \"DELETE\",\n path: `/price/${this.ctx.tenant}/price-lists/${listId}/prices/bulk`,\n auth: authCtx,\n body,\n }),\n };\n}\n"]}
package/dist/price.js CHANGED
@@ -1,5 +1,5 @@
1
- export { PriceService } from './chunk-K4KXT6NX.js';
1
+ export { PriceService } from './chunk-ENMMDGUB.js';
2
2
  import './chunk-ZWJUDXTK.js';
3
- import './chunk-UWGGF4MC.js';
3
+ import './chunk-4Q76UV4J.js';
4
4
  //# sourceMappingURL=price.js.map
5
5
  //# sourceMappingURL=price.js.map
package/dist/product.cjs CHANGED
@@ -54,8 +54,8 @@ var ProductService = class {
54
54
  }
55
55
  ctx;
56
56
  static channel = "product";
57
- /** Fetches one product by id. */
58
- async get(productId, _opts, auth = ANON) {
57
+ async get(productId, authOrOpts, legacyAuth) {
58
+ const auth = legacyAuth ?? (authOrOpts !== void 0 && "kind" in authOrOpts ? authOrOpts : ANON);
59
59
  return this.ctx.http.request({
60
60
  method: "GET",
61
61
  path: `/product/${this.ctx.tenant}/products/${productId}`,
@@ -222,20 +222,31 @@ var ProductService = class {
222
222
  return pages.flat();
223
223
  }
224
224
  /**
225
- * Streams the VARIANT children of a PARENT_VARIANT product, page by page,
226
- * via the search query `productType:VARIANT parentVariantId:<id>`. Default
227
- * pageSize 200. The query syntax (space-separated fields = implicit AND) is
228
- * encapsulated here so consumers don't build it themselves.
225
+ * Streams the variants below a product, page by page, in two searches: the
226
+ * VARIANT children of a PARENT_VARIANT (`productType:VARIANT
227
+ * parentVariantId:<id>`), then the DYNAMIC_VARIANT descendants of every level
228
+ * (`parentVariantPath:<id>` — every ancestor is in the path). Only one of the
229
+ * two finds anything for a given product. Default pageSize 200. The query
230
+ * syntax (space-separated fields = implicit AND) is encapsulated here so
231
+ * consumers don't build it themselves.
229
232
  */
230
- listVariantChildrenAll(parentVariantId, params = {}, auth = ANON) {
233
+ async *listVariantChildrenAll(parentVariantId, params = {}, auth = ANON) {
231
234
  const pageSize = params.pageSize ?? 200;
232
- const q = `productType:VARIANT parentVariantId:${parentVariantId}`;
233
- return iterateAll((pageNumber) => this.search(q, { pageNumber, pageSize }, auth));
235
+ for (const q of [
236
+ `productType:VARIANT parentVariantId:${parentVariantId}`,
237
+ `parentVariantPath:${parentVariantId}`
238
+ ]) {
239
+ yield* iterateAll(
240
+ (pageNumber) => this.search(q, { pageNumber, pageSize }, auth)
241
+ );
242
+ }
234
243
  }
235
244
  /**
236
- * Resolves ALL VARIANT children of a PARENT_VARIANT product into a flat
237
- * array (loads every page). Default pageSize 200. Returns `[]` when there are
238
- * no children — never throws.
245
+ * Resolves every variant below a product into a flat array (loads every
246
+ * page): the VARIANT children of a PARENT_VARIANT, or the DYNAMIC_VARIANT
247
+ * descendants of all levels — tell them apart by `parentVariantId` (the
248
+ * direct parent) or pick the purchasable ones by `sellable`. Default pageSize
249
+ * 200. Returns `[]` when there are none — never throws.
239
250
  */
240
251
  async listVariantChildren(parentVariantId, params = {}, auth = ANON) {
241
252
  const out = [];