meta-cloud-api 0.1.5 → 0.1.8

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 (124) hide show
  1. package/dist/api/businessProfile.d.mts +10 -7
  2. package/dist/api/businessProfile.d.ts +10 -7
  3. package/dist/api/businessProfile.js +1 -1
  4. package/dist/api/businessProfile.js.map +1 -1
  5. package/dist/api/businessProfile.mjs +1 -1
  6. package/dist/api/businessProfile.mjs.map +1 -1
  7. package/dist/api/encryption.d.mts +3 -3
  8. package/dist/api/encryption.d.ts +3 -3
  9. package/dist/api/encryption.js.map +1 -1
  10. package/dist/api/encryption.mjs.map +1 -1
  11. package/dist/api/flow.d.mts +14 -25
  12. package/dist/api/flow.d.ts +14 -25
  13. package/dist/api/flow.js +1 -1
  14. package/dist/api/flow.js.map +1 -1
  15. package/dist/api/flow.mjs +1 -1
  16. package/dist/api/flow.mjs.map +1 -1
  17. package/dist/api/index.js +1 -1
  18. package/dist/api/index.js.map +1 -1
  19. package/dist/api/index.mjs +1 -1
  20. package/dist/api/index.mjs.map +1 -1
  21. package/dist/api/media.d.mts +5 -5
  22. package/dist/api/media.d.ts +5 -5
  23. package/dist/api/media.js.map +1 -1
  24. package/dist/api/media.mjs.map +1 -1
  25. package/dist/api/messages.d.mts +21 -21
  26. package/dist/api/messages.d.ts +21 -21
  27. package/dist/api/messages.js +1 -1
  28. package/dist/api/messages.js.map +1 -1
  29. package/dist/api/messages.mjs +1 -1
  30. package/dist/api/messages.mjs.map +1 -1
  31. package/dist/api/phoneNumber.d.mts +5 -5
  32. package/dist/api/phoneNumber.d.ts +5 -5
  33. package/dist/api/phoneNumber.js +1 -1
  34. package/dist/api/phoneNumber.js.map +1 -1
  35. package/dist/api/phoneNumber.mjs.map +1 -1
  36. package/dist/api/qrCode.d.mts +6 -6
  37. package/dist/api/qrCode.d.ts +6 -6
  38. package/dist/api/qrCode.js +1 -1
  39. package/dist/api/qrCode.js.map +1 -1
  40. package/dist/api/qrCode.mjs.map +1 -1
  41. package/dist/api/registration.d.mts +3 -3
  42. package/dist/api/registration.d.ts +3 -3
  43. package/dist/api/registration.js +1 -1
  44. package/dist/api/registration.js.map +1 -1
  45. package/dist/api/registration.mjs.map +1 -1
  46. package/dist/api/template.d.mts +6 -6
  47. package/dist/api/template.d.ts +6 -6
  48. package/dist/api/template.js +1 -1
  49. package/dist/api/template.js.map +1 -1
  50. package/dist/api/template.mjs +1 -1
  51. package/dist/api/template.mjs.map +1 -1
  52. package/dist/api/twoStepVerification.d.mts +3 -3
  53. package/dist/api/twoStepVerification.d.ts +3 -3
  54. package/dist/api/twoStepVerification.js +1 -1
  55. package/dist/api/twoStepVerification.js.map +1 -1
  56. package/dist/api/twoStepVerification.mjs.map +1 -1
  57. package/dist/api/waba.d.mts +5 -5
  58. package/dist/api/waba.d.ts +5 -5
  59. package/dist/api/waba.js.map +1 -1
  60. package/dist/api/waba.mjs.map +1 -1
  61. package/dist/index.d.mts +1 -1
  62. package/dist/index.d.ts +1 -1
  63. package/dist/index.js +1 -1
  64. package/dist/index.js.map +1 -1
  65. package/dist/index.mjs +1 -1
  66. package/dist/index.mjs.map +1 -1
  67. package/dist/types/businessProfile.d.mts +13 -9
  68. package/dist/types/businessProfile.d.ts +13 -9
  69. package/dist/types/businessProfile.js +1 -1
  70. package/dist/types/businessProfile.js.map +1 -1
  71. package/dist/types/encryption.d.mts +3 -3
  72. package/dist/types/encryption.d.ts +3 -3
  73. package/dist/types/encryption.js +1 -1
  74. package/dist/types/encryption.js.map +1 -1
  75. package/dist/types/flow.d.mts +12 -12
  76. package/dist/types/flow.d.ts +12 -12
  77. package/dist/types/flow.js +1 -1
  78. package/dist/types/flow.js.map +1 -1
  79. package/dist/types/flow.mjs +1 -1
  80. package/dist/types/flow.mjs.map +1 -1
  81. package/dist/types/index.d.mts +1 -1
  82. package/dist/types/index.d.ts +1 -1
  83. package/dist/types/index.js +1 -1
  84. package/dist/types/index.js.map +1 -1
  85. package/dist/types/index.mjs +1 -1
  86. package/dist/types/index.mjs.map +1 -1
  87. package/dist/types/media.d.mts +5 -5
  88. package/dist/types/media.d.ts +5 -5
  89. package/dist/types/media.js +1 -1
  90. package/dist/types/media.js.map +1 -1
  91. package/dist/types/messages.d.mts +21 -21
  92. package/dist/types/messages.d.ts +21 -21
  93. package/dist/types/messages.js.map +1 -1
  94. package/dist/types/phoneNumber.d.mts +5 -5
  95. package/dist/types/phoneNumber.d.ts +5 -5
  96. package/dist/types/phoneNumber.js +1 -1
  97. package/dist/types/phoneNumber.js.map +1 -1
  98. package/dist/types/qrCode.d.mts +6 -6
  99. package/dist/types/qrCode.d.ts +6 -6
  100. package/dist/types/qrCode.js +1 -1
  101. package/dist/types/qrCode.js.map +1 -1
  102. package/dist/types/registration.d.mts +3 -3
  103. package/dist/types/registration.d.ts +3 -3
  104. package/dist/types/registration.js +1 -1
  105. package/dist/types/registration.js.map +1 -1
  106. package/dist/types/template.d.mts +6 -6
  107. package/dist/types/template.d.ts +6 -6
  108. package/dist/types/template.js +1 -1
  109. package/dist/types/template.js.map +1 -1
  110. package/dist/types/twoStepVerification.d.mts +2 -2
  111. package/dist/types/twoStepVerification.d.ts +2 -2
  112. package/dist/types/twoStepVerification.js +1 -1
  113. package/dist/types/twoStepVerification.js.map +1 -1
  114. package/dist/types/waba.d.mts +5 -5
  115. package/dist/types/waba.d.ts +5 -5
  116. package/dist/types/waba.js +1 -1
  117. package/dist/types/waba.js.map +1 -1
  118. package/dist/types/waba.mjs +1 -1
  119. package/dist/types/waba.mjs.map +1 -1
  120. package/dist/whatsapp.js +1 -1
  121. package/dist/whatsapp.js.map +1 -1
  122. package/dist/whatsapp.mjs +1 -1
  123. package/dist/whatsapp.mjs.map +1 -1
  124. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  import { WabaConfigType } from '../types/config.js';
2
- import { FlowClass, FlowsListResponse, FlowCategoryEnum, FlowValidationError, Flow, FlowPreviewResponse, FlowAssetsResponse, FlowMigrationResponse } from '../types/flow.js';
3
- import { RequesterClass, RequesterResponseInterface, ResponseSuccess } from '../types/request.js';
2
+ import { FlowClass, FlowsListResponse, FlowCategoryEnum, CreateFlowResponse, Flow, FlowPreviewResponse, FlowAssetsResponse, UpdateFlowResponse, ValidateFlowJsonResponse, FlowMigrationResponse } from '../types/flow.js';
3
+ import { RequesterClass, ResponseSuccess } from '../types/request.js';
4
4
  import BaseAPI from './base.js';
5
5
  import '../enums-D7paGoTY.js';
6
6
  import '../types/base.js';
@@ -13,7 +13,7 @@ declare class FlowAPI extends BaseAPI implements FlowClass {
13
13
  * @param wabaId - The WABA ID
14
14
  * @returns Promise with the list of flows
15
15
  */
16
- listFlows(wabaId: string): Promise<RequesterResponseInterface<FlowsListResponse>>;
16
+ listFlows(wabaId: string): Promise<FlowsListResponse>;
17
17
  /**
18
18
  * Create Flow
19
19
  *
@@ -28,11 +28,7 @@ declare class FlowAPI extends BaseAPI implements FlowClass {
28
28
  clone_flow_id?: string;
29
29
  flow_json?: string;
30
30
  publish?: boolean;
31
- }): Promise<RequesterResponseInterface<{
32
- id: string;
33
- success: boolean;
34
- validation_errors?: FlowValidationError[];
35
- }>>;
31
+ }): Promise<CreateFlowResponse>;
36
32
  /**
37
33
  * Get Flow details
38
34
  *
@@ -41,7 +37,7 @@ declare class FlowAPI extends BaseAPI implements FlowClass {
41
37
  * @param dateFormat - Optional date format
42
38
  * @returns Promise with the flow details or preview response
43
39
  */
44
- getFlow(flowId: string, fields?: string, dateFormat?: string): Promise<RequesterResponseInterface<Flow | FlowPreviewResponse>>;
40
+ getFlow(flowId: string, fields?: string, dateFormat?: string): Promise<Flow | FlowPreviewResponse>;
45
41
  /**
46
42
  * Get Flow Preview URL
47
43
  *
@@ -49,7 +45,7 @@ declare class FlowAPI extends BaseAPI implements FlowClass {
49
45
  * @param invalidate - Optional. If true, invalidates existing preview and generates a new one. Defaults to false.
50
46
  * @returns Promise with the flow preview details
51
47
  */
52
- getFlowPreview(flowId: string, invalidate?: boolean): Promise<RequesterResponseInterface<FlowPreviewResponse>>;
48
+ getFlowPreview(flowId: string, invalidate?: boolean): Promise<FlowPreviewResponse>;
53
49
  /**
54
50
  * Update Flow Metadata
55
51
  *
@@ -62,21 +58,21 @@ declare class FlowAPI extends BaseAPI implements FlowClass {
62
58
  categories?: FlowCategoryEnum[];
63
59
  endpoint_uri?: string;
64
60
  application_id?: string;
65
- }): Promise<RequesterResponseInterface<ResponseSuccess>>;
61
+ }): Promise<ResponseSuccess>;
66
62
  /**
67
63
  * Delete Flow (only works if the Flow is in DRAFT status)
68
64
  *
69
65
  * @param flowId - The flow ID
70
66
  * @returns Promise with the success status
71
67
  */
72
- deleteFlow(flowId: string): Promise<RequesterResponseInterface<ResponseSuccess>>;
68
+ deleteFlow(flowId: string): Promise<ResponseSuccess>;
73
69
  /**
74
70
  * List Assets (e.g., get Flow JSON download URL)
75
71
  *
76
72
  * @param flowId - The flow ID
77
73
  * @returns Promise with the list of assets
78
74
  */
79
- listAssets(flowId: string): Promise<RequesterResponseInterface<FlowAssetsResponse>>;
75
+ listAssets(flowId: string): Promise<FlowAssetsResponse>;
80
76
  /**
81
77
  * Update Flow JSON by uploading a file, buffer, JSON object, or Blob.
82
78
  *
@@ -89,10 +85,7 @@ declare class FlowAPI extends BaseAPI implements FlowClass {
89
85
  updateFlowJson(flowId: string, data: {
90
86
  file: Blob | Buffer | object;
91
87
  name?: string;
92
- }): Promise<RequesterResponseInterface<{
93
- success: boolean;
94
- validation_errors?: FlowValidationError[];
95
- }>>;
88
+ }): Promise<UpdateFlowResponse>;
96
89
  /**
97
90
  * Validate Flow JSON by attempting an update without publishing.
98
91
  * This is a convenience method; the API doesn't have a dedicated validation endpoint.
@@ -101,25 +94,21 @@ declare class FlowAPI extends BaseAPI implements FlowClass {
101
94
  * @param flowJsonData - The Flow JSON content as a file path (string), Buffer, JSON object, or Blob.
102
95
  * @returns Promise indicating if the JSON is valid and includes validation errors if any.
103
96
  */
104
- validateFlowJson(flowId: string, flowJsonData: Blob | Buffer | object): Promise<RequesterResponseInterface<{
105
- valid: boolean;
106
- success: boolean;
107
- validation_errors?: FlowValidationError[];
108
- }>>;
97
+ validateFlowJson(flowId: string, flowJsonData: Blob | Buffer | object): Promise<ValidateFlowJsonResponse>;
109
98
  /**
110
99
  * Publish Flow
111
100
  *
112
101
  * @param flowId - The flow ID
113
102
  * @returns Promise with the success status
114
103
  */
115
- publishFlow(flowId: string): Promise<RequesterResponseInterface<ResponseSuccess>>;
104
+ publishFlow(flowId: string): Promise<ResponseSuccess>;
116
105
  /**
117
106
  * Deprecate Flow
118
107
  *
119
108
  * @param flowId - The flow ID
120
109
  * @returns Promise with the success status
121
110
  */
122
- deprecateFlow(flowId: string): Promise<RequesterResponseInterface<ResponseSuccess>>;
111
+ deprecateFlow(flowId: string): Promise<ResponseSuccess>;
123
112
  /**
124
113
  * Migrate Flows between WABAs
125
114
  *
@@ -130,7 +119,7 @@ declare class FlowAPI extends BaseAPI implements FlowClass {
130
119
  migrateFlows(destinationWabaId: string, data: {
131
120
  source_waba_id: string;
132
121
  source_flow_names?: string[];
133
- }): Promise<RequesterResponseInterface<FlowMigrationResponse>>;
122
+ }): Promise<FlowMigrationResponse>;
134
123
  }
135
124
 
136
125
  export { FlowAPI as default };
package/dist/api/flow.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var N=Object.defineProperty;var _=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var G=Object.prototype.hasOwnProperty;var U=(A,i)=>{for(var t in i)N(A,t,{get:i[t],enumerable:!0})},I=(A,i,t,R)=>{if(i&&typeof i=="object"||typeof i=="function")for(let l of O(i))!G.call(A,l)&&l!==t&&N(A,l,{get:()=>i[l],enumerable:!(R=_(i,l))||R.enumerable});return A};var F=A=>I(N({},"__esModule",{value:!0}),A);var o={};U(o,{default:()=>D});module.exports=F(o);var S=class{name;debug;constructor(i,t=!1){this.name=i,this.debug=t}log(...i){if(this.debug){let t=`[ ${Date.now()} ]`;this.name&&(t+=` - ${this.name}`),console.log.apply(console,[t,": ",...i])}}error(...i){let t=`[ ${Date.now()} ] - ERROR`;this.name&&(t+=` - ${this.name}`),console.error.apply(console,[t,": ",...i])}warn(...i){let t=`[ ${Date.now()} ] - WARN`;this.name&&(t+=` - ${this.name}`),console.warn.apply(console,[t,": ",...i])}info(...i){let t=`[ ${Date.now()} ] - INFO`;this.name&&(t+=` - ${this.name}`),console.info.apply(console,[t,": ",...i])}};var w="BaseAPI",T=!1,K=new S(w,process.env.DEBUG==="true"||T),P=class{config;client;constructor(i,t){this.config=i,this.client=t,K.log("Initialized with HTTPSClient")}sendJson(i,t,R,l){return this.client.getJson(i,t,R,l)}};var M="FlowAPI",h=!1,f=new S(M,process.env.DEBUG==="true"||h),D=class extends P{constructor(i,t){super(i,t),f.log("FlowAPI initialized")}async listFlows(i){return this.sendJson("GET",`/${i}/flows`,this.config.REQUEST_TIMEOUT,null)}async createFlow(i,t){let R={name:t.name,categories:t.categories,...t.endpoint_uri&&{endpoint_uri:t.endpoint_uri},...t.clone_flow_id&&{clone_flow_id:t.clone_flow_id},...t.flow_json&&{flow_json:t.flow_json},...t.publish!==void 0&&{publish:t.publish}};return this.sendJson("POST",`/${i}/flows`,this.config.REQUEST_TIMEOUT,JSON.stringify(R))}async getFlow(i,t,R){let l=new URLSearchParams;t&&l.append("fields",t),R&&l.append("date_format",R);let p=l.toString()?`?${l.toString()}`:"";return this.sendJson("GET",`/${i}${p}`,this.config.REQUEST_TIMEOUT,null)}async getFlowPreview(i,t=!1){let R=`preview.invalidate(${t})`;return this.getFlow(i,R)}async updateFlowMetadata(i,t){let R={...t.name&&{name:t.name},...t.categories&&{categories:t.categories},...t.endpoint_uri&&{endpoint_uri:t.endpoint_uri},...t.application_id&&{application_id:t.application_id}};return this.sendJson("POST",`/${i}`,this.config.REQUEST_TIMEOUT,JSON.stringify(R))}async deleteFlow(i){return this.sendJson("DELETE",`/${i}`,this.config.REQUEST_TIMEOUT,null)}async listAssets(i){return this.sendJson("GET",`/${i}/assets`,this.config.REQUEST_TIMEOUT,null)}async updateFlowJson(i,t){let R=new FormData,l;if(t.file instanceof Buffer)l=new globalThis.Blob([t.file]),R.append("file",l);else if(typeof t.file=="object"&&!(t.file instanceof Blob))try{l=new globalThis.Blob([JSON.stringify(t.file,null,2)],{type:"application/json"}),R.append("file",l)}catch{throw new Error("Failed to stringify JSON object for Flow JSON update.")}else if(t.file instanceof Blob)l=t.file,R.append("file",l);else throw new Error("Invalid file type provided for Flow JSON update. Must be a Buffer, JSON object, or Blob.");return R.append("asset_type","FLOW_JSON"),R.append("name",t.name||"flow.json"),this.sendJson("POST",`/${i}/assets`,this.config.REQUEST_TIMEOUT,R)}async validateFlowJson(i,t){try{let l=await(await this.updateFlowJson(i,{file:t})).json(),p=!l.validation_errors||l.validation_errors.length===0,B={...l,valid:p};return{json:async()=>B}}catch(R){throw f.error("Error during Flow JSON validation attempt:",R),R}}async publishFlow(i){return this.sendJson("POST",`/${i}/publish`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async deprecateFlow(i){return this.sendJson("POST",`/${i}/deprecate`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async migrateFlows(i,t){let R={source_waba_id:t.source_waba_id,...t.source_flow_names&&{source_flow_names:t.source_flow_names}};return this.sendJson("POST",`/${i}/migrate_flows`,this.config.REQUEST_TIMEOUT,JSON.stringify(R))}};
1
+ "use strict";var N=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var G=Object.prototype.hasOwnProperty;var U=(A,i)=>{for(var t in i)N(A,t,{get:i[t],enumerable:!0})},f=(A,i,t,R)=>{if(i&&typeof i=="object"||typeof i=="function")for(let l of _(i))!G.call(A,l)&&l!==t&&N(A,l,{get:()=>i[l],enumerable:!(R=O(i,l))||R.enumerable});return A};var F=A=>f(N({},"__esModule",{value:!0}),A);var h={};U(h,{default:()=>D});module.exports=F(h);var S=class{name;debug;constructor(i,t=!1){this.name=i,this.debug=t}log(...i){if(this.debug){let t=`[ ${Date.now()} ]`;this.name&&(t+=` - ${this.name}`),console.log.apply(console,[t,": ",...i])}}error(...i){let t=`[ ${Date.now()} ] - ERROR`;this.name&&(t+=` - ${this.name}`),console.error.apply(console,[t,": ",...i])}warn(...i){let t=`[ ${Date.now()} ] - WARN`;this.name&&(t+=` - ${this.name}`),console.warn.apply(console,[t,": ",...i])}info(...i){let t=`[ ${Date.now()} ] - INFO`;this.name&&(t+=` - ${this.name}`),console.info.apply(console,[t,": ",...i])}};var w="BaseAPI",T=!1,I=new S(w,process.env.DEBUG==="true"||T),P=class{config;client;constructor(i,t){this.config=i,this.client=t,I.log("Initialized with HTTPSClient")}sendJson(i,t,R,l){return this.client.getJson(i,t,R,l)}};var K="FlowAPI",M=!1,B=new S(K,process.env.DEBUG==="true"||M),D=class extends P{constructor(i,t){super(i,t),B.log("FlowAPI initialized")}async listFlows(i){return this.sendJson("GET",`/${i}/flows`,this.config.REQUEST_TIMEOUT,null)}async createFlow(i,t){let R={name:t.name,categories:t.categories,...t.endpoint_uri&&{endpoint_uri:t.endpoint_uri},...t.clone_flow_id&&{clone_flow_id:t.clone_flow_id},...t.flow_json&&{flow_json:t.flow_json},...t.publish!==void 0&&{publish:t.publish}};return this.sendJson("POST",`/${i}/flows`,this.config.REQUEST_TIMEOUT,JSON.stringify(R))}async getFlow(i,t,R){let l=new URLSearchParams;t&&l.append("fields",t),R&&l.append("date_format",R);let p=l.toString()?`?${l.toString()}`:"";return this.sendJson("GET",`/${i}${p}`,this.config.REQUEST_TIMEOUT,null)}async getFlowPreview(i,t=!1){let R=`preview.invalidate(${t})`;return this.getFlow(i,R)}async updateFlowMetadata(i,t){let R={...t.name&&{name:t.name},...t.categories&&{categories:t.categories},...t.endpoint_uri&&{endpoint_uri:t.endpoint_uri},...t.application_id&&{application_id:t.application_id}};return this.sendJson("POST",`/${i}`,this.config.REQUEST_TIMEOUT,JSON.stringify(R))}async deleteFlow(i){return this.sendJson("DELETE",`/${i}`,this.config.REQUEST_TIMEOUT,null)}async listAssets(i){return this.sendJson("GET",`/${i}/assets`,this.config.REQUEST_TIMEOUT,null)}async updateFlowJson(i,t){let R=new FormData,l;if(t.file instanceof Buffer)l=new globalThis.Blob([t.file]),R.append("file",l);else if(typeof t.file=="object"&&!(t.file instanceof Blob))try{l=new globalThis.Blob([JSON.stringify(t.file,null,2)],{type:"application/json"}),R.append("file",l)}catch{throw new Error("Failed to stringify JSON object for Flow JSON update.")}else if(t.file instanceof Blob)l=t.file,R.append("file",l);else throw new Error("Invalid file type provided for Flow JSON update. Must be a Buffer, JSON object, or Blob.");return R.append("asset_type","FLOW_JSON"),R.append("name",t.name||"flow.json"),this.sendJson("POST",`/${i}/assets`,this.config.REQUEST_TIMEOUT,R)}async validateFlowJson(i,t){try{let R=await this.updateFlowJson(i,{file:t}),l=!R.validation_errors||R.validation_errors.length===0;return{...R,valid:l}}catch(R){throw B.error("Error during Flow JSON validation attempt:",R),R}}async publishFlow(i){return this.sendJson("POST",`/${i}/publish`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async deprecateFlow(i){return this.sendJson("POST",`/${i}/deprecate`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async migrateFlows(i,t){let R={source_waba_id:t.source_waba_id,...t.source_flow_names&&{source_flow_names:t.source_flow_names}};return this.sendJson("POST",`/${i}/migrate_flows`,this.config.REQUEST_TIMEOUT,JSON.stringify(R))}};
2
2
  //# sourceMappingURL=flow.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/api/flow.ts","../../src/utils/logger.ts","../../src/api/base.ts"],"sourcesContent":["import { WabaConfigType } from '../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../types/enums';\nimport {\n Flow,\n FlowAssetsResponse,\n FlowCategoryEnum,\n FlowClass,\n FlowMigrationResponse,\n FlowPreviewResponse,\n FlowsListResponse,\n FlowValidationError,\n} from '../types/flow';\nimport { RequesterClass, RequesterResponseInterface, ResponseSuccess } from '../types/request';\nimport Logger from '../utils/logger';\nimport BaseAPI from './base';\n\nconst LIB_NAME = 'FlowAPI';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class FlowAPI extends BaseAPI implements FlowClass {\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n LOGGER.log('FlowAPI initialized');\n }\n\n /**\n * List Flows\n *\n * @param wabaId - The WABA ID\n * @returns Promise with the list of flows\n */\n async listFlows(wabaId: string): Promise<RequesterResponseInterface<FlowsListResponse>> {\n return this.sendJson(HttpMethodsEnum.Get, `/${wabaId}/flows`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * Create Flow\n *\n * @param wabaId - The WABA ID\n * @param data - The flow data including name, categories, endpoint_uri, and optional clone_flow_id\n * @returns Promise with the created flow ID and validation errors if any\n */\n async createFlow(\n wabaId: string,\n data: {\n name: string;\n categories?: FlowCategoryEnum[];\n endpoint_uri?: string;\n clone_flow_id?: string;\n flow_json?: string; // Flow JSON as a string\n publish?: boolean;\n },\n ): Promise<\n RequesterResponseInterface<{ id: string; success: boolean; validation_errors?: FlowValidationError[] }>\n > {\n // The API expects application/json for this endpoint based on documentation examples\n // Let's ensure we send JSON, not FormData, unless specifically required by an endpoint variation.\n const payload = {\n name: data.name,\n categories: data.categories,\n ...(data.endpoint_uri && { endpoint_uri: data.endpoint_uri }),\n ...(data.clone_flow_id && { clone_flow_id: data.clone_flow_id }),\n ...(data.flow_json && { flow_json: data.flow_json }),\n ...(data.publish !== undefined && { publish: data.publish }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${wabaId}/flows`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(payload), // Send as JSON\n );\n }\n\n /**\n * Get Flow details\n *\n * @param flowId - The flow ID\n * @param fields - Optional fields to return (e.g., 'name,status,preview.invalidate(false)')\n * @param dateFormat - Optional date format\n * @returns Promise with the flow details or preview response\n */\n async getFlow(\n flowId: string,\n fields?: string,\n dateFormat?: string,\n ): Promise<RequesterResponseInterface<Flow | FlowPreviewResponse>> {\n const params = new URLSearchParams();\n if (fields) params.append('fields', fields);\n if (dateFormat) params.append('date_format', dateFormat);\n\n const queryString = params.toString() ? `?${params.toString()}` : '';\n return this.sendJson(\n HttpMethodsEnum.Get,\n `/${flowId}${queryString}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get Flow Preview URL\n *\n * @param flowId - The flow ID\n * @param invalidate - Optional. If true, invalidates existing preview and generates a new one. Defaults to false.\n * @returns Promise with the flow preview details\n */\n async getFlowPreview(\n flowId: string,\n invalidate: boolean = false,\n ): Promise<RequesterResponseInterface<FlowPreviewResponse>> {\n const fields = `preview.invalidate(${invalidate})`;\n // Type assertion needed as getFlow can return Flow or FlowPreviewResponse\n return this.getFlow(flowId, fields) as Promise<RequesterResponseInterface<FlowPreviewResponse>>;\n }\n\n /**\n * Update Flow Metadata\n *\n * @param flowId - The flow ID\n * @param data - The flow metadata to update (name, categories, endpoint_uri, application_id)\n * @returns Promise with the success status\n */\n async updateFlowMetadata(\n flowId: string,\n data: {\n name?: string;\n categories?: FlowCategoryEnum[];\n endpoint_uri?: string;\n application_id?: string;\n },\n ): Promise<RequesterResponseInterface<ResponseSuccess>> {\n // The API expects application/json for this endpoint based on documentation examples\n const payload = {\n ...(data.name && { name: data.name }),\n ...(data.categories && { categories: data.categories }),\n ...(data.endpoint_uri && { endpoint_uri: data.endpoint_uri }),\n ...(data.application_id && { application_id: data.application_id }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(payload), // Send as JSON\n );\n }\n\n /**\n * Delete Flow (only works if the Flow is in DRAFT status)\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async deleteFlow(flowId: string): Promise<RequesterResponseInterface<ResponseSuccess>> {\n return this.sendJson(HttpMethodsEnum.Delete, `/${flowId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * List Assets (e.g., get Flow JSON download URL)\n *\n * @param flowId - The flow ID\n * @returns Promise with the list of assets\n */\n async listAssets(flowId: string): Promise<RequesterResponseInterface<FlowAssetsResponse>> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `/${flowId}/assets`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Update Flow JSON by uploading a file, buffer, JSON object, or Blob.\n *\n * @param flowId - The flow ID\n * @param data - Object containing the file data and optional name.\n * @param data.file - The Flow JSON content as a Buffer, JSON object, or Blob.\n * @param data.name - Optional name for the asset, defaults to 'flow.json'.\n * @returns Promise with the success status and validation errors, if any.\n */\n async updateFlowJson(\n flowId: string,\n data: {\n file: Blob | Buffer | object; // JSON object, Buffer, or Blob\n name?: string; // Default to \"flow.json\"\n },\n ): Promise<RequesterResponseInterface<{ success: boolean; validation_errors?: FlowValidationError[] }>> {\n const formData = new FormData();\n let fileContent: Blob;\n\n // Handle different input types for the file\n if (data.file instanceof Buffer) {\n // Buffer\n // Create a Blob from the Buffer and cast it to the global Blob type\n fileContent = new globalThis.Blob([data.file]);\n formData.append('file', fileContent as unknown as Blob);\n } else if (typeof data.file === 'object' && !(data.file instanceof Blob)) {\n // JSON object - stringify and create Blob\n try {\n // Create a Blob from the JSON string and cast it to the global Blob type\n fileContent = new globalThis.Blob([JSON.stringify(data.file, null, 2)], { type: 'application/json' });\n formData.append('file', fileContent as unknown as Blob);\n } catch (e) {\n throw new Error('Failed to stringify JSON object for Flow JSON update.');\n }\n } else if (data.file instanceof Blob) {\n // Blob (already in correct format)\n fileContent = data.file;\n formData.append('file', fileContent as unknown as Blob);\n } else {\n throw new Error('Invalid file type provided for Flow JSON update. Must be a Buffer, JSON object, or Blob.');\n }\n\n formData.append('asset_type', 'FLOW_JSON'); // Required by API\n formData.append('name', data.name || 'flow.json'); // Required by API\n\n // The underlying.sendJson needs to correctly handle FormData\n // It might need specific headers like `Content-Type: multipart/form-data; boundary=...`\n // which FormData library usually helps generate.\n // Assuming.sendJson handles FormData correctly:\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/assets`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData, // Pass FormData directly\n // Headers might be set automatically by the client when FormData is detected,\n // or might need to be explicitly set depending on the client implementation.\n // e.g., { 'Content-Type': `multipart/form-data; boundary=${formData.getBoundary()}` }\n );\n }\n\n /**\n * Validate Flow JSON by attempting an update without publishing.\n * This is a convenience method; the API doesn't have a dedicated validation endpoint.\n *\n * @param flowId - The ID of the Flow (must exist, can be in DRAFT status).\n * @param flowJsonData - The Flow JSON content as a file path (string), Buffer, JSON object, or Blob.\n * @returns Promise indicating if the JSON is valid and includes validation errors if any.\n */\n async validateFlowJson(\n flowId: string,\n flowJsonData: Blob | Buffer | object,\n ): Promise<\n RequesterResponseInterface<{ valid: boolean; success: boolean; validation_errors?: FlowValidationError[] }>\n > {\n try {\n // Attempt to update the Flow JSON. The API response includes validation errors.\n const result = await this.updateFlowJson(flowId, {\n file: flowJsonData,\n });\n\n // Get the response data\n const responseData = await result.json();\n\n const isValid = !responseData.validation_errors || responseData.validation_errors.length === 0;\n\n // Create a new response with the 'valid' flag\n const enhancedResponse = {\n ...responseData,\n valid: isValid,\n };\n\n // Return a new RequesterResponseInterface with the enhanced data\n return {\n json: async () => enhancedResponse,\n };\n } catch (error) {\n // If the update itself fails (e.g., network error, auth error), rethrow.\n // Specific API validation errors are handled within the 'result' above.\n LOGGER.error('Error during Flow JSON validation attempt:', error);\n throw error;\n }\n }\n\n /**\n * Publish Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async publishFlow(flowId: string): Promise<RequesterResponseInterface<ResponseSuccess>> {\n // This endpoint expects an empty JSON body or no body\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/publish`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify({}), // Send empty JSON object\n );\n }\n\n /**\n * Deprecate Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async deprecateFlow(flowId: string): Promise<RequesterResponseInterface<ResponseSuccess>> {\n // This endpoint expects an empty JSON body or no body\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/deprecate`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify({}), // Send empty JSON object\n );\n }\n\n /**\n * Migrate Flows between WABAs\n *\n * @param destinationWabaId - The destination WABA ID\n * @param data - The migration data including source_waba_id and optional source_flow_names\n * @returns Promise with migration results (successes and failures)\n */\n async migrateFlows(\n destinationWabaId: string,\n data: {\n source_waba_id: string;\n source_flow_names?: string[];\n },\n ): Promise<RequesterResponseInterface<FlowMigrationResponse>> {\n // API documentation suggests this endpoint might expect application/json\n // Let's double-check or assume JSON based on typical Graph API patterns unless FormData is confirmed.\n // Assuming JSON for now:\n const payload = {\n source_waba_id: data.source_waba_id,\n ...(data.source_flow_names && { source_flow_names: data.source_flow_names }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${destinationWabaId}/migrate_flows`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(payload),\n );\n }\n}\n","// @ts-nocheck\nimport type { LoggerInterface } from '../types/logger';\n\nexport default class Logger implements LoggerInterface {\n private name: string;\n private debug: boolean;\n\n constructor(name: string, debug: boolean = false) {\n this.name = name;\n this.debug = debug;\n }\n\n log(...data: any[]) {\n if (this.debug) {\n let prefix = `[ ${Date.now()} ]`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.log.apply(console, [prefix, ': ', ...data]);\n }\n }\n\n error(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - ERROR`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.error.apply(console, [prefix, ': ', ...data]);\n }\n\n warn(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - WARN`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.warn.apply(console, [prefix, ': ', ...data]);\n }\n\n info(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - INFO`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.info.apply(console, [prefix, ': ', ...data]);\n }\n}\n","import Logger from '../utils/logger';\nimport type { BaseClass } from '../types/base';\nimport type { WabaConfigType } from '../types/config';\nimport type { RequesterClass } from '../types/request';\nimport { HttpMethodsEnum } from 'src/types/enums';\n\nconst LIB_NAME = 'BaseAPI';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class BaseAPI implements BaseClass {\n protected config: WabaConfigType;\n protected client: RequesterClass;\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n this.config = config;\n this.client = client;\n LOGGER.log('Initialized with HTTPSClient');\n }\n\n protected sendJson<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any): Promise<T> {\n return this.client.getJson<T>(method, endpoint, timeout, body);\n }\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,GCGA,IAAqBI,EAArB,KAAuD,CAC3C,KACA,MAER,YAAYC,EAAcC,EAAiB,GAAO,CAC9C,KAAK,KAAOD,EACZ,KAAK,MAAQC,CACjB,CAEA,OAAOC,EAAa,CAChB,GAAI,KAAK,MAAO,CACZ,IAAIC,EAAS,KAAK,KAAK,IAAI,CAAC,KACxB,KAAK,OACLA,GAAU,MAAM,KAAK,IAAI,IAE7B,QAAQ,IAAI,MAAM,QAAS,CAACA,EAAQ,KAAM,GAAGD,CAAI,CAAC,CACtD,CACJ,CAEA,SAASA,EAAa,CAClB,IAAIC,EAAS,KAAK,KAAK,IAAI,CAAC,aACxB,KAAK,OACLA,GAAU,MAAM,KAAK,IAAI,IAE7B,QAAQ,MAAM,MAAM,QAAS,CAACA,EAAQ,KAAM,GAAGD,CAAI,CAAC,CACxD,CAEA,QAAQA,EAAa,CACjB,IAAIC,EAAS,KAAK,KAAK,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Fa,EACAf,EAI0D,CAI1D,IAAMC,EAAU,CACZ,eAAgBD,EAAK,eACrB,GAAIA,EAAK,mBAAqB,CAAE,kBAAmBA,EAAK,iBAAkB,CAC9E,EAEA,OAAO,KAAK,gBAER,IAAIe,CAAiB,iBACrB,KAAK,OAAO,gBACZ,KAAK,UAAUd,CAAO,CAC1B,CACJ,CACJ","names":["flow_exports","__export","FlowAPI","__toCommonJS","Logger","name","debug","data","prefix","LIB_NAME","LOG_LOCAL","LOGGER","Logger","BaseAPI","config","client","method","endpoint","timeout","body","LIB_NAME","LOG_LOCAL","LOGGER","Logger","FlowAPI","BaseAPI","config","client","wabaId","data","payload","flowId","fields","dateFormat","params","queryString","invalidate","formData","fileContent","flowJsonData","responseData","isValid","enhancedResponse","error","destinationWabaId"]}
1
+ {"version":3,"sources":["../../src/api/flow.ts","../../src/utils/logger.ts","../../src/api/base.ts"],"sourcesContent":["import { WabaConfigType } from '../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../types/enums';\nimport {\n CreateFlowResponse,\n Flow,\n FlowAssetsResponse,\n FlowCategoryEnum,\n FlowClass,\n FlowMigrationResponse,\n FlowPreviewResponse,\n FlowsListResponse,\n UpdateFlowResponse,\n ValidateFlowJsonResponse,\n} from '../types/flow';\nimport { RequesterClass, ResponseSuccess } from '../types/request';\nimport Logger from '../utils/logger';\nimport BaseAPI from './base';\n\nconst LIB_NAME = 'FlowAPI';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class FlowAPI extends BaseAPI implements FlowClass {\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n LOGGER.log('FlowAPI initialized');\n }\n\n /**\n * List Flows\n *\n * @param wabaId - The WABA ID\n * @returns Promise with the list of flows\n */\n async listFlows(wabaId: string): Promise<FlowsListResponse> {\n return this.sendJson(HttpMethodsEnum.Get, `/${wabaId}/flows`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * Create Flow\n *\n * @param wabaId - The WABA ID\n * @param data - The flow data including name, categories, endpoint_uri, and optional clone_flow_id\n * @returns Promise with the created flow ID and validation errors if any\n */\n async createFlow(\n wabaId: string,\n data: {\n name: string;\n categories?: FlowCategoryEnum[];\n endpoint_uri?: string;\n clone_flow_id?: string;\n flow_json?: string; // Flow JSON as a string\n publish?: boolean;\n },\n ): Promise<CreateFlowResponse> {\n // The API expects application/json for this endpoint based on documentation examples\n // Let's ensure we send JSON, not FormData, unless specifically required by an endpoint variation.\n const payload = {\n name: data.name,\n categories: data.categories,\n ...(data.endpoint_uri && { endpoint_uri: data.endpoint_uri }),\n ...(data.clone_flow_id && { clone_flow_id: data.clone_flow_id }),\n ...(data.flow_json && { flow_json: data.flow_json }),\n ...(data.publish !== undefined && { publish: data.publish }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${wabaId}/flows`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(payload), // Send as JSON\n );\n }\n\n /**\n * Get Flow details\n *\n * @param flowId - The flow ID\n * @param fields - Optional fields to return (e.g., 'name,status,preview.invalidate(false)')\n * @param dateFormat - Optional date format\n * @returns Promise with the flow details or preview response\n */\n async getFlow(flowId: string, fields?: string, dateFormat?: string): Promise<Flow | FlowPreviewResponse> {\n const params = new URLSearchParams();\n if (fields) params.append('fields', fields);\n if (dateFormat) params.append('date_format', dateFormat);\n\n const queryString = params.toString() ? `?${params.toString()}` : '';\n return this.sendJson(\n HttpMethodsEnum.Get,\n `/${flowId}${queryString}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get Flow Preview URL\n *\n * @param flowId - The flow ID\n * @param invalidate - Optional. If true, invalidates existing preview and generates a new one. Defaults to false.\n * @returns Promise with the flow preview details\n */\n async getFlowPreview(flowId: string, invalidate: boolean = false): Promise<FlowPreviewResponse> {\n const fields = `preview.invalidate(${invalidate})`;\n // Type assertion needed as getFlow can return Flow or FlowPreviewResponse\n return this.getFlow(flowId, fields) as Promise<FlowPreviewResponse>;\n }\n\n /**\n * Update Flow Metadata\n *\n * @param flowId - The flow ID\n * @param data - The flow metadata to update (name, categories, endpoint_uri, application_id)\n * @returns Promise with the success status\n */\n async updateFlowMetadata(\n flowId: string,\n data: {\n name?: string;\n categories?: FlowCategoryEnum[];\n endpoint_uri?: string;\n application_id?: string;\n },\n ): Promise<ResponseSuccess> {\n // The API expects application/json for this endpoint based on documentation examples\n const payload = {\n ...(data.name && { name: data.name }),\n ...(data.categories && { categories: data.categories }),\n ...(data.endpoint_uri && { endpoint_uri: data.endpoint_uri }),\n ...(data.application_id && { application_id: data.application_id }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(payload), // Send as JSON\n );\n }\n\n /**\n * Delete Flow (only works if the Flow is in DRAFT status)\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async deleteFlow(flowId: string): Promise<ResponseSuccess> {\n return this.sendJson(HttpMethodsEnum.Delete, `/${flowId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * List Assets (e.g., get Flow JSON download URL)\n *\n * @param flowId - The flow ID\n * @returns Promise with the list of assets\n */\n async listAssets(flowId: string): Promise<FlowAssetsResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `/${flowId}/assets`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Update Flow JSON by uploading a file, buffer, JSON object, or Blob.\n *\n * @param flowId - The flow ID\n * @param data - Object containing the file data and optional name.\n * @param data.file - The Flow JSON content as a Buffer, JSON object, or Blob.\n * @param data.name - Optional name for the asset, defaults to 'flow.json'.\n * @returns Promise with the success status and validation errors, if any.\n */\n async updateFlowJson(\n flowId: string,\n data: {\n file: Blob | Buffer | object; // JSON object, Buffer, or Blob\n name?: string; // Default to \"flow.json\"\n },\n ): Promise<UpdateFlowResponse> {\n const formData = new FormData();\n let fileContent: Blob;\n\n // Handle different input types for the file\n if (data.file instanceof Buffer) {\n // Buffer\n // Create a Blob from the Buffer and cast it to the global Blob type\n fileContent = new globalThis.Blob([data.file]);\n formData.append('file', fileContent as unknown as Blob);\n } else if (typeof data.file === 'object' && !(data.file instanceof Blob)) {\n // JSON object - stringify and create Blob\n try {\n // Create a Blob from the JSON string and cast it to the global Blob type\n fileContent = new globalThis.Blob([JSON.stringify(data.file, null, 2)], { type: 'application/json' });\n formData.append('file', fileContent as unknown as Blob);\n } catch (e) {\n throw new Error('Failed to stringify JSON object for Flow JSON update.');\n }\n } else if (data.file instanceof Blob) {\n // Blob (already in correct format)\n fileContent = data.file;\n formData.append('file', fileContent as unknown as Blob);\n } else {\n throw new Error('Invalid file type provided for Flow JSON update. Must be a Buffer, JSON object, or Blob.');\n }\n\n formData.append('asset_type', 'FLOW_JSON'); // Required by API\n formData.append('name', data.name || 'flow.json'); // Required by API\n\n // The underlying.sendJson needs to correctly handle FormData\n // It might need specific headers like `Content-Type: multipart/form-data; boundary=...`\n // which FormData library usually helps generate.\n // Assuming.sendJson handles FormData correctly:\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/assets`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData, // Pass FormData directly\n // Headers might be set automatically by the client when FormData is detected,\n // or might need to be explicitly set depending on the client implementation.\n // e.g., { 'Content-Type': `multipart/form-data; boundary=${formData.getBoundary()}` }\n );\n }\n\n /**\n * Validate Flow JSON by attempting an update without publishing.\n * This is a convenience method; the API doesn't have a dedicated validation endpoint.\n *\n * @param flowId - The ID of the Flow (must exist, can be in DRAFT status).\n * @param flowJsonData - The Flow JSON content as a file path (string), Buffer, JSON object, or Blob.\n * @returns Promise indicating if the JSON is valid and includes validation errors if any.\n */\n async validateFlowJson(flowId: string, flowJsonData: Blob | Buffer | object): Promise<ValidateFlowJsonResponse> {\n try {\n const result = await this.updateFlowJson(flowId, {\n file: flowJsonData,\n });\n\n const isValid = !result.validation_errors || result.validation_errors.length === 0;\n\n const enhancedResponse = {\n ...result,\n valid: isValid,\n };\n\n return enhancedResponse;\n } catch (error) {\n LOGGER.error('Error during Flow JSON validation attempt:', error);\n throw error;\n }\n }\n\n /**\n * Publish Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async publishFlow(flowId: string): Promise<ResponseSuccess> {\n // This endpoint expects an empty JSON body or no body\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/publish`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify({}), // Send empty JSON object\n );\n }\n\n /**\n * Deprecate Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async deprecateFlow(flowId: string): Promise<ResponseSuccess> {\n // This endpoint expects an empty JSON body or no body\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/deprecate`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify({}), // Send empty JSON object\n );\n }\n\n /**\n * Migrate Flows between WABAs\n *\n * @param destinationWabaId - The destination WABA ID\n * @param data - The migration data including source_waba_id and optional source_flow_names\n * @returns Promise with migration results (successes and failures)\n */\n async migrateFlows(\n destinationWabaId: string,\n data: {\n source_waba_id: string;\n source_flow_names?: string[];\n },\n ): Promise<FlowMigrationResponse> {\n // API documentation suggests this endpoint might expect application/json\n // Let's double-check or assume JSON based on typical Graph API patterns unless FormData is confirmed.\n // Assuming JSON for now:\n const payload = {\n source_waba_id: data.source_waba_id,\n ...(data.source_flow_names && { source_flow_names: data.source_flow_names }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${destinationWabaId}/migrate_flows`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(payload),\n );\n }\n}\n","// @ts-nocheck\nimport type { LoggerInterface } from '../types/logger';\n\nexport default class Logger implements LoggerInterface {\n private name: string;\n private debug: boolean;\n\n constructor(name: string, debug: boolean = false) {\n this.name = name;\n this.debug = debug;\n }\n\n log(...data: any[]) {\n if (this.debug) {\n let prefix = `[ ${Date.now()} ]`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.log.apply(console, [prefix, ': ', ...data]);\n }\n }\n\n error(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - ERROR`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.error.apply(console, [prefix, ': ', ...data]);\n }\n\n warn(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - WARN`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.warn.apply(console, [prefix, ': ', ...data]);\n }\n\n info(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - INFO`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.info.apply(console, [prefix, ': ', ...data]);\n }\n}\n","import Logger from '../utils/logger';\nimport type { BaseClass } from '../types/base';\nimport type { WabaConfigType } from '../types/config';\nimport type { RequesterClass } from '../types/request';\nimport { HttpMethodsEnum } from 'src/types/enums';\n\nconst LIB_NAME = 'BaseAPI';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class BaseAPI implements BaseClass {\n protected config: WabaConfigType;\n protected client: RequesterClass;\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n this.config = config;\n this.client = client;\n LOGGER.log('Initialized with HTTPSClient');\n }\n\n protected sendJson<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any): Promise<T> {\n return this.client.getJson<T>(method, endpoint, timeout, body);\n }\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,GCGA,IAAqBI,EAArB,KAAuD,CAC3C,KACA,MAER,YAAYC,EAAcC,EAAiB,GAAO,CAC9C,KAAK,KAAOD,EACZ,KAAK,MAAQC,CACjB,CAEA,OAAOC,EAAa,CAChB,GAAI,KAAK,MAAO,CACZ,IAAIC,EAAS,KAAK,KAAK,IAAI,CAAC,KACxB,KAA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AAO,MAAM,6CAA8CoB,CAAK,EAC1DA,CACV,CACJ,CAQA,MAAM,YAAYX,EAA0C,CAExD,OAAO,KAAK,gBAER,IAAIA,CAAM,WACV,KAAK,OAAO,gBACZ,KAAK,UAAU,CAAC,CAAC,CACrB,CACJ,CAQA,MAAM,cAAcA,EAA0C,CAE1D,OAAO,KAAK,gBAER,IAAIA,CAAM,aACV,KAAK,OAAO,gBACZ,KAAK,UAAU,CAAC,CAAC,CACrB,CACJ,CASA,MAAM,aACFY,EACAd,EAI8B,CAI9B,IAAMC,EAAU,CACZ,eAAgBD,EAAK,eACrB,GAAIA,EAAK,mBAAqB,CAAE,kBAAmBA,EAAK,iBAAkB,CAC9E,EAEA,OAAO,KAAK,gBAER,IAAIc,CAAiB,iBACrB,KAAK,OAAO,gBACZ,KAAK,UAAUb,CAAO,CAC1B,CACJ,CACJ","names":["flow_exports","__export","FlowAPI","__toCommonJS","Logger","name","debug","data","prefix","LIB_NAME","LOG_LOCAL","LOGGER","Logger","BaseAPI","config","client","method","endpoint","timeout","body","LIB_NAME","LOG_LOCAL","LOGGER","Logger","FlowAPI","BaseAPI","config","client","wabaId","data","payload","flowId","fields","dateFormat","params","queryString","invalidate","formData","fileContent","flowJsonData","result","isValid","error","destinationWabaId"]}
package/dist/api/flow.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var A=class{name;debug;constructor(i,t=!1){this.name=i,this.debug=t}log(...i){if(this.debug){let t=`[ ${Date.now()} ]`;this.name&&(t+=` - ${this.name}`),console.log.apply(console,[t,": ",...i])}}error(...i){let t=`[ ${Date.now()} ] - ERROR`;this.name&&(t+=` - ${this.name}`),console.error.apply(console,[t,": ",...i])}warn(...i){let t=`[ ${Date.now()} ] - WARN`;this.name&&(t+=` - ${this.name}`),console.warn.apply(console,[t,": ",...i])}info(...i){let t=`[ ${Date.now()} ] - INFO`;this.name&&(t+=` - ${this.name}`),console.info.apply(console,[t,": ",...i])}};var B="BaseAPI",_=!1,O=new A(B,process.env.DEBUG==="true"||_),S=class{config;client;constructor(i,t){this.config=i,this.client=t,O.log("Initialized with HTTPSClient")}sendJson(i,t,R,l){return this.client.getJson(i,t,R,l)}};var G="FlowAPI",U=!1,N=new A(G,process.env.DEBUG==="true"||U),p=class extends S{constructor(i,t){super(i,t),N.log("FlowAPI initialized")}async listFlows(i){return this.sendJson("GET",`/${i}/flows`,this.config.REQUEST_TIMEOUT,null)}async createFlow(i,t){let R={name:t.name,categories:t.categories,...t.endpoint_uri&&{endpoint_uri:t.endpoint_uri},...t.clone_flow_id&&{clone_flow_id:t.clone_flow_id},...t.flow_json&&{flow_json:t.flow_json},...t.publish!==void 0&&{publish:t.publish}};return this.sendJson("POST",`/${i}/flows`,this.config.REQUEST_TIMEOUT,JSON.stringify(R))}async getFlow(i,t,R){let l=new URLSearchParams;t&&l.append("fields",t),R&&l.append("date_format",R);let P=l.toString()?`?${l.toString()}`:"";return this.sendJson("GET",`/${i}${P}`,this.config.REQUEST_TIMEOUT,null)}async getFlowPreview(i,t=!1){let R=`preview.invalidate(${t})`;return this.getFlow(i,R)}async updateFlowMetadata(i,t){let R={...t.name&&{name:t.name},...t.categories&&{categories:t.categories},...t.endpoint_uri&&{endpoint_uri:t.endpoint_uri},...t.application_id&&{application_id:t.application_id}};return this.sendJson("POST",`/${i}`,this.config.REQUEST_TIMEOUT,JSON.stringify(R))}async deleteFlow(i){return this.sendJson("DELETE",`/${i}`,this.config.REQUEST_TIMEOUT,null)}async listAssets(i){return this.sendJson("GET",`/${i}/assets`,this.config.REQUEST_TIMEOUT,null)}async updateFlowJson(i,t){let R=new FormData,l;if(t.file instanceof Buffer)l=new globalThis.Blob([t.file]),R.append("file",l);else if(typeof t.file=="object"&&!(t.file instanceof Blob))try{l=new globalThis.Blob([JSON.stringify(t.file,null,2)],{type:"application/json"}),R.append("file",l)}catch{throw new Error("Failed to stringify JSON object for Flow JSON update.")}else if(t.file instanceof Blob)l=t.file,R.append("file",l);else throw new Error("Invalid file type provided for Flow JSON update. Must be a Buffer, JSON object, or Blob.");return R.append("asset_type","FLOW_JSON"),R.append("name",t.name||"flow.json"),this.sendJson("POST",`/${i}/assets`,this.config.REQUEST_TIMEOUT,R)}async validateFlowJson(i,t){try{let l=await(await this.updateFlowJson(i,{file:t})).json(),P=!l.validation_errors||l.validation_errors.length===0,f={...l,valid:P};return{json:async()=>f}}catch(R){throw N.error("Error during Flow JSON validation attempt:",R),R}}async publishFlow(i){return this.sendJson("POST",`/${i}/publish`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async deprecateFlow(i){return this.sendJson("POST",`/${i}/deprecate`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async migrateFlows(i,t){let R={source_waba_id:t.source_waba_id,...t.source_flow_names&&{source_flow_names:t.source_flow_names}};return this.sendJson("POST",`/${i}/migrate_flows`,this.config.REQUEST_TIMEOUT,JSON.stringify(R))}};export{p as default};
1
+ var A=class{name;debug;constructor(i,t=!1){this.name=i,this.debug=t}log(...i){if(this.debug){let t=`[ ${Date.now()} ]`;this.name&&(t+=` - ${this.name}`),console.log.apply(console,[t,": ",...i])}}error(...i){let t=`[ ${Date.now()} ] - ERROR`;this.name&&(t+=` - ${this.name}`),console.error.apply(console,[t,": ",...i])}warn(...i){let t=`[ ${Date.now()} ] - WARN`;this.name&&(t+=` - ${this.name}`),console.warn.apply(console,[t,": ",...i])}info(...i){let t=`[ ${Date.now()} ] - INFO`;this.name&&(t+=` - ${this.name}`),console.info.apply(console,[t,": ",...i])}};var B="BaseAPI",O=!1,_=new A(B,process.env.DEBUG==="true"||O),S=class{config;client;constructor(i,t){this.config=i,this.client=t,_.log("Initialized with HTTPSClient")}sendJson(i,t,R,l){return this.client.getJson(i,t,R,l)}};var G="FlowAPI",U=!1,N=new A(G,process.env.DEBUG==="true"||U),D=class extends S{constructor(i,t){super(i,t),N.log("FlowAPI initialized")}async listFlows(i){return this.sendJson("GET",`/${i}/flows`,this.config.REQUEST_TIMEOUT,null)}async createFlow(i,t){let R={name:t.name,categories:t.categories,...t.endpoint_uri&&{endpoint_uri:t.endpoint_uri},...t.clone_flow_id&&{clone_flow_id:t.clone_flow_id},...t.flow_json&&{flow_json:t.flow_json},...t.publish!==void 0&&{publish:t.publish}};return this.sendJson("POST",`/${i}/flows`,this.config.REQUEST_TIMEOUT,JSON.stringify(R))}async getFlow(i,t,R){let l=new URLSearchParams;t&&l.append("fields",t),R&&l.append("date_format",R);let P=l.toString()?`?${l.toString()}`:"";return this.sendJson("GET",`/${i}${P}`,this.config.REQUEST_TIMEOUT,null)}async getFlowPreview(i,t=!1){let R=`preview.invalidate(${t})`;return this.getFlow(i,R)}async updateFlowMetadata(i,t){let R={...t.name&&{name:t.name},...t.categories&&{categories:t.categories},...t.endpoint_uri&&{endpoint_uri:t.endpoint_uri},...t.application_id&&{application_id:t.application_id}};return this.sendJson("POST",`/${i}`,this.config.REQUEST_TIMEOUT,JSON.stringify(R))}async deleteFlow(i){return this.sendJson("DELETE",`/${i}`,this.config.REQUEST_TIMEOUT,null)}async listAssets(i){return this.sendJson("GET",`/${i}/assets`,this.config.REQUEST_TIMEOUT,null)}async updateFlowJson(i,t){let R=new FormData,l;if(t.file instanceof Buffer)l=new globalThis.Blob([t.file]),R.append("file",l);else if(typeof t.file=="object"&&!(t.file instanceof Blob))try{l=new globalThis.Blob([JSON.stringify(t.file,null,2)],{type:"application/json"}),R.append("file",l)}catch{throw new Error("Failed to stringify JSON object for Flow JSON update.")}else if(t.file instanceof Blob)l=t.file,R.append("file",l);else throw new Error("Invalid file type provided for Flow JSON update. Must be a Buffer, JSON object, or Blob.");return R.append("asset_type","FLOW_JSON"),R.append("name",t.name||"flow.json"),this.sendJson("POST",`/${i}/assets`,this.config.REQUEST_TIMEOUT,R)}async validateFlowJson(i,t){try{let R=await this.updateFlowJson(i,{file:t}),l=!R.validation_errors||R.validation_errors.length===0;return{...R,valid:l}}catch(R){throw N.error("Error during Flow JSON validation attempt:",R),R}}async publishFlow(i){return this.sendJson("POST",`/${i}/publish`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async deprecateFlow(i){return this.sendJson("POST",`/${i}/deprecate`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async migrateFlows(i,t){let R={source_waba_id:t.source_waba_id,...t.source_flow_names&&{source_flow_names:t.source_flow_names}};return this.sendJson("POST",`/${i}/migrate_flows`,this.config.REQUEST_TIMEOUT,JSON.stringify(R))}};export{D as default};
2
2
  //# sourceMappingURL=flow.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/logger.ts","../../src/api/base.ts","../../src/api/flow.ts"],"sourcesContent":["// @ts-nocheck\nimport type { LoggerInterface } from '../types/logger';\n\nexport default class Logger implements LoggerInterface {\n private name: string;\n private debug: boolean;\n\n constructor(name: string, debug: boolean = false) {\n this.name = name;\n this.debug = debug;\n }\n\n log(...data: any[]) {\n if (this.debug) {\n let prefix = `[ ${Date.now()} ]`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.log.apply(console, [prefix, ': ', ...data]);\n }\n }\n\n error(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - ERROR`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.error.apply(console, [prefix, ': ', ...data]);\n }\n\n warn(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - WARN`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.warn.apply(console, [prefix, ': ', ...data]);\n }\n\n info(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - INFO`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.info.apply(console, [prefix, ': ', ...data]);\n }\n}\n","import Logger from '../utils/logger';\nimport type { BaseClass } from '../types/base';\nimport type { WabaConfigType } from '../types/config';\nimport type { RequesterClass } from '../types/request';\nimport { HttpMethodsEnum } from 'src/types/enums';\n\nconst LIB_NAME = 'BaseAPI';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class BaseAPI implements BaseClass {\n protected config: WabaConfigType;\n protected client: RequesterClass;\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n this.config = config;\n this.client = client;\n LOGGER.log('Initialized with HTTPSClient');\n }\n\n protected sendJson<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any): Promise<T> {\n return this.client.getJson<T>(method, endpoint, timeout, body);\n }\n}\n","import { WabaConfigType } from '../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../types/enums';\nimport {\n Flow,\n FlowAssetsResponse,\n FlowCategoryEnum,\n FlowClass,\n FlowMigrationResponse,\n FlowPreviewResponse,\n FlowsListResponse,\n FlowValidationError,\n} from '../types/flow';\nimport { RequesterClass, RequesterResponseInterface, ResponseSuccess } from '../types/request';\nimport Logger from '../utils/logger';\nimport BaseAPI from './base';\n\nconst LIB_NAME = 'FlowAPI';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class FlowAPI extends BaseAPI implements FlowClass {\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n LOGGER.log('FlowAPI initialized');\n }\n\n /**\n * List Flows\n *\n * @param wabaId - The WABA ID\n * @returns Promise with the list of flows\n */\n async listFlows(wabaId: string): Promise<RequesterResponseInterface<FlowsListResponse>> {\n return this.sendJson(HttpMethodsEnum.Get, `/${wabaId}/flows`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * Create Flow\n *\n * @param wabaId - The WABA ID\n * @param data - The flow data including name, categories, endpoint_uri, and optional clone_flow_id\n * @returns Promise with the created flow ID and validation errors if any\n */\n async createFlow(\n wabaId: string,\n data: {\n name: string;\n categories?: FlowCategoryEnum[];\n endpoint_uri?: string;\n clone_flow_id?: string;\n flow_json?: string; // Flow JSON as a string\n publish?: boolean;\n },\n ): Promise<\n RequesterResponseInterface<{ id: string; success: boolean; validation_errors?: FlowValidationError[] }>\n > {\n // The API expects application/json for this endpoint based on documentation examples\n // Let's ensure we send JSON, not FormData, unless specifically required by an endpoint variation.\n const payload = {\n name: data.name,\n categories: data.categories,\n ...(data.endpoint_uri && { endpoint_uri: data.endpoint_uri }),\n ...(data.clone_flow_id && { clone_flow_id: data.clone_flow_id }),\n ...(data.flow_json && { flow_json: data.flow_json }),\n ...(data.publish !== undefined && { publish: data.publish }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${wabaId}/flows`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(payload), // Send as JSON\n );\n }\n\n /**\n * Get Flow details\n *\n * @param flowId - The flow ID\n * @param fields - Optional fields to return (e.g., 'name,status,preview.invalidate(false)')\n * @param dateFormat - Optional date format\n * @returns Promise with the flow details or preview response\n */\n async getFlow(\n flowId: string,\n fields?: string,\n dateFormat?: string,\n ): Promise<RequesterResponseInterface<Flow | FlowPreviewResponse>> {\n const params = new URLSearchParams();\n if (fields) params.append('fields', fields);\n if (dateFormat) params.append('date_format', dateFormat);\n\n const queryString = params.toString() ? `?${params.toString()}` : '';\n return this.sendJson(\n HttpMethodsEnum.Get,\n `/${flowId}${queryString}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get Flow Preview URL\n *\n * @param flowId - The flow ID\n * @param invalidate - Optional. If true, invalidates existing preview and generates a new one. Defaults to false.\n * @returns Promise with the flow preview details\n */\n async getFlowPreview(\n flowId: string,\n invalidate: boolean = false,\n ): Promise<RequesterResponseInterface<FlowPreviewResponse>> {\n const fields = `preview.invalidate(${invalidate})`;\n // Type assertion needed as getFlow can return Flow or FlowPreviewResponse\n return this.getFlow(flowId, fields) as Promise<RequesterResponseInterface<FlowPreviewResponse>>;\n }\n\n /**\n * Update Flow Metadata\n *\n * @param flowId - The flow ID\n * @param data - The flow metadata to update (name, categories, endpoint_uri, application_id)\n * @returns Promise with the success status\n */\n async updateFlowMetadata(\n flowId: string,\n data: {\n name?: string;\n categories?: FlowCategoryEnum[];\n endpoint_uri?: string;\n application_id?: string;\n },\n ): Promise<RequesterResponseInterface<ResponseSuccess>> {\n // The API expects application/json for this endpoint based on documentation examples\n const payload = {\n ...(data.name && { name: data.name }),\n ...(data.categories && { categories: data.categories }),\n ...(data.endpoint_uri && { endpoint_uri: data.endpoint_uri }),\n ...(data.application_id && { application_id: data.application_id }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(payload), // Send as JSON\n );\n }\n\n /**\n * Delete Flow (only works if the Flow is in DRAFT status)\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async deleteFlow(flowId: string): Promise<RequesterResponseInterface<ResponseSuccess>> {\n return this.sendJson(HttpMethodsEnum.Delete, `/${flowId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * List Assets (e.g., get Flow JSON download URL)\n *\n * @param flowId - The flow ID\n * @returns Promise with the list of assets\n */\n async listAssets(flowId: string): Promise<RequesterResponseInterface<FlowAssetsResponse>> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `/${flowId}/assets`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Update Flow JSON by uploading a file, buffer, JSON object, or Blob.\n *\n * @param flowId - The flow ID\n * @param data - Object containing the file data and optional name.\n * @param data.file - The Flow JSON content as a Buffer, JSON object, or Blob.\n * @param data.name - Optional name for the asset, defaults to 'flow.json'.\n * @returns Promise with the success status and validation errors, if any.\n */\n async updateFlowJson(\n flowId: string,\n data: {\n file: Blob | Buffer | object; // JSON object, Buffer, or Blob\n name?: string; // Default to \"flow.json\"\n },\n ): Promise<RequesterResponseInterface<{ success: boolean; validation_errors?: FlowValidationError[] }>> {\n const formData = new FormData();\n let fileContent: Blob;\n\n // Handle different input types for the file\n if (data.file instanceof Buffer) {\n // Buffer\n // Create a Blob from the Buffer and cast it to the global Blob type\n fileContent = new globalThis.Blob([data.file]);\n formData.append('file', fileContent as unknown as Blob);\n } else if (typeof data.file === 'object' && !(data.file instanceof Blob)) {\n // JSON object - stringify and create Blob\n try {\n // Create a Blob from the JSON string and cast it to the global Blob type\n fileContent = new globalThis.Blob([JSON.stringify(data.file, null, 2)], { type: 'application/json' });\n formData.append('file', fileContent as unknown as Blob);\n } catch (e) {\n throw new Error('Failed to stringify JSON object for Flow JSON update.');\n }\n } else if (data.file instanceof Blob) {\n // Blob (already in correct format)\n fileContent = data.file;\n formData.append('file', fileContent as unknown as Blob);\n } else {\n throw new Error('Invalid file type provided for Flow JSON update. Must be a Buffer, JSON object, or Blob.');\n }\n\n formData.append('asset_type', 'FLOW_JSON'); // Required by API\n formData.append('name', data.name || 'flow.json'); // Required by API\n\n // The underlying.sendJson needs to correctly handle FormData\n // It might need specific headers like `Content-Type: multipart/form-data; boundary=...`\n // which FormData library usually helps generate.\n // Assuming.sendJson handles FormData correctly:\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/assets`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData, // Pass FormData directly\n // Headers might be set automatically by the client when FormData is detected,\n // or might need to be explicitly set depending on the client implementation.\n // e.g., { 'Content-Type': `multipart/form-data; boundary=${formData.getBoundary()}` }\n );\n }\n\n /**\n * Validate Flow JSON by attempting an update without publishing.\n * This is a convenience method; the API doesn't have a dedicated validation endpoint.\n *\n * @param flowId - The ID of the Flow (must exist, can be in DRAFT status).\n * @param flowJsonData - The Flow JSON content as a file path (string), Buffer, JSON object, or Blob.\n * @returns Promise indicating if the JSON is valid and includes validation errors if any.\n */\n async validateFlowJson(\n flowId: string,\n flowJsonData: Blob | Buffer | object,\n ): Promise<\n RequesterResponseInterface<{ valid: boolean; success: boolean; validation_errors?: FlowValidationError[] }>\n > {\n try {\n // Attempt to update the Flow JSON. The API response includes validation errors.\n const result = await this.updateFlowJson(flowId, {\n file: flowJsonData,\n });\n\n // Get the response data\n const responseData = await result.json();\n\n const isValid = !responseData.validation_errors || responseData.validation_errors.length === 0;\n\n // Create a new response with the 'valid' flag\n const enhancedResponse = {\n ...responseData,\n valid: isValid,\n };\n\n // Return a new RequesterResponseInterface with the enhanced data\n return {\n json: async () => enhancedResponse,\n };\n } catch (error) {\n // If the update itself fails (e.g., network error, auth error), rethrow.\n // Specific API validation errors are handled within the 'result' above.\n LOGGER.error('Error during Flow JSON validation attempt:', error);\n throw error;\n }\n }\n\n /**\n * Publish Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async publishFlow(flowId: string): Promise<RequesterResponseInterface<ResponseSuccess>> {\n // This endpoint expects an empty JSON body or no body\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/publish`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify({}), // Send empty JSON object\n );\n }\n\n /**\n * Deprecate Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async deprecateFlow(flowId: string): Promise<RequesterResponseInterface<ResponseSuccess>> {\n // This endpoint expects an empty JSON body or no body\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/deprecate`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify({}), // Send empty JSON object\n );\n }\n\n /**\n * Migrate Flows between WABAs\n *\n * @param destinationWabaId - The destination WABA ID\n * @param data - The migration data including source_waba_id and optional source_flow_names\n * @returns Promise with migration results (successes and failures)\n */\n async migrateFlows(\n destinationWabaId: string,\n data: {\n source_waba_id: string;\n source_flow_names?: string[];\n },\n ): Promise<RequesterResponseInterface<FlowMigrationResponse>> {\n // API documentation suggests this endpoint might expect application/json\n // Let's double-check or assume JSON based on typical Graph API patterns unless FormData is confirmed.\n // Assuming JSON for now:\n const payload = {\n source_waba_id: data.source_waba_id,\n ...(data.source_flow_names && { source_flow_names: data.source_flow_names }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${destinationWabaId}/migrate_flows`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(payload),\n );\n }\n}\n"],"mappings":"AAGA,IAAqBA,EAAr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AAK,eAAeT,EAAQ,CAC7C,KAAMQ,CACV,CAAC,GAGiC,KAAK,EAEjCE,EAAU,CAACD,EAAa,mBAAqBA,EAAa,kBAAkB,SAAW,EAGvFE,EAAmB,CACrB,GAAGF,EACH,MAAOC,CACX,EAGA,MAAO,CACH,KAAM,SAAYC,CACtB,CACJ,OAASC,EAAO,CAGZ,MAAArB,EAAO,MAAM,6CAA8CqB,CAAK,EAC1DA,CACV,CACJ,CAQA,MAAM,YAAYZ,EAAsE,CAEpF,OAAO,KAAK,gBAER,IAAIA,CAAM,WACV,KAAK,OAAO,gBACZ,KAAK,UAAU,CAAC,CAAC,CACrB,CACJ,CAQA,MAAM,cAAcA,EAAsE,CAEtF,OAAO,KAAK,gBAER,IAAIA,CAAM,aACV,KAAK,OAAO,gBACZ,KAAK,UAAU,CAAC,CAAC,CACrB,CACJ,CASA,MAAM,aACFa,EACAf,EAI0D,CAI1D,IAAMC,EAAU,CACZ,eAAgBD,EAAK,eACrB,GAAIA,EAAK,mBAAqB,CAAE,kBAAmBA,EAAK,iBAAkB,CAC9E,EAEA,OAAO,KAAK,gBAER,IAAIe,CAAiB,iBACrB,KAAK,OAAO,gBACZ,KAAK,UAAUd,CAAO,CAC1B,CACJ,CACJ","names":["Logger","name","debug","data","prefix","LIB_NAME","LOG_LOCAL","LOGGER","Logger","BaseAPI","config","client","method","endpoint","timeout","body","LIB_NAME","LOG_LOCAL","LOGGER","Logger","FlowAPI","BaseAPI","config","client","wabaId","data","payload","flowId","fields","dateFormat","params","queryString","invalidate","formData","fileContent","flowJsonData","responseData","isValid","enhancedResponse","error","destinationWabaId"]}
1
+ {"version":3,"sources":["../../src/utils/logger.ts","../../src/api/base.ts","../../src/api/flow.ts"],"sourcesContent":["// @ts-nocheck\nimport type { LoggerInterface } from '../types/logger';\n\nexport default class Logger implements LoggerInterface {\n private name: string;\n private debug: boolean;\n\n constructor(name: string, debug: boolean = false) {\n this.name = name;\n this.debug = debug;\n }\n\n log(...data: any[]) {\n if (this.debug) {\n let prefix = `[ ${Date.now()} ]`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.log.apply(console, [prefix, ': ', ...data]);\n }\n }\n\n error(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - ERROR`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.error.apply(console, [prefix, ': ', ...data]);\n }\n\n warn(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - WARN`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.warn.apply(console, [prefix, ': ', ...data]);\n }\n\n info(...data: any[]) {\n let prefix = `[ ${Date.now()} ] - INFO`;\n if (this.name) {\n prefix += ` - ${this.name}`;\n }\n console.info.apply(console, [prefix, ': ', ...data]);\n }\n}\n","import Logger from '../utils/logger';\nimport type { BaseClass } from '../types/base';\nimport type { WabaConfigType } from '../types/config';\nimport type { RequesterClass } from '../types/request';\nimport { HttpMethodsEnum } from 'src/types/enums';\n\nconst LIB_NAME = 'BaseAPI';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class BaseAPI implements BaseClass {\n protected config: WabaConfigType;\n protected client: RequesterClass;\n\n constructor(config: WabaConfigType, client: RequesterClass) {\n this.config = config;\n this.client = client;\n LOGGER.log('Initialized with HTTPSClient');\n }\n\n protected sendJson<T>(method: HttpMethodsEnum, endpoint: string, timeout: number, body?: any): Promise<T> {\n return this.client.getJson<T>(method, endpoint, timeout, body);\n }\n}\n","import { WabaConfigType } from '../types/config';\nimport { HttpMethodsEnum, WabaConfigEnum } from '../types/enums';\nimport {\n CreateFlowResponse,\n Flow,\n FlowAssetsResponse,\n FlowCategoryEnum,\n FlowClass,\n FlowMigrationResponse,\n FlowPreviewResponse,\n FlowsListResponse,\n UpdateFlowResponse,\n ValidateFlowJsonResponse,\n} from '../types/flow';\nimport { RequesterClass, ResponseSuccess } from '../types/request';\nimport Logger from '../utils/logger';\nimport BaseAPI from './base';\n\nconst LIB_NAME = 'FlowAPI';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class FlowAPI extends BaseAPI implements FlowClass {\n constructor(config: WabaConfigType, client: RequesterClass) {\n super(config, client);\n LOGGER.log('FlowAPI initialized');\n }\n\n /**\n * List Flows\n *\n * @param wabaId - The WABA ID\n * @returns Promise with the list of flows\n */\n async listFlows(wabaId: string): Promise<FlowsListResponse> {\n return this.sendJson(HttpMethodsEnum.Get, `/${wabaId}/flows`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * Create Flow\n *\n * @param wabaId - The WABA ID\n * @param data - The flow data including name, categories, endpoint_uri, and optional clone_flow_id\n * @returns Promise with the created flow ID and validation errors if any\n */\n async createFlow(\n wabaId: string,\n data: {\n name: string;\n categories?: FlowCategoryEnum[];\n endpoint_uri?: string;\n clone_flow_id?: string;\n flow_json?: string; // Flow JSON as a string\n publish?: boolean;\n },\n ): Promise<CreateFlowResponse> {\n // The API expects application/json for this endpoint based on documentation examples\n // Let's ensure we send JSON, not FormData, unless specifically required by an endpoint variation.\n const payload = {\n name: data.name,\n categories: data.categories,\n ...(data.endpoint_uri && { endpoint_uri: data.endpoint_uri }),\n ...(data.clone_flow_id && { clone_flow_id: data.clone_flow_id }),\n ...(data.flow_json && { flow_json: data.flow_json }),\n ...(data.publish !== undefined && { publish: data.publish }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${wabaId}/flows`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(payload), // Send as JSON\n );\n }\n\n /**\n * Get Flow details\n *\n * @param flowId - The flow ID\n * @param fields - Optional fields to return (e.g., 'name,status,preview.invalidate(false)')\n * @param dateFormat - Optional date format\n * @returns Promise with the flow details or preview response\n */\n async getFlow(flowId: string, fields?: string, dateFormat?: string): Promise<Flow | FlowPreviewResponse> {\n const params = new URLSearchParams();\n if (fields) params.append('fields', fields);\n if (dateFormat) params.append('date_format', dateFormat);\n\n const queryString = params.toString() ? `?${params.toString()}` : '';\n return this.sendJson(\n HttpMethodsEnum.Get,\n `/${flowId}${queryString}`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Get Flow Preview URL\n *\n * @param flowId - The flow ID\n * @param invalidate - Optional. If true, invalidates existing preview and generates a new one. Defaults to false.\n * @returns Promise with the flow preview details\n */\n async getFlowPreview(flowId: string, invalidate: boolean = false): Promise<FlowPreviewResponse> {\n const fields = `preview.invalidate(${invalidate})`;\n // Type assertion needed as getFlow can return Flow or FlowPreviewResponse\n return this.getFlow(flowId, fields) as Promise<FlowPreviewResponse>;\n }\n\n /**\n * Update Flow Metadata\n *\n * @param flowId - The flow ID\n * @param data - The flow metadata to update (name, categories, endpoint_uri, application_id)\n * @returns Promise with the success status\n */\n async updateFlowMetadata(\n flowId: string,\n data: {\n name?: string;\n categories?: FlowCategoryEnum[];\n endpoint_uri?: string;\n application_id?: string;\n },\n ): Promise<ResponseSuccess> {\n // The API expects application/json for this endpoint based on documentation examples\n const payload = {\n ...(data.name && { name: data.name }),\n ...(data.categories && { categories: data.categories }),\n ...(data.endpoint_uri && { endpoint_uri: data.endpoint_uri }),\n ...(data.application_id && { application_id: data.application_id }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(payload), // Send as JSON\n );\n }\n\n /**\n * Delete Flow (only works if the Flow is in DRAFT status)\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async deleteFlow(flowId: string): Promise<ResponseSuccess> {\n return this.sendJson(HttpMethodsEnum.Delete, `/${flowId}`, this.config[WabaConfigEnum.RequestTimeout], null);\n }\n\n /**\n * List Assets (e.g., get Flow JSON download URL)\n *\n * @param flowId - The flow ID\n * @returns Promise with the list of assets\n */\n async listAssets(flowId: string): Promise<FlowAssetsResponse> {\n return this.sendJson(\n HttpMethodsEnum.Get,\n `/${flowId}/assets`,\n this.config[WabaConfigEnum.RequestTimeout],\n null,\n );\n }\n\n /**\n * Update Flow JSON by uploading a file, buffer, JSON object, or Blob.\n *\n * @param flowId - The flow ID\n * @param data - Object containing the file data and optional name.\n * @param data.file - The Flow JSON content as a Buffer, JSON object, or Blob.\n * @param data.name - Optional name for the asset, defaults to 'flow.json'.\n * @returns Promise with the success status and validation errors, if any.\n */\n async updateFlowJson(\n flowId: string,\n data: {\n file: Blob | Buffer | object; // JSON object, Buffer, or Blob\n name?: string; // Default to \"flow.json\"\n },\n ): Promise<UpdateFlowResponse> {\n const formData = new FormData();\n let fileContent: Blob;\n\n // Handle different input types for the file\n if (data.file instanceof Buffer) {\n // Buffer\n // Create a Blob from the Buffer and cast it to the global Blob type\n fileContent = new globalThis.Blob([data.file]);\n formData.append('file', fileContent as unknown as Blob);\n } else if (typeof data.file === 'object' && !(data.file instanceof Blob)) {\n // JSON object - stringify and create Blob\n try {\n // Create a Blob from the JSON string and cast it to the global Blob type\n fileContent = new globalThis.Blob([JSON.stringify(data.file, null, 2)], { type: 'application/json' });\n formData.append('file', fileContent as unknown as Blob);\n } catch (e) {\n throw new Error('Failed to stringify JSON object for Flow JSON update.');\n }\n } else if (data.file instanceof Blob) {\n // Blob (already in correct format)\n fileContent = data.file;\n formData.append('file', fileContent as unknown as Blob);\n } else {\n throw new Error('Invalid file type provided for Flow JSON update. Must be a Buffer, JSON object, or Blob.');\n }\n\n formData.append('asset_type', 'FLOW_JSON'); // Required by API\n formData.append('name', data.name || 'flow.json'); // Required by API\n\n // The underlying.sendJson needs to correctly handle FormData\n // It might need specific headers like `Content-Type: multipart/form-data; boundary=...`\n // which FormData library usually helps generate.\n // Assuming.sendJson handles FormData correctly:\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/assets`,\n this.config[WabaConfigEnum.RequestTimeout],\n formData, // Pass FormData directly\n // Headers might be set automatically by the client when FormData is detected,\n // or might need to be explicitly set depending on the client implementation.\n // e.g., { 'Content-Type': `multipart/form-data; boundary=${formData.getBoundary()}` }\n );\n }\n\n /**\n * Validate Flow JSON by attempting an update without publishing.\n * This is a convenience method; the API doesn't have a dedicated validation endpoint.\n *\n * @param flowId - The ID of the Flow (must exist, can be in DRAFT status).\n * @param flowJsonData - The Flow JSON content as a file path (string), Buffer, JSON object, or Blob.\n * @returns Promise indicating if the JSON is valid and includes validation errors if any.\n */\n async validateFlowJson(flowId: string, flowJsonData: Blob | Buffer | object): Promise<ValidateFlowJsonResponse> {\n try {\n const result = await this.updateFlowJson(flowId, {\n file: flowJsonData,\n });\n\n const isValid = !result.validation_errors || result.validation_errors.length === 0;\n\n const enhancedResponse = {\n ...result,\n valid: isValid,\n };\n\n return enhancedResponse;\n } catch (error) {\n LOGGER.error('Error during Flow JSON validation attempt:', error);\n throw error;\n }\n }\n\n /**\n * Publish Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async publishFlow(flowId: string): Promise<ResponseSuccess> {\n // This endpoint expects an empty JSON body or no body\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/publish`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify({}), // Send empty JSON object\n );\n }\n\n /**\n * Deprecate Flow\n *\n * @param flowId - The flow ID\n * @returns Promise with the success status\n */\n async deprecateFlow(flowId: string): Promise<ResponseSuccess> {\n // This endpoint expects an empty JSON body or no body\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${flowId}/deprecate`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify({}), // Send empty JSON object\n );\n }\n\n /**\n * Migrate Flows between WABAs\n *\n * @param destinationWabaId - The destination WABA ID\n * @param data - The migration data including source_waba_id and optional source_flow_names\n * @returns Promise with migration results (successes and failures)\n */\n async migrateFlows(\n destinationWabaId: string,\n data: {\n source_waba_id: string;\n source_flow_names?: string[];\n },\n ): Promise<FlowMigrationResponse> {\n // API documentation suggests this endpoint might expect application/json\n // Let's double-check or assume JSON based on typical Graph API patterns unless FormData is confirmed.\n // Assuming JSON for now:\n const payload = {\n source_waba_id: data.source_waba_id,\n ...(data.source_flow_names && { source_flow_names: data.source_flow_names }),\n };\n\n return this.sendJson(\n HttpMethodsEnum.Post,\n `/${destinationWabaId}/migrate_flows`,\n this.config[WabaConfigEnum.RequestTimeout],\n JSON.stringify(payload),\n );\n }\n}\n"],"mappings":"AAGA,IAAqBA,EAArB,KAAuD,CAC3C,KACA,MAER,YAAYC,EAAcC,EAAiB,GAAO,CAC9C,KAAK,KAAOD,EACZ,KAAK,MAAQC,CACjB,CAEA,OAAOC,EAAa,CAChB,GAAI,KAAK,MAAO,CACZ,IAAIC,EAAS,KAAK,KAAK,IAAI,CAAC,KACxB,KAAK,OACLA,GAAU,MAAM,KAAK,IAAI,IAE7B,QAAQ,IAAI,MAAM,QAAS,CAACA,EAAQ,KAAM,GAAGD,CAAI,CAAC,CACtD,CACJ,CAEA,SAASA,EAAa,CAClB,IAAIC,EAAS,KAAK,KAAK,IAAI,CAAC,aACxB,KAAK,OACLA,GAAU,MAAM,KAAK,IAAI,IAE7B,QAAQ,MAAM,MAAM,QAAS,CAACA,EAAQ,KAAM,GAAGD,CAAI,CAAC,CACxD,CAEA,QAAQA,EAAa,CACjB,IAAIC,EAAS,KAAK,KAAK,IAAI,CAAC,YACxB,KAAK,OACLA,GAAU,MAAM,KAAK,IAAI,IAE7B,QAAQ,KAAK,MAAM,QAAS,CAACA,EAAQ,KAAM,GAAGD,CAAI,CAAC,CACvD,CAEA,QAAQA,EAAa,CACjB,IAAIC,EAAS,KAAK,KAAK,IAAI,CAAC,YACxB,KAAK,OACLA,GAAU,MAAM,KAAK,IAAI,IAE7B,QAAQ,KAAK,MAAM,QAAS,CAACA,EAAQ,KAAM,GAAGD,CAAI,CAAC,CACvD,CACJ,ECvCA,IAAME,EAAW,UACXC,EAAY,GACZC,EAAS,IAAIC,EAAOH,EAAU,QAAQ,IAAI,QAAU,QAAUC,CAAS,EAExDG,EAArB,KAAkD,CACpC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B,MAEtD,OAAM,IAAI,MAAM,0FAA0F,EAG9G,OAAAD,EAAS,OAAO,aAAc,WAAW,EACzCA,EAAS,OAAO,OAAQR,EAAK,MAAQ,WAAW,EAMzC,KAAK,gBAER,IAAIE,CAAM,UACV,KAAK,OAAO,gBACZM,CAIJ,CACJ,CAUA,MAAM,iBAAiBN,EAAgBQ,EAAyE,CAC5G,GAAI,CACA,IAAMC,EAAS,MAAM,KAAK,eAAeT,EAAQ,CAC7C,KAAMQ,CACV,CAAC,EAEKE,EAAU,CAACD,EAAO,mBAAqBA,EAAO,kBAAkB,SAAW,EAOjF,MALyB,CACrB,GAAGA,EACH,MAAOC,CACX,CAGJ,OAASC,EAAO,CACZ,MAAApB,EAAO,MAAM,6CAA8CoB,CAAK,EAC1DA,CACV,CACJ,CAQA,MAAM,YAAYX,EAA0C,CAExD,OAAO,KAAK,gBAER,IAAIA,CAAM,WACV,KAAK,OAAO,gBACZ,KAAK,UAAU,CAAC,CAAC,CACrB,CACJ,CAQA,MAAM,cAAcA,EAA0C,CAE1D,OAAO,KAAK,gBAER,IAAIA,CAAM,aACV,KAAK,OAAO,gBACZ,KAAK,UAAU,CAAC,CAAC,CACrB,CACJ,CASA,MAAM,aACFY,EACAd,EAI8B,CAI9B,IAAMC,EAAU,CACZ,eAAgBD,EAAK,eACrB,GAAIA,EAAK,mBAAqB,CAAE,kBAAmBA,EAAK,iBAAkB,CAC9E,EAEA,OAAO,KAAK,gBAER,IAAIc,CAAiB,iBACrB,KAAK,OAAO,gBACZ,KAAK,UAAUb,CAAO,CAC1B,CACJ,CACJ","names":["Logger","name","debug","data","prefix","LIB_NAME","LOG_LOCAL","LOGGER","Logger","BaseAPI","config","client","method","endpoint","timeout","body","LIB_NAME","LOG_LOCAL","LOGGER","Logger","FlowAPI","BaseAPI","config","client","wabaId","data","payload","flowId","fields","dateFormat","params","queryString","invalidate","formData","fileContent","flowJsonData","result","isValid","error","destinationWabaId"]}
package/dist/api/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var N=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var D=Object.prototype.hasOwnProperty;var m=(o,e)=>{for(var t in e)N(o,t,{get:e[t],enumerable:!0})},U=(o,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of _(e))!D.call(o,i)&&i!==t&&N(o,i,{get:()=>e[i],enumerable:!(s=O(e,i))||s.enumerable});return o};var G=o=>U(N({},"__esModule",{value:!0}),o);var v={};m(v,{BaseAPI:()=>a,BusinessProfileAPI:()=>c,EncryptionAPI:()=>P,FlowAPI:()=>h,MediaAPI:()=>I,MessagesAPI:()=>g,PhoneNumberAPI:()=>S,QrCodeAPI:()=>T,RegistrationAPI:()=>A,TemplateAPI:()=>b,TwoStepVerificationAPI:()=>d,WabaAPI:()=>q});module.exports=G(v);var l=class{name;debug;constructor(e,t=!1){this.name=e,this.debug=t}log(...e){if(this.debug){let t=`[ ${Date.now()} ]`;this.name&&(t+=` - ${this.name}`),console.log.apply(console,[t,": ",...e])}}error(...e){let t=`[ ${Date.now()} ] - ERROR`;this.name&&(t+=` - ${this.name}`),console.error.apply(console,[t,": ",...e])}warn(...e){let t=`[ ${Date.now()} ] - WARN`;this.name&&(t+=` - ${this.name}`),console.warn.apply(console,[t,": ",...e])}info(...e){let t=`[ ${Date.now()} ] - INFO`;this.name&&(t+=` - ${this.name}`),console.info.apply(console,[t,": ",...e])}};var w="BaseAPI",F=!1,J=new l(w,process.env.DEBUG==="true"||F),a=class{config;client;constructor(e,t){this.config=e,this.client=t,J.log("Initialized with HTTPSClient")}sendJson(e,t,s,i){return this.client.getJson(e,t,s,i)}};var R=o=>{if(!o||Object.keys(o).length===0)return"";let e=new URLSearchParams;for(let[s,i]of Object.entries(o))i!==void 0&&e.append(s,String(i));let t=e.toString();return t?`?${t}`:""};var c=class extends a{endpoint="whatsapp_business_profile";constructor(e,t){super(e,t)}async getBusinessProfile(e){let t=e?R({fields:e}):"";return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}${t}`,this.config.REQUEST_TIMEOUT,null)}async updateBusinessProfile(e){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async createUploadSession(e,t,s){let i=R({file_length:e,file_type:t,file_name:s});return this.sendJson("POST",`app/uploads/${i}`,this.config.REQUEST_TIMEOUT,null)}async uploadMedia(e,t){return this.sendJson("POST",`${e}`,this.config.REQUEST_TIMEOUT,t)}async getUploadHandle(e){return this.sendJson("GET",`${e}`,this.config.REQUEST_TIMEOUT,null)}};var P=class extends a{endpoint="whatsapp_business_encryption";constructor(e,t){super(e,t)}async getEncryptionPublicKey(){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async setEncryptionPublicKey(e){let t=new FormData;return t.append("business_public_key",e),this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,t)}};var x="FlowAPI",K=!1,M=new l(x,process.env.DEBUG==="true"||K),h=class extends a{constructor(e,t){super(e,t),M.log("FlowAPI initialized")}async listFlows(e){return this.sendJson("GET",`/${e}/flows`,this.config.REQUEST_TIMEOUT,null)}async createFlow(e,t){let s={name:t.name,categories:t.categories,...t.endpoint_uri&&{endpoint_uri:t.endpoint_uri},...t.clone_flow_id&&{clone_flow_id:t.clone_flow_id},...t.flow_json&&{flow_json:t.flow_json},...t.publish!==void 0&&{publish:t.publish}};return this.sendJson("POST",`/${e}/flows`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}async getFlow(e,t,s){let i=new URLSearchParams;t&&i.append("fields",t),s&&i.append("date_format",s);let p=i.toString()?`?${i.toString()}`:"";return this.sendJson("GET",`/${e}${p}`,this.config.REQUEST_TIMEOUT,null)}async getFlowPreview(e,t=!1){let s=`preview.invalidate(${t})`;return this.getFlow(e,s)}async updateFlowMetadata(e,t){let s={...t.name&&{name:t.name},...t.categories&&{categories:t.categories},...t.endpoint_uri&&{endpoint_uri:t.endpoint_uri},...t.application_id&&{application_id:t.application_id}};return this.sendJson("POST",`/${e}`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}async deleteFlow(e){return this.sendJson("DELETE",`/${e}`,this.config.REQUEST_TIMEOUT,null)}async listAssets(e){return this.sendJson("GET",`/${e}/assets`,this.config.REQUEST_TIMEOUT,null)}async updateFlowJson(e,t){let s=new FormData,i;if(t.file instanceof Buffer)i=new globalThis.Blob([t.file]),s.append("file",i);else if(typeof t.file=="object"&&!(t.file instanceof Blob))try{i=new globalThis.Blob([JSON.stringify(t.file,null,2)],{type:"application/json"}),s.append("file",i)}catch{throw new Error("Failed to stringify JSON object for Flow JSON update.")}else if(t.file instanceof Blob)i=t.file,s.append("file",i);else throw new Error("Invalid file type provided for Flow JSON update. Must be a Buffer, JSON object, or Blob.");return s.append("asset_type","FLOW_JSON"),s.append("name",t.name||"flow.json"),this.sendJson("POST",`/${e}/assets`,this.config.REQUEST_TIMEOUT,s)}async validateFlowJson(e,t){try{let i=await(await this.updateFlowJson(e,{file:t})).json(),p=!i.validation_errors||i.validation_errors.length===0,f={...i,valid:p};return{json:async()=>f}}catch(s){throw M.error("Error during Flow JSON validation attempt:",s),s}}async publishFlow(e){return this.sendJson("POST",`/${e}/publish`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async deprecateFlow(e){return this.sendJson("POST",`/${e}/deprecate`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async migrateFlows(e,t){let s={source_waba_id:t.source_waba_id,...t.source_flow_names&&{source_flow_names:t.source_flow_names}};return this.sendJson("POST",`/${e}/migrate_flows`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}};var I=class extends a{endpoint="media";constructor(e,t){super(e,t)}async getMediaById(e){return this.sendJson("GET",`${e}`,this.config.REQUEST_TIMEOUT,null)}async uploadMedia(e,t="whatsapp"){let s=new FormData;return s.append("file",e),s.append("messaging_product",t),s.append("type",e.type),this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,s)}async deleteMedia(e){return this.sendJson("DELETE",`${e}`,this.config.REQUEST_TIMEOUT,null)}async downloadMedia(e){return this.sendJson("GET",e,this.config.REQUEST_TIMEOUT,null)}};var g=class extends a{commonMethod="POST";commonEndpoint="messages";constructor(e,t){super(e,t)}bodyBuilder(e,t,s,i){let p={messaging_product:"whatsapp",recipient_type:"individual",to:s,type:e,[e]:t};return i&&(p.context={message_id:i}),p}send(e){return this.sendJson(this.commonMethod,`${this.config.WA_PHONE_NUMBER_ID}/${this.commonEndpoint}`,this.config.REQUEST_TIMEOUT,e)}async audio(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("audio",t,s,i)))}async contacts(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("contacts",t,s,i)))}async document(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("document",t,s,i)))}async image(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("image",t,s,i)))}async interactive(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s,i)))}async location(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("location",t,s,i)))}async sticker(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("sticker",t,s,i)))}async template(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("template",t,s,i)))}async text(e){let{body:t,previewUrl:s,to:i,replyMessageId:p}=e,f;return typeof t=="string"?f={body:t,preview_url:s}:f=t,this.send(JSON.stringify(this.bodyBuilder("text",f,i,p)))}async video(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("video",t,s,i)))}async status(e){let{status:t,messageId:s,typingIndicator:i}=e,p={messaging_product:"whatsapp",status:t,message_id:s,...i&&{typing_indicator:i}};return this.send(JSON.stringify(p))}async markAsRead(e){return this.status({status:"read",messageId:e.messageId})}async showTypingIndicator(e){return this.status({status:"read",messageId:e.messageId,typingIndicator:{type:"text"}})}async interactiveList(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s,i)))}async interactiveCtaUrl(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s,i)))}async interactiveLocationRequest(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s,i)))}async interactiveAddressMessage(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s,i)))}async interactiveReplyButtons(e){let{body:t,to:s,replyMessageId:i}=e;return this.send(JSON.stringify(this.bodyBuilder("interactive",t,s,i)))}async interactiveFlow(e){let{body:t,to:s,replyMessageId:i}=e;return t.action.parameters.flow_message_version===void 0&&(t.action.parameters.flow_message_version="3"),t.action.parameters.mode===void 0&&(t.action.parameters.mode="published"),t.action.parameters.flow_action===void 0&&(t.action.parameters.flow_action="navigate"),t.action.parameters.flow_action==="navigate"?t.action.parameters.flow_action_payload?.screen===void 0&&(t.action.parameters.flow_action_payload={...t.action.parameters.flow_action_payload,screen:"INIT"}):t.action.parameters.flow_action==="data_exchange"&&delete t.action.parameters.flow_action_payload,this.send(JSON.stringify(this.bodyBuilder("interactive",t,s,i)))}async reaction(e){let{messageId:t,emoji:s,to:i}=e,p={messaging_product:"whatsapp",recipient_type:"individual",to:i,type:"reaction",reaction:{message_id:t,emoji:s}};return this.send(JSON.stringify(p))}};var S=class extends a{endpoint="phone_numbers";constructor(e,t){super(e,t)}async getPhoneNumberById(e){let t=e?R({fields:e}):"";return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}${t}`,this.config.REQUEST_TIMEOUT,null)}async getPhoneNumbers(){return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async requestVerificationCode(e){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/request_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async verifyCode(e){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/verify_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}};var T=class extends a{endpoint="message_qrdls";constructor(e,t){super(e,t)}async createQrCode(e){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getQrCodes(){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async getQrCode(e){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${e}`,this.config.REQUEST_TIMEOUT,null)}async updateQrCode(e){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async deleteQrCode(e){return this.sendJson("DELETE",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${e}`,this.config.REQUEST_TIMEOUT,null)}};var A=class extends a{constructor(e,t){super(e,t)}async register(e,t){let s={messaging_product:"whatsapp",pin:e,...t&&{data_localization_region:t}};return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/register`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}async deregister(){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/deregister`,this.config.REQUEST_TIMEOUT,null)}};var b=class extends a{endpoint="message_templates";constructor(e,t){super(e,t)}async getTemplate(e){return this.sendJson("GET",`${e}`,this.config.REQUEST_TIMEOUT,null)}async updateTemplate(e,t){return this.sendJson("POST",`${e}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getTemplates(e){return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${R(e)}`,this.config.REQUEST_TIMEOUT,null)}async createTemplate(e){return this.sendJson("POST",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async deleteTemplate(e){return this.sendJson("DELETE",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${R(e)}`,this.config.REQUEST_TIMEOUT,null)}};var d=class extends a{constructor(e,t){super(e,t)}async setTwoStepVerificationCode(e){let t={pin:e};return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}};function B(o){if(!o)return"";let e="";return Array.isArray(o)?e=o.join(","):e=Object.entries(o).filter(([t,s])=>s).map(([t])=>t).join(","),e?`?fields=${e}`:""}var q=class extends a{constructor(e,t){super(e,t)}async getWabaAccount(e){let t=B(e)?.replace(/,/g,"%2C");return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}${t}`,this.config.REQUEST_TIMEOUT,null)}async getAllWabaSubscriptions(){return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,null)}async updateWabaSubscription({override_callback_uri:e,verify_token:t}){let s={override_callback_uri:e,verify_token:t};return this.sendJson("POST",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}async unsubscribeFromWaba(){return this.sendJson("DELETE",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,null)}};0&&(module.exports={BaseAPI,BusinessProfileAPI,EncryptionAPI,FlowAPI,MediaAPI,MessagesAPI,PhoneNumberAPI,QrCodeAPI,RegistrationAPI,TemplateAPI,TwoStepVerificationAPI,WabaAPI});
1
+ "use strict";var B=Object.defineProperty;var _=Object.getOwnPropertyDescriptor;var D=Object.getOwnPropertyNames;var m=Object.prototype.hasOwnProperty;var U=(o,t)=>{for(var e in t)B(o,e,{get:t[e],enumerable:!0})},G=(o,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of D(t))!m.call(o,i)&&i!==e&&B(o,i,{get:()=>t[i],enumerable:!(s=_(t,i))||s.enumerable});return o};var w=o=>G(B({},"__esModule",{value:!0}),o);var v={};U(v,{BaseAPI:()=>a,BusinessProfileAPI:()=>n,EncryptionAPI:()=>P,FlowAPI:()=>h,MediaAPI:()=>c,MessagesAPI:()=>g,PhoneNumberAPI:()=>S,QrCodeAPI:()=>T,RegistrationAPI:()=>A,TemplateAPI:()=>b,TwoStepVerificationAPI:()=>d,WabaAPI:()=>I});module.exports=w(v);var R=class{name;debug;constructor(t,e=!1){this.name=t,this.debug=e}log(...t){if(this.debug){let e=`[ ${Date.now()} ]`;this.name&&(e+=` - ${this.name}`),console.log.apply(console,[e,": ",...t])}}error(...t){let e=`[ ${Date.now()} ] - ERROR`;this.name&&(e+=` - ${this.name}`),console.error.apply(console,[e,": ",...t])}warn(...t){let e=`[ ${Date.now()} ] - WARN`;this.name&&(e+=` - ${this.name}`),console.warn.apply(console,[e,": ",...t])}info(...t){let e=`[ ${Date.now()} ] - INFO`;this.name&&(e+=` - ${this.name}`),console.info.apply(console,[e,": ",...t])}};var q="BaseAPI",F=!1,J=new R(q,process.env.DEBUG==="true"||F),a=class{config;client;constructor(t,e){this.config=t,this.client=e,J.log("Initialized with HTTPSClient")}sendJson(t,e,s,i){return this.client.getJson(t,e,s,i)}};function N(o){if(!o)return"";let t="";return Array.isArray(o)?t=o.join(","):t=Object.entries(o).filter(([e,s])=>s).map(([e])=>e).join(","),t?`?fields=${t}`:""}var f=o=>{if(!o||Object.keys(o).length===0)return"";let t=new URLSearchParams;for(let[s,i]of Object.entries(o))i!==void 0&&t.append(s,String(i));let e=t.toString();return e?`?${e}`:""};var n=class extends a{endpoint="whatsapp_business_profile";constructor(t,e){super(t,e)}async getBusinessProfile(t){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}${N(t)}`,this.config.REQUEST_TIMEOUT,null)}async updateBusinessProfile(t){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async createUploadSession(t,e,s){let i=f({file_length:t,file_type:e,file_name:s});return this.sendJson("POST",`app/uploads/${i}`,this.config.REQUEST_TIMEOUT,null)}async uploadMedia(t,e){return this.sendJson("POST",`${t}`,this.config.REQUEST_TIMEOUT,e)}async getUploadHandle(t){return this.sendJson("GET",`${t}`,this.config.REQUEST_TIMEOUT,null)}};var P=class extends a{endpoint="whatsapp_business_encryption";constructor(t,e){super(t,e)}async getEncryptionPublicKey(){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async setEncryptionPublicKey(t){let e=new FormData;return e.append("business_public_key",t),this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,e)}};var x="FlowAPI",K=!1,O=new R(x,process.env.DEBUG==="true"||K),h=class extends a{constructor(t,e){super(t,e),O.log("FlowAPI initialized")}async listFlows(t){return this.sendJson("GET",`/${t}/flows`,this.config.REQUEST_TIMEOUT,null)}async createFlow(t,e){let s={name:e.name,categories:e.categories,...e.endpoint_uri&&{endpoint_uri:e.endpoint_uri},...e.clone_flow_id&&{clone_flow_id:e.clone_flow_id},...e.flow_json&&{flow_json:e.flow_json},...e.publish!==void 0&&{publish:e.publish}};return this.sendJson("POST",`/${t}/flows`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}async getFlow(t,e,s){let i=new URLSearchParams;e&&i.append("fields",e),s&&i.append("date_format",s);let p=i.toString()?`?${i.toString()}`:"";return this.sendJson("GET",`/${t}${p}`,this.config.REQUEST_TIMEOUT,null)}async getFlowPreview(t,e=!1){let s=`preview.invalidate(${e})`;return this.getFlow(t,s)}async updateFlowMetadata(t,e){let s={...e.name&&{name:e.name},...e.categories&&{categories:e.categories},...e.endpoint_uri&&{endpoint_uri:e.endpoint_uri},...e.application_id&&{application_id:e.application_id}};return this.sendJson("POST",`/${t}`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}async deleteFlow(t){return this.sendJson("DELETE",`/${t}`,this.config.REQUEST_TIMEOUT,null)}async listAssets(t){return this.sendJson("GET",`/${t}/assets`,this.config.REQUEST_TIMEOUT,null)}async updateFlowJson(t,e){let s=new FormData,i;if(e.file instanceof Buffer)i=new globalThis.Blob([e.file]),s.append("file",i);else if(typeof e.file=="object"&&!(e.file instanceof Blob))try{i=new globalThis.Blob([JSON.stringify(e.file,null,2)],{type:"application/json"}),s.append("file",i)}catch{throw new Error("Failed to stringify JSON object for Flow JSON update.")}else if(e.file instanceof Blob)i=e.file,s.append("file",i);else throw new Error("Invalid file type provided for Flow JSON update. Must be a Buffer, JSON object, or Blob.");return s.append("asset_type","FLOW_JSON"),s.append("name",e.name||"flow.json"),this.sendJson("POST",`/${t}/assets`,this.config.REQUEST_TIMEOUT,s)}async validateFlowJson(t,e){try{let s=await this.updateFlowJson(t,{file:e}),i=!s.validation_errors||s.validation_errors.length===0;return{...s,valid:i}}catch(s){throw O.error("Error during Flow JSON validation attempt:",s),s}}async publishFlow(t){return this.sendJson("POST",`/${t}/publish`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async deprecateFlow(t){return this.sendJson("POST",`/${t}/deprecate`,this.config.REQUEST_TIMEOUT,JSON.stringify({}))}async migrateFlows(t,e){let s={source_waba_id:e.source_waba_id,...e.source_flow_names&&{source_flow_names:e.source_flow_names}};return this.sendJson("POST",`/${t}/migrate_flows`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}};var c=class extends a{endpoint="media";constructor(t,e){super(t,e)}async getMediaById(t){return this.sendJson("GET",`${t}`,this.config.REQUEST_TIMEOUT,null)}async uploadMedia(t,e="whatsapp"){let s=new FormData;return s.append("file",t),s.append("messaging_product",e),s.append("type",t.type),this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,s)}async deleteMedia(t){return this.sendJson("DELETE",`${t}`,this.config.REQUEST_TIMEOUT,null)}async downloadMedia(t){return this.sendJson("GET",t,this.config.REQUEST_TIMEOUT,null)}};var g=class extends a{commonMethod="POST";commonEndpoint="messages";constructor(t,e){super(t,e)}bodyBuilder(t,e,s,i){let p={messaging_product:"whatsapp",recipient_type:"individual",to:s,type:t,[t]:e};return i&&(p.context={message_id:i}),p}send(t){return this.sendJson(this.commonMethod,`${this.config.WA_PHONE_NUMBER_ID}/${this.commonEndpoint}`,this.config.REQUEST_TIMEOUT,t)}async audio(t){let{body:e,to:s,replyMessageId:i}=t;return this.send(JSON.stringify(this.bodyBuilder("audio",e,s,i)))}async contacts(t){let{body:e,to:s,replyMessageId:i}=t;return this.send(JSON.stringify(this.bodyBuilder("contacts",e,s,i)))}async document(t){let{body:e,to:s,replyMessageId:i}=t;return this.send(JSON.stringify(this.bodyBuilder("document",e,s,i)))}async image(t){let{body:e,to:s,replyMessageId:i}=t;return this.send(JSON.stringify(this.bodyBuilder("image",e,s,i)))}async interactive(t){let{body:e,to:s,replyMessageId:i}=t;return this.send(JSON.stringify(this.bodyBuilder("interactive",e,s,i)))}async location(t){let{body:e,to:s,replyMessageId:i}=t;return this.send(JSON.stringify(this.bodyBuilder("location",e,s,i)))}async sticker(t){let{body:e,to:s,replyMessageId:i}=t;return this.send(JSON.stringify(this.bodyBuilder("sticker",e,s,i)))}async template(t){let{body:e,to:s,replyMessageId:i}=t;return this.send(JSON.stringify(this.bodyBuilder("template",e,s,i)))}async text(t){let{body:e,previewUrl:s,to:i,replyMessageId:p}=t,M;return typeof e=="string"?M={body:e,preview_url:s}:M=e,this.send(JSON.stringify(this.bodyBuilder("text",M,i,p)))}async video(t){let{body:e,to:s,replyMessageId:i}=t;return this.send(JSON.stringify(this.bodyBuilder("video",e,s,i)))}async status(t){let{status:e,messageId:s,typingIndicator:i}=t,p={messaging_product:"whatsapp",status:e,message_id:s,...i&&{typing_indicator:i}};return this.send(JSON.stringify(p))}async markAsRead(t){return this.status({status:"read",messageId:t.messageId})}async showTypingIndicator(t){return this.status({status:"read",messageId:t.messageId,typingIndicator:{type:"text"}})}async interactiveList(t){let{body:e,to:s,replyMessageId:i}=t;return this.send(JSON.stringify(this.bodyBuilder("interactive",e,s,i)))}async interactiveCtaUrl(t){let{body:e,to:s,replyMessageId:i}=t;return this.send(JSON.stringify(this.bodyBuilder("interactive",e,s,i)))}async interactiveLocationRequest(t){let{body:e,to:s,replyMessageId:i}=t;return this.send(JSON.stringify(this.bodyBuilder("interactive",e,s,i)))}async interactiveAddressMessage(t){let{body:e,to:s,replyMessageId:i}=t;return this.send(JSON.stringify(this.bodyBuilder("interactive",e,s,i)))}async interactiveReplyButtons(t){let{body:e,to:s,replyMessageId:i}=t;return this.send(JSON.stringify(this.bodyBuilder("interactive",e,s,i)))}async interactiveFlow(t){let{body:e,to:s,replyMessageId:i}=t;return e.action.parameters.flow_message_version===void 0&&(e.action.parameters.flow_message_version="3"),e.action.parameters.mode===void 0&&(e.action.parameters.mode="published"),e.action.parameters.flow_action===void 0&&(e.action.parameters.flow_action="navigate"),e.action.parameters.flow_action==="navigate"?e.action.parameters.flow_action_payload?.screen===void 0&&(e.action.parameters.flow_action_payload={...e.action.parameters.flow_action_payload,screen:"INIT"}):e.action.parameters.flow_action==="data_exchange"&&delete e.action.parameters.flow_action_payload,this.send(JSON.stringify(this.bodyBuilder("interactive",e,s,i)))}async reaction(t){let{messageId:e,emoji:s,to:i}=t,p={messaging_product:"whatsapp",recipient_type:"individual",to:i,type:"reaction",reaction:{message_id:e,emoji:s}};return this.send(JSON.stringify(p))}};var S=class extends a{endpoint="phone_numbers";constructor(t,e){super(t,e)}async getPhoneNumberById(t){let e=t?f({fields:t}):"";return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}${e}`,this.config.REQUEST_TIMEOUT,null)}async getPhoneNumbers(){return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async requestVerificationCode(t){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/request_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async verifyCode(t){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/verify_code`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}};var T=class extends a{endpoint="message_qrdls";constructor(t,e){super(t,e)}async createQrCode(t){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async getQrCodes(){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,null)}async getQrCode(t){return this.sendJson("GET",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${t}`,this.config.REQUEST_TIMEOUT,null)}async updateQrCode(t){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async deleteQrCode(t){return this.sendJson("DELETE",`${this.config.WA_PHONE_NUMBER_ID}/${this.endpoint}/${t}`,this.config.REQUEST_TIMEOUT,null)}};var A=class extends a{constructor(t,e){super(t,e)}async register(t,e){let s={messaging_product:"whatsapp",pin:t,...e&&{data_localization_region:e}};return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/register`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}async deregister(){return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}/deregister`,this.config.REQUEST_TIMEOUT,null)}};var b=class extends a{endpoint="message_templates";constructor(t,e){super(t,e)}async getTemplate(t){return this.sendJson("GET",`${t}`,this.config.REQUEST_TIMEOUT,null)}async updateTemplate(t,e){return this.sendJson("POST",`${t}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}async getTemplates(t){return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${f(t)}`,this.config.REQUEST_TIMEOUT,null)}async createTemplate(t){return this.sendJson("POST",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}`,this.config.REQUEST_TIMEOUT,JSON.stringify(t))}async deleteTemplate(t){return this.sendJson("DELETE",`${this.config.WA_BUSINESS_ACCOUNT_ID}/${this.endpoint}${f(t)}`,this.config.REQUEST_TIMEOUT,null)}};var d=class extends a{constructor(t,e){super(t,e)}async setTwoStepVerificationCode(t){let e={pin:t};return this.sendJson("POST",`${this.config.WA_PHONE_NUMBER_ID}`,this.config.REQUEST_TIMEOUT,JSON.stringify(e))}};var I=class extends a{constructor(t,e){super(t,e)}async getWabaAccount(t){let e=N(t)?.replace(/,/g,"%2C");return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}${e}`,this.config.REQUEST_TIMEOUT,null)}async getAllWabaSubscriptions(){return this.sendJson("GET",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,null)}async updateWabaSubscription({override_callback_uri:t,verify_token:e}){let s={override_callback_uri:t,verify_token:e};return this.sendJson("POST",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,JSON.stringify(s))}async unsubscribeFromWaba(){return this.sendJson("DELETE",`${this.config.WA_BUSINESS_ACCOUNT_ID}/subscribed_apps`,this.config.REQUEST_TIMEOUT,null)}};0&&(module.exports={BaseAPI,BusinessProfileAPI,EncryptionAPI,FlowAPI,MediaAPI,MessagesAPI,PhoneNumberAPI,QrCodeAPI,RegistrationAPI,TemplateAPI,TwoStepVerificationAPI,WabaAPI});
2
2
  //# sourceMappingURL=index.js.map