@thebes/cadmea-plugin-printful 1.0.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 +46 -0
- package/dist/index.cjs +150 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +26 -0
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +149 -0
- package/dist/index.js.map +1 -0
- package/package.json +55 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 BowenLabs
|
|
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
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# @thebes/cadmea-plugin-printful
|
|
2
|
+
|
|
3
|
+
Printful `FulfillmentProvider` for [`@thebes/cadmea-plugin-ecommerce`](../cadmea-plugin-ecommerce) — raw `fetch()` + `crypto.subtle`, no Printful Node SDK.
|
|
4
|
+
|
|
5
|
+
## Usage
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { createWebhookHandler } from "@thebes/cadmea-plugin-ecommerce";
|
|
9
|
+
import { createPrintfulProvider } from "@thebes/cadmea-plugin-printful";
|
|
10
|
+
import { createFulfillmentOrder } from "@thebes/cadmea-plugin-ecommerce";
|
|
11
|
+
|
|
12
|
+
const printful = createPrintfulProvider({ apiKey: env.PRINTFUL_API_KEY });
|
|
13
|
+
|
|
14
|
+
app.post(
|
|
15
|
+
"/api/webhooks/stripe",
|
|
16
|
+
createWebhookHandler({
|
|
17
|
+
provider: stripeProvider,
|
|
18
|
+
orders,
|
|
19
|
+
payments,
|
|
20
|
+
webhookEvents,
|
|
21
|
+
secret: env.STRIPE_WEBHOOK_SECRET,
|
|
22
|
+
context,
|
|
23
|
+
onOrderPaid: (order) =>
|
|
24
|
+
createFulfillmentOrder(order, { provider: printful, orders, context }),
|
|
25
|
+
}),
|
|
26
|
+
);
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
import { createFulfillmentWebhookHandler } from "@thebes/cadmea-plugin-ecommerce";
|
|
31
|
+
|
|
32
|
+
app.post(
|
|
33
|
+
"/api/webhooks/printful",
|
|
34
|
+
createFulfillmentWebhookHandler({
|
|
35
|
+
provider: printful,
|
|
36
|
+
orders,
|
|
37
|
+
webhookEvents,
|
|
38
|
+
secret: env.PRINTFUL_WEBHOOKS_SECRET,
|
|
39
|
+
context,
|
|
40
|
+
}),
|
|
41
|
+
);
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## `catalogRef` format
|
|
45
|
+
|
|
46
|
+
A Printful order line needs both a catalog variant id and a file id; `FulfillmentLineItem.catalogRef` is a single opaque string, so this provider expects it in `"{catalogVariantId}:{fileId}"` form — set directly on each `products` variant's `catalogRef` field once the print file has been uploaded to Printful. See `provider.ts`'s top-of-file note for the reasoning and what a future real catalog-sync collection would replace this with.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
//#region src/provider.ts
|
|
3
|
+
const BASE_URL = "https://api.printful.com";
|
|
4
|
+
var PrintfulApiError = class extends Error {
|
|
5
|
+
status;
|
|
6
|
+
body;
|
|
7
|
+
constructor(message, status, body) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.status = status;
|
|
10
|
+
this.body = body;
|
|
11
|
+
this.name = "PrintfulApiError";
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
async function printfulFetch(config, path, init) {
|
|
15
|
+
const response = await fetch(`${BASE_URL}${path}`, {
|
|
16
|
+
...init,
|
|
17
|
+
headers: {
|
|
18
|
+
Authorization: `Bearer ${config.apiKey}`,
|
|
19
|
+
"Content-Type": "application/json",
|
|
20
|
+
...init?.headers
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
const text = await response.text();
|
|
24
|
+
const parsed = text ? JSON.parse(text) : {};
|
|
25
|
+
if (!response.ok) throw new PrintfulApiError(`Printful API request to "${path}" failed with status ${response.status}`, response.status, parsed);
|
|
26
|
+
return parsed;
|
|
27
|
+
}
|
|
28
|
+
/** Splits a `"{catalogVariantId}:{fileId}"` catalogRef — see provider.ts's top-of-file design note. */
|
|
29
|
+
function parseCatalogRef(catalogRef) {
|
|
30
|
+
const [variantPart, filePart] = catalogRef.split(":");
|
|
31
|
+
const catalogVariantId = Number(variantPart);
|
|
32
|
+
const fileId = Number(filePart);
|
|
33
|
+
if (!Number.isFinite(catalogVariantId) || !Number.isFinite(fileId)) throw new Error(`Printful catalogRef "${catalogRef}" must be in "{catalogVariantId}:{fileId}" form`);
|
|
34
|
+
return {
|
|
35
|
+
catalogVariantId,
|
|
36
|
+
fileId
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
async function createFulfillmentOrder(config, request) {
|
|
40
|
+
const orderItems = request.lineItems.map((item) => {
|
|
41
|
+
const { catalogVariantId, fileId } = parseCatalogRef(item.catalogRef);
|
|
42
|
+
return {
|
|
43
|
+
source: "catalog",
|
|
44
|
+
catalog_variant_id: catalogVariantId,
|
|
45
|
+
quantity: item.quantity,
|
|
46
|
+
placements: [{
|
|
47
|
+
placement: "default",
|
|
48
|
+
technique: "digital",
|
|
49
|
+
layers: [{
|
|
50
|
+
type: "file",
|
|
51
|
+
id: fileId
|
|
52
|
+
}]
|
|
53
|
+
}]
|
|
54
|
+
};
|
|
55
|
+
});
|
|
56
|
+
if (!orderItems.length) throw new Error(`Fulfillment order for orderId ${request.orderId} has no valid line items`);
|
|
57
|
+
const address = request.shippingAddress;
|
|
58
|
+
const order = (await printfulFetch(config, "/orders", {
|
|
59
|
+
method: "POST",
|
|
60
|
+
body: JSON.stringify({
|
|
61
|
+
external_id: `cadmea-order-${request.orderId}`,
|
|
62
|
+
recipient: {
|
|
63
|
+
name: [address.firstName, address.lastName].filter(Boolean).join(" "),
|
|
64
|
+
address1: address.address1 ?? "",
|
|
65
|
+
address2: address.address2,
|
|
66
|
+
city: address.city ?? "",
|
|
67
|
+
state_code: address.state ?? "",
|
|
68
|
+
country_code: address.country ?? "US",
|
|
69
|
+
zip: address.zip ?? "",
|
|
70
|
+
phone: address.phone,
|
|
71
|
+
email: request.customerEmail
|
|
72
|
+
},
|
|
73
|
+
order_items: orderItems
|
|
74
|
+
})
|
|
75
|
+
})).data;
|
|
76
|
+
if (config.autoConfirm) await printfulFetch(config, `/orders/${order.id}/confirmation`, { method: "POST" }).catch((error) => {
|
|
77
|
+
console.error(`[cadmea-plugin-printful] order ${order.id} confirmation failed — manual confirmation required`, error);
|
|
78
|
+
});
|
|
79
|
+
return {
|
|
80
|
+
providerFulfillmentRef: String(order.id),
|
|
81
|
+
status: "pending"
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
async function hmacSha256Hex(message, keyHex) {
|
|
85
|
+
const keyBytes = new Uint8Array(keyHex.match(/.{1,2}/g)?.map((byte) => Number.parseInt(byte, 16)) ?? []);
|
|
86
|
+
const key = await crypto.subtle.importKey("raw", keyBytes, {
|
|
87
|
+
name: "HMAC",
|
|
88
|
+
hash: "SHA-256"
|
|
89
|
+
}, false, ["sign"]);
|
|
90
|
+
const signature = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(message));
|
|
91
|
+
return Array.from(new Uint8Array(signature), (b) => b.toString(16).padStart(2, "0")).join("");
|
|
92
|
+
}
|
|
93
|
+
function timingSafeEqual(a, b) {
|
|
94
|
+
if (a.length !== b.length) return false;
|
|
95
|
+
let mismatch = 0;
|
|
96
|
+
for (let i = 0; i < a.length; i++) mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
97
|
+
return mismatch === 0;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Verifies Printful's webhook signature: `x-pf-webhook-signature` is a hex
|
|
101
|
+
* HMAC-SHA256 of the raw body, keyed by the webhook config's secret (itself
|
|
102
|
+
* a hex string, decoded to bytes before use — Printful's own documented
|
|
103
|
+
* format, ported from the source app's Node `crypto.createHmac` version).
|
|
104
|
+
*/
|
|
105
|
+
async function verifyWebhookSignature({ rawBody, headers, secret }) {
|
|
106
|
+
const signature = headers.get("x-pf-webhook-signature");
|
|
107
|
+
if (!signature) return false;
|
|
108
|
+
return timingSafeEqual(await hmacSha256Hex(rawBody, secret), signature);
|
|
109
|
+
}
|
|
110
|
+
function parseWebhookEvent(rawBody) {
|
|
111
|
+
const payload = JSON.parse(rawBody);
|
|
112
|
+
const eventId = `${payload.data.order.id}:${payload.type}`;
|
|
113
|
+
if (payload.type === "shipment_sent" && payload.data.shipment) return {
|
|
114
|
+
eventId,
|
|
115
|
+
event: {
|
|
116
|
+
kind: "fulfillment.updated",
|
|
117
|
+
providerFulfillmentRef: String(payload.data.order.id),
|
|
118
|
+
status: "shipped",
|
|
119
|
+
trackingNumber: payload.data.shipment.tracking_number,
|
|
120
|
+
trackingCarrier: payload.data.shipment.service,
|
|
121
|
+
trackingUrl: payload.data.shipment.tracking_url
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
return {
|
|
125
|
+
eventId,
|
|
126
|
+
event: {
|
|
127
|
+
kind: "unhandled",
|
|
128
|
+
rawType: payload.type
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Creates a `FulfillmentProvider` backed by Printful's REST API — raw
|
|
134
|
+
* `fetch()` + `crypto.subtle`, no Printful Node SDK. Implements
|
|
135
|
+
* `createFulfillmentOrder`/`verifyWebhookSignature`/`parseWebhookEvent`,
|
|
136
|
+
* the full `FulfillmentProvider` surface (no optional capabilities are
|
|
137
|
+
* defined on that interface yet).
|
|
138
|
+
*/
|
|
139
|
+
function createPrintfulProvider(config) {
|
|
140
|
+
return {
|
|
141
|
+
name: "printful",
|
|
142
|
+
createFulfillmentOrder: (request) => createFulfillmentOrder(config, request),
|
|
143
|
+
verifyWebhookSignature,
|
|
144
|
+
parseWebhookEvent
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
//#endregion
|
|
148
|
+
exports.createPrintfulProvider = createPrintfulProvider;
|
|
149
|
+
|
|
150
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":[],"sources":["../src/provider.ts"],"sourcesContent":["// Copyright (c) 2026 BowenLabs. All rights reserved.\n// MIT licensed. See LICENSE in the repo root.\n//\n// Printful's REST API (v2 for orders, v1 for shipping rates) directly via\n// fetch() — never a Node-targeted Printful SDK. Webhook signature\n// verification uses crypto.subtle, mirroring\n// @thebes/cadmea-plugin-ecommerce-stripe's provider.ts.\n//\n// Design note on `catalogRef`: `FulfillmentLineItem.catalogRef` is one\n// opaque string per the FulfillmentProvider contract, but a Printful order\n// item needs two independent ids — a `catalog_variant_id` (which blank\n// product/size) and a `file id` (which artwork file gets printed on it).\n// The source app modeled this as two linked Payload collections\n// (PrintfulProducts + PrintAssets with a manual sync step uploading files to\n// Printful ahead of checkout). That collection pair has no Cadmea analog\n// yet and is out of scope for this port (see project plan's flagged\n// architecture changes). Instead, `catalogRef` here is the two ids joined\n// with a colon — `\"{catalogVariantId}:{fileId}\"` — set directly on each\n// `products` variant's `catalogRef` field in the Cadmea admin once a file is\n// uploaded to Printful by hand or via Printful's own dashboard. Revisit with\n// a real sync collection only once manual catalogRef entry is a measured\n// operational problem, not a theoretical one.\n\nimport type {\n FulfillmentOrderRequest,\n FulfillmentOrderResult,\n FulfillmentProvider,\n NormalizedFulfillmentWebhookEvent,\n} from \"@thebes/cadmea-plugin-ecommerce\";\n\nexport interface PrintfulProviderConfig {\n apiKey: string;\n /**\n * Printful orders are created as drafts by default — call\n * `/confirmation` to submit them for production. Default: false, same\n * \"explicit opt-in\" reasoning as the source app's\n * `PRINTFUL_CONFIRM_ORDERS` env var — a misconfigured store should fail\n * safe into \"drafts piling up for manual review,\" not \"real money spent\n * printing untested orders.\"\n */\n autoConfirm?: boolean;\n}\n\nconst BASE_URL = \"https://api.printful.com\";\n\nclass PrintfulApiError extends Error {\n constructor(\n message: string,\n public readonly status: number,\n public readonly body: unknown,\n ) {\n super(message);\n this.name = \"PrintfulApiError\";\n }\n}\n\nasync function printfulFetch(\n config: PrintfulProviderConfig,\n path: string,\n init?: RequestInit,\n): Promise<Record<string, unknown>> {\n const response = await fetch(`${BASE_URL}${path}`, {\n ...init,\n headers: {\n Authorization: `Bearer ${config.apiKey}`,\n \"Content-Type\": \"application/json\",\n ...init?.headers,\n },\n });\n const text = await response.text();\n const parsed = text ? JSON.parse(text) : {};\n if (!response.ok) {\n throw new PrintfulApiError(\n `Printful API request to \"${path}\" failed with status ${response.status}`,\n response.status,\n parsed,\n );\n }\n return parsed;\n}\n\n/** Splits a `\"{catalogVariantId}:{fileId}\"` catalogRef — see provider.ts's top-of-file design note. */\nfunction parseCatalogRef(catalogRef: string): {\n catalogVariantId: number;\n fileId: number;\n} {\n const [variantPart, filePart] = catalogRef.split(\":\");\n const catalogVariantId = Number(variantPart);\n const fileId = Number(filePart);\n if (!Number.isFinite(catalogVariantId) || !Number.isFinite(fileId)) {\n throw new Error(\n `Printful catalogRef \"${catalogRef}\" must be in \"{catalogVariantId}:{fileId}\" form`,\n );\n }\n return { catalogVariantId, fileId };\n}\n\ninterface PrintfulOrderItem {\n source: \"catalog\";\n catalog_variant_id: number;\n quantity: number;\n placements: Array<{\n placement: string;\n technique: string;\n layers: Array<{ type: \"file\"; id: number }>;\n }>;\n}\n\nasync function createFulfillmentOrder(\n config: PrintfulProviderConfig,\n request: FulfillmentOrderRequest,\n): Promise<FulfillmentOrderResult> {\n const orderItems: PrintfulOrderItem[] = request.lineItems.map((item) => {\n const { catalogVariantId, fileId } = parseCatalogRef(item.catalogRef);\n return {\n source: \"catalog\",\n catalog_variant_id: catalogVariantId,\n quantity: item.quantity,\n placements: [\n {\n placement: \"default\",\n technique: \"digital\",\n layers: [{ type: \"file\", id: fileId }],\n },\n ],\n };\n });\n\n if (!orderItems.length) {\n throw new Error(\n `Fulfillment order for orderId ${request.orderId} has no valid line items`,\n );\n }\n\n const address = request.shippingAddress;\n const response = await printfulFetch(config, \"/orders\", {\n method: \"POST\",\n body: JSON.stringify({\n external_id: `cadmea-order-${request.orderId}`,\n recipient: {\n name: [address.firstName, address.lastName].filter(Boolean).join(\" \"),\n address1: address.address1 ?? \"\",\n address2: address.address2,\n city: address.city ?? \"\",\n state_code: address.state ?? \"\",\n country_code: address.country ?? \"US\",\n zip: address.zip ?? \"\",\n phone: address.phone,\n email: request.customerEmail,\n },\n order_items: orderItems,\n }),\n });\n\n const order = response.data as { id: number; status: string };\n\n if (config.autoConfirm) {\n // A confirmation failure is logged, never thrown — the draft order\n // already exists at Printful and is visible for manual confirmation;\n // surfacing this as a fulfillment-creation failure would cause the\n // order-paid hook's caller to retry order creation and risk a\n // duplicate Printful order for the same Cadmea order.\n await printfulFetch(config, `/orders/${order.id}/confirmation`, {\n method: \"POST\",\n }).catch((error) => {\n console.error(\n `[cadmea-plugin-printful] order ${order.id} confirmation failed — manual confirmation required`,\n error,\n );\n });\n }\n\n return {\n providerFulfillmentRef: String(order.id),\n status: \"pending\",\n };\n}\n\nasync function hmacSha256Hex(message: string, keyHex: string): Promise<string> {\n const keyBytes = new Uint8Array(\n keyHex.match(/.{1,2}/g)?.map((byte) => Number.parseInt(byte, 16)) ?? [],\n );\n const key = await crypto.subtle.importKey(\n \"raw\",\n keyBytes,\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n const signature = await crypto.subtle.sign(\n \"HMAC\",\n key,\n new TextEncoder().encode(message),\n );\n return Array.from(new Uint8Array(signature), (b) =>\n b.toString(16).padStart(2, \"0\"),\n ).join(\"\");\n}\n\nfunction timingSafeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n let mismatch = 0;\n for (let i = 0; i < a.length; i++) {\n mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i);\n }\n return mismatch === 0;\n}\n\n/**\n * Verifies Printful's webhook signature: `x-pf-webhook-signature` is a hex\n * HMAC-SHA256 of the raw body, keyed by the webhook config's secret (itself\n * a hex string, decoded to bytes before use — Printful's own documented\n * format, ported from the source app's Node `crypto.createHmac` version).\n */\nasync function verifyWebhookSignature({\n rawBody,\n headers,\n secret,\n}: {\n rawBody: string;\n headers: Headers;\n secret: string;\n}): Promise<boolean> {\n const signature = headers.get(\"x-pf-webhook-signature\");\n if (!signature) return false;\n const expected = await hmacSha256Hex(rawBody, secret);\n return timingSafeEqual(expected, signature);\n}\n\ninterface ShipmentSentPayload {\n type: string;\n data: {\n order: { id: number };\n shipment?: {\n tracking_number: string;\n tracking_url: string;\n service: string;\n };\n };\n}\n\nfunction parseWebhookEvent(rawBody: string): {\n eventId: string;\n event: NormalizedFulfillmentWebhookEvent;\n} {\n const payload = JSON.parse(rawBody) as ShipmentSentPayload;\n // Printful doesn't include a stable webhook event id in its payload (no\n // `id` field, unlike Stripe) — the order id + type pair is unique enough\n // for this plugin's dedup purposes, since a real duplicate delivery\n // re-sends the exact same order/type combination.\n const eventId = `${payload.data.order.id}:${payload.type}`;\n\n if (payload.type === \"shipment_sent\" && payload.data.shipment) {\n return {\n eventId,\n event: {\n kind: \"fulfillment.updated\",\n providerFulfillmentRef: String(payload.data.order.id),\n status: \"shipped\",\n trackingNumber: payload.data.shipment.tracking_number,\n trackingCarrier: payload.data.shipment.service,\n trackingUrl: payload.data.shipment.tracking_url,\n },\n };\n }\n\n return { eventId, event: { kind: \"unhandled\", rawType: payload.type } };\n}\n\n/**\n * Creates a `FulfillmentProvider` backed by Printful's REST API — raw\n * `fetch()` + `crypto.subtle`, no Printful Node SDK. Implements\n * `createFulfillmentOrder`/`verifyWebhookSignature`/`parseWebhookEvent`,\n * the full `FulfillmentProvider` surface (no optional capabilities are\n * defined on that interface yet).\n */\nexport function createPrintfulProvider(\n config: PrintfulProviderConfig,\n): FulfillmentProvider {\n return {\n name: \"printful\",\n createFulfillmentOrder: (request) =>\n createFulfillmentOrder(config, request),\n verifyWebhookSignature,\n parseWebhookEvent,\n };\n}\n"],"mappings":";;AA2CA,MAAM,WAAW;AAEjB,IAAM,mBAAN,cAA+B,MAAM;CAGjB;CACA;CAHlB,YACE,SACA,QACA,MACA;EACA,MAAM,OAAO;EAHG,KAAA,SAAA;EACA,KAAA,OAAA;EAGhB,KAAK,OAAO;CACd;AACF;AAEA,eAAe,cACb,QACA,MACA,MACkC;CAClC,MAAM,WAAW,MAAM,MAAM,GAAG,WAAW,QAAQ;EACjD,GAAG;EACH,SAAS;GACP,eAAe,UAAU,OAAO;GAChC,gBAAgB;GAChB,GAAG,MAAM;EACX;CACF,CAAC;CACD,MAAM,OA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AS,MAAM,GACnB,SAAS;AAC5C;AAcA,SAAS,kBAAkB,SAGzB;CACA,MAAM,UAAU,KAAK,MAAM,OAAO;CAKlC,MAAM,UAAU,GAAG,QAAQ,KAAK,MAAM,GAAG,GAAG,QAAQ;CAEpD,IAAI,QAAQ,SAAS,mBAAmB,QAAQ,KAAK,UACnD,OAAO;EACL;EACA,OAAO;GACL,MAAM;GACN,wBAAwB,OAAO,QAAQ,KAAK,MAAM,EAAE;GACpD,QAAQ;GACR,gBAAgB,QAAQ,KAAK,SAAS;GACtC,iBAAiB,QAAQ,KAAK,SAAS;GACvC,aAAa,QAAQ,KAAK,SAAS;EACrC;CACF;CAGF,OAAO;EAAE;EAAS,OAAO;GAAE,MAAM;GAAa,SAAS,QAAQ;EAAK;CAAE;AACxE;;;;;;;;AASA,SAAgB,uBACd,QACqB;CACrB,OAAO;EACL,MAAM;EACN,yBAAyB,YACvB,uBAAuB,QAAQ,OAAO;EACxC;EACA;CACF;AACF"}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { FulfillmentProvider } from "@thebes/cadmea-plugin-ecommerce";
|
|
2
|
+
|
|
3
|
+
//#region src/provider.d.ts
|
|
4
|
+
interface PrintfulProviderConfig {
|
|
5
|
+
apiKey: string;
|
|
6
|
+
/**
|
|
7
|
+
* Printful orders are created as drafts by default — call
|
|
8
|
+
* `/confirmation` to submit them for production. Default: false, same
|
|
9
|
+
* "explicit opt-in" reasoning as the source app's
|
|
10
|
+
* `PRINTFUL_CONFIRM_ORDERS` env var — a misconfigured store should fail
|
|
11
|
+
* safe into "drafts piling up for manual review," not "real money spent
|
|
12
|
+
* printing untested orders."
|
|
13
|
+
*/
|
|
14
|
+
autoConfirm?: boolean;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Creates a `FulfillmentProvider` backed by Printful's REST API — raw
|
|
18
|
+
* `fetch()` + `crypto.subtle`, no Printful Node SDK. Implements
|
|
19
|
+
* `createFulfillmentOrder`/`verifyWebhookSignature`/`parseWebhookEvent`,
|
|
20
|
+
* the full `FulfillmentProvider` surface (no optional capabilities are
|
|
21
|
+
* defined on that interface yet).
|
|
22
|
+
*/
|
|
23
|
+
declare function createPrintfulProvider(config: PrintfulProviderConfig): FulfillmentProvider;
|
|
24
|
+
//#endregion
|
|
25
|
+
export { PrintfulProviderConfig, createPrintfulProvider };
|
|
26
|
+
//# sourceMappingURL=index.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../src/provider.ts"],"mappings":";;;UA8BiB,sBAAA;EACf,MAAA;EADe;;;;AAUJ;AA4Ob;;;EA5OE,WAAW;AAAA;;;;AA8OS;;;;iBAFN,sBAAA,CACd,MAAA,EAAQ,sBAAA,GACP,mBAAmB"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { FulfillmentProvider } from "@thebes/cadmea-plugin-ecommerce";
|
|
2
|
+
|
|
3
|
+
//#region src/provider.d.ts
|
|
4
|
+
interface PrintfulProviderConfig {
|
|
5
|
+
apiKey: string;
|
|
6
|
+
/**
|
|
7
|
+
* Printful orders are created as drafts by default — call
|
|
8
|
+
* `/confirmation` to submit them for production. Default: false, same
|
|
9
|
+
* "explicit opt-in" reasoning as the source app's
|
|
10
|
+
* `PRINTFUL_CONFIRM_ORDERS` env var — a misconfigured store should fail
|
|
11
|
+
* safe into "drafts piling up for manual review," not "real money spent
|
|
12
|
+
* printing untested orders."
|
|
13
|
+
*/
|
|
14
|
+
autoConfirm?: boolean;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Creates a `FulfillmentProvider` backed by Printful's REST API — raw
|
|
18
|
+
* `fetch()` + `crypto.subtle`, no Printful Node SDK. Implements
|
|
19
|
+
* `createFulfillmentOrder`/`verifyWebhookSignature`/`parseWebhookEvent`,
|
|
20
|
+
* the full `FulfillmentProvider` surface (no optional capabilities are
|
|
21
|
+
* defined on that interface yet).
|
|
22
|
+
*/
|
|
23
|
+
declare function createPrintfulProvider(config: PrintfulProviderConfig): FulfillmentProvider;
|
|
24
|
+
//#endregion
|
|
25
|
+
export { PrintfulProviderConfig, createPrintfulProvider };
|
|
26
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/provider.ts"],"mappings":";;;UA8BiB,sBAAA;EACf,MAAA;EADe;;;;AAUJ;AA4Ob;;;EA5OE,WAAW;AAAA;;;;AA8OS;;;;iBAFN,sBAAA,CACd,MAAA,EAAQ,sBAAA,GACP,mBAAmB"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
//#region src/provider.ts
|
|
2
|
+
const BASE_URL = "https://api.printful.com";
|
|
3
|
+
var PrintfulApiError = class extends Error {
|
|
4
|
+
status;
|
|
5
|
+
body;
|
|
6
|
+
constructor(message, status, body) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.status = status;
|
|
9
|
+
this.body = body;
|
|
10
|
+
this.name = "PrintfulApiError";
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
async function printfulFetch(config, path, init) {
|
|
14
|
+
const response = await fetch(`${BASE_URL}${path}`, {
|
|
15
|
+
...init,
|
|
16
|
+
headers: {
|
|
17
|
+
Authorization: `Bearer ${config.apiKey}`,
|
|
18
|
+
"Content-Type": "application/json",
|
|
19
|
+
...init?.headers
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
const text = await response.text();
|
|
23
|
+
const parsed = text ? JSON.parse(text) : {};
|
|
24
|
+
if (!response.ok) throw new PrintfulApiError(`Printful API request to "${path}" failed with status ${response.status}`, response.status, parsed);
|
|
25
|
+
return parsed;
|
|
26
|
+
}
|
|
27
|
+
/** Splits a `"{catalogVariantId}:{fileId}"` catalogRef — see provider.ts's top-of-file design note. */
|
|
28
|
+
function parseCatalogRef(catalogRef) {
|
|
29
|
+
const [variantPart, filePart] = catalogRef.split(":");
|
|
30
|
+
const catalogVariantId = Number(variantPart);
|
|
31
|
+
const fileId = Number(filePart);
|
|
32
|
+
if (!Number.isFinite(catalogVariantId) || !Number.isFinite(fileId)) throw new Error(`Printful catalogRef "${catalogRef}" must be in "{catalogVariantId}:{fileId}" form`);
|
|
33
|
+
return {
|
|
34
|
+
catalogVariantId,
|
|
35
|
+
fileId
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
async function createFulfillmentOrder(config, request) {
|
|
39
|
+
const orderItems = request.lineItems.map((item) => {
|
|
40
|
+
const { catalogVariantId, fileId } = parseCatalogRef(item.catalogRef);
|
|
41
|
+
return {
|
|
42
|
+
source: "catalog",
|
|
43
|
+
catalog_variant_id: catalogVariantId,
|
|
44
|
+
quantity: item.quantity,
|
|
45
|
+
placements: [{
|
|
46
|
+
placement: "default",
|
|
47
|
+
technique: "digital",
|
|
48
|
+
layers: [{
|
|
49
|
+
type: "file",
|
|
50
|
+
id: fileId
|
|
51
|
+
}]
|
|
52
|
+
}]
|
|
53
|
+
};
|
|
54
|
+
});
|
|
55
|
+
if (!orderItems.length) throw new Error(`Fulfillment order for orderId ${request.orderId} has no valid line items`);
|
|
56
|
+
const address = request.shippingAddress;
|
|
57
|
+
const order = (await printfulFetch(config, "/orders", {
|
|
58
|
+
method: "POST",
|
|
59
|
+
body: JSON.stringify({
|
|
60
|
+
external_id: `cadmea-order-${request.orderId}`,
|
|
61
|
+
recipient: {
|
|
62
|
+
name: [address.firstName, address.lastName].filter(Boolean).join(" "),
|
|
63
|
+
address1: address.address1 ?? "",
|
|
64
|
+
address2: address.address2,
|
|
65
|
+
city: address.city ?? "",
|
|
66
|
+
state_code: address.state ?? "",
|
|
67
|
+
country_code: address.country ?? "US",
|
|
68
|
+
zip: address.zip ?? "",
|
|
69
|
+
phone: address.phone,
|
|
70
|
+
email: request.customerEmail
|
|
71
|
+
},
|
|
72
|
+
order_items: orderItems
|
|
73
|
+
})
|
|
74
|
+
})).data;
|
|
75
|
+
if (config.autoConfirm) await printfulFetch(config, `/orders/${order.id}/confirmation`, { method: "POST" }).catch((error) => {
|
|
76
|
+
console.error(`[cadmea-plugin-printful] order ${order.id} confirmation failed — manual confirmation required`, error);
|
|
77
|
+
});
|
|
78
|
+
return {
|
|
79
|
+
providerFulfillmentRef: String(order.id),
|
|
80
|
+
status: "pending"
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
async function hmacSha256Hex(message, keyHex) {
|
|
84
|
+
const keyBytes = new Uint8Array(keyHex.match(/.{1,2}/g)?.map((byte) => Number.parseInt(byte, 16)) ?? []);
|
|
85
|
+
const key = await crypto.subtle.importKey("raw", keyBytes, {
|
|
86
|
+
name: "HMAC",
|
|
87
|
+
hash: "SHA-256"
|
|
88
|
+
}, false, ["sign"]);
|
|
89
|
+
const signature = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(message));
|
|
90
|
+
return Array.from(new Uint8Array(signature), (b) => b.toString(16).padStart(2, "0")).join("");
|
|
91
|
+
}
|
|
92
|
+
function timingSafeEqual(a, b) {
|
|
93
|
+
if (a.length !== b.length) return false;
|
|
94
|
+
let mismatch = 0;
|
|
95
|
+
for (let i = 0; i < a.length; i++) mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
96
|
+
return mismatch === 0;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Verifies Printful's webhook signature: `x-pf-webhook-signature` is a hex
|
|
100
|
+
* HMAC-SHA256 of the raw body, keyed by the webhook config's secret (itself
|
|
101
|
+
* a hex string, decoded to bytes before use — Printful's own documented
|
|
102
|
+
* format, ported from the source app's Node `crypto.createHmac` version).
|
|
103
|
+
*/
|
|
104
|
+
async function verifyWebhookSignature({ rawBody, headers, secret }) {
|
|
105
|
+
const signature = headers.get("x-pf-webhook-signature");
|
|
106
|
+
if (!signature) return false;
|
|
107
|
+
return timingSafeEqual(await hmacSha256Hex(rawBody, secret), signature);
|
|
108
|
+
}
|
|
109
|
+
function parseWebhookEvent(rawBody) {
|
|
110
|
+
const payload = JSON.parse(rawBody);
|
|
111
|
+
const eventId = `${payload.data.order.id}:${payload.type}`;
|
|
112
|
+
if (payload.type === "shipment_sent" && payload.data.shipment) return {
|
|
113
|
+
eventId,
|
|
114
|
+
event: {
|
|
115
|
+
kind: "fulfillment.updated",
|
|
116
|
+
providerFulfillmentRef: String(payload.data.order.id),
|
|
117
|
+
status: "shipped",
|
|
118
|
+
trackingNumber: payload.data.shipment.tracking_number,
|
|
119
|
+
trackingCarrier: payload.data.shipment.service,
|
|
120
|
+
trackingUrl: payload.data.shipment.tracking_url
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
return {
|
|
124
|
+
eventId,
|
|
125
|
+
event: {
|
|
126
|
+
kind: "unhandled",
|
|
127
|
+
rawType: payload.type
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Creates a `FulfillmentProvider` backed by Printful's REST API — raw
|
|
133
|
+
* `fetch()` + `crypto.subtle`, no Printful Node SDK. Implements
|
|
134
|
+
* `createFulfillmentOrder`/`verifyWebhookSignature`/`parseWebhookEvent`,
|
|
135
|
+
* the full `FulfillmentProvider` surface (no optional capabilities are
|
|
136
|
+
* defined on that interface yet).
|
|
137
|
+
*/
|
|
138
|
+
function createPrintfulProvider(config) {
|
|
139
|
+
return {
|
|
140
|
+
name: "printful",
|
|
141
|
+
createFulfillmentOrder: (request) => createFulfillmentOrder(config, request),
|
|
142
|
+
verifyWebhookSignature,
|
|
143
|
+
parseWebhookEvent
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
//#endregion
|
|
147
|
+
export { createPrintfulProvider };
|
|
148
|
+
|
|
149
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/provider.ts"],"sourcesContent":["// Copyright (c) 2026 BowenLabs. All rights reserved.\n// MIT licensed. See LICENSE in the repo root.\n//\n// Printful's REST API (v2 for orders, v1 for shipping rates) directly via\n// fetch() — never a Node-targeted Printful SDK. Webhook signature\n// verification uses crypto.subtle, mirroring\n// @thebes/cadmea-plugin-ecommerce-stripe's provider.ts.\n//\n// Design note on `catalogRef`: `FulfillmentLineItem.catalogRef` is one\n// opaque string per the FulfillmentProvider contract, but a Printful order\n// item needs two independent ids — a `catalog_variant_id` (which blank\n// product/size) and a `file id` (which artwork file gets printed on it).\n// The source app modeled this as two linked Payload collections\n// (PrintfulProducts + PrintAssets with a manual sync step uploading files to\n// Printful ahead of checkout). That collection pair has no Cadmea analog\n// yet and is out of scope for this port (see project plan's flagged\n// architecture changes). Instead, `catalogRef` here is the two ids joined\n// with a colon — `\"{catalogVariantId}:{fileId}\"` — set directly on each\n// `products` variant's `catalogRef` field in the Cadmea admin once a file is\n// uploaded to Printful by hand or via Printful's own dashboard. Revisit with\n// a real sync collection only once manual catalogRef entry is a measured\n// operational problem, not a theoretical one.\n\nimport type {\n FulfillmentOrderRequest,\n FulfillmentOrderResult,\n FulfillmentProvider,\n NormalizedFulfillmentWebhookEvent,\n} from \"@thebes/cadmea-plugin-ecommerce\";\n\nexport interface PrintfulProviderConfig {\n apiKey: string;\n /**\n * Printful orders are created as drafts by default — call\n * `/confirmation` to submit them for production. Default: false, same\n * \"explicit opt-in\" reasoning as the source app's\n * `PRINTFUL_CONFIRM_ORDERS` env var — a misconfigured store should fail\n * safe into \"drafts piling up for manual review,\" not \"real money spent\n * printing untested orders.\"\n */\n autoConfirm?: boolean;\n}\n\nconst BASE_URL = \"https://api.printful.com\";\n\nclass PrintfulApiError extends Error {\n constructor(\n message: string,\n public readonly status: number,\n public readonly body: unknown,\n ) {\n super(message);\n this.name = \"PrintfulApiError\";\n }\n}\n\nasync function printfulFetch(\n config: PrintfulProviderConfig,\n path: string,\n init?: RequestInit,\n): Promise<Record<string, unknown>> {\n const response = await fetch(`${BASE_URL}${path}`, {\n ...init,\n headers: {\n Authorization: `Bearer ${config.apiKey}`,\n \"Content-Type\": \"application/json\",\n ...init?.headers,\n },\n });\n const text = await response.text();\n const parsed = text ? JSON.parse(text) : {};\n if (!response.ok) {\n throw new PrintfulApiError(\n `Printful API request to \"${path}\" failed with status ${response.status}`,\n response.status,\n parsed,\n );\n }\n return parsed;\n}\n\n/** Splits a `\"{catalogVariantId}:{fileId}\"` catalogRef — see provider.ts's top-of-file design note. */\nfunction parseCatalogRef(catalogRef: string): {\n catalogVariantId: number;\n fileId: number;\n} {\n const [variantPart, filePart] = catalogRef.split(\":\");\n const catalogVariantId = Number(variantPart);\n const fileId = Number(filePart);\n if (!Number.isFinite(catalogVariantId) || !Number.isFinite(fileId)) {\n throw new Error(\n `Printful catalogRef \"${catalogRef}\" must be in \"{catalogVariantId}:{fileId}\" form`,\n );\n }\n return { catalogVariantId, fileId };\n}\n\ninterface PrintfulOrderItem {\n source: \"catalog\";\n catalog_variant_id: number;\n quantity: number;\n placements: Array<{\n placement: string;\n technique: string;\n layers: Array<{ type: \"file\"; id: number }>;\n }>;\n}\n\nasync function createFulfillmentOrder(\n config: PrintfulProviderConfig,\n request: FulfillmentOrderRequest,\n): Promise<FulfillmentOrderResult> {\n const orderItems: PrintfulOrderItem[] = request.lineItems.map((item) => {\n const { catalogVariantId, fileId } = parseCatalogRef(item.catalogRef);\n return {\n source: \"catalog\",\n catalog_variant_id: catalogVariantId,\n quantity: item.quantity,\n placements: [\n {\n placement: \"default\",\n technique: \"digital\",\n layers: [{ type: \"file\", id: fileId }],\n },\n ],\n };\n });\n\n if (!orderItems.length) {\n throw new Error(\n `Fulfillment order for orderId ${request.orderId} has no valid line items`,\n );\n }\n\n const address = request.shippingAddress;\n const response = await printfulFetch(config, \"/orders\", {\n method: \"POST\",\n body: JSON.stringify({\n external_id: `cadmea-order-${request.orderId}`,\n recipient: {\n name: [address.firstName, address.lastName].filter(Boolean).join(\" \"),\n address1: address.address1 ?? \"\",\n address2: address.address2,\n city: address.city ?? \"\",\n state_code: address.state ?? \"\",\n country_code: address.country ?? \"US\",\n zip: address.zip ?? \"\",\n phone: address.phone,\n email: request.customerEmail,\n },\n order_items: orderItems,\n }),\n });\n\n const order = response.data as { id: number; status: string };\n\n if (config.autoConfirm) {\n // A confirmation failure is logged, never thrown — the draft order\n // already exists at Printful and is visible for manual confirmation;\n // surfacing this as a fulfillment-creation failure would cause the\n // order-paid hook's caller to retry order creation and risk a\n // duplicate Printful order for the same Cadmea order.\n await printfulFetch(config, `/orders/${order.id}/confirmation`, {\n method: \"POST\",\n }).catch((error) => {\n console.error(\n `[cadmea-plugin-printful] order ${order.id} confirmation failed — manual confirmation required`,\n error,\n );\n });\n }\n\n return {\n providerFulfillmentRef: String(order.id),\n status: \"pending\",\n };\n}\n\nasync function hmacSha256Hex(message: string, keyHex: string): Promise<string> {\n const keyBytes = new Uint8Array(\n keyHex.match(/.{1,2}/g)?.map((byte) => Number.parseInt(byte, 16)) ?? [],\n );\n const key = await crypto.subtle.importKey(\n \"raw\",\n keyBytes,\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n const signature = await crypto.subtle.sign(\n \"HMAC\",\n key,\n new TextEncoder().encode(message),\n );\n return Array.from(new Uint8Array(signature), (b) =>\n b.toString(16).padStart(2, \"0\"),\n ).join(\"\");\n}\n\nfunction timingSafeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n let mismatch = 0;\n for (let i = 0; i < a.length; i++) {\n mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i);\n }\n return mismatch === 0;\n}\n\n/**\n * Verifies Printful's webhook signature: `x-pf-webhook-signature` is a hex\n * HMAC-SHA256 of the raw body, keyed by the webhook config's secret (itself\n * a hex string, decoded to bytes before use — Printful's own documented\n * format, ported from the source app's Node `crypto.createHmac` version).\n */\nasync function verifyWebhookSignature({\n rawBody,\n headers,\n secret,\n}: {\n rawBody: string;\n headers: Headers;\n secret: string;\n}): Promise<boolean> {\n const signature = headers.get(\"x-pf-webhook-signature\");\n if (!signature) return false;\n const expected = await hmacSha256Hex(rawBody, secret);\n return timingSafeEqual(expected, signature);\n}\n\ninterface ShipmentSentPayload {\n type: string;\n data: {\n order: { id: number };\n shipment?: {\n tracking_number: string;\n tracking_url: string;\n service: string;\n };\n };\n}\n\nfunction parseWebhookEvent(rawBody: string): {\n eventId: string;\n event: NormalizedFulfillmentWebhookEvent;\n} {\n const payload = JSON.parse(rawBody) as ShipmentSentPayload;\n // Printful doesn't include a stable webhook event id in its payload (no\n // `id` field, unlike Stripe) — the order id + type pair is unique enough\n // for this plugin's dedup purposes, since a real duplicate delivery\n // re-sends the exact same order/type combination.\n const eventId = `${payload.data.order.id}:${payload.type}`;\n\n if (payload.type === \"shipment_sent\" && payload.data.shipment) {\n return {\n eventId,\n event: {\n kind: \"fulfillment.updated\",\n providerFulfillmentRef: String(payload.data.order.id),\n status: \"shipped\",\n trackingNumber: payload.data.shipment.tracking_number,\n trackingCarrier: payload.data.shipment.service,\n trackingUrl: payload.data.shipment.tracking_url,\n },\n };\n }\n\n return { eventId, event: { kind: \"unhandled\", rawType: payload.type } };\n}\n\n/**\n * Creates a `FulfillmentProvider` backed by Printful's REST API — raw\n * `fetch()` + `crypto.subtle`, no Printful Node SDK. Implements\n * `createFulfillmentOrder`/`verifyWebhookSignature`/`parseWebhookEvent`,\n * the full `FulfillmentProvider` surface (no optional capabilities are\n * defined on that interface yet).\n */\nexport function createPrintfulProvider(\n config: PrintfulProviderConfig,\n): FulfillmentProvider {\n return {\n name: \"printful\",\n createFulfillmentOrder: (request) =>\n createFulfillmentOrder(config, request),\n verifyWebhookSignature,\n parseWebhookEvent,\n };\n}\n"],"mappings":";AA2CA,MAAM,WAAW;AAEjB,IAAM,mBAAN,cAA+B,MAAM;CAGjB;CACA;CAHlB,YACE,SACA,QACA,MACA;EACA,MAAM,OAAO;EAHG,KAAA,SAAA;EACA,KAAA,OAAA;EAGhB,KAAK,OAAO;CACd;AACF;AAEA,eAAe,cACb,QACA,MAC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Aa;AACtB;;;;;;;AAQA,eAAe,uBAAuB,EACpC,SACA,SACA,UAKmB;CACnB,MAAM,YAAY,QAAQ,IAAI,wBAAwB;CACtD,IAAI,CAAC,WAAW,OAAO;CAEvB,OAAO,gBAAgB,MADA,cAAc,SAAS,MAAM,GACnB,SAAS;AAC5C;AAcA,SAAS,kBAAkB,SAGzB;CACA,MAAM,UAAU,KAAK,MAAM,OAAO;CAKlC,MAAM,UAAU,GAAG,QAAQ,KAAK,MAAM,GAAG,GAAG,QAAQ;CAEpD,IAAI,QAAQ,SAAS,mBAAmB,QAAQ,KAAK,UACnD,OAAO;EACL;EACA,OAAO;GACL,MAAM;GACN,wBAAwB,OAAO,QAAQ,KAAK,MAAM,EAAE;GACpD,QAAQ;GACR,gBAAgB,QAAQ,KAAK,SAAS;GACtC,iBAAiB,QAAQ,KAAK,SAAS;GACvC,aAAa,QAAQ,KAAK,SAAS;EACrC;CACF;CAGF,OAAO;EAAE;EAAS,OAAO;GAAE,MAAM;GAAa,SAAS,QAAQ;EAAK;CAAE;AACxE;;;;;;;;AASA,SAAgB,uBACd,QACqB;CACrB,OAAO;EACL,MAAM;EACN,yBAAyB,YACvB,uBAAuB,QAAQ,OAAO;EACxC;EACA;CACF;AACF"}
|
package/package.json
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@thebes/cadmea-plugin-printful",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Printful FulfillmentProvider for @thebes/cadmea-plugin-ecommerce — raw fetch() + crypto.subtle, no Printful Node SDK",
|
|
5
|
+
"author": "BowenLabs <hello@bowenlabs.io>",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "https://github.com/bowenlabs/project-thebes",
|
|
10
|
+
"directory": "packages/cadmea-plugin-printful"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/bowenlabs/project-thebes/tree/main/packages/cadmea-plugin-printful#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/bowenlabs/project-thebes/issues"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"cadmea",
|
|
18
|
+
"cadmus",
|
|
19
|
+
"cms",
|
|
20
|
+
"ecommerce",
|
|
21
|
+
"printful",
|
|
22
|
+
"fulfillment",
|
|
23
|
+
"print-on-demand",
|
|
24
|
+
"cloudflare"
|
|
25
|
+
],
|
|
26
|
+
"type": "module",
|
|
27
|
+
"exports": {
|
|
28
|
+
".": {
|
|
29
|
+
"types": "./dist/index.d.ts",
|
|
30
|
+
"default": "./dist/index.js"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"peerDependencies": {
|
|
34
|
+
"@thebes/cadmea-plugin-ecommerce": "^1.1.0",
|
|
35
|
+
"@thebes/cadmus": "^0.2.1"
|
|
36
|
+
},
|
|
37
|
+
"devDependencies": {
|
|
38
|
+
"typescript": "latest",
|
|
39
|
+
"vite-plus": "latest",
|
|
40
|
+
"vitest": "latest",
|
|
41
|
+
"@thebes/cadmea-plugin-ecommerce": "^1.1.0",
|
|
42
|
+
"@thebes/cadmus": "^0.2.1"
|
|
43
|
+
},
|
|
44
|
+
"files": [
|
|
45
|
+
"dist",
|
|
46
|
+
"README.md",
|
|
47
|
+
"LICENSE"
|
|
48
|
+
],
|
|
49
|
+
"scripts": {
|
|
50
|
+
"build": "vp pack",
|
|
51
|
+
"dev": "vp pack --watch",
|
|
52
|
+
"test": "vitest run",
|
|
53
|
+
"test:watch": "vitest"
|
|
54
|
+
}
|
|
55
|
+
}
|