@shopnex/cj-plugin 1.0.1 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +110 -0
- package/dist/CjConfig.d.ts +7 -0
- package/dist/CjConfig.js +93 -0
- package/dist/CjConfig.js.map +1 -0
- package/dist/api-client.d.ts +2 -0
- package/dist/api-client.js +27 -0
- package/dist/api-client.js.map +1 -0
- package/dist/auth.d.ts +15 -0
- package/dist/auth.js +47 -0
- package/dist/auth.js.map +1 -0
- package/dist/cj-settings.d.ts +2 -0
- package/dist/cj-settings.js +90 -0
- package/dist/cj-settings.js.map +1 -0
- package/dist/error-handler.d.ts +12 -0
- package/dist/error-handler.js +41 -0
- package/dist/error-handler.js.map +1 -0
- package/dist/error-types.d.ts +20 -0
- package/dist/error-types.js +7 -0
- package/dist/error-types.js.map +1 -0
- package/dist/exports/rsc.d.ts +1 -0
- package/dist/exports/rsc.js +3 -0
- package/dist/exports/rsc.js.map +1 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +56 -0
- package/dist/index.js.map +1 -0
- package/dist/rsc/ApiToken.d.ts +9 -0
- package/dist/rsc/ApiToken.js +21 -0
- package/dist/rsc/ApiToken.js.map +1 -0
- package/dist/rsc/ApiToken.scss +5 -0
- package/dist/sdk/access-token.d.ts +9 -0
- package/dist/sdk/access-token.js +24 -0
- package/dist/sdk/access-token.js.map +1 -0
- package/dist/sdk/cj-sdk.d.ts +4 -0
- package/dist/sdk/cj-sdk.js +6 -0
- package/dist/sdk/cj-sdk.js.map +1 -0
- package/dist/sdk/dispute/dispute-types.d.ts +64 -0
- package/dist/sdk/dispute/dispute-types.js +4 -0
- package/dist/sdk/dispute/dispute-types.js.map +1 -0
- package/dist/sdk/dispute/dispute.d.ts +4 -0
- package/dist/sdk/dispute/dispute.js +52 -0
- package/dist/sdk/dispute/dispute.js.map +1 -0
- package/dist/sdk/inventory/inventory-types.d.ts +7 -0
- package/dist/sdk/inventory/inventory-types.js +3 -0
- package/dist/sdk/inventory/inventory-types.js.map +1 -0
- package/dist/sdk/inventory/inventory.d.ts +3 -0
- package/dist/sdk/inventory/inventory.js +41 -0
- package/dist/sdk/inventory/inventory.js.map +1 -0
- package/dist/sdk/orders/order-types.d.ts +135 -0
- package/dist/sdk/orders/order-types.js +3 -0
- package/dist/sdk/orders/order-types.js.map +1 -0
- package/dist/sdk/orders/orders.d.ts +16 -0
- package/dist/sdk/orders/orders.js +167 -0
- package/dist/sdk/orders/orders.js.map +1 -0
- package/dist/sdk/products/product-types.d.ts +186 -0
- package/dist/sdk/products/product-types.js +5 -0
- package/dist/sdk/products/product-types.js.map +1 -0
- package/dist/sdk/products/products.d.ts +9 -0
- package/dist/sdk/products/products.js +96 -0
- package/dist/sdk/products/products.js.map +1 -0
- package/dist/sdk/settings/settings-api.d.ts +2 -0
- package/dist/sdk/settings/settings-api.js +20 -0
- package/dist/sdk/settings/settings-api.js.map +1 -0
- package/dist/sdk/settings/settings-types.d.ts +22 -0
- package/dist/sdk/settings/settings-types.js +3 -0
- package/dist/sdk/settings/settings-types.js.map +1 -0
- package/dist/sdk/variants/variant-types.d.ts +18 -0
- package/dist/sdk/variants/variant-types.js +3 -0
- package/dist/sdk/variants/variant-types.js.map +1 -0
- package/dist/sdk/variants/variants.d.ts +8 -0
- package/dist/sdk/variants/variants.js +76 -0
- package/dist/sdk/variants/variants.js.map +1 -0
- package/dist/service/convert-html-to-lexical.d.ts +0 -0
- package/dist/service/convert-html-to-lexical.js +75 -0
- package/dist/service/convert-html-to-lexical.js.map +1 -0
- package/dist/service/create-order.hook.d.ts +12 -0
- package/dist/service/create-order.hook.js +70 -0
- package/dist/service/create-order.hook.js.map +1 -0
- package/dist/service/sync-products.d.ts +4 -0
- package/dist/service/sync-products.js +148 -0
- package/dist/service/sync-products.js.map +1 -0
- package/dist/types.d.ts +74 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -0
- package/dist/ui/refund-button.d.ts +3 -0
- package/dist/ui/refund-button.js +24 -0
- package/dist/ui/refund-button.js.map +1 -0
- package/dist/util/manage-tokens.d.ts +4 -0
- package/dist/util/manage-tokens.js +41 -0
- package/dist/util/manage-tokens.js.map +1 -0
- package/package.json +1 -1
package/README.md
ADDED
@@ -0,0 +1,110 @@
|
|
1
|
+
# CJ Dropshipping Plugin for Payload CMS
|
2
|
+
|
3
|
+
This plugin integrates **CJ Dropshipping** into your **Payload CMS** project by:
|
4
|
+
|
5
|
+
- Adding "CJ" as a product source.
|
6
|
+
- Automatically creating CJ orders after local orders are created.
|
7
|
+
- (Optionally) generating a `cj-settings` collection for managing API credentials dynamically.
|
8
|
+
- Syncing CJ credentials on app initialization.
|
9
|
+
|
10
|
+
---
|
11
|
+
|
12
|
+
## Installation
|
13
|
+
|
14
|
+
```bash
|
15
|
+
pnpm install @shopnex/cj-plugin
|
16
|
+
```
|
17
|
+
|
18
|
+
or
|
19
|
+
|
20
|
+
```bash
|
21
|
+
npm install @shopnex/cj-plugin
|
22
|
+
```
|
23
|
+
|
24
|
+
or
|
25
|
+
|
26
|
+
```bash
|
27
|
+
yarn add @shopnex/cj-plugin
|
28
|
+
```
|
29
|
+
|
30
|
+
---
|
31
|
+
|
32
|
+
## Usage
|
33
|
+
|
34
|
+
Import and add the `cjPlugin` to your Payload config:
|
35
|
+
|
36
|
+
```ts
|
37
|
+
import { buildConfig } from "payload/config";
|
38
|
+
import { cjPlugin } from "@shopnex/cj-plugin";
|
39
|
+
|
40
|
+
export default buildConfig({
|
41
|
+
collections: [
|
42
|
+
// your collections
|
43
|
+
],
|
44
|
+
plugins: [
|
45
|
+
cjPlugin({
|
46
|
+
cjApiKey: "your-cj-api-key",
|
47
|
+
cjEmailAddress: "your-email@example.com",
|
48
|
+
cjRefreshToken: "optional-refresh-token", // optional
|
49
|
+
asCollection: true, // optional - creates a cj-settings collection
|
50
|
+
collectionOverrides: {
|
51
|
+
// optional - override fields or settings for the cj-settings collection
|
52
|
+
},
|
53
|
+
}),
|
54
|
+
],
|
55
|
+
});
|
56
|
+
```
|
57
|
+
|
58
|
+
---
|
59
|
+
|
60
|
+
## Plugin Options
|
61
|
+
|
62
|
+
| Option | Type | Required | Description |
|
63
|
+
| --------------------- | --------- | -------- | ------------------------------------------------------------------------------------------------------- |
|
64
|
+
| `cjApiKey` | `string` | Yes | Your CJ Dropshipping API key. |
|
65
|
+
| `cjEmailAddress` | `string` | Yes | Your CJ account email address. |
|
66
|
+
| `cjRefreshToken` | `string` | No | Your CJ refresh token if available. |
|
67
|
+
| `asCollection` | `boolean` | No | If true, automatically creates a `cj-settings` collection to manage CJ API credentials per tenant/shop. |
|
68
|
+
| `collectionOverrides` | `object` | No | Allows overriding the default `cj-settings` collection config (fields, hooks, etc). |
|
69
|
+
|
70
|
+
---
|
71
|
+
|
72
|
+
## What the Plugin Does
|
73
|
+
|
74
|
+
- **Modifies the `products` collection**:
|
75
|
+
- Adds a `source` option: `{ label: 'CJ', value: 'cj' }`.
|
76
|
+
- **Hooks into the `orders` collection**:
|
77
|
+
- On every new order or update, triggers the CJ order creation logic automatically.
|
78
|
+
- **Manages CJ credentials dynamically**:
|
79
|
+
- On Payload startup (`onInit`), loads all `cj-settings` documents and sets up credentials per shop.
|
80
|
+
- **Optional `cj-settings` collection**:
|
81
|
+
- If `asCollection` is true, a new `cj-settings` collection will be added automatically.
|
82
|
+
- Useful for multi-tenant setups or dynamically changing credentials.
|
83
|
+
|
84
|
+
---
|
85
|
+
|
86
|
+
## Example: cj-settings Collection
|
87
|
+
|
88
|
+
If `asCollection: true`, the following collection will be generated by default:
|
89
|
+
|
90
|
+
| Field | Type | Description |
|
91
|
+
| ---------- | -------- | --------------------------------- |
|
92
|
+
| `shop` | Relation | Reference to your shop or tenant. |
|
93
|
+
| `email` | Text | Your CJ email address. |
|
94
|
+
| `apiToken` | Text | Your CJ API key. |
|
95
|
+
|
96
|
+
You can override this structure with `collectionOverrides`.
|
97
|
+
|
98
|
+
---
|
99
|
+
|
100
|
+
## Notes
|
101
|
+
|
102
|
+
- The plugin assumes you have a `products` collection with a `source` select field already created.
|
103
|
+
- It assumes you have an `orders` collection.
|
104
|
+
- Make sure the `source` field in `products` uses a `select` type with `options` array.
|
105
|
+
|
106
|
+
---
|
107
|
+
|
108
|
+
## License
|
109
|
+
|
110
|
+
MIT
|
package/dist/CjConfig.js
ADDED
@@ -0,0 +1,93 @@
|
|
1
|
+
import { decryptToken, encryptToken } from "./util/manage-tokens";
|
2
|
+
import { syncProducts } from "./service/sync-products";
|
3
|
+
export const CjConfigCollection = ({ overrides })=>({
|
4
|
+
slug: "cj-settings",
|
5
|
+
access: {
|
6
|
+
...overrides?.access
|
7
|
+
},
|
8
|
+
admin: {
|
9
|
+
group: "Plugins"
|
10
|
+
},
|
11
|
+
fields: [
|
12
|
+
{
|
13
|
+
label: "Credentials",
|
14
|
+
type: "collapsible",
|
15
|
+
fields: [
|
16
|
+
{
|
17
|
+
type: "row",
|
18
|
+
fields: [
|
19
|
+
{
|
20
|
+
name: "emailAddress",
|
21
|
+
type: "text"
|
22
|
+
},
|
23
|
+
{
|
24
|
+
name: "apiToken",
|
25
|
+
type: "text",
|
26
|
+
admin: {
|
27
|
+
components: {
|
28
|
+
Field: "@shopnex/cj-plugin/rsc#ApiToken"
|
29
|
+
}
|
30
|
+
}
|
31
|
+
}
|
32
|
+
]
|
33
|
+
}
|
34
|
+
]
|
35
|
+
},
|
36
|
+
{
|
37
|
+
label: "Logo Area POD",
|
38
|
+
name: "pod",
|
39
|
+
type: "upload",
|
40
|
+
relationTo: "media"
|
41
|
+
},
|
42
|
+
{
|
43
|
+
name: "items",
|
44
|
+
type: "array",
|
45
|
+
admin: {
|
46
|
+
description: "A list of product URLs to sync with CJ Dropshipping"
|
47
|
+
},
|
48
|
+
fields: [
|
49
|
+
{
|
50
|
+
name: "productUrl",
|
51
|
+
type: "text"
|
52
|
+
}
|
53
|
+
],
|
54
|
+
label: "Products",
|
55
|
+
labels: {
|
56
|
+
plural: "Product URLs",
|
57
|
+
singular: "Product URL"
|
58
|
+
}
|
59
|
+
}
|
60
|
+
],
|
61
|
+
hooks: {
|
62
|
+
beforeChange: [
|
63
|
+
({ data })=>{
|
64
|
+
const tokenToEncrypt = data.apiToken;
|
65
|
+
const encryptedToken = encryptToken(tokenToEncrypt);
|
66
|
+
data.apiToken = encryptedToken;
|
67
|
+
}
|
68
|
+
],
|
69
|
+
beforeRead: [
|
70
|
+
({ doc })=>{
|
71
|
+
doc.apiToken = doc?.apiToken && decryptToken(doc.apiToken);
|
72
|
+
}
|
73
|
+
],
|
74
|
+
afterChange: [
|
75
|
+
async ({ doc, req: { payload } })=>{
|
76
|
+
const productIds = doc.items.map((item)=>{
|
77
|
+
const match = item.productUrl.match(/(?<=-p-)([0-9A-Fa-f-]+)(?=\.html)/);
|
78
|
+
return match ? match[0] : null;
|
79
|
+
});
|
80
|
+
await syncProducts(productIds, payload);
|
81
|
+
},
|
82
|
+
({ doc })=>{
|
83
|
+
doc.apiToken = doc.apiToken && decryptToken(doc.apiToken);
|
84
|
+
}
|
85
|
+
]
|
86
|
+
},
|
87
|
+
labels: {
|
88
|
+
singular: "CJ Dropshipping",
|
89
|
+
plural: "CJ Configs"
|
90
|
+
}
|
91
|
+
});
|
92
|
+
|
93
|
+
//# sourceMappingURL=CjConfig.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"sources":["../src/CjConfig.ts"],"sourcesContent":["import { CollectionConfig } from \"payload\";\nimport { decryptToken, encryptToken } from \"./util/manage-tokens\";\nimport { syncProducts } from \"./service/sync-products\";\n\nexport type CjCollectionProps = {\n overrides?: {\n access: CollectionConfig[\"access\"];\n };\n};\n\nexport const CjConfigCollection = ({ overrides }: CjCollectionProps): CollectionConfig => ({\n slug: \"cj-settings\",\n access: {\n ...overrides?.access,\n },\n admin: {\n group: \"Plugins\",\n },\n fields: [\n {\n label: \"Credentials\",\n type: \"collapsible\",\n fields: [\n {\n type: \"row\",\n fields: [\n {\n name: \"emailAddress\",\n type: \"text\",\n },\n {\n name: \"apiToken\",\n type: \"text\",\n admin: {\n components: {\n Field: \"@shopnex/cj-plugin/rsc#ApiToken\",\n },\n },\n },\n ],\n },\n ],\n },\n {\n label: \"Logo Area POD\",\n name: \"pod\",\n type: \"upload\",\n relationTo: \"media\",\n },\n {\n name: \"items\",\n type: \"array\",\n admin: {\n description: \"A list of product URLs to sync with CJ Dropshipping\",\n },\n fields: [\n {\n name: \"productUrl\",\n type: \"text\",\n },\n ],\n label: \"Products\",\n labels: {\n plural: \"Product URLs\",\n singular: \"Product URL\",\n },\n },\n ],\n hooks: {\n beforeChange: [\n ({ data }) => {\n const tokenToEncrypt = data.apiToken;\n const encryptedToken = encryptToken(tokenToEncrypt);\n data.apiToken = encryptedToken;\n },\n ],\n beforeRead: [\n ({ doc }) => {\n doc.apiToken = doc?.apiToken && decryptToken(doc.apiToken);\n },\n ],\n afterChange: [\n async ({ doc, req: { payload } }) => {\n const productIds = doc.items.map((item: any) => {\n const match = item.productUrl.match(/(?<=-p-)([0-9A-Fa-f-]+)(?=\\.html)/);\n return match ? match[0] : null;\n });\n await syncProducts(productIds, payload);\n },\n ({ doc }) => {\n doc.apiToken = doc.apiToken && decryptToken(doc.apiToken);\n },\n ],\n },\n labels: {\n singular: \"CJ Dropshipping\",\n plural: \"CJ Configs\",\n },\n});\n"],"names":["decryptToken","encryptToken","syncProducts","CjConfigCollection","overrides","slug","access","admin","group","fields","label","type","name","components","Field","relationTo","description","labels","plural","singular","hooks","beforeChange","data","tokenToEncrypt","apiToken","encryptedToken","beforeRead","doc","afterChange","req","payload","productIds","items","map","item","match","productUrl"],"mappings":"AACA,SAASA,YAAY,EAAEC,YAAY,QAAQ,uBAAuB;AAClE,SAASC,YAAY,QAAQ,0BAA0B;AAQvD,OAAO,MAAMC,qBAAqB,CAAC,EAAEC,SAAS,EAAqB,GAAwB,CAAA;QACvFC,MAAM;QACNC,QAAQ;YACJ,GAAGF,WAAWE,MAAM;QACxB;QACAC,OAAO;YACHC,OAA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UAAU;YACVD,QAAQ;QACZ;IACJ,CAAA,EAAG"}
|
@@ -0,0 +1,27 @@
|
|
1
|
+
import axios from 'axios';
|
2
|
+
import { handleCJError } from './error-handler';
|
3
|
+
export const cjApiClient = axios.create({
|
4
|
+
baseURL: 'https://developers.cjdropshipping.com/api2.0/v1/',
|
5
|
+
headers: {
|
6
|
+
'Content-Type': 'application/json'
|
7
|
+
},
|
8
|
+
timeout: 20000
|
9
|
+
});
|
10
|
+
// Response interceptor for automatic error handling
|
11
|
+
cjApiClient.interceptors.response.use((response)=>{
|
12
|
+
if (response.data.code !== 200) {
|
13
|
+
handleCJError(response.data);
|
14
|
+
}
|
15
|
+
return response;
|
16
|
+
}, (error)=>{
|
17
|
+
if (error.response) {
|
18
|
+
// Handle CJ API errors
|
19
|
+
handleCJError(error.response.data);
|
20
|
+
} else if (error.request) {
|
21
|
+
throw new Error('Network error: No response from CJ API');
|
22
|
+
} else {
|
23
|
+
throw new Error(`Axios error: ${error.message}`);
|
24
|
+
}
|
25
|
+
});
|
26
|
+
|
27
|
+
//# sourceMappingURL=api-client.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"sources":["../src/api-client.ts"],"sourcesContent":["import axios, { type AxiosError, type AxiosInstance, type AxiosResponse } from 'axios'\n\nimport { handleCJError } from './error-handler'\n\nexport const cjApiClient: AxiosInstance = axios.create({\n baseURL: 'https://developers.cjdropshipping.com/api2.0/v1/',\n headers: {\n 'Content-Type': 'application/json',\n },\n timeout: 20000,\n})\n \n// Response interceptor for automatic error handling\ncjApiClient.interceptors.response.use(\n (response: AxiosResponse) => {\n if (response.data.code !== 200) {\n handleCJError(response.data)\n }\n return response\n },\n (error: AxiosError) => {\n if (error.response) {\n // Handle CJ API errors\n handleCJError(error.response.data as { code: number; message?: string })\n } else if (error.request) {\n throw new Error('Network error: No response from CJ API')\n } else {\n throw new Error(`Axios error: ${error.message}`)\n }\n },\n)\n"],"names":["axios","handleCJError","cjApiClient","create","baseURL","headers","timeout","interceptors","response","use","data","code","error","request","Error","message"],"mappings":"AAAA,OAAOA,WAAwE,QAAO;AAEtF,SAASC,aAAa,QAAQ,kBAAiB;AAE/C,OAAO,MAAMC,cAA6BF,MAAMG,MAAM,CAAC;IACrDC,SAAS;IACTC,SAAS;QACP,gBAAgB;IAClB;IACAC,SAAS;AACX,GAAE;AAEF,oDAAoD;AACpDJ,YAAYK,YAAY,CAACC,QAAQ,CAACC,GAAG,CACnC,CAACD;IACC,IAAIA,SAASE,IAAI,CAACC,IAAI,KAAK,KAAK;QAC9BV,cAAcO,SAASE,IAAI;IAC7B;IACA,OAAOF;AACT,GACA,CAACI;IACC,IAAIA,MAAMJ,QAAQ,EAAE;QAClB,uBAAuB;QACvBP,cAAcW,MAAMJ,QAAQ,CAACE,IAAI;IACnC,OAAO,IAAIE,MAAMC,OAAO,EAAE;QACxB,MAAM,IAAIC,MAAM;IAClB,OAAO;QACL,MAAM,IAAIA,MAAM,CAAC,aAAa,EAAEF,MAAMG,OAAO,EAAE;IACjD;AACF"}
|
package/dist/auth.d.ts
ADDED
@@ -0,0 +1,15 @@
|
|
1
|
+
export declare function getAccessToken(email: string, password: string): Promise<{
|
2
|
+
accessToken: string;
|
3
|
+
accessTokenExpiryDate: string | Date;
|
4
|
+
refreshToken: string;
|
5
|
+
refreshTokenExpiryDate: string | Date;
|
6
|
+
createDate: string;
|
7
|
+
}>;
|
8
|
+
export declare function refreshAccessToken(refreshToken: string): Promise<{
|
9
|
+
accessToken: string;
|
10
|
+
accessTokenExpiryDate: string;
|
11
|
+
createDate: string;
|
12
|
+
refreshToken: string;
|
13
|
+
refreshTokenExpiryDate: string;
|
14
|
+
}>;
|
15
|
+
export declare function logout(accessToken: string): Promise<void>;
|
package/dist/auth.js
ADDED
@@ -0,0 +1,47 @@
|
|
1
|
+
import { cjApiClient } from './api-client';
|
2
|
+
export async function getAccessToken(email, password) {
|
3
|
+
try {
|
4
|
+
const response = await cjApiClient.post('authentication/getAccessToken', {
|
5
|
+
email,
|
6
|
+
password
|
7
|
+
});
|
8
|
+
if (!response.data.data?.accessToken) {
|
9
|
+
throw new Error('Failed to fetch access token');
|
10
|
+
}
|
11
|
+
// TODO: add logger
|
12
|
+
// console.log('Access Token:', response.data.data?.accessToken)
|
13
|
+
return response.data.data;
|
14
|
+
} catch (error) {
|
15
|
+
console.error('Error fetching access token:', error);
|
16
|
+
throw error // Rethrow for caller to handle
|
17
|
+
;
|
18
|
+
}
|
19
|
+
}
|
20
|
+
export async function refreshAccessToken(refreshToken) {
|
21
|
+
try {
|
22
|
+
const response = await cjApiClient.post('authentication/refreshAccessToken', {
|
23
|
+
refreshToken
|
24
|
+
});
|
25
|
+
// TODO: add logger
|
26
|
+
// console.info('New Access Token:', response.data.data.accessToken)
|
27
|
+
return response.data.data;
|
28
|
+
} catch (error) {
|
29
|
+
console.error('Error refreshing access token:', error);
|
30
|
+
throw error;
|
31
|
+
}
|
32
|
+
}
|
33
|
+
export async function logout(accessToken) {
|
34
|
+
try {
|
35
|
+
await cjApiClient.post('authentication/logout', {}, {
|
36
|
+
headers: {
|
37
|
+
'CJ-Access-Token': accessToken
|
38
|
+
}
|
39
|
+
});
|
40
|
+
console.log('Successfully logged out');
|
41
|
+
} catch (error) {
|
42
|
+
console.error('Logout failed:', error);
|
43
|
+
throw error;
|
44
|
+
}
|
45
|
+
}
|
46
|
+
|
47
|
+
//# sourceMappingURL=auth.js.map
|
package/dist/auth.js.map
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"sources":["../src/auth.ts"],"sourcesContent":["import type { AccessTokenResponse } from './types'\n\nimport { cjApiClient } from './api-client'\n\ninterface RefreshTokenResponse {\n code: number\n data: {\n accessToken: string\n accessTokenExpiryDate: string\n createDate: string\n refreshToken: string\n refreshTokenExpiryDate: string\n }\n message: string\n requestId: string\n result: boolean\n}\n\ninterface LogoutResponse {\n code: number\n data: boolean\n message: string\n requestId: string\n result: boolean\n}\n\nexport async function getAccessToken(email: string, password: string) {\n try {\n const response = await cjApiClient.post<AccessTokenResponse>('authentication/getAccessToken', {\n email,\n password,\n })\n\n if (!response.data.data?.accessToken) {\n throw new Error('Failed to fetch access token')\n }\n // TODO: add logger\n // console.log('Access Token:', response.data.data?.accessToken)\n return response.data.data\n } catch (error) {\n console.error('Error fetching access token:', error)\n throw error // Rethrow for caller to handle\n }\n}\n\nexport async function refreshAccessToken(refreshToken: string) {\n try {\n const response = await cjApiClient.post<RefreshTokenResponse>(\n 'authentication/refreshAccessToken',\n {\n refreshToken,\n },\n )\n\n // TODO: add logger\n // console.info('New Access Token:', response.data.data.accessToken)\n return response.data.data\n } catch (error) {\n console.error('Error refreshing access token:', error)\n throw error\n }\n}\n\nexport async function logout(accessToken: string) {\n try {\n await cjApiClient.post<LogoutResponse>(\n 'authentication/logout',\n {},\n {\n headers: { 'CJ-Access-Token': accessToken },\n },\n )\n\n console.log('Successfully logged out')\n } catch (error) {\n console.error('Logout failed:', error)\n throw error\n }\n}\n"],"names":["cjApiClient","getAccessToken","email","password","response","post","data","accessToken","Error","error","console","refreshAccessToken","refreshToken","logout","headers","log"],"mappings":"AAEA,SAASA,WAAW,QAAQ,eAAc;AAwB1C,OAAO,eAAeC,eAAeC,KAAa,EAAEC,QAAgB;IAClE,IAAI;QACF,MAAMC,WAAW,MAAMJ,YAAYK,IAAI,CAAsB,iCAAiC;YAC5FH;YACAC;QACF;QAEA,IAAI,CAACC,SAASE,IAAI,CAACA,IAAI,EAAEC,aAAa;YACpC,MAAM,IAAIC,MAAM;QAClB;QACA,mBAAmB;QACnB,gEAAgE;QAChE,OAAOJ,SAASE,IAAI,CAACA,IAAI;IAC3B,EAAE,OAAOG,OAAO;QACdC,QAAQD,KAAK,CAAC,gCAAgCA;QAC9C,MAAMA,MAAM,+BAA+B;;IAC7C;AACF;AAEA,OAAO,eAAeE,mBAAmBC,YAAoB;IAC3D,IAAI;QACF,MAAMR,WAAW,MAAMJ,YAAYK,IAAI,CACrC,qCACA;YACEO;QACF;QAGF,mBAAmB;QACnB,oEAAoE;QACpE,OAAOR,SAASE,IAAI,CAACA,IAAI;IAC3B,EAAE,OAAOG,OAAO;QACdC,QAAQD,KAAK,CAAC,kCAAkCA;QAChD,MAAMA;IACR;AACF;AAEA,OAAO,eAAeI,OAAON,WAAmB;IAC9C,IAAI;QACF,MAAMP,YAAYK,IAAI,CACpB,yBACA,CAAC,GACD;YACES,SAAS;gBAAE,mBAAmBP;YAAY;QAC5C;QAGFG,QAAQK,GAAG,CAAC;IACd,EAAE,OAAON,OAAO;QACdC,QAAQD,KAAK,CAAC,kBAAkBA;QAChC,MAAMA;IACR;AACF"}
|
@@ -0,0 +1,90 @@
|
|
1
|
+
import { syncProducts } from "./service/sync-products";
|
2
|
+
import { decryptToken, encryptToken } from "./util/manage-tokens";
|
3
|
+
export const CjSettings = {
|
4
|
+
slug: "cj-settings",
|
5
|
+
access: {
|
6
|
+
read: ()=>true
|
7
|
+
},
|
8
|
+
admin: {
|
9
|
+
group: "Plugins"
|
10
|
+
},
|
11
|
+
fields: [
|
12
|
+
{
|
13
|
+
label: "Credentials",
|
14
|
+
type: "collapsible",
|
15
|
+
fields: [
|
16
|
+
{
|
17
|
+
type: "row",
|
18
|
+
fields: [
|
19
|
+
{
|
20
|
+
name: "emailAddress",
|
21
|
+
type: "text"
|
22
|
+
},
|
23
|
+
{
|
24
|
+
name: "apiToken",
|
25
|
+
type: "text",
|
26
|
+
admin: {
|
27
|
+
components: {
|
28
|
+
Field: "@shopnex/cj-plugin/rsc#ApiToken"
|
29
|
+
}
|
30
|
+
}
|
31
|
+
}
|
32
|
+
]
|
33
|
+
}
|
34
|
+
]
|
35
|
+
},
|
36
|
+
{
|
37
|
+
label: "Logo Area POD",
|
38
|
+
name: "pod",
|
39
|
+
type: "upload",
|
40
|
+
relationTo: "media"
|
41
|
+
},
|
42
|
+
{
|
43
|
+
name: "items",
|
44
|
+
type: "array",
|
45
|
+
admin: {
|
46
|
+
description: "A list of product URLs to sync with CJ Dropshipping"
|
47
|
+
},
|
48
|
+
fields: [
|
49
|
+
{
|
50
|
+
name: "productUrl",
|
51
|
+
type: "text"
|
52
|
+
}
|
53
|
+
],
|
54
|
+
label: "Products",
|
55
|
+
labels: {
|
56
|
+
plural: "Product URLs",
|
57
|
+
singular: "Product URL"
|
58
|
+
}
|
59
|
+
}
|
60
|
+
],
|
61
|
+
hooks: {
|
62
|
+
beforeChange: [
|
63
|
+
({ data })=>{
|
64
|
+
const tokenToEncrypt = data.apiToken;
|
65
|
+
const encryptedToken = encryptToken(tokenToEncrypt);
|
66
|
+
data.apiToken = encryptedToken;
|
67
|
+
}
|
68
|
+
],
|
69
|
+
beforeRead: [
|
70
|
+
({ doc })=>{
|
71
|
+
doc.apiToken = doc.apiToken && decryptToken(doc.apiToken);
|
72
|
+
}
|
73
|
+
],
|
74
|
+
afterChange: [
|
75
|
+
async ({ doc, req: { payload } })=>{
|
76
|
+
const productIds = doc.items.map((item)=>{
|
77
|
+
const match = item.productUrl.match(/(?<=-p-)([0-9A-Fa-f-]+)(?=\.html)/);
|
78
|
+
return match ? match[0] : null;
|
79
|
+
});
|
80
|
+
await syncProducts(productIds, payload);
|
81
|
+
},
|
82
|
+
({ doc })=>{
|
83
|
+
doc.apiToken = doc.apiToken && decryptToken(doc.apiToken);
|
84
|
+
}
|
85
|
+
]
|
86
|
+
},
|
87
|
+
label: "CJ Dropshipping"
|
88
|
+
};
|
89
|
+
|
90
|
+
//# sourceMappingURL=cj-settings.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"sources":["../src/cj-settings.ts"],"sourcesContent":["import type { GlobalConfig } from \"payload\";\n\nimport { syncProducts } from \"./service/sync-products\";\nimport { decryptToken, encryptToken } from \"./util/manage-tokens\";\n\nexport const CjSettings: GlobalConfig = {\n slug: \"cj-settings\",\n access: {\n read: () => true,\n // update: ({ req }) => !!req.user?.roles?.includes(\"user\"),\n },\n admin: {\n group: \"Plugins\",\n },\n fields: [\n {\n label: \"Credentials\",\n type: \"collapsible\",\n fields: [\n {\n type: \"row\",\n fields: [\n {\n name: \"emailAddress\",\n type: \"text\",\n },\n {\n name: \"apiToken\",\n type: \"text\",\n admin: {\n components: {\n Field: \"@shopnex/cj-plugin/rsc#ApiToken\",\n },\n },\n },\n ],\n },\n ],\n },\n {\n label: \"Logo Area POD\",\n name: \"pod\",\n type: \"upload\",\n relationTo: \"media\",\n },\n {\n name: \"items\",\n type: \"array\",\n admin: {\n description: \"A list of product URLs to sync with CJ Dropshipping\",\n },\n fields: [\n {\n name: \"productUrl\",\n type: \"text\",\n },\n ],\n label: \"Products\",\n labels: {\n plural: \"Product URLs\",\n singular: \"Product URL\",\n },\n },\n ],\n hooks: {\n beforeChange: [\n ({ data }) => {\n const tokenToEncrypt = data.apiToken;\n const encryptedToken = encryptToken(tokenToEncrypt);\n data.apiToken = encryptedToken;\n },\n ],\n beforeRead: [\n ({ doc }) => {\n doc.apiToken = doc.apiToken && decryptToken(doc.apiToken);\n },\n ],\n afterChange: [\n async ({ doc, req: { payload } }) => {\n const productIds = doc.items.map((item: any) => {\n const match = item.productUrl.match(/(?<=-p-)([0-9A-Fa-f-]+)(?=\\.html)/);\n return match ? match[0] : null;\n });\n await syncProducts(productIds, payload);\n },\n ({ doc }) => {\n doc.apiToken = doc.apiToken && decryptToken(doc.apiToken);\n },\n ],\n },\n label: \"CJ Dropshipping\",\n};\n"],"names":["syncProducts","decryptToken","encryptToken","CjSettings","slug","access","read","admin","group","fields","label","type","name","components","Field","relationTo","description","labels","plural","singular","hooks","beforeChange","data","tokenToEncrypt","apiToken","encryptedToken","beforeRead","doc","afterChange","req","payload","productIds","items","map","item","match","productUrl"],"mappings":"AAEA,SAASA,YAAY,QAAQ,0BAA0B;AACvD,SAASC,YAAY,EAAEC,YAAY,QAAQ,uBAAuB;AAElE,OAAO,MAAMC,aAA2B;IACpCC,MAAM;IACNC,QAAQ;QACJC,MAAM,IAAM;IAEhB;IACAC,OAAO;QACHC,OAAO;IACX;IACAC,QAAQ;QACJ;YACIC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* Gets a human-readable error message for a given error code.
|
3
|
+
*/
|
4
|
+
declare function getCJErrorMessage(code: number): string;
|
5
|
+
/**
|
6
|
+
* Throws a formatted error based on the API response.
|
7
|
+
*/
|
8
|
+
declare function handleCJError(response: {
|
9
|
+
code: number;
|
10
|
+
message?: string;
|
11
|
+
}): never;
|
12
|
+
export { getCJErrorMessage, handleCJError };
|
@@ -0,0 +1,41 @@
|
|
1
|
+
const CJ_ERROR_MESSAGES = {
|
2
|
+
200: "Success",
|
3
|
+
1600000: "System busy. Please try again later.",
|
4
|
+
1600001: "No permission. CJ-Access-Token is invalid.",
|
5
|
+
1600002: "CJ-Access-Token not found.",
|
6
|
+
1600003: "Refresh token failed.",
|
7
|
+
1600100: "The interface has been taken offline. Contact admin.",
|
8
|
+
1600101: "Interface not found. Check the endpoint URL.",
|
9
|
+
1600200: "Call exceeded limit. Try again later.",
|
10
|
+
1600201: "Quota has been used up. Contact support.",
|
11
|
+
1600300: "Illegal parameter. Check API documentation.",
|
12
|
+
1601000: "User not found. Check your email.",
|
13
|
+
1602000: "Variant not found.",
|
14
|
+
1602001: "Product not found or offline.",
|
15
|
+
1603000: "Order creation failed. Contact CJ support.",
|
16
|
+
1603001: "Order confirmation failed. Contact CJ support.",
|
17
|
+
1603002: "Order deletion failed. Contact CJ support.",
|
18
|
+
1603100: "Order not found. Check CJ order ID.",
|
19
|
+
1603101: "Order payment failed. Contact CJ Order Center.",
|
20
|
+
1604000: "Insufficient balance.",
|
21
|
+
1605000: "Logistics not found.",
|
22
|
+
1606000: "Webhook setup failed. Already exists.",
|
23
|
+
1606001: "Webhook setup failed. Contact CJ support.",
|
24
|
+
1607000: "Webhook URL error. URL cannot be empty."
|
25
|
+
};
|
26
|
+
/**
|
27
|
+
* Gets a human-readable error message for a given error code.
|
28
|
+
*/ function getCJErrorMessage(code) {
|
29
|
+
return CJ_ERROR_MESSAGES[code] || `Unknown error: ${code}`;
|
30
|
+
}
|
31
|
+
/**
|
32
|
+
* Throws a formatted error based on the API response.
|
33
|
+
*/ function handleCJError(response) {
|
34
|
+
const errorMessage = response.message || getCJErrorMessage(response.code);
|
35
|
+
const error = new Error(`CJ API Error (${response.code}): ${errorMessage}`);
|
36
|
+
error.code = response.code;
|
37
|
+
throw error;
|
38
|
+
}
|
39
|
+
export { getCJErrorMessage, handleCJError };
|
40
|
+
|
41
|
+
//# sourceMappingURL=error-handler.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"sources":["../src/error-handler.ts"],"sourcesContent":["const CJ_ERROR_MESSAGES: Record<number, string> = {\n 200: \"Success\",\n 1600000: \"System busy. Please try again later.\",\n 1600001: \"No permission. CJ-Access-Token is invalid.\",\n 1600002: \"CJ-Access-Token not found.\",\n 1600003: \"Refresh token failed.\",\n 1600100: \"The interface has been taken offline. Contact admin.\",\n 1600101: \"Interface not found. Check the endpoint URL.\",\n 1600200: \"Call exceeded limit. Try again later.\",\n 1600201: \"Quota has been used up. Contact support.\",\n 1600300: \"Illegal parameter. Check API documentation.\",\n 1601000: \"User not found. Check your email.\",\n 1602000: \"Variant not found.\",\n 1602001: \"Product not found or offline.\",\n 1603000: \"Order creation failed. Contact CJ support.\",\n 1603001: \"Order confirmation failed. Contact CJ support.\",\n 1603002: \"Order deletion failed. Contact CJ support.\",\n 1603100: \"Order not found. Check CJ order ID.\",\n 1603101: \"Order payment failed. Contact CJ Order Center.\",\n 1604000: \"Insufficient balance.\",\n 1605000: \"Logistics not found.\",\n 1606000: \"Webhook setup failed. Already exists.\",\n 1606001: \"Webhook setup failed. Contact CJ support.\",\n 1607000: \"Webhook URL error. URL cannot be empty.\",\n};\n\n/**\n * Gets a human-readable error message for a given error code.\n */\nfunction getCJErrorMessage(code: number): string {\n return CJ_ERROR_MESSAGES[code] || `Unknown error: ${code}`;\n}\n\n/**\n * Throws a formatted error based on the API response.\n */\nfunction handleCJError(response: {\n code: number;\n message?: string;\n}): never {\n const errorMessage = response.message || getCJErrorMessage(response.code);\n const error = new Error(`CJ API Error (${response.code}): ${errorMessage}`);\n (error as any).code = response.code;\n throw error;\n}\n\nexport { getCJErrorMessage, handleCJError };\n"],"names":["CJ_ERROR_MESSAGES","getCJErrorMessage","code","handleCJError","response","errorMessage","message","error","Error"],"mappings":"AAAA,MAAMA,oBAA4C;IAC9C,KAAK;IACL,SAAS;IACT,SAAS;IACT,SAAS;IACT,SAAS;IACT,SAAS;IACT,SAAS;IACT,SAAS;IACT,SAAS;IACT,SAAS;IACT,SAAS;IACT,SAAS;IACT,SAAS;IACT,SAAS;IACT,SAAS;IACT,SAAS;IACT,SAAS;IACT,SAAS;IACT,SAAS;IACT,SAAS;IACT,SAAS;IACT,SAAS;IACT,SAAS;AACb;AAEA;;CAEC,GACD,SAASC,kBAAkBC,IAAY;IACnC,OAAOF,iBAAiB,CAACE,KAAK,IAAI,CAAC,eAAe,EAAEA,MAAM;AAC9D;AAEA;;CAEC,GACD,SAASC,cAAcC,QAGtB;IACG,MAAMC,eAAeD,SAASE,OAAO,IAAIL,kBAAkBG,SAASF,IAAI;IACxE,MAAMK,QAAQ,IAAIC,MAAM,CAAC,cAAc,EAAEJ,SAASF,IAAI,CAAC,GAAG,EAAEG,cAAc;IACzEE,MAAcL,IAAI,GAAGE,SAASF,IAAI;IACnC,MAAMK;AACV;AAEA,SAASN,iBAAiB,EAAEE,aAAa,GAAG"}
|
@@ -0,0 +1,20 @@
|
|
1
|
+
/**
|
2
|
+
* API Response Structure
|
3
|
+
*/
|
4
|
+
export type APIResponse<T> = {
|
5
|
+
data: T;
|
6
|
+
error?: never;
|
7
|
+
} | {
|
8
|
+
data?: never;
|
9
|
+
error: string;
|
10
|
+
};
|
11
|
+
/**
|
12
|
+
* API Error Response Structure
|
13
|
+
*/
|
14
|
+
export interface ApiResponseError {
|
15
|
+
code: number;
|
16
|
+
result: boolean;
|
17
|
+
message: string;
|
18
|
+
data: null;
|
19
|
+
requestId: string;
|
20
|
+
}
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"sources":["../src/error-types.ts"],"sourcesContent":["/**\n * API Response Structure\n */\nexport type APIResponse<T> =\n | { data: T; error?: never }\n | { data?: never; error: string };\n\n/**\n * API Error Response Structure\n */\nexport interface ApiResponseError {\n code: number;\n result: boolean;\n message: string;\n data: null;\n requestId: string;\n}\n\n"],"names":[],"mappings":"AAAA;;CAEC,GAKD;;CAEC,GACD,WAMC"}
|
@@ -0,0 +1 @@
|
|
1
|
+
export { ApiToken } from "../rsc/ApiToken";
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"sources":["../../src/exports/rsc.ts"],"sourcesContent":["export { ApiToken } from \"../rsc/ApiToken\";\n"],"names":["ApiToken"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,kBAAkB"}
|
package/dist/index.d.ts
ADDED
@@ -0,0 +1,11 @@
|
|
1
|
+
import type { Config } from "payload";
|
2
|
+
import { CjCollectionProps } from "./CjConfig";
|
3
|
+
interface PluginOptions {
|
4
|
+
cjApiKey: string;
|
5
|
+
cjEmailAddress: string;
|
6
|
+
cjRefreshToken?: string;
|
7
|
+
asCollection?: boolean;
|
8
|
+
collectionOverrides?: CjCollectionProps["overrides"];
|
9
|
+
}
|
10
|
+
export declare const cjPlugin: (pluginOptions: PluginOptions) => (config: Config) => Config;
|
11
|
+
export {};
|
package/dist/index.js
ADDED
@@ -0,0 +1,56 @@
|
|
1
|
+
import { setTenantCredentials } from "./sdk/access-token";
|
2
|
+
import { createOrderHook } from "./service/create-order.hook";
|
3
|
+
import { CjConfigCollection } from "./CjConfig";
|
4
|
+
const updateCollection = (collection)=>{
|
5
|
+
if (collection.slug === "orders") {
|
6
|
+
return {
|
7
|
+
...collection,
|
8
|
+
hooks: {
|
9
|
+
...collection.hooks,
|
10
|
+
afterChange: [
|
11
|
+
...collection.hooks?.afterChange || [],
|
12
|
+
createOrderHook
|
13
|
+
]
|
14
|
+
}
|
15
|
+
};
|
16
|
+
}
|
17
|
+
return collection;
|
18
|
+
};
|
19
|
+
export const cjPlugin = (pluginOptions)=>(config)=>{
|
20
|
+
const updatedCollections = config.collections?.map(updateCollection) || [];
|
21
|
+
if (pluginOptions.asCollection) {
|
22
|
+
updatedCollections.push(CjConfigCollection({
|
23
|
+
overrides: pluginOptions.collectionOverrides
|
24
|
+
}));
|
25
|
+
}
|
26
|
+
const productCollection = updatedCollections.find((collection)=>collection.slug === "products");
|
27
|
+
const sourceField = productCollection?.fields?.find((field)=>field.name === "source");
|
28
|
+
sourceField.options.push({
|
29
|
+
label: "CJ",
|
30
|
+
value: "cj"
|
31
|
+
});
|
32
|
+
const incomingOnInit = config.onInit;
|
33
|
+
config.onInit = async (payload)=>{
|
34
|
+
if (incomingOnInit) {
|
35
|
+
await incomingOnInit(payload);
|
36
|
+
}
|
37
|
+
const cjSettings = await payload.find({
|
38
|
+
collection: "cj-settings"
|
39
|
+
});
|
40
|
+
cjSettings.docs.forEach((config)=>{
|
41
|
+
setTenantCredentials(config?.shop?.slug || "default", {
|
42
|
+
emailAddress: config.email,
|
43
|
+
password: config.apiToken
|
44
|
+
});
|
45
|
+
});
|
46
|
+
};
|
47
|
+
return {
|
48
|
+
...config,
|
49
|
+
collections: updatedCollections,
|
50
|
+
globals: [
|
51
|
+
...config.globals || []
|
52
|
+
]
|
53
|
+
};
|
54
|
+
};
|
55
|
+
|
56
|
+
//# sourceMappingURL=index.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { CollectionConfig, Config, FieldBase, SelectField } from \"payload\";\nimport { setTenantCredentials } from \"./sdk/access-token\";\nimport { createOrderHook } from \"./service/create-order.hook\";\nimport { CjConfigCollection, CjCollectionProps } from \"./CjConfig\";\n\ninterface PluginOptions {\n cjApiKey: string;\n cjEmailAddress: string;\n cjRefreshToken?: string;\n asCollection?: boolean;\n collectionOverrides?: CjCollectionProps[\"overrides\"];\n}\n\nconst updateCollection = (collection: CollectionConfig) => {\n if (collection.slug === \"orders\") {\n return {\n ...collection,\n hooks: {\n ...collection.hooks,\n afterChange: [...(collection.hooks?.afterChange || []), createOrderHook],\n },\n };\n }\n return collection;\n};\n\nexport const cjPlugin =\n (pluginOptions: PluginOptions) =>\n (config: Config): Config => {\n const updatedCollections = config.collections?.map(updateCollection) || [];\n\n if (pluginOptions.asCollection) {\n updatedCollections.push(\n CjConfigCollection({ overrides: pluginOptions.collectionOverrides }),\n );\n }\n\n const productCollection = updatedCollections.find(\n (collection) => collection.slug === \"products\",\n );\n\n const sourceField = productCollection?.fields?.find(\n (field) => (field as SelectField).name === \"source\",\n ) as SelectField;\n\n sourceField.options.push({\n label: \"CJ\",\n value: \"cj\",\n });\n\n const incomingOnInit = config.onInit;\n\n config.onInit = async (payload) => {\n if (incomingOnInit) {\n await incomingOnInit(payload);\n }\n const cjSettings = await payload.find({\n collection: \"cj-settings\",\n });\n cjSettings.docs.forEach((config: any) => {\n setTenantCredentials(config?.shop?.slug || \"default\", {\n emailAddress: config.email,\n password: config.apiToken,\n });\n });\n };\n\n return {\n ...config,\n collections: updatedCollections,\n globals: [...(config.globals || [])],\n };\n };\n"],"names":["setTenantCredentials","createOrderHook","CjConfigCollection","updateCollection","collection","slug","hooks","afterChange","cjPlugin","pluginOptions","config","updatedCollections","collections","map","asCollection","push","overrides","collectionOverrides","productCollection","find","sourceField","fields","field","name","options","label","value","incomingOnInit","onInit","payload","cjSettings","docs","forEach","shop","emailAddress","email","password","apiToken","globals"],"mappings":"AACA,SAASA,oBAAoB,QAAQ,qBAAqB;AAC1D,SAASC,eAAe,QAAQ,8BAA8B;AAC9D,SAASC,kBAAkB,QAA2B,aAAa;AAUnE,MAAMC,mBAAmB,CAACC;IACtB,IAAIA,WAAWC,IAAI,KAAK,UAAU;QAC9B,OAAO;YACH,GAAGD,UAAU;YACbE,OAAO;gBACH,GAAGF,WAAWE,KAAK;gBACnBC,aAAa;uBAAKH,WAAWE,KAAK,EAAEC,eAAe,EAAE;oBAAGN;iBAAgB;YAC5E;QACJ;IACJ;IACA,OAAOG;AACX;AAEA,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