@takeshape/purchase-order-chat 1.51.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +305 -0
- package/dist/pdf-CYwqEJpJ.js +20562 -0
- package/dist/pdf-CYwqEJpJ.js.map +1 -0
- package/dist/pdf.worker-eoyvlo7V.js +37634 -0
- package/dist/pdf.worker-eoyvlo7V.js.map +1 -0
- package/dist/purchase-order-chat-wrapper-D8d5NFc9.js +7899 -0
- package/dist/purchase-order-chat-wrapper-D8d5NFc9.js.map +1 -0
- package/dist/shadow.d.ts +1505 -0
- package/dist/shadow.js +58 -0
- package/dist/shadow.js.map +1 -0
- package/dist/sources.css +4 -0
- package/dist/tailwind.d.ts +1502 -0
- package/dist/tailwind.js +15 -0
- package/dist/tailwind.js.map +1 -0
- package/dist/testing.d.ts +456 -0
- package/dist/testing.js +610 -0
- package/dist/testing.js.map +1 -0
- package/dist/theme.css +75 -0
- package/dist/utilities.css +233 -0
- package/package.json +87 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"purchase-order-chat-wrapper-D8d5NFc9.js","sources":["../../../node_modules/.pnpm/react@19.2.3/node_modules/react/cjs/react-jsx-runtime.production.js","../../../node_modules/.pnpm/react@19.2.3/node_modules/react/cjs/react-jsx-runtime.development.js","../../../node_modules/.pnpm/react@19.2.3/node_modules/react/jsx-runtime.js","../../../node_modules/.pnpm/throttleit@2.1.0/node_modules/throttleit/index.js","../../../node_modules/.pnpm/@ai-sdk+react@3.0.55_react@19.2.3_zod@4.3.6/node_modules/@ai-sdk/react/dist/index.mjs","../src/stores/chat-display-store.ts","../src/components/chat-view/expanded-chat-view.tsx","../src/components/icons/cart-icon.tsx","../src/components/icons/check-icon.tsx","../src/components/icons/copy-icon.tsx","../src/components/icons/maximize-icon.tsx","../src/components/icons/minimize-icon.tsx","../src/constants.ts","../src/lib/utils.ts","../src/components/icons/alert-circle-icon.tsx","../src/components/icons/spinner-icon.tsx","../src/components/chat-view/cartifact/cartifact-address.tsx","../src/lib/formatting.ts","../src/components/chat-view/cartifact/cartifact-footer.tsx","../src/components/icons/x-icon.tsx","../src/components/step-button.tsx","../src/components/quantity-selector.tsx","../src/components/chat-view/cartifact/cartifact-line-item.tsx","../src/components/chat-view/cartifact/panel-action-button.tsx","../src/components/chat-view/cartifact/cartifact-new-order.tsx","../src/components/icons/order-list-icon.tsx","../src/components/chat-view/cartifact/empty-cartifact.tsx","../../../node_modules/.pnpm/zustand@5.0.11_@types+react@19.2.9_react@19.2.3_use-sync-external-store@1.6.0_react@19.2.3_/node_modules/zustand/esm/middleware.mjs","../src/stores/slices/bc-session-slice.ts","../src/lib/bigcommerce/b2b/graphql.ts","../src/lib/bigcommerce/b2b/queries.ts","../src/lib/bigcommerce/storefront/graphql.ts","../src/lib/bigcommerce/storefront/queries.ts","../src/lib/bigcommerce/utils.ts","../src/stores/slices/cartifact-slice.ts","../src/stores/slices/chat-slice.ts","../src/stores/slices/customer-slice.ts","../src/stores/slices/parser-slice.ts","../src/stores/slices/ui-slice.ts","../src/stores/slices/user-settings-slice.ts","../src/stores/purchase-order-store.ts","../src/components/chat-view/cartifact/line-item-warning.tsx","../src/components/chat-view/cartifact/cartifact.tsx","../src/components/chat-view/chat-panel/chat-error.tsx","../src/components/icons/send-icon.tsx","../src/components/chat-view/chat-panel/chat-input.tsx","../src/utils/group-renderable-parts.ts","../src/components/icons/file-icon.tsx","../src/components/icons/expand-chevron-icon.tsx","../src/components/tools/generic-tool-message.tsx","../src/components/tools/parse-tool-output.ts","../src/components/tools/get-product-variants-tool.tsx","../src/components/tools/search-products-by-sku-tool.tsx","../src/components/tools/search-products-tool.tsx","../src/contexts/bigcommerce-client-context.tsx","../src/hooks/use-product-variants.ts","../src/components/icons/placeholder-image-icon.tsx","../src/components/variant-picker.tsx","../src/components/product-card.tsx","../src/components/product-grid.tsx","../src/components/tools/show-products-tool.tsx","../src/components/tools/tool.tsx","../src/components/tools/collapsible-tool-calls.tsx","../src/components/chat-view/chat-panel/collapsible-agent-message.tsx","../src/components/chat-view/chat-panel/chat-message.tsx","../src/hooks/use-touch-device.ts","../src/lib/file-validation.ts","../src/components/icons/upload-document-icon.tsx","../src/components/icons/camera-icon.tsx","../src/components/uploader/camera-button.tsx","../src/components/chat-view/chat-panel/chat-panel-empty-state.tsx","../src/components/chat-view/chat-panel/typing-indicator.tsx","../src/components/chat-view/chat-panel/chat-panel.tsx","../src/components/chat-view/hooks/use-resizable-panel.ts","../src/components/chat-view/tab-bar.tsx","../src/components/chat-view/index.tsx","../src/components/existing-cart-prompt.tsx","../src/components/fatal-error.tsx","../src/components/uploader/processing-steps.tsx","../src/components/uploader/upload-drop-zone.tsx","../src/components/uploader/initial-state.tsx","../src/components/uploader/cart-preview.tsx","../src/stores/tool-call-store.ts","../src/hooks/use-progressive-cart-items.ts","../src/hooks/use-progressive-tool-calls.ts","../src/utils/processing-helpers.ts","../src/components/uploader/processing-steps-vertical.tsx","../src/components/uploader/processing.tsx","../src/components/uploader/index.tsx","../src/contexts/takeshape-config-context.tsx","../src/utils/cart-sync-helpers.ts","../src/hooks/use-bigcommerce-cart.ts","../src/hooks/use-cart-handlers.ts","../src/hooks/use-chat-orchestration.ts","../src/lib/tracing.ts","../src/lib/read-file.ts","../src/lib/spreadsheet.ts","../src/lib/validate-pdf.ts","../src/hooks/use-file-upload.ts","../src/schema.ts","../src/hooks/use-takeshape-thread.ts","../src/hooks/use-document-parser.ts","../src/hooks/use-processing-state.ts","../src/lib/tool-handlers/add-to-cart.ts","../src/lib/tool-handlers/clear-cart.ts","../src/lib/tool-handlers/get-cart.ts","../src/lib/tool-handlers/remove-from-cart.ts","../src/lib/tool-handlers/remove-item-warnings.ts","../src/lib/tool-handlers/set-item-warnings.ts","../src/lib/tool-handlers/set-po-metadata.ts","../src/lib/tool-handlers/update-cart.ts","../src/lib/tool-handlers/index.ts","../src/hooks/use-tool-call-handlers.ts","../src/lib/bigcommerce/b2b/client.ts","../src/stores/session-validation.ts","../src/utils/ai-sdk-helpers.ts","../src/purchase-order-chat.tsx","../src/lib/bigcommerce/storefront/pagination.ts","../src/lib/bigcommerce/storefront/client.ts","../src/purchase-order-chat-wrapper.tsx"],"sourcesContent":["/**\n * @license React\n * react-jsx-runtime.production.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\nvar REACT_ELEMENT_TYPE = Symbol.for(\"react.transitional.element\"),\n REACT_FRAGMENT_TYPE = Symbol.for(\"react.fragment\");\nfunction jsxProd(type, config, maybeKey) {\n var key = null;\n void 0 !== maybeKey && (key = \"\" + maybeKey);\n void 0 !== config.key && (key = \"\" + config.key);\n if (\"key\" in config) {\n maybeKey = {};\n for (var propName in config)\n \"key\" !== propName && (maybeKey[propName] = config[propName]);\n } else maybeKey = config;\n config = maybeKey.ref;\n return {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key,\n ref: void 0 !== config ? config : null,\n props: maybeKey\n };\n}\nexports.Fragment = REACT_FRAGMENT_TYPE;\nexports.jsx = jsxProd;\nexports.jsxs = jsxProd;\n","/**\n * @license React\n * react-jsx-runtime.development.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\n\"production\" !== process.env.NODE_ENV &&\n (function () {\n function getComponentNameFromType(type) {\n if (null == type) return null;\n if (\"function\" === typeof type)\n return type.$$typeof === REACT_CLIENT_REFERENCE\n ? null\n : type.displayName || type.name || null;\n if (\"string\" === typeof type) return type;\n switch (type) {\n case REACT_FRAGMENT_TYPE:\n return \"Fragment\";\n case REACT_PROFILER_TYPE:\n return \"Profiler\";\n case REACT_STRICT_MODE_TYPE:\n return \"StrictMode\";\n case REACT_SUSPENSE_TYPE:\n return \"Suspense\";\n case REACT_SUSPENSE_LIST_TYPE:\n return \"SuspenseList\";\n case REACT_ACTIVITY_TYPE:\n return \"Activity\";\n }\n if (\"object\" === typeof type)\n switch (\n (\"number\" === typeof type.tag &&\n console.error(\n \"Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue.\"\n ),\n type.$$typeof)\n ) {\n case REACT_PORTAL_TYPE:\n return \"Portal\";\n case REACT_CONTEXT_TYPE:\n return type.displayName || \"Context\";\n case REACT_CONSUMER_TYPE:\n return (type._context.displayName || \"Context\") + \".Consumer\";\n case REACT_FORWARD_REF_TYPE:\n var innerType = type.render;\n type = type.displayName;\n type ||\n ((type = innerType.displayName || innerType.name || \"\"),\n (type = \"\" !== type ? \"ForwardRef(\" + type + \")\" : \"ForwardRef\"));\n return type;\n case REACT_MEMO_TYPE:\n return (\n (innerType = type.displayName || null),\n null !== innerType\n ? innerType\n : getComponentNameFromType(type.type) || \"Memo\"\n );\n case REACT_LAZY_TYPE:\n innerType = type._payload;\n type = type._init;\n try {\n return getComponentNameFromType(type(innerType));\n } catch (x) {}\n }\n return null;\n }\n function testStringCoercion(value) {\n return \"\" + value;\n }\n function checkKeyStringCoercion(value) {\n try {\n testStringCoercion(value);\n var JSCompiler_inline_result = !1;\n } catch (e) {\n JSCompiler_inline_result = !0;\n }\n if (JSCompiler_inline_result) {\n JSCompiler_inline_result = console;\n var JSCompiler_temp_const = JSCompiler_inline_result.error;\n var JSCompiler_inline_result$jscomp$0 =\n (\"function\" === typeof Symbol &&\n Symbol.toStringTag &&\n value[Symbol.toStringTag]) ||\n value.constructor.name ||\n \"Object\";\n JSCompiler_temp_const.call(\n JSCompiler_inline_result,\n \"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.\",\n JSCompiler_inline_result$jscomp$0\n );\n return testStringCoercion(value);\n }\n }\n function getTaskName(type) {\n if (type === REACT_FRAGMENT_TYPE) return \"<>\";\n if (\n \"object\" === typeof type &&\n null !== type &&\n type.$$typeof === REACT_LAZY_TYPE\n )\n return \"<...>\";\n try {\n var name = getComponentNameFromType(type);\n return name ? \"<\" + name + \">\" : \"<...>\";\n } catch (x) {\n return \"<...>\";\n }\n }\n function getOwner() {\n var dispatcher = ReactSharedInternals.A;\n return null === dispatcher ? null : dispatcher.getOwner();\n }\n function UnknownOwner() {\n return Error(\"react-stack-top-frame\");\n }\n function hasValidKey(config) {\n if (hasOwnProperty.call(config, \"key\")) {\n var getter = Object.getOwnPropertyDescriptor(config, \"key\").get;\n if (getter && getter.isReactWarning) return !1;\n }\n return void 0 !== config.key;\n }\n function defineKeyPropWarningGetter(props, displayName) {\n function warnAboutAccessingKey() {\n specialPropKeyWarningShown ||\n ((specialPropKeyWarningShown = !0),\n console.error(\n \"%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)\",\n displayName\n ));\n }\n warnAboutAccessingKey.isReactWarning = !0;\n Object.defineProperty(props, \"key\", {\n get: warnAboutAccessingKey,\n configurable: !0\n });\n }\n function elementRefGetterWithDeprecationWarning() {\n var componentName = getComponentNameFromType(this.type);\n didWarnAboutElementRef[componentName] ||\n ((didWarnAboutElementRef[componentName] = !0),\n console.error(\n \"Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.\"\n ));\n componentName = this.props.ref;\n return void 0 !== componentName ? componentName : null;\n }\n function ReactElement(type, key, props, owner, debugStack, debugTask) {\n var refProp = props.ref;\n type = {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key,\n props: props,\n _owner: owner\n };\n null !== (void 0 !== refProp ? refProp : null)\n ? Object.defineProperty(type, \"ref\", {\n enumerable: !1,\n get: elementRefGetterWithDeprecationWarning\n })\n : Object.defineProperty(type, \"ref\", { enumerable: !1, value: null });\n type._store = {};\n Object.defineProperty(type._store, \"validated\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: 0\n });\n Object.defineProperty(type, \"_debugInfo\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: null\n });\n Object.defineProperty(type, \"_debugStack\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: debugStack\n });\n Object.defineProperty(type, \"_debugTask\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: debugTask\n });\n Object.freeze && (Object.freeze(type.props), Object.freeze(type));\n return type;\n }\n function jsxDEVImpl(\n type,\n config,\n maybeKey,\n isStaticChildren,\n debugStack,\n debugTask\n ) {\n var children = config.children;\n if (void 0 !== children)\n if (isStaticChildren)\n if (isArrayImpl(children)) {\n for (\n isStaticChildren = 0;\n isStaticChildren < children.length;\n isStaticChildren++\n )\n validateChildKeys(children[isStaticChildren]);\n Object.freeze && Object.freeze(children);\n } else\n console.error(\n \"React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.\"\n );\n else validateChildKeys(children);\n if (hasOwnProperty.call(config, \"key\")) {\n children = getComponentNameFromType(type);\n var keys = Object.keys(config).filter(function (k) {\n return \"key\" !== k;\n });\n isStaticChildren =\n 0 < keys.length\n ? \"{key: someKey, \" + keys.join(\": ..., \") + \": ...}\"\n : \"{key: someKey}\";\n didWarnAboutKeySpread[children + isStaticChildren] ||\n ((keys =\n 0 < keys.length ? \"{\" + keys.join(\": ..., \") + \": ...}\" : \"{}\"),\n console.error(\n 'A props object containing a \"key\" prop is being spread into JSX:\\n let props = %s;\\n <%s {...props} />\\nReact keys must be passed directly to JSX without using spread:\\n let props = %s;\\n <%s key={someKey} {...props} />',\n isStaticChildren,\n children,\n keys,\n children\n ),\n (didWarnAboutKeySpread[children + isStaticChildren] = !0));\n }\n children = null;\n void 0 !== maybeKey &&\n (checkKeyStringCoercion(maybeKey), (children = \"\" + maybeKey));\n hasValidKey(config) &&\n (checkKeyStringCoercion(config.key), (children = \"\" + config.key));\n if (\"key\" in config) {\n maybeKey = {};\n for (var propName in config)\n \"key\" !== propName && (maybeKey[propName] = config[propName]);\n } else maybeKey = config;\n children &&\n defineKeyPropWarningGetter(\n maybeKey,\n \"function\" === typeof type\n ? type.displayName || type.name || \"Unknown\"\n : type\n );\n return ReactElement(\n type,\n children,\n maybeKey,\n getOwner(),\n debugStack,\n debugTask\n );\n }\n function validateChildKeys(node) {\n isValidElement(node)\n ? node._store && (node._store.validated = 1)\n : \"object\" === typeof node &&\n null !== node &&\n node.$$typeof === REACT_LAZY_TYPE &&\n (\"fulfilled\" === node._payload.status\n ? isValidElement(node._payload.value) &&\n node._payload.value._store &&\n (node._payload.value._store.validated = 1)\n : node._store && (node._store.validated = 1));\n }\n function isValidElement(object) {\n return (\n \"object\" === typeof object &&\n null !== object &&\n object.$$typeof === REACT_ELEMENT_TYPE\n );\n }\n var React = require(\"react\"),\n REACT_ELEMENT_TYPE = Symbol.for(\"react.transitional.element\"),\n REACT_PORTAL_TYPE = Symbol.for(\"react.portal\"),\n REACT_FRAGMENT_TYPE = Symbol.for(\"react.fragment\"),\n REACT_STRICT_MODE_TYPE = Symbol.for(\"react.strict_mode\"),\n REACT_PROFILER_TYPE = Symbol.for(\"react.profiler\"),\n REACT_CONSUMER_TYPE = Symbol.for(\"react.consumer\"),\n REACT_CONTEXT_TYPE = Symbol.for(\"react.context\"),\n REACT_FORWARD_REF_TYPE = Symbol.for(\"react.forward_ref\"),\n REACT_SUSPENSE_TYPE = Symbol.for(\"react.suspense\"),\n REACT_SUSPENSE_LIST_TYPE = Symbol.for(\"react.suspense_list\"),\n REACT_MEMO_TYPE = Symbol.for(\"react.memo\"),\n REACT_LAZY_TYPE = Symbol.for(\"react.lazy\"),\n REACT_ACTIVITY_TYPE = Symbol.for(\"react.activity\"),\n REACT_CLIENT_REFERENCE = Symbol.for(\"react.client.reference\"),\n ReactSharedInternals =\n React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,\n hasOwnProperty = Object.prototype.hasOwnProperty,\n isArrayImpl = Array.isArray,\n createTask = console.createTask\n ? console.createTask\n : function () {\n return null;\n };\n React = {\n react_stack_bottom_frame: function (callStackForError) {\n return callStackForError();\n }\n };\n var specialPropKeyWarningShown;\n var didWarnAboutElementRef = {};\n var unknownOwnerDebugStack = React.react_stack_bottom_frame.bind(\n React,\n UnknownOwner\n )();\n var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));\n var didWarnAboutKeySpread = {};\n exports.Fragment = REACT_FRAGMENT_TYPE;\n exports.jsx = function (type, config, maybeKey) {\n var trackActualOwner =\n 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;\n return jsxDEVImpl(\n type,\n config,\n maybeKey,\n !1,\n trackActualOwner\n ? Error(\"react-stack-top-frame\")\n : unknownOwnerDebugStack,\n trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask\n );\n };\n exports.jsxs = function (type, config, maybeKey) {\n var trackActualOwner =\n 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;\n return jsxDEVImpl(\n type,\n config,\n maybeKey,\n !0,\n trackActualOwner\n ? Error(\"react-stack-top-frame\")\n : unknownOwnerDebugStack,\n trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask\n );\n };\n })();\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-jsx-runtime.production.js');\n} else {\n module.exports = require('./cjs/react-jsx-runtime.development.js');\n}\n","function throttle(function_, wait) {\n\tif (typeof function_ !== 'function') {\n\t\tthrow new TypeError(`Expected the first argument to be a \\`function\\`, got \\`${typeof function_}\\`.`);\n\t}\n\n\t// TODO: Add `wait` validation too in the next major version.\n\n\tlet timeoutId;\n\tlet lastCallTime = 0;\n\n\treturn function throttled(...arguments_) { // eslint-disable-line func-names\n\t\tclearTimeout(timeoutId);\n\n\t\tconst now = Date.now();\n\t\tconst timeSinceLastCall = now - lastCallTime;\n\t\tconst delayForNextCall = wait - timeSinceLastCall;\n\n\t\tif (delayForNextCall <= 0) {\n\t\t\tlastCallTime = now;\n\t\t\tfunction_.apply(this, arguments_);\n\t\t} else {\n\t\t\ttimeoutId = setTimeout(() => {\n\t\t\t\tlastCallTime = Date.now();\n\t\t\t\tfunction_.apply(this, arguments_);\n\t\t\t}, delayForNextCall);\n\t\t}\n\t};\n}\n\nmodule.exports = throttle;\n","var __accessCheck = (obj, member, msg) => {\n if (!member.has(obj))\n throw TypeError(\"Cannot \" + msg);\n};\nvar __privateGet = (obj, member, getter) => {\n __accessCheck(obj, member, \"read from private field\");\n return getter ? getter.call(obj) : member.get(obj);\n};\nvar __privateAdd = (obj, member, value) => {\n if (member.has(obj))\n throw TypeError(\"Cannot add the same private member more than once\");\n member instanceof WeakSet ? member.add(obj) : member.set(obj, value);\n};\nvar __privateSet = (obj, member, value, setter) => {\n __accessCheck(obj, member, \"write to private field\");\n setter ? setter.call(obj, value) : member.set(obj, value);\n return value;\n};\n\n// src/use-chat.ts\nimport { useCallback, useEffect, useRef, useSyncExternalStore } from \"react\";\n\n// src/chat.react.ts\nimport { AbstractChat } from \"ai\";\n\n// src/throttle.ts\nimport throttleFunction from \"throttleit\";\nfunction throttle(fn, waitMs) {\n return waitMs != null ? throttleFunction(fn, waitMs) : fn;\n}\n\n// src/chat.react.ts\nvar _messages, _status, _error, _messagesCallbacks, _statusCallbacks, _errorCallbacks, _callMessagesCallbacks, _callStatusCallbacks, _callErrorCallbacks;\nvar ReactChatState = class {\n constructor(initialMessages = []) {\n __privateAdd(this, _messages, void 0);\n __privateAdd(this, _status, \"ready\");\n __privateAdd(this, _error, void 0);\n __privateAdd(this, _messagesCallbacks, /* @__PURE__ */ new Set());\n __privateAdd(this, _statusCallbacks, /* @__PURE__ */ new Set());\n __privateAdd(this, _errorCallbacks, /* @__PURE__ */ new Set());\n this.pushMessage = (message) => {\n __privateSet(this, _messages, __privateGet(this, _messages).concat(message));\n __privateGet(this, _callMessagesCallbacks).call(this);\n };\n this.popMessage = () => {\n __privateSet(this, _messages, __privateGet(this, _messages).slice(0, -1));\n __privateGet(this, _callMessagesCallbacks).call(this);\n };\n this.replaceMessage = (index, message) => {\n __privateSet(this, _messages, [\n ...__privateGet(this, _messages).slice(0, index),\n // We deep clone the message here to ensure the new React Compiler (currently in RC) detects deeply nested parts/metadata changes:\n this.snapshot(message),\n ...__privateGet(this, _messages).slice(index + 1)\n ]);\n __privateGet(this, _callMessagesCallbacks).call(this);\n };\n this.snapshot = (value) => structuredClone(value);\n this[\"~registerMessagesCallback\"] = (onChange, throttleWaitMs) => {\n const callback = throttleWaitMs ? throttle(onChange, throttleWaitMs) : onChange;\n __privateGet(this, _messagesCallbacks).add(callback);\n return () => {\n __privateGet(this, _messagesCallbacks).delete(callback);\n };\n };\n this[\"~registerStatusCallback\"] = (onChange) => {\n __privateGet(this, _statusCallbacks).add(onChange);\n return () => {\n __privateGet(this, _statusCallbacks).delete(onChange);\n };\n };\n this[\"~registerErrorCallback\"] = (onChange) => {\n __privateGet(this, _errorCallbacks).add(onChange);\n return () => {\n __privateGet(this, _errorCallbacks).delete(onChange);\n };\n };\n __privateAdd(this, _callMessagesCallbacks, () => {\n __privateGet(this, _messagesCallbacks).forEach((callback) => callback());\n });\n __privateAdd(this, _callStatusCallbacks, () => {\n __privateGet(this, _statusCallbacks).forEach((callback) => callback());\n });\n __privateAdd(this, _callErrorCallbacks, () => {\n __privateGet(this, _errorCallbacks).forEach((callback) => callback());\n });\n __privateSet(this, _messages, initialMessages);\n }\n get status() {\n return __privateGet(this, _status);\n }\n set status(newStatus) {\n __privateSet(this, _status, newStatus);\n __privateGet(this, _callStatusCallbacks).call(this);\n }\n get error() {\n return __privateGet(this, _error);\n }\n set error(newError) {\n __privateSet(this, _error, newError);\n __privateGet(this, _callErrorCallbacks).call(this);\n }\n get messages() {\n return __privateGet(this, _messages);\n }\n set messages(newMessages) {\n __privateSet(this, _messages, [...newMessages]);\n __privateGet(this, _callMessagesCallbacks).call(this);\n }\n};\n_messages = new WeakMap();\n_status = new WeakMap();\n_error = new WeakMap();\n_messagesCallbacks = new WeakMap();\n_statusCallbacks = new WeakMap();\n_errorCallbacks = new WeakMap();\n_callMessagesCallbacks = new WeakMap();\n_callStatusCallbacks = new WeakMap();\n_callErrorCallbacks = new WeakMap();\nvar _state;\nvar Chat = class extends AbstractChat {\n constructor({ messages, ...init }) {\n const state = new ReactChatState(messages);\n super({ ...init, state });\n __privateAdd(this, _state, void 0);\n this[\"~registerMessagesCallback\"] = (onChange, throttleWaitMs) => __privateGet(this, _state)[\"~registerMessagesCallback\"](onChange, throttleWaitMs);\n this[\"~registerStatusCallback\"] = (onChange) => __privateGet(this, _state)[\"~registerStatusCallback\"](onChange);\n this[\"~registerErrorCallback\"] = (onChange) => __privateGet(this, _state)[\"~registerErrorCallback\"](onChange);\n __privateSet(this, _state, state);\n }\n};\n_state = new WeakMap();\n\n// src/use-chat.ts\nfunction useChat({\n experimental_throttle: throttleWaitMs,\n resume = false,\n ...options\n} = {}) {\n const callbacksRef = useRef(\n !(\"chat\" in options) ? {\n onToolCall: options.onToolCall,\n onData: options.onData,\n onFinish: options.onFinish,\n onError: options.onError,\n sendAutomaticallyWhen: options.sendAutomaticallyWhen\n } : {}\n );\n if (!(\"chat\" in options)) {\n callbacksRef.current = {\n onToolCall: options.onToolCall,\n onData: options.onData,\n onFinish: options.onFinish,\n onError: options.onError,\n sendAutomaticallyWhen: options.sendAutomaticallyWhen\n };\n }\n const optionsWithCallbacks = {\n ...options,\n onToolCall: (arg) => {\n var _a, _b;\n return (_b = (_a = callbacksRef.current).onToolCall) == null ? void 0 : _b.call(_a, arg);\n },\n onData: (arg) => {\n var _a, _b;\n return (_b = (_a = callbacksRef.current).onData) == null ? void 0 : _b.call(_a, arg);\n },\n onFinish: (arg) => {\n var _a, _b;\n return (_b = (_a = callbacksRef.current).onFinish) == null ? void 0 : _b.call(_a, arg);\n },\n onError: (arg) => {\n var _a, _b;\n return (_b = (_a = callbacksRef.current).onError) == null ? void 0 : _b.call(_a, arg);\n },\n sendAutomaticallyWhen: (arg) => {\n var _a, _b, _c;\n return (_c = (_b = (_a = callbacksRef.current).sendAutomaticallyWhen) == null ? void 0 : _b.call(_a, arg)) != null ? _c : false;\n }\n };\n const chatRef = useRef(\n \"chat\" in options ? options.chat : new Chat(optionsWithCallbacks)\n );\n const shouldRecreateChat = \"chat\" in options && options.chat !== chatRef.current || \"id\" in options && chatRef.current.id !== options.id;\n if (shouldRecreateChat) {\n chatRef.current = \"chat\" in options ? options.chat : new Chat(optionsWithCallbacks);\n }\n const subscribeToMessages = useCallback(\n (update) => chatRef.current[\"~registerMessagesCallback\"](update, throttleWaitMs),\n // `chatRef.current.id` is required to trigger re-subscription when the chat ID changes\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [throttleWaitMs, chatRef.current.id]\n );\n const messages = useSyncExternalStore(\n subscribeToMessages,\n () => chatRef.current.messages,\n () => chatRef.current.messages\n );\n const status = useSyncExternalStore(\n chatRef.current[\"~registerStatusCallback\"],\n () => chatRef.current.status,\n () => chatRef.current.status\n );\n const error = useSyncExternalStore(\n chatRef.current[\"~registerErrorCallback\"],\n () => chatRef.current.error,\n () => chatRef.current.error\n );\n const setMessages = useCallback(\n (messagesParam) => {\n if (typeof messagesParam === \"function\") {\n messagesParam = messagesParam(chatRef.current.messages);\n }\n chatRef.current.messages = messagesParam;\n },\n [chatRef]\n );\n useEffect(() => {\n if (resume) {\n chatRef.current.resumeStream();\n }\n }, [resume, chatRef]);\n return {\n id: chatRef.current.id,\n messages,\n setMessages,\n sendMessage: chatRef.current.sendMessage,\n regenerate: chatRef.current.regenerate,\n clearError: chatRef.current.clearError,\n stop: chatRef.current.stop,\n error,\n resumeStream: chatRef.current.resumeStream,\n status,\n /**\n * @deprecated Use `addToolOutput` instead.\n */\n addToolResult: chatRef.current.addToolOutput,\n addToolOutput: chatRef.current.addToolOutput,\n addToolApprovalResponse: chatRef.current.addToolApprovalResponse\n };\n}\n\n// src/use-completion.ts\nimport {\n callCompletionApi\n} from \"ai\";\nimport { useCallback as useCallback2, useEffect as useEffect2, useId, useRef as useRef2, useState } from \"react\";\nimport useSWR from \"swr\";\nfunction useCompletion({\n api = \"/api/completion\",\n id,\n initialCompletion = \"\",\n initialInput = \"\",\n credentials,\n headers,\n body,\n streamProtocol = \"data\",\n fetch: fetch2,\n onFinish,\n onError,\n experimental_throttle: throttleWaitMs\n} = {}) {\n const hookId = useId();\n const completionId = id || hookId;\n const { data, mutate } = useSWR([api, completionId], null, {\n fallbackData: initialCompletion\n });\n const { data: isLoading = false, mutate: mutateLoading } = useSWR(\n [completionId, \"loading\"],\n null\n );\n const [error, setError] = useState(void 0);\n const completion = data;\n const [abortController, setAbortController] = useState(null);\n const extraMetadataRef = useRef2({\n credentials,\n headers,\n body\n });\n useEffect2(() => {\n extraMetadataRef.current = {\n credentials,\n headers,\n body\n };\n }, [credentials, headers, body]);\n const triggerRequest = useCallback2(\n async (prompt, options) => callCompletionApi({\n api,\n prompt,\n credentials: extraMetadataRef.current.credentials,\n headers: { ...extraMetadataRef.current.headers, ...options == null ? void 0 : options.headers },\n body: {\n ...extraMetadataRef.current.body,\n ...options == null ? void 0 : options.body\n },\n streamProtocol,\n fetch: fetch2,\n // throttle streamed ui updates:\n setCompletion: throttle(\n (completion2) => mutate(completion2, false),\n throttleWaitMs\n ),\n setLoading: mutateLoading,\n setError,\n setAbortController,\n onFinish,\n onError\n }),\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n setAbortController,\n onFinish,\n onError,\n setError,\n streamProtocol,\n fetch2,\n throttleWaitMs\n ]\n );\n const stop = useCallback2(() => {\n if (abortController) {\n abortController.abort();\n setAbortController(null);\n }\n }, [abortController]);\n const setCompletion = useCallback2(\n (completion2) => {\n mutate(completion2, false);\n },\n [mutate]\n );\n const complete = useCallback2(\n async (prompt, options) => {\n return triggerRequest(prompt, options);\n },\n [triggerRequest]\n );\n const [input, setInput] = useState(initialInput);\n const handleSubmit = useCallback2(\n (event) => {\n var _a;\n (_a = event == null ? void 0 : event.preventDefault) == null ? void 0 : _a.call(event);\n return input ? complete(input) : void 0;\n },\n [input, complete]\n );\n const handleInputChange = useCallback2(\n (e) => {\n setInput(e.target.value);\n },\n [setInput]\n );\n return {\n completion,\n complete,\n error,\n setCompletion,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading\n };\n}\n\n// src/use-object.ts\nimport {\n isAbortError,\n resolve,\n normalizeHeaders,\n safeValidateTypes\n} from \"@ai-sdk/provider-utils\";\nimport { asSchema, isDeepEqualData, parsePartialJson } from \"ai\";\nimport { useCallback as useCallback3, useId as useId2, useRef as useRef3, useState as useState2 } from \"react\";\nimport useSWR2 from \"swr\";\nvar getOriginalFetch = () => fetch;\nfunction useObject({\n api,\n id,\n schema,\n // required, in the future we will use it for validation\n initialValue,\n fetch: fetch2,\n onError,\n onFinish,\n headers,\n credentials\n}) {\n const hookId = useId2();\n const completionId = id != null ? id : hookId;\n const { data, mutate } = useSWR2(\n [api, completionId],\n null,\n { fallbackData: initialValue }\n );\n const [error, setError] = useState2(void 0);\n const [isLoading, setIsLoading] = useState2(false);\n const abortControllerRef = useRef3(null);\n const stop = useCallback3(() => {\n var _a;\n try {\n (_a = abortControllerRef.current) == null ? void 0 : _a.abort();\n } catch (ignored) {\n } finally {\n setIsLoading(false);\n abortControllerRef.current = null;\n }\n }, []);\n const submit = async (input) => {\n var _a;\n try {\n clearObject();\n setIsLoading(true);\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n const resolvedHeaders = await resolve(headers);\n const actualFetch = fetch2 != null ? fetch2 : getOriginalFetch();\n const response = await actualFetch(api, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...normalizeHeaders(resolvedHeaders)\n },\n credentials,\n signal: abortController.signal,\n body: JSON.stringify(input)\n });\n if (!response.ok) {\n throw new Error(\n (_a = await response.text()) != null ? _a : \"Failed to fetch the response.\"\n );\n }\n if (response.body == null) {\n throw new Error(\"The response body is empty.\");\n }\n let accumulatedText = \"\";\n let latestObject = void 0;\n await response.body.pipeThrough(new TextDecoderStream()).pipeTo(\n new WritableStream({\n async write(chunk) {\n accumulatedText += chunk;\n const { value } = await parsePartialJson(accumulatedText);\n const currentObject = value;\n if (!isDeepEqualData(latestObject, currentObject)) {\n latestObject = currentObject;\n mutate(currentObject);\n }\n },\n async close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n if (onFinish != null) {\n const validationResult = await safeValidateTypes({\n value: latestObject,\n schema: asSchema(schema)\n });\n onFinish(\n validationResult.success ? { object: validationResult.value, error: void 0 } : { object: void 0, error: validationResult.error }\n );\n }\n }\n })\n );\n } catch (error2) {\n if (isAbortError(error2)) {\n return;\n }\n if (onError && error2 instanceof Error) {\n onError(error2);\n }\n setIsLoading(false);\n setError(error2 instanceof Error ? error2 : new Error(String(error2)));\n }\n };\n const clear = () => {\n stop();\n clearObject();\n };\n const clearObject = () => {\n setError(void 0);\n setIsLoading(false);\n mutate(void 0);\n };\n return {\n submit,\n object: data,\n error,\n isLoading,\n stop,\n clear\n };\n}\nvar experimental_useObject = useObject;\nexport {\n Chat,\n experimental_useObject,\n useChat,\n useCompletion\n};\n//# sourceMappingURL=index.mjs.map","import { create } from 'zustand';\n\ninterface ChatDisplayState {\n isExpanded: boolean;\n setExpanded: (expanded: boolean) => void;\n toggleExpanded: () => void;\n reset: () => void;\n}\n\nexport const useChatDisplayStore = create<ChatDisplayState>((set) => ({\n isExpanded: false,\n setExpanded: (expanded) => set({ isExpanded: expanded }),\n toggleExpanded: () => set((state) => ({ isExpanded: !state.isExpanded })),\n reset: () => set({ isExpanded: false })\n}));\n","import { type ReactNode, useEffect, useLayoutEffect, useRef } from 'react';\nimport { useChatDisplayStore } from '../../stores/chat-display-store.js';\n\ninterface ExpandedChatViewProps {\n children: ReactNode;\n}\n\nexport function ExpandedChatView({ children }: ExpandedChatViewProps) {\n const isExpanded = useChatDisplayStore((state) => state.isExpanded);\n const setExpanded = useChatDisplayStore((state) => state.setExpanded);\n const overlayRef = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n if (!isExpanded) return;\n\n const handleKeyDown = (e: KeyboardEvent) => {\n if (e.key === 'Escape') {\n setExpanded(false);\n }\n };\n\n document.addEventListener('keydown', handleKeyDown);\n return () => document.removeEventListener('keydown', handleKeyDown);\n }, [isExpanded, setExpanded]);\n\n // Prevent background scroll while expanded, restoring scroll position on close.\n useLayoutEffect(() => {\n if (!isExpanded) return;\n\n const scrollY = window.scrollY;\n const originalOverflow = document.body.style.overflow;\n const originalPosition = document.body.style.position;\n const originalTop = document.body.style.top;\n const originalWidth = document.body.style.width;\n\n document.body.style.overflow = 'hidden';\n document.body.style.position = 'fixed';\n document.body.style.top = `-${scrollY}px`;\n document.body.style.width = '100%';\n\n return () => {\n document.body.style.overflow = originalOverflow;\n document.body.style.position = originalPosition;\n document.body.style.top = originalTop;\n document.body.style.width = originalWidth;\n window.scrollTo(0, scrollY);\n };\n }, [isExpanded]);\n\n // Elevate the Shadow DOM host so the modal appears above the host page.\n // This is the JS equivalent of the :host:has() CSS rule in utilities.css,\n // which Firefox does not support.\n useLayoutEffect(() => {\n if (!isExpanded || !overlayRef.current) return;\n\n const root = overlayRef.current.getRootNode();\n if (!(root instanceof ShadowRoot)) return;\n\n const host = root.host as HTMLElement;\n const prev = {\n position: host.style.position,\n top: host.style.top,\n right: host.style.right,\n bottom: host.style.bottom,\n left: host.style.left,\n zIndex: host.style.zIndex,\n overflow: host.style.overflow\n };\n\n host.style.position = 'fixed';\n host.style.top = '0';\n host.style.right = '0';\n host.style.bottom = '0';\n host.style.left = '0';\n host.style.zIndex = '2147483647';\n host.style.overflow = 'hidden';\n\n return () => {\n host.style.position = prev.position;\n host.style.top = prev.top;\n host.style.right = prev.right;\n host.style.bottom = prev.bottom;\n host.style.left = prev.left;\n host.style.zIndex = prev.zIndex;\n host.style.overflow = prev.overflow;\n };\n }, [isExpanded]);\n\n if (!isExpanded) {\n return null;\n }\n\n return (\n <div\n ref={overlayRef}\n data-state=\"expanded\"\n data-testid=\"modal-overlay\"\n className=\"fixed inset-0 z-50 flex items-center justify-center\"\n >\n {/* Backdrop */}\n <div\n data-testid=\"modal-backdrop\"\n className=\"absolute inset-0 bg-black/50 animate-modal-backdrop-in\"\n />\n\n {/* Content */}\n <div className=\"relative w-[95vw] max-w-[1440px] h-[95vh] bg-surface rounded-lg shadow-2xl flex flex-col overflow-hidden animate-modal-content-in\">\n <div className=\"flex-1 min-h-0\">{children}</div>\n </div>\n </div>\n );\n}\n","export const CartIcon = () => (\n <svg\n width=\"18\"\n height=\"18\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n >\n <title>Cart</title>\n <circle cx=\"9\" cy=\"21\" r=\"1\" />\n <circle cx=\"20\" cy=\"21\" r=\"1\" />\n <path d=\"M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6\" />\n </svg>\n);\n","interface CheckIconProps {\n size?: number;\n title?: string;\n}\n\nexport const CheckIcon = ({ size = 12, title = 'Saved' }: CheckIconProps) => (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"3\"\n >\n <title>{title}</title>\n <polyline points=\"20 6 9 17 4 12\" />\n </svg>\n);\n","interface CopyIconProps {\n size?: number;\n}\n\nexport const CopyIcon = ({ size = 12 }: CopyIconProps) => (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <title>Copy</title>\n <rect x=\"9\" y=\"9\" width=\"13\" height=\"13\" rx=\"2\" ry=\"2\" />\n <path d=\"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1\" />\n </svg>\n);\n","export const MaximizeIcon = ({ size = 16 }: { size?: number }) => (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <title>Expand</title>\n <polyline points=\"15 3 21 3 21 9\" />\n <polyline points=\"9 21 3 21 3 15\" />\n <line x1=\"21\" y1=\"3\" x2=\"14\" y2=\"10\" />\n <line x1=\"3\" y1=\"21\" x2=\"10\" y2=\"14\" />\n </svg>\n);\n","export const MinimizeIcon = ({ size = 16 }: { size?: number }) => (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <title>Minimize</title>\n <polyline points=\"4 14 10 14 10 20\" />\n <polyline points=\"20 10 14 10 14 4\" />\n <line x1=\"14\" y1=\"10\" x2=\"21\" y2=\"3\" />\n <line x1=\"3\" y1=\"21\" x2=\"10\" y2=\"14\" />\n </svg>\n);\n","export const DEFAULT_AGENT_NAME = 'bigcommercePurchaseOrderAgent';\n\nexport const B2B_GRAPHQL_URL = 'https://api-b2b.bigcommerce.com/graphql';\n\n// The well-known B2B Edition client ID used for Current Customer JWT requests\nexport const B2B_APP_CLIENT_ID = 'dl7c39mdpul6hyc489yk0vzxl6jesyx';\n\n// Synthetic message sent after client tool responses to trigger server processing\n// TODO: Remove after https://app.shortcut.com/takeshape/story/16151/support-sending-agent-tool-call-results-without-a-user-message\nexport const CLIENT_TOOL_RESPONSE_MESSAGE =\n '[client is providing tool response]';\n\nexport const PO_ADDRESS_ID = '__po_address__';\nexport const PO_BILLING_ADDRESS_ID = '__po_billing_address__';\nexport const CHECKOUT_ADDRESS_ID = '__checkout_address__';\n\n// Storage key for persistence\nexport const STORAGE_KEY = 'purchase-order-chat-session';\n\n// Persistence version for future migrations\nexport const STORAGE_VERSION = 3;\n","import { type ClassValue, clsx } from 'clsx';\nimport { twMerge } from 'tailwind-merge';\n\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs));\n}\n","interface AlertCircleIconProps {\n size?: number;\n title?: string;\n}\n\nexport const AlertCircleIcon = ({\n size = 12,\n title = 'Error'\n}: AlertCircleIconProps) => (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n >\n <title>{title}</title>\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <line x1=\"12\" y1=\"8\" x2=\"12\" y2=\"12\" />\n <line x1=\"12\" y1=\"16\" x2=\"12.01\" y2=\"16\" />\n </svg>\n);\n","interface SpinnerIconProps {\n size?: number;\n}\n\nexport const SpinnerIcon = ({ size = 12 }: SpinnerIconProps) => (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n className=\"animate-spin\"\n >\n <title>Loading</title>\n <path d=\"M21 12a9 9 0 1 1-6.219-8.56\" />\n </svg>\n);\n","import { useCallback, useEffect, useRef, useState } from 'react';\nimport { CHECKOUT_ADDRESS_ID } from '../../../constants.js';\nimport type { CustomerAddress } from '../../../lib/bigcommerce/index.js';\nimport { cn } from '../../../lib/utils.js';\nimport type { AddressUpdateStatus } from '../../../types.js';\nimport { AlertCircleIcon } from '../../icons/alert-circle-icon.js';\nimport { CheckIcon } from '../../icons/check-icon.js';\nimport { CopyIcon } from '../../icons/copy-icon.js';\nimport { SpinnerIcon } from '../../icons/spinner-icon.js';\n\nexport interface CartifactAddressProps {\n addresses: CustomerAddress[];\n selectedAddressId?: string;\n addressUpdateStatus?: AddressUpdateStatus;\n onAddressChange?: (addressId: string) => void;\n shipToAddress?: CustomerAddress;\n billingAddress?: CustomerAddress;\n selectedBillingAddressId?: string;\n billingAddressUpdateStatus?: AddressUpdateStatus;\n onBillingAddressChange?: (addressId: string) => void;\n}\n\nexport function CartifactAddress({\n addresses,\n selectedAddressId,\n addressUpdateStatus = 'idle',\n onAddressChange,\n shipToAddress,\n billingAddress,\n selectedBillingAddressId,\n billingAddressUpdateStatus = 'idle',\n onBillingAddressChange\n}: CartifactAddressProps) {\n const canShowDefaultAddressWarning =\n addresses.some((addr) => addr.isDefaultShipping) &&\n addresses.some((addr) => addr.isDefaultBilling);\n\n return (\n <div\n className={cn(\n 'grid gap-2',\n billingAddress ? 'grid-cols-2' : 'grid-cols-1'\n )}\n >\n {/* Billing Address */}\n {billingAddress && (\n <AddressSelect\n label=\"Bill to\"\n onAddressChange={onBillingAddressChange}\n addresses={addresses}\n selectedAddressId={selectedBillingAddressId}\n addressUpdateStatus={billingAddressUpdateStatus}\n poAddress={billingAddress}\n defaultAddressFilter={(addr) => addr.isDefaultShipping}\n addressFilter={(addr) => addr.isBilling}\n canShowDefaultAddressWarning={canShowDefaultAddressWarning}\n />\n )}\n\n {/* Ship To Address */}\n <AddressSelect\n label=\"Ship to\"\n onAddressChange={onAddressChange}\n addresses={addresses}\n selectedAddressId={selectedAddressId}\n addressUpdateStatus={addressUpdateStatus}\n poAddress={shipToAddress}\n defaultAddressFilter={(addr) => addr.isDefaultShipping}\n addressFilter={(addr) => addr.isShipping}\n canShowDefaultAddressWarning={canShowDefaultAddressWarning}\n />\n </div>\n );\n}\n\nexport interface AddressSelectProps {\n label: string;\n addresses: CustomerAddress[];\n selectedAddressId?: string;\n addressUpdateStatus?: AddressUpdateStatus;\n onAddressChange?: (addressId: string) => void;\n poAddress?: CustomerAddress;\n defaultAddressFilter?: (addr: CustomerAddress) => boolean;\n addressFilter?: (addr: CustomerAddress) => boolean;\n canShowDefaultAddressWarning: boolean;\n}\n\nfunction AddressSelect(props: AddressSelectProps) {\n const {\n label,\n addresses,\n selectedAddressId,\n addressUpdateStatus = 'idle',\n onAddressChange,\n poAddress,\n defaultAddressFilter = (addr) => addr.isDefaultShipping,\n addressFilter = (addr) => addr.isShipping,\n canShowDefaultAddressWarning\n } = props;\n\n const isCheckoutAddress = selectedAddressId === CHECKOUT_ADDRESS_ID;\n\n const defaultAddress = addresses.find(defaultAddressFilter);\n\n let showDefaultAddressWarning =\n canShowDefaultAddressWarning && !!selectedAddressId && !isCheckoutAddress;\n\n if (showDefaultAddressWarning && defaultAddress) {\n showDefaultAddressWarning = defaultAddress.id !== selectedAddressId;\n }\n\n const addressOptions = addresses.filter(addressFilter);\n\n return (\n <div\n className={`p-2 px-2.5 rounded border border-solid ${showDefaultAddressWarning ? 'bg-warning-bg border-warning' : 'bg-surface-secondary border-border'}`}\n >\n <div className=\"flex justify-between items-center mb-0.5\">\n <span className=\"text-[0.625rem] text-text-tertiary uppercase tracking-[0.05em]\">\n {label}\n </span>\n {addressUpdateStatus === 'updating' && (\n <span className=\"flex items-center gap-1 text-[0.625rem] font-medium text-text-tertiary uppercase tracking-[0.025em]\">\n <SpinnerIcon size={10} />\n Updating...\n </span>\n )}\n {addressUpdateStatus === 'success' && (\n <span className=\"flex items-center gap-0.5 text-[0.625rem] font-semibold text-success-text uppercase tracking-[0.025em]\">\n <CheckIcon size={10} title=\"Updated\" />\n Updated\n </span>\n )}\n {addressUpdateStatus === 'error' && (\n <span className=\"flex items-center gap-0.5 text-[0.625rem] font-semibold text-error-text uppercase tracking-[0.025em]\">\n <AlertCircleIcon size={12} title=\"Failed\" />\n Failed to update\n </span>\n )}\n </div>\n <select\n value={selectedAddressId ?? ''}\n onChange={(e) => onAddressChange?.(e.target.value)}\n disabled={addressUpdateStatus === 'updating'}\n className=\"w-full px-2 py-1.5 text-[0.8125rem] font-medium rounded cursor-pointer transition-colors focus:outline-none focus:border-border-focus disabled:opacity-50 disabled:cursor-not-allowed border border-solid font-[inherit] appearance-auto text-text bg-transparent border-border-strong\"\n >\n {poAddress && (\n <>\n <option key={poAddress.id} value={poAddress.id}>\n <AddressSelectOption address={poAddress} />\n </option>\n <option disabled>---</option>\n </>\n )}\n\n {addressOptions.map((addr) => (\n <option key={addr.id} value={addr.id}>\n <AddressSelectOption\n address={addr}\n isDefault={defaultAddressFilter}\n />\n </option>\n ))}\n\n {addressOptions.length > 0 && <option disabled>---</option>}\n\n <option key={CHECKOUT_ADDRESS_ID} value={CHECKOUT_ADDRESS_ID}>\n Enter an address at checkout\n </option>\n </select>\n\n {poAddress && <FormattedAddress address={poAddress} />}\n\n {/* Default address warning */}\n {showDefaultAddressWarning && (\n <p className=\"mt-1.5 pt-1.5 m-0 text-[0.6875rem] leading-[1.4]\">\n Your company has a default address set. Verify your address on the\n checkout page as it may not populate automatically.\n </p>\n )}\n </div>\n );\n}\n\ntype AddressSelectOptionProps = {\n address: CustomerAddress;\n isDefault?: (addr: CustomerAddress) => boolean;\n};\n\nfunction AddressSelectOption(props: AddressSelectOptionProps) {\n const { address, isDefault } = props;\n\n return (\n <>\n {isDefault?.(address) ? '[DEFAULT] ' : ''}\n {address.label ? `[${address.label.toUpperCase()}] ` : ''}\n {address.firstName} {address.lastName} - {address.address1},{' '}\n {address.city}, {address.stateOrProvince} {address.postalCode}\n </>\n );\n}\n\nfunction formatAddress(address: CustomerAddress): string {\n const parts = [address.address1];\n if (address.address2) parts.push(address.address2);\n if (address.city) parts.push(address.city);\n if (address.stateOrProvince) parts.push(address.stateOrProvince);\n // postalCode attaches to the state without a comma\n const lastPart = parts.pop();\n if (address.postalCode) {\n parts.push(`${lastPart} ${address.postalCode}`);\n } else if (lastPart) {\n parts.push(lastPart);\n }\n return parts.join(', ');\n}\n\nfunction FormattedAddress({ address }: { address: CustomerAddress }) {\n const [isCopied, setIsCopied] = useState(false);\n const timerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n\n useEffect(() => {\n return () => {\n if (timerRef.current) clearTimeout(timerRef.current);\n };\n }, []);\n\n const formattedAddress = formatAddress(address);\n\n const handleCopy = useCallback(async () => {\n try {\n await navigator.clipboard.writeText(formattedAddress);\n setIsCopied(true);\n if (timerRef.current) clearTimeout(timerRef.current);\n timerRef.current = setTimeout(() => setIsCopied(false), 1500);\n } catch {\n // Clipboard API unavailable — fail silently\n }\n }, [formattedAddress]);\n\n return (\n <button\n type=\"button\"\n aria-label=\"Copy PO address to clipboard\"\n onClick={handleCopy}\n className={`mt-1.5 pt-1.5 m-0 text-[0.6875rem] leading-[1.4] cursor-pointer flex justify-between items-start gap-1 w-full bg-transparent text-left border-0 border-t border-solid p-0 font-[inherit] border-border-strong text-text-tertiary`}\n >\n <span>\n <span className=\"text-text-tertiary\">PO address:</span>{' '}\n {formattedAddress}\n </span>\n <span className=\"shrink-0 mt-0.5\">\n {isCopied ? (\n <CheckIcon size={12} title=\"Copied\" />\n ) : (\n <CopyIcon size={12} />\n )}\n </span>\n </button>\n );\n}\n","export const formatCurrency = (amount: number, currencyCode = 'USD') => {\n return new Intl.NumberFormat('en-US', {\n style: 'currency',\n currency: currencyCode\n }).format(amount);\n};\n","import { formatCurrency } from '../../../lib/formatting.js';\n\nfunction FooterRow({ label, value }: { label: string; value: string }) {\n return (\n <div className=\"flex justify-between py-0.5\">\n <span className=\"text-[0.8125rem] text-text-tertiary\">{label}</span>\n <span className=\"text-[0.8125rem] text-text\">{value}</span>\n </div>\n );\n}\n\nfunction formatOptional(\n value: number | null | undefined,\n currencyCode?: string\n): string {\n return value !== null && value !== undefined\n ? formatCurrency(value, currencyCode)\n : '...';\n}\n\nexport interface CartifactFooterProps {\n subtotal: number;\n tax?: number | null;\n shipping?: number | null;\n total?: number | null;\n currencyCode?: string;\n totalQuantity: number;\n availableItemCount: number;\n onCheckout: () => void;\n isLoading?: boolean;\n allowCheckout?: boolean;\n}\n\nexport function CartifactFooter({\n subtotal,\n tax,\n shipping,\n total,\n currencyCode,\n totalQuantity,\n availableItemCount,\n onCheckout,\n isLoading,\n allowCheckout = true\n}: CartifactFooterProps) {\n return (\n <div className=\"px-4 py-2.5 shrink-0 bg-surface-secondary\">\n <FooterRow\n label=\"Subtotal\"\n value={formatCurrency(subtotal, currencyCode)}\n />\n <FooterRow label=\"Tax\" value={formatOptional(tax, currencyCode)} />\n <FooterRow\n label=\"Shipping\"\n value={formatOptional(shipping, currencyCode)}\n />\n <div className=\"flex justify-between mt-1 pt-1.5 border-t border-border\">\n <span className=\"text-[0.875rem] font-semibold text-text\">Total</span>\n <span className=\"text-[0.875rem] font-semibold text-text\">\n {formatOptional(total, currencyCode)}\n </span>\n </div>\n <button\n type=\"button\"\n onClick={onCheckout}\n disabled={availableItemCount === 0 || isLoading || !allowCheckout}\n className=\"bg-surface-invert shadow-button transition-all duration-200 ease-in-out enabled:hover:bg-surface-invert-hover enabled:hover:shadow-button-hover enabled:hover:-translate-y-px relative w-full mt-2.5 px-4 py-2.5 min-h-11 text-text-invert rounded-full text-[0.875rem] font-semibold flex items-center justify-center gap-1.5 cursor-pointer overflow-hidden disabled:opacity-50 disabled:cursor-not-allowed\"\n aria-label={`Checkout with ${totalQuantity} items`}\n >\n {isLoading ? (\n 'Loading...'\n ) : (\n <>\n Checkout with {totalQuantity}{' '}\n {totalQuantity === 1 ? 'product' : 'products'}\n <svg\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2.5\"\n aria-hidden=\"true\"\n >\n <title>Checkout</title>\n <path d=\"M5 12h14M12 5l7 7-7 7\" />\n </svg>\n </>\n )}\n </button>\n </div>\n );\n}\n","export const XIcon = () => (\n <svg\n width=\"14\"\n height=\"14\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n >\n <title>Remove</title>\n <line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\" />\n <line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\" />\n </svg>\n);\n","import type { ButtonHTMLAttributes, ReactNode } from 'react';\nimport { cn } from '../lib/utils.js';\n\nexport interface StepButtonProps\n extends ButtonHTMLAttributes<HTMLButtonElement> {\n children: ReactNode;\n}\n\nconst baseClass =\n 'w-8 h-8 p-0 flex items-center justify-center bg-surface-tertiary border border-border rounded-sm text-text-tertiary cursor-pointer transition-all duration-150 hover:bg-surface-disabled hover:border-border-strong hover:text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed';\n\nexport function StepButton({\n children,\n className,\n ...props\n}: StepButtonProps) {\n return (\n <button\n type=\"button\"\n className={className ? cn(baseClass, className) : baseClass}\n {...props}\n >\n {children}\n </button>\n );\n}","import type React from 'react';\nimport { useEffect, useRef, useState } from 'react';\nimport { CheckIcon } from './icons/check-icon.js';\nimport { SpinnerIcon } from './icons/spinner-icon.js';\nimport { StepButton } from './step-button.js';\n\nexport interface QuantitySelectorProps {\n value: number;\n onChange: (value: number) => void | Promise<void>;\n min?: number;\n max?: number;\n className?: string;\n /** When true, updates happen on blur with status indicators. When false, updates are immediate. */\n asyncMode?: boolean;\n /** Test ID for the input element */\n testId?: string;\n}\n\nexport function QuantitySelector({\n value,\n onChange,\n min = 1,\n max,\n className = '',\n asyncMode = false,\n testId\n}: QuantitySelectorProps) {\n const [inputValue, setInputValue] = useState(String(value));\n const [status, setStatus] = useState<'idle' | 'saving' | 'success' | 'error'>(\n 'idle'\n );\n const statusTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n // Clear timeout on unmount\n useEffect(() => {\n return () => {\n if (statusTimeoutRef.current) {\n clearTimeout(statusTimeoutRef.current);\n }\n };\n }, []);\n\n // Sync local state when external value changes\n useEffect(() => {\n setInputValue(String(value));\n }, [value]);\n\n const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n const rawValue = e.target.value;\n\n // Allow empty input temporarily while typing\n if (rawValue === '') {\n setInputValue('');\n return;\n }\n\n // Only allow numeric characters\n if (!/^\\d+$/.test(rawValue)) {\n return;\n }\n\n setInputValue(rawValue);\n\n // In sync mode, update immediately\n if (!asyncMode) {\n const newValue = Number.parseInt(rawValue, 10);\n if (!Number.isNaN(newValue)) {\n const clampedValue = Math.max(\n min,\n max !== undefined ? Math.min(newValue, max) : newValue\n );\n onChange(clampedValue);\n }\n }\n };\n\n const handleBlur = async () => {\n const newQty = Number.parseInt(inputValue, 10);\n\n if (asyncMode) {\n // Async mode: save on blur with status indicators\n if (!Number.isNaN(newQty) && newQty >= min && newQty !== value) {\n const clampedQty = max !== undefined ? Math.min(newQty, max) : newQty;\n setStatus('saving');\n try {\n await onChange(clampedQty);\n setStatus('success');\n statusTimeoutRef.current = setTimeout(() => {\n setStatus((prev) => (prev === 'success' ? 'idle' : prev));\n }, 1500);\n } catch {\n setInputValue(String(value));\n setStatus('error');\n statusTimeoutRef.current = setTimeout(() => {\n setStatus((prev) => (prev === 'error' ? 'idle' : prev));\n }, 3000);\n }\n } else if (Number.isNaN(newQty) || newQty < min) {\n setInputValue(String(value));\n }\n } else {\n // Sync mode: reset to min if empty or invalid\n if (inputValue === '' || Number.isNaN(newQty)) {\n setInputValue(String(min));\n onChange(min);\n }\n }\n };\n\n const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {\n if (e.key === 'Enter') {\n e.currentTarget.blur();\n }\n };\n\n const handleStep = async (delta: number) => {\n const current = Number.parseInt(inputValue, 10);\n const base = Number.isNaN(current) ? value : current;\n const newValue = Math.max(\n min,\n max !== undefined ? Math.min(base + delta, max) : base + delta\n );\n if (newValue === base) return;\n\n setInputValue(String(newValue));\n\n if (asyncMode) {\n if (statusTimeoutRef.current) {\n clearTimeout(statusTimeoutRef.current);\n }\n setStatus('saving');\n try {\n await onChange(newValue);\n setStatus('success');\n statusTimeoutRef.current = setTimeout(() => {\n setStatus((prev) => (prev === 'success' ? 'idle' : prev));\n }, 1500);\n } catch {\n setInputValue(String(value));\n setStatus('error');\n statusTimeoutRef.current = setTimeout(() => {\n setStatus((prev) => (prev === 'error' ? 'idle' : prev));\n }, 3000);\n }\n } else {\n onChange(newValue);\n }\n };\n\n const atMin = value <= min;\n const atMax = max !== undefined && value >= max;\n const isSaving = status === 'saving';\n\n return (\n <span className={`inline-flex items-center gap-0.5 ${className}`}>\n <StepButton\n onClick={() => handleStep(-1)}\n disabled={atMin || isSaving}\n aria-label=\"Decrease quantity\"\n >\n <svg\n width=\"10\"\n height=\"10\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n aria-hidden=\"true\"\n >\n <line x1=\"5\" y1=\"12\" x2=\"19\" y2=\"12\" />\n </svg>\n </StepButton>\n <input\n type=\"text\"\n inputMode=\"numeric\"\n pattern=\"[0-9]*\"\n value={inputValue}\n disabled={isSaving}\n onChange={handleChange}\n onBlur={handleBlur}\n onKeyDown={handleKeyDown}\n data-testid={testId}\n className={`w-8 h-8 px-0.5 py-0.5 text-xs text-center focus:outline-none focus:border-border-focus text-text border border-solid ${\n isSaving\n ? 'border-border bg-surface-tertiary opacity-60'\n : 'border-border'\n }`}\n />\n <StepButton\n onClick={() => handleStep(1)}\n disabled={atMax || isSaving}\n aria-label=\"Increase quantity\"\n >\n <svg\n width=\"10\"\n height=\"10\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n aria-hidden=\"true\"\n >\n <line x1=\"12\" y1=\"5\" x2=\"12\" y2=\"19\" />\n <line x1=\"5\" y1=\"12\" x2=\"19\" y2=\"12\" />\n </svg>\n </StepButton>\n {isSaving && (\n <span className=\"text-text-tertiary ml-0.5\">\n <SpinnerIcon />\n </span>\n )}\n {status === 'success' && (\n <span className=\"text-success ml-0.5\">\n <CheckIcon />\n </span>\n )}\n {status === 'error' && (\n <span className=\"text-error text-[0.6875rem] ml-0.5\">Failed</span>\n )}\n </span>\n );\n}\n","import type { JSX } from 'react';\nimport { formatCurrency } from '../../../lib/formatting.js';\nimport type { CartItem } from '../../../types.js';\nimport { XIcon } from '../../icons/x-icon.js';\nimport { QuantitySelector } from '../../quantity-selector.js';\n\nexport interface CartifactLineItemProps {\n item: CartItem;\n onUpdateQuantity: (id: string, quantity: number) => void | Promise<void>;\n onRemove: (id: string) => void;\n onShowMoreLikeThis: (itemName: string, sku?: string) => void;\n onViewProduct?: (item: CartItem) => void;\n}\n\nexport function CartifactLineItem(props: CartifactLineItemProps) {\n const {\n item,\n onUpdateQuantity,\n onRemove,\n onShowMoreLikeThis,\n onViewProduct\n } = props;\n const poPriceValue = item.poPriceValue;\n const hasPriceMismatch =\n item.status === 'price-mismatch' &&\n poPriceValue !== undefined &&\n poPriceValue > 0;\n const currenciesDiffer =\n item.poPriceCurrencyCode &&\n item.catalogPriceCurrencyCode &&\n item.poPriceCurrencyCode !== item.catalogPriceCurrencyCode;\n const isFavorable =\n hasPriceMismatch &&\n poPriceValue !== undefined &&\n poPriceValue > (item.price ?? 0);\n\n return (\n <div className=\"group flex gap-3 p-2 rounded mb-2 last:mb-0\">\n {item.imageUrl ? (\n <img\n src={item.imageUrl}\n alt={item.name}\n className=\"w-12 h-12 object-cover rounded shrink-0\"\n />\n ) : (\n <div className=\"w-12 h-12 bg-surface-tertiary rounded shrink-0\" />\n )}\n <div className=\"flex-1 min-w-0\">\n <div className=\"flex items-start justify-between gap-2\">\n <div className=\"flex-1 min-w-0\">\n {onViewProduct ? (\n <button\n type=\"button\"\n onClick={() => onViewProduct(item)}\n className=\"text-sm font-medium text-text m-0 truncate bg-transparent border-none cursor-pointer p-0 text-left hover:underline\"\n title={item.name}\n >\n {item.name}\n </button>\n ) : (\n <p className=\"text-sm font-medium text-text m-0 truncate\">\n {item.name}\n </p>\n )}\n <p className=\"text-xs text-text-secondary m-0\">SKU: {item.sku}</p>\n </div>\n <div className=\"flex items-center gap-2 shrink-0\">\n <QuantitySelector\n value={item.quantity}\n onChange={(qty) => onUpdateQuantity(item.id, qty)}\n max={item.availableQuantity}\n asyncMode\n />\n <button\n type=\"button\"\n onClick={() => onRemove(item.id)}\n className=\"p-2 text-text-quaternary hover:text-text-secondary shrink-0\"\n aria-label=\"Remove item\"\n >\n <XIcon />\n </button>\n </div>\n </div>\n\n {/* Price Mismatch Badge */}\n {hasPriceMismatch && !currenciesDiffer && (\n <div\n className={`flex items-center gap-1.5 text-[0.6875rem] px-1.5 py-0.5 rounded mt-1 ${\n isFavorable\n ? 'bg-success-bg text-success-text'\n : 'bg-warning-bg text-warning-text'\n }`}\n >\n <span>\n {isFavorable ? 'Catalog price lower' : 'Catalog price higher'}\n {' · '}\n PO: {formatCurrency(poPriceValue, item.poPriceCurrencyCode)} →\n Catalog:{' '}\n {formatCurrency(item.price ?? 0, item.catalogPriceCurrencyCode)}\n </span>\n </div>\n )}\n\n {item.status === 'unavailable' && (\n <span className=\"inline-block text-[0.6875rem] font-medium px-1.5 py-0.5 rounded mt-1 bg-error/20 text-error-text\">\n Unavailable\n </span>\n )}\n\n {item.status === 'pending' && (\n <span className=\"inline-block text-[0.6875rem] font-medium px-1.5 py-0.5 rounded mt-1 bg-warning/20 text-warning-text\">\n Pending\n </span>\n )}\n\n <div className=\"flex items-center justify-between mt-2\">\n <div className=\"flex items-center gap-1.5\">\n <CartifactActionButton\n onClick={() => onShowMoreLikeThis(item.name, item.sku)}\n />\n </div>\n {item.price !== undefined && (\n <span className=\"text-sm font-semibold text-text\">\n {formatCurrency(\n item.price * item.quantity,\n item.catalogPriceCurrencyCode\n )}\n </span>\n )}\n </div>\n </div>\n </div>\n );\n}\n\nfunction CartifactActionButton(props: JSX.IntrinsicElements['button']) {\n return (\n <button\n type=\"button\"\n className=\"text-xs min-h-9 px-2.5 py-1.5 rounded transition-opacity text-text-secondary bg-surface-tertiary hover:bg-surface-disabled hover:text-text opacity-0 group-hover:opacity-100\"\n {...props}\n >\n Show more like this\n </button>\n );\n}\n","import type { ButtonHTMLAttributes, ReactNode } from 'react';\nimport { cn } from '../../../lib/utils.js';\n\nexport interface PanelActionButtonProps\n extends ButtonHTMLAttributes<HTMLButtonElement> {\n children: ReactNode;\n}\n\nconst baseClass =\n 'flex items-center gap-1 min-h-11 px-3 py-1 text-[0.6875rem] font-medium text-text bg-surface-secondary border border-border-focus/20 rounded-md hover:bg-surface-tertiary hover:border-border-focus/35 transition-all whitespace-nowrap';\n\nexport function PanelActionButton({\n children,\n className,\n ...props\n}: PanelActionButtonProps) {\n return (\n <button\n type=\"button\"\n className={className ? cn(baseClass, className) : baseClass}\n {...props}\n >\n {children}\n </button>\n );\n}","import { useEffect, useRef, useState } from 'react';\nimport { PanelActionButton } from './panel-action-button.js';\n\nexport interface CartifactNewOrderProps {\n onNewOrder: () => void;\n}\n\nexport function CartifactNewOrder({ onNewOrder }: CartifactNewOrderProps) {\n const [confirmingReset, setConfirmingReset] = useState(false);\n const resetTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(\n undefined\n );\n\n const handleNewOrderClick = () => {\n if (!confirmingReset) {\n setConfirmingReset(true);\n resetTimerRef.current = setTimeout(() => setConfirmingReset(false), 3000);\n }\n };\n\n const handleConfirmReset = () => {\n if (resetTimerRef.current) clearTimeout(resetTimerRef.current);\n setConfirmingReset(false);\n onNewOrder();\n };\n\n const handleCancelReset = () => {\n if (resetTimerRef.current) clearTimeout(resetTimerRef.current);\n setConfirmingReset(false);\n };\n\n useEffect(() => {\n return () => {\n if (resetTimerRef.current) clearTimeout(resetTimerRef.current);\n };\n }, []);\n\n if (confirmingReset) {\n return (\n <span className=\"flex items-center gap-1.5 text-[0.6875rem] animate-[fadeIn_0.15s_ease]\">\n <span className=\"text-text-tertiary font-medium\">Reset?</span>\n <button\n type=\"button\"\n onClick={handleConfirmReset}\n className=\"min-h-11 min-w-11 px-3 py-1 text-[0.6875rem] font-semibold text-error-text bg-error-bg border border-error/30 rounded hover:bg-error/20 transition-all\"\n >\n Yes\n </button>\n <button\n type=\"button\"\n onClick={handleCancelReset}\n className=\"min-h-11 min-w-11 px-3 py-1 text-[0.6875rem] font-semibold text-text-tertiary bg-surface-secondary border border-border rounded hover:bg-surface-tertiary transition-all\"\n >\n No\n </button>\n </span>\n );\n }\n\n return (\n <PanelActionButton onClick={handleNewOrderClick} title=\"Start a new order\">\n <svg\n width=\"14\"\n height=\"14\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n aria-hidden=\"true\"\n >\n <path d=\"M12 5v14M5 12h14\" />\n </svg>\n New Order\n </PanelActionButton>\n );\n}\n","export const OrderListIcon = () => (\n <svg\n width=\"48\"\n height=\"48\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <title>Order list</title>\n {/* Clipboard body */}\n <path d=\"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2\" />\n {/* Clipboard tab */}\n <rect x=\"8\" y=\"2\" width=\"8\" height=\"4\" rx=\"1\" />\n {/* List lines */}\n <line x1=\"9\" y1=\"12\" x2=\"15\" y2=\"12\" />\n <line x1=\"9\" y1=\"16\" x2=\"13\" y2=\"16\" />\n </svg>\n);\n","import { MaximizeIcon } from '../../icons/maximize-icon.js';\nimport { MinimizeIcon } from '../../icons/minimize-icon.js';\nimport { OrderListIcon } from '../../icons/order-list-icon.js';\nimport { CartifactNewOrder } from './cartifact-new-order.js';\nimport { PanelActionButton } from './panel-action-button.js';\n\nexport interface EmptyCartifactProps {\n className?: string;\n onNewOrder?: () => void;\n onExpand?: () => void;\n onMinimize?: () => void;\n}\n\nexport function EmptyCartifact({\n className = '',\n onNewOrder,\n onExpand,\n onMinimize\n}: EmptyCartifactProps) {\n const hasHeaderButtons = onNewOrder || onExpand || onMinimize;\n return (\n <div\n className={`rounded-lg flex flex-col h-full bg-surface-secondary relative ${className}`}\n >\n {hasHeaderButtons && (\n <div className=\"absolute top-0 right-0 px-4 py-3 z-10 flex items-center gap-2\">\n {onNewOrder && <CartifactNewOrder onNewOrder={onNewOrder} />}\n {onExpand && (\n <PanelActionButton onClick={onExpand} aria-label=\"Expand\">\n <MaximizeIcon size={14} />\n Expand\n </PanelActionButton>\n )}\n {onMinimize && (\n <PanelActionButton onClick={onMinimize} aria-label=\"Minimize\">\n <MinimizeIcon size={14} />\n Minimize\n </PanelActionButton>\n )}\n </div>\n )}\n <div className=\"flex flex-col flex-1 items-center justify-center gap-4 py-3 px-8\">\n <div className=\"flex items-center justify-center w-16 h-16 rounded-[14px] p-1 text-text\">\n <OrderListIcon />\n </div>\n <h3 className=\"m-0 text-base font-semibold text-text\">\n Your cart will appear here\n </h3>\n {/* Balances content below heading to match left panel's description+badges */}\n <div className=\"h-[50px]\" aria-hidden=\"true\" />\n </div>\n {/* Matches ChatInput height for vertical centering alignment with left panel */}\n <div className=\"shrink-0 h-[67px]\" />\n </div>\n );\n}\n","const reduxImpl = (reducer, initial) => (set, _get, api) => {\n api.dispatch = (action) => {\n set((state) => reducer(state, action), false, action);\n return action;\n };\n api.dispatchFromDevtools = true;\n return { dispatch: (...args) => api.dispatch(...args), ...initial };\n};\nconst redux = reduxImpl;\n\nconst shouldDispatchFromDevtools = (api) => !!api.dispatchFromDevtools && typeof api.dispatch === \"function\";\nconst trackedConnections = /* @__PURE__ */ new Map();\nconst getTrackedConnectionState = (name) => {\n const api = trackedConnections.get(name);\n if (!api) return {};\n return Object.fromEntries(\n Object.entries(api.stores).map(([key, api2]) => [key, api2.getState()])\n );\n};\nconst extractConnectionInformation = (store, extensionConnector, options) => {\n if (store === void 0) {\n return {\n type: \"untracked\",\n connection: extensionConnector.connect(options)\n };\n }\n const existingConnection = trackedConnections.get(options.name);\n if (existingConnection) {\n return { type: \"tracked\", store, ...existingConnection };\n }\n const newConnection = {\n connection: extensionConnector.connect(options),\n stores: {}\n };\n trackedConnections.set(options.name, newConnection);\n return { type: \"tracked\", store, ...newConnection };\n};\nconst removeStoreFromTrackedConnections = (name, store) => {\n if (store === void 0) return;\n const connectionInfo = trackedConnections.get(name);\n if (!connectionInfo) return;\n delete connectionInfo.stores[store];\n if (Object.keys(connectionInfo.stores).length === 0) {\n trackedConnections.delete(name);\n }\n};\nconst findCallerName = (stack) => {\n var _a, _b;\n if (!stack) return void 0;\n const traceLines = stack.split(\"\\n\");\n const apiSetStateLineIndex = traceLines.findIndex(\n (traceLine) => traceLine.includes(\"api.setState\")\n );\n if (apiSetStateLineIndex < 0) return void 0;\n const callerLine = ((_a = traceLines[apiSetStateLineIndex + 1]) == null ? void 0 : _a.trim()) || \"\";\n return (_b = /.+ (.+) .+/.exec(callerLine)) == null ? void 0 : _b[1];\n};\nconst devtoolsImpl = (fn, devtoolsOptions = {}) => (set, get, api) => {\n const { enabled, anonymousActionType, store, ...options } = devtoolsOptions;\n let extensionConnector;\n try {\n extensionConnector = (enabled != null ? enabled : (import.meta.env ? import.meta.env.MODE : void 0) !== \"production\") && window.__REDUX_DEVTOOLS_EXTENSION__;\n } catch (e) {\n }\n if (!extensionConnector) {\n return fn(set, get, api);\n }\n const { connection, ...connectionInformation } = extractConnectionInformation(store, extensionConnector, options);\n let isRecording = true;\n api.setState = ((state, replace, nameOrAction) => {\n const r = set(state, replace);\n if (!isRecording) return r;\n const action = nameOrAction === void 0 ? {\n type: anonymousActionType || findCallerName(new Error().stack) || \"anonymous\"\n } : typeof nameOrAction === \"string\" ? { type: nameOrAction } : nameOrAction;\n if (store === void 0) {\n connection == null ? void 0 : connection.send(action, get());\n return r;\n }\n connection == null ? void 0 : connection.send(\n {\n ...action,\n type: `${store}/${action.type}`\n },\n {\n ...getTrackedConnectionState(options.name),\n [store]: api.getState()\n }\n );\n return r;\n });\n api.devtools = {\n cleanup: () => {\n if (connection && typeof connection.unsubscribe === \"function\") {\n connection.unsubscribe();\n }\n removeStoreFromTrackedConnections(options.name, store);\n }\n };\n const setStateFromDevtools = (...a) => {\n const originalIsRecording = isRecording;\n isRecording = false;\n set(...a);\n isRecording = originalIsRecording;\n };\n const initialState = fn(api.setState, get, api);\n if (connectionInformation.type === \"untracked\") {\n connection == null ? void 0 : connection.init(initialState);\n } else {\n connectionInformation.stores[connectionInformation.store] = api;\n connection == null ? void 0 : connection.init(\n Object.fromEntries(\n Object.entries(connectionInformation.stores).map(([key, store2]) => [\n key,\n key === connectionInformation.store ? initialState : store2.getState()\n ])\n )\n );\n }\n if (shouldDispatchFromDevtools(api)) {\n let didWarnAboutReservedActionType = false;\n const originalDispatch = api.dispatch;\n api.dispatch = (...args) => {\n if ((import.meta.env ? import.meta.env.MODE : void 0) !== \"production\" && args[0].type === \"__setState\" && !didWarnAboutReservedActionType) {\n console.warn(\n '[zustand devtools middleware] \"__setState\" action type is reserved to set state from the devtools. Avoid using it.'\n );\n didWarnAboutReservedActionType = true;\n }\n originalDispatch(...args);\n };\n }\n connection.subscribe((message) => {\n var _a;\n switch (message.type) {\n case \"ACTION\":\n if (typeof message.payload !== \"string\") {\n console.error(\n \"[zustand devtools middleware] Unsupported action format\"\n );\n return;\n }\n return parseJsonThen(\n message.payload,\n (action) => {\n if (action.type === \"__setState\") {\n if (store === void 0) {\n setStateFromDevtools(action.state);\n return;\n }\n if (Object.keys(action.state).length !== 1) {\n console.error(\n `\n [zustand devtools middleware] Unsupported __setState action format.\n When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),\n and value of this only key should be a state object. Example: { \"type\": \"__setState\", \"state\": { \"abc123Store\": { \"foo\": \"bar\" } } }\n `\n );\n }\n const stateFromDevtools = action.state[store];\n if (stateFromDevtools === void 0 || stateFromDevtools === null) {\n return;\n }\n if (JSON.stringify(api.getState()) !== JSON.stringify(stateFromDevtools)) {\n setStateFromDevtools(stateFromDevtools);\n }\n return;\n }\n if (shouldDispatchFromDevtools(api)) {\n api.dispatch(action);\n }\n }\n );\n case \"DISPATCH\":\n switch (message.payload.type) {\n case \"RESET\":\n setStateFromDevtools(initialState);\n if (store === void 0) {\n return connection == null ? void 0 : connection.init(api.getState());\n }\n return connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));\n case \"COMMIT\":\n if (store === void 0) {\n connection == null ? void 0 : connection.init(api.getState());\n return;\n }\n return connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));\n case \"ROLLBACK\":\n return parseJsonThen(message.state, (state) => {\n if (store === void 0) {\n setStateFromDevtools(state);\n connection == null ? void 0 : connection.init(api.getState());\n return;\n }\n setStateFromDevtools(state[store]);\n connection == null ? void 0 : connection.init(getTrackedConnectionState(options.name));\n });\n case \"JUMP_TO_STATE\":\n case \"JUMP_TO_ACTION\":\n return parseJsonThen(message.state, (state) => {\n if (store === void 0) {\n setStateFromDevtools(state);\n return;\n }\n if (JSON.stringify(api.getState()) !== JSON.stringify(state[store])) {\n setStateFromDevtools(state[store]);\n }\n });\n case \"IMPORT_STATE\": {\n const { nextLiftedState } = message.payload;\n const lastComputedState = (_a = nextLiftedState.computedStates.slice(-1)[0]) == null ? void 0 : _a.state;\n if (!lastComputedState) return;\n if (store === void 0) {\n setStateFromDevtools(lastComputedState);\n } else {\n setStateFromDevtools(lastComputedState[store]);\n }\n connection == null ? void 0 : connection.send(\n null,\n // FIXME no-any\n nextLiftedState\n );\n return;\n }\n case \"PAUSE_RECORDING\":\n return isRecording = !isRecording;\n }\n return;\n }\n });\n return initialState;\n};\nconst devtools = devtoolsImpl;\nconst parseJsonThen = (stringified, fn) => {\n let parsed;\n try {\n parsed = JSON.parse(stringified);\n } catch (e) {\n console.error(\n \"[zustand devtools middleware] Could not parse the received json\",\n e\n );\n }\n if (parsed !== void 0) fn(parsed);\n};\n\nconst subscribeWithSelectorImpl = (fn) => (set, get, api) => {\n const origSubscribe = api.subscribe;\n api.subscribe = ((selector, optListener, options) => {\n let listener = selector;\n if (optListener) {\n const equalityFn = (options == null ? void 0 : options.equalityFn) || Object.is;\n let currentSlice = selector(api.getState());\n listener = (state) => {\n const nextSlice = selector(state);\n if (!equalityFn(currentSlice, nextSlice)) {\n const previousSlice = currentSlice;\n optListener(currentSlice = nextSlice, previousSlice);\n }\n };\n if (options == null ? void 0 : options.fireImmediately) {\n optListener(currentSlice, currentSlice);\n }\n }\n return origSubscribe(listener);\n });\n const initialState = fn(set, get, api);\n return initialState;\n};\nconst subscribeWithSelector = subscribeWithSelectorImpl;\n\nfunction combine(initialState, create) {\n return (...args) => Object.assign({}, initialState, create(...args));\n}\n\nfunction createJSONStorage(getStorage, options) {\n let storage;\n try {\n storage = getStorage();\n } catch (e) {\n return;\n }\n const persistStorage = {\n getItem: (name) => {\n var _a;\n const parse = (str2) => {\n if (str2 === null) {\n return null;\n }\n return JSON.parse(str2, options == null ? void 0 : options.reviver);\n };\n const str = (_a = storage.getItem(name)) != null ? _a : null;\n if (str instanceof Promise) {\n return str.then(parse);\n }\n return parse(str);\n },\n setItem: (name, newValue) => storage.setItem(name, JSON.stringify(newValue, options == null ? void 0 : options.replacer)),\n removeItem: (name) => storage.removeItem(name)\n };\n return persistStorage;\n}\nconst toThenable = (fn) => (input) => {\n try {\n const result = fn(input);\n if (result instanceof Promise) {\n return result;\n }\n return {\n then(onFulfilled) {\n return toThenable(onFulfilled)(result);\n },\n catch(_onRejected) {\n return this;\n }\n };\n } catch (e) {\n return {\n then(_onFulfilled) {\n return this;\n },\n catch(onRejected) {\n return toThenable(onRejected)(e);\n }\n };\n }\n};\nconst persistImpl = (config, baseOptions) => (set, get, api) => {\n let options = {\n storage: createJSONStorage(() => window.localStorage),\n partialize: (state) => state,\n version: 0,\n merge: (persistedState, currentState) => ({\n ...currentState,\n ...persistedState\n }),\n ...baseOptions\n };\n let hasHydrated = false;\n let hydrationVersion = 0;\n const hydrationListeners = /* @__PURE__ */ new Set();\n const finishHydrationListeners = /* @__PURE__ */ new Set();\n let storage = options.storage;\n if (!storage) {\n return config(\n (...args) => {\n console.warn(\n `[zustand persist middleware] Unable to update item '${options.name}', the given storage is currently unavailable.`\n );\n set(...args);\n },\n get,\n api\n );\n }\n const setItem = () => {\n const state = options.partialize({ ...get() });\n return storage.setItem(options.name, {\n state,\n version: options.version\n });\n };\n const savedSetState = api.setState;\n api.setState = (state, replace) => {\n savedSetState(state, replace);\n return setItem();\n };\n const configResult = config(\n (...args) => {\n set(...args);\n return setItem();\n },\n get,\n api\n );\n api.getInitialState = () => configResult;\n let stateFromStorage;\n const hydrate = () => {\n var _a, _b;\n if (!storage) return;\n const currentVersion = ++hydrationVersion;\n hasHydrated = false;\n hydrationListeners.forEach((cb) => {\n var _a2;\n return cb((_a2 = get()) != null ? _a2 : configResult);\n });\n const postRehydrationCallback = ((_b = options.onRehydrateStorage) == null ? void 0 : _b.call(options, (_a = get()) != null ? _a : configResult)) || void 0;\n return toThenable(storage.getItem.bind(storage))(options.name).then((deserializedStorageValue) => {\n if (deserializedStorageValue) {\n if (typeof deserializedStorageValue.version === \"number\" && deserializedStorageValue.version !== options.version) {\n if (options.migrate) {\n const migration = options.migrate(\n deserializedStorageValue.state,\n deserializedStorageValue.version\n );\n if (migration instanceof Promise) {\n return migration.then((result) => [true, result]);\n }\n return [true, migration];\n }\n console.error(\n `State loaded from storage couldn't be migrated since no migrate function was provided`\n );\n } else {\n return [false, deserializedStorageValue.state];\n }\n }\n return [false, void 0];\n }).then((migrationResult) => {\n var _a2;\n if (currentVersion !== hydrationVersion) {\n return;\n }\n const [migrated, migratedState] = migrationResult;\n stateFromStorage = options.merge(\n migratedState,\n (_a2 = get()) != null ? _a2 : configResult\n );\n set(stateFromStorage, true);\n if (migrated) {\n return setItem();\n }\n }).then(() => {\n if (currentVersion !== hydrationVersion) {\n return;\n }\n postRehydrationCallback == null ? void 0 : postRehydrationCallback(stateFromStorage, void 0);\n stateFromStorage = get();\n hasHydrated = true;\n finishHydrationListeners.forEach((cb) => cb(stateFromStorage));\n }).catch((e) => {\n if (currentVersion !== hydrationVersion) {\n return;\n }\n postRehydrationCallback == null ? void 0 : postRehydrationCallback(void 0, e);\n });\n };\n api.persist = {\n setOptions: (newOptions) => {\n options = {\n ...options,\n ...newOptions\n };\n if (newOptions.storage) {\n storage = newOptions.storage;\n }\n },\n clearStorage: () => {\n storage == null ? void 0 : storage.removeItem(options.name);\n },\n getOptions: () => options,\n rehydrate: () => hydrate(),\n hasHydrated: () => hasHydrated,\n onHydrate: (cb) => {\n hydrationListeners.add(cb);\n return () => {\n hydrationListeners.delete(cb);\n };\n },\n onFinishHydration: (cb) => {\n finishHydrationListeners.add(cb);\n return () => {\n finishHydrationListeners.delete(cb);\n };\n }\n };\n if (!options.skipHydration) {\n hydrate();\n }\n return stateFromStorage || configResult;\n};\nconst persist = persistImpl;\n\nfunction ssrSafe(config, isSSR = typeof window === \"undefined\") {\n return (set, get, api) => {\n if (!isSSR) {\n return config(set, get, api);\n }\n const ssrSet = () => {\n throw new Error(\"Cannot set state of Zustand store in SSR\");\n };\n api.setState = ssrSet;\n return config(ssrSet, get, api);\n };\n}\n\nexport { combine, createJSONStorage, devtools, persist, redux, subscribeWithSelector, ssrSafe as unstable_ssrSafe };\n","import type { StateCreator } from 'zustand';\nimport type { Cart, Checkout } from '../../lib/bigcommerce/storefront/types.js';\nimport type { PurchaseOrderStore } from '../purchase-order-store.js';\n\n/**\n * BigCommerce session state fetched from the API.\n * This data is not persisted to localStorage - it's fetched fresh each session.\n */\nexport interface BcSessionSlice {\n bcSession: {\n bcCart: Cart | null;\n checkout: Checkout | null;\n isLoading: boolean;\n productPaths: Record<number, string>;\n };\n setBcCart: (cart: Cart | null) => void;\n setCheckout: (checkout: Checkout | null) => void;\n setIsLoading: (loading: boolean) => void;\n setProductPaths: (paths: Record<number, string>) => void;\n clearBcSession: () => void;\n}\n\nexport const initialBcSessionState: BcSessionSlice['bcSession'] = {\n bcCart: null,\n checkout: null,\n isLoading: false,\n productPaths: {}\n};\n\nexport const createBcSessionSlice: StateCreator<\n PurchaseOrderStore,\n [['zustand/devtools', never], ['zustand/persist', unknown]],\n [],\n BcSessionSlice\n> = (set) => ({\n bcSession: { ...initialBcSessionState },\n setBcCart: (bcCart) =>\n set(\n (state) => ({ bcSession: { ...state.bcSession, bcCart } }),\n false,\n 'bcSession/setBcCart'\n ),\n setCheckout: (checkout) =>\n set(\n (state) => ({ bcSession: { ...state.bcSession, checkout } }),\n false,\n 'bcSession/setCheckout'\n ),\n setIsLoading: (isLoading) =>\n set(\n (state) => ({ bcSession: { ...state.bcSession, isLoading } }),\n false,\n 'bcSession/setIsLoading'\n ),\n setProductPaths: (productPaths) =>\n set(\n (state) => ({ bcSession: { ...state.bcSession, productPaths } }),\n false,\n 'bcSession/setProductPaths'\n ),\n clearBcSession: () =>\n set(\n () => ({ bcSession: { ...initialBcSessionState } }),\n false,\n 'bcSession/clearBcSession'\n )\n});\n","import { initGraphQLTada } from 'gql.tada';\nimport type { introspection } from './graphql-env.gen.d.ts';\n\nexport const graphql = initGraphQLTada<{\n introspection: introspection;\n}>();\n\nexport type { FragmentOf, ResultOf, VariablesOf } from 'gql.tada';\nexport { readFragment } from 'gql.tada';\n","import { graphql } from './graphql.js';\n\nexport const UserAuthorizationFragment = graphql(`\n fragment UserAuthorizationFragment on UserAuthorization {\n result {\n token\n }\n }\n`);\n\nexport const AuthorizationMutation = graphql(\n `\n mutation Authorization($authData: UserAuthType!) {\n authorization(authData: $authData) {\n ...UserAuthorizationFragment\n }\n }\n`,\n [UserAuthorizationFragment]\n);\n\nexport const UserFragment = graphql(`\n fragment UserFragment on UserType {\n companyInfo {\n companyId\n }\n }\n`);\n\nexport const CurrentUserQuery = graphql(\n `\n query CurrentUser {\n currentUser {\n ...UserFragment\n }\n }\n`,\n [UserFragment]\n);\n\nexport const CompanyAddressFragment = graphql(`\n fragment CompanyAddressFragment on AddressType {\n id\n firstName\n lastName\n company\n addressLine1\n addressLine2\n city\n state\n zipCode\n country\n countryCode\n phoneNumber\n isDefaultShipping\n isDefaultBilling\n isShipping\n isBilling\n label\n }\n`);\n\nexport const CompanyAddressesQuery = graphql(\n `\n query CompanyAddressesQuery(\n $companyId: Int!\n $first: Int\n $offset: Int\n ) {\n addresses(\n companyId: $companyId\n first: $first\n offset: $offset\n ) {\n totalCount\n edges {\n node {\n ...CompanyAddressFragment\n }\n }\n }\n }\n`,\n [CompanyAddressFragment]\n);\n\nexport const CheckoutResultFragment = graphql(`\n fragment CheckoutResultFragment on CheckoutLoginResultType {\n redirectUrl\n }\n`);\n\nexport const CheckoutLoginMutation = graphql(\n `\n mutation CheckoutLoginMutation(\n $cartData: CheckoutLoginType!\n ) {\n checkoutLogin(cartData: $cartData) {\n result {\n redirectUrl\n }\n }\n }\n`\n);\n","import { initGraphQLTada } from 'gql.tada';\nimport type { introspection } from './graphql-env.gen.d.ts';\n\nexport const graphql = initGraphQLTada<{\n introspection: introspection;\n scalars: {\n DateTime: string;\n JSON: unknown;\n JSONObject: Record<string, unknown>;\n BigDecimal: number;\n };\n}>();\n\nexport type { FragmentOf, ResultOf, VariablesOf } from 'gql.tada';\nexport { readFragment } from 'gql.tada';\n","// BigCommerce GraphQL Storefront API Queries and Mutations\nimport { graphql } from './graphql.js';\n\nexport const CartFragment = graphql(`\n fragment CartFields on Cart {\n id\n entityId\n lineItems {\n physicalItems {\n entityId\n productEntityId\n variantEntityId\n quantity\n name\n sku\n originalPrice {\n value\n currencyCode\n }\n listPrice {\n value\n currencyCode\n }\n extendedListPrice {\n value\n currencyCode\n }\n extendedSalePrice {\n value\n currencyCode\n }\n imageUrl\n }\n digitalItems {\n entityId\n productEntityId\n variantEntityId\n quantity\n name\n sku\n originalPrice {\n value\n currencyCode\n }\n listPrice {\n value\n currencyCode\n }\n extendedListPrice {\n value\n currencyCode\n }\n extendedSalePrice {\n value\n currencyCode\n }\n imageUrl\n }\n }\n amount {\n value\n currencyCode\n }\n baseAmount {\n value\n currencyCode\n }\n discountedAmount {\n value\n currencyCode\n }\n createdAt {\n utc\n }\n updatedAt {\n utc\n }\n }\n`);\n\nexport const GetCartQuery = graphql(\n `\n query GetCart($cartEntityId: String) {\n site {\n cart(entityId: $cartEntityId) {\n ...CartFields\n }\n }\n }\n`,\n [CartFragment]\n);\n\nexport const CreateCartMutation = graphql(\n `\n mutation CreateCart($input: CreateCartInput!) {\n cart {\n createCart(input: $input) {\n cart {\n ...CartFields\n }\n }\n }\n }\n`,\n [CartFragment]\n);\n\nexport const AddCartLineItemsMutation = graphql(\n `\n mutation AddCartLineItems($input: AddCartLineItemsInput!) {\n cart {\n addCartLineItems(input: $input) {\n cart {\n ...CartFields\n }\n }\n }\n }\n`,\n [CartFragment]\n);\n\nexport const UpdateCartLineItemMutation = graphql(\n `\n mutation UpdateCartLineItem($input: UpdateCartLineItemInput!) {\n cart {\n updateCartLineItem(input: $input) {\n cart {\n ...CartFields\n }\n }\n }\n }\n`,\n [CartFragment]\n);\n\nexport const DeleteCartLineItemMutation = graphql(\n `\n mutation DeleteCartLineItem($input: DeleteCartLineItemInput!) {\n cart {\n deleteCartLineItem(input: $input) {\n cart {\n ...CartFields\n }\n }\n }\n }\n`,\n [CartFragment]\n);\n\nexport const DeleteCartMutation = graphql(`\n mutation DeleteCart($input: DeleteCartInput!) {\n cart {\n deleteCart(input: $input) {\n deletedCartEntityId\n }\n }\n }\n`);\n\nexport const CreateCartRedirectUrlsMutation = graphql(`\n mutation CreateCartRedirectUrls($input: CreateCartRedirectUrlsInput) {\n cart {\n createCartRedirectUrls(input: $input) {\n redirectUrls {\n redirectedCheckoutUrl\n }\n }\n }\n }\n`);\n\nexport const CreateCartMetafieldMutation = graphql(`\n mutation CreateCartMetafield($input: CreateCartMetafieldInput!) {\n cart {\n createCartMetafield(input: $input) {\n metafield {\n id\n entityId\n }\n }\n }\n }\n`);\n\n// Checkout Queries and Mutations\nexport const CheckoutFragment = graphql(`\n fragment CheckoutFields on Checkout {\n entityId\n subtotal {\n value\n currencyCode\n }\n taxTotal {\n value\n currencyCode\n }\n grandTotal {\n value\n currencyCode\n }\n shippingCostTotal {\n value\n currencyCode\n }\n handlingCostTotal {\n value\n currencyCode\n }\n billingAddress {\n firstName\n lastName\n address1\n address2\n city\n stateOrProvince\n stateOrProvinceCode\n countryCode\n postalCode\n phone\n email\n }\n shippingConsignments {\n entityId\n address {\n firstName\n lastName\n address1\n address2\n city\n stateOrProvince\n stateOrProvinceCode\n countryCode\n postalCode\n phone\n email\n }\n availableShippingOptions {\n entityId\n description\n type\n cost {\n value\n currencyCode\n }\n }\n selectedShippingOption {\n entityId\n description\n type\n cost {\n value\n currencyCode\n }\n }\n shippingCost {\n value\n currencyCode\n }\n lineItemIds\n }\n }\n`);\n\nexport const GetCheckoutQuery = graphql(\n `\n query GetCheckout($checkoutEntityId: String) {\n site {\n checkout(entityId: $checkoutEntityId) {\n ...CheckoutFields\n }\n }\n }\n`,\n [CheckoutFragment]\n);\n\nexport const AddCheckoutShippingConsignmentsMutation = graphql(\n `\n mutation AddCheckoutShippingConsignments($input: AddCheckoutShippingConsignmentsInput!) {\n checkout {\n addCheckoutShippingConsignments(input: $input) {\n checkout {\n ...CheckoutFields\n }\n }\n }\n }\n`,\n [CheckoutFragment]\n);\n\nexport const AddCheckoutBillingAddressMutation = graphql(\n `\n mutation AddCheckoutBillingAddressMutation($input: AddCheckoutBillingAddressInput!) {\n checkout {\n addCheckoutBillingAddress(input: $input) {\n checkout {\n ...CheckoutFields\n }\n }\n }\n }\n`,\n [CheckoutFragment]\n);\n\nexport const DeleteCheckoutConsignmentMutation = graphql(\n `\n mutation DeleteCheckoutConsignment($input: DeleteCheckoutConsignmentInput!) {\n checkout {\n deleteCheckoutConsignment(input: $input) {\n checkout {\n ...CheckoutFields\n }\n }\n }\n }\n`,\n [CheckoutFragment]\n);\n\nexport const UpdateCheckoutCustomerMessageMutation = graphql(\n `\n mutation UpdateCheckoutCustomerMessage($input: UpdateCheckoutCustomerMessageInput!) {\n checkout {\n updateCheckoutCustomerMessage(input: $input) {\n checkout {\n ...CheckoutFields\n }\n }\n }\n }\n`,\n [CheckoutFragment]\n);\n\n// Product Variant Details Query\nexport const GetProductVariantDetailsQuery = graphql(`\n query GetProductVariantDetails($entityIds: [Int!], $first: Int = 50) {\n site {\n products(entityIds: $entityIds) {\n edges {\n node {\n entityId\n productOptions(first: $first) {\n edges {\n node {\n entityId\n displayName\n isRequired\n isVariantOption\n ... on MultipleChoiceOption {\n displayStyle\n values(first: $first) {\n edges {\n node {\n entityId\n label\n isDefault\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n variants(first: $first) {\n edges {\n node {\n entityId\n sku\n isPurchasable\n defaultImage {\n urlTemplate\n }\n prices {\n price {\n value\n currencyCode\n }\n }\n inventory {\n aggregated {\n availableToSell\n warningLevel\n }\n }\n options(first: $first) {\n edges {\n node {\n entityId\n displayName\n values(first: 1) {\n edges {\n node {\n entityId\n label\n }\n }\n }\n }\n }\n }\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n }\n }\n }\n }\n`);\n\n// Query for fetching products to display (includes names, prices, images)\nexport const GetProductsForDisplayQuery = graphql(`\n query GetProductsForDisplay($entityIds: [Int!], $first: Int = 50) {\n site {\n products(entityIds: $entityIds) {\n edges {\n node {\n entityId\n name\n sku\n path\n defaultImage {\n urlTemplate\n }\n variants(first: $first) {\n edges {\n node {\n entityId\n sku\n isPurchasable\n defaultImage {\n urlTemplate\n }\n prices {\n price {\n value\n currencyCode\n }\n }\n inventory {\n isInStock\n aggregated {\n availableToSell\n warningLevel\n }\n }\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n }\n }\n }\n }\n`);\n\n// Pagination query for product variants (for display)\nexport const GetProductVariantsForDisplayPageQuery = graphql(`\n query GetProductVariantsForDisplayPage($entityId: Int!, $first: Int = 50, $after: String!) {\n site {\n product(entityId: $entityId) {\n variants(first: $first, after: $after) {\n edges {\n node {\n entityId\n sku\n isPurchasable\n defaultImage {\n urlTemplate\n }\n prices {\n price {\n value\n currencyCode\n }\n }\n inventory {\n isInStock\n aggregated {\n availableToSell\n warningLevel\n }\n }\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n }\n }\n`);\n\nexport const CustomerAddressFragment = graphql(`\n fragment CustomerAddressFields on CustomerAddress {\n entityId\n firstName\n lastName\n address1\n address2\n city\n stateOrProvince\n postalCode\n countryCode\n country\n phone\n }\n`);\n\n// Customer Address Query\nexport const GetCustomerAddressesQuery = graphql(\n `\n query GetCustomerAddresses($first: Int = 50, $after: String) {\n customer {\n entityId\n firstName\n lastName\n email\n addresses(first: $first, after: $after) {\n edges {\n node {\n ...CustomerAddressFields\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n }\n`,\n [CustomerAddressFragment]\n);\n\n// Follow-up pagination queries for fetching additional pages\n\nexport const GetProductVariantsPageQuery = graphql(`\n query GetProductVariantsPage($entityId: Int!, $first: Int = 50, $after: String!) {\n site {\n product(entityId: $entityId) {\n variants(first: $first, after: $after) {\n edges {\n node {\n entityId\n sku\n isPurchasable\n defaultImage {\n urlTemplate\n }\n prices {\n price {\n value\n currencyCode\n }\n }\n inventory {\n aggregated {\n availableToSell\n warningLevel\n }\n }\n options(first: 50) {\n edges {\n node {\n entityId\n displayName\n values(first: 1) {\n edges {\n node {\n entityId\n label\n }\n }\n }\n }\n }\n }\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n }\n }\n`);\n\nexport const GetProductOptionsPageQuery = graphql(`\n query GetProductOptionsPage($entityId: Int!, $first: Int = 50, $after: String!) {\n site {\n product(entityId: $entityId) {\n productOptions(first: $first, after: $after) {\n edges {\n node {\n entityId\n displayName\n isRequired\n isVariantOption\n ... on MultipleChoiceOption {\n displayStyle\n values(first: 50) {\n edges {\n node {\n entityId\n label\n isDefault\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n }\n }\n`);\n\nexport const GetProductPathsQuery = graphql(`\n query GetProductPaths($entityIds: [Int!]) {\n site {\n products(entityIds: $entityIds) {\n edges {\n node {\n entityId\n path\n }\n }\n }\n }\n }\n`);\n\nexport const GetProductOptionValuesPageQuery = graphql(`\n query GetProductOptionValuesPage($entityId: Int!, $optionEntityId: Int!, $first: Int = 50, $after: String!) {\n site {\n product(entityId: $entityId) {\n productOptions(entityIds: [$optionEntityId]) {\n edges {\n node {\n entityId\n displayName\n isRequired\n isVariantOption\n ... on MultipleChoiceOption {\n displayStyle\n values(first: $first, after: $after) {\n edges {\n node {\n entityId\n label\n isDefault\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n }\n }\n }\n }\n }\n }\n`);\n\n// Store Settings Query (used to get storeHash for B2B Edition)\nexport const GetStoreSettingsQuery = graphql(`\n query GetStoreSettings {\n site {\n settings {\n storeHash\n }\n }\n }\n`);\n","import { PO_ADDRESS_ID, PO_BILLING_ADDRESS_ID } from '../../constants.js';\nimport type { Address } from '../../types.js';\nimport { type FragmentOf, readFragment } from './b2b/graphql.js';\nimport { CompanyAddressFragment } from './b2b/queries.js';\nimport { CustomerAddressFragment } from './storefront/queries.js';\nimport type { CustomerAddress } from './storefront/types.js';\n\n/**\n * Convert a B2B company address to the standard CustomerAddress format.\n * Uses negative numeric IDs to avoid collisions with storefront address IDs.\n */\nexport function convertCompanyAddressToCustomerAddress(\n companyAddress: FragmentOf<typeof CompanyAddressFragment>\n): CustomerAddress {\n const address = readFragment(CompanyAddressFragment, companyAddress);\n return {\n source: 'b2b',\n id: `${address.id}`,\n firstName: address.firstName,\n lastName: address.lastName,\n address1: address.addressLine1 ?? '',\n address2: address.addressLine2 || undefined,\n city: address.city,\n stateOrProvince: address.state || undefined,\n postalCode: address.zipCode || undefined,\n countryCode: address.countryCode ?? '',\n country: address.country || undefined,\n phone: address.phoneNumber || undefined,\n isShipping: address.isShipping === 1,\n isBilling: address.isBilling === 1,\n isDefaultShipping: address.isDefaultShipping === 1,\n isDefaultBilling: address.isDefaultBilling === 1,\n label: address.label || undefined\n };\n}\n\nexport function convertCustomerAddressToCustomerAddress(\n customerAddress: FragmentOf<typeof CustomerAddressFragment>,\n index = 0\n): CustomerAddress {\n const address = readFragment(CustomerAddressFragment, customerAddress);\n return {\n source: 'storefront',\n id: `${address.entityId}`,\n firstName: address.firstName,\n lastName: address.lastName,\n address1: address.address1 ?? '',\n address2: address.address2 || undefined,\n city: address.city,\n stateOrProvince: address.stateOrProvince || undefined,\n postalCode: address.postalCode || undefined,\n countryCode: address.countryCode ?? '',\n country: address.country || undefined,\n phone: address.phone || undefined,\n isShipping: true,\n // Unclear how to determine billing vs shipping from storefront address, so default to true for both\n isBilling: true,\n // Just make the first address the default\n isDefaultShipping: index === 0,\n isDefaultBilling: index === 0\n };\n}\n\nexport function convertPoAddressToCustomerAddress(\n addr: Address,\n options: {\n id: typeof PO_ADDRESS_ID | typeof PO_BILLING_ADDRESS_ID;\n }\n): CustomerAddress {\n return {\n source: 'po',\n id: options.id,\n firstName: addr.firstName ?? '',\n lastName: addr.lastName ?? '',\n address1: addr.address1,\n address2: addr.address2,\n city: addr.city ?? '',\n stateOrProvince: addr.stateOrProvince ?? '',\n countryCode: addr.countryCode ?? 'US',\n postalCode: addr.postalCode,\n phone: addr.phone,\n isShipping: options.id === PO_ADDRESS_ID,\n isBilling: options.id === PO_BILLING_ADDRESS_ID,\n isDefaultShipping: false,\n isDefaultBilling: false,\n label: 'PO Address'\n };\n}\n","import type { StateCreator } from 'zustand';\nimport { PO_ADDRESS_ID, PO_BILLING_ADDRESS_ID } from '../../constants.js';\nimport type { CustomerAddress } from '../../lib/bigcommerce/storefront/types.js';\nimport { convertPoAddressToCustomerAddress } from '../../lib/bigcommerce/utils.js';\nimport type { Address, BuyerInfo, ItemWarning } from '../../types.js';\nimport type { PurchaseOrderStore } from '../purchase-order-store.js';\n\nexport interface POPriceInfo {\n productEntityId: number;\n variantEntityId?: number;\n poPrice: number;\n poCurrency: string;\n}\n\nexport interface CartifactSlice {\n cartifact: {\n cartEntityId: string | null;\n poItemPrices: Record<string, POPriceInfo>;\n // PO metadata\n orderId: string | null;\n buyerInfo: BuyerInfo | null;\n shipToAddress: CustomerAddress | null;\n billingAddress: CustomerAddress | null;\n poMetadataSet: boolean;\n itemWarnings: ItemWarning[];\n };\n // Actions\n setCartEntityId: (cartEntityId: string | null) => void;\n setPoItemPrice: (\n productEntityId: number,\n variantEntityId: number | undefined,\n poPrice: number,\n poCurrency: string\n ) => void;\n removePoItemPrice: (\n productEntityId: number,\n variantEntityId?: number\n ) => void;\n clearPoItemPrices: () => void;\n setOrderId: (orderId: string | null) => void;\n setBuyerInfo: (buyerInfo: BuyerInfo | null) => void;\n setShipToAddress: (address: Address | null) => void;\n setBillingAddress: (address: Address | null) => void;\n setPoMetadataSet: (set: boolean) => void;\n setItemWarnings: (warnings: ItemWarning[]) => void;\n removeItemWarning: (warning: ItemWarning) => void;\n clearCartifact: () => void;\n}\n\nfunction makePoItemPriceKey(\n productEntityId: number,\n variantEntityId?: number\n): string {\n return `${productEntityId}-${variantEntityId}`;\n}\n\nexport const initialCartifactState: CartifactSlice['cartifact'] = {\n cartEntityId: null,\n poItemPrices: {},\n orderId: null,\n buyerInfo: null,\n shipToAddress: null,\n billingAddress: null,\n poMetadataSet: false,\n itemWarnings: []\n};\n\nexport const createCartifactSlice: StateCreator<\n PurchaseOrderStore,\n [['zustand/devtools', never], ['zustand/persist', unknown]],\n [],\n CartifactSlice\n> = (set) => ({\n cartifact: { ...initialCartifactState },\n setCartEntityId: (cartEntityId) =>\n set(\n (state) => ({ cartifact: { ...state.cartifact, cartEntityId } }),\n false,\n 'cartifact/setCartEntityId'\n ),\n setPoItemPrice: (productEntityId, variantEntityId, poPrice, poCurrency) =>\n set(\n (state) => ({\n cartifact: {\n ...state.cartifact,\n poItemPrices: {\n ...state.cartifact.poItemPrices,\n [makePoItemPriceKey(productEntityId, variantEntityId)]: {\n productEntityId,\n variantEntityId,\n poPrice,\n poCurrency\n }\n }\n }\n }),\n false,\n 'cartifact/setPoItemPrice'\n ),\n removePoItemPrice: (productEntityId, variantEntityId) =>\n set(\n (state) => {\n const newPrices = { ...state.cartifact.poItemPrices };\n delete newPrices[makePoItemPriceKey(productEntityId, variantEntityId)];\n return { cartifact: { ...state.cartifact, poItemPrices: newPrices } };\n },\n false,\n 'cartifact/removePoItemPrice'\n ),\n clearPoItemPrices: () =>\n set(\n (state) => ({ cartifact: { ...state.cartifact, poItemPrices: {} } }),\n false,\n 'cartifact/clearPoItemPrices'\n ),\n setOrderId: (orderId) =>\n set(\n (state) => ({ cartifact: { ...state.cartifact, orderId } }),\n false,\n 'cartifact/setOrderId'\n ),\n setBuyerInfo: (buyerInfo) =>\n set(\n (state) => ({ cartifact: { ...state.cartifact, buyerInfo } }),\n false,\n 'cartifact/setBuyerInfo'\n ),\n setShipToAddress: (shipToAddress) =>\n set(\n (state) => ({\n cartifact: {\n ...state.cartifact,\n shipToAddress: shipToAddress\n ? convertPoAddressToCustomerAddress(shipToAddress, {\n id: PO_ADDRESS_ID\n })\n : null\n }\n }),\n false,\n 'cartifact/setShipToAddress'\n ),\n setBillingAddress: (billingAddress) =>\n set(\n (state) => ({\n cartifact: {\n ...state.cartifact,\n billingAddress: billingAddress\n ? convertPoAddressToCustomerAddress(billingAddress, {\n id: PO_BILLING_ADDRESS_ID\n })\n : null\n }\n }),\n false,\n 'cartifact/setBillingAddress'\n ),\n setPoMetadataSet: (poMetadataSet) =>\n set(\n (state) => ({ cartifact: { ...state.cartifact, poMetadataSet } }),\n false,\n 'cartifact/setPoMetadataSet'\n ),\n setItemWarnings: (itemWarnings) =>\n set(\n (state) => ({ cartifact: { ...state.cartifact, itemWarnings } }),\n false,\n 'cartifact/setItemWarnings'\n ),\n removeItemWarning: (warning) =>\n set(\n (state) => ({\n cartifact: {\n ...state.cartifact,\n itemWarnings: state.cartifact.itemWarnings.filter(\n (w) =>\n w.productSku !== warning.productSku ||\n w.productName !== warning.productName ||\n w.status !== warning.status\n )\n }\n }),\n false,\n 'cartifact/removeItemWarning'\n ),\n clearCartifact: () =>\n set(\n (state) => ({\n cartifact: {\n ...state.cartifact,\n cartEntityId: null,\n poItemPrices: {},\n orderId: null,\n buyerInfo: null,\n shipToAddress: null,\n billingAddress: null,\n poMetadataSet: false,\n itemWarnings: []\n }\n }),\n false,\n 'cartifact/clearCartifact'\n )\n});\n","import type { UIMessage } from 'ai';\nimport type { StateCreator } from 'zustand';\nimport type { PurchaseOrderStore } from '../purchase-order-store.js';\n\nexport interface ChatSlice {\n chat: {\n messages: UIMessage[];\n input: string;\n threadId: string | null;\n toolCallErrors: Record<string, string>;\n };\n // Actions\n setMessages: (messages: UIMessage[]) => void;\n addMessage: (message: UIMessage) => void;\n setInput: (input: string) => void;\n setThreadId: (threadId: string | null) => void;\n setToolCallError: (toolCallId: string, error: string) => void;\n clearChat: () => void;\n}\n\nexport const initialChatState: ChatSlice['chat'] = {\n messages: [],\n input: '',\n threadId: null,\n toolCallErrors: {}\n};\n\nexport const createChatSlice: StateCreator<\n PurchaseOrderStore,\n [['zustand/devtools', never], ['zustand/persist', unknown]],\n [],\n ChatSlice\n> = (set) => ({\n chat: { ...initialChatState },\n setMessages: (messages) =>\n set(\n (state) => ({ chat: { ...state.chat, messages } }),\n false,\n 'chat/setMessages'\n ),\n addMessage: (message) =>\n set(\n (state) => ({\n chat: { ...state.chat, messages: [...state.chat.messages, message] }\n }),\n false,\n 'chat/addMessage'\n ),\n setInput: (input) =>\n set(\n (state) => ({ chat: { ...state.chat, input } }),\n false,\n 'chat/setInput'\n ),\n setThreadId: (threadId) =>\n set(\n (state) => ({ chat: { ...state.chat, threadId } }),\n false,\n 'chat/setThreadId'\n ),\n setToolCallError: (toolCallId, error) =>\n set(\n (state) => ({\n chat: {\n ...state.chat,\n toolCallErrors: {\n ...state.chat.toolCallErrors,\n [toolCallId]: error\n }\n }\n }),\n false,\n 'chat/setToolCallError'\n ),\n clearChat: () =>\n set(\n (state) => ({\n chat: {\n ...state.chat,\n messages: [],\n input: '',\n threadId: null,\n toolCallErrors: {}\n }\n }),\n false,\n 'chat/clearChat'\n )\n});\n","import type { StateCreator } from 'zustand';\nimport type {\n CustomerAddress,\n CustomerInfo\n} from '../../lib/bigcommerce/storefront/types.js';\nimport type { PurchaseOrderStore } from '../purchase-order-store.js';\n\n/**\n * Customer data fetched from BigCommerce on init.\n * This data is not persisted to localStorage - it's fetched fresh each page load.\n */\nexport interface CustomerSlice {\n customer: {\n customerInfo: CustomerInfo | null;\n customerAddresses: CustomerAddress[];\n };\n setCustomerInfo: (info: CustomerInfo | null) => void;\n setCustomerAddresses: (addresses: CustomerAddress[]) => void;\n}\n\nexport const initialCustomerState: CustomerSlice['customer'] = {\n customerInfo: null,\n customerAddresses: []\n};\n\nexport const createCustomerSlice: StateCreator<\n PurchaseOrderStore,\n [['zustand/devtools', never], ['zustand/persist', unknown]],\n [],\n CustomerSlice\n> = (set) => ({\n customer: { ...initialCustomerState },\n setCustomerInfo: (customerInfo) => {\n set(\n (state) => ({\n customer: { ...state.customer, customerInfo },\n customerEntityId: customerInfo?.entityId ?? null\n }),\n false,\n 'customer/setCustomerInfo'\n );\n },\n setCustomerAddresses: (customerAddresses) =>\n set(\n (state) => ({\n customer: { ...state.customer, customerAddresses }\n }),\n false,\n 'customer/setCustomerAddresses'\n )\n});\n","import type { StateCreator } from 'zustand';\nimport type { PurchaseOrderStore } from '../purchase-order-store.js';\n\nexport interface ParserSlice {\n parser: {\n uploadedFileName: string | null;\n parsedContent: string | null;\n hasProcessedDocument: boolean;\n };\n // Actions\n setUploadedFileName: (fileName: string | null) => void;\n setParsedContent: (content: string | null) => void;\n setHasProcessedDocument: (hasProcessed: boolean) => void;\n clearParser: () => void;\n}\n\nexport const initialParserState: ParserSlice['parser'] = {\n uploadedFileName: null,\n parsedContent: null,\n hasProcessedDocument: false\n};\n\nexport const createParserSlice: StateCreator<\n PurchaseOrderStore,\n [['zustand/devtools', never], ['zustand/persist', unknown]],\n [],\n ParserSlice\n> = (set) => ({\n parser: { ...initialParserState },\n setUploadedFileName: (uploadedFileName) =>\n set(\n (state) => ({ parser: { ...state.parser, uploadedFileName } }),\n false,\n 'parser/setUploadedFileName'\n ),\n setParsedContent: (parsedContent) =>\n set(\n (state) => ({ parser: { ...state.parser, parsedContent } }),\n false,\n 'parser/setParsedContent'\n ),\n setHasProcessedDocument: (hasProcessedDocument) =>\n set(\n (state) => ({ parser: { ...state.parser, hasProcessedDocument } }),\n false,\n 'parser/setHasProcessedDocument'\n ),\n clearParser: () =>\n set(\n (state) => ({\n parser: {\n ...state.parser,\n uploadedFileName: null,\n parsedContent: null,\n hasProcessedDocument: false\n }\n }),\n false,\n 'parser/clearParser'\n )\n});\n","import type { StateCreator } from 'zustand';\nimport type { Cart } from '../../lib/bigcommerce/storefront/types.js';\nimport type { AddressUpdateStatus } from '../../types.js';\nimport type { PurchaseOrderStore } from '../purchase-order-store.js';\n\n/**\n * Initialization status for the store.\n * - 'pending': Waiting for validation\n * - 'existing-cart': Orphan cart detected, awaiting user confirmation\n * - 'ready': Initialization complete, app can render normally\n */\nexport type InitStatus = 'pending' | 'existing-cart' | 'ready';\n\n/**\n * Transient UI state.\n * It is not fetched or restored externally, nor is it persisted anywhere.\n */\nexport interface UISlice {\n ui: {\n initStatus: InitStatus;\n initError: string | null;\n /** Orphan cart detected during initialization, awaiting user confirmation */\n existingCart: Cart | null;\n /** IDs of assistant messages the user has explicitly expanded (not persisted) */\n expandedMessageIds: string[];\n /**\n * Selected shipping address ID\n * TODO: Restore selected address from checkout (and move out of UI state)\n */\n selectedAddressId: string | null;\n /** Shipping address update status */\n addressUpdateStatus: AddressUpdateStatus;\n /**\n * Selected billing address ID\n * TODO: Restore selected billing address from checkout (and move out of UI state)\n */\n selectedBillingAddressId: string | null;\n /** Billing address update status */\n billingAddressUpdateStatus: AddressUpdateStatus;\n };\n // Actions\n /** Toggle expanded state for a message */\n toggleMessageExpanded: (messageId: string) => void;\n setSelectedAddressId: (id: string | null) => void;\n setAddressUpdateStatus: (status: AddressUpdateStatus) => void;\n setSelectedBillingAddressId: (id: string | null) => void;\n setBillingAddressUpdateStatus: (status: AddressUpdateStatus) => void;\n clearAddressSelections: () => void;\n}\n\nexport const initialUIState: UISlice['ui'] = {\n initStatus: 'pending',\n initError: null,\n existingCart: null,\n expandedMessageIds: [],\n selectedAddressId: null,\n addressUpdateStatus: 'idle',\n selectedBillingAddressId: null,\n billingAddressUpdateStatus: 'idle'\n};\n\nexport const createUISlice: StateCreator<\n PurchaseOrderStore,\n [['zustand/devtools', never], ['zustand/persist', unknown]],\n [],\n UISlice\n> = (set) => ({\n ui: { ...initialUIState },\n toggleMessageExpanded: (messageId) =>\n set(\n (state) => {\n const ids = state.ui.expandedMessageIds;\n const isExpanded = ids.includes(messageId);\n return {\n ui: {\n ...state.ui,\n expandedMessageIds: isExpanded\n ? ids.filter((id) => id !== messageId)\n : [...ids, messageId]\n }\n };\n },\n false,\n 'ui/toggleMessageExpanded'\n ),\n setSelectedAddressId: (selectedAddressId) =>\n set(\n (state) => ({ ui: { ...state.ui, selectedAddressId } }),\n false,\n 'ui/setSelectedAddressId'\n ),\n setAddressUpdateStatus: (addressUpdateStatus) =>\n set(\n (state) => ({ ui: { ...state.ui, addressUpdateStatus } }),\n false,\n 'ui/setAddressUpdateStatus'\n ),\n setSelectedBillingAddressId: (selectedBillingAddressId) =>\n set(\n (state) => ({ ui: { ...state.ui, selectedBillingAddressId } }),\n false,\n 'ui/setSelectedBillingAddressId'\n ),\n setBillingAddressUpdateStatus: (billingAddressUpdateStatus) =>\n set(\n (state) => ({ ui: { ...state.ui, billingAddressUpdateStatus } }),\n false,\n 'ui/setBillingAddressUpdateStatus'\n ),\n clearAddressSelections: () =>\n set(\n (state) => ({\n ui: {\n ...state.ui,\n selectedAddressId: null,\n addressUpdateStatus: 'idle',\n selectedBillingAddressId: null,\n billingAddressUpdateStatus: 'idle'\n }\n }),\n false,\n 'ui/clearAddressSelections'\n )\n});\n","import type { StateCreator } from 'zustand';\nimport { STORAGE_KEY } from '../../constants.js';\nimport type { PurchaseOrderStore } from '../purchase-order-store.js';\n\n// Default panel width for the resizable panels (percentage: 0-100)\nexport const DEFAULT_PANEL_WIDTH = 25;\n\n/**\n * User preferences that are persisted to localstorage.\n */\nexport interface UserSettingsSlice {\n userSettings: {\n /** Left panel width as percentage (0-100) */\n panelWidth: number;\n };\n // Actions\n /** Set left panel width as percentage (0-100) */\n setPanelWidth: (width: number) => void;\n /** Restore user settings from localStorage */\n restoreUserSettings: () => void;\n}\n\nexport const initialUserSettingsState: UserSettingsSlice['userSettings'] = {\n panelWidth: DEFAULT_PANEL_WIDTH\n};\n\nexport const createUserSettingsSlice: StateCreator<\n PurchaseOrderStore,\n [['zustand/devtools', never], ['zustand/persist', unknown]],\n [],\n UserSettingsSlice\n> = (set) => ({\n userSettings: { ...initialUserSettingsState },\n setPanelWidth: (panelWidth) =>\n set(\n (state) => ({ userSettings: { ...state.userSettings, panelWidth } }),\n false,\n 'userSettings/setPanelWidth'\n ),\n restoreUserSettings: () => {\n try {\n const raw = localStorage.getItem(STORAGE_KEY);\n if (!raw) return;\n const parsed = JSON.parse(raw);\n const settings = parsed?.state?.userSettings;\n if (settings) {\n set({ userSettings: settings }, false, 'userSettings/restore');\n }\n } catch {\n // Ignore localStorage errors\n }\n }\n});\n","import type { UIMessage } from 'ai';\nimport { create } from 'zustand';\nimport { devtools, persist } from 'zustand/middleware';\nimport { STORAGE_KEY, STORAGE_VERSION } from '../constants.js';\nimport type {\n BigCommerceClient,\n MockBigCommerceClient\n} from '../lib/bigcommerce/index.js';\nimport type { Cart } from '../lib/bigcommerce/storefront/types.js';\nimport type { AppState } from '../types.js';\nimport {\n type BcSessionSlice,\n createBcSessionSlice\n} from './slices/bc-session-slice.js';\nimport {\n type CartifactSlice,\n createCartifactSlice\n} from './slices/cartifact-slice.js';\nimport { type ChatSlice, createChatSlice } from './slices/chat-slice.js';\nimport {\n type CustomerSlice,\n createCustomerSlice\n} from './slices/customer-slice.js';\nimport { createParserSlice, type ParserSlice } from './slices/parser-slice.js';\nimport {\n createUISlice,\n type InitStatus,\n type UISlice\n} from './slices/ui-slice.js';\nimport {\n createUserSettingsSlice,\n DEFAULT_PANEL_WIDTH,\n type UserSettingsSlice\n} from './slices/user-settings-slice.js';\n\n// Maximum number of messages to persist to localStorage\nconst MAX_PERSISTED_MESSAGES = 100;\n\n// Maximum number of tool call errors to persist to localStorage\nconst MAX_TOOL_CALL_ERRORS = 100;\n\nexport interface PurchaseOrderStore\n extends ChatSlice,\n CartifactSlice,\n CustomerSlice,\n BcSessionSlice,\n ParserSlice,\n UISlice,\n UserSettingsSlice {\n // Top-level state\n appState: AppState;\n customerEntityId: number | null;\n fatalError: string | null;\n\n // Actions\n setCustomerEntityId: (id: number | null) => void;\n setFatalError: (error: string | null) => void;\n setAppState: (appState: AppState) => void;\n\n // Initialization actions\n /**\n * Call when all validation passes. Derives UI state from persisted data.\n * Transitions: pending → ready\n */\n completeValidation: () => void;\n\n /**\n * Call when validation fails. Clears persisted state and shows error.\n * Transitions: pending → ready with fresh state\n */\n failValidation: (error: string) => void;\n\n /**\n * Get current init status for conditional rendering.\n */\n getInitStatus: () => InitStatus;\n\n /**\n * Set an existing orphan cart and transition to 'existing-cart' status.\n * Called during initialization when an orphan cart is detected.\n */\n setExistingCart: (cart: Cart) => void;\n\n /**\n * Confirm clearing an existing orphan cart detected during initialization.\n * Deletes the cart via BigCommerce API, clears existingCart, and transitions to 'ready'.\n */\n confirmClearExistingCart: (\n client: BigCommerceClient | MockBigCommerceClient\n ) => Promise<void>;\n\n /**\n * Clear the init error message (after user acknowledges).\n */\n clearInitError: () => void;\n\n /**\n * Restore session from persisted data.\n * Called during initialization to bypass the persist middleware's rehydrate\n * (which can be overwritten by state changes during validation).\n */\n restoreSession: (data: PersistedStateData) => void;\n}\n\n/**\n * Shape of persisted state data passed to restoreSession.\n */\nexport interface PersistedStateData {\n appState?: AppState;\n customerEntityId?: number | null;\n chat?: {\n messages?: unknown[];\n input?: string;\n threadId?: string | null;\n toolCallErrors?: Record<string, string>;\n };\n cartifact?: {\n cartEntityId?: string | null;\n poItemPrices?: Record<string, unknown>;\n orderId?: string | null;\n buyerInfo?: unknown | null;\n shipToAddress?: unknown | null;\n billingAddress?: unknown | null;\n poMetadataSet?: boolean;\n itemWarnings?: unknown[];\n };\n parser?: {\n uploadedFileName?: string | null;\n parsedContent?: string | null;\n hasProcessedDocument?: boolean;\n };\n userSettings?: {\n panelWidth?: number;\n };\n}\n\n/**\n * Clears all persisted state except panel width preference.\n */\nfunction getCleanState(panelWidth: number) {\n return {\n appState: 'upload' as const,\n customerEntityId: null,\n fatalError: null,\n chat: {\n messages: [],\n input: '',\n threadId: null,\n toolCallErrors: {}\n },\n cartifact: {\n cartEntityId: null,\n poItemPrices: {},\n orderId: null,\n buyerInfo: null,\n shipToAddress: null,\n billingAddress: null,\n poMetadataSet: false,\n itemWarnings: []\n },\n customer: {\n customerInfo: null,\n customerAddresses: []\n },\n bcSession: {\n bcCart: null,\n checkout: null,\n isLoading: false,\n productPaths: {}\n },\n parser: {\n uploadedFileName: null,\n parsedContent: null,\n hasProcessedDocument: false\n },\n ui: {\n initStatus: 'ready' as const,\n initError: null,\n existingCart: null,\n expandedMessageIds: [],\n selectedAddressId: null,\n addressUpdateStatus: 'idle' as const,\n selectedBillingAddressId: null,\n billingAddressUpdateStatus: 'idle' as const\n },\n userSettings: {\n panelWidth\n }\n };\n}\n\nexport const usePurchaseOrderStore = create<PurchaseOrderStore>()(\n devtools(\n persist(\n (set, get) => ({\n // Combine all slices\n ...createChatSlice(set, get, {} as never),\n ...createCartifactSlice(set, get, {} as never),\n ...createCustomerSlice(set, get, {} as never),\n ...createBcSessionSlice(set, get, {} as never),\n ...createParserSlice(set, get, {} as never),\n ...createUISlice(set, get, {} as never),\n ...createUserSettingsSlice(set, get, {} as never),\n\n // Top-level state\n appState: 'upload',\n customerEntityId: null,\n fatalError: null,\n\n // Top-level actions\n setCustomerEntityId: (customerEntityId) =>\n set({ customerEntityId }, false, 'setCustomerEntityId'),\n setFatalError: (fatalError) =>\n set({ fatalError }, false, 'setFatalError'),\n setAppState: (appState) => set({ appState }, false, 'setAppState'),\n\n /**\n * Complete validation successfully. Keeps existing UI state.\n */\n completeValidation: () => {\n set(\n (s) => ({\n ui: {\n ...s.ui,\n initStatus: 'ready',\n initError: null\n }\n }),\n false,\n 'completeValidation'\n );\n },\n\n /**\n * Set an existing orphan cart and transition to 'existing-cart' status.\n */\n setExistingCart: (cart: Cart) => {\n set(\n (s) => ({\n ui: {\n ...s.ui,\n existingCart: cart,\n initStatus: 'existing-cart' as const\n }\n }),\n false,\n 'setExistingCart'\n );\n },\n\n /**\n * Confirm clearing an existing orphan cart.\n * Deletes the cart, clears existingCart, transitions to 'ready'.\n */\n confirmClearExistingCart: async (\n client: BigCommerceClient | MockBigCommerceClient\n ) => {\n try {\n const existingCart = get().ui.existingCart;\n if (existingCart) {\n await client.deleteCart(existingCart.entityId);\n }\n set(\n (s) => ({\n ui: {\n ...s.ui,\n existingCart: null,\n initStatus: 'ready' as const\n }\n }),\n false,\n 'confirmClearExistingCart'\n );\n } catch (error) {\n console.error('Failed to delete existing cart:', error);\n get().setFatalError(\n 'Unable to clear your existing cart. Please refresh and try again.'\n );\n }\n },\n\n /**\n * Validation failed. Clear persisted state and start fresh.\n */\n failValidation: (error: string) => {\n const panelWidth = get().userSettings.panelWidth;\n set(\n {\n ...getCleanState(panelWidth),\n appState: 'upload',\n ui: {\n initStatus: 'ready', // Ready with fresh state\n initError: error, // Keep error for display\n existingCart: null,\n expandedMessageIds: [],\n selectedAddressId: null,\n addressUpdateStatus: 'idle',\n selectedBillingAddressId: null,\n billingAddressUpdateStatus: 'idle'\n }\n },\n false,\n 'failValidation'\n );\n },\n\n /**\n * Get current init status.\n */\n getInitStatus: () => get().ui.initStatus,\n\n /**\n * Clear the init error message.\n */\n clearInitError: () => {\n set(\n (s) => ({\n ui: { ...s.ui, initError: null, initStatus: 'pending' as const }\n }),\n false,\n 'clearInitError'\n );\n },\n\n /**\n * Restore session from persisted data.\n * Bypasses the persist middleware's rehydrate to avoid race conditions\n * where state changes during validation overwrite localStorage.\n */\n restoreSession: (data: PersistedStateData) => {\n set(\n {\n customerEntityId: data.customerEntityId ?? null,\n appState: data.appState ?? 'upload',\n chat: {\n messages: (data.chat?.messages ?? []) as UIMessage[],\n input: data.chat?.input ?? '',\n threadId: data.chat?.threadId ?? null,\n toolCallErrors: data.chat?.toolCallErrors ?? {}\n },\n cartifact: data.cartifact as CartifactSlice['cartifact'],\n parser: data.parser as ParserSlice['parser'],\n userSettings: {\n panelWidth: data.userSettings?.panelWidth ?? DEFAULT_PANEL_WIDTH\n }\n },\n false,\n 'restoreSession'\n );\n }\n }),\n {\n name: STORAGE_KEY,\n version: STORAGE_VERSION,\n partialize: (state) => ({\n // Persist customer ID for validation\n customerEntityId: state.customerEntityId,\n\n // Persist app state (workflow phase)\n appState: state.appState,\n\n // Persist chat state with message truncation\n chat: {\n messages: state.chat.messages.slice(-MAX_PERSISTED_MESSAGES),\n input: state.chat.input,\n threadId: state.chat.threadId,\n toolCallErrors: Object.fromEntries(\n Object.entries(state.chat.toolCallErrors).slice(\n -MAX_TOOL_CALL_ERRORS\n )\n )\n },\n\n // Persist cartifact state\n cartifact: state.cartifact,\n\n // Persist parser state\n parser: state.parser,\n\n // Persist user settings\n userSettings: state.userSettings\n }),\n migrate: (persisted, version) => {\n if (!persisted || typeof persisted !== 'object') {\n return { userSettings: { panelWidth: DEFAULT_PANEL_WIDTH } };\n }\n const state = persisted as Record<string, unknown>;\n // v2 → v3: reset panel width to new default (25%)\n if (version < 3) {\n return {\n ...state,\n userSettings: {\n ...(state.userSettings as Record<string, unknown>),\n panelWidth: DEFAULT_PANEL_WIDTH\n }\n };\n }\n return state;\n },\n // Skip automatic rehydration - we manually restore via restoreSession()\n // after validation to avoid race conditions with localStorage overwrites\n skipHydration: true\n }\n ),\n {\n name: 'PurchaseOrderStore',\n store: 'PurchaseOrderStore',\n enabled: true\n }\n )\n);\n","import type { ItemWarning } from '../../../types.js';\nimport { usePurchaseOrderStore } from '../../../stores/purchase-order-store.js';\nimport { XIcon } from '../../icons/x-icon.js';\n\nexport interface LineItemWarningProps {\n item: ItemWarning;\n onSuggestAlternatives: (identifier: string) => void;\n}\n\nexport function itemWarningToString({ productName, productSku }: ItemWarning) {\n if (productName && productSku) {\n return `${productName} (${productSku})`;\n }\n if (productName) {\n return productName;\n }\n if (productSku) {\n return productSku;\n }\n return 'Unknown Product';\n}\n\nexport function LineItemWarning({\n item,\n onSuggestAlternatives\n}: LineItemWarningProps) {\n const removeItemWarning = usePurchaseOrderStore(\n (state) => state.removeItemWarning\n );\n\n return (\n <div className=\"flex gap-3 p-2 rounded mb-2 bg-surface-secondary border border-dashed border-border opacity-70\">\n <div className=\"w-12 h-12 bg-surface-disabled rounded shrink-0 animate-pulse\" />\n <div className=\"flex-1 min-w-0\">\n <div className=\"flex items-start justify-between gap-2\">\n <div className=\"flex-1 min-w-0\">\n {(item.productName || item.productSku) && (\n <p className=\"text-sm font-medium text-text-secondary m-0 truncate\">\n {itemWarningToString(item)}\n </p>\n )}\n <div className=\"flex items-center gap-1.5 mt-1\">\n <span className=\"inline-flex items-center gap-1 text-[0.625rem] font-medium px-1.5 py-0.5 rounded bg-surface-tertiary text-text-secondary\">\n <span className=\"w-1.5 h-1.5 bg-text-secondary rounded-full animate-pulse\" />\n {item.status}\n </span>\n </div>\n </div>\n <button\n type=\"button\"\n onClick={() => removeItemWarning(item)}\n className=\"p-1 text-text-quaternary hover:text-text-secondary shrink-0\"\n aria-label=\"Dismiss warning\"\n >\n <XIcon />\n </button>\n </div>\n {(item.productName || item.productSku) && (\n <div className=\"mt-2\">\n <button\n type=\"button\"\n onClick={() => onSuggestAlternatives(itemWarningToString(item))}\n className=\"text-xs px-1.5 py-1 rounded text-warning-text bg-warning/20 hover:bg-warning/30\"\n >\n Suggest alternatives\n </button>\n </div>\n )}\n </div>\n </div>\n );\n}\n","import { useCallback, useRef, useState } from 'react';\nimport type { CustomerAddress } from '../../../lib/bigcommerce/index.js';\nimport type {\n AddressUpdateStatus,\n BuyerInfo,\n CartItem,\n CheckoutTotals,\n CustomerInfo,\n ItemWarning\n} from '../../../types.js';\nimport { CartIcon } from '../../icons/cart-icon.js';\nimport { CheckIcon } from '../../icons/check-icon.js';\nimport { CopyIcon } from '../../icons/copy-icon.js';\nimport { MaximizeIcon } from '../../icons/maximize-icon.js';\nimport { MinimizeIcon } from '../../icons/minimize-icon.js';\nimport { CartifactAddress } from './cartifact-address.js';\nimport { CartifactFooter } from './cartifact-footer.js';\nimport { CartifactLineItem } from './cartifact-line-item.js';\nimport { CartifactNewOrder } from './cartifact-new-order.js';\nimport { EmptyCartifact } from './empty-cartifact.js';\nimport { itemWarningToString, LineItemWarning } from './line-item-warning.js';\nimport { PanelActionButton } from './panel-action-button.js';\n\nexport interface CartPanelProps {\n items: CartItem[];\n itemWarnings?: ItemWarning[];\n onUpdateQuantity: (id: string, quantity: number) => void | Promise<void>;\n onRemove: (id: string) => void;\n onCheckout: () => void;\n onSuggestAlternatives: (itemName: string, sku?: string) => void;\n onShowMoreLikeThis: (itemName: string, sku?: string) => void;\n onViewProduct?: (item: CartItem) => void;\n className?: string;\n orderId?: string;\n buyerInfo?: BuyerInfo;\n customerInfo?: CustomerInfo;\n addresses?: CustomerAddress[];\n selectedAddressId?: string;\n addressUpdateStatus?: AddressUpdateStatus;\n onAddressChange?: (addressId: string) => void;\n selectedBillingAddressId?: string;\n billingAddressUpdateStatus?: AddressUpdateStatus;\n onBillingAddressChange?: (addressId: string) => void;\n shipToAddress?: CustomerAddress;\n billingAddress?: CustomerAddress;\n checkoutTotals?: CheckoutTotals;\n isLoading?: boolean;\n poMetadataSet?: boolean;\n onNewOrder?: () => void;\n onExpand?: () => void;\n onMinimize?: () => void;\n}\n\nexport function CartPanel({\n items,\n itemWarnings = [],\n onUpdateQuantity,\n onRemove,\n onCheckout,\n onSuggestAlternatives,\n onShowMoreLikeThis,\n onViewProduct,\n className = '',\n orderId,\n addresses = [],\n selectedAddressId,\n addressUpdateStatus,\n onAddressChange,\n selectedBillingAddressId,\n billingAddressUpdateStatus,\n onBillingAddressChange,\n shipToAddress,\n billingAddress,\n checkoutTotals,\n isLoading,\n poMetadataSet = false,\n onNewOrder,\n onExpand,\n onMinimize\n}: CartPanelProps) {\n const [copied, setCopied] = useState(false);\n const copyTimeoutRef = useRef<ReturnType<typeof setTimeout>>(undefined);\n\n const handleCopyOrderId = useCallback(() => {\n if (!orderId) return;\n navigator.clipboard.writeText(orderId).then(() => {\n setCopied(true);\n clearTimeout(copyTimeoutRef.current);\n copyTimeoutRef.current = setTimeout(() => setCopied(false), 2000);\n });\n }, [orderId]);\n\n const subtotal = items\n .filter((item) => item.status !== 'unavailable')\n .reduce((sum, item) => sum + (item.price ?? 0) * item.quantity, 0);\n\n const availableItems = items.filter((item) => item.status !== 'unavailable');\n const totalQuantity = availableItems.reduce(\n (sum, item) => sum + item.quantity,\n 0\n );\n\n // Get currency code from first item\n const currencyCode = items.find(\n (item) => item.catalogPriceCurrencyCode\n )?.catalogPriceCurrencyCode;\n\n // Get display values\n const displayTax = checkoutTotals?.tax;\n const displayShipping = checkoutTotals?.shipping;\n const displayTotal =\n checkoutTotals?.grandTotal ??\n (displayTax !== null\n ? subtotal + (displayTax ?? 0) + (displayShipping ?? 0)\n : null);\n\n if (items.length === 0 && itemWarnings.length === 0 && !poMetadataSet) {\n return (\n <EmptyCartifact\n className={className}\n onNewOrder={onNewOrder}\n onExpand={onExpand}\n onMinimize={onMinimize}\n />\n );\n }\n\n return (\n <div\n className={`bg-surface-secondary rounded-lg flex flex-col h-full min-h-0 border border-solid border-border-strong ${className}`}\n style={{\n boxShadow:\n '0 2px 8px -2px rgba(0, 0, 0, 0.04), 0 1px 3px -1px rgba(0, 0, 0, 0.03)'\n }}\n >\n {/* Header */}\n <div className=\"px-4 py-3 shrink-0\">\n <div className=\"flex items-center justify-between mb-2\">\n <h2 className=\"text-[1.125rem] font-normal text-text m-0\">Cart</h2>\n <div className=\"flex items-center gap-2\">\n {onNewOrder && <CartifactNewOrder onNewOrder={onNewOrder} />}\n {onExpand && (\n <PanelActionButton onClick={onExpand} aria-label=\"Expand\">\n <MaximizeIcon size={14} />\n Expand\n </PanelActionButton>\n )}\n {onMinimize && (\n <PanelActionButton onClick={onMinimize} aria-label=\"Minimize\">\n <MinimizeIcon size={14} />\n Minimize\n </PanelActionButton>\n )}\n </div>\n </div>\n\n {/* Order ID and Item Count */}\n {orderId && (\n <div className=\"flex gap-5 mb-2\">\n <div className=\"flex flex-col gap-0\">\n <span className=\"text-[0.625rem] text-text-tertiary uppercase tracking-[0.05em]\">\n PO Number\n </span>\n <button\n type=\"button\"\n onClick={handleCopyOrderId}\n className=\"flex items-center gap-1 text-[0.8125rem] font-semibold text-text bg-transparent border-none cursor-pointer p-0 hover:opacity-70 transition-opacity\"\n title={copied ? 'Copied!' : 'Copy PO Number'}\n >\n {orderId}\n <span className=\"text-text-tertiary\">\n {copied ? (\n <CheckIcon size={12} title=\"Copied\" />\n ) : (\n <CopyIcon size={12} />\n )}\n </span>\n </button>\n </div>\n <div className=\"flex flex-col gap-0\">\n <span className=\"text-[0.625rem] text-text-tertiary uppercase tracking-[0.05em]\">\n Items\n </span>\n <span className=\"text-[0.8125rem] font-semibold text-text\">\n {items.length}\n </span>\n </div>\n </div>\n )}\n\n {/* Address Section */}\n <CartifactAddress\n addresses={addresses}\n selectedAddressId={selectedAddressId}\n addressUpdateStatus={addressUpdateStatus}\n onAddressChange={onAddressChange}\n selectedBillingAddressId={selectedBillingAddressId}\n billingAddressUpdateStatus={billingAddressUpdateStatus}\n onBillingAddressChange={onBillingAddressChange}\n shipToAddress={shipToAddress}\n billingAddress={billingAddress}\n />\n </div>\n\n {/* Divider */}\n <div className=\"h-px shrink-0 bg-border\" />\n\n {/* Items Section */}\n <div className=\"flex-1 min-h-0 overflow-y-auto flex flex-col\">\n {/* Items List */}\n <div className=\"flex-1 min-h-0 overflow-y-auto p-2 bg-surface\">\n {/* Empty state when metadata exists but no items */}\n {items.length === 0 && itemWarnings.length === 0 && (\n <div className=\"flex flex-col items-center justify-center h-full text-center\">\n <div className=\"w-12 h-12 mx-auto mb-3 rounded-full bg-surface-tertiary flex items-center justify-center text-text-quaternary\">\n <CartIcon />\n </div>\n <p className=\"text-sm text-text-quaternary m-0\">\n No items in cart yet\n </p>\n </div>\n )}\n\n {/* Pending Items */}\n {itemWarnings.length > 0 && (\n <>\n {itemWarnings.map((warning) => (\n <LineItemWarning\n key={`${itemWarningToString(warning)}-${warning.status}`}\n item={warning}\n onSuggestAlternatives={(identifier) =>\n onSuggestAlternatives(identifier)\n }\n />\n ))}\n {items.length > 0 && (\n <div className=\"border-b border-border mb-2\" />\n )}\n </>\n )}\n\n {items.map((item) => (\n <CartifactLineItem\n key={item.id}\n item={item}\n onUpdateQuantity={onUpdateQuantity}\n onRemove={onRemove}\n onShowMoreLikeThis={onShowMoreLikeThis}\n onViewProduct={onViewProduct}\n />\n ))}\n </div>\n </div>\n\n {/* Divider */}\n <div className=\"h-px shrink-0 bg-border\" />\n\n {/* Footer */}\n <CartifactFooter\n subtotal={subtotal}\n tax={displayTax}\n shipping={displayShipping}\n total={displayTotal}\n currencyCode={currencyCode}\n totalQuantity={totalQuantity}\n availableItemCount={availableItems.length}\n onCheckout={onCheckout}\n isLoading={isLoading}\n allowCheckout={!!selectedAddressId}\n />\n </div>\n );\n}\n","export interface ChatErrorProps {\n error: Error | null;\n onRetry?: () => void;\n}\n\nconst networkErrorPatterns = [\n 'failed to fetch',\n 'networkerror',\n 'network request failed',\n 'internet connection appears to be offline',\n 'the network connection was lost',\n 'net::err_internet_disconnected',\n 'net::err_network_changed'\n];\n\nexport function isOfflineError(error: Error): boolean {\n if (typeof navigator !== 'undefined' && !navigator.onLine) {\n return true;\n }\n\n const message = error.message.toLowerCase();\n return networkErrorPatterns.some((pattern) => message.includes(pattern));\n}\n\nexport function ChatError({ error, onRetry }: ChatErrorProps) {\n if (!error) {\n return null;\n }\n\n const offline = isOfflineError(error);\n\n return (\n <div className=\"mx-4 my-3 px-4 py-3 bg-error-bg border border-error/30 rounded-lg\">\n <p className=\"text-sm text-error-text\">\n {offline\n ? \"You're offline. Please check your internet connection and try again.\"\n : 'Something went wrong. Please try again.'}\n </p>\n {onRetry && (\n <button\n type=\"button\"\n onClick={onRetry}\n className=\"mt-2 text-sm font-medium text-error-text underline\"\n >\n Retry\n </button>\n )}\n </div>\n );\n}\n","export const SendIcon = () => (\n <svg\n width=\"18\"\n height=\"18\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n >\n <title>Send</title>\n <line x1=\"22\" y1=\"2\" x2=\"11\" y2=\"13\" />\n <polygon points=\"22 2 15 22 11 13 2 9 22 2\" />\n </svg>\n);\n","import type { ChangeEvent, FormEvent, KeyboardEvent } from 'react';\nimport { SendIcon } from '../../icons/send-icon.js';\n\nexport interface ChatInputProps {\n input: string;\n onInputChange: (e: ChangeEvent<HTMLTextAreaElement>) => void;\n onSubmit: (e: FormEvent<HTMLFormElement>) => void;\n isLoading: boolean;\n}\n\nexport function ChatInput({\n input,\n onInputChange,\n onSubmit,\n isLoading\n}: ChatInputProps) {\n const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n const form = e.currentTarget.form;\n if (form) {\n form.requestSubmit();\n }\n }\n };\n\n return (\n <div className=\"px-4 pb-4 pt-2 shrink-0\">\n <form\n onSubmit={onSubmit}\n className=\"flex items-center gap-1 rounded-xl border border-border bg-surface shadow-sm focus-within:border-border-focus focus-within:shadow-[0_0_0_3px_rgba(0,0,0,0.08)] transition-shadow\"\n >\n <textarea\n placeholder=\"Describe what you need...\"\n className=\"flex-1 resize-none border-none rounded-xl px-4 py-3 text-[0.9375rem] font-inherit bg-transparent min-h-[44px] max-h-[120px] leading-normal focus:outline-none placeholder:text-text-quaternary disabled:cursor-not-allowed\"\n rows={1}\n value={input}\n onChange={onInputChange}\n onKeyDown={handleKeyDown}\n disabled={isLoading}\n />\n <button\n type=\"submit\"\n className=\"w-10 h-10 mr-1.5 border-none rounded-lg bg-surface-invert text-text-invert cursor-pointer flex items-center justify-center transition-colors shrink-0 hover:bg-surface-invert-hover disabled:bg-surface-disabled disabled:cursor-not-allowed\"\n disabled={!input.trim() || isLoading}\n aria-label=\"Send message\"\n >\n <SendIcon />\n </button>\n </form>\n </div>\n );\n}\n","import type { RenderablePart, ToolPart } from '../types.js';\n\nexport interface ToolCallGroup {\n type: 'tool-group';\n tools: ToolPart[];\n}\n\nexport type GroupedPart = RenderablePart | ToolCallGroup;\n\nconst NON_COLLAPSIBLE_TOOLS = new Set(['showProducts']);\n\nfunction isCollapsibleTool(part: RenderablePart): part is ToolPart {\n return part.type === 'tool' && !NON_COLLAPSIBLE_TOOLS.has(part.toolName);\n}\n\nexport function groupRenderableParts(parts: RenderablePart[]): GroupedPart[] {\n const result: GroupedPart[] = [];\n let accumulator: ToolPart[] = [];\n\n function flush() {\n if (accumulator.length >= 2) {\n result.push({ type: 'tool-group', tools: accumulator });\n } else if (accumulator.length === 1) {\n result.push(accumulator[0]!);\n }\n accumulator = [];\n }\n\n for (const part of parts) {\n if (isCollapsibleTool(part)) {\n accumulator.push(part);\n } else {\n flush();\n result.push(part);\n }\n }\n\n flush();\n return result;\n}\n","export const FileIcon = () => (\n <svg\n width=\"14\"\n height=\"14\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n >\n <title>Attachment</title>\n <path d=\"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z\" />\n <polyline points=\"14 2 14 8 20 8\" />\n </svg>\n);\n","export const ExpandChevronIcon = () => (\n <svg\n width=\"12\"\n height=\"12\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n >\n <title>Expand</title>\n <polyline points=\"9 18 15 12 9 6\" />\n </svg>\n);\n","import {\n type PurchaseOrderStore,\n usePurchaseOrderStore\n} from '../../stores/purchase-order-store.js';\n\nexport interface GenericToolMessageProps {\n toolCallId: string;\n loadingMessage?: string;\n failedMessage?: string;\n successMessage: string;\n toolOutput?: unknown;\n}\n\nexport function GenericToolMessage({\n toolCallId,\n loadingMessage,\n failedMessage,\n successMessage,\n toolOutput\n}: GenericToolMessageProps) {\n const hasError = usePurchaseOrderStore(\n (state: PurchaseOrderStore) => toolCallId in state.chat.toolCallErrors\n );\n const isLoading = loadingMessage && toolOutput === undefined;\n const hasFailed = hasError && failedMessage;\n\n let message: string;\n let variant: 'default' | 'error' = 'default';\n\n if (isLoading) {\n message = loadingMessage;\n } else if (hasFailed) {\n message = failedMessage;\n variant = 'error';\n } else {\n message = successMessage;\n }\n\n return (\n <div\n className={`text-xs italic ${variant === 'error' ? 'text-red-500' : 'text-text-secondary'}`}\n >\n {message}\n </div>\n );\n}\n","export function parseToolOutput(output: unknown): unknown {\n if (!output) return undefined;\n try {\n return typeof output === 'string' ? JSON.parse(output) : output;\n } catch {\n return undefined;\n }\n}\n","import { GenericToolMessage } from './generic-tool-message.js';\nimport { parseToolOutput } from './parse-tool-output.js';\n\nexport interface GetProductVariantsToolProps {\n toolCallId: string;\n toolInput: unknown;\n toolOutput: unknown;\n toolState: string;\n}\n\nexport function GetProductVariantsTool({\n toolCallId,\n toolInput,\n toolOutput,\n toolState\n}: GetProductVariantsToolProps) {\n const productEntityId =\n (toolInput as { productEntityId?: string } | undefined)?.productEntityId ??\n '';\n const isComplete = toolState === 'output-available';\n\n if (!isComplete) {\n return (\n <GenericToolMessage\n toolCallId={toolCallId}\n loadingMessage={`Retrieving variants for product ${productEntityId}...`}\n successMessage=\"\"\n />\n );\n }\n\n const parsed = parseToolOutput(toolOutput);\n const variants = (\n parsed as {\n data?: {\n BigCommerce_product?: {\n variants?: {\n edges?: unknown[];\n pageInfo?: { hasNextPage?: boolean };\n };\n };\n };\n }\n )?.data?.BigCommerce_product?.variants;\n const count = variants?.edges?.length ?? 0;\n const hasMore = variants?.pageInfo?.hasNextPage ?? false;\n\n return (\n <GenericToolMessage\n toolCallId={toolCallId}\n successMessage={`Found ${count} variant${count !== 1 ? 's' : ''} for product ${productEntityId}${hasMore ? ' (more available)' : ''}`}\n toolOutput={toolOutput}\n />\n );\n}\n","import { GenericToolMessage } from './generic-tool-message.js';\nimport { parseToolOutput } from './parse-tool-output.js';\n\nexport interface SearchProductsBySkuToolProps {\n toolCallId: string;\n toolInput: unknown;\n toolOutput: unknown;\n toolState: string;\n}\n\nexport function SearchProductsBySkuTool({\n toolCallId,\n toolInput,\n toolOutput,\n toolState\n}: SearchProductsBySkuToolProps) {\n const sku = (toolInput as { sku?: string } | undefined)?.sku ?? '';\n const isComplete = toolState === 'output-available';\n\n if (!isComplete) {\n return (\n <GenericToolMessage\n toolCallId={toolCallId}\n loadingMessage={`Searching for SKU '${sku}'...`}\n successMessage=\"\"\n />\n );\n }\n\n const parsed = parseToolOutput(toolOutput);\n const count =\n (parsed as { data?: { searchProductsBySku?: { total?: number } } })?.data\n ?.searchProductsBySku?.total ?? 0;\n\n return (\n <GenericToolMessage\n toolCallId={toolCallId}\n successMessage={`Found ${count} product${count !== 1 ? 's' : ''} with SKU '${sku}'`}\n toolOutput={toolOutput}\n />\n );\n}\n","import { GenericToolMessage } from './generic-tool-message.js';\nimport { parseToolOutput } from './parse-tool-output.js';\n\nexport interface SearchProductsToolProps {\n toolCallId: string;\n toolInput: unknown;\n toolOutput: unknown;\n toolState: string;\n}\n\nexport function SearchProductsTool({\n toolCallId,\n toolInput,\n toolOutput,\n toolState\n}: SearchProductsToolProps) {\n const matchPhrase =\n (toolInput as { matchPhrase?: string } | undefined)?.matchPhrase ??\n 'products';\n const isComplete = toolState === 'output-available';\n\n if (!isComplete) {\n return (\n <GenericToolMessage\n toolCallId={toolCallId}\n loadingMessage={`Searching for '${matchPhrase}'...`}\n successMessage=\"\"\n />\n );\n }\n\n const parsed = parseToolOutput(toolOutput);\n const count =\n (parsed as { data?: { searchProducts?: { total?: number } } })?.data\n ?.searchProducts?.total ?? 0;\n\n return (\n <GenericToolMessage\n toolCallId={toolCallId}\n successMessage={`Found ${count} product${count !== 1 ? 's' : ''} for '${matchPhrase}'`}\n toolOutput={toolOutput}\n />\n );\n}\n","'use client';\n\nimport { createContext, type ReactNode, useContext } from 'react';\nimport type { BigCommerceClient } from '../lib/bigcommerce/storefront/client.js';\nimport type { MockBigCommerceClient } from '../lib/bigcommerce/storefront/mock-client.js';\n\ntype BigCommerceClientType = BigCommerceClient | MockBigCommerceClient;\n\nconst BigCommerceClientContext = createContext<BigCommerceClientType | null>(\n null\n);\n\nexport interface BigCommerceClientProviderProps {\n client: BigCommerceClientType | null;\n children: ReactNode;\n}\n\nexport function BigCommerceClientProvider({\n client,\n children\n}: BigCommerceClientProviderProps) {\n return (\n <BigCommerceClientContext.Provider value={client}>\n {children}\n </BigCommerceClientContext.Provider>\n );\n}\n\nexport function useBigCommerceClient(): BigCommerceClientType | null {\n return useContext(BigCommerceClientContext);\n}\n","import { useQuery } from '@tanstack/react-query';\nimport type { BigCommerceClient } from '../lib/bigcommerce/index.js';\nimport type { ProductVariantDetails } from '../lib/bigcommerce/storefront/types.js';\n\n/**\n * Fetch product variant details for multiple products\n * Uses React Query for caching and deduplication\n */\nexport function useProductVariants(\n client: BigCommerceClient,\n productEntityIds: number[]\n) {\n return useQuery({\n queryKey: [\n 'productVariants',\n productEntityIds\n .slice()\n .sort((a, b) => a - b)\n .join(',')\n ],\n queryFn: () => client.getProductVariantDetails(productEntityIds),\n enabled: productEntityIds.length > 0,\n staleTime: 5 * 60 * 1000 // 5 minutes\n });\n}\n\n// Helper type for variant selections: Map of optionEntityId -> selected valueEntityId\nexport type VariantSelections = Map<number, number>;\n\n/**\n * Extract optionId -> valueId mapping from a variant's options\n */\nexport function getVariantOptionValues(\n variant: ProductVariantDetails['variants'][number]\n): Map<number, number> {\n const map = new Map<number, number>();\n for (const option of variant.options) {\n const selectedValue = option.values[0];\n if (selectedValue) {\n map.set(option.entityId, selectedValue.entityId);\n }\n }\n return map;\n}\n\n/**\n * Find the variant that matches the given selections\n */\nexport function findMatchingVariant(\n variants: ProductVariantDetails['variants'],\n selections: VariantSelections\n): ProductVariantDetails['variants'][number] | null {\n return (\n variants.find((variant) => {\n const variantValues = getVariantOptionValues(variant);\n return Array.from(selections.entries()).every(\n ([optionId, valueId]) => variantValues.get(optionId) === valueId\n );\n }) ?? null\n );\n}\n\n/**\n * Get the initial variant selection based on default values or first variant\n */\nexport function getInitialSelections(\n details: ProductVariantDetails\n): VariantSelections {\n const selections: VariantSelections = new Map();\n\n // Try to use default values from product options\n for (const option of details.productOptions) {\n const defaultValue = option.values.find((v) => v.isDefault);\n if (defaultValue) {\n selections.set(option.entityId, defaultValue.entityId);\n } else if (option.values[0]) {\n // Fall back to first value\n selections.set(option.entityId, option.values[0].entityId);\n }\n }\n\n // Verify the selection maps to a valid variant, otherwise use first variant\n const matchingVariant = findMatchingVariant(details.variants, selections);\n if (!matchingVariant && details.variants[0]) {\n // Use first variant's option values\n const firstVariant = details.variants[0];\n selections.clear();\n for (const option of firstVariant.options) {\n const value = option.values[0];\n if (value) {\n selections.set(option.entityId, value.entityId);\n }\n }\n }\n\n return selections;\n}\n\n/**\n * Get the initial variant entityId for a product\n */\nexport function getInitialVariantEntityId(\n details: ProductVariantDetails\n): number | null {\n const selections = getInitialSelections(details);\n const variant = findMatchingVariant(details.variants, selections);\n return variant?.entityId ?? null;\n}\n","export const PlaceholderImage = () => (\n <div className=\"w-full h-full bg-surface-tertiary flex items-center justify-center text-text-quaternary\">\n <svg\n width=\"40\"\n height=\"40\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.5\"\n >\n <title>Product</title>\n <rect x=\"3\" y=\"3\" width=\"18\" height=\"18\" rx=\"2\" ry=\"2\" />\n <circle cx=\"8.5\" cy=\"8.5\" r=\"1.5\" />\n <polyline points=\"21 15 16 10 5 21\" />\n </svg>\n </div>\n);\n","import {\n findMatchingVariant,\n type VariantSelections\n} from '../hooks/use-product-variants.js';\nimport type { ProductVariantDetails } from '../lib/bigcommerce/storefront/types.js';\n\nexport interface VariantPickerProps {\n variantDetails: ProductVariantDetails;\n selections: VariantSelections;\n onSelectionChange: (optionEntityId: number, valueEntityId: number) => void;\n}\n\nexport function VariantPicker({\n variantDetails,\n selections,\n onSelectionChange\n}: VariantPickerProps) {\n const matchingVariant = findMatchingVariant(\n variantDetails.variants,\n selections\n );\n const hasInvalidCombination = !matchingVariant;\n\n return (\n <div className=\"flex flex-col gap-2\">\n {variantDetails.productOptions.map((option) => (\n <div key={option.entityId} className=\"flex flex-col gap-1\">\n <label\n htmlFor={`option-${option.entityId}`}\n className=\"text-xs text-text-tertiary\"\n >\n {option.displayName}\n </label>\n <select\n id={`option-${option.entityId}`}\n value={selections.get(option.entityId) ?? ''}\n onChange={(e) =>\n onSelectionChange(option.entityId, Number(e.target.value))\n }\n className=\"w-full px-2 py-1 text-xs border border-border rounded bg-surface text-text cursor-pointer focus:outline-none focus:ring-1 focus:ring-border-focus focus:border-border-focus\"\n >\n {option.values.map((value) => (\n <option key={value.entityId} value={value.entityId}>\n {value.label}\n </option>\n ))}\n </select>\n </div>\n ))}\n {hasInvalidCombination && (\n <p className=\"text-xs text-error m-0\" role=\"alert\" aria-live=\"polite\">\n This combination is not available\n </p>\n )}\n </div>\n );\n}\n","import { useCallback, useState } from 'react';\nimport {\n findMatchingVariant,\n type VariantSelections\n} from '../hooks/use-product-variants.js';\nimport type { ProductVariantDetails } from '../lib/bigcommerce/storefront/types.js';\nimport { formatCurrency } from '../lib/formatting.js';\nimport type { CartItem, Product } from '../types.js';\nimport { PlaceholderImage } from './icons/placeholder-image-icon.js';\nimport { QuantitySelector } from './quantity-selector.js';\nimport { VariantPicker } from './variant-picker.js';\n\nexport interface ProductCardProps {\n product: Product;\n onAddToCart?: (\n product: Product,\n quantity: number,\n selectedVariantEntityId?: number\n ) => Promise<boolean> | boolean | undefined;\n cart?: CartItem[];\n className?: string;\n layout?: 'vertical' | 'horizontal';\n onViewProduct?: (product: Product) => void;\n // Variant support\n variantDetails?: ProductVariantDetails;\n selections?: VariantSelections;\n onSelectionChange?: (optionEntityId: number, valueEntityId: number) => void;\n}\n\nconst LOW_STOCK_QUANTITY = 10;\n\nfunction addToCartButtonClass(\n isAdding: boolean,\n showAdded: boolean,\n isDisabled: boolean\n): string {\n if (isAdding) return 'bg-surface-tertiary text-text cursor-not-allowed';\n if (showAdded) return 'bg-success/20 text-success-text cursor-not-allowed';\n if (isDisabled)\n return 'bg-surface-disabled text-text-quaternary cursor-not-allowed';\n return 'bg-surface-invert text-text-invert hover:bg-surface-invert-hover cursor-pointer';\n}\n\nexport function ProductCard({\n product,\n onAddToCart,\n cart = [],\n className = '',\n layout = 'vertical',\n onViewProduct,\n variantDetails,\n selections,\n onSelectionChange\n}: ProductCardProps) {\n const [quantity, setQuantity] = useState(1);\n const [isAdding, setIsAdding] = useState(false);\n const [showAdded, setShowAdded] = useState(false);\n\n const isHorizontal = layout === 'horizontal';\n\n // Find the selected variant if we have variant details and selections\n const selectedVariant =\n variantDetails && selections\n ? findMatchingVariant(variantDetails.variants, selections)\n : null;\n\n // Compute cart status using the selected variant\n const selectedVariantEntityId =\n selectedVariant?.entityId ?? product.variantEntityId;\n const cartItem = cart.find(\n (item) =>\n item.productEntityId === product.productEntityId &&\n item.variantEntityId === selectedVariantEntityId\n );\n const inCart = !!cartItem;\n const cartQuantity = cartItem?.quantity ?? 0;\n\n // Use variant data when available, fall back to product data\n const displaySku = selectedVariant?.sku ?? product.sku;\n const displayPrice = selectedVariant?.prices?.price?.value ?? product.price;\n const displayAvailableQuantity =\n selectedVariant?.inventory?.aggregated?.availableToSell ??\n product.availableQuantity;\n\n // Only show low stock warning if we have a positive quantity less than threshold\n // This prevents showing \"Only 0 left\" when inventory tracking is disabled (quantity=0)\n const lowStock =\n displayAvailableQuantity !== undefined &&\n displayAvailableQuantity > 0 &&\n displayAvailableQuantity < LOW_STOCK_QUANTITY;\n\n // Check if product is out of stock:\n // 1. If we have variant details loaded, check variant stock (isPurchasable, isInStock, availableToSell)\n // 2. If no variant details, fall back to product-level stock (isInStock, availableQuantity)\n // 3. If isInStock is explicitly set, use it (handles inventory tracking disabled)\n // 4. Otherwise check if quantity is 0\n const displayIsInStock =\n selectedVariant?.inventory?.isInStock ?? product.isInStock;\n const isOutOfStock =\n selectedVariant !== null\n ? // Have variant details: check variant stock\n !selectedVariant.isPurchasable ||\n displayIsInStock === false ||\n (displayIsInStock === undefined &&\n (selectedVariant.inventory?.aggregated?.availableToSell ?? 0) === 0)\n : // No variant details: check product-level stock\n displayIsInStock === false ||\n (displayIsInStock === undefined && product.availableQuantity === 0);\n\n const hasInvalidCombination =\n variantDetails && selections && !selectedVariant;\n\n const handleAddToCart = useCallback(async () => {\n if (!onAddToCart) return;\n if (hasInvalidCombination || isOutOfStock) return;\n if (quantity < 1) return; // Never allow adding with quantity < 1\n setIsAdding(true);\n try {\n const result = await onAddToCart(\n product,\n quantity,\n selectedVariant?.entityId\n );\n // Only show \"Added\" if the callback returned true (or didn't return anything for backwards compatibility)\n if (result !== false) {\n setShowAdded(true);\n setTimeout(() => {\n setShowAdded(false);\n setQuantity(1);\n }, 1500);\n }\n } finally {\n setIsAdding(false);\n }\n }, [\n onAddToCart,\n product,\n quantity,\n selectedVariant,\n hasInvalidCombination,\n isOutOfStock\n ]);\n\n // Use variant image if available, fall back to product image\n const variantImageUrl = selectedVariant?.defaultImage?.urlTemplate?.replace(\n '{:size}',\n '200w'\n );\n const productImageUrl =\n product.imageUrl ??\n product.defaultImage?.urlTemplate?.replace('{:size}', '200w');\n const imageUrl = variantImageUrl ?? productImageUrl;\n\n // Low stock warning - rendered in different positions based on variant\n const lowStockWarning = lowStock && !isOutOfStock && (\n <p className={`text-xs text-warning m-0 ${isHorizontal ? 'mt-1' : 'mb-2'}`}>\n Only {displayAvailableQuantity} left\n </p>\n );\n\n return (\n <div\n className={`bg-surface rounded-[10px] border overflow-hidden transition-[border-color,box-shadow] duration-150 flex ${\n isHorizontal\n ? 'flex-row border-border hover:shadow-md'\n : `w-[180px] shrink-0 flex-col border-border hover:border-border-strong hover:shadow-[0_2px_8px_rgba(0,0,0,0.06)]${isOutOfStock ? ' opacity-70' : ''}`\n } ${className}`}\n >\n {/* Image section */}\n <div\n className={\n isHorizontal\n ? 'shrink-0 w-[120px] h-[120px]'\n : 'relative shrink-0 aspect-[4/3] overflow-hidden bg-surface-tertiary'\n }\n >\n {imageUrl ? (\n <img\n src={imageUrl}\n alt={product.name}\n className=\"w-full h-full object-cover\"\n />\n ) : (\n <PlaceholderImage />\n )}\n {!isHorizontal && isOutOfStock && (\n <div className=\"absolute top-2 right-2 bg-error text-text-invert text-[0.6875rem] font-semibold px-2 py-0.5 rounded\">\n Out of stock\n </div>\n )}\n </div>\n\n {/* Content section */}\n <div\n className={\n isHorizontal\n ? 'flex-1 p-3 flex flex-col justify-between min-w-0'\n : 'flex-1 flex flex-col'\n }\n >\n {/* Info: name, sku, price, out of stock */}\n <div className={isHorizontal ? '' : 'grow p-3 pb-0'}>\n {onViewProduct ? (\n <button\n type=\"button\"\n onClick={() => onViewProduct(product)}\n className=\"text-sm font-medium text-text m-0 truncate bg-transparent border-none cursor-pointer p-0 text-left hover:underline w-full\"\n title={product.name}\n >\n {product.name}\n </button>\n ) : (\n <h4\n className=\"text-sm font-medium text-text m-0 truncate\"\n title={product.name}\n >\n {product.name}\n </h4>\n )}\n <p className=\"text-xs text-text-quaternary m-0 mt-0.5\">\n {displaySku}\n </p>\n {displayPrice !== undefined && (\n <p className=\"text-sm font-semibold text-text m-0 mt-1\">\n {formatCurrency(displayPrice)}\n </p>\n )}\n {isOutOfStock && (\n <p className=\"text-xs text-error m-0 mt-1 font-medium\">\n Out of Stock\n </p>\n )}\n {!isHorizontal &&\n !isOutOfStock &&\n displayAvailableQuantity !== undefined &&\n displayAvailableQuantity > 0 && (\n <p className=\"text-[0.625rem] text-success font-medium m-0 mt-0.5\">\n {displayAvailableQuantity} in stock\n </p>\n )}\n {/* Low stock in info section for horizontal */}\n {isHorizontal && lowStockWarning}\n </div>\n\n {/* Variant picker */}\n {variantDetails && selections && onSelectionChange && (\n <div className={isHorizontal ? 'mt-2' : 'shrink-0 px-3 pt-2'}>\n <VariantPicker\n variantDetails={variantDetails}\n selections={selections}\n onSelectionChange={onSelectionChange}\n />\n </div>\n )}\n\n {/* Actions section */}\n <div\n className={\n isHorizontal ? 'flex items-center gap-2 mt-2' : 'shrink-0 p-3 pt-2'\n }\n >\n {/* Low stock in actions section for vertical */}\n {!isHorizontal && lowStockWarning}\n\n {inCart && (\n <p className=\"text-xs text-text-tertiary m-0 mb-1\">\n In cart (×{cartQuantity})\n </p>\n )}\n <div\n className={\n isHorizontal ? 'flex items-center gap-2' : 'flex flex-col gap-2'\n }\n >\n <QuantitySelector\n value={quantity}\n onChange={setQuantity}\n max={\n displayAvailableQuantity && displayAvailableQuantity > 0\n ? displayAvailableQuantity\n : undefined\n }\n className={isHorizontal ? '' : 'justify-center'}\n testId={`quantity-input-${displaySku}`}\n />\n <button\n type=\"button\"\n onClick={handleAddToCart}\n disabled={\n isAdding || showAdded || !!hasInvalidCombination || isOutOfStock\n }\n className={`py-1.5 px-3 text-xs font-medium rounded border-none ${\n isHorizontal ? '' : 'w-full'\n } ${addToCartButtonClass(isAdding, showAdded, !!hasInvalidCombination || isOutOfStock)}`}\n >\n {isAdding ? 'Adding...' : showAdded ? '✓ Added' : 'Add to cart'}\n </button>\n </div>\n </div>\n </div>\n </div>\n );\n}\n","import { useEffect, useMemo, useState } from 'react';\nimport { useBigCommerceClient } from '../contexts/bigcommerce-client-context.js';\nimport {\n getInitialSelections,\n getVariantOptionValues,\n useProductVariants,\n type VariantSelections\n} from '../hooks/use-product-variants.js';\nimport type { BigCommerceClient } from '../lib/bigcommerce/index.js';\nimport type { CartItem, Product } from '../types.js';\nimport { ProductCard } from './product-card.js';\n\nexport interface ProductGridProps {\n products: Product[];\n onAddToCart?: (\n product: Product,\n quantity: number,\n selectedVariantEntityId?: number\n ) => Promise<boolean> | boolean | undefined;\n onViewProduct?: (product: Product) => void;\n cart: CartItem[];\n isLoading?: boolean;\n loadingText?: string;\n className?: string;\n}\n\nexport function ProductGrid({\n products,\n onAddToCart,\n onViewProduct,\n cart,\n isLoading = false,\n loadingText = 'Searching for products...',\n className = ''\n}: ProductGridProps) {\n const client = useBigCommerceClient();\n\n // Get product entity IDs for fetching variant details\n const productEntityIds = useMemo(\n () =>\n products\n .filter((p) => p.productEntityId !== undefined)\n .map((p) => p.productEntityId as number),\n [products]\n );\n\n // Fetch variant details for all products (if client available from context)\n const { data: variantDetailsArray } = useProductVariants(\n client as BigCommerceClient,\n client ? productEntityIds : []\n );\n\n // Create a map of productEntityId -> variantDetails\n const variantDetailsMap = useMemo(() => {\n const map = new Map<\n number,\n NonNullable<typeof variantDetailsArray>[number]\n >();\n if (variantDetailsArray) {\n for (const details of variantDetailsArray) {\n // Only include products with multiple variants (has variant options)\n if (details.productOptions.length > 0) {\n map.set(details.entityId, details);\n }\n }\n }\n return map;\n }, [variantDetailsArray]);\n\n // Track selections per product: Map<product.id, VariantSelections>\n const [selectionsMap, setSelectionsMap] = useState<\n Map<string, VariantSelections>\n >(new Map());\n\n // Initialize selections when variant details are loaded\n useEffect(() => {\n if (!variantDetailsArray) return;\n\n setSelectionsMap((prev) => {\n const next = new Map(prev);\n\n // Initialize selections for each product in the list\n for (const product of products) {\n if (product.productEntityId === undefined) continue;\n if (next.has(product.id)) continue; // Already initialized\n\n const details = variantDetailsArray.find(\n (d) => d.entityId === product.productEntityId\n );\n if (!details || details.productOptions.length === 0) continue;\n\n let selections: VariantSelections;\n if (product.variantEntityId) {\n // Find the specific variant and use its option values\n const requestedVariant = details.variants.find(\n (v) => v.entityId === product.variantEntityId\n );\n if (requestedVariant) {\n selections = getVariantOptionValues(requestedVariant);\n } else {\n selections = getInitialSelections(details);\n }\n } else {\n selections = getInitialSelections(details);\n }\n\n next.set(product.id, selections);\n }\n\n return next;\n });\n }, [variantDetailsArray, products]);\n\n // Handler for selection changes\n const handleSelectionChange = (\n productId: string,\n optionEntityId: number,\n valueEntityId: number\n ) => {\n setSelectionsMap((prev) => {\n const next = new Map(prev);\n const selections = new Map(next.get(productId) ?? new Map());\n selections.set(optionEntityId, valueEntityId);\n next.set(productId, selections);\n return next;\n });\n };\n\n if (isLoading) {\n return (\n <div className={`py-3 ${className}`}>\n <div className=\"flex items-center gap-2 text-sm text-text-tertiary\">\n <div className=\"w-4 h-4 border-2 border-border-focus border-t-transparent rounded-full animate-spin\" />\n <span>{loadingText}</span>\n </div>\n </div>\n );\n }\n\n const availableProducts = products.filter((product) => {\n // If isInStock is explicitly set, use it (handles inventory tracking disabled case)\n if (product.isInStock !== undefined) {\n return product.isInStock;\n }\n // Fallback to checking availableQuantity for older data or when isInStock is missing\n return product.availableQuantity !== 0;\n });\n\n if (availableProducts.length === 0) {\n return null;\n }\n\n // Single product: use horizontal layout\n const [singleProduct] = availableProducts;\n if (availableProducts.length === 1 && singleProduct) {\n const variantDetails =\n singleProduct.productEntityId !== undefined\n ? variantDetailsMap.get(singleProduct.productEntityId)\n : undefined;\n const selections = selectionsMap.get(singleProduct.id);\n\n return (\n <div className={`py-2 ${className}`}>\n <ProductCard\n layout=\"horizontal\"\n product={singleProduct}\n onAddToCart={onAddToCart}\n onViewProduct={onViewProduct}\n cart={cart}\n variantDetails={variantDetails}\n selections={selections}\n onSelectionChange={\n variantDetails\n ? (optionId, valueId) =>\n handleSelectionChange(singleProduct.id, optionId, valueId)\n : undefined\n }\n />\n </div>\n );\n }\n\n // Multiple products: use wrapping grid\n return (\n <div className={`flex flex-wrap gap-3 py-2 ${className}`}>\n {availableProducts.map((product) => {\n const variantDetails =\n product.productEntityId !== undefined\n ? variantDetailsMap.get(product.productEntityId)\n : undefined;\n const selections = selectionsMap.get(product.id);\n\n return (\n <ProductCard\n key={product.id}\n product={product}\n onAddToCart={onAddToCart}\n onViewProduct={onViewProduct}\n cart={cart}\n variantDetails={variantDetails}\n selections={selections}\n onSelectionChange={\n variantDetails\n ? (optionId, valueId) =>\n handleSelectionChange(product.id, optionId, valueId)\n : undefined\n }\n />\n );\n })}\n </div>\n );\n}\n","import { useEffect, useState } from 'react';\nimport { useBigCommerceClient } from '../../contexts/bigcommerce-client-context.js';\nimport type { CartItem, Product } from '../../types.js';\nimport { ProductGrid } from '../product-grid.js';\n\nexport interface ShowProductsInput {\n products: Array<{\n entityId: number;\n variantEntityId?: number;\n }>;\n}\n\nexport interface ShowProductsToolProps {\n toolInput?: ShowProductsInput;\n toolOutput: unknown;\n toolState: string;\n cart: CartItem[];\n onAddToCart?: (\n product: Product,\n quantity: number\n ) => Promise<boolean> | boolean | undefined;\n onViewProduct?: (product: Product) => void;\n}\n\nexport function ShowProductsTool({\n toolInput,\n toolState,\n cart,\n onAddToCart,\n onViewProduct\n}: ShowProductsToolProps) {\n const client = useBigCommerceClient();\n const [products, setProducts] = useState<Product[]>([]);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n const isToolLoading = toolState !== 'output-available';\n\n useEffect(() => {\n async function fetchProducts() {\n if (!client) {\n console.error('BigCommerce client not available');\n setError('Unable to load products');\n setIsLoading(false);\n return;\n }\n\n try {\n setError(null);\n if (!toolInput?.products?.length) {\n setProducts([]);\n setIsLoading(false);\n return;\n }\n\n // Extract unique product entity IDs\n const productEntityIds = [\n ...new Set(toolInput.products.map((p) => p.entityId))\n ];\n\n // Fetch product details\n const productsData =\n await client.getProductsForDisplay(productEntityIds);\n\n // Transform to Product[] format, matching specific variants if provided\n const transformedProducts: Product[] = [];\n\n for (const inputProduct of toolInput.products) {\n const productData = productsData.find(\n (p) => p.entityId === inputProduct.entityId\n );\n\n if (!productData) continue;\n\n // If a specific variant is requested, find it\n const variant = inputProduct.variantEntityId\n ? productData.variants.find(\n (v) => v.entityId === inputProduct.variantEntityId\n )\n : productData.variants[0];\n\n if (variant) {\n transformedProducts.push({\n id: `${productData.entityId}-${variant.entityId}`,\n sku: variant.sku,\n name: productData.name,\n path: productData.path,\n price: variant.prices?.price?.value,\n imageUrl:\n variant.defaultImage?.urlTemplate?.replace('{:size}', '200w') ??\n productData.defaultImage?.urlTemplate?.replace(\n '{:size}',\n '200w'\n ),\n availableQuantity:\n variant.inventory?.aggregated?.availableToSell ?? undefined,\n isInStock: variant.inventory?.isInStock ?? undefined,\n productEntityId: productData.entityId,\n variantEntityId: variant.entityId\n });\n }\n }\n\n setProducts(transformedProducts);\n } catch (err) {\n console.error('Failed to fetch products:', err);\n setError('Failed to load products');\n setProducts([]);\n } finally {\n setIsLoading(false);\n }\n }\n\n fetchProducts();\n }, [client, toolInput]);\n\n if (error) {\n return <div className=\"py-2 text-sm text-error-text\">{error}</div>;\n }\n\n return (\n <ProductGrid\n products={products}\n onAddToCart={onAddToCart}\n onViewProduct={onViewProduct}\n cart={cart}\n isLoading={isToolLoading || isLoading}\n loadingText=\"Loading suggested products...\"\n />\n );\n}\n","import type { CartItem, Product } from '../../types.js';\nimport { GenericToolMessage } from './generic-tool-message.js';\nimport { GetProductVariantsTool } from './get-product-variants-tool.js';\nimport { SearchProductsBySkuTool } from './search-products-by-sku-tool.js';\nimport { SearchProductsTool } from './search-products-tool.js';\nimport {\n type ShowProductsInput,\n ShowProductsTool\n} from './show-products-tool.js';\n\nexport interface ToolProps {\n toolCallId: string;\n toolName: string;\n toolInput?: unknown;\n toolOutput?: unknown;\n toolState?: string;\n cart: CartItem[];\n onAddToCart?: (\n product: Product,\n quantity: number,\n selectedVariantEntityId?: number\n ) => Promise<boolean> | boolean | undefined;\n onViewProduct?: (product: Product) => void;\n}\n\nexport function Tool({\n toolCallId,\n toolName,\n toolInput,\n toolOutput,\n toolState,\n cart,\n onAddToCart,\n onViewProduct\n}: ToolProps) {\n if (toolName === 'showProducts') {\n return (\n <div className=\"mt-3\">\n <ShowProductsTool\n toolInput={toolInput as ShowProductsInput}\n toolOutput={toolOutput}\n toolState={toolState ?? ''}\n cart={cart}\n onAddToCart={onAddToCart}\n onViewProduct={onViewProduct}\n />\n </div>\n );\n }\n\n if (toolName === 'searchProducts') {\n return (\n <SearchProductsTool\n toolCallId={toolCallId}\n toolInput={toolInput}\n toolOutput={toolOutput}\n toolState={toolState ?? ''}\n />\n );\n }\n\n if (toolName === 'searchProductsBySku') {\n return (\n <SearchProductsBySkuTool\n toolCallId={toolCallId}\n toolInput={toolInput}\n toolOutput={toolOutput}\n toolState={toolState ?? ''}\n />\n );\n }\n\n if (toolName === 'getProductVariants') {\n return (\n <GetProductVariantsTool\n toolCallId={toolCallId}\n toolInput={toolInput}\n toolOutput={toolOutput}\n toolState={toolState ?? ''}\n />\n );\n }\n\n if (toolName === 'addToCart') {\n return (\n <GenericToolMessage\n toolCallId={toolCallId}\n loadingMessage=\"Adding to cart...\"\n failedMessage=\"Failed to add to cart\"\n successMessage=\"Added to cart\"\n toolOutput={toolOutput}\n />\n );\n }\n\n if (toolName === 'updateCart') {\n return (\n <GenericToolMessage\n toolCallId={toolCallId}\n loadingMessage=\"Updating cart...\"\n failedMessage=\"Failed to update cart\"\n successMessage=\"Updated cart\"\n toolOutput={toolOutput}\n />\n );\n }\n\n if (toolName === 'removeFromCart') {\n return (\n <GenericToolMessage\n toolCallId={toolCallId}\n loadingMessage=\"Removing from cart...\"\n failedMessage=\"Failed to remove from cart\"\n successMessage=\"Removed from cart\"\n toolOutput={toolOutput}\n />\n );\n }\n\n if (toolName === 'clearCart') {\n return (\n <GenericToolMessage\n toolCallId={toolCallId}\n loadingMessage=\"Clearing cart...\"\n failedMessage=\"Failed to clear cart\"\n successMessage=\"Cart cleared\"\n toolOutput={toolOutput}\n />\n );\n }\n\n if (toolName === 'getCart') {\n return (\n <GenericToolMessage\n toolCallId={toolCallId}\n loadingMessage=\"Retrieving cart...\"\n successMessage=\"Retrieved cart\"\n toolOutput={toolOutput}\n />\n );\n }\n\n if (toolName === 'setPoMetadata') {\n return (\n <GenericToolMessage\n toolCallId={toolCallId}\n loadingMessage=\"Saving metadata...\"\n successMessage=\"Saved metadata\"\n toolOutput={toolOutput}\n />\n );\n }\n\n if (toolName === 'setItemWarnings') {\n return (\n <GenericToolMessage\n toolCallId={toolCallId}\n loadingMessage=\"Updating warnings...\"\n successMessage=\"Warnings updated\"\n toolOutput={toolOutput}\n />\n );\n }\n\n if (toolName === 'removeItemWarnings') {\n return (\n <GenericToolMessage\n toolCallId={toolCallId}\n loadingMessage=\"Removing warnings...\"\n successMessage=\"Warnings removed\"\n toolOutput={toolOutput}\n />\n );\n }\n\n return null;\n}\n","import { useState } from 'react';\nimport type { CartItem, Product, ToolPart } from '../../types.js';\nimport { ExpandChevronIcon } from '../icons/expand-chevron-icon.js';\nimport { Tool } from './tool.js';\n\ninterface CollapsibleToolCallsProps {\n tools: ToolPart[];\n messageId: string;\n cart: CartItem[];\n onAddToCart?: (\n product: Product,\n quantity: number,\n selectedVariantEntityId?: number\n ) => Promise<boolean> | boolean | undefined;\n onViewProduct?: (product: Product) => void;\n}\n\nexport function CollapsibleToolCalls({\n tools,\n messageId,\n cart,\n onAddToCart,\n onViewProduct\n}: CollapsibleToolCallsProps) {\n const [isExpanded, setIsExpanded] = useState(false);\n\n if (tools.length === 0) return null;\n\n return (\n <div>\n <button\n type=\"button\"\n aria-expanded={isExpanded}\n aria-controls={`collapsible-${messageId}`}\n onClick={() => setIsExpanded(!isExpanded)}\n className=\"flex items-center gap-1.5 text-xs text-text-secondary italic w-full group\"\n >\n <span\n className={`transition-transform duration-200 ${isExpanded ? 'rotate-90' : ''}`}\n aria-hidden=\"true\"\n >\n <ExpandChevronIcon />\n </span>\n <span className=\"flex-1 text-left\">\n {tools.length} tool call{tools.length !== 1 ? 's' : ''}\n </span>\n </button>\n <div\n id={`collapsible-${messageId}`}\n data-testid=\"collapsible-panel\"\n className={`collapsible-panel ${isExpanded ? 'collapsible-panel-open' : ''}`}\n >\n <div className=\"overflow-hidden\">\n <div className=\"pl-2.5 border-l border-gray-200 ml-[1px] my-2\">\n {tools.map((toolPart) => (\n <Tool\n key={toolPart.toolCallId}\n toolCallId={toolPart.toolCallId}\n toolName={toolPart.toolName}\n toolInput={toolPart.toolInput}\n toolOutput={toolPart.toolOutput}\n toolState={toolPart.toolState}\n cart={cart}\n onAddToCart={onAddToCart}\n onViewProduct={onViewProduct}\n />\n ))}\n </div>\n </div>\n </div>\n </div>\n );\n}\n","import { useMemo } from 'react';\nimport { Streamdown } from 'streamdown';\nimport { usePurchaseOrderStore } from '../../../stores/purchase-order-store.js';\nimport { ExpandChevronIcon } from '../../icons/expand-chevron-icon.js';\n\ninterface CollapsibleAgentMessageProps {\n messageId: string;\n isLatestAssistantMessage: boolean;\n text: string;\n}\n\nexport function CollapsibleAgentMessage({\n messageId,\n isLatestAssistantMessage,\n text\n}: CollapsibleAgentMessageProps) {\n const previewText = useMemo(() => {\n return text.slice(0, 80);\n }, [text]);\n const expandedMessageIds = usePurchaseOrderStore(\n (state) => state.ui.expandedMessageIds\n );\n const toggleMessageExpanded = usePurchaseOrderStore(\n (state) => state.toggleMessageExpanded\n );\n\n // Latest assistant message is always expanded\n // Older messages are expanded only if explicitly toggled\n const isExpanded =\n isLatestAssistantMessage || expandedMessageIds.includes(messageId);\n\n // Latest message doesn't need the collapsible wrapper\n if (isLatestAssistantMessage) {\n return (\n <div className=\"my-2\">\n <Streamdown className=\"leading-relaxed text-text\" plugins={{}}>\n {text}\n </Streamdown>\n </div>\n );\n }\n\n return (\n <div className=\"\">\n <button\n type=\"button\"\n aria-expanded={isExpanded}\n aria-controls={`collapsible-message-${messageId}`}\n onClick={() => toggleMessageExpanded(messageId)}\n className=\"flex items-center gap-1.5 text-xs text-text w-full group\"\n >\n <span\n className={`transition-transform duration-200 ${isExpanded ? 'rotate-90' : ''}`}\n aria-hidden=\"true\"\n >\n <ExpandChevronIcon />\n </span>\n <span className=\"flex-1 text-left truncate\">\n {isExpanded ? 'Hide message' : previewText}\n </span>\n </button>\n <div\n id={`collapsible-message-${messageId}`}\n data-testid=\"collapsible-message-panel\"\n className={`collapsible-panel ${isExpanded ? 'collapsible-panel-open' : ''}`}\n >\n <div className=\"overflow-hidden\">\n <div className=\"pl-2.5 border-l border-gray-200 ml-[1px] my-2\">\n <Streamdown\n className=\"text-xs leading-relaxed text-text\"\n plugins={{}}\n >\n {text}\n </Streamdown>\n </div>\n </div>\n </div>\n </div>\n );\n}\n","import type { UIMessage } from 'ai';\nimport { Streamdown } from 'streamdown';\nimport { CLIENT_TOOL_RESPONSE_MESSAGE } from '../../../constants.js';\nimport type { CartItem, Product, RenderablePart } from '../../../types.js';\nimport { groupRenderableParts } from '../../../utils/group-renderable-parts.js';\nimport { FileIcon } from '../../icons/file-icon.js';\nimport { CollapsibleToolCalls } from '../../tools/collapsible-tool-calls.js';\nimport { Tool } from '../../tools/tool.js';\nimport { CollapsibleAgentMessage } from './collapsible-agent-message.js';\n\nexport interface ChatMessageProps {\n message: UIMessage;\n isFirstUserMessage: boolean;\n isLatestAssistantMessage: boolean;\n isDocumentExpanded: boolean;\n onToggleDocument: () => void;\n uploadedFileName: string | null;\n cart: CartItem[];\n onAddToCart?: (\n product: Product,\n quantity: number\n ) => Promise<boolean> | boolean | undefined;\n onViewProduct?: (product: Product) => void;\n}\n\nfunction getOrderedParts(message: UIMessage): RenderablePart[] {\n if (!message.parts) {\n return [];\n }\n\n const results: RenderablePart[] = [];\n\n for (const part of message.parts) {\n if (part.type === 'text' && part.text !== CLIENT_TOOL_RESPONSE_MESSAGE) {\n results.push({\n type: 'text',\n text: part.text\n });\n } else if (part.type.startsWith('tool-') && 'state' in part) {\n const toolName = part.type.slice(5);\n const toolPart = part as {\n toolCallId: string;\n input?: unknown;\n output?: unknown;\n state: string;\n };\n results.push({\n type: 'tool',\n toolCallId: toolPart.toolCallId,\n toolName,\n toolInput: toolPart.input,\n toolOutput:\n toolPart.state === 'output-available' ? toolPart.output : undefined,\n toolState: toolPart.state\n });\n }\n }\n\n return results;\n}\n\nfunction getFilename(parts: UIMessage['parts']): string {\n const filePart = parts?.find((part) => part.type === 'file');\n if (\n filePart &&\n 'filename' in filePart &&\n typeof filePart.filename === 'string'\n ) {\n return filePart.filename;\n }\n return 'Attachment';\n}\n\nexport function ChatMessage({\n message,\n isFirstUserMessage,\n isLatestAssistantMessage,\n isDocumentExpanded,\n onToggleDocument,\n uploadedFileName,\n cart,\n onAddToCart,\n onViewProduct\n}: ChatMessageProps) {\n const isAssistant = message.role === 'assistant';\n const orderedParts = getOrderedParts(message);\n\n if (orderedParts.length === 0) {\n return null;\n }\n\n return (\n <div\n className={`flex px-5 ${isAssistant ? 'justify-start' : 'justify-end my-2'}`}\n >\n <div className={isAssistant ? 'min-w-0 w-full' : 'max-w-[80%]'}>\n {/* Render first user message as expandable attachment */}\n {isFirstUserMessage ? (\n <div className=\"rounded-2xl bg-surface-tertiary px-4 py-2.5\">\n <button\n type=\"button\"\n onClick={onToggleDocument}\n className=\"flex items-center gap-2 px-3 py-2 bg-surface hover:bg-surface-secondary rounded-lg transition-colors border border-border text-left w-full\"\n >\n <FileIcon />\n <span className=\"text-[0.9375rem] text-text font-medium\">\n {uploadedFileName || 'Uploaded Document'}\n </span>\n <svg\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n className={`ml-auto transition-transform ${isDocumentExpanded ? 'rotate-180' : ''}`}\n >\n <title>{isDocumentExpanded ? 'Collapse' : 'Expand'}</title>\n <polyline points=\"6 9 12 15 18 9\" />\n </svg>\n </button>\n {isDocumentExpanded && (\n <div className=\"mt-2 p-3 bg-surface border border-border rounded-lg max-h-96 overflow-y-auto\">\n {orderedParts.map((part, index) => {\n if (part.type === 'text') {\n return (\n <Streamdown\n key={`text-${message.id}-${index}`}\n className=\"text-[0.875rem] leading-normal text-text\"\n plugins={{}}\n >\n {part.text}\n </Streamdown>\n );\n }\n return null;\n })}\n </div>\n )}\n </div>\n ) : (\n <>\n {groupRenderableParts(orderedParts).map((part, index) => {\n if (part.type === 'tool-group') {\n return (\n <CollapsibleToolCalls\n key={`group-${message.id}-${index}`}\n tools={part.tools}\n messageId={`${message.id}-${index}`}\n cart={cart}\n onAddToCart={onAddToCart}\n onViewProduct={onViewProduct}\n />\n );\n }\n\n if (part.type === 'text') {\n return isAssistant ? (\n <CollapsibleAgentMessage\n key={`text-${message.id}-${index}`}\n messageId={`${message.id}-${index}`}\n isLatestAssistantMessage={isLatestAssistantMessage}\n text={part.text}\n />\n ) : (\n <div\n key={`text-${message.id}-${index}`}\n className=\"rounded-2xl bg-surface-tertiary px-4 py-2.5\"\n >\n <Streamdown\n className=\"text-[0.9375rem] leading-relaxed text-text\"\n plugins={{}}\n >\n {part.text}\n </Streamdown>\n </div>\n );\n }\n\n if (part.type === 'tool') {\n return (\n <div key={part.toolCallId} className=\"ml-5\">\n <Tool\n toolCallId={part.toolCallId}\n toolName={part.toolName}\n toolInput={part.toolInput}\n toolOutput={part.toolOutput}\n toolState={part.toolState}\n cart={cart}\n onAddToCart={onAddToCart}\n onViewProduct={onViewProduct}\n />\n </div>\n );\n }\n\n return null;\n })}\n {/* Show attachment indicator for user messages with files */}\n {!isAssistant &&\n message.parts?.some((part) => part.type === 'file') && (\n <div className=\"flex items-center gap-1.5 mt-2 text-xs text-text-tertiary\">\n <FileIcon />\n <span>{getFilename(message.parts)}</span>\n </div>\n )}\n </>\n )}\n </div>\n </div>\n );\n}\n","import { useEffect, useState } from 'react';\n\nexport function useTouchDevice(): boolean {\n const [isTouch, setIsTouch] = useState(false);\n\n useEffect(() => {\n if (typeof window.matchMedia !== 'function') {\n setIsTouch(\n 'ontouchstart' in window || navigator.maxTouchPoints > 0\n );\n return;\n }\n\n const mq = window.matchMedia('(pointer: coarse)');\n setIsTouch(mq.matches);\n const handler = (e: MediaQueryListEvent) => setIsTouch(e.matches);\n mq.addEventListener('change', handler);\n return () => mq.removeEventListener('change', handler);\n }, []);\n\n return isTouch;\n}\n","const ALLOWED_FILE_TYPES: Record<string, string> = {\n 'application/pdf': '.pdf',\n 'text/csv': '.csv',\n 'application/vnd.ms-excel': '.xls',\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': '.xlsx',\n 'text/plain': '.txt',\n 'application/json': '.json',\n 'image/png': '.png',\n 'image/jpeg': '.jpg,.jpeg',\n 'image/heic': '.heic',\n 'image/heif': '.heif'\n};\n\nconst ALLOWED_TYPES = Object.keys(ALLOWED_FILE_TYPES);\n\nexport const ACCEPTED_EXTENSIONS = Object.values(ALLOWED_FILE_TYPES).join(',');\nexport const ALLOWED_TYPES_DISPLAY = 'PDF, Excel, CSV, text, or image files';\nexport const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB\n\nexport interface FileValidationResult {\n valid: boolean;\n error?: string;\n}\n\nexport function validateFile(file: File): FileValidationResult {\n if (file.size > MAX_FILE_SIZE) {\n return {\n valid: false,\n error: 'File size exceeds 10MB limit. Please choose a smaller file.'\n };\n }\n\n if (!ALLOWED_TYPES.includes(file.type)) {\n return {\n valid: false,\n error: `File type not supported. Please upload ${ALLOWED_TYPES_DISPLAY}.`\n };\n }\n\n return { valid: true };\n}\n","export const UploadDocumentIcon = () => (\n <svg\n width=\"48\"\n height=\"48\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.5\"\n >\n <title>Upload file</title>\n <path d=\"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z\" />\n <polyline points=\"14 2 14 8 20 8\" />\n <line x1=\"12\" y1=\"18\" x2=\"12\" y2=\"12\" />\n <polyline points=\"9 15 12 12 15 15\" />\n </svg>\n);\n","export const CameraIcon = () => (\n <svg\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <title>Take photo</title>\n <path d=\"M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z\" />\n <circle cx=\"12\" cy=\"13\" r=\"4\" />\n </svg>\n);\n","import { CameraIcon } from '../icons/camera-icon.js';\n\nexport interface CameraButtonProps {\n onClick: () => void;\n}\n\nexport function CameraButton({ onClick }: CameraButtonProps) {\n return (\n <button\n type=\"button\"\n className=\"flex items-center gap-2 min-h-11 py-2.5 px-5 bg-surface border border-border-strong rounded-full text-sm font-medium text-text cursor-pointer transition-colors hover:bg-surface-secondary focus-visible:outline-2 focus-visible:outline-border-focus focus-visible:outline-offset-2\"\n onClick={onClick}\n >\n <CameraIcon />\n Take a photo\n </button>\n );\n}","import { type ChangeEvent, useCallback, useRef, useState } from 'react';\nimport { useTouchDevice } from '../../../hooks/use-touch-device.js';\nimport {\n ACCEPTED_EXTENSIONS,\n validateFile\n} from '../../../lib/file-validation.js';\nimport { UploadDocumentIcon } from '../../icons/upload-document-icon.js';\nimport { CameraButton } from '../../uploader/camera-button.js';\n\nexport interface ChatPanelEmptyStateProps {\n onFileUpload?: (file: File) => void;\n}\n\nexport function ChatPanelEmptyState({\n onFileUpload\n}: ChatPanelEmptyStateProps) {\n const fileInputRef = useRef<HTMLInputElement>(null);\n const cameraInputRef = useRef<HTMLInputElement>(null);\n const isTouchDevice = useTouchDevice();\n const [fileError, setFileError] = useState<string | null>(null);\n\n const handleClick = useCallback(() => {\n if (onFileUpload) {\n fileInputRef.current?.click();\n }\n }, [onFileUpload]);\n\n const handleCameraClick = useCallback(() => {\n if (onFileUpload) {\n cameraInputRef.current?.click();\n }\n }, [onFileUpload]);\n\n const handleFileChange = useCallback(\n (e: ChangeEvent<HTMLInputElement>) => {\n const file = e.target.files?.[0];\n if (file && onFileUpload) {\n const result = validateFile(file);\n if (!result.valid) {\n setFileError(result.error ?? null);\n return;\n }\n setFileError(null);\n onFileUpload(file);\n }\n if (e.target) {\n e.target.value = '';\n }\n },\n [onFileUpload]\n );\n\n return (\n <div className=\"flex-1 flex items-center justify-center animate-fade-in-up\">\n <div className=\"flex flex-col items-center gap-4\">\n <button\n type=\"button\"\n className=\"flex flex-col items-center gap-4 bg-transparent border-none cursor-pointer p-6 rounded-2xl transition-colors hover:bg-surface-secondary\"\n onClick={handleClick}\n >\n <input\n ref={fileInputRef}\n type=\"file\"\n className=\"hidden\"\n onChange={handleFileChange}\n accept={ACCEPTED_EXTENSIONS}\n />\n <input\n ref={cameraInputRef}\n type=\"file\"\n className=\"hidden\"\n onChange={handleFileChange}\n accept=\"image/*\"\n capture=\"environment\"\n />\n <div className=\"flex items-center justify-center w-16 h-16 rounded-[14px] p-1 border-2 border-dashed border-border-focus text-text\">\n <UploadDocumentIcon />\n </div>\n <h3 className=\"m-0 text-base font-semibold text-text text-center\">\n Upload your Purchase Order\n </h3>\n <p className=\"m-0 text-sm text-text-tertiary text-center\">\n Get automagical product matching and stock availability\n </p>\n <div className=\"flex flex-wrap justify-center gap-2\">\n {['PDF', 'Excel', 'CSV'].map((label) => (\n <span\n key={label}\n className=\"py-1 px-3 bg-surface-invert/5 border border-border-strong rounded-full text-xs font-medium text-text\"\n >\n {label}\n </span>\n ))}\n </div>\n </button>\n {isTouchDevice && onFileUpload && (\n <CameraButton onClick={handleCameraClick} />\n )}\n {fileError && (\n <div className=\"flex items-center gap-2 py-3 px-4 bg-error-bg border border-error/30 rounded-lg text-error-text text-sm max-w-[400px] text-center\">\n {fileError}\n </div>\n )}\n </div>\n </div>\n );\n}\n","export function TypingIndicator() {\n return (\n <div className=\"flex justify-start px-5 py-2\">\n <div className=\"flex flex-col gap-2 w-3/4\">\n <div className=\"h-3 rounded-full animate-shimmer\" />\n <div\n className=\"h-3 w-1/2 rounded-full animate-shimmer\"\n style={{ animationDelay: '0.15s' }}\n />\n </div>\n </div>\n );\n}\n","import type { UIMessage } from 'ai';\nimport {\n type ChangeEvent,\n type FormEvent,\n forwardRef,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n useState\n} from 'react';\nimport type { CartItem, Product } from '../../../types.js';\nimport { ChatError } from './chat-error.js';\nimport { ChatInput } from './chat-input.js';\nimport { ChatMessage } from './chat-message.js';\nimport { ChatPanelEmptyState } from './chat-panel-empty-state.js';\nimport { TypingIndicator } from './typing-indicator.js';\n\nexport interface ChatPanelProps {\n messages: UIMessage[];\n input: string;\n onInputChange: (e: ChangeEvent<HTMLTextAreaElement>) => void;\n onSubmit: (e: FormEvent<HTMLFormElement>) => void;\n isLoading: boolean;\n cart: CartItem[];\n onAddToCart?: (\n product: Product,\n quantity: number\n ) => Promise<boolean> | boolean | undefined;\n onViewProduct?: (product: Product) => void;\n className?: string;\n error?: Error | null;\n onRetry?: () => void;\n hasProcessedDocument?: boolean;\n uploadedFileName?: string | null;\n onFileUpload?: (file: File) => void;\n}\n\nexport interface ChatPanelRef {\n scrollToBottom: () => void;\n}\n\nexport const ChatPanel = forwardRef<ChatPanelRef, ChatPanelProps>(\n function ChatPanel(\n {\n messages,\n input,\n onInputChange,\n onSubmit,\n isLoading,\n cart,\n onAddToCart,\n onViewProduct,\n className = '',\n error = null,\n onRetry,\n hasProcessedDocument = false,\n uploadedFileName = null,\n onFileUpload\n },\n ref\n ) {\n const scrollContainerRef = useRef<HTMLDivElement>(null);\n const shouldAutoScrollRef = useRef(true);\n const [isDocumentExpanded, setIsDocumentExpanded] = useState(false);\n\n const latestAssistantMessageId = useMemo(() => {\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (msg?.role === 'assistant') {\n return msg.id;\n }\n }\n return null;\n }, [messages]);\n\n useImperativeHandle(ref, () => ({\n scrollToBottom: () => {\n const container = scrollContainerRef.current;\n if (container) {\n const distance =\n container.scrollHeight -\n container.scrollTop -\n container.clientHeight;\n if (distance > 500 || !container.scrollTo) {\n container.scrollTop = container.scrollHeight;\n } else {\n container.scrollTo({\n top: container.scrollHeight,\n behavior: 'smooth'\n });\n }\n }\n shouldAutoScrollRef.current = true;\n }\n }));\n\n // Autoscroll when new messages come in while scrolled to bottom\n useEffect(() => {\n const container = scrollContainerRef.current;\n if (!container) return;\n\n const handleScroll = () => {\n // Track if user is near bottom\n const isNearBottom =\n container.scrollHeight -\n container.scrollTop -\n container.clientHeight <\n 50;\n shouldAutoScrollRef.current = isNearBottom;\n };\n\n const observer = new MutationObserver(() => {\n if (shouldAutoScrollRef.current) {\n container.scrollTop = container.scrollHeight;\n }\n });\n\n container.addEventListener('scroll', handleScroll);\n observer.observe(container, {\n childList: true,\n subtree: true,\n characterData: true\n });\n\n return () => {\n container.removeEventListener('scroll', handleScroll);\n observer.disconnect();\n };\n }, []);\n\n return (\n <div className={`bg-white flex flex-col h-full min-h-0 ${className}`}>\n {/* Messages */}\n <div\n ref={scrollContainerRef}\n className=\"flex-1 min-h-0 overflow-y-auto py-3 flex flex-col\"\n >\n {messages.length === 0 && !isLoading && (\n <ChatPanelEmptyState onFileUpload={onFileUpload} />\n )}\n {messages.map((message, messageIndex) => {\n const isFirstUserMessage =\n hasProcessedDocument &&\n message.role !== 'assistant' &&\n messageIndex === 0;\n\n const isLatestAssistantMessage =\n message.role === 'assistant' &&\n message.id === latestAssistantMessageId;\n\n return (\n <ChatMessage\n key={message.id}\n message={message}\n isFirstUserMessage={isFirstUserMessage}\n isLatestAssistantMessage={isLatestAssistantMessage}\n isDocumentExpanded={isDocumentExpanded}\n onToggleDocument={() =>\n setIsDocumentExpanded(!isDocumentExpanded)\n }\n uploadedFileName={uploadedFileName}\n cart={cart}\n onAddToCart={onAddToCart}\n onViewProduct={onViewProduct}\n />\n );\n })}\n\n {isLoading && <TypingIndicator />}\n <ChatError error={error} onRetry={onRetry} />\n </div>\n\n <ChatInput\n input={input}\n onInputChange={onInputChange}\n onSubmit={onSubmit}\n isLoading={isLoading}\n />\n </div>\n );\n }\n);\n","import { useCallback, useEffect, useRef, useState } from 'react';\nimport { usePurchaseOrderStore } from '../../../stores/purchase-order-store.js';\n\nexport function useResizablePanel() {\n // Read panel width from store (persisted across reloads)\n const leftPanelWidth = usePurchaseOrderStore(\n (state) => state.userSettings.panelWidth\n );\n const setPanelWidth = usePurchaseOrderStore((state) => state.setPanelWidth);\n\n const [isDesktop, setIsDesktop] = useState<boolean>(\n typeof window !== 'undefined' && window.innerWidth >= 1024\n );\n const containerRef = useRef<HTMLDivElement>(null);\n const isDragging = useRef(false);\n const leftPanelWidthRef = useRef<number>(leftPanelWidth);\n\n // Sync ref when store value changes\n useEffect(() => {\n leftPanelWidthRef.current = leftPanelWidth;\n }, [leftPanelWidth]);\n\n // Setup desktop detection\n useEffect(() => {\n const updateLayout = () => {\n setIsDesktop(window.innerWidth >= 1024);\n };\n\n updateLayout();\n window.addEventListener('resize', updateLayout);\n return () => {\n window.removeEventListener('resize', updateLayout);\n };\n }, []);\n\n const handleMouseMove = useCallback(\n (e: MouseEvent) => {\n if (!isDragging.current || !containerRef.current) return;\n\n const containerRect = containerRef.current.getBoundingClientRect();\n const newWidth =\n ((e.clientX - containerRect.left) / containerRect.width) * 100;\n const clampedWidth = Math.min(80, Math.max(20, newWidth));\n\n leftPanelWidthRef.current = clampedWidth;\n setPanelWidth(clampedWidth);\n },\n [setPanelWidth]\n );\n\n const handleMouseUp = useCallback(() => {\n isDragging.current = false;\n // Panel width is automatically persisted by Zustand store\n document.body.style.cursor = '';\n document.body.style.userSelect = '';\n document.removeEventListener('mousemove', handleMouseMove);\n document.removeEventListener('mouseup', handleMouseUp);\n }, [handleMouseMove]);\n\n const handleMouseDown = useCallback(\n (e: React.MouseEvent) => {\n e.preventDefault();\n isDragging.current = true;\n document.body.style.cursor = 'col-resize';\n document.body.style.userSelect = 'none';\n document.addEventListener('mousemove', handleMouseMove);\n document.addEventListener('mouseup', handleMouseUp);\n },\n [handleMouseMove, handleMouseUp]\n );\n\n const handleKeyDown = useCallback(\n (e: React.KeyboardEvent) => {\n const increment = 2; // 2% change per key press\n\n if (e.key === 'ArrowLeft') {\n e.preventDefault();\n const newWidth = Math.max(20, leftPanelWidthRef.current - increment);\n leftPanelWidthRef.current = newWidth;\n setPanelWidth(newWidth);\n } else if (e.key === 'ArrowRight') {\n e.preventDefault();\n const newWidth = Math.min(80, leftPanelWidthRef.current + increment);\n leftPanelWidthRef.current = newWidth;\n setPanelWidth(newWidth);\n }\n },\n [setPanelWidth]\n );\n\n const handleBlur = useCallback(() => {\n // Panel width is automatically persisted by Zustand store, no need to save manually\n }, []);\n\n // Cleanup on unmount\n useEffect(() => {\n return () => {\n handleMouseUp();\n };\n }, [handleMouseUp]);\n\n return {\n leftPanelWidth,\n isDesktop,\n containerRef,\n handleMouseDown,\n handleKeyDown,\n handleBlur\n };\n}\n","export type ActiveTab = 'cart' | 'chat';\n\nexport interface TabBarProps {\n activeTab: ActiveTab;\n onTabChange: (tab: ActiveTab) => void;\n hasUnread: boolean;\n}\n\nexport function TabBar({ activeTab, onTabChange, hasUnread }: TabBarProps) {\n const chatHasUnread = hasUnread && activeTab !== 'chat';\n\n return (\n <div className=\"flex border-b border-border-strong shrink-0\" role=\"tablist\">\n <button\n type=\"button\"\n role=\"tab\"\n id=\"tab-cart\"\n aria-selected={activeTab === 'cart'}\n aria-controls=\"tabpanel-cart\"\n className={`flex-1 min-h-11 py-2.5 px-4 text-sm font-medium border-b-2 transition-colors cursor-pointer bg-transparent ${activeTab === 'cart' ? 'border-border-focus text-text' : 'border-transparent text-text-tertiary hover:text-text-secondary hover:border-border'}`}\n onClick={() => onTabChange('cart')}\n >\n Cart\n </button>\n <button\n type=\"button\"\n role=\"tab\"\n id=\"tab-chat\"\n aria-selected={activeTab === 'chat'}\n aria-controls=\"tabpanel-chat\"\n aria-label={chatHasUnread ? 'Chat (new messages)' : 'Chat'}\n className={`relative flex-1 min-h-11 py-2.5 px-4 text-sm font-medium border-b-2 transition-colors cursor-pointer bg-transparent ${activeTab === 'chat' ? 'border-border-focus text-text' : 'border-transparent text-text-tertiary hover:text-text-secondary hover:border-border'}`}\n onClick={() => onTabChange('chat')}\n >\n Chat\n {chatHasUnread && (\n <span\n className=\"absolute top-2 right-[calc(50%-24px)] w-2 h-2 rounded-full bg-error\"\n aria-hidden=\"true\"\n />\n )}\n </button>\n </div>\n );\n}\n","import type { UIMessage } from 'ai';\nimport {\n type ChangeEvent,\n type FormEvent,\n type RefObject,\n useCallback,\n useEffect,\n useRef,\n useState\n} from 'react';\nimport type { CustomerAddress } from '../../lib/bigcommerce/index.js';\nimport type {\n AddressUpdateStatus,\n BuyerInfo,\n CartItem,\n CheckoutTotals,\n CustomerInfo,\n ItemWarning,\n Product\n} from '../../types.js';\nimport { CartPanel } from './cartifact/cartifact.js';\nimport { ChatPanel, type ChatPanelRef } from './chat-panel/chat-panel.js';\nimport { useResizablePanel } from './hooks/use-resizable-panel.js';\nimport { type ActiveTab, TabBar } from './tab-bar.js';\n\nexport interface ChatViewProps {\n // Chat panel props\n messages: UIMessage[];\n input: string;\n onInputChange: (e: ChangeEvent<HTMLTextAreaElement>) => void;\n onSubmit: (e: FormEvent<HTMLFormElement>) => void;\n isLoading: boolean;\n error?: Error | null;\n onRetry?: () => void;\n hasProcessedDocument?: boolean;\n uploadedFileName?: string | null;\n chatPanelRef?: RefObject<ChatPanelRef | null>;\n onFileUpload?: (file: File) => void;\n\n // Cart panel props\n cartItems: CartItem[];\n itemWarnings?: ItemWarning[];\n onUpdateQuantity: (id: string, quantity: number) => void | Promise<void>;\n onRemove: (id: string) => void;\n onCheckout: () => void;\n onSuggestAlternatives: (itemName: string, sku?: string) => void;\n onShowMoreLikeThis: (itemName: string, sku?: string) => void;\n onViewProduct?: (item: {\n productEntityId?: number;\n sku: string;\n name: string;\n path?: string;\n }) => void;\n onAddToCart?: (\n product: Product,\n quantity: number\n ) => Promise<boolean> | boolean | undefined;\n orderId?: string | null;\n buyerInfo?: BuyerInfo | null;\n customerInfo?: CustomerInfo;\n addresses?: CustomerAddress[];\n selectedAddressId?: string;\n addressUpdateStatus?: AddressUpdateStatus;\n onAddressChange?: (addressId: string) => void;\n selectedBillingAddressId?: string;\n billingAddressUpdateStatus?: AddressUpdateStatus;\n onBillingAddressChange?: (addressId: string) => void;\n shipToAddress?: CustomerAddress | null;\n billingAddress?: CustomerAddress | null;\n checkoutTotals?: CheckoutTotals | null;\n isCartLoading?: boolean;\n poMetadataSet?: boolean;\n onNewOrder?: () => void;\n onExpand?: () => void;\n onMinimize?: () => void;\n\n className?: string;\n}\n\nexport function ChatView({\n // Chat panel props\n messages,\n input,\n onInputChange,\n onSubmit,\n isLoading,\n error,\n onRetry,\n hasProcessedDocument,\n uploadedFileName,\n chatPanelRef,\n onFileUpload,\n\n // Cart panel props\n cartItems,\n itemWarnings,\n onUpdateQuantity,\n onRemove,\n onCheckout,\n onSuggestAlternatives,\n onShowMoreLikeThis,\n onViewProduct,\n onAddToCart,\n orderId,\n buyerInfo,\n customerInfo,\n addresses,\n selectedAddressId,\n addressUpdateStatus,\n onAddressChange,\n selectedBillingAddressId,\n billingAddressUpdateStatus,\n onBillingAddressChange,\n shipToAddress,\n billingAddress,\n checkoutTotals,\n isCartLoading,\n poMetadataSet,\n onNewOrder,\n onExpand,\n onMinimize,\n\n className = ''\n}: ChatViewProps) {\n const panel = useResizablePanel();\n const [activeTab, setActiveTab] = useState<ActiveTab>('cart');\n const [hasUnread, setHasUnread] = useState(false);\n const prevMessageCount = useRef(messages.length);\n const activeTabRef = useRef(activeTab);\n activeTabRef.current = activeTab;\n\n // Track new messages arriving while the chat tab is not active\n useEffect(() => {\n if (\n messages.length > prevMessageCount.current &&\n activeTabRef.current !== 'chat'\n ) {\n setHasUnread(true);\n }\n prevMessageCount.current = messages.length;\n }, [messages.length]);\n\n // Clear unread when switching to desktop (both panels are visible)\n useEffect(() => {\n if (panel.isDesktop) {\n setHasUnread(false);\n }\n }, [panel.isDesktop]);\n\n const handleTabChange = useCallback((tab: ActiveTab) => {\n setActiveTab(tab);\n if (tab === 'chat') {\n setHasUnread(false);\n }\n }, []);\n\n const chatPanel = (\n <ChatPanel\n ref={chatPanelRef}\n messages={messages}\n input={input}\n onInputChange={onInputChange}\n onSubmit={onSubmit}\n isLoading={isLoading}\n cart={cartItems}\n onAddToCart={onAddToCart}\n onViewProduct={onViewProduct}\n error={error}\n onRetry={onRetry}\n hasProcessedDocument={hasProcessedDocument}\n uploadedFileName={uploadedFileName}\n onFileUpload={onFileUpload}\n />\n );\n\n const cartPanel = (\n <CartPanel\n items={cartItems}\n itemWarnings={itemWarnings}\n onUpdateQuantity={onUpdateQuantity}\n onRemove={onRemove}\n onCheckout={onCheckout}\n onSuggestAlternatives={onSuggestAlternatives}\n onShowMoreLikeThis={onShowMoreLikeThis}\n onViewProduct={onViewProduct}\n orderId={orderId ?? undefined}\n buyerInfo={buyerInfo ?? undefined}\n customerInfo={customerInfo}\n addresses={addresses}\n selectedAddressId={selectedAddressId}\n addressUpdateStatus={addressUpdateStatus}\n onAddressChange={onAddressChange}\n selectedBillingAddressId={selectedBillingAddressId}\n billingAddressUpdateStatus={billingAddressUpdateStatus}\n onBillingAddressChange={onBillingAddressChange}\n shipToAddress={shipToAddress ?? undefined}\n billingAddress={billingAddress ?? undefined}\n checkoutTotals={checkoutTotals ?? undefined}\n isLoading={isCartLoading}\n poMetadataSet={poMetadataSet}\n onNewOrder={onNewOrder}\n onExpand={onExpand}\n onMinimize={onMinimize}\n className={panel.isDesktop ? 'rounded-l-none border-0' : ''}\n />\n );\n\n if (!panel.isDesktop) {\n return (\n <div\n ref={panel.containerRef}\n className={`flex flex-col h-full min-h-0 border border-solid border-border-strong rounded-md overflow-hidden ${className}`}\n >\n <TabBar\n activeTab={activeTab}\n onTabChange={handleTabChange}\n hasUnread={hasUnread}\n />\n <div\n className=\"flex-1 min-h-0 overflow-hidden\"\n role=\"tabpanel\"\n id={`tabpanel-${activeTab}`}\n aria-labelledby={`tab-${activeTab}`}\n >\n {activeTab === 'cart' ? cartPanel : chatPanel}\n </div>\n </div>\n );\n }\n\n return (\n <div\n ref={panel.containerRef}\n className={`flex flex-row h-full ${className}`}\n >\n <div\n className=\"h-full border border-r-0 border-solid border-border-strong rounded-md rounded-r-none overflow-hidden\"\n style={{ width: `${panel.leftPanelWidth}%`, minWidth: 0 }}\n >\n {chatPanel}\n </div>\n {/* biome-ignore lint/a11y/useSemanticElements: hr cannot have children */}\n <div\n className=\"w-px cursor-col-resize bg-border shrink-0 z-10 relative transition-colors hover:bg-text-quaternary before:content-[''] before:absolute before:inset-y-0 before:-left-1.5 before:-right-1.5\"\n onMouseDown={panel.handleMouseDown}\n onKeyDown={panel.handleKeyDown}\n onBlur={panel.handleBlur}\n role=\"separator\"\n tabIndex={0}\n aria-orientation=\"vertical\"\n aria-label=\"Resize panels\"\n aria-valuenow={panel.leftPanelWidth}\n aria-valuemin={20}\n aria-valuemax={80}\n aria-valuetext={`Chat panel width: ${Math.round(panel.leftPanelWidth)}%`}\n />\n <div\n className=\"h-full border border-l-0 border-border-strong border-solid rounded-md rounded-l-none overflow-hidden\"\n style={{ width: `${100 - panel.leftPanelWidth}%`, minWidth: 0 }}\n >\n {cartPanel}\n </div>\n </div>\n );\n}\n","import { useCallback, useMemo, useState } from 'react';\nimport { useBigCommerceClient } from '../contexts/bigcommerce-client-context.js';\nimport { usePurchaseOrderStore } from '../stores/purchase-order-store.js';\nimport { SpinnerIcon } from './icons/spinner-icon.js';\n\nexport function ExistingCartPrompt() {\n const client = useBigCommerceClient();\n const existingCart = usePurchaseOrderStore((state) => state.ui.existingCart);\n const confirmClearExistingCart = usePurchaseOrderStore(\n (state) => state.confirmClearExistingCart\n );\n const [isClearing, setIsClearing] = useState(false);\n\n const itemCount = useMemo(\n () =>\n existingCart?.lineItems.physicalItems.reduce(\n (sum, item) => sum + item.quantity,\n 0\n ) ?? 0,\n [existingCart]\n );\n\n const handleClearCart = useCallback(async () => {\n if (!client || isClearing) return;\n setIsClearing(true);\n await confirmClearExistingCart(client);\n }, [confirmClearExistingCart, client, isClearing]);\n\n return (\n <div className=\"flex h-full items-center justify-center\">\n <div className=\"text-center max-w-md px-4\">\n <p className=\"text-lg text-text-secondary mb-2\">Existing cart found</p>\n <p className=\"text-sm text-text-tertiary mb-6\">\n You have {itemCount} {itemCount === 1 ? 'item' : 'items'} in an\n existing cart. This cart will be cleared to start a new purchase\n order.\n </p>\n <button\n type=\"button\"\n onClick={handleClearCart}\n disabled={isClearing}\n className=\"bg-surface-invert shadow-button transition-all duration-200 ease-in-out hover:bg-surface-invert-hover hover:shadow-button-hover hover:-translate-y-px px-4 py-2 text-text-invert rounded-full font-medium cursor-pointer disabled:opacity-50 disabled:pointer-events-none\"\n >\n {isClearing ? (\n <span className=\"flex items-center gap-2\">\n <SpinnerIcon size={14} />\n Clearing cart…\n </span>\n ) : (\n 'Clear Cart & Continue'\n )}\n </button>\n </div>\n </div>\n );\n}\n","export interface FatalErrorProps {\n message?: string;\n}\n\nexport function FatalError({ message }: FatalErrorProps) {\n const handleRefresh = () => {\n window.location.reload();\n };\n\n return (\n <div className=\"flex items-center justify-center h-full w-full bg-surface-secondary\">\n <div className=\"text-center max-w-md px-4\">\n <p className=\"text-lg text-text-secondary mb-2\">Something went wrong</p>\n <p className=\"text-sm text-text-tertiary mb-6\">\n {message ||\n 'An unexpected error occurred. Please refresh the page to try again.'}\n </p>\n <button\n type=\"button\"\n onClick={handleRefresh}\n className=\"bg-surface-invert shadow-button transition-all duration-200 ease-in-out hover:bg-surface-invert-hover hover:shadow-button-hover hover:-translate-y-px px-4 py-2 text-text-invert rounded-full font-medium cursor-pointer\"\n >\n Refresh page\n </button>\n </div>\n </div>\n );\n}\n","const steps = [\n { label: 'Upload', number: 1 },\n { label: 'Analyze', number: 2 },\n { label: 'Checkout', number: 3 }\n];\n\n// biome-ignore lint/suspicious/noEmptyInterface: needed for storybook type inference\nexport interface ProcessingStepsProps {}\n\nexport function ProcessingSteps(_props: ProcessingStepsProps = {}) {\n return (\n <div className=\"flex items-center justify-center gap-0 p-4 md:py-1 md:px-0\">\n {steps.map((step, index) => (\n <div key={step.label} className=\"flex items-center gap-2\">\n {index > 0 && (\n <div className=\"w-6 md:w-10 h-px mx-2 md:mx-3 rounded-[1px] bg-border\" />\n )}\n <div className=\"flex items-center justify-center w-5 h-5 rounded-full shrink-0 bg-transparent border-[1.5px] border-border-strong text-text-quaternary\">\n <span className=\"text-[0.6875rem] font-medium\">{step.number}</span>\n </div>\n <span className=\"text-s font-normal whitespace-nowrap text-text-quaternary\">\n {step.label}\n </span>\n </div>\n ))}\n </div>\n );\n}\n","import type { ChangeEvent, RefObject } from 'react';\nimport { cn } from '../../lib/utils.js';\nimport { UploadDocumentIcon } from '../icons/upload-document-icon.js';\n\nexport interface UploadDropZoneProps {\n isDragging: boolean;\n fileInputRef: RefObject<HTMLInputElement | null>;\n cameraInputRef: RefObject<HTMLInputElement | null>;\n acceptedExtensions: string;\n onDropZoneClick: () => void;\n onFileChange: (e: ChangeEvent<HTMLInputElement>) => void;\n}\n\nexport function UploadDropZone({\n isDragging,\n fileInputRef,\n cameraInputRef,\n acceptedExtensions,\n onDropZoneClick,\n onFileChange\n}: UploadDropZoneProps) {\n return (\n <button\n type=\"button\"\n className=\"shadow-upload transition-all duration-[250ms] ease-[cubic-bezier(0.34,1.56,0.64,1)] flex flex-col items-center gap-4 pb-6 max-md:min-w-0 min-w-lg max-md:p-8 max-md:w-full max-md:max-w-[400px] cursor-pointer hover:-translate-y-[3px] hover:border-surface-invert-hover focus-visible:outline focus-visible:outline-border-focus focus-visible:outline-offset\"\n onClick={onDropZoneClick}\n >\n <input\n ref={fileInputRef}\n type=\"file\"\n className=\"hidden\"\n onChange={onFileChange}\n accept={acceptedExtensions}\n />\n <input\n ref={cameraInputRef}\n type=\"file\"\n className=\"hidden\"\n onChange={onFileChange}\n accept=\"image/*\"\n capture=\"environment\"\n />\n <div\n className={cn(\n 'flex items-center justify-center w-16 h-16 rounded-[14px] p-1 border-2 border-dashed border-border-focus text-text transition-transform duration-200',\n isDragging && 'animate-icon-bounce'\n )}\n >\n <UploadDocumentIcon />\n </div>\n <h2 className=\"m-0 text-2xl max-md:text-xl font-semibold text-text text-center\">\n Upload your Purchase Order\n </h2>\n <p className=\"m-0 text-[15px] text-text-tertiary text-center\">\n Get automagical product matching and stock availability\n </p>\n <div className=\"flex flex-wrap justify-center gap-2 mt-2\">\n {['PDF', 'Excel', 'CSV', 'Images'].map((label) => (\n <span\n key={label}\n className=\"py-1 px-3 bg-surface-invert/5 border border-border-strong rounded-full text-xs font-medium text-text backdrop-blur\"\n >\n {label}\n </span>\n ))}\n </div>\n </button>\n );\n}","import type { ChangeEvent, RefObject } from 'react';\nimport { useCallback, useRef } from 'react';\nimport { cn } from '../../lib/utils.js';\nimport { useTouchDevice } from '../../hooks/use-touch-device.js';\nimport { CameraButton } from './camera-button.js';\nimport { ProcessingSteps } from './processing-steps.js';\nimport { UploadDropZone } from './upload-drop-zone.js';\n\nexport interface InitialStateProps {\n isDragging: boolean;\n fileInputRef: RefObject<HTMLInputElement | null>;\n acceptedExtensions: string;\n displayError: string | null;\n onDropZoneClick: () => void;\n onFileChange: (e: ChangeEvent<HTMLInputElement>) => void;\n onSkip: () => void;\n}\n\nexport function InitialState({\n isDragging,\n fileInputRef,\n acceptedExtensions,\n displayError,\n onDropZoneClick,\n onFileChange,\n onSkip\n}: InitialStateProps) {\n const isTouchDevice = useTouchDevice();\n const cameraInputRef = useRef<HTMLInputElement>(null);\n\n const handleCameraClick = useCallback(() => {\n cameraInputRef.current?.click();\n }, []);\n\n return (\n <div\n className={cn(\n 'flex flex-col items-center gap-6 border-border border-solid bg-surface border rounded-2xl transition-all duration-[250ms] ease-[cubic-bezier(0.34,1.56,0.64,1)] hover:border-border-strong',\n isDragging &&\n 'ring-2 ring-border-focus border-border-focus bg-surface-tertiary shadow-upload-active'\n )}\n >\n <div className=\"upload-zone-steps mb-3 py-4 px-8 border-b border-solid border-border-strong\">\n <ProcessingSteps />\n </div>\n\n <UploadDropZone\n isDragging={isDragging}\n fileInputRef={fileInputRef}\n cameraInputRef={cameraInputRef}\n acceptedExtensions={acceptedExtensions}\n onDropZoneClick={onDropZoneClick}\n onFileChange={onFileChange}\n />\n\n {isTouchDevice && <CameraButton onClick={handleCameraClick} />}\n\n {displayError && (\n <div className=\"flex items-center gap-2 py-3 px-4 bg-error-bg border border-error/30 rounded-lg text-error-text text-sm max-w-[400px] text-center\">\n {displayError}\n </div>\n )}\n\n <div className=\"upload-zone-steps px-8 border-b border-solid border-border-strong\" />\n\n <button\n type=\"button\"\n className=\"border-none pt-4 pb-8 px-4 text-[15px] text-text-tertiary cursor-pointer transition-colors duration-150 hover:text-text hover:underline focus-visible:outline-2 focus-visible:outline-border-focus focus-visible:outline-offset-2 rounded\"\n onClick={onSkip}\n >\n Or start by describing what you need\n </button>\n </div>\n );\n}\n","import type { CartItem, ProcessingStep } from '../../types.js';\n\nexport interface CartPreviewProps {\n items: CartItem[];\n orderId?: string | null;\n parsedContent?: string | null;\n isUploading?: boolean;\n currentStep?: ProcessingStep | null;\n}\n\nexport function CartPreview({\n items,\n orderId,\n parsedContent,\n isUploading = false,\n currentStep = null\n}: CartPreviewProps) {\n const hasProducts = items.length > 0;\n const isReadingOrMatching =\n currentStep === 'reading' || currentStep === 'matching';\n const isBuildingCart = currentStep === 'building';\n\n return (\n <div className=\"w-full max-w-xs overflow-hidden rounded-xl bg-surface-secondary shadow-preview\">\n <div className=\"flex items-center justify-between px-6 py-4 text-text-invert bg-surface-invert\">\n <h3 className=\"m-0 text-base font-semibold\">Cart</h3>\n {orderId && <span className=\"text-xs opacity-80\">{orderId}</span>}\n </div>\n {parsedContent && !hasProducts && isReadingOrMatching && (\n <div className=\"flex h-40 flex-col items-center justify-center gap-4 px-4\">\n <svg\n className=\"text-text animate-icon-scan\"\n width=\"48\"\n height=\"48\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.5\"\n >\n <title>Matching icon</title>\n <circle cx=\"11\" cy=\"11\" r=\"8\" />\n <path d=\"m21 21-4.35-4.35\" />\n </svg>\n </div>\n )}\n <div className=\"max-h-72 overflow-y-auto p-3\">\n {items.map((item) => (\n <div\n key={item.id}\n className=\"flex items-center gap-3 rounded-md p-2 cart-preview-item-real animate-item-slide-in\"\n >\n {item.imageUrl ? (\n <img\n src={item.imageUrl}\n alt={item.name}\n className=\"size-10 shrink-0 rounded-md bg-surface-secondary object-cover\"\n />\n ) : (\n <div className=\"size-10 shrink-0 rounded-md bg-surface-secondary\" />\n )}\n <div className=\"flex min-w-0 flex-1 flex-col gap-0.5\">\n <p className=\"m-0 truncate text-sm font-medium text-text\">\n {item.name}\n </p>\n <p className=\"m-0 text-xs text-text-tertiary\">{item.sku}</p>\n <p className=\"m-0 text-xs text-text-tertiary\">\n Quantity: {item.quantity}\n </p>\n </div>\n </div>\n ))}\n\n {isUploading && !parsedContent && items.length === 0 && (\n <div className=\"flex h-40 flex-col items-center justify-center gap-4 px-4\">\n <svg\n className=\"text-text animate-icon-bounce\"\n width=\"48\"\n height=\"48\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.5\"\n >\n <title>Upload icon</title>\n <path d=\"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z\" />\n <polyline points=\"14 2 14 8 20 8\" />\n <line x1=\"12\" y1=\"18\" x2=\"12\" y2=\"12\" />\n <polyline points=\"9 15 12 12 15 15\" />\n </svg>\n </div>\n )}\n\n {items.length < 4 &&\n isBuildingCart &&\n Array.from({ length: 4 - items.length }).map((_, index) => (\n <div\n key={`skeleton-${items.length}-${index}`}\n className=\"flex items-center gap-3 rounded-md p-2 opacity-50\"\n >\n <div className=\"size-10 shrink-0 rounded-md animate-shimmer\" />\n <div className=\"flex min-w-0 flex-1 flex-col gap-1.5\">\n <div className=\"h-2.5 w-4/5 rounded animate-shimmer\" />\n <div className=\"h-2.5 w-2/5 rounded animate-shimmer\" />\n </div>\n </div>\n ))}\n </div>\n </div>\n );\n}\n","import type { UIMessage } from 'ai';\nimport { create } from 'zustand';\n\nexport interface ToolCall {\n name: string;\n args: Record<string, unknown>;\n resultCount: number | null;\n}\n\ninterface ToolCallState {\n toolCalls: ToolCall[];\n revealedCount: number;\n setToolCalls: (messages: UIMessage[]) => void;\n incrementRevealed: () => void;\n reset: () => void;\n}\n\n// Extract relevant tool call info from messages\nfunction extractToolCalls(messages: UIMessage[]): ToolCall[] {\n const toolCalls: ToolCall[] = [];\n\n for (const message of messages) {\n if (message.role !== 'assistant' || !message.parts) continue;\n\n for (const part of message.parts) {\n if (\n typeof part === 'object' &&\n part !== null &&\n 'type' in part &&\n typeof part.type === 'string' &&\n part.type.startsWith('tool-')\n ) {\n const name = part.type.slice(5);\n const args =\n 'input' in part &&\n typeof part.input === 'object' &&\n part.input !== null\n ? (part.input as Record<string, unknown>)\n : {};\n\n let resultCount: number | null = null;\n if (name === 'searchProducts' || name === 'searchProductsBySku') {\n const output = 'output' in part ? part.output : null;\n if (output != null) {\n try {\n const parsed =\n typeof output === 'string' ? JSON.parse(output) : output;\n resultCount = parsed?.data?.[name]?.total ?? null;\n } catch {\n // Invalid JSON, skip this tool call\n continue;\n }\n }\n }\n\n toolCalls.push({ name, args, resultCount });\n }\n }\n }\n\n return toolCalls;\n}\n\nexport const useToolCallStore = create<ToolCallState>((set) => ({\n toolCalls: [],\n revealedCount: 0,\n setToolCalls: (messages) => set({ toolCalls: extractToolCalls(messages) }),\n incrementRevealed: () =>\n set((state) => ({ revealedCount: state.revealedCount + 1 })),\n reset: () => set({ toolCalls: [], revealedCount: 0 })\n}));\n","import { useEffect, useState } from 'react';\nimport { useToolCallStore } from '../stores/tool-call-store.js';\n\nconst TARGET_TOTAL_MS = 3000;\nconst MIN_INTERVAL_MS = 200;\n\nfunction computeInterval(totalItems: number): number {\n if (totalItems <= 0) return MIN_INTERVAL_MS;\n return Math.max(MIN_INTERVAL_MS, Math.round(TARGET_TOTAL_MS / totalItems));\n}\n\ninterface UseProgressiveCartItemsResult {\n revealedCount: number;\n totalItems: number;\n isRevealing: boolean;\n}\n\nexport function useProgressiveCartItems(): UseProgressiveCartItemsResult {\n const toolCalls = useToolCallStore((state) => state.toolCalls);\n\n const addToCartCall = toolCalls.find((tc) => tc.name === 'addToCart');\n const totalItems =\n addToCartCall &&\n 'value' in addToCartCall.args &&\n Array.isArray(addToCartCall.args.value)\n ? addToCartCall.args.value.length\n : 0;\n\n const [revealedCount, setRevealedCount] = useState(0);\n\n useEffect(() => {\n if (totalItems === 0 || revealedCount >= totalItems) return;\n\n const interval = computeInterval(totalItems);\n const timer = setTimeout(() => {\n setRevealedCount((prev) => Math.min(prev + 1, totalItems));\n }, interval);\n\n return () => clearTimeout(timer);\n }, [totalItems, revealedCount]);\n\n return {\n revealedCount,\n totalItems,\n isRevealing: totalItems > 0 && revealedCount < totalItems\n };\n}\n","import { useEffect } from 'react';\n\nimport { type ToolCall, useToolCallStore } from '../stores/tool-call-store.js';\n\n/** Interval in ms between revealing each tool call */\nconst REVEAL_INTERVAL_MS = 1000;\n\ninterface UseProgressiveToolCallsResult {\n /** The currently visible tool call (most recently revealed) */\n currentToolCall: ToolCall | null;\n /** All tool calls revealed so far */\n visibleToolCalls: ToolCall[];\n /** Whether we're still revealing tool calls */\n isRevealing: boolean;\n}\n\n/**\n * Reveals tool calls one at a time.\n * When multiple tool calls come in at once, this ensures each one is displayed\n * sequentially rather than only showing the latest, giving a better sense of\n * progress by not skipping intermediate steps.\n */\nexport function useProgressiveToolCalls(): UseProgressiveToolCallsResult {\n const toolCalls = useToolCallStore((state) => state.toolCalls);\n const revealedCount = useToolCallStore((state) => state.revealedCount);\n const incrementRevealed = useToolCallStore(\n (state) => state.incrementRevealed\n );\n\n useEffect(() => {\n if (revealedCount >= toolCalls.length) {\n return;\n }\n\n const timer = setTimeout(incrementRevealed, REVEAL_INTERVAL_MS);\n return () => clearTimeout(timer);\n }, [toolCalls.length, revealedCount, incrementRevealed]);\n\n const visibleToolCalls = toolCalls.slice(0, revealedCount);\n const currentToolCall = visibleToolCalls[visibleToolCalls.length - 1] ?? null;\n\n return {\n currentToolCall,\n visibleToolCalls,\n isRevealing: revealedCount < toolCalls.length\n };\n}\n","import type { UIMessage } from 'ai';\nimport type { ProcessingStep } from '../types.js';\n\n// Define step order for comparison (only the 3 UI steps)\nconst STEP_ORDER: ProcessingStep[] = ['reading', 'matching', 'building'];\n\nexport type StepStatus = 'pending' | 'active' | 'complete';\n\n// Get status for a processing step (used by both components)\nexport function getProcessingStepStatus(\n stepId: ProcessingStep,\n currentStep: ProcessingStep | null\n): StepStatus {\n if (!currentStep) return 'pending';\n\n const currentIndex = STEP_ORDER.indexOf(currentStep);\n const stepIndex = STEP_ORDER.indexOf(stepId);\n\n if (stepIndex < currentIndex) return 'complete';\n if (stepIndex === currentIndex) return 'active';\n return 'pending';\n}\n\n// Derive current step based on tool calls from the PO agent\n// Returns 'building' once addToCart has been called (actually building the cart)\n// The hook will default to 'reading' and upgrade to 'matching' based on parsedContent\nexport function deriveCurrentStep(\n messages: UIMessage[]\n): ProcessingStep | null {\n if (messages.length === 0) return null;\n\n // Check if addToCart has been called (cart is being built)\n for (const message of messages) {\n if (message.role !== 'assistant' || !message.parts) continue;\n\n for (const part of message.parts) {\n if (\n typeof part === 'object' &&\n part !== null &&\n 'type' in part &&\n typeof part.type === 'string'\n ) {\n const toolName = part.type.startsWith('tool-')\n ? part.type.slice(5)\n : null;\n\n if (toolName === 'addToCart') {\n return 'building';\n }\n }\n }\n }\n\n // Otherwise, let the hook determine the step based on parsedContent\n return null;\n}\n\n// Detect when first assistant response is complete\nexport function isFirstResponseComplete(\n messages: UIMessage[],\n status: string\n): boolean {\n // Check if we have at least 2 messages (user + assistant)\n // AND status is not 'submitted' or 'streaming'\n // Same logic as chat loading indicator\n return (\n messages.length >= 2 && status !== 'submitted' && status !== 'streaming'\n );\n}\n","import type { ReactNode } from 'react';\nimport { useProgressiveCartItems } from '../../hooks/use-progressive-cart-items.js';\nimport { useProgressiveToolCalls } from '../../hooks/use-progressive-tool-calls.js';\nimport { usePurchaseOrderStore } from '../../stores/purchase-order-store.js';\nimport type { ToolCall } from '../../stores/tool-call-store.js';\nimport type { ProcessingStep } from '../../types.js';\nimport { getProcessingStepStatus } from '../../utils/processing-helpers.js';\nimport { CheckIcon } from '../icons/check-icon.js';\nimport { SpinnerIcon } from '../icons/spinner-icon.js';\n\ninterface ToolCallRendererContext {\n visibleToolCalls: ToolCall[];\n resultCount: number | null;\n}\n\n// Registry of custom tool call renderers\n// Tool calls without a renderer here will not be displayed\nconst TOOL_CALL_RENDERERS: Record<\n string,\n (args: Record<string, unknown>, context: ToolCallRendererContext) => ReactNode\n> = {\n searchProductsBySku: (args, { resultCount }) => {\n const sku = (args.sku as string) ?? '';\n if (resultCount === null) return `Looking up SKU ${sku}`;\n return (\n <>\n Looked up SKU {sku}\n <br />\n <span className=\"opacity-60 italic\">\n {resultCount} result{resultCount !== 1 ? 's' : ''}\n </span>\n </>\n );\n },\n searchProducts: (args, { resultCount }) => {\n const matchPhrase = (args.matchPhrase as string) ?? 'products';\n if (resultCount === null) return `Searching for \"${matchPhrase}\"`;\n return (\n <>\n Searched \"{matchPhrase}\"\n <br />\n <span className=\"opacity-60 italic\">\n {resultCount} result{resultCount !== 1 ? 's' : ''}\n </span>\n </>\n );\n },\n getProductVariants: (args, { visibleToolCalls }) => {\n const productId = args.productEntityId as string;\n // Count how many getProductVariants calls we've seen for this product\n const pageNumber = visibleToolCalls.filter(\n (tc) =>\n tc.name === 'getProductVariants' &&\n tc.args.productEntityId === productId\n ).length;\n return (\n <>\n Checking variants\n <br />\n <span className=\"opacity-60 italic\">Page {pageNumber}</span>\n </>\n );\n }\n};\n\nfunction renderToolCall(\n toolCall: ToolCall,\n visibleToolCalls: ToolCall[]\n): ReactNode | null {\n const renderer = TOOL_CALL_RENDERERS[toolCall.name];\n if (!renderer) return null;\n return renderer(toolCall.args, {\n visibleToolCalls,\n resultCount: toolCall.resultCount\n });\n}\n\ninterface ProcessingStepsVerticalProps {\n currentStep: ProcessingStep | null;\n}\n\ninterface StepConfig {\n id: ProcessingStep;\n label: string;\n}\n\nconst STEPS: StepConfig[] = [\n { id: 'reading', label: 'Reading document...' },\n { id: 'matching', label: 'Matching products...' },\n { id: 'building', label: 'Building cart...' }\n];\n\nconst statusStyles = {\n pending: {\n row: 'opacity-40',\n icon: 'bg-surface-secondary border-2 border-border-strong'\n },\n active: {\n row: 'opacity-100',\n icon: 'border-2 border-border-focus text-text-invert'\n },\n complete: {\n row: 'opacity-100',\n icon: 'bg-surface border-2 border-success text-success'\n }\n} as const;\n\nexport function ProcessingStepsVertical({\n currentStep\n}: ProcessingStepsVerticalProps) {\n const { currentToolCall, visibleToolCalls } = useProgressiveToolCalls();\n const { revealedCount, totalItems } = useProgressiveCartItems();\n const uploadedFileName = usePurchaseOrderStore(\n (state) => state.parser.uploadedFileName\n );\n\n return (\n <div className=\"flex flex-col gap-6 w-64\">\n <div className=\"flex flex-col gap-6\">\n {STEPS.map((step) => {\n const status = getProcessingStepStatus(step.id, currentStep);\n // Only show tool call if we're in matching step, it's active, and there's a custom renderer\n const fileNameContent =\n step.id === 'reading' &&\n (status === 'active' || status === 'complete') &&\n uploadedFileName\n ? uploadedFileName\n : null;\n const toolCallContent =\n step.id === 'matching' && status === 'active' && currentToolCall\n ? renderToolCall(currentToolCall, visibleToolCalls)\n : null;\n const cartProgressContent =\n step.id === 'building' && status === 'active' && totalItems > 0\n ? `Adding item ${revealedCount} of ${totalItems}...`\n : null;\n\n return (\n <div\n key={step.id}\n data-testid=\"processing-step-row\"\n data-status={status}\n className={`flex items-center gap-4 transition-opacity duration-300 ${statusStyles[status].row}`}\n >\n <div\n className={`flex items-center justify-center w-8 h-8 rounded-full shrink-0 transition-all duration-300 ${statusStyles[status].icon}${status === 'complete' ? ' animate-step-pulse' : ''}${status === 'active' ? ' bg-surface-invert shadow-step' : ''}`}\n >\n {status === 'complete' && (\n <CheckIcon size={16} title=\"Complete\" />\n )}\n {status === 'active' && <SpinnerIcon size={16} />}\n {status === 'pending' && (\n <div className=\"w-2 h-2 rounded-full bg-border-strong\" />\n )}\n </div>\n <div className=\"flex flex-col min-w-0\">\n <span className=\"text-base font-medium text-text\">\n {step.label}\n </span>\n {fileNameContent && (\n <span\n className={`text-xs truncate ${status === 'active' ? 'animate-text-shimmer' : 'text-text-tertiary animate-ticker-enter'}`}\n >\n {fileNameContent}\n </span>\n )}\n {toolCallContent && currentToolCall && (\n <span\n key={visibleToolCalls.length}\n className=\"text-xs text-text-tertiary animate-ticker-enter\"\n >\n {toolCallContent}\n </span>\n )}\n {cartProgressContent && (\n <span\n key={revealedCount}\n className=\"text-xs text-text-tertiary animate-ticker-enter\"\n >\n {cartProgressContent}\n </span>\n )}\n </div>\n </div>\n );\n })}\n </div>\n </div>\n );\n}\n","import type { CartItem, ProcessingStep } from '../../types.js';\nimport { CartPreview } from './cart-preview.js';\nimport { ProcessingStepsVertical } from './processing-steps-vertical.js';\n\nexport interface ProcessingProps {\n currentStep: ProcessingStep;\n cartItems: CartItem[];\n orderId?: string | null;\n parsedContent?: string | null;\n isUploading?: boolean;\n}\n\nexport function Processing({\n currentStep,\n cartItems,\n orderId = null,\n parsedContent = null,\n isUploading = false\n}: ProcessingProps) {\n return (\n <div className=\"animate-fade-in-scale flex flex-col w-full max-w-[900px] gap-10 bg-surface rounded-2xl p-10 max-md:p-6 border border-border-strong border-solid\">\n <div className=\"flex w-full justify-center gap-32 max-md:flex-col max-md:gap-8\">\n <div className=\"shrink-0 flex items-center justify-center\">\n <ProcessingStepsVertical currentStep={currentStep} />\n </div>\n <div className=\"shrink-0 flex items-center justify-center min-w-80\">\n <CartPreview\n items={cartItems}\n orderId={orderId}\n parsedContent={parsedContent}\n isUploading={isUploading}\n currentStep={currentStep}\n />\n </div>\n </div>\n </div>\n );\n}\n","import type { ChangeEvent, DragEvent } from 'react';\nimport { useCallback, useRef, useState } from 'react';\nimport {\n ACCEPTED_EXTENSIONS,\n validateFile\n} from '../../lib/file-validation.js';\nimport type { CartItem, ProcessingStep } from '../../types.js';\nimport { InitialState } from './initial-state.js';\nimport { Processing } from './processing.js';\n\nexport interface UploaderProps {\n onFileUpload: (file: File) => void;\n onSkip: () => void;\n onClearError: () => void;\n currentStep?: ProcessingStep | null;\n cartItems?: CartItem[];\n orderId?: string | null;\n parsedContent?: string | null;\n isUploading?: boolean;\n parserError?: string | null;\n}\n\nexport function Uploader({\n onFileUpload,\n onSkip,\n onClearError,\n currentStep = null,\n cartItems = [],\n orderId = null,\n parsedContent = null,\n isUploading = false,\n parserError = null\n}: UploaderProps) {\n const [isDragging, setIsDragging] = useState(false);\n const [fileError, setFileError] = useState<string | null>(null);\n const fileInputRef = useRef<HTMLInputElement>(null);\n const isProcessing = currentStep !== null;\n\n // Determine which error to display (file validation or parser error)\n const displayError = parserError || fileError;\n\n const validateAndUploadFile = useCallback(\n (file: File) => {\n setFileError(null);\n onClearError();\n\n const result = validateFile(file);\n if (!result.valid) {\n setFileError(result.error ?? null);\n return;\n }\n\n onFileUpload(file);\n },\n [onFileUpload, onClearError]\n );\n\n const handleDragOver = useCallback((e: DragEvent<HTMLDivElement>) => {\n e.preventDefault();\n e.stopPropagation();\n setIsDragging(true);\n }, []);\n\n const handleDragLeave = useCallback((e: DragEvent<HTMLDivElement>) => {\n e.preventDefault();\n e.stopPropagation();\n setIsDragging(false);\n }, []);\n\n const handleDrop = useCallback(\n (e: DragEvent<HTMLDivElement>) => {\n e.preventDefault();\n e.stopPropagation();\n setIsDragging(false);\n\n const files = e.dataTransfer.files;\n const file = files[0];\n if (file) {\n validateAndUploadFile(file);\n }\n },\n [validateAndUploadFile]\n );\n\n const handleFileChange = useCallback(\n (e: ChangeEvent<HTMLInputElement>) => {\n const files = e.target.files;\n const file = files?.[0];\n if (file) {\n validateAndUploadFile(file);\n }\n if (e.target) {\n e.target.value = '';\n }\n },\n [validateAndUploadFile]\n );\n\n const handleDropZoneClick = useCallback(() => {\n fileInputRef.current?.click();\n }, []);\n\n return (\n // biome-ignore lint/a11y/noStaticElementInteractions: dnd is optional\n <div\n className={`upload-step flex flex-col w-full flex-1 min-h-0 ${isDragging ? 'upload-step-dragging' : ''} ${isProcessing ? 'upload-step-processing' : ''}`}\n onDragOver={handleDragOver}\n onDragLeave={handleDragLeave}\n onDrop={handleDrop}\n >\n <div className=\"upload-step-content animate-fade-in-up flex-1 flex items-center justify-center min-h-0 relative\">\n {!isProcessing ? (\n <InitialState\n isDragging={isDragging}\n fileInputRef={fileInputRef}\n acceptedExtensions={ACCEPTED_EXTENSIONS}\n displayError={displayError}\n onDropZoneClick={handleDropZoneClick}\n onFileChange={handleFileChange}\n onSkip={onSkip}\n />\n ) : (\n <Processing\n currentStep={currentStep}\n cartItems={cartItems}\n orderId={orderId}\n parsedContent={parsedContent}\n isUploading={isUploading}\n />\n )}\n </div>\n </div>\n );\n}\n","'use client';\n\nimport { createContext, type ReactNode, useContext } from 'react';\n\nexport const DEFAULT_ORIGIN = 'https://api.takeshape.io';\n\nexport type TakeShapeConfig = {\n projectId: string;\n apiKey: string;\n origin: string;\n sseOrigin: string;\n};\n\nconst TakeShapeConfigContext = createContext<TakeShapeConfig | null>(null);\n\ntype TakeShapeConfigProviderProps = {\n projectId: string;\n apiKey: string;\n origin?: string;\n sseOrigin?: string;\n children: ReactNode;\n};\n\nexport function TakeShapeConfigProvider({\n projectId,\n apiKey,\n origin = DEFAULT_ORIGIN,\n sseOrigin = DEFAULT_ORIGIN,\n children\n}: TakeShapeConfigProviderProps) {\n return (\n <TakeShapeConfigContext.Provider\n value={{ projectId, apiKey, origin, sseOrigin }}\n >\n {children}\n </TakeShapeConfigContext.Provider>\n );\n}\n\nexport function useTakeShapeConfig(): TakeShapeConfig {\n const context = useContext(TakeShapeConfigContext);\n if (!context) {\n throw new Error(\n 'useTakeShapeConfig must be used within a TakeShapeConfigProvider'\n );\n }\n return context;\n}\n","import type {\n Cart,\n CheckoutAddress,\n CustomerAddress\n} from '../lib/bigcommerce/storefront/types.js';\nimport type { CartItem, ItemWarning, SetCartItem } from '../types.js';\n\nexport function toCheckoutAddress(addr: CustomerAddress): CheckoutAddress {\n return {\n firstName: addr.firstName,\n lastName: addr.lastName,\n address1: addr.address1,\n address2: addr.address2,\n city: addr.city,\n stateOrProvince: addr.stateOrProvince,\n countryCode: addr.countryCode,\n postalCode: addr.postalCode,\n shouldSaveAddress: false\n };\n}\n\nexport function findMatchingCustomerAddress(\n poAddress: CustomerAddress,\n customerAddresses: CustomerAddress[]\n): CustomerAddress | undefined {\n if (!poAddress.address1 || !poAddress.postalCode) return undefined;\n return customerAddresses.find(\n (addr) =>\n addr.address1?.toLowerCase() === poAddress.address1.toLowerCase() &&\n addr.postalCode?.toLowerCase() === poAddress.postalCode?.toLowerCase()\n );\n}\n\nexport function hasPriceMismatch(\n poPriceValue: number | undefined,\n catalogPrice: number\n): boolean {\n return (\n poPriceValue !== undefined && Math.abs(poPriceValue - catalogPrice) > 0.01\n );\n}\n\n// Merge incoming items into existing stored items (for price tracking)\nexport function mergePoCartItems(\n existing: SetCartItem[],\n incoming: SetCartItem[]\n): SetCartItem[] {\n const merged = [...existing];\n for (const newItem of incoming) {\n const existingIndex = merged.findIndex(\n (item) =>\n item.productEntityId === newItem.productEntityId &&\n item.productVariantEntityId === newItem.productVariantEntityId\n );\n if (existingIndex >= 0) {\n merged[existingIndex] = newItem; // Replace with updated quantity/price\n } else {\n merged.push(newItem);\n }\n }\n return merged;\n}\n\n// Diff incoming items against current cart to determine adds/updates\nexport interface CartDiff {\n toAdd: SetCartItem[];\n toUpdate: Array<{\n lineItemEntityId: string;\n productEntityId: number;\n variantEntityId?: number;\n newQuantity: number;\n }>;\n}\n\nexport function diffCartItems(\n cartPhysicalItems: Cart['lineItems']['physicalItems'],\n incomingItems: SetCartItem[]\n): CartDiff {\n const toAdd: SetCartItem[] = [];\n const toUpdate: CartDiff['toUpdate'] = [];\n\n for (const incoming of incomingItems) {\n const existingCartItem = cartPhysicalItems.find(\n (ci) =>\n ci.productEntityId === incoming.productEntityId &&\n ci.variantEntityId === incoming.productVariantEntityId\n );\n\n if (!existingCartItem) {\n toAdd.push(incoming);\n } else if (existingCartItem.quantity !== incoming.quantity) {\n toUpdate.push({\n lineItemEntityId: existingCartItem.entityId,\n productEntityId: incoming.productEntityId,\n variantEntityId: existingCartItem.variantEntityId ?? undefined,\n newQuantity: incoming.quantity\n });\n }\n // If quantity matches, skip (no API call needed)\n }\n\n return { toAdd, toUpdate };\n}\n\n// Build CartItem list from a synced cart\nexport function buildSyncedCartResult(\n syncedCart: Cart,\n mergedItems: SetCartItem[]\n): { cartItems: CartItem[] } {\n const cartItems: CartItem[] = [];\n\n for (const item of syncedCart.lineItems.physicalItems) {\n const storedItem = mergedItems.find(\n (si) =>\n si.productEntityId === item.productEntityId &&\n si.productVariantEntityId === item.variantEntityId\n );\n\n const poPriceValue = storedItem?.poPriceValue;\n const catalogPrice = item.listPrice.value;\n const mismatch = hasPriceMismatch(poPriceValue, catalogPrice);\n\n cartItems.push({\n id: item.entityId,\n sku: item.sku,\n name: item.name,\n price: catalogPrice,\n imageUrl: item.imageUrl,\n productEntityId: item.productEntityId,\n variantEntityId: item.variantEntityId,\n quantity: item.quantity,\n bcLineItemEntityId: item.entityId,\n poPriceValue,\n poPriceCurrencyCode: storedItem?.poPriceCurrencyCode,\n status: mismatch ? 'price-mismatch' : 'matched'\n } as CartItem);\n }\n\n return { cartItems };\n}\n\nexport function normalizeProductSku(sku: string): string {\n return sku.replace(/-/g, '').toLowerCase();\n}\n\nexport function normalizeProductName(name: string): string {\n return name.toLowerCase();\n}\n\n// Filter out item warnings that are resolved by the given cart items\nexport function filterMatchingWarnings(\n warnings: ItemWarning[],\n cartItems: CartItem[]\n): ItemWarning[] {\n return warnings.filter(\n (w) =>\n !cartItems.some(\n (ci) =>\n (w.productSku &&\n ci.sku &&\n normalizeProductSku(w.productSku) ===\n normalizeProductSku(ci.sku)) ||\n (w.productName &&\n ci.name &&\n normalizeProductName(w.productName) ===\n normalizeProductName(ci.name))\n )\n );\n}\n","import { useCallback, useEffect, useMemo, useRef } from 'react';\nimport {\n CHECKOUT_ADDRESS_ID,\n PO_ADDRESS_ID,\n PO_BILLING_ADDRESS_ID\n} from '../constants.js';\nimport type {\n BigCommerceClient,\n MockBigCommerceClient\n} from '../lib/bigcommerce/index.js';\nimport type {\n Cart,\n CartRedirectUrls,\n CheckoutAddress,\n CustomerAddress\n} from '../lib/bigcommerce/storefront/types.js';\nimport { usePurchaseOrderStore } from '../stores/purchase-order-store.js';\nimport type { POPriceInfo } from '../stores/slices/cartifact-slice.js';\nimport type { CartItem, CheckoutTotals, SetCartItem } from '../types.js';\nimport {\n buildSyncedCartResult,\n diffCartItems,\n filterMatchingWarnings,\n findMatchingCustomerAddress,\n hasPriceMismatch,\n mergePoCartItems,\n toCheckoutAddress\n} from '../utils/cart-sync-helpers.js';\n\nexport interface UseBigCommerceCartOptions {\n client: BigCommerceClient | MockBigCommerceClient;\n onError?: (error: Error) => void;\n}\n\nexport function useBigCommerceCart(options: UseBigCommerceCartOptions) {\n const { client, onError } = options;\n const clientRef = useRef<BigCommerceClient | MockBigCommerceClient>(client);\n const onErrorRef = useRef(onError);\n onErrorRef.current = onError;\n\n // Get cart state from store\n const bcCart = usePurchaseOrderStore((state) => state.bcSession.bcCart);\n const checkout = usePurchaseOrderStore((state) => state.bcSession.checkout);\n const customerInfo = usePurchaseOrderStore(\n (state) => state.customer.customerInfo\n );\n const customerAddresses = usePurchaseOrderStore(\n (state) => state.customer.customerAddresses\n );\n const selectedAddressId = usePurchaseOrderStore(\n (state) => state.ui.selectedAddressId\n );\n const addressUpdateStatus = usePurchaseOrderStore(\n (state) => state.ui.addressUpdateStatus\n );\n const isLoading = usePurchaseOrderStore((state) => state.bcSession.isLoading);\n const productPaths = usePurchaseOrderStore(\n (state) => state.bcSession.productPaths\n );\n const poItemPrices = usePurchaseOrderStore(\n (state) => state.cartifact.poItemPrices\n );\n\n // Get cart actions from store\n const setBcCart = usePurchaseOrderStore((state) => state.setBcCart);\n const setCheckout = usePurchaseOrderStore((state) => state.setCheckout);\n const setSelectedAddressId = usePurchaseOrderStore(\n (state) => state.setSelectedAddressId\n );\n const setAddressUpdateStatus = usePurchaseOrderStore(\n (state) => state.setAddressUpdateStatus\n );\n const setIsLoading = usePurchaseOrderStore((state) => state.setIsLoading);\n\n const setProductPaths = usePurchaseOrderStore(\n (state) => state.setProductPaths\n );\n const shipToAddress = usePurchaseOrderStore(\n (state) => state.cartifact.shipToAddress\n );\n const billingAddress = usePurchaseOrderStore(\n (state) => state.cartifact.billingAddress\n );\n const selectedBillingAddressId = usePurchaseOrderStore(\n (state) => state.ui.selectedBillingAddressId\n );\n const billingAddressUpdateStatus = usePurchaseOrderStore(\n (state) => state.ui.billingAddressUpdateStatus\n );\n const setSelectedBillingAddressId = usePurchaseOrderStore(\n (state) => state.setSelectedBillingAddressId\n );\n const setBillingAddressUpdateStatus = usePurchaseOrderStore(\n (state) => state.setBillingAddressUpdateStatus\n );\n const setItemWarnings = usePurchaseOrderStore(\n (state) => state.setItemWarnings\n );\n\n // Store cart items for price comparison (PO prices) - derived from store\n const storedCartItems = useMemo<SetCartItem[]>(() => {\n if (!bcCart) return [];\n\n return bcCart.lineItems.physicalItems.map((item) => {\n const key = `${item.productEntityId}-${item.variantEntityId}`;\n const priceData = poItemPrices[key] as POPriceInfo | undefined;\n return {\n productEntityId: item.productEntityId,\n productVariantEntityId: item.variantEntityId ?? undefined,\n quantity: item.quantity,\n poPriceValue: priceData?.poPrice,\n poPriceCurrencyCode: priceData?.poCurrency\n };\n });\n }, [bcCart, poItemPrices]);\n\n // Track which product paths we've already fetched\n const fetchedPathIdsRef = useRef<Set<number>>(new Set());\n\n const updateCheckoutShippingAddress = useCallback(\n async (cart: Cart, address: CheckoutAddress) => {\n if (!clientRef.current) {\n return;\n }\n\n const lineItems = cart.lineItems.physicalItems.map((item) => ({\n lineItemEntityId: item.entityId,\n quantity: item.quantity\n }));\n\n if (lineItems.length === 0) {\n console.warn(\n 'Skipping checkout shipping address update: cart has no physical line items.'\n );\n return;\n }\n\n try {\n const updatedCheckout =\n await clientRef.current.setCheckoutShippingAddress(\n cart.entityId,\n address,\n lineItems\n );\n\n if (updatedCheckout) {\n setCheckout(updatedCheckout);\n }\n } catch (err) {\n console.error('Failed to update checkout shipping address:', err);\n onErrorRef.current?.(\n err instanceof Error\n ? err\n : new Error('Failed to update shipping address')\n );\n }\n },\n [setCheckout]\n );\n\n const updateCheckoutBillingAddress = useCallback(\n async (cart: Cart, address: CheckoutAddress) => {\n if (!clientRef.current) {\n return;\n }\n\n try {\n const updatedCheckout =\n await clientRef.current.setCheckoutBillingAddress(\n cart.entityId,\n address\n );\n\n if (updatedCheckout) {\n setCheckout(updatedCheckout);\n }\n } catch (err) {\n console.error('Failed to update checkout billing address:', err);\n onErrorRef.current?.(\n err instanceof Error\n ? err\n : new Error('Failed to update billing address')\n );\n }\n },\n [setCheckout]\n );\n\n // Fetch product paths for cart items we haven't fetched yet\n useEffect(() => {\n if (!bcCart || !clientRef.current) return;\n\n const productEntityIds = [\n ...new Set(\n bcCart.lineItems.physicalItems.map((item) => item.productEntityId)\n )\n ];\n const missingIds = productEntityIds.filter(\n (id) => !fetchedPathIdsRef.current.has(id)\n );\n if (missingIds.length === 0) return;\n\n // Mark as fetched before the request to prevent duplicate fetches\n for (const id of missingIds) {\n fetchedPathIdsRef.current.add(id);\n }\n\n clientRef.current.getProductPaths(missingIds).then((newPaths) => {\n if (newPaths.size > 0) {\n const newPathsRecord: Record<number, string> = {};\n for (const [id, path] of newPaths) {\n newPathsRecord[id] = path;\n }\n const currentPaths =\n usePurchaseOrderStore.getState().bcSession.productPaths;\n setProductPaths({ ...currentPaths, ...newPathsRecord });\n }\n });\n }, [bcCart, setProductPaths]);\n\n // Track whether checkout addresses have been applied\n const shippingAddressAppliedRef = useRef(false);\n const billingAddressAppliedRef = useRef(false);\n\n // Auto-select shipping address from PO (or default to \"enter at checkout\")\n useEffect(() => {\n if (selectedAddressId) {\n return;\n }\n\n if (!shipToAddress) {\n // No PO address — default to \"enter at checkout\"\n if (customerAddresses.length === 0) {\n setSelectedAddressId(CHECKOUT_ADDRESS_ID);\n }\n return;\n }\n\n let addressId: string;\n\n if (customerAddresses.length > 0) {\n const match = findMatchingCustomerAddress(\n shipToAddress,\n customerAddresses\n );\n addressId = match ? match.id : PO_ADDRESS_ID;\n } else {\n addressId = PO_ADDRESS_ID;\n }\n\n shippingAddressAppliedRef.current = false;\n setSelectedAddressId(addressId);\n }, [\n customerAddresses,\n shipToAddress,\n setSelectedAddressId,\n selectedAddressId\n ]);\n\n // Apply shipping address to checkout once bcCart is ready\n useEffect(() => {\n if (\n shippingAddressAppliedRef.current ||\n !bcCart ||\n !selectedAddressId ||\n selectedAddressId === CHECKOUT_ADDRESS_ID\n ) {\n return;\n }\n\n let checkoutAddress: CustomerAddress | undefined;\n\n if (selectedAddressId === PO_ADDRESS_ID) {\n checkoutAddress = shipToAddress ?? undefined;\n } else {\n checkoutAddress =\n customerAddresses.find((a) => a.id === selectedAddressId) ?? undefined;\n }\n\n if (!checkoutAddress) return;\n\n shippingAddressAppliedRef.current = true;\n void updateCheckoutShippingAddress(\n bcCart,\n toCheckoutAddress(checkoutAddress)\n );\n }, [\n bcCart,\n selectedAddressId,\n customerAddresses,\n shipToAddress,\n updateCheckoutShippingAddress\n ]);\n\n // Auto-select billing address from PO\n useEffect(() => {\n if (!billingAddress || selectedBillingAddressId) {\n return;\n }\n\n let addressId: string;\n\n if (customerAddresses.length > 0) {\n const match = findMatchingCustomerAddress(\n billingAddress,\n customerAddresses\n );\n addressId = match ? match.id : PO_BILLING_ADDRESS_ID;\n } else {\n addressId = PO_BILLING_ADDRESS_ID;\n }\n\n billingAddressAppliedRef.current = false;\n setSelectedBillingAddressId(addressId);\n }, [\n customerAddresses,\n billingAddress,\n setSelectedBillingAddressId,\n selectedBillingAddressId\n ]);\n\n // Apply billing address to checkout once bcCart is ready\n useEffect(() => {\n if (\n billingAddressAppliedRef.current ||\n !bcCart ||\n !selectedBillingAddressId ||\n selectedBillingAddressId === CHECKOUT_ADDRESS_ID\n ) {\n return;\n }\n\n let checkoutAddress: CustomerAddress | undefined;\n\n if (selectedBillingAddressId === PO_BILLING_ADDRESS_ID) {\n checkoutAddress = billingAddress ?? undefined;\n } else {\n checkoutAddress =\n customerAddresses.find((a) => a.id === selectedBillingAddressId) ??\n undefined;\n }\n\n if (!checkoutAddress) return;\n\n billingAddressAppliedRef.current = true;\n void updateCheckoutBillingAddress(\n bcCart,\n toCheckoutAddress(checkoutAddress)\n );\n }, [\n bcCart,\n selectedBillingAddressId,\n customerAddresses,\n billingAddress,\n updateCheckoutBillingAddress\n ]);\n\n // Store timeout IDs for cleanup\n const addressStatusTimeoutRef = useRef<number | undefined>(undefined);\n const billingAddressStatusTimeoutRef = useRef<number | undefined>(undefined);\n\n // Convert BC cart line items to CartItem format with price comparison\n const cartItems = useMemo<CartItem[]>(() => {\n if (!bcCart) return [];\n\n return bcCart.lineItems.physicalItems.map((item) => {\n const storedItem = storedCartItems.find(\n (si) =>\n si.productEntityId === item.productEntityId &&\n si.productVariantEntityId === item.variantEntityId\n );\n\n const poPriceValue = storedItem?.poPriceValue;\n const catalogPrice = item.listPrice.value;\n const hasMismatch = hasPriceMismatch(poPriceValue, catalogPrice);\n\n return {\n id: item.entityId,\n sku: item.sku ?? '',\n name: item.name,\n path: productPaths[item.productEntityId],\n price: catalogPrice,\n imageUrl: item.imageUrl ?? undefined,\n productEntityId: item.productEntityId,\n variantEntityId: item.variantEntityId ?? undefined,\n quantity: item.quantity,\n bcLineItemEntityId: item.entityId,\n poPriceValue,\n poPriceCurrencyCode: storedItem?.poPriceCurrencyCode,\n catalogPriceCurrencyCode: item.listPrice.currencyCode,\n status: hasMismatch ? 'price-mismatch' : 'matched'\n };\n });\n }, [bcCart, storedCartItems, productPaths]);\n\n // Checkout totals\n const checkoutTotals = useMemo<CheckoutTotals>(\n () => ({\n subtotal: bcCart?.amount?.value ?? 0,\n tax: checkout?.taxTotal?.value ?? null,\n shipping: checkout?.shippingCostTotal?.value ?? null,\n grandTotal: checkout?.grandTotal?.value ?? null\n }),\n [bcCart, checkout]\n );\n\n // Helper: Re-apply shipping address after cart modifications to keep totals fresh\n const reapplyShippingAddressAfterCartChange = useCallback(\n async (updatedCart: Cart | null): Promise<void> => {\n // Only re-apply if we have a cart, selected address, and line items\n if (\n !clientRef.current ||\n !updatedCart ||\n !selectedAddressId ||\n selectedAddressId === CHECKOUT_ADDRESS_ID ||\n updatedCart.lineItems.physicalItems.length === 0\n ) {\n return;\n }\n\n let checkoutAddress: CheckoutAddress | null = null;\n\n if (selectedAddressId === PO_ADDRESS_ID) {\n if (shipToAddress) {\n checkoutAddress = toCheckoutAddress(shipToAddress);\n }\n } else {\n const address = customerAddresses.find(\n (a) => a.id === selectedAddressId\n );\n if (address) {\n checkoutAddress = toCheckoutAddress(address);\n }\n }\n\n if (!checkoutAddress) {\n return;\n }\n\n await updateCheckoutShippingAddress(updatedCart, checkoutAddress);\n },\n [\n selectedAddressId,\n customerAddresses,\n shipToAddress,\n updateCheckoutShippingAddress\n ]\n );\n\n // Create or update cart from cart items (incremental updates)\n const syncCartItems = useCallback(\n async (\n items: SetCartItem[]\n ): Promise<{\n cart: Cart | null;\n cartItems: CartItem[];\n }> => {\n if (!clientRef.current) return { cart: null, cartItems: [] };\n\n // Early return for empty items - don't modify cart\n if (items.length === 0) {\n return { cart: bcCart, cartItems: [] };\n }\n\n setIsLoading(true);\n\n try {\n // Merge incoming items with stored items (for price tracking)\n const mergedItems = mergePoCartItems(storedCartItems, items);\n\n // Fetch current cart from BigCommerce\n const existingCart = await clientRef.current.getCart();\n\n let syncedCart: Cart | null = null;\n\n if (!existingCart) {\n // No cart exists - create fresh cart\n const lineItems = items.map((item) => ({\n productEntityId: item.productEntityId,\n variantEntityId: item.productVariantEntityId,\n quantity: item.quantity\n }));\n\n syncedCart = await clientRef.current.createCart(lineItems);\n\n // Store thread ID as cart metafield (fire-and-forget)\n if (syncedCart) {\n const threadId = usePurchaseOrderStore.getState().chat.threadId;\n if (threadId) {\n clientRef.current\n .createCartMetafield(syncedCart.entityId, 'thread_id', threadId)\n .catch((err: unknown) => {\n console.warn(\n '[useBigCommerceCart] Failed to set thread_id metafield:',\n err\n );\n });\n }\n }\n } else {\n // Cart exists and not first call - diff and apply incremental changes\n const { toAdd, toUpdate } = diffCartItems(\n existingCart.lineItems.physicalItems,\n items\n );\n syncedCart = existingCart;\n\n // Add new items in batch\n if (toAdd.length > 0) {\n const lineItems = toAdd.map((item) => ({\n productEntityId: item.productEntityId,\n variantEntityId: item.productVariantEntityId,\n quantity: item.quantity\n }));\n syncedCart =\n (await clientRef.current.addCartLineItems(\n existingCart.entityId,\n lineItems\n )) ?? syncedCart;\n }\n\n // Update quantities one by one\n for (const update of toUpdate) {\n syncedCart =\n (await clientRef.current.updateCartLineItem(\n existingCart.entityId,\n update.lineItemEntityId,\n update.newQuantity,\n update.productEntityId,\n update.variantEntityId\n )) ?? syncedCart;\n }\n\n // Re-apply shipping address to refresh totals after cart modifications\n if (toAdd.length > 0 || toUpdate.length > 0) {\n await reapplyShippingAddressAfterCartChange(syncedCart);\n }\n }\n\n setBcCart(syncedCart);\n\n // Sync cart entity ID and PO item prices to Zustand store for persistence\n const store = usePurchaseOrderStore.getState();\n store.setCartEntityId(syncedCart?.entityId ?? null);\n\n // Sync PO item prices to store for persistence\n for (const item of mergedItems) {\n if (\n item.poPriceValue !== undefined &&\n item.poPriceCurrencyCode !== undefined\n ) {\n store.setPoItemPrice(\n item.productEntityId,\n item.productVariantEntityId,\n item.poPriceValue,\n item.poPriceCurrencyCode\n );\n }\n }\n\n // Clean up stale price entries for items not in the final cart\n // (handles cases where items failed to add or were externally removed)\n if (syncedCart) {\n const finalCartItemKeys = new Set(\n syncedCart.lineItems.physicalItems.map(\n (item) => `${item.productEntityId}-${item.variantEntityId}`\n )\n );\n const storedKeys = Object.keys(store.cartifact.poItemPrices);\n for (const key of storedKeys) {\n if (!finalCartItemKeys.has(key)) {\n const parts = key.split('-');\n const productId = Number(parts[0]);\n const variantId = Number(parts[1]);\n if (!Number.isNaN(productId) && !Number.isNaN(variantId)) {\n store.removePoItemPrice(productId, variantId);\n }\n }\n }\n }\n\n // Set shipping address on newly created checkout if address is selected\n if (syncedCart && !existingCart && selectedAddressId) {\n const address = customerAddresses.find(\n (a) => a.id === selectedAddressId\n );\n if (address && syncedCart.lineItems.physicalItems.length > 0) {\n shippingAddressAppliedRef.current = true;\n await updateCheckoutShippingAddress(\n syncedCart,\n toCheckoutAddress(address)\n );\n }\n }\n\n if (!syncedCart) return { cart: null, cartItems: [] };\n\n const { cartItems: newCartItems } = buildSyncedCartResult(\n syncedCart,\n mergedItems\n );\n\n const currentWarnings =\n usePurchaseOrderStore.getState().cartifact.itemWarnings;\n const filteredWarnings = filterMatchingWarnings(\n currentWarnings,\n newCartItems\n );\n if (filteredWarnings.length !== currentWarnings.length) {\n setItemWarnings(filteredWarnings);\n }\n\n return { cart: syncedCart, cartItems: newCartItems };\n } catch (err) {\n throw err;\n } finally {\n setIsLoading(false);\n }\n },\n [\n bcCart,\n storedCartItems,\n selectedAddressId,\n customerAddresses,\n reapplyShippingAddressAfterCartChange,\n setBcCart,\n setIsLoading,\n setItemWarnings,\n updateCheckoutShippingAddress\n ]\n );\n\n // Add items to cart (additive - merges quantities with existing items)\n const addToCart = useCallback(\n async (items: SetCartItem[]): Promise<void> => {\n if (!clientRef.current) return;\n\n // Merge duplicate items within input (sum quantities)\n const mergedInput: SetCartItem[] = [];\n for (const item of items) {\n const existingIndex = mergedInput.findIndex(\n (i) =>\n i.productEntityId === item.productEntityId &&\n i.productVariantEntityId === item.productVariantEntityId\n );\n if (existingIndex >= 0) {\n const existing = mergedInput[existingIndex];\n if (existing) {\n existing.quantity += item.quantity;\n // Keep the price info from the latest item\n if (\n item.poPriceValue !== undefined &&\n item.poPriceCurrencyCode !== undefined\n ) {\n existing.poPriceValue = item.poPriceValue;\n existing.poPriceCurrencyCode = item.poPriceCurrencyCode;\n }\n }\n } else {\n mergedInput.push({ ...item });\n }\n }\n\n // Merge with existing cart items (add quantities for existing items)\n const itemsToSet: SetCartItem[] = [...storedCartItems];\n for (const item of mergedInput) {\n const existingIndex = itemsToSet.findIndex(\n (i) =>\n i.productEntityId === item.productEntityId &&\n i.productVariantEntityId === item.productVariantEntityId\n );\n if (existingIndex >= 0) {\n const existing = itemsToSet[existingIndex];\n if (existing) {\n // Add quantities together\n existing.quantity += item.quantity;\n // Update price info if provided\n if (\n item.poPriceValue !== undefined &&\n item.poPriceCurrencyCode !== undefined\n ) {\n existing.poPriceValue = item.poPriceValue;\n existing.poPriceCurrencyCode = item.poPriceCurrencyCode;\n }\n }\n } else {\n // New item\n itemsToSet.push(item);\n }\n }\n\n // Use syncCartItems to apply the changes\n await syncCartItems(itemsToSet);\n },\n [syncCartItems, storedCartItems]\n );\n\n // Update line item quantity\n const updateLineItemQuantity = useCallback(\n async (\n lineItemId: string,\n quantity: number,\n productEntityId: number,\n variantEntityId?: number\n ): Promise<Cart | null> => {\n if (!clientRef.current || !bcCart?.entityId) {\n return null;\n }\n\n setIsLoading(true);\n try {\n const updatedCart = await clientRef.current.updateCartLineItem(\n bcCart.entityId,\n lineItemId,\n quantity,\n productEntityId,\n variantEntityId\n );\n if (updatedCart) {\n setBcCart(updatedCart);\n // Re-apply shipping address to refresh totals\n await reapplyShippingAddressAfterCartChange(updatedCart);\n }\n return updatedCart;\n } catch (err) {\n onErrorRef.current?.(\n err instanceof Error ? err : new Error('Failed to update quantity')\n );\n return null;\n } finally {\n setIsLoading(false);\n }\n },\n [\n bcCart?.entityId,\n reapplyShippingAddressAfterCartChange,\n setBcCart,\n setIsLoading\n ]\n );\n\n // Remove line item\n const removeLineItem = useCallback(\n async (lineItemId: string): Promise<Cart | null> => {\n if (!clientRef.current || !bcCart?.entityId) {\n return null;\n }\n\n setIsLoading(true);\n\n try {\n const updatedCart = await clientRef.current.deleteCartLineItem(\n bcCart.entityId,\n lineItemId\n );\n\n setBcCart(updatedCart);\n\n // Remove price info for deleted items from the store\n const store = usePurchaseOrderStore.getState();\n if (updatedCart) {\n const remainingItems = updatedCart.lineItems.physicalItems;\n // Find removed items and remove their price info from store\n const removedItems = storedCartItems.filter(\n (stored) =>\n !remainingItems.some(\n (item) =>\n item.productEntityId === stored.productEntityId &&\n item.variantEntityId === stored.productVariantEntityId\n )\n );\n for (const removed of removedItems) {\n store.removePoItemPrice(\n removed.productEntityId,\n removed.productVariantEntityId\n );\n }\n // Re-apply shipping address to refresh totals\n await reapplyShippingAddressAfterCartChange(updatedCart);\n } else {\n // Cart is now empty (deleted)\n store.setCartEntityId(null);\n store.clearPoItemPrices();\n // Clear checkout when cart is deleted\n setCheckout(null);\n }\n\n return updatedCart;\n } catch (err) {\n onErrorRef.current?.(\n err instanceof Error ? err : new Error('Failed to remove item')\n );\n return null;\n } finally {\n setIsLoading(false);\n }\n },\n [\n bcCart?.entityId,\n reapplyShippingAddressAfterCartChange,\n setBcCart,\n setIsLoading,\n setCheckout,\n storedCartItems\n ]\n );\n\n // Initiate checkout (create redirect URL)\n const initiateCheckout =\n useCallback(async (): Promise<CartRedirectUrls | null> => {\n if (!clientRef.current) {\n console.error('initiateCheckout: No BigCommerce client');\n return null;\n }\n if (!bcCart?.entityId) {\n console.error('initiateCheckout: No cart entity ID', { bcCart });\n return null;\n }\n\n setIsLoading(true);\n try {\n // Set customer message (orderId) before creating redirect URLs\n // If this fails, continue with checkout anyway\n const threadId = usePurchaseOrderStore.getState().chat.threadId;\n const orderId = usePurchaseOrderStore.getState().cartifact.orderId;\n if (threadId) {\n try {\n await clientRef.current.updateCheckoutCustomerMessage(\n bcCart.entityId,\n {\n purchaseOrderNumber: orderId,\n threadId\n }\n );\n } catch {\n // Ignore errors - checkout should continue\n }\n }\n\n return await clientRef.current.createCartRedirectUrls(bcCart.entityId);\n } catch (err) {\n console.error('initiateCheckout: API error', err);\n onErrorRef.current?.(\n err instanceof Error\n ? err\n : new Error('Failed to create checkout URL')\n );\n // Only clear loading on error; on success, keep loading until redirect\n setIsLoading(false);\n return null;\n }\n }, [bcCart, setIsLoading]);\n\n // Set shipping address on checkout\n const setShippingAddressOnCheckout = useCallback(\n async (addressId: string) => {\n // \"Enter at checkout\" — just update the selection, no API call\n if (addressId === CHECKOUT_ADDRESS_ID) {\n setSelectedAddressId(addressId);\n return;\n }\n\n if (!clientRef.current) {\n console.error('setShippingAddressOnCheckout: No BigCommerce client');\n return;\n }\n if (!bcCart?.entityId) {\n console.error('setShippingAddressOnCheckout: No cart entity ID');\n return;\n }\n\n // Find the address\n let checkoutAddress: CheckoutAddress | null = null;\n\n if (addressId === PO_ADDRESS_ID) {\n if (shipToAddress) {\n checkoutAddress = toCheckoutAddress(shipToAddress);\n }\n } else {\n const address = customerAddresses.find((a) => a.id === addressId);\n if (address) {\n checkoutAddress = toCheckoutAddress(address);\n }\n }\n\n if (!checkoutAddress) {\n console.error(\n 'setShippingAddressOnCheckout: Address not found',\n addressId\n );\n return;\n }\n\n // Build line items array from current cart\n const lineItems = bcCart.lineItems.physicalItems.map((item) => ({\n lineItemEntityId: item.entityId,\n quantity: item.quantity\n }));\n\n if (lineItems.length === 0) {\n console.error('setShippingAddressOnCheckout: No line items in cart');\n return;\n }\n\n shippingAddressAppliedRef.current = true;\n setIsLoading(true);\n setAddressUpdateStatus('updating');\n try {\n // Checkout entityId equals cart entityId\n const updatedCheckout =\n await clientRef.current.setCheckoutShippingAddress(\n bcCart.entityId,\n checkoutAddress,\n lineItems\n );\n\n if (updatedCheckout) {\n setCheckout(updatedCheckout);\n }\n\n // Update selected address ID\n setSelectedAddressId(addressId);\n setAddressUpdateStatus('success');\n\n // Reset to idle after showing success briefly\n if (addressStatusTimeoutRef.current !== undefined) {\n clearTimeout(addressStatusTimeoutRef.current);\n }\n addressStatusTimeoutRef.current = window.setTimeout(() => {\n setAddressUpdateStatus('idle');\n addressStatusTimeoutRef.current = undefined;\n }, 1500);\n } catch (err) {\n console.error('setShippingAddressOnCheckout: API error', err);\n setAddressUpdateStatus('error');\n onErrorRef.current?.(\n err instanceof Error\n ? err\n : new Error('Failed to set shipping address')\n );\n\n // Reset to idle after showing error briefly\n if (addressStatusTimeoutRef.current !== undefined) {\n clearTimeout(addressStatusTimeoutRef.current);\n }\n addressStatusTimeoutRef.current = window.setTimeout(() => {\n setAddressUpdateStatus('idle');\n addressStatusTimeoutRef.current = undefined;\n }, 3000);\n } finally {\n setIsLoading(false);\n }\n },\n [\n bcCart,\n customerAddresses,\n shipToAddress,\n setIsLoading,\n setAddressUpdateStatus,\n setCheckout,\n setSelectedAddressId\n ]\n );\n\n // Set billing address on checkout\n const setBillingAddressOnCheckout = useCallback(\n async (addressId: string) => {\n // \"Enter at checkout\" — just update the selection, no API call\n if (addressId === CHECKOUT_ADDRESS_ID) {\n setSelectedBillingAddressId(addressId);\n return;\n }\n\n if (!clientRef.current) {\n return;\n }\n if (!bcCart?.entityId) {\n return;\n }\n\n let checkoutAddress: CheckoutAddress | null = null;\n\n if (addressId === PO_BILLING_ADDRESS_ID) {\n if (billingAddress) {\n checkoutAddress = toCheckoutAddress(billingAddress);\n }\n } else {\n const address = customerAddresses.find((a) => a.id === addressId);\n if (address) {\n checkoutAddress = toCheckoutAddress(address);\n }\n }\n\n if (!checkoutAddress) {\n return;\n }\n\n billingAddressAppliedRef.current = true;\n setIsLoading(true);\n setBillingAddressUpdateStatus('updating');\n try {\n const updatedCheckout =\n await clientRef.current.setCheckoutBillingAddress(\n bcCart.entityId,\n checkoutAddress\n );\n\n if (updatedCheckout) {\n setCheckout(updatedCheckout);\n }\n\n setSelectedBillingAddressId(addressId);\n setBillingAddressUpdateStatus('success');\n\n if (billingAddressStatusTimeoutRef.current !== undefined) {\n clearTimeout(billingAddressStatusTimeoutRef.current);\n }\n billingAddressStatusTimeoutRef.current = window.setTimeout(() => {\n setBillingAddressUpdateStatus('idle');\n billingAddressStatusTimeoutRef.current = undefined;\n }, 1500);\n } catch (err) {\n setBillingAddressUpdateStatus('error');\n onErrorRef.current?.(\n err instanceof Error\n ? err\n : new Error('Failed to set billing address')\n );\n\n if (billingAddressStatusTimeoutRef.current !== undefined) {\n clearTimeout(billingAddressStatusTimeoutRef.current);\n }\n billingAddressStatusTimeoutRef.current = window.setTimeout(() => {\n setBillingAddressUpdateStatus('idle');\n billingAddressStatusTimeoutRef.current = undefined;\n }, 3000);\n } finally {\n setIsLoading(false);\n }\n },\n [\n bcCart,\n customerAddresses,\n billingAddress,\n setIsLoading,\n setBillingAddressUpdateStatus,\n setCheckout,\n setSelectedBillingAddressId\n ]\n );\n\n // Clear cart\n const clearCart = useCallback(async () => {\n if (clientRef.current && bcCart?.entityId) {\n try {\n await clientRef.current.deleteCart(bcCart.entityId);\n } catch {\n // Ignore errors when clearing\n }\n }\n // Clear any pending timeouts\n if (addressStatusTimeoutRef.current !== undefined) {\n clearTimeout(addressStatusTimeoutRef.current);\n addressStatusTimeoutRef.current = undefined;\n }\n if (billingAddressStatusTimeoutRef.current !== undefined) {\n clearTimeout(billingAddressStatusTimeoutRef.current);\n billingAddressStatusTimeoutRef.current = undefined;\n }\n setBcCart(null);\n setCheckout(null);\n\n // Sync cart state to Zustand store\n const store = usePurchaseOrderStore.getState();\n store.setCartEntityId(null);\n store.clearPoItemPrices();\n }, [bcCart?.entityId, setBcCart, setCheckout]);\n\n return {\n bcCart,\n checkout,\n customerInfo,\n customerAddresses,\n selectedAddressId,\n addressUpdateStatus,\n selectedBillingAddressId,\n billingAddressUpdateStatus,\n isLoading,\n checkoutTotals,\n cartItems,\n addToCart,\n updateLineItemQuantity,\n removeLineItem,\n initiateCheckout,\n setShippingAddressOnCheckout,\n setBillingAddressOnCheckout,\n clearCart,\n setSelectedAddressId,\n setSelectedBillingAddressId\n };\n}\n\nexport type UseBigCommerceCartReturn = ReturnType<typeof useBigCommerceCart>;\n","import { useCallback } from 'react';\nimport type { CartItem, Product } from '../types.js';\nimport type { UseBigCommerceCartReturn } from './use-bigcommerce-cart.js';\n\ninterface UseCartHandlersOptions {\n bcCart: UseBigCommerceCartReturn;\n cartItems: CartItem[];\n sendMessage: (params: { text: string }) => void;\n onCheckoutInitiated?: (error?: Error) => void;\n onCheckout?: (checkoutUrl: string) => void | Promise<void>;\n}\n\nexport function useCartHandlers({\n bcCart,\n cartItems,\n sendMessage,\n onCheckoutInitiated,\n onCheckout\n}: UseCartHandlersOptions) {\n // Get cart actions from Zustand store\n const handleCheckout = useCallback(async () => {\n if (!bcCart.bcCart?.entityId) {\n console.error('No cart available for checkout');\n return;\n }\n\n const redirectUrls = await bcCart.initiateCheckout();\n if (redirectUrls?.redirectedCheckoutUrl) {\n onCheckoutInitiated?.();\n if (onCheckout) {\n await onCheckout(redirectUrls.redirectedCheckoutUrl);\n } else {\n window.location.href = redirectUrls.redirectedCheckoutUrl;\n }\n } else {\n const error = new Error('Failed to get checkout redirect URL');\n console.error(error.message, { redirectUrls, bcCart: bcCart.bcCart });\n onCheckoutInitiated?.(error);\n }\n }, [bcCart, onCheckoutInitiated, onCheckout]);\n\n const handleUpdateQuantity = useCallback(\n async (itemId: string, quantity: number) => {\n const item = cartItems.find((i) => i.id === itemId);\n if (!item?.productEntityId || !item?.variantEntityId) return;\n\n await bcCart.updateLineItemQuantity(\n itemId,\n quantity,\n item.productEntityId,\n item.variantEntityId\n );\n },\n [cartItems, bcCart]\n );\n\n const handleRemoveItem = useCallback(\n async (itemId: string) => {\n await bcCart.removeLineItem(itemId);\n },\n [bcCart]\n );\n\n const handleAddToCartFromSuggestion = useCallback(\n async (\n product: Product,\n quantity: number,\n selectedVariantEntityId?: number\n ): Promise<boolean> => {\n const { productEntityId } = product;\n // Use the selected variant if provided, otherwise fall back to product's default variant\n const variantEntityId =\n selectedVariantEntityId ?? product.variantEntityId;\n\n if (!productEntityId || !variantEntityId) {\n console.error('Cannot add to cart: missing entity IDs', product);\n return false;\n }\n\n const actualQuantity =\n product.availableQuantity !== undefined && product.availableQuantity > 0\n ? Math.min(quantity, product.availableQuantity)\n : quantity;\n\n try {\n await bcCart.addToCart([\n {\n productEntityId,\n productVariantEntityId: variantEntityId,\n quantity: actualQuantity\n }\n ]);\n\n return true;\n } catch (err) {\n console.error('Failed to add to cart:', err);\n return false;\n }\n },\n [bcCart]\n );\n\n const handleSuggestAlternatives = useCallback(\n (itemName: string, sku?: string) => {\n const message = sku\n ? `Suggest alternatives for \"${itemName}\" (SKU: ${sku})`\n : `Suggest alternatives for \"${itemName}\"`;\n sendMessage({ text: message });\n },\n [sendMessage]\n );\n\n const handleShowMoreLikeThis = useCallback(\n (itemName: string, sku?: string) => {\n const message = sku\n ? `Show more products like \"${itemName}\" (SKU: ${sku})`\n : `Show more products like \"${itemName}\"`;\n sendMessage({ text: message });\n },\n [sendMessage]\n );\n\n return {\n handleCheckout,\n handleUpdateQuantity,\n handleRemoveItem,\n handleAddToCartFromSuggestion,\n handleSuggestAlternatives,\n handleShowMoreLikeThis\n };\n}\n","import { useEffect, useRef } from 'react';\nimport type { AppState } from '../types.js';\nimport type { ChatPanelRef } from '../components/chat-view/chat-panel/chat-panel.js';\nimport type { useDocumentParser } from './use-document-parser.js';\nimport type { useProcessingState } from './use-processing-state.js';\nimport { usePurchaseOrderStore } from '../stores/purchase-order-store.js';\n\ninterface UseChatOrchestrationOptions {\n appState: AppState;\n setAppState: (value: AppState) => void;\n parser: ReturnType<typeof useDocumentParser>;\n sendMessage: (options: { text: string }) => void;\n processingState: ReturnType<typeof useProcessingState>;\n chatPanelRef: React.RefObject<ChatPanelRef | null>;\n}\n\nexport function useChatOrchestration({\n appState,\n setAppState,\n parser,\n sendMessage,\n processingState,\n chatPanelRef\n}: UseChatOrchestrationOptions) {\n const hasSentToPOAgent = useRef(false);\n const hasProcessedDocument = usePurchaseOrderStore(\n (state) => state.parser.hasProcessedDocument\n );\n const setHasProcessedDocument = usePurchaseOrderStore(\n (state) => state.setHasProcessedDocument\n );\n\n // When parser finishes streaming, send the parsed content to PO agent\n useEffect(() => {\n if (\n appState === 'processing' &&\n parser.parserStatus !== 'streaming' &&\n parser.parserStatus !== 'submitted' &&\n parser.parsedContent &&\n parser.parserMessages.length > 0 &&\n !hasSentToPOAgent.current\n ) {\n hasSentToPOAgent.current = true;\n setHasProcessedDocument(true);\n sendMessage({\n text: parser.parsedContent\n });\n }\n }, [\n parser.parserStatus,\n parser.parsedContent,\n appState,\n parser.parserMessages.length,\n sendMessage,\n setHasProcessedDocument\n ]);\n\n // Auto-transition from processing to ready when first response completes\n useEffect(() => {\n if (appState === 'processing' && processingState.isComplete) {\n const timer = setTimeout(() => {\n setAppState('chatting');\n requestAnimationFrame(() => {\n chatPanelRef.current?.scrollToBottom();\n });\n }, 500);\n return () => clearTimeout(timer);\n }\n }, [appState, processingState.isComplete, setAppState, chatPanelRef]);\n\n const reset = () => {\n hasSentToPOAgent.current = false;\n setHasProcessedDocument(false);\n };\n\n return {\n hasProcessedDocument,\n reset\n };\n}\n","// biome-ignore lint/suspicious/noExplicitAny: Module type kept loose to avoid tight coupling to Sentry internals\nlet Sentry: any = null;\n\n// Marked as external for packaging, and we want this to always be present in our app\nimport('@sentry/react')\n .then((m) => {\n Sentry = m;\n })\n .catch(() => {\n // @sentry/react not installed — tracing is a no-op\n });\n\nexport interface TracingSpan {\n end: () => void;\n setStatus: (status: { code: number; message: string }) => void;\n setAttribute: (key: string, value: string | number | boolean) => void;\n}\n\nconst NOOP_SPAN: TracingSpan = {\n end: () => {},\n setStatus: () => {},\n setAttribute: () => {}\n};\n\nexport function startInactiveSpan(options: {\n name: string;\n op?: string;\n attributes?: Record<string, string | number | boolean | undefined>;\n}): TracingSpan {\n if (!Sentry) return NOOP_SPAN;\n return Sentry.startInactiveSpan(options);\n}\n","export function readFileAsText(file: File): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result as string);\n reader.onerror = () => reject(new Error('Failed to read file'));\n reader.readAsText(file);\n });\n}\n\nexport function readFileAsDataUrl(file: File): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result as string);\n reader.onerror = () => reject(new Error('Failed to read file'));\n reader.readAsDataURL(file);\n });\n}\n","const SPREADSHEET_TYPES = new Set([\n 'application/vnd.ms-excel',\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'\n]);\n\nexport function isSpreadsheet(mimeType: string): boolean {\n return SPREADSHEET_TYPES.has(mimeType);\n}\n\nexport async function convertSpreadsheetToCsv(file: File): Promise<string> {\n const xlsx = await import('xlsx');\n const buffer = await file.arrayBuffer();\n const workbook = xlsx.read(buffer, { type: 'array' });\n\n if (workbook.SheetNames.length === 0) {\n throw new Error('Workbook contains no sheets');\n }\n\n const allRows: Record<string, unknown>[] = [];\n for (const name of workbook.SheetNames) {\n const sheet = workbook.Sheets[name]!;\n const rows = xlsx.utils.sheet_to_json<Record<string, unknown>>(sheet);\n allRows.push(...rows);\n }\n\n const merged = xlsx.utils.json_to_sheet(allRows);\n return xlsx.utils.sheet_to_csv(merged);\n}\n","const PDF_HEADER = '%PDF-';\nconst PDF_EOF = '%%EOF';\nconst MIN_PDF_SIZE = 256;\n\nexport type PdfValidationResult =\n | { valid: true }\n | { valid: false; reason: 'invalid' | 'password-protected' };\n\nfunction readFileAsArrayBuffer(file: Blob): Promise<ArrayBuffer> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result as ArrayBuffer);\n reader.onerror = () => reject(reader.error);\n reader.readAsArrayBuffer(file);\n });\n}\n\nexport async function validatePdf(file: File): Promise<PdfValidationResult> {\n if (file.size < MIN_PDF_SIZE) return { valid: false, reason: 'invalid' };\n\n let buffer: Uint8Array;\n try {\n buffer = new Uint8Array(await readFileAsArrayBuffer(file));\n } catch {\n return { valid: false, reason: 'invalid' };\n }\n\n const headerStr = String.fromCharCode(...buffer.slice(0, 5));\n if (!headerStr.startsWith(PDF_HEADER)) {\n return { valid: false, reason: 'invalid' };\n }\n\n const tailSize = Math.min(1024, buffer.length);\n const tailStr = String.fromCharCode(\n ...buffer.slice(buffer.length - tailSize)\n );\n if (!tailStr.includes(PDF_EOF)) {\n return { valid: false, reason: 'invalid' };\n }\n\n // Check for /Encrypt in the trailer dictionary (always near end of file)\n const trailerStart = Math.max(0, buffer.length - 8192);\n const trailerText = new TextDecoder().decode(buffer.slice(trailerStart));\n const start = trailerText.lastIndexOf('<<');\n const end = trailerText.lastIndexOf('>>');\n if (\n start !== -1 &&\n end !== -1 &&\n start < end &&\n trailerText.substring(start, end).includes('/Encrypt')\n ) {\n // The PDF is encrypted, but it may still be viewable without a password\n // (e.g., owner-password-only restrictions with an empty user password).\n // Use pdf.js to attempt opening — it will throw PasswordException only\n // when a user password is actually required.\n try {\n // Import the worker module first and register it on globalThis so pdf.js\n // can find it via its #mainThreadWorkerMessageHandler check. Without this,\n // pdf.js fails in the browser because GlobalWorkerOptions.workerSrc is only\n // auto-configured in Node.js, and the @vite-ignore on pdf.js's internal\n // worker import prevents Vite from bundling the worker file.\n const pdfjsWorker = await import(\n // @ts-ignore -- no type declarations for the worker bundle\n 'pdfjs-dist/legacy/build/pdf.worker.mjs'\n );\n (globalThis as Record<string, unknown>).pdfjsWorker = pdfjsWorker;\n\n const { getDocument } = await import('pdfjs-dist/legacy/build/pdf.mjs');\n const loadingTask = getDocument({\n data: buffer,\n isEvalSupported: false\n });\n try {\n const doc = await loadingTask.promise;\n doc.destroy();\n } catch (e) {\n await loadingTask.destroy();\n if (e instanceof Error && e.name === 'PasswordException') {\n return { valid: false, reason: 'password-protected' };\n }\n return { valid: false, reason: 'invalid' };\n }\n } catch (e) {\n // Import or worker setup failed\n console.error('PDF validation error:', e);\n return { valid: false, reason: 'invalid' };\n }\n }\n\n return { valid: true };\n}\n","import type { useChat } from '@ai-sdk/react';\nimport { useCallback, useState } from 'react';\nimport { readFileAsDataUrl, readFileAsText } from '../lib/read-file.js';\nimport { convertSpreadsheetToCsv, isSpreadsheet } from '../lib/spreadsheet.js';\nimport { validatePdf } from '../lib/validate-pdf.js';\nimport { usePurchaseOrderStore } from '../stores/purchase-order-store.js';\n\nconst TEXT_BASED_TYPES = new Set([\n 'text/csv',\n 'text/plain',\n 'application/json'\n]);\n\nconst PARSE_PROMPT =\n 'Please parse this document and extract relevant purchase order information.';\n\nfunction buildTextParts(fileName: string, content: string) {\n return [\n {\n type: 'text' as const,\n text: `${PARSE_PROMPT.replace('this document', `this ${fileName} document`)}\\n\\n${content}`\n }\n ];\n}\n\nfunction buildFileParts(dataUrl: string, mediaType: string, filename: string) {\n return [\n { type: 'text' as const, text: PARSE_PROMPT },\n {\n type: 'file' as const,\n url: dataUrl,\n mediaType,\n filename\n }\n ];\n}\n\ninterface UseFileUploadOptions {\n createParserThread: () => Promise<void>;\n sendParserMessage: ReturnType<typeof useChat>['sendMessage'];\n}\n\nexport function useFileUpload({\n createParserThread,\n sendParserMessage\n}: UseFileUploadOptions) {\n const [isUploadingFile, setIsUploadingFile] = useState(false);\n const [parserError, setParserError] = useState<string | null>(null);\n\n const handleFileUpload = useCallback(\n async (file: File) => {\n const store = usePurchaseOrderStore.getState();\n store.setParsedContent(null);\n setIsUploadingFile(true);\n store.setUploadedFileName(file.name);\n setParserError(null);\n\n if (file.type === 'application/pdf') {\n const result = await validatePdf(file);\n if (!result.valid) {\n setParserError(\n result.reason === 'password-protected'\n ? 'The PDF appears to be password protected.'\n : 'The file does not appear to be a valid PDF.'\n );\n setIsUploadingFile(false);\n return false;\n }\n }\n\n await createParserThread();\n\n try {\n if (isSpreadsheet(file.type)) {\n const csvContent = await convertSpreadsheetToCsv(file);\n sendParserMessage({ parts: buildTextParts(file.name, csvContent) });\n } else if (TEXT_BASED_TYPES.has(file.type)) {\n const textContent = await readFileAsText(file);\n sendParserMessage({ parts: buildTextParts(file.name, textContent) });\n } else {\n const dataUrl = await readFileAsDataUrl(file);\n sendParserMessage({\n parts: buildFileParts(dataUrl, file.type, file.name)\n });\n }\n } catch (error) {\n console.error('Failed to read file:', error);\n if (isSpreadsheet(file.type)) {\n setParserError(\n 'Failed to read the spreadsheet file. Please try saving it as CSV and uploading again.'\n );\n } else {\n usePurchaseOrderStore.getState().setParsedContent(null);\n }\n setIsUploadingFile(false);\n }\n },\n [createParserThread, sendParserMessage]\n );\n\n return {\n isUploadingFile,\n setIsUploadingFile,\n parserError,\n setParserError,\n handleFileUpload\n };\n}\n","import { z } from 'zod';\n\nexport const Thread = z.object({\n id: z.string()\n});\n\nexport type Thread = z.infer<typeof Thread>;\n","import { useCallback, useEffect, useRef, useState } from 'react';\nimport { useTakeShapeConfig } from '../contexts/takeshape-config-context.js';\nimport { Thread } from '../schema.js';\nimport { usePurchaseOrderStore } from '../stores/purchase-order-store.js';\n\nexport interface UseTakeShapeThreadOptions {\n agentName: string;\n createOnMount?: boolean;\n /**\n * If provided, the hook will use this thread ID instead of creating a new one.\n * Used for reconnecting to an existing thread after page reload.\n */\n existingThreadId?: string | null;\n /**\n * Whether to persist the thread ID to the store for session restoration.\n * Set to false for ephemeral threads like the document parser.\n * Defaults to true.\n */\n persist?: boolean;\n}\n\nexport function useTakeShapeThread(options: UseTakeShapeThreadOptions) {\n const {\n agentName,\n createOnMount,\n existingThreadId,\n persist = true\n } = options;\n\n const { projectId, apiKey, origin } = useTakeShapeConfig();\n\n const [isCreating, setIsCreating] = useState(false);\n // Initialize with existing thread ID if provided\n const thread = useRef<{ id: string } | null>(\n existingThreadId ? { id: existingThreadId } : null\n );\n\n const createThread = useCallback(async () => {\n setIsCreating(true);\n\n const maxRetries = 2;\n let attempt = 0;\n\n while (attempt <= maxRetries) {\n try {\n const response = await fetch(\n `${origin}/project/${projectId}/agents/threads`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`\n },\n body: JSON.stringify({\n agentName\n })\n }\n );\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n const data = await response.json();\n const parsed = Thread.parse(data);\n\n setIsCreating(false);\n thread.current = parsed;\n if (persist) {\n usePurchaseOrderStore.getState().setThreadId(parsed.id);\n }\n return;\n } catch (error) {\n const isLastAttempt = attempt === maxRetries;\n\n if (isLastAttempt) {\n setIsCreating(false);\n console.error(\n `Failed to create thread after ${maxRetries + 1} attempts:`,\n error\n );\n return;\n }\n\n // Exponential backoff: 500ms, 1000ms\n const backoffMs = 500 * 2 ** attempt;\n console.warn(\n `Thread creation failed (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${backoffMs}ms...`,\n error\n );\n\n await new Promise((resolve) => setTimeout(resolve, backoffMs));\n attempt++;\n }\n }\n }, [agentName, apiKey, origin, persist, projectId]);\n\n useEffect(() => {\n if (createOnMount && !isCreating && !thread.current) {\n createThread();\n }\n }, [createThread, createOnMount, isCreating]);\n\n // If we have an existingThreadId and no thread yet, use it.\n // This handles Zustand rehydration happening after initial mount.\n // Idempotent - once thread.current is set, this is a no-op.\n if (existingThreadId && !thread.current) {\n thread.current = { id: existingThreadId };\n }\n\n return {\n thread,\n isCreating,\n createThread\n };\n}\n","import { useChat } from '@ai-sdk/react';\nimport { DefaultChatTransport } from 'ai';\nimport { useCallback, useEffect, useRef } from 'react';\nimport { useTakeShapeConfig } from '../contexts/takeshape-config-context.js';\nimport { startInactiveSpan } from '../lib/tracing.js';\nimport { usePurchaseOrderStore } from '../stores/purchase-order-store.js';\nimport { useFileUpload } from './use-file-upload.js';\nimport { useTakeShapeThread } from './use-takeshape-thread.js';\n\nexport function useDocumentParser() {\n const { sseOrigin, projectId, apiKey } = useTakeShapeConfig();\n const { thread: parserThread, createThread: createParserThread } =\n useTakeShapeThread({\n agentName: 'documentParser',\n createOnMount: true,\n persist: false // Document parser is ephemeral, don't overwrite main chat thread\n });\n\n // Persisted state from Zustand store (read-only subscriptions)\n const parsedContent = usePurchaseOrderStore(\n (state) => state.parser.parsedContent\n );\n const uploadedFileName = usePurchaseOrderStore(\n (state) => state.parser.uploadedFileName\n );\n\n const parserSpanRef = useRef<ReturnType<typeof startInactiveSpan> | null>(\n null\n );\n\n const {\n messages: parserMessages,\n sendMessage: sendParserMessage,\n status: parserStatus,\n setMessages: setParserMessages\n } = useChat({\n transport: new DefaultChatTransport({\n api: `${sseOrigin}/project/${projectId}/agents/messages`,\n headers: {\n Authorization: `Bearer ${apiKey}`\n },\n prepareSendMessagesRequest: async (options) => {\n const lastMessage = options.messages[options.messages.length - 1];\n return {\n body: {\n id: parserThread.current?.id ?? '',\n messages: [lastMessage],\n trigger: options.trigger,\n messageId: options.messageId,\n metadata: {\n ...(options.requestMetadata as Record<string, unknown>),\n custom: {\n inputName: 'documentParser'\n }\n }\n }\n };\n }\n }),\n messages: [],\n onError: (error) => {\n console.error('Document parser error:', error);\n setParserError(\n 'Failed to process the document. Please try a different file.'\n );\n parserSpanRef.current?.setStatus({ code: 2, message: 'internal_error' });\n parserSpanRef.current?.end();\n parserSpanRef.current = null;\n setIsUploadingFile(false);\n }\n });\n\n const {\n isUploadingFile,\n setIsUploadingFile,\n parserError,\n setParserError,\n handleFileUpload: baseHandleFileUpload\n } = useFileUpload({\n createParserThread,\n sendParserMessage\n });\n\n const handleFileUpload = useCallback(\n async (file: File) => {\n parserSpanRef.current?.end();\n parserSpanRef.current = startInactiveSpan({\n name: 'document-parser',\n op: 'ai.parse',\n attributes: {\n 'file.name': file.name,\n 'file.type': file.type,\n 'file.size': file.size\n }\n });\n\n return baseHandleFileUpload(file);\n },\n [baseHandleFileUpload]\n );\n\n // Update parsed content as parser streams\n useEffect(() => {\n if (parserMessages.length > 0) {\n const lastMessage = parserMessages[parserMessages.length - 1];\n if (\n lastMessage?.role === 'assistant' &&\n Array.isArray(lastMessage.parts)\n ) {\n const textParts = lastMessage.parts\n .filter((part) => part.type === 'text')\n .map((part) => part.text)\n .filter(Boolean);\n const textContent = textParts.join('');\n usePurchaseOrderStore.getState().setParsedContent(textContent);\n if (textContent) {\n setIsUploadingFile(false);\n }\n }\n }\n }, [parserMessages, setIsUploadingFile]);\n\n // Clean up open parser span on unmount\n useEffect(() => {\n return () => {\n parserSpanRef.current?.setStatus({ code: 2, message: 'cancelled' });\n parserSpanRef.current?.end();\n parserSpanRef.current = null;\n };\n }, []);\n\n // End parser span when parsing is fully complete (not on first streamed chunk)\n useEffect(() => {\n if (\n parserStatus === 'ready' &&\n parserSpanRef.current &&\n parsedContent !== null\n ) {\n parserSpanRef.current.setStatus({ code: 1, message: 'ok' });\n parserSpanRef.current.end();\n parserSpanRef.current = null;\n }\n }, [parserStatus, parsedContent]);\n\n const handleClearError = useCallback(() => {\n parserSpanRef.current?.setStatus({ code: 2, message: 'cancelled' });\n parserSpanRef.current?.end();\n parserSpanRef.current = null;\n setParserError(null);\n setParserMessages([]);\n usePurchaseOrderStore.getState().setParsedContent(null);\n createParserThread();\n }, [setParserError, setParserMessages, createParserThread]);\n\n const reset = useCallback(() => {\n parserSpanRef.current?.setStatus({ code: 2, message: 'cancelled' });\n parserSpanRef.current?.end();\n parserSpanRef.current = null;\n setParserMessages([]);\n usePurchaseOrderStore.getState().clearParser();\n setIsUploadingFile(false);\n setParserError(null);\n createParserThread();\n }, [\n setParserMessages,\n setIsUploadingFile,\n setParserError,\n createParserThread\n ]);\n\n return {\n parsedContent,\n isUploadingFile,\n uploadedFileName,\n parserError,\n parserStatus,\n parserMessages,\n handleFileUpload,\n handleClearError,\n reset\n };\n}\n","import type { UIMessage } from 'ai';\nimport { useMemo } from 'react';\nimport type { AppState, ProcessingStep } from '../types.js';\nimport {\n deriveCurrentStep,\n isFirstResponseComplete\n} from '../utils/processing-helpers.js';\n\nexport interface ProcessingState {\n currentStep: ProcessingStep | null;\n isProcessing: boolean;\n isComplete: boolean;\n}\n\nexport function useProcessingState(\n messages: UIMessage[],\n appState: AppState,\n status: string,\n parsedContent?: string | null\n): ProcessingState {\n return useMemo(() => {\n if (appState !== 'processing') {\n return {\n currentStep: null,\n isProcessing: false,\n isComplete: false\n };\n }\n\n const isComplete = isFirstResponseComplete(messages, status);\n\n // Determine current step:\n // - 'reading': Initial state (no parsedContent yet)\n // - 'matching': Have parsedContent, but setPoMetadata/addToCart not called yet\n // - 'building': setPoMetadata or addToCart has been called\n const derivedStep = deriveCurrentStep(messages);\n let currentStep: ProcessingStep = 'reading';\n\n if (derivedStep === 'building') {\n currentStep = 'building';\n } else if (parsedContent) {\n currentStep = 'matching';\n }\n\n return {\n currentStep,\n isProcessing: true,\n isComplete\n };\n }, [messages, appState, status, parsedContent]);\n}\n","import type { UseBigCommerceCartReturn } from '../../hooks/use-bigcommerce-cart.js';\nimport { usePurchaseOrderStore } from '../../stores/purchase-order-store.js';\nimport type { AddToCartInput } from '../../types.js';\nimport type { PendingToolOutput, ToolCall } from './types.js';\n\nexport async function handleAddToCart(\n toolCall: ToolCall,\n bcCart: UseBigCommerceCartReturn\n): Promise<PendingToolOutput> {\n const { setToolCallError } = usePurchaseOrderStore.getState();\n\n const input = toolCall.input as AddToCartInput;\n let output = 'No items provided to add to cart.';\n\n if (input.value && input.value.length > 0) {\n try {\n await bcCart.addToCart(input.value);\n output = `Successfully added ${input.value.length} item(s) to cart.`;\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n output = `Failed to add items to cart: ${message}`;\n setToolCallError(toolCall.toolCallId, message);\n }\n }\n\n return {\n tool: 'addToCart',\n toolCallId: toolCall.toolCallId,\n output\n };\n}\n","import type { UseBigCommerceCartReturn } from '../../hooks/use-bigcommerce-cart.js';\nimport { usePurchaseOrderStore } from '../../stores/purchase-order-store.js';\nimport type { PendingToolOutput, ToolCall } from './types.js';\n\nexport async function handleClearCart(\n toolCall: ToolCall,\n bcCart: UseBigCommerceCartReturn\n): Promise<PendingToolOutput> {\n const { setToolCallError } = usePurchaseOrderStore.getState();\n\n let output = 'Cart cleared successfully.';\n\n try {\n await bcCart.clearCart();\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n output = `Failed to clear cart: ${message}`;\n setToolCallError(toolCall.toolCallId, message);\n }\n\n return {\n tool: 'clearCart',\n toolCallId: toolCall.toolCallId,\n output\n };\n}\n","import type { UseBigCommerceCartReturn } from '../../hooks/use-bigcommerce-cart.js';\nimport type { PendingToolOutput, ToolCall } from './types.js';\n\nexport function handleGetCart(\n toolCall: ToolCall,\n bcCart: UseBigCommerceCartReturn\n): PendingToolOutput {\n const cartData = {\n items: bcCart.cartItems.map((item) => ({\n productEntityId: item.productEntityId,\n variantEntityId: item.variantEntityId,\n sku: item.sku,\n name: item.name,\n quantity: item.quantity,\n price: item.price,\n poPriceValue: item.poPriceValue,\n status: item.status\n })),\n totals: bcCart.checkoutTotals\n };\n\n return {\n tool: 'getCart',\n toolCallId: toolCall.toolCallId,\n output: JSON.stringify(cartData)\n };\n}\n","import type { UseBigCommerceCartReturn } from '../../hooks/use-bigcommerce-cart.js';\nimport type { CartPhysicalItem } from '../../lib/bigcommerce/storefront/types.js';\nimport { usePurchaseOrderStore } from '../../stores/purchase-order-store.js';\nimport type { RemoveFromCartInput } from '../../types.js';\nimport type { PendingToolOutput, ToolCall } from './types.js';\n\nexport async function handleRemoveFromCart(\n toolCall: ToolCall,\n bcCart: UseBigCommerceCartReturn\n): Promise<PendingToolOutput> {\n const { setToolCallError } = usePurchaseOrderStore.getState();\n\n const input = toolCall.input as RemoveFromCartInput;\n let output = 'Item removed from cart successfully.';\n\n try {\n const bcCartItem = bcCart.bcCart?.lineItems.physicalItems.find(\n (i: CartPhysicalItem) =>\n i.productEntityId === input.productEntityId &&\n i.variantEntityId === input.productVariantEntityId\n );\n\n if (bcCartItem) {\n await bcCart.removeLineItem(bcCartItem.entityId);\n } else {\n return {\n tool: 'removeFromCart',\n toolCallId: toolCall.toolCallId,\n output: 'Cart item not found.'\n };\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n output = `Failed to remove item from cart: ${message}`;\n setToolCallError(toolCall.toolCallId, message);\n }\n\n return {\n tool: 'removeFromCart',\n toolCallId: toolCall.toolCallId,\n output\n };\n}\n","import { usePurchaseOrderStore } from '../../stores/purchase-order-store.js';\nimport type { ItemWarning, RemoveItemWarningsInput } from '../../types.js';\nimport {\n normalizeProductName,\n normalizeProductSku\n} from '../../utils/cart-sync-helpers.js';\nimport type { PendingToolOutput, ToolCall } from './types.js';\n\nexport function handleRemoveItemWarnings(\n toolCall: ToolCall\n): PendingToolOutput {\n const {\n cartifact: { itemWarnings },\n setItemWarnings\n } = usePurchaseOrderStore.getState();\n\n const input = toolCall.input as RemoveItemWarningsInput;\n const remaining = itemWarnings.filter(\n (w: ItemWarning) =>\n !(\n (input.productSku !== undefined &&\n w.productSku !== undefined &&\n normalizeProductSku(w.productSku) ===\n normalizeProductSku(input.productSku)) ||\n (input.productName !== undefined &&\n w.productName !== undefined &&\n normalizeProductName(w.productName) ===\n normalizeProductName(input.productName))\n )\n );\n setItemWarnings(remaining);\n\n return {\n tool: 'removeItemWarnings',\n toolCallId: toolCall.toolCallId,\n output: 'Item warnings removed successfully.'\n };\n}\n","import { usePurchaseOrderStore } from '../../stores/purchase-order-store.js';\nimport type { SetItemWarningsInput } from '../../types.js';\nimport type { PendingToolOutput, ToolCall } from './types.js';\n\nexport function handleSetItemWarnings(toolCall: ToolCall): PendingToolOutput {\n const { setItemWarnings } = usePurchaseOrderStore.getState();\n\n const input = toolCall.input as SetItemWarningsInput;\n if (input.itemWarnings) {\n setItemWarnings(input.itemWarnings);\n }\n\n return {\n tool: 'setItemWarnings',\n toolCallId: toolCall.toolCallId,\n output: 'Item warnings set successfully.'\n };\n}\n","import { usePurchaseOrderStore } from '../../stores/purchase-order-store.js';\nimport type { SetPoMetadataInput } from '../../types.js';\nimport type { PendingToolOutput, ToolCall } from './types.js';\n\nexport function handleSetPoMetadata(toolCall: ToolCall): PendingToolOutput {\n const {\n setPoMetadataSet,\n setOrderId,\n setBuyerInfo,\n setShipToAddress,\n setBillingAddress\n } = usePurchaseOrderStore.getState();\n\n const input = toolCall.input as SetPoMetadataInput;\n const { poMetadata } = input;\n\n setPoMetadataSet(true);\n\n if (poMetadata.orderId) {\n setOrderId(poMetadata.orderId);\n }\n\n if (\n poMetadata.buyerEmail ||\n poMetadata.buyerFirstName ||\n poMetadata.buyerLastName\n ) {\n setBuyerInfo({\n email: poMetadata.buyerEmail,\n firstName: poMetadata.buyerFirstName,\n lastName: poMetadata.buyerLastName\n });\n }\n\n if (poMetadata.shipToAddress) {\n setShipToAddress(poMetadata.shipToAddress);\n }\n\n if (poMetadata.billingAddress) {\n setBillingAddress(poMetadata.billingAddress);\n }\n\n return {\n tool: 'setPoMetadata',\n toolCallId: toolCall.toolCallId,\n output: 'PO metadata set successfully.'\n };\n}\n","import type { UseBigCommerceCartReturn } from '../../hooks/use-bigcommerce-cart.js';\nimport type { CartPhysicalItem } from '../../lib/bigcommerce/storefront/types.js';\nimport { usePurchaseOrderStore } from '../../stores/purchase-order-store.js';\nimport type { UpdateCartInput } from '../../types.js';\nimport type { PendingToolOutput, ToolCall } from './types.js';\n\nexport async function handleUpdateCart(\n toolCall: ToolCall,\n bcCart: UseBigCommerceCartReturn\n): Promise<PendingToolOutput> {\n const { setToolCallError, setPoItemPrice } = usePurchaseOrderStore.getState();\n\n const input = toolCall.input as UpdateCartInput;\n let itemsUpdated = 0;\n\n try {\n const bcCartItem = bcCart.bcCart?.lineItems.physicalItems.find(\n (i: CartPhysicalItem) =>\n i.productEntityId === input.where.productEntityId &&\n i.variantEntityId === input.where.productVariantEntityId\n );\n\n if (bcCartItem && input.data.quantity !== undefined) {\n await bcCart.updateLineItemQuantity(\n bcCartItem.entityId,\n input.data.quantity,\n bcCartItem.productEntityId,\n bcCartItem.variantEntityId ?? undefined\n );\n itemsUpdated++;\n }\n\n if (\n input.data.poPriceValue !== undefined &&\n input.data.poPriceCurrencyCode !== undefined\n ) {\n setPoItemPrice(\n input.where.productEntityId,\n input.where.productVariantEntityId,\n input.data.poPriceValue,\n input.data.poPriceCurrencyCode\n );\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n setToolCallError(toolCall.toolCallId, message);\n return {\n tool: 'updateCart',\n toolCallId: toolCall.toolCallId,\n output: `Failed to update cart item: ${message}`\n };\n }\n\n return {\n tool: 'updateCart',\n toolCallId: toolCall.toolCallId,\n output: `${itemsUpdated} cart item(s) updated.`\n };\n}\n","import type { UseBigCommerceCartReturn } from '../../hooks/use-bigcommerce-cart.js';\nimport { handleAddToCart } from './add-to-cart.js';\nimport { handleClearCart } from './clear-cart.js';\nimport { handleGetCart } from './get-cart.js';\nimport { handleRemoveFromCart } from './remove-from-cart.js';\nimport { handleRemoveItemWarnings } from './remove-item-warnings.js';\nimport { handleSetItemWarnings } from './set-item-warnings.js';\nimport { handleSetPoMetadata } from './set-po-metadata.js';\nimport type { PendingToolOutput, ToolCall, ToolHandler } from './types.js';\nimport { handleUpdateCart } from './update-cart.js';\n\nexport type { PendingToolOutput, ToolCall, ToolHandler } from './types.js';\n\nconst toolHandlers: Record<string, ToolHandler> = {\n addToCart: handleAddToCart,\n updateCart: handleUpdateCart,\n removeFromCart: handleRemoveFromCart,\n clearCart: handleClearCart,\n getCart: handleGetCart,\n setPoMetadata: handleSetPoMetadata,\n setItemWarnings: handleSetItemWarnings,\n removeItemWarnings: handleRemoveItemWarnings\n};\n\nexport async function handleToolCall(\n toolCall: ToolCall,\n bcCart: UseBigCommerceCartReturn\n): Promise<PendingToolOutput | undefined> {\n const handler = toolHandlers[toolCall.toolName];\n return handler?.(toolCall, bcCart);\n}\n","import { useRef } from 'react';\nimport {\n handleToolCall,\n type PendingToolOutput,\n type ToolCall\n} from '../lib/tool-handlers/index.js';\nimport type { UseBigCommerceCartReturn } from './use-bigcommerce-cart.js';\n\nexport type { PendingToolOutput };\n\ninterface UseToolCallHandlersOptions {\n bcCart: UseBigCommerceCartReturn;\n}\n\nexport function useToolCallHandlers({ bcCart }: UseToolCallHandlersOptions) {\n // Pending async tool outputs — consumed by useEffect in app.tsx after streaming ends.\n // This ref is returned and read by the parent component rather than passed in as a callback\n // to avoid a circular dependency: useToolCallHandlers produces outputs that useChat's\n // addToolOutput consumes, but addToolOutput comes from useChat which depends on onToolCall.\n const pendingToolOutputsRef = useRef<PendingToolOutput[]>([]);\n\n const onToolCall = async ({ toolCall }: { toolCall: ToolCall }) => {\n const output = await handleToolCall(toolCall, bcCart);\n if (output) {\n pendingToolOutputsRef.current.push(output);\n }\n };\n\n return { onToolCall, pendingToolOutputsRef };\n}\n","// B2B Edition GraphQL Client\n// Handles authentication and address fetching from the BigCommerce B2B Edition API\n\nimport type { ResultOf, TadaDocumentNode } from 'gql.tada';\nimport { GraphQLClient, type Variables } from 'graphql-request';\nimport { B2B_APP_CLIENT_ID, B2B_GRAPHQL_URL } from '../../../constants.js';\nimport type { CustomerAddress } from '../storefront/types.js';\nimport type { TadaRequestOptions } from '../types.js';\nimport { convertCompanyAddressToCustomerAddress } from '../utils.js';\nimport { readFragment } from './graphql.js';\nimport {\n AuthorizationMutation,\n CheckoutLoginMutation,\n CompanyAddressesQuery,\n CurrentUserQuery,\n UserAuthorizationFragment,\n UserFragment\n} from './queries.js';\n\nexport interface B2BClientConfig {\n channelId: number;\n /** Optional B2B JWT fetcher. Receives channelId and returns a B2B storefront token. If not provided, B2B features are disabled. */\n getB2BJwt?: (channelId: number) => Promise<string | null>;\n}\n\nexport class B2BClient {\n private b2bToken: string | null = null;\n private companyId: number | null = null;\n private channelId: number;\n private graphQLClient: GraphQLClient;\n private getB2BJwt: ((channelId: number) => Promise<string | null>) | null;\n readonly initPromise: Promise<void>;\n\n constructor(config: B2BClientConfig) {\n this.channelId = config.channelId;\n this.getB2BJwt = config.getB2BJwt ?? null;\n\n this.graphQLClient = new GraphQLClient(B2B_GRAPHQL_URL, {\n credentials: 'same-origin',\n headers: {\n 'content-type': 'application/json',\n accept: 'application/json'\n }\n });\n\n if (this.getB2BJwt) {\n this.initPromise = this.init();\n } else {\n this.initPromise = Promise.resolve();\n this.b2bToken = null;\n }\n }\n\n get isAvailable(): boolean {\n return this.b2bToken !== null && this.companyId !== null;\n }\n\n private async init(): Promise<void> {\n if (!this.getB2BJwt) {\n console.info(\n '[B2BClient] No B2B token fetcher provided, B2B features disabled'\n );\n this.b2bToken = null;\n return;\n }\n\n try {\n const jwt = await this.getB2BJwt(this.channelId);\n if (!jwt) {\n console.info('[B2BClient] No JWT returned, B2B features disabled');\n this.b2bToken = null;\n return;\n }\n this.b2bToken = jwt;\n this.companyId = await this.getB2BCompanyId(this.b2bToken);\n console.info('[B2BClient] B2B Edition authenticated successfully');\n } catch {\n console.info(\n '[B2BClient] B2B Edition not available, skipping B2B address enrichment'\n );\n this.b2bToken = null;\n }\n }\n\n /**\n * Execute a request with retry logic (up to 5 attempts with exponential backoff)\n */\n private async request<const R, V extends Variables | undefined>(\n options: TadaRequestOptions<R, V>,\n attempt = 1\n ): Promise<ResultOf<TadaDocumentNode<R, V>>> {\n const maxAttempts = 5;\n const delays = [1000, 2000, 4000, 8000, 16000]; // 1s, 2s, 4s, 8s, 16s\n\n try {\n const result = await this.graphQLClient.request(options);\n return result;\n } catch (error) {\n if (attempt !== -1 && attempt < maxAttempts) {\n const delay = delays[attempt - 1] ?? 16000;\n console.warn(\n `[BigCommerceClient] Request failed, retrying in ${delay / 1000}s (attempt ${attempt}/${maxAttempts})`,\n error\n );\n await new Promise((resolve) => setTimeout(resolve, delay));\n return this.request(options, attempt + 1);\n }\n console.error(\n `[BigCommerceClient] Request failed after ${maxAttempts} attempts:`,\n error\n );\n throw error;\n }\n }\n\n private async getB2BStorefrontToken(jwt: string): Promise<string> {\n const result = await this.request({\n document: AuthorizationMutation,\n variables: {\n authData: {\n bcToken: jwt,\n channelId: this.channelId\n }\n },\n requestHeaders: {\n Authorization: `Bearer ${jwt}`\n }\n });\n\n const userAuthorization = readFragment(\n UserAuthorizationFragment,\n result.authorization\n );\n const token = userAuthorization?.result?.token;\n\n if (!token) {\n throw new Error('No token returned from B2B authorization mutation');\n }\n\n return token;\n }\n\n private async getB2BCompanyId(jwt: string): Promise<number> {\n console.debug('[B2BClient] Requesting company ID with customer JWT');\n\n const result = await this.request(\n {\n document: CurrentUserQuery,\n requestHeaders: {\n Authorization: `Bearer ${jwt}`\n }\n },\n -1\n );\n\n const currentUser = readFragment(UserFragment, result.currentUser);\n const companyId = currentUser?.companyInfo?.companyId;\n\n if (!companyId) {\n throw new Error('No company ID returned from current user query');\n }\n\n console.debug('[B2BClient] Received company ID', companyId);\n\n return Number(companyId);\n }\n\n async getCompanyAddresses(): Promise<CustomerAddress[]> {\n await this.initPromise;\n\n if (!this.isAvailable) {\n return [];\n }\n\n try {\n const result = await this.request({\n document: CompanyAddressesQuery,\n variables: {\n companyId: this.companyId!\n },\n requestHeaders: {\n Authorization: `Bearer ${this.b2bToken!}`\n }\n });\n\n const addressEdges = result?.addresses?.edges;\n\n if (!addressEdges) {\n return [];\n }\n\n return addressEdges.map((edge) =>\n convertCompanyAddressToCustomerAddress(edge.node)\n );\n } catch (error) {\n console.info(\n '[B2BClient] Failed to fetch B2B company addresses, continuing without them',\n error\n );\n return [];\n }\n }\n\n async createCartRedirectUrls(\n cartId: string\n ): Promise<{ redirectedCheckoutUrl: string }> {\n await this.initPromise;\n\n if (!this.isAvailable) {\n throw new Error('B2B client is not available');\n }\n\n try {\n const result = await this.request({\n document: CheckoutLoginMutation,\n variables: {\n cartData: {\n cartId\n }\n },\n requestHeaders: {\n Authorization: `Bearer ${this.b2bToken!}`\n }\n });\n\n const redirectedCheckoutUrl = result?.checkoutLogin?.result?.redirectUrl;\n\n if (!redirectedCheckoutUrl) {\n throw new Error(\n 'No redirect URL returned from checkout login mutation'\n );\n }\n\n return {\n redirectedCheckoutUrl\n };\n } catch (error) {\n console.error('[B2BClient] Failed to create cart redirect URLs', error);\n throw error;\n }\n }\n}\n\n/**\n * Create a B2B client with the given configuration.\n */\nexport function createB2BClient(config: B2BClientConfig): B2BClient {\n console.debug(\n `[createB2BClient] Initializing B2B client for channelId=${config.channelId}`\n );\n return new B2BClient(config);\n}\n\n/**\n * B2B JWT fetcher for Stencil storefronts.\n * Fetches the customer JWT from /customer/current.jwt and exchanges it for a B2B storefront token.\n *\n * @param channelId - BigCommerce channel ID (passed by the B2BClient)\n * @returns B2B storefront token, or null if not available\n *\n * @example\n * ```tsx\n * import { stencilB2BJwt } from '@takeshape/purchase-order-chat';\n *\n * <PurchaseOrderChat\n * bigCommerce={{\n * endpoint: '/graphql',\n * channelId: 1,\n * getB2BJwt: stencilB2BJwt\n * }}\n * // ...\n * />\n * ```\n */\nexport async function stencilB2BJwt(channelId: number): Promise<string | null> {\n // Fetch customer JWT from Stencil's /customer/current.jwt endpoint\n let customerJwt: string | null = null;\n try {\n const resp = await fetch(\n `/customer/current.jwt?app_client_id=${B2B_APP_CLIENT_ID}`,\n {\n method: 'GET',\n credentials: 'same-origin',\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json'\n }\n }\n );\n\n if (resp.ok) {\n const data = await resp.json();\n customerJwt = data?.token ?? null;\n }\n } catch {\n return null;\n }\n\n if (!customerJwt) {\n return null;\n }\n\n // Exchange customer JWT for B2B storefront token\n try {\n console.debug(\n '[stencilB2BJwt] Exchanging customer JWT for B2B storefront token'\n );\n\n const client = new GraphQLClient(B2B_GRAPHQL_URL, {\n credentials: 'same-origin',\n headers: {\n 'content-type': 'application/json',\n accept: 'application/json',\n Authorization: `Bearer ${customerJwt}`\n }\n });\n\n const result = await client.request({\n document: AuthorizationMutation,\n variables: {\n authData: {\n bcToken: customerJwt,\n channelId\n }\n }\n });\n\n const userAuthorization = readFragment(\n UserAuthorizationFragment,\n result.authorization\n );\n const token = userAuthorization?.result?.token;\n\n if (!token) {\n return null;\n }\n\n console.debug('[stencilB2BJwt] Received B2B storefront token');\n return token;\n } catch {\n return null;\n }\n}\n","import { STORAGE_KEY, STORAGE_VERSION } from '../constants.js';\nimport type { TakeShapeConfig } from '../contexts/takeshape-config-context.js';\nimport type { B2BClient } from '../lib/bigcommerce/b2b/client.js';\nimport type {\n BigCommerceClient,\n MockBigCommerceClient\n} from '../lib/bigcommerce/index.js';\nimport type {\n Cart,\n CustomerAddress,\n CustomerInfo\n} from '../lib/bigcommerce/storefront/types.js';\nimport { usePurchaseOrderStore } from './purchase-order-store.js';\n\n/**\n * Dependencies required for session validation.\n */\nexport interface ValidationDependencies {\n storefrontClient: BigCommerceClient | MockBigCommerceClient;\n b2bClient: B2BClient;\n takeShapeConfig: TakeShapeConfig;\n}\n\ninterface ValidationResult {\n valid: boolean;\n error?: string;\n}\n\n/**\n * The full persisted state structure from localStorage.\n * This matches what the persist middleware saves via partialize.\n */\nexport interface PersistedState {\n customerEntityId: number | null;\n chat: {\n messages: unknown[];\n input: string;\n threadId: string | null;\n };\n cartifact: {\n cartEntityId: string | null;\n poItemPrices: Record<string, unknown>;\n orderId: string | null;\n buyerInfo: unknown | null;\n shipToAddress: unknown | null;\n billingAddress: unknown | null;\n poMetadataSet: boolean;\n itemWarnings: unknown[];\n };\n parser: {\n uploadedFileName: string | null;\n parsedContent: string | null;\n hasProcessedDocument: boolean;\n };\n appState: 'upload' | 'processing' | 'chatting';\n userSettings: {\n panelWidth: number;\n };\n}\n\ninterface LoadSessionResult {\n /** Whether the data is valid (correct version) or absent */\n valid: boolean;\n /** Error message if version validation failed */\n error?: string;\n /** Full persisted state if valid and present, null if no session or invalid */\n data: PersistedState | null;\n /** Quick access to IDs for validation */\n threadId: string | null;\n cartEntityId: string | null;\n}\n\n/**\n * Load and validate persisted session data from localStorage.\n * Returns the full persisted state if valid, or null if no session exists.\n * Returns an error if the data exists but has an invalid version.\n */\nfunction loadPersistedSession(): LoadSessionResult {\n try {\n const raw = localStorage.getItem(STORAGE_KEY);\n if (!raw) {\n // No stored data - fresh session\n return { valid: true, data: null, threadId: null, cartEntityId: null };\n }\n\n const parsed = JSON.parse(raw);\n const storedVersion = parsed?.version;\n\n // Version validation\n if (storedVersion === undefined) {\n return {\n valid: false,\n error: 'Session data format is outdated.',\n data: null,\n threadId: null,\n cartEntityId: null\n };\n }\n\n if (storedVersion !== STORAGE_VERSION) {\n return {\n valid: false,\n error:\n 'The app version has changed. Your previous session is not compatible.',\n data: null,\n threadId: null,\n cartEntityId: null\n };\n }\n\n // Extract the full persisted state\n const state = parsed?.state as PersistedState | undefined;\n const threadId = state?.chat?.threadId ?? null;\n const cartEntityId = state?.cartifact?.cartEntityId ?? null;\n const appState = state?.appState ?? 'upload';\n\n // Only restore sessions that finished processing\n if (appState === 'upload' || appState === 'processing') {\n return { valid: true, data: null, threadId: null, cartEntityId: null };\n }\n\n return {\n valid: true,\n data: state ?? null,\n threadId,\n cartEntityId\n };\n } catch (error) {\n console.error('Failed to load persisted session:', error);\n return {\n valid: false,\n error: 'Unable to read session data.',\n data: null,\n threadId: null,\n cartEntityId: null\n };\n }\n}\n\n/**\n * Clear the persisted session from localStorage.\n * Call this when a session ends (e.g., checkout completed).\n */\nexport function clearPersistedSession(): void {\n try {\n localStorage.removeItem(STORAGE_KEY);\n } catch (error) {\n console.error('Failed to clear persisted session:', error);\n }\n}\n\n/**\n * Validate that the persisted customer matches the currently logged-in customer.\n * Allows restoring anonymous sessions (no persisted customer ID and no current customer).\n * Takes the fetched customerInfo as input rather than fetching it internally.\n */\nfunction validateCustomer(\n persistedCustomerEntityId: number | null,\n customerInfo: unknown | null\n): ValidationResult {\n // Case 1: Anonymous to anonymous - valid (restoring anonymous session)\n if (!persistedCustomerEntityId && !customerInfo) {\n return { valid: true };\n }\n\n // Case 2: Logged-in to anonymous - invalid (user logged out)\n if (persistedCustomerEntityId && !customerInfo) {\n return {\n valid: false,\n error: 'Your previous session was reset because you signed out.'\n };\n }\n\n // Case 3: Anonymous to logged-in - invalid (user logged in)\n if (!persistedCustomerEntityId && customerInfo) {\n return {\n valid: false,\n error: 'Your previous session was reset because you signed in.'\n };\n }\n\n // Case 4: Logged-in to logged-in with different ID - invalid (different user)\n if (\n persistedCustomerEntityId &&\n customerInfo &&\n (customerInfo as { entityId: number }).entityId !==\n persistedCustomerEntityId\n ) {\n return {\n valid: false,\n error:\n 'Your previous session was reset because you signed in as a different user.'\n };\n }\n\n // Case 5: Logged-in to logged-in with same ID - valid\n return { valid: true };\n}\n\n/**\n * Validate that a thread exists on TakeShape.\n * NOTE: Thread validation is not yet available via the TakeShape API.\n * For now, we skip thread validation and rely on error handling during message sending.\n */\nasync function validateThread(\n _threadId: string,\n _config: TakeShapeConfig\n): Promise<ValidationResult> {\n // Skip thread validation - not available yet\n // Thread errors will be handled during message send attempts\n return { valid: true };\n}\n\n/**\n * Validate that a cart exists and has the expected structure.\n * Takes the fetched cart as input rather than fetching it internally.\n */\nfunction validateCart(cart: unknown | null): ValidationResult {\n if (cart) {\n return { valid: true };\n }\n return {\n valid: false,\n error: 'The cart from your previous session is no longer available.'\n };\n}\n\n/**\n * Validate persisted session and initialize the store.\n *\n * This function:\n * 1. Loads persisted data from localStorage and validates the version\n * 2. If no data or invalid version → starts fresh (no rehydration)\n * 3. If valid data → validates thread/cart still exist remotely\n * 4. If remote validation passes → rehydrates the store with persisted data\n * 5. If remote validation fails → clears localStorage and starts fresh\n */\nexport async function validateAndInit(\n deps: ValidationDependencies\n): Promise<void> {\n const store = usePurchaseOrderStore.getState();\n\n // Already initialized or in progress\n if (store.ui.initStatus !== 'pending') {\n return;\n }\n\n // Load and validate persisted data\n const loadResult = loadPersistedSession();\n\n // Version validation failed - clear storage and start fresh\n if (!loadResult.valid) {\n clearPersistedSession();\n store.failValidation(loadResult.error ?? 'Session validation failed');\n return;\n }\n\n // Fetch customer addresses and info (always, for all valid paths)\n let fetchedAddresses: CustomerAddress[] = [];\n let fetchedCustomerInfo: CustomerInfo | null = null;\n try {\n const result = await deps.storefrontClient.getCustomerAddresses();\n\n fetchedCustomerInfo = result.customerInfo;\n fetchedAddresses = result.addresses;\n\n // Wait for B2B client initialization to complete\n await deps.b2bClient.initPromise;\n\n if (deps.b2bClient.isAvailable) {\n console.debug('[BigCommerceClient] Fetching B2B company addresses');\n const companyAddresses = await deps.b2bClient.getCompanyAddresses();\n if (companyAddresses.length > 0) {\n fetchedAddresses = [...companyAddresses];\n }\n }\n } catch (error) {\n console.error('Failed to fetch customer addresses:', error);\n if (loadResult.data) {\n // Persisted session: fail hard since we need to validate customer identity\n clearPersistedSession();\n store.failValidation('Unable to verify customer identity.');\n return;\n }\n // Fresh start: soft failure - continue without addresses\n }\n\n // No persisted session data - start fresh\n if (!loadResult.data) {\n // Restore user settings even when session data is not restored\n store.restoreUserSettings();\n\n if (fetchedCustomerInfo) {\n store.setCustomerInfo(fetchedCustomerInfo);\n }\n if (fetchedAddresses.length > 0) {\n store.setCustomerAddresses(fetchedAddresses);\n }\n\n // Check for an orphan cart (existing cart with no associated session)\n try {\n const orphanCart = await deps.storefrontClient.getCart();\n if (orphanCart) {\n store.setExistingCart(orphanCart);\n return;\n }\n } catch (error) {\n console.error('Failed to check for existing cart:', error);\n store.failValidation(\n 'Unable to check for an existing cart. Please try again.'\n );\n return;\n }\n\n store.completeValidation();\n return;\n }\n\n const { threadId, cartEntityId, data: persistedData } = loadResult;\n\n // Fetch cart first if we have a cartEntityId (before validation)\n let fetchedCart: Cart | null = null;\n if (cartEntityId) {\n try {\n fetchedCart = await deps.storefrontClient.getCart(cartEntityId);\n } catch (error) {\n console.error('Failed to fetch cart:', error);\n clearPersistedSession();\n store.failValidation('Unable to restore previous cart.');\n return;\n }\n }\n\n // Validate remote resources in parallel (don't update store yet to avoid overwriting localStorage)\n const validationPromises: Promise<ValidationResult>[] = [];\n\n // Always validate customer if we have persisted data\n validationPromises.push(\n Promise.resolve(\n validateCustomer(\n persistedData.customerEntityId ?? null,\n fetchedCustomerInfo\n )\n )\n );\n\n if (threadId) {\n validationPromises.push(validateThread(threadId, deps.takeShapeConfig));\n }\n if (cartEntityId) {\n validationPromises.push(Promise.resolve(validateCart(fetchedCart)));\n }\n\n const results = await Promise.all(validationPromises);\n\n // Check for any validation failures\n const failedResult = results.find((r) => !r.valid);\n if (failedResult) {\n clearPersistedSession();\n store.failValidation(failedResult.error ?? 'Session validation failed');\n return;\n }\n\n // All validations passed - restore state directly from the data we already read\n // (bypassing rehydrate() which would read from localStorage that may have been overwritten)\n if (persistedData) {\n store.restoreSession(persistedData);\n }\n\n // If we fetched a cart, store it in the cartifact slice for immediate display\n if (fetchedCart) {\n store.setBcCart(fetchedCart);\n }\n\n // Store fetched customer addresses and info (always from BC session, never from localStorage)\n if (fetchedCustomerInfo) {\n store.setCustomerInfo(fetchedCustomerInfo);\n }\n if (fetchedAddresses.length > 0) {\n store.setCustomerAddresses(fetchedAddresses);\n }\n\n store.completeValidation();\n}\n","import { isToolUIPart, type UIMessage } from 'ai';\n\n/**\n * Extract tool part types from the SDK's union type.\n */\ntype ToolPart = Extract<\n UIMessage['parts'][number],\n { type: `tool-${string}` } | { type: 'dynamic-tool' }\n>;\n\n/**\n * Type representing a tool UI part that has completed with output available.\n * Derived from the SDK's types to ensure assignability.\n */\nexport type CompletedToolPart = ToolPart & {\n state: 'output-available';\n toolCallId: string;\n output: unknown;\n};\n\n/**\n * Type predicate that checks if a message part is a completed tool part with output available.\n */\nfunction isCompletedToolPart(\n part: UIMessage['parts'][number]\n): part is CompletedToolPart {\n return (\n isToolUIPart(part) &&\n 'toolCallId' in part &&\n typeof part.toolCallId === 'string' &&\n 'output' in part &&\n part.output !== undefined &&\n 'state' in part &&\n part.state === 'output-available'\n );\n}\n\n/**\n * Extracts completed tool parts from a message's parts array.\n * Returns properly typed CompletedToolPart[] for type-safe access to toolCallId, input, output.\n */\nexport function getCompletedToolParts(\n parts: UIMessage['parts'] | undefined\n): CompletedToolPart[] {\n if (!parts) return [];\n return parts.filter(isCompletedToolPart);\n}\n\n/**\n * Extracts the tool name from a completed tool part.\n * For static tools (type: \"tool-{name}\"), extracts the name portion.\n * For dynamic tools, returns the toolName property.\n */\nexport function getToolNameFromPart(part: CompletedToolPart): string {\n if (part.type === 'dynamic-tool') {\n return part.toolName ?? 'unknown';\n }\n // Static tool: type is \"tool-{name}\"\n return part.type.slice(5);\n}\n","'use client';\n\nimport { useChat } from '@ai-sdk/react';\nimport { QueryClient, QueryClientProvider } from '@tanstack/react-query';\nimport { DefaultChatTransport } from 'ai';\nimport {\n type ChangeEvent,\n type FormEvent,\n useCallback,\n useEffect,\n useRef\n} from 'react';\nimport type { ChatPanelRef } from './components/chat-view/chat-panel/chat-panel.js';\nimport { ExpandedChatView } from './components/chat-view/expanded-chat-view.js';\nimport { ChatView } from './components/chat-view/index.js';\nimport { ExistingCartPrompt } from './components/existing-cart-prompt.js';\nimport { FatalError } from './components/fatal-error.js';\nimport { SpinnerIcon } from './components/icons/spinner-icon.js';\nimport { Uploader } from './components/uploader/index.js';\nimport {\n CLIENT_TOOL_RESPONSE_MESSAGE,\n DEFAULT_AGENT_NAME\n} from './constants.js';\nimport { BigCommerceClientProvider } from './contexts/bigcommerce-client-context.js';\nimport { useTakeShapeConfig } from './contexts/takeshape-config-context.js';\nimport { useBigCommerceCart } from './hooks/use-bigcommerce-cart.js';\nimport { useCartHandlers } from './hooks/use-cart-handlers.js';\nimport { useChatOrchestration } from './hooks/use-chat-orchestration.js';\nimport { useDocumentParser } from './hooks/use-document-parser.js';\nimport { useProcessingState } from './hooks/use-processing-state.js';\nimport { useTakeShapeThread } from './hooks/use-takeshape-thread.js';\nimport { useToolCallHandlers } from './hooks/use-tool-call-handlers.js';\nimport { createB2BClient } from './lib/bigcommerce/b2b/client.js';\nimport { startInactiveSpan } from './lib/tracing.js';\nimport { useChatDisplayStore } from './stores/chat-display-store.js';\nimport { usePurchaseOrderStore } from './stores/purchase-order-store.js';\nimport { validateAndInit } from './stores/session-validation.js';\nimport { useToolCallStore } from './stores/tool-call-store.js';\nimport type { PurchaseOrderChatProps } from './types.js';\nimport {\n getCompletedToolParts,\n getToolNameFromPart\n} from './utils/ai-sdk-helpers.js';\n\nconst queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n staleTime: 5 * 60 * 1000 // 5 minutes\n }\n }\n});\n\nexport function PurchaseOrderChat(props: PurchaseOrderChatProps) {\n // Always render providers so initializer has access to contexts\n return (\n <QueryClientProvider client={queryClient}>\n <BigCommerceClientProvider client={props.bigcommerce.client}>\n <PurchaseOrderChatInitializer {...props} />\n </BigCommerceClientProvider>\n </QueryClientProvider>\n );\n}\n\n/**\n * Handles session validation before rendering the main app.\n * Validates persisted thread/cart exist, then renders PurchaseOrderChatInner.\n */\nfunction PurchaseOrderChatInitializer(props: PurchaseOrderChatProps) {\n const takeShapeConfig = useTakeShapeConfig();\n const initStatus = usePurchaseOrderStore((state) => state.ui.initStatus);\n const initError = usePurchaseOrderStore((state) => state.ui.initError);\n const fatalError = usePurchaseOrderStore((state) => state.fatalError);\n const clearInitError = usePurchaseOrderStore((state) => state.clearInitError);\n\n // Run validation when pending (on mount, or after error dismissal)\n useEffect(() => {\n if (initStatus === 'pending') {\n validateAndInit({\n storefrontClient: props.bigcommerce.client,\n b2bClient: createB2BClient({\n channelId: props.bigcommerce.client.channelId,\n getB2BJwt: props.bigcommerce.getB2BJwt\n }),\n takeShapeConfig\n });\n }\n }, [initStatus, props.bigcommerce, takeShapeConfig]);\n\n // Show fatal error immediately, regardless of init status\n if (fatalError) {\n return (\n <div\n className={`flex h-full items-center justify-center ${props.className ?? ''}`}\n >\n <FatalError message={fatalError} />\n </div>\n );\n }\n\n // Show loading while pending\n if (initStatus === 'pending') {\n return (\n <div\n className={`flex h-full items-center justify-center ${props.className ?? ''}`}\n >\n <div className=\"flex items-center\">\n <SpinnerIcon size={16} />\n </div>\n </div>\n );\n }\n\n // Show existing cart prompt if orphan cart detected\n if (initStatus === 'existing-cart') {\n return (\n <div\n className={`flex h-full items-center justify-center ${props.className ?? ''}`}\n >\n <ExistingCartPrompt />\n </div>\n );\n }\n\n // Show error screen if validation failed\n if (initError) {\n return (\n <div\n className={`flex h-full flex-col items-center justify-center gap-4 ${props.className ?? ''}`}\n >\n <div className=\"text-center\">\n <p className=\"text-gray-600\">{initError}</p>\n </div>\n <button\n type=\"button\"\n onClick={clearInitError}\n className=\"rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2\"\n >\n Start New Session\n </button>\n </div>\n );\n }\n\n return <PurchaseOrderChatInner {...props} />;\n}\n\nfunction PurchaseOrderChatInner({\n className = '',\n agentName = DEFAULT_AGENT_NAME,\n inputName = DEFAULT_AGENT_NAME,\n bigcommerce,\n expandOnReady\n}: PurchaseOrderChatProps) {\n const { sseOrigin, projectId, apiKey } = useTakeShapeConfig();\n\n // Get persisted state from store (guaranteed valid - parent checks isInitializing)\n const persistedThreadId = usePurchaseOrderStore(\n (state) => state.chat.threadId\n );\n const input = usePurchaseOrderStore((state) => state.chat.input);\n const persistedMessages = usePurchaseOrderStore(\n (state) => state.chat.messages\n );\n\n const {\n thread,\n isCreating: isCreatingThread,\n createThread\n } = useTakeShapeThread({\n agentName,\n createOnMount: !persistedThreadId, // Only create if no existing thread\n existingThreadId: persistedThreadId\n });\n\n const setToolCalls = useToolCallStore((state) => state.setToolCalls);\n\n const appState = usePurchaseOrderStore((state) => state.appState);\n const setAppState = usePurchaseOrderStore((state) => state.setAppState);\n const chatPanelRef = useRef<ChatPanelRef | null>(null);\n const agentTurnSpanRef = useRef<ReturnType<typeof startInactiveSpan> | null>(\n null\n );\n const sessionSpanRef = useRef<ReturnType<typeof startInactiveSpan> | null>(\n null\n );\n\n const isExpanded = useChatDisplayStore((state) => state.isExpanded);\n const setExpanded = useChatDisplayStore((state) => state.setExpanded);\n const resetChatDisplay = useChatDisplayStore((state) => state.reset);\n\n // Document parser\n const parser = useDocumentParser();\n\n const bcCart = useBigCommerceCart({\n client: bigcommerce.client,\n onError: (err) => console.error('BigCommerce error:', err)\n });\n\n // Get cart state from Zustand store (persisted)\n const orderId = usePurchaseOrderStore((state) => state.cartifact.orderId);\n const buyerInfo = usePurchaseOrderStore((state) => state.cartifact.buyerInfo);\n const shipToAddress = usePurchaseOrderStore(\n (state) => state.cartifact.shipToAddress\n );\n const billingAddress = usePurchaseOrderStore(\n (state) => state.cartifact.billingAddress\n );\n const poMetadataSet = usePurchaseOrderStore(\n (state) => state.cartifact.poMetadataSet\n );\n const itemWarnings = usePurchaseOrderStore(\n (state) => state.cartifact.itemWarnings\n );\n\n // Get cart actions from Zustand store\n const clearCartifact = usePurchaseOrderStore((state) => state.clearCartifact);\n const clearBcSession = usePurchaseOrderStore((state) => state.clearBcSession);\n const clearAddressSelections = usePurchaseOrderStore(\n (state) => state.clearAddressSelections\n );\n const clearChat = usePurchaseOrderStore((state) => state.clearChat);\n\n // Keep these from bcCart hook - they're API-related state\n const { cartItems } = bcCart;\n\n // Tool call handlers\n const { onToolCall, pendingToolOutputsRef } = useToolCallHandlers({\n bcCart\n });\n\n // Tracks toolCallIds of completed async tool outputs, so prepareSendMessagesRequest\n // can filter the assistant message to only include those specific tool results\n const completedToolCallIdsRef = useRef<Set<string>>(new Set());\n\n const { messages, sendMessage, status, error, setMessages, addToolOutput } =\n useChat({\n transport: new DefaultChatTransport({\n api: `${sseOrigin}/project/${projectId}/agents/messages`,\n headers: {\n Authorization: `Bearer ${apiKey}`\n },\n prepareSendMessagesRequest: async (options) => {\n const lastMessage = options.messages[options.messages.length - 1];\n if (!lastMessage) {\n throw new Error('No messages to send');\n }\n\n // When sending a user message, check if the previous message is an assistant\n // message with completed yield tools - if so, include it so the server can\n // extract the tool results and merge them into the conversation history.\n let messagesToSend = [lastMessage];\n if (lastMessage.role === 'user' && options.messages.length >= 2) {\n const prevMessage = options.messages[options.messages.length - 2];\n const ids = completedToolCallIdsRef.current;\n\n if (prevMessage?.role === 'assistant' && ids.size > 0) {\n // Only include tool parts for client-side async tools (yield tools).\n // Server-side tools already have their results in the session history.\n const allCompletedParts = getCompletedToolParts(\n prevMessage.parts\n );\n const completedParts = allCompletedParts.filter((p) =>\n ids.has(p.toolCallId)\n );\n\n ids.clear();\n\n if (completedParts.length > 0) {\n const transformedPrevMessage = {\n ...prevMessage,\n parts: completedParts.map((part) => ({\n type: part.type,\n toolName: getToolNameFromPart(part),\n toolCallId: part.toolCallId,\n state: part.state,\n input: part.input,\n output: part.output\n }))\n };\n\n messagesToSend = [transformedPrevMessage, lastMessage];\n }\n }\n }\n\n return {\n body: {\n id: thread.current?.id ?? '',\n messages: messagesToSend,\n trigger: options.trigger,\n messageId: options.messageId,\n metadata: {\n ...(options.requestMetadata as Record<string, unknown>),\n custom: {\n inputName\n }\n }\n }\n };\n }\n }),\n messages: persistedMessages,\n onToolCall,\n onError: (err) => {\n console.error('[useChat onError]', err);\n agentTurnSpanRef.current?.setStatus({\n code: 2,\n message: 'internal_error'\n });\n agentTurnSpanRef.current?.end();\n agentTurnSpanRef.current = null;\n }\n });\n\n const tracedSendMessage = useCallback(\n (params: { text: string }) => {\n agentTurnSpanRef.current?.end();\n agentTurnSpanRef.current = startInactiveSpan({\n name: 'po-agent-turn',\n op: 'ai.agent',\n attributes: {\n 'agent.name': inputName\n }\n });\n sendMessage(params);\n },\n [sendMessage, inputName]\n );\n\n // End agent turn span when status returns to ready\n useEffect(() => {\n if (status === 'ready' && agentTurnSpanRef.current) {\n agentTurnSpanRef.current.setStatus({ code: 1, message: 'ok' });\n agentTurnSpanRef.current.end();\n agentTurnSpanRef.current = null;\n }\n }, [status]);\n\n // Clean up open spans on unmount\n useEffect(() => {\n return () => {\n agentTurnSpanRef.current?.end();\n sessionSpanRef.current?.end();\n };\n }, []);\n\n // When streaming completes and there are pending async tool outputs,\n // provide the outputs and send a follow-up message to trigger server continuation.\n // TODO: Investigate if the AI SDK provides a way to trigger server continuation\n // without injecting a synthetic user message (e.g., resumeStream, or if addToolOutput\n // alone can trigger a new server request).\n useEffect(() => {\n if (status === 'ready' && pendingToolOutputsRef.current.length > 0) {\n const pendingOutputs = [...pendingToolOutputsRef.current];\n pendingToolOutputsRef.current = [];\n\n void (async () => {\n for (const pending of pendingOutputs) {\n completedToolCallIdsRef.current.add(pending.toolCallId);\n await addToolOutput(pending);\n }\n tracedSendMessage({ text: CLIENT_TOOL_RESPONSE_MESSAGE });\n })();\n }\n }, [status, pendingToolOutputsRef, addToolOutput, tracedSendMessage]);\n\n // Sync messages to store for persistence\n useEffect(() => {\n usePurchaseOrderStore.getState().setMessages(messages);\n }, [messages]);\n\n // Sync tool calls to store for display during processing\n useEffect(() => {\n setToolCalls(messages);\n }, [messages, setToolCalls]);\n\n // Auto-expand when transitioning to chatting state\n useEffect(() => {\n if (expandOnReady && appState === 'chatting') {\n setExpanded(true);\n }\n }, [expandOnReady, appState, setExpanded]);\n\n const isLoading =\n isCreatingThread || status === 'submitted' || status === 'streaming';\n\n const processingState = useProcessingState(\n messages,\n appState,\n status,\n parser.parsedContent\n );\n\n const sendMessageAndScroll = useCallback(\n (params: { text: string }) => {\n tracedSendMessage(params);\n requestAnimationFrame(() => {\n chatPanelRef.current?.scrollToBottom();\n });\n },\n [tracedSendMessage]\n );\n\n // Chat orchestration - handles parser→agent flow and UI state transitions.\n // Uses tracedSendMessage (not sendMessageAndScroll); orchestration is system-initiated\n // (not user-initiated) and manages its own scrollToBottom after processing completes.\n const orchestration = useChatOrchestration({\n appState,\n setAppState,\n parser,\n sendMessage: tracedSendMessage,\n processingState,\n chatPanelRef\n });\n\n // Cart handlers\n const cartHandlers = useCartHandlers({\n bcCart,\n cartItems,\n sendMessage: sendMessageAndScroll,\n onCheckoutInitiated: (error?: Error) => {\n if (error) {\n sessionSpanRef.current?.setStatus({ code: 2, message: error.message });\n } else {\n sessionSpanRef.current?.setStatus({ code: 1, message: 'ok' });\n }\n sessionSpanRef.current?.end();\n sessionSpanRef.current = null;\n },\n onCheckout: bigcommerce.onCheckout\n });\n\n const handleInputChange = (e: ChangeEvent<HTMLTextAreaElement>) => {\n usePurchaseOrderStore.getState().setInput(e.target.value);\n };\n\n const handleSubmit = (e: FormEvent<HTMLFormElement>) => {\n e.preventDefault();\n if (input.trim()) {\n sendMessageAndScroll({ text: input });\n usePurchaseOrderStore.getState().setInput('');\n }\n };\n\n const handleFileUpload = async (file: File) => {\n sessionSpanRef.current?.end();\n sessionSpanRef.current = startInactiveSpan({\n name: 'upload-to-checkout',\n op: 'purchase-order.session',\n attributes: {\n 'file.name': file.name\n }\n });\n setAppState('processing');\n orchestration.reset();\n const ok = await parser.handleFileUpload(file);\n if (ok === false) {\n setAppState('upload');\n }\n };\n\n const handleViewProduct = useCallback(\n (item: {\n productEntityId?: number;\n sku: string;\n name: string;\n path?: string;\n }) => {\n if (bigcommerce.onViewProduct) {\n bigcommerce.onViewProduct({\n productEntityId: item.productEntityId,\n sku: item.sku,\n name: item.name,\n path: item.path\n });\n }\n },\n [bigcommerce.onViewProduct]\n );\n\n const handleRetry = useCallback(() => {\n const lastUserMessage = [...messages]\n .reverse()\n .find((m) => m.role === 'user');\n if (!lastUserMessage) return;\n\n // Extract text from message parts\n const text = lastUserMessage.parts\n ?.filter(\n (part): part is { type: 'text'; text: string } => part.type === 'text'\n )\n .map((part) => part.text)\n .join('\\n');\n if (!text) return;\n\n // Remove the last user message and any failed response after it\n const lastUserIndex = messages.lastIndexOf(lastUserMessage);\n setMessages(messages.slice(0, lastUserIndex));\n\n // Resend the last user message\n sendMessageAndScroll({ text });\n }, [messages, setMessages, sendMessageAndScroll]);\n\n const handleSkip = useCallback(() => {\n setAppState('chatting');\n }, [setAppState]);\n\n const resetToolCalls = useToolCallStore((state) => state.reset);\n\n const handleStartOver = useCallback(async () => {\n sessionSpanRef.current?.setStatus({ code: 2, message: 'cancelled' });\n sessionSpanRef.current?.end();\n sessionSpanRef.current = null;\n\n // Clear BigCommerce cart via API\n await bcCart.clearCart();\n\n // Clear Zustand store state\n clearCartifact();\n clearBcSession();\n clearAddressSelections();\n\n // Clear chat state in Zustand store (messages, input, threadId)\n // Also clear useChat's internal state to stay in sync\n clearChat();\n setMessages([]);\n resetToolCalls();\n resetChatDisplay();\n parser.reset();\n orchestration.reset();\n\n setAppState('upload');\n\n createThread();\n }, [\n bcCart.clearCart,\n clearCartifact,\n clearBcSession,\n clearAddressSelections,\n clearChat,\n setMessages,\n resetToolCalls,\n resetChatDisplay,\n parser.reset,\n orchestration.reset,\n createThread,\n setAppState\n ]);\n\n // Upload step - shown before chat/cart, and during processing\n if (appState === 'upload' || appState === 'processing') {\n return (\n <div className={`flex h-full ${className}`}>\n <Uploader\n onFileUpload={handleFileUpload}\n onSkip={handleSkip}\n onClearError={parser.handleClearError}\n currentStep={processingState.currentStep}\n cartItems={cartItems}\n orderId={orderId}\n parsedContent={parser.parsedContent}\n isUploading={parser.isUploadingFile}\n parserError={parser.parserError}\n />\n </div>\n );\n }\n\n const chatViewProps = {\n className,\n messages,\n input,\n onInputChange: handleInputChange,\n onSubmit: handleSubmit,\n isLoading,\n error,\n onRetry: error ? handleRetry : undefined,\n hasProcessedDocument: orchestration.hasProcessedDocument,\n uploadedFileName: parser.uploadedFileName,\n chatPanelRef,\n onFileUpload: handleFileUpload,\n cartItems,\n itemWarnings,\n onUpdateQuantity: cartHandlers.handleUpdateQuantity,\n onRemove: cartHandlers.handleRemoveItem,\n onCheckout: cartHandlers.handleCheckout,\n onSuggestAlternatives: cartHandlers.handleSuggestAlternatives,\n onShowMoreLikeThis: cartHandlers.handleShowMoreLikeThis,\n onViewProduct: bigcommerce.onViewProduct ? handleViewProduct : undefined,\n onAddToCart: cartHandlers.handleAddToCartFromSuggestion,\n orderId,\n buyerInfo,\n customerInfo: bcCart.customerInfo ?? undefined,\n addresses: bcCart.customerAddresses,\n selectedAddressId: bcCart.selectedAddressId ?? undefined,\n addressUpdateStatus: bcCart.addressUpdateStatus,\n onAddressChange: bcCart.setShippingAddressOnCheckout,\n selectedBillingAddressId: bcCart.selectedBillingAddressId ?? undefined,\n billingAddressUpdateStatus: bcCart.billingAddressUpdateStatus,\n onBillingAddressChange: bcCart.setBillingAddressOnCheckout,\n shipToAddress,\n billingAddress: billingAddress ?? undefined,\n checkoutTotals: bcCart.checkoutTotals,\n isCartLoading: bcCart.isLoading,\n poMetadataSet,\n onNewOrder: handleStartOver\n };\n\n if (expandOnReady && isExpanded) {\n return (\n <ExpandedChatView>\n <ChatView {...chatViewProps} onMinimize={() => setExpanded(false)} />\n </ExpandedChatView>\n );\n }\n\n return (\n <div className=\"h-full max-w-[1440px] mx-auto\">\n <ChatView\n {...chatViewProps}\n onExpand={expandOnReady ? () => setExpanded(true) : undefined}\n />\n </div>\n );\n}\n","import type { ResultOf, TadaDocumentNode } from 'gql.tada';\nimport type { Variables } from 'graphql-request';\nimport type { TadaRequestOptions } from '../types.js';\nimport type { PageInfo } from './types.js';\n\ninterface Connection<TNode> {\n edges: Array<{ node: TNode }> | null;\n pageInfo: PageInfo;\n}\n\nexport interface GraphQLRequestClient {\n request<R, V extends Variables | undefined = Variables>(\n options: TadaRequestOptions<R, V>\n ): Promise<ResultOf<TadaDocumentNode<R, V>>>;\n}\n\nexport const MAX_PAGES = 20; // Safety limit: 50 items/page * 20 = 1,000 items max\n\nexport async function fetchAllPages<R, V extends Variables | undefined, TNode>(\n client: GraphQLRequestClient,\n document: TadaRequestOptions<R, V>['document'],\n baseVariables: Record<string, unknown>,\n getConnection: (result: R) => Connection<TNode> | null\n): Promise<Array<{ node: TNode }>> {\n const allEdges: Array<{ node: TNode }> = [];\n let after: string | null | undefined;\n let pages = 0;\n\n while (pages < MAX_PAGES) {\n const variables =\n after !== undefined ? { ...baseVariables, after } : { ...baseVariables };\n\n const result = await client.request({\n document,\n variables: variables as V\n });\n\n const connection = getConnection(result);\n if (!connection) {\n break;\n }\n\n allEdges.push(...(connection.edges ?? []));\n pages++;\n\n if (!connection.pageInfo.hasNextPage || !connection.pageInfo.endCursor) {\n break;\n }\n\n after = connection.pageInfo.endCursor;\n }\n\n return allEdges;\n}\n","// BigCommerce GraphQL Storefront API Client\n\nimport type { FragmentOf, ResultOf, TadaDocumentNode } from 'gql.tada';\nimport { ClientError, GraphQLClient, type Variables } from 'graphql-request';\nimport type { TadaRequestOptions } from '../types.js';\nimport { convertCustomerAddressToCustomerAddress } from '../utils.js';\nimport { readFragment } from './graphql.js';\nimport { fetchAllPages } from './pagination.js';\nimport {\n AddCartLineItemsMutation,\n AddCheckoutBillingAddressMutation,\n AddCheckoutShippingConsignmentsMutation,\n CartFragment,\n CheckoutFragment,\n CreateCartMetafieldMutation,\n CreateCartMutation,\n CreateCartRedirectUrlsMutation,\n DeleteCartLineItemMutation,\n DeleteCartMutation,\n GetCartQuery,\n GetCheckoutQuery,\n GetCustomerAddressesQuery,\n GetProductOptionsPageQuery,\n GetProductOptionValuesPageQuery,\n GetProductPathsQuery,\n GetProductsForDisplayQuery,\n GetProductVariantDetailsQuery,\n GetProductVariantsForDisplayPageQuery,\n GetProductVariantsPageQuery,\n UpdateCartLineItemMutation,\n UpdateCheckoutCustomerMessageMutation\n} from './queries.js';\nimport type {\n BigCommerceConfig,\n CartLineItemInput,\n CartRedirectUrls,\n CheckoutAddress,\n CheckoutConsignmentLineItem,\n CustomerAddress,\n CustomerInfo,\n GetCustomerAddressesResult,\n GetProductOptionValuesPageResult,\n ProductForDisplay,\n ProductVariantDetails\n} from './types.js';\n\ntype QueuedRequest<R, V extends Variables | undefined> = {\n options: TadaRequestOptions<R, V>;\n resolve: (value: R) => void;\n reject: (reason: any) => void;\n};\n\n/**\n * Maximum number of items to add to cart in a single operation\n * This is to avoid BigCommerce API 500 errors when adding too many items at once\n */\nconst CART_BATCH_SIZE = 20;\n\n/**\n * Unmask a CartFragment result and map to domain Cart type.\n * Handles null-vs-undefined differences between tada types and domain types.\n */\nfunction toCart(raw: FragmentOf<typeof CartFragment>) {\n return readFragment(CartFragment, raw);\n}\n\n/**\n * Unmask a CheckoutFragment result and map to domain Checkout type.\n */\nfunction toCheckout(raw: FragmentOf<typeof CheckoutFragment>) {\n return readFragment(CheckoutFragment, raw);\n}\n\n/**\n * Resolve a potentially relative URL to an absolute URL.\n * In browser context, prepends window.location.origin for relative paths.\n */\nfunction resolveEndpoint(endpoint: string): string {\n // Already absolute\n if (endpoint.startsWith('http://') || endpoint.startsWith('https://')) {\n return endpoint;\n }\n\n // Relative URL in browser context\n if (typeof window !== 'undefined' && window.location?.origin) {\n return `${window.location.origin}${endpoint.startsWith('/') ? '' : '/'}${endpoint}`;\n }\n\n // Fallback: return as-is (may fail, but provides clear error)\n return endpoint;\n}\n\nexport class BigCommerceClient {\n private endpoint: string;\n private storefrontToken: string | undefined;\n private graphQLClient: GraphQLClient;\n private isProcessing = false;\n // biome-ignore lint/suspicious/noExplicitAny: Necessary to allow for the tada type inference\n private requestQueue: QueuedRequest<any, any>[] = [];\n\n readonly channelId: number;\n\n constructor(config: BigCommerceConfig) {\n this.endpoint = resolveEndpoint(config.endpoint);\n this.storefrontToken = config.storefrontToken;\n this.channelId = config.channelId ?? 1;\n\n const headers: Record<string, string> = {\n 'content-type': 'application/json',\n accept: 'application/json'\n };\n\n if (this.storefrontToken) {\n headers.authorization = `Bearer ${this.storefrontToken}`;\n }\n\n this.graphQLClient = new GraphQLClient(this.endpoint, {\n credentials: 'same-origin',\n headers\n });\n }\n\n /**\n * Execute a request with retry logic (up to 5 attempts with exponential backoff)\n */\n private async executeWithRetry<const R, V extends Variables | undefined>(\n options: TadaRequestOptions<R, V>,\n attempt = 1\n ): Promise<ResultOf<TadaDocumentNode<R, V>>> {\n const maxAttempts = 5;\n const delays = [1000, 2000, 4000, 8000, 16000]; // 1s, 2s, 4s, 8s, 16s\n\n try {\n const result = await this.graphQLClient.request(options);\n return result;\n } catch (error) {\n // GraphQL business errors (HTTP 200 with errors payload) are not retriable\n if (error instanceof ClientError && error.response.status === 200) {\n throw error;\n }\n\n if (attempt < maxAttempts) {\n const delay = delays[attempt - 1] ?? 16000;\n console.warn(\n `[BigCommerceClient] Request failed, retrying in ${delay / 1000}s (attempt ${attempt}/${maxAttempts})`,\n error\n );\n await new Promise((resolve) => setTimeout(resolve, delay));\n return this.executeWithRetry(options, attempt + 1);\n }\n console.error(\n `[BigCommerceClient] Request failed after ${maxAttempts} attempts:`,\n error\n );\n throw error;\n }\n }\n\n /**\n * Process the next request in the queue\n */\n private processNextInQueue(): void {\n if (this.requestQueue.length === 0) {\n this.isProcessing = false;\n return;\n }\n\n const next = this.requestQueue.shift();\n if (!next) return;\n\n this.executeWithRetry(next.options)\n .then((result) => {\n next.resolve(result);\n this.processNextInQueue();\n })\n .catch((error) => {\n next.reject(error);\n this.processNextInQueue();\n });\n }\n\n async request<const R, V extends Variables | undefined>(\n options: TadaRequestOptions<R, V>\n ) {\n // If already processing a request, queue this one\n if (this.isProcessing) {\n return new Promise<R>((resolve, reject) => {\n this.requestQueue.push({ options, resolve, reject });\n });\n }\n\n // Execute immediately\n this.isProcessing = true;\n try {\n const result = await this.executeWithRetry(options);\n this.processNextInQueue();\n return result;\n } catch (error) {\n this.processNextInQueue();\n throw error;\n }\n }\n\n /**\n * Get an existing cart by ID\n */\n async getCart(cartEntityId?: string) {\n const result = await this.request({\n document: GetCartQuery,\n variables: {\n cartEntityId\n }\n });\n\n const cart = result.site.cart;\n return cart ? toCart(cart) : null;\n }\n\n /**\n * Create a new cart with line items\n * Batches items if more than CART_BATCH_SIZE\n */\n async createCart(lineItems: CartLineItemInput[]) {\n if (lineItems.length === 0) {\n throw new Error('Cannot create cart with no line items');\n }\n\n // Create cart with first batch\n const firstBatch = lineItems.slice(0, CART_BATCH_SIZE);\n const result = await this.request({\n document: CreateCartMutation,\n variables: {\n input: {\n lineItems: firstBatch.map((item) => ({\n productEntityId: item.productEntityId,\n variantEntityId: item.variantEntityId,\n quantity: item.quantity\n }))\n }\n }\n });\n\n const rawCart = result.cart.createCart?.cart;\n let cart = rawCart ? toCart(rawCart) : null;\n\n if (!cart) {\n throw new Error('Failed to create cart');\n }\n\n // Add remaining items in batches with retry logic\n if (lineItems.length > CART_BATCH_SIZE) {\n const remainingItems = lineItems.slice(CART_BATCH_SIZE);\n cart = await this.addCartLineItems(cart.entityId, remainingItems);\n\n if (!cart) {\n throw new Error('Failed to add all items to cart');\n }\n }\n\n return cart;\n }\n\n /**\n * Add a single batch of line items to a cart\n * Returns the updated cart or null if the operation failed\n */\n private async addBatchToCart(\n cartEntityId: string,\n batch: CartLineItemInput[]\n ) {\n const result = await this.request({\n document: AddCartLineItemsMutation,\n variables: {\n input: {\n cartEntityId,\n data: {\n lineItems: batch.map((item) => ({\n productEntityId: item.productEntityId,\n variantEntityId: item.variantEntityId,\n quantity: item.quantity\n }))\n }\n }\n }\n });\n\n const rawCart = result.cart.addCartLineItems?.cart;\n return rawCart ? toCart(rawCart) : null;\n }\n\n /**\n * Add line items to an existing cart\n * Batches items if more than CART_BATCH_SIZE\n */\n async addCartLineItems(cartEntityId: string, lineItems: CartLineItemInput[]) {\n let cart: ResultOf<typeof CartFragment> | null = null;\n\n // Process items in batches\n for (let i = 0; i < lineItems.length; i += CART_BATCH_SIZE) {\n const batch = lineItems.slice(i, i + CART_BATCH_SIZE);\n cart = await this.addBatchToCart(cartEntityId, batch);\n }\n\n return cart;\n }\n\n /**\n * Update the quantity of a cart line item\n */\n async updateCartLineItem(\n cartEntityId: string,\n lineItemEntityId: string,\n quantity: number,\n productEntityId: number,\n variantEntityId?: number\n ) {\n const result = await this.request({\n document: UpdateCartLineItemMutation,\n variables: {\n input: {\n cartEntityId,\n lineItemEntityId,\n data: {\n lineItem: {\n productEntityId,\n variantEntityId,\n quantity\n }\n }\n }\n }\n });\n\n const rawCart = result.cart.updateCartLineItem?.cart;\n return rawCart ? toCart(rawCart) : null;\n }\n\n /**\n * Remove a line item from the cart\n */\n async deleteCartLineItem(cartEntityId: string, lineItemEntityId: string) {\n const result = await this.request({\n document: DeleteCartLineItemMutation,\n variables: {\n input: {\n cartEntityId,\n lineItemEntityId\n }\n }\n });\n\n const rawCart = result.cart.deleteCartLineItem?.cart;\n return rawCart ? toCart(rawCart) : null;\n }\n\n /**\n * Delete an entire cart\n */\n async deleteCart(cartEntityId: string) {\n const result = await this.request({\n document: DeleteCartMutation,\n variables: {\n input: {\n cartEntityId\n }\n }\n });\n\n return result.cart.deleteCart?.deletedCartEntityId ?? null;\n }\n\n /**\n * Create a cart or add to existing cart\n * Convenience method that handles both cases\n */\n async addToCart(lineItems: CartLineItemInput[], existingCartId?: string) {\n if (existingCartId) {\n return this.addCartLineItems(existingCartId, lineItems);\n }\n return this.createCart(lineItems);\n }\n\n /**\n * Create single-use redirect URLs for a cart\n * URLs should be generated just-in-time (within 30s of use)\n */\n async createCartRedirectUrls(\n cartEntityId: string\n ): Promise<CartRedirectUrls | null> {\n const result = await this.request({\n document: CreateCartRedirectUrlsMutation,\n variables: {\n input: {\n cartEntityId\n }\n }\n });\n\n return result.cart.createCartRedirectUrls?.redirectUrls ?? null;\n }\n\n /**\n * Create a metafield on a cart\n */\n async createCartMetafield(\n cartEntityId: string,\n key: string,\n value: string\n ): Promise<void> {\n await this.executeWithRetry({\n document: CreateCartMetafieldMutation,\n variables: {\n input: {\n cartEntityId,\n data: {\n key,\n value\n }\n }\n }\n });\n }\n\n /**\n * Get checkout by entity ID\n * Checkouts are automatically created when a cart is created\n */\n async getCheckout(checkoutEntityId?: string) {\n const result = await this.request({\n document: GetCheckoutQuery,\n variables: {\n checkoutEntityId\n }\n });\n\n const rawCheckout = result.site.checkout;\n return rawCheckout ? toCheckout(rawCheckout) : null;\n }\n\n /**\n * Add shipping consignments (addresses) to a checkout\n * This is required for tax calculation\n */\n async setCheckoutShippingAddress(\n checkoutEntityId: string,\n address: CheckoutAddress,\n lineItems: CheckoutConsignmentLineItem[]\n ) {\n // Add the new consignment with the provided address and line items\n const result = await this.request({\n document: AddCheckoutShippingConsignmentsMutation,\n variables: {\n input: {\n checkoutEntityId,\n data: {\n consignments: [\n {\n address,\n lineItems\n }\n ]\n }\n }\n }\n });\n\n const rawCheckout =\n result.checkout.addCheckoutShippingConsignments?.checkout;\n\n return rawCheckout ? toCheckout(rawCheckout) : null;\n }\n\n /**\n * Add shipping consignments (addresses) to a checkout\n * This is required for tax calculation\n */\n async setCheckoutBillingAddress(\n checkoutEntityId: string,\n address: CheckoutAddress\n ) {\n // Add the new consignment with the provided address and line items\n const result = await this.request({\n document: AddCheckoutBillingAddressMutation,\n variables: {\n input: {\n checkoutEntityId,\n data: {\n address\n }\n }\n }\n });\n\n const rawCheckout = result.checkout.addCheckoutBillingAddress?.checkout;\n\n return rawCheckout ? toCheckout(rawCheckout) : null;\n }\n\n /**\n * Get customer's saved addresses and customer info\n * Requires the customer to be logged in\n * Automatically paginates through all addresses\n */\n async getCustomerAddresses(): Promise<{\n customerInfo: CustomerInfo | null;\n addresses: CustomerAddress[];\n }> {\n const result = await this.request({\n document: GetCustomerAddressesQuery\n });\n\n if (!result.customer) {\n return {\n customerInfo: null,\n addresses: []\n };\n }\n\n const customerInfo: CustomerInfo = {\n entityId: result.customer.entityId,\n firstName: result.customer.firstName,\n lastName: result.customer.lastName,\n email: result.customer.email\n };\n\n const allAddressEdges = [...(result.customer.addresses.edges ?? [])];\n\n if (result.customer.addresses.pageInfo.hasNextPage) {\n const additionalEdges = await fetchAllPages(\n this,\n GetCustomerAddressesQuery,\n { after: result.customer.addresses.pageInfo.endCursor },\n (r: GetCustomerAddressesResult) => r.customer?.addresses ?? null\n );\n allAddressEdges.push(...additionalEdges);\n }\n\n const addresses = allAddressEdges.map((edge, index) =>\n convertCustomerAddressToCustomerAddress(edge.node, index)\n );\n\n return {\n customerInfo,\n addresses\n };\n }\n\n /**\n * Update checkout customer message (order notes)\n * This message will be included with the order\n */\n async updateCheckoutCustomerMessage(\n checkoutEntityId: string,\n options: { purchaseOrderNumber: string | null; threadId: string | null }\n ) {\n let message = '';\n\n if (options.purchaseOrderNumber) {\n message += `PO Number: ${options.purchaseOrderNumber}, `;\n }\n\n if (options.threadId) {\n if (message) {\n message += '\\n';\n }\n message += `Thread ID: ${options.threadId}`;\n }\n\n const result = await this.request({\n document: UpdateCheckoutCustomerMessageMutation,\n variables: {\n input: {\n checkoutEntityId,\n data: {\n message\n }\n }\n }\n });\n\n const rawCheckout = result.checkout.updateCheckoutCustomerMessage?.checkout;\n return rawCheckout ? toCheckout(rawCheckout) : null;\n }\n\n /**\n * Get product variant details for multiple products\n * Returns product options and all variants with their option values\n * Automatically paginates through all variants, options, and option values\n */\n async getProductVariantDetails(\n productEntityIds: number[]\n ): Promise<ProductVariantDetails[]> {\n const result = await this.request({\n document: GetProductVariantDetailsQuery,\n variables: {\n entityIds: productEntityIds\n }\n });\n\n const products: ProductVariantDetails[] = [];\n\n for (const edge of result.site.products.edges ?? []) {\n const product = edge.node;\n\n // Paginate variants\n const allVariantEdges = [...(product.variants.edges ?? [])];\n if (product.variants.pageInfo.hasNextPage) {\n const additionalVariants = await fetchAllPages(\n this,\n GetProductVariantsPageQuery,\n {\n entityId: product.entityId,\n after: product.variants.pageInfo.endCursor\n },\n (r) => r.site.product?.variants ?? null\n );\n allVariantEdges.push(...additionalVariants);\n }\n\n // Paginate productOptions\n const allOptionEdges = [...(product.productOptions.edges ?? [])];\n if (product.productOptions.pageInfo.hasNextPage) {\n const additionalOptions = await fetchAllPages(\n this,\n GetProductOptionsPageQuery,\n {\n entityId: product.entityId,\n after: product.productOptions.pageInfo.endCursor\n },\n (r) => r.site.product?.productOptions ?? null\n );\n allOptionEdges.push(...additionalOptions);\n }\n\n // Paginate option values for each MultipleChoiceOption\n // Accumulate into a separate map to avoid mutating API response objects\n // biome-ignore lint/suspicious/noExplicitAny: option node is a union; we narrow via __typename at runtime\n const paginatedValueEdges = new Map<number, any>();\n for (const optionEdge of allOptionEdges) {\n const node = optionEdge.node as Record<string, any>;\n if (\n node.values?.pageInfo.hasNextPage &&\n node.values.pageInfo.endCursor\n ) {\n const additionalValues = await fetchAllPages(\n this,\n GetProductOptionValuesPageQuery,\n {\n entityId: product.entityId,\n optionEntityId: node.entityId,\n after: node.values.pageInfo.endCursor\n },\n (r: GetProductOptionValuesPageResult) => {\n const edges = r.site.product?.productOptions.edges;\n const firstEdge = edges?.[0];\n if (!firstEdge) return null;\n const firstNode = firstEdge.node as Record<string, any>;\n return firstNode.values ?? null;\n }\n );\n paginatedValueEdges.set(node.entityId, {\n ...node.values,\n edges: [...(node.values.edges ?? []), ...additionalValues]\n });\n }\n }\n\n // Map to ProductVariantDetails (same mapping as before)\n products.push({\n entityId: product.entityId,\n productOptions: allOptionEdges\n .filter((optionEdge) => optionEdge.node.isVariantOption)\n .map((optionEdge) => {\n const node = optionEdge.node as Record<string, any>;\n const values =\n paginatedValueEdges.get(node.entityId) ?? node.values;\n return {\n entityId: node.entityId,\n displayName: node.displayName,\n isRequired: node.isRequired,\n isVariantOption: node.isVariantOption,\n displayStyle: node.displayStyle,\n values:\n values?.edges?.map(\n (valueEdge: {\n node: {\n entityId: number;\n label: string;\n isDefault: boolean;\n };\n }) => ({\n entityId: valueEdge.node.entityId,\n label: valueEdge.node.label,\n isDefault: valueEdge.node.isDefault\n })\n ) ?? []\n };\n }),\n variants: allVariantEdges.map((variantEdge) => ({\n entityId: variantEdge.node.entityId,\n sku: variantEdge.node.sku,\n isPurchasable: variantEdge.node.isPurchasable,\n defaultImage: variantEdge.node.defaultImage ?? undefined,\n prices: variantEdge.node\n .prices as ProductVariantDetails['variants'][number]['prices'],\n inventory: variantEdge.node\n .inventory as ProductVariantDetails['variants'][number]['inventory'],\n options: (variantEdge.node.options.edges ?? []).map((optionEdge) => ({\n entityId: optionEdge.node.entityId,\n displayName: optionEdge.node.displayName,\n values: (optionEdge.node.values.edges ?? []).map((valueEdge) => ({\n entityId: valueEdge.node.entityId,\n label: valueEdge.node.label\n }))\n }))\n }))\n });\n }\n\n return products;\n }\n\n /**\n * Get product paths for building product page URLs\n * Returns a map of productEntityId to path\n */\n async getProductPaths(\n productEntityIds: number[]\n ): Promise<Map<number, string>> {\n const result = await this.request({\n document: GetProductPathsQuery,\n variables: {\n entityIds: productEntityIds\n }\n });\n\n const paths = new Map<number, string>();\n for (const edge of result.site.products.edges ?? []) {\n if (edge.node.path) {\n paths.set(edge.node.entityId, edge.node.path);\n }\n }\n return paths;\n }\n\n /**\n * Get products for display (used by showProducts tool)\n * Returns product names, images, prices, and variant information\n */\n async getProductsForDisplay(\n productEntityIds: number[]\n ): Promise<ProductForDisplay[]> {\n const result = await this.request({\n document: GetProductsForDisplayQuery,\n variables: {\n entityIds: productEntityIds\n }\n });\n\n const products: ProductForDisplay[] = [];\n\n for (const edge of result.site.products.edges ?? []) {\n const product = edge.node;\n\n // Paginate variants if needed\n const allVariantEdges = [...(product.variants.edges ?? [])];\n if (product.variants.pageInfo.hasNextPage) {\n const additionalVariants = await fetchAllPages(\n this,\n GetProductVariantsForDisplayPageQuery,\n {\n entityId: product.entityId,\n after: product.variants.pageInfo.endCursor\n },\n (r) => r.site.product?.variants ?? null\n );\n allVariantEdges.push(...additionalVariants);\n }\n\n products.push({\n entityId: product.entityId,\n name: product.name,\n sku: product.sku,\n path: product.path,\n defaultImage: product.defaultImage ?? undefined,\n variants: allVariantEdges.map((variantEdge) => ({\n entityId: variantEdge.node.entityId,\n sku: variantEdge.node.sku,\n isPurchasable: variantEdge.node.isPurchasable,\n defaultImage: variantEdge.node.defaultImage ?? undefined,\n prices: variantEdge.node\n .prices as ProductForDisplay['variants'][number]['prices'],\n inventory: variantEdge.node\n .inventory as ProductForDisplay['variants'][number]['inventory']\n }))\n });\n }\n\n return products;\n }\n}\n\n/**\n * Construct the BigCommerce GraphQL Storefront API endpoint from a store hash.\n * Use this when you have a store hash (e.g., from Catalyst's BIGCOMMERCE_STORE_HASH).\n *\n * @example\n * const endpoint = createBigCommerceEndpoint('abc123');\n * // Returns: 'https://store-abc123.mybigcommerce.com/graphql'\n */\nexport function createBigCommerceEndpoint(storeHash: string): string {\n return `https://store-${storeHash}.mybigcommerce.com/graphql`;\n}\n\n/**\n * Create a BigCommerce client instance\n */\nexport function createBigCommerceClient(\n config: BigCommerceConfig\n): BigCommerceClient {\n return new BigCommerceClient(config);\n}\n","'use client';\n\nimport { useMemo } from 'react';\nimport { DEFAULT_AGENT_NAME } from './constants.js';\nimport { TakeShapeConfigProvider } from './contexts/takeshape-config-context.js';\nimport { createBigCommerceClient } from './lib/bigcommerce/storefront/client.js';\nimport { PurchaseOrderChat } from './purchase-order-chat.js';\nimport type { PurchaseOrderChatWidgetProps } from './types.js';\n\n/**\n * Simplified PurchaseOrderChatWidget component that handles all configuration internally.\n * This is the recommended way to integrate the component in most applications.\n *\n * For advanced use cases requiring custom provider setup, use PurchaseOrderChat\n * with TakeShapeConfigProvider directly.\n */\nexport function PurchaseOrderChatWidget({\n takeshape,\n bigcommerce,\n agentName = DEFAULT_AGENT_NAME,\n inputName = DEFAULT_AGENT_NAME,\n onViewProduct,\n onCheckout,\n className,\n expandOnReady\n}: PurchaseOrderChatWidgetProps) {\n const bigCommerceClient = useMemo(\n () =>\n createBigCommerceClient({\n endpoint: bigcommerce.endpoint,\n storefrontToken: bigcommerce.storefrontToken,\n channelId: bigcommerce.channelId\n }),\n [bigcommerce.endpoint, bigcommerce.storefrontToken, bigcommerce.channelId]\n );\n\n return (\n <TakeShapeConfigProvider\n projectId={takeshape.projectId}\n apiKey={takeshape.apiKey}\n origin={takeshape.origin}\n sseOrigin={takeshape.sseOrigin}\n >\n <PurchaseOrderChat\n agentName={agentName}\n inputName={inputName}\n className={className}\n expandOnReady={expandOnReady}\n bigcommerce={{\n client: bigCommerceClient,\n onViewProduct,\n onCheckout,\n getB2BJwt: bigcommerce.getB2BJwt\n }}\n />\n </TakeShapeConfigProvider>\n );\n}\n"],"names":["REACT_ELEMENT_TYPE","REACT_FRAGMENT_TYPE","jsxProd","type","config","maybeKey","key","propName","reactJsxRuntime_production","getComponentNameFromType","REACT_CLIENT_REFERENCE","REACT_PROFILER_TYPE","REACT_STRICT_MODE_TYPE","REACT_SUSPENSE_TYPE","REACT_SUSPENSE_LIST_TYPE","REACT_ACTIVITY_TYPE","REACT_PORTAL_TYPE","REACT_CONTEXT_TYPE","REACT_CONSUMER_TYPE","REACT_FORWARD_REF_TYPE","innerType","REACT_MEMO_TYPE","REACT_LAZY_TYPE","testStringCoercion","value","checkKeyStringCoercion","JSCompiler_inline_result","JSCompiler_temp_const","JSCompiler_inline_result$jscomp$0","getTaskName","name","getOwner","dispatcher","ReactSharedInternals","UnknownOwner","hasValidKey","hasOwnProperty","getter","defineKeyPropWarningGetter","props","displayName","warnAboutAccessingKey","specialPropKeyWarningShown","elementRefGetterWithDeprecationWarning","componentName","didWarnAboutElementRef","ReactElement","owner","debugStack","debugTask","refProp","jsxDEVImpl","isStaticChildren","children","isArrayImpl","validateChildKeys","keys","k","didWarnAboutKeySpread","node","isValidElement","object","React","require$$0","createTask","callStackForError","unknownOwnerDebugStack","unknownOwnerDebugTask","reactJsxRuntime_development","trackActualOwner","jsxRuntimeModule","require$$1","throttle","function_","wait","timeoutId","lastCallTime","arguments_","now","timeSinceLastCall","delayForNextCall","throttleit","__accessCheck","obj","member","msg","__privateGet","__privateAdd","__privateSet","setter","fn","waitMs","throttleFunction","_messages","_status","_error","_messagesCallbacks","_statusCallbacks","_errorCallbacks","_callMessagesCallbacks","_callStatusCallbacks","_callErrorCallbacks","ReactChatState","initialMessages","message","index","onChange","throttleWaitMs","callback","newStatus","newError","newMessages","_state","Chat","AbstractChat","messages","init","state","useChat","resume","options","callbacksRef","useRef","optionsWithCallbacks","arg","_a","_b","_c","chatRef","subscribeToMessages","useCallback","update","useSyncExternalStore","status","error","setMessages","messagesParam","useEffect","useChatDisplayStore","create","set","expanded","ExpandedChatView","isExpanded","setExpanded","overlayRef","handleKeyDown","e","useLayoutEffect","scrollY","originalOverflow","originalPosition","originalTop","originalWidth","root","host","prev","jsxs","jsx","CartIcon","CheckIcon","size","title","CopyIcon","MaximizeIcon","MinimizeIcon","DEFAULT_AGENT_NAME","B2B_GRAPHQL_URL","B2B_APP_CLIENT_ID","CLIENT_TOOL_RESPONSE_MESSAGE","PO_ADDRESS_ID","PO_BILLING_ADDRESS_ID","CHECKOUT_ADDRESS_ID","STORAGE_KEY","STORAGE_VERSION","cn","inputs","twMerge","clsx","AlertCircleIcon","SpinnerIcon","CartifactAddress","addresses","selectedAddressId","addressUpdateStatus","onAddressChange","shipToAddress","billingAddress","selectedBillingAddressId","billingAddressUpdateStatus","onBillingAddressChange","canShowDefaultAddressWarning","addr","AddressSelect","label","poAddress","defaultAddressFilter","addressFilter","isCheckoutAddress","defaultAddress","showDefaultAddressWarning","addressOptions","Fragment","AddressSelectOption","FormattedAddress","address","isDefault","formatAddress","parts","lastPart","isCopied","setIsCopied","useState","timerRef","formattedAddress","handleCopy","formatCurrency","amount","currencyCode","FooterRow","formatOptional","CartifactFooter","subtotal","tax","shipping","total","totalQuantity","availableItemCount","onCheckout","isLoading","allowCheckout","XIcon","baseClass","StepButton","className","QuantitySelector","min","max","asyncMode","testId","inputValue","setInputValue","setStatus","statusTimeoutRef","handleChange","rawValue","newValue","clampedValue","handleBlur","newQty","clampedQty","handleStep","delta","current","base","atMin","atMax","isSaving","CartifactLineItem","item","onUpdateQuantity","onRemove","onShowMoreLikeThis","onViewProduct","poPriceValue","hasPriceMismatch","currenciesDiffer","isFavorable","qty","CartifactActionButton","PanelActionButton","CartifactNewOrder","onNewOrder","confirmingReset","setConfirmingReset","resetTimerRef","handleNewOrderClick","handleConfirmReset","handleCancelReset","OrderListIcon","EmptyCartifact","onExpand","onMinimize","hasHeaderButtons","shouldDispatchFromDevtools","api","trackedConnections","getTrackedConnectionState","api2","extractConnectionInformation","store","extensionConnector","existingConnection","newConnection","removeStoreFromTrackedConnections","connectionInfo","findCallerName","stack","traceLines","apiSetStateLineIndex","traceLine","callerLine","devtoolsImpl","devtoolsOptions","get","enabled","anonymousActionType","__vite_import_meta_env__","connection","connectionInformation","isRecording","replace","nameOrAction","r","action","setStateFromDevtools","a","originalIsRecording","initialState","store2","didWarnAboutReservedActionType","originalDispatch","args","parseJsonThen","stateFromDevtools","nextLiftedState","lastComputedState","devtools","stringified","parsed","createJSONStorage","getStorage","storage","parse","str2","str","toThenable","input","result","onFulfilled","_onRejected","_onFulfilled","onRejected","persistImpl","baseOptions","persistedState","currentState","hasHydrated","hydrationVersion","hydrationListeners","finishHydrationListeners","setItem","savedSetState","configResult","stateFromStorage","hydrate","currentVersion","cb","_a2","postRehydrationCallback","deserializedStorageValue","migration","migrationResult","migrated","migratedState","newOptions","persist","initialBcSessionState","createBcSessionSlice","bcCart","checkout","productPaths","graphql","initGraphQLTada","UserAuthorizationFragment","AuthorizationMutation","UserFragment","CurrentUserQuery","CompanyAddressFragment","CompanyAddressesQuery","CheckoutLoginMutation","CartFragment","GetCartQuery","CreateCartMutation","AddCartLineItemsMutation","UpdateCartLineItemMutation","DeleteCartLineItemMutation","DeleteCartMutation","CreateCartRedirectUrlsMutation","CreateCartMetafieldMutation","CheckoutFragment","GetCheckoutQuery","AddCheckoutShippingConsignmentsMutation","AddCheckoutBillingAddressMutation","UpdateCheckoutCustomerMessageMutation","GetProductVariantDetailsQuery","GetProductsForDisplayQuery","GetProductVariantsForDisplayPageQuery","CustomerAddressFragment","GetCustomerAddressesQuery","GetProductVariantsPageQuery","GetProductOptionsPageQuery","GetProductPathsQuery","GetProductOptionValuesPageQuery","convertCompanyAddressToCustomerAddress","companyAddress","readFragment","convertCustomerAddressToCustomerAddress","customerAddress","convertPoAddressToCustomerAddress","makePoItemPriceKey","productEntityId","variantEntityId","initialCartifactState","createCartifactSlice","cartEntityId","poPrice","poCurrency","newPrices","orderId","buyerInfo","poMetadataSet","itemWarnings","warning","w","initialChatState","createChatSlice","threadId","toolCallId","initialCustomerState","createCustomerSlice","customerInfo","customerAddresses","initialParserState","createParserSlice","uploadedFileName","parsedContent","hasProcessedDocument","initialUIState","createUISlice","messageId","ids","id","DEFAULT_PANEL_WIDTH","initialUserSettingsState","createUserSettingsSlice","panelWidth","raw","settings","getCleanState","usePurchaseOrderStore","customerEntityId","fatalError","appState","s","cart","client","existingCart","data","persisted","version","itemWarningToString","productName","productSku","LineItemWarning","onSuggestAlternatives","removeItemWarning","CartPanel","items","checkoutTotals","copied","setCopied","copyTimeoutRef","handleCopyOrderId","sum","availableItems","displayTax","displayShipping","displayTotal","identifier","networkErrorPatterns","isOfflineError","pattern","ChatError","onRetry","offline","SendIcon","ChatInput","onInputChange","onSubmit","form","NON_COLLAPSIBLE_TOOLS","isCollapsibleTool","part","groupRenderableParts","accumulator","flush","FileIcon","ExpandChevronIcon","GenericToolMessage","loadingMessage","failedMessage","successMessage","toolOutput","hasError","hasFailed","variant","parseToolOutput","output","GetProductVariantsTool","toolInput","toolState","variants","count","hasMore","SearchProductsBySkuTool","sku","SearchProductsTool","matchPhrase","BigCommerceClientContext","createContext","BigCommerceClientProvider","useBigCommerceClient","useContext","useProductVariants","productEntityIds","useQuery","b","getVariantOptionValues","map","option","selectedValue","findMatchingVariant","selections","variantValues","optionId","valueId","getInitialSelections","details","defaultValue","v","firstVariant","PlaceholderImage","VariantPicker","variantDetails","onSelectionChange","hasInvalidCombination","LOW_STOCK_QUANTITY","addToCartButtonClass","isAdding","showAdded","isDisabled","ProductCard","product","onAddToCart","layout","quantity","setQuantity","setIsAdding","setShowAdded","isHorizontal","selectedVariant","selectedVariantEntityId","cartItem","inCart","cartQuantity","displaySku","displayPrice","displayAvailableQuantity","lowStock","displayIsInStock","isOutOfStock","handleAddToCart","variantImageUrl","productImageUrl","imageUrl","lowStockWarning","ProductGrid","products","loadingText","useMemo","p","variantDetailsArray","variantDetailsMap","selectionsMap","setSelectionsMap","next","d","requestedVariant","handleSelectionChange","productId","optionEntityId","valueEntityId","availableProducts","singleProduct","ShowProductsTool","setProducts","setIsLoading","setError","isToolLoading","fetchProducts","productsData","transformedProducts","inputProduct","productData","err","Tool","toolName","CollapsibleToolCalls","tools","setIsExpanded","toolPart","CollapsibleAgentMessage","isLatestAssistantMessage","text","previewText","expandedMessageIds","toggleMessageExpanded","Streamdown","getOrderedParts","results","getFilename","filePart","ChatMessage","isFirstUserMessage","isDocumentExpanded","onToggleDocument","isAssistant","orderedParts","useTouchDevice","isTouch","setIsTouch","mq","handler","ALLOWED_FILE_TYPES","ALLOWED_TYPES","ACCEPTED_EXTENSIONS","ALLOWED_TYPES_DISPLAY","MAX_FILE_SIZE","validateFile","file","UploadDocumentIcon","CameraIcon","CameraButton","onClick","ChatPanelEmptyState","onFileUpload","fileInputRef","cameraInputRef","isTouchDevice","fileError","setFileError","handleClick","handleCameraClick","handleFileChange","TypingIndicator","ChatPanel","forwardRef","ref","scrollContainerRef","shouldAutoScrollRef","setIsDocumentExpanded","latestAssistantMessageId","i","useImperativeHandle","container","handleScroll","isNearBottom","observer","messageIndex","useResizablePanel","leftPanelWidth","setPanelWidth","isDesktop","setIsDesktop","containerRef","isDragging","leftPanelWidthRef","updateLayout","handleMouseMove","containerRect","newWidth","clampedWidth","handleMouseUp","handleMouseDown","TabBar","activeTab","onTabChange","hasUnread","chatHasUnread","ChatView","chatPanelRef","cartItems","isCartLoading","panel","setActiveTab","setHasUnread","prevMessageCount","activeTabRef","handleTabChange","tab","chatPanel","cartPanel","ExistingCartPrompt","confirmClearExistingCart","isClearing","setIsClearing","itemCount","handleClearCart","FatalError","handleRefresh","steps","ProcessingSteps","_props","step","UploadDropZone","acceptedExtensions","onDropZoneClick","onFileChange","InitialState","displayError","onSkip","CartPreview","isUploading","currentStep","hasProducts","isReadingOrMatching","isBuildingCart","_","extractToolCalls","toolCalls","resultCount","useToolCallStore","TARGET_TOTAL_MS","MIN_INTERVAL_MS","computeInterval","totalItems","useProgressiveCartItems","addToCartCall","tc","revealedCount","setRevealedCount","interval","timer","REVEAL_INTERVAL_MS","useProgressiveToolCalls","incrementRevealed","visibleToolCalls","STEP_ORDER","getProcessingStepStatus","stepId","currentIndex","stepIndex","deriveCurrentStep","isFirstResponseComplete","TOOL_CALL_RENDERERS","pageNumber","renderToolCall","toolCall","renderer","STEPS","statusStyles","ProcessingStepsVertical","currentToolCall","fileNameContent","toolCallContent","cartProgressContent","Processing","Uploader","onClearError","parserError","setIsDragging","isProcessing","validateAndUploadFile","handleDragOver","handleDragLeave","handleDrop","handleDropZoneClick","DEFAULT_ORIGIN","TakeShapeConfigContext","TakeShapeConfigProvider","projectId","apiKey","origin","sseOrigin","useTakeShapeConfig","context","toCheckoutAddress","findMatchingCustomerAddress","catalogPrice","mergePoCartItems","existing","incoming","merged","newItem","existingIndex","diffCartItems","cartPhysicalItems","incomingItems","toAdd","toUpdate","existingCartItem","ci","buildSyncedCartResult","syncedCart","mergedItems","storedItem","si","mismatch","normalizeProductSku","normalizeProductName","filterMatchingWarnings","warnings","useBigCommerceCart","onError","clientRef","onErrorRef","poItemPrices","setBcCart","setCheckout","setSelectedAddressId","setAddressUpdateStatus","setProductPaths","setSelectedBillingAddressId","setBillingAddressUpdateStatus","setItemWarnings","storedCartItems","priceData","fetchedPathIdsRef","updateCheckoutShippingAddress","lineItems","updatedCheckout","updateCheckoutBillingAddress","missingIds","newPaths","newPathsRecord","path","currentPaths","shippingAddressAppliedRef","billingAddressAppliedRef","addressId","match","checkoutAddress","addressStatusTimeoutRef","billingAddressStatusTimeoutRef","hasMismatch","reapplyShippingAddressAfterCartChange","updatedCart","syncCartItems","finalCartItemKeys","storedKeys","variantId","newCartItems","currentWarnings","filteredWarnings","addToCart","mergedInput","itemsToSet","updateLineItemQuantity","lineItemId","removeLineItem","remainingItems","removedItems","stored","removed","initiateCheckout","setShippingAddressOnCheckout","setBillingAddressOnCheckout","clearCart","useCartHandlers","sendMessage","onCheckoutInitiated","handleCheckout","redirectUrls","handleUpdateQuantity","itemId","handleRemoveItem","handleAddToCartFromSuggestion","actualQuantity","handleSuggestAlternatives","itemName","handleShowMoreLikeThis","useChatOrchestration","setAppState","parser","processingState","hasSentToPOAgent","setHasProcessedDocument","Sentry","m","NOOP_SPAN","startInactiveSpan","readFileAsText","resolve","reject","reader","readFileAsDataUrl","SPREADSHEET_TYPES","isSpreadsheet","mimeType","convertSpreadsheetToCsv","xlsx","buffer","workbook","allRows","sheet","rows","PDF_HEADER","PDF_EOF","MIN_PDF_SIZE","readFileAsArrayBuffer","validatePdf","tailSize","trailerStart","trailerText","start","end","pdfjsWorker","getDocument","loadingTask","TEXT_BASED_TYPES","PARSE_PROMPT","buildTextParts","fileName","content","buildFileParts","dataUrl","mediaType","filename","useFileUpload","createParserThread","sendParserMessage","isUploadingFile","setIsUploadingFile","setParserError","handleFileUpload","csvContent","textContent","Thread","z","useTakeShapeThread","agentName","createOnMount","existingThreadId","isCreating","setIsCreating","thread","createThread","maxRetries","attempt","response","backoffMs","useDocumentParser","parserThread","parserSpanRef","parserMessages","parserStatus","setParserMessages","DefaultChatTransport","lastMessage","baseHandleFileUpload","handleClearError","reset","useProcessingState","isComplete","derivedStep","setToolCallError","handleGetCart","cartData","handleRemoveFromCart","bcCartItem","handleRemoveItemWarnings","remaining","handleSetItemWarnings","handleSetPoMetadata","setPoMetadataSet","setOrderId","setBuyerInfo","setShipToAddress","setBillingAddress","poMetadata","handleUpdateCart","setPoItemPrice","itemsUpdated","toolHandlers","handleToolCall","useToolCallHandlers","pendingToolOutputsRef","B2BClient","GraphQLClient","jwt","delays","delay","token","companyId","addressEdges","edge","cartId","redirectedCheckoutUrl","createB2BClient","stencilB2BJwt","channelId","customerJwt","resp","loadPersistedSession","storedVersion","clearPersistedSession","validateCustomer","persistedCustomerEntityId","validateThread","_threadId","_config","validateCart","validateAndInit","deps","loadResult","fetchedAddresses","fetchedCustomerInfo","companyAddresses","orphanCart","persistedData","fetchedCart","validationPromises","failedResult","isCompletedToolPart","isToolUIPart","getCompletedToolParts","getToolNameFromPart","queryClient","QueryClient","PurchaseOrderChat","QueryClientProvider","PurchaseOrderChatInitializer","takeShapeConfig","initStatus","initError","clearInitError","PurchaseOrderChatInner","inputName","bigcommerce","expandOnReady","persistedThreadId","persistedMessages","isCreatingThread","setToolCalls","agentTurnSpanRef","sessionSpanRef","resetChatDisplay","clearCartifact","clearBcSession","clearAddressSelections","clearChat","onToolCall","completedToolCallIdsRef","addToolOutput","messagesToSend","prevMessage","completedParts","tracedSendMessage","params","pendingOutputs","pending","sendMessageAndScroll","orchestration","cartHandlers","handleInputChange","handleSubmit","handleViewProduct","handleRetry","lastUserMessage","lastUserIndex","handleSkip","resetToolCalls","handleStartOver","chatViewProps","MAX_PAGES","fetchAllPages","document","baseVariables","getConnection","allEdges","after","pages","variables","CART_BATCH_SIZE","toCart","toCheckout","resolveEndpoint","endpoint","BigCommerceClient","headers","ClientError","firstBatch","rawCart","batch","lineItemEntityId","existingCartId","checkoutEntityId","rawCheckout","allAddressEdges","additionalEdges","allVariantEdges","additionalVariants","allOptionEdges","additionalOptions","paginatedValueEdges","optionEdge","additionalValues","firstEdge","values","valueEdge","variantEdge","paths","createBigCommerceEndpoint","storeHash","createBigCommerceClient","PurchaseOrderChatWidget","takeshape","bigCommerceClient"],"mappings":";;;;;;;;;;;;;;;;;;AAWA,MAAIA,IAAqB,uBAAO,IAAI,4BAA4B,GAC9DC,IAAsB,uBAAO,IAAI,gBAAgB;AACnD,WAASC,EAAQC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