@payloadcms/plugin-stripe 4.0.0-canary.32 → 4.0.0-canary.34

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 (45) hide show
  1. package/dist/admin.d.ts.map +1 -1
  2. package/dist/admin.js +4 -2
  3. package/dist/admin.js.map +1 -1
  4. package/dist/exports/types.d.ts +1 -1
  5. package/dist/exports/types.d.ts.map +1 -1
  6. package/dist/exports/types.js.map +1 -1
  7. package/dist/fields/getFields.d.ts.map +1 -1
  8. package/dist/fields/getFields.js +8 -0
  9. package/dist/fields/getFields.js.map +1 -1
  10. package/dist/hooks/createNewInStripe.d.ts.map +1 -1
  11. package/dist/hooks/createNewInStripe.js +6 -7
  12. package/dist/hooks/createNewInStripe.js.map +1 -1
  13. package/dist/hooks/syncExistingWithStripe.d.ts.map +1 -1
  14. package/dist/hooks/syncExistingWithStripe.js +6 -7
  15. package/dist/hooks/syncExistingWithStripe.js.map +1 -1
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +5 -2
  18. package/dist/index.js.map +1 -1
  19. package/dist/index.spec.js +73 -0
  20. package/dist/index.spec.js.map +1 -0
  21. package/dist/routes/rest.d.ts +3 -3
  22. package/dist/routes/rest.d.ts.map +1 -1
  23. package/dist/routes/rest.js +104 -27
  24. package/dist/routes/rest.js.map +1 -1
  25. package/dist/routes/rest.spec.js +275 -0
  26. package/dist/routes/rest.spec.js.map +1 -0
  27. package/dist/types.d.ts +10 -3
  28. package/dist/types.d.ts.map +1 -1
  29. package/dist/types.js.map +1 -1
  30. package/dist/utilities/deepen.d.ts +6 -0
  31. package/dist/utilities/deepen.d.ts.map +1 -1
  32. package/dist/utilities/deepen.js +33 -3
  33. package/dist/utilities/deepen.js.map +1 -1
  34. package/dist/utilities/deepen.spec.js +110 -0
  35. package/dist/utilities/deepen.spec.js.map +1 -0
  36. package/dist/utilities/sanitizeStripeRESTConfig.d.ts +5 -0
  37. package/dist/utilities/sanitizeStripeRESTConfig.d.ts.map +1 -0
  38. package/dist/utilities/sanitizeStripeRESTConfig.js +25 -0
  39. package/dist/utilities/sanitizeStripeRESTConfig.js.map +1 -0
  40. package/dist/utilities/sanitizeStripeRESTConfig.spec.js +116 -0
  41. package/dist/utilities/sanitizeStripeRESTConfig.spec.js.map +1 -0
  42. package/dist/webhooks/handleCreatedOrUpdated.d.ts.map +1 -1
  43. package/dist/webhooks/handleCreatedOrUpdated.js +6 -6
  44. package/dist/webhooks/handleCreatedOrUpdated.js.map +1 -1
  45. package/package.json +6 -6
@@ -1 +1 @@
1
- {"version":3,"file":"admin.d.ts","sourceRoot":"","sources":["../src/admin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,CAAA;AAErC,OAAO,KAAK,EAA+B,kBAAkB,EAAE,MAAM,YAAY,CAAA;AAIjF,eAAO,MAAM,YAAY,yBACA,kBAAkB,cAChC,MAAM,KAAG,MAmCjB,CAAA"}
1
+ {"version":3,"file":"admin.d.ts","sourceRoot":"","sources":["../src/admin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,CAAA;AAErC,OAAO,KAAK,EAA+B,kBAAkB,EAAE,MAAM,YAAY,CAAA;AAKjF,eAAO,MAAM,YAAY,yBACA,kBAAkB,cAChC,MAAM,KAAG,MAkCjB,CAAA"}
package/dist/admin.js CHANGED
@@ -1,11 +1,13 @@
1
1
  import { getFields } from './fields/getFields.js';
2
+ import { sanitizeStripeRESTConfig } from './utilities/sanitizeStripeRESTConfig.js';
2
3
  export const stripePlugin = (incomingPluginConfig)=>(config)=>{
3
4
  const { collections } = config;
4
5
  // set config defaults here
5
6
  const pluginConfig = {
6
7
  ...incomingPluginConfig,
7
- // TODO: in the next major version, default this to `false`
8
- rest: incomingPluginConfig?.rest ?? true,
8
+ rest: sanitizeStripeRESTConfig({
9
+ rest: incomingPluginConfig?.rest
10
+ }),
9
11
  sync: incomingPluginConfig?.sync || []
10
12
  };
11
13
  // NOTE: env variables are never passed to the client, but we need to know if `stripeSecretKey` is a test key
package/dist/admin.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/admin.ts"],"sourcesContent":["import type { Config } from 'payload'\n\nimport type { SanitizedStripePluginConfig, StripePluginConfig } from './types.js'\n\nimport { getFields } from './fields/getFields.js'\n\nexport const stripePlugin =\n (incomingPluginConfig: StripePluginConfig) =>\n (config: Config): Config => {\n const { collections } = config\n\n // set config defaults here\n const pluginConfig: SanitizedStripePluginConfig = {\n ...incomingPluginConfig,\n // TODO: in the next major version, default this to `false`\n rest: incomingPluginConfig?.rest ?? true,\n sync: incomingPluginConfig?.sync || [],\n }\n\n // NOTE: env variables are never passed to the client, but we need to know if `stripeSecretKey` is a test key\n // unfortunately we must set the 'isTestKey' property on the config instead of using the following code:\n // const isTestKey = stripeConfig.stripeSecretKey?.startsWith('sk_test_');\n\n return {\n ...config,\n collections: collections?.map((collection) => {\n const syncConfig = pluginConfig.sync?.find((sync) => sync.collection === collection.slug)\n\n if (syncConfig) {\n const fields = getFields({\n collection,\n pluginConfig,\n syncConfig,\n })\n return {\n ...collection,\n fields,\n }\n }\n\n return collection\n }),\n }\n }\n"],"names":["getFields","stripePlugin","incomingPluginConfig","config","collections","pluginConfig","rest","sync","map","collection","syncConfig","find","slug","fields"],"mappings":"AAIA,SAASA,SAAS,QAAQ,wBAAuB;AAEjD,OAAO,MAAMC,eACX,CAACC,uBACD,CAACC;QACC,MAAM,EAAEC,WAAW,EAAE,GAAGD;QAExB,2BAA2B;QAC3B,MAAME,eAA4C;YAChD,GAAGH,oBAAoB;YACvB,2DAA2D;YAC3DI,MAAMJ,sBAAsBI,QAAQ;YACpCC,MAAML,sBAAsBK,QAAQ,EAAE;QACxC;QAEA,6GAA6G;QAC7G,wGAAwG;QACxG,0EAA0E;QAE1E,OAAO;YACL,GAAGJ,MAAM;YACTC,aAAaA,aAAaI,IAAI,CAACC;gBAC7B,MAAMC,aAAaL,aAAaE,IAAI,EAAEI,KAAK,CAACJ,OAASA,KAAKE,UAAU,KAAKA,WAAWG,IAAI;gBAExF,IAAIF,YAAY;oBACd,MAAMG,SAASb,UAAU;wBACvBS;wBACAJ;wBACAK;oBACF;oBACA,OAAO;wBACL,GAAGD,UAAU;wBACbI;oBACF;gBACF;gBAEA,OAAOJ;YACT;QACF;IACF,EAAC"}
1
+ {"version":3,"sources":["../src/admin.ts"],"sourcesContent":["import type { Config } from 'payload'\n\nimport type { SanitizedStripePluginConfig, StripePluginConfig } from './types.js'\n\nimport { getFields } from './fields/getFields.js'\nimport { sanitizeStripeRESTConfig } from './utilities/sanitizeStripeRESTConfig.js'\n\nexport const stripePlugin =\n (incomingPluginConfig: StripePluginConfig) =>\n (config: Config): Config => {\n const { collections } = config\n\n // set config defaults here\n const pluginConfig: SanitizedStripePluginConfig = {\n ...incomingPluginConfig,\n rest: sanitizeStripeRESTConfig({ rest: incomingPluginConfig?.rest }),\n sync: incomingPluginConfig?.sync || [],\n }\n\n // NOTE: env variables are never passed to the client, but we need to know if `stripeSecretKey` is a test key\n // unfortunately we must set the 'isTestKey' property on the config instead of using the following code:\n // const isTestKey = stripeConfig.stripeSecretKey?.startsWith('sk_test_');\n\n return {\n ...config,\n collections: collections?.map((collection) => {\n const syncConfig = pluginConfig.sync?.find((sync) => sync.collection === collection.slug)\n\n if (syncConfig) {\n const fields = getFields({\n collection,\n pluginConfig,\n syncConfig,\n })\n return {\n ...collection,\n fields,\n }\n }\n\n return collection\n }),\n }\n }\n"],"names":["getFields","sanitizeStripeRESTConfig","stripePlugin","incomingPluginConfig","config","collections","pluginConfig","rest","sync","map","collection","syncConfig","find","slug","fields"],"mappings":"AAIA,SAASA,SAAS,QAAQ,wBAAuB;AACjD,SAASC,wBAAwB,QAAQ,0CAAyC;AAElF,OAAO,MAAMC,eACX,CAACC,uBACD,CAACC;QACC,MAAM,EAAEC,WAAW,EAAE,GAAGD;QAExB,2BAA2B;QAC3B,MAAME,eAA4C;YAChD,GAAGH,oBAAoB;YACvBI,MAAMN,yBAAyB;gBAAEM,MAAMJ,sBAAsBI;YAAK;YAClEC,MAAML,sBAAsBK,QAAQ,EAAE;QACxC;QAEA,6GAA6G;QAC7G,wGAAwG;QACxG,0EAA0E;QAE1E,OAAO;YACL,GAAGJ,MAAM;YACTC,aAAaA,aAAaI,IAAI,CAACC;gBAC7B,MAAMC,aAAaL,aAAaE,IAAI,EAAEI,KAAK,CAACJ,OAASA,KAAKE,UAAU,KAAKA,WAAWG,IAAI;gBAExF,IAAIF,YAAY;oBACd,MAAMG,SAASd,UAAU;wBACvBU;wBACAJ;wBACAK;oBACF;oBACA,OAAO;wBACL,GAAGD,UAAU;wBACbI;oBACF;gBACF;gBAEA,OAAOJ;YACT;QACF;IACF,EAAC"}
@@ -1,2 +1,2 @@
1
- export type { FieldSyncConfig, SanitizedStripePluginConfig, StripePluginConfig, StripeProxy, StripeWebhookHandler, StripeWebhookHandlers, SyncConfig, } from '../types.js';
1
+ export type { FieldSyncConfig, SanitizedStripePluginConfig, StripePluginConfig, StripeProxy, StripeRESTAccess, StripeRESTConfig, StripeWebhookHandler, StripeWebhookHandlers, SyncConfig, } from '../types.js';
2
2
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/exports/types.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,eAAe,EACf,2BAA2B,EAC3B,kBAAkB,EAClB,WAAW,EACX,oBAAoB,EACpB,qBAAqB,EACrB,UAAU,GACX,MAAM,aAAa,CAAA"}
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/exports/types.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,eAAe,EACf,2BAA2B,EAC3B,kBAAkB,EAClB,WAAW,EACX,gBAAgB,EAChB,gBAAgB,EAChB,oBAAoB,EACpB,qBAAqB,EACrB,UAAU,GACX,MAAM,aAAa,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/exports/types.ts"],"sourcesContent":["export type {\n FieldSyncConfig,\n SanitizedStripePluginConfig,\n StripePluginConfig,\n StripeProxy,\n StripeWebhookHandler,\n StripeWebhookHandlers,\n SyncConfig,\n} from '../types.js'\n"],"names":[],"mappings":"AAAA,WAQoB"}
1
+ {"version":3,"sources":["../../src/exports/types.ts"],"sourcesContent":["export type {\n FieldSyncConfig,\n SanitizedStripePluginConfig,\n StripePluginConfig,\n StripeProxy,\n StripeRESTAccess,\n StripeRESTConfig,\n StripeWebhookHandler,\n StripeWebhookHandlers,\n SyncConfig,\n} from '../types.js'\n"],"names":[],"mappings":"AAAA,WAUoB"}
@@ -1 +1 @@
1
- {"version":3,"file":"getFields.d.ts","sourceRoot":"","sources":["../../src/fields/getFields.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAEtD,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAA;AAE9D,UAAU,IAAI;IACZ,UAAU,EAAE,gBAAgB,CAAA;IAC5B,YAAY,EAAE,2BAA2B,CAAA;IACzC,UAAU,EAAE;QACV,kBAAkB,EAAE,MAAM,CAAA;KAC3B,CAAA;CACF;AAED,eAAO,MAAM,SAAS,6CAA8C,IAAI,KAAG,KAAK,EAyC/E,CAAA"}
1
+ {"version":3,"file":"getFields.d.ts","sourceRoot":"","sources":["../../src/fields/getFields.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAEtD,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAA;AAE9D,UAAU,IAAI;IACZ,UAAU,EAAE,gBAAgB,CAAA;IAC5B,YAAY,EAAE,2BAA2B,CAAA;IACzC,UAAU,EAAE;QACV,kBAAkB,EAAE,MAAM,CAAA;KAC3B,CAAA;CACF;AAED,eAAO,MAAM,SAAS,6CAA8C,IAAI,KAAG,KAAK,EAiD/E,CAAA"}
@@ -2,6 +2,10 @@ export const getFields = ({ collection, pluginConfig, syncConfig })=>{
2
2
  const stripeIDField = {
3
3
  name: 'stripeID',
4
4
  type: 'text',
5
+ access: {
6
+ create: ()=>false,
7
+ update: ()=>false
8
+ },
5
9
  admin: {
6
10
  position: 'sidebar',
7
11
  readOnly: true
@@ -12,6 +16,10 @@ export const getFields = ({ collection, pluginConfig, syncConfig })=>{
12
16
  const skipSyncField = {
13
17
  name: 'skipSync',
14
18
  type: 'checkbox',
19
+ access: {
20
+ create: ()=>false,
21
+ update: ()=>false
22
+ },
15
23
  admin: {
16
24
  position: 'sidebar',
17
25
  readOnly: true
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/fields/getFields.ts"],"sourcesContent":["import type { CollectionConfig, Field } from 'payload'\n\nimport type { SanitizedStripePluginConfig } from '../types.js'\n\ninterface Args {\n collection: CollectionConfig\n pluginConfig: SanitizedStripePluginConfig\n syncConfig: {\n stripeResourceType: string\n }\n}\n\nexport const getFields = ({ collection, pluginConfig, syncConfig }: Args): Field[] => {\n const stripeIDField: Field = {\n name: 'stripeID',\n type: 'text',\n admin: {\n position: 'sidebar',\n readOnly: true,\n },\n label: 'Stripe ID',\n saveToJWT: true,\n }\n\n const skipSyncField: Field = {\n name: 'skipSync',\n type: 'checkbox',\n admin: {\n position: 'sidebar',\n readOnly: true,\n },\n label: 'Skip Sync',\n }\n\n const docUrlField: Field = {\n name: 'docUrl',\n type: 'ui',\n admin: {\n components: {\n Field: '@payloadcms/plugin-stripe/client#LinkToDoc',\n },\n custom: {\n isTestKey: pluginConfig.isTestKey,\n nameOfIDField: 'stripeID',\n stripeResourceType: syncConfig.stripeResourceType,\n },\n position: 'sidebar',\n },\n }\n\n const fields = [...collection.fields, stripeIDField, skipSyncField, docUrlField]\n\n return fields\n}\n"],"names":["getFields","collection","pluginConfig","syncConfig","stripeIDField","name","type","admin","position","readOnly","label","saveToJWT","skipSyncField","docUrlField","components","Field","custom","isTestKey","nameOfIDField","stripeResourceType","fields"],"mappings":"AAYA,OAAO,MAAMA,YAAY,CAAC,EAAEC,UAAU,EAAEC,YAAY,EAAEC,UAAU,EAAQ;IACtE,MAAMC,gBAAuB;QAC3BC,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,UAAU;YACVC,UAAU;QACZ;QACAC,OAAO;QACPC,WAAW;IACb;IAEA,MAAMC,gBAAuB;QAC3BP,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,UAAU;YACVC,UAAU;QACZ;QACAC,OAAO;IACT;IAEA,MAAMG,cAAqB;QACzBR,MAAM;QACNC,MAAM;QACNC,OAAO;YACLO,YAAY;gBACVC,OAAO;YACT;YACAC,QAAQ;gBACNC,WAAWf,aAAae,SAAS;gBACjCC,eAAe;gBACfC,oBAAoBhB,WAAWgB,kBAAkB;YACnD;YACAX,UAAU;QACZ;IACF;IAEA,MAAMY,SAAS;WAAInB,WAAWmB,MAAM;QAAEhB;QAAeQ;QAAeC;KAAY;IAEhF,OAAOO;AACT,EAAC"}
1
+ {"version":3,"sources":["../../src/fields/getFields.ts"],"sourcesContent":["import type { CollectionConfig, Field } from 'payload'\n\nimport type { SanitizedStripePluginConfig } from '../types.js'\n\ninterface Args {\n collection: CollectionConfig\n pluginConfig: SanitizedStripePluginConfig\n syncConfig: {\n stripeResourceType: string\n }\n}\n\nexport const getFields = ({ collection, pluginConfig, syncConfig }: Args): Field[] => {\n const stripeIDField: Field = {\n name: 'stripeID',\n type: 'text',\n access: {\n create: () => false,\n update: () => false,\n },\n admin: {\n position: 'sidebar',\n readOnly: true,\n },\n label: 'Stripe ID',\n saveToJWT: true,\n }\n\n const skipSyncField: Field = {\n name: 'skipSync',\n type: 'checkbox',\n access: {\n create: () => false,\n update: () => false,\n },\n admin: {\n position: 'sidebar',\n readOnly: true,\n },\n label: 'Skip Sync',\n }\n\n const docUrlField: Field = {\n name: 'docUrl',\n type: 'ui',\n admin: {\n components: {\n Field: '@payloadcms/plugin-stripe/client#LinkToDoc',\n },\n custom: {\n isTestKey: pluginConfig.isTestKey,\n nameOfIDField: 'stripeID',\n stripeResourceType: syncConfig.stripeResourceType,\n },\n position: 'sidebar',\n },\n }\n\n const fields = [...collection.fields, stripeIDField, skipSyncField, docUrlField]\n\n return fields\n}\n"],"names":["getFields","collection","pluginConfig","syncConfig","stripeIDField","name","type","access","create","update","admin","position","readOnly","label","saveToJWT","skipSyncField","docUrlField","components","Field","custom","isTestKey","nameOfIDField","stripeResourceType","fields"],"mappings":"AAYA,OAAO,MAAMA,YAAY,CAAC,EAAEC,UAAU,EAAEC,YAAY,EAAEC,UAAU,EAAQ;IACtE,MAAMC,gBAAuB;QAC3BC,MAAM;QACNC,MAAM;QACNC,QAAQ;YACNC,QAAQ,IAAM;YACdC,QAAQ,IAAM;QAChB;QACAC,OAAO;YACLC,UAAU;YACVC,UAAU;QACZ;QACAC,OAAO;QACPC,WAAW;IACb;IAEA,MAAMC,gBAAuB;QAC3BV,MAAM;QACNC,MAAM;QACNC,QAAQ;YACNC,QAAQ,IAAM;YACdC,QAAQ,IAAM;QAChB;QACAC,OAAO;YACLC,UAAU;YACVC,UAAU;QACZ;QACAC,OAAO;IACT;IAEA,MAAMG,cAAqB;QACzBX,MAAM;QACNC,MAAM;QACNI,OAAO;YACLO,YAAY;gBACVC,OAAO;YACT;YACAC,QAAQ;gBACNC,WAAWlB,aAAakB,SAAS;gBACjCC,eAAe;gBACfC,oBAAoBnB,WAAWmB,kBAAkB;YACnD;YACAX,UAAU;QACZ;IACF;IAEA,MAAMY,SAAS;WAAItB,WAAWsB,MAAM;QAAEnB;QAAeW;QAAeC;KAAY;IAEhF,OAAOO;AACT,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"createNewInStripe.d.ts","sourceRoot":"","sources":["../../src/hooks/createNewInStripe.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,4BAA4B,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAK7E,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAA;AAIrD,KAAK,4BAA4B,GAAG;IAClC,UAAU,EAAE,gBAAgB,CAAA;CAC7B,GAAG,IAAI,CAAC,UAAU,CAAC,4BAA4B,CAAC,CAAC,CAAC,CAAC,EAAE,YAAY,CAAC,CAAA;AAEnE,MAAM,MAAM,oCAAoC,GAAG,CACjD,IAAI,EAAE;IACJ,UAAU,CAAC,EAAE,gBAAgB,CAAA;IAC7B,YAAY,CAAC,EAAE,kBAAkB,CAAA;CAClC,GAAG,4BAA4B,KAC7B,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAA;AAE1B,eAAO,MAAM,iBAAiB,EAAE,oCA0H/B,CAAA"}
1
+ {"version":3,"file":"createNewInStripe.d.ts","sourceRoot":"","sources":["../../src/hooks/createNewInStripe.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,4BAA4B,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAK7E,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAA;AAIrD,KAAK,4BAA4B,GAAG;IAClC,UAAU,EAAE,gBAAgB,CAAA;CAC7B,GAAG,IAAI,CAAC,UAAU,CAAC,4BAA4B,CAAC,CAAC,CAAC,CAAC,EAAE,YAAY,CAAC,CAAA;AAEnE,MAAM,MAAM,oCAAoC,GAAG,CACjD,IAAI,EAAE;IACJ,UAAU,CAAC,EAAE,gBAAgB,CAAA;IAC7B,YAAY,CAAC,EAAE,kBAAkB,CAAA;CAClC,GAAG,4BAA4B,KAC7B,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAA;AAE1B,eAAO,MAAM,iBAAiB,EAAE,oCAoH/B,CAAA"}
@@ -1,6 +1,6 @@
1
1
  import { APIError } from 'payload';
2
2
  import Stripe from 'stripe';
3
- import { deepen } from '../utilities/deepen.js';
3
+ import { getSyncedFields } from '../utilities/deepen.js';
4
4
  export const createNewInStripe = async (args)=>{
5
5
  const { collection, data, operation, pluginConfig, req } = args;
6
6
  const { logs, sync } = pluginConfig || {};
@@ -24,12 +24,11 @@ export const createNewInStripe = async (args)=>{
24
24
  const syncConfig = sync?.find((conf)=>conf.collection === collectionSlug);
25
25
  if (syncConfig) {
26
26
  // combine all fields of this object and match their respective values within the document
27
- let syncedFields = syncConfig.fields.reduce((acc, field)=>{
28
- const { fieldPath, stripeProperty } = field;
29
- acc[stripeProperty] = dataRef[fieldPath];
30
- return acc;
31
- }, {});
32
- syncedFields = deepen(syncedFields);
27
+ const syncedFields = getSyncedFields({
28
+ data: dataRef,
29
+ fields: syncConfig.fields,
30
+ source: 'payload'
31
+ });
33
32
  // api version can only be the latest, stripe recommends ts ignoring it
34
33
  const stripe = new Stripe(pluginConfig?.stripeSecretKey || '', {
35
34
  apiVersion: '2022-08-01'
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/hooks/createNewInStripe.ts"],"sourcesContent":["import type { CollectionBeforeValidateHook, CollectionConfig } from 'payload'\n\nimport { APIError } from 'payload'\nimport Stripe from 'stripe'\n\nimport type { StripePluginConfig } from '../types.js'\n\nimport { deepen } from '../utilities/deepen.js'\n\ntype HookArgsWithCustomCollection = {\n collection: CollectionConfig\n} & Omit<Parameters<CollectionBeforeValidateHook>[0], 'collection'>\n\nexport type CollectionBeforeValidateHookWithArgs = (\n args: {\n collection?: CollectionConfig\n pluginConfig?: StripePluginConfig\n } & HookArgsWithCustomCollection,\n) => Promise<Partial<any>>\n\nexport const createNewInStripe: CollectionBeforeValidateHookWithArgs = async (args) => {\n const { collection, data, operation, pluginConfig, req } = args\n\n const { logs, sync } = pluginConfig || {}\n\n const payload = req?.payload\n\n const dataRef = data || {}\n\n if (process.env.NODE_ENV === 'test') {\n dataRef.stripeID = 'test'\n return dataRef\n }\n\n if (payload) {\n if (data?.skipSync) {\n if (logs) {\n payload.logger.info(`Bypassing collection-level hooks.`)\n }\n } else {\n // initialize as 'false' so that all Payload admin events sync to Stripe\n // then conditionally set to 'true' to for events that originate from webhooks\n // this will prevent webhook events from triggering an unnecessary sync / infinite loop\n dataRef.skipSync = false\n\n const { slug: collectionSlug } = collection || {}\n const syncConfig = sync?.find((conf) => conf.collection === collectionSlug)\n\n if (syncConfig) {\n // combine all fields of this object and match their respective values within the document\n let syncedFields = syncConfig.fields.reduce(\n (acc, field) => {\n const { fieldPath, stripeProperty } = field\n\n acc[stripeProperty] = dataRef[fieldPath]\n return acc\n },\n {} as Record<string, any>,\n )\n\n syncedFields = deepen(syncedFields)\n\n // api version can only be the latest, stripe recommends ts ignoring it\n const stripe = new Stripe(pluginConfig?.stripeSecretKey || '', { apiVersion: '2022-08-01' })\n\n if (operation === 'update') {\n if (logs) {\n payload.logger.info(\n `A '${collectionSlug}' document has changed in Payload with ID: '${data?.id}', syncing with Stripe...`,\n )\n }\n\n // NOTE: the Stripe document will be created in the \"afterChange\" hook, so create a new stripe document here if no stripeID exists\n if (!dataRef.stripeID) {\n try {\n // NOTE: Typed as \"any\" because the \"create\" method is not standard across all Stripe resources\n const stripeResource = await stripe?.[syncConfig.stripeResourceType]?.create(\n // @ts-expect-error\n syncedFields,\n )\n\n if (logs) {\n payload.logger.info(\n `✅ Successfully created new '${syncConfig.stripeResourceType}' resource in Stripe with ID: '${stripeResource.id}'.`,\n )\n }\n\n dataRef.stripeID = stripeResource.id\n\n // NOTE: this is to prevent sync in the \"afterChange\" hook\n dataRef.skipSync = true\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : error\n if (logs) {\n payload.logger.error(`- Error creating Stripe document: ${msg}`)\n }\n }\n }\n }\n\n if (operation === 'create') {\n if (logs) {\n payload.logger.info(\n `A new '${collectionSlug}' document was created in Payload with ID: '${data?.id}', syncing with Stripe...`,\n )\n }\n\n try {\n if (logs) {\n payload.logger.info(\n `- Creating new '${syncConfig.stripeResourceType}' resource in Stripe...`,\n )\n }\n\n // NOTE: Typed as \"any\" because the \"create\" method is not standard across all Stripe resources\n const stripeResource = await stripe?.[syncConfig.stripeResourceType]?.create(\n // @ts-expect-error\n syncedFields,\n )\n\n if (logs) {\n payload.logger.info(\n `✅ Successfully created new '${syncConfig.stripeResourceType}' resource in Stripe with ID: '${stripeResource.id}'.`,\n )\n }\n\n dataRef.stripeID = stripeResource.id\n\n // IMPORTANT: this is to prevent sync in the \"afterChange\" hook\n dataRef.skipSync = true\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : error\n throw new APIError(\n `Failed to create new '${syncConfig.stripeResourceType}' resource in Stripe: ${msg}`,\n )\n }\n }\n }\n }\n }\n\n return dataRef\n}\n"],"names":["APIError","Stripe","deepen","createNewInStripe","args","collection","data","operation","pluginConfig","req","logs","sync","payload","dataRef","process","env","NODE_ENV","stripeID","skipSync","logger","info","slug","collectionSlug","syncConfig","find","conf","syncedFields","fields","reduce","acc","field","fieldPath","stripeProperty","stripe","stripeSecretKey","apiVersion","id","stripeResource","stripeResourceType","create","error","msg","Error","message"],"mappings":"AAEA,SAASA,QAAQ,QAAQ,UAAS;AAClC,OAAOC,YAAY,SAAQ;AAI3B,SAASC,MAAM,QAAQ,yBAAwB;AAa/C,OAAO,MAAMC,oBAA0D,OAAOC;IAC5E,MAAM,EAAEC,UAAU,EAAEC,IAAI,EAAEC,SAAS,EAAEC,YAAY,EAAEC,GAAG,EAAE,GAAGL;IAE3D,MAAM,EAAEM,IAAI,EAAEC,IAAI,EAAE,GAAGH,gBAAgB,CAAC;IAExC,MAAMI,UAAUH,KAAKG;IAErB,MAAMC,UAAUP,QAAQ,CAAC;IAEzB,IAAIQ,QAAQC,GAAG,CAACC,QAAQ,KAAK,QAAQ;QACnCH,QAAQI,QAAQ,GAAG;QACnB,OAAOJ;IACT;IAEA,IAAID,SAAS;QACX,IAAIN,MAAMY,UAAU;YAClB,IAAIR,MAAM;gBACRE,QAAQO,MAAM,CAACC,IAAI,CAAC,CAAC,iCAAiC,CAAC;YACzD;QACF,OAAO;YACL,wEAAwE;YACxE,8EAA8E;YAC9E,uFAAuF;YACvF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ACRE,QAAQO,MAAM,CAACqB,KAAK,CAAC,CAAC,kCAAkC,EAAEC,KAAK;4BACjE;wBACF;oBACF;gBACF;gBAEA,IAAIlC,cAAc,UAAU;oBAC1B,IAAIG,MAAM;wBACRE,QAAQO,MAAM,CAACC,IAAI,CACjB,CAAC,OAAO,EAAEE,eAAe,4CAA4C,EAAEhB,MAAM8B,GAAG,yBAAyB,CAAC;oBAE9G;oBAEA,IAAI;wBACF,IAAI1B,MAAM;4BACRE,QAAQO,MAAM,CAACC,IAAI,CACjB,CAAC,gBAAgB,EAAEG,WAAWe,kBAAkB,CAAC,uBAAuB,CAAC;wBAE7E;wBAEA,+FAA+F;wBAC/F,MAAMD,iBAAiB,MAAMJ,QAAQ,CAACV,WAAWe,kBAAkB,CAAC,EAAEC,OACpE,mBAAmB;wBACnBb;wBAGF,IAAIhB,MAAM;4BACRE,QAAQO,MAAM,CAACC,IAAI,CACjB,CAAC,4BAA4B,EAAEG,WAAWe,kBAAkB,CAAC,+BAA+B,EAAED,eAAeD,EAAE,CAAC,EAAE,CAAC;wBAEvH;wBAEAvB,QAAQI,QAAQ,GAAGoB,eAAeD,EAAE;wBAEpC,+DAA+D;wBAC/DvB,QAAQK,QAAQ,GAAG;oBACrB,EAAE,OAAOsB,OAAgB;wBACvB,MAAMC,MAAMD,iBAAiBE,QAAQF,MAAMG,OAAO,GAAGH;wBACrD,MAAM,IAAIxC,SACR,CAAC,sBAAsB,EAAEuB,WAAWe,kBAAkB,CAAC,sBAAsB,EAAEG,KAAK;oBAExF;gBACF;YACF;QACF;IACF;IAEA,OAAO5B;AACT,EAAC"}
1
+ {"version":3,"sources":["../../src/hooks/createNewInStripe.ts"],"sourcesContent":["import type { CollectionBeforeValidateHook, CollectionConfig } from 'payload'\n\nimport { APIError } from 'payload'\nimport Stripe from 'stripe'\n\nimport type { StripePluginConfig } from '../types.js'\n\nimport { getSyncedFields } from '../utilities/deepen.js'\n\ntype HookArgsWithCustomCollection = {\n collection: CollectionConfig\n} & Omit<Parameters<CollectionBeforeValidateHook>[0], 'collection'>\n\nexport type CollectionBeforeValidateHookWithArgs = (\n args: {\n collection?: CollectionConfig\n pluginConfig?: StripePluginConfig\n } & HookArgsWithCustomCollection,\n) => Promise<Partial<any>>\n\nexport const createNewInStripe: CollectionBeforeValidateHookWithArgs = async (args) => {\n const { collection, data, operation, pluginConfig, req } = args\n\n const { logs, sync } = pluginConfig || {}\n\n const payload = req?.payload\n\n const dataRef = data || {}\n\n if (process.env.NODE_ENV === 'test') {\n dataRef.stripeID = 'test'\n return dataRef\n }\n\n if (payload) {\n if (data?.skipSync) {\n if (logs) {\n payload.logger.info(`Bypassing collection-level hooks.`)\n }\n } else {\n // initialize as 'false' so that all Payload admin events sync to Stripe\n // then conditionally set to 'true' to for events that originate from webhooks\n // this will prevent webhook events from triggering an unnecessary sync / infinite loop\n dataRef.skipSync = false\n\n const { slug: collectionSlug } = collection || {}\n const syncConfig = sync?.find((conf) => conf.collection === collectionSlug)\n\n if (syncConfig) {\n // combine all fields of this object and match their respective values within the document\n const syncedFields = getSyncedFields({\n data: dataRef,\n fields: syncConfig.fields,\n source: 'payload',\n })\n\n // api version can only be the latest, stripe recommends ts ignoring it\n const stripe = new Stripe(pluginConfig?.stripeSecretKey || '', { apiVersion: '2022-08-01' })\n\n if (operation === 'update') {\n if (logs) {\n payload.logger.info(\n `A '${collectionSlug}' document has changed in Payload with ID: '${data?.id}', syncing with Stripe...`,\n )\n }\n\n // NOTE: the Stripe document will be created in the \"afterChange\" hook, so create a new stripe document here if no stripeID exists\n if (!dataRef.stripeID) {\n try {\n // NOTE: Typed as \"any\" because the \"create\" method is not standard across all Stripe resources\n const stripeResource = await stripe?.[syncConfig.stripeResourceType]?.create(\n // @ts-expect-error\n syncedFields,\n )\n\n if (logs) {\n payload.logger.info(\n `✅ Successfully created new '${syncConfig.stripeResourceType}' resource in Stripe with ID: '${stripeResource.id}'.`,\n )\n }\n\n dataRef.stripeID = stripeResource.id\n\n // NOTE: this is to prevent sync in the \"afterChange\" hook\n dataRef.skipSync = true\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : error\n if (logs) {\n payload.logger.error(`- Error creating Stripe document: ${msg}`)\n }\n }\n }\n }\n\n if (operation === 'create') {\n if (logs) {\n payload.logger.info(\n `A new '${collectionSlug}' document was created in Payload with ID: '${data?.id}', syncing with Stripe...`,\n )\n }\n\n try {\n if (logs) {\n payload.logger.info(\n `- Creating new '${syncConfig.stripeResourceType}' resource in Stripe...`,\n )\n }\n\n // NOTE: Typed as \"any\" because the \"create\" method is not standard across all Stripe resources\n const stripeResource = await stripe?.[syncConfig.stripeResourceType]?.create(\n // @ts-expect-error\n syncedFields,\n )\n\n if (logs) {\n payload.logger.info(\n `✅ Successfully created new '${syncConfig.stripeResourceType}' resource in Stripe with ID: '${stripeResource.id}'.`,\n )\n }\n\n dataRef.stripeID = stripeResource.id\n\n // IMPORTANT: this is to prevent sync in the \"afterChange\" hook\n dataRef.skipSync = true\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : error\n throw new APIError(\n `Failed to create new '${syncConfig.stripeResourceType}' resource in Stripe: ${msg}`,\n )\n }\n }\n }\n }\n }\n\n return dataRef\n}\n"],"names":["APIError","Stripe","getSyncedFields","createNewInStripe","args","collection","data","operation","pluginConfig","req","logs","sync","payload","dataRef","process","env","NODE_ENV","stripeID","skipSync","logger","info","slug","collectionSlug","syncConfig","find","conf","syncedFields","fields","source","stripe","stripeSecretKey","apiVersion","id","stripeResource","stripeResourceType","create","error","msg","Error","message"],"mappings":"AAEA,SAASA,QAAQ,QAAQ,UAAS;AAClC,OAAOC,YAAY,SAAQ;AAI3B,SAASC,eAAe,QAAQ,yBAAwB;AAaxD,OAAO,MAAMC,oBAA0D,OAAOC;IAC5E,MAAM,EAAEC,UAAU,EAAEC,IAAI,EAAEC,SAAS,EAAEC,YAAY,EAAEC,GAAG,EAAE,GAAGL;IAE3D,MAAM,EAAEM,IAAI,EAAEC,IAAI,EAAE,GAAGH,gBA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@@
1
- {"version":3,"file":"syncExistingWithStripe.d.ts","sourceRoot":"","sources":["../../src/hooks/syncExistingWithStripe.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,0BAA0B,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAK3E,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAA;AAIrD,KAAK,4BAA4B,GAAG;IAClC,UAAU,EAAE,gBAAgB,CAAA;CAC7B,GAAG,IAAI,CAAC,UAAU,CAAC,0BAA0B,CAAC,CAAC,CAAC,CAAC,EAAE,YAAY,CAAC,CAAA;AAEjE,MAAM,MAAM,kCAAkC,GAAG,CAC/C,IAAI,EAAE;IACJ,UAAU,CAAC,EAAE,gBAAgB,CAAA;IAC7B,YAAY,CAAC,EAAE,kBAAkB,CAAA;CAClC,GAAG,4BAA4B,KAC7B,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAA;AAE1B,eAAO,MAAM,sBAAsB,EAAE,kCAwEpC,CAAA"}
1
+ {"version":3,"file":"syncExistingWithStripe.d.ts","sourceRoot":"","sources":["../../src/hooks/syncExistingWithStripe.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,0BAA0B,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAK3E,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAA;AAIrD,KAAK,4BAA4B,GAAG;IAClC,UAAU,EAAE,gBAAgB,CAAA;CAC7B,GAAG,IAAI,CAAC,UAAU,CAAC,0BAA0B,CAAC,CAAC,CAAC,CAAC,EAAE,YAAY,CAAC,CAAA;AAEjE,MAAM,MAAM,kCAAkC,GAAG,CAC/C,IAAI,EAAE;IACJ,UAAU,CAAC,EAAE,gBAAgB,CAAA;IAC7B,YAAY,CAAC,EAAE,kBAAkB,CAAA;CAClC,GAAG,4BAA4B,KAC7B,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAA;AAE1B,eAAO,MAAM,sBAAsB,EAAE,kCAkEpC,CAAA"}
@@ -1,6 +1,6 @@
1
1
  import { APIError } from 'payload';
2
2
  import Stripe from 'stripe';
3
- import { deepen } from '../utilities/deepen.js';
3
+ import { getSyncedFields } from '../utilities/deepen.js';
4
4
  export const syncExistingWithStripe = async (args)=>{
5
5
  const { collection, data, operation, originalDoc, pluginConfig, req } = args;
6
6
  const { logs, sync } = pluginConfig || {};
@@ -11,12 +11,11 @@ export const syncExistingWithStripe = async (args)=>{
11
11
  if (syncConfig) {
12
12
  if (operation === 'update') {
13
13
  // combine all fields of this object and match their respective values within the document
14
- let syncedFields = syncConfig.fields.reduce((acc, field)=>{
15
- const { fieldPath, stripeProperty } = field;
16
- acc[stripeProperty] = data[fieldPath];
17
- return acc;
18
- }, {});
19
- syncedFields = deepen(syncedFields);
14
+ const syncedFields = getSyncedFields({
15
+ data,
16
+ fields: syncConfig.fields,
17
+ source: 'payload'
18
+ });
20
19
  if (logs) {
21
20
  payload.logger.info(`A '${collectionSlug}' document has changed in Payload with ID: '${originalDoc?._id}', syncing with Stripe...`);
22
21
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/hooks/syncExistingWithStripe.ts"],"sourcesContent":["import type { CollectionBeforeChangeHook, CollectionConfig } from 'payload'\n\nimport { APIError } from 'payload'\nimport Stripe from 'stripe'\n\nimport type { StripePluginConfig } from '../types.js'\n\nimport { deepen } from '../utilities/deepen.js'\n\ntype HookArgsWithCustomCollection = {\n collection: CollectionConfig\n} & Omit<Parameters<CollectionBeforeChangeHook>[0], 'collection'>\n\nexport type CollectionBeforeChangeHookWithArgs = (\n args: {\n collection?: CollectionConfig\n pluginConfig?: StripePluginConfig\n } & HookArgsWithCustomCollection,\n) => Promise<Partial<any>>\n\nexport const syncExistingWithStripe: CollectionBeforeChangeHookWithArgs = async (args) => {\n const { collection, data, operation, originalDoc, pluginConfig, req } = args\n\n const { logs, sync } = pluginConfig || {}\n\n const { payload } = req\n\n const { slug: collectionSlug } = collection || {}\n\n if (process.env.NODE_ENV !== 'test' && !data.skipSync) {\n const syncConfig = sync?.find((conf) => conf.collection === collectionSlug)\n\n if (syncConfig) {\n if (operation === 'update') {\n // combine all fields of this object and match their respective values within the document\n let syncedFields = syncConfig.fields.reduce(\n (acc, field) => {\n const { fieldPath, stripeProperty } = field\n\n acc[stripeProperty] = data[fieldPath]\n return acc\n },\n {} as Record<string, any>,\n )\n\n syncedFields = deepen(syncedFields)\n\n if (logs) {\n payload.logger.info(\n `A '${collectionSlug}' document has changed in Payload with ID: '${originalDoc?._id}', syncing with Stripe...`,\n )\n }\n\n if (!data.stripeID) {\n // NOTE: the \"beforeValidate\" hook populates this\n if (logs) {\n payload.logger.error(`- There is no Stripe ID for this document, skipping.`)\n }\n } else {\n if (logs) {\n payload.logger.info(`- Syncing to Stripe resource with ID: '${data.stripeID}'...`)\n }\n\n try {\n // api version can only be the latest, stripe recommends ts ignoring it\n const stripe = new Stripe(pluginConfig?.stripeSecretKey || '', {\n apiVersion: '2022-08-01',\n })\n\n const stripeResource = await stripe?.[syncConfig?.stripeResourceType]?.update(\n data.stripeID,\n syncedFields,\n )\n\n if (logs) {\n payload.logger.info(\n `✅ Successfully synced Stripe resource with ID: '${stripeResource.id}'.`,\n )\n }\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : error\n throw new APIError(`Failed to sync document with ID: '${data.id}' to Stripe: ${msg}`)\n }\n }\n }\n }\n }\n\n // Set back to 'false' so that all changes continue to sync to Stripe, see note in './createNewInStripe.ts'\n data.skipSync = false\n\n return data\n}\n"],"names":["APIError","Stripe","deepen","syncExistingWithStripe","args","collection","data","operation","originalDoc","pluginConfig","req","logs","sync","payload","slug","collectionSlug","process","env","NODE_ENV","skipSync","syncConfig","find","conf","syncedFields","fields","reduce","acc","field","fieldPath","stripeProperty","logger","info","_id","stripeID","error","stripe","stripeSecretKey","apiVersion","stripeResource","stripeResourceType","update","id","msg","Error","message"],"mappings":"AAEA,SAASA,QAAQ,QAAQ,UAA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F;oBAEA,IAAI;wBACF,uEAAuE;wBACvE,MAAME,SAAS,IAAIlC,OAAOQ,cAAc2B,mBAAmB,IAAI;4BAC7DC,YAAY;wBACd;wBAEA,MAAMC,iBAAiB,MAAMH,QAAQ,CAACf,YAAYmB,mBAAmB,EAAEC,OACrElC,KAAK2B,QAAQ,EACbV;wBAGF,IAAIZ,MAAM;4BACRE,QAAQiB,MAAM,CAACC,IAAI,CACjB,CAAC,gDAAgD,EAAEO,eAAeG,EAAE,CAAC,EAAE,CAAC;wBAE5E;oBACF,EAAE,OAAOP,OAAgB;wBACvB,MAAMQ,MAAMR,iBAAiBS,QAAQT,MAAMU,OAAO,GAAGV;wBACrD,MAAM,IAAIlC,SAAS,CAAC,kCAAkC,EAAEM,KAAKmC,EAAE,CAAC,aAAa,EAAEC,KAAK;oBACtF;gBACF;YACF;QACF;IACF;IAEA,2GAA2G;IAC3GpC,KAAKa,QAAQ,GAAG;IAEhB,OAAOb;AACT,EAAC"}
1
+ {"version":3,"sources":["../../src/hooks/syncExistingWithStripe.ts"],"sourcesContent":["import type { CollectionBeforeChangeHook, CollectionConfig } from 'payload'\n\nimport { APIError } from 'payload'\nimport Stripe from 'stripe'\n\nimport type { StripePluginConfig } from '../types.js'\n\nimport { getSyncedFields } from '../utilities/deepen.js'\n\ntype HookArgsWithCustomCollection = {\n collection: CollectionConfig\n} & Omit<Parameters<CollectionBeforeChangeHook>[0], 'collection'>\n\nexport type CollectionBeforeChangeHookWithArgs = (\n args: {\n collection?: CollectionConfig\n pluginConfig?: StripePluginConfig\n } & HookArgsWithCustomCollection,\n) => Promise<Partial<any>>\n\nexport const syncExistingWithStripe: CollectionBeforeChangeHookWithArgs = async (args) => {\n const { collection, data, operation, originalDoc, pluginConfig, req } = args\n\n const { logs, sync } = pluginConfig || {}\n\n const { payload } = req\n\n const { slug: collectionSlug } = collection || {}\n\n if (process.env.NODE_ENV !== 'test' && !data.skipSync) {\n const syncConfig = sync?.find((conf) => conf.collection === collectionSlug)\n\n if (syncConfig) {\n if (operation === 'update') {\n // combine all fields of this object and match their respective values within the document\n const syncedFields = getSyncedFields({\n data,\n fields: syncConfig.fields,\n source: 'payload',\n })\n\n if (logs) {\n payload.logger.info(\n `A '${collectionSlug}' document has changed in Payload with ID: '${originalDoc?._id}', syncing with Stripe...`,\n )\n }\n\n if (!data.stripeID) {\n // NOTE: the \"beforeValidate\" hook populates this\n if (logs) {\n payload.logger.error(`- There is no Stripe ID for this document, skipping.`)\n }\n } else {\n if (logs) {\n payload.logger.info(`- Syncing to Stripe resource with ID: '${data.stripeID}'...`)\n }\n\n try {\n // api version can only be the latest, stripe recommends ts ignoring it\n const stripe = new Stripe(pluginConfig?.stripeSecretKey || '', {\n apiVersion: '2022-08-01',\n })\n\n const stripeResource = await stripe?.[syncConfig?.stripeResourceType]?.update(\n data.stripeID,\n syncedFields,\n )\n\n if (logs) {\n payload.logger.info(\n `✅ Successfully synced Stripe resource with ID: '${stripeResource.id}'.`,\n )\n }\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : error\n throw new APIError(`Failed to sync document with ID: '${data.id}' to Stripe: ${msg}`)\n }\n }\n }\n }\n }\n\n // Set back to 'false' so that all changes continue to sync to Stripe, see note in './createNewInStripe.ts'\n data.skipSync = false\n\n return data\n}\n"],"names":["APIError","Stripe","getSyncedFields","syncExistingWithStripe","args","collection","data","operation","originalDoc","pluginConfig","req","logs","sync","payload","slug","collectionSlug","process","env","NODE_ENV","skipSync","syncConfig","find","conf","syncedFields","fields","source","logger","info","_id","stripeID","error","stripe","stripeSecretKey","apiVersion","stripeResource","stripeResourceType","update","id","msg","Error","message"],"mappings":"AAEA,SAASA,QAAQ,QAAQ,UAAS;AAClC,OAAOC,YAAY,SAAQ;AAI3B,SAASC,eAAe,QAAQ,yBAAwB;AAaxD,OAAO,MAAMC,yBAA6D,OAAOC;IAC/E,MAAM,EAAEC,UAAU,EAAEC,IAAI,EAAEC,SAAS,EAAEC,WAAW,EAAEC,YAAY,EAAEC,GA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AE,OAAOP,OAAgB;wBACvB,MAAMQ,MAAMR,iBAAiBS,QAAQT,MAAMU,OAAO,GAAGV;wBACrD,MAAM,IAAI9B,SAAS,CAAC,kCAAkC,EAAEM,KAAK+B,EAAE,CAAC,aAAa,EAAEC,KAAK;oBACtF;gBACF;YACF;QACF;IACF;IAEA,2GAA2G;IAC3GhC,KAAKa,QAAQ,GAAG;IAEhB,OAAOb;AACT,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAA+B,kBAAkB,EAAE,MAAM,YAAY,CAAA;AASjF,OAAO,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAA;AAExD,eAAO,MAAM,YAAY,2DAoGvB,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAA+B,kBAAkB,EAAE,MAAM,YAAY,CAAA;AAUjF,OAAO,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAA;AAExD,eAAO,MAAM,YAAY,2DAoGvB,CAAA"}
package/dist/index.js CHANGED
@@ -5,6 +5,7 @@ import { deleteFromStripe } from './hooks/deleteFromStripe.js';
5
5
  import { syncExistingWithStripe } from './hooks/syncExistingWithStripe.js';
6
6
  import { stripeREST } from './routes/rest.js';
7
7
  import { stripeWebhooks } from './routes/webhooks.js';
8
+ import { sanitizeStripeRESTConfig } from './utilities/sanitizeStripeRESTConfig.js';
8
9
  export { stripeProxy } from './utilities/stripeProxy.js';
9
10
  export const stripePlugin = definePlugin({
10
11
  slug: '@payloadcms/plugin-stripe',
@@ -13,7 +14,9 @@ export const stripePlugin = definePlugin({
13
14
  // set config defaults here
14
15
  const pluginConfig = {
15
16
  ...incomingStripeConfig,
16
- rest: incomingStripeConfig?.rest ?? false,
17
+ rest: sanitizeStripeRESTConfig({
18
+ rest: incomingStripeConfig?.rest
19
+ }),
17
20
  sync: incomingStripeConfig?.sync || []
18
21
  };
19
22
  // NOTE: env variables are never passed to the client, but we need to know if `stripeSecretKey` is a test key
@@ -34,7 +37,7 @@ export const stripePlugin = definePlugin({
34
37
  path: '/stripe/webhooks'
35
38
  }
36
39
  ];
37
- if (incomingStripeConfig?.rest) {
40
+ if (pluginConfig.rest) {
38
41
  endpoints.push({
39
42
  handler: async (req)=>{
40
43
  const res = await stripeREST({
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Endpoint } from 'payload'\n\nimport { definePlugin } from 'payload'\n\nimport type { SanitizedStripePluginConfig, StripePluginConfig } from './types.js'\n\nimport { getFields } from './fields/getFields.js'\nimport { createNewInStripe } from './hooks/createNewInStripe.js'\nimport { deleteFromStripe } from './hooks/deleteFromStripe.js'\nimport { syncExistingWithStripe } from './hooks/syncExistingWithStripe.js'\nimport { stripeREST } from './routes/rest.js'\nimport { stripeWebhooks } from './routes/webhooks.js'\n\nexport { stripeProxy } from './utilities/stripeProxy.js'\n\nexport const stripePlugin = definePlugin<StripePluginConfig>({\n slug: '@payloadcms/plugin-stripe',\n plugin: ({ config, options: incomingStripeConfig }) => {\n const { collections } = config\n\n // set config defaults here\n const pluginConfig: SanitizedStripePluginConfig = {\n ...incomingStripeConfig,\n rest: incomingStripeConfig?.rest ?? false,\n sync: incomingStripeConfig?.sync || [],\n }\n\n // NOTE: env variables are never passed to the client, but we need to know if `stripeSecretKey` is a test key\n // unfortunately we must set the 'isTestKey' property on the config instead of using the following code:\n // const isTestKey = stripeConfig.stripeSecretKey?.startsWith('sk_test_');\n\n const endpoints: Endpoint[] = [\n ...(config?.endpoints || []),\n {\n handler: async (req) => {\n const res = await stripeWebhooks({\n config,\n pluginConfig,\n req,\n })\n\n return res\n },\n method: 'post',\n path: '/stripe/webhooks',\n },\n ]\n\n if (incomingStripeConfig?.rest) {\n endpoints.push({\n handler: async (req) => {\n const res = await stripeREST({\n pluginConfig,\n req,\n })\n\n return res\n },\n method: 'post' as Endpoint['method'],\n path: '/stripe/rest',\n })\n }\n\n for (const collection of collections!) {\n const { hooks: existingHooks } = collection\n\n const syncConfig = pluginConfig.sync?.find((sync) => sync.collection === collection.slug)\n\n if (!syncConfig) {\n continue\n }\n const fields = getFields({\n collection,\n pluginConfig,\n syncConfig,\n })\n collection.fields = fields\n\n if (!collection.hooks) {\n collection.hooks = {}\n }\n\n collection.hooks.afterDelete = [\n ...(existingHooks?.afterDelete || []),\n (args) =>\n deleteFromStripe({\n ...args,\n collection,\n pluginConfig,\n }),\n ]\n collection.hooks.beforeChange = [\n ...(existingHooks?.beforeChange || []),\n (args) =>\n syncExistingWithStripe({\n ...args,\n collection,\n pluginConfig,\n }),\n ]\n collection.hooks.beforeValidate = [\n ...(existingHooks?.beforeValidate || []),\n (args) =>\n createNewInStripe({\n ...args,\n collection,\n pluginConfig,\n }),\n ]\n }\n\n config.endpoints = endpoints\n\n return config\n },\n})\n"],"names":["definePlugin","getFields","createNewInStripe","deleteFromStripe","syncExistingWithStripe","stripeREST","stripeWebhooks","stripeProxy","stripePlugin","slug","plugin","config","options","incomingStripeConfig","collections","pluginConfig","rest","sync","endpoints","handler","req","res","method","path","push","collection","hooks","existingHooks","syncConfig","find","fields","afterDelete","args","beforeChange","beforeValidate"],"mappings":"AAEA,SAASA,YAAY,QAAQ,UAAS;AAItC,SAASC,SAAS,QAAQ,wBAAuB;AACjD,SAASC,iBAAiB,QAAQ,+BAA8B;AAChE,SAASC,gBAAgB,QAAQ,8BAA6B;AAC9D,SAASC,sBAAsB,QAAQ,oCAAmC;AAC1E,SAASC,UAAU,QAAQ,mBAAkB;AAC7C,SAASC,cAAc,QAAQ,uBAAsB;AAErD,SAASC,WAAW,QAAQ,6BAA4B;AAExD,OAAO,MAAMC,eAAeR,aAAiC;IAC3DS,MAAM;IACNC,QAAQ,CAAC,EAAEC,MAAM,EAAEC,SAASC,oBAAoB,EAAE;QAChD,MAAM,EAAEC,WAAW,EAAE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,WAAWC,KAAK,CAACQ,cAAc,GAAG;mBAC5BP,eAAeO,kBAAkB,EAAE;gBACvC,CAACF,OACC9B,kBAAkB;wBAChB,GAAG8B,IAAI;wBACPP;wBACAV;oBACF;aACH;QACH;QAEAJ,OAAOO,SAAS,GAAGA;QAEnB,OAAOP;IACT;AACF,GAAE"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Endpoint } from 'payload'\n\nimport { definePlugin } from 'payload'\n\nimport type { SanitizedStripePluginConfig, StripePluginConfig } from './types.js'\n\nimport { getFields } from './fields/getFields.js'\nimport { createNewInStripe } from './hooks/createNewInStripe.js'\nimport { deleteFromStripe } from './hooks/deleteFromStripe.js'\nimport { syncExistingWithStripe } from './hooks/syncExistingWithStripe.js'\nimport { stripeREST } from './routes/rest.js'\nimport { stripeWebhooks } from './routes/webhooks.js'\nimport { sanitizeStripeRESTConfig } from './utilities/sanitizeStripeRESTConfig.js'\n\nexport { stripeProxy } from './utilities/stripeProxy.js'\n\nexport const stripePlugin = definePlugin<StripePluginConfig>({\n slug: '@payloadcms/plugin-stripe',\n plugin: ({ config, options: incomingStripeConfig }) => {\n const { collections } = config\n\n // set config defaults here\n const pluginConfig: SanitizedStripePluginConfig = {\n ...incomingStripeConfig,\n rest: sanitizeStripeRESTConfig({ rest: incomingStripeConfig?.rest }),\n sync: incomingStripeConfig?.sync || [],\n }\n\n // NOTE: env variables are never passed to the client, but we need to know if `stripeSecretKey` is a test key\n // unfortunately we must set the 'isTestKey' property on the config instead of using the following code:\n // const isTestKey = stripeConfig.stripeSecretKey?.startsWith('sk_test_');\n\n const endpoints: Endpoint[] = [\n ...(config?.endpoints || []),\n {\n handler: async (req) => {\n const res = await stripeWebhooks({\n config,\n pluginConfig,\n req,\n })\n\n return res\n },\n method: 'post',\n path: '/stripe/webhooks',\n },\n ]\n\n if (pluginConfig.rest) {\n endpoints.push({\n handler: async (req) => {\n const res = await stripeREST({\n pluginConfig,\n req,\n })\n\n return res\n },\n method: 'post' as Endpoint['method'],\n path: '/stripe/rest',\n })\n }\n\n for (const collection of collections!) {\n const { hooks: existingHooks } = collection\n\n const syncConfig = pluginConfig.sync?.find((sync) => sync.collection === collection.slug)\n\n if (!syncConfig) {\n continue\n }\n const fields = getFields({\n collection,\n pluginConfig,\n syncConfig,\n })\n collection.fields = fields\n\n if (!collection.hooks) {\n collection.hooks = {}\n }\n\n collection.hooks.afterDelete = [\n ...(existingHooks?.afterDelete || []),\n (args) =>\n deleteFromStripe({\n ...args,\n collection,\n pluginConfig,\n }),\n ]\n collection.hooks.beforeChange = [\n ...(existingHooks?.beforeChange || []),\n (args) =>\n syncExistingWithStripe({\n ...args,\n collection,\n pluginConfig,\n }),\n ]\n collection.hooks.beforeValidate = [\n ...(existingHooks?.beforeValidate || []),\n (args) =>\n createNewInStripe({\n ...args,\n collection,\n pluginConfig,\n }),\n ]\n }\n\n config.endpoints = endpoints\n\n return config\n },\n})\n"],"names":["definePlugin","getFields","createNewInStripe","deleteFromStripe","syncExistingWithStripe","stripeREST","stripeWebhooks","sanitizeStripeRESTConfig","stripeProxy","stripePlugin","slug","plugin","config","options","incomingStripeConfig","collections","pluginConfig","rest","sync","endpoints","handler","req","res","method","path","push","collection","hooks","existingHooks","syncConfig","find","fields","afterDelete","args","beforeChange","beforeValidate"],"mappings":"AAEA,SAASA,YAAY,QAAQ,UAAS;AAItC,SAASC,SAAS,QAAQ,wBAAuB;AACjD,SAASC,iBAAiB,QAAQ,+BAA8B;AAChE,SAASC,gBAAgB,QAAQ,8BAA6B;AAC9D,SAASC,sBAAsB,QAAQ,oCAAmC;AAC1E,SAASC,UAAU,QAAQ,mBAAkB;AAC7C,SAASC,cAAc,QAAQ,uBAAsB;AACrD,SAASC,wBAAwB,QAAQ,0CAAyC;AAElF,SAASC,WAAW,QAAQ,6BAA4B;AAExD,OAAO,MAAMC,eAAeT,aAAiC;IAC3DU,MAAM;IACNC,QAAQ,CAAC,EAAEC,MAAM,EAAEC,SAASC,oBAAoB,EA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BAAuB;wBACrB,GAAG6B,IAAI;wBACPP;wBACAV;oBACF;aACH;YACDU,WAAWC,KAAK,CAACQ,cAAc,GAAG;mBAC5BP,eAAeO,kBAAkB,EAAE;gBACvC,CAACF,OACC/B,kBAAkB;wBAChB,GAAG+B,IAAI;wBACPP;wBACAV;oBACF;aACH;QACH;QAEAJ,OAAOO,SAAS,GAAGA;QAEnB,OAAOP;IACT;AACF,GAAE"}
@@ -0,0 +1,73 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { stripePlugin } from './index.js';
3
+ const createBaseConfig = ()=>({
4
+ collections: []
5
+ });
6
+ const getStripeRESTEndpoints = async (pluginConfig)=>{
7
+ const transformedConfig = await stripePlugin(pluginConfig)(createBaseConfig());
8
+ return transformedConfig.endpoints?.filter(({ path })=>path === '/stripe/rest') ?? [];
9
+ };
10
+ describe('stripePlugin REST endpoint registration', ()=>{
11
+ it('should not register the REST endpoint when the option is absent', async ()=>{
12
+ const endpoints = await getStripeRESTEndpoints({
13
+ stripeSecretKey: 'sk_test_example'
14
+ });
15
+ expect(endpoints).toHaveLength(0);
16
+ });
17
+ it('should treat false from an untyped configuration as disabled', async ()=>{
18
+ const endpoints = await getStripeRESTEndpoints({
19
+ // @ts-expect-error -- omission is the supported way to disable the endpoint.
20
+ rest: false,
21
+ stripeSecretKey: 'sk_test_example'
22
+ });
23
+ expect(endpoints).toHaveLength(0);
24
+ });
25
+ it('should register exactly one POST endpoint for a valid REST configuration', async ()=>{
26
+ const endpoints = await getStripeRESTEndpoints({
27
+ rest: {
28
+ allowedMethods: [
29
+ 'subscriptions.list'
30
+ ]
31
+ },
32
+ stripeSecretKey: 'sk_test_example'
33
+ });
34
+ expect(endpoints).toHaveLength(1);
35
+ expect(endpoints[0]?.method).toBe('post');
36
+ });
37
+ it.each([
38
+ [
39
+ 'the legacy boolean form',
40
+ true
41
+ ],
42
+ [
43
+ 'an empty allowlist',
44
+ {
45
+ allowedMethods: []
46
+ }
47
+ ],
48
+ [
49
+ 'a wildcard method',
50
+ {
51
+ allowedMethods: [
52
+ 'subscriptions.*'
53
+ ]
54
+ }
55
+ ],
56
+ [
57
+ 'a non-string method',
58
+ {
59
+ allowedMethods: [
60
+ 123
61
+ ]
62
+ }
63
+ ]
64
+ ])('should reject %s during plugin transformation', async (_description, rest)=>{
65
+ const invalidConfig = {
66
+ rest,
67
+ stripeSecretKey: 'sk_test_example'
68
+ };
69
+ expect(()=>stripePlugin(invalidConfig)(createBaseConfig())).toThrow('The Stripe REST endpoint now requires an object with a non-empty allowedMethods array');
70
+ });
71
+ });
72
+
73
+ //# sourceMappingURL=index.spec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.spec.ts"],"sourcesContent":["import type { Config } from 'payload'\n\nimport { describe, expect, it } from 'vitest'\n\nimport type { StripePluginConfig } from './types.js'\n\nimport { stripePlugin } from './index.js'\n\nconst createBaseConfig = (): Config => ({ collections: [] })\n\nconst getStripeRESTEndpoints = async (pluginConfig: StripePluginConfig) => {\n const transformedConfig = await stripePlugin(pluginConfig)(createBaseConfig())\n\n return transformedConfig.endpoints?.filter(({ path }) => path === '/stripe/rest') ?? []\n}\n\ndescribe('stripePlugin REST endpoint registration', () => {\n it('should not register the REST endpoint when the option is absent', async () => {\n const endpoints = await getStripeRESTEndpoints({ stripeSecretKey: 'sk_test_example' })\n\n expect(endpoints).toHaveLength(0)\n })\n\n it('should treat false from an untyped configuration as disabled', async () => {\n const endpoints = await getStripeRESTEndpoints({\n // @ts-expect-error -- omission is the supported way to disable the endpoint.\n rest: false,\n stripeSecretKey: 'sk_test_example',\n })\n\n expect(endpoints).toHaveLength(0)\n })\n\n it('should register exactly one POST endpoint for a valid REST configuration', async () => {\n const endpoints = await getStripeRESTEndpoints({\n rest: { allowedMethods: ['subscriptions.list'] },\n stripeSecretKey: 'sk_test_example',\n })\n\n expect(endpoints).toHaveLength(1)\n expect(endpoints[0]?.method).toBe('post')\n })\n\n it.each([\n ['the legacy boolean form', true],\n ['an empty allowlist', { allowedMethods: [] }],\n ['a wildcard method', { allowedMethods: ['subscriptions.*'] }],\n ['a non-string method', { allowedMethods: [123] }],\n ])('should reject %s during plugin transformation', async (_description, rest) => {\n const invalidConfig = {\n rest,\n stripeSecretKey: 'sk_test_example',\n } as unknown as StripePluginConfig\n\n expect(() => stripePlugin(invalidConfig)(createBaseConfig())).toThrow(\n 'The Stripe REST endpoint now requires an object with a non-empty allowedMethods array',\n )\n })\n})\n"],"names":["describe","expect","it","stripePlugin","createBaseConfig","collections","getStripeRESTEndpoints","pluginConfig","transformedConfig","endpoints","filter","path","stripeSecretKey","toHaveLength","rest","allowedMethods","method","toBe","each","_description","invalidConfig","toThrow"],"mappings":"AAEA,SAASA,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAQ;AAI7C,SAASC,YAAY,QAAQ,aAAY;AAEzC,MAAMC,mBAAmB,IAAe,CAAA;QAAEC,aAAa,EAAE;IAAC,CAAA;AAE1D,MAAMC,yBAAyB,OAAOC;IACpC,MAAMC,oBAAoB,MAAML,aAAaI,cAAcH;IAE3D,OAAOI,kBAAkBC,SAAS,EAAEC,OAAO,CAAC,EAAEC,IAAI,EAAE,GAAKA,SAAS,mBAAmB,EAAE;AACzF;AAEAX,SAAS,2CAA2C;IAClDE,GAAG,mEAAmE;QACpE,MAAMO,YAAY,MAAMH,uBAAuB;YAAEM,iBAAiB;QAAkB;QAEpFX,OAAOQ,WAAWI,YAAY,CAAC;IACjC;IAEAX,GAAG,gEAAgE;QACjE,MAAMO,YAAY,MAAMH,uBAAuB;YAC7C,6EAA6E;YAC7EQ,MAAM;YACNF,iBAAiB;QACnB;QAEAX,OAAOQ,WAAWI,YAAY,CAAC;IACjC;IAEAX,GAAG,4EAA4E;QAC7E,MAAMO,YAAY,MAAMH,uBAAuB;YAC7CQ,MAAM;gBAAEC,gBAAgB;oBAAC;iBAAqB;YAAC;YAC/CH,iBAAiB;QACnB;QAEAX,OAAOQ,WAAWI,YAAY,CAAC;QAC/BZ,OAAOQ,SAAS,CAAC,EAAE,EAAEO,QAAQC,IAAI,CAAC;IACpC;IAEAf,GAAGgB,IAAI,CAAC;QACN;YAAC;YAA2B;SAAK;QACjC;YAAC;YAAsB;gBAAEH,gBAAgB,EAAE;YAAC;SAAE;QAC9C;YAAC;YAAqB;gBAAEA,gBAAgB;oBAAC;iBAAkB;YAAC;SAAE;QAC9D;YAAC;YAAuB;gBAAEA,gBAAgB;oBAAC;iBAAI;YAAC;SAAE;KACnD,EAAE,iDAAiD,OAAOI,cAAcL;QACvE,MAAMM,gBAAgB;YACpBN;YACAF,iBAAiB;QACnB;QAEAX,OAAO,IAAME,aAAaiB,eAAehB,qBAAqBiB,OAAO,CACnE;IAEJ;AACF"}
@@ -1,7 +1,7 @@
1
1
  import type { PayloadRequest } from 'payload';
2
- import type { StripePluginConfig } from '../types.js';
2
+ import type { SanitizedStripePluginConfig } from '../types.js';
3
3
  export declare const stripeREST: (args: {
4
- pluginConfig: StripePluginConfig;
4
+ pluginConfig: SanitizedStripePluginConfig;
5
5
  req: PayloadRequest;
6
- }) => Promise<any>;
6
+ }) => Promise<Response>;
7
7
  //# sourceMappingURL=rest.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"rest.d.ts","sourceRoot":"","sources":["../../src/routes/rest.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAI7C,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAA;AAIrD,eAAO,MAAM,UAAU,SAAgB;IACrC,YAAY,EAAE,kBAAkB,CAAA;IAChC,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,OAAO,CAAC,GAAG,CAyCd,CAAA"}
1
+ {"version":3,"file":"rest.d.ts","sourceRoot":"","sources":["../../src/routes/rest.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAI7C,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAA;AAI9D,eAAO,MAAM,UAAU,SAAgB;IACrC,YAAY,EAAE,2BAA2B,CAAA;IACzC,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,OAAO,CAAC,QAAQ,CAiEnB,CAAA"}
@@ -1,35 +1,112 @@
1
- import { addDataAndFileToRequest, Forbidden } from 'payload';
1
+ import { addDataAndFileToRequest, canAccessAdmin, UnauthorizedError } from 'payload';
2
2
  import { stripeProxy } from '../utilities/stripeProxy.js';
3
3
  export const stripeREST = async (args)=>{
4
- let responseStatus = 200;
5
- let responseJSON;
6
4
  const { pluginConfig, req } = args;
7
- await addDataAndFileToRequest(req);
8
- const requestWithData = req;
9
- const { data, payload, user } = requestWithData;
10
- const { stripeSecretKey } = pluginConfig;
11
5
  try {
12
- if (!user) {
13
- // TODO: make this customizable from the config
14
- throw new Forbidden(req.t);
6
+ await addDataAndFileToRequest(req);
7
+ } catch (err) {
8
+ return unexpectedErrorResponse({
9
+ err,
10
+ req
11
+ });
12
+ }
13
+ if (!req.user) {
14
+ return errorResponse({
15
+ message: 'Unauthorized',
16
+ status: 401
17
+ });
18
+ }
19
+ if (!pluginConfig.rest) {
20
+ return unexpectedErrorResponse({
21
+ err: new Error('Stripe REST handler called while disabled'),
22
+ req
23
+ });
24
+ }
25
+ let hasAccess;
26
+ if (pluginConfig.rest.access) {
27
+ try {
28
+ hasAccess = await pluginConfig.rest.access({
29
+ req
30
+ });
31
+ } catch (err) {
32
+ return unexpectedErrorResponse({
33
+ err,
34
+ req
35
+ });
36
+ }
37
+ } else {
38
+ try {
39
+ hasAccess = await hasAdminAccess({
40
+ req
41
+ });
42
+ } catch (err) {
43
+ return unexpectedErrorResponse({
44
+ err,
45
+ req
46
+ });
15
47
  }
16
- responseJSON = await stripeProxy({
17
- stripeArgs: data?.stripeArgs,
18
- stripeMethod: data?.stripeMethod,
19
- stripeSecretKey
20
- });
21
- const { status } = responseJSON;
22
- responseStatus = status;
23
- } catch (error) {
24
- const message = `An error has occurred in the Stripe plugin REST handler: '${JSON.stringify(error)}'`;
25
- payload.logger.error(message);
26
- responseStatus = 500;
27
- responseJSON = {
28
- message
29
- };
30
- }
31
- return Response.json(responseJSON, {
32
- status: responseStatus
48
+ }
49
+ if (!hasAccess) {
50
+ return errorResponse({
51
+ message: 'Forbidden',
52
+ status: 403
53
+ });
54
+ }
55
+ const { stripeArgs, stripeMethod } = req.data ?? {};
56
+ if (typeof stripeMethod !== 'string' || stripeMethod.trim().length === 0 || !pluginConfig.rest.allowedMethods.includes(stripeMethod)) {
57
+ return errorResponse({
58
+ message: 'Invalid request',
59
+ status: 400
60
+ });
61
+ }
62
+ if (!Array.isArray(stripeArgs)) {
63
+ return errorResponse({
64
+ message: 'Invalid request',
65
+ status: 400
66
+ });
67
+ }
68
+ try {
69
+ const responseJSON = await stripeProxy({
70
+ stripeArgs,
71
+ stripeMethod,
72
+ stripeSecretKey: pluginConfig.stripeSecretKey
73
+ });
74
+ return Response.json(responseJSON, {
75
+ status: responseJSON.status
76
+ });
77
+ } catch (err) {
78
+ return unexpectedErrorResponse({
79
+ err,
80
+ req
81
+ });
82
+ }
83
+ };
84
+ const hasAdminAccess = async ({ req })=>{
85
+ try {
86
+ await canAccessAdmin({
87
+ req
88
+ });
89
+ return true;
90
+ } catch (err) {
91
+ if (err instanceof UnauthorizedError) {
92
+ return false;
93
+ }
94
+ throw err;
95
+ }
96
+ };
97
+ const errorResponse = ({ message, status })=>Response.json({
98
+ message
99
+ }, {
100
+ status
101
+ });
102
+ const unexpectedErrorResponse = ({ err, req })=>{
103
+ req.payload.logger.error({
104
+ err,
105
+ msg: 'An unexpected error occurred in the Stripe plugin REST handler.'
106
+ });
107
+ return errorResponse({
108
+ message: 'Internal server error',
109
+ status: 500
33
110
  });
34
111
  };
35
112
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/routes/rest.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport { addDataAndFileToRequest, Forbidden } from 'payload'\n\nimport type { StripePluginConfig } from '../types.js'\n\nimport { stripeProxy } from '../utilities/stripeProxy.js'\n\nexport const stripeREST = async (args: {\n pluginConfig: StripePluginConfig\n req: PayloadRequest\n}): Promise<any> => {\n let responseStatus = 200\n let responseJSON\n\n const { pluginConfig, req } = args\n\n await addDataAndFileToRequest(req)\n\n const requestWithData = req\n const { data, payload, user } = requestWithData\n\n const { stripeSecretKey } = pluginConfig\n\n try {\n if (!user) {\n // TODO: make this customizable from the config\n throw new Forbidden(req.t)\n }\n\n responseJSON = await stripeProxy({\n stripeArgs: data?.stripeArgs, // example: ['cus_MGgt3Tuj3D66f2'] or [{ limit: 100 }, { stripeAccount: 'acct_1J9Z4pKZ4Z4Z4Z4Z' }]\n stripeMethod: data?.stripeMethod, // example: 'subscriptions.list',\n stripeSecretKey,\n })\n\n const { status } = responseJSON\n responseStatus = status\n } catch (error: unknown) {\n const message = `An error has occurred in the Stripe plugin REST handler: '${JSON.stringify(\n error,\n )}'`\n payload.logger.error(message)\n responseStatus = 500\n responseJSON = {\n message,\n }\n }\n\n return Response.json(responseJSON, {\n status: responseStatus,\n })\n}\n"],"names":["addDataAndFileToRequest","Forbidden","stripeProxy","stripeREST","args","responseStatus","responseJSON","pluginConfig","req","requestWithData","data","payload","user","stripeSecretKey","t","stripeArgs","stripeMethod","status","error","message","JSON","stringify","logger","Response","json"],"mappings":"AAEA,SAASA,uBAAuB,EAAEC,SAAS,QAAQ,UAAS;AAI5D,SAASC,WAAW,QAAQ,8BAA6B;AAEzD,OAAO,MAAMC,aAAa,OAAOC;IAI/B,IAAIC,iBAAiB;IACrB,IAAIC;IAEJ,MAAM,EAAEC,YAAY,EAAEC,GAAG,EAAE,GAAGJ;IAE9B,MAAMJ,wBAAwBQ;IAE9B,MAAMC,kBAAkBD;IACxB,MAAM,EAAEE,IAAI,EAAEC,OAAO,EAAEC,IAAI,EAAE,GAAGH;IAEhC,MAAM,EAAEI,eAAe,EAAE,GAAGN;IAE5B,IAAI;QACF,IAAI,CAACK,MAAM;YACT,+CAA+C;YAC/C,MAAM,IAAIX,UAAUO,IAAIM,CAAC;QAC3B;QAEAR,eAAe,MAAMJ,YAAY;YAC/Ba,YAAYL,MAAMK;YAClBC,cAAcN,MAAMM;YACpBH;QACF;QAEA,MAAM,EAAEI,MAAM,EAAE,GAAGX;QACnBD,iBAAiBY;IACnB,EAAE,OAAOC,OAAgB;QACvB,MAAMC,UAAU,CAAC,0DAA0D,EAAEC,KAAKC,SAAS,CACzFH,OACA,CAAC,CAAC;QACJP,QAAQW,MAAM,CAACJ,KAAK,CAACC;QACrBd,iBAAiB;QACjBC,eAAe;YACba;QACF;IACF;IAEA,OAAOI,SAASC,IAAI,CAAClB,cAAc;QACjCW,QAAQZ;IACV;AACF,EAAC"}
1
+ {"version":3,"sources":["../../src/routes/rest.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport { addDataAndFileToRequest, canAccessAdmin, UnauthorizedError } from 'payload'\n\nimport type { SanitizedStripePluginConfig } from '../types.js'\n\nimport { stripeProxy } from '../utilities/stripeProxy.js'\n\nexport const stripeREST = async (args: {\n pluginConfig: SanitizedStripePluginConfig\n req: PayloadRequest\n}): Promise<Response> => {\n const { pluginConfig, req } = args\n\n try {\n await addDataAndFileToRequest(req)\n } catch (err) {\n return unexpectedErrorResponse({ err, req })\n }\n\n if (!req.user) {\n return errorResponse({ message: 'Unauthorized', status: 401 })\n }\n\n if (!pluginConfig.rest) {\n return unexpectedErrorResponse({\n err: new Error('Stripe REST handler called while disabled'),\n req,\n })\n }\n\n let hasAccess: boolean\n\n if (pluginConfig.rest.access) {\n try {\n hasAccess = await pluginConfig.rest.access({ req })\n } catch (err) {\n return unexpectedErrorResponse({ err, req })\n }\n } else {\n try {\n hasAccess = await hasAdminAccess({ req })\n } catch (err) {\n return unexpectedErrorResponse({ err, req })\n }\n }\n\n if (!hasAccess) {\n return errorResponse({ message: 'Forbidden', status: 403 })\n }\n\n const { stripeArgs, stripeMethod } = req.data ?? {}\n\n if (\n typeof stripeMethod !== 'string' ||\n stripeMethod.trim().length === 0 ||\n !pluginConfig.rest.allowedMethods.includes(stripeMethod)\n ) {\n return errorResponse({ message: 'Invalid request', status: 400 })\n }\n\n if (!Array.isArray(stripeArgs)) {\n return errorResponse({ message: 'Invalid request', status: 400 })\n }\n\n try {\n const responseJSON = await stripeProxy({\n stripeArgs,\n stripeMethod,\n stripeSecretKey: pluginConfig.stripeSecretKey,\n })\n\n return Response.json(responseJSON, { status: responseJSON.status })\n } catch (err) {\n return unexpectedErrorResponse({ err, req })\n }\n}\n\nconst hasAdminAccess = async ({ req }: { req: PayloadRequest }): Promise<boolean> => {\n try {\n await canAccessAdmin({ req })\n return true\n } catch (err) {\n if (err instanceof UnauthorizedError) {\n return false\n }\n\n throw err\n }\n}\n\nconst errorResponse = ({ message, status }: { message: string; status: number }): Response =>\n Response.json({ message }, { status })\n\nconst unexpectedErrorResponse = ({ err, req }: { err: unknown; req: PayloadRequest }): Response => {\n req.payload.logger.error({\n err,\n msg: 'An unexpected error occurred in the Stripe plugin REST handler.',\n })\n\n return errorResponse({ message: 'Internal server error', status: 500 })\n}\n"],"names":["addDataAndFileToRequest","canAccessAdmin","UnauthorizedError","stripeProxy","stripeREST","args","pluginConfig","req","err","unexpectedErrorResponse","user","errorResponse","message","status","rest","Error","hasAccess","access","hasAdminAccess","stripeArgs","stripeMethod","data","trim","length","allowedMethods","includes","Array","isArray","responseJSON","stripeSecretKey","Response","json","payload","logger","error","msg"],"mappings":"AAEA,SAASA,uBAAuB,EAAEC,cAAc,EAAEC,iBAAiB,QAAQ,UAAS;AAIpF,SAASC,WAAW,QAAQ,8BAA6B;AAEzD,OAAO,MAAMC,aAAa,OAAOC;IAI/B,MAAM,EAAEC,YAAY,EAAEC,GAAG,EAAE,GAAGF;IAE9B,IAAI;QACF,MAAML,wBAAwBO;IAChC,EAAE,OAAOC,KAAK;QACZ,OAAOC,wBAAwB;YAAED;YAAKD;QAAI;IAC5C;IAEA,IAAI,CAAC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