The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.
TypeScript b2b-marketplacecomposable-commerceecommerceenterpriseheadless-commercemarketplacemedusamedusajsmulti-vendortypescript
feat(integrations): Magento 2 connector plugin with webhooks and external payments (#1683)
Viktor Holikbee3e79896a8
diff --git a/.github/workflows/integration-tests.yml b/.github/workflows/integration-tests.ymlindex c52a1e8de..e6427910c 100644--- a/.github/workflows/integration-tests.yml+++ b/.github/workflows/integration-tests.yml@@ -76,6 +76,7 @@ jobs:apps/*/node_modulespackages/*/node_modulespackages/providers/*/node_modules+ packages/plugins/*/node_modulesintegration-tests/node_moduleskey: ${{ runner.os }}-node-modules-${{ hashFiles('bun.lock', 'bun.lockb') }}@@ -190,6 +191,7 @@ jobs:apps/*/node_modulespackages/*/node_modulespackages/providers/*/node_modules+ packages/plugins/*/node_modulesintegration-tests/node_moduleskey: ${{ runner.os }}-node-modules-${{ hashFiles('bun.lock', 'bun.lockb') }}diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.ymlindex 4ceae3f00..d12c362de 100644--- a/.github/workflows/lint.yml+++ b/.github/workflows/lint.yml@@ -56,6 +56,7 @@ jobs:apps/*/node_modulespackages/*/node_modulespackages/providers/*/node_modules+ packages/plugins/*/node_modulesintegration-tests/node_moduleskey: ${{ runner.os }}-node-modules-${{ hashFiles('bun.lock', 'bun.lockb') }}diff --git a/apps/docs/docs.json b/apps/docs/docs.jsonindex 1005c5bda..f8729edd1 100644--- a/apps/docs/docs.json+++ b/apps/docs/docs.json@@ -41,6 +41,7 @@"home","learn/introduction","learn/why-mercur",+ "learn/use-cases",{"group": "Build with AI","pages": [@@ -417,7 +418,8 @@"icon": "plug","pages": ["resources/integrations/overview",- "resources/integrations/stripe-connect"+ "resources/integrations/stripe-connect",+ "resources/integrations/magento2"]},{diff --git a/apps/docs/figures/use-case-hybrid.mjs b/apps/docs/figures/use-case-hybrid.mjsnew file mode 100644index 000000000..6f362d69d--- /dev/null+++ b/apps/docs/figures/use-case-hybrid.mjs@@ -0,0 +1,71 @@+const LEFT = { x: 40, y: 96, w: 470, h: 330 }+const RIGHT = { x: 580, y: 180, w: 420, h: 300 }++export default {+ name: "use-case-hybrid",+ width: 1040,+ height: 540,+ alt: "A product page in your own store lists your warehouse next to two seller offers from ACME and GLOBEX. A wire leads from the seller rows to a Mercur order group with one order per seller; your own line never leaves your store.",+ draw(f) {+ f.panel({ ...LEFT, name: "your store" }, (p) => {+ p.header({+ marker: "mid",+ title: "Linen shirt",+ note: "your store · product page",+ })+ p.table({+ y: 76,+ columns: [+ { label: "Sold by", w: 180 },+ { label: "Price", w: 100, align: "right" },+ { label: "Source", w: 126, align: "right" },+ ],+ rowH: 56,+ rows: [+ ["Your warehouse", "€ 49.00", { chip: "yours", tone: "green" }],+ ["ACME", "€ 47.00", { chip: "offer", tone: "mid" }],+ ["GLOBEX", "€ 45.00", { chip: "offer", tone: "mid" }],+ ],+ })+ p.line(0, 298, LEFT.w, 298)+ p.label(32, 314, "1 payment, in your checkout", { size: 15, tone: "lo" })+ })++ const fromY = LEFT.y + 76 + 54 + 56 + 56+ f.wire([+ [LEFT.x + LEFT.w, fromY],+ [LEFT.x + LEFT.w + 35, fromY],+ [LEFT.x + LEFT.w + 35, RIGHT.y + 38],+ [RIGHT.x + 6, RIGHT.y + 38],+ ])++ f.panel({ ...RIGHT, name: "mercur" }, (p) => {+ p.header({+ marker: "violet",+ title: "Order group #G1042",+ note: "Mercur",+ })+ p.table({+ y: 76,+ columns: [+ { label: "Order", w: 120 },+ { label: "Seller", w: 116 },+ { label: "Status", w: 120, align: "right" },+ ],+ rowH: 56,+ rows: [+ { accent: true, cells: ["#1042-1", "ACME", { chip: "shipped", tone: "green" }] },+ ["#1042-2", "GLOBEX", { chip: "open", tone: "amber" }],+ ],+ })+ p.line(0, 242, RIGHT.w, 242)+ p.label(32, 270, "commission · payout per seller", { size: 15, tone: "lo" })+ })++ f.tiles({+ seed: 17,+ density: 0.22,+ clear: [{ x: LEFT.x + LEFT.w, y: RIGHT.y, w: RIGHT.x - LEFT.x - LEFT.w, h: fromY - RIGHT.y + 20 }],+ })+ },+}diff --git a/apps/docs/figures/use-case-platform.mjs b/apps/docs/figures/use-case-platform.mjsnew file mode 100644index 000000000..1ceacc7b8--- /dev/null+++ b/apps/docs/figures/use-case-platform.mjs@@ -0,0 +1,78 @@+export default {+ name: "use-case-platform",+ width: 1040,+ height: 560,+ alt: "Three Mercur surfaces stacked back to front: the admin Sellers list, the vendor panel's Offers table for ACME, and the storefront product page for the Linen shirt listing the offers a shopper can buy.",+ draw(f) {+ f.tiles({ seed: 41, density: 0.24 })+ f.cascade({ x: 40, y: 190, w: 860, h: 330, dx: -70, dy: 76 }, [+ (p) => {+ p.header({+ marker: "mid",+ title: "Sellers",+ tabs: ["All", "Pending approval"],+ note: "/admin/sellers",+ })+ p.table({+ y: 76,+ columns: [+ { label: "Seller", w: 260 },+ { label: "Members", w: 160 },+ { label: "Offers", w: 160, align: "right" },+ { label: "Status", w: 216, align: "right" },+ ],+ rows: [+ ["ACME", "3", "128", { chip: "open", tone: "green" }],+ ["GLOBEX", "1", "41", { chip: "open", tone: "green" }],+ ["INITECH", "2", { text: "0", tone: "mid" }, { chip: "pending", tone: "amber" }],+ ],+ })+ },+ (p) => {+ p.header({+ marker: "mid",+ title: "Offers",+ tabs: ["All", "Out of stock"],+ note: "/vendor/offers · ACME",+ })+ p.table({+ y: 76,+ columns: [+ { label: "Product", w: 300 },+ { label: "SKU", w: 220 },+ { label: "Price", w: 140, align: "right" },+ { label: "Stock", w: 136, align: "right" },+ ],+ rows: [+ ["Linen shirt / M", "ACME-LS-M", "€ 47.00", "50"],+ ["Linen shirt / L", "ACME-LS-L", "€ 47.00", "18"],+ ["Wool scarf", "ACME-WS-1", "€ 29.00", { text: "0", tone: "mid" }],+ ],+ })+ },+ (p) => {+ p.header({+ marker: "violet",+ title: "Linen shirt",+ tabs: ["M"],+ note: "/store/products/linen-shirt",+ })+ p.table({+ y: 76,+ columns: [+ { label: "Sold by", w: 280 },+ { label: "Ships in", w: 180 },+ { label: "Price", w: 140, align: "right" },+ { label: "", w: 40 },+ { label: "", w: 156 },+ ],+ rows: [+ { accent: true, cells: ["ACME", "2 days", "€ 47.00", "", { tag: "Add to cart" }] },+ ["GLOBEX", "4 days", "€ 45.00", "", { tag: "Add to cart" }],+ ["INITECH", "1 day", "€ 49.00", "", { tag: "Add to cart" }],+ ],+ })+ },+ ])+ },+}diff --git a/apps/docs/images/figures/use-case-hybrid-dark.svg b/apps/docs/images/figures/use-case-hybrid-dark.svgnew file mode 100644index 000000000..e0a598515--- /dev/null+++ b/apps/docs/images/figures/use-case-hybrid-dark.svg@@ -0,0 +1,5 @@+<svg xmlns="http://www.w3.org/2000/svg" width="1040" height="540" viewBox="0 0 1040 540" font-family="JetBrains Mono, SF Mono, SFMono-Regular, Menlo, Consolas, Liberation Mono, monospace" role="img" aria-label="A product page in your own store lists your warehouse next to two seller offers from ACME and GLOBEX. A wire leads from the seller rows to a Mercur order group with one order per seller; your own line never leaves your store.">+<title>A product page in your own store lists your warehouse next to two seller offers from ACME and GLOBEX. A wire leads from the seller rows to a Mercur order group with one order per seller; your own line never leaves your store.</title>+<defs><filter id="sh" x="-30%" y="-30%" width="160%" height="170%"><feDropShadow dx="0" dy="18" stdDeviation="22" flood-color="#000000" flood-opacity="0.55"/></filter><filter id="gr" x="0" y="0" width="100%" height="100%"><feTurbulence type="fractalNoise" baseFrequency="0.85" numOctaves="2" seed="7" stitchTiles="stitch"/><feColorMatrix type="saturate" values="0"/><feComponentTransfer><feFuncA type="table" tableValues="0 1"/></feComponentTransfer><feComposite in2="SourceGraphic" operator="in"/></filter><pattern id="dt" width="11" height="11" patternUnits="userSpaceOnUse"><rect x="4.5" y="4.5" width="1.6" height="1.6" fill="#2c2737"/></pattern><clipPath id="c1"><rect x="0" y="0" width="470" height="330"/></clipPath><clipPath id="c2"><rect x="0" y="0" width="420" height="300"/></clipPath></defs>+<rect x="0" y="-88" width="88" height="88" fill="url(#dt)"/><rect x="88.5" y="-87.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="264" y="-88" width="88" height="88" fill="url(#dt)"/><rect x="352" y="-88" width="88" height="88" fill="url(#dt)"/><rect x="528.5" y="-87.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="616" y="-88" width="88" height="88" fill="url(#dt)"/><rect x="792" y="-88" width="88" height="88" fill="url(#dt)"/><rect x="176.5" y="0.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="704.5" y="0.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="880" y="0" width="88" height="88" fill="#1d1926"/><rect x="880" y="0" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="1056" y="0" width="88" height="88" fill="url(#dt)"/><rect x="-87.5" y="88.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="88" y="88" width="88" height="88" fill="url(#dt)"/><rect x="968" y="88" width="88" height="88" fill="url(#dt)"/><rect x="88" y="176" width="88" height="88" fill="url(#dt)"/><rect x="352" y="176" width="88" height="88" fill="url(#dt)"/><rect x="0" y="264" width="88" height="88" fill="url(#dt)"/><rect x="264" y="264" width="88" height="88" fill="#1d1926"/><rect x="264" y="264" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="352" y="264" width="88" height="88" fill="url(#dt)"/><rect x="792" y="264" width="88" height="88" fill="url(#dt)"/><rect x="968" y="264" width="88" height="88" fill="url(#dt)"/><rect x="968" y="352" width="88" height="88" fill="#1d1926"/><rect x="968" y="352" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="704.5" y="440.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="968" y="440" width="88" height="88" fill="url(#dt)"/><rect x="1056.5" y="440.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="-88" y="528" width="88" height="88" fill="url(#dt)"/><rect x="176.5" y="528.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="440" y="528" width="88" height="88" fill="#1d1926"/><rect x="440" y="528" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="704" y="528" width="88" height="88" fill="#1d1926"/><rect x="704" y="528" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="792.5" y="528.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="-88" y="616" width="88" height="88" fill="#1d1926"/><rect x="-88" y="616" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="176.5" y="616.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="352.5" y="616.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="528.5" y="616.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="616" y="616" width="88" height="88" fill="url(#dt)"/><rect x="704" y="616" width="88" height="88" fill="url(#dt)"/><rect x="40" y="96" width="470" height="330" fill="#15121d" filter="url(#sh)"/><rect x="40" y="96" width="470" height="330" fill="#15121d"/><g transform="translate(40 96)"><g clip-path="url(#c1)"><rect x="24" y="33" width="10" height="10" fill="#a1a1aa"/><text x="46" y="44.3" font-size="18" fill="#f4f4f5" font-weight="500">Linen shirt</text><text x="446" y="43.3" font-size="15" fill="#71717a" text-anchor="end">your store · product page</text><line x1="0" y1="76" x2="470" y2="76" stroke="#2b2636" stroke-width="1"/><text x="32" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2">SOLD BY</text><text x="312" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2" text-anchor="end">PRICE</text><text x="438" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2" text-anchor="end">SOURCE</text><line x1="0" y1="130" x2="470" y2="130" stroke="#221e2b" stroke-width="1"/><text x="32" y="163.6" font-size="16" fill="#f4f4f5">Your warehouse</text><text x="312" y="163.6" font-size="16" fill="#f4f4f5" text-anchor="end">€ 49.00</text><rect x="346" y="142" width="92" height="32" fill="#1f1b29"/><rect x="358" y="153" width="10" height="10" fill="#6fbf68"/><text x="380" y="162.9" font-size="14" fill="#d4d4d8" letter-spacing="1.2">YOURS</text><line x1="0" y1="186" x2="470" y2="186" stroke="#221e2b" stroke-width="1"/><text x="32" y="219.6" font-size="16" fill="#f4f4f5">ACME</text><text x="312" y="219.6" font-size="16" fill="#f4f4f5" text-anchor="end">€ 47.00</text><rect x="346" y="198" width="92" height="32" fill="#1f1b29"/><rect x="358" y="209" width="10" height="10" fill="#a1a1aa"/><text x="380" y="218.9" font-size="14" fill="#d4d4d8" letter-spacing="1.2">OFFER</text><line x1="0" y1="242" x2="470" y2="242" stroke="#221e2b" stroke-width="1"/><text x="32" y="275.6" font-size="16" fill="#f4f4f5">GLOBEX</text><text x="312" y="275.6" font-size="16" fill="#f4f4f5" text-anchor="end">€ 45.00</text><rect x="346" y="254" width="92" height="32" fill="#1f1b29"/><rect x="358" y="265" width="10" height="10" fill="#a1a1aa"/><text x="380" y="274.9" font-size="14" fill="#d4d4d8" letter-spacing="1.2">OFFER</text><line x1="0" y1="298" x2="470" y2="298" stroke="#221e2b" stroke-width="1"/><line x1="0" y1="298" x2="470" y2="298" stroke="#2b2636" stroke-width="1"/><text x="32" y="319.3" font-size="15" fill="#71717a">1 payment, in your checkout</text></g></g><rect x="40.5" y="96.5" width="469" height="329" fill="none" stroke="#2b2636" stroke-width="1"/><path d="M510 338 L545 338 L545 218 L586 218" fill="none" stroke="#3d3749" stroke-width="1"/><rect x="583" y="215" width="6" height="6" fill="#3d3749"/><rect x="580" y="180" width="420" height="300" fill="#15121d" filter="url(#sh)"/><rect x="580" y="180" width="420" height="300" fill="#15121d"/><g transform="translate(580 180)"><g clip-path="url(#c2)"><rect x="24" y="33" width="10" height="10" fill="#a78bfa"/><text x="46" y="44.3" font-size="18" fill="#f4f4f5" font-weight="500">Order group #G1042</text><text x="396" y="43.3" font-size="15" fill="#71717a" text-anchor="end">Mercur</text><line x1="0" y1="76" x2="420" y2="76" stroke="#2b2636" stroke-width="1"/><text x="32" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2">ORDER</text><text x="152" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2">SELLER</text><text x="388" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2" text-anchor="end">STATUS</text><line x1="0" y1="130" x2="420" y2="130" stroke="#221e2b" stroke-width="1"/><rect x="0" y="130" width="3" height="56" fill="#a78bfa"/><text x="32" y="163.6" font-size="16" fill="#f4f4f5">#1042-1</text><text x="152" y="163.6" font-size="16" fill="#f4f4f5">ACME</text><rect x="276.8" y="142" width="111.2" height="32" fill="#1f1b29"/><rect x="288.8" y="153" width="10" height="10" fill="#6fbf68"/><text x="310.8" y="162.9" font-size="14" fill="#d4d4d8" letter-spacing="1.2">SHIPPED</text><line x1="0" y1="186" x2="420" y2="186" stroke="#221e2b" stroke-width="1"/><text x="32" y="219.6" font-size="16" fill="#f4f4f5">#1042-2</text><text x="152" y="219.6" font-size="16" fill="#f4f4f5">GLOBEX</text><rect x="305.6" y="198" width="82.4" height="32" fill="#1f1b29"/><rect x="317.6" y="209" width="10" height="10" fill="#f2a14b"/><text x="339.6" y="218.9" font-size="14" fill="#d4d4d8" letter-spacing="1.2">OPEN</text><line x1="0" y1="242" x2="420" y2="242" stroke="#221e2b" stroke-width="1"/><line x1="0" y1="242" x2="420" y2="242" stroke="#2b2636" stroke-width="1"/><text x="32" y="275.3" font-size="15" fill="#71717a">commission · payout per seller</text></g></g><rect x="580.5" y="180.5" width="419" height="299" fill="none" stroke="#2b2636" stroke-width="1"/>+</svg>\ No newline at end of filediff --git a/apps/docs/images/figures/use-case-hybrid-light.svg b/apps/docs/images/figures/use-case-hybrid-light.svgnew file mode 100644index 000000000..bff395d2c--- /dev/null+++ b/apps/docs/images/figures/use-case-hybrid-light.svg@@ -0,0 +1,5 @@+<svg xmlns="http://www.w3.org/2000/svg" width="1040" height="540" viewBox="0 0 1040 540" font-family="JetBrains Mono, SF Mono, SFMono-Regular, Menlo, Consolas, Liberation Mono, monospace" role="img" aria-label="A product page in your own store lists your warehouse next to two seller offers from ACME and GLOBEX. A wire leads from the seller rows to a Mercur order group with one order per seller; your own line never leaves your store.">+<title>A product page in your own store lists your warehouse next to two seller offers from ACME and GLOBEX. A wire leads from the seller rows to a Mercur order group with one order per seller; your own line never leaves your store.</title>+<defs><filter id="sh" x="-30%" y="-30%" width="160%" height="170%"><feDropShadow dx="0" dy="18" stdDeviation="22" flood-color="#18181b" flood-opacity="0.07"/></filter><filter id="gr" x="0" y="0" width="100%" height="100%"><feTurbulence type="fractalNoise" baseFrequency="0.85" numOctaves="2" seed="7" stitchTiles="stitch"/><feColorMatrix type="saturate" values="0"/><feComponentTransfer><feFuncA type="table" tableValues="0 1"/></feComponentTransfer><feComposite in2="SourceGraphic" operator="in"/></filter><pattern id="dt" width="11" height="11" patternUnits="userSpaceOnUse"><rect x="4.5" y="4.5" width="1.6" height="1.6" fill="#d9d9de"/></pattern><clipPath id="c1"><rect x="0" y="0" width="470" height="330"/></clipPath><clipPath id="c2"><rect x="0" y="0" width="420" height="300"/></clipPath></defs>+<rect x="0" y="-88" width="88" height="88" fill="url(#dt)"/><rect x="88.5" y="-87.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="264" y="-88" width="88" height="88" fill="url(#dt)"/><rect x="352" y="-88" width="88" height="88" fill="url(#dt)"/><rect x="528.5" y="-87.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="616" y="-88" width="88" height="88" fill="url(#dt)"/><rect x="792" y="-88" width="88" height="88" fill="url(#dt)"/><rect x="176.5" y="0.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="704.5" y="0.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="880" y="0" width="88" height="88" fill="#e4e4e7"/><rect x="880" y="0" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="1056" y="0" width="88" height="88" fill="url(#dt)"/><rect x="-87.5" y="88.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="88" y="88" width="88" height="88" fill="url(#dt)"/><rect x="968" y="88" width="88" height="88" fill="url(#dt)"/><rect x="88" y="176" width="88" height="88" fill="url(#dt)"/><rect x="352" y="176" width="88" height="88" fill="url(#dt)"/><rect x="0" y="264" width="88" height="88" fill="url(#dt)"/><rect x="264" y="264" width="88" height="88" fill="#e4e4e7"/><rect x="264" y="264" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="352" y="264" width="88" height="88" fill="url(#dt)"/><rect x="792" y="264" width="88" height="88" fill="url(#dt)"/><rect x="968" y="264" width="88" height="88" fill="url(#dt)"/><rect x="968" y="352" width="88" height="88" fill="#e4e4e7"/><rect x="968" y="352" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="704.5" y="440.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="968" y="440" width="88" height="88" fill="url(#dt)"/><rect x="1056.5" y="440.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="-88" y="528" width="88" height="88" fill="url(#dt)"/><rect x="176.5" y="528.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="440" y="528" width="88" height="88" fill="#e4e4e7"/><rect x="440" y="528" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="704" y="528" width="88" height="88" fill="#e4e4e7"/><rect x="704" y="528" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="792.5" y="528.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="-88" y="616" width="88" height="88" fill="#e4e4e7"/><rect x="-88" y="616" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="176.5" y="616.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="352.5" y="616.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="528.5" y="616.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="616" y="616" width="88" height="88" fill="url(#dt)"/><rect x="704" y="616" width="88" height="88" fill="url(#dt)"/><rect x="40" y="96" width="470" height="330" fill="#ffffff" filter="url(#sh)"/><rect x="40" y="96" width="470" height="330" fill="#ffffff"/><g transform="translate(40 96)"><g clip-path="url(#c1)"><rect x="24" y="33" width="10" height="10" fill="#71717a"/><text x="46" y="44.3" font-size="18" fill="#18181b" font-weight="500">Linen shirt</text><text x="446" y="43.3" font-size="15" fill="#a1a1aa" text-anchor="end">your store · product page</text><line x1="0" y1="76" x2="470" y2="76" stroke="#e4e4e7" stroke-width="1"/><text x="32" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2">SOLD BY</text><text x="312" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2" text-anchor="end">PRICE</text><text x="438" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2" text-anchor="end">SOURCE</text><line x1="0" y1="130" x2="470" y2="130" stroke="#ededf0" stroke-width="1"/><text x="32" y="163.6" font-size="16" fill="#18181b">Your warehouse</text><text x="312" y="163.6" font-size="16" fill="#18181b" text-anchor="end">€ 49.00</text><rect x="346" y="142" width="92" height="32" fill="#f4f4f5"/><rect x="358" y="153" width="10" height="10" fill="#3f7d3a"/><text x="380" y="162.9" font-size="14" fill="#3f3f46" letter-spacing="1.2">YOURS</text><line x1="0" y1="186" x2="470" y2="186" stroke="#ededf0" stroke-width="1"/><text x="32" y="219.6" font-size="16" fill="#18181b">ACME</text><text x="312" y="219.6" font-size="16" fill="#18181b" text-anchor="end">€ 47.00</text><rect x="346" y="198" width="92" height="32" fill="#f4f4f5"/><rect x="358" y="209" width="10" height="10" fill="#71717a"/><text x="380" y="218.9" font-size="14" fill="#3f3f46" letter-spacing="1.2">OFFER</text><line x1="0" y1="242" x2="470" y2="242" stroke="#ededf0" stroke-width="1"/><text x="32" y="275.6" font-size="16" fill="#18181b">GLOBEX</text><text x="312" y="275.6" font-size="16" fill="#18181b" text-anchor="end">€ 45.00</text><rect x="346" y="254" width="92" height="32" fill="#f4f4f5"/><rect x="358" y="265" width="10" height="10" fill="#71717a"/><text x="380" y="274.9" font-size="14" fill="#3f3f46" letter-spacing="1.2">OFFER</text><line x1="0" y1="298" x2="470" y2="298" stroke="#ededf0" stroke-width="1"/><line x1="0" y1="298" x2="470" y2="298" stroke="#e4e4e7" stroke-width="1"/><text x="32" y="319.3" font-size="15" fill="#a1a1aa">1 payment, in your checkout</text></g></g><rect x="40.5" y="96.5" width="469" height="329" fill="none" stroke="#e4e4e7" stroke-width="1"/><path d="M510 338 L545 338 L545 218 L586 218" fill="none" stroke="#c4c4cc" stroke-width="1"/><rect x="583" y="215" width="6" height="6" fill="#c4c4cc"/><rect x="580" y="180" width="420" height="300" fill="#ffffff" filter="url(#sh)"/><rect x="580" y="180" width="420" height="300" fill="#ffffff"/><g transform="translate(580 180)"><g clip-path="url(#c2)"><rect x="24" y="33" width="10" height="10" fill="#7c3aed"/><text x="46" y="44.3" font-size="18" fill="#18181b" font-weight="500">Order group #G1042</text><text x="396" y="43.3" font-size="15" fill="#a1a1aa" text-anchor="end">Mercur</text><line x1="0" y1="76" x2="420" y2="76" stroke="#e4e4e7" stroke-width="1"/><text x="32" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2">ORDER</text><text x="152" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2">SELLER</text><text x="388" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2" text-anchor="end">STATUS</text><line x1="0" y1="130" x2="420" y2="130" stroke="#ededf0" stroke-width="1"/><rect x="0" y="130" width="3" height="56" fill="#7c3aed"/><text x="32" y="163.6" font-size="16" fill="#18181b">#1042-1</text><text x="152" y="163.6" font-size="16" fill="#18181b">ACME</text><rect x="276.8" y="142" width="111.2" height="32" fill="#f4f4f5"/><rect x="288.8" y="153" width="10" height="10" fill="#3f7d3a"/><text x="310.8" y="162.9" font-size="14" fill="#3f3f46" letter-spacing="1.2">SHIPPED</text><line x1="0" y1="186" x2="420" y2="186" stroke="#ededf0" stroke-width="1"/><text x="32" y="219.6" font-size="16" fill="#18181b">#1042-2</text><text x="152" y="219.6" font-size="16" fill="#18181b">GLOBEX</text><rect x="305.6" y="198" width="82.4" height="32" fill="#f4f4f5"/><rect x="317.6" y="209" width="10" height="10" fill="#c2680c"/><text x="339.6" y="218.9" font-size="14" fill="#3f3f46" letter-spacing="1.2">OPEN</text><line x1="0" y1="242" x2="420" y2="242" stroke="#ededf0" stroke-width="1"/><line x1="0" y1="242" x2="420" y2="242" stroke="#e4e4e7" stroke-width="1"/><text x="32" y="275.3" font-size="15" fill="#a1a1aa">commission · payout per seller</text></g></g><rect x="580.5" y="180.5" width="419" height="299" fill="none" stroke="#e4e4e7" stroke-width="1"/>+</svg>\ No newline at end of filediff --git a/apps/docs/images/figures/use-case-platform-dark.svg b/apps/docs/images/figures/use-case-platform-dark.svgnew file mode 100644index 000000000..492917273--- /dev/null+++ b/apps/docs/images/figures/use-case-platform-dark.svg@@ -0,0 +1,5 @@+<svg xmlns="http://www.w3.org/2000/svg" width="1040" height="560" viewBox="0 0 1040 560" font-family="JetBrains Mono, SF Mono, SFMono-Regular, Menlo, Consolas, Liberation Mono, monospace" role="img" aria-label="Three Mercur surfaces stacked back to front: the admin Sellers list, the vendor panel's Offers table for ACME, and the storefront product page for the Linen shirt listing the offers a shopper can buy.">+<title>Three Mercur surfaces stacked back to front: the admin Sellers list, the vendor panel's Offers table for ACME, and the storefront product page for the Linen shirt listing the offers a shopper can buy.</title>+<defs><filter id="sh" x="-30%" y="-30%" width="160%" height="170%"><feDropShadow dx="0" dy="18" stdDeviation="22" flood-color="#000000" flood-opacity="0.55"/></filter><filter id="gr" x="0" y="0" width="100%" height="100%"><feTurbulence type="fractalNoise" baseFrequency="0.85" numOctaves="2" seed="7" stitchTiles="stitch"/><feColorMatrix type="saturate" values="0"/><feComponentTransfer><feFuncA type="table" tableValues="0 1"/></feComponentTransfer><feComposite in2="SourceGraphic" operator="in"/></filter><pattern id="dt" width="11" height="11" patternUnits="userSpaceOnUse"><rect x="4.5" y="4.5" width="1.6" height="1.6" fill="#2c2737"/></pattern><clipPath id="c1"><rect x="0" y="0" width="860" height="330"/></clipPath><clipPath id="c2"><rect x="0" y="0" width="860" height="330"/></clipPath><clipPath id="c3"><rect x="0" y="0" width="860" height="330"/></clipPath></defs>+<rect x="616" y="-88" width="88" height="88" fill="url(#dt)"/><rect x="792.5" y="-87.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="1056.5" y="-87.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="352.5" y="0.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="440" y="0" width="88" height="88" fill="url(#dt)"/><rect x="616" y="0" width="88" height="88" fill="#1d1926"/><rect x="616" y="0" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="704.5" y="0.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="-88" y="88" width="88" height="88" fill="url(#dt)"/><rect x="176.5" y="88.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="792.5" y="88.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="880" y="88" width="88" height="88" fill="url(#dt)"/><rect x="968" y="88" width="88" height="88" fill="url(#dt)"/><rect x="1056.5" y="88.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="264.5" y="176.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="-87.5" y="264.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="88" y="352" width="88" height="88" fill="#1d1926"/><rect x="88" y="352" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="352" y="352" width="88" height="88" fill="#1d1926"/><rect x="352" y="352" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="968.5" y="352.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="-87.5" y="440.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="528.5" y="440.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="880.5" y="440.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="0" y="528" width="88" height="88" fill="url(#dt)"/><rect x="264.5" y="528.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="-87.5" y="616.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="352" y="616" width="88" height="88" fill="url(#dt)"/><rect x="440" y="616" width="88" height="88" fill="url(#dt)"/><rect x="528" y="616" width="88" height="88" fill="#1d1926"/><rect x="528" y="616" width="88" height="88" fill="#a1a1aa" opacity="0.35" filter="url(#gr)"/><rect x="704.5" y="616.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="792.5" y="616.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="968.5" y="616.5" width="87" height="87" fill="none" stroke="#1d1926" stroke-width="1"/><rect x="180" y="38" width="860" height="330" fill="#15121d" filter="url(#sh)"/><rect x="180" y="38" width="860" height="330" fill="#15121d"/><g transform="translate(180 38)"><g clip-path="url(#c1)"><rect x="24" y="33" width="10" height="10" fill="#a1a1aa"/><text x="46" y="44.3" font-size="18" fill="#f4f4f5" font-weight="500">Sellers</text><line x1="145.6" y1="20" x2="145.6" y2="56" stroke="#2b2636" stroke-width="1"/><text x="177.6" y="44" font-size="17" fill="#f4f4f5">All</text><rect x="159.6" y="73" width="66.6" height="3" fill="#f4f4f5"/><text x="248.2" y="44" font-size="17" fill="#a1a1aa">Pending approval</text><text x="836" y="43.3" font-size="15" fill="#71717a" text-anchor="end">/admin/sellers</text><line x1="0" y1="76" x2="860" y2="76" stroke="#2b2636" stroke-width="1"/><text x="32" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2">SELLER</text><text x="292" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2">MEMBERS</text><text x="612" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2" text-anchor="end">OFFERS</text><text x="828" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2" text-anchor="end">STATUS</text><line x1="0" y1="130" x2="860" y2="130" stroke="#221e2b" stroke-width="1"/><text x="32" y="167.6" font-size="16" fill="#f4f4f5">ACME</text><text x="292" y="167.6" font-size="16" fill="#f4f4f5">3</text><text x="612" y="167.6" font-size="16" fill="#f4f4f5" text-anchor="end">128</text><rect x="745.6" y="146" width="82.4" height="32" fill="#1f1b29"/><rect x="757.6" y="157" width="10" height="10" fill="#6fbf68"/><text x="779.6" y="166.9" font-size="14" fill="#d4d4d8" letter-spacing="1.2">OPEN</text><line x1="0" y1="194" x2="860" y2="194" stroke="#221e2b" stroke-width="1"/><text x="32" y="231.6" font-size="16" fill="#f4f4f5">GLOBEX</text><text x="292" y="231.6" font-size="16" fill="#f4f4f5">1</text><text x="612" y="231.6" font-size="16" fill="#f4f4f5" text-anchor="end">41</text><rect x="745.6" y="210" width="82.4" height="32" fill="#1f1b29"/><rect x="757.6" y="221" width="10" height="10" fill="#6fbf68"/><text x="779.6" y="230.9" font-size="14" fill="#d4d4d8" letter-spacing="1.2">OPEN</text><line x1="0" y1="258" x2="860" y2="258" stroke="#221e2b" stroke-width="1"/><text x="32" y="295.6" font-size="16" fill="#f4f4f5">INITECH</text><text x="292" y="295.6" font-size="16" fill="#f4f4f5">2</text><text x="612" y="295.6" font-size="16" fill="#a1a1aa" text-anchor="end">0</text><rect x="716.8" y="274" width="111.2" height="32" fill="#1f1b29"/><rect x="728.8" y="285" width="10" height="10" fill="#f2a14b"/><text x="750.8" y="294.9" font-size="14" fill="#d4d4d8" letter-spacing="1.2">PENDING</text><line x1="0" y1="322" x2="860" y2="322" stroke="#221e2b" stroke-width="1"/></g></g><rect x="180.5" y="38.5" width="859" height="329" fill="none" stroke="#2b2636" stroke-width="1"/><rect x="110" y="114" width="860" height="330" fill="#15121d" filter="url(#sh)"/><rect x="110" y="114" width="860" height="330" fill="#15121d"/><g transform="translate(110 114)"><g clip-path="url(#c2)"><rect x="24" y="33" width="10" height="10" fill="#a1a1aa"/><text x="46" y="44.3" font-size="18" fill="#f4f4f5" font-weight="500">Offers</text><line x1="134.8" y1="20" x2="134.8" y2="56" stroke="#2b2636" stroke-width="1"/><text x="166.8" y="44" font-size="17" fill="#f4f4f5">All</text><rect x="148.8" y="73" width="66.6" height="3" fill="#f4f4f5"/><text x="237.4" y="44" font-size="17" fill="#a1a1aa">Out of stock</text><text x="836" y="43.3" font-size="15" fill="#71717a" text-anchor="end">/vendor/offers · ACME</text><line x1="0" y1="76" x2="860" y2="76" stroke="#2b2636" stroke-width="1"/><text x="32" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2">PRODUCT</text><text x="332" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2">SKU</text><text x="692" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2" text-anchor="end">PRICE</text><text x="828" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2" text-anchor="end">STOCK</text><line x1="0" y1="130" x2="860" y2="130" stroke="#221e2b" stroke-width="1"/><text x="32" y="167.6" font-size="16" fill="#f4f4f5">Linen shirt / M</text><text x="332" y="167.6" font-size="16" fill="#f4f4f5">ACME-LS-M</text><text x="692" y="167.6" font-size="16" fill="#f4f4f5" text-anchor="end">€ 47.00</text><text x="828" y="167.6" font-size="16" fill="#f4f4f5" text-anchor="end">50</text><line x1="0" y1="194" x2="860" y2="194" stroke="#221e2b" stroke-width="1"/><text x="32" y="231.6" font-size="16" fill="#f4f4f5">Linen shirt / L</text><text x="332" y="231.6" font-size="16" fill="#f4f4f5">ACME-LS-L</text><text x="692" y="231.6" font-size="16" fill="#f4f4f5" text-anchor="end">€ 47.00</text><text x="828" y="231.6" font-size="16" fill="#f4f4f5" text-anchor="end">18</text><line x1="0" y1="258" x2="860" y2="258" stroke="#221e2b" stroke-width="1"/><text x="32" y="295.6" font-size="16" fill="#f4f4f5">Wool scarf</text><text x="332" y="295.6" font-size="16" fill="#f4f4f5">ACME-WS-1</text><text x="692" y="295.6" font-size="16" fill="#f4f4f5" text-anchor="end">€ 29.00</text><text x="828" y="295.6" font-size="16" fill="#a1a1aa" text-anchor="end">0</text><line x1="0" y1="322" x2="860" y2="322" stroke="#221e2b" stroke-width="1"/></g></g><rect x="110.5" y="114.5" width="859" height="329" fill="none" stroke="#2b2636" stroke-width="1"/><rect x="40" y="190" width="860" height="330" fill="#15121d" filter="url(#sh)"/><rect x="40" y="190" width="860" height="330" fill="#15121d"/><g transform="translate(40 190)"><g clip-path="url(#c3)"><rect x="24" y="33" width="10" height="10" fill="#a78bfa"/><text x="46" y="44.3" font-size="18" fill="#f4f4f5" font-weight="500">Linen shirt</text><line x1="188.8" y1="20" x2="188.8" y2="56" stroke="#2b2636" stroke-width="1"/><text x="220.8" y="44" font-size="17" fill="#f4f4f5">M</text><rect x="202.8" y="73" width="46.2" height="3" fill="#f4f4f5"/><text x="836" y="43.3" font-size="15" fill="#71717a" text-anchor="end">/store/products/linen-shirt</text><line x1="0" y1="76" x2="860" y2="76" stroke="#2b2636" stroke-width="1"/><text x="32" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2">SOLD BY</text><text x="312" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2">SHIPS IN</text><text x="632" y="107.9" font-size="14" fill="#a1a1aa" letter-spacing="1.2" text-anchor="end">PRICE</text><line x1="0" y1="130" x2="860" y2="130" stroke="#221e2b" stroke-width="1"/><rect x="0" y="130" width="3" height="64" fill="#a78bfa"/><text x="32" y="167.6" font-size="16" fill="#f4f4f5">ACME</text><text x="312" y="167.6" font-size="16" fill="#f4f4f5">2 days</text><text x="632" y="167.6" font-size="16" fill="#f4f4f5" text-anchor="end">€ 47.00</text><rect x="672" y="147" width="123" height="30" fill="#1f1b29"/><text x="684" y="167.3" font-size="15" fill="#a1a1aa">Add to cart</text><line x1="0" y1="194" x2="860" y2="194" stroke="#221e2b" stroke-width="1"/><text x="32" y="231.6" font-size="16" fill="#f4f4f5">GLOBEX</text><text x="312" y="231.6" font-size="16" fill="#f4f4f5">4 days</text><text x="632" y="231.6" font-size="16" fill="#f4f4f5" text-anchor="end">€ 45.00</text><rect x="672" y="211" width="123" height="30" fill="#1f1b29"/><text x="684" y="231.3" font-size="15" fill="#a1a1aa">Add to cart</text><line x1="0" y1="258" x2="860" y2="258" stroke="#221e2b" stroke-width="1"/><text x="32" y="295.6" font-size="16" fill="#f4f4f5">INITECH</text><text x="312" y="295.6" font-size="16" fill="#f4f4f5">1 day</text><text x="632" y="295.6" font-size="16" fill="#f4f4f5" text-anchor="end">€ 49.00</text><rect x="672" y="275" width="123" height="30" fill="#1f1b29"/><text x="684" y="295.3" font-size="15" fill="#a1a1aa">Add to cart</text><line x1="0" y1="322" x2="860" y2="322" stroke="#221e2b" stroke-width="1"/></g></g><rect x="40.5" y="190.5" width="859" height="329" fill="none" stroke="#2b2636" stroke-width="1"/>+</svg>\ No newline at end of filediff --git a/apps/docs/images/figures/use-case-platform-light.svg b/apps/docs/images/figures/use-case-platform-light.svgnew file mode 100644index 000000000..08e50588b--- /dev/null+++ b/apps/docs/images/figures/use-case-platform-light.svg@@ -0,0 +1,5 @@+<svg xmlns="http://www.w3.org/2000/svg" width="1040" height="560" viewBox="0 0 1040 560" font-family="JetBrains Mono, SF Mono, SFMono-Regular, Menlo, Consolas, Liberation Mono, monospace" role="img" aria-label="Three Mercur surfaces stacked back to front: the admin Sellers list, the vendor panel's Offers table for ACME, and the storefront product page for the Linen shirt listing the offers a shopper can buy.">+<title>Three Mercur surfaces stacked back to front: the admin Sellers list, the vendor panel's Offers table for ACME, and the storefront product page for the Linen shirt listing the offers a shopper can buy.</title>+<defs><filter id="sh" x="-30%" y="-30%" width="160%" height="170%"><feDropShadow dx="0" dy="18" stdDeviation="22" flood-color="#18181b" flood-opacity="0.07"/></filter><filter id="gr" x="0" y="0" width="100%" height="100%"><feTurbulence type="fractalNoise" baseFrequency="0.85" numOctaves="2" seed="7" stitchTiles="stitch"/><feColorMatrix type="saturate" values="0"/><feComponentTransfer><feFuncA type="table" tableValues="0 1"/></feComponentTransfer><feComposite in2="SourceGraphic" operator="in"/></filter><pattern id="dt" width="11" height="11" patternUnits="userSpaceOnUse"><rect x="4.5" y="4.5" width="1.6" height="1.6" fill="#d9d9de"/></pattern><clipPath id="c1"><rect x="0" y="0" width="860" height="330"/></clipPath><clipPath id="c2"><rect x="0" y="0" width="860" height="330"/></clipPath><clipPath id="c3"><rect x="0" y="0" width="860" height="330"/></clipPath></defs>+<rect x="616" y="-88" width="88" height="88" fill="url(#dt)"/><rect x="792.5" y="-87.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="1056.5" y="-87.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="352.5" y="0.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="440" y="0" width="88" height="88" fill="url(#dt)"/><rect x="616" y="0" width="88" height="88" fill="#e4e4e7"/><rect x="616" y="0" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="704.5" y="0.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="-88" y="88" width="88" height="88" fill="url(#dt)"/><rect x="176.5" y="88.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="792.5" y="88.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="880" y="88" width="88" height="88" fill="url(#dt)"/><rect x="968" y="88" width="88" height="88" fill="url(#dt)"/><rect x="1056.5" y="88.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="264.5" y="176.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="-87.5" y="264.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="88" y="352" width="88" height="88" fill="#e4e4e7"/><rect x="88" y="352" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="352" y="352" width="88" height="88" fill="#e4e4e7"/><rect x="352" y="352" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="968.5" y="352.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="-87.5" y="440.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="528.5" y="440.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="880.5" y="440.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="0" y="528" width="88" height="88" fill="url(#dt)"/><rect x="264.5" y="528.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="-87.5" y="616.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="352" y="616" width="88" height="88" fill="url(#dt)"/><rect x="440" y="616" width="88" height="88" fill="url(#dt)"/><rect x="528" y="616" width="88" height="88" fill="#e4e4e7"/><rect x="528" y="616" width="88" height="88" fill="#71717a" opacity="0.22" filter="url(#gr)"/><rect x="704.5" y="616.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="792.5" y="616.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="968.5" y="616.5" width="87" height="87" fill="none" stroke="#ececef" stroke-width="1"/><rect x="180" y="38" width="860" height="330" fill="#ffffff" filter="url(#sh)"/><rect x="180" y="38" width="860" height="330" fill="#ffffff"/><g transform="translate(180 38)"><g clip-path="url(#c1)"><rect x="24" y="33" width="10" height="10" fill="#71717a"/><text x="46" y="44.3" font-size="18" fill="#18181b" font-weight="500">Sellers</text><line x1="145.6" y1="20" x2="145.6" y2="56" stroke="#e4e4e7" stroke-width="1"/><text x="177.6" y="44" font-size="17" fill="#18181b">All</text><rect x="159.6" y="73" width="66.6" height="3" fill="#18181b"/><text x="248.2" y="44" font-size="17" fill="#71717a">Pending approval</text><text x="836" y="43.3" font-size="15" fill="#a1a1aa" text-anchor="end">/admin/sellers</text><line x1="0" y1="76" x2="860" y2="76" stroke="#e4e4e7" stroke-width="1"/><text x="32" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2">SELLER</text><text x="292" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2">MEMBERS</text><text x="612" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2" text-anchor="end">OFFERS</text><text x="828" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2" text-anchor="end">STATUS</text><line x1="0" y1="130" x2="860" y2="130" stroke="#ededf0" stroke-width="1"/><text x="32" y="167.6" font-size="16" fill="#18181b">ACME</text><text x="292" y="167.6" font-size="16" fill="#18181b">3</text><text x="612" y="167.6" font-size="16" fill="#18181b" text-anchor="end">128</text><rect x="745.6" y="146" width="82.4" height="32" fill="#f4f4f5"/><rect x="757.6" y="157" width="10" height="10" fill="#3f7d3a"/><text x="779.6" y="166.9" font-size="14" fill="#3f3f46" letter-spacing="1.2">OPEN</text><line x1="0" y1="194" x2="860" y2="194" stroke="#ededf0" stroke-width="1"/><text x="32" y="231.6" font-size="16" fill="#18181b">GLOBEX</text><text x="292" y="231.6" font-size="16" fill="#18181b">1</text><text x="612" y="231.6" font-size="16" fill="#18181b" text-anchor="end">41</text><rect x="745.6" y="210" width="82.4" height="32" fill="#f4f4f5"/><rect x="757.6" y="221" width="10" height="10" fill="#3f7d3a"/><text x="779.6" y="230.9" font-size="14" fill="#3f3f46" letter-spacing="1.2">OPEN</text><line x1="0" y1="258" x2="860" y2="258" stroke="#ededf0" stroke-width="1"/><text x="32" y="295.6" font-size="16" fill="#18181b">INITECH</text><text x="292" y="295.6" font-size="16" fill="#18181b">2</text><text x="612" y="295.6" font-size="16" fill="#71717a" text-anchor="end">0</text><rect x="716.8" y="274" width="111.2" height="32" fill="#f4f4f5"/><rect x="728.8" y="285" width="10" height="10" fill="#c2680c"/><text x="750.8" y="294.9" font-size="14" fill="#3f3f46" letter-spacing="1.2">PENDING</text><line x1="0" y1="322" x2="860" y2="322" stroke="#ededf0" stroke-width="1"/></g></g><rect x="180.5" y="38.5" width="859" height="329" fill="none" stroke="#e4e4e7" stroke-width="1"/><rect x="110" y="114" width="860" height="330" fill="#ffffff" filter="url(#sh)"/><rect x="110" y="114" width="860" height="330" fill="#ffffff"/><g transform="translate(110 114)"><g clip-path="url(#c2)"><rect x="24" y="33" width="10" height="10" fill="#71717a"/><text x="46" y="44.3" font-size="18" fill="#18181b" font-weight="500">Offers</text><line x1="134.8" y1="20" x2="134.8" y2="56" stroke="#e4e4e7" stroke-width="1"/><text x="166.8" y="44" font-size="17" fill="#18181b">All</text><rect x="148.8" y="73" width="66.6" height="3" fill="#18181b"/><text x="237.4" y="44" font-size="17" fill="#71717a">Out of stock</text><text x="836" y="43.3" font-size="15" fill="#a1a1aa" text-anchor="end">/vendor/offers · ACME</text><line x1="0" y1="76" x2="860" y2="76" stroke="#e4e4e7" stroke-width="1"/><text x="32" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2">PRODUCT</text><text x="332" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2">SKU</text><text x="692" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2" text-anchor="end">PRICE</text><text x="828" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2" text-anchor="end">STOCK</text><line x1="0" y1="130" x2="860" y2="130" stroke="#ededf0" stroke-width="1"/><text x="32" y="167.6" font-size="16" fill="#18181b">Linen shirt / M</text><text x="332" y="167.6" font-size="16" fill="#18181b">ACME-LS-M</text><text x="692" y="167.6" font-size="16" fill="#18181b" text-anchor="end">€ 47.00</text><text x="828" y="167.6" font-size="16" fill="#18181b" text-anchor="end">50</text><line x1="0" y1="194" x2="860" y2="194" stroke="#ededf0" stroke-width="1"/><text x="32" y="231.6" font-size="16" fill="#18181b">Linen shirt / L</text><text x="332" y="231.6" font-size="16" fill="#18181b">ACME-LS-L</text><text x="692" y="231.6" font-size="16" fill="#18181b" text-anchor="end">€ 47.00</text><text x="828" y="231.6" font-size="16" fill="#18181b" text-anchor="end">18</text><line x1="0" y1="258" x2="860" y2="258" stroke="#ededf0" stroke-width="1"/><text x="32" y="295.6" font-size="16" fill="#18181b">Wool scarf</text><text x="332" y="295.6" font-size="16" fill="#18181b">ACME-WS-1</text><text x="692" y="295.6" font-size="16" fill="#18181b" text-anchor="end">€ 29.00</text><text x="828" y="295.6" font-size="16" fill="#71717a" text-anchor="end">0</text><line x1="0" y1="322" x2="860" y2="322" stroke="#ededf0" stroke-width="1"/></g></g><rect x="110.5" y="114.5" width="859" height="329" fill="none" stroke="#e4e4e7" stroke-width="1"/><rect x="40" y="190" width="860" height="330" fill="#ffffff" filter="url(#sh)"/><rect x="40" y="190" width="860" height="330" fill="#ffffff"/><g transform="translate(40 190)"><g clip-path="url(#c3)"><rect x="24" y="33" width="10" height="10" fill="#7c3aed"/><text x="46" y="44.3" font-size="18" fill="#18181b" font-weight="500">Linen shirt</text><line x1="188.8" y1="20" x2="188.8" y2="56" stroke="#e4e4e7" stroke-width="1"/><text x="220.8" y="44" font-size="17" fill="#18181b">M</text><rect x="202.8" y="73" width="46.2" height="3" fill="#18181b"/><text x="836" y="43.3" font-size="15" fill="#a1a1aa" text-anchor="end">/store/products/linen-shirt</text><line x1="0" y1="76" x2="860" y2="76" stroke="#e4e4e7" stroke-width="1"/><text x="32" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2">SOLD BY</text><text x="312" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2">SHIPS IN</text><text x="632" y="107.9" font-size="14" fill="#71717a" letter-spacing="1.2" text-anchor="end">PRICE</text><line x1="0" y1="130" x2="860" y2="130" stroke="#ededf0" stroke-width="1"/><rect x="0" y="130" width="3" height="64" fill="#7c3aed"/><text x="32" y="167.6" font-size="16" fill="#18181b">ACME</text><text x="312" y="167.6" font-size="16" fill="#18181b">2 days</text><text x="632" y="167.6" font-size="16" fill="#18181b" text-anchor="end">€ 47.00</text><rect x="672" y="147" width="123" height="30" fill="#f4f4f5"/><text x="684" y="167.3" font-size="15" fill="#71717a">Add to cart</text><line x1="0" y1="194" x2="860" y2="194" stroke="#ededf0" stroke-width="1"/><text x="32" y="231.6" font-size="16" fill="#18181b">GLOBEX</text><text x="312" y="231.6" font-size="16" fill="#18181b">4 days</text><text x="632" y="231.6" font-size="16" fill="#18181b" text-anchor="end">€ 45.00</text><rect x="672" y="211" width="123" height="30" fill="#f4f4f5"/><text x="684" y="231.3" font-size="15" fill="#71717a">Add to cart</text><line x1="0" y1="258" x2="860" y2="258" stroke="#ededf0" stroke-width="1"/><text x="32" y="295.6" font-size="16" fill="#18181b">INITECH</text><text x="312" y="295.6" font-size="16" fill="#18181b">1 day</text><text x="632" y="295.6" font-size="16" fill="#18181b" text-anchor="end">€ 49.00</text><rect x="672" y="275" width="123" height="30" fill="#f4f4f5"/><text x="684" y="295.3" font-size="15" fill="#71717a">Add to cart</text><line x1="0" y1="322" x2="860" y2="322" stroke="#ededf0" stroke-width="1"/></g></g><rect x="40.5" y="190.5" width="859" height="329" fill="none" stroke="#e4e4e7" stroke-width="1"/>+</svg>\ No newline at end of filediff --git a/apps/docs/learn/use-cases.mdx b/apps/docs/learn/use-cases.mdxnew file mode 100644index 000000000..828839265--- /dev/null+++ b/apps/docs/learn/use-cases.mdx@@ -0,0 +1,70 @@+---+title: "Use cases"+sidebarTitle: "Use cases"+description: "Two ways to run Mercur: as the whole marketplace, with its own storefront, admin and vendor panels, or as the marketplace layer inside a store you already run, selling seller offers next to your own products."+---++Mercur fits two kinds of business. Pick the one that matches yours; the modules underneath are the same.++<Tabs>+ <Tab title="Marketplace platform">+ You are building a marketplace from scratch, or replacing one. Mercur runs everything: the storefront, the operator admin, the vendor panel sellers log into, and the backend that splits every checkout into one order per seller, computes commissions and pays sellers out.++ <img className="block dark:hidden" src="/images/figures/use-case-platform-light.svg" alt="Three Mercur surfaces stacked back to front: the admin Sellers list, the vendor panel's Offers table for ACME, and the storefront product page for the Linen shirt listing the offers a shopper can buy." />+ <img className="hidden dark:block" src="/images/figures/use-case-platform-dark.svg" alt="Three Mercur surfaces stacked back to front: the admin Sellers list, the vendor panel's Offers table for ACME, and the storefront product page for the Linen shirt listing the offers a shopper can buy." />++ **Pick this when**++ - You don't have a store yet, or you want the marketplace to be the product+ - Sellers should get their own panel: offers, orders, fulfillment, payouts+ - You want one shared catalog that every seller lists against++ **What you get**++ | Surface | Who uses it | Package |+ | --- | --- | --- |+ | Storefront | Shoppers | Any framework on the Store API, or the starter storefront |+ | Admin panel | Operators | `@mercurjs/admin` |+ | Vendor panel | Sellers | `@mercurjs/vendor` |+ | Backend | Everyone | `@mercurjs/core` on Medusa |++ <CardGroup cols={2}>+ <Card title="Install Mercur" icon="rocket" href="/learn/introduction">+ Create a marketplace project and run it locally.+ </Card>+ <Card title="Architecture" icon="sitemap" href="/learn/architecture">+ How the panels, the API and the modules fit together.+ </Card>+ </CardGroup>+ </Tab>+ <Tab title="Marketplace inside your store">+ You already sell your own products on a platform like Magento. You want third-party sellers next to them, in the same product page and the same checkout, without moving your catalog or your payments. Your store stays the storefront; Mercur becomes the marketplace layer behind it.++ <img className="block dark:hidden" src="/images/figures/use-case-hybrid-light.svg" alt="A product page in your own store lists your warehouse next to two seller offers from ACME and GLOBEX. A wire leads from the seller rows to a Mercur order group with one order per seller; your own line never leaves your store." />+ <img className="hidden dark:block" src="/images/figures/use-case-hybrid-dark.svg" alt="A product page in your own store lists your warehouse next to two seller offers from ACME and GLOBEX. A wire leads from the seller rows to a Mercur order group with one order per seller; your own line never leaves your store." />++ **Pick this when**++ - Your store, checkout and payment provider are already live and should stay+ - You sell first-party stock and want sellers to compete on the same SKUs+ - Sellers need a panel, but shoppers should never notice a second system++ **Who runs what**++ | Concern | Your store | Mercur |+ | --- | --- | --- |+ | Catalog, prices, stock of your own products | ✔ | |+ | Storefront, cart, checkout, payment capture | ✔ | |+ | Sellers, their offers, their panel | | ✔ |+ | One order per seller, commissions, payouts | | ✔ |++ <CardGroup cols={2}>+ <Card title="Magento 2 integration" icon="store" href="/resources/integrations/magento2">+ Install the connector and run a mixed first-party and seller order.+ </Card>+ <Card title="Order Group module" icon="layer-group" href="/platform/order-group/overview">+ How one checkout becomes one order per seller.+ </Card>+ </CardGroup>+ </Tab>+</Tabs>diff --git a/apps/docs/references/api/conventions.mdx b/apps/docs/references/api/conventions.mdxindex c3b5af1ab..32ba22756 100644--- a/apps/docs/references/api/conventions.mdx+++ b/apps/docs/references/api/conventions.mdx@@ -35,6 +35,26 @@ A handful of vendor routes are public by design: seller registration (`POST /venStore routes are public. Customer authentication (session or bearer) is **required** for `/store/order-groups` and **optional** for `/store/offers` and `/store/products`, where it enriches the pricing context when present. Public seller routes only return sellers whose status is `open` and who are not inside a scheduled closure window.+### With the client++`@mercurjs/client` carries the credential for you. Pass `auth` once and every request resolves it fresh, so a token stored after login is picked up by the next call:++```typescript+import { createClient, adminAuth, vendorAuth, apiKeyAuth, publishableKeyAuth } from "@mercurjs/client"++// inside the admin or vendor panel, or a plugin's dashboard code+const admin = createClient({ baseUrl, auth: adminAuth() })+const vendor = createClient({ baseUrl, auth: vendorAuth() })++// a server-side integration with a secret API key+const integration = createClient({ baseUrl, auth: apiKeyAuth(() => process.env.MERCUR_API_KEY) })++// a storefront+const store = createClient({ baseUrl, auth: publishableKeyAuth(() => publishableKey) })+```++`adminAuth()` and `vendorAuth()` read the same token stores the panels write on login (`adminTokenStore`, `vendorTokenStore`, `vendorSellerStore`), so dashboard extensions share the user's session without knowing a storage key. `createTokenStore(key)` builds your own store, falling back to memory where `localStorage` is unavailable. A `401` clears the bearer store unless you pass `onUnauthorized`.+## PaginationList endpoints use offset pagination with two query parameters:diff --git a/apps/docs/resources/integrations/magento2.mdx b/apps/docs/resources/integrations/magento2.mdxnew file mode 100644index 000000000..aff212f6a--- /dev/null+++ b/apps/docs/resources/integrations/magento2.mdx@@ -0,0 +1,162 @@+---+title: "Magento 2 marketplace integration"+sidebarTitle: "Magento 2"+description: "Turn your Magento 2 or Adobe Commerce store into a multi-vendor marketplace with Mercur. Install the connector, sync seller offers, and split each order per seller."+---++The Magento 2 connector lets a store you already run sell marketplace offers next to its own catalog. Magento keeps the storefront, cart, checkout, payment capture and your first-party products. Mercur keeps sellers, their offers, the split of one checkout into one order per seller, commission lines and payouts.++The integration has two halves:++- **`@mercurjs/magento2-connector-plugin`**, a plugin for your Mercur API that adds outbound webhooks, an external payment provider and a few admin routes+- **`mercurjs/magento2-connector`**, a Composer package of Magento modules that mirrors sellers and offers into Magento and talks to Mercur during checkout++<Tip>+ This page is the setup guide. The connector's source, module layout and development workflow live in the [magento2-connector repository](https://github.com/mercurjs/magento2-connector).+</Tip>++## Quick start++<Steps>+ <Step title="Install the plugin in Mercur">+ Add the plugin and register its payment provider in `medusa-config.ts`:++ ```ts+ module.exports = withMercur({+ plugins: [+ { resolve: "@mercurjs/magento2-connector-plugin", options: {} },+ ],+ modules: [+ {+ resolve: "@medusajs/medusa/payment",+ options: {+ providers: [+ {+ resolve: "@mercurjs/magento2-connector-plugin/providers/payment-external",+ id: "external",+ },+ ],+ },+ },+ ],+ })+ ```++ Run `medusa db:migrate` afterwards. The provider is registered as `pp_external_external`; it records a payment Magento already captured instead of charging anyone.++ Then enable it for the region your Magento website sells in: open the region in the Mercur admin and add **pp_external_external** to its payment providers. The shadow cart cannot complete without it.+ </Step>+ <Step title="Install the Magento package">+ In your Magento root. The package is installed from its Git repository until it is published to Packagist, so add the repository first:++ ```bash+ composer config repositories.mercur vcs https://github.com/mercurjs/magento2-connector+ composer require mercurjs/magento2-connector:dev-main+ bin/magento module:enable Mercur_Core Mercur_Process Mercur_Connector \+ Mercur_OfferIndexer Mercur_Catalog Mercur_Settlement Mercur_Frontend Mercur_GraphQl+ # Only on stores that run Multi-Source Inventory:+ bin/magento module:enable Mercur_Inventory+ bin/magento setup:upgrade+ bin/magento setup:di:compile+ bin/magento cache:flush+ ```+ </Step>+ <Step title="Get API details">+ You need four values from Mercur:++ - **Admin API key**: create a secret API key under **Settings → API keys**. If your deployment runs a roles module, bind it to a role that holds only the `integrations` permission; without one the key has full admin access, so treat it like an admin password+ - **Publishable API key**: the publishable key of the sales channel the shadow cart is created in+ - **Sales channel ID** and **Region ID**: the channel and the region whose prices the Magento website shows, one region per website+ </Step>+ <Step title="Connect Magento">+ In Magento open **Stores → Configuration → Mercur → Marketplace** and enter the API URL and the four values above. Choose a best offer rule: lowest price, your own stock first, or premium sellers first.+ </Step>+ <Step title="Register the webhook">+ In the Mercur admin open **Settings → Magento → Add endpoint**, enter `https://your_shop_domain/mercur/webhook`, keep every event selected, and copy the signing secret. The connector needs the fulfillment, shipment, delivery, return and refund events to keep orders in step. It is shown once. Paste it into the Magento configuration under **Webhooks → Signing secret**.+ </Step>+ <Step title="Run the first sync">+ Push your taxonomy, then mirror everything:++ ```bash+ bin/magento mercur:sync taxonomy+ bin/magento mercur:sync full+ ```++ Cron keeps the mirror current afterwards: sellers every 15 minutes, offers every 5 minutes, published products hourly, a full resync every night. Each run is a process under **Mercur → Processes** in the Magento admin.+ </Step>+</Steps>++## How a mixed order flows++A shopper buys one of your own products and one seller offer in the same checkout and pays once:++1. The product page lists every active seller offer next to your own stock, with its price for that website, any price list strike-through, quantity tiers and an estimated delivery date. Adding an offer marks the cart line as a marketplace line priced by the offer and labels it "Sold by" the seller. The same works through REST and GraphQL with `mercur_offer_id`.+2. The cart and the checkout group the marketplace lines by seller. Magento copies them into a shadow Mercur cart, asks Mercur for each seller's shipping options and lets the shopper pick one per seller; the sum is the "Seller shipping" total. Your own carriers only price your own lines, and a cart of seller lines only gets the "Shipped by the sellers" method.+3. The shopper pays in Magento. The invoice includes seller shipping.+4. After the order is placed, Magento records the capture on the external payment provider and completes the Mercur cart. Mercur answers with an order group, one order per seller, and Magento stores those ids on the order and its lines.+5. Sellers fulfill in the vendor panel. Each shipped fulfillment becomes its own Magento shipment with its tracking numbers, so partial and multi-parcel deliveries show up as they happen. Deliveries, returns and cancellations update the line's marketplace status, shown to the shopper in their account and to you in the admin.+6. Mercur computes commission lines when the cart completes and pays sellers from the recorded capture.++If Mercur is unreachable at step 4, the Magento order still succeeds and the `order_retry` process completes the Mercur side on its next run.++## Refunds++| Starts in | What happens |+| --- | --- |+| Magento | A credit memo on marketplace lines is reported to Mercur per seller order, with seller shipping split by what each seller charged, so commission lines and payout balances follow |+| Mercur, a seller or operator refund | Mercur sends `order.refund_requested`; Magento creates an adjustment credit memo and refunds the shopper online when the invoice was captured online |+| Mercur, a canceled seller order | Magento refunds that seller's lines and shipping |++A `refunds` process every 15 minutes picks up any refund whose webhook did not arrive.++## Essential practices++### One region per website++Offer prices are read for the region configured on each Magento website, including Mercur price lists. A store with a US and an EU website needs two Mercur regions and two website-scoped values of **Mercur region ID**, and each website's base currency must match its region's currency.++### Set delivery estimates++Under **Mercur → Marketplace → Delivery estimates** set the order cut-off time, business days and transit days for each website. A Mercur shipping option can carry its own `transit_days_min` and `transit_days_max` in its data.++### Keep the operator's stock as a candidate++Your own product is always one of the ways to buy a SKU. The best offer rule decides whether it wins over a cheaper seller; `operator_first` keeps your stock on top whenever it is in stock.++### Let webhooks drive, keep cron as the floor++Offer, seller and product events enqueue the matching delta sync within a minute. The cron schedules exist so the mirror heals after a missed delivery; a full nightly resync removes anything a delta could not see.++## Your products or seller offers++| Situation | What happens |+| --- | --- |+| A product only you sell | A normal Magento line: your price, your stock, your carriers |+| A product only sellers sell | Imported from Mercur, as a configurable product when its variant axes are Magento attributes; it is in stock while an offer is available and every line is a marketplace line |+| A product both you and sellers sell | Same SKU, one buy box; the best offer rule picks the default and the shopper can choose another. When you run out, the product stays buyable from sellers |++Each seller has a page at `/seller/{handle}` listing what they sell on your store. In the Magento admin, **Mercur → Sellers** and **Mercur → Offers** show the mirror, orders show each seller order with its status, and the product page lists the offers for that SKU.++## Not supported yet++- Buyer and seller messaging, order incidents and seller ratings+- Documents sellers attach to orders+- A third-party tax engine for seller lines; Magento taxes them with the product's tax class+- Mercur promotions; Magento cart rules still apply to seller lines++## Next steps++<CardGroup cols={2}>+ <Card title="Connector repository" icon="github" href="https://github.com/mercurjs/magento2-connector">+ Modules, development workflow, and the webhook handler registry.+ </Card>+ <Card title="Offer module" icon="tag" href="/platform/offer/overview">+ How offers carry seller SKU, price, inventory and shipping.+ </Card>+ <Card title="Order Group module" icon="layer-group" href="/platform/order-group/overview">+ How one checkout becomes one order per seller.+ </Card>+ <Card title="Commission module" icon="percent" href="/platform/commission/overview">+ How commission lines are computed at completion.+ </Card>+</CardGroup>diff --git a/apps/docs/resources/integrations/overview.mdx b/apps/docs/resources/integrations/overview.mdxindex ec7e0d4a8..02273e8a2 100644--- a/apps/docs/resources/integrations/overview.mdx+++ b/apps/docs/resources/integrations/overview.mdx@@ -23,6 +23,16 @@ interface.</Card></CardGroup>+## Storefront platforms++A storefront you already run can sell marketplace offers next to its own catalog. Mercur keeps sellers, offers, split orders, commissions and payouts; the platform keeps checkout and payment.++<CardGroup cols={2}>+ <Card title="Magento 2" icon="store" href="/resources/integrations/magento2">+ Set up the Magento 2 connector.+ </Card>+</CardGroup>+## BlocksOther integrations ship as installable blocks. You add the block, own its sourcediff --git a/apps/docs/resources/tutorials/custom-api-route.mdx b/apps/docs/resources/tutorials/custom-api-route.mdxindex 331d25221..3718302d6 100644--- a/apps/docs/resources/tutorials/custom-api-route.mdx+++ b/apps/docs/resources/tutorials/custom-api-route.mdx@@ -54,14 +54,15 @@ A `GET /vendor/sales-summary` endpoint returns the seller's order count. You calCodegen rewrites the generated `Routes` type that your panel apps already import:```typescript apps/vendor/src/lib/client.ts- import { createClient, type InferClient } from "@mercurjs/client"+ import { createClient, vendorAuth, type InferClient } from "@mercurjs/client"import type { Routes } from "@acme/api/_generated"declare const __BACKEND_URL__: stringexport const client: InferClient<Routes> = createClient({baseUrl: __BACKEND_URL__,- fetchOptions: { credentials: "include" },+ fetchOptions: { credentials: "omit" },+ auth: vendorAuth(),})```diff --git a/bun.lock b/bun.lockindex 90117c584..558521a4c 100644--- a/bun.lock+++ b/bun.lock@@ -261,6 +261,7 @@"@medusajs/framework": "2.22.0","@medusajs/medusa": "2.22.0","@mercurjs/core": "*",+ "@mercurjs/magento2-connector-plugin": "*","jsonwebtoken": "^9.0.3","meilisearch": "^0.59.0","scrypt-kdf": "^2.0.1",@@ -390,6 +391,7 @@"@types/qs": "^6.9.18","tsup": "^8.5.0","typescript": "5.9.3",+ "vitest": "^3.2.4",},"peerDependencies": {"typescript": ">=4.8.0",@@ -567,6 +569,57 @@"name": "@mercurjs/docs","version": "2.3.8",},+ "packages/plugins/magento2-connector": {+ "name": "@mercurjs/magento2-connector-plugin",+ "version": "2.3.8",+ "dependencies": {+ "zod": "4.6.5",+ },+ "devDependencies": {+ "@hookform/resolvers": "5.4.0",+ "@medusajs/cli": "2.22.0",+ "@medusajs/core-flows": "2.22.0",+ "@medusajs/framework": "2.22.0",+ "@medusajs/icons": "2.22.0",+ "@medusajs/medusa": "2.22.0",+ "@medusajs/types": "2.22.0",+ "@medusajs/ui": "4.2.3",+ "@mercurjs/cli": "2.3.8",+ "@mercurjs/client": "2.3.8",+ "@mercurjs/core": "2.3.8",+ "@mercurjs/dashboard-sdk": "2.3.8",+ "@mercurjs/dashboard-shared": "2.3.8",+ "@mercurjs/types": "2.3.8",+ "@tanstack/react-query": "5.64.2",+ "@tanstack/react-table": "8.21.3",+ "@types/node": "^26.1.0",+ "@types/react": "^18.3.2",+ "radix-ui": "1.1.2",+ "react": "^18.3.1",+ "react-dom": "^18.3.1",+ "react-hook-form": "7.88.0",+ "react-router-dom": "7.18.1",+ "typescript": "5.9.3",+ },+ "peerDependencies": {+ "@hookform/resolvers": "^5.4.0",+ "@medusajs/core-flows": ">=2.22.0",+ "@medusajs/framework": ">=2.22.0",+ "@medusajs/icons": ">=2.22.0",+ "@medusajs/medusa": ">=2.22.0",+ "@medusajs/ui": ">=4.1.19",+ "@mercurjs/client": ">=2.3.8",+ "@mercurjs/core": "*",+ "@mercurjs/dashboard-sdk": ">=2.3.8",+ "@mercurjs/dashboard-shared": ">=2.3.8",+ "@tanstack/react-query": "^5.64.2",+ "@tanstack/react-table": "^8.20.5",+ "react": "^18.0.0",+ "react-dom": "^18.0.0",+ "react-hook-form": "^7.49.1",+ "react-router-dom": "^7.0.0",+ },+ },"packages/providers/payout-stripe-connect": {"name": "@mercurjs/payout-stripe-connect","version": "2.3.8",@@ -1554,6 +1607,8 @@"@mercurjs/integration-tests": ["@mercurjs/integration-tests@workspace:integration-tests"],+ "@mercurjs/magento2-connector-plugin": ["@mercurjs/magento2-connector-plugin@workspace:packages/plugins/magento2-connector"],+"@mercurjs/payout-stripe-connect": ["@mercurjs/payout-stripe-connect@workspace:packages/providers/payout-stripe-connect"],"@mercurjs/registry": ["@mercurjs/registry@workspace:packages/registry"],@@ -2252,10 +2307,14 @@"@types/body-parser": ["@types/[email protected]", "", { "dependencies": { "@types/connect": "*", "@types/node": "*" } }, "sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g=="],+ "@types/chai": ["@types/[email protected]", "", { "dependencies": { "@types/deep-eql": "*", "assertion-error": "^2.0.1" } }, "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA=="],+"@types/connect": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug=="],"@types/cors": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg=="],+ "@types/deep-eql": ["@types/[email protected]", "", {}, "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw=="],+"@types/doctrine": ["@types/[email protected]", "", {}, "sha512-eOIHzCUSH7SMfonMG1LsC2f8vxBFtho6NGBznK41R84YzPuvSBzrhEps33IsQiOW9+VL6NQ9DbjQJznk/S4uRA=="],"@types/esrecurse": ["@types/[email protected]", "", {}, "sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw=="],@@ -2476,13 +2535,19 @@"@vitejs/plugin-react": ["@vitejs/[email protected]", "", { "dependencies": { "@rolldown/pluginutils": "^1.0.1" }, "peerDependencies": { "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0", "babel-plugin-react-compiler": "^1.0.0", "vite": "^8.0.0" }, "optionalPeers": ["@rolldown/plugin-babel", "babel-plugin-react-compiler"] }, "sha512-vmFvco5/QuC2f9Oj+wTk0+9XeDFkHxSamwZKYc7MxYwKICfvUvlMhqKI0VuICPltGqh1neqBKDvO4kes1ya8vg=="],- "@vitest/expect": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/spy": "2.0.5", "@vitest/utils": "2.0.5", "chai": "^5.1.1", "tinyrainbow": "^1.2.0" } }, "sha512-yHZtwuP7JZivj65Gxoi8upUN2OzHTi3zVfjwdpu2WrvCZPLwsJ2Ey5ILIPccoW23dd/zQBlJ4/dhi7DWNyXCpA=="],+ "@vitest/expect": ["@vitest/[email protected]", "", { "dependencies": { "@types/chai": "^5.2.2", "@vitest/spy": "3.2.7", "@vitest/utils": "3.2.7", "chai": "^5.2.0", "tinyrainbow": "^2.0.0" } }, "sha512-E8eBXaKibuvH2pSZErOjdVb5vF4PbKYcrnluBTYxEk1l/VhhwZg1kZQsdtjq+CsF5CFydf2Rdkz7jDHKSisi3w=="],- "@vitest/pretty-format": ["@vitest/[email protected]", "", { "dependencies": { "tinyrainbow": "^1.2.0" } }, "sha512-KhRIdGV2U9HOUzxfiHmY8IFHTdqtOhIzCpd8WRdJiE7D/HUcZVD0EgQCVjm+Q9gkUXWgBvMmTtZgIG48wq7sOQ=="],+ "@vitest/mocker": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/spy": "3.2.7", "estree-walker": "^3.0.3", "magic-string": "^0.30.17" }, "peerDependencies": { "msw": "^2.4.9", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" }, "optionalPeers": ["msw", "vite"] }, "sha512-Trr0hYO9CM3Wj6ksWHRhK9IZpIY6wTMO5u/MqXurMxT57sWBaOPEtP3Oq60ihZuh5JsiagKfz95OcxdEP6dBrA=="],- "@vitest/spy": ["@vitest/[email protected]", "", { "dependencies": { "tinyspy": "^3.0.0" } }, "sha512-c/jdthAhvJdpfVuaexSrnawxZz6pywlTPe84LUB2m/4t3rl2fTo9NFGBG4oWgaD+FTgDDV8hJ/nibT7IfH3JfA=="],+ "@vitest/pretty-format": ["@vitest/[email protected]", "", { "dependencies": { "tinyrainbow": "^2.0.0" } }, "sha512-KUHlwqVu0sRlhCdyPdQ/wBoTfRahjUky1MubOmYw9fWfIZy1gNoHpuaaQBPAaMaVYdQYHJLurzj8ECCj5OwTqA=="],- "@vitest/utils": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/pretty-format": "2.1.9", "loupe": "^3.1.2", "tinyrainbow": "^1.2.0" } }, "sha512-v0psaMSkNJ3A2NMrUEHFRzJtDPFn+/VWZ5WxImB21T9fjucJRmS7xCS3ppEnARb9y11OAzaD+P2Ps+b+BGX5iQ=="],+ "@vitest/runner": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/utils": "3.2.7", "pathe": "^2.0.3", "strip-literal": "^3.0.0" } }, "sha512-sB9y4ovltoQP+WaUPwmSxO9WIg9Ig694Di5PalVPsYHklAdE027mehpWF2SQSVq+k6sFgaivbTjTJwZLSHbedA=="],++ "@vitest/snapshot": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/pretty-format": "3.2.7", "magic-string": "^0.30.17", "pathe": "^2.0.3" } }, "sha512-7C+MwShwtBSI5Buwoyg3s/iY1eHL9PKAf+O1wVh/TdnjXUtkoL/9YQtre90i4MtNXM6edP1wJ2zOBpfCyhIS7g=="],++ "@vitest/spy": ["@vitest/[email protected]", "", { "dependencies": { "tinyspy": "^4.0.3" } }, "sha512-Q2eQGI6d2L/hBtZ0qNuKcAGid68XK6cv1xsoaIma6PaJhHPoqcEJhYpXZ/5myCMqkNgtP6UKuBhbc0nHKnrkuQ=="],++ "@vitest/utils": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/pretty-format": "3.2.7", "loupe": "^3.1.4", "tinyrainbow": "^2.0.0" } }, "sha512-x6BDOd7dyo3PFLY3I9/HJ25X/6OurhGXk2/B9gOZNPF7XDVjeBK4k01lQE5uvDpbuheErh91qYuE1E2OEjK3Rw=="],"@webassemblyjs/ast": ["@webassemblyjs/[email protected]", "", { "dependencies": { "@webassemblyjs/helper-numbers": "1.13.2", "@webassemblyjs/helper-wasm-bytecode": "1.13.2" } }, "sha512-nuBEDgQfm1ccRp/8bCQrx1frohyufl4JlbMMZ4P1wpeOfDhF6FQkxZJ1b/e+PLwr6X1Nhw6OLme5usuBWYBvuQ=="],@@ -3138,6 +3203,8 @@"expect": ["[email protected]", "", { "dependencies": { "@jest/expect-utils": "30.4.1", "@jest/get-type": "30.1.0", "jest-matcher-utils": "30.4.1", "jest-message-util": "30.4.1", "jest-mock": "30.4.1", "jest-util": "30.4.1" } }, "sha512-PMARsyh/JtqC20HoGqlFcIlQAyqUtW4PlI1rup1uhYJtKuwAjbvWi3GQMAn+STdHum/dk8xrKfUM1+5SAwpolA=="],+ "expect-type": ["[email protected]", "", {}, "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA=="],+"express": ["[email protected]", "", { "dependencies": { "accepts": "~1.3.8", "array-flatten": "1.1.1", "body-parser": "~1.20.5", "content-disposition": "~0.5.4", "content-type": "~1.0.4", "cookie": "~0.7.1", "cookie-signature": "~1.0.6", "debug": "2.6.9", "depd": "2.0.0", "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "etag": "~1.8.1", "finalhandler": "~1.3.1", "fresh": "~0.5.2", "http-errors": "~2.0.0", "merge-descriptors": "1.0.3", "methods": "~1.1.2", "on-finished": "~2.4.1", "parseurl": "~1.3.3", "path-to-regexp": "~0.1.12", "proxy-addr": "~2.0.7", "qs": "~6.15.1", "range-parser": "~1.2.1", "safe-buffer": "5.2.1", "send": "~0.19.0", "serve-static": "~1.16.2", "setprototypeof": "1.2.0", "statuses": "~2.0.1", "type-is": "~1.6.18", "utils-merge": "1.0.1", "vary": "~1.1.2" } }, "sha512-IuL+Elrou2ZvCFHs18/CIzy2Nzvo25nZ1/D2eIZlz7c+QUayAcYoiM2BthCjs+EBHVpjYjcuLDAiCWgeIX3X1Q=="],"express-session": ["[email protected]", "", { "dependencies": { "cookie": "~0.7.2", "cookie-signature": "~1.0.7", "debug": "~2.6.9", "depd": "~2.0.0", "on-headers": "~1.1.0", "parseurl": "~1.3.3", "safe-buffer": "~5.2.1", "uid-safe": "~2.1.5" } }, "sha512-0csaMkGq+vaiZTmSMMGkfdCOabYv192VbytFypcvI0MANrp+4i/7yEkJ0sbAEhycQjntaKGzYfjfXQyVb7BHMA=="],@@ -4344,6 +4411,8 @@"side-channel-weakmap": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3", "side-channel-map": "^1.0.1" } }, "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A=="],+ "siginfo": ["[email protected]", "", {}, "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g=="],+"signal-exit": ["[email protected]", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="],"simple-swizzle": ["[email protected]", "", { "dependencies": { "is-arrayish": "^0.3.1" } }, "sha512-nAu1WFPQSMNr2Zn9PGSZK9AGn4t/y97lEm+MXTtUDwfP0ksAIX4nO+6ruD9Jwut4C49SB1Ws+fbXsm/yScWOHw=="],@@ -4380,12 +4449,16 @@"stack-utils": ["[email protected]", "", { "dependencies": { "escape-string-regexp": "^2.0.0" } }, "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ=="],+ "stackback": ["[email protected]", "", {}, "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw=="],+"stackframe": ["[email protected]", "", {}, "sha512-oeVtt7eWQS+Na6F//S4kJ2K2VbRlS9D43mAlMyVpVWovy9o+jfgH8O9agzANzaiLjclA0oYzUXEM4PurhSUChw=="],"standard-as-callback": ["[email protected]", "", {}, "sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A=="],"statuses": ["[email protected]", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],+ "std-env": ["[email protected]", "", {}, "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg=="],+"stdin-discarder": ["[email protected]", "", {}, "sha512-eCPu1qRxPVkl5605OTWF8Wz40b4Mf45NY5LQmVPQ599knfs5QhASUm9GbJ5BDMDOXgrnh0wyEdvzmL//YMlw0A=="],"stop-iteration-iterator": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "internal-slot": "^1.1.0" } }, "sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ=="],@@ -4432,6 +4505,8 @@"strip-json-comments": ["[email protected]", "", {}, "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig=="],+ "strip-literal": ["[email protected]", "", { "dependencies": { "js-tokens": "^9.0.1" } }, "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg=="],+"stripe": ["[email protected]", "", { "dependencies": { "@types/node": ">=8.1.0", "qs": "^6.11.0" } }, "sha512-slTbYS1WhRJXVB8YXU8fgHizkUrM9KJyrw4Dd8pLEwzKHYyQTIE46EePC2MVbSDZdE24o1GdNtzmJV4PrPpmJA=="],"strnum": ["[email protected]", "", {}, "sha512-ums3KNd42PGyx5xaoVTO1mjU1bH3NpY4vsrVlnv9PNGqQj8wd7rJ6nEypLrJ7z5vxK5RP0yMLo6J/Gsm62DI5Q=="],@@ -4490,13 +4565,17 @@"tiny-invariant": ["[email protected]", "", {}, "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg=="],+ "tinybench": ["[email protected]", "", {}, "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg=="],+"tinyexec": ["[email protected]", "", {}, "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA=="],"tinyglobby": ["[email protected]", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="],- "tinyrainbow": ["[email protected]", "", {}, "sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ=="],+ "tinypool": ["[email protected]", "", {}, "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg=="],++ "tinyrainbow": ["[email protected]", "", {}, "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw=="],- "tinyspy": ["[email protected]", "", {}, "sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q=="],+ "tinyspy": ["[email protected]", "", {}, "sha512-u8KszXvGfU68hVcZpRHKG28T0krMuv2G5nDhiHaMLen/gIuFEgIJhaJuO69qjnXg5paSrbPMFfx3brNuN8eVSg=="],"title-case": ["[email protected]", "", { "dependencies": { "tslib": "^2.0.3" } }, "sha512-e1zGYRvbffpcHIrnuqT0Dh+gEJtDaxDSoG4JAIpq4oDFyooziLBIiYQv0GBT4FUAnUop5uZ1hiIAj7oAF6sOCA=="],@@ -4638,6 +4717,10 @@"vite": ["[email protected]", "", { "dependencies": { "lightningcss": "^1.32.0", "picomatch": "^4.0.4", "postcss": "^8.5.16", "rolldown": "~1.1.3", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.3.0", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-Ds+gBRbj0lwRO2Y5hwnUBdxSwlAve9LeRyU4sNnAr0ewW0gWF0n5bgXgUzbgZ49MV9BVUAQUFYVcDUcilUExMA=="],+ "vite-node": ["[email protected]", "", { "dependencies": { "cac": "^6.7.14", "debug": "^4.4.1", "es-module-lexer": "^1.7.0", "pathe": "^2.0.3", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" }, "bin": { "vite-node": "vite-node.mjs" } }, "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg=="],++ "vitest": ["[email protected]", "", { "dependencies": { "@types/chai": "^5.2.2", "@vitest/expect": "3.2.7", "@vitest/mocker": "3.2.7", "@vitest/pretty-format": "^3.2.7", "@vitest/runner": "3.2.7", "@vitest/snapshot": "3.2.7", "@vitest/spy": "3.2.7", "@vitest/utils": "3.2.7", "chai": "^5.2.0", "debug": "^4.4.1", "expect-type": "^1.2.1", "magic-string": "^0.30.17", "pathe": "^2.0.3", "picomatch": "^4.0.2", "std-env": "^3.9.0", "tinybench": "^2.9.0", "tinyexec": "^0.3.2", "tinyglobby": "^0.2.14", "tinypool": "^1.1.1", "tinyrainbow": "^2.0.0", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0", "vite-node": "3.2.4", "why-is-node-running": "^2.3.0" }, "peerDependencies": { "@edge-runtime/vm": "*", "@types/debug": "^4.1.12", "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", "@vitest/browser": "3.2.7", "@vitest/ui": "3.2.7", "happy-dom": "*", "jsdom": "*" }, "optionalPeers": ["@edge-runtime/vm", "@types/debug", "@types/node", "@vitest/browser", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "./vitest.mjs" } }, "sha512-KrxIJ62Fd89gfysR4WotlgZABiz2dqFPgqGzX7s+CwsqLFomRH7777ZcrOD6+WVAh7khPQP41A+BKbpcJFrdEg=="],+"vm-browserify": ["[email protected]", "", {}, "sha512-2ham8XPWTONajOR0ohOKOHXkm3+gaBmGut3SRuu75xLd/RRaY6vqgh8NBYYk7+RW3u5AtzPQZG8F10LHkl0lAQ=="],"void-elements": ["[email protected]", "", {}, "sha512-Dhxzh5HZuiHQhbvTW9AMetFfBHDMYpo23Uo9btPXgdYP+3T5S+p+jgNy7spra+veYhBP2dCSgxR/i2Y02h5/6w=="],@@ -4680,6 +4763,8 @@"which-typed-array": ["[email protected]", "", { "dependencies": { "available-typed-arrays": "^1.0.7", "call-bind": "^1.0.9", "call-bound": "^1.0.4", "for-each": "^0.3.5", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-tostringtag": "^1.0.2" } }, "sha512-fvO4ExWMFsqyhG3AiPAObMuY1lxaqgYcxbc49CNdWDDECOJNgQyvsOWVwbZc+qf3rzRtxojBK+CMEv0Ld5CYpw=="],+ "why-is-node-running": ["[email protected]", "", { "dependencies": { "siginfo": "^2.0.0", "stackback": "0.0.2" }, "bin": { "why-is-node-running": "cli.js" } }, "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w=="],+"widest-line": ["[email protected]", "", { "dependencies": { "string-width": "^4.0.0" } }, "sha512-NsmoXalsWVDMGupxZ5R08ka9flZjjiLvHVAWYOKtiKM8ujtZWr9cRffak+uSE48+Ob8ObalXpwyeUiyDD6QFgg=="],"winston": ["[email protected]", "", { "dependencies": { "@colors/colors": "^1.6.0", "@dabh/diagnostics": "^2.0.8", "async": "^3.2.3", "is-stream": "^2.0.0", "logform": "^2.7.0", "one-time": "^1.0.0", "readable-stream": "^3.4.0", "safe-stable-stringify": "^2.3.1", "stack-trace": "0.0.x", "triple-beam": "^1.3.0", "winston-transport": "^4.9.0" } }, "sha512-LZNJgPzfKR+/J3cHkxcpHKpKKvGfDZVPS4hfJCc4cCG0CgYzvlD6yE/S3CIL/Yt91ak327YCpiF/0MyeZHEHKA=="],@@ -5294,6 +5379,8 @@"@storybook/csf/type-fest": ["[email protected]", "", {}, "sha512-RAH822pAdBgcNMAfWnCBU3CFZcfZ/i1eZjwFU/dsLKumyuuP3niueg2UAukXYF0E2AAoc82ZSSf9J0WQBinzHA=="],+ "@storybook/instrumenter/@vitest/utils": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/pretty-format": "2.1.9", "loupe": "^3.1.2", "tinyrainbow": "^1.2.0" } }, "sha512-v0psaMSkNJ3A2NMrUEHFRzJtDPFn+/VWZ5WxImB21T9fjucJRmS7xCS3ppEnARb9y11OAzaD+P2Ps+b+BGX5iQ=="],+"@storybook/nextjs/@babel/runtime": ["@babel/[email protected]", "", {}, "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw=="],"@storybook/react-docgen-typescript-plugin/find-cache-dir": ["[email protected]", "", { "dependencies": { "commondir": "^1.0.1", "make-dir": "^3.0.2", "pkg-dir": "^4.1.0" } }, "sha512-wXZV5emFEjrridIgED11OoUKLxiYjAcqot/NJdAkOhlJ+vGzwhOAfcG5OX1jP+S0PcjEn8bdMJv+g2jwQ3Onig=="],@@ -5304,6 +5391,10 @@"@storybook/test/@storybook/instrumenter": ["@storybook/[email protected]", "", { "dependencies": { "@storybook/global": "^5.0.0", "@vitest/utils": "^2.1.1" }, "peerDependencies": { "storybook": "^8.6.18" } }, "sha512-viEC1BGlYyjAzi1Tv3LZjByh7Y3Oh04u6QKsujxdeUbr5rUOH4pa/wCKmxXmY6yWrD4WjcNtojmUvQZN/66FXQ=="],+ "@storybook/test/@vitest/expect": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/spy": "2.0.5", "@vitest/utils": "2.0.5", "chai": "^5.1.1", "tinyrainbow": "^1.2.0" } }, "sha512-yHZtwuP7JZivj65Gxoi8upUN2OzHTi3zVfjwdpu2WrvCZPLwsJ2Ey5ILIPccoW23dd/zQBlJ4/dhi7DWNyXCpA=="],++ "@storybook/test/@vitest/spy": ["@vitest/[email protected]", "", { "dependencies": { "tinyspy": "^3.0.0" } }, "sha512-c/jdthAhvJdpfVuaexSrnawxZz6pywlTPe84LUB2m/4t3rl2fTo9NFGBG4oWgaD+FTgDDV8hJ/nibT7IfH3JfA=="],+"@swc/helpers/tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],"@testing-library/dom/@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="],@@ -5372,8 +5463,6 @@"@unrs/resolver-binding-wasm32-wasi/@napi-rs/wasm-runtime": ["@napi-rs/[email protected]", "", { "dependencies": { "@tybys/wasm-util": "^0.10.1" }, "peerDependencies": { "@emnapi/core": "^1.7.1", "@emnapi/runtime": "^1.7.1" } }, "sha512-3NQNNgA1YSlJb/kMH1ildASP9HW7/7kYnRI2szWJaofaS1hWmbGI4H+d3+22aGzXXN9IJ+n+GiFVcGipJP18ow=="],- "@vitest/expect/@vitest/utils": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/pretty-format": "2.0.5", "estree-walker": "^3.0.3", "loupe": "^3.1.1", "tinyrainbow": "^1.2.0" } }, "sha512-d8HKbqIcya+GR67mkZbrzhS5kKhtp8dQLcmRZLGTscGVg7yImT82cIrhtn2L8+VujWcy6KZweApgNmPsTAO/UQ=="],-"@whatwg-node/promise-helpers/tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],"accepts/negotiator": ["[email protected]", "", {}, "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg=="],@@ -5796,6 +5885,8 @@"strip-ansi-cjs/ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],+ "strip-literal/js-tokens": ["[email protected]", "", {}, "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ=="],+"stripe/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-GUUEShf+PBCGW2KaXwcIt3Yk+e3pkKwWKb9GSyM9WQVE+ep2jzmHdGsHzu4wgcZy5fN9FBdVzjpBQsYlpfpgLA=="],"sucrase/commander": ["[email protected]", "", {}, "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA=="],@@ -5846,6 +5937,10 @@"v8-to-istanbul/@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],+ "vite-node/vite": ["[email protected]", "", { "dependencies": { "esbuild": "^0.27.0 || ^0.28.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg=="],++ "vitest/vite": ["[email protected]", "", { "dependencies": { "esbuild": "^0.27.0 || ^0.28.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg=="],+"webpack/es-module-lexer": ["[email protected]", "", {}, "sha512-shc1dbU90Yl/xq1QrC7QRtfcwURZuVRfPhZbDoldJ1cn1gzDvBaBWlv0eFolj5+0znnPJz5TXLxsN77X/12KTA=="],"webpack/eslint-scope": ["[email protected]", "", { "dependencies": { "esrecurse": "^4.3.0", "estraverse": "^4.1.1" } }, "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw=="],@@ -6350,6 +6445,10 @@"@storybook/addon-docs/react-dom/scheduler": ["[email protected]", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],+ "@storybook/addon-interactions/@storybook/test/@vitest/expect": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/spy": "2.0.5", "@vitest/utils": "2.0.5", "chai": "^5.1.1", "tinyrainbow": "^1.2.0" } }, "sha512-yHZtwuP7JZivj65Gxoi8upUN2OzHTi3zVfjwdpu2WrvCZPLwsJ2Ey5ILIPccoW23dd/zQBlJ4/dhi7DWNyXCpA=="],++ "@storybook/addon-interactions/@storybook/test/@vitest/spy": ["@vitest/[email protected]", "", { "dependencies": { "tinyspy": "^3.0.0" } }, "sha512-c/jdthAhvJdpfVuaexSrnawxZz6pywlTPe84LUB2m/4t3rl2fTo9NFGBG4oWgaD+FTgDDV8hJ/nibT7IfH3JfA=="],+"@storybook/core/esbuild/@esbuild/aix-ppc64": ["@esbuild/[email protected]", "", { "os": "aix", "cpu": "ppc64" }, "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ=="],"@storybook/core/esbuild/@esbuild/android-arm": ["@esbuild/[email protected]", "", { "os": "android", "cpu": "arm" }, "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg=="],@@ -6396,8 +6495,20 @@"@storybook/core/esbuild/@esbuild/win32-x64": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw=="],+ "@storybook/instrumenter/@vitest/utils/@vitest/pretty-format": ["@vitest/[email protected]", "", { "dependencies": { "tinyrainbow": "^1.2.0" } }, "sha512-KhRIdGV2U9HOUzxfiHmY8IFHTdqtOhIzCpd8WRdJiE7D/HUcZVD0EgQCVjm+Q9gkUXWgBvMmTtZgIG48wq7sOQ=="],++ "@storybook/instrumenter/@vitest/utils/tinyrainbow": ["[email protected]", "", {}, "sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ=="],+"@storybook/react-docgen-typescript-plugin/find-cache-dir/pkg-dir": ["[email protected]", "", { "dependencies": { "find-up": "^4.0.0" } }, "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ=="],+ "@storybook/test/@storybook/instrumenter/@vitest/utils": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/pretty-format": "2.1.9", "loupe": "^3.1.2", "tinyrainbow": "^1.2.0" } }, "sha512-v0psaMSkNJ3A2NMrUEHFRzJtDPFn+/VWZ5WxImB21T9fjucJRmS7xCS3ppEnARb9y11OAzaD+P2Ps+b+BGX5iQ=="],++ "@storybook/test/@vitest/expect/@vitest/utils": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/pretty-format": "2.0.5", "estree-walker": "^3.0.3", "loupe": "^3.1.1", "tinyrainbow": "^1.2.0" } }, "sha512-d8HKbqIcya+GR67mkZbrzhS5kKhtp8dQLcmRZLGTscGVg7yImT82cIrhtn2L8+VujWcy6KZweApgNmPsTAO/UQ=="],++ "@storybook/test/@vitest/expect/tinyrainbow": ["[email protected]", "", {}, "sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ=="],++ "@storybook/test/@vitest/spy/tinyspy": ["[email protected]", "", {}, "sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q=="],+"@testing-library/dom/@babel/code-frame/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],"@testing-library/dom/pretty-format/ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],@@ -6462,8 +6573,6 @@"@unrs/resolver-binding-wasm32-wasi/@napi-rs/wasm-runtime/@tybys/wasm-util": ["@tybys/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg=="],- "@vitest/expect/@vitest/utils/@vitest/pretty-format": ["@vitest/[email protected]", "", { "dependencies": { "tinyrainbow": "^1.2.0" } }, "sha512-h8k+1oWHfwTkyTkb9egzwNMfJAEx4veaPSnMeKbVSjp4euqGSbQlm5+6VHwTr7u4FJslVVsUG5nopCaAYdOmSQ=="],-"ajv-formats/ajv/json-schema-traverse": ["[email protected]", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],"ajv-keywords/ajv/json-schema-traverse": ["[email protected]", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],@@ -6798,6 +6907,10 @@"tsx/esbuild/@esbuild/win32-x64": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-pEl1bO9mfAmIC+tW5btTmrKaujg3zGtUmWNdCw/xs70FBjwAL3o9OEKNHvNmnyylD6ubxUERiEhdsL0xBQ9efw=="],+ "vite-node/vite/esbuild": ["[email protected]", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.0", "@esbuild/android-arm": "0.28.0", "@esbuild/android-arm64": "0.28.0", "@esbuild/android-x64": "0.28.0", "@esbuild/darwin-arm64": "0.28.0", "@esbuild/darwin-x64": "0.28.0", "@esbuild/freebsd-arm64": "0.28.0", "@esbuild/freebsd-x64": "0.28.0", "@esbuild/linux-arm": "0.28.0", "@esbuild/linux-arm64": "0.28.0", "@esbuild/linux-ia32": "0.28.0", "@esbuild/linux-loong64": "0.28.0", "@esbuild/linux-mips64el": "0.28.0", "@esbuild/linux-ppc64": "0.28.0", "@esbuild/linux-riscv64": "0.28.0", "@esbuild/linux-s390x": "0.28.0", "@esbuild/linux-x64": "0.28.0", "@esbuild/netbsd-arm64": "0.28.0", "@esbuild/netbsd-x64": "0.28.0", "@esbuild/openbsd-arm64": "0.28.0", "@esbuild/openbsd-x64": "0.28.0", "@esbuild/openharmony-arm64": "0.28.0", "@esbuild/sunos-x64": "0.28.0", "@esbuild/win32-arm64": "0.28.0", "@esbuild/win32-ia32": "0.28.0", "@esbuild/win32-x64": "0.28.0" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-sNR9MHpXSUV/XB4zmsFKN+QgVG82Cc7+/aaxJ8Adi8hyOac+EXptIp45QBPaVyX3N70664wRbTcLTOemCAnyqw=="],++ "vitest/vite/esbuild": ["[email protected]", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.0", "@esbuild/android-arm": "0.28.0", "@esbuild/android-arm64": "0.28.0", "@esbuild/android-x64": "0.28.0", "@esbuild/darwin-arm64": "0.28.0", "@esbuild/darwin-x64": "0.28.0", "@esbuild/freebsd-arm64": "0.28.0", "@esbuild/freebsd-x64": "0.28.0", "@esbuild/linux-arm": "0.28.0", "@esbuild/linux-arm64": "0.28.0", "@esbuild/linux-ia32": "0.28.0", "@esbuild/linux-loong64": "0.28.0", "@esbuild/linux-mips64el": "0.28.0", "@esbuild/linux-ppc64": "0.28.0", "@esbuild/linux-riscv64": "0.28.0", "@esbuild/linux-s390x": "0.28.0", "@esbuild/linux-x64": "0.28.0", "@esbuild/netbsd-arm64": "0.28.0", "@esbuild/netbsd-x64": "0.28.0", "@esbuild/openbsd-arm64": "0.28.0", "@esbuild/openbsd-x64": "0.28.0", "@esbuild/openharmony-arm64": "0.28.0", "@esbuild/sunos-x64": "0.28.0", "@esbuild/win32-arm64": "0.28.0", "@esbuild/win32-ia32": "0.28.0", "@esbuild/win32-x64": "0.28.0" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-sNR9MHpXSUV/XB4zmsFKN+QgVG82Cc7+/aaxJ8Adi8hyOac+EXptIp45QBPaVyX3N70664wRbTcLTOemCAnyqw=="],+"webpack-hot-middleware/strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],"webpack/eslint-scope/estraverse": ["[email protected]", "", {}, "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw=="],@@ -7148,8 +7261,20 @@"@so-ric/colorspace/color/color-string/color-name": ["[email protected]", "", {}, "sha512-1bPaDNFm0axzE4MEAzKPuqKWeRaT43U/hyxKPBdqTfmPF+d6n7FSoTFxLVULUJOmiLp01KjhIPPH+HrXZJN4Rg=="],+ "@storybook/addon-interactions/@storybook/test/@vitest/expect/@vitest/utils": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/pretty-format": "2.0.5", "estree-walker": "^3.0.3", "loupe": "^3.1.1", "tinyrainbow": "^1.2.0" } }, "sha512-d8HKbqIcya+GR67mkZbrzhS5kKhtp8dQLcmRZLGTscGVg7yImT82cIrhtn2L8+VujWcy6KZweApgNmPsTAO/UQ=="],++ "@storybook/addon-interactions/@storybook/test/@vitest/expect/tinyrainbow": ["[email protected]", "", {}, "sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ=="],++ "@storybook/addon-interactions/@storybook/test/@vitest/spy/tinyspy": ["[email protected]", "", {}, "sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q=="],+"@storybook/react-docgen-typescript-plugin/find-cache-dir/pkg-dir/find-up": ["[email protected]", "", { "dependencies": { "locate-path": "^5.0.0", "path-exists": "^4.0.0" } }, "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw=="],+ "@storybook/test/@storybook/instrumenter/@vitest/utils/@vitest/pretty-format": ["@vitest/[email protected]", "", { "dependencies": { "tinyrainbow": "^1.2.0" } }, "sha512-KhRIdGV2U9HOUzxfiHmY8IFHTdqtOhIzCpd8WRdJiE7D/HUcZVD0EgQCVjm+Q9gkUXWgBvMmTtZgIG48wq7sOQ=="],++ "@storybook/test/@storybook/instrumenter/@vitest/utils/tinyrainbow": ["[email protected]", "", {}, "sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ=="],++ "@storybook/test/@vitest/expect/@vitest/utils/@vitest/pretty-format": ["@vitest/[email protected]", "", { "dependencies": { "tinyrainbow": "^1.2.0" } }, "sha512-h8k+1oWHfwTkyTkb9egzwNMfJAEx4veaPSnMeKbVSjp4euqGSbQlm5+6VHwTr7u4FJslVVsUG5nopCaAYdOmSQ=="],+"@testing-library/jest-dom/chalk/supports-color/has-flag": ["[email protected]", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="],"@unrs/resolver-binding-wasm32-wasi/@napi-rs/wasm-runtime/@tybys/wasm-util/tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],@@ -7238,6 +7363,110 @@"test-exclude/minimatch/brace-expansion/balanced-match": ["[email protected]", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],+ "vite-node/vite/esbuild/@esbuild/aix-ppc64": ["@esbuild/[email protected]", "", { "os": "aix", "cpu": "ppc64" }, "sha512-lhRUCeuOyJQURhTxl4WkpFTjIsbDayJHih5kZC1giwE+MhIzAb7mEsQMqMf18rHLsrb5qI1tafG20mLxEWcWlA=="],++ "vite-node/vite/esbuild/@esbuild/android-arm": ["@esbuild/[email protected]", "", { "os": "android", "cpu": "arm" }, "sha512-wqh0ByljabXLKHeWXYLqoJ5jKC4XBaw6Hk08OfMrCRd2nP2ZQ5eleDZC41XHyCNgktBGYMbqnrJKq/K/lzPMSQ=="],++ "vite-node/vite/esbuild/@esbuild/android-arm64": ["@esbuild/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-+WzIXQOSaGs33tLEgYPYe/yQHf0WTU0X42Jca3y8NWMbUVhp7rUnw+vAsRC/QiDrdD31IszMrZy+qwPOPjd+rw=="],++ "vite-node/vite/esbuild/@esbuild/android-x64": ["@esbuild/[email protected]", "", { "os": "android", "cpu": "x64" }, "sha512-+VJggoaKhk2VNNqVL7f6S189UzShHC/mR9EE8rDdSkdpN0KflSwWY/gWjDrNxxisg8Fp1ZCD9jLMo4m0OUfeUA=="],++ "vite-node/vite/esbuild/@esbuild/darwin-arm64": ["@esbuild/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-0T+A9WZm+bZ84nZBtk1ckYsOvyA3x7e2Acj1KdVfV4/2tdG4fzUp91YHx+GArWLtwqp77pBXVCPn2We7Letr0Q=="],++ "vite-node/vite/esbuild/@esbuild/darwin-x64": ["@esbuild/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-fyzLm/DLDl/84OCfp2f/XQ4flmORsjU7VKt8HLjvIXChJoFFOIL6pLJPH4Yhd1n1gGFF9mPwtlN5Wf82DZs+LQ=="],++ "vite-node/vite/esbuild/@esbuild/freebsd-arm64": ["@esbuild/[email protected]", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-l9GeW5UZBT9k9brBYI+0WDffcRxgHQD8ShN2Ur4xWq/NFzUKm3k5lsH4PdaRgb2w7mI9u61nr2gI2mLI27Nh3Q=="],++ "vite-node/vite/esbuild/@esbuild/freebsd-x64": ["@esbuild/[email protected]", "", { "os": "freebsd", "cpu": "x64" }, "sha512-BXoQai/A0wPO6Es3yFJ7APCiKGc1tdAEOgeTNy3SsB491S3aHn4S4r3e976eUnPdU+NbdtmBuLncYir2tMU9Nw=="],++ "vite-node/vite/esbuild/@esbuild/linux-arm": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-CjaaREJagqJp7iTaNQjjidaNbCKYcd4IDkzbwwxtSvjI7NZm79qiHc8HqciMddQ6CKvJT6aBd8lO9kN/ZudLlw=="],++ "vite-node/vite/esbuild/@esbuild/linux-arm64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-RVyzfb3FWsGA55n6WY0MEIEPURL1FcbhFE6BffZEMEekfCzCIMtB5yyDcFnVbTnwk+CLAgTujmV/Lgvih56W+A=="],++ "vite-node/vite/esbuild/@esbuild/linux-ia32": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "ia32" }, "sha512-KBnSTt1kxl9x70q+ydterVdl+Cn0H18ngRMRCEQfrbqdUuntQQ0LoMZv47uB97NljZFzY6HcfqEZ2SAyIUTQBQ=="],++ "vite-node/vite/esbuild/@esbuild/linux-loong64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-zpSlUce1mnxzgBADvxKXX5sl8aYQHo2ezvMNI8I0lbblJtp8V4odlm3Yzlj7gPyt3T8ReksE6bK+pT3WD+aJRg=="],++ "vite-node/vite/esbuild/@esbuild/linux-mips64el": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-2jIfP6mmjkdmeTlsX/9vmdmhBmKADrWqN7zcdtHIeNSCH1SqIoNI63cYsjQR8J+wGa4Y5izRcSHSm8K3QWmk3w=="],++ "vite-node/vite/esbuild/@esbuild/linux-ppc64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "ppc64" }, "sha512-bc0FE9wWeC0WBm49IQMPSPILRocGTQt3j5KPCA8os6VprfuJ7KD+5PzESSrJ6GmPIPJK965ZJHTUlSA6GNYEhg=="],++ "vite-node/vite/esbuild/@esbuild/linux-riscv64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-SQPZOwoTTT/HXFXQJG/vBX8sOFagGqvZyXcgLA3NhIqcBv1BJU1d46c0rGcrij2B56Z2rNiSLaZOYW5cUk7yLQ=="],++ "vite-node/vite/esbuild/@esbuild/linux-s390x": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "s390x" }, "sha512-SCfR0HN8CEEjnYnySJTd2cw0k9OHB/YFzt5zgJEwa+wL/T/raGWYMBqwDNAC6dqFKmJYZoQBRfHjgwLHGSrn3Q=="],++ "vite-node/vite/esbuild/@esbuild/linux-x64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-us0dSb9iFxIi8srnpl931Nvs65it/Jd2a2K3qs7fz2WfGPHqzfzZTfec7oxZJRNPXPnNYZtanmRc4AL/JwVzHQ=="],++ "vite-node/vite/esbuild/@esbuild/netbsd-arm64": ["@esbuild/[email protected]", "", { "os": "none", "cpu": "arm64" }, "sha512-CR/RYotgtCKwtftMwJlUU7xCVNg3lMYZ0RzTmAHSfLCXw3NtZtNpswLEj/Kkf6kEL3Gw+BpOekRX0BYCtklhUw=="],++ "vite-node/vite/esbuild/@esbuild/netbsd-x64": ["@esbuild/[email protected]", "", { "os": "none", "cpu": "x64" }, "sha512-nU1yhmYutL+fQ71Kxnhg8uEOdC0pwEW9entHykTgEbna2pw2dkbFSMeqjjyHZoCmt8SBkOSvV+yNmm94aUrrqw=="],++ "vite-node/vite/esbuild/@esbuild/openbsd-arm64": ["@esbuild/[email protected]", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-cXb5vApOsRsxsEl4mcZ1XY3D4DzcoMxR/nnc4IyqYs0rTI8ZKmW6kyyg+11Z8yvgMfAEldKzP7AdP64HnSC/6g=="],++ "vite-node/vite/esbuild/@esbuild/openbsd-x64": ["@esbuild/[email protected]", "", { "os": "openbsd", "cpu": "x64" }, "sha512-8wZM2qqtv9UP3mzy7HiGYNH/zjTA355mpeuA+859TyR+e+Tc08IHYpLJuMsfpDJwoLo1ikIJI8jC3GFjnRClzA=="],++ "vite-node/vite/esbuild/@esbuild/openharmony-arm64": ["@esbuild/[email protected]", "", { "os": "none", "cpu": "arm64" }, "sha512-FLGfyizszcef5C3YtoyQDACyg95+dndv79i2EekILBofh5wpCa1KuBqOWKrEHZg3zrL3t5ouE5jgr94vA+Wb2w=="],++ "vite-node/vite/esbuild/@esbuild/sunos-x64": ["@esbuild/[email protected]", "", { "os": "sunos", "cpu": "x64" }, "sha512-1ZgjUoEdHZZl/YlV76TSCz9Hqj9h9YmMGAgAPYd+q4SicWNX3G5GCyx9uhQWSLcbvPW8Ni7lj4gDa1T40akdlw=="],++ "vite-node/vite/esbuild/@esbuild/win32-arm64": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-Q9StnDmQ/enxnpxCCLSg0oo4+34B9TdXpuyPeTedN/6+iXBJ4J+zwfQI28u/Jl40nOYAxGoNi7mFP40RUtkmUA=="],++ "vite-node/vite/esbuild/@esbuild/win32-ia32": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "ia32" }, "sha512-zF3ag/gfiCe6U2iczcRzSYJKH1DCI+ByzSENHlM2FcDbEeo5Zd2C86Aq0tKUYAJJ1obRP84ymxIAksZUcdztHA=="],++ "vite-node/vite/esbuild/@esbuild/win32-x64": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-pEl1bO9mfAmIC+tW5btTmrKaujg3zGtUmWNdCw/xs70FBjwAL3o9OEKNHvNmnyylD6ubxUERiEhdsL0xBQ9efw=="],++ "vitest/vite/esbuild/@esbuild/aix-ppc64": ["@esbuild/[email protected]", "", { "os": "aix", "cpu": "ppc64" }, "sha512-lhRUCeuOyJQURhTxl4WkpFTjIsbDayJHih5kZC1giwE+MhIzAb7mEsQMqMf18rHLsrb5qI1tafG20mLxEWcWlA=="],++ "vitest/vite/esbuild/@esbuild/android-arm": ["@esbuild/[email protected]", "", { "os": "android", "cpu": "arm" }, "sha512-wqh0ByljabXLKHeWXYLqoJ5jKC4XBaw6Hk08OfMrCRd2nP2ZQ5eleDZC41XHyCNgktBGYMbqnrJKq/K/lzPMSQ=="],++ "vitest/vite/esbuild/@esbuild/android-arm64": ["@esbuild/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-+WzIXQOSaGs33tLEgYPYe/yQHf0WTU0X42Jca3y8NWMbUVhp7rUnw+vAsRC/QiDrdD31IszMrZy+qwPOPjd+rw=="],++ "vitest/vite/esbuild/@esbuild/android-x64": ["@esbuild/[email protected]", "", { "os": "android", "cpu": "x64" }, "sha512-+VJggoaKhk2VNNqVL7f6S189UzShHC/mR9EE8rDdSkdpN0KflSwWY/gWjDrNxxisg8Fp1ZCD9jLMo4m0OUfeUA=="],++ "vitest/vite/esbuild/@esbuild/darwin-arm64": ["@esbuild/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-0T+A9WZm+bZ84nZBtk1ckYsOvyA3x7e2Acj1KdVfV4/2tdG4fzUp91YHx+GArWLtwqp77pBXVCPn2We7Letr0Q=="],++ "vitest/vite/esbuild/@esbuild/darwin-x64": ["@esbuild/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-fyzLm/DLDl/84OCfp2f/XQ4flmORsjU7VKt8HLjvIXChJoFFOIL6pLJPH4Yhd1n1gGFF9mPwtlN5Wf82DZs+LQ=="],++ "vitest/vite/esbuild/@esbuild/freebsd-arm64": ["@esbuild/[email protected]", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-l9GeW5UZBT9k9brBYI+0WDffcRxgHQD8ShN2Ur4xWq/NFzUKm3k5lsH4PdaRgb2w7mI9u61nr2gI2mLI27Nh3Q=="],++ "vitest/vite/esbuild/@esbuild/freebsd-x64": ["@esbuild/[email protected]", "", { "os": "freebsd", "cpu": "x64" }, "sha512-BXoQai/A0wPO6Es3yFJ7APCiKGc1tdAEOgeTNy3SsB491S3aHn4S4r3e976eUnPdU+NbdtmBuLncYir2tMU9Nw=="],++ "vitest/vite/esbuild/@esbuild/linux-arm": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-CjaaREJagqJp7iTaNQjjidaNbCKYcd4IDkzbwwxtSvjI7NZm79qiHc8HqciMddQ6CKvJT6aBd8lO9kN/ZudLlw=="],++ "vitest/vite/esbuild/@esbuild/linux-arm64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-RVyzfb3FWsGA55n6WY0MEIEPURL1FcbhFE6BffZEMEekfCzCIMtB5yyDcFnVbTnwk+CLAgTujmV/Lgvih56W+A=="],++ "vitest/vite/esbuild/@esbuild/linux-ia32": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "ia32" }, "sha512-KBnSTt1kxl9x70q+ydterVdl+Cn0H18ngRMRCEQfrbqdUuntQQ0LoMZv47uB97NljZFzY6HcfqEZ2SAyIUTQBQ=="],++ "vitest/vite/esbuild/@esbuild/linux-loong64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-zpSlUce1mnxzgBADvxKXX5sl8aYQHo2ezvMNI8I0lbblJtp8V4odlm3Yzlj7gPyt3T8ReksE6bK+pT3WD+aJRg=="],++ "vitest/vite/esbuild/@esbuild/linux-mips64el": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-2jIfP6mmjkdmeTlsX/9vmdmhBmKADrWqN7zcdtHIeNSCH1SqIoNI63cYsjQR8J+wGa4Y5izRcSHSm8K3QWmk3w=="],++ "vitest/vite/esbuild/@esbuild/linux-ppc64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "ppc64" }, "sha512-bc0FE9wWeC0WBm49IQMPSPILRocGTQt3j5KPCA8os6VprfuJ7KD+5PzESSrJ6GmPIPJK965ZJHTUlSA6GNYEhg=="],++ "vitest/vite/esbuild/@esbuild/linux-riscv64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-SQPZOwoTTT/HXFXQJG/vBX8sOFagGqvZyXcgLA3NhIqcBv1BJU1d46c0rGcrij2B56Z2rNiSLaZOYW5cUk7yLQ=="],++ "vitest/vite/esbuild/@esbuild/linux-s390x": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "s390x" }, "sha512-SCfR0HN8CEEjnYnySJTd2cw0k9OHB/YFzt5zgJEwa+wL/T/raGWYMBqwDNAC6dqFKmJYZoQBRfHjgwLHGSrn3Q=="],++ "vitest/vite/esbuild/@esbuild/linux-x64": ["@esbuild/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-us0dSb9iFxIi8srnpl931Nvs65it/Jd2a2K3qs7fz2WfGPHqzfzZTfec7oxZJRNPXPnNYZtanmRc4AL/JwVzHQ=="],++ "vitest/vite/esbuild/@esbuild/netbsd-arm64": ["@esbuild/[email protected]", "", { "os": "none", "cpu": "arm64" }, "sha512-CR/RYotgtCKwtftMwJlUU7xCVNg3lMYZ0RzTmAHSfLCXw3NtZtNpswLEj/Kkf6kEL3Gw+BpOekRX0BYCtklhUw=="],++ "vitest/vite/esbuild/@esbuild/netbsd-x64": ["@esbuild/[email protected]", "", { "os": "none", "cpu": "x64" }, "sha512-nU1yhmYutL+fQ71Kxnhg8uEOdC0pwEW9entHykTgEbna2pw2dkbFSMeqjjyHZoCmt8SBkOSvV+yNmm94aUrrqw=="],++ "vitest/vite/esbuild/@esbuild/openbsd-arm64": ["@esbuild/[email protected]", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-cXb5vApOsRsxsEl4mcZ1XY3D4DzcoMxR/nnc4IyqYs0rTI8ZKmW6kyyg+11Z8yvgMfAEldKzP7AdP64HnSC/6g=="],++ "vitest/vite/esbuild/@esbuild/openbsd-x64": ["@esbuild/[email protected]", "", { "os": "openbsd", "cpu": "x64" }, "sha512-8wZM2qqtv9UP3mzy7HiGYNH/zjTA355mpeuA+859TyR+e+Tc08IHYpLJuMsfpDJwoLo1ikIJI8jC3GFjnRClzA=="],++ "vitest/vite/esbuild/@esbuild/openharmony-arm64": ["@esbuild/[email protected]", "", { "os": "none", "cpu": "arm64" }, "sha512-FLGfyizszcef5C3YtoyQDACyg95+dndv79i2EekILBofh5wpCa1KuBqOWKrEHZg3zrL3t5ouE5jgr94vA+Wb2w=="],++ "vitest/vite/esbuild/@esbuild/sunos-x64": ["@esbuild/[email protected]", "", { "os": "sunos", "cpu": "x64" }, "sha512-1ZgjUoEdHZZl/YlV76TSCz9Hqj9h9YmMGAgAPYd+q4SicWNX3G5GCyx9uhQWSLcbvPW8Ni7lj4gDa1T40akdlw=="],++ "vitest/vite/esbuild/@esbuild/win32-arm64": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-Q9StnDmQ/enxnpxCCLSg0oo4+34B9TdXpuyPeTedN/6+iXBJ4J+zwfQI28u/Jl40nOYAxGoNi7mFP40RUtkmUA=="],++ "vitest/vite/esbuild/@esbuild/win32-ia32": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "ia32" }, "sha512-zF3ag/gfiCe6U2iczcRzSYJKH1DCI+ByzSENHlM2FcDbEeo5Zd2C86Aq0tKUYAJJ1obRP84ymxIAksZUcdztHA=="],++ "vitest/vite/esbuild/@esbuild/win32-x64": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-pEl1bO9mfAmIC+tW5btTmrKaujg3zGtUmWNdCw/xs70FBjwAL3o9OEKNHvNmnyylD6ubxUERiEhdsL0xBQ9efw=="],+"widest-line/string-width/strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],"yargs/string-width/strip-ansi/ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],@@ -7290,6 +7519,8 @@"@oclif/plugin-help/@oclif/config/@oclif/errors/fs-extra/universalify": ["[email protected]", "", {}, "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg=="],+ "@storybook/addon-interactions/@storybook/test/@vitest/expect/@vitest/utils/@vitest/pretty-format": ["@vitest/[email protected]", "", { "dependencies": { "tinyrainbow": "^1.2.0" } }, "sha512-h8k+1oWHfwTkyTkb9egzwNMfJAEx4veaPSnMeKbVSjp4euqGSbQlm5+6VHwTr7u4FJslVVsUG5nopCaAYdOmSQ=="],+"@storybook/react-docgen-typescript-plugin/find-cache-dir/pkg-dir/find-up/locate-path": ["[email protected]", "", { "dependencies": { "p-locate": "^4.1.0" } }, "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g=="],"find-cache-dir/pkg-dir/find-up/locate-path/p-locate": ["[email protected]", "", { "dependencies": { "p-limit": "^4.0.0" } }, "sha512-wPrq66Llhl7/4AGC6I+cqxT07LhXvWL08LNXz1fENOw0Ap4sRZZ/gZpTTJ5jpurzzzfS2W/Ge9BY3LgLjCShcw=="],diff --git a/claude-progress.md b/claude-progress.mdindex 8c5901d8a..722bb1fec 100644--- a/claude-progress.md+++ b/claude-progress.md@@ -7,7 +7,7 @@ session detail aggressively. The per-spec source of truth lives in## Current Verified State- **Repository root**: `/Users/viktorholik/Desktop/mercur`-- **Current branch**: `main`+- **Current branch**: `feat/magento2-connector`- **Current version**: `2.2.0-rc.1`- **Standard startup path**: `bun install && bun run dev`- **Standard verification path**: `bun run build`, `bun run lint` (oxlint),@@ -30,6 +30,31 @@ test-utils dropped the `inApp` option, removed from both `health.spec.ts`. `rout`payment/split-order-payments` + `order/admin/order-payment-status` 16/16. Gotcha: after changing a patch,rebuild core and `jest --clearCache`, or the transformer replays the old manifest from `.medusa/server`.+## Session — Magento 2 connector, Part A (2026-10-21), branch `feat/magento2-connector`++Spec: `docs/specs/SPEC-003-magento2-connector.md` (local, `in_progress`). Design: Magento keeps+storefront, checkout, payment capture and 1P products; Mercur owns sellers, 3P offers, split orders,+commissions, payouts. Checkout drives a shadow Mercur cart (line items by `offer_id`, per-seller+shipping, `pp_external_external` session, complete).+- New plugin `packages/plugins/magento2-connector` (`@mercurjs/magento2-connector-plugin`):+ `magento_webhook` module (endpoints + signed, retried deliveries), `external` payment provider,+ `/admin/magento/*` routes (webhooks CRUD, deliveries, redeliver, status, external refund), fan-out+ subscriber, retry/prune jobs, admin UI at `/settings/magento` built with `mercurjs dashboard:build`.+- Core: `deleted_at` filter + `with_deleted` forwarding on admin offers/sellers lists; `order_group.metadata`+ (+ migration) copied from `cart.metadata`; `integrations` permission key (core catalog + SDK).+- Verified: turbo build 7/7, plugin admin tsc clean, oxlint clean, integration specs+ `magento2-connector/*` 9/9 and `offer/admin/offer-soft-delete` 1/1. `test:unit` cannot resolve+ `@swc/jest` locally; registry spec left to CI.+- Reviewed with the enterprise `medusa-review` skill (Medusa eslint preset + exemplar diff) and fixed all+ findings: writes go through workflows with compensation and refetch, validation step instead of throw in+ transform, service under `services/` with `IMagentoWebhookModuleService`, generated migration, typed+ responses, strict validators. Gate clean on plugin files; specs 10/10 after the refactor.+- Part B pushed: github.com/mercurjs/magento2-connector (`mercurjs/magento2-connector` Composer package,+ modules Core/Process/Connector/OfferIndexer/Catalog/Settlement/Frontend/GraphQl). Lint + 13 unit tests+ green locally via a static PHP binary in the scratchpad (Homebrew PHP won't build on this macOS). Not+ yet run on a Magento install.+- Next: dashboard Channel column/filter, roles preset once a roles module exists, Magento end-to-end run.+## Session — Core hot-path performance (2026-10-21), branch `perf/core-hot-path-optimizations`, PR #1677Technique catalog from the Medusa source in `docs/PERFORMANCE.md` (section 4 lists what this branchdiff --git a/integration-tests/helpers/split-order-checkout.ts b/integration-tests/helpers/split-order-checkout.tsindex bc29726ef..a1e7f2669 100644--- a/integration-tests/helpers/split-order-checkout.ts+++ b/integration-tests/helpers/split-order-checkout.ts@@ -138,7 +138,7 @@ export const seedSellerOfferWithShipping = async (opts: {)).data.offer- return { sellerId: result.seller.id, headers, offer }+ return { sellerId: result.seller.id, headers, offer, stockLocationId: stockLocation.id }}type SplitOrderCheckoutOptions = {diff --git a/integration-tests/http/magento2-connector/external-payment.spec.ts b/integration-tests/http/magento2-connector/external-payment.spec.tsnew file mode 100644index 000000000..b05e725b7--- /dev/null+++ b/integration-tests/http/magento2-connector/external-payment.spec.ts@@ -0,0 +1,306 @@+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"+import {+ IRegionModuleService,+ ISalesChannelModuleService,+ MedusaContainer,+} from "@medusajs/framework/types"+import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"++import {+ adminHeaders,+ createAdminUser,+ generatePublishableKey,+ generateStoreHeaders,+} from "../../helpers/create-admin-user"+import { createCustomerUser } from "../../helpers/create-customer-user"+import { seedSellerOfferWithShipping } from "../../helpers/split-order-checkout"+import { completeExternalCheckout, startWebhookReceiver, waitFor, WebhookReceiver } from "./helpers"++jest.setTimeout(120000)++medusaIntegrationTestRunner({+ testSuite: ({ getContainer, api, dbConnection }) => {+ describe("Magento connector - external payment provider", () => {+ let appContainer: MedusaContainer+ let storeHeaders: any+ let customerEmail: string+ let region: any+ let salesChannel: any+ let seedA: any+ let seedB: any++ beforeAll(async () => {+ appContainer = getContainer()+ })++ beforeEach(async () => {+ await createAdminUser(dbConnection, adminHeaders, appContainer)++ const customer = await createCustomerUser(appContainer, {+ email: "[email protected]",+ first_name: "Magento",+ last_name: "Buyer",+ })+ customerEmail = customer.customer.email!+ const apiKey = await generatePublishableKey(appContainer)+ storeHeaders = {+ headers: {+ ...generateStoreHeaders({ publishableKey: apiKey }).headers,+ ...customer.headers.headers,+ },+ }++ salesChannel = await appContainer+ .resolve<ISalesChannelModuleService>(Modules.SALES_CHANNEL)+ .createSalesChannels({ name: "Magento" })+ region = await appContainer+ .resolve<IRegionModuleService>(Modules.REGION)+ .createRegions({ name: "US", currency_code: "usd", countries: ["us"] })++ const link = appContainer.resolve(ContainerRegistrationKeys.LINK)+ await link.create({+ [Modules.REGION]: { region_id: region.id },+ [Modules.PAYMENT]: { payment_provider_id: "pp_external_external" },+ })++ seedA = await seedSellerOfferWithShipping({+ container: appContainer,+ api,+ salesChannelId: salesChannel.id,+ email: "[email protected]",+ name: "MagentoA",+ stocked: 10,+ offerPrice: 2500,+ })+ seedB = await seedSellerOfferWithShipping({+ container: appContainer,+ api,+ salesChannelId: salesChannel.id,+ email: "[email protected]",+ name: "MagentoB",+ stocked: 10,+ offerPrice: 1500,+ })+ })++ const checkout = (reference = "MIR$000001") =>+ completeExternalCheckout({+ container: appContainer,+ api,+ storeHeaders,+ regionId: region.id,+ salesChannelId: salesChannel.id,+ offerIds: [seedA.offer.id, seedB.offer.id],+ email: customerEmail,+ reference,+ })++ it("completes a two-seller cart on the external provider and carries the channel onto the order group", async () => {+ const { completed, orderGroup } = await checkout()++ expect(completed.type).toEqual("order_group")+ expect(orderGroup.metadata).toEqual({ channel: "magento" })+ expect(orderGroup.orders).toHaveLength(2)+ for (const order of orderGroup.orders) {+ expect(order.metadata).toEqual({ channel: "magento" })+ }++ const { data } = await api.get(+ `/admin/order-groups/${orderGroup.id}?fields=id,metadata`,+ adminHeaders+ )+ expect(data.order_group.metadata).toEqual({ channel: "magento" })+ })++ it("records the external capture so each child order is paid and commission lines exist", async () => {+ const { orderGroup } = await checkout("MIR$000002")++ for (const order of orderGroup.orders) {+ await waitFor(async () => {+ const { data } = await api.get(+ `/admin/orders/${order.id}?fields=id,payment_status,*payment_collections,*payment_collections.payments`,+ adminHeaders+ )+ return data.order.payment_status === "captured"+ })++ const { data } = await api.get(+ `/admin/orders/${order.id}?fields=id,payment_status,total,*payment_collections,*payment_collections.payments`,+ adminHeaders+ )+ const payments = data.order.payment_collections.flatMap((pc: any) => pc.payments)+ expect(payments.length).toBeGreaterThan(0)+ expect(payments[0].provider_id).toEqual("pp_external_external")+ expect(payments[0].captured_at).toBeTruthy()+ expect(payments[0].data).toEqual(+ expect.objectContaining({ reference: "MIR$000002", channel: "magento" })+ )++ const lines = await api.get(`/admin/orders/${order.id}/commission-lines`, adminHeaders)+ expect(lines.status).toEqual(200)+ expect(Array.isArray(lines.data.commission_lines)).toBe(true)+ }+ })++ it("records an external refund on the child order and emits order.refund_recorded", async () => {+ const receiver: WebhookReceiver = await startWebhookReceiver()+ try {+ await api.post(+ `/admin/magento/webhooks`,+ { url: receiver.url, events: ["order.refund_recorded"] },+ adminHeaders+ )++ const { orderGroup } = await checkout("MIR$000003")+ const order = orderGroup.orders[0]++ await waitFor(async () => {+ const { data } = await api.get(+ `/admin/orders/${order.id}?fields=id,payment_status`,+ adminHeaders+ )+ return data.order.payment_status === "captured"+ })++ const refund = await api.post(+ `/admin/magento/orders/${order.id}/refunds/external`,+ { amount: 500, reference: "CM-1", note: "Damaged" },+ adminHeaders+ )+ expect(refund.status).toEqual(200)+ expect(refund.data.payment.refunds).toHaveLength(1)+ expect(refund.data.payment.refunds[0].amount).toEqual(500)++ await waitFor(() => receiver.received.length > 0)+ const body = JSON.parse(receiver.received[0].body)+ expect(body.event).toEqual("order.refund_recorded")+ expect(body.data).toEqual(+ expect.objectContaining({ id: order.id, amount: 500, reference: "CM-1" })+ )+ } finally {+ await receiver.close()+ }+ })++ it("announces a refund started in Mercur as order.refund_requested, but not one recorded from Magento", async () => {+ const receiver: WebhookReceiver = await startWebhookReceiver()+ try {+ await api.post(+ `/admin/magento/webhooks`,+ { url: receiver.url, events: ["order.refund_requested"] },+ adminHeaders+ )++ const { orderGroup } = await checkout("MIR$000004")+ const order = orderGroup.orders[0]++ await waitFor(async () => {+ const { data } = await api.get(+ `/admin/orders/${order.id}?fields=id,payment_status`,+ adminHeaders+ )+ return data.order.payment_status === "captured"+ })++ await api.post(+ `/admin/magento/orders/${order.id}/refunds/external`,+ { amount: 300, reference: "CM-2" },+ adminHeaders+ )++ const { data } = await api.get(+ `/admin/orders/${order.id}?fields=id,*payment_collections,*payment_collections.payments`,+ adminHeaders+ )+ const payment = data.order.payment_collections+ .flatMap((pc: any) => pc.payments)+ .find((p: any) => p.provider_id === "pp_external_external")++ const sellerHeaders = order.seller?.id === seedB.sellerId ? seedB.headers : seedA.headers+ const refund = await api.post(+ `/vendor/payments/${payment.id}/refund`,+ { amount: 200, note: "Missing part" },+ sellerHeaders+ )+ expect(refund.status).toEqual(200)++ await waitFor(() => receiver.received.length > 0)+ await new Promise((resolve) => setTimeout(resolve, 1500))++ expect(receiver.received).toHaveLength(1)+ const body = JSON.parse(receiver.received[0].body)+ expect(body.event).toEqual("order.refund_requested")+ expect(body.data).toEqual(+ expect.objectContaining({+ order_id: order.id,+ payment_id: payment.id,+ amount: 200,+ note: "Missing part",+ })+ )+ expect(body.data.refund_id).toMatch(/^ref/)+ } finally {+ await receiver.close()+ }+ })++ it("adds the order id to shipment.created and delivery.created deliveries", async () => {+ const receiver: WebhookReceiver = await startWebhookReceiver()+ try {+ await api.post(+ `/admin/magento/webhooks`,+ { url: receiver.url, events: ["shipment.created", "delivery.created"] },+ adminHeaders+ )++ const { orderGroup } = await checkout("MIR$000005")+ const order = orderGroup.orders[0]+ const seed = order.seller?.id === seedB.sellerId ? seedB : seedA++ const { data } = await api.get(`/vendor/orders/${order.id}?fields=*items`, seed.headers)+ const items = data.order.items.map((item: any) => ({ id: item.id, quantity: item.quantity }))++ const fulfillment = (+ await api.post(+ `/vendor/orders/${order.id}/fulfillments`,+ { items, requires_shipping: true, location_id: seed.stockLocationId },+ seed.headers+ )+ ).data.fulfillment+ await api.post(+ `/vendor/orders/${order.id}/fulfillments/${fulfillment.id}/shipments`,+ { items },+ seed.headers+ )+ await api.post(+ `/vendor/orders/${order.id}/fulfillments/${fulfillment.id}/mark-as-delivered`,+ {},+ seed.headers+ )++ await waitFor(() => receiver.received.length >= 2)+ const bodies = receiver.received.map((r) => JSON.parse(r.body))+ expect(bodies.map((b) => b.event).sort()).toEqual(["delivery.created", "shipment.created"])+ for (const body of bodies) {+ expect(body.data).toEqual(+ expect.objectContaining({ order_id: order.id, fulfillment_id: fulfillment.id })+ )+ }+ } finally {+ await receiver.close()+ }+ })++ it("refuses an external refund on an order without an external payment", async () => {+ const res = await api+ .post(+ `/admin/magento/orders/order_does_not_exist/refunds/external`,+ { amount: 100 },+ adminHeaders+ )+ .catch((e: any) => e.response)+ expect([400, 404]).toContain(res.status)+ })+ })+ },+})diff --git a/integration-tests/http/magento2-connector/helpers.ts b/integration-tests/http/magento2-connector/helpers.tsnew file mode 100644index 000000000..e2b2d8a94--- /dev/null+++ b/integration-tests/http/magento2-connector/helpers.ts@@ -0,0 +1,149 @@+import { createServer, IncomingMessage, Server } from "node:http"+import { AddressInfo } from "node:net"++import { MedusaContainer } from "@medusajs/framework/types"+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"++export type ReceivedWebhook = {+ headers: IncomingMessage["headers"]+ body: string+}++export type WebhookReceiver = {+ url: string+ received: ReceivedWebhook[]+ respondWith: { status: number }+ close: () => Promise<void>+}++export const startWebhookReceiver = async (): Promise<WebhookReceiver> => {+ const received: ReceivedWebhook[] = []+ const respondWith = { status: 200 }++ const server: Server = createServer((req, res) => {+ let body = ""+ req.on("data", (chunk) => {+ body += chunk+ })+ req.on("end", () => {+ received.push({ headers: req.headers, body })+ res.statusCode = respondWith.status+ res.end("ok")+ })+ })++ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve))+ const { port } = server.address() as AddressInfo++ return {+ url: `http://127.0.0.1:${port}/webhook`,+ received,+ respondWith,+ close: () => new Promise((resolve) => server.close(() => resolve())),+ }+}++export const waitFor = async (+ predicate: () => boolean | Promise<boolean>,+ { timeoutMs = 15000, intervalMs = 200 } = {}+) => {+ const started = Date.now()+ while (Date.now() - started < timeoutMs) {+ if (await predicate()) {+ return+ }+ await new Promise((resolve) => setTimeout(resolve, intervalMs))+ }+ throw new Error("Timed out waiting for condition")+}++const address = {+ first_name: "Buyer",+ last_name: "Test",+ address_1: "123 Main St",+ city: "New York",+ country_code: "us",+ postal_code: "10001",+}++export const completeExternalCheckout = async (opts: {+ container: MedusaContainer+ api: any+ storeHeaders: any+ regionId: string+ salesChannelId: string+ offerIds: string[]+ email: string+ reference: string+ channel?: string+}) => {+ const { api, storeHeaders } = opts++ const cart = (+ await api.post(+ `/store/carts`,+ {+ region_id: opts.regionId,+ sales_channel_id: opts.salesChannelId,+ currency_code: "usd",+ metadata: { channel: opts.channel ?? "magento" },+ },+ storeHeaders+ )+ ).data.cart++ for (const offerId of opts.offerIds) {+ await api.post(+ `/store/carts/${cart.id}/line-items`,+ { offer_id: offerId, quantity: 1 },+ storeHeaders+ )+ }++ await api.post(+ `/store/carts/${cart.id}`,+ { email: opts.email, shipping_address: address, billing_address: address },+ storeHeaders+ )++ const shippingOptions = Object.values(+ (await api.get(`/store/shipping-options?cart_id=${cart.id}`, storeHeaders))+ .data.shipping_options as Record<string, any[]>+ ).flat()+ for (const option of shippingOptions) {+ await api.post(+ `/store/carts/${cart.id}/shipping-methods`,+ { option_id: option.id },+ storeHeaders+ )+ }++ const paymentCollection = (+ await api.post(`/store/payment-collections`, { cart_id: cart.id }, storeHeaders)+ ).data.payment_collection+ await api.post(+ `/store/payment-collections/${paymentCollection.id}/payment-sessions`,+ {+ provider_id: "pp_external_external",+ data: {+ reference: opts.reference,+ captured_at: new Date().toISOString(),+ channel: opts.channel ?? "magento",+ },+ },+ storeHeaders+ )++ const completed = (+ await api.post(`/store/carts/${cart.id}/complete`, {}, storeHeaders)+ ).data++ const query = opts.container.resolve(ContainerRegistrationKeys.QUERY)+ const { data: groups } = await query.graph({+ entity: "order_group",+ filters: { id: completed.order_group.id },+ fields: ["id", "metadata", "orders.id", "orders.metadata", "orders.seller.id"],+ })++ return { cart, completed, orderGroup: groups[0] as any }+}diff --git a/integration-tests/http/magento2-connector/webhooks.spec.ts b/integration-tests/http/magento2-connector/webhooks.spec.tsnew file mode 100644index 000000000..9e6d9d5f4--- /dev/null+++ b/integration-tests/http/magento2-connector/webhooks.spec.ts@@ -0,0 +1,191 @@+import { createHmac } from "node:crypto"++import { medusaIntegrationTestRunner } from "@medusajs/test-utils"+import { MedusaContainer } from "@medusajs/framework/types"++import { adminHeaders, createAdminUser } from "../../helpers/create-admin-user"+import { createSellerUser } from "../../helpers/create-seller-user"+import { startWebhookReceiver, waitFor, WebhookReceiver } from "./helpers"++jest.setTimeout(120000)++medusaIntegrationTestRunner({+ testSuite: ({ getContainer, api, dbConnection }) => {+ describe("Magento connector - webhooks", () => {+ let appContainer: MedusaContainer+ let receiver: WebhookReceiver++ beforeAll(async () => {+ appContainer = getContainer()+ })++ beforeEach(async () => {+ await createAdminUser(dbConnection, adminHeaders, appContainer)+ receiver = await startWebhookReceiver()+ })++ afterEach(async () => {+ await receiver.close()+ })++ it("creates, lists, updates and deletes a webhook endpoint", async () => {+ const created = await api.post(+ `/admin/magento/webhooks`,+ { url: receiver.url, events: ["offer.created"], description: "Magento" },+ adminHeaders+ )+ expect(created.status).toEqual(200)+ expect(created.data.webhook).toEqual(+ expect.objectContaining({+ id: expect.stringMatching(/^mwhe_/),+ url: receiver.url,+ events: ["offer.created"],+ is_active: true,+ secret: expect.any(String),+ })+ )+ const id = created.data.webhook.id++ const listed = await api.get(`/admin/magento/webhooks`, adminHeaders)+ expect(listed.status).toEqual(200)+ expect(listed.data).toEqual(+ expect.objectContaining({ count: 1, offset: 0, limit: 50 })+ )+ expect(listed.data.webhooks).toEqual([+ expect.objectContaining({ id, url: receiver.url, events: ["offer.created"] }),+ ])+ expect(listed.data.webhooks[0].secret).toBeUndefined()++ const updated = await api.post(+ `/admin/magento/webhooks/${id}`,+ { events: ["offer.created", "seller.updated"], is_active: false },+ adminHeaders+ )+ expect(updated.data.webhook.events).toEqual(["offer.created", "seller.updated"])+ expect(updated.data.webhook.is_active).toEqual(false)++ const deleted = await api.delete(`/admin/magento/webhooks/${id}`, adminHeaders)+ expect(deleted.data).toEqual({ id, object: "magento_webhook", deleted: true })+ })++ it("rejects an unknown event", async () => {+ const res = await api+ .post(+ `/admin/magento/webhooks`,+ { url: receiver.url, events: ["cart.exploded"] },+ adminHeaders+ )+ .catch((e: any) => e.response)+ expect(res.status).toEqual(400)+ })++ it("delivers a signed payload when a subscribed event fires", async () => {+ const webhook = (+ await api.post(+ `/admin/magento/webhooks`,+ { url: receiver.url, events: ["seller.updated"] },+ adminHeaders+ )+ ).data.webhook++ const { seller, headers } = await createSellerUser(appContainer, {+ email: "[email protected]",+ name: "Hooked",+ })+ await api.post(`/vendor/sellers/me`, { name: "Hooked Renamed" }, headers)++ await waitFor(() => receiver.received.length > 0)++ const [hit] = receiver.received+ expect(hit.headers["x-mercur-event"]).toEqual("seller.updated")+ expect(hit.headers["x-mercur-delivery"]).toMatch(/^mwhd_/)+ const expected = `sha256=${createHmac("sha256", webhook.secret)+ .update(hit.body)+ .digest("hex")}`+ expect(hit.headers["x-mercur-signature"]).toEqual(expected)++ const body = JSON.parse(hit.body)+ expect(body.event).toEqual("seller.updated")+ expect(body.data).toEqual(expect.objectContaining({ id: seller.id }))++ await waitFor(async () => {+ const { data } = await api.get(+ `/admin/magento/webhooks/${webhook.id}/deliveries`,+ adminHeaders+ )+ return data.deliveries.some((d: any) => d.status === "delivered")+ })+ const { data } = await api.get(+ `/admin/magento/webhooks/${webhook.id}/deliveries?status=delivered`,+ adminHeaders+ )+ expect(data).toEqual(expect.objectContaining({ count: 1, offset: 0, limit: 50 }))+ expect(data.deliveries[0]).toEqual(+ expect.objectContaining({+ event: "seller.updated",+ attempts: 1,+ response_status: 200,+ next_attempt_at: null,+ })+ )+ })++ it("schedules a retry on failure and redelivers on demand", async () => {+ receiver.respondWith.status = 500++ const webhook = (+ await api.post(+ `/admin/magento/webhooks`,+ { url: receiver.url, events: ["seller.updated"] },+ adminHeaders+ )+ ).data.webhook++ const { headers } = await createSellerUser(appContainer, {+ email: "[email protected]",+ name: "Retry",+ })+ await api.post(`/vendor/sellers/me`, { name: "Retry Renamed" }, headers)++ let delivery: any+ await waitFor(async () => {+ const { data } = await api.get(+ `/admin/magento/webhooks/${webhook.id}/deliveries`,+ adminHeaders+ )+ delivery = data.deliveries.find((d: any) => d.status === "failed")+ return !!delivery+ })+ expect(delivery.attempts).toEqual(1)+ expect(delivery.response_status).toEqual(500)+ expect(new Date(delivery.next_attempt_at).getTime()).toBeGreaterThan(Date.now())++ receiver.respondWith.status = 200+ const redelivered = await api.post(+ `/admin/magento/webhooks/${webhook.id}/deliveries/${delivery.id}/redeliver`,+ {},+ adminHeaders+ )+ expect(redelivered.data.delivery).toEqual(+ expect.objectContaining({ status: "delivered", attempts: 2, response_status: 200 })+ )+ })++ it("does not deliver events the endpoint did not subscribe to", async () => {+ await api.post(+ `/admin/magento/webhooks`,+ { url: receiver.url, events: ["offer.created"] },+ adminHeaders+ )+ const { headers } = await createSellerUser(appContainer, {+ email: "[email protected]",+ name: "Silent",+ })+ await api.post(`/vendor/sellers/me`, { name: "Silent Renamed" }, headers)++ await new Promise((resolve) => setTimeout(resolve, 1500))+ expect(receiver.received).toHaveLength(0)+ })+ })+ },+})diff --git a/integration-tests/http/offer/admin/offer-soft-delete.spec.ts b/integration-tests/http/offer/admin/offer-soft-delete.spec.tsnew file mode 100644index 000000000..96216562c--- /dev/null+++ b/integration-tests/http/offer/admin/offer-soft-delete.spec.ts@@ -0,0 +1,82 @@+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"+import { MedusaContainer } from "@medusajs/framework/types"++import { adminHeaders, createAdminUser } from "../../../helpers/create-admin-user"+import { createSellerUser } from "../../../helpers/create-seller-user"+import { createShippingProfile } from "../../../helpers/create-shipping-profile"+import { createVendorProduct } from "../../../helpers/create-product"++jest.setTimeout(120000)++medusaIntegrationTestRunner({+ testSuite: ({ getContainer, api, dbConnection }) => {+ describe("Admin - Offers soft-delete visibility", () => {+ let appContainer: MedusaContainer+ let sellerHeaders: any+ let offerId: string++ beforeAll(async () => {+ appContainer = getContainer()+ })++ beforeEach(async () => {+ await createAdminUser(dbConnection, adminHeaders, appContainer)+ const { headers } = await createSellerUser(appContainer, {+ email: "[email protected]",+ name: "SoftDelete",+ })+ sellerHeaders = headers++ const shippingProfile = await createShippingProfile(appContainer, { name: "SoftDel Profile" })+ const product = await createVendorProduct(api, sellerHeaders, {+ title: "Soft Delete Product",+ sku: "SOFT-DEL",+ })+ const stockLocation = (+ await api.post(`/vendor/stock-locations`, { name: "SoftDel WH" }, sellerHeaders)+ ).data.stock_location++ offerId = (+ await api.post(+ `/vendor/offers`,+ {+ sku: "SOFT-DEL-OFFER",+ variant_id: product.variants[0].id,+ shipping_profile_id: shippingProfile.id,+ prices: [{ amount: 1000, currency_code: "usd" }],+ inventory_items: [+ {+ title: "SoftDel Inv",+ required_quantity: 1,+ stock_levels: [{ location_id: stockLocation.id, stocked_quantity: 5 }],+ },+ ],+ },+ sellerHeaders+ )+ ).data.offer.id+ })++ it("hides deleted offers by default and exposes them with with_deleted or a deleted_at filter", async () => {+ const before = new Date().toISOString()+ await api.delete(`/admin/offers/${offerId}`, adminHeaders)++ const hidden = await api.get(`/admin/offers?id=${offerId}`, adminHeaders)+ expect(hidden.data.offers).toHaveLength(0)++ const shown = await api.get(+ `/admin/offers?id=${offerId}&with_deleted=true`,+ adminHeaders+ )+ expect(shown.data.offers).toHaveLength(1)+ expect(shown.data.offers[0].deleted_at).toBeTruthy()++ const byCursor = await api.get(+ `/admin/offers?deleted_at[$gte]=${encodeURIComponent(before)}`,+ adminHeaders+ )+ expect(byCursor.data.offers.map((o: any) => o.id)).toContain(offerId)+ })+ })+ },+})diff --git a/integration-tests/medusa-config.ts b/integration-tests/medusa-config.tsindex 00a42713e..0e756dba4 100644--- a/integration-tests/medusa-config.ts+++ b/integration-tests/medusa-config.ts@@ -18,7 +18,21 @@ module.exports = withMercur({featureFlags: {seller_registration: true,},+ plugins: [+ { resolve: '@mercurjs/magento2-connector-plugin', options: {} },+ ],modules: [+ {+ resolve: '@medusajs/medusa/payment',+ options: {+ providers: [+ {+ resolve: '@mercurjs/magento2-connector-plugin/providers/payment-external',+ id: 'external',+ },+ ],+ },+ },{resolve: '@mercurjs/core/modules/admin-ui',options: {diff --git a/integration-tests/package.json b/integration-tests/package.jsonindex e45425379..bf321371f 100644--- a/integration-tests/package.json+++ b/integration-tests/package.json@@ -11,6 +11,7 @@"@medusajs/framework": "2.22.0","@medusajs/medusa": "2.22.0","@mercurjs/core": "*",+ "@mercurjs/magento2-connector-plugin": "*","jsonwebtoken": "^9.0.3","scrypt-kdf": "^2.0.1","@medusajs/draft-order": "2.22.0",diff --git a/package.json b/package.jsonindex fdc0cc2e0..33d2d68b7 100644--- a/package.json+++ b/package.json@@ -30,6 +30,7 @@"apps/*","packages/*","packages/providers/*",+ "packages/plugins/*","integration-tests","e2e-tests","e2e-tests/hosts/*"diff --git a/packages/admin/src/lib/client/auth-token.ts b/packages/admin/src/lib/client/auth-token.tsindex 68af12da6..d8f466e5a 100644--- a/packages/admin/src/lib/client/auth-token.ts+++ b/packages/admin/src/lib/client/auth-token.ts@@ -1,31 +1,7 @@-const AUTH_TOKEN_KEY = 'mercur_admin_auth_token'+import { adminAuth, adminTokenStore, resolveAuthHeaders } from '@mercurjs/client'-const read = (key: string) => {- try {- return localStorage.getItem(key)- } catch {- return null- }-}+export const getAuthToken = () => adminTokenStore.get()+export const setAuthToken = (token: string) => adminTokenStore.set(token)+export const clearAuthToken = () => adminTokenStore.clear()-const write = (key: string, value: string | null) => {- try {- if (value === null) {- localStorage.removeItem(key)- } else {- localStorage.setItem(key, value)- }- } catch {- return- }-}--export const getAuthToken = () => read(AUTH_TOKEN_KEY)-export const setAuthToken = (token: string) => write(AUTH_TOKEN_KEY, token)-export const clearAuthToken = () => write(AUTH_TOKEN_KEY, null)--export const getAuthHeaders = (): Record<string, string> => {- const token = getAuthToken()-- return token ? { Authorization: `Bearer ${token}` } : {}-}+export const getAuthHeaders = () => resolveAuthHeaders(adminAuth())diff --git a/packages/admin/src/lib/client/client.ts b/packages/admin/src/lib/client/client.tsindex 07787f2f9..5ca146555 100644--- a/packages/admin/src/lib/client/client.ts+++ b/packages/admin/src/lib/client/client.ts@@ -1,4 +1,4 @@-import { createClient, InferClient } from '@mercurjs/client'+import { createClient, InferClient, adminAuth } from '@mercurjs/client'import { Routes } from '@mercurjs/core/_generated'import config from 'virtual:mercur/config'@@ -12,7 +12,7 @@ export const sdk: InferClient<Routes> = createClient({fetchOptions: {credentials: 'omit',},- headers: getAuthHeaders,+ auth: adminAuth(),})export const fetchQuery = async (@@ -60,7 +60,7 @@ export const fetchQuery = async (credentials: 'omit',headers: {'Content-Type': 'application/json',- ...getAuthHeaders(),+ ...(await getAuthHeaders()),...headers,},body: body ? JSON.stringify(body) : null,diff --git a/packages/client/package.json b/packages/client/package.jsonindex e77abbf96..00474c73c 100644--- a/packages/client/package.json+++ b/packages/client/package.json@@ -32,7 +32,8 @@"scripts": {"typecheck": "tsc --noEmit","dev": "tsup --watch",- "build": "tsup"+ "build": "tsup",+ "test": "vitest run"},"dependencies": {"@tanstack/react-query": "^5.64.2",@@ -42,7 +43,8 @@"@medusajs/framework": "2.22.0","@types/qs": "^6.9.18","tsup": "^8.5.0",- "typescript": "5.9.3"+ "typescript": "5.9.3",+ "vitest": "^3.2.4"},"peerDependencies": {"typescript": ">=4.8.0"diff --git a/packages/client/src/__tests__/auth.spec.ts b/packages/client/src/__tests__/auth.spec.tsnew file mode 100644index 000000000..9aaba9d47--- /dev/null+++ b/packages/client/src/__tests__/auth.spec.ts@@ -0,0 +1,123 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import {+ adminTokenStore,+ apiKeyAuth,+ bearerAuth,+ createClient,+ createTokenStore,+ headerAuth,+ publishableKeyAuth,+ resolveAuthHeaders,+} from "..";++const memory = () => {+ const map = new Map<string, string>();+ return {+ getItem: (k: string) => map.get(k) ?? null,+ setItem: (k: string, v: string) => void map.set(k, v),+ removeItem: (k: string) => void map.delete(k),+ };+};++describe("createTokenStore", () => {+ it("reads, writes, clears and notifies subscribers", () => {+ const store = createTokenStore("t", memory());+ const seen: (string | null)[] = [];+ const unsubscribe = store.subscribe((t) => seen.push(t));++ expect(store.get()).toBeNull();+ store.set("abc");+ expect(store.get()).toBe("abc");+ store.clear();+ expect(store.get()).toBeNull();+ unsubscribe();+ store.set("ignored");++ expect(seen).toEqual(["abc", null]);+ });++ it("survives a storage that throws", () => {+ const store = createTokenStore("t", {+ getItem: () => {+ throw new Error("blocked");+ },+ setItem: () => {+ throw new Error("blocked");+ },+ removeItem: () => {+ throw new Error("blocked");+ },+ });+ expect(() => store.set("x")).not.toThrow();+ expect(store.get()).toBeNull();+ });+});++describe("resolveAuthHeaders", () => {+ it("turns a bare token store into a bearer header", async () => {+ const store = createTokenStore("t", memory());+ store.set("tok");+ expect(await resolveAuthHeaders(store)).toEqual({ Authorization: "Bearer tok" });+ });++ it("sends secret keys as basic auth and publishable keys as their header", async () => {+ expect(await resolveAuthHeaders(apiKeyAuth(() => "sk_123"))).toEqual({+ Authorization: `Basic ${btoa("sk_123:")}`,+ });+ expect(await resolveAuthHeaders(publishableKeyAuth(async () => "pk_123"))).toEqual({+ "x-publishable-api-key": "pk_123",+ });+ });++ it("combines schemes and skips empty credentials", async () => {+ const seller = createTokenStore("s", memory());+ expect(+ await resolveAuthHeaders([bearerAuth(() => null), headerAuth("x-seller-id", seller)])+ ).toEqual({});+ seller.set("sel_1");+ expect(+ await resolveAuthHeaders([bearerAuth(() => "tok"), headerAuth("x-seller-id", seller)])+ ).toEqual({ Authorization: "Bearer tok", "x-seller-id": "sel_1" });+ });+});++describe("createClient auth", () => {+ const fetchMock = vi.fn();+ afterEach(() => {+ fetchMock.mockReset();+ adminTokenStore.clear();+ });++ const json = (status: number, body: unknown) =>+ new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });++ it("resolves the token on every request, not when the client is created", async () => {+ vi.stubGlobal("fetch", fetchMock.mockImplementation(() => Promise.resolve(json(200, { ok: true }))));+ const store = createTokenStore("t", memory());+ const client = createClient({ baseUrl: "http://api.test", auth: store }) as any;++ await client.admin.sellers.query();+ expect((fetchMock.mock.calls[0][1].headers as Headers).get("authorization")).toBeNull();++ store.set("later");+ await client.admin.sellers.query();+ expect((fetchMock.mock.calls[1][1].headers as Headers).get("authorization")).toBe("Bearer later");+ });++ it("clears the bearer store on 401 unless a handler is given", async () => {+ vi.stubGlobal("fetch", fetchMock.mockImplementation(() => Promise.resolve(json(401, { message: "Unauthorized" }))));+ adminTokenStore.set("stale");+ const client = createClient({ baseUrl: "http://api.test", auth: bearerAuth(adminTokenStore) }) as any;++ await expect(client.admin.sellers.query()).rejects.toMatchObject({ status: 401 });+ expect(adminTokenStore.get()).toBeNull();++ adminTokenStore.set("kept");+ const onUnauthorized = vi.fn();+ const custom = createClient({ baseUrl: "http://api.test", auth: adminTokenStore, onUnauthorized }) as any;+ await expect(custom.admin.sellers.query()).rejects.toMatchObject({ status: 401 });+ expect(onUnauthorized).toHaveBeenCalledWith({ status: 401, message: "Unauthorized" });+ expect(adminTokenStore.get()).toBe("kept");+ });+});diff --git a/packages/client/src/auth.ts b/packages/client/src/auth.tsnew file mode 100644index 000000000..d87a901f3--- /dev/null+++ b/packages/client/src/auth.ts@@ -0,0 +1,181 @@+/**+ * Token storage and request authentication for the client.+ *+ * A token store keeps one credential under one key and survives reloads+ * through `localStorage` when it exists, falling back to memory on the server+ * or when storage is blocked. An auth scheme turns stores into the headers a+ * Mercur API expects, resolved freshly on every request.+ */++export type TokenStorage = {+ getItem(key: string): string | null;+ setItem(key: string, value: string): void;+ removeItem(key: string): void;+};++export type TokenStore = {+ readonly key: string;+ get(): string | null;+ set(token: string): void;+ clear(): void;+ /** Called with the new value after every `set` and `clear`, in this tab. */+ subscribe(listener: (token: string | null) => void): () => void;+};++const memoryStorage = (): TokenStorage => {+ const map = new Map<string, string>();+ return {+ getItem: (key) => map.get(key) ?? null,+ setItem: (key, value) => void map.set(key, value),+ removeItem: (key) => void map.delete(key),+ };+};++const resolveStorage = (storage?: TokenStorage): TokenStorage => {+ if (storage) return storage;+ try {+ if (typeof localStorage !== "undefined") {+ // A throwing accessor (private mode, blocked storage) must not take the client down.+ localStorage.getItem("__mercur_probe__");+ return localStorage;+ }+ } catch {+ // fall through+ }+ return memoryStorage();+};++export function createTokenStore(key: string, storage?: TokenStorage): TokenStore {+ const backing = resolveStorage(storage);+ const listeners = new Set<(token: string | null) => void>();+ const notify = (token: string | null) => listeners.forEach((l) => l(token));++ return {+ key,+ get() {+ try {+ return backing.getItem(key);+ } catch {+ return null;+ }+ },+ set(token) {+ try {+ backing.setItem(key, token);+ } catch {+ return;+ }+ notify(token);+ },+ clear() {+ try {+ backing.removeItem(key);+ } catch {+ return;+ }+ notify(null);+ },+ subscribe(listener) {+ listeners.add(listener);+ return () => void listeners.delete(listener);+ },+ };+}++type MaybePromise<T> = T | Promise<T>;+type Credential = string | null | undefined;++/** One way of authenticating a request. Several can be combined in `ClientOptions.auth`. */+export type AuthScheme =+ | { type: "bearer"; token: TokenStore | (() => MaybePromise<Credential>) }+ | { type: "api-key"; key: TokenStore | (() => MaybePromise<Credential>) }+ | { type: "publishable-key"; key: TokenStore | (() => MaybePromise<Credential>) }+ | { type: "header"; name: string; value: TokenStore | (() => MaybePromise<Credential>) };++export type AuthOption = TokenStore | AuthScheme | AuthScheme[];++const read = (source: TokenStore | (() => MaybePromise<Credential>)): MaybePromise<Credential> =>+ typeof source === "function" ? source() : source.get();++const isTokenStore = (value: unknown): value is TokenStore =>+ typeof value === "object" && value !== null && "get" in value && "subscribe" in value;++const toBase64 = (value: string): string =>+ typeof btoa === "function" ? btoa(value) : Buffer.from(value, "utf8").toString("base64");++/** The session token of an admin or vendor panel user, as `Authorization: Bearer`. */+export const bearerAuth = (token: TokenStore | (() => MaybePromise<Credential>)): AuthScheme => ({ type: "bearer", token });++/** A secret API key (`sk_…`), sent the way Medusa expects it: HTTP Basic with the key as the user. */+export const apiKeyAuth = (key: TokenStore | (() => MaybePromise<Credential>)): AuthScheme => ({ type: "api-key", key });++/** A publishable API key (`pk_…`) for the Store API. */+export const publishableKeyAuth = (key: TokenStore | (() => MaybePromise<Credential>)): AuthScheme => ({ type: "publishable-key", key });++/** Any other credential header, e.g. the vendor panel's active seller. */+export const headerAuth = (name: string, value: TokenStore | (() => MaybePromise<Credential>)): AuthScheme => ({ type: "header", name, value });++export async function resolveAuthHeaders(auth: AuthOption | undefined): Promise<Record<string, string>> {+ if (!auth) return {};+ const schemes: AuthScheme[] = isTokenStore(auth) ? [bearerAuth(auth)] : Array.isArray(auth) ? auth : [auth];+ const headers: Record<string, string> = {};++ for (const scheme of schemes) {+ switch (scheme.type) {+ case "bearer": {+ const token = await read(scheme.token);+ if (token) headers.Authorization = `Bearer ${token}`;+ break;+ }+ case "api-key": {+ const key = await read(scheme.key);+ if (key) headers.Authorization = `Basic ${toBase64(`${key}:`)}`;+ break;+ }+ case "publishable-key": {+ const key = await read(scheme.key);+ if (key) headers["x-publishable-api-key"] = key;+ break;+ }+ case "header": {+ const value = await read(scheme.value);+ if (value) headers[scheme.name] = value;+ break;+ }+ }+ }++ return headers;+}++/** Clears every token store the auth option reads from; used after a 401. */+export function clearAuthStores(auth: AuthOption | undefined): void {+ if (!auth) return;+ const schemes: AuthScheme[] = isTokenStore(auth) ? [bearerAuth(auth)] : Array.isArray(auth) ? auth : [auth];+ for (const scheme of schemes) {+ const source = scheme.type === "bearer" ? scheme.token : scheme.type === "header" ? scheme.value : scheme.key;+ if (isTokenStore(source) && scheme.type === "bearer") source.clear();+ }+}++/**+ * The stores the admin and vendor panels keep their sessions in. A plugin's+ * dashboard code reads the same session by using the same store, so it never+ * has to know the storage key.+ */+export const ADMIN_TOKEN_KEY = "mercur_admin_auth_token";+export const VENDOR_TOKEN_KEY = "mercur_vendor_auth_token";+export const VENDOR_SELLER_KEY = "mercur_vendor_seller_id";++export const adminTokenStore: TokenStore = createTokenStore(ADMIN_TOKEN_KEY);+export const vendorTokenStore: TokenStore = createTokenStore(VENDOR_TOKEN_KEY);+export const vendorSellerStore: TokenStore = createTokenStore(VENDOR_SELLER_KEY);++/** Auth for anything that talks to `/admin/*` as the signed-in panel user. */+export const adminAuth = (): AuthScheme[] => [bearerAuth(adminTokenStore)];++/** Auth for `/vendor/*` as the signed-in seller member, scoped to the active seller. */+export const vendorAuth = (): AuthScheme[] => [+ bearerAuth(vendorTokenStore),+ headerAuth("x-seller-id", vendorSellerStore),+];diff --git a/packages/client/src/index.ts b/packages/client/src/index.tsindex b3b29bf0c..2ad008c31 100644--- a/packages/client/src/index.ts+++ b/packages/client/src/index.ts@@ -3,6 +3,8 @@ import { createRecursiveProxy } from "./create-proxy";import { ActionType, ClientOptions } from "./types";export type { InferClient } from "./types";import { kebabCase } from "./utils";+import { clearAuthStores, resolveAuthHeaders } from "./auth";+export * from "./auth";type DistributiveOmit<T, K extends keyof any> = T extends any ? Omit<T, K> : never;@@ -72,9 +74,9 @@ const toFormData = (payload: Record<string, any>): FormData => {};export function createClient(options: ClientOptions) {- const { baseUrl, fetchOptions: defaultFetchOptions, headers: resolveHeaders } = options;+ const { baseUrl, fetchOptions: defaultFetchOptions, headers: resolveHeaders, auth, onUnauthorized } = options;- return createRecursiveProxy((path, args) => {+ return createRecursiveProxy(async (path, args) => {const action = path.pop() as ActionType;const input: Record<string, any> = args[0] ?? {};@@ -128,9 +130,10 @@ export function createClient(options: ClientOptions) {const headers = new Headers({...defaultHeaders,- ...defaultFetchOptions?.headers,- ...resolveHeaders?.(),- ...inputFetchOptions?.headers,+ ...(defaultFetchOptions?.headers as Record<string, string> | undefined),+ ...(await resolveAuthHeaders(auth)),+ ...(await resolveHeaders?.()),+ ...(inputFetchOptions?.headers as Record<string, string> | undefined),});return fetch(url, {@@ -145,6 +148,10 @@ export function createClient(options: ClientOptions) {message?: string;code?: string;};+ if (response.status === 401) {+ const message = jsonError.message ?? response.statusText;+ onUnauthorized ? onUnauthorized({ status: 401, message }) : clearAuthStores(auth);+ }throw new ClientError(jsonError.message ?? response.statusText,response.statusText,diff --git a/packages/client/src/types/client.ts b/packages/client/src/types/client.tsindex a80aa7e1b..e2bc738cb 100644--- a/packages/client/src/types/client.ts+++ b/packages/client/src/types/client.ts@@ -1,3 +1,4 @@+import type { AuthOption } from "../auth";import { ChildKeys, InferInput, InferOutput, TypeError } from "./helpers";export type ActionType = "query" | "mutate" | "delete";@@ -5,7 +6,19 @@ export type ActionType = "query" | "mutate" | "delete";export type ClientOptions = {baseUrl: string;fetchOptions?: RequestInit;- headers?: () => Record<string, string>;+ /**+ * How requests authenticate: a token store (sent as a bearer token), one+ * scheme, or several. Resolved on every request, so a token set after the+ * client was created is picked up by the next call.+ */+ auth?: AuthOption;+ /** Extra headers computed per request, on top of `auth`. */+ headers?: () => Record<string, string> | Promise<Record<string, string>>;+ /**+ * Runs when the API answers 401. By default the bearer token stores in+ * `auth` are cleared so the panel falls back to its login screen.+ */+ onUnauthorized?: (error: { status: number; message: string }) => void;};type AddParamsToFn<Fn, TParams> =diff --git a/packages/client/vitest.config.ts b/packages/client/vitest.config.tsnew file mode 100644index 000000000..1f91d442a--- /dev/null+++ b/packages/client/vitest.config.ts@@ -0,0 +1,8 @@+import { defineConfig } from "vitest/config";++export default defineConfig({+ test: {+ include: ["src/**/*.spec.ts"],+ environment: "node",+ },+});diff --git a/packages/core/src/api/admin/offers/route.ts b/packages/core/src/api/admin/offers/route.tsindex 3c0a45e6e..a1d8710a5 100644--- a/packages/core/src/api/admin/offers/route.ts+++ b/packages/core/src/api/admin/offers/route.ts@@ -12,11 +12,14 @@ export const GET = async () => {const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)+ const filters = req.filterableFields+const { data: offers, metadata } = await query.graph({entity: "offer",fields: req.queryConfig.fields,- filters: req.filterableFields,+ filters,pagination: req.queryConfig.pagination,+ withDeleted: req.queryConfig.withDeleted || "deleted_at" in filters,})res.json({diff --git a/packages/core/src/api/admin/offers/validators.ts b/packages/core/src/api/admin/offers/validators.tsindex 09c303c1d..e278491dd 100644--- a/packages/core/src/api/admin/offers/validators.ts+++ b/packages/core/src/api/admin/offers/validators.ts@@ -36,6 +36,7 @@ export const AdminGetOffersParams = createFindParams({tag_id: z.union([z.string(), z.array(z.string())]).optional(),created_at: createOperatorMap().optional(),updated_at: createOperatorMap().optional(),+ deleted_at: createOperatorMap().optional(),}))diff --git a/packages/core/src/api/admin/order-groups/query-config.ts b/packages/core/src/api/admin/order-groups/query-config.tsindex 7c66af3eb..baef8abee 100644--- a/packages/core/src/api/admin/order-groups/query-config.ts+++ b/packages/core/src/api/admin/order-groups/query-config.ts@@ -1,6 +1,7 @@export const adminOrderGroupFields = ["id","customer_id",+ "metadata","seller_count","total","created_at",diff --git a/packages/core/src/api/admin/sellers/route.ts b/packages/core/src/api/admin/sellers/route.tsindex bd488595e..97e6fc11a 100644--- a/packages/core/src/api/admin/sellers/route.ts+++ b/packages/core/src/api/admin/sellers/route.ts@@ -14,11 +14,14 @@ export const GET = async () => {const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)+ const filters = req.filterableFields+const { data: sellers, metadata } = await query.graph({entity: "seller",fields: req.queryConfig.fields,- filters: req.filterableFields,+ filters,pagination: req.queryConfig.pagination,+ withDeleted: req.queryConfig.withDeleted || "deleted_at" in filters,})res.json({diff --git a/packages/core/src/api/admin/sellers/validators.ts b/packages/core/src/api/admin/sellers/validators.tsindex 36325f949..45bcfef31 100644--- a/packages/core/src/api/admin/sellers/validators.ts+++ b/packages/core/src/api/admin/sellers/validators.ts@@ -27,6 +27,7 @@ export const AdminGetSellersParams = createFindParams({region_id: z.union([z.string(), z.array(z.string())]).optional(),created_at: createOperatorMap().optional(),updated_at: createOperatorMap().optional(),+ deleted_at: createOperatorMap().optional(),}))diff --git a/packages/core/src/api/store/order-groups/query-config.ts b/packages/core/src/api/store/order-groups/query-config.tsindex 300295c3a..245d043f1 100644--- a/packages/core/src/api/store/order-groups/query-config.ts+++ b/packages/core/src/api/store/order-groups/query-config.ts@@ -2,6 +2,7 @@ export const storeOrderGroupFields = ["id","display_id","customer_id",+ "metadata","seller_count","total","created_at",diff --git a/packages/core/src/modules/seller/migrations/Migration20261021120000.ts b/packages/core/src/modules/seller/migrations/Migration20261021120000.tsnew file mode 100644index 000000000..0e1903173--- /dev/null+++ b/packages/core/src/modules/seller/migrations/Migration20261021120000.ts@@ -0,0 +1,13 @@+import { Migration } from "@medusajs/framework/mikro-orm/migrations"++export class Migration20261021120000 extends Migration {+ override async up(): Promise<void> {+ this.addSql(+ `ALTER TABLE IF EXISTS "order_group" ADD COLUMN IF NOT EXISTS "metadata" jsonb NULL;`+ )+ }++ override async down(): Promise<void> {+ this.addSql(`ALTER TABLE IF EXISTS "order_group" DROP COLUMN IF EXISTS "metadata";`)+ }+}diff --git a/packages/core/src/modules/seller/models/order-group.ts b/packages/core/src/modules/seller/models/order-group.tsindex fc90b06b1..26e299d98 100644--- a/packages/core/src/modules/seller/models/order-group.ts+++ b/packages/core/src/modules/seller/models/order-group.ts@@ -8,6 +8,7 @@ const OrderGroup = modelcustomer_id: model.text().nullable(),total: model.bigNumber().computed(),cart_id: model.text(),+ metadata: model.json().nullable(),}).indexes([{diff --git a/packages/core/src/permissions/__tests__/registry.unit.spec.ts b/packages/core/src/permissions/__tests__/registry.unit.spec.tsindex 0f2ad8ded..ce35504d2 100644--- a/packages/core/src/permissions/__tests__/registry.unit.spec.ts+++ b/packages/core/src/permissions/__tests__/registry.unit.spec.ts@@ -23,7 +23,7 @@ describe("permission catalog", () => {const catalog = getPermissionCatalog()expect(catalog.map((p) => p.key)).toEqual(- expect.arrayContaining(["orders", "orders.refunds", "payouts", "sellers"])+ expect.arrayContaining(["orders", "orders.refunds", "payouts", "sellers", "integrations"]))expect(() => validatePermissionCatalog(catalog)).not.toThrow()})diff --git a/packages/core/src/permissions/definitions/integrations.ts b/packages/core/src/permissions/definitions/integrations.tsnew file mode 100644index 000000000..b804e0a9e--- /dev/null+++ b/packages/core/src/permissions/definitions/integrations.ts@@ -0,0 +1,5 @@+import { defineMercurPermissions } from "../registry"++export const integrationsPermissions = defineMercurPermissions([+ { key: "integrations", group: "integrations", surface: ["admin"], rights: ["view", "edit", "manage"] },+])diff --git a/packages/core/src/permissions/index.ts b/packages/core/src/permissions/index.tsindex a5259988f..8be4bfba4 100644--- a/packages/core/src/permissions/index.ts+++ b/packages/core/src/permissions/index.ts@@ -24,5 +24,6 @@ import "./definitions/translations"import "./definitions/notifications"import "./definitions/workflow-executions"import "./definitions/reviews"+import "./definitions/integrations"export * from "./registry"diff --git a/packages/core/src/workflows/cart/workflows/complete-cart-with-split-orders.ts b/packages/core/src/workflows/cart/workflows/complete-cart-with-split-orders.tsindex d82dacada..c3f524411 100644--- a/packages/core/src/workflows/cart/workflows/complete-cart-with-split-orders.ts+++ b/packages/core/src/workflows/cart/workflows/complete-cart-with-split-orders.ts@@ -402,6 +402,7 @@ export const completeCartWithSplitOrdersWorkflow = createWorkflow(return {customer_id: cart.customer?.id,cart_id: cart.id,+ metadata: cart.metadata ?? null,} satisfies CreateOrderGroupDTO})diff --git a/packages/dashboard-sdk/src/permissions.ts b/packages/dashboard-sdk/src/permissions.tsindex ef68c440e..52d899f73 100644--- a/packages/dashboard-sdk/src/permissions.ts+++ b/packages/dashboard-sdk/src/permissions.ts@@ -57,6 +57,7 @@ export interface PermissionKeys {"shipping_profiles": true"shipping_options": true"fulfillment_sets": true+ "integrations": true"regions": true"tax_regions": true"store": truediff --git a/packages/plugins/magento2-connector/.gitignore b/packages/plugins/magento2-connector/.gitignorenew file mode 100644index 000000000..f02823277--- /dev/null+++ b/packages/plugins/magento2-connector/.gitignore@@ -0,0 +1,2 @@+.medusa+node_modulesdiff --git a/packages/plugins/magento2-connector/README.md b/packages/plugins/magento2-connector/README.mdnew file mode 100644index 000000000..a15a4fab9--- /dev/null+++ b/packages/plugins/magento2-connector/README.md@@ -0,0 +1,56 @@+# @mercurjs/magento2-connector-plugin++Server-side half of the Mercur Magento 2 connector. Pairs with the+`mercurjs/magento2-connector` Composer package installed in Magento.++It adds to a Mercur API:++- **Outbound webhooks** (`magento_webhook` module): register endpoints under+ `/admin/magento/webhooks`, pick the events to receive, and Mercur POSTs each+ event with an HMAC-SHA256 signature in `x-mercur-signature`. Failed+ deliveries retry on a 1m / 5m / 30m / 2h / 12h ladder, then stop.+- **External payment provider** (`pp_external_external`): lets a storefront+ that already captured the customer's payment complete a Mercur cart with+ the captured amount, so split orders, commission lines, and payouts run on+ real numbers without Mercur charging anything.+- **External refunds**: `POST /admin/magento/orders/:id/refunds/external`+ mirrors a refund that happened in the storefront onto the Mercur order.++## Install++```ts+// medusa-config.ts+module.exports = withMercur({+ plugins: [{ resolve: "@mercurjs/magento2-connector-plugin", options: {} }],+ modules: [+ {+ resolve: "@medusajs/medusa/payment",+ options: {+ providers: [+ {+ resolve: "@mercurjs/magento2-connector-plugin/providers/payment-external",+ id: "external",+ },+ ],+ },+ },+ ],+})+```++Run `medusa db:migrate` afterwards.++## Checkout from an external storefront++1. `POST /store/carts` with `region_id` and `sales_channel_id`.+2. `POST /store/carts/:id/line-items` with `{ offer_id, quantity }` per line.+3. `POST /store/carts/:id` with email and addresses.+4. `GET /store/shipping-options?cart_id=` then one+ `POST /store/carts/:id/shipping-methods` per seller.+5. `POST /store/payment-collections` and+ `POST /store/payment-collections/:id/payment-sessions` with+ `{ provider_id: "pp_external_external", data: { reference, captured_at, channel } }`.+6. `POST /store/carts/:id/complete`.++Put `metadata.channel` on the cart in step 1; it is copied onto the order+group and every child order.diff --git a/packages/plugins/magento2-connector/package.json b/packages/plugins/magento2-connector/package.jsonnew file mode 100644index 000000000..acbfc434f--- /dev/null+++ b/packages/plugins/magento2-connector/package.json@@ -0,0 +1,98 @@+{+ "name": "@mercurjs/magento2-connector-plugin",+ "version": "2.3.8",+ "description": "Mercur plugin that lets a Magento 2 storefront sell marketplace offers: outbound webhooks, an external payment provider, and external refund recording.",+ "repository": {+ "type": "git",+ "url": "https://github.com/mercurjs/mercur",+ "directory": "packages/plugins/magento2-connector"+ },+ "author": "Mercur",+ "license": "MIT",+ "files": [+ ".medusa/server"+ ],+ "exports": {+ "./package.json": "./package.json",+ "./workflows": "./.medusa/server/src/workflows/index.js",+ "./types": "./.medusa/server/src/types/index.js",+ "./.medusa/server/src/modules/*": "./.medusa/server/src/modules/*/index.js",+ "./modules/*": {+ "types": "./.medusa/server/src/modules/*/index.d.ts",+ "default": "./.medusa/server/src/modules/*/index.js"+ },+ "./providers/*": {+ "types": "./.medusa/server/src/providers/*/index.d.ts",+ "default": "./.medusa/server/src/providers/*/index.js"+ },+ "./*": "./.medusa/server/src/*.js",+ "./admin": {+ "import": "./.medusa/server/src/admin/index.mjs",+ "default": "./.medusa/server/src/admin/index.js"+ }+ },+ "keywords": [+ "medusa-plugin",+ "medusa-v2",+ "mercur",+ "marketplace",+ "magento2"+ ],+ "scripts": {+ "build": "rm -rf .medusa && tsc --declaration --outDir .medusa/server && bun run build:dashboards",+ "build:dashboards": "bun ./node_modules/@mercurjs/cli/dist/index.js dashboard:build --app admin --src src/admin --out .medusa/server/src/admin/index.mjs",+ "typecheck:admin": "tsc -p src/admin/tsconfig.json",+ "dev": "medusa plugin:develop",+ "prepublishOnly": "tsc --declaration --outDir .medusa/server && bun run build:dashboards"+ },+ "devDependencies": {+ "@medusajs/cli": "2.22.0",+ "@medusajs/core-flows": "2.22.0",+ "@medusajs/framework": "2.22.0",+ "@medusajs/medusa": "2.22.0",+ "@medusajs/types": "2.22.0",+ "@mercurjs/core": "2.3.8",+ "@mercurjs/types": "2.3.8",+ "@types/node": "^26.1.0",+ "typescript": "5.9.3",+ "@hookform/resolvers": "5.4.0",+ "@medusajs/icons": "2.22.0",+ "@medusajs/ui": "4.2.3",+ "@mercurjs/cli": "2.3.8",+ "@mercurjs/client": "2.3.8",+ "@mercurjs/dashboard-sdk": "2.3.8",+ "@mercurjs/dashboard-shared": "2.3.8",+ "@tanstack/react-query": "5.64.2",+ "@tanstack/react-table": "8.21.3",+ "@types/react": "^18.3.2",+ "react": "^18.3.1",+ "react-dom": "^18.3.1",+ "react-hook-form": "7.88.0",+ "react-router-dom": "7.18.1",+ "radix-ui": "1.1.2"+ },+ "peerDependencies": {+ "@medusajs/core-flows": ">=2.22.0",+ "@medusajs/framework": ">=2.22.0",+ "@medusajs/medusa": ">=2.22.0",+ "@mercurjs/core": "*",+ "@medusajs/icons": ">=2.22.0",+ "@medusajs/ui": ">=4.1.19",+ "@mercurjs/client": ">=2.3.8",+ "@mercurjs/dashboard-sdk": ">=2.3.8",+ "@mercurjs/dashboard-shared": ">=2.3.8",+ "@tanstack/react-query": "^5.64.2",+ "@tanstack/react-table": "^8.20.5",+ "react": "^18.0.0",+ "react-dom": "^18.0.0",+ "react-hook-form": "^7.49.1",+ "react-router-dom": "^7.0.0",+ "@hookform/resolvers": "^5.4.0"+ },+ "dependencies": {+ "zod": "4.6.5"+ },+ "engines": {+ "node": ">=22.22.0"+ }+}diff --git a/packages/plugins/magento2-connector/src/admin/hooks/api/magento.tsx b/packages/plugins/magento2-connector/src/admin/hooks/api/magento.tsxnew file mode 100644index 000000000..d6b9ca8cc--- /dev/null+++ b/packages/plugins/magento2-connector/src/admin/hooks/api/magento.tsx@@ -0,0 +1,166 @@+import { queryKeysFactory } from "@mercurjs/dashboard-shared"+import {+ useMutation,+ useQuery,+ useQueryClient,+ type UseMutationOptions,+ type UseQueryOptions,+} from "@tanstack/react-query"++import {+ client,+ type MagentoStatus,+ type MagentoWebhook,+ type MagentoWebhookDelivery,+ type MagentoWebhookDeliveryStatus,+} from "../../lib/client"++export const magentoStatusQueryKeys = queryKeysFactory("admin_magento_status")+export const magentoWebhookQueryKeys = queryKeysFactory("admin_magento_webhooks")+export const magentoDeliveryQueryKeys = queryKeysFactory("admin_magento_deliveries")++type QueryOptions<T> = Omit<UseQueryOptions<T, Error, T>, "queryKey" | "queryFn">++export const useMagentoStatus = (options?: QueryOptions<MagentoStatus>) => {+ const { data, ...rest } = useQuery({+ queryKey: magentoStatusQueryKeys.all,+ queryFn: () => client.admin.magento.status.query({}),+ ...options,+ })++ return { connection: data, ...rest }+}++export const useMagentoWebhooks = (+ query: { limit?: number; offset?: number } = {},+ options?: QueryOptions<{ webhooks: MagentoWebhook[]; count: number }>+) => {+ const { data, ...rest } = useQuery({+ queryKey: magentoWebhookQueryKeys.list(query),+ queryFn: () => client.admin.magento.webhooks.query(query),+ ...options,+ })++ return { webhooks: data?.webhooks, count: data?.count, ...rest }+}++export const useMagentoWebhook = (+ id: string,+ options?: QueryOptions<{ webhook: MagentoWebhook }>+) => {+ const { data, ...rest } = useQuery({+ queryKey: magentoWebhookQueryKeys.detail(id),+ queryFn: () => client.admin.magento.webhooks.$id.query({ $id: id }),+ ...options,+ })++ return { webhook: data?.webhook, ...rest }+}++export const useMagentoWebhookDeliveries = (+ id: string,+ query: {+ limit?: number+ offset?: number+ status?: MagentoWebhookDeliveryStatus | MagentoWebhookDeliveryStatus[]+ } = {},+ options?: QueryOptions<{ deliveries: MagentoWebhookDelivery[]; count: number }>+) => {+ const { data, ...rest } = useQuery({+ queryKey: magentoDeliveryQueryKeys.list({ id, ...query }),+ queryFn: () => client.admin.magento.webhooks.$id.deliveries.query({ $id: id, ...query }),+ ...options,+ })++ return { deliveries: data?.deliveries, count: data?.count, ...rest }+}++const useInvalidateMagento = () => {+ const queryClient = useQueryClient()++ return (id?: string) => {+ queryClient.invalidateQueries({ queryKey: magentoStatusQueryKeys.all })+ queryClient.invalidateQueries({ queryKey: magentoWebhookQueryKeys.lists() })+ queryClient.invalidateQueries({ queryKey: magentoDeliveryQueryKeys.lists() })+ if (id) {+ queryClient.invalidateQueries({ queryKey: magentoWebhookQueryKeys.detail(id) })+ }+ }+}++type CreateInput = { url: string; events: string[]; description?: string | null }++export const useCreateMagentoWebhook = (+ options?: UseMutationOptions<{ webhook: MagentoWebhook & { secret: string } }, Error, CreateInput>+) => {+ const invalidate = useInvalidateMagento()++ return useMutation({+ mutationFn: (payload: CreateInput) => client.admin.magento.webhooks.mutate(payload),+ ...options,+ onSuccess: (data, variables, context) => {+ invalidate()+ options?.onSuccess?.(data, variables, context)+ },+ })+}++type UpdateInput = {+ url?: string+ events?: string[]+ is_active?: boolean+ description?: string | null+}++export const useUpdateMagentoWebhook = (+ id: string,+ options?: UseMutationOptions<{ webhook: MagentoWebhook }, Error, UpdateInput>+) => {+ const invalidate = useInvalidateMagento()++ return useMutation({+ mutationFn: (payload: UpdateInput) =>+ client.admin.magento.webhooks.$id.mutate({ $id: id, ...payload }),+ ...options,+ onSuccess: (data, variables, context) => {+ invalidate(id)+ options?.onSuccess?.(data, variables, context)+ },+ })+}++export const useDeleteMagentoWebhook = (+ id: string,+ options?: UseMutationOptions<{ id: string; deleted: boolean }, Error, void>+) => {+ const invalidate = useInvalidateMagento()++ return useMutation({+ mutationFn: () => client.admin.magento.webhooks.$id.delete({ $id: id }),+ ...options,+ onSuccess: (data, variables, context) => {+ invalidate(id)+ options?.onSuccess?.(data, variables, context)+ },+ })+}++export const useRedeliverMagentoWebhook = (+ id: string,+ options?: UseMutationOptions<{ delivery: MagentoWebhookDelivery }, Error, string>+) => {+ const invalidate = useInvalidateMagento()++ return useMutation({+ mutationFn: (deliveryId: string) =>+ client.admin.magento.webhooks.$id.deliveries.$delivery_id.redeliver.mutate({+ $id: id,+ $delivery_id: deliveryId,+ }),+ ...options,+ onSuccess: (data, variables, context) => {+ invalidate(id)+ options?.onSuccess?.(data, variables, context)+ },+ })+}diff --git a/packages/plugins/magento2-connector/src/admin/hooks/use-action-blocker.ts b/packages/plugins/magento2-connector/src/admin/hooks/use-action-blocker.tsnew file mode 100644index 000000000..4df6f5c37--- /dev/null+++ b/packages/plugins/magento2-connector/src/admin/hooks/use-action-blocker.ts@@ -0,0 +1,18 @@+import { useCan } from "@mercurjs/dashboard-shared"+import type { PermissionKey, PermissionRight } from "@mercurjs/dashboard-sdk"+import { useMemo } from "react"++export const useActionBlocker = (+ key: PermissionKey,+ right: PermissionRight+): { disabled: boolean; disabledTooltip?: string } => {+ const allowed = useCan(key, right)++ return useMemo(+ () =>+ allowed+ ? { disabled: false }+ : { disabled: true, disabledTooltip: "You do not have permission to do this" },+ [allowed]+ )+}diff --git a/packages/plugins/magento2-connector/src/admin/lib/client.ts b/packages/plugins/magento2-connector/src/admin/lib/client.tsnew file mode 100644index 000000000..7b3671580--- /dev/null+++ b/packages/plugins/magento2-connector/src/admin/lib/client.ts@@ -0,0 +1,98 @@+import { adminAuth, createClient, type InferClient } from "@mercurjs/client"+import type { MedusaResponse } from "@medusajs/framework"+++export type MagentoWebhookDeliveryStatus = "pending" | "delivered" | "failed" | "dead"++export type MagentoWebhook = {+ id: string+ url: string+ events: string[]+ is_active: boolean+ description: string | null+ metadata: Record<string, unknown> | null+ created_at: string+ updated_at: string+}++export type MagentoWebhookDelivery = {+ id: string+ endpoint_id: string+ event: string+ payload: Record<string, unknown>+ status: MagentoWebhookDeliveryStatus+ attempts: number+ next_attempt_at: string | null+ response_status: number | null+ response_body: string | null+ delivered_at: string | null+ created_at: string+ updated_at: string+}++export type MagentoStatus = {+ payment_provider: { id: string; installed: boolean }+ events: string[]+ webhooks: { total: number; active: number }+ deliveries: {+ window_hours: number+ delivered: number+ failed: number+ dead: number+ pending: number+ last_delivered_at: string | null+ }+ orders: { channel: string; last_24h: number }+}++type ListQuery = { limit?: number; offset?: number }++type Route<Input, Output> = (+ req: { validatedBody: Input },+ res: MedusaResponse<Output>+) => Promise<void>++type Empty = { fields?: string }++type Routes = {+ admin: {+ magento: {+ status: { GET: Route<Empty, MagentoStatus> }+ webhooks: {+ GET: Route<+ ListQuery & { is_active?: boolean },+ { webhooks: MagentoWebhook[]; count: number; offset: number; limit: number }+ >+ POST: Route<+ { url: string; events: string[]; description?: string | null; secret?: string },+ { webhook: MagentoWebhook & { secret: string } }+ >+ $id: {+ GET: Route<Empty, { webhook: MagentoWebhook }>+ POST: Route<+ { url?: string; events?: string[]; is_active?: boolean; description?: string | null },+ { webhook: MagentoWebhook }+ >+ DELETE: Route<Empty, { id: string; object: string; deleted: boolean }>+ deliveries: {+ GET: Route<+ ListQuery & { status?: MagentoWebhookDeliveryStatus | MagentoWebhookDeliveryStatus[] },+ { deliveries: MagentoWebhookDelivery[]; count: number; offset: number; limit: number }+ >+ $delivery_id: {+ redeliver: {+ POST: Route<Empty, { delivery: MagentoWebhookDelivery }>+ }+ }+ }+ }+ }+ }+ }+}++export const client: InferClient<Routes> = createClient({+ baseUrl: import.meta.env.VITE_MERCUR_BACKEND_URL || "http://localhost:9000",+ fetchOptions: { credentials: "omit" },+ auth: adminAuth(),+})diff --git a/packages/plugins/magento2-connector/src/admin/providers/settings-providers.tsx b/packages/plugins/magento2-connector/src/admin/providers/settings-providers.tsxnew file mode 100644index 000000000..eaecb2571--- /dev/null+++ b/packages/plugins/magento2-connector/src/admin/providers/settings-providers.tsx@@ -0,0 +1,11 @@+import { TooltipProvider } from "@medusajs/ui"+import { queryClient } from "@mercurjs/dashboard-shared"+import { QueryClientProvider } from "@tanstack/react-query"+import type { ReactNode } from "react"++/** Settings routes mount outside the host dashboard's React providers, so each one supplies its own. */+export const SettingsProviders = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={queryClient}>+ <TooltipProvider>{children}</TooltipProvider>+ </QueryClientProvider>+)diff --git a/packages/plugins/magento2-connector/src/admin/routes/settings/magento/[id]/breadcrumb.tsx b/packages/plugins/magento2-connector/src/admin/routes/settings/magento/[id]/breadcrumb.tsxnew file mode 100644index 000000000..718b1268f--- /dev/null+++ b/packages/plugins/magento2-connector/src/admin/routes/settings/magento/[id]/breadcrumb.tsx@@ -0,0 +1,15 @@+import type { UIMatch } from "react-router-dom"++import { useMagentoWebhook } from "../../../../hooks/api/magento"++export const MagentoWebhookDetailBreadcrumb = (props: UIMatch) => {+ const { id } = props.params || {}++ const { webhook } = useMagentoWebhook(id!, { enabled: Boolean(id) })++ if (!webhook) {+ return null+ }++ return <span>{webhook.description || webhook.url}</span>+}diff --git a/packages/plugins/magento2-connector/src/admin/routes/settings/magento/[id]/components/magento-delivery-list-section.tsx b/packages/plugins/magento2-connector/src/admin/routes/settings/magento/[id]/components/magento-delivery-list-section.tsxnew file mode 100644index 000000000..70ad69361--- /dev/null+++ b/packages/plugins/magento2-connector/src/admin/routes/settings/magento/[id]/components/magento-delivery-list-section.tsx@@ -0,0 +1,153 @@+import { ArrowPath } from "@medusajs/icons"+import { Container, Heading, Text, toast } from "@medusajs/ui"+import {+ ActionMenu,+ DateCell,+ PlaceholderCell,+ StatusCell,+ TextCell,+ TextHeader,+ _DataTable,+ useDataTable,+} from "@mercurjs/dashboard-shared"+import { keepPreviousData } from "@tanstack/react-query"+import { createColumnHelper } from "@tanstack/react-table"+import { useMemo } from "react"++import {+ useMagentoWebhookDeliveries,+ useRedeliverMagentoWebhook,+} from "../../../../../hooks/api/magento"+import { useActionBlocker } from "../../../../../hooks/use-action-blocker"+import type { MagentoWebhookDelivery } from "../../../../../lib/client"+import {+ DELIVERY_STATE_COLOR,+ DELIVERY_STATE_LABEL,+ LIVE_DELIVERY_STATES,+} from "../../lib/delivery-state"++const PAGE_SIZE = 10++export const MagentoDeliveryListSection = ({ webhookId }: { webhookId: string }) => {+ const { deliveries, count, isPending, isError, error } = useMagentoWebhookDeliveries(+ webhookId,+ { limit: PAGE_SIZE },+ {+ placeholderData: keepPreviousData,+ refetchInterval: (query) =>+ query.state.data?.deliveries?.some((d) => LIVE_DELIVERY_STATES.includes(d.status))+ ? 3_000+ : false,+ }+ )++ const { mutateAsync: redeliver } = useRedeliverMagentoWebhook(webhookId, {+ onSuccess: ({ delivery }) =>+ delivery.status === "delivered"+ ? toast.success("Delivered")+ : toast.error(`Delivery failed with status ${delivery.response_status ?? "n/a"}`),+ onError: (e) => toast.error(e.message),+ })++ const data = useMemo(() => deliveries ?? [], [deliveries])+ const columns = useColumns(redeliver)++ const { table } = useDataTable({+ data,+ columns,+ count: count ?? 0,+ enablePagination: true,+ getRowId: (row) => row.id,+ pageSize: PAGE_SIZE,+ })++ if (isError) {+ throw error+ }++ return (+ <Container className="divide-y p-0" data-testid="magento-delivery-list-section">+ <div className="px-6 py-4">+ <Heading level="h2">Deliveries</Heading>+ <Text size="small" className="text-ui-fg-subtle">+ Most recent attempts to reach this endpoint.+ </Text>+ </div>+ <_DataTable+ table={table}+ columns={columns}+ count={count ?? 0}+ pageSize={PAGE_SIZE}+ isLoading={isPending}+ pagination+ noRecords={{+ title: "No deliveries yet",+ message: "Deliveries appear here once a subscribed event fires.",+ }}+ />+ </Container>+ )+}++const columnHelper = createColumnHelper<MagentoWebhookDelivery>()++const useColumns = (redeliver: (id: string) => Promise<unknown>) => {+ const redeliverBlocker = useActionBlocker("integrations", "edit")++ return useMemo(+ () => [+ columnHelper.accessor("event", {+ header: () => <TextHeader text="Event" />,+ cell: ({ getValue }) => <TextCell text={getValue()} />,+ }),+ columnHelper.accessor("status", {+ header: () => <TextHeader text="Status" />,+ cell: ({ getValue }) => (+ <StatusCell color={DELIVERY_STATE_COLOR[getValue()]}>+ {DELIVERY_STATE_LABEL[getValue()]}+ </StatusCell>+ ),+ }),+ columnHelper.accessor("response_status", {+ header: () => <TextHeader text="Response" />,+ cell: ({ getValue }) =>+ getValue() === null ? <PlaceholderCell /> : <TextCell text={String(getValue())} />,+ }),+ columnHelper.accessor("attempts", {+ header: () => <TextHeader text="Attempts" />,+ cell: ({ getValue }) => <TextCell text={String(getValue())} />,+ }),+ columnHelper.accessor("next_attempt_at", {+ header: () => <TextHeader text="Next attempt" />,+ cell: ({ getValue }) => {+ const value = getValue()+ return value ? <DateCell date={value} /> : <PlaceholderCell />+ },+ }),+ columnHelper.accessor("created_at", {+ header: () => <TextHeader text="Created" />,+ cell: ({ getValue }) => <DateCell date={getValue()} />,+ }),+ columnHelper.display({+ id: "actions",+ cell: ({ row }) => (+ <ActionMenu+ groups={[+ {+ actions: [+ {+ label: "Redeliver",+ icon: <ArrowPath />,+ onClick: () => redeliver(row.original.id),+ ...redeliverBlocker,+ },+ ],+ },+ ]}+ />+ ),+ }),+ ],+ [redeliver, redeliverBlocker]+ )+}diff --git a/packages/plugins/magento2-connector/src/admin/routes/settings/magento/[id]/components/magento-webhook-general-section.tsx b/packages/plugins/magento2-connector/src/admin/routes/settings/magento/[id]/components/magento-webhook-general-section.tsxnew file mode 100644index 000000000..5a5a3e15d--- /dev/null+++ b/packages/plugins/magento2-connector/src/admin/routes/settings/magento/[id]/components/magento-webhook-general-section.tsx@@ -0,0 +1,104 @@+import { PauseSolid, PlaySolid, Trash } from "@medusajs/icons"+import { Badge, Container, Heading, StatusBadge, toast, usePrompt } from "@medusajs/ui"+import { ActionMenu, SectionRow } from "@mercurjs/dashboard-shared"+import { useNavigate } from "react-router-dom"++import {+ useDeleteMagentoWebhook,+ useUpdateMagentoWebhook,+} from "../../../../../hooks/api/magento"+import { useActionBlocker } from "../../../../../hooks/use-action-blocker"+import type { MagentoWebhook } from "../../../../../lib/client"++export const MagentoWebhookGeneralSection = ({ webhook }: { webhook: MagentoWebhook }) => {+ const navigate = useNavigate()+ const prompt = usePrompt()+ const editBlocker = useActionBlocker("integrations", "edit")+ const deleteBlocker = useActionBlocker("integrations", "manage")++ const { mutateAsync: update } = useUpdateMagentoWebhook(webhook.id, {+ onError: (e) => toast.error(e.message),+ })+ const { mutateAsync: remove } = useDeleteMagentoWebhook(webhook.id, {+ onSuccess: () => {+ toast.success("Webhook endpoint deleted")+ navigate("/settings/magento", { replace: true })+ },+ onError: (e) => toast.error(e.message),+ })++ const handleDelete = async () => {+ const confirmed = await prompt({+ title: "Delete webhook endpoint?",+ description:+ "Magento will stop receiving events at this URL. Delivery history for it is removed.",+ confirmText: "Delete",+ cancelText: "Cancel",+ })+ if (confirmed) {+ await remove()+ }+ }++ return (+ <Container className="divide-y p-0" data-testid="magento-webhook-general-section">+ <div className="flex items-center justify-between px-6 py-4">+ <Heading>{webhook.description || "Webhook endpoint"}</Heading>+ <div className="flex items-center gap-x-2">+ {webhook.is_active ? (+ <StatusBadge color="green">Active</StatusBadge>+ ) : (+ <StatusBadge color="grey">Paused</StatusBadge>+ )}+ <ActionMenu+ groups={[+ {+ actions: [+ webhook.is_active+ ? {+ label: "Pause",+ icon: <PauseSolid />,+ onClick: () => update({ is_active: false }),+ ...editBlocker,+ }+ : {+ label: "Resume",+ icon: <PlaySolid />,+ onClick: () => update({ is_active: true }),+ ...editBlocker,+ },+ ],+ },+ {+ actions: [+ {+ label: "Delete",+ icon: <Trash />,+ onClick: handleDelete,+ ...deleteBlocker,+ },+ ],+ },+ ]}+ />+ </div>+ </div>+ <SectionRow title="ID" value={webhook.id} />+ <SectionRow title="URL" value={webhook.url} />+ <SectionRow+ title="Events"+ value={+ <div className="flex flex-wrap gap-1">+ {webhook.events.map((event) => (+ <Badge key={event} size="2xsmall">+ {event}+ </Badge>+ ))}+ </div>+ }+ />+ <SectionRow title="Signature" value="HMAC-SHA256 in the x-mercur-signature header" />+ <SectionRow title="Created" value={new Date(webhook.created_at).toLocaleString()} />+ </Container>+ )+}diff --git a/packages/plugins/magento2-connector/src/admin/routes/settings/magento/[id]/page.tsx b/packages/plugins/magento2-connector/src/admin/routes/settings/magento/[id]/page.tsxnew file mode 100644index 000000000..382f7cba4--- /dev/null+++ b/packages/plugins/magento2-connector/src/admin/routes/settings/magento/[id]/page.tsx@@ -0,0 +1,44 @@+import { SingleColumnPage, SingleColumnPageSkeleton, WidgetZone } from "@mercurjs/dashboard-shared"+import { useParams, type UIMatch } from "react-router-dom"++import { useMagentoWebhook } from "../../../../hooks/api/magento"+import { SettingsProviders } from "../../../../providers/settings-providers"+import { MagentoWebhookDetailBreadcrumb } from "./breadcrumb"+import { MagentoDeliveryListSection } from "./components/magento-delivery-list-section"+import { MagentoWebhookGeneralSection } from "./components/magento-webhook-general-section"++const MagentoWebhookDetailPage = () => {+ const { id } = useParams()++ const { webhook, isLoading, isError, error } = useMagentoWebhook(id!)++ if (isError) {+ throw error+ }++ if (isLoading || !webhook) {+ return <SingleColumnPageSkeleton sections={2} />+ }++ return (+ <SingleColumnPage data={webhook} data-testid="magento-webhook-detail-page">+ <WidgetZone id="magento.detail.main">+ <MagentoWebhookGeneralSection webhook={webhook} />+ <MagentoDeliveryListSection webhookId={webhook.id} />+ </WidgetZone>+ </SingleColumnPage>+ )+}++const MagentoWebhookDetailRoute = () => (+ <SettingsProviders>+ <MagentoWebhookDetailPage />+ </SettingsProviders>+)++export const handle = {+ breadcrumb: (match: UIMatch) => <MagentoWebhookDetailBreadcrumb {...match} />,+ permissions: "integrations:view",+}++export default MagentoWebhookDetailRoutediff --git a/packages/plugins/magento2-connector/src/admin/routes/settings/magento/components/magento-status-section.tsx b/packages/plugins/magento2-connector/src/admin/routes/settings/magento/components/magento-status-section.tsxnew file mode 100644index 000000000..ff2f2cf8b--- /dev/null+++ b/packages/plugins/magento2-connector/src/admin/routes/settings/magento/components/magento-status-section.tsx@@ -0,0 +1,81 @@+import { Container, Heading, StatusBadge, Text } from "@medusajs/ui"+import { SectionRow } from "@mercurjs/dashboard-shared"++import { useMagentoStatus } from "../../../../hooks/api/magento"++const formatDate = (value: string | null) =>+ value ? new Date(value).toLocaleString() : "Never"++export const MagentoStatusSection = () => {+ const { connection: status, isPending, isError, error } = useMagentoStatus({+ refetchInterval: 30_000,+ })++ if (isError) {+ throw error+ }++ const connected =+ !!status?.payment_provider.installed && (status?.webhooks.active ?? 0) > 0++ return (+ <Container className="divide-y p-0" data-testid="magento-status-section">+ <div className="flex items-center justify-between px-6 py-4">+ <div>+ <Heading>Magento</Heading>+ <Text size="small" className="text-ui-fg-subtle">+ Connection between this marketplace and your Magento 2 storefront.+ </Text>+ </div>+ {isPending || !status ? (+ <StatusBadge color="grey">Checking</StatusBadge>+ ) : connected ? (+ <StatusBadge color="green">Connected</StatusBadge>+ ) : (+ <StatusBadge color="orange">Not configured</StatusBadge>+ )}+ </div>+ <SectionRow+ title="Payment provider"+ value={+ status ? (+ status.payment_provider.installed ? (+ <StatusBadge color="green">{status.payment_provider.id}</StatusBadge>+ ) : (+ <StatusBadge color="red">Missing from payment module</StatusBadge>+ )+ ) : (+ "-"+ )+ }+ />+ <SectionRow+ title="Webhooks"+ value={status ? `${status.webhooks.active} active of ${status.webhooks.total}` : "-"}+ />+ <SectionRow+ title={`Deliveries (last ${status?.deliveries.window_hours ?? 24}h)`}+ value={+ status+ ? [+ `${status.deliveries.delivered} delivered`,+ status.deliveries.failed ? `${status.deliveries.failed} retrying` : null,+ status.deliveries.dead ? `${status.deliveries.dead} gave up` : null,+ status.deliveries.pending ? `${status.deliveries.pending} queued` : null,+ ]+ .filter(Boolean)+ .join(" · ")+ : "-"+ }+ />+ <SectionRow+ title="Last delivery"+ value={status ? formatDate(status.deliveries.last_delivered_at) : "-"}+ />+ <SectionRow+ title="Orders from Magento (24h)"+ value={status ? String(status.orders.last_24h) : "-"}+ />+ </Container>+ )+}diff --git a/packages/plugins/magento2-connector/src/admin/routes/settings/magento/components/magento-webhook-table.tsx b/packages/plugins/magento2-connector/src/admin/routes/settings/magento/components/magento-webhook-table.tsxnew file mode 100644index 000000000..f3ac51b74--- /dev/null+++ b/packages/plugins/magento2-connector/src/admin/routes/settings/magento/components/magento-webhook-table.tsx@@ -0,0 +1,126 @@+import { Button, Container, Heading, Text } from "@medusajs/ui"+import {+ DateCell,+ StatusCell,+ TextCell,+ TextHeader,+ _DataTable,+ useDataTable,+ useQueryParams,+} from "@mercurjs/dashboard-shared"+import { keepPreviousData } from "@tanstack/react-query"+import { createColumnHelper } from "@tanstack/react-table"+import { useMemo } from "react"+import { Link } from "react-router-dom"++import { useMagentoWebhooks } from "../../../../hooks/api/magento"+import { useActionBlocker } from "../../../../hooks/use-action-blocker"+import type { MagentoWebhook } from "../../../../lib/client"++const PAGE_SIZE = 20++export const MagentoWebhookTable = () => (+ <Container className="divide-y p-0" data-testid="magento-webhook-table">+ <MagentoWebhookHeader />+ <MagentoWebhookDataTable />+ </Container>+)++const MagentoWebhookHeader = () => {+ const createBlocker = useActionBlocker("integrations", "manage")++ return (+ <div className="flex items-center justify-between px-6 py-4">+ <div>+ <Heading>Webhooks</Heading>+ <Text size="small" className="text-ui-fg-subtle">+ Endpoints in Magento that receive offer, seller, product and order events.+ </Text>+ </div>+ <Button+ size="small"+ variant="secondary"+ asChild+ disabled={createBlocker.disabled}+ data-testid="magento-webhook-create-button"+ >+ <Link to="create">Add endpoint</Link>+ </Button>+ </div>+ )+}++const MagentoWebhookDataTable = () => {+ const raw = useQueryParams(["offset"])+ const searchParams = {+ limit: PAGE_SIZE,+ offset: raw.offset ? Number(raw.offset) : 0,+ }++ const { webhooks, count, isPending, isError, error } = useMagentoWebhooks(searchParams, {+ placeholderData: keepPreviousData,+ })++ const data = useMemo(() => webhooks ?? [], [webhooks])+ const columns = useColumns()++ const { table } = useDataTable({+ data,+ columns,+ count: count ?? 0,+ enablePagination: true,+ getRowId: (row) => row.id,+ pageSize: PAGE_SIZE,+ })++ if (isError) {+ throw error+ }++ return (+ <_DataTable+ table={table}+ columns={columns}+ count={count ?? 0}+ pageSize={PAGE_SIZE}+ isLoading={isPending}+ queryObject={raw}+ pagination+ navigateTo={(row) => row.original.id}+ noRecords={{+ title: "No webhook endpoints yet",+ message: "Add the endpoint your Magento connector exposes to start receiving events.",+ }}+ />+ )+}++const columnHelper = createColumnHelper<MagentoWebhook>()++const useColumns = () =>+ useMemo(+ () => [+ columnHelper.accessor("url", {+ header: () => <TextHeader text="URL" />,+ cell: ({ getValue }) => <TextCell text={getValue()} />,+ }),+ columnHelper.accessor("events", {+ header: () => <TextHeader text="Events" />,+ cell: ({ getValue }) => <TextCell text={`${getValue().length} events`} />,+ }),+ columnHelper.accessor("is_active", {+ header: () => <TextHeader text="Status" />,+ cell: ({ getValue }) =>+ getValue() ? (+ <StatusCell color="green">Active</StatusCell>+ ) : (+ <StatusCell color="grey">Paused</StatusCell>+ ),+ }),+ columnHelper.accessor("created_at", {+ header: () => <TextHeader text="Created" />,+ cell: ({ getValue }) => <DateCell date={getValue()} />,+ }),+ ],+ []+ )diff --git a/packages/plugins/magento2-connector/src/admin/routes/settings/magento/create/page.tsx b/packages/plugins/magento2-connector/src/admin/routes/settings/magento/create/page.tsxnew file mode 100644index 000000000..8d38045c2--- /dev/null+++ b/packages/plugins/magento2-connector/src/admin/routes/settings/magento/create/page.tsx@@ -0,0 +1,226 @@+import { zodResolver } from "@hookform/resolvers/zod"+import { Button, Checkbox, Heading, Input, Text, Textarea, toast } from "@medusajs/ui"+import { Form, KeyboundForm, RouteDrawer, useRouteModal } from "@mercurjs/dashboard-shared"+import { useState } from "react"+import { useForm } from "react-hook-form"+import * as zod from "zod"++import { useCreateMagentoWebhook } from "../../../../hooks/api/magento"+import { SettingsProviders } from "../../../../providers/settings-providers"++const EVENT_GROUPS: { label: string; events: string[] }[] = [+ { label: "Offers", events: ["offer.created", "offer.updated", "offer.deleted"] },+ {+ label: "Sellers",+ events: [+ "seller.updated",+ "seller.approved",+ "seller.suspended",+ "seller.unsuspended",+ "seller.terminated",+ "seller.unterminated",+ ],+ },+ { label: "Products", events: ["product.published", "product.rejected"] },+ {+ label: "Orders",+ events: [+ "order_group.created",+ "order.updated",+ "order.canceled",+ "order.fulfillment_created",+ "order.fulfillment_canceled",+ "shipment.created",+ "delivery.created",+ ],+ },+ {+ label: "Returns and refunds",+ events: [+ "order.return_requested",+ "order.return_received",+ "order.refund_requested",+ "order.refund_recorded",+ ],+ },+]++const ALL_EVENTS = EVENT_GROUPS.flatMap((group) => group.events)++const CreateMagentoWebhookSchema = zod.object({+ url: zod.string().url("Enter a full URL including https://"),+ description: zod.string().optional(),+ events: zod.array(zod.string()).min(1, "Pick at least one event"),+})++type CreateMagentoWebhookSchemaType = zod.infer<typeof CreateMagentoWebhookSchema>++const CreateMagentoWebhookForm = () => {+ const { handleSuccess } = useRouteModal()+ const [secret, setSecret] = useState<string | null>(null)+ const [createdId, setCreatedId] = useState<string | null>(null)++ const form = useForm<CreateMagentoWebhookSchemaType>({+ defaultValues: { url: "", description: "", events: ALL_EVENTS },+ resolver: zodResolver(CreateMagentoWebhookSchema),+ })++ const { mutateAsync, isPending } = useCreateMagentoWebhook({+ onSuccess: ({ webhook }) => {+ setSecret(webhook.secret)+ setCreatedId(webhook.id)+ },+ onError: (e) => toast.error(e.message),+ })++ const handleSubmit = form.handleSubmit(async (data) => {+ await mutateAsync({+ url: data.url,+ events: data.events,+ description: data.description || null,+ })+ })++ if (secret && createdId) {+ return (+ <>+ <RouteDrawer.Body>+ <div className="flex flex-col gap-y-4">+ <div>+ <Heading level="h2">Signing secret</Heading>+ <Text size="small" className="text-ui-fg-subtle">+ Paste this into the Magento connector configuration. It is shown only once.+ </Text>+ </div>+ <Input readOnly value={secret} data-testid="magento-webhook-secret-input" />+ </div>+ </RouteDrawer.Body>+ <RouteDrawer.Footer>+ <div className="flex items-center gap-x-2">+ <Button+ size="small"+ variant="secondary"+ onClick={() => navigator.clipboard?.writeText(secret).then(() => toast.success("Copied"))}+ >+ Copy+ </Button>+ <Button size="small" onClick={() => handleSuccess(`/settings/magento/${createdId}`)}>+ Done+ </Button>+ </div>+ </RouteDrawer.Footer>+ </>+ )+ }++ return (+ <RouteDrawer.Form form={form}>+ <KeyboundForm onSubmit={handleSubmit} className="flex flex-1 flex-col overflow-hidden">+ <RouteDrawer.Body className="flex flex-1 flex-col gap-y-6 overflow-y-auto">+ <Form.Field+ control={form.control}+ name="url"+ render={({ field }) => (+ <Form.Item>+ <Form.Label>Endpoint URL</Form.Label>+ <Form.Control>+ <Input+ placeholder="https://shop.example.com/mercur/webhook"+ autoComplete="off"+ data-testid="magento-webhook-url-input"+ {...field}+ />+ </Form.Control>+ <Form.Hint>The route the Magento connector exposes for Mercur events.</Form.Hint>+ <Form.ErrorMessage />+ </Form.Item>+ )}+ />+ <Form.Field+ control={form.control}+ name="description"+ render={({ field }) => (+ <Form.Item>+ <Form.Label optional>Description</Form.Label>+ <Form.Control>+ <Textarea rows={2} data-testid="magento-webhook-description-input" {...field} />+ </Form.Control>+ <Form.ErrorMessage />+ </Form.Item>+ )}+ />+ <Form.Field+ control={form.control}+ name="events"+ render={({ field }) => (+ <Form.Item>+ <Form.Label>Events</Form.Label>+ <div className="flex flex-col gap-y-4">+ {EVENT_GROUPS.map((group) => (+ <div key={group.label} className="flex flex-col gap-y-2">+ <Text size="small" weight="plus">+ {group.label}+ </Text>+ {group.events.map((event) => {+ const checked = field.value.includes(event)+ return (+ <label key={event} className="flex items-center gap-x-2">+ <Checkbox+ checked={checked}+ onCheckedChange={(next) =>+ field.onChange(+ next === true+ ? [...field.value, event]+ : field.value.filter((e) => e !== event)+ )+ }+ data-testid={`magento-webhook-event-${event}`}+ />+ <Text size="small" leading="compact">+ {event}+ </Text>+ </label>+ )+ })}+ </div>+ ))}+ </div>+ <Form.ErrorMessage />+ </Form.Item>+ )}+ />+ </RouteDrawer.Body>+ <RouteDrawer.Footer>+ <div className="flex items-center gap-x-2">+ <RouteDrawer.Close asChild>+ <Button size="small" variant="secondary">+ Cancel+ </Button>+ </RouteDrawer.Close>+ <Button size="small" type="submit" isLoading={isPending} data-testid="magento-webhook-save-button">+ Create+ </Button>+ </div>+ </RouteDrawer.Footer>+ </KeyboundForm>+ </RouteDrawer.Form>+ )+}++const CreateMagentoWebhookPage = () => (+ <SettingsProviders>+ <RouteDrawer>+ <RouteDrawer.Header>+ <RouteDrawer.Title asChild>+ <Heading>Add webhook endpoint</Heading>+ </RouteDrawer.Title>+ <RouteDrawer.Description className="sr-only">+ Register a Magento endpoint that receives Mercur events.+ </RouteDrawer.Description>+ </RouteDrawer.Header>+ <CreateMagentoWebhookForm />+ </RouteDrawer>+ </SettingsProviders>+)++export default CreateMagentoWebhookPagediff --git a/packages/plugins/magento2-connector/src/admin/routes/settings/magento/lib/delivery-state.ts b/packages/plugins/magento2-connector/src/admin/routes/settings/magento/lib/delivery-state.tsnew file mode 100644index 000000000..25e0f58f7--- /dev/null+++ b/packages/plugins/magento2-connector/src/admin/routes/settings/magento/lib/delivery-state.ts@@ -0,0 +1,20 @@+import type { MagentoWebhookDeliveryStatus } from "../../../../lib/client"++export const DELIVERY_STATE_COLOR: Record<+ MagentoWebhookDeliveryStatus,+ "green" | "red" | "orange" | "grey"+> = {+ pending: "orange",+ delivered: "green",+ failed: "orange",+ dead: "red",+}++export const DELIVERY_STATE_LABEL: Record<MagentoWebhookDeliveryStatus, string> = {+ pending: "Queued",+ delivered: "Delivered",+ failed: "Retrying",+ dead: "Gave up",+}++export const LIVE_DELIVERY_STATES: MagentoWebhookDeliveryStatus[] = ["pending", "failed"]diff --git a/packages/plugins/magento2-connector/src/admin/routes/settings/magento/page.tsx b/packages/plugins/magento2-connector/src/admin/routes/settings/magento/page.tsxnew file mode 100644index 000000000..d191c3518--- /dev/null+++ b/packages/plugins/magento2-connector/src/admin/routes/settings/magento/page.tsx@@ -0,0 +1,40 @@+import { ShoppingBag } from "@medusajs/icons"+import { SingleColumnPage, WidgetZone } from "@mercurjs/dashboard-shared"+import { defineRouteConfig } from "@mercurjs/dashboard-sdk"+import { Children, type ReactNode } from "react"++import { SettingsProviders } from "../../../providers/settings-providers"+import { MagentoStatusSection } from "./components/magento-status-section"+import { MagentoWebhookTable } from "./components/magento-webhook-table"++const MagentoPage = ({ children }: { children?: ReactNode }) => (+ <SettingsProviders>+ <SingleColumnPage hasOutlet data-testid="magento-page">+ <WidgetZone id="magento.list">+ {Children.count(children) > 0 ? (+ children+ ) : (+ <>+ <MagentoStatusSection />+ <MagentoWebhookTable />+ </>+ )}+ </WidgetZone>+ </SingleColumnPage>+ </SettingsProviders>+)++export const config = defineRouteConfig({+ label: "Magento",+ icon: ShoppingBag,+ rank: 60,+ group: "developer",+ permissions: ["integrations:view"],+})++export const handle = {+ breadcrumb: () => <span>Magento</span>,+ permissions: "integrations:view",+}++export default MagentoPagediff --git a/packages/plugins/magento2-connector/src/admin/tsconfig.json b/packages/plugins/magento2-connector/src/admin/tsconfig.jsonnew file mode 100644index 000000000..89f49d8ea--- /dev/null+++ b/packages/plugins/magento2-connector/src/admin/tsconfig.json@@ -0,0 +1,17 @@+{+ "compilerOptions": {+ "target": "ES2021",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "jsx": "react-jsx",+ "lib": ["ES2021", "DOM"],+ "strict": true,+ "strictNullChecks": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "noEmit": true,+ "resolveJsonModule": true+ },+ "include": ["./**/*", "./vite-env.d.ts"],+ "exclude": ["node_modules"]+}diff --git a/packages/plugins/magento2-connector/src/admin/vite-env.d.ts b/packages/plugins/magento2-connector/src/admin/vite-env.d.tsnew file mode 100644index 000000000..a7707bed6--- /dev/null+++ b/packages/plugins/magento2-connector/src/admin/vite-env.d.ts@@ -0,0 +1,7 @@+interface ImportMetaEnv {+ readonly VITE_MERCUR_BACKEND_URL?: string+}++interface ImportMeta {+ readonly env: ImportMetaEnv+}diff --git a/packages/plugins/magento2-connector/src/api/admin/magento/middlewares.ts b/packages/plugins/magento2-connector/src/api/admin/magento/middlewares.tsnew file mode 100644index 000000000..49a53d238--- /dev/null+++ b/packages/plugins/magento2-connector/src/api/admin/magento/middlewares.ts@@ -0,0 +1,108 @@+import {+ validateAndTransformBody,+ validateAndTransformQuery,+} from "@medusajs/framework"+import { MiddlewareRoute } from "@medusajs/framework/http"+import { requirePermission } from "@mercurjs/core/api/utils/permissions-middleware"++import { AdminRecordExternalRefund } from "./orders/validators"+import {+ adminMagentoWebhookDeliveryQueryConfig,+ adminMagentoWebhookQueryConfig,+} from "./webhooks/query-config"+import {+ AdminCreateMagentoWebhook,+ AdminGetMagentoWebhookDeliveriesParams,+ AdminGetMagentoWebhookParams,+ AdminGetMagentoWebhooksParams,+ AdminUpdateMagentoWebhook,+} from "./webhooks/validators"++export const adminMagentoMiddlewares: MiddlewareRoute[] = [+ {+ method: ["GET"],+ matcher: "/admin/magento/status",+ middlewares: [requirePermission("integrations", "view")],+ },+ {+ method: ["GET"],+ matcher: "/admin/magento/webhooks",+ middlewares: [+ requirePermission("integrations", "view"),+ validateAndTransformQuery(+ AdminGetMagentoWebhooksParams,+ adminMagentoWebhookQueryConfig.list+ ),+ ],+ },+ {+ method: ["POST"],+ matcher: "/admin/magento/webhooks",+ middlewares: [+ requirePermission("integrations", "manage"),+ validateAndTransformBody(AdminCreateMagentoWebhook),+ validateAndTransformQuery(+ AdminGetMagentoWebhookParams,+ adminMagentoWebhookQueryConfig.retrieve+ ),+ ],+ },+ {+ method: ["GET"],+ matcher: "/admin/magento/webhooks/:id",+ middlewares: [+ requirePermission("integrations", "view"),+ validateAndTransformQuery(+ AdminGetMagentoWebhookParams,+ adminMagentoWebhookQueryConfig.retrieve+ ),+ ],+ },+ {+ method: ["POST"],+ matcher: "/admin/magento/webhooks/:id",+ middlewares: [+ requirePermission("integrations", "manage"),+ validateAndTransformBody(AdminUpdateMagentoWebhook),+ validateAndTransformQuery(+ AdminGetMagentoWebhookParams,+ adminMagentoWebhookQueryConfig.retrieve+ ),+ ],+ },+ {+ method: ["DELETE"],+ matcher: "/admin/magento/webhooks/:id",+ middlewares: [requirePermission("integrations", "manage")],+ },+ {+ method: ["GET"],+ matcher: "/admin/magento/webhooks/:id/deliveries",+ middlewares: [+ requirePermission("integrations", "view"),+ validateAndTransformQuery(+ AdminGetMagentoWebhookDeliveriesParams,+ adminMagentoWebhookDeliveryQueryConfig.list+ ),+ ],+ },+ {+ method: ["POST"],+ matcher: "/admin/magento/webhooks/:id/deliveries/:delivery_id/redeliver",+ middlewares: [+ requirePermission("integrations", "edit"),+ validateAndTransformQuery(+ AdminGetMagentoWebhookParams,+ adminMagentoWebhookDeliveryQueryConfig.retrieve+ ),+ ],+ },+ {+ method: ["POST"],+ matcher: "/admin/magento/orders/:id/refunds/external",+ middlewares: [+ requirePermission("integrations", "edit"),+ validateAndTransformBody(AdminRecordExternalRefund),+ ],+ },+]diff --git a/packages/plugins/magento2-connector/src/api/admin/magento/orders/[id]/refunds/external/route.ts b/packages/plugins/magento2-connector/src/api/admin/magento/orders/[id]/refunds/external/route.tsnew file mode 100644index 000000000..232ab6aa8--- /dev/null+++ b/packages/plugins/magento2-connector/src/api/admin/magento/orders/[id]/refunds/external/route.ts@@ -0,0 +1,43 @@+import {+ AuthenticatedMedusaRequest,+ MedusaResponse,+ refetchEntity,+} from "@medusajs/framework/http"++import { AdminExternalRefundResponse } from "../../../../../../../types"+import { recordExternalRefundWorkflow } from "../../../../../../../workflows"+import { AdminRecordExternalRefundType } from "../../../validators"++const PAYMENT_FIELDS = [+ "id",+ "amount",+ "currency_code",+ "provider_id",+ "captured_at",+ "refunds.id",+ "refunds.amount",+ "refunds.note",+ "refunds.created_at",+]++export const POST = async (+ req: AuthenticatedMedusaRequest<AdminRecordExternalRefundType>,+ res: MedusaResponse<AdminExternalRefundResponse>+) => {+ const { result } = await recordExternalRefundWorkflow(req.scope).run({+ input: {+ order_id: req.params.id,+ created_by: req.auth_context?.actor_id,+ ...req.validatedBody,+ },+ })++ const payment = await refetchEntity({+ entity: "payment",+ idOrFilter: result.id,+ scope: req.scope,+ fields: PAYMENT_FIELDS,+ })++ res.status(200).json({ payment })+}diff --git a/packages/plugins/magento2-connector/src/api/admin/magento/orders/validators.ts b/packages/plugins/magento2-connector/src/api/admin/magento/orders/validators.tsnew file mode 100644index 000000000..758d75f16--- /dev/null+++ b/packages/plugins/magento2-connector/src/api/admin/magento/orders/validators.ts@@ -0,0 +1,10 @@+import { z } from "@medusajs/framework/zod"++export type AdminRecordExternalRefundType = z.infer<typeof AdminRecordExternalRefund>+export const AdminRecordExternalRefund = z+ .object({+ amount: z.number().positive(),+ reference: z.string().min(1).optional(),+ note: z.string().optional(),+ })+ .strict()diff --git a/packages/plugins/magento2-connector/src/api/admin/magento/status/route.ts b/packages/plugins/magento2-connector/src/api/admin/magento/status/route.tsnew file mode 100644index 000000000..73033eef7--- /dev/null+++ b/packages/plugins/magento2-connector/src/api/admin/magento/status/route.ts@@ -0,0 +1,68 @@+import {+ AuthenticatedMedusaRequest,+ MedusaResponse,+} from "@medusajs/framework/http"+import { IPaymentModuleService } from "@medusajs/framework/types"+import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"++import {+ AdminMagentoStatusResponse,+ EXTERNAL_PAYMENT_PROVIDER_ID,+ IMagentoWebhookModuleService,+ MAGENTO_WEBHOOK_EVENTS,+ MAGENTO_WEBHOOK_MODULE,+} from "../../../../types"++const WINDOW_HOURS = 24++export const GET = async (+ req: AuthenticatedMedusaRequest,+ res: MedusaResponse<AdminMagentoStatusResponse>+) => {+ const webhooks = req.scope.resolve<IMagentoWebhookModuleService>(MAGENTO_WEBHOOK_MODULE)+ const payment = req.scope.resolve<IPaymentModuleService>(Modules.PAYMENT)+ const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)++ const since = new Date(Date.now() - WINDOW_HOURS * 60 * 60_000)++ const [providers, endpoints, recent, lastDelivered, orders] = await Promise.all([+ payment.listPaymentProviders({ id: EXTERNAL_PAYMENT_PROVIDER_ID }),+ webhooks.listMagentoWebhookEndpoints({}, { select: ["id", "is_active"] }),+ webhooks.listMagentoWebhookDeliveries(+ { created_at: { $gte: since } },+ { select: ["id", "status"] }+ ),+ webhooks.listMagentoWebhookDeliveries(+ { status: "delivered" },+ { select: ["id", "delivered_at"], order: { delivered_at: "DESC" }, take: 1 }+ ),+ query.graph({+ entity: "order_group",+ fields: ["id"],+ filters: { created_at: { $gte: since }, metadata: { channel: "magento" } },+ }),+ ])++ const counts = { delivered: 0, failed: 0, dead: 0, pending: 0 }+ for (const delivery of recent) {+ counts[delivery.status] += 1+ }++ res.json({+ payment_provider: {+ id: EXTERNAL_PAYMENT_PROVIDER_ID,+ installed: providers.length > 0,+ },+ events: MAGENTO_WEBHOOK_EVENTS,+ webhooks: {+ total: endpoints.length,+ active: endpoints.filter((e) => e.is_active).length,+ },+ deliveries: {+ window_hours: WINDOW_HOURS,+ ...counts,+ last_delivered_at: lastDelivered[0]?.delivered_at ?? null,+ },+ orders: { channel: "magento", last_24h: orders.data.length },+ })+}diff --git a/packages/plugins/magento2-connector/src/api/admin/magento/webhooks/[id]/deliveries/[delivery_id]/redeliver/route.ts b/packages/plugins/magento2-connector/src/api/admin/magento/webhooks/[id]/deliveries/[delivery_id]/redeliver/route.tsnew file mode 100644index 000000000..472f1af80--- /dev/null+++ b/packages/plugins/magento2-connector/src/api/admin/magento/webhooks/[id]/deliveries/[delivery_id]/redeliver/route.ts@@ -0,0 +1,31 @@+import {+ AuthenticatedMedusaRequest,+ MedusaResponse,+ refetchEntity,+} from "@medusajs/framework/http"++import { AdminMagentoWebhookDeliveryResponse } from "../../../../../../../../types"+import { deliverMagentoWebhookWorkflow } from "../../../../../../../../workflows"+import { AdminGetMagentoWebhookParamsType } from "../../../../validators"++export const POST = async (+ req: AuthenticatedMedusaRequest<AdminGetMagentoWebhookParamsType>,+ res: MedusaResponse<AdminMagentoWebhookDeliveryResponse>+) => {+ await deliverMagentoWebhookWorkflow(req.scope).run({+ input: {+ delivery_id: req.params.delivery_id,+ endpoint_id: req.params.id,+ force: true,+ },+ })++ const delivery = await refetchEntity({+ entity: "magento_webhook_delivery",+ idOrFilter: req.params.delivery_id,+ scope: req.scope,+ fields: req.queryConfig.fields,+ })++ res.status(200).json({ delivery })+}diff --git a/packages/plugins/magento2-connector/src/api/admin/magento/webhooks/[id]/deliveries/route.ts b/packages/plugins/magento2-connector/src/api/admin/magento/webhooks/[id]/deliveries/route.tsnew file mode 100644index 000000000..6ad4dcb64--- /dev/null+++ b/packages/plugins/magento2-connector/src/api/admin/magento/webhooks/[id]/deliveries/route.ts@@ -0,0 +1,29 @@+import {+ AuthenticatedMedusaRequest,+ MedusaResponse,+} from "@medusajs/framework/http"+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"++import { AdminMagentoWebhookDeliveryListResponse } from "../../../../../../types"+import { AdminGetMagentoWebhookDeliveriesParamsType } from "../../validators"++export const GET = async (+ req: AuthenticatedMedusaRequest<AdminGetMagentoWebhookDeliveriesParamsType>,+ res: MedusaResponse<AdminMagentoWebhookDeliveryListResponse>+) => {+ const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)++ const { data: deliveries, metadata } = await query.graph({+ entity: "magento_webhook_delivery",+ fields: req.queryConfig.fields,+ filters: { ...req.filterableFields, endpoint_id: req.params.id },+ pagination: req.queryConfig.pagination,+ })++ res.json({+ deliveries,+ count: metadata?.count ?? 0,+ offset: metadata?.skip ?? 0,+ limit: metadata?.take ?? 0,+ })+}diff --git a/packages/plugins/magento2-connector/src/api/admin/magento/webhooks/[id]/route.ts b/packages/plugins/magento2-connector/src/api/admin/magento/webhooks/[id]/route.tsnew file mode 100644index 000000000..8568ab724--- /dev/null+++ b/packages/plugins/magento2-connector/src/api/admin/magento/webhooks/[id]/route.ts@@ -0,0 +1,69 @@+import {+ AuthenticatedMedusaRequest,+ MedusaResponse,+ refetchEntity,+} from "@medusajs/framework/http"+import { MedusaError } from "@medusajs/framework/utils"++import {+ AdminMagentoWebhookDeleteResponse,+ AdminMagentoWebhookResponse,+} from "../../../../../types"+import {+ deleteMagentoWebhookEndpointsWorkflow,+ updateMagentoWebhookEndpointsWorkflow,+} from "../../../../../workflows"+import {+ AdminGetMagentoWebhookParamsType,+ AdminUpdateMagentoWebhookType,+} from "../validators"++export const GET = async (+ req: AuthenticatedMedusaRequest<AdminGetMagentoWebhookParamsType>,+ res: MedusaResponse<AdminMagentoWebhookResponse>+) => {+ const webhook = await refetchEntity({+ entity: "magento_webhook_endpoint",+ idOrFilter: req.params.id,+ scope: req.scope,+ fields: req.queryConfig.fields,+ })++ if (!webhook) {+ throw new MedusaError(+ MedusaError.Types.NOT_FOUND,+ `Magento webhook with id "${req.params.id}" not found`+ )+ }++ res.json({ webhook })+}++export const POST = async (+ req: AuthenticatedMedusaRequest<AdminUpdateMagentoWebhookType>,+ res: MedusaResponse<AdminMagentoWebhookResponse>+) => {+ await updateMagentoWebhookEndpointsWorkflow(req.scope).run({+ input: { endpoints: [{ id: req.params.id, ...req.validatedBody }] },+ })++ const webhook = await refetchEntity({+ entity: "magento_webhook_endpoint",+ idOrFilter: req.params.id,+ scope: req.scope,+ fields: req.queryConfig.fields,+ })++ res.status(200).json({ webhook })+}++export const DELETE = async (+ req: AuthenticatedMedusaRequest,+ res: MedusaResponse<AdminMagentoWebhookDeleteResponse>+) => {+ await deleteMagentoWebhookEndpointsWorkflow(req.scope).run({+ input: { ids: [req.params.id] },+ })++ res.status(200).json({ id: req.params.id, object: "magento_webhook", deleted: true })+}diff --git a/packages/plugins/magento2-connector/src/api/admin/magento/webhooks/query-config.ts b/packages/plugins/magento2-connector/src/api/admin/magento/webhooks/query-config.tsnew file mode 100644index 000000000..700bfd86d--- /dev/null+++ b/packages/plugins/magento2-connector/src/api/admin/magento/webhooks/query-config.ts@@ -0,0 +1,35 @@+export const adminMagentoWebhookFields = [+ "id",+ "url",+ "events",+ "is_active",+ "description",+ "metadata",+ "created_at",+ "updated_at",+]++export const adminMagentoWebhookDeliveryFields = [+ "id",+ "endpoint_id",+ "event",+ "payload",+ "status",+ "attempts",+ "next_attempt_at",+ "response_status",+ "response_body",+ "delivered_at",+ "created_at",+ "updated_at",+]++export const adminMagentoWebhookQueryConfig = {+ list: { defaults: adminMagentoWebhookFields, isList: true },+ retrieve: { defaults: adminMagentoWebhookFields, isList: false },+}++export const adminMagentoWebhookDeliveryQueryConfig = {+ list: { defaults: adminMagentoWebhookDeliveryFields, isList: true },+ retrieve: { defaults: adminMagentoWebhookDeliveryFields, isList: false },+}diff --git a/packages/plugins/magento2-connector/src/api/admin/magento/webhooks/route.ts b/packages/plugins/magento2-connector/src/api/admin/magento/webhooks/route.tsnew file mode 100644index 000000000..3f6d039d1--- /dev/null+++ b/packages/plugins/magento2-connector/src/api/admin/magento/webhooks/route.ts@@ -0,0 +1,56 @@+import {+ AuthenticatedMedusaRequest,+ MedusaResponse,+ refetchEntity,+} from "@medusajs/framework/http"+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"++import {+ AdminMagentoWebhookCreateResponse,+ AdminMagentoWebhookListResponse,+} from "../../../../types"+import { createMagentoWebhookEndpointsWorkflow } from "../../../../workflows"+import {+ AdminCreateMagentoWebhookType,+ AdminGetMagentoWebhooksParamsType,+} from "./validators"++export const GET = async (+ req: AuthenticatedMedusaRequest<AdminGetMagentoWebhooksParamsType>,+ res: MedusaResponse<AdminMagentoWebhookListResponse>+) => {+ const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)++ const { data: webhooks, metadata } = await query.graph({+ entity: "magento_webhook_endpoint",+ fields: req.queryConfig.fields,+ filters: req.filterableFields,+ pagination: req.queryConfig.pagination,+ })++ res.json({+ webhooks,+ count: metadata?.count ?? 0,+ offset: metadata?.skip ?? 0,+ limit: metadata?.take ?? 0,+ })+}++export const POST = async (+ req: AuthenticatedMedusaRequest<AdminCreateMagentoWebhookType>,+ res: MedusaResponse<AdminMagentoWebhookCreateResponse>+) => {+ const { result } = await createMagentoWebhookEndpointsWorkflow(req.scope).run({+ input: { endpoints: [req.validatedBody] },+ })++ const webhook = await refetchEntity({+ entity: "magento_webhook_endpoint",+ idOrFilter: result[0].id,+ scope: req.scope,+ fields: req.queryConfig.fields,+ })++ // The secret is returned once, on creation; list and retrieve never expose it.+ res.status(200).json({ webhook: { ...webhook, secret: result[0].secret } })+}diff --git a/packages/plugins/magento2-connector/src/api/admin/magento/webhooks/validators.ts b/packages/plugins/magento2-connector/src/api/admin/magento/webhooks/validators.tsnew file mode 100644index 000000000..4d0a407e9--- /dev/null+++ b/packages/plugins/magento2-connector/src/api/admin/magento/webhooks/validators.ts@@ -0,0 +1,64 @@+import { z } from "@medusajs/framework/zod"+import {+ createFindParams,+ createOperatorMap,+ createSelectParams,+} from "@medusajs/medusa/api/utils/validators"+import { booleanString } from "@medusajs/medusa/api/utils/common-validators/common"++import { MAGENTO_WEBHOOK_EVENTS } from "../../../../types"++const eventEnum = z.enum(MAGENTO_WEBHOOK_EVENTS)+const statusEnum = z.enum(["pending", "delivered", "failed", "dead"])++export type AdminGetMagentoWebhookParamsType = z.infer<typeof AdminGetMagentoWebhookParams>+export const AdminGetMagentoWebhookParams = createSelectParams()++export type AdminGetMagentoWebhooksParamsType = z.infer<typeof AdminGetMagentoWebhooksParams>+export const AdminGetMagentoWebhooksParams = createFindParams({+ offset: 0,+ limit: 50,+}).merge(+ z.object({+ id: z.union([z.string(), z.array(z.string())]).optional(),+ is_active: booleanString().optional(),+ })+)++export type AdminGetMagentoWebhookDeliveriesParamsType = z.infer<+ typeof AdminGetMagentoWebhookDeliveriesParams+>+export const AdminGetMagentoWebhookDeliveriesParams = createFindParams({+ offset: 0,+ limit: 50,+}).merge(+ z.object({+ status: z.union([statusEnum, z.array(statusEnum)]).optional(),+ event: z.union([z.string(), z.array(z.string())]).optional(),+ created_at: createOperatorMap().optional(),+ })+)++export type AdminCreateMagentoWebhookType = z.infer<typeof AdminCreateMagentoWebhook>+export const AdminCreateMagentoWebhook = z+ .object({+ url: z.string().url(),+ secret: z.string().min(16).optional(),+ events: z.array(eventEnum).min(1),+ is_active: z.boolean().optional(),+ description: z.string().nullish(),+ metadata: z.record(z.string(), z.unknown()).nullish(),+ })+ .strict()++export type AdminUpdateMagentoWebhookType = z.infer<typeof AdminUpdateMagentoWebhook>+export const AdminUpdateMagentoWebhook = z+ .object({+ url: z.string().url().optional(),+ secret: z.string().min(16).optional(),+ events: z.array(eventEnum).min(1).optional(),+ is_active: z.boolean().optional(),+ description: z.string().nullish(),+ metadata: z.record(z.string(), z.unknown()).nullish(),+ })+ .strict()diff --git a/packages/plugins/magento2-connector/src/api/middlewares.ts b/packages/plugins/magento2-connector/src/api/middlewares.tsnew file mode 100644index 000000000..213ddbd07--- /dev/null+++ b/packages/plugins/magento2-connector/src/api/middlewares.ts@@ -0,0 +1,7 @@+import { defineMiddlewares } from "@medusajs/framework"++import { adminMagentoMiddlewares } from "./admin/magento/middlewares"++export default defineMiddlewares({+ routes: [...adminMagentoMiddlewares],+})diff --git a/packages/plugins/magento2-connector/src/index.ts b/packages/plugins/magento2-connector/src/index.tsnew file mode 100644index 000000000..18a867d04--- /dev/null+++ b/packages/plugins/magento2-connector/src/index.ts@@ -0,0 +1,4 @@+export * from "./types"+export * from "./workflows"+export { MagentoWebhookModuleService } from "./modules/magento-webhook/services/magento-webhook-module-service"+export { ExternalPaymentProviderService } from "./providers/payment-external"diff --git a/packages/plugins/magento2-connector/src/jobs/prune-magento-webhook-deliveries.ts b/packages/plugins/magento2-connector/src/jobs/prune-magento-webhook-deliveries.tsnew file mode 100644index 000000000..8b168bf57--- /dev/null+++ b/packages/plugins/magento2-connector/src/jobs/prune-magento-webhook-deliveries.ts@@ -0,0 +1,16 @@+import { MedusaContainer } from "@medusajs/framework/types"++import { pruneMagentoWebhookDeliveriesWorkflow } from "../workflows"++const RETENTION_DAYS = 30++export default async function pruneMagentoWebhookDeliveries(container: MedusaContainer) {+ await pruneMagentoWebhookDeliveriesWorkflow(container).run({+ input: { delivered_before: new Date(Date.now() - RETENTION_DAYS * 24 * 60 * 60_000) },+ })+}++export const config = {+ name: "prune-magento-webhook-deliveries",+ schedule: "0 3 * * *",+}diff --git a/packages/plugins/magento2-connector/src/jobs/retry-magento-webhook-deliveries.ts b/packages/plugins/magento2-connector/src/jobs/retry-magento-webhook-deliveries.tsnew file mode 100644index 000000000..56f7a7052--- /dev/null+++ b/packages/plugins/magento2-connector/src/jobs/retry-magento-webhook-deliveries.ts@@ -0,0 +1,24 @@+import { MedusaContainer } from "@medusajs/framework/types"++import { IMagentoWebhookModuleService, MAGENTO_WEBHOOK_MODULE } from "../types"+import { deliverMagentoWebhookWorkflow } from "../workflows"++export default async function retryMagentoWebhookDeliveries(container: MedusaContainer) {+ const service = container.resolve<IMagentoWebhookModuleService>(MAGENTO_WEBHOOK_MODULE)++ const due = await service.listMagentoWebhookDeliveries(+ { status: ["pending", "failed"], next_attempt_at: { $lte: new Date() } },+ { select: ["id"], take: 200 }+ )++ for (const delivery of due) {+ await deliverMagentoWebhookWorkflow(container).run({+ input: { delivery_id: delivery.id },+ })+ }+}++export const config = {+ name: "retry-magento-webhook-deliveries",+ schedule: "* * * * *",+}diff --git a/packages/plugins/magento2-connector/src/modules/magento-webhook/index.ts b/packages/plugins/magento2-connector/src/modules/magento-webhook/index.tsnew file mode 100644index 000000000..c65fbe273--- /dev/null+++ b/packages/plugins/magento2-connector/src/modules/magento-webhook/index.ts@@ -0,0 +1,10 @@+import { Module } from "@medusajs/framework/utils"++import { MAGENTO_WEBHOOK_MODULE } from "../../types"+import MagentoWebhookModuleService from "./services/magento-webhook-module-service"++export { MAGENTO_WEBHOOK_MODULE }++export default Module(MAGENTO_WEBHOOK_MODULE, {+ service: MagentoWebhookModuleService,+})diff --git a/packages/plugins/magento2-connector/src/modules/magento-webhook/migrations/.snapshot-medusa-magento-webhook.json b/packages/plugins/magento2-connector/src/modules/magento-webhook/migrations/.snapshot-medusa-magento-webhook.jsonnew file mode 100644index 000000000..1bee1095d--- /dev/null+++ b/packages/plugins/magento2-connector/src/modules/magento-webhook/migrations/.snapshot-medusa-magento-webhook.json@@ -0,0 +1,474 @@+{+ "namespaces": [+ "public"+ ],+ "name": "public",+ "tables": [+ {+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "unsigned": false,+ "autoincrement": false,+ "primary": true,+ "nullable": false,+ "unique": false,+ "length": null,+ "precision": null,+ "scale": null,+ "default": null,+ "comment": null,+ "enumItems": [],+ "mappedType": "text"+ },+ "url": {+ "name": "url",+ "type": "text",+ "unsigned": false,+ "autoincrement": false,+ "primary": false,+ "nullable": false,+ "unique": false,+ "length": null,+ "precision": null,+ "scale": null,+ "default": null,+ "comment": null,+ "enumItems": [],+ "mappedType": "text"+ },+ "secret": {+ "name": "secret",+ "type": "text",+ "unsigned": false,+ "autoincrement": false,+ "primary": false,+ "nullable": false,+ "unique": false,+ "length": null,+ "precision": null,+ "scale": null,+ "default": null,+ "comment": null,+ "enumItems": [],+ "mappedType": "text"+ },+ "events": {+ "name": "events",+ "type": "text[]",+ "unsigned": false,+ "autoincrement": false,+ "primary": false,+ "nullable": false,+ "unique": false,+ "length": null,+ "precision": null,+ "scale": null,+ "default": null,+ "comment": null,+ "enumItems": [],+ "mappedType": "array"+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "unsigned": false,+ "autoincrement": false,+ "primary": false,+ "nullable": false,+ "unique": false,+ "length": null,+ "precision": null,+ "scale": null,+ "default": "true",+ "comment": null,+ "enumItems": [],+ "mappedType": "boolean"+ },+ "description": {+ "name": "description",+ "type": "text",+ "unsigned": false,+ "autoincrement": false,+ "primary": false,+ "nullable": true,+ "unique": false,+ "length": null,+ "precision": null,+ "scale": null,+ "default": null,+ "comment": null,+ "enumItems": [],+ "mappedType": "text"+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "unsigned": false,+ "autoincrement": false,+ "primary": false,+ "nullable": true,+ "unique": false,+ "length": null,+ "precision": null,+ "scale": null,+ "default": null,+ "comment": null,+ "enumItems": [],+ "mappedType": "json"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamptz",+ "unsigned": false,+ "autoincrement": false,+ "primary": false,+ "nullable": false,+ "unique": false,+ "length": 6,+ "precision": null,+ "scale": null,+ "default": "now()",+ "comment": null,+ "enumItems": [],+ "mappedType": "datetime"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamptz",+ "unsigned": false,+ "autoincrement": false,+ "primary": false,+ "nullable": false,+ "unique": false,+ "length": 6,+ "precision": null,+ "scale": null,+ "default": "now()",+ "comment": null,+ "enumItems": [],+ "mappedType": "datetime"+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "timestamptz",+ "unsigned": false,+ "autoincrement": false,+ "primary": false,+ "nullable": true,+ "unique": false,+ "length": 6,+ "precision": null,+ "scale": null,+ "default": null,+ "comment": null,+ "enumItems": [],+ "mappedType": "datetime"+ }+ },+ "name": "magento_webhook_endpoint",+ "schema": "public",+ "indexes": [+ {+ "keyName": "IDX_magento_webhook_endpoint_deleted_at",+ "columnNames": [],+ "composite": false,+ "constraint": false,+ "primary": false,+ "unique": false,+ "expression": "CREATE INDEX IF NOT EXISTS \"IDX_magento_webhook_endpoint_deleted_at\" ON \"magento_webhook_endpoint\" (\"deleted_at\") WHERE deleted_at IS NULL"+ },+ {+ "keyName": "magento_webhook_endpoint_pkey",+ "columnNames": [+ "id"+ ],+ "composite": false,+ "constraint": true,+ "primary": true,+ "unique": true+ }+ ],+ "checks": [],+ "foreignKeys": {},+ "nativeEnums": {}+ },+ {+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "unsigned": false,+ "autoincrement": false,+ "primary": true,+ "nullable": false,+ "unique": false,+ "length": null,+ "precision": null,+ "scale": null,+ "default": null,+ "comment": null,+ "enumItems": [],+ "mappedType": "text"+ },+ "event": {+ "name": "event",+ "type": "text",+ "unsigned": false,+ "autoincrement": false,+ "primary": false,+ "nullable": false,+ "unique": false,+ "length": null,+ "precision": null,+ "scale": null,+ "default": null,+ "comment": null,+ "enumItems": [],+ "mappedType": "text"+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "unsigned": false,+ "autoincrement": false,+ "primary": false,+ "nullable": false,+ "unique": false,+ "length": null,+ "precision": null,+ "scale": null,+ "default": null,+ "comment": null,+ "enumItems": [],+ "mappedType": "json"+ },+ "status": {+ "name": "status",+ "type": "text",+ "unsigned": false,+ "autoincrement": false,+ "primary": false,+ "nullable": false,+ "unique": false,+ "length": null,+ "precision": null,+ "scale": null,+ "default": "'pending'",+ "comment": null,+ "enumItems": [+ "pending",+ "delivered",+ "failed",+ "dead"+ ],+ "mappedType": "enum"+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "unsigned": false,+ "autoincrement": false,+ "primary": false,+ "nullable": false,+ "unique": false,+ "length": null,+ "precision": null,+ "scale": null,+ "default": "0",+ "comment": null,+ "enumItems": [],+ "mappedType": "integer"+ },+ "next_attempt_at": {+ "name": "next_attempt_at",+ "type": "timestamptz",+ "unsigned": false,+ "autoincrement": false,+ "primary": false,+ "nullable": true,+ "unique": false,+ "length": 6,+ "precision": null,+ "scale": null,+ "default": null,+ "comment": null,+ "enumItems": [],+ "mappedType": "datetime"+ },+ "response_status": {+ "name": "response_status",+ "type": "integer",+ "unsigned": false,+ "autoincrement": false,+ "primary": false,+ "nullable": true,+ "unique": false,+ "length": null,+ "precision": null,+ "scale": null,+ "default": null,+ "comment": null,+ "enumItems": [],+ "mappedType": "integer"+ },+ "response_body": {+ "name": "response_body",+ "type": "text",+ "unsigned": false,+ "autoincrement": false,+ "primary": false,+ "nullable": true,+ "unique": false,+ "length": null,+ "precision": null,+ "scale": null,+ "default": null,+ "comment": null,+ "enumItems": [],+ "mappedType": "text"+ },+ "delivered_at": {+ "name": "delivered_at",+ "type": "timestamptz",+ "unsigned": false,+ "autoincrement": false,+ "primary": false,+ "nullable": true,+ "unique": false,+ "length": 6,+ "precision": null,+ "scale": null,+ "default": null,+ "comment": null,+ "enumItems": [],+ "mappedType": "datetime"+ },+ "endpoint_id": {+ "name": "endpoint_id",+ "type": "text",+ "unsigned": false,+ "autoincrement": false,+ "primary": false,+ "nullable": false,+ "unique": false,+ "length": null,+ "precision": null,+ "scale": null,+ "default": null,+ "comment": null,+ "enumItems": [],+ "mappedType": "text"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamptz",+ "unsigned": false,+ "autoincrement": false,+ "primary": false,+ "nullable": false,+ "unique": false,+ "length": 6,+ "precision": null,+ "scale": null,+ "default": "now()",+ "comment": null,+ "enumItems": [],+ "mappedType": "datetime"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamptz",+ "unsigned": false,+ "autoincrement": false,+ "primary": false,+ "nullable": false,+ "unique": false,+ "length": 6,+ "precision": null,+ "scale": null,+ "default": "now()",+ "comment": null,+ "enumItems": [],+ "mappedType": "datetime"+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "timestamptz",+ "unsigned": false,+ "autoincrement": false,+ "primary": false,+ "nullable": true,+ "unique": false,+ "length": 6,+ "precision": null,+ "scale": null,+ "default": null,+ "comment": null,+ "enumItems": [],+ "mappedType": "datetime"+ }+ },+ "name": "magento_webhook_delivery",+ "schema": "public",+ "indexes": [+ {+ "keyName": "IDX_magento_webhook_delivery_endpoint_id",+ "columnNames": [],+ "composite": false,+ "constraint": false,+ "primary": false,+ "unique": false,+ "expression": "CREATE INDEX IF NOT EXISTS \"IDX_magento_webhook_delivery_endpoint_id\" ON \"magento_webhook_delivery\" (\"endpoint_id\") WHERE deleted_at IS NULL"+ },+ {+ "keyName": "IDX_magento_webhook_delivery_deleted_at",+ "columnNames": [],+ "composite": false,+ "constraint": false,+ "primary": false,+ "unique": false,+ "expression": "CREATE INDEX IF NOT EXISTS \"IDX_magento_webhook_delivery_deleted_at\" ON \"magento_webhook_delivery\" (\"deleted_at\") WHERE deleted_at IS NULL"+ },+ {+ "keyName": "IDX_magento_webhook_delivery_due",+ "columnNames": [],+ "composite": false,+ "constraint": false,+ "primary": false,+ "unique": false,+ "expression": "CREATE INDEX IF NOT EXISTS \"IDX_magento_webhook_delivery_due\" ON \"magento_webhook_delivery\" (\"status\", \"next_attempt_at\") WHERE deleted_at IS NULL"+ },+ {+ "keyName": "magento_webhook_delivery_pkey",+ "columnNames": [+ "id"+ ],+ "composite": false,+ "constraint": true,+ "primary": true,+ "unique": true+ }+ ],+ "checks": [],+ "foreignKeys": {+ "magento_webhook_delivery_endpoint_id_foreign": {+ "constraintName": "magento_webhook_delivery_endpoint_id_foreign",+ "columnNames": [+ "endpoint_id"+ ],+ "localTableName": "public.magento_webhook_delivery",+ "referencedColumnNames": [+ "id"+ ],+ "referencedTableName": "public.magento_webhook_endpoint",+ "deleteRule": "cascade",+ "updateRule": "cascade"+ }+ },+ "nativeEnums": {}+ }+ ],+ "nativeEnums": {}+}diff --git a/packages/plugins/magento2-connector/src/modules/magento-webhook/migrations/Migration20261021155148.ts b/packages/plugins/magento2-connector/src/modules/magento-webhook/migrations/Migration20261021155148.tsnew file mode 100644index 000000000..a4a46410d--- /dev/null+++ b/packages/plugins/magento2-connector/src/modules/magento-webhook/migrations/Migration20261021155148.ts@@ -0,0 +1,25 @@+import { Migration } from "@medusajs/framework/mikro-orm/migrations";++export class Migration20261021155148 extends Migration {++ override async up(): Promise<void> {+ this.addSql(`create table if not exists "magento_webhook_endpoint" ("id" text not null, "url" text not null, "secret" text not null, "events" text[] not null, "is_active" boolean not null default true, "description" text null, "metadata" jsonb null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "magento_webhook_endpoint_pkey" primary key ("id"));`);+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_magento_webhook_endpoint_deleted_at" ON "magento_webhook_endpoint" ("deleted_at") WHERE deleted_at IS NULL;`);++ this.addSql(`create table if not exists "magento_webhook_delivery" ("id" text not null, "event" text not null, "payload" jsonb not null, "status" text check ("status" in ('pending', 'delivered', 'failed', 'dead')) not null default 'pending', "attempts" integer not null default 0, "next_attempt_at" timestamptz null, "response_status" integer null, "response_body" text null, "delivered_at" timestamptz null, "endpoint_id" text not null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "magento_webhook_delivery_pkey" primary key ("id"));`);+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_magento_webhook_delivery_endpoint_id" ON "magento_webhook_delivery" ("endpoint_id") WHERE deleted_at IS NULL;`);+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_magento_webhook_delivery_deleted_at" ON "magento_webhook_delivery" ("deleted_at") WHERE deleted_at IS NULL;`);+ this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_magento_webhook_delivery_due" ON "magento_webhook_delivery" ("status", "next_attempt_at") WHERE deleted_at IS NULL;`);++ this.addSql(`alter table if exists "magento_webhook_delivery" add constraint "magento_webhook_delivery_endpoint_id_foreign" foreign key ("endpoint_id") references "magento_webhook_endpoint" ("id") on update cascade on delete cascade;`);+ }++ override async down(): Promise<void> {+ this.addSql(`alter table if exists "magento_webhook_delivery" drop constraint if exists "magento_webhook_delivery_endpoint_id_foreign";`);++ this.addSql(`drop table if exists "magento_webhook_endpoint" cascade;`);++ this.addSql(`drop table if exists "magento_webhook_delivery" cascade;`);+ }++}diff --git a/packages/plugins/magento2-connector/src/modules/magento-webhook/models/index.ts b/packages/plugins/magento2-connector/src/modules/magento-webhook/models/index.tsnew file mode 100644index 000000000..571a3f5e4--- /dev/null+++ b/packages/plugins/magento2-connector/src/modules/magento-webhook/models/index.ts@@ -0,0 +1,2 @@+export { default as MagentoWebhookEndpoint } from "./magento-webhook-endpoint"+export { default as MagentoWebhookDelivery } from "./magento-webhook-delivery"diff --git a/packages/plugins/magento2-connector/src/modules/magento-webhook/models/magento-webhook-delivery.ts b/packages/plugins/magento2-connector/src/modules/magento-webhook/models/magento-webhook-delivery.tsnew file mode 100644index 000000000..4de1d1dd3--- /dev/null+++ b/packages/plugins/magento2-connector/src/modules/magento-webhook/models/magento-webhook-delivery.ts@@ -0,0 +1,35 @@+import { model } from "@medusajs/framework/utils"++import MagentoWebhookEndpoint from "./magento-webhook-endpoint"++const MagentoWebhookDelivery = model+ .define("magento_webhook_delivery", {+ id: model.id({ prefix: "mwhd" }).primaryKey(),+ event: model.text(),+ payload: model.json(),+ status: model+ .enum(["pending", "delivered", "failed", "dead"])+ .default("pending"),+ attempts: model.number().default(0),+ next_attempt_at: model.dateTime().nullable(),+ response_status: model.number().nullable(),+ response_body: model.text().nullable(),+ delivered_at: model.dateTime().nullable(),+ endpoint: model.belongsTo(() => MagentoWebhookEndpoint, {+ mappedBy: "deliveries",+ }),+ })+ .indexes([+ {+ name: "IDX_magento_webhook_delivery_due",+ on: ["status", "next_attempt_at"],+ where: "deleted_at IS NULL",+ },+ {+ name: "IDX_magento_webhook_delivery_endpoint_id",+ on: ["endpoint_id"],+ where: "deleted_at IS NULL",+ },+ ])++export default MagentoWebhookDeliverydiff --git a/packages/plugins/magento2-connector/src/modules/magento-webhook/models/magento-webhook-endpoint.ts b/packages/plugins/magento2-connector/src/modules/magento-webhook/models/magento-webhook-endpoint.tsnew file mode 100644index 000000000..d88da5c51--- /dev/null+++ b/packages/plugins/magento2-connector/src/modules/magento-webhook/models/magento-webhook-endpoint.ts@@ -0,0 +1,20 @@+import { model } from "@medusajs/framework/utils"++import MagentoWebhookDelivery from "./magento-webhook-delivery"++const MagentoWebhookEndpoint = model+ .define("magento_webhook_endpoint", {+ id: model.id({ prefix: "mwhe" }).primaryKey(),+ url: model.text(),+ secret: model.text(),+ events: model.array(),+ is_active: model.boolean().default(true),+ description: model.text().nullable(),+ metadata: model.json().nullable(),+ deliveries: model.hasMany(() => MagentoWebhookDelivery, {+ mappedBy: "endpoint",+ }),+ })+ .cascades({ delete: ["deliveries"] })++export default MagentoWebhookEndpointdiff --git a/packages/plugins/magento2-connector/src/modules/magento-webhook/services/magento-webhook-module-service.ts b/packages/plugins/magento2-connector/src/modules/magento-webhook/services/magento-webhook-module-service.tsnew file mode 100644index 000000000..09a53025f--- /dev/null+++ b/packages/plugins/magento2-connector/src/modules/magento-webhook/services/magento-webhook-module-service.ts@@ -0,0 +1,10 @@+import { MedusaService } from "@medusajs/framework/utils"++import { IMagentoWebhookModuleService } from "../../../types"+import { MagentoWebhookDelivery, MagentoWebhookEndpoint } from "../models"++export class MagentoWebhookModuleService+ extends MedusaService({ MagentoWebhookEndpoint, MagentoWebhookDelivery })+ implements IMagentoWebhookModuleService {}++export default MagentoWebhookModuleServicediff --git a/packages/plugins/magento2-connector/src/modules/magento-webhook/utils/index.ts b/packages/plugins/magento2-connector/src/modules/magento-webhook/utils/index.tsnew file mode 100644index 000000000..d2d67b568--- /dev/null+++ b/packages/plugins/magento2-connector/src/modules/magento-webhook/utils/index.ts@@ -0,0 +1,2 @@+export * from "./signature"+export * from "./retry"diff --git a/packages/plugins/magento2-connector/src/modules/magento-webhook/utils/retry.ts b/packages/plugins/magento2-connector/src/modules/magento-webhook/utils/retry.tsnew file mode 100644index 000000000..e9613084b--- /dev/null+++ b/packages/plugins/magento2-connector/src/modules/magento-webhook/utils/retry.ts@@ -0,0 +1,16 @@+const RETRY_DELAYS_MS = [+ 60_000,+ 5 * 60_000,+ 30 * 60_000,+ 2 * 60 * 60_000,+ 12 * 60 * 60_000,+]++export const nextWebhookAttemptAt = (+ attempts: number,+ now = new Date()+): Date | null => {+ const delay = RETRY_DELAYS_MS[attempts - 1]++ return delay === undefined ? null : new Date(now.getTime() + delay)+}diff --git a/packages/plugins/magento2-connector/src/modules/magento-webhook/utils/signature.ts b/packages/plugins/magento2-connector/src/modules/magento-webhook/utils/signature.tsnew file mode 100644index 000000000..a107c9c24--- /dev/null+++ b/packages/plugins/magento2-connector/src/modules/magento-webhook/utils/signature.ts@@ -0,0 +1,15 @@+import { createHmac, timingSafeEqual } from "node:crypto"++export const signWebhookBody = (body: string, secret: string): string =>+ `sha256=${createHmac("sha256", secret).update(body).digest("hex")}`++export const verifyWebhookSignature = (+ body: string,+ secret: string,+ signature: string+): boolean => {+ const expected = Buffer.from(signWebhookBody(body, secret))+ const received = Buffer.from(signature)++ return expected.length === received.length && timingSafeEqual(expected, received)+}diff --git a/packages/plugins/magento2-connector/src/providers/payment-external/index.ts b/packages/plugins/magento2-connector/src/providers/payment-external/index.tsnew file mode 100644index 000000000..7cdb8633e--- /dev/null+++ b/packages/plugins/magento2-connector/src/providers/payment-external/index.ts@@ -0,0 +1,9 @@+import { ModuleProvider, Modules } from "@medusajs/framework/utils"++import ExternalPaymentProviderService from "./service"++export { ExternalPaymentProviderService }++export default ModuleProvider(Modules.PAYMENT, {+ services: [ExternalPaymentProviderService],+})diff --git a/packages/plugins/magento2-connector/src/providers/payment-external/service.ts b/packages/plugins/magento2-connector/src/providers/payment-external/service.tsnew file mode 100644index 000000000..e5b26802d--- /dev/null+++ b/packages/plugins/magento2-connector/src/providers/payment-external/service.ts@@ -0,0 +1,130 @@+import {+ AuthorizePaymentInput,+ AuthorizePaymentOutput,+ CancelPaymentInput,+ CancelPaymentOutput,+ CapturePaymentInput,+ CapturePaymentOutput,+ DeletePaymentInput,+ DeletePaymentOutput,+ GetPaymentStatusInput,+ GetPaymentStatusOutput,+ InitiatePaymentInput,+ InitiatePaymentOutput,+ Logger,+ ProviderWebhookPayload,+ RefundPaymentInput,+ RefundPaymentOutput,+ RetrievePaymentInput,+ RetrievePaymentOutput,+ UpdatePaymentInput,+ UpdatePaymentOutput,+ WebhookActionResult,+} from "@medusajs/framework/types"+import {+ AbstractPaymentProvider,+ BigNumber,+ PaymentActions,+ PaymentSessionStatus,+} from "@medusajs/framework/utils"++import { ExternalPaymentSessionData } from "../../types"++const toNumber = (value: unknown): number =>+ new BigNumber(value as never).numeric++type InjectedDependencies = {+ logger: Logger+}++type ExternalPaymentOptions = Record<string, never>++/**+ * Records a payment the external storefront already captured; no provider is charged.+ */+class ExternalPaymentProviderService extends AbstractPaymentProvider<ExternalPaymentOptions> {+ static identifier = "external"++ constructor(container: InjectedDependencies, options: ExternalPaymentOptions = {}) {+ super(container, options)+ }++ async initiatePayment(+ input: InitiatePaymentInput+ ): Promise<InitiatePaymentOutput> {+ const data = (input.data ?? {}) as ExternalPaymentSessionData+ const id = data.reference ?? `ext_${Date.now()}`++ return {+ id,+ status: PaymentSessionStatus.CAPTURED,+ data: {+ ...data,+ reference: id,+ amount: toNumber(input.amount),+ currency_code: input.currency_code,+ captured_at: data.captured_at ?? new Date().toISOString(),+ },+ }+ }++ async updatePayment(input: UpdatePaymentInput): Promise<UpdatePaymentOutput> {+ return {+ status: PaymentSessionStatus.AUTHORIZED,+ data: {+ ...(input.data ?? {}),+ amount: toNumber(input.amount),+ currency_code: input.currency_code,+ },+ }+ }++ async authorizePayment(+ input: AuthorizePaymentInput+ ): Promise<AuthorizePaymentOutput> {+ return { status: PaymentSessionStatus.CAPTURED, data: input.data }+ }++ async capturePayment(input: CapturePaymentInput): Promise<CapturePaymentOutput> {+ return { data: input.data }+ }++ async refundPayment(input: RefundPaymentInput): Promise<RefundPaymentOutput> {+ const data = (input.data ?? {}) as ExternalPaymentSessionData++ return {+ data: {+ ...data,+ refunds: [...(data.refunds ?? []), { amount: toNumber(input.amount) }],+ },+ }+ }++ async cancelPayment(input: CancelPaymentInput): Promise<CancelPaymentOutput> {+ return { data: input.data }+ }++ async deletePayment(input: DeletePaymentInput): Promise<DeletePaymentOutput> {+ return { data: input.data }+ }++ async retrievePayment(+ input: RetrievePaymentInput+ ): Promise<RetrievePaymentOutput> {+ return { data: input.data }+ }++ async getPaymentStatus(+ input: GetPaymentStatusInput+ ): Promise<GetPaymentStatusOutput> {+ return { status: PaymentSessionStatus.CAPTURED, data: input.data }+ }++ async getWebhookActionAndData(+ _payload: ProviderWebhookPayload["payload"]+ ): Promise<WebhookActionResult> {+ return { action: PaymentActions.NOT_SUPPORTED }+ }+}++export default ExternalPaymentProviderServicediff --git a/packages/plugins/magento2-connector/src/subscribers/magento-refund-requested.ts b/packages/plugins/magento2-connector/src/subscribers/magento-refund-requested.tsnew file mode 100644index 000000000..68ff53a17--- /dev/null+++ b/packages/plugins/magento2-connector/src/subscribers/magento-refund-requested.ts@@ -0,0 +1,18 @@+import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"+import { PaymentEvents } from "@medusajs/framework/utils"++import { emitRefundRequestedWorkflow } from "../workflows"++export default async function magentoRefundRequestedHandler({+ event,+ container,+}: SubscriberArgs<{ id: string }>) {+ await emitRefundRequestedWorkflow(container).run({+ input: { payment_id: event.data.id },+ })+}++export const config: SubscriberConfig = {+ event: PaymentEvents.REFUNDED,+ context: { subscriberId: "magento-refund-requested" },+}diff --git a/packages/plugins/magento2-connector/src/subscribers/magento-webhook-deliver-on-create.ts b/packages/plugins/magento2-connector/src/subscribers/magento-webhook-deliver-on-create.tsnew file mode 100644index 000000000..3986dbed0--- /dev/null+++ b/packages/plugins/magento2-connector/src/subscribers/magento-webhook-deliver-on-create.ts@@ -0,0 +1,18 @@+import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"++import { MagentoWebhookEvents } from "../types"+import { deliverMagentoWebhookWorkflow } from "../workflows"++export default async function magentoWebhookDeliverOnCreateHandler({+ event,+ container,+}: SubscriberArgs<{ id: string }>) {+ await deliverMagentoWebhookWorkflow(container).run({+ input: { delivery_id: event.data.id },+ })+}++export const config: SubscriberConfig = {+ event: MagentoWebhookEvents.DELIVERY_CREATED,+ context: { subscriberId: "magento-webhook-deliver-on-create" },+}diff --git a/packages/plugins/magento2-connector/src/subscribers/magento-webhook-fan-out.ts b/packages/plugins/magento2-connector/src/subscribers/magento-webhook-fan-out.tsnew file mode 100644index 000000000..f01943b25--- /dev/null+++ b/packages/plugins/magento2-connector/src/subscribers/magento-webhook-fan-out.ts@@ -0,0 +1,31 @@+import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"++import { FULFILLMENT_SCOPED_EVENTS, MAGENTO_WEBHOOK_EVENTS } from "../types"+import { enqueueMagentoWebhookDeliveriesWorkflow } from "../workflows"++export default async function magentoWebhookFanOutHandler({+ event,+ container,+}: SubscriberArgs<Record<string, unknown>>) {+ let payload: Record<string, unknown> = event.data ?? {}++ if (FULFILLMENT_SCOPED_EVENTS.includes(event.name) && typeof payload.id === "string") {+ const query = container.resolve(ContainerRegistrationKeys.QUERY)+ const { data } = await query.graph({+ entity: "order_fulfillment",+ fields: ["order_id", "fulfillment_id"],+ filters: { fulfillment_id: payload.id },+ })+ payload = { ...payload, fulfillment_id: payload.id, order_id: data[0]?.order_id ?? null }+ }++ await enqueueMagentoWebhookDeliveriesWorkflow(container).run({+ input: { event: event.name, payload },+ })+}++export const config: SubscriberConfig = {+ event: [...MAGENTO_WEBHOOK_EVENTS],+ context: { subscriberId: "magento-webhook-fan-out" },+}diff --git a/packages/plugins/magento2-connector/src/types/common.ts b/packages/plugins/magento2-connector/src/types/common.tsnew file mode 100644index 000000000..5e2e2ed5d--- /dev/null+++ b/packages/plugins/magento2-connector/src/types/common.ts@@ -0,0 +1,143 @@+import { BaseFilterable, OperatorMap } from "@medusajs/framework/types"++export const MAGENTO_WEBHOOK_MODULE = "magento_webhook"++export const EXTERNAL_PAYMENT_PROVIDER_ID = "pp_external_external"++export const MAGENTO_WEBHOOK_EVENTS = [+ "offer.created",+ "offer.updated",+ "offer.deleted",+ "seller.updated",+ "seller.approved",+ "seller.suspended",+ "seller.unsuspended",+ "seller.terminated",+ "seller.unterminated",+ "product.published",+ "product.rejected",+ "order_group.created",+ "order.updated",+ "order.canceled",+ "order.fulfillment_created",+ "order.fulfillment_canceled",+ "order.shipment_created",+ "shipment.created",+ "delivery.created",+ "order.return_requested",+ "order.return_received",+ "order.refund_recorded",+ "order.refund_requested",+] as const++/**+ * Medusa emits these with the fulfillment id as `data.id` and no order id.+ */+export const FULFILLMENT_SCOPED_EVENTS: readonly string[] = ["shipment.created", "delivery.created"]++export type MagentoWebhookEvent = (typeof MAGENTO_WEBHOOK_EVENTS)[number]++export const MagentoWebhookEvents = {+ DELIVERY_CREATED: "magento_webhook_delivery.created",+ REFUND_RECORDED: "order.refund_recorded",+ REFUND_REQUESTED: "order.refund_requested",+} as const++export const EXTERNAL_REFUND_SOURCE = "external"++export type MagentoWebhookDeliveryStatus = "pending" | "delivered" | "failed" | "dead"++export type MagentoWebhookEndpointDTO = {+ id: string+ url: string+ secret: string+ events: string[]+ is_active: boolean+ description: string | null+ metadata: Record<string, unknown> | null+ deliveries?: MagentoWebhookDeliveryDTO[]+ created_at: Date+ updated_at: Date+ deleted_at: Date | null+}++export type MagentoWebhookDeliveryDTO = {+ id: string+ endpoint_id: string+ endpoint?: MagentoWebhookEndpointDTO+ event: string+ payload: Record<string, unknown>+ status: MagentoWebhookDeliveryStatus+ attempts: number+ next_attempt_at: Date | null+ response_status: number | null+ response_body: string | null+ delivered_at: Date | null+ created_at: Date+ updated_at: Date+ deleted_at: Date | null+}++export type CreateMagentoWebhookEndpointDTO = {+ url: string+ secret: string+ events: string[]+ is_active?: boolean+ description?: string | null+ metadata?: Record<string, unknown> | null+}++export type UpdateMagentoWebhookEndpointDTO = {+ id: string+ url?: string+ secret?: string+ events?: string[]+ is_active?: boolean+ description?: string | null+ metadata?: Record<string, unknown> | null+}++export type CreateMagentoWebhookDeliveryDTO = {+ endpoint_id: string+ event: string+ payload: Record<string, unknown>+ status?: MagentoWebhookDeliveryStatus+ attempts?: number+ next_attempt_at?: Date | null+}++export type UpdateMagentoWebhookDeliveryDTO = {+ id: string+ status?: MagentoWebhookDeliveryStatus+ attempts?: number+ next_attempt_at?: Date | null+ response_status?: number | null+ response_body?: string | null+ delivered_at?: Date | null+}++export type FilterableMagentoWebhookEndpointProps =+ BaseFilterable<FilterableMagentoWebhookEndpointProps> & {+ id?: string | string[]+ is_active?: boolean+ }++export type FilterableMagentoWebhookDeliveryProps =+ BaseFilterable<FilterableMagentoWebhookDeliveryProps> & {+ id?: string | string[]+ endpoint_id?: string | string[]+ event?: string | string[]+ status?: MagentoWebhookDeliveryStatus | MagentoWebhookDeliveryStatus[]+ next_attempt_at?: OperatorMap<Date>+ delivered_at?: OperatorMap<Date>+ created_at?: OperatorMap<Date>+ }++export type ExternalPaymentSessionData = {+ reference?: string+ captured_at?: string+ channel?: string+ amount?: number+ currency_code?: string+ refunds?: { reference?: string; amount: number }[]+}diff --git a/packages/plugins/magento2-connector/src/types/http.ts b/packages/plugins/magento2-connector/src/types/http.tsnew file mode 100644index 000000000..c8f699646--- /dev/null+++ b/packages/plugins/magento2-connector/src/types/http.ts@@ -0,0 +1,122 @@+import {+ DeleteResponse,+ FindParams,+ OperatorMap,+ PaginatedResponse,+ SelectParams,+} from "@medusajs/framework/types"++import { MagentoWebhookDeliveryStatus, MagentoWebhookEvent } from "./common"++export interface AdminMagentoWebhook {+ id: string+ url: string+ events: string[]+ is_active: boolean+ description: string | null+ metadata: Record<string, unknown> | null+ created_at: string+ updated_at: string+}++export interface AdminMagentoWebhookWithSecret extends AdminMagentoWebhook {+ secret: string+}++export interface AdminMagentoWebhookDelivery {+ id: string+ endpoint_id: string+ event: string+ payload: Record<string, unknown>+ status: MagentoWebhookDeliveryStatus+ attempts: number+ next_attempt_at: string | null+ response_status: number | null+ response_body: string | null+ delivered_at: string | null+ created_at: string+ updated_at: string+}++export interface AdminMagentoWebhookListParams extends FindParams {+ id?: string | string[]+ is_active?: boolean+}++export interface AdminMagentoWebhookParams extends SelectParams {}++export interface AdminMagentoWebhookDeliveryListParams extends FindParams {+ status?: MagentoWebhookDeliveryStatus | MagentoWebhookDeliveryStatus[]+ event?: string | string[]+ created_at?: OperatorMap<string>+}++export interface AdminCreateMagentoWebhook {+ url: string+ secret?: string+ events: MagentoWebhookEvent[]+ is_active?: boolean+ description?: string | null+ metadata?: Record<string, unknown> | null+}++export interface AdminUpdateMagentoWebhook {+ url?: string+ secret?: string+ events?: MagentoWebhookEvent[]+ is_active?: boolean+ description?: string | null+ metadata?: Record<string, unknown> | null+}++export interface AdminRecordExternalRefund {+ amount: number+ reference?: string+ note?: string+}++export interface AdminMagentoWebhookResponse {+ webhook: AdminMagentoWebhook+}++export interface AdminMagentoWebhookCreateResponse {+ webhook: AdminMagentoWebhookWithSecret+}++export interface AdminMagentoWebhookListResponse+ extends PaginatedResponse<{ webhooks: AdminMagentoWebhook[] }> {}++export interface AdminMagentoWebhookDeleteResponse extends DeleteResponse<"magento_webhook"> {}++export interface AdminMagentoWebhookDeliveryResponse {+ delivery: AdminMagentoWebhookDelivery+}++export interface AdminMagentoWebhookDeliveryListResponse+ extends PaginatedResponse<{ deliveries: AdminMagentoWebhookDelivery[] }> {}++export interface AdminMagentoStatusResponse {+ payment_provider: { id: string; installed: boolean }+ events: readonly string[]+ webhooks: { total: number; active: number }+ deliveries: {+ window_hours: number+ delivered: number+ failed: number+ dead: number+ pending: number+ last_delivered_at: string | Date | null+ }+ orders: { channel: string; last_24h: number }+}++export interface AdminExternalRefundResponse {+ payment: {+ id: string+ amount: number+ currency_code: string+ provider_id: string+ captured_at: string | null+ refunds: { id: string; amount: number; note: string | null; created_at: string }[]+ }+}diff --git a/packages/plugins/magento2-connector/src/types/index.ts b/packages/plugins/magento2-connector/src/types/index.tsnew file mode 100644index 000000000..20e429aed--- /dev/null+++ b/packages/plugins/magento2-connector/src/types/index.ts@@ -0,0 +1,3 @@+export * from "./common"+export * from "./service"+export * from "./http"diff --git a/packages/plugins/magento2-connector/src/types/service.ts b/packages/plugins/magento2-connector/src/types/service.tsnew file mode 100644index 000000000..d7583200c--- /dev/null+++ b/packages/plugins/magento2-connector/src/types/service.ts@@ -0,0 +1,78 @@+import {+ Context,+ FindConfig,+ IModuleService,+} from "@medusajs/framework/types"++import {+ CreateMagentoWebhookDeliveryDTO,+ CreateMagentoWebhookEndpointDTO,+ FilterableMagentoWebhookDeliveryProps,+ FilterableMagentoWebhookEndpointProps,+ MagentoWebhookDeliveryDTO,+ MagentoWebhookEndpointDTO,+ UpdateMagentoWebhookDeliveryDTO,+ UpdateMagentoWebhookEndpointDTO,+} from "./common"++export interface IMagentoWebhookModuleService extends IModuleService {+ retrieveMagentoWebhookEndpoint(+ id: string,+ config?: FindConfig<MagentoWebhookEndpointDTO>,+ sharedContext?: Context+ ): Promise<MagentoWebhookEndpointDTO>+ listMagentoWebhookEndpoints(+ filters?: FilterableMagentoWebhookEndpointProps,+ config?: FindConfig<MagentoWebhookEndpointDTO>,+ sharedContext?: Context+ ): Promise<MagentoWebhookEndpointDTO[]>+ createMagentoWebhookEndpoints(+ data: CreateMagentoWebhookEndpointDTO,+ sharedContext?: Context+ ): Promise<MagentoWebhookEndpointDTO>+ createMagentoWebhookEndpoints(+ data: CreateMagentoWebhookEndpointDTO[],+ sharedContext?: Context+ ): Promise<MagentoWebhookEndpointDTO[]>+ updateMagentoWebhookEndpoints(+ data: UpdateMagentoWebhookEndpointDTO,+ sharedContext?: Context+ ): Promise<MagentoWebhookEndpointDTO>+ updateMagentoWebhookEndpoints(+ data: UpdateMagentoWebhookEndpointDTO[],+ sharedContext?: Context+ ): Promise<MagentoWebhookEndpointDTO[]>+ softDeleteMagentoWebhookEndpoints(+ ids: string | string[],+ config?: unknown,+ sharedContext?: Context+ ): Promise<Record<string, string[]> | void>+ restoreMagentoWebhookEndpoints(+ ids: string | string[],+ config?: unknown,+ sharedContext?: Context+ ): Promise<Record<string, string[]> | void>++ retrieveMagentoWebhookDelivery(+ id: string,+ config?: FindConfig<MagentoWebhookDeliveryDTO>,+ sharedContext?: Context+ ): Promise<MagentoWebhookDeliveryDTO>+ listMagentoWebhookDeliveries(+ filters?: FilterableMagentoWebhookDeliveryProps,+ config?: FindConfig<MagentoWebhookDeliveryDTO>,+ sharedContext?: Context+ ): Promise<MagentoWebhookDeliveryDTO[]>+ createMagentoWebhookDeliveries(+ data: CreateMagentoWebhookDeliveryDTO[],+ sharedContext?: Context+ ): Promise<MagentoWebhookDeliveryDTO[]>+ updateMagentoWebhookDeliveries(+ data: UpdateMagentoWebhookDeliveryDTO[],+ sharedContext?: Context+ ): Promise<MagentoWebhookDeliveryDTO[]>+ deleteMagentoWebhookDeliveries(+ ids: string | string[],+ sharedContext?: Context+ ): Promise<void>+}diff --git a/packages/plugins/magento2-connector/src/workflows/external-payment/index.ts b/packages/plugins/magento2-connector/src/workflows/external-payment/index.tsnew file mode 100644index 000000000..68de82c9f--- /dev/null+++ b/packages/plugins/magento2-connector/src/workflows/external-payment/index.ts@@ -0,0 +1,2 @@+export * from "./steps"+export * from "./workflows"diff --git a/packages/plugins/magento2-connector/src/workflows/external-payment/steps/build-refund-requested-event.ts b/packages/plugins/magento2-connector/src/workflows/external-payment/steps/build-refund-requested-event.tsnew file mode 100644index 000000000..fb96ce697--- /dev/null+++ b/packages/plugins/magento2-connector/src/workflows/external-payment/steps/build-refund-requested-event.ts@@ -0,0 +1,73 @@+import { MedusaError } from "@medusajs/framework/utils"+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"++import { EXTERNAL_PAYMENT_PROVIDER_ID, EXTERNAL_REFUND_SOURCE } from "../../../types"++type RefundRow = {+ id: string+ amount: unknown+ note?: string | null+ metadata?: Record<string, unknown> | null+ created_at?: string | Date | null+}++export type BuildRefundRequestedEventStepInput = {+ payment?: {+ id: string+ provider_id: string+ currency_code: string+ payment_collection_id?: string | null+ refunds?: (RefundRow | null)[] | null+ } | null+ order_id?: string | null+}++export type RefundRequestedEventData = {+ order_id: string+ payment_id: string+ refund_id: string+ amount: number+ currency_code: string+ note: string | null+}++export const buildRefundRequestedEventStepId = "build-refund-requested-event"++/**+ * Picks the newest refund on an external-provider payment that did not come+ * from Magento itself. Returns an empty list when there is nothing to forward.+ */+export const buildRefundRequestedEventStep = createStep(+ buildRefundRequestedEventStepId,+ async (input: BuildRefundRequestedEventStepInput) => {+ const payment = input.payment+ if (!payment || payment.provider_id !== EXTERNAL_PAYMENT_PROVIDER_ID) {+ return new StepResponse<RefundRequestedEventData[]>([])+ }+ if (!input.order_id) {+ throw new MedusaError(+ MedusaError.Types.NOT_FOUND,+ `Payment ${payment.id} is not attached to an order`+ )+ }++ const newest = (payment.refunds ?? [])+ .filter((r): r is RefundRow => !!r)+ .sort((a, b) => new Date(b.created_at ?? 0).getTime() - new Date(a.created_at ?? 0).getTime())[0]++ if (!newest || newest.metadata?.source === EXTERNAL_REFUND_SOURCE) {+ return new StepResponse<RefundRequestedEventData[]>([])+ }++ return new StepResponse<RefundRequestedEventData[]>([+ {+ order_id: input.order_id,+ payment_id: payment.id,+ refund_id: newest.id,+ amount: Number(newest.amount),+ currency_code: payment.currency_code,+ note: newest.note ?? null,+ },+ ])+ }+)diff --git a/packages/plugins/magento2-connector/src/workflows/external-payment/steps/index.ts b/packages/plugins/magento2-connector/src/workflows/external-payment/steps/index.tsnew file mode 100644index 000000000..602d7c925--- /dev/null+++ b/packages/plugins/magento2-connector/src/workflows/external-payment/steps/index.ts@@ -0,0 +1,2 @@+export * from "./build-refund-requested-event"+export * from "./validate-external-payment"diff --git a/packages/plugins/magento2-connector/src/workflows/external-payment/steps/validate-external-payment.ts b/packages/plugins/magento2-connector/src/workflows/external-payment/steps/validate-external-payment.tsnew file mode 100644index 000000000..b6cdf3da4--- /dev/null+++ b/packages/plugins/magento2-connector/src/workflows/external-payment/steps/validate-external-payment.ts@@ -0,0 +1,28 @@+import { MedusaError } from "@medusajs/framework/utils"+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"++import { EXTERNAL_PAYMENT_PROVIDER_ID } from "../../../types"++export type ValidateExternalPaymentStepInput = {+ order_id: string+ payments: { id: string; provider_id: string; captured_at: Date | string | null }[]+}++export const validateExternalPaymentStepId = "validate-external-payment"+export const validateExternalPaymentStep = createStep(+ validateExternalPaymentStepId,+ async (input: ValidateExternalPaymentStepInput) => {+ const payment = input.payments.find(+ (p) => p.provider_id === EXTERNAL_PAYMENT_PROVIDER_ID && !!p.captured_at+ )++ if (!payment) {+ throw new MedusaError(+ MedusaError.Types.INVALID_DATA,+ `Order with id "${input.order_id}" has no captured payment on the external provider`+ )+ }++ return new StepResponse(payment.id)+ }+)diff --git a/packages/plugins/magento2-connector/src/workflows/external-payment/workflows/emit-refund-requested.ts b/packages/plugins/magento2-connector/src/workflows/external-payment/workflows/emit-refund-requested.tsnew file mode 100644index 000000000..eb717bbd6--- /dev/null+++ b/packages/plugins/magento2-connector/src/workflows/external-payment/workflows/emit-refund-requested.ts@@ -0,0 +1,65 @@+import {+ WorkflowData,+ WorkflowResponse,+ createWorkflow,+ transform,+ when,+} from "@medusajs/framework/workflows-sdk"+import { emitEventStep, useQueryGraphStep } from "@medusajs/medusa/core-flows"++import { MagentoWebhookEvents } from "../../../types"+import { buildRefundRequestedEventStep } from "../steps"++export type EmitRefundRequestedWorkflowInput = {+ payment_id: string+}++export const emitRefundRequestedWorkflowId = "emit-refund-requested"+/**+ * A refund recorded in Mercur on an external-provider payment moved no money:+ * the storefront that captured the payment has to execute it. This announces+ * it as `order.refund_requested`.+ */+export const emitRefundRequestedWorkflow = createWorkflow(+ emitRefundRequestedWorkflowId,+ (input: WorkflowData<EmitRefundRequestedWorkflowInput>) => {+ const payments = useQueryGraphStep({+ entity: "payment",+ fields: [+ "id",+ "provider_id",+ "currency_code",+ "payment_collection_id",+ "refunds.id",+ "refunds.amount",+ "refunds.note",+ "refunds.metadata",+ "refunds.created_at",+ ],+ filters: { id: input.payment_id },+ }).config({ name: "payment" })++ const collectionId = transform({ payments }, ({ payments }) =>+ payments.data[0]?.payment_collection_id ?? "__none__"+ )++ const links = useQueryGraphStep({+ entity: "order_payment_collection",+ fields: ["order_id"],+ filters: { payment_collection_id: collectionId },+ }).config({ name: "order-payment-collection" })++ const events = buildRefundRequestedEventStep(+ transform({ payments, links }, ({ payments, links }) => ({+ payment: payments.data[0] ?? null,+ order_id: links.data[0]?.order_id ?? null,+ }))+ )++ when({ events }, ({ events }) => events.length > 0).then(() => {+ emitEventStep({ eventName: MagentoWebhookEvents.REFUND_REQUESTED, data: events })+ })++ return new WorkflowResponse(events)+ }+)diff --git a/packages/plugins/magento2-connector/src/workflows/external-payment/workflows/index.ts b/packages/plugins/magento2-connector/src/workflows/external-payment/workflows/index.tsnew file mode 100644index 000000000..a607ac0f9--- /dev/null+++ b/packages/plugins/magento2-connector/src/workflows/external-payment/workflows/index.ts@@ -0,0 +1,2 @@+export * from "./emit-refund-requested"+export * from "./record-external-refund"diff --git a/packages/plugins/magento2-connector/src/workflows/external-payment/workflows/record-external-refund.ts b/packages/plugins/magento2-connector/src/workflows/external-payment/workflows/record-external-refund.tsnew file mode 100644index 000000000..c5237f38d--- /dev/null+++ b/packages/plugins/magento2-connector/src/workflows/external-payment/workflows/record-external-refund.ts@@ -0,0 +1,80 @@+import {+ WorkflowData,+ WorkflowResponse,+ createWorkflow,+ transform,+} from "@medusajs/framework/workflows-sdk"+import {+ emitEventStep,+ refundPaymentWorkflow,+ useQueryGraphStep,+} from "@medusajs/medusa/core-flows"++import { EXTERNAL_REFUND_SOURCE, MagentoWebhookEvents } from "../../../types"+import { validateExternalPaymentStep } from "../steps"++export type RecordExternalRefundWorkflowInput = {+ order_id: string+ amount: number+ reference?: string+ note?: string+ created_by?: string+}++export const recordExternalRefundWorkflowId = "record-external-refund"+/**+ * Mirrors a refund that already happened in the external storefront onto the+ * order's external-provider payment, so totals, commission lines and the+ * payout balance follow.+ */+export const recordExternalRefundWorkflow = createWorkflow(+ recordExternalRefundWorkflowId,+ (input: WorkflowData<RecordExternalRefundWorkflowInput>) => {+ const orders = useQueryGraphStep({+ entity: "order",+ fields: [+ "id",+ "payment_collections.payments.id",+ "payment_collections.payments.provider_id",+ "payment_collections.payments.captured_at",+ ],+ filters: { id: input.order_id },+ options: { throwIfKeyNotFound: true },+ })++ const validationInput = transform({ input, orders }, ({ input, orders }) => ({+ order_id: input.order_id,+ payments: (orders.data[0]?.payment_collections ?? []).flatMap(+ (pc) => pc?.payments ?? []+ ),+ }))++ const paymentId = validateExternalPaymentStep(validationInput)++ const refundInput = transform({ input, paymentId }, ({ input, paymentId }) => ({+ payment_id: paymentId,+ amount: input.amount,+ note: input.reference+ ? `${input.note ?? "External refund"} (${input.reference})`+ : input.note,+ created_by: input.created_by,+ // Lets the refund-requested subscriber tell this refund apart from one+ // a seller or operator starts in Mercur, which Magento must execute.+ metadata: { source: EXTERNAL_REFUND_SOURCE, reference: input.reference ?? null },+ }))++ const payment = refundPaymentWorkflow.runAsStep({ input: refundInput })++ emitEventStep({+ eventName: MagentoWebhookEvents.REFUND_RECORDED,+ data: transform({ input, paymentId }, ({ input, paymentId }) => ({+ id: input.order_id,+ payment_id: paymentId,+ amount: input.amount,+ reference: input.reference ?? null,+ })),+ })++ return new WorkflowResponse(payment)+ }+)diff --git a/packages/plugins/magento2-connector/src/workflows/index.ts b/packages/plugins/magento2-connector/src/workflows/index.tsnew file mode 100644index 000000000..4f4169d9d--- /dev/null+++ b/packages/plugins/magento2-connector/src/workflows/index.ts@@ -0,0 +1,2 @@+export * from "./magento-webhook"+export * from "./external-payment"diff --git a/packages/plugins/magento2-connector/src/workflows/magento-webhook/index.ts b/packages/plugins/magento2-connector/src/workflows/magento-webhook/index.tsnew file mode 100644index 000000000..68de82c9f--- /dev/null+++ b/packages/plugins/magento2-connector/src/workflows/magento-webhook/index.ts@@ -0,0 +1,2 @@+export * from "./steps"+export * from "./workflows"diff --git a/packages/plugins/magento2-connector/src/workflows/magento-webhook/steps/create-magento-webhook-deliveries.ts b/packages/plugins/magento2-connector/src/workflows/magento-webhook/steps/create-magento-webhook-deliveries.tsnew file mode 100644index 000000000..eba1d35a2--- /dev/null+++ b/packages/plugins/magento2-connector/src/workflows/magento-webhook/steps/create-magento-webhook-deliveries.ts@@ -0,0 +1,47 @@+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"++import { IMagentoWebhookModuleService, MAGENTO_WEBHOOK_MODULE } from "../../../types"++export type CreateMagentoWebhookDeliveriesStepInput = {+ event: string+ payload: Record<string, unknown>+}++export const createMagentoWebhookDeliveriesStepId = "create-magento-webhook-deliveries"+export const createMagentoWebhookDeliveriesStep = createStep(+ createMagentoWebhookDeliveriesStepId,+ async (input: CreateMagentoWebhookDeliveriesStepInput, { container }) => {+ const service = container.resolve<IMagentoWebhookModuleService>(MAGENTO_WEBHOOK_MODULE)++ const endpoints = await service.listMagentoWebhookEndpoints({ is_active: true })+ const subscribed = endpoints.filter((endpoint) => endpoint.events.includes(input.event))++ if (!subscribed.length) {+ return new StepResponse([], [])+ }++ const deliveries = await service.createMagentoWebhookDeliveries(+ subscribed.map((endpoint) => ({+ endpoint_id: endpoint.id,+ event: input.event,+ payload: input.payload,+ status: "pending" as const,+ attempts: 0,+ next_attempt_at: new Date(),+ }))+ )++ return new StepResponse(+ deliveries,+ deliveries.map((d) => d.id)+ )+ },+ async (ids, { container }) => {+ if (!ids?.length) {+ return+ }++ const service = container.resolve<IMagentoWebhookModuleService>(MAGENTO_WEBHOOK_MODULE)+ await service.deleteMagentoWebhookDeliveries(ids)+ }+)diff --git a/packages/plugins/magento2-connector/src/workflows/magento-webhook/steps/create-magento-webhook-endpoints.ts b/packages/plugins/magento2-connector/src/workflows/magento-webhook/steps/create-magento-webhook-endpoints.tsnew file mode 100644index 000000000..a75f55dfa--- /dev/null+++ b/packages/plugins/magento2-connector/src/workflows/magento-webhook/steps/create-magento-webhook-endpoints.ts@@ -0,0 +1,32 @@+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"++import {+ CreateMagentoWebhookEndpointDTO,+ IMagentoWebhookModuleService,+ MAGENTO_WEBHOOK_MODULE,+} from "../../../types"++export type CreateMagentoWebhookEndpointsStepInput = CreateMagentoWebhookEndpointDTO[]++export const createMagentoWebhookEndpointsStepId = "create-magento-webhook-endpoints"+export const createMagentoWebhookEndpointsStep = createStep(+ createMagentoWebhookEndpointsStepId,+ async (data: CreateMagentoWebhookEndpointsStepInput, { container }) => {+ const service = container.resolve<IMagentoWebhookModuleService>(MAGENTO_WEBHOOK_MODULE)++ const endpoints = await service.createMagentoWebhookEndpoints(data)++ return new StepResponse(+ endpoints,+ endpoints.map((e) => e.id)+ )+ },+ async (ids, { container }) => {+ if (!ids?.length) {+ return+ }++ const service = container.resolve<IMagentoWebhookModuleService>(MAGENTO_WEBHOOK_MODULE)+ await service.softDeleteMagentoWebhookEndpoints(ids)+ }+)diff --git a/packages/plugins/magento2-connector/src/workflows/magento-webhook/steps/delete-magento-webhook-deliveries.ts b/packages/plugins/magento2-connector/src/workflows/magento-webhook/steps/delete-magento-webhook-deliveries.tsnew file mode 100644index 000000000..cb513c4aa--- /dev/null+++ b/packages/plugins/magento2-connector/src/workflows/magento-webhook/steps/delete-magento-webhook-deliveries.ts@@ -0,0 +1,27 @@+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"++import { IMagentoWebhookModuleService, MAGENTO_WEBHOOK_MODULE } from "../../../types"++export type DeleteMagentoWebhookDeliveriesStepInput = {+ delivered_before: Date+ limit?: number+}++export const deleteMagentoWebhookDeliveriesStepId = "delete-magento-webhook-deliveries"+export const deleteMagentoWebhookDeliveriesStep = createStep(+ deleteMagentoWebhookDeliveriesStepId,+ async (input: DeleteMagentoWebhookDeliveriesStepInput, { container }) => {+ const service = container.resolve<IMagentoWebhookModuleService>(MAGENTO_WEBHOOK_MODULE)++ const stale = await service.listMagentoWebhookDeliveries(+ { status: "delivered", delivered_at: { $lt: input.delivered_before } },+ { select: ["id"], take: input.limit ?? 1000 }+ )++ if (stale.length) {+ await service.deleteMagentoWebhookDeliveries(stale.map((d) => d.id))+ }++ return new StepResponse(stale.length)+ }+)diff --git a/packages/plugins/magento2-connector/src/workflows/magento-webhook/steps/delete-magento-webhook-endpoints.ts b/packages/plugins/magento2-connector/src/workflows/magento-webhook/steps/delete-magento-webhook-endpoints.tsnew file mode 100644index 000000000..e254ebd56--- /dev/null+++ b/packages/plugins/magento2-connector/src/workflows/magento-webhook/steps/delete-magento-webhook-endpoints.ts@@ -0,0 +1,25 @@+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"++import { IMagentoWebhookModuleService, MAGENTO_WEBHOOK_MODULE } from "../../../types"++export type DeleteMagentoWebhookEndpointsStepInput = string[]++export const deleteMagentoWebhookEndpointsStepId = "delete-magento-webhook-endpoints"+export const deleteMagentoWebhookEndpointsStep = createStep(+ deleteMagentoWebhookEndpointsStepId,+ async (ids: DeleteMagentoWebhookEndpointsStepInput, { container }) => {+ const service = container.resolve<IMagentoWebhookModuleService>(MAGENTO_WEBHOOK_MODULE)++ await service.softDeleteMagentoWebhookEndpoints(ids)++ return new StepResponse(void 0, ids)+ },+ async (ids, { container }) => {+ if (!ids?.length) {+ return+ }++ const service = container.resolve<IMagentoWebhookModuleService>(MAGENTO_WEBHOOK_MODULE)+ await service.restoreMagentoWebhookEndpoints(ids)+ }+)diff --git a/packages/plugins/magento2-connector/src/workflows/magento-webhook/steps/index.ts b/packages/plugins/magento2-connector/src/workflows/magento-webhook/steps/index.tsnew file mode 100644index 000000000..1e6174ad6--- /dev/null+++ b/packages/plugins/magento2-connector/src/workflows/magento-webhook/steps/index.ts@@ -0,0 +1,7 @@+export * from "./create-magento-webhook-endpoints"+export * from "./update-magento-webhook-endpoints"+export * from "./delete-magento-webhook-endpoints"+export * from "./create-magento-webhook-deliveries"+export * from "./validate-magento-webhook-delivery"+export * from "./send-magento-webhook-delivery"+export * from "./delete-magento-webhook-deliveries"diff --git a/packages/plugins/magento2-connector/src/workflows/magento-webhook/steps/send-magento-webhook-delivery.ts b/packages/plugins/magento2-connector/src/workflows/magento-webhook/steps/send-magento-webhook-delivery.tsnew file mode 100644index 000000000..fb8196659--- /dev/null+++ b/packages/plugins/magento2-connector/src/workflows/magento-webhook/steps/send-magento-webhook-delivery.ts@@ -0,0 +1,98 @@+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"++import { nextWebhookAttemptAt, signWebhookBody } from "../../../modules/magento-webhook/utils"+import {+ IMagentoWebhookModuleService,+ MAGENTO_WEBHOOK_MODULE,+ MagentoWebhookDeliveryDTO,+ UpdateMagentoWebhookDeliveryDTO,+} from "../../../types"++const REQUEST_TIMEOUT_MS = 10_000+const MAX_RESPONSE_BODY = 2_000++export type SendMagentoWebhookDeliveryStepInput = {+ delivery: MagentoWebhookDeliveryDTO+ skip: boolean+}++export const sendMagentoWebhookDeliveryStepId = "send-magento-webhook-delivery"+export const sendMagentoWebhookDeliveryStep = createStep(+ sendMagentoWebhookDeliveryStepId,+ async ({ delivery, skip }: SendMagentoWebhookDeliveryStepInput, { container }) => {+ const endpoint = delivery.endpoint+ if (skip || !endpoint) {+ return new StepResponse(delivery)+ }++ const service = container.resolve<IMagentoWebhookModuleService>(MAGENTO_WEBHOOK_MODULE)++ const body = JSON.stringify({+ id: delivery.id,+ event: delivery.event,+ created_at: delivery.created_at,+ data: delivery.payload,+ })++ let responseStatus: number | null = null+ let responseBody: string | null = null++ try {+ const response = await fetch(endpoint.url, {+ method: "POST",+ headers: {+ "content-type": "application/json",+ "user-agent": "mercur-magento2-connector",+ "x-mercur-event": delivery.event,+ "x-mercur-delivery": delivery.id,+ "x-mercur-signature": signWebhookBody(body, endpoint.secret),+ },+ body,+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),+ })+ responseStatus = response.status+ responseBody = (await response.text()).slice(0, MAX_RESPONSE_BODY)+ } catch (error) {+ responseBody = String(error instanceof Error ? error.message : error).slice(+ 0,+ MAX_RESPONSE_BODY+ )+ }++ const attempts = delivery.attempts + 1+ const ok = responseStatus !== null && responseStatus >= 200 && responseStatus < 300+ const nextAttemptAt = ok ? null : nextWebhookAttemptAt(attempts)++ const previous: UpdateMagentoWebhookDeliveryDTO = {+ id: delivery.id,+ status: delivery.status,+ attempts: delivery.attempts,+ next_attempt_at: delivery.next_attempt_at,+ response_status: delivery.response_status,+ response_body: delivery.response_body,+ delivered_at: delivery.delivered_at,+ }++ const [updated] = await service.updateMagentoWebhookDeliveries([+ {+ id: delivery.id,+ attempts,+ response_status: responseStatus,+ response_body: responseBody,+ status: ok ? "delivered" : nextAttemptAt ? "failed" : "dead",+ next_attempt_at: nextAttemptAt,+ delivered_at: ok ? new Date() : null,+ },+ ])++ return new StepResponse(updated, previous)+ },+ async (previous, { container }) => {+ if (!previous) {+ return+ }++ const service = container.resolve<IMagentoWebhookModuleService>(MAGENTO_WEBHOOK_MODULE)+ await service.updateMagentoWebhookDeliveries([previous])+ }+)diff --git a/packages/plugins/magento2-connector/src/workflows/magento-webhook/steps/update-magento-webhook-endpoints.ts b/packages/plugins/magento2-connector/src/workflows/magento-webhook/steps/update-magento-webhook-endpoints.tsnew file mode 100644index 000000000..3a9dde2ec--- /dev/null+++ b/packages/plugins/magento2-connector/src/workflows/magento-webhook/steps/update-magento-webhook-endpoints.ts@@ -0,0 +1,44 @@+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"++import {+ IMagentoWebhookModuleService,+ MAGENTO_WEBHOOK_MODULE,+ UpdateMagentoWebhookEndpointDTO,+} from "../../../types"++export type UpdateMagentoWebhookEndpointsStepInput = UpdateMagentoWebhookEndpointDTO[]++export const updateMagentoWebhookEndpointsStepId = "update-magento-webhook-endpoints"+export const updateMagentoWebhookEndpointsStep = createStep(+ updateMagentoWebhookEndpointsStepId,+ async (data: UpdateMagentoWebhookEndpointsStepInput, { container }) => {+ const service = container.resolve<IMagentoWebhookModuleService>(MAGENTO_WEBHOOK_MODULE)++ const previous = await service.listMagentoWebhookEndpoints({+ id: data.map((d) => d.id),+ })++ const endpoints = await service.updateMagentoWebhookEndpoints(data)++ return new StepResponse(+ endpoints,+ previous.map((e) => ({+ id: e.id,+ url: e.url,+ secret: e.secret,+ events: e.events,+ is_active: e.is_active,+ description: e.description,+ metadata: e.metadata,+ }))+ )+ },+ async (previous, { container }) => {+ if (!previous?.length) {+ return+ }++ const service = container.resolve<IMagentoWebhookModuleService>(MAGENTO_WEBHOOK_MODULE)+ await service.updateMagentoWebhookEndpoints(previous)+ }+)diff --git a/packages/plugins/magento2-connector/src/workflows/magento-webhook/steps/validate-magento-webhook-delivery.ts b/packages/plugins/magento2-connector/src/workflows/magento-webhook/steps/validate-magento-webhook-delivery.tsnew file mode 100644index 000000000..2ff46992a--- /dev/null+++ b/packages/plugins/magento2-connector/src/workflows/magento-webhook/steps/validate-magento-webhook-delivery.ts@@ -0,0 +1,34 @@+import { MedusaError } from "@medusajs/framework/utils"+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"++import { IMagentoWebhookModuleService, MAGENTO_WEBHOOK_MODULE } from "../../../types"++export type ValidateMagentoWebhookDeliveryStepInput = {+ delivery_id: string+ endpoint_id?: string+ force?: boolean+}++export const validateMagentoWebhookDeliveryStepId = "validate-magento-webhook-delivery"+export const validateMagentoWebhookDeliveryStep = createStep(+ validateMagentoWebhookDeliveryStepId,+ async (input: ValidateMagentoWebhookDeliveryStepInput, { container }) => {+ const service = container.resolve<IMagentoWebhookModuleService>(MAGENTO_WEBHOOK_MODULE)++ const delivery = await service.retrieveMagentoWebhookDelivery(input.delivery_id, {+ relations: ["endpoint"],+ })++ if (input.endpoint_id && delivery.endpoint_id !== input.endpoint_id) {+ throw new MedusaError(+ MedusaError.Types.NOT_FOUND,+ `Delivery with id "${input.delivery_id}" not found`+ )+ }++ const skip =+ !input.force && (delivery.status === "delivered" || delivery.status === "dead")++ return new StepResponse({ delivery, skip })+ }+)diff --git a/packages/plugins/magento2-connector/src/workflows/magento-webhook/workflows/create-magento-webhook-endpoints.ts b/packages/plugins/magento2-connector/src/workflows/magento-webhook/workflows/create-magento-webhook-endpoints.tsnew file mode 100644index 000000000..2aa5b61a7--- /dev/null+++ b/packages/plugins/magento2-connector/src/workflows/magento-webhook/workflows/create-magento-webhook-endpoints.ts@@ -0,0 +1,32 @@+import { randomBytes } from "node:crypto"++import {+ WorkflowData,+ WorkflowResponse,+ createWorkflow,+ transform,+} from "@medusajs/framework/workflows-sdk"++import { CreateMagentoWebhookEndpointDTO } from "../../../types"+import { createMagentoWebhookEndpointsStep } from "../steps"++export type CreateMagentoWebhookEndpointsWorkflowInput = {+ endpoints: (Omit<CreateMagentoWebhookEndpointDTO, "secret"> & { secret?: string })[]+}++export const createMagentoWebhookEndpointsWorkflowId = "create-magento-webhook-endpoints"+export const createMagentoWebhookEndpointsWorkflow = createWorkflow(+ createMagentoWebhookEndpointsWorkflowId,+ (input: WorkflowData<CreateMagentoWebhookEndpointsWorkflowInput>) => {+ const data = transform({ input }, ({ input }) =>+ input.endpoints.map((endpoint) => ({+ ...endpoint,+ secret: endpoint.secret ?? randomBytes(32).toString("hex"),+ }))+ )++ const endpoints = createMagentoWebhookEndpointsStep(data)++ return new WorkflowResponse(endpoints)+ }+)diff --git a/packages/plugins/magento2-connector/src/workflows/magento-webhook/workflows/delete-magento-webhook-endpoints.ts b/packages/plugins/magento2-connector/src/workflows/magento-webhook/workflows/delete-magento-webhook-endpoints.tsnew file mode 100644index 000000000..eedd32059--- /dev/null+++ b/packages/plugins/magento2-connector/src/workflows/magento-webhook/workflows/delete-magento-webhook-endpoints.ts@@ -0,0 +1,19 @@+import {+ WorkflowData,+ WorkflowResponse,+ createWorkflow,+} from "@medusajs/framework/workflows-sdk"++import { deleteMagentoWebhookEndpointsStep } from "../steps"++export type DeleteMagentoWebhookEndpointsWorkflowInput = { ids: string[] }++export const deleteMagentoWebhookEndpointsWorkflowId = "delete-magento-webhook-endpoints"+export const deleteMagentoWebhookEndpointsWorkflow = createWorkflow(+ deleteMagentoWebhookEndpointsWorkflowId,+ (input: WorkflowData<DeleteMagentoWebhookEndpointsWorkflowInput>) => {+ const deleted = deleteMagentoWebhookEndpointsStep(input.ids)++ return new WorkflowResponse(deleted)+ }+)diff --git a/packages/plugins/magento2-connector/src/workflows/magento-webhook/workflows/deliver-magento-webhook.ts b/packages/plugins/magento2-connector/src/workflows/magento-webhook/workflows/deliver-magento-webhook.tsnew file mode 100644index 000000000..bc4eaaaaa--- /dev/null+++ b/packages/plugins/magento2-connector/src/workflows/magento-webhook/workflows/deliver-magento-webhook.ts@@ -0,0 +1,24 @@+import {+ WorkflowData,+ WorkflowResponse,+ createWorkflow,+} from "@medusajs/framework/workflows-sdk"++import { sendMagentoWebhookDeliveryStep, validateMagentoWebhookDeliveryStep } from "../steps"++export type DeliverMagentoWebhookWorkflowInput = {+ delivery_id: string+ endpoint_id?: string+ force?: boolean+}++export const deliverMagentoWebhookWorkflowId = "deliver-magento-webhook"+export const deliverMagentoWebhookWorkflow = createWorkflow(+ deliverMagentoWebhookWorkflowId,+ (input: WorkflowData<DeliverMagentoWebhookWorkflowInput>) => {+ const validated = validateMagentoWebhookDeliveryStep(input)+ const delivery = sendMagentoWebhookDeliveryStep(validated)++ return new WorkflowResponse(delivery)+ }+)diff --git a/packages/plugins/magento2-connector/src/workflows/magento-webhook/workflows/enqueue-magento-webhook-deliveries.ts b/packages/plugins/magento2-connector/src/workflows/magento-webhook/workflows/enqueue-magento-webhook-deliveries.tsnew file mode 100644index 000000000..2e9489bae--- /dev/null+++ b/packages/plugins/magento2-connector/src/workflows/magento-webhook/workflows/enqueue-magento-webhook-deliveries.ts@@ -0,0 +1,32 @@+import {+ WorkflowData,+ WorkflowResponse,+ createWorkflow,+ transform,+} from "@medusajs/framework/workflows-sdk"+import { emitEventStep } from "@medusajs/medusa/core-flows"++import { MagentoWebhookEvents } from "../../../types"+import { createMagentoWebhookDeliveriesStep } from "../steps"++export type EnqueueMagentoWebhookDeliveriesWorkflowInput = {+ event: string+ payload: Record<string, unknown>+}++export const enqueueMagentoWebhookDeliveriesWorkflowId = "enqueue-magento-webhook-deliveries"+export const enqueueMagentoWebhookDeliveriesWorkflow = createWorkflow(+ enqueueMagentoWebhookDeliveriesWorkflowId,+ (input: WorkflowData<EnqueueMagentoWebhookDeliveriesWorkflowInput>) => {+ const deliveries = createMagentoWebhookDeliveriesStep(input)++ emitEventStep({+ eventName: MagentoWebhookEvents.DELIVERY_CREATED,+ data: transform({ deliveries }, ({ deliveries }) =>+ deliveries.map((d) => ({ id: d.id }))+ ),+ })++ return new WorkflowResponse(deliveries)+ }+)diff --git a/packages/plugins/magento2-connector/src/workflows/magento-webhook/workflows/index.ts b/packages/plugins/magento2-connector/src/workflows/magento-webhook/workflows/index.tsnew file mode 100644index 000000000..28e776686--- /dev/null+++ b/packages/plugins/magento2-connector/src/workflows/magento-webhook/workflows/index.ts@@ -0,0 +1,6 @@+export * from "./create-magento-webhook-endpoints"+export * from "./update-magento-webhook-endpoints"+export * from "./delete-magento-webhook-endpoints"+export * from "./enqueue-magento-webhook-deliveries"+export * from "./deliver-magento-webhook"+export * from "./prune-magento-webhook-deliveries"diff --git a/packages/plugins/magento2-connector/src/workflows/magento-webhook/workflows/prune-magento-webhook-deliveries.ts b/packages/plugins/magento2-connector/src/workflows/magento-webhook/workflows/prune-magento-webhook-deliveries.tsnew file mode 100644index 000000000..d2a9eb99d--- /dev/null+++ b/packages/plugins/magento2-connector/src/workflows/magento-webhook/workflows/prune-magento-webhook-deliveries.ts@@ -0,0 +1,22 @@+import {+ WorkflowData,+ WorkflowResponse,+ createWorkflow,+} from "@medusajs/framework/workflows-sdk"++import { deleteMagentoWebhookDeliveriesStep } from "../steps"++export type PruneMagentoWebhookDeliveriesWorkflowInput = {+ delivered_before: Date+ limit?: number+}++export const pruneMagentoWebhookDeliveriesWorkflowId = "prune-magento-webhook-deliveries"+export const pruneMagentoWebhookDeliveriesWorkflow = createWorkflow(+ pruneMagentoWebhookDeliveriesWorkflowId,+ (input: WorkflowData<PruneMagentoWebhookDeliveriesWorkflowInput>) => {+ const deleted = deleteMagentoWebhookDeliveriesStep(input)++ return new WorkflowResponse(deleted)+ }+)diff --git a/packages/plugins/magento2-connector/src/workflows/magento-webhook/workflows/update-magento-webhook-endpoints.ts b/packages/plugins/magento2-connector/src/workflows/magento-webhook/workflows/update-magento-webhook-endpoints.tsnew file mode 100644index 000000000..7ab641449--- /dev/null+++ b/packages/plugins/magento2-connector/src/workflows/magento-webhook/workflows/update-magento-webhook-endpoints.ts@@ -0,0 +1,22 @@+import {+ WorkflowData,+ WorkflowResponse,+ createWorkflow,+} from "@medusajs/framework/workflows-sdk"++import { UpdateMagentoWebhookEndpointDTO } from "../../../types"+import { updateMagentoWebhookEndpointsStep } from "../steps"++export type UpdateMagentoWebhookEndpointsWorkflowInput = {+ endpoints: UpdateMagentoWebhookEndpointDTO[]+}++export const updateMagentoWebhookEndpointsWorkflowId = "update-magento-webhook-endpoints"+export const updateMagentoWebhookEndpointsWorkflow = createWorkflow(+ updateMagentoWebhookEndpointsWorkflowId,+ (input: WorkflowData<UpdateMagentoWebhookEndpointsWorkflowInput>) => {+ const endpoints = updateMagentoWebhookEndpointsStep(input.endpoints)++ return new WorkflowResponse(endpoints)+ }+)diff --git a/packages/plugins/magento2-connector/tsconfig.json b/packages/plugins/magento2-connector/tsconfig.jsonnew file mode 100644index 000000000..157546f98--- /dev/null+++ b/packages/plugins/magento2-connector/tsconfig.json@@ -0,0 +1,23 @@+{+ "compilerOptions": {+ "target": "ES2021",+ "esModuleInterop": true,+ "module": "Node16",+ "moduleResolution": "Node16",+ "emitDecoratorMetadata": true,+ "experimentalDecorators": true,+ "skipLibCheck": true,+ "skipDefaultLibCheck": true,+ "declaration": false,+ "sourceMap": false,+ "inlineSourceMap": true,+ "outDir": "./.medusa/server",+ "rootDir": "./",+ "forceConsistentCasingInFileNames": true,+ "resolveJsonModule": true,+ "checkJs": false,+ "strictNullChecks": true+ },+ "include": ["**/*", ".medusa/types/*"],+ "exclude": ["node_modules", ".medusa/server", ".cache", "src/admin", "**/__tests__/**", "**/*.spec.ts"]+}diff --git a/packages/types/src/order-group/common.ts b/packages/types/src/order-group/common.tsindex f139ded12..ec815df40 100644--- a/packages/types/src/order-group/common.ts+++ b/packages/types/src/order-group/common.ts@@ -3,6 +3,7 @@ export type OrderGroupDTO = {display_id: numbercustomer_id: string | nullcart_id: string+ metadata: Record<string, unknown> | nullseller_count: numbertotal: numbercreated_at: Datediff --git a/packages/types/src/order-group/mutation.ts b/packages/types/src/order-group/mutation.tsindex 279f018f3..02363bb1a 100644--- a/packages/types/src/order-group/mutation.ts+++ b/packages/types/src/order-group/mutation.ts@@ -1,10 +1,12 @@export type CreateOrderGroupDTO = {customer_id?: string | nullcart_id: string+ metadata?: Record<string, unknown> | null}export type UpdateOrderGroupDTO = {id: stringcustomer_id?: stringcart_id?: string+ metadata?: Record<string, unknown> | null}diff --git a/packages/vendor/src/lib/client/auth-token.ts b/packages/vendor/src/lib/client/auth-token.tsindex 7f7e52fd0..f2364c0d0 100644--- a/packages/vendor/src/lib/client/auth-token.ts+++ b/packages/vendor/src/lib/client/auth-token.ts@@ -1,42 +1,16 @@-const AUTH_TOKEN_KEY = 'mercur_vendor_auth_token'--const SELLER_ID_KEY = 'mercur_vendor_seller_id'--const read = (key: string) => {- try {- return localStorage.getItem(key)- } catch {- return null- }-}--const write = (key: string, value: string | null) => {- try {- if (value === null) {- localStorage.removeItem(key)- } else {- localStorage.setItem(key, value)- }- } catch {- return- }-}--export const getAuthToken = () => read(AUTH_TOKEN_KEY)-export const setAuthToken = (token: string) => write(AUTH_TOKEN_KEY, token)-export const clearAuthToken = () => write(AUTH_TOKEN_KEY, null)--export const getSellerId = () => read(SELLER_ID_KEY)-export const setSellerId = (sellerId: string) => write(SELLER_ID_KEY, sellerId)-export const clearSellerId = () => write(SELLER_ID_KEY, null)--export const getAuthHeaders = (): Record<string, string> => {- const token = getAuthToken()-- const sellerId = getSellerId()-- return {- ...(token ? { Authorization: `Bearer ${token}` } : {}),- ...(sellerId ? { 'x-seller-id': sellerId } : {}),- }-}+import {+ resolveAuthHeaders,+ vendorAuth,+ vendorSellerStore,+ vendorTokenStore,+} from '@mercurjs/client'++export const getAuthToken = () => vendorTokenStore.get()+export const setAuthToken = (token: string) => vendorTokenStore.set(token)+export const clearAuthToken = () => vendorTokenStore.clear()++export const getSellerId = () => vendorSellerStore.get()+export const setSellerId = (sellerId: string) => vendorSellerStore.set(sellerId)+export const clearSellerId = () => vendorSellerStore.clear()++export const getAuthHeaders = () => resolveAuthHeaders(vendorAuth())diff --git a/packages/vendor/src/lib/client/client.ts b/packages/vendor/src/lib/client/client.tsindex 07787f2f9..57fb6a7b3 100644--- a/packages/vendor/src/lib/client/client.ts+++ b/packages/vendor/src/lib/client/client.ts@@ -1,4 +1,4 @@-import { createClient, InferClient } from '@mercurjs/client'+import { createClient, InferClient, vendorAuth } from '@mercurjs/client'import { Routes } from '@mercurjs/core/_generated'import config from 'virtual:mercur/config'@@ -12,7 +12,7 @@ export const sdk: InferClient<Routes> = createClient({fetchOptions: {credentials: 'omit',},- headers: getAuthHeaders,+ auth: vendorAuth(),})export const fetchQuery = async (@@ -60,7 +60,7 @@ export const fetchQuery = async (credentials: 'omit',headers: {'Content-Type': 'application/json',- ...getAuthHeaders(),+ ...(await getAuthHeaders()),...headers,},body: body ? JSON.stringify(body) : null,