@shopnex/cj-plugin 1.0.6 → 1.0.7

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.
Files changed (69) hide show
  1. package/dist/CjCollection.d.ts +21 -0
  2. package/dist/CjCollection.js +113 -0
  3. package/dist/CjCollection.js.map +1 -0
  4. package/dist/api-client.d.ts +1 -1
  5. package/dist/api-client.js +5 -5
  6. package/dist/api-client.js.map +1 -1
  7. package/dist/error-handler.js.map +1 -1
  8. package/dist/error-types.js.map +1 -1
  9. package/dist/index.d.ts +1 -3
  10. package/dist/index.js +8 -24
  11. package/dist/index.js.map +1 -1
  12. package/dist/rsc/ApiToken.d.ts +1 -1
  13. package/dist/rsc/ApiToken.js.map +1 -1
  14. package/dist/rsc/ApiToken.scss +1 -2
  15. package/dist/sdk/access-token.d.ts +1 -1
  16. package/dist/sdk/access-token.js +11 -11
  17. package/dist/sdk/access-token.js.map +1 -1
  18. package/dist/{auth.js → sdk/auth.js} +11 -12
  19. package/dist/sdk/auth.js.map +1 -0
  20. package/dist/sdk/cj-sdk.d.ts +18 -4
  21. package/dist/sdk/cj-sdk.js +42 -4
  22. package/dist/sdk/cj-sdk.js.map +1 -1
  23. package/dist/sdk/dispute/dispute-types.js.map +1 -1
  24. package/dist/sdk/dispute/dispute.d.ts +2 -2
  25. package/dist/sdk/dispute/dispute.js +12 -14
  26. package/dist/sdk/dispute/dispute.js.map +1 -1
  27. package/dist/sdk/inventory/inventory-types.js.map +1 -1
  28. package/dist/sdk/inventory/inventory.d.ts +2 -2
  29. package/dist/sdk/inventory/inventory.js +9 -10
  30. package/dist/sdk/inventory/inventory.js.map +1 -1
  31. package/dist/sdk/orders/orders.d.ts +2 -2
  32. package/dist/sdk/orders/orders.js +32 -32
  33. package/dist/sdk/orders/orders.js.map +1 -1
  34. package/dist/sdk/products/product-types.d.ts +14 -3
  35. package/dist/sdk/products/product-types.js +1 -3
  36. package/dist/sdk/products/product-types.js.map +1 -1
  37. package/dist/sdk/products/products.d.ts +7 -1
  38. package/dist/sdk/products/products.js +51 -2
  39. package/dist/sdk/products/products.js.map +1 -1
  40. package/dist/sdk/settings/settings-api.d.ts +1 -1
  41. package/dist/sdk/settings/settings-api.js +4 -4
  42. package/dist/sdk/settings/settings-api.js.map +1 -1
  43. package/dist/sdk/settings/settings-types.js.map +1 -1
  44. package/dist/sdk/variants/variant-types.js.map +1 -1
  45. package/dist/sdk/variants/variants.d.ts +2 -2
  46. package/dist/sdk/variants/variants.js +16 -18
  47. package/dist/sdk/variants/variants.js.map +1 -1
  48. package/dist/service/access-token.d.ts +2 -0
  49. package/dist/service/access-token.js +53 -0
  50. package/dist/service/access-token.js.map +1 -0
  51. package/dist/service/create-order.hook.js +5 -2
  52. package/dist/service/create-order.hook.js.map +1 -1
  53. package/dist/service/sync-products.d.ts +7 -2
  54. package/dist/service/sync-products.js +99 -100
  55. package/dist/service/sync-products.js.map +1 -1
  56. package/dist/ui/refund-button.d.ts +1 -1
  57. package/dist/ui/refund-button.js +2 -2
  58. package/dist/ui/refund-button.js.map +1 -1
  59. package/dist/util/get-product-id.d.ts +1 -0
  60. package/dist/util/get-product-id.js +10 -0
  61. package/dist/util/get-product-id.js.map +1 -0
  62. package/dist/util/manage-tokens.js.map +1 -1
  63. package/package.json +5 -2
  64. package/LICENSE.md +0 -9
  65. package/dist/auth.js.map +0 -1
  66. package/dist/cj-settings.d.ts +0 -9
  67. package/dist/cj-settings.js +0 -99
  68. package/dist/cj-settings.js.map +0 -1
  69. /package/dist/{auth.d.ts → sdk/auth.d.ts} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/service/sync-products.ts"],"sourcesContent":["import type { DefaultNodeTypes, TypedEditorState } from \"@payloadcms/richtext-lexical\";\nimport type { BasePayload } from \"payload\";\n\nimport { convertHTMLToLexical, editorConfigFactory } from \"@payloadcms/richtext-lexical\";\nimport decimal from \"decimal.js\";\nimport { JSDOM } from \"jsdom\";\n\nimport type { ProductDetails } from \"../sdk/products/product-types\";\n\nimport * as cjSdk from \"../sdk/cj-sdk\";\nimport path, { dirname, join } from \"path\";\nimport fs from \"fs\";\nimport { promisify } from \"util\";\nimport { pipeline } from \"stream\";\nimport { writeFile } from \"fs/promises\";\nimport { fileURLToPath } from \"url\";\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\nconst streamPipeline = promisify(pipeline);\n\ninterface Product {\n description: TypedEditorState<DefaultNodeTypes>;\n pid: string;\n title: string;\n source: \"manual\" | \"cj\";\n variants?: Array<{\n imageUrl?: string;\n options?: Array<{ option: string; value: string }>;\n price?: number;\n vid: string;\n }>;\n}\n\nconst delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\nconst download = async (uri: string, filename: string): Promise<void> => {\n try {\n const response = await fetch(uri);\n\n if (!response.ok) {\n throw new Error(`Failed to fetch ${uri}: ${response.statusText}`);\n }\n\n const contentType = response.headers.get(\"content-type\");\n const contentLength = response.headers.get(\"content-length\");\n\n console.log(\"content-type:\", contentType);\n console.log(\"content-length:\", contentLength);\n\n const buffer = Buffer.from(await response.arrayBuffer());\n\n await writeFile(filename, buffer);\n\n console.log(\"Download complete:\", filename);\n } catch (error) {\n console.error(\"Error downloading file:\", error);\n }\n};\n\nasync function uploadImageToPayload(src: string, payload: BasePayload): Promise<any | null> {\n const tempFilePath = path.join(__dirname, \"temp-image.jpg\");\n\n try {\n // Fetch the image\n const response = await fetch(src);\n if (!response.ok) throw new Error(`Failed to fetch image: ${response.statusText}`);\n\n // Stream the response body to a temporary file\n await download(src, tempFilePath);\n\n // Upload the image using Payload's Local API\n const uploadedImage = await payload.create({\n collection: \"media\",\n data: {\n alt: \"Some alt text\",\n },\n\n filePath: tempFilePath,\n });\n\n console.log(\"Uploaded media document:\", uploadedImage);\n\n // Clean up: delete the temporary file\n fs.unlink(tempFilePath, (err) => {\n if (err) console.error(\"Error deleting temporary file:\", err);\n });\n\n return {\n id: uploadedImage.id,\n alt: uploadedImage.alt || \"\",\n prefix: \"media\",\n updatedAt: uploadedImage.updatedAt,\n createdAt: uploadedImage.createdAt,\n url: uploadedImage.url,\n thumbnailURL: uploadedImage.thumbnailURL || null,\n filename: uploadedImage.filename,\n mimeType: uploadedImage.mimeType,\n filesize: uploadedImage.filesize,\n width: uploadedImage.width,\n height: uploadedImage.height,\n focalX: 50,\n focalY: 50,\n };\n } catch (error) {\n console.error(\"Error uploading image:\", error);\n }\n}\nfunction mapMockProductToSchema(\n product: ProductDetails,\n editorConfig: any,\n rate: number,\n payload: BasePayload,\n) {\n return {\n description: convertHTMLToLexical({\n editorConfig,\n html: product.description || \"\",\n JSDOM,\n // uploadImage: async (src: string) => {\n // return uploadImageToPayload(src, payload);\n // },\n }),\n source: \"cj\",\n pid: product.pid,\n title: product.productNameEn,\n variants: product.variants?.map((variant) => ({\n imageUrl: variant.variantImage, // Map image URL to 'id' if using media collection\n options: variant.variantKey?.split(\"-\").map((key, index) => ({\n option: index === 0 ? \"Color\" : \"Size\", // Assuming 'Color' and 'Size', adjust keys if needed\n value: key,\n })),\n price: new decimal(variant.variantSellPrice || 0).mul(rate).toNumber().toFixed(2),\n vid: variant.vid,\n })),\n };\n}\n\nconst findProductById = async (productId: string) => {\n const result = await cjSdk.getProductDetails({\n pid: productId,\n });\n return result.data;\n};\n\nconst createOrUpdateProduct = async (\n product: Omit<Product, \"createdAt\" | \"id\" | \"updatedAt\">,\n payload: BasePayload,\n shopId?: string,\n) => {\n const { totalDocs } = await payload.count({\n collection: \"products\",\n where: {\n pid: {\n equals: product.pid,\n },\n },\n });\n\n if (totalDocs === 0) {\n return payload.create({\n collection: \"products\",\n data: {\n ...product,\n shop: shopId,\n } as any,\n });\n }\n};\n\nexport const fetchExchangeRates = async () => {\n const response = await fetch(\"https://open.er-api.com/v6/latest/USD\");\n const data = await response.json();\n\n return data;\n};\n\nexport const syncProducts = async (productIds: string[], payload: BasePayload, shopId?: string) => {\n const exchangeRates = await fetchExchangeRates();\n const storeSettings = await payload.findGlobal({\n slug: \"store-settings\",\n });\n const rate = exchangeRates.rates[storeSettings.currency || \"USD\"];\n\n const editorConfig = await editorConfigFactory.default({\n config: payload.config,\n });\n const products: ProductDetails[] = [];\n for (const productId of productIds) {\n const product = await findProductById(productId);\n if (!product) {\n continue;\n }\n products.push(product);\n await delay(1010);\n }\n const mappedProducts = products.map((product) => {\n return mapMockProductToSchema(product, editorConfig, rate, payload);\n });\n\n await Promise.all(\n mappedProducts.map((product) => createOrUpdateProduct(product as any, payload, shopId)),\n );\n\n return products;\n};\n"],"names":["convertHTMLToLexical","editorConfigFactory","decimal","JSDOM","cjSdk","path","dirname","fs","promisify","pipeline","writeFile","fileURLToPath","__filename","url","__dirname","streamPipeline","delay","ms","Promise","resolve","setTimeout","download","uri","filename","response","fetch","ok","Error","statusText","contentType","headers","get","contentLength","console","log","buffer","Buffer","from","arrayBuffer","error","uploadImageToPayload","src","payload","tempFilePath","join","uploadedImage","create","collection","data","alt","filePath","unlink","err","id","prefix","updatedAt","createdAt","thumbnailURL","mimeType","filesize","width","height","focalX","focalY","mapMockProductToSchema","product","editorConfig","rate","description","html","source","pid","title","productNameEn","variants","map","variant","imageUrl","variantImage","options","variantKey","split","key","index","option","value","price","variantSellPrice","mul","toNumber","toFixed","vid","findProductById","productId","result","getProductDetails","createOrUpdateProduct","shopId","totalDocs","count","where","equals","shop","fetchExchangeRates","json","syncProducts","productIds","exchangeRates","storeSettings","findGlobal","slug","rates","currency","default","config","products","push","mappedProducts","all"],"mappings":"AAGA,SAASA,oBAAoB,EAAEC,mBAAmB,QAAQ,+BAA+B;AACzF,OAAOC,aAAa,aAAa;AACjC,SAASC,KAAK,QAAQ,QAAQ;AAI9B,YAAYC,WAAW,gBAAgB;AACvC,OAAOC,QAAQC,OAAO,QAAc,OAAO;AAC3C,OAAOC,QAAQ,KAAK;AACpB,SAASC,SAAS,QAAQ,OAAO;AACjC,SAASC,QAAQ,QAAQ,SAAS;AAClC,SAASC,SAAS,QAAQ,cAAc;A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,CACbD,eAAe1C,GAAG,CAAC,CAACV,UAAY+B,sBAAsB/B,SAAgBvB,SAASuD;IAGnF,OAAOkB;AACX,EAAE"}
1
+ {"version":3,"sources":["../../src/service/sync-products.ts"],"sourcesContent":["import type { BasePayload, Where } from \"payload\";\nimport { Product } from \"@shopnex/types\";\nimport {\n convertHTMLToLexical,\n editorConfigFactory,\n} from \"@payloadcms/richtext-lexical\";\nimport decimal from \"decimal.js\";\nimport { JSDOM } from \"jsdom\";\n\nimport type { ProductDetails } from \"../sdk/products/product-types\";\n\nimport { CjSdk, cjSdk } from \"../sdk/cj-sdk\";\nimport { CjData } from \"../CjCollection\";\nimport { retrieveAccessToken } from \"./access-token\";\n\nconst delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\nconst upsertImage = async ({\n payload,\n imageUrl,\n filename,\n alt,\n shopId,\n}: {\n payload: BasePayload;\n imageUrl: string;\n filename: string;\n alt: string;\n shopId?: number;\n}) => {\n const whereClause: Where = {\n filename: {\n equals: filename,\n },\n };\n\n if (shopId !== undefined) {\n whereClause.shop = {\n equals: shopId,\n };\n }\n\n const imageData = await payload.find({\n collection: \"media\",\n where: whereClause,\n limit: 1,\n });\n if (imageData.totalDocs === 0) {\n return payload.create({\n collection: \"media\",\n data: {\n alt,\n filename,\n thumbnailURL: imageUrl,\n url: imageUrl,\n shop: shopId,\n },\n });\n }\n return imageData.docs[0];\n};\n\nasync function mapMockProductToSchema({\n product,\n payload,\n shopId,\n sdk,\n}: {\n product: ProductDetails;\n payload: BasePayload;\n shopId?: number;\n sdk: CjSdk;\n}) {\n const variants: Product[\"variants\"] = [];\n\n for (const variant of product.variants || []) {\n const filename = `${shopId}-${variant?.variantImage?.split(\"/\").pop()}`;\n if (!filename || !variant.variantImage) {\n continue;\n }\n const alt = filename.split(\".\")[0];\n const imageUrl = variant.variantImage;\n const imageData = await upsertImage({\n payload,\n imageUrl,\n filename,\n alt,\n shopId,\n });\n\n const imageId = imageData.id;\n\n const data = await sdk.products.getProductStockByVid({\n vid: variant.vid,\n });\n if (!data.data) {\n throw new Error(\"Failed to fetch stock information\");\n }\n const cjInventoryNum = data.data.reduce(\n (sum, item) => sum + (item?.cjInventoryNum || 0),\n 0\n );\n\n variants.push({\n gallery: [imageId],\n options: variant.variantKey?.split(\"-\").map((key, index) => ({\n option: index === 0 ? \"Color\" : \"Size\",\n value: key,\n })),\n price: Number(\n new decimal(variant.variantSellPrice || 0).toNumber().toFixed(2)\n ),\n vid: variant.vid,\n stockCount: cjInventoryNum,\n });\n }\n\n const cleanHtml = product.description?.replace(/<img[^>]*>/g, \"\");\n\n return {\n description: convertHTMLToLexical({\n editorConfig: await editorConfigFactory.default({\n config: payload.config, // Your Payload Config\n }),\n html: cleanHtml || \"<p></p>\",\n JSDOM, // Pass in the JSDOM import; it's not bundled to keep package size small\n }) as any,\n source: \"cj\" as any,\n pid: product.pid,\n title: product.productNameEn,\n variants,\n };\n}\n\nconst findProductById = async (productId: string, sdk: any) => {\n const result = await sdk.products.getProductDetails({\n pid: productId,\n });\n\n return result.data;\n};\n\nconst createOrUpdateProduct = async ({\n product,\n payload,\n shopId,\n}: {\n product: Omit<Product, \"createdAt\" | \"id\" | \"updatedAt\">;\n payload: BasePayload;\n shopId?: number;\n}) => {\n const { totalDocs } = await payload.count({\n collection: \"products\" as any,\n where: {\n pid: {\n equals: product.pid,\n },\n ...(shopId && {\n shop: {\n equals: shopId,\n },\n }),\n },\n });\n\n if (totalDocs === 0) {\n return payload.create({\n collection: \"products\" as any,\n data: {\n ...product,\n shop: shopId,\n } as any,\n });\n }\n};\n\nexport const syncProducts = async ({\n productIds,\n payload,\n shopId,\n data,\n}: {\n productIds: string[];\n payload: BasePayload;\n shopId?: number;\n data: Partial<CjData>;\n}) => {\n const accessToken = await retrieveAccessToken(data);\n const sdk = cjSdk({ accessToken });\n\n const fetchedProducts: ProductDetails[] = [];\n\n for (const productId of productIds) {\n const product = await findProductById(productId, sdk);\n if (product) {\n fetchedProducts.push(product);\n }\n await delay(1010); // throttle CJ API requests\n }\n\n // Wait for all async mapping to resolve\n const mappedProducts = await Promise.all(\n fetchedProducts.map((product) =>\n mapMockProductToSchema({ product, payload, shopId, sdk })\n )\n );\n\n // Create or update each mapped product\n await Promise.all(\n mappedProducts.map((product) =>\n createOrUpdateProduct({ product, payload, shopId })\n )\n );\n\n return fetchedProducts;\n};\n"],"names":["convertHTMLToLexical","editorConfigFactory","decimal","JSDOM","cjSdk","retrieveAccessToken","delay","ms","Promise","resolve","setTimeout","upsertImage","payload","imageUrl","filename","alt","shopId","whereClause","equals","undefined","shop","imageData","find","collection","where","limit","totalDocs","create","data","thumbnailURL","url","docs","mapMockProductToSchema","product","sdk","variants","variant","variantImage","split","pop","imageId","id","products","getProductStockByVid","vid","Error","cjInventoryNum","reduce","sum","item","push","gallery","options","variantKey","map","key","index","option","value","price","Number","variantSellPrice","toNumber","toFixed","stockCount","cleanHtml","description","replace","editorConfig","default","config","html","source","pid","title","productNameEn","findProductById","productId","result","getProductDetails","createOrUpdateProduct","count","syncProducts","productIds","accessToken","fetchedProducts","mappedProducts","all"],"mappings":"AAEA,SACIA,oBAAoB,EACpBC,mBAAmB,QAChB,+BAA+B;AACtC,OAAOC,aAAa,aAAa;AACjC,SAASC,KAAK,QAAQ,QAAQ;AAI9B,SAAgBC,KAAK,QAAQ,gBAAgB;AAE7C,SAASC,mBAAmB,QAAQ,iBAAiB;AAErD,MAAMC,QAAQ,CAACC,KAAe,IAAIC,QAAQ,CAACC,UAAYC,WAAWD,SAASF;AAE3E,MAAMI,cAAc,OAAO,EACvBC,OAAO,EACPC,QAAQ,EACRC,QAAQ,EACRC,GAAG,EACHC,MAAM,EAOT;IACG,MAAMC,cAAqB;QACvBH,UAAU;YACNI,QAAQJ;QACZ;IACJ;IAEA,IAAIE,WAAWG,WAAW;QACtBF,YAAYG,IAAI,GAAG;YACfF,QAAQF;QACZ;IACJ;IAEA,MAAMK,YAAY,MAAMT,QAAQU,IAAI,CAAC;QACjCC,YA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AEgF;IAAY;IAEhC,MAAMC,kBAAoC,EAAE;IAE5C,KAAK,MAAMR,aAAaM,WAAY;QAChC,MAAMlD,UAAU,MAAM2C,gBAAgBC,WAAW3C;QACjD,IAAID,SAAS;YACToD,gBAAgBnC,IAAI,CAACjB;QACzB;QACA,MAAM3B,MAAM,OAAO,2BAA2B;IAClD;IAEA,wCAAwC;IACxC,MAAMgF,iBAAiB,MAAM9E,QAAQ+E,GAAG,CACpCF,gBAAgB/B,GAAG,CAAC,CAACrB,UACjBD,uBAAuB;YAAEC;YAASrB;YAASI;YAAQkB;QAAI;IAI/D,uCAAuC;IACvC,MAAM1B,QAAQ+E,GAAG,CACbD,eAAehC,GAAG,CAAC,CAACrB,UAChB+C,sBAAsB;YAAE/C;YAASrB;YAASI;QAAO;IAIzD,OAAOqE;AACX,EAAE"}
@@ -1,3 +1,3 @@
1
- import type { FieldServerComponent } from 'payload';
1
+ import type { FieldServerComponent } from "payload";
2
2
  declare const RefundButton: FieldServerComponent;
3
3
  export default RefundButton;
@@ -1,6 +1,6 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
- import { Button, Modal } from '@payloadcms/ui';
3
- import React from 'react';
2
+ import { Button, Modal } from "@payloadcms/ui";
3
+ import React from "react";
4
4
  const RefundButton = ({ data, payload })=>{
5
5
  return /*#__PURE__*/ _jsxs(_Fragment, {
6
6
  children: [
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/ui/refund-button.tsx"],"sourcesContent":["import type { FieldServerComponent } from 'payload'\n\nimport { Button, Modal } from '@payloadcms/ui'\nimport React from 'react'\n\nconst RefundButton: FieldServerComponent = ({ data, payload }) => {\n return (\n <>\n <Modal slug=\"refundModal\" title=\"Refund\">\n <h1>Refund</h1>\n </Modal>\n <Button buttonStyle=\"secondary\" size=\"small\">\n Refund\n </Button>\n </>\n )\n}\n\nexport default RefundButton\n"],"names":["Button","Modal","React","RefundButton","data","payload","slug","title","h1","buttonStyle","size"],"mappings":";AAEA,SAASA,MAAM,EAAEC,KAAK,QAAQ,iBAAgB;AAC9C,OAAOC,WAAW,QAAO;AAEzB,MAAMC,eAAqC,CAAC,EAAEC,IAAI,EAAEC,OAAO,EAAE;IAC3D,qBACE;;0BACE,KAACJ;gBAAMK,MAAK;gBAAcC,OAAM;0BAC9B,cAAA,KAACC;8BAAG;;;0BAEN,KAACR;gBAAOS,aAAY;gBAAYC,MAAK;0BAAQ;;;;AAKnD;AAEA,eAAeP,aAAY"}
1
+ {"version":3,"sources":["../../src/ui/refund-button.tsx"],"sourcesContent":["import type { FieldServerComponent } from \"payload\";\n\nimport { Button, Modal } from \"@payloadcms/ui\";\nimport React from \"react\";\n\nconst RefundButton: FieldServerComponent = ({ data, payload }) => {\n return (\n <>\n <Modal slug=\"refundModal\" title=\"Refund\">\n <h1>Refund</h1>\n </Modal>\n <Button buttonStyle=\"secondary\" size=\"small\">\n Refund\n </Button>\n </>\n );\n};\n\nexport default RefundButton;\n"],"names":["Button","Modal","React","RefundButton","data","payload","slug","title","h1","buttonStyle","size"],"mappings":";AAEA,SAASA,MAAM,EAAEC,KAAK,QAAQ,iBAAiB;AAC/C,OAAOC,WAAW,QAAQ;AAE1B,MAAMC,eAAqC,CAAC,EAAEC,IAAI,EAAEC,OAAO,EAAE;IACzD,qBACI;;0BACI,KAACJ;gBAAMK,MAAK;gBAAcC,OAAM;0BAC5B,cAAA,KAACC;8BAAG;;;0BAER,KAACR;gBAAOS,aAAY;gBAAYC,MAAK;0BAAQ;;;;AAKzD;AAEA,eAAeP,aAAa"}
@@ -0,0 +1 @@
1
+ export declare function getProductId(url: string): string | null;
@@ -0,0 +1,10 @@
1
+ export function getProductId(url) {
2
+ try {
3
+ const match = url.match(/(?<=-p-)([0-9A-Fa-f-]+)(?=\.html)/);
4
+ return match ? match[0] : null;
5
+ } catch (e) {
6
+ return null;
7
+ }
8
+ }
9
+
10
+ //# sourceMappingURL=get-product-id.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/util/get-product-id.ts"],"sourcesContent":["export function getProductId(url: string): string | null {\n try {\n const match = url.match(/(?<=-p-)([0-9A-Fa-f-]+)(?=\\.html)/);\n return match ? match[0] : null;\n } catch (e) {\n return null;\n }\n}\n"],"names":["getProductId","url","match","e"],"mappings":"AAAA,OAAO,SAASA,aAAaC,GAAW;IACpC,IAAI;QACA,MAAMC,QAAQD,IAAIC,KAAK,CAAC;QACxB,OAAOA,QAAQA,KAAK,CAAC,EAAE,GAAG;IAC9B,EAAE,OAAOC,GAAG;QACR,OAAO;IACX;AACJ"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/util/manage-tokens.ts"],"sourcesContent":["import crypto from \"crypto\";\n\ntype TokenPayload = string;\ntype EncryptedData = {\n iv: string;\n tag: string;\n content: string;\n};\n\nconst getKey = (rawKey: string): Buffer => {\n return crypto.createHash(\"sha256\").update(rawKey).digest();\n};\n\nconst getTenantSecret = (tenantId: string): Buffer => {\n const key = tenantId;\n if (!key) throw new Error(`Missing secret for tenant: ${tenantId}`);\n return Buffer.from(key, \"hex\");\n};\n\nexport const encryptToken = (token: TokenPayload): string => {\n const key = getKey(process.env.ENCRYPTION_KEY!);\n const iv = crypto.randomBytes(12);\n const cipher = crypto.createCipheriv(\"aes-256-gcm\", key, iv);\n\n const encrypted = Buffer.concat([cipher.update(token, \"utf8\"), cipher.final()]);\n\n const tag = cipher.getAuthTag();\n\n const result: EncryptedData = {\n iv: iv.toString(\"hex\"),\n tag: tag.toString(\"hex\"),\n content: encrypted.toString(\"hex\"),\n };\n\n return Buffer.from(JSON.stringify(result)).toString(\"base64\");\n};\n\nexport const decryptToken = (encryptedToken: string): string => {\n const key = getKey(process.env.ENCRYPTION_KEY!);\n const decoded = JSON.parse(\n Buffer.from(encryptedToken, \"base64\").toString(\"utf8\"),\n ) as EncryptedData;\n\n const iv = Buffer.from(decoded.iv, \"hex\");\n const tag = Buffer.from(decoded.tag, \"hex\");\n const content = Buffer.from(decoded.content, \"hex\");\n\n const decipher = crypto.createDecipheriv(\"aes-256-gcm\", key, iv);\n decipher.setAuthTag(tag);\n\n const decrypted = Buffer.concat([decipher.update(content), decipher.final()]);\n\n return decrypted.toString(\"utf8\");\n};\n"],"names":["crypto","getKey","rawKey","createHash","update","digest","getTenantSecret","tenantId","key","Error","Buffer","from","encryptToken","token","process","env","ENCRYPTION_KEY","iv","randomBytes","cipher","createCipheriv","encrypted","concat","final","tag","getAuthTag","result","toString","content","JSON","stringify","decryptToken","encryptedToken","decoded","parse","decipher","createDecipheriv","setAuthTag","decrypted"],"mappings":"AAAA,OAAOA,YAAY,SAAS;AAS5B,MAAMC,SAAS,CAACC;IACZ,OAAOF,OAAOG,UAAU,CAAC,UAAUC,MAAM,CAACF,QAAQG,MAAM;AAC5D;AAEA,MAAMC,kBAAkB,CAACC;IACrB,MAAMC,MAAMD;IACZ,IAAI,CAACC,KAAK,MAAM,IAAIC,MAAM,CAAC,2BAA2B,EAAEF,UAAU;IAClE,OAAOG,OAAOC,IAAI,CAACH,KAAK;AAC5B;AAEA,OAAO,MAAMI,eAAe,CAACC;IACzB,MAAML,MAAMP,OAAOa,QAAQC,GAAG,CAACC,cAAc;IAC7C,MAAMC,KAAKjB,OAAOkB,WAAW,CAAC;IAC9B,MAAMC,SAASnB,OAAOoB,cAAc,CAAC,eAAeZ,KAAKS;IAEzD,MAAMI,YAAYX,OAAOY,MAAM,CAAC;QAACH,OAAOf,MAAM,CAACS,OAAO;QAASM,OAAOI,KAAK;KAAG;IAE9E,MAAMC,MAAML,OAAOM,UAAU;IAE7B,MAAMC,SAAwB;QAC1BT,IAAIA,GAAGU,QAAQ,CAAC;QAChBH,KAAKA,IAAIG,QAAQ,CAAC;QAClBC,SAASP,UAAUM,QAAQ,CAAC;IAChC;IAEA,OAAOjB,OAAOC,IAAI,CAACkB,KAAKC,SAAS,CAACJ,SAASC,QAAQ,CAAC;AACxD,EAAE;AAEF,OAAO,MAAMI,eAAe,CAACC;IACzB,MAAMxB,MAAMP,OAAOa,QAAQC,GAAG,CAACC,cAAc;IAC7C,MAAMiB,UAAUJ,KAAKK,KAAK,CACtBxB,OAAOC,IAAI,CAACqB,gBAAgB,UAAUL,QAAQ,CAAC;IAGnD,MAAMV,KAAKP,OAAOC,IAAI,CAACsB,QAAQhB,EAAE,EAAE;IACnC,MAAMO,MAAMd,OAAOC,IAAI,CAACsB,QAAQT,GAAG,EAAE;IACrC,MAAMI,UAAUlB,OAAOC,IAAI,CAACsB,QAAQL,OAAO,EAAE;IAE7C,MAAMO,WAAWnC,OAAOoC,gBAAgB,CAAC,eAAe5B,KAAKS;IAC7DkB,SAASE,UAAU,CAACb;IAEpB,MAAMc,YAAY5B,OAAOY,MAAM,CAAC;QAACa,SAAS/B,MAAM,CAACwB;QAAUO,SAASZ,KAAK;KAAG;IAE5E,OAAOe,UAAUX,QAAQ,CAAC;AAC9B,EAAE"}
1
+ {"version":3,"sources":["../../src/util/manage-tokens.ts"],"sourcesContent":["import crypto from \"crypto\";\n\ntype TokenPayload = string;\ntype EncryptedData = {\n iv: string;\n tag: string;\n content: string;\n};\n\nconst getKey = (rawKey: string): Buffer => {\n return crypto.createHash(\"sha256\").update(rawKey).digest();\n};\n\nconst getTenantSecret = (tenantId: string): Buffer => {\n const key = tenantId;\n if (!key) throw new Error(`Missing secret for tenant: ${tenantId}`);\n return Buffer.from(key, \"hex\");\n};\n\nexport const encryptToken = (token: TokenPayload): string => {\n const key = getKey(process.env.ENCRYPTION_KEY!);\n const iv = crypto.randomBytes(12);\n const cipher = crypto.createCipheriv(\"aes-256-gcm\", key, iv);\n\n const encrypted = Buffer.concat([\n cipher.update(token, \"utf8\"),\n cipher.final(),\n ]);\n\n const tag = cipher.getAuthTag();\n\n const result: EncryptedData = {\n iv: iv.toString(\"hex\"),\n tag: tag.toString(\"hex\"),\n content: encrypted.toString(\"hex\"),\n };\n\n return Buffer.from(JSON.stringify(result)).toString(\"base64\");\n};\n\nexport const decryptToken = (encryptedToken: string): string => {\n const key = getKey(process.env.ENCRYPTION_KEY!);\n const decoded = JSON.parse(\n Buffer.from(encryptedToken, \"base64\").toString(\"utf8\")\n ) as EncryptedData;\n\n const iv = Buffer.from(decoded.iv, \"hex\");\n const tag = Buffer.from(decoded.tag, \"hex\");\n const content = Buffer.from(decoded.content, \"hex\");\n\n const decipher = crypto.createDecipheriv(\"aes-256-gcm\", key, iv);\n decipher.setAuthTag(tag);\n\n const decrypted = Buffer.concat([\n decipher.update(content),\n decipher.final(),\n ]);\n\n return decrypted.toString(\"utf8\");\n};\n"],"names":["crypto","getKey","rawKey","createHash","update","digest","getTenantSecret","tenantId","key","Error","Buffer","from","encryptToken","token","process","env","ENCRYPTION_KEY","iv","randomBytes","cipher","createCipheriv","encrypted","concat","final","tag","getAuthTag","result","toString","content","JSON","stringify","decryptToken","encryptedToken","decoded","parse","decipher","createDecipheriv","setAuthTag","decrypted"],"mappings":"AAAA,OAAOA,YAAY,SAAS;AAS5B,MAAMC,SAAS,CAACC;IACZ,OAAOF,OAAOG,UAAU,CAAC,UAAUC,MAAM,CAACF,QAAQG,MAAM;AAC5D;AAEA,MAAMC,kBAAkB,CAACC;IACrB,MAAMC,MAAMD;IACZ,IAAI,CAACC,KAAK,MAAM,IAAIC,MAAM,CAAC,2BAA2B,EAAEF,UAAU;IAClE,OAAOG,OAAOC,IAAI,CAACH,KAAK;AAC5B;AAEA,OAAO,MAAMI,eAAe,CAACC;IACzB,MAAML,MAAMP,OAAOa,QAAQC,GAAG,CAACC,cAAc;IAC7C,MAAMC,KAAKjB,OAAOkB,WAAW,CAAC;IAC9B,MAAMC,SAASnB,OAAOoB,cAAc,CAAC,eAAeZ,KAAKS;IAEzD,MAAMI,YAAYX,OAAOY,MAAM,CAAC;QAC5BH,OAAOf,MAAM,CAACS,OAAO;QACrBM,OAAOI,KAAK;KACf;IAED,MAAMC,MAAML,OAAOM,UAAU;IAE7B,MAAMC,SAAwB;QAC1BT,IAAIA,GAAGU,QAAQ,CAAC;QAChBH,KAAKA,IAAIG,QAAQ,CAAC;QAClBC,SAASP,UAAUM,QAAQ,CAAC;IAChC;IAEA,OAAOjB,OAAOC,IAAI,CAACkB,KAAKC,SAAS,CAACJ,SAASC,QAAQ,CAAC;AACxD,EAAE;AAEF,OAAO,MAAMI,eAAe,CAACC;IACzB,MAAMxB,MAAMP,OAAOa,QAAQC,GAAG,CAACC,cAAc;IAC7C,MAAMiB,UAAUJ,KAAKK,KAAK,CACtBxB,OAAOC,IAAI,CAACqB,gBAAgB,UAAUL,QAAQ,CAAC;IAGnD,MAAMV,KAAKP,OAAOC,IAAI,CAACsB,QAAQhB,EAAE,EAAE;IACnC,MAAMO,MAAMd,OAAOC,IAAI,CAACsB,QAAQT,GAAG,EAAE;IACrC,MAAMI,UAAUlB,OAAOC,IAAI,CAACsB,QAAQL,OAAO,EAAE;IAE7C,MAAMO,WAAWnC,OAAOoC,gBAAgB,CAAC,eAAe5B,KAAKS;IAC7DkB,SAASE,UAAU,CAACb;IAEpB,MAAMc,YAAY5B,OAAOY,MAAM,CAAC;QAC5Ba,SAAS/B,MAAM,CAACwB;QAChBO,SAASZ,KAAK;KACjB;IAED,OAAOe,UAAUX,QAAQ,CAAC;AAC9B,EAAE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shopnex/cj-plugin",
3
- "version": "1.0.6",
3
+ "version": "1.0.7",
4
4
  "description": "A blank template to get started with Payload 3.0",
5
5
  "type": "module",
6
6
  "exports": {
@@ -30,8 +30,11 @@
30
30
  "@lexical/headless": "0.28.0",
31
31
  "@lexical/html": "0.28.0",
32
32
  "axios": "^1.8.3",
33
+ "decimal.js": "^10.5.0",
33
34
  "jsdom": "^26.0.0",
34
- "lexical": "0.28.0"
35
+ "lexical": "0.28.0",
36
+ "@shopnex/utils": "1.0.6",
37
+ "@shopnex/types": "0.0.1"
35
38
  },
36
39
  "devDependencies": {
37
40
  "@types/jsdom": "^21.1.7"
package/LICENSE.md DELETED
@@ -1,9 +0,0 @@
1
- The MIT License (MIT)
2
-
3
- Copyright 2025 Shopnex
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
-
7
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
-
9
- THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/dist/auth.js.map DELETED
@@ -1 +0,0 @@
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"}
@@ -1,9 +0,0 @@
1
- import type { CollectionConfig, GlobalConfig } from "payload";
2
- export type CjCollectionProps = {
3
- overrides?: Partial<CollectionConfig>;
4
- };
5
- export type CjGlobalProps = {
6
- overrides?: Partial<GlobalConfig>;
7
- };
8
- export declare const CjSettings: ({ overrides }: CjGlobalProps) => GlobalConfig;
9
- export declare const CjConfigCollection: ({ overrides }: CjCollectionProps) => CollectionConfig;
@@ -1,99 +0,0 @@
1
- import { syncProducts } from "./service/sync-products";
2
- // Shared fields definition
3
- const sharedFields = [
4
- // {
5
- // label: "Credentials",
6
- // type: "collapsible",
7
- // fields: [
8
- // {
9
- // type: "row",
10
- // fields: [
11
- // {
12
- // name: "emailAddress",
13
- // type: "text",
14
- // },
15
- // {
16
- // name: "apiToken",
17
- // type: "text",
18
- // admin: {
19
- // components: {
20
- // Field: "@shopnex/cj-plugin/rsc#ApiToken",
21
- // },
22
- // },
23
- // },
24
- // ],
25
- // },
26
- // ],
27
- // },
28
- // {
29
- // label: "Logo Area POD",
30
- // name: "pod",
31
- // type: "upload",
32
- // relationTo: "media",
33
- // },
34
- {
35
- name: "items",
36
- type: "array",
37
- admin: {
38
- description: "A list of product URLs to sync with CJ Dropshipping"
39
- },
40
- fields: [
41
- {
42
- name: "productUrl",
43
- type: "text"
44
- }
45
- ],
46
- label: "Products",
47
- labels: {
48
- plural: "Product URLs",
49
- singular: "Product URL"
50
- }
51
- }
52
- ];
53
- // Shared hooks definition
54
- const sharedHooks = {
55
- beforeChange: [
56
- async ({ data, req })=>{
57
- const productIds = data.items.map((item)=>{
58
- const match = item.productUrl.match(/(?<=-p-)([0-9A-Fa-f-]+)(?=\.html)/);
59
- return match ? match[0] : null;
60
- });
61
- const shopId = req.user?.shops?.[0]?.shop?.id;
62
- await syncProducts(productIds, req.payload, shopId);
63
- }
64
- ]
65
- };
66
- // Global Config
67
- export const CjSettings = ({ overrides })=>({
68
- slug: "cj-settings",
69
- access: {
70
- ...overrides?.access
71
- },
72
- admin: {
73
- group: "Plugins",
74
- ...overrides?.admin
75
- },
76
- fields: sharedFields,
77
- hooks: sharedHooks,
78
- label: "CJ Dropshipping",
79
- ...overrides || {}
80
- });
81
- export const CjConfigCollection = ({ overrides })=>({
82
- slug: "cj-settings",
83
- access: {
84
- ...overrides?.access
85
- },
86
- admin: {
87
- group: "Plugins",
88
- ...overrides?.admin
89
- },
90
- fields: sharedFields,
91
- hooks: sharedHooks,
92
- labels: {
93
- singular: "CJ Dropshipping",
94
- plural: "CJ Configs"
95
- },
96
- ...overrides || {}
97
- });
98
-
99
- //# sourceMappingURL=cj-settings.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/cj-settings.ts"],"sourcesContent":["import type { CollectionConfig, Field, GlobalConfig } from \"payload\";\nimport { syncProducts } from \"./service/sync-products\";\nimport { before } from \"lodash\";\n\n// Collection Config\nexport type CjCollectionProps = {\n overrides?: Partial<CollectionConfig>;\n};\n\nexport type CjGlobalProps = {\n overrides?: Partial<GlobalConfig>;\n};\n\n// Shared fields definition\nconst sharedFields: Field[] = [\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\n// Shared hooks definition\nconst sharedHooks = {\n beforeChange: [\n async ({ data, req }) => {\n const productIds = data.items.map((item: any) => {\n const match = item.productUrl.match(/(?<=-p-)([0-9A-Fa-f-]+)(?=\\.html)/);\n return match ? match[0] : null;\n });\n const shopId = req.user?.shops?.[0]?.shop?.id;\n await syncProducts(productIds, req.payload, shopId);\n },\n ],\n};\n\n// Global Config\nexport const CjSettings = ({ overrides }: CjGlobalProps): GlobalConfig => ({\n slug: \"cj-settings\",\n access: {\n ...overrides?.access,\n },\n admin: {\n group: \"Plugins\",\n ...overrides?.admin,\n },\n fields: sharedFields,\n hooks: sharedHooks,\n label: \"CJ Dropshipping\",\n ...(overrides || {}),\n});\n\nexport const CjConfigCollection = ({ overrides }: CjCollectionProps): CollectionConfig => ({\n slug: \"cj-settings\",\n access: {\n ...overrides?.access,\n },\n admin: {\n group: \"Plugins\",\n ...overrides?.admin,\n },\n fields: sharedFields,\n hooks: sharedHooks,\n labels: {\n singular: \"CJ Dropshipping\",\n plural: \"CJ Configs\",\n },\n ...(overrides || {}),\n});\n"],"names":["syncProducts","sharedFields","name","type","admin","description","fields","label","labels","plural","singular","sharedHooks","beforeChange","data","req","productIds","items","map","item","match","productUrl","shopId","user","shops","shop","id","payload","CjSettings","overrides","slug","access","group","hooks","CjConfigCollection"],"mappings":"AACA,SAASA,YAAY,QAAQ,0BAA0B;AAYvD,2BAA2B;AAC3B,MAAMC,eAAwB;IAC1B,IAAI;IACJ,4BAA4B;IAC5B,2BAA2B;IAC3B,gBAAgB;IAChB,YAAY;IACZ,2BAA2B;IAC3B,wBAAwB;IACxB,oBAAoB;IACpB,4CAA4C;IAC5C,oCAAoC;IACpC,qBAAqB;IACrB,oBAAoB;IACpB,wCAAwC;IACxC,oCAAoC;IACpC,+BAA+B;IAC/B,wCAAwC;IACxC,wEAAwE;IACxE,6BAA6B;IAC7B,yBAAyB;IACzB,qBAAqB;IACrB,iBAAiB;IACj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