@storewatch/medusa 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +23 -2
- package/dist/chunk-DQHAPSCU.js +15 -0
- package/dist/index.cjs +238 -0
- package/dist/index.d.cts +152 -0
- package/dist/index.d.ts +152 -0
- package/dist/index.js +198 -0
- package/dist/storefront.cjs +41 -0
- package/dist/storefront.d.cts +28 -0
- package/dist/storefront.d.ts +28 -0
- package/dist/storefront.js +10 -0
- package/package.json +51 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Edin Skeja
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,24 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @storewatch/medusa
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Storewatch for Medusa v2: server-confirmed orders, cancellations and refunds,
|
|
4
|
+
tied to the shopper's live session.
|
|
5
|
+
|
|
6
|
+
```ts
|
|
7
|
+
// src/subscribers/storewatch-order-placed.ts (one file per event)
|
|
8
|
+
export { orderPlacedSubscriber as default, orderPlacedConfig as config } from "@storewatch/medusa";
|
|
9
|
+
// also: orderCanceledSubscriber/orderCanceledConfig, paymentRefundedSubscriber/paymentRefundedConfig
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Set `STOREWATCH_SECRET_KEY` and `STOREWATCH_ENDPOINT` in the backend. Without
|
|
13
|
+
them the subscribers do nothing; with them they never throw into Medusa.
|
|
14
|
+
|
|
15
|
+
On the storefront, put the session on the cart (Medusa copies cart metadata
|
|
16
|
+
to the order):
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { storewatchCartMetadata } from "@storewatch/medusa/storefront";
|
|
20
|
+
await sdk.store.cart.update(cart.id, { metadata: { ...cart.metadata, ...storewatchCartMetadata(getStorewatch().ids()) } });
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
For failed payments (Medusa has no event for them), call `trackPaymentFailed`
|
|
24
|
+
from your payment webhook. ESM and CommonJS.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// src/storefront.ts
|
|
2
|
+
var METADATA_KEY = "storewatch";
|
|
3
|
+
function storewatchCartMetadata(ids) {
|
|
4
|
+
return { [METADATA_KEY]: { sessionId: ids.sessionId, ...ids.anonymousId ? { anonymousId: ids.anonymousId } : {} } };
|
|
5
|
+
}
|
|
6
|
+
function cartHasSession(metadata, sessionId) {
|
|
7
|
+
const current = metadata?.[METADATA_KEY];
|
|
8
|
+
return typeof current === "object" && current !== null && current.sessionId === sessionId;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export {
|
|
12
|
+
METADATA_KEY,
|
|
13
|
+
storewatchCartMetadata,
|
|
14
|
+
cartHasSession
|
|
15
|
+
};
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
METADATA_KEY: () => METADATA_KEY,
|
|
24
|
+
ORDER_FIELDS: () => ORDER_FIELDS,
|
|
25
|
+
configureStorewatch: () => configureStorewatch,
|
|
26
|
+
orderCanceledConfig: () => orderCanceledConfig,
|
|
27
|
+
orderCanceledSubscriber: () => orderCanceledSubscriber,
|
|
28
|
+
orderCompletedEvent: () => orderCompletedEvent,
|
|
29
|
+
orderPlacedConfig: () => orderPlacedConfig,
|
|
30
|
+
orderPlacedSubscriber: () => orderPlacedSubscriber,
|
|
31
|
+
paymentRefundedConfig: () => paymentRefundedConfig,
|
|
32
|
+
paymentRefundedSubscriber: () => paymentRefundedSubscriber,
|
|
33
|
+
resetStorewatchForTests: () => resetStorewatchForTests,
|
|
34
|
+
sessionOf: () => sessionOf,
|
|
35
|
+
toMinor: () => toMinor,
|
|
36
|
+
toNumber: () => toNumber,
|
|
37
|
+
trackPaymentFailed: () => trackPaymentFailed
|
|
38
|
+
});
|
|
39
|
+
module.exports = __toCommonJS(index_exports);
|
|
40
|
+
var import_node = require("@storewatch/node");
|
|
41
|
+
var import_constants = require("@storewatch/schema/constants");
|
|
42
|
+
|
|
43
|
+
// src/storefront.ts
|
|
44
|
+
var METADATA_KEY = "storewatch";
|
|
45
|
+
|
|
46
|
+
// src/index.ts
|
|
47
|
+
function toNumber(amount) {
|
|
48
|
+
if (amount === null || amount === void 0) return 0;
|
|
49
|
+
if (typeof amount === "number") return amount;
|
|
50
|
+
if (typeof amount === "string") return Number(amount);
|
|
51
|
+
const a = amount;
|
|
52
|
+
if (typeof a.numeric === "number") return a.numeric;
|
|
53
|
+
if (a.value !== void 0) return Number(a.value);
|
|
54
|
+
if (typeof a.toJSON === "function") return Number(a.toJSON());
|
|
55
|
+
return Number(String(amount));
|
|
56
|
+
}
|
|
57
|
+
var ORDER_FIELDS = [
|
|
58
|
+
"id",
|
|
59
|
+
"display_id",
|
|
60
|
+
"currency_code",
|
|
61
|
+
"total",
|
|
62
|
+
"created_at",
|
|
63
|
+
"customer_id",
|
|
64
|
+
"metadata",
|
|
65
|
+
"items.id",
|
|
66
|
+
"items.product_id",
|
|
67
|
+
"items.variant_id",
|
|
68
|
+
"items.title",
|
|
69
|
+
"items.product_title",
|
|
70
|
+
"items.quantity",
|
|
71
|
+
"items.unit_price"
|
|
72
|
+
];
|
|
73
|
+
function toMinor(amount, currency) {
|
|
74
|
+
const major = toNumber(amount);
|
|
75
|
+
if (!Number.isFinite(major)) return 0;
|
|
76
|
+
return Math.round(major * 10 ** (0, import_constants.currencyExponent)(currency));
|
|
77
|
+
}
|
|
78
|
+
function sessionOf(order) {
|
|
79
|
+
const meta = order.metadata?.[METADATA_KEY];
|
|
80
|
+
if (meta && typeof meta === "object") {
|
|
81
|
+
const { sessionId, anonymousId } = meta;
|
|
82
|
+
if (typeof sessionId === "string" && sessionId.length > 0 && sessionId.length <= import_constants.LIMITS.sessionIdMaxLength) {
|
|
83
|
+
return { sessionId, ...typeof anonymousId === "string" && anonymousId ? { anonymousId } : {}, linked: true };
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return { sessionId: `srv_${order.id}`.slice(0, import_constants.LIMITS.sessionIdMaxLength), linked: false };
|
|
87
|
+
}
|
|
88
|
+
function sessionFields(order) {
|
|
89
|
+
const { linked: _linked, ...fields } = sessionOf(order);
|
|
90
|
+
return fields;
|
|
91
|
+
}
|
|
92
|
+
function orderCompletedEvent(order) {
|
|
93
|
+
const currency = order.currency_code.toUpperCase();
|
|
94
|
+
const money = (amount) => ({ amount: toMinor(amount, currency), currency });
|
|
95
|
+
return {
|
|
96
|
+
...sessionFields(order),
|
|
97
|
+
...order.customer_id ? { customerId: order.customer_id } : {},
|
|
98
|
+
eventId: (0, import_node.eventIdFor)("order_completed", order.id),
|
|
99
|
+
...order.created_at ? { timestamp: new Date(order.created_at) } : {},
|
|
100
|
+
properties: {
|
|
101
|
+
orderId: order.id,
|
|
102
|
+
...order.display_id != null ? { orderNumber: String(order.display_id) } : {},
|
|
103
|
+
total: money(order.total),
|
|
104
|
+
items: (order.items ?? []).slice(0, import_constants.LIMITS.orderMaxItems).map((item) => ({
|
|
105
|
+
productId: item.product_id ?? item.id,
|
|
106
|
+
...item.variant_id ? { variantId: item.variant_id } : {},
|
|
107
|
+
...item.product_title || item.title ? { name: String(item.product_title || item.title).slice(0, 200) } : {},
|
|
108
|
+
quantity: Math.max(1, Math.round(toNumber(item.quantity) || 1)),
|
|
109
|
+
price: money(item.unit_price)
|
|
110
|
+
}))
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
var client;
|
|
115
|
+
var warnedUnconfigured = false;
|
|
116
|
+
function configureStorewatch(storewatch) {
|
|
117
|
+
client = storewatch;
|
|
118
|
+
}
|
|
119
|
+
function getClient(logger) {
|
|
120
|
+
if (client !== void 0) return client;
|
|
121
|
+
const secretKey = process.env.STOREWATCH_SECRET_KEY;
|
|
122
|
+
const endpoint = process.env.STOREWATCH_ENDPOINT;
|
|
123
|
+
if (!secretKey || !endpoint) {
|
|
124
|
+
if (!warnedUnconfigured) logger?.warn("[storewatch] STOREWATCH_SECRET_KEY / STOREWATCH_ENDPOINT not set; Medusa events are not sent.");
|
|
125
|
+
warnedUnconfigured = true;
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
client = (0, import_node.createStorewatch)({ secretKey, endpoint, onError: (e) => logger?.warn(`[storewatch] ${e.message}`) });
|
|
129
|
+
return client;
|
|
130
|
+
}
|
|
131
|
+
var resolveSafe = (container, key) => {
|
|
132
|
+
try {
|
|
133
|
+
return container.resolve(key);
|
|
134
|
+
} catch {
|
|
135
|
+
return void 0;
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
async function failOpen(container, label, run) {
|
|
139
|
+
const logger = resolveSafe(container, "logger");
|
|
140
|
+
try {
|
|
141
|
+
const storewatch = getClient(logger);
|
|
142
|
+
const query = resolveSafe(container, "query");
|
|
143
|
+
if (!storewatch || !query) return;
|
|
144
|
+
await run(query, storewatch);
|
|
145
|
+
} catch (error) {
|
|
146
|
+
logger?.warn(`[storewatch] ${label} failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
async function fetchOrder(query, id) {
|
|
150
|
+
const { data } = await query.graph({ entity: "order", fields: ORDER_FIELDS, filters: { id } });
|
|
151
|
+
return data[0];
|
|
152
|
+
}
|
|
153
|
+
async function orderPlacedSubscriber({ event, container }) {
|
|
154
|
+
await failOpen(container, "order.placed", async (query, storewatch) => {
|
|
155
|
+
const order = await fetchOrder(query, event.data.id);
|
|
156
|
+
if (!order) return;
|
|
157
|
+
storewatch.track("order_completed", orderCompletedEvent(order));
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
var orderPlacedConfig = { event: "order.placed", context: { subscriberId: "storewatch-order-placed" } };
|
|
161
|
+
async function orderCanceledSubscriber({ event, container }) {
|
|
162
|
+
await failOpen(container, "order.canceled", async (query, storewatch) => {
|
|
163
|
+
const order = await fetchOrder(query, event.data.id);
|
|
164
|
+
if (!order) return;
|
|
165
|
+
storewatch.track("order_cancelled", {
|
|
166
|
+
...sessionFields(order),
|
|
167
|
+
eventId: (0, import_node.eventIdFor)("order_cancelled", order.id),
|
|
168
|
+
properties: { orderId: order.id }
|
|
169
|
+
});
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
var orderCanceledConfig = { event: "order.canceled", context: { subscriberId: "storewatch-order-canceled" } };
|
|
173
|
+
async function paymentRefundedSubscriber({ event, container }) {
|
|
174
|
+
await failOpen(container, "payment.refunded", async (query, storewatch) => {
|
|
175
|
+
const { data: payments } = await query.graph({
|
|
176
|
+
entity: "payment",
|
|
177
|
+
fields: ["id", "currency_code", "payment_collection_id", "refunds.id", "refunds.amount", "refunds.created_at"],
|
|
178
|
+
filters: { id: event.data.id }
|
|
179
|
+
});
|
|
180
|
+
const payment = payments[0];
|
|
181
|
+
if (!payment?.payment_collection_id || !payment.refunds?.length) return;
|
|
182
|
+
const { data: links } = await query.graph({
|
|
183
|
+
entity: "order_payment_collection",
|
|
184
|
+
fields: ["order_id"],
|
|
185
|
+
filters: { payment_collection_id: payment.payment_collection_id }
|
|
186
|
+
});
|
|
187
|
+
const orderId = links[0]?.order_id;
|
|
188
|
+
if (!orderId) return;
|
|
189
|
+
const order = await fetchOrder(query, orderId);
|
|
190
|
+
const currency = payment.currency_code.toUpperCase();
|
|
191
|
+
for (const refund of payment.refunds) {
|
|
192
|
+
storewatch.track("refund_created", {
|
|
193
|
+
...sessionFields(order ?? { id: orderId }),
|
|
194
|
+
eventId: (0, import_node.eventIdFor)("refund_created", refund.id),
|
|
195
|
+
...refund.created_at ? { timestamp: new Date(refund.created_at) } : {},
|
|
196
|
+
properties: { orderId, refundId: refund.id, amount: { amount: toMinor(refund.amount, currency), currency } }
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
var paymentRefundedConfig = { event: "payment.refunded", context: { subscriberId: "storewatch-payment-refunded" } };
|
|
202
|
+
function trackPaymentFailed(input) {
|
|
203
|
+
try {
|
|
204
|
+
getClient(void 0)?.track("payment_failed", {
|
|
205
|
+
...sessionFields(input.cart),
|
|
206
|
+
eventId: (0, import_node.eventIdFor)("payment_failed", input.failureId),
|
|
207
|
+
properties: {
|
|
208
|
+
checkoutId: input.cart.id,
|
|
209
|
+
...input.provider ? { provider: input.provider } : {},
|
|
210
|
+
...input.reason ? { reason: input.reason } : {},
|
|
211
|
+
...input.amount ? { amount: input.amount } : {}
|
|
212
|
+
}
|
|
213
|
+
});
|
|
214
|
+
} catch {
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
function resetStorewatchForTests() {
|
|
218
|
+
client = void 0;
|
|
219
|
+
warnedUnconfigured = false;
|
|
220
|
+
}
|
|
221
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
222
|
+
0 && (module.exports = {
|
|
223
|
+
METADATA_KEY,
|
|
224
|
+
ORDER_FIELDS,
|
|
225
|
+
configureStorewatch,
|
|
226
|
+
orderCanceledConfig,
|
|
227
|
+
orderCanceledSubscriber,
|
|
228
|
+
orderCompletedEvent,
|
|
229
|
+
orderPlacedConfig,
|
|
230
|
+
orderPlacedSubscriber,
|
|
231
|
+
paymentRefundedConfig,
|
|
232
|
+
paymentRefundedSubscriber,
|
|
233
|
+
resetStorewatchForTests,
|
|
234
|
+
sessionOf,
|
|
235
|
+
toMinor,
|
|
236
|
+
toNumber,
|
|
237
|
+
trackPaymentFailed
|
|
238
|
+
});
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Storewatch for Medusa v2. Your Medusa backend becomes the source of truth
|
|
3
|
+
* for revenue: placed orders, cancellations and refunds are sent from the
|
|
4
|
+
* server, tied to the shopper's live session through cart metadata.
|
|
5
|
+
*
|
|
6
|
+
* One subscriber file per event in your Medusa project (Medusa reads each
|
|
7
|
+
* file's default export and `config`):
|
|
8
|
+
*
|
|
9
|
+
* // src/subscribers/storewatch-order-placed.ts
|
|
10
|
+
* export { orderPlacedSubscriber as default, orderPlacedConfig as config } from "@storewatch/medusa";
|
|
11
|
+
*
|
|
12
|
+
* Configure with STOREWATCH_SECRET_KEY and STOREWATCH_ENDPOINT, or call
|
|
13
|
+
* `configureStorewatch()` once at startup. Without configuration the
|
|
14
|
+
* subscribers log once and do nothing. They never throw into Medusa.
|
|
15
|
+
*/
|
|
16
|
+
import { type Storewatch } from "@storewatch/node";
|
|
17
|
+
import { METADATA_KEY } from "./storefront.cjs";
|
|
18
|
+
type Container = {
|
|
19
|
+
resolve(key: string): unknown;
|
|
20
|
+
};
|
|
21
|
+
export type SubscriberArgs<T> = {
|
|
22
|
+
event: {
|
|
23
|
+
data: T;
|
|
24
|
+
name?: string;
|
|
25
|
+
};
|
|
26
|
+
container: Container;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Medusa returns amounts and quantities as numbers, numeric strings, `raw_*`
|
|
30
|
+
* objects (`{ value, precision }`) or BigNumber class instances (computed
|
|
31
|
+
* totals, order item quantities), in major units.
|
|
32
|
+
*/
|
|
33
|
+
type Amount = number | string | {
|
|
34
|
+
value: number | string;
|
|
35
|
+
} | {
|
|
36
|
+
numeric: number;
|
|
37
|
+
} | object | null | undefined;
|
|
38
|
+
/** Any of Medusa's amount shapes → a plain number (NaN when unreadable). */
|
|
39
|
+
export declare function toNumber(amount: Amount): number;
|
|
40
|
+
export type MedusaOrder = {
|
|
41
|
+
id: string;
|
|
42
|
+
display_id?: number | null;
|
|
43
|
+
currency_code: string;
|
|
44
|
+
total: Amount;
|
|
45
|
+
created_at?: string | Date | null;
|
|
46
|
+
customer_id?: string | null;
|
|
47
|
+
metadata?: Record<string, unknown> | null;
|
|
48
|
+
items?: {
|
|
49
|
+
id: string;
|
|
50
|
+
product_id?: string | null;
|
|
51
|
+
variant_id?: string | null;
|
|
52
|
+
title?: string | null;
|
|
53
|
+
product_title?: string | null;
|
|
54
|
+
quantity: Amount;
|
|
55
|
+
unit_price: Amount;
|
|
56
|
+
}[] | null;
|
|
57
|
+
};
|
|
58
|
+
export declare const ORDER_FIELDS: string[];
|
|
59
|
+
/** Medusa v2 amounts are major units ("1299.5"); Storewatch uses integer minor units. */
|
|
60
|
+
export declare function toMinor(amount: Amount, currency: string): number;
|
|
61
|
+
export { METADATA_KEY };
|
|
62
|
+
/**
|
|
63
|
+
* The shopper's Storewatch session, if the storefront put it on the cart
|
|
64
|
+
* (Medusa copies cart metadata to the order). Otherwise a stable per-order
|
|
65
|
+
* id: the order still counts as revenue, it just isn't tied to a visitor.
|
|
66
|
+
*/
|
|
67
|
+
export declare function sessionOf(order: Pick<MedusaOrder, "id" | "metadata">): {
|
|
68
|
+
sessionId: string;
|
|
69
|
+
anonymousId?: string;
|
|
70
|
+
linked: boolean;
|
|
71
|
+
};
|
|
72
|
+
export declare function orderCompletedEvent(order: MedusaOrder): {
|
|
73
|
+
sessionId: string;
|
|
74
|
+
anonymousId?: string;
|
|
75
|
+
customerId?: string;
|
|
76
|
+
eventId: string;
|
|
77
|
+
timestamp?: Date;
|
|
78
|
+
properties: {
|
|
79
|
+
orderId: string;
|
|
80
|
+
orderNumber?: string;
|
|
81
|
+
total: {
|
|
82
|
+
amount: number;
|
|
83
|
+
currency: string;
|
|
84
|
+
};
|
|
85
|
+
items: {
|
|
86
|
+
productId: string;
|
|
87
|
+
variantId?: string;
|
|
88
|
+
name?: string;
|
|
89
|
+
quantity: number;
|
|
90
|
+
price: {
|
|
91
|
+
amount: number;
|
|
92
|
+
currency: string;
|
|
93
|
+
};
|
|
94
|
+
}[];
|
|
95
|
+
};
|
|
96
|
+
};
|
|
97
|
+
/** Use your own client (e.g. with OpenTelemetry trace context). Call once at startup. */
|
|
98
|
+
export declare function configureStorewatch(storewatch: Storewatch): void;
|
|
99
|
+
export declare function orderPlacedSubscriber({ event, container }: SubscriberArgs<{
|
|
100
|
+
id: string;
|
|
101
|
+
}>): Promise<void>;
|
|
102
|
+
export declare const orderPlacedConfig: {
|
|
103
|
+
event: string;
|
|
104
|
+
context: {
|
|
105
|
+
subscriberId: string;
|
|
106
|
+
};
|
|
107
|
+
};
|
|
108
|
+
export declare function orderCanceledSubscriber({ event, container }: SubscriberArgs<{
|
|
109
|
+
id: string;
|
|
110
|
+
}>): Promise<void>;
|
|
111
|
+
export declare const orderCanceledConfig: {
|
|
112
|
+
event: string;
|
|
113
|
+
context: {
|
|
114
|
+
subscriberId: string;
|
|
115
|
+
};
|
|
116
|
+
};
|
|
117
|
+
/**
|
|
118
|
+
* `payment.refunded` carries the payment id. Every refund on the payment is
|
|
119
|
+
* sent with an id derived from the refund, so earlier ones dedupe at ingest.
|
|
120
|
+
*/
|
|
121
|
+
export declare function paymentRefundedSubscriber({ event, container }: SubscriberArgs<{
|
|
122
|
+
id: string;
|
|
123
|
+
}>): Promise<void>;
|
|
124
|
+
export declare const paymentRefundedConfig: {
|
|
125
|
+
event: string;
|
|
126
|
+
context: {
|
|
127
|
+
subscriberId: string;
|
|
128
|
+
};
|
|
129
|
+
};
|
|
130
|
+
/**
|
|
131
|
+
* Medusa has no event for a failed payment attempt. Call this where you see
|
|
132
|
+
* one (a payment webhook, a failed cart completion) so the live checkout
|
|
133
|
+
* health view shows it.
|
|
134
|
+
*/
|
|
135
|
+
export declare function trackPaymentFailed(input: {
|
|
136
|
+
/** The cart being paid for: its metadata links the failure to the shopper's session. */
|
|
137
|
+
cart: {
|
|
138
|
+
id: string;
|
|
139
|
+
metadata?: Record<string, unknown> | null;
|
|
140
|
+
};
|
|
141
|
+
provider?: string;
|
|
142
|
+
/** A provider error code (e.g. "card_declined"), never a free-text message: those can contain personal data. */
|
|
143
|
+
reason?: string;
|
|
144
|
+
amount?: {
|
|
145
|
+
amount: number;
|
|
146
|
+
currency: string;
|
|
147
|
+
};
|
|
148
|
+
/** Identifies this failure (e.g. the provider's event id) so a retried webhook counts once. */
|
|
149
|
+
failureId: string;
|
|
150
|
+
}): void;
|
|
151
|
+
/** For tests: forget the configured client. */
|
|
152
|
+
export declare function resetStorewatchForTests(): void;
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Storewatch for Medusa v2. Your Medusa backend becomes the source of truth
|
|
3
|
+
* for revenue: placed orders, cancellations and refunds are sent from the
|
|
4
|
+
* server, tied to the shopper's live session through cart metadata.
|
|
5
|
+
*
|
|
6
|
+
* One subscriber file per event in your Medusa project (Medusa reads each
|
|
7
|
+
* file's default export and `config`):
|
|
8
|
+
*
|
|
9
|
+
* // src/subscribers/storewatch-order-placed.ts
|
|
10
|
+
* export { orderPlacedSubscriber as default, orderPlacedConfig as config } from "@storewatch/medusa";
|
|
11
|
+
*
|
|
12
|
+
* Configure with STOREWATCH_SECRET_KEY and STOREWATCH_ENDPOINT, or call
|
|
13
|
+
* `configureStorewatch()` once at startup. Without configuration the
|
|
14
|
+
* subscribers log once and do nothing. They never throw into Medusa.
|
|
15
|
+
*/
|
|
16
|
+
import { type Storewatch } from "@storewatch/node";
|
|
17
|
+
import { METADATA_KEY } from "./storefront.js";
|
|
18
|
+
type Container = {
|
|
19
|
+
resolve(key: string): unknown;
|
|
20
|
+
};
|
|
21
|
+
export type SubscriberArgs<T> = {
|
|
22
|
+
event: {
|
|
23
|
+
data: T;
|
|
24
|
+
name?: string;
|
|
25
|
+
};
|
|
26
|
+
container: Container;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Medusa returns amounts and quantities as numbers, numeric strings, `raw_*`
|
|
30
|
+
* objects (`{ value, precision }`) or BigNumber class instances (computed
|
|
31
|
+
* totals, order item quantities), in major units.
|
|
32
|
+
*/
|
|
33
|
+
type Amount = number | string | {
|
|
34
|
+
value: number | string;
|
|
35
|
+
} | {
|
|
36
|
+
numeric: number;
|
|
37
|
+
} | object | null | undefined;
|
|
38
|
+
/** Any of Medusa's amount shapes → a plain number (NaN when unreadable). */
|
|
39
|
+
export declare function toNumber(amount: Amount): number;
|
|
40
|
+
export type MedusaOrder = {
|
|
41
|
+
id: string;
|
|
42
|
+
display_id?: number | null;
|
|
43
|
+
currency_code: string;
|
|
44
|
+
total: Amount;
|
|
45
|
+
created_at?: string | Date | null;
|
|
46
|
+
customer_id?: string | null;
|
|
47
|
+
metadata?: Record<string, unknown> | null;
|
|
48
|
+
items?: {
|
|
49
|
+
id: string;
|
|
50
|
+
product_id?: string | null;
|
|
51
|
+
variant_id?: string | null;
|
|
52
|
+
title?: string | null;
|
|
53
|
+
product_title?: string | null;
|
|
54
|
+
quantity: Amount;
|
|
55
|
+
unit_price: Amount;
|
|
56
|
+
}[] | null;
|
|
57
|
+
};
|
|
58
|
+
export declare const ORDER_FIELDS: string[];
|
|
59
|
+
/** Medusa v2 amounts are major units ("1299.5"); Storewatch uses integer minor units. */
|
|
60
|
+
export declare function toMinor(amount: Amount, currency: string): number;
|
|
61
|
+
export { METADATA_KEY };
|
|
62
|
+
/**
|
|
63
|
+
* The shopper's Storewatch session, if the storefront put it on the cart
|
|
64
|
+
* (Medusa copies cart metadata to the order). Otherwise a stable per-order
|
|
65
|
+
* id: the order still counts as revenue, it just isn't tied to a visitor.
|
|
66
|
+
*/
|
|
67
|
+
export declare function sessionOf(order: Pick<MedusaOrder, "id" | "metadata">): {
|
|
68
|
+
sessionId: string;
|
|
69
|
+
anonymousId?: string;
|
|
70
|
+
linked: boolean;
|
|
71
|
+
};
|
|
72
|
+
export declare function orderCompletedEvent(order: MedusaOrder): {
|
|
73
|
+
sessionId: string;
|
|
74
|
+
anonymousId?: string;
|
|
75
|
+
customerId?: string;
|
|
76
|
+
eventId: string;
|
|
77
|
+
timestamp?: Date;
|
|
78
|
+
properties: {
|
|
79
|
+
orderId: string;
|
|
80
|
+
orderNumber?: string;
|
|
81
|
+
total: {
|
|
82
|
+
amount: number;
|
|
83
|
+
currency: string;
|
|
84
|
+
};
|
|
85
|
+
items: {
|
|
86
|
+
productId: string;
|
|
87
|
+
variantId?: string;
|
|
88
|
+
name?: string;
|
|
89
|
+
quantity: number;
|
|
90
|
+
price: {
|
|
91
|
+
amount: number;
|
|
92
|
+
currency: string;
|
|
93
|
+
};
|
|
94
|
+
}[];
|
|
95
|
+
};
|
|
96
|
+
};
|
|
97
|
+
/** Use your own client (e.g. with OpenTelemetry trace context). Call once at startup. */
|
|
98
|
+
export declare function configureStorewatch(storewatch: Storewatch): void;
|
|
99
|
+
export declare function orderPlacedSubscriber({ event, container }: SubscriberArgs<{
|
|
100
|
+
id: string;
|
|
101
|
+
}>): Promise<void>;
|
|
102
|
+
export declare const orderPlacedConfig: {
|
|
103
|
+
event: string;
|
|
104
|
+
context: {
|
|
105
|
+
subscriberId: string;
|
|
106
|
+
};
|
|
107
|
+
};
|
|
108
|
+
export declare function orderCanceledSubscriber({ event, container }: SubscriberArgs<{
|
|
109
|
+
id: string;
|
|
110
|
+
}>): Promise<void>;
|
|
111
|
+
export declare const orderCanceledConfig: {
|
|
112
|
+
event: string;
|
|
113
|
+
context: {
|
|
114
|
+
subscriberId: string;
|
|
115
|
+
};
|
|
116
|
+
};
|
|
117
|
+
/**
|
|
118
|
+
* `payment.refunded` carries the payment id. Every refund on the payment is
|
|
119
|
+
* sent with an id derived from the refund, so earlier ones dedupe at ingest.
|
|
120
|
+
*/
|
|
121
|
+
export declare function paymentRefundedSubscriber({ event, container }: SubscriberArgs<{
|
|
122
|
+
id: string;
|
|
123
|
+
}>): Promise<void>;
|
|
124
|
+
export declare const paymentRefundedConfig: {
|
|
125
|
+
event: string;
|
|
126
|
+
context: {
|
|
127
|
+
subscriberId: string;
|
|
128
|
+
};
|
|
129
|
+
};
|
|
130
|
+
/**
|
|
131
|
+
* Medusa has no event for a failed payment attempt. Call this where you see
|
|
132
|
+
* one (a payment webhook, a failed cart completion) so the live checkout
|
|
133
|
+
* health view shows it.
|
|
134
|
+
*/
|
|
135
|
+
export declare function trackPaymentFailed(input: {
|
|
136
|
+
/** The cart being paid for: its metadata links the failure to the shopper's session. */
|
|
137
|
+
cart: {
|
|
138
|
+
id: string;
|
|
139
|
+
metadata?: Record<string, unknown> | null;
|
|
140
|
+
};
|
|
141
|
+
provider?: string;
|
|
142
|
+
/** A provider error code (e.g. "card_declined"), never a free-text message: those can contain personal data. */
|
|
143
|
+
reason?: string;
|
|
144
|
+
amount?: {
|
|
145
|
+
amount: number;
|
|
146
|
+
currency: string;
|
|
147
|
+
};
|
|
148
|
+
/** Identifies this failure (e.g. the provider's event id) so a retried webhook counts once. */
|
|
149
|
+
failureId: string;
|
|
150
|
+
}): void;
|
|
151
|
+
/** For tests: forget the configured client. */
|
|
152
|
+
export declare function resetStorewatchForTests(): void;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import {
|
|
2
|
+
METADATA_KEY
|
|
3
|
+
} from "./chunk-DQHAPSCU.js";
|
|
4
|
+
|
|
5
|
+
// src/index.ts
|
|
6
|
+
import { createStorewatch, eventIdFor } from "@storewatch/node";
|
|
7
|
+
import { currencyExponent, LIMITS } from "@storewatch/schema/constants";
|
|
8
|
+
function toNumber(amount) {
|
|
9
|
+
if (amount === null || amount === void 0) return 0;
|
|
10
|
+
if (typeof amount === "number") return amount;
|
|
11
|
+
if (typeof amount === "string") return Number(amount);
|
|
12
|
+
const a = amount;
|
|
13
|
+
if (typeof a.numeric === "number") return a.numeric;
|
|
14
|
+
if (a.value !== void 0) return Number(a.value);
|
|
15
|
+
if (typeof a.toJSON === "function") return Number(a.toJSON());
|
|
16
|
+
return Number(String(amount));
|
|
17
|
+
}
|
|
18
|
+
var ORDER_FIELDS = [
|
|
19
|
+
"id",
|
|
20
|
+
"display_id",
|
|
21
|
+
"currency_code",
|
|
22
|
+
"total",
|
|
23
|
+
"created_at",
|
|
24
|
+
"customer_id",
|
|
25
|
+
"metadata",
|
|
26
|
+
"items.id",
|
|
27
|
+
"items.product_id",
|
|
28
|
+
"items.variant_id",
|
|
29
|
+
"items.title",
|
|
30
|
+
"items.product_title",
|
|
31
|
+
"items.quantity",
|
|
32
|
+
"items.unit_price"
|
|
33
|
+
];
|
|
34
|
+
function toMinor(amount, currency) {
|
|
35
|
+
const major = toNumber(amount);
|
|
36
|
+
if (!Number.isFinite(major)) return 0;
|
|
37
|
+
return Math.round(major * 10 ** currencyExponent(currency));
|
|
38
|
+
}
|
|
39
|
+
function sessionOf(order) {
|
|
40
|
+
const meta = order.metadata?.[METADATA_KEY];
|
|
41
|
+
if (meta && typeof meta === "object") {
|
|
42
|
+
const { sessionId, anonymousId } = meta;
|
|
43
|
+
if (typeof sessionId === "string" && sessionId.length > 0 && sessionId.length <= LIMITS.sessionIdMaxLength) {
|
|
44
|
+
return { sessionId, ...typeof anonymousId === "string" && anonymousId ? { anonymousId } : {}, linked: true };
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return { sessionId: `srv_${order.id}`.slice(0, LIMITS.sessionIdMaxLength), linked: false };
|
|
48
|
+
}
|
|
49
|
+
function sessionFields(order) {
|
|
50
|
+
const { linked: _linked, ...fields } = sessionOf(order);
|
|
51
|
+
return fields;
|
|
52
|
+
}
|
|
53
|
+
function orderCompletedEvent(order) {
|
|
54
|
+
const currency = order.currency_code.toUpperCase();
|
|
55
|
+
const money = (amount) => ({ amount: toMinor(amount, currency), currency });
|
|
56
|
+
return {
|
|
57
|
+
...sessionFields(order),
|
|
58
|
+
...order.customer_id ? { customerId: order.customer_id } : {},
|
|
59
|
+
eventId: eventIdFor("order_completed", order.id),
|
|
60
|
+
...order.created_at ? { timestamp: new Date(order.created_at) } : {},
|
|
61
|
+
properties: {
|
|
62
|
+
orderId: order.id,
|
|
63
|
+
...order.display_id != null ? { orderNumber: String(order.display_id) } : {},
|
|
64
|
+
total: money(order.total),
|
|
65
|
+
items: (order.items ?? []).slice(0, LIMITS.orderMaxItems).map((item) => ({
|
|
66
|
+
productId: item.product_id ?? item.id,
|
|
67
|
+
...item.variant_id ? { variantId: item.variant_id } : {},
|
|
68
|
+
...item.product_title || item.title ? { name: String(item.product_title || item.title).slice(0, 200) } : {},
|
|
69
|
+
quantity: Math.max(1, Math.round(toNumber(item.quantity) || 1)),
|
|
70
|
+
price: money(item.unit_price)
|
|
71
|
+
}))
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
var client;
|
|
76
|
+
var warnedUnconfigured = false;
|
|
77
|
+
function configureStorewatch(storewatch) {
|
|
78
|
+
client = storewatch;
|
|
79
|
+
}
|
|
80
|
+
function getClient(logger) {
|
|
81
|
+
if (client !== void 0) return client;
|
|
82
|
+
const secretKey = process.env.STOREWATCH_SECRET_KEY;
|
|
83
|
+
const endpoint = process.env.STOREWATCH_ENDPOINT;
|
|
84
|
+
if (!secretKey || !endpoint) {
|
|
85
|
+
if (!warnedUnconfigured) logger?.warn("[storewatch] STOREWATCH_SECRET_KEY / STOREWATCH_ENDPOINT not set; Medusa events are not sent.");
|
|
86
|
+
warnedUnconfigured = true;
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
client = createStorewatch({ secretKey, endpoint, onError: (e) => logger?.warn(`[storewatch] ${e.message}`) });
|
|
90
|
+
return client;
|
|
91
|
+
}
|
|
92
|
+
var resolveSafe = (container, key) => {
|
|
93
|
+
try {
|
|
94
|
+
return container.resolve(key);
|
|
95
|
+
} catch {
|
|
96
|
+
return void 0;
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
async function failOpen(container, label, run) {
|
|
100
|
+
const logger = resolveSafe(container, "logger");
|
|
101
|
+
try {
|
|
102
|
+
const storewatch = getClient(logger);
|
|
103
|
+
const query = resolveSafe(container, "query");
|
|
104
|
+
if (!storewatch || !query) return;
|
|
105
|
+
await run(query, storewatch);
|
|
106
|
+
} catch (error) {
|
|
107
|
+
logger?.warn(`[storewatch] ${label} failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
async function fetchOrder(query, id) {
|
|
111
|
+
const { data } = await query.graph({ entity: "order", fields: ORDER_FIELDS, filters: { id } });
|
|
112
|
+
return data[0];
|
|
113
|
+
}
|
|
114
|
+
async function orderPlacedSubscriber({ event, container }) {
|
|
115
|
+
await failOpen(container, "order.placed", async (query, storewatch) => {
|
|
116
|
+
const order = await fetchOrder(query, event.data.id);
|
|
117
|
+
if (!order) return;
|
|
118
|
+
storewatch.track("order_completed", orderCompletedEvent(order));
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
var orderPlacedConfig = { event: "order.placed", context: { subscriberId: "storewatch-order-placed" } };
|
|
122
|
+
async function orderCanceledSubscriber({ event, container }) {
|
|
123
|
+
await failOpen(container, "order.canceled", async (query, storewatch) => {
|
|
124
|
+
const order = await fetchOrder(query, event.data.id);
|
|
125
|
+
if (!order) return;
|
|
126
|
+
storewatch.track("order_cancelled", {
|
|
127
|
+
...sessionFields(order),
|
|
128
|
+
eventId: eventIdFor("order_cancelled", order.id),
|
|
129
|
+
properties: { orderId: order.id }
|
|
130
|
+
});
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
var orderCanceledConfig = { event: "order.canceled", context: { subscriberId: "storewatch-order-canceled" } };
|
|
134
|
+
async function paymentRefundedSubscriber({ event, container }) {
|
|
135
|
+
await failOpen(container, "payment.refunded", async (query, storewatch) => {
|
|
136
|
+
const { data: payments } = await query.graph({
|
|
137
|
+
entity: "payment",
|
|
138
|
+
fields: ["id", "currency_code", "payment_collection_id", "refunds.id", "refunds.amount", "refunds.created_at"],
|
|
139
|
+
filters: { id: event.data.id }
|
|
140
|
+
});
|
|
141
|
+
const payment = payments[0];
|
|
142
|
+
if (!payment?.payment_collection_id || !payment.refunds?.length) return;
|
|
143
|
+
const { data: links } = await query.graph({
|
|
144
|
+
entity: "order_payment_collection",
|
|
145
|
+
fields: ["order_id"],
|
|
146
|
+
filters: { payment_collection_id: payment.payment_collection_id }
|
|
147
|
+
});
|
|
148
|
+
const orderId = links[0]?.order_id;
|
|
149
|
+
if (!orderId) return;
|
|
150
|
+
const order = await fetchOrder(query, orderId);
|
|
151
|
+
const currency = payment.currency_code.toUpperCase();
|
|
152
|
+
for (const refund of payment.refunds) {
|
|
153
|
+
storewatch.track("refund_created", {
|
|
154
|
+
...sessionFields(order ?? { id: orderId }),
|
|
155
|
+
eventId: eventIdFor("refund_created", refund.id),
|
|
156
|
+
...refund.created_at ? { timestamp: new Date(refund.created_at) } : {},
|
|
157
|
+
properties: { orderId, refundId: refund.id, amount: { amount: toMinor(refund.amount, currency), currency } }
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
var paymentRefundedConfig = { event: "payment.refunded", context: { subscriberId: "storewatch-payment-refunded" } };
|
|
163
|
+
function trackPaymentFailed(input) {
|
|
164
|
+
try {
|
|
165
|
+
getClient(void 0)?.track("payment_failed", {
|
|
166
|
+
...sessionFields(input.cart),
|
|
167
|
+
eventId: eventIdFor("payment_failed", input.failureId),
|
|
168
|
+
properties: {
|
|
169
|
+
checkoutId: input.cart.id,
|
|
170
|
+
...input.provider ? { provider: input.provider } : {},
|
|
171
|
+
...input.reason ? { reason: input.reason } : {},
|
|
172
|
+
...input.amount ? { amount: input.amount } : {}
|
|
173
|
+
}
|
|
174
|
+
});
|
|
175
|
+
} catch {
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
function resetStorewatchForTests() {
|
|
179
|
+
client = void 0;
|
|
180
|
+
warnedUnconfigured = false;
|
|
181
|
+
}
|
|
182
|
+
export {
|
|
183
|
+
METADATA_KEY,
|
|
184
|
+
ORDER_FIELDS,
|
|
185
|
+
configureStorewatch,
|
|
186
|
+
orderCanceledConfig,
|
|
187
|
+
orderCanceledSubscriber,
|
|
188
|
+
orderCompletedEvent,
|
|
189
|
+
orderPlacedConfig,
|
|
190
|
+
orderPlacedSubscriber,
|
|
191
|
+
paymentRefundedConfig,
|
|
192
|
+
paymentRefundedSubscriber,
|
|
193
|
+
resetStorewatchForTests,
|
|
194
|
+
sessionOf,
|
|
195
|
+
toMinor,
|
|
196
|
+
toNumber,
|
|
197
|
+
trackPaymentFailed
|
|
198
|
+
};
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/storefront.ts
|
|
21
|
+
var storefront_exports = {};
|
|
22
|
+
__export(storefront_exports, {
|
|
23
|
+
METADATA_KEY: () => METADATA_KEY,
|
|
24
|
+
cartHasSession: () => cartHasSession,
|
|
25
|
+
storewatchCartMetadata: () => storewatchCartMetadata
|
|
26
|
+
});
|
|
27
|
+
module.exports = __toCommonJS(storefront_exports);
|
|
28
|
+
var METADATA_KEY = "storewatch";
|
|
29
|
+
function storewatchCartMetadata(ids) {
|
|
30
|
+
return { [METADATA_KEY]: { sessionId: ids.sessionId, ...ids.anonymousId ? { anonymousId: ids.anonymousId } : {} } };
|
|
31
|
+
}
|
|
32
|
+
function cartHasSession(metadata, sessionId) {
|
|
33
|
+
const current = metadata?.[METADATA_KEY];
|
|
34
|
+
return typeof current === "object" && current !== null && current.sessionId === sessionId;
|
|
35
|
+
}
|
|
36
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
37
|
+
0 && (module.exports = {
|
|
38
|
+
METADATA_KEY,
|
|
39
|
+
cartHasSession,
|
|
40
|
+
storewatchCartMetadata
|
|
41
|
+
});
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Storefront side of the Medusa integration: put the shopper's Storewatch
|
|
3
|
+
* session on the cart, so the order Medusa creates from it carries the link
|
|
4
|
+
* back to their live journey. Browser-safe, no dependencies.
|
|
5
|
+
*
|
|
6
|
+
* import { getStorewatch } from "@storewatch/browser";
|
|
7
|
+
* import { storewatchCartMetadata } from "@storewatch/medusa/storefront";
|
|
8
|
+
*
|
|
9
|
+
* await sdk.store.cart.update(cart.id, {
|
|
10
|
+
* metadata: { ...cart.metadata, ...storewatchCartMetadata(getStorewatch().ids()) },
|
|
11
|
+
* });
|
|
12
|
+
*
|
|
13
|
+
* Spread the cart's existing metadata in, so other keys (attribution,
|
|
14
|
+
* consent) are kept.
|
|
15
|
+
*/
|
|
16
|
+
export declare const METADATA_KEY = "storewatch";
|
|
17
|
+
export type StorewatchCartMetadata = {
|
|
18
|
+
[METADATA_KEY]: {
|
|
19
|
+
sessionId: string;
|
|
20
|
+
anonymousId?: string;
|
|
21
|
+
};
|
|
22
|
+
};
|
|
23
|
+
export declare function storewatchCartMetadata(ids: {
|
|
24
|
+
sessionId: string;
|
|
25
|
+
anonymousId: string | null;
|
|
26
|
+
}): StorewatchCartMetadata;
|
|
27
|
+
/** True when the cart already points at this session (skip the update). */
|
|
28
|
+
export declare function cartHasSession(metadata: Record<string, unknown> | null | undefined, sessionId: string): boolean;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Storefront side of the Medusa integration: put the shopper's Storewatch
|
|
3
|
+
* session on the cart, so the order Medusa creates from it carries the link
|
|
4
|
+
* back to their live journey. Browser-safe, no dependencies.
|
|
5
|
+
*
|
|
6
|
+
* import { getStorewatch } from "@storewatch/browser";
|
|
7
|
+
* import { storewatchCartMetadata } from "@storewatch/medusa/storefront";
|
|
8
|
+
*
|
|
9
|
+
* await sdk.store.cart.update(cart.id, {
|
|
10
|
+
* metadata: { ...cart.metadata, ...storewatchCartMetadata(getStorewatch().ids()) },
|
|
11
|
+
* });
|
|
12
|
+
*
|
|
13
|
+
* Spread the cart's existing metadata in, so other keys (attribution,
|
|
14
|
+
* consent) are kept.
|
|
15
|
+
*/
|
|
16
|
+
export declare const METADATA_KEY = "storewatch";
|
|
17
|
+
export type StorewatchCartMetadata = {
|
|
18
|
+
[METADATA_KEY]: {
|
|
19
|
+
sessionId: string;
|
|
20
|
+
anonymousId?: string;
|
|
21
|
+
};
|
|
22
|
+
};
|
|
23
|
+
export declare function storewatchCartMetadata(ids: {
|
|
24
|
+
sessionId: string;
|
|
25
|
+
anonymousId: string | null;
|
|
26
|
+
}): StorewatchCartMetadata;
|
|
27
|
+
/** True when the cart already points at this session (skip the update). */
|
|
28
|
+
export declare function cartHasSession(metadata: Record<string, unknown> | null | undefined, sessionId: string): boolean;
|
package/package.json
CHANGED
|
@@ -1,6 +1,54 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@storewatch/medusa",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Storewatch for Medusa v2: server-confirmed orders, cancellations and refunds, tied to the shopper's live session.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"import": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"default": "./dist/index.js"
|
|
13
|
+
},
|
|
14
|
+
"require": {
|
|
15
|
+
"types": "./dist/index.d.cts",
|
|
16
|
+
"default": "./dist/index.cjs"
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
"./storefront": {
|
|
20
|
+
"import": {
|
|
21
|
+
"types": "./dist/storefront.d.ts",
|
|
22
|
+
"default": "./dist/storefront.js"
|
|
23
|
+
},
|
|
24
|
+
"require": {
|
|
25
|
+
"types": "./dist/storefront.d.cts",
|
|
26
|
+
"default": "./dist/storefront.cjs"
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"publishConfig": {
|
|
31
|
+
"access": "public"
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"dist"
|
|
35
|
+
],
|
|
36
|
+
"dependencies": {
|
|
37
|
+
"@storewatch/node": "0.2.0",
|
|
38
|
+
"@storewatch/schema": "0.2.0"
|
|
39
|
+
},
|
|
40
|
+
"devDependencies": {
|
|
41
|
+
"tsup": "^9.0.0",
|
|
42
|
+
"@storewatch/config": "0.0.0"
|
|
43
|
+
},
|
|
44
|
+
"keywords": [
|
|
45
|
+
"storewatch",
|
|
46
|
+
"analytics",
|
|
47
|
+
"ecommerce"
|
|
48
|
+
],
|
|
49
|
+
"scripts": {
|
|
50
|
+
"build": "rm -rf dist && tsup && tsc -p tsconfig.build.json && node ../../scripts/dual-dts.mjs dist",
|
|
51
|
+
"typecheck": "tsc -p .",
|
|
52
|
+
"test": "vitest run"
|
|
53
|
+
}
|
|
6
54
|
}
|