UNPKG

@godaddy/react

Version:

The `createCheckoutSession` function creates a new checkout session with GoDaddy's commerce API.

738 lines (726 loc) • 22.5 kB
import { D as convertCamelCaseToKebabCase, v as getEnabledStoreUiExtensions } from "./godaddy-BJi9zezb.js"; import React, { Component, useEffect, useInsertionEffect, useMemo, useRef } from "react"; import { enUs } from "@godaddy/localizations"; import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query"; import { Fragment, jsx, jsxs } from "react/jsx-runtime"; //#region src/hooks/use-theme.tsx const themes = { base: { value: "theme-base", label: "Base" }, purple: { value: "theme-purple", label: "Purple" }, orange: { value: "theme-orange", label: "Orange" } }; /** * Hook that applies theme from override or context * @param {Theme} [overrideTheme] - Optional theme that overrides context theme */ function useTheme(overrideTheme) { const { appearance } = useGoDaddyContext(); const theme = overrideTheme ?? appearance?.theme; useInsertionEffect(() => { document.documentElement.classList.remove(...Object.values(themes).map((t) => t.value)); if (theme && theme !== "base") document.documentElement.classList.add(themes?.[theme]?.value); }, [theme]); } //#endregion //#region src/hooks/use-variables.tsx /** * Checks if a variables object is already in kebab-case format by checking for hyphens */ function isKebabCase(obj) { return Object.keys(obj).some((key) => key.includes("-")); } /** * Sanitize CSS values to prevent XSS attacks */ function sanitizeCSSValue(value) { return value.replace(/[<>{}]/g, "").replace(/javascript:/gi, "").replace(/data:/gi, "").replace(/vbscript:/gi, "").replace(/expression\(/gi, ""); } /** * Processes and merges CSS variables */ function processVariables(contextVariables, overrideVariables) { let contextCssVars; if (contextVariables) if ("checkout" in contextVariables) contextCssVars = contextVariables.checkout; else contextCssVars = contextVariables; let overrideCssVars; if (overrideVariables) { let rawVars; if ("checkout" in overrideVariables) rawVars = overrideVariables.checkout; else rawVars = overrideVariables; if (isKebabCase(rawVars)) overrideCssVars = rawVars; else overrideCssVars = convertCamelCaseToKebabCase(rawVars); } return { ...contextCssVars, ...overrideCssVars }; } /** * Hook that applies CSS variables from the GoDaddy context to the document * Priority: overrideVariables > context.appearance * @param {GoDaddyVariables} [overrideVariables] - Optional variables that override context variables (can be camelCase or kebab-case) */ function useVariables(overrideVariables) { const { appearance } = useGoDaddyContext(); const contextVariables = appearance?.variables; const mergedVars = useMemo(() => processVariables(contextVariables, overrideVariables), [contextVariables, overrideVariables]); useInsertionEffect(() => { if (Object.keys(mergedVars).length === 0) return; const rootStyle = document.documentElement.style; for (const [key, value] of Object.entries(mergedVars)) if (value != null) { const sanitizedValue = sanitizeCSSValue(String(value)); rootStyle.setProperty(`--gd-${key}`, sanitizedValue); } return () => { for (const key of Object.keys(mergedVars)) rootStyle.removeProperty(`--gd-${key}`); }; }, [mergedVars]); } //#endregion //#region src/godaddy-provider.tsx function createQueryClient() { return new QueryClient({ defaultOptions: { queries: { retry: false, refetchOnWindowFocus: false } } }); } const queryClient = createQueryClient(); const godaddyContext = React.createContext({ t: enUs, debug: false }); const useGoDaddyContext = () => React.useContext(godaddyContext); function GoDaddyProvider({ localization = enUs, appearance, debug, apiHost, clientId, storeId, channelId, locale = "en-US", queryClient: providedQueryClient, Link, children }) { const [clientInstance] = React.useState(() => providedQueryClient ?? createQueryClient()); const processedAppearance = React.useMemo(() => { if (!appearance?.variables) return appearance; const processedVariables = "checkout" in appearance.variables ? { checkout: appearance.variables.checkout } : appearance.variables; return { ...appearance, variables: processedVariables }; }, [appearance]); const inlineStyles = React.useMemo(() => { if (!processedAppearance?.variables) return ""; const rawVars = "checkout" in processedAppearance.variables ? processedAppearance.variables.checkout : processedAppearance.variables; const vars = !Object.keys(rawVars).some((key) => key.includes("-")) ? convertCamelCaseToKebabCase(rawVars) : rawVars; const sanitizeCSSValue$1 = (value) => { return value.replace(/[<>{}]/g, "").replace(/javascript:/gi, "").replace(/data:/gi, "").replace(/vbscript:/gi, "").replace(/expression\(/gi, ""); }; const cssVars = Object.entries(vars).filter(([_, value]) => value != null).map(([key, value]) => { return `--gd-${key}: ${sanitizeCSSValue$1(String(value))};`; }).join(" "); return cssVars ? `:root { ${cssVars} }` : ""; }, [processedAppearance]); const themeScript = React.useMemo(() => { const theme = processedAppearance?.theme; if (!theme || theme === "base") return null; const themeValues = Object.values(themes).map((t) => t.value); const themeClass = themes[theme]?.value; if (!themeClass) return null; return ` (function() { var themeClasses = ${JSON.stringify(themeValues)}; var root = document.documentElement; themeClasses.forEach(function(t) { root.classList.remove(t); }); root.classList.add(${JSON.stringify(themeClass)}); })(); `; }, [processedAppearance?.theme]); useVariables(processedAppearance?.variables); useTheme(processedAppearance?.theme); return /* @__PURE__ */ jsxs(godaddyContext.Provider, { value: { t: localization, appearance: processedAppearance, debug, apiHost, clientId, storeId, channelId, locale, Link }, children: [ inlineStyles && /* @__PURE__ */ jsx("style", { dangerouslySetInnerHTML: { __html: inlineStyles }, "data-godaddy-vars": true }), themeScript && /* @__PURE__ */ jsx("script", { dangerouslySetInnerHTML: { __html: themeScript }, "data-godaddy-theme": true }), /* @__PURE__ */ jsx(QueryClientProvider, { client: clientInstance, children }) ] }); } //#endregion //#region src/ui-extensions/hooks/use-enabled-store-ui-extensions.ts function useEnabledStoreUiExtensions({ target, storeId, enabled = true }) { const { apiHost, storeId: contextStoreId } = useGoDaddyContext(); const resolvedStoreId = storeId || contextStoreId || ""; return useQuery({ queryKey: [ "ui-extension-target", apiHost, target, resolvedStoreId ], queryFn: () => getEnabledStoreUiExtensions({ storeId: resolvedStoreId, target }, apiHost), enabled: Boolean(enabled && target && resolvedStoreId) }); } //#endregion //#region src/ui-extensions/runtime/context.ts function buildUiExtensionContext({ id, storeId, orderId, locale, currencyCode, theme }) { return { target: id, ...storeId ? { storeId } : {}, ...orderId ? { orderId } : {}, ...locale ? { locale } : {}, ...currencyCode ? { currencyCode } : {}, ...theme ? { theme } : {} }; } //#endregion //#region src/ui-extensions/runtime/script-url.ts function encodePathSegment(value) { return encodeURIComponent(value); } function getUiExtensionCdnBaseUrl(apiHost) { return `https://${(apiHost || "api.godaddy.com").trim().replace(/^https?:\/\//i, "").replace(/\/$/, "").replace(/^api\./i, "cdn.ui-extensions.commerce.")}`; } function getUiExtensionScriptUrl(extension, apiHost) { const { applicationId, id, releaseId, target } = extension; if (!target || !applicationId || !releaseId) return { success: false, error: { code: "missing_required_field", message: "UI extension requires target, applicationId, and releaseId to load.", runtimeType: "dom-bundle", extensionId: id, applicationId, releaseId, target } }; try { return { success: true, url: [ getUiExtensionCdnBaseUrl(apiHost), "apps", "targets", encodePathSegment(target), encodePathSegment(applicationId), encodePathSegment(releaseId), "index.js" ].join("/") }; } catch (cause) { return { success: false, error: { code: "invalid_script_url", message: "Failed to build UI extension script URL.", runtimeType: "dom-bundle", extensionId: id, applicationId, releaseId, target, cause } }; } } //#endregion //#region src/ui-extensions/runtime/dom-bundle-runtime.ts const DEFAULT_TIMEOUT_MS = 5e3; let scriptLoadQueue = Promise.resolve(); function enqueueScriptLoad(task) { const result = scriptLoadQueue.then(task, task); scriptLoadQueue = result.then(() => void 0, () => void 0); return result; } function withTimeout(promise, timeoutMs, getError) { return new Promise((resolve, reject) => { const timeout = window.setTimeout(() => reject(getError()), timeoutMs); promise.then((value) => { window.clearTimeout(timeout); resolve(value); }, (error) => { window.clearTimeout(timeout); reject(error); }); }); } function createRuntimeError(extension, error) { return { runtimeType: "dom-bundle", extensionId: extension.id, applicationId: extension.applicationId, releaseId: extension.releaseId, target: extension.target, ...error }; } function getExtensionMetadata(extension) { return { id: extension.id, applicationId: extension.applicationId || "", releaseId: extension.releaseId || "", target: extension.target || "" }; } function isDomExtensionContract(value) { return Boolean(value && typeof value === "object" && typeof value.mount === "function"); } function loadRegisteredContract(scriptUrl, extension, timeoutMs) { return enqueueScriptLoad(() => new Promise((resolve, reject) => { if (typeof window === "undefined" || typeof document === "undefined") { reject(createRuntimeError(extension, { code: "load_failed", message: "UI extension scripts can only be loaded in a browser." })); return; } const previousRegistry = window.GoDaddyUiExtensions; let registeredContract; let isSettled = false; const script = document.createElement("script"); const cleanup = () => { window.clearTimeout(timeout); script.remove(); if (previousRegistry) window.GoDaddyUiExtensions = previousRegistry; else delete window.GoDaddyUiExtensions; }; const settle = (callback) => { if (isSettled) return; isSettled = true; cleanup(); callback(); }; const timeout = window.setTimeout(() => { settle(() => reject(createRuntimeError(extension, { code: "registration_timeout", message: "UI extension did not register before the timeout." }))); }, timeoutMs); window.GoDaddyUiExtensions = { register(contract) { registeredContract = contract; } }; script.async = true; script.src = scriptUrl; script.crossOrigin = "anonymous"; script.onload = () => { settle(() => { if (!isDomExtensionContract(registeredContract)) { reject(createRuntimeError(extension, { code: "invalid_module_contract", message: "UI extension bundle must register a contract with a mount function." })); return; } resolve(registeredContract); }); }; script.onerror = () => { settle(() => reject(createRuntimeError(extension, { code: "load_failed", message: "Failed to load UI extension script." }))); }; document.head.appendChild(script); })); } var DomBundleUiExtensionRuntime = class { contract; extension; hasMounted = false; isDisposed = false; isMounting = false; metadata; pendingUpdate; timeoutMs; constructor(options = {}) { this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS; } async mount(input) { const { apiHost, container, context, extension, initialProps, onError } = input; this.clearRuntimeState(); this.isDisposed = false; this.extension = extension; if (!container) { onError(createRuntimeError(extension, { code: "mount_failed", message: "UI extension DOM bundle runtime requires a container." })); return; } this.metadata = getExtensionMetadata(extension); const scriptUrlResult = getUiExtensionScriptUrl(extension, apiHost); if (!scriptUrlResult.success) { onError(scriptUrlResult.error); return; } try { const contract = await loadRegisteredContract(scriptUrlResult.url, extension, this.timeoutMs); if (this.isDisposed) { this.clearRuntimeState(); return; } this.contract = contract; this.isMounting = true; await withTimeout(Promise.resolve(contract.mount({ container, context, initialProps, extension: this.metadata })), this.timeoutMs, () => createRuntimeError(extension, { code: "mount_timeout", message: "UI extension mount timed out." })); this.isMounting = false; this.hasMounted = true; if (this.isDisposed) { await this.unmount(); return; } const pendingUpdate = this.pendingUpdate; if (pendingUpdate && (pendingUpdate.context !== context || pendingUpdate.initialProps !== initialProps)) await this.update(pendingUpdate); } catch (cause) { this.isMounting = false; await this.cleanupFailedMount(); if (this.isDisposed) { this.clearRuntimeState(); return; } onError(isRuntimeError(cause) ? cause : createRuntimeError(extension, { code: "mount_failed", message: "Failed to mount UI extension.", cause })); this.clearRuntimeState(); } } async update(input) { this.pendingUpdate = input; if (this.isDisposed || !this.contract?.update || !this.extension || !this.metadata || !this.hasMounted) return; try { await withTimeout(Promise.resolve(this.contract.update({ context: input.context, initialProps: input.initialProps, extension: this.metadata })), this.timeoutMs, () => createRuntimeError(this.extension, { code: "update_failed", message: "UI extension update timed out." })); } catch (cause) { throw createRuntimeError(this.extension, { code: "update_failed", message: "Failed to update UI extension.", cause }); } } async unmount() { this.isDisposed = true; if (this.isMounting && !this.hasMounted) return; if (!this.hasMounted) { this.clearRuntimeState(); return; } if (!this.contract?.unmount || !this.extension) { this.clearRuntimeState(); return; } try { await withTimeout(Promise.resolve(this.contract.unmount()), this.timeoutMs, () => createRuntimeError(this.extension, { code: "unmount_failed", message: "UI extension unmount timed out." })); } catch (cause) { throw createRuntimeError(this.extension, { code: "unmount_failed", message: "Failed to unmount UI extension.", cause }); } finally { this.clearRuntimeState(); } } async cleanupFailedMount() { if (!this.contract?.unmount || !this.extension) return; try { await withTimeout(Promise.resolve(this.contract.unmount()), this.timeoutMs, () => createRuntimeError(this.extension, { code: "unmount_failed", message: "UI extension cleanup timed out after mount failure." })); } catch {} } clearRuntimeState() { this.contract = void 0; this.extension = void 0; this.hasMounted = false; this.isMounting = false; this.metadata = void 0; this.pendingUpdate = void 0; } }; function isRuntimeError(value) { return Boolean(value && typeof value === "object" && "code" in value && "runtimeType" in value && "extensionId" in value); } //#endregion //#region src/ui-extensions/runtime/runtime-host.tsx function createUiExtensionRuntime(runtimeType) { switch (runtimeType) { case "dom-bundle": default: return new DomBundleUiExtensionRuntime(); } } function getExtensionKey(extension) { return [ extension.id, extension.applicationId || "", extension.releaseId || "", extension.target || "" ].join(":"); } function createHostRuntimeError(extension, error, code, message) { return error && typeof error === "object" && "code" in error ? error : { code, message, runtimeType: "dom-bundle", extensionId: extension.id, applicationId: extension.applicationId, releaseId: extension.releaseId, target: extension.target, cause: error }; } var UiExtensionErrorBoundary = class extends Component { state = { hasError: false }; static getDerivedStateFromError() { return { hasError: true }; } componentDidCatch(error) { const { extension, onError } = this.props; onError?.(createHostRuntimeError(extension, error, "mount_failed", "UI extension runtime host failed to render.")); } render() { if (this.state.hasError) return this.props.fallback ?? null; return this.props.children; } }; function UiExtensionRuntimeHostContainer({ apiHost, context, extension, initialProps, runtimeType = "dom-bundle", onError }) { const containerRef = useRef(null); const runtimeRef = useRef(void 0); const onErrorRef = useRef(onError); const extensionKey = useMemo(() => getExtensionKey(extension), [extension]); useEffect(() => { onErrorRef.current = onError; }, [onError]); useEffect(() => { const runtime = createUiExtensionRuntime(runtimeType); runtimeRef.current = runtime; runtime.mount({ extension, apiHost, context, initialProps, container: containerRef.current || void 0, onError: (error) => onErrorRef.current?.(error) }); return () => { runtimeRef.current = void 0; Promise.resolve(runtime.unmount()).catch((error) => { onErrorRef.current?.(createHostRuntimeError(extension, error, "unmount_failed", "Failed to unmount UI extension.")); }); }; }, [ apiHost, extensionKey, runtimeType ]); useEffect(() => { Promise.resolve(runtimeRef.current?.update({ context, initialProps })).catch((error) => { onErrorRef.current?.(createHostRuntimeError(extension, error, "update_failed", "Failed to update UI extension.")); }); }, [ context, extension, initialProps ]); return /* @__PURE__ */ jsx("div", { "data-gd-ui-extension-container": "true", "data-gd-ui-extension-id": extension.id, "data-gd-ui-extension-target": extension.target || context.target, ref: containerRef }); } function UiExtensionRuntimeHost(props) { return /* @__PURE__ */ jsx(UiExtensionErrorBoundary, { extension: props.extension, onError: props.onError, children: /* @__PURE__ */ jsx(UiExtensionRuntimeHostContainer, { ...props }) }); } //#endregion //#region src/ui-extensions/target.tsx function getInitialPropKeys(initialProps) { return initialProps ? Object.keys(initialProps).sort() : []; } function getDiscoveryErrorMessage(error) { return error instanceof Error ? error.message : String(error); } function getDiscoveryErrorSignature(id, error) { return JSON.stringify({ target: id, error: getDiscoveryErrorMessage(error) }); } function getDebugLogSignature({ context, id, initialPropKeys, targetExtensions }) { return JSON.stringify({ target: id, extensionKeys: targetExtensions.map((extension) => [ extension.id, extension.applicationId, extension.releaseId, extension.target ]), context, initialPropKeys }); } function Target({ id, apps, storeId, orderId, runtime = "dom-bundle", initialProps, locale, currencyCode, theme, onExtensionError }) { const { apiHost, debug } = useGoDaddyContext(); const lastDebugLogSignatureRef = useRef(void 0); const lastDiscoveryErrorSignatureRef = useRef(void 0); const { data, error, isLoading } = useEnabledStoreUiExtensions({ target: id, storeId, enabled: !apps }); const targetExtensions = useMemo(() => apps?.flatMap((app) => app.uiExtensions.filter((extension) => extension.target === id)), [apps, id]) || data || []; const context = useMemo(() => buildUiExtensionContext({ id, storeId, orderId, locale, currencyCode, theme }), [ id, storeId, orderId, locale, currencyCode, theme ]); useEffect(() => { if (!error) return; const signature = getDiscoveryErrorSignature(id, error); if (lastDiscoveryErrorSignatureRef.current === signature) return; lastDiscoveryErrorSignatureRef.current = signature; onExtensionError?.({ code: "load_failed", message: `Failed to discover UI extensions: ${getDiscoveryErrorMessage(error)}`, runtimeType: "dom-bundle", extensionId: id, target: id, cause: error }); }, [ error, id, onExtensionError ]); useEffect(() => { if (!debug || !targetExtensions.length) return; const initialPropKeys = getInitialPropKeys(initialProps); const signature = getDebugLogSignature({ context, id, initialPropKeys, targetExtensions }); if (lastDebugLogSignatureRef.current === signature) return; lastDebugLogSignatureRef.current = signature; console.info("[GoDaddy UI Extensions]", { target: id, uiExtensions: targetExtensions, context, initialPropKeys }); }, [ debug, id, targetExtensions, context, initialProps ]); if (targetExtensions.length) return /* @__PURE__ */ jsx(Fragment, { children: targetExtensions.map((extension) => /* @__PURE__ */ jsx(UiExtensionRuntimeHost, { apiHost, context, extension, initialProps, onError: onExtensionError, runtimeType: runtime }, extension.id)) }); if (error) return null; if (isLoading) return null; return null; } //#endregion //#region src/ui-extensions/types.ts function withReleaseUiExtensions(app) { return { ...app, uiExtensions: app.release?.uiExtensions || [] }; } //#endregion //#region src/ui-extensions/utils.ts function groupAppsByUiExtensionTarget(apps) { const grouped = {}; for (const enabledApp of apps || []) { const app = withReleaseUiExtensions(enabledApp); const uiExtensionsByTarget = /* @__PURE__ */ new Map(); for (const extension of app.uiExtensions) { if (!extension.target) continue; uiExtensionsByTarget.set(extension.target, [...uiExtensionsByTarget.get(extension.target) || [], extension]); } for (const [target, uiExtensions] of uiExtensionsByTarget) { grouped[target] ??= []; grouped[target].push({ ...app, release: app.release ? { ...app.release, uiExtensions } : app.release, uiExtensions }); } } return grouped; } //#endregion export { DomBundleUiExtensionRuntime as a, useEnabledStoreUiExtensions as c, useGoDaddyContext as d, useVariables as f, UiExtensionRuntimeHost as i, GoDaddyProvider as l, withReleaseUiExtensions as n, getUiExtensionScriptUrl as o, useTheme as p, Target as r, buildUiExtensionContext as s, groupAppsByUiExtensionTarget as t, queryClient as u };