@extantape/payload-plugin-shipping 0.0.0-stage → 0.1.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 +78 -2
- package/dist/address.d.ts +58 -0
- package/dist/address.js +75 -0
- package/dist/api.d.ts +45 -0
- package/dist/api.js +64 -0
- package/dist/easypost.d.ts +22 -0
- package/dist/easypost.js +121 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +6 -0
- package/dist/parcel.d.ts +27 -0
- package/dist/parcel.js +50 -0
- package/dist/plugin.d.ts +6 -0
- package/dist/plugin.js +90 -0
- package/dist/testing.d.ts +65 -0
- package/dist/testing.js +83 -0
- package/dist/tracking.d.ts +8 -0
- package/dist/tracking.js +19 -0
- package/dist/types.d.ts +118 -0
- package/dist/types.js +1 -0
- package/package.json +67 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 EXTANT APE
|
|
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,79 @@
|
|
|
1
|
-
#
|
|
1
|
+
# payload-plugin-shipping
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Shipping for Payload: addresses, carrier rates, labels, refunds of unused labels and tracking webhooks, with EasyPost as the first carrier provider.
|
|
4
|
+
|
|
5
|
+
**Status:** 0.1.0, not on npm yet. 21 tests pass against Payload 3.92 with an in-memory MongoDB and a fake carrier. They cover addresses, parcels, buying, returns, the side-effects hook, production refused without it, a timed-out purchase, errors without addresses, and the webhook's 503, 401 (a custom provider's async check included), unknown, too-old, too-new, retry and refund cases, and purchases whose outcome is unclear. It has never called EasyPost: the request shapes follow EasyPost's documentation and are checked in test mode once a test key is saved. No site uses it yet.
|
|
6
|
+
|
|
7
|
+
## What it does
|
|
8
|
+
|
|
9
|
+
- **Addresses** of three kinds (street, PO Box, General Delivery), with `addressProblems` in plain codes, `labelAddress` (refuses a guessed or placeholder address), `addressKey` and `carriersFor`: PO Box and General Delivery take USPS only. Both addresses on a label always come from your records, never a carrier account's defaults.
|
|
10
|
+
- **Carrier calls**, through a provider (EasyPost first):
|
|
11
|
+
- `quote`: Ground Advantage first, else the cheapest allowed. A PO Box or General Delivery address on either side gets USPS only, whatever the caller asked;
|
|
12
|
+
- `buy`, and `buyLabel` (a quote then a purchase);
|
|
13
|
+
- `buyReturn`: from the customer to your hub's address, USPS only;
|
|
14
|
+
- `quoteReturn`;
|
|
15
|
+
- `refund`, for an unused label, within 30 days for USPS;
|
|
16
|
+
- `verifyAddress`.
|
|
17
|
+
- **Your go-ahead before every outside call.** `beforeExternalCall({ action, mode })` runs before every verify, quote, buy and refund, and a throw stops the call. Without the hook, test mode (an `EZTK…` key) is allowed and production mode is refused, so a copied live key can't buy postage from a test site by accident.
|
|
18
|
+
- **Errors in plain words**, with a stable code. They never include a name, an address or your key. A purchase whose outcome is unclear (a timeout, a dropped connection, a 5xx, an unreadable reply, or a label with no tracking number) fails with `MAYBE_BOUGHT` and says it may have been bought, so nobody buys twice. Address checks return EasyPost's codes, never its text.
|
|
19
|
+
- **Parcels:** `parcelFor` (a box's outside size, longest side first, and weight), `billableLb` and `dimWeightLb` (USPS dimensional weight past one cubic foot), and `mailability` (too big, too heavy, the nonstandard fees, in words).
|
|
20
|
+
- **Tracking:** `trackingLink` for USPS and UPS, and `noticeFor`, which maps a carrier status to out for delivery, delivered or an exception. Sending the emails is yours, through Notifications or your own code.
|
|
21
|
+
- **The webhook** at `/api/easypost/webhook` (a root endpoint, `webhookPath`). It fails closed:
|
|
22
|
+
- no secret configured: 503;
|
|
23
|
+
- unsigned or wrongly signed: 401, with the HMAC checked over the raw bytes before anything is parsed. A custom provider's `webhook.verify` may be sync or async, and only an answer of exactly `true` counts: `false`, `1`, an object such as `{ valid: false }`, or an error thrown or rejected is a 401;
|
|
24
|
+
- a tracker or refund event older than 7 days, or dated more than 10 minutes ahead, is ignored, so a captured body can't be replayed later;
|
|
25
|
+
- an event no handler claims: 200 "unknown", nothing written;
|
|
26
|
+
- a handler that throws, or answers anything but `'handled'` or `'unknown'`: 500, so the carrier retries.
|
|
27
|
+
|
|
28
|
+
Handlers are yours, or another plugin's, registered at `config.custom.shippingHandlers` with no import. They must be idempotent, because carriers retry.
|
|
29
|
+
- **No collections.** The plugin that buys a label records it.
|
|
30
|
+
- **A fake carrier for tests and dry runs**, only from `@extantape/payload-plugin-shipping/testing`, so a production bundle can't pick it by accident. Its prices are made up, and every rate and label says `fake: true`.
|
|
31
|
+
|
|
32
|
+
## On its own, and with others
|
|
33
|
+
|
|
34
|
+
**On its own:** Shipping needs only Payload and an EasyPost key, which your site passes in, or the fake carrier for tests. It adds no collections, so your own code records each label it buys, and your own handlers answer the webhook.
|
|
35
|
+
|
|
36
|
+
**Works with:**
|
|
37
|
+
- **Sample Kits:** your site passes Shipping's functions into Sample Kits' `adapters.shipping`, and Sample Kits registers its tracking and refund handler at `config.custom.shippingHandlers`. The two never import each other.
|
|
38
|
+
- **Notifications:** Shipping sends nothing itself. `noticeFor` turns a carrier status into out for delivery, delivered or a problem, and the plugin that owns the parcel can send that through Notifications.
|
|
39
|
+
- **Kitting:** Kitting's box suggestions can use Shipping's rates. From Kitting 0.3.0 (not released yet), pass Shipping's `quote` to Kitting's adapter as it is: `shipping: { provider: ratesFromShipping({ quote, from }) }`. Neither plugin imports the other, and every quote still goes through your `beforeExternalCall` hook. If a quote fails, Kitting packs by its own postage rates and marks the suggestion.
|
|
40
|
+
|
|
41
|
+
**Family:** Shipping sits in the Fulfillment family, with Kitting, Restock, Sample Kits, Scan, Labels, Wizards, Custody and Sequences, though the families are a working draft and Fulfillment is due to be split into different groups.
|
|
42
|
+
|
|
43
|
+
## Install
|
|
44
|
+
|
|
45
|
+
```sh
|
|
46
|
+
npm install @extantape/payload-plugin-shipping
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
import { easyPost, shippingPlugin } from '@extantape/payload-plugin-shipping'
|
|
51
|
+
|
|
52
|
+
shippingPlugin({
|
|
53
|
+
provider: easyPost({ apiKey: process.env.EASYPOST_API_KEY, webhookSecret: process.env.EASYPOST_WEBHOOK_SECRET }),
|
|
54
|
+
beforeExternalCall: ({ action, mode }) => mySideEffectsCheck('easypost', action, mode), // throw to refuse
|
|
55
|
+
handlers: [{ owner: 'orders', onTracker: async ({ event }) => (await markTracking(event)) ? 'handled' : 'unknown' }],
|
|
56
|
+
})
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
The plugin reads no environment: your site passes the key and the secret in.
|
|
60
|
+
|
|
61
|
+
The go-ahead hook guards the plugin's functions (`quote`, `buy`, `buyLabel`, `refund` and the rest). The provider object itself, from `easyPost()` or `config.custom.shipping.provider`, calls the carrier directly: it's server code, so treat it like your key and go through the functions.
|
|
62
|
+
|
|
63
|
+
## Limits
|
|
64
|
+
|
|
65
|
+
- US addresses only for now.
|
|
66
|
+
- EasyPost is the only provider. The contract allows others.
|
|
67
|
+
- A label ledger across owners is planned, not in 0.1.
|
|
68
|
+
|
|
69
|
+
## Commands
|
|
70
|
+
|
|
71
|
+
```sh
|
|
72
|
+
npm test # integration tests, in-memory MongoDB, fake carrier
|
|
73
|
+
npm run typecheck
|
|
74
|
+
npm run build
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## License
|
|
78
|
+
|
|
79
|
+
MIT. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mailing addresses for labels (kits plan §6, owner 2026-11-09). A hub's address is one of three
|
|
3
|
+
* kinds, switchable in the admin without a code change:
|
|
4
|
+
* - street: a street address (also a private mailbox at a mail store, which is street-style);
|
|
5
|
+
* - po-box: a USPS PO Box, with no street;
|
|
6
|
+
* - general-delivery: USPS General Delivery at a post office: "GENERAL DELIVERY" as the street line and
|
|
7
|
+
* the office's ZIP+4 ending in -9999. Mail waits there about 30 days, so returns need prompt pickup.
|
|
8
|
+
* PO Box and General Delivery take USPS only. Labels always carry the address from the record, never
|
|
9
|
+
* a carrier account's default. Names and addresses live in the database only.
|
|
10
|
+
*/
|
|
11
|
+
export declare const ADDRESS_KINDS: readonly ["street", "po-box", "general-delivery"];
|
|
12
|
+
export type AddressKind = (typeof ADDRESS_KINDS)[number];
|
|
13
|
+
export type StoredAddress = {
|
|
14
|
+
kind?: AddressKind | null;
|
|
15
|
+
/** The recipient line, e.g. a person's name. */
|
|
16
|
+
name?: string | null;
|
|
17
|
+
/** The "C/O" line: the company the mail is in care of. */
|
|
18
|
+
company?: string | null;
|
|
19
|
+
line1?: string | null;
|
|
20
|
+
line2?: string | null;
|
|
21
|
+
poBox?: string | null;
|
|
22
|
+
city?: string | null;
|
|
23
|
+
state?: string | null;
|
|
24
|
+
postalCode?: string | null;
|
|
25
|
+
phone?: string | null;
|
|
26
|
+
};
|
|
27
|
+
/** What a label needs (EasyPost's address shape). */
|
|
28
|
+
export type LabelAddress = {
|
|
29
|
+
name: string;
|
|
30
|
+
company: string | null;
|
|
31
|
+
street1: string;
|
|
32
|
+
street2: string | null;
|
|
33
|
+
city: string;
|
|
34
|
+
state: string;
|
|
35
|
+
zip: string;
|
|
36
|
+
country: 'US';
|
|
37
|
+
phone: string | null;
|
|
38
|
+
};
|
|
39
|
+
export type AddressProblem = 'placeholder' | 'name' | 'street' | 'poBox' | 'city' | 'state' | 'zip' | 'gdZip';
|
|
40
|
+
/** Why this address can't go on a label, or an empty list. */
|
|
41
|
+
export declare function addressProblems(a: StoredAddress | null | undefined, opts?: {
|
|
42
|
+
placeholder?: boolean | null;
|
|
43
|
+
}): AddressProblem[];
|
|
44
|
+
/** The address as it goes on a label. Refuses an address with problems: no label to a guessed address. */
|
|
45
|
+
export declare function labelAddress(a: StoredAddress | null | undefined, opts?: {
|
|
46
|
+
placeholder?: boolean | null;
|
|
47
|
+
}): LabelAddress;
|
|
48
|
+
/**
|
|
49
|
+
* A short fingerprint of where a label sends mail, so a label made for an older hub address can be
|
|
50
|
+
* found after the address changes. Only the delivery fields count, not the phone.
|
|
51
|
+
*/
|
|
52
|
+
export declare function addressKey(a: LabelAddress): string;
|
|
53
|
+
/** Carriers allowed to deliver to this kind of address. */
|
|
54
|
+
export declare const carriersFor: (kind: AddressKind | null | undefined) => "any" | "USPS";
|
|
55
|
+
export declare class AddressError extends Error {
|
|
56
|
+
readonly problems: AddressProblem[];
|
|
57
|
+
constructor(problems: AddressProblem[]);
|
|
58
|
+
}
|
package/dist/address.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
/**
|
|
3
|
+
* Mailing addresses for labels (kits plan §6, owner 2026-11-09). A hub's address is one of three
|
|
4
|
+
* kinds, switchable in the admin without a code change:
|
|
5
|
+
* - street: a street address (also a private mailbox at a mail store, which is street-style);
|
|
6
|
+
* - po-box: a USPS PO Box, with no street;
|
|
7
|
+
* - general-delivery: USPS General Delivery at a post office: "GENERAL DELIVERY" as the street line and
|
|
8
|
+
* the office's ZIP+4 ending in -9999. Mail waits there about 30 days, so returns need prompt pickup.
|
|
9
|
+
* PO Box and General Delivery take USPS only. Labels always carry the address from the record, never
|
|
10
|
+
* a carrier account's default. Names and addresses live in the database only.
|
|
11
|
+
*/
|
|
12
|
+
export const ADDRESS_KINDS = ['street', 'po-box', 'general-delivery'];
|
|
13
|
+
const clean = (v) => (v ?? '').trim();
|
|
14
|
+
const ZIP = /^\d{5}(-\d{4})?$/;
|
|
15
|
+
/** Why this address can't go on a label, or an empty list. */
|
|
16
|
+
export function addressProblems(a, opts = {}) {
|
|
17
|
+
const out = [];
|
|
18
|
+
if (opts.placeholder)
|
|
19
|
+
out.push('placeholder');
|
|
20
|
+
const kind = a?.kind ?? 'street';
|
|
21
|
+
// A PO Box or General Delivery item is only handed to the named person.
|
|
22
|
+
if (kind !== 'street' && !clean(a?.name))
|
|
23
|
+
out.push('name');
|
|
24
|
+
if (kind === 'street' && !clean(a?.line1))
|
|
25
|
+
out.push('street');
|
|
26
|
+
if (kind === 'po-box' && !/^\d{1,10}$/.test(clean(a?.poBox).replace(/^(PO\s*BOX\s*)/i, '')))
|
|
27
|
+
out.push('poBox');
|
|
28
|
+
if (!clean(a?.city))
|
|
29
|
+
out.push('city');
|
|
30
|
+
if (!/^[A-Z]{2}$/i.test(clean(a?.state)))
|
|
31
|
+
out.push('state');
|
|
32
|
+
const zip = clean(a?.postalCode);
|
|
33
|
+
if (!ZIP.test(zip))
|
|
34
|
+
out.push('zip');
|
|
35
|
+
else if (kind === 'general-delivery' && !/^\d{5}-9999$/.test(zip))
|
|
36
|
+
out.push('gdZip');
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
/** The address as it goes on a label. Refuses an address with problems: no label to a guessed address. */
|
|
40
|
+
export function labelAddress(a, opts = {}) {
|
|
41
|
+
const problems = addressProblems(a, opts);
|
|
42
|
+
if (problems.length)
|
|
43
|
+
throw new AddressError(problems);
|
|
44
|
+
const kind = a.kind ?? 'street';
|
|
45
|
+
const street1 = kind === 'po-box' ? `PO BOX ${clean(a.poBox).replace(/^(PO\s*BOX\s*)/i, '')}` : kind === 'general-delivery' ? 'GENERAL DELIVERY' : clean(a.line1);
|
|
46
|
+
return {
|
|
47
|
+
name: clean(a.name) || clean(a.company),
|
|
48
|
+
company: clean(a.company) ? `C/O ${clean(a.company).replace(/^C\/O\s*/i, '')}` : null,
|
|
49
|
+
street1,
|
|
50
|
+
// PO Box and General Delivery have no street; a second line would confuse the carrier.
|
|
51
|
+
street2: kind === 'street' ? clean(a.line2) || null : null,
|
|
52
|
+
city: clean(a.city),
|
|
53
|
+
state: clean(a.state).toUpperCase(),
|
|
54
|
+
zip: clean(a.postalCode),
|
|
55
|
+
country: 'US',
|
|
56
|
+
phone: clean(a.phone) || null,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* A short fingerprint of where a label sends mail, so a label made for an older hub address can be
|
|
61
|
+
* found after the address changes. Only the delivery fields count, not the phone.
|
|
62
|
+
*/
|
|
63
|
+
export function addressKey(a) {
|
|
64
|
+
const fields = [a.name, a.company ?? '', a.street1, a.street2 ?? '', a.city, a.state, a.zip].map((f) => f.trim().toUpperCase().replace(/\s+/g, ' '));
|
|
65
|
+
return createHash('sha256').update(fields.join('|')).digest('hex').slice(0, 16);
|
|
66
|
+
}
|
|
67
|
+
/** Carriers allowed to deliver to this kind of address. */
|
|
68
|
+
export const carriersFor = (kind) => (kind && kind !== 'street' ? 'USPS' : 'any');
|
|
69
|
+
export class AddressError extends Error {
|
|
70
|
+
problems;
|
|
71
|
+
constructor(problems) {
|
|
72
|
+
super(`The address can't go on a label: ${problems.join(', ')}.`);
|
|
73
|
+
this.problems = problems;
|
|
74
|
+
}
|
|
75
|
+
}
|
package/dist/api.d.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { Payload } from 'payload';
|
|
2
|
+
import { type LabelAddress, type StoredAddress } from './address.js';
|
|
3
|
+
import type { Label, Parcel, Quote, RefundStatus, Req, Verification } from './types.js';
|
|
4
|
+
export declare function verifyAddress(payload: Payload, a: LabelAddress, req?: Req): Promise<Verification>;
|
|
5
|
+
export declare function quote(payload: Payload, input: {
|
|
6
|
+
from: LabelAddress;
|
|
7
|
+
to: LabelAddress;
|
|
8
|
+
parcel: Parcel;
|
|
9
|
+
carrier?: 'any' | 'USPS';
|
|
10
|
+
reference: string;
|
|
11
|
+
}, req?: Req): Promise<Quote>;
|
|
12
|
+
export declare function buy(payload: Payload, q: Quote, req?: Req): Promise<Label>;
|
|
13
|
+
/** A quote and a purchase. Both addresses always come from the caller: never the carrier account's defaults. */
|
|
14
|
+
export declare function buyLabel(payload: Payload, input: {
|
|
15
|
+
from: LabelAddress;
|
|
16
|
+
to: LabelAddress;
|
|
17
|
+
parcel: Parcel;
|
|
18
|
+
carrier?: 'any' | 'USPS';
|
|
19
|
+
reference: string;
|
|
20
|
+
}, req?: Req): Promise<Label>;
|
|
21
|
+
/**
|
|
22
|
+
* A return label from the customer to a hub, written out from the hub's record, USPS only (PO Box and General
|
|
23
|
+
* Delivery take nothing else). Refuses a placeholder or incomplete hub address, and any other carrier.
|
|
24
|
+
*/
|
|
25
|
+
export declare function buyReturn(payload: Payload, input: {
|
|
26
|
+
customer: LabelAddress;
|
|
27
|
+
hub: {
|
|
28
|
+
address?: StoredAddress | null;
|
|
29
|
+
placeholder?: boolean | null;
|
|
30
|
+
};
|
|
31
|
+
parcel: Parcel;
|
|
32
|
+
carrier?: string;
|
|
33
|
+
reference: string;
|
|
34
|
+
}, req?: Req): Promise<Label>;
|
|
35
|
+
export declare function quoteReturn(payload: Payload, input: {
|
|
36
|
+
customer: LabelAddress;
|
|
37
|
+
hub: {
|
|
38
|
+
address?: StoredAddress | null;
|
|
39
|
+
placeholder?: boolean | null;
|
|
40
|
+
};
|
|
41
|
+
parcel: Parcel;
|
|
42
|
+
reference: string;
|
|
43
|
+
}, req?: Req): Promise<Quote>;
|
|
44
|
+
/** Ask for an unused label's money back (USPS: within 30 days, never scanned). */
|
|
45
|
+
export declare function refund(payload: Payload, shipmentId: string, req?: Req): Promise<RefundStatus>;
|
package/dist/api.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { labelAddress } from './address.js';
|
|
2
|
+
import { CarrierError } from './easypost.js';
|
|
3
|
+
const configOf = (payload) => {
|
|
4
|
+
const o = payload.config.custom?.shipping;
|
|
5
|
+
if (!o)
|
|
6
|
+
throw new Error('Shipping: the plugin is not configured on this site.');
|
|
7
|
+
return o;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* Every call that costs money or reaches the carrier passes the site's `beforeExternalCall` first; if it throws, the
|
|
11
|
+
* call doesn't happen. With no hook, test mode is allowed and production mode is refused: the plugin fails closed.
|
|
12
|
+
*/
|
|
13
|
+
async function guard(payload, action, req) {
|
|
14
|
+
const o = configOf(payload);
|
|
15
|
+
const mode = o.provider.mode;
|
|
16
|
+
if (!mode)
|
|
17
|
+
throw new CarrierError(0, 'NO_KEY', 'Shipping isn’t set up here.');
|
|
18
|
+
if (o.beforeExternalCall)
|
|
19
|
+
await o.beforeExternalCall({ action, mode, req });
|
|
20
|
+
else if (mode === 'production')
|
|
21
|
+
throw new CarrierError(0, 'REFUSED', 'Live postage needs the site’s go-ahead (beforeExternalCall), which isn’t set.');
|
|
22
|
+
}
|
|
23
|
+
export async function verifyAddress(payload, a, req) {
|
|
24
|
+
await guard(payload, 'verify', req);
|
|
25
|
+
return configOf(payload).provider.verify(a);
|
|
26
|
+
}
|
|
27
|
+
/** PO Box and General Delivery take USPS only, whatever the caller asked: the label addresses say which they are. */
|
|
28
|
+
const USPS_ONLY = /^(PO BOX\b|GENERAL DELIVERY$)/i;
|
|
29
|
+
const carrierFor = (input) => input.carrier === 'USPS' || [input.from, input.to].some((a) => USPS_ONLY.test(a.street1.trim())) ? 'USPS' : 'any';
|
|
30
|
+
export async function quote(payload, input, req) {
|
|
31
|
+
await guard(payload, 'quote', req);
|
|
32
|
+
return configOf(payload).provider.quote({ ...input, carrier: carrierFor(input) });
|
|
33
|
+
}
|
|
34
|
+
export async function buy(payload, q, req) {
|
|
35
|
+
await guard(payload, 'buy', req);
|
|
36
|
+
return configOf(payload).provider.buy(q);
|
|
37
|
+
}
|
|
38
|
+
/** A quote and a purchase. Both addresses always come from the caller: never the carrier account's defaults. */
|
|
39
|
+
export async function buyLabel(payload, input, req) {
|
|
40
|
+
// Both checks before anything leaves: a refused purchase costs no quote. The hook sees each action once.
|
|
41
|
+
await guard(payload, 'buy', req);
|
|
42
|
+
await guard(payload, 'quote', req);
|
|
43
|
+
const provider = configOf(payload).provider;
|
|
44
|
+
return provider.buy(await provider.quote({ ...input, carrier: carrierFor(input) }));
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* A return label from the customer to a hub, written out from the hub's record, USPS only (PO Box and General
|
|
48
|
+
* Delivery take nothing else). Refuses a placeholder or incomplete hub address, and any other carrier.
|
|
49
|
+
*/
|
|
50
|
+
export async function buyReturn(payload, input, req) {
|
|
51
|
+
if (input.carrier && input.carrier.toUpperCase() !== 'USPS')
|
|
52
|
+
throw new CarrierError(0, 'USPS_ONLY', 'Return labels are USPS only.');
|
|
53
|
+
const to = labelAddress(input.hub.address, { placeholder: input.hub.placeholder });
|
|
54
|
+
return buyLabel(payload, { from: input.customer, to, parcel: input.parcel, carrier: 'USPS', reference: input.reference }, req);
|
|
55
|
+
}
|
|
56
|
+
export async function quoteReturn(payload, input, req) {
|
|
57
|
+
const to = labelAddress(input.hub.address, { placeholder: input.hub.placeholder });
|
|
58
|
+
return quote(payload, { from: input.customer, to, parcel: input.parcel, carrier: 'USPS', reference: input.reference }, req);
|
|
59
|
+
}
|
|
60
|
+
/** Ask for an unused label's money back (USPS: within 30 days, never scanned). */
|
|
61
|
+
export async function refund(payload, shipmentId, req) {
|
|
62
|
+
await guard(payload, 'refund', req);
|
|
63
|
+
return configOf(payload).provider.refund(shipmentId);
|
|
64
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { CarrierProvider, Mode, Rate } from './types.js';
|
|
2
|
+
/** Every EasyPost call gives up after this long. */
|
|
3
|
+
export declare const CALL_TIMEOUT_MS = 60000;
|
|
4
|
+
/** An error from EasyPost or the client, in plain words, with a stable code. Never carries an address or a key. */
|
|
5
|
+
export declare class CarrierError extends Error {
|
|
6
|
+
readonly status: number;
|
|
7
|
+
readonly code: string;
|
|
8
|
+
constructor(status: number, code: string, message: string);
|
|
9
|
+
}
|
|
10
|
+
export declare const modeOf: (key?: string | null) => Mode | null;
|
|
11
|
+
/** Ground Advantage first, else the cheapest allowed rate. PO Box and General Delivery take USPS only. */
|
|
12
|
+
export declare function pickRate(rates: Rate[], carrier: 'any' | 'USPS'): Rate | null;
|
|
13
|
+
/**
|
|
14
|
+
* EasyPost, by plain REST (no SDK). The site reads its environment and passes the key and the webhook secret in:
|
|
15
|
+
* the plugin reads no environment. A test key (EZTK…) makes free test labels; any other key is production.
|
|
16
|
+
*/
|
|
17
|
+
export declare function easyPost(opts: {
|
|
18
|
+
apiKey?: string | null;
|
|
19
|
+
webhookSecret?: string | null;
|
|
20
|
+
fetchImpl?: typeof fetch;
|
|
21
|
+
timeoutMs?: number;
|
|
22
|
+
}): CarrierProvider;
|
package/dist/easypost.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
const API = 'https://api.easypost.com/v2';
|
|
3
|
+
/** Every EasyPost call gives up after this long. */
|
|
4
|
+
export const CALL_TIMEOUT_MS = 60_000;
|
|
5
|
+
/** An error from EasyPost or the client, in plain words, with a stable code. Never carries an address or a key. */
|
|
6
|
+
export class CarrierError extends Error {
|
|
7
|
+
status;
|
|
8
|
+
code;
|
|
9
|
+
constructor(status, code, message) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.status = status;
|
|
12
|
+
this.code = code;
|
|
13
|
+
this.name = 'CarrierError';
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
/** A purchase whose outcome isn't known: it may have been bought, so nobody should simply buy again. */
|
|
17
|
+
const maybeBought = (why) => new CarrierError(0, 'MAYBE_BOUGHT', `EasyPost’s answer was unclear (${why}). The label may have been bought anyway: check EasyPost’s shipments for this reference before trying again.`);
|
|
18
|
+
export const modeOf = (key) => (!key ? null : key.startsWith('EZTK') ? 'test' : 'production');
|
|
19
|
+
const toEasyPost = (a) => ({ name: a.name, company: a.company, street1: a.street1, street2: a.street2, city: a.city, state: a.state, zip: a.zip, country: a.country, phone: a.phone });
|
|
20
|
+
const parcelBody = (p) => ({ weight: p.weightOz, ...(p.lengthIn ? { length: p.lengthIn, width: p.widthIn, height: p.heightIn } : {}) });
|
|
21
|
+
/** Ground Advantage first, else the cheapest allowed rate. PO Box and General Delivery take USPS only. */
|
|
22
|
+
export function pickRate(rates, carrier) {
|
|
23
|
+
const allowed = rates.filter((r) => carrier === 'any' || r.carrier.toUpperCase() === 'USPS');
|
|
24
|
+
return allowed.find((r) => r.carrier.toUpperCase() === 'USPS' && r.service === 'GroundAdvantage') ?? [...allowed].sort((a, b) => Number(a.rate) - Number(b.rate))[0] ?? null;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* EasyPost, by plain REST (no SDK). The site reads its environment and passes the key and the webhook secret in:
|
|
28
|
+
* the plugin reads no environment. A test key (EZTK…) makes free test labels; any other key is production.
|
|
29
|
+
*/
|
|
30
|
+
export function easyPost(opts) {
|
|
31
|
+
const key = opts.apiKey ?? null;
|
|
32
|
+
const mode = modeOf(key);
|
|
33
|
+
const call = async (method, path, body) => {
|
|
34
|
+
if (!key)
|
|
35
|
+
throw new CarrierError(0, 'NO_KEY', 'EasyPost isn’t set up here.');
|
|
36
|
+
const buying = path.endsWith('/buy');
|
|
37
|
+
let res;
|
|
38
|
+
try {
|
|
39
|
+
res = await (opts.fetchImpl ?? fetch)(`${API}${path}`, {
|
|
40
|
+
signal: AbortSignal.timeout(opts.timeoutMs ?? CALL_TIMEOUT_MS),
|
|
41
|
+
method,
|
|
42
|
+
headers: { Authorization: `Basic ${Buffer.from(`${key}:`).toString('base64')}`, 'Content-Type': 'application/json' },
|
|
43
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
const name = error?.name;
|
|
48
|
+
// A purchase whose request may have left this machine may still have gone through: say so, never "nothing was bought".
|
|
49
|
+
if (buying)
|
|
50
|
+
throw maybeBought(name === 'TimeoutError' || name === 'AbortError' ? 'TIMEOUT' : 'NETWORK');
|
|
51
|
+
if (name !== 'TimeoutError' && name !== 'AbortError')
|
|
52
|
+
throw new CarrierError(0, 'NETWORK', 'EasyPost couldn’t be reached. Nothing was bought; try again.');
|
|
53
|
+
throw new CarrierError(0, 'TIMEOUT', 'EasyPost didn’t answer in time. Nothing was bought; try again.');
|
|
54
|
+
}
|
|
55
|
+
const json = (await res.json().catch(() => null));
|
|
56
|
+
// Only a clear 4xx is a clear refusal. A 5xx or 502 from a gateway, or a reply that can't be read, leaves a purchase unknown.
|
|
57
|
+
if (buying && (res.status >= 500 || (res.ok && !json) || (!res.ok && res.status < 400)))
|
|
58
|
+
throw maybeBought(`HTTP_${res.status}`);
|
|
59
|
+
if (!res.ok)
|
|
60
|
+
throw new CarrierError(res.status, json?.error?.code ?? 'HTTP_ERROR', `EasyPost refused (${json?.error?.code ?? res.status}).`);
|
|
61
|
+
if (!json)
|
|
62
|
+
throw new CarrierError(res.status, 'BAD_REPLY', 'EasyPost’s reply couldn’t be read. Nothing was bought; try again.');
|
|
63
|
+
return json;
|
|
64
|
+
};
|
|
65
|
+
const asLabel = (b, fallback) => {
|
|
66
|
+
// A label with no shipment id or tracking number can't be refunded or followed: treat the purchase as unknown.
|
|
67
|
+
if (!b.id || !b.tracking_code)
|
|
68
|
+
throw maybeBought('INCOMPLETE');
|
|
69
|
+
const chosen = b.selected_rate ?? fallback;
|
|
70
|
+
return { shipmentId: b.id, tracking: b.tracking_code, carrier: chosen.carrier, service: chosen.service, rateCents: Math.round(Number(chosen.rate) * 100), labelUrl: b.postage_label?.label_url ?? '', trackerUrl: b.tracker?.public_url ?? null, mode: mode, ...(chosen.fake ? { fake: true } : {}) };
|
|
71
|
+
};
|
|
72
|
+
return {
|
|
73
|
+
name: 'easypost',
|
|
74
|
+
mode,
|
|
75
|
+
verify: async (a) => {
|
|
76
|
+
const r = await call('POST', '/addresses', { address: { ...toEasyPost(a), verify: true } });
|
|
77
|
+
const v = r.verifications?.delivery;
|
|
78
|
+
return { ok: Boolean(v?.success), errors: (v?.errors ?? []).map((e) => e.code ?? 'UNKNOWN'), corrected: v?.success && (r.street1 !== a.street1 || r.zip !== a.zip) ? { street1: r.street1, zip: r.zip } : null };
|
|
79
|
+
},
|
|
80
|
+
quote: async (input) => {
|
|
81
|
+
if (!(input.parcel.weightOz > 0))
|
|
82
|
+
throw new CarrierError(0, 'NO_WEIGHT', 'The parcel needs a weight.');
|
|
83
|
+
const shipment = await call('POST', '/shipments', { shipment: { from_address: toEasyPost(input.from), to_address: toEasyPost(input.to), parcel: parcelBody(input.parcel), reference: input.reference, options: { label_format: 'PDF' } } });
|
|
84
|
+
const rate = pickRate(shipment.rates ?? [], input.carrier ?? 'any');
|
|
85
|
+
if (!rate)
|
|
86
|
+
throw new CarrierError(0, 'NO_RATE', input.carrier === 'USPS' ? 'EasyPost offered no USPS rate for this parcel.' : 'EasyPost offered no rate for this parcel.');
|
|
87
|
+
return { shipmentId: shipment.id, rate, rateCents: Math.round(Number(rate.rate) * 100), mode: mode, ...(rate.fake ? { fake: true } : {}) };
|
|
88
|
+
},
|
|
89
|
+
buy: async (quote) => asLabel(await call('POST', `/shipments/${encodeURIComponent(quote.shipmentId)}/buy`, { rate: { id: quote.rate.id } }), quote.rate),
|
|
90
|
+
refund: async (shipmentId) => (await call('POST', `/shipments/${encodeURIComponent(shipmentId)}/refund`, {})).refund_status ?? 'submitted',
|
|
91
|
+
webhook: {
|
|
92
|
+
configured: Boolean(opts.webhookSecret),
|
|
93
|
+
// EasyPost signs the raw body: `X-Hmac-Signature: hmac-sha256-hex=<HMAC>`, the secret NFKD-normalized.
|
|
94
|
+
verify: (raw, headers) => {
|
|
95
|
+
const secret = opts.webhookSecret;
|
|
96
|
+
const header = headers.get('x-hmac-signature');
|
|
97
|
+
if (!secret || !header)
|
|
98
|
+
return false;
|
|
99
|
+
const expected = `hmac-sha256-hex=${createHmac('sha256', secret.normalize('NFKD')).update(raw, 'utf8').digest('hex')}`;
|
|
100
|
+
const a = Buffer.from(header.trim());
|
|
101
|
+
const b = Buffer.from(expected);
|
|
102
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
103
|
+
},
|
|
104
|
+
parse: (raw) => {
|
|
105
|
+
let body;
|
|
106
|
+
try {
|
|
107
|
+
body = JSON.parse(raw);
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
const r = body.result;
|
|
113
|
+
if (body.id && body.created_at && /^refund\./.test(body.description ?? '') && r?.object === 'Refund' && r.tracking_code && ['submitted', 'refunded', 'rejected', 'not_applicable'].includes(r.status ?? ''))
|
|
114
|
+
return { refund: { id: body.id, createdAt: body.created_at, tracking: r.tracking_code.toUpperCase(), status: r.status } };
|
|
115
|
+
if (body.id && body.created_at && /^tracker\./.test(body.description ?? '') && r?.object === 'Tracker' && r.tracking_code && r.status)
|
|
116
|
+
return { tracker: { id: body.id, createdAt: body.created_at, tracking: r.tracking_code.toUpperCase(), status: r.status, carrier: r.carrier ?? null, publicUrl: r.public_url ?? null } };
|
|
117
|
+
return null;
|
|
118
|
+
},
|
|
119
|
+
},
|
|
120
|
+
};
|
|
121
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { shippingPlugin, handlersOf } from './plugin.js';
|
|
2
|
+
export { buy, buyLabel, buyReturn, quote, quoteReturn, refund, verifyAddress } from './api.js';
|
|
3
|
+
export { CALL_TIMEOUT_MS, CarrierError, easyPost, modeOf, pickRate } from './easypost.js';
|
|
4
|
+
export { ADDRESS_KINDS, AddressError, addressKey, addressProblems, carriersFor, labelAddress, type AddressKind, type AddressProblem, type LabelAddress, type StoredAddress } from './address.js';
|
|
5
|
+
export { billableLb, dimWeightLb, mailability, parcelFor, type ParcelSize } from './parcel.js';
|
|
6
|
+
export { noticeFor, trackingLink, USPS_REFUND_DAYS, type ShipmentEvent } from './tracking.js';
|
|
7
|
+
export type { CarrierProvider, ExternalAction, Label, Mode, Parcel, Quote, Rate, RefundEvent, RefundStatus, ShippingHandler, ShippingOptions, TrackerEvent, TrackerStatus, Verification } from './types.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { shippingPlugin, handlersOf } from './plugin.js';
|
|
2
|
+
export { buy, buyLabel, buyReturn, quote, quoteReturn, refund, verifyAddress } from './api.js';
|
|
3
|
+
export { CALL_TIMEOUT_MS, CarrierError, easyPost, modeOf, pickRate } from './easypost.js';
|
|
4
|
+
export { ADDRESS_KINDS, AddressError, addressKey, addressProblems, carriersFor, labelAddress } from './address.js';
|
|
5
|
+
export { billableLb, dimWeightLb, mailability, parcelFor } from './parcel.js';
|
|
6
|
+
export { noticeFor, trackingLink, USPS_REFUND_DAYS } from './tracking.js';
|
package/dist/parcel.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/** A parcel's outside size, in inches, and its weight, in ounces. */
|
|
2
|
+
export type ParcelSize = {
|
|
3
|
+
lengthIn: number;
|
|
4
|
+
widthIn: number;
|
|
5
|
+
heightIn: number;
|
|
6
|
+
weightOz: number;
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* A box holding some contents: its outside size, longest side first, and its weight. The box's own weight and the
|
|
10
|
+
* contents' weight come from the caller, who knows what's in it.
|
|
11
|
+
*/
|
|
12
|
+
export declare function parcelFor(box: {
|
|
13
|
+
outside: [number, number, number] | null;
|
|
14
|
+
emptyWeightOz?: number | null;
|
|
15
|
+
}, contentsWeightOz: number): ParcelSize | null;
|
|
16
|
+
/** USPS dimensional weight in pounds (volume ÷ 139), which counts only past one cubic foot. */
|
|
17
|
+
export declare function dimWeightLb(p: ParcelSize): number;
|
|
18
|
+
/** The weight USPS charges for, in whole pounds: the actual weight, or the dimensional weight past 1 cu ft. */
|
|
19
|
+
export declare function billableLb(p: ParcelSize): number;
|
|
20
|
+
/**
|
|
21
|
+
* What USPS's rules say about a parcel (DMM 101, 223 and 283): too big or too heavy to mail, the nonstandard fees,
|
|
22
|
+
* dimensional weight past one cubic foot. Plain words; the fee amounts come from the rates.
|
|
23
|
+
*/
|
|
24
|
+
export declare function mailability(p: ParcelSize): {
|
|
25
|
+
mailable: boolean;
|
|
26
|
+
notes: string[];
|
|
27
|
+
};
|
package/dist/parcel.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A box holding some contents: its outside size, longest side first, and its weight. The box's own weight and the
|
|
3
|
+
* contents' weight come from the caller, who knows what's in it.
|
|
4
|
+
*/
|
|
5
|
+
export function parcelFor(box, contentsWeightOz) {
|
|
6
|
+
if (!box.outside)
|
|
7
|
+
return null;
|
|
8
|
+
const [lengthIn, widthIn, heightIn] = [...box.outside].sort((a, b) => b - a);
|
|
9
|
+
return { lengthIn, widthIn, heightIn, weightOz: Math.round(((box.emptyWeightOz ?? 0) + contentsWeightOz) * 10) / 10 };
|
|
10
|
+
}
|
|
11
|
+
/** USPS dimensional weight in pounds (volume ÷ 139), which counts only past one cubic foot. */
|
|
12
|
+
export function dimWeightLb(p) {
|
|
13
|
+
return (Math.round(p.lengthIn) * Math.round(p.widthIn) * Math.round(p.heightIn)) / 139;
|
|
14
|
+
}
|
|
15
|
+
/** The weight USPS charges for, in whole pounds: the actual weight, or the dimensional weight past 1 cu ft. */
|
|
16
|
+
export function billableLb(p) {
|
|
17
|
+
const actual = p.weightOz / 16;
|
|
18
|
+
const cubic = Math.round(p.lengthIn) * Math.round(p.widthIn) * Math.round(p.heightIn);
|
|
19
|
+
return Math.max(1, Math.ceil(cubic > 1728 ? Math.max(actual, dimWeightLb(p)) : actual));
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* What USPS's rules say about a parcel (DMM 101, 223 and 283): too big or too heavy to mail, the nonstandard fees,
|
|
23
|
+
* dimensional weight past one cubic foot. Plain words; the fee amounts come from the rates.
|
|
24
|
+
*/
|
|
25
|
+
export function mailability(p) {
|
|
26
|
+
const [l, w, h] = [p.lengthIn, p.widthIn, p.heightIn].sort((a, b) => b - a);
|
|
27
|
+
const girth = 2 * (w + h);
|
|
28
|
+
const cubicIn = Math.round(l) * Math.round(w) * Math.round(h);
|
|
29
|
+
const notes = [];
|
|
30
|
+
let mailable = true;
|
|
31
|
+
if (p.weightOz > 70 * 16) {
|
|
32
|
+
mailable = false;
|
|
33
|
+
notes.push('over 70 lb: too heavy to mail');
|
|
34
|
+
}
|
|
35
|
+
if (l + girth > 130) {
|
|
36
|
+
mailable = false;
|
|
37
|
+
notes.push('over 130 in length plus girth: too big to mail');
|
|
38
|
+
}
|
|
39
|
+
else if (l + girth > 108)
|
|
40
|
+
notes.push('over 108 in length plus girth: oversized');
|
|
41
|
+
if (l > 30)
|
|
42
|
+
notes.push('over 30 in long: nonstandard fee');
|
|
43
|
+
else if (l > 22)
|
|
44
|
+
notes.push('over 22 in long: nonstandard fee');
|
|
45
|
+
if (cubicIn > 3456)
|
|
46
|
+
notes.push('over 2 cubic feet: nonstandard fee');
|
|
47
|
+
if (cubicIn > 1728)
|
|
48
|
+
notes.push(`over 1 cubic foot: dimensional weight (${Math.ceil(dimWeightLb(p))} lb)`);
|
|
49
|
+
return { mailable, notes };
|
|
50
|
+
}
|
package/dist/plugin.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { Payload, Plugin } from 'payload';
|
|
2
|
+
import type { ShippingHandler, ShippingOptions } from './types.js';
|
|
3
|
+
/** Every handler: the plugin's own options and those other plugins registered at `config.custom.shippingHandlers`. */
|
|
4
|
+
export declare const handlersOf: (payload: Payload) => ShippingHandler[];
|
|
5
|
+
/** Shipping: addresses, carrier quotes and labels, refunds of unused labels, and the carrier's webhook. */
|
|
6
|
+
export declare const shippingPlugin: (options: ShippingOptions) => Plugin;
|
package/dist/plugin.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
const DAY = 86_400_000;
|
|
2
|
+
/** Clocks differ a little; an event dated further ahead than this is refused. */
|
|
3
|
+
const FUTURE_SKEW_MS = 10 * 60_000;
|
|
4
|
+
const json = (body, status = 200) => Response.json(body, { status, headers: { 'Cache-Control': 'no-store' } });
|
|
5
|
+
/** Every handler: the plugin's own options and those other plugins registered at `config.custom.shippingHandlers`. */
|
|
6
|
+
export const handlersOf = (payload) => {
|
|
7
|
+
const o = payload.config.custom.shipping;
|
|
8
|
+
const extra = payload.config.custom?.shippingHandlers;
|
|
9
|
+
return [...o.handlers, ...(Array.isArray(extra) ? extra : [])];
|
|
10
|
+
};
|
|
11
|
+
/** Only an answer of exactly `true` (or a promise of it) passes; anything else, a thrown or rejected error included, is no. */
|
|
12
|
+
async function signedExactly(check) {
|
|
13
|
+
try {
|
|
14
|
+
return (await check()) === true;
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return false;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* The carrier's webhook. It fails closed:
|
|
22
|
+
* - no secret configured: 503;
|
|
23
|
+
* - an unsigned or wrongly signed body: 401, checked over the raw bytes before anything is parsed. Only `verify`
|
|
24
|
+
* answering exactly `true` (sync or async) counts; anything else, a throw included, is 401;
|
|
25
|
+
* - too old (a captured body replayed later), dated in the future, or not ours: 200, nothing written;
|
|
26
|
+
* - no handler claims it: 200 "unknown", nothing written;
|
|
27
|
+
* - a handler throws, or answers anything but "handled" or "unknown": 500, so the carrier retries (handlers must be idempotent).
|
|
28
|
+
*/
|
|
29
|
+
const webhook = (path) => ({
|
|
30
|
+
path,
|
|
31
|
+
method: 'post',
|
|
32
|
+
handler: async (req) => {
|
|
33
|
+
const o = req.payload.config.custom.shipping;
|
|
34
|
+
const hook = o.provider.webhook;
|
|
35
|
+
if (!hook?.configured)
|
|
36
|
+
return json({ error: 'Not configured' }, 503);
|
|
37
|
+
const raw = (await req.text?.()) ?? '';
|
|
38
|
+
// Only an exact `true`, awaited: a promise (a custom provider's async verify), any other truthy answer, or a
|
|
39
|
+
// throw is unsigned. EasyPost's own verify is sync and answers a boolean.
|
|
40
|
+
if (!(await signedExactly(() => hook.verify(raw, req.headers))))
|
|
41
|
+
return json({ error: 'Unauthorized' }, 401);
|
|
42
|
+
const ev = hook.parse(raw);
|
|
43
|
+
if (!ev)
|
|
44
|
+
return json({ result: 'ignored' });
|
|
45
|
+
// Both kinds of event: a captured body can't be replayed after the window, nor dated ahead to outlive it.
|
|
46
|
+
const at = new Date((ev.tracker ?? ev.refund).createdAt).getTime();
|
|
47
|
+
if (!(at > Date.now() - o.maxEventAgeDays * DAY))
|
|
48
|
+
return json({ result: 'too-old' });
|
|
49
|
+
if (!(at < Date.now() + FUTURE_SKEW_MS))
|
|
50
|
+
return json({ result: 'too-new' });
|
|
51
|
+
try {
|
|
52
|
+
for (const h of handlersOf(req.payload)) {
|
|
53
|
+
const fn = ev.tracker ? h.onTracker : h.onRefund;
|
|
54
|
+
if (!fn)
|
|
55
|
+
continue;
|
|
56
|
+
const result = ev.tracker ? await h.onTracker({ event: ev.tracker, req, payload: req.payload }) : await h.onRefund({ event: ev.refund, req, payload: req.payload });
|
|
57
|
+
if (result === 'handled')
|
|
58
|
+
return json({ result: 'handled' });
|
|
59
|
+
// A handler that forgot to answer may have half-done its work: fail closed, so the carrier retries.
|
|
60
|
+
if (result !== 'unknown')
|
|
61
|
+
throw new Error('shipping: a handler answered neither "handled" nor "unknown"');
|
|
62
|
+
}
|
|
63
|
+
return json({ result: 'unknown' });
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
req.payload.logger.error({ err: { name: error?.name }, msg: 'shipping: a webhook handler failed; the carrier will retry' });
|
|
67
|
+
return json({ error: 'Handler failed' }, 500);
|
|
68
|
+
}
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
/** Shipping: addresses, carrier quotes and labels, refunds of unused labels, and the carrier's webhook. */
|
|
72
|
+
export const shippingPlugin = (options) => (config) => {
|
|
73
|
+
if (!options?.provider || typeof options.provider.quote !== 'function')
|
|
74
|
+
throw new Error('Shipping: give a `provider`, for example easyPost({ apiKey, webhookSecret }).');
|
|
75
|
+
const o = {
|
|
76
|
+
provider: options.provider,
|
|
77
|
+
webhookPath: options.webhookPath ?? '/easypost/webhook',
|
|
78
|
+
maxEventAgeDays: options.maxEventAgeDays ?? 7,
|
|
79
|
+
beforeExternalCall: options.beforeExternalCall,
|
|
80
|
+
handlers: options.handlers ?? [],
|
|
81
|
+
};
|
|
82
|
+
if (!o.webhookPath.startsWith('/'))
|
|
83
|
+
throw new Error('Shipping: webhookPath starts with "/".');
|
|
84
|
+
return {
|
|
85
|
+
...config,
|
|
86
|
+
custom: { ...config.custom, shipping: o },
|
|
87
|
+
// A root endpoint, so the URL is exactly /api<webhookPath>.
|
|
88
|
+
endpoints: [...(config.endpoints ?? []), webhook(o.webhookPath)],
|
|
89
|
+
};
|
|
90
|
+
};
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { type ParcelSize } from './parcel.js';
|
|
2
|
+
/**
|
|
3
|
+
* For tests and dry runs only, from `@extantape/payload-plugin-shipping/testing`, so a production bundle can't
|
|
4
|
+
* pick it by accident. A stand-in for EasyPost: nothing leaves the process. **Its prices are made up** (USPS-shaped,
|
|
5
|
+
* so the logic can be tested); every rate and label says `fake: true`.
|
|
6
|
+
*/
|
|
7
|
+
export declare function fakeZone(fromZip?: string, toZip?: string): number;
|
|
8
|
+
export declare function fakePrices(p: ParcelSize, zone: number): {
|
|
9
|
+
ground: number;
|
|
10
|
+
priority: number;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* A fake carrier: EasyPost's shapes answered in memory. `calls` records what was asked, for tests. `fail` makes a
|
|
14
|
+
* path answer with an error, `hang` makes it time out, and `offer` leaves services out of the rates.
|
|
15
|
+
*/
|
|
16
|
+
export declare function fakeCarrier(over?: {
|
|
17
|
+
mode?: 'test' | 'production';
|
|
18
|
+
refund?: 'submitted' | 'rejected';
|
|
19
|
+
webhookSecret?: string | null;
|
|
20
|
+
fail?: (path: string) => {
|
|
21
|
+
status: number;
|
|
22
|
+
code: string;
|
|
23
|
+
} | null;
|
|
24
|
+
hang?: (path: string) => boolean;
|
|
25
|
+
timeoutMs?: number;
|
|
26
|
+
offer?: (rate: {
|
|
27
|
+
carrier: string;
|
|
28
|
+
service: string;
|
|
29
|
+
}) => boolean;
|
|
30
|
+
}): {
|
|
31
|
+
provider: {
|
|
32
|
+
name: string;
|
|
33
|
+
mode: import("./types.js").Mode | null;
|
|
34
|
+
verify: (a: import("./address.js").LabelAddress) => Promise<import("./types.js").Verification>;
|
|
35
|
+
quote: (input: {
|
|
36
|
+
from: import("./address.js").LabelAddress;
|
|
37
|
+
to: import("./address.js").LabelAddress;
|
|
38
|
+
parcel: import("./types.js").Parcel;
|
|
39
|
+
carrier?: "any" | "USPS";
|
|
40
|
+
reference: string;
|
|
41
|
+
}) => Promise<import("./types.js").Quote>;
|
|
42
|
+
buy: (quote: import("./types.js").Quote) => Promise<import("./types.js").Label>;
|
|
43
|
+
refund: (shipmentId: string) => Promise<import("./types.js").RefundStatus>;
|
|
44
|
+
webhook?: {
|
|
45
|
+
configured: boolean;
|
|
46
|
+
verify: (raw: string, headers: Headers) => boolean | Promise<boolean>;
|
|
47
|
+
parse: (raw: string) => {
|
|
48
|
+
tracker?: import("./types.js").TrackerEvent;
|
|
49
|
+
refund?: import("./types.js").RefundEvent;
|
|
50
|
+
} | null;
|
|
51
|
+
};
|
|
52
|
+
};
|
|
53
|
+
calls: {
|
|
54
|
+
path: string;
|
|
55
|
+
body: Record<string, unknown>;
|
|
56
|
+
}[];
|
|
57
|
+
shipments: Map<string, {
|
|
58
|
+
id: string;
|
|
59
|
+
carrier: string;
|
|
60
|
+
service: string;
|
|
61
|
+
rate: string;
|
|
62
|
+
fake: true;
|
|
63
|
+
}[]>;
|
|
64
|
+
sign: (raw: string) => string;
|
|
65
|
+
};
|
package/dist/testing.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { createHmac, randomInt } from 'node:crypto';
|
|
2
|
+
import { easyPost } from './easypost.js';
|
|
3
|
+
import { billableLb } from './parcel.js';
|
|
4
|
+
/**
|
|
5
|
+
* For tests and dry runs only, from `@extantape/payload-plugin-shipping/testing`, so a production bundle can't
|
|
6
|
+
* pick it by accident. A stand-in for EasyPost: nothing leaves the process. **Its prices are made up** (USPS-shaped,
|
|
7
|
+
* so the logic can be tested); every rate and label says `fake: true`.
|
|
8
|
+
*/
|
|
9
|
+
export function fakeZone(fromZip = '', toZip = '') {
|
|
10
|
+
const a = Number(String(fromZip).slice(0, 3));
|
|
11
|
+
const b = Number(String(toZip).slice(0, 3));
|
|
12
|
+
if (!Number.isFinite(a) || !Number.isFinite(b))
|
|
13
|
+
return 5;
|
|
14
|
+
const remote = (z) => (z >= 995 && z <= 999) || z === 967 || z === 968;
|
|
15
|
+
if (remote(a) !== remote(b))
|
|
16
|
+
return 8;
|
|
17
|
+
return Math.min(8, 1 + Math.floor(Math.abs(a - b) / 120));
|
|
18
|
+
}
|
|
19
|
+
export function fakePrices(p, zone) {
|
|
20
|
+
const lb = billableLb(p);
|
|
21
|
+
const light = p.weightOz <= 15.99 && Math.round(p.lengthIn) * Math.round(p.widthIn) * Math.round(p.heightIn) <= 1728;
|
|
22
|
+
let ground = light ? 450 + zone * 25 + Math.ceil(p.weightOz / 4) * 20 : 700 + zone * 60 + (lb - 1) * (35 + zone * 12);
|
|
23
|
+
const long = Math.max(p.lengthIn, p.widthIn, p.heightIn);
|
|
24
|
+
const cubic = Math.round(p.lengthIn) * Math.round(p.widthIn) * Math.round(p.heightIn);
|
|
25
|
+
ground += Math.max(long > 30 ? 1500 : long > 22 ? 400 : 0, cubic > 3456 ? 1500 : 0);
|
|
26
|
+
return { ground, priority: Math.round(ground * 1.4) };
|
|
27
|
+
}
|
|
28
|
+
const API = 'https://api.easypost.com/v2';
|
|
29
|
+
const digits = (n) => Array.from({ length: n }, () => randomInt(10)).join('');
|
|
30
|
+
/**
|
|
31
|
+
* A fake carrier: EasyPost's shapes answered in memory. `calls` records what was asked, for tests. `fail` makes a
|
|
32
|
+
* path answer with an error, `hang` makes it time out, and `offer` leaves services out of the rates.
|
|
33
|
+
*/
|
|
34
|
+
export function fakeCarrier(over = {}) {
|
|
35
|
+
const shipments = new Map();
|
|
36
|
+
const calls = [];
|
|
37
|
+
const fetchImpl = (async (url, init) => {
|
|
38
|
+
const path = String(url).replace(API, '');
|
|
39
|
+
const body = (init?.body ? JSON.parse(String(init.body)) : {});
|
|
40
|
+
calls.push({ path, body });
|
|
41
|
+
if (over.hang?.(path)) {
|
|
42
|
+
await new Promise((_, reject) => init?.signal?.addEventListener('abort', () => reject(Object.assign(new Error('timed out'), { name: 'TimeoutError' }))));
|
|
43
|
+
}
|
|
44
|
+
const json = (status, reply) => new Response(JSON.stringify(reply), { status, headers: { 'Content-Type': 'application/json' } });
|
|
45
|
+
const failure = over.fail?.(path);
|
|
46
|
+
if (failure)
|
|
47
|
+
return json(failure.status, { error: { code: failure.code, message: 'made-up failure' } });
|
|
48
|
+
if (path === '/shipments') {
|
|
49
|
+
const s = (body.shipment ?? {});
|
|
50
|
+
const p = s.parcel ?? {};
|
|
51
|
+
const size = { lengthIn: p.length ?? 6, widthIn: p.width ?? 6, heightIn: p.height ?? 2, weightOz: p.weight ?? 1 };
|
|
52
|
+
const { ground, priority } = fakePrices(size, fakeZone(s.from_address?.zip, s.to_address?.zip));
|
|
53
|
+
const id = `shp_fake${digits(10)}`;
|
|
54
|
+
const rates = [
|
|
55
|
+
{ id: `rate_g${digits(8)}`, carrier: 'USPS', service: 'GroundAdvantage', rate: (ground / 100).toFixed(2), fake: true },
|
|
56
|
+
{ id: `rate_p${digits(8)}`, carrier: 'USPS', service: 'Priority', rate: (priority / 100).toFixed(2), fake: true },
|
|
57
|
+
{ id: `rate_u${digits(8)}`, carrier: 'UPS', service: 'Ground', rate: ((ground - 50) / 100).toFixed(2), fake: true },
|
|
58
|
+
].filter((r) => over.offer?.(r) ?? true);
|
|
59
|
+
shipments.set(id, rates);
|
|
60
|
+
return json(201, { id, rates });
|
|
61
|
+
}
|
|
62
|
+
const buy = path.match(/^\/shipments\/([^/]+)\/buy$/);
|
|
63
|
+
if (buy) {
|
|
64
|
+
const chosen = shipments.get(buy[1])?.find((r) => r.id === body.rate?.id);
|
|
65
|
+
if (!chosen)
|
|
66
|
+
return json(422, { error: { code: 'SHIPMENT.RATE.INVALID', message: 'That rate isn’t on this shipment.' } });
|
|
67
|
+
return json(200, { id: buy[1], tracking_code: `9400${digits(18)}`, postage_label: { label_url: `https://example.invalid/labels/${buy[1]}.pdf` }, tracker: { public_url: `https://example.invalid/track/${buy[1]}` }, selected_rate: chosen });
|
|
68
|
+
}
|
|
69
|
+
const refund = path.match(/^\/shipments\/([^/]+)\/refund$/);
|
|
70
|
+
if (refund)
|
|
71
|
+
return json(200, { id: refund[1], refund_status: over.refund ?? 'submitted' });
|
|
72
|
+
if (path === '/addresses') {
|
|
73
|
+
const a = (body.address ?? {});
|
|
74
|
+
return json(201, { ...a, verifications: { delivery: { success: true, errors: [] } } });
|
|
75
|
+
}
|
|
76
|
+
return json(404, { error: { code: 'NOT_FOUND', message: 'not answered' } });
|
|
77
|
+
});
|
|
78
|
+
const secret = over.webhookSecret === undefined ? 'a-made-up-webhook-secret' : over.webhookSecret;
|
|
79
|
+
const provider = easyPost({ apiKey: over.mode === 'production' ? 'EZAK_made_up' : 'EZTK_made_up', webhookSecret: secret, fetchImpl, timeoutMs: over.timeoutMs });
|
|
80
|
+
/** Signs a body the way EasyPost does, for webhook tests. */
|
|
81
|
+
const sign = (raw) => `hmac-sha256-hex=${createHmac('sha256', String(secret).normalize('NFKD')).update(raw, 'utf8').digest('hex')}`;
|
|
82
|
+
return { provider: { ...provider, name: 'fake' }, calls, shipments, sign };
|
|
83
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { TrackerStatus } from './types.js';
|
|
2
|
+
/** The carrier's public tracking page for a number. UPS numbers start with 1Z; everything else is taken as USPS. */
|
|
3
|
+
export declare function trackingLink(number: string, carrier?: string | null): string;
|
|
4
|
+
export type ShipmentEvent = 'out-for-delivery' | 'delivered' | 'exception';
|
|
5
|
+
/** Which customer notice a carrier status means, if any. "Available for pickup" is delivered to a PO Box or General Delivery. */
|
|
6
|
+
export declare function noticeFor(status: TrackerStatus): ShipmentEvent | null;
|
|
7
|
+
/** USPS refund window for an unused label, in days. */
|
|
8
|
+
export declare const USPS_REFUND_DAYS = 30;
|
package/dist/tracking.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** The carrier's public tracking page for a number. UPS numbers start with 1Z; everything else is taken as USPS. */
|
|
2
|
+
export function trackingLink(number, carrier) {
|
|
3
|
+
const n = number.replace(/\s/g, '').toUpperCase();
|
|
4
|
+
if (carrier?.toUpperCase() === 'UPS' || (!carrier && /^1Z[0-9A-Z]{16}$/.test(n)))
|
|
5
|
+
return `https://www.ups.com/track?tracknum=${encodeURIComponent(n)}`;
|
|
6
|
+
return `https://tools.usps.com/go/TrackConfirmAction?tLabels=${encodeURIComponent(n)}`;
|
|
7
|
+
}
|
|
8
|
+
/** Which customer notice a carrier status means, if any. "Available for pickup" is delivered to a PO Box or General Delivery. */
|
|
9
|
+
export function noticeFor(status) {
|
|
10
|
+
if (status === 'out_for_delivery')
|
|
11
|
+
return 'out-for-delivery';
|
|
12
|
+
if (status === 'delivered' || status === 'available_for_pickup')
|
|
13
|
+
return 'delivered';
|
|
14
|
+
if (status === 'return_to_sender' || status === 'failure' || status === 'error')
|
|
15
|
+
return 'exception';
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
/** USPS refund window for an unused label, in days. */
|
|
19
|
+
export const USPS_REFUND_DAYS = 30;
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import type { Payload, PayloadRequest } from 'payload';
|
|
2
|
+
import type { LabelAddress } from './address.js';
|
|
3
|
+
export type Req = Partial<PayloadRequest>;
|
|
4
|
+
export type Mode = 'test' | 'production';
|
|
5
|
+
export type Parcel = {
|
|
6
|
+
weightOz: number;
|
|
7
|
+
lengthIn?: number | null;
|
|
8
|
+
widthIn?: number | null;
|
|
9
|
+
heightIn?: number | null;
|
|
10
|
+
};
|
|
11
|
+
export type Rate = {
|
|
12
|
+
id: string;
|
|
13
|
+
carrier: string;
|
|
14
|
+
service: string;
|
|
15
|
+
rate: string;
|
|
16
|
+
fake?: boolean;
|
|
17
|
+
};
|
|
18
|
+
export type Quote = {
|
|
19
|
+
shipmentId: string;
|
|
20
|
+
rate: Rate;
|
|
21
|
+
rateCents: number;
|
|
22
|
+
mode: Mode;
|
|
23
|
+
fake?: boolean;
|
|
24
|
+
};
|
|
25
|
+
export type Label = {
|
|
26
|
+
shipmentId: string;
|
|
27
|
+
tracking: string;
|
|
28
|
+
carrier: string;
|
|
29
|
+
service: string;
|
|
30
|
+
rateCents: number;
|
|
31
|
+
labelUrl: string;
|
|
32
|
+
trackerUrl: string | null;
|
|
33
|
+
mode: Mode;
|
|
34
|
+
fake?: boolean;
|
|
35
|
+
};
|
|
36
|
+
export type RefundStatus = 'submitted' | 'refunded' | 'rejected' | 'not_applicable';
|
|
37
|
+
export type Verification = {
|
|
38
|
+
ok: boolean;
|
|
39
|
+
errors: string[];
|
|
40
|
+
corrected: {
|
|
41
|
+
street1?: string;
|
|
42
|
+
zip?: string;
|
|
43
|
+
} | null;
|
|
44
|
+
};
|
|
45
|
+
export type TrackerStatus = 'unknown' | 'pre_transit' | 'in_transit' | 'out_for_delivery' | 'delivered' | 'available_for_pickup' | 'return_to_sender' | 'failure' | 'cancelled' | 'error';
|
|
46
|
+
export type TrackerEvent = {
|
|
47
|
+
id: string;
|
|
48
|
+
createdAt: string;
|
|
49
|
+
tracking: string;
|
|
50
|
+
status: TrackerStatus;
|
|
51
|
+
carrier: string | null;
|
|
52
|
+
publicUrl: string | null;
|
|
53
|
+
};
|
|
54
|
+
export type RefundEvent = {
|
|
55
|
+
id: string;
|
|
56
|
+
createdAt: string;
|
|
57
|
+
tracking: string;
|
|
58
|
+
status: RefundStatus;
|
|
59
|
+
};
|
|
60
|
+
/** What a carrier provider does. EasyPost is the first; the fake one is for tests. */
|
|
61
|
+
export type CarrierProvider = {
|
|
62
|
+
name: string;
|
|
63
|
+
/** test or production, from the key. Null when not set up. */
|
|
64
|
+
mode: Mode | null;
|
|
65
|
+
verify: (a: LabelAddress) => Promise<Verification>;
|
|
66
|
+
quote: (input: {
|
|
67
|
+
from: LabelAddress;
|
|
68
|
+
to: LabelAddress;
|
|
69
|
+
parcel: Parcel;
|
|
70
|
+
carrier?: 'any' | 'USPS';
|
|
71
|
+
reference: string;
|
|
72
|
+
}) => Promise<Quote>;
|
|
73
|
+
buy: (quote: Quote) => Promise<Label>;
|
|
74
|
+
refund: (shipmentId: string) => Promise<RefundStatus>;
|
|
75
|
+
/** Webhooks: is this raw body signed by the carrier, and what does it say? */
|
|
76
|
+
webhook?: {
|
|
77
|
+
configured: boolean;
|
|
78
|
+
/** Is the raw body signed by the carrier? Answer exactly `true` (or a promise of it) for yes; anything else, a throw included, is a 401. */
|
|
79
|
+
verify: (raw: string, headers: Headers) => boolean | Promise<boolean>;
|
|
80
|
+
parse: (raw: string) => {
|
|
81
|
+
tracker?: TrackerEvent;
|
|
82
|
+
refund?: RefundEvent;
|
|
83
|
+
} | null;
|
|
84
|
+
};
|
|
85
|
+
};
|
|
86
|
+
export type ExternalAction = 'verify' | 'quote' | 'buy' | 'refund';
|
|
87
|
+
/** An owner's handler for webhook events. Must be idempotent: carriers retry. 'unknown' when it isn't theirs. */
|
|
88
|
+
export type ShippingHandler = {
|
|
89
|
+
owner: string;
|
|
90
|
+
onTracker?: (args: {
|
|
91
|
+
event: TrackerEvent;
|
|
92
|
+
req: PayloadRequest;
|
|
93
|
+
payload: Payload;
|
|
94
|
+
}) => Promise<'handled' | 'unknown'>;
|
|
95
|
+
onRefund?: (args: {
|
|
96
|
+
event: RefundEvent;
|
|
97
|
+
req: PayloadRequest;
|
|
98
|
+
payload: Payload;
|
|
99
|
+
}) => Promise<'handled' | 'unknown'>;
|
|
100
|
+
};
|
|
101
|
+
export type ShippingOptions = {
|
|
102
|
+
provider: CarrierProvider;
|
|
103
|
+
/** A root endpoint path. Default '/easypost/webhook', so it serves /api/easypost/webhook. */
|
|
104
|
+
webhookPath?: string;
|
|
105
|
+
/** Runs before every call that costs money or reaches the carrier. Throw to refuse. Without it, production mode is refused. */
|
|
106
|
+
beforeExternalCall?: (args: {
|
|
107
|
+
action: ExternalAction;
|
|
108
|
+
mode: Mode;
|
|
109
|
+
req?: Req;
|
|
110
|
+
}) => void | Promise<void>;
|
|
111
|
+
handlers?: ShippingHandler[];
|
|
112
|
+
/** Events older than this are ignored, so a captured body can't be replayed later. Default 7. */
|
|
113
|
+
maxEventAgeDays?: number;
|
|
114
|
+
};
|
|
115
|
+
export type Resolved = Required<Pick<ShippingOptions, 'provider' | 'webhookPath' | 'maxEventAgeDays'>> & {
|
|
116
|
+
beforeExternalCall?: ShippingOptions['beforeExternalCall'];
|
|
117
|
+
handlers: ShippingHandler[];
|
|
118
|
+
};
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,69 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@extantape/payload-plugin-shipping",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Shipping for Payload: addresses, carrier rates, labels, refunds of unused labels and tracking webhooks, with EasyPost as the first carrier provider.",
|
|
5
|
+
"homepage": "https://github.com/ExtantApe/payload-plugin-shipping#readme",
|
|
6
|
+
"bugs": {
|
|
7
|
+
"url": "https://github.com/ExtantApe/payload-plugin-shipping/issues"
|
|
8
|
+
},
|
|
9
|
+
"keywords": [
|
|
10
|
+
"payload",
|
|
11
|
+
"payload-plugin",
|
|
12
|
+
"payloadcms",
|
|
13
|
+
"ecommerce",
|
|
14
|
+
"integrations",
|
|
15
|
+
"shipping",
|
|
16
|
+
"easypost",
|
|
17
|
+
"usps",
|
|
18
|
+
"postage",
|
|
19
|
+
"shipping-labels",
|
|
20
|
+
"tracking",
|
|
21
|
+
"webhooks"
|
|
22
|
+
],
|
|
23
|
+
"license": "MIT",
|
|
24
|
+
"repository": {
|
|
25
|
+
"type": "git",
|
|
26
|
+
"url": "git+https://github.com/ExtantApe/payload-plugin-shipping.git"
|
|
27
|
+
},
|
|
28
|
+
"type": "module",
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"import": "./dist/index.js"
|
|
33
|
+
},
|
|
34
|
+
"./testing": {
|
|
35
|
+
"types": "./dist/testing.d.ts",
|
|
36
|
+
"import": "./dist/testing.js"
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
"main": "./dist/index.js",
|
|
40
|
+
"types": "./dist/index.d.ts",
|
|
41
|
+
"files": [
|
|
42
|
+
"dist",
|
|
43
|
+
"README.md",
|
|
44
|
+
"LICENSE"
|
|
45
|
+
],
|
|
46
|
+
"engines": {
|
|
47
|
+
"node": ">=22"
|
|
48
|
+
},
|
|
49
|
+
"scripts": {
|
|
50
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json",
|
|
51
|
+
"typecheck": "tsc --noEmit",
|
|
52
|
+
"test": "vitest run",
|
|
53
|
+
"leak-check": "bash scripts/leak-check.sh",
|
|
54
|
+
"prepack": "npm run build",
|
|
55
|
+
"prepublishOnly": "npm run typecheck && npm test"
|
|
56
|
+
},
|
|
57
|
+
"peerDependencies": {
|
|
58
|
+
"payload": "^3.80.0"
|
|
59
|
+
},
|
|
60
|
+
"devDependencies": {
|
|
61
|
+
"@payloadcms/db-mongodb": "3.92.1",
|
|
62
|
+
"@types/node": "^24.0.0",
|
|
63
|
+
"graphql": "^16.14.2",
|
|
64
|
+
"mongodb-memory-server": "^11.3.0",
|
|
65
|
+
"payload": "3.92.1",
|
|
66
|
+
"typescript": "^5.9.0",
|
|
67
|
+
"vitest": "^3.2.0"
|
|
68
|
+
}
|
|
69
|
+
}
|