@code.store/arcxp-sdk-ts 4.49.0 → 5.0.0-beta

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 (192) hide show
  1. package/dist/api/abstract-api.d.ts +2 -2
  2. package/dist/api/author/index.d.ts +2 -2
  3. package/dist/api/author/types.d.ts +32 -1
  4. package/dist/api/content/index.d.ts +4 -4
  5. package/dist/api/content/types.d.ts +11 -7
  6. package/dist/api/content-ops/index.d.ts +2 -2
  7. package/dist/api/custom/index.d.ts +1 -1
  8. package/dist/api/draft/index.d.ts +4 -4
  9. package/dist/api/draft/types.d.ts +4 -4
  10. package/dist/api/global-settings/index.d.ts +2 -2
  11. package/dist/api/identity/index.d.ts +2 -2
  12. package/dist/api/ifx/index.d.ts +2 -2
  13. package/dist/api/index.d.ts +19 -20
  14. package/dist/api/migration-center/index.d.ts +2 -2
  15. package/dist/api/migration-center/types.d.ts +4 -38
  16. package/dist/api/photo-center/index.d.ts +8 -9
  17. package/dist/api/photo-center/types.d.ts +3 -4
  18. package/dist/api/redirect/index.d.ts +2 -2
  19. package/dist/api/retail-events/index.d.ts +2 -2
  20. package/dist/api/sales/index.d.ts +2 -2
  21. package/dist/api/signing-service/index.d.ts +2 -2
  22. package/dist/api/site/index.d.ts +3 -4
  23. package/dist/api/site/types.d.ts +88 -1
  24. package/dist/api/tags/index.d.ts +2 -2
  25. package/dist/api/websked/index.d.ts +2 -2
  26. package/dist/api/ws.client.d.ts +1 -1
  27. package/dist/content-elements/content-elements.d.ts +54 -54
  28. package/dist/content-elements/html/html.processor.d.ts +7 -7
  29. package/dist/content-elements/html/html.utils.d.ts +2 -2
  30. package/dist/content-elements/html/index.d.ts +3 -3
  31. package/dist/content-elements/index.d.ts +2 -2
  32. package/dist/content-elements/types.d.ts +4 -0
  33. package/dist/index.cjs +1905 -0
  34. package/dist/index.cjs.map +1 -0
  35. package/dist/index.d.ts +9 -20
  36. package/dist/index.js +1872 -62
  37. package/dist/index.js.map +1 -1
  38. package/dist/lib/axios-rate-limiter.d.ts +2 -0
  39. package/dist/lib/platform/index.d.ts +6 -0
  40. package/dist/lib/platform/node.d.ts +6 -0
  41. package/dist/mapper/doc.d.ts +26 -25
  42. package/dist/mapper/index.d.ts +2 -2
  43. package/dist/mapper/story.d.ts +4 -4
  44. package/dist/types/ans-types.d.ts +2287 -0
  45. package/dist/types/gallery.d.ts +1 -1
  46. package/dist/types/index.d.ts +15 -7
  47. package/dist/types/section.d.ts +1 -1
  48. package/dist/utils/arc/ans.d.ts +2 -2
  49. package/dist/utils/arc/content.d.ts +1 -1
  50. package/dist/utils/arc/index.d.ts +3 -3
  51. package/dist/utils/decorator.d.ts +1 -1
  52. package/package.json +28 -18
  53. package/dist/api/abstract-api.js +0 -61
  54. package/dist/api/abstract-api.js.map +0 -1
  55. package/dist/api/author/index.js +0 -19
  56. package/dist/api/author/index.js.map +0 -1
  57. package/dist/api/author/types.js +0 -3
  58. package/dist/api/author/types.js.map +0 -1
  59. package/dist/api/content/index.js +0 -29
  60. package/dist/api/content/index.js.map +0 -1
  61. package/dist/api/content/types.js +0 -3
  62. package/dist/api/content/types.js.map +0 -1
  63. package/dist/api/content-ops/index.js +0 -27
  64. package/dist/api/content-ops/index.js.map +0 -1
  65. package/dist/api/content-ops/types.js +0 -3
  66. package/dist/api/content-ops/types.js.map +0 -1
  67. package/dist/api/custom/index.js +0 -18
  68. package/dist/api/custom/index.js.map +0 -1
  69. package/dist/api/draft/index.js +0 -63
  70. package/dist/api/draft/index.js.map +0 -1
  71. package/dist/api/draft/types.js +0 -3
  72. package/dist/api/draft/types.js.map +0 -1
  73. package/dist/api/error.js +0 -26
  74. package/dist/api/error.js.map +0 -1
  75. package/dist/api/global-settings/index.js +0 -19
  76. package/dist/api/global-settings/index.js.map +0 -1
  77. package/dist/api/global-settings/types.js +0 -3
  78. package/dist/api/global-settings/types.js.map +0 -1
  79. package/dist/api/identity/index.js +0 -35
  80. package/dist/api/identity/index.js.map +0 -1
  81. package/dist/api/identity/types.js +0 -3
  82. package/dist/api/identity/types.js.map +0 -1
  83. package/dist/api/ifx/index.js +0 -94
  84. package/dist/api/ifx/index.js.map +0 -1
  85. package/dist/api/ifx/types.js +0 -3
  86. package/dist/api/ifx/types.js.map +0 -1
  87. package/dist/api/index.js +0 -49
  88. package/dist/api/index.js.map +0 -1
  89. package/dist/api/migration-center/index.js +0 -45
  90. package/dist/api/migration-center/index.js.map +0 -1
  91. package/dist/api/migration-center/types.js +0 -41
  92. package/dist/api/migration-center/types.js.map +0 -1
  93. package/dist/api/photo-center/index.js +0 -64
  94. package/dist/api/photo-center/index.js.map +0 -1
  95. package/dist/api/photo-center/types.js +0 -3
  96. package/dist/api/photo-center/types.js.map +0 -1
  97. package/dist/api/redirect/index.js +0 -23
  98. package/dist/api/redirect/index.js.map +0 -1
  99. package/dist/api/redirect/types.js +0 -3
  100. package/dist/api/redirect/types.js.map +0 -1
  101. package/dist/api/retail-events/index.js +0 -18
  102. package/dist/api/retail-events/index.js.map +0 -1
  103. package/dist/api/sales/index.js +0 -25
  104. package/dist/api/sales/index.js.map +0 -1
  105. package/dist/api/sales/types.js +0 -3
  106. package/dist/api/sales/types.js.map +0 -1
  107. package/dist/api/signing-service/index.js +0 -15
  108. package/dist/api/signing-service/index.js.map +0 -1
  109. package/dist/api/signing-service/types.js +0 -3
  110. package/dist/api/signing-service/types.js.map +0 -1
  111. package/dist/api/site/index.js +0 -44
  112. package/dist/api/site/index.js.map +0 -1
  113. package/dist/api/site/types.js +0 -3
  114. package/dist/api/site/types.js.map +0 -1
  115. package/dist/api/tags/index.js +0 -36
  116. package/dist/api/tags/index.js.map +0 -1
  117. package/dist/api/tags/types.js +0 -3
  118. package/dist/api/tags/types.js.map +0 -1
  119. package/dist/api/websked/index.js +0 -47
  120. package/dist/api/websked/index.js.map +0 -1
  121. package/dist/api/websked/types.js +0 -3
  122. package/dist/api/websked/types.js.map +0 -1
  123. package/dist/api/ws.client.js +0 -68
  124. package/dist/api/ws.client.js.map +0 -1
  125. package/dist/content-elements/content-elements.js +0 -235
  126. package/dist/content-elements/content-elements.js.map +0 -1
  127. package/dist/content-elements/html/html.constants.js +0 -40
  128. package/dist/content-elements/html/html.constants.js.map +0 -1
  129. package/dist/content-elements/html/html.processor.js +0 -370
  130. package/dist/content-elements/html/html.processor.js.map +0 -1
  131. package/dist/content-elements/html/html.utils.js +0 -79
  132. package/dist/content-elements/html/html.utils.js.map +0 -1
  133. package/dist/content-elements/html/index.js +0 -41
  134. package/dist/content-elements/html/index.js.map +0 -1
  135. package/dist/content-elements/index.js +0 -42
  136. package/dist/content-elements/index.js.map +0 -1
  137. package/dist/mapper/doc.js +0 -146
  138. package/dist/mapper/doc.js.map +0 -1
  139. package/dist/mapper/index.js +0 -8
  140. package/dist/mapper/index.js.map +0 -1
  141. package/dist/mapper/story.js +0 -111
  142. package/dist/mapper/story.js.map +0 -1
  143. package/dist/scripts/json-schema-to-ts.js +0 -8
  144. package/dist/scripts/json-schema-to-ts.js.map +0 -1
  145. package/dist/tests/ans/mapper.test.d.ts +0 -1
  146. package/dist/tests/ans/mapper.test.js +0 -93
  147. package/dist/tests/ans/mapper.test.js.map +0 -1
  148. package/dist/tests/api/basic.test.d.ts +0 -1
  149. package/dist/tests/api/basic.test.js +0 -20
  150. package/dist/tests/api/basic.test.js.map +0 -1
  151. package/dist/tests/api/retry.test.d.ts +0 -1
  152. package/dist/tests/api/retry.test.js +0 -51
  153. package/dist/tests/api/retry.test.js.map +0 -1
  154. package/dist/tests/api/utils.test.d.ts +0 -1
  155. package/dist/tests/api/utils.test.js +0 -255
  156. package/dist/tests/api/utils.test.js.map +0 -1
  157. package/dist/tests/content-elements/html.processor.test.d.ts +0 -1
  158. package/dist/tests/content-elements/html.processor.test.js +0 -35
  159. package/dist/tests/content-elements/html.processor.test.js.map +0 -1
  160. package/dist/types/author.js +0 -8
  161. package/dist/types/author.js.map +0 -1
  162. package/dist/types/content-elements.d.ts +0 -4
  163. package/dist/types/content-elements.js +0 -3
  164. package/dist/types/content-elements.js.map +0 -1
  165. package/dist/types/gallery.js +0 -3
  166. package/dist/types/gallery.js.map +0 -1
  167. package/dist/types/index.js +0 -44
  168. package/dist/types/index.js.map +0 -1
  169. package/dist/types/section.js +0 -3
  170. package/dist/types/section.js.map +0 -1
  171. package/dist/types/story.js +0 -8
  172. package/dist/types/story.js.map +0 -1
  173. package/dist/types/utils.js +0 -3
  174. package/dist/types/utils.js.map +0 -1
  175. package/dist/types/video.js +0 -8
  176. package/dist/types/video.js.map +0 -1
  177. package/dist/utils/arc/ans.js +0 -14
  178. package/dist/utils/arc/ans.js.map +0 -1
  179. package/dist/utils/arc/content.js +0 -79
  180. package/dist/utils/arc/content.js.map +0 -1
  181. package/dist/utils/arc/id.js +0 -40
  182. package/dist/utils/arc/id.js.map +0 -1
  183. package/dist/utils/arc/index.js +0 -45
  184. package/dist/utils/arc/index.js.map +0 -1
  185. package/dist/utils/cache.js +0 -63
  186. package/dist/utils/cache.js.map +0 -1
  187. package/dist/utils/decorator.js +0 -20
  188. package/dist/utils/decorator.js.map +0 -1
  189. package/dist/utils/duration.js +0 -21
  190. package/dist/utils/duration.js.map +0 -1
  191. package/dist/utils/index.js +0 -52
  192. package/dist/utils/index.js.map +0 -1
package/dist/index.cjs ADDED
@@ -0,0 +1,1905 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var axios = require('axios');
6
+ var rateLimit = require('axios-rate-limit');
7
+ var axiosRetry = require('axios-retry');
8
+ var ws = require('ws');
9
+ var FormData = require('form-data');
10
+ var encode = require('base32-encode');
11
+ var uuid = require('uuid');
12
+ var nodeHtmlParser = require('node-html-parser');
13
+ var htmlEntities = require('html-entities');
14
+
15
+ function _interopNamespaceDefault(e) {
16
+ var n = Object.create(null);
17
+ if (e) {
18
+ Object.keys(e).forEach(function (k) {
19
+ if (k !== 'default') {
20
+ var d = Object.getOwnPropertyDescriptor(e, k);
21
+ Object.defineProperty(n, k, d.get ? d : {
22
+ enumerable: true,
23
+ get: function () { return e[k]; }
24
+ });
25
+ }
26
+ });
27
+ }
28
+ n.default = e;
29
+ return Object.freeze(n);
30
+ }
31
+
32
+ var rateLimit__namespace = /*#__PURE__*/_interopNamespaceDefault(rateLimit);
33
+ var ws__namespace = /*#__PURE__*/_interopNamespaceDefault(ws);
34
+
35
+ const safeJSONStringify = (data) => {
36
+ try {
37
+ return JSON.stringify(data) || '';
38
+ }
39
+ catch {
40
+ return '';
41
+ }
42
+ };
43
+ const AxiosResponseErrorInterceptor = (errorConstructor) => {
44
+ return [
45
+ (response) => response,
46
+ (error) => {
47
+ throw errorConstructor(error);
48
+ },
49
+ ];
50
+ };
51
+
52
+ class ArcError extends Error {
53
+ constructor(service, e) {
54
+ const ratelimitRemaining = e.response?.headers['arcpub-ratelimit-remaining'];
55
+ const ratelimitReset = e.response?.headers['arcpub-ratelimit-reset'];
56
+ const data = {
57
+ name: `${service}Error`,
58
+ message: e.message,
59
+ responseData: e.response?.data,
60
+ responseStatus: e.response?.status,
61
+ responseConfig: e.response?.config,
62
+ ratelimitRemaining,
63
+ ratelimitReset,
64
+ service,
65
+ };
66
+ const message = safeJSONStringify(data);
67
+ super(message);
68
+ Object.assign(this, data);
69
+ this.stack = e.stack;
70
+ }
71
+ }
72
+
73
+ class ArcAbstractAPI {
74
+ constructor(options) {
75
+ this.name = this.constructor.name;
76
+ this.token = '';
77
+ this.host = '';
78
+ this.headers = {
79
+ Authorization: '',
80
+ };
81
+ this.host = `api.${options.credentials.organizationName}.arcpublishing.com`;
82
+ this.token = `Bearer ${options.credentials.accessToken}`;
83
+ this.headers.Authorization = this.token;
84
+ const instance = axios.create({
85
+ baseURL: `https://${this.host}/${options.apiPath}`,
86
+ headers: this.headers,
87
+ });
88
+ // apply rate limiting
89
+ this.client = rateLimit__namespace.default(instance, { maxRPS: options.maxRPS || 10 });
90
+ // apply retry
91
+ const retry = typeof axiosRetry === 'function' ? axiosRetry : axiosRetry.default;
92
+ retry(this.client, {
93
+ retries: 5,
94
+ retryDelay: axiosRetry.exponentialDelay,
95
+ retryCondition: (err) => this.retryCondition(err),
96
+ });
97
+ // wrap response errors
98
+ this.client.interceptors.response.use(...AxiosResponseErrorInterceptor((e) => {
99
+ if (e instanceof ArcError)
100
+ return e;
101
+ return new ArcError(this.name, e);
102
+ }));
103
+ }
104
+ setMaxRPS(rps) {
105
+ this.client.setMaxRPS(rps);
106
+ }
107
+ retryCondition(error) {
108
+ const status = error.response?.status;
109
+ switch (status) {
110
+ case axios.HttpStatusCode.RequestTimeout:
111
+ case axios.HttpStatusCode.TooManyRequests:
112
+ case axios.HttpStatusCode.InternalServerError:
113
+ case axios.HttpStatusCode.BadGateway:
114
+ case axios.HttpStatusCode.ServiceUnavailable:
115
+ case axios.HttpStatusCode.GatewayTimeout:
116
+ return true;
117
+ default:
118
+ return false;
119
+ }
120
+ }
121
+ }
122
+
123
+ class ArcAuthor extends ArcAbstractAPI {
124
+ constructor(options) {
125
+ super({ ...options, apiPath: 'author' });
126
+ }
127
+ async listAuthors(params) {
128
+ const { data } = await this.client.get('/v2/author-service', { params });
129
+ return data;
130
+ }
131
+ async delete(userId) {
132
+ const { data } = await this.client.delete(`/v2/author-service/${userId}`);
133
+ return data;
134
+ }
135
+ }
136
+
137
+ class ArcContentOps extends ArcAbstractAPI {
138
+ constructor(options) {
139
+ super({ ...options, apiPath: 'contentops/v1' });
140
+ }
141
+ async schedulePublish(payload) {
142
+ const { data } = await this.client.put('/publish', payload);
143
+ return data;
144
+ }
145
+ async scheduleUnpublish(payload) {
146
+ const { data } = await this.client.put('/unpublish', payload);
147
+ return data;
148
+ }
149
+ async unscheduleUnpublish(payload) {
150
+ const { data } = await this.client.put('/unschedule_unpublish', payload);
151
+ return data;
152
+ }
153
+ async unschedulePublish(payload) {
154
+ const { data } = await this.client.put('/unschedule_publish', payload);
155
+ return data;
156
+ }
157
+ }
158
+
159
+ class ArcContent extends ArcAbstractAPI {
160
+ constructor(options) {
161
+ super({ ...options, apiPath: 'content/v4' });
162
+ }
163
+ async getStory(params) {
164
+ const { data } = await this.client.get('/stories', { params });
165
+ return data;
166
+ }
167
+ async search(params) {
168
+ const { data } = await this.client.get('/search', { params });
169
+ return data;
170
+ }
171
+ async scan(params) {
172
+ const { data } = await this.client.get('/scan', { params });
173
+ return data;
174
+ }
175
+ async getStoriesByIds(params) {
176
+ const { data } = await this.client.get('/ids', {
177
+ params: { ...params, ids: params.ids.join(',') },
178
+ });
179
+ return data;
180
+ }
181
+ }
182
+
183
+ class Custom extends ArcAbstractAPI {
184
+ constructor(options) {
185
+ super({ ...options, apiPath: '' });
186
+ }
187
+ async request(endpoint, config = {}) {
188
+ const response = await this.client.request({
189
+ url: endpoint,
190
+ ...config,
191
+ });
192
+ return response;
193
+ }
194
+ }
195
+
196
+ class ArcDraft extends ArcAbstractAPI {
197
+ constructor(options) {
198
+ super({ ...options, apiPath: 'draft/v1' });
199
+ }
200
+ async generateId(id) {
201
+ const { data } = await this.client.get('/arcuuid', { params: { id } });
202
+ return data.id;
203
+ }
204
+ async createDocument(ans, type = 'story') {
205
+ const { data } = await this.client.post(`/${type}`, ans);
206
+ return data;
207
+ }
208
+ async publishDocument(id, type = 'story') {
209
+ const { data } = await this.client.post(`/${type}/${id}/revision/published`);
210
+ return data;
211
+ }
212
+ async unpublishDocument(id, type = 'story') {
213
+ const { data } = await this.client.delete(`/${type}/${id}/revision/published`);
214
+ return data;
215
+ }
216
+ async deleteDocument(id, type = 'story') {
217
+ const { data } = await this.client.delete(`/${type}/${id}`);
218
+ return data;
219
+ }
220
+ async getPublishedRevision(id, type = 'story') {
221
+ const { data } = await this.client.get(`/${type}/${id}/revision/published`);
222
+ return data;
223
+ }
224
+ async getDraftRevision(id, type = 'story') {
225
+ const { data } = await this.client.get(`/${type}/${id}/revision/draft`);
226
+ return data;
227
+ }
228
+ async getCirculations(id, type = 'story', after) {
229
+ const { data } = await this.client.get(`/${type}/${id}/circulation`, { params: { after } });
230
+ return data;
231
+ }
232
+ async getRevisions(id, type = 'story', after) {
233
+ const { data } = await this.client.get(`/${type}/${id}/revision`, { params: { after } });
234
+ return data;
235
+ }
236
+ async getRevision(id, revisionId, type = 'story') {
237
+ const { data } = await this.client.get(`/${type}/${id}/revision/${revisionId}`);
238
+ return data;
239
+ }
240
+ async createRedirect(website, websiteUrl, payload) {
241
+ const { data } = await this.client.post(`/redirect/${website}/${websiteUrl}`, payload);
242
+ return data;
243
+ }
244
+ async getRedirect(website, websiteUrl) {
245
+ const { data } = await this.client.get(`/redirect/${website}/${websiteUrl}`);
246
+ return data;
247
+ }
248
+ async updateDraftRevision(id, payload, type = 'story') {
249
+ const { data } = await this.client.put(`/${type}/${id}/revision/draft`, payload);
250
+ return data;
251
+ }
252
+ }
253
+
254
+ class GlobalSettings extends ArcAbstractAPI {
255
+ constructor(options) {
256
+ super({ ...options, apiPath: 'settings/v1' });
257
+ }
258
+ async getDistributors(params) {
259
+ const { data } = await this.client.get('/distributor', { params });
260
+ return data;
261
+ }
262
+ async createDistributors(payload) {
263
+ const { data } = await this.client.post('/distributor', payload);
264
+ return data;
265
+ }
266
+ }
267
+
268
+ class ArcIdentity extends ArcAbstractAPI {
269
+ constructor(options) {
270
+ super({ ...options, apiPath: 'identity/api/v1' });
271
+ }
272
+ async migrateBatch(payload) {
273
+ const { data } = await this.client.post('/migrate', payload);
274
+ return data;
275
+ }
276
+ async *migrateBatchGenerator(payload, batchSize = 100) {
277
+ const copy = [...payload.records];
278
+ while (copy.length) {
279
+ const records = copy.splice(0, batchSize);
280
+ const response = await this.migrateBatch({ records });
281
+ yield response;
282
+ }
283
+ }
284
+ async getUser(id) {
285
+ const { data } = await this.client.get(`/user?search=uuid=${id}`);
286
+ return data;
287
+ }
288
+ async getUserByEmail(email) {
289
+ const { data } = await this.client.get(`/user?search=email=${email}`);
290
+ return data;
291
+ }
292
+ async updateUserProfile(id, payload) {
293
+ const { data } = await this.client.patch(`/profile/${id}`, payload);
294
+ return data;
295
+ }
296
+ }
297
+
298
+ const importNodeModule = async (moduleId) => await import(moduleId);
299
+ const modules = {
300
+ // make it like that so static analyzer of webpack won't bundle it
301
+ fs: () => importNodeModule('node:fs'),
302
+ path: () => importNodeModule('node:path'),
303
+ form_data: () => importNodeModule('form-data'),
304
+ };
305
+
306
+ var platform = {
307
+ ...modules,
308
+ };
309
+
310
+ class ArcIFX extends ArcAbstractAPI {
311
+ constructor(options) {
312
+ super({ ...options, apiPath: 'ifx/api/v1' });
313
+ }
314
+ async createIntegration(payload) {
315
+ await this.client.post('/admin/integration', payload);
316
+ }
317
+ async updateIntegration(integrationName, payload) {
318
+ await this.client.put(`/admin/integration/${integrationName}`, payload);
319
+ }
320
+ async deleteIntegration(integrationName, token) {
321
+ await this.client.delete(`/admin/integration/${integrationName}`, { params: { token } });
322
+ }
323
+ async generateDeleteIntegrationToken(integrationName) {
324
+ const response = await this.client.get(`/admin/integration/${integrationName}/token`);
325
+ return response.data;
326
+ }
327
+ async getIntegrations() {
328
+ const { data } = await this.client.get('/admin/integrations');
329
+ return data;
330
+ }
331
+ async getJobs(integrationName) {
332
+ const { data } = await this.client.get(`/admin/jobs/status/${integrationName}`);
333
+ return data;
334
+ }
335
+ async getStatus(integrationName) {
336
+ const { data } = await this.client.get(`/admin/integration/${integrationName}/provisionStatus`);
337
+ return data;
338
+ }
339
+ async initializeQuery(integrationName, query) {
340
+ const { data } = await this.client.get(`/admin/logs/integration/${integrationName}?${query}`);
341
+ return data;
342
+ }
343
+ async getLogs(queryId, raw = true) {
344
+ const { data } = await this.client.get('/admin/logs/results', { params: { queryId, raw } });
345
+ return data;
346
+ }
347
+ async subscribe(payload) {
348
+ const { data } = await this.client.post('/admin/events/subscriptions', payload);
349
+ return data;
350
+ }
351
+ async updateSubscription(payload) {
352
+ const { data } = await this.client.put('/admin/events/subscriptions', payload);
353
+ return data;
354
+ }
355
+ async getSubscriptions() {
356
+ const { data } = await this.client.get('/admin/events/subscriptions');
357
+ return data;
358
+ }
359
+ async addSecret(payload) {
360
+ const { data } = await this.client.post(`/admin/secret?integrationName=${payload.integrationName}`, {
361
+ secretName: payload.secretName,
362
+ secretValue: payload.secretValue,
363
+ });
364
+ return data;
365
+ }
366
+ async getSecrets(integrationName) {
367
+ const { data } = await this.client.get(`/admin/secret?integrationName=${integrationName}`);
368
+ return data;
369
+ }
370
+ async getBundles(integrationName) {
371
+ const { data } = await this.client.get(`/admin/bundles/${integrationName}`);
372
+ return data;
373
+ }
374
+ async uploadBundle(integrationName, name, bundlePath) {
375
+ const fs = await platform.fs();
376
+ const FormData = await platform.form_data();
377
+ const form = new FormData();
378
+ console.log('platform', platform);
379
+ console.log(form);
380
+ const bundle = fs.createReadStream(bundlePath);
381
+ form.append('bundle', bundle);
382
+ form.append('name', name);
383
+ const { data } = await this.client.post(`/admin/bundles/${integrationName}`, form, {
384
+ headers: form.getHeaders(),
385
+ });
386
+ return data;
387
+ }
388
+ async deployBundle(integrationName, name) {
389
+ const { data } = await this.client.post(`/admin/bundles/${integrationName}/deploy/${name}`);
390
+ return data;
391
+ }
392
+ async promoteBundle(integrationName, version) {
393
+ const { data } = await this.client.post(`/admin/bundles/${integrationName}/promote/${version}`);
394
+ return data;
395
+ }
396
+ }
397
+
398
+ class ArcMigrationCenter extends ArcAbstractAPI {
399
+ constructor(options) {
400
+ super({ ...options, apiPath: 'migrations/v3' });
401
+ }
402
+ async summary(params) {
403
+ const { data, headers } = await this.client.get('/report/summary', { params });
404
+ const nextFromId = headers['amc-record-id'];
405
+ return { records: data, nextFromId };
406
+ }
407
+ async detailed(params) {
408
+ const { data } = await this.client.get('/report/detail', { params });
409
+ return data;
410
+ }
411
+ async count(params) {
412
+ const { data } = await this.client.get('/report/status/count', {
413
+ params: {
414
+ startDate: params?.startDate?.toISOString(),
415
+ endDate: params?.endDate?.toISOString(),
416
+ },
417
+ });
418
+ return data;
419
+ }
420
+ async postAns(params, payload) {
421
+ const { data } = await this.client.post('/content/ans', payload, { params });
422
+ return data;
423
+ }
424
+ async getAns(params) {
425
+ const { data } = await this.client.get('/content/ans', { params });
426
+ return data;
427
+ }
428
+ async getRemainingTime(params) {
429
+ const { data } = await this.client.get('/report/remaining-time', { params });
430
+ return data;
431
+ }
432
+ async getRecentGroupIds() {
433
+ const { data } = await this.client.get('/report/group-ids');
434
+ return data;
435
+ }
436
+ }
437
+
438
+ class ArcProtoCenter extends ArcAbstractAPI {
439
+ constructor(options) {
440
+ super({ ...options, apiPath: 'photo/api' });
441
+ }
442
+ async getImageDataById(imageId) {
443
+ const { data } = await this.client.get(`/v2/photos/${imageId}`);
444
+ return data;
445
+ }
446
+ async uploadImageANS(image) {
447
+ const FormData = await platform.form_data();
448
+ const form = new FormData();
449
+ form.append('ans', JSON.stringify(image), {
450
+ filename: 'ans.json',
451
+ contentType: 'application/json',
452
+ });
453
+ const { data } = await this.client.post('/v2/photos', form, { headers: form.getHeaders() });
454
+ return data;
455
+ }
456
+ async uploadImageStream(readableStream, options) {
457
+ const path = await platform.path();
458
+ const FormData = await platform.form_data();
459
+ const form = new FormData();
460
+ const contentType = options?.contentType ?? 'application/octet-stream';
461
+ const filename = path.basename(String(options?.filename || readableStream.path || 'file.jpg'));
462
+ form.append('file', readableStream, {
463
+ filename: filename,
464
+ contentType,
465
+ });
466
+ const { data } = await this.client.post('/v2/photos', form, { headers: form.getHeaders() });
467
+ return data;
468
+ }
469
+ async deleteImage(imageId) {
470
+ const { data } = await this.client.delete(`/v2/photos/${imageId}`);
471
+ return data;
472
+ }
473
+ async deleteGallery(galleryId) {
474
+ const { data } = await this.client.delete(`/v2/galleries/${galleryId}`);
475
+ return data;
476
+ }
477
+ async getImages(params) {
478
+ const { data } = await this.client.get('/v2/photos', { params });
479
+ return data;
480
+ }
481
+ async getGalleries(params) {
482
+ const { data } = await this.client.get('/v2/galleries', { params });
483
+ return data;
484
+ }
485
+ async getGallery(galleryId) {
486
+ const { data } = await this.client.get(`/v2/galleries/${galleryId}`);
487
+ return data;
488
+ }
489
+ async updateImage(imageId, photoDto) {
490
+ const { data } = await this.client.put(`/v2/photos/${imageId}`, photoDto);
491
+ return data;
492
+ }
493
+ }
494
+
495
+ class ArcRedirect extends ArcAbstractAPI {
496
+ constructor(options) {
497
+ super({ ...options, apiPath: 'delivery-api/v1/cloudlet/redirector/site' });
498
+ }
499
+ async getRedirects(orgSiteEnv) {
500
+ const { data } = await this.client.get(`/${orgSiteEnv}/rule?limit=1000`);
501
+ return data;
502
+ }
503
+ async updateArcRedirectRule(orgSiteEnv, redirectID, redirectRuleContent) {
504
+ const { data } = await this.client.put(`/${orgSiteEnv}/rule/${redirectID}`, redirectRuleContent);
505
+ return data;
506
+ }
507
+ async activateRedirectsVersion(orgSiteEnv) {
508
+ const { data } = await this.client.post(`/${orgSiteEnv}/version`);
509
+ return data;
510
+ }
511
+ }
512
+
513
+ class WsClient {
514
+ constructor(address, options) {
515
+ this.address = address;
516
+ this.options = options;
517
+ this._closing = false;
518
+ }
519
+ async connect() {
520
+ if (this.socket && this.socket.readyState === this.socket.OPEN)
521
+ return;
522
+ const socket = new ws__namespace.WebSocket(this.address, this.options);
523
+ this._closing = false;
524
+ socket.onclose = (event) => this.close(event);
525
+ await new Promise((resolve, reject) => {
526
+ socket.onerror = (error) => reject(error);
527
+ socket.onopen = () => resolve(true);
528
+ });
529
+ socket.onmessage = ({ data }) => {
530
+ let message;
531
+ try {
532
+ message = JSON.parse(data.toString());
533
+ }
534
+ catch {
535
+ throw new Error('failed to parse message');
536
+ }
537
+ this.onMessage?.(message);
538
+ };
539
+ this.socket = socket;
540
+ this.onOpen?.();
541
+ }
542
+ close(event) {
543
+ if (this._closing)
544
+ return;
545
+ this._closing = true;
546
+ this.socket?.close();
547
+ this.onClose?.(event);
548
+ }
549
+ async send(data) {
550
+ this.throwIfNotOpen();
551
+ await new Promise((resolve, reject) => {
552
+ this.socket.send(data, (error) => {
553
+ error ? reject(error) : resolve(undefined);
554
+ });
555
+ });
556
+ }
557
+ throwIfNotOpen() {
558
+ if (!this.socket) {
559
+ throw new Error('Client is not connected');
560
+ }
561
+ const { readyState, OPEN } = this.socket;
562
+ if (readyState === OPEN)
563
+ return;
564
+ if (readyState < OPEN) {
565
+ throw new Error('socket is still connecting');
566
+ }
567
+ if (readyState > OPEN) {
568
+ throw new Error('socket was closed');
569
+ }
570
+ }
571
+ }
572
+
573
+ class ArcRetailEvents {
574
+ constructor(options) {
575
+ this.options = options;
576
+ }
577
+ createWsClient(index = '0') {
578
+ const address = `wss://api.${this.options.credentials.organizationName}.arcpublishing.com/retail/api/v1/event/stream/${index}`;
579
+ const headers = {
580
+ Authorization: `Bearer ${this.options.credentials.accessToken}`,
581
+ };
582
+ return new WsClient(address, { headers });
583
+ }
584
+ }
585
+
586
+ class ArcSales extends ArcAbstractAPI {
587
+ constructor(options) {
588
+ super({ ...options, apiPath: 'sales/api/v1' });
589
+ }
590
+ async migrate(payload) {
591
+ const form = new FormData();
592
+ form.append('file', JSON.stringify(payload), { filename: 'subs.json', contentType: 'application/json' });
593
+ const { data } = await this.client.post('/migrate', form, {
594
+ headers: {
595
+ ...form.getHeaders(),
596
+ },
597
+ });
598
+ return data;
599
+ }
600
+ }
601
+
602
+ class ArcSigningService extends ArcAbstractAPI {
603
+ constructor(options) {
604
+ super({ ...options, apiPath: 'signing-service' });
605
+ }
606
+ async sign(service, serviceVersion, imageId) {
607
+ const { data } = await this.client.get(`/v2/sign/${service}/${serviceVersion}?value=${encodeURI(imageId)}`);
608
+ return data;
609
+ }
610
+ }
611
+
612
+ class ArcSite extends ArcAbstractAPI {
613
+ constructor(options) {
614
+ super({ ...options, apiPath: 'site/v3' });
615
+ }
616
+ async getSections(params) {
617
+ const { data } = await this.client.get(`/website/${params.website}/section`, {
618
+ params: { _website: params.website, ...params },
619
+ });
620
+ return data;
621
+ }
622
+ async getSection(id, website) {
623
+ const { data } = await this.client.get(`/website/${website}/section?_id=${id}`);
624
+ return data;
625
+ }
626
+ async deleteSection(id, website) {
627
+ await this.client.delete(`/website/${website}/section?_id=${id}`);
628
+ }
629
+ async putSection(section) {
630
+ const { data } = await this.client.put(`/website/${section.website}/section?_id=${section._id}`, section);
631
+ return data;
632
+ }
633
+ async getWebsites() {
634
+ const { data } = await this.client.get('/website');
635
+ return data;
636
+ }
637
+ async putLink(link) {
638
+ const { data } = await this.client.put(`/website/${link._website}/link/${link._id}`, link);
639
+ return data;
640
+ }
641
+ async deleteLink(id, website) {
642
+ const { data } = await this.client.delete(`/website/${website}/link/${id}`);
643
+ return data;
644
+ }
645
+ async getLinks(params) {
646
+ const { data } = await this.client.get(`/website/${params.website}/link`, { params });
647
+ return data;
648
+ }
649
+ }
650
+
651
+ class ArcTags extends ArcAbstractAPI {
652
+ constructor(options) {
653
+ super({ ...options, apiPath: 'tags' });
654
+ }
655
+ async getAllTags(params) {
656
+ const { data } = await this.client.get('/', { params });
657
+ return data;
658
+ }
659
+ /*
660
+ * @Deprecated
661
+ * May return incorrect results
662
+ * Use searchTagsV2 instead
663
+ */
664
+ async searchTags(params) {
665
+ const { data } = await this.client.get('/search', { params });
666
+ return data;
667
+ }
668
+ async searchTagsV2(params) {
669
+ const { data } = await this.client.get('/v2/search', { params });
670
+ return data;
671
+ }
672
+ async addTags(payload) {
673
+ const { data } = await this.client.post('/add', payload);
674
+ return data;
675
+ }
676
+ async deleteTags(payload) {
677
+ const { data } = await this.client.post('/delete', payload);
678
+ return data;
679
+ }
680
+ }
681
+
682
+ class ArcWebsked extends ArcAbstractAPI {
683
+ constructor(options) {
684
+ super({ ...options, apiPath: 'websked' });
685
+ }
686
+ async reportStatusChange(payload) {
687
+ const { data } = await this.client.post('/tasks/workflowStatusChange', payload);
688
+ return data;
689
+ }
690
+ async createTask(payload) {
691
+ const { data } = await this.client.post('/tasks', payload);
692
+ return data;
693
+ }
694
+ async getEditionTimes(publicationId, startDate, endDate, numEditions = 1) {
695
+ const { data } = await this.client.get(`/publications/${publicationId}/editionTimes`, {
696
+ params: { startDate, endDate, numEditions },
697
+ });
698
+ return data;
699
+ }
700
+ async getSectionStories(publicationId, sectionId, timestamp, includeStories = true) {
701
+ const { data } = await this.client.get(`/publications/${publicationId}/sections/${sectionId}/editions/${timestamp}`, { params: { includeStories } });
702
+ return data;
703
+ }
704
+ async getSectionEditions(publicationId, sectionId, startDate, numEditions = 100) {
705
+ const { data } = await this.client.get(`/publications/${publicationId}/sections/${sectionId}/editions`, {
706
+ params: { startDate, numEditions },
707
+ });
708
+ return data;
709
+ }
710
+ async getPublications(nameRegex) {
711
+ const { data } = await this.client.get('/publications', { params: { nameRegex } });
712
+ return data;
713
+ }
714
+ async getPublicationById(publicationId) {
715
+ const { data } = await this.client.get(`/publications/${publicationId}`);
716
+ return data;
717
+ }
718
+ async getStatuses() {
719
+ const { data } = await this.client.get('/statuses');
720
+ return data;
721
+ }
722
+ }
723
+
724
+ const ArcAPI = (options) => {
725
+ const API = {
726
+ Author: new ArcAuthor(options),
727
+ Draft: new ArcDraft(options),
728
+ Identity: new ArcIdentity(options),
729
+ IFX: new ArcIFX(options),
730
+ Redirect: new ArcRedirect(options),
731
+ MigrationCenter: new ArcMigrationCenter(options),
732
+ Sales: new ArcSales(options),
733
+ Site: new ArcSite(options),
734
+ Websked: new ArcWebsked(options),
735
+ Content: new ArcContent(options),
736
+ SigningService: new ArcSigningService(options),
737
+ PhotoCenter: new ArcProtoCenter(options),
738
+ GlobalSettings: new GlobalSettings(options),
739
+ Tags: new ArcTags(options),
740
+ ContentOps: new ArcContentOps(options),
741
+ RetailEvents: new ArcRetailEvents(options),
742
+ Custom: new Custom(options),
743
+ };
744
+ API.MigrationCenter.setMaxRPS(8);
745
+ API.Draft.setMaxRPS(4);
746
+ API.Content.setMaxRPS(3);
747
+ return API;
748
+ };
749
+
750
+ /* eslint-disable */
751
+ /**
752
+ * This file was automatically generated by json-schema-to-typescript.
753
+ * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
754
+ * and run json-schema-to-typescript to regenerate this file.
755
+ */
756
+
757
+ var ansTypes = /*#__PURE__*/Object.freeze({
758
+ __proto__: null
759
+ });
760
+
761
+ var utils = /*#__PURE__*/Object.freeze({
762
+ __proto__: null
763
+ });
764
+
765
+ var ANSType;
766
+ (function (ANSType) {
767
+ ANSType["Story"] = "story";
768
+ ANSType["Video"] = "video";
769
+ ANSType["Tag"] = "tag";
770
+ ANSType["Author"] = "author";
771
+ ANSType["Gallery"] = "gallery";
772
+ ANSType["Image"] = "image";
773
+ ANSType["Redirect"] = "redirect";
774
+ })(ANSType || (ANSType = {}));
775
+ var MigrationStatus;
776
+ (function (MigrationStatus) {
777
+ MigrationStatus["Success"] = "Success";
778
+ MigrationStatus["Queued"] = "Queued";
779
+ MigrationStatus["Circulated"] = "Circulated";
780
+ MigrationStatus["Published"] = "Published";
781
+ MigrationStatus["Scheduled"] = "Scheduled";
782
+ MigrationStatus["FailVideo"] = "FailVideo";
783
+ MigrationStatus["FailImage"] = "FailImage";
784
+ MigrationStatus["FailPhoto"] = "FailPhoto";
785
+ MigrationStatus["FailStory"] = "FailStory";
786
+ MigrationStatus["FailGallery"] = "FailGallery";
787
+ MigrationStatus["FailAuthor"] = "FailAuthor";
788
+ MigrationStatus["FailTag"] = "FailTag";
789
+ MigrationStatus["ValidationFailed"] = "ValidationFailed";
790
+ })(MigrationStatus || (MigrationStatus = {}));
791
+ var SummarySortBy;
792
+ (function (SummarySortBy) {
793
+ SummarySortBy["CreateDate"] = "createDate";
794
+ SummarySortBy["UpdateDate"] = "updateDate";
795
+ SummarySortBy["Id"] = "id";
796
+ })(SummarySortBy || (SummarySortBy = {}));
797
+ var SummarySortOrder;
798
+ (function (SummarySortOrder) {
799
+ SummarySortOrder["ASC"] = "ASC";
800
+ SummarySortOrder["DESC"] = "DESC";
801
+ })(SummarySortOrder || (SummarySortOrder = {}));
802
+
803
+ var index$3 = /*#__PURE__*/Object.freeze({
804
+ __proto__: null,
805
+ ANS: ansTypes,
806
+ get ANSType () { return ANSType; },
807
+ get MigrationStatus () { return MigrationStatus; },
808
+ get SummarySortBy () { return SummarySortBy; },
809
+ get SummarySortOrder () { return SummarySortOrder; },
810
+ TypeUtils: utils
811
+ });
812
+
813
+ const reference = (ref) => {
814
+ return {
815
+ _id: ref.id,
816
+ type: 'reference',
817
+ referent: {
818
+ ...ref,
819
+ },
820
+ };
821
+ };
822
+
823
+ var ANS = /*#__PURE__*/Object.freeze({
824
+ __proto__: null,
825
+ reference: reference
826
+ });
827
+
828
+ const ContentElement = {
829
+ divider: () => {
830
+ return {
831
+ type: 'divider',
832
+ };
833
+ },
834
+ text: (content, alignment = 'left') => {
835
+ return {
836
+ type: 'text',
837
+ content,
838
+ alignment: alignment || undefined,
839
+ };
840
+ },
841
+ quote: (items, citation = '', subtype = 'pullquote') => {
842
+ return {
843
+ type: 'quote',
844
+ subtype,
845
+ citation: {
846
+ type: 'text',
847
+ content: citation,
848
+ },
849
+ content_elements: items,
850
+ };
851
+ },
852
+ interstitial_link: (url, content) => {
853
+ return {
854
+ type: 'interstitial_link',
855
+ url,
856
+ content,
857
+ };
858
+ },
859
+ header: (content, level) => {
860
+ return {
861
+ type: 'header',
862
+ content,
863
+ level,
864
+ };
865
+ },
866
+ raw_html: (content) => {
867
+ return {
868
+ type: 'raw_html',
869
+ content,
870
+ };
871
+ },
872
+ gallery: (id) => {
873
+ return {
874
+ type: 'reference',
875
+ referent: {
876
+ type: 'gallery',
877
+ id,
878
+ },
879
+ };
880
+ },
881
+ list: (type, items) => {
882
+ return {
883
+ type: 'list',
884
+ list_type: type,
885
+ items,
886
+ };
887
+ },
888
+ link_list: (title, links) => {
889
+ return {
890
+ type: 'link_list',
891
+ title,
892
+ items: links.map(({ content, url }) => {
893
+ return {
894
+ type: 'interstitial_link',
895
+ content,
896
+ url,
897
+ };
898
+ }),
899
+ };
900
+ },
901
+ image: (id, properties) => {
902
+ return {
903
+ referent: {
904
+ id,
905
+ type: 'image',
906
+ referent_properties: {
907
+ _id: id,
908
+ type: 'image',
909
+ ...properties,
910
+ },
911
+ },
912
+ type: 'reference',
913
+ };
914
+ },
915
+ jwPlayer: (id) => {
916
+ return {
917
+ embed: {
918
+ config: {},
919
+ id,
920
+ url: 'https://cdn.jwplayer.com/players',
921
+ },
922
+ subtype: 'jw_player',
923
+ type: 'custom_embed',
924
+ };
925
+ },
926
+ twitter: (id, provider = 'https://publish.twitter.com/oembed?url=') => {
927
+ return {
928
+ referent: {
929
+ id,
930
+ provider,
931
+ service: 'oembed',
932
+ type: 'twitter',
933
+ },
934
+ type: 'reference',
935
+ };
936
+ },
937
+ youtube: (id, provider = 'https://www.youtube.com/oembed?url=') => {
938
+ return {
939
+ referent: {
940
+ id,
941
+ provider,
942
+ service: 'oembed',
943
+ type: 'youtube',
944
+ },
945
+ type: 'reference',
946
+ };
947
+ },
948
+ facebook_video: (id, provider = 'https://www.facebook.com/plugins/post/oembed.json/?url=') => {
949
+ return {
950
+ referent: {
951
+ id,
952
+ provider,
953
+ service: 'oembed',
954
+ type: 'facebook-video',
955
+ },
956
+ type: 'reference',
957
+ };
958
+ },
959
+ facebook_post: (id, provider = 'https://www.facebook.com/plugins/post/oembed.json/?url=') => {
960
+ return {
961
+ referent: {
962
+ id,
963
+ provider,
964
+ service: 'oembed',
965
+ type: 'facebook-post',
966
+ },
967
+ type: 'reference',
968
+ };
969
+ },
970
+ soundcloud: (id, provider = 'https://soundcloud.com/oembed.json/?url=') => {
971
+ return {
972
+ referent: {
973
+ id,
974
+ provider,
975
+ service: 'oembed',
976
+ type: 'soundcloud',
977
+ },
978
+ type: 'reference',
979
+ };
980
+ },
981
+ vimeo: (id, provider = 'https://vimeo.com/api/oembed.json?url=') => {
982
+ return {
983
+ referent: {
984
+ id,
985
+ provider,
986
+ service: 'oembed',
987
+ type: 'vimeo',
988
+ },
989
+ type: 'reference',
990
+ };
991
+ },
992
+ instagram: (id, provider = 'https://api.instagram.com/oembed?url=') => {
993
+ return {
994
+ referent: {
995
+ id,
996
+ provider,
997
+ service: 'oembed',
998
+ type: 'instagram',
999
+ },
1000
+ type: 'reference',
1001
+ };
1002
+ },
1003
+ dailymotion: (id, provider = 'https://www.dailymotion.com/services/oembed?url=') => {
1004
+ return {
1005
+ referent: {
1006
+ id,
1007
+ provider,
1008
+ service: 'oembed',
1009
+ type: 'dailymotion',
1010
+ },
1011
+ type: 'reference',
1012
+ };
1013
+ },
1014
+ tiktok: (id, provider = 'https://www.tiktok.com/oembed?url=') => {
1015
+ return {
1016
+ referent: {
1017
+ id,
1018
+ provider,
1019
+ service: 'oembed',
1020
+ type: 'tiktok',
1021
+ },
1022
+ type: 'reference',
1023
+ };
1024
+ },
1025
+ issuu: (id, provider = 'https://issuu.com/oembed_wp?url=') => {
1026
+ return {
1027
+ referent: {
1028
+ id,
1029
+ provider,
1030
+ service: 'oembed',
1031
+ type: 'issuu',
1032
+ },
1033
+ type: 'reference',
1034
+ };
1035
+ },
1036
+ kickstarter: (id, provider = 'https://www.kickstarter.com/services/oembed?url=') => {
1037
+ return {
1038
+ referent: {
1039
+ id,
1040
+ provider,
1041
+ service: 'oembed',
1042
+ type: 'kickstarter',
1043
+ },
1044
+ type: 'reference',
1045
+ };
1046
+ },
1047
+ polldaddy: (id, provider = 'https://polldaddy.com/oembed/?url=') => {
1048
+ return {
1049
+ referent: {
1050
+ id,
1051
+ provider,
1052
+ service: 'oembed',
1053
+ type: 'polldaddy',
1054
+ },
1055
+ type: 'reference',
1056
+ };
1057
+ },
1058
+ };
1059
+
1060
+ const socialRegExps = {
1061
+ instagram: /(?:https?:\/\/)?(?:www.)?instagram.com\/?([a-zA-Z0-9\.\_\-]+)?\/([p]+)?([reel]+)?([tv]+)?([stories]+)?\/([a-zA-Z0-9\-\_\.]+)\/?([0-9]+)?/,
1062
+ twitter: /https:\/\/(?:www\.)?twitter\.com\/[^\/]+\/status(?:es)?\/(\d+)/,
1063
+ tiktok: /https:\/\/(?:m|www|vm)?\.?tiktok\.com\/((?:.*\b(?:(?:usr|v|embed|user|video)\/|\?shareId=|\&item_id=)(\d+))|\w+)/,
1064
+ facebookPost: /https:\/\/www\.facebook\.com\/(photo(\.php|s)|permalink\.php|media|questions|notes|[^\/]+\/(activity|posts))[\/?].*$/,
1065
+ facebookVideo: /https:\/\/www\.facebook\.com\/([^\/?].+\/)?video(s|\.php)[\/?].*/,
1066
+ };
1067
+ function match(url, regex) {
1068
+ return url.match(regex)?.[0];
1069
+ }
1070
+ function youtubeURLParser(url = '') {
1071
+ const regExp = /(?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]vi?=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/;
1072
+ const id = url?.match(regExp)?.[1];
1073
+ if (id) {
1074
+ return `https://youtu.be/${id}`;
1075
+ }
1076
+ const paylistMatch = url?.match(/[?&]list=([^#&?]+)/);
1077
+ if (paylistMatch?.[1]) {
1078
+ return `https://www.youtube.com/embed/videoseries?list=${paylistMatch?.[1]}`;
1079
+ }
1080
+ return undefined;
1081
+ }
1082
+ function twitterURLParser(url) {
1083
+ return match(url, socialRegExps.twitter);
1084
+ }
1085
+ function instagramURLParser(url) {
1086
+ return match(url, socialRegExps.instagram);
1087
+ }
1088
+ function tiktokURLParser(url) {
1089
+ return match(url, socialRegExps.tiktok);
1090
+ }
1091
+ function facebookVideoURLParser(url) {
1092
+ return match(url, socialRegExps.facebookVideo);
1093
+ }
1094
+ function facebookPostURLParser(url) {
1095
+ return match(url, socialRegExps.facebookPost);
1096
+ }
1097
+ function createSocial(url = '') {
1098
+ const embeds = [];
1099
+ const instagram = instagramURLParser(url);
1100
+ if (instagram) {
1101
+ embeds.push(ContentElement.instagram(instagram));
1102
+ }
1103
+ const twitter = twitterURLParser(url);
1104
+ if (twitter) {
1105
+ embeds.push(ContentElement.twitter(twitter));
1106
+ }
1107
+ const tiktok = tiktokURLParser(url);
1108
+ if (tiktok) {
1109
+ embeds.push(ContentElement.tiktok(tiktok));
1110
+ }
1111
+ const youtube = youtubeURLParser(url);
1112
+ if (youtube) {
1113
+ embeds.push(ContentElement.youtube(youtube));
1114
+ }
1115
+ const facebookPost = facebookPostURLParser(url);
1116
+ if (facebookPost) {
1117
+ embeds.push(ContentElement.facebook_post(facebookPost));
1118
+ }
1119
+ const facebookVideo = facebookVideoURLParser(url);
1120
+ if (facebookVideo) {
1121
+ embeds.push(ContentElement.facebook_video(facebookVideo));
1122
+ }
1123
+ return embeds;
1124
+ }
1125
+ const randomId = () => `${new Date().toISOString()}-${Math.random()}`;
1126
+
1127
+ var ContentElements = /*#__PURE__*/Object.freeze({
1128
+ __proto__: null,
1129
+ createSocial: createSocial,
1130
+ facebookPostURLParser: facebookPostURLParser,
1131
+ facebookVideoURLParser: facebookVideoURLParser,
1132
+ instagramURLParser: instagramURLParser,
1133
+ randomId: randomId,
1134
+ tiktokURLParser: tiktokURLParser,
1135
+ twitterURLParser: twitterURLParser,
1136
+ youtubeURLParser: youtubeURLParser
1137
+ });
1138
+
1139
+ const generateArcId = (identifier, orgHostname) => {
1140
+ const namespace = uuid.v5(orgHostname, uuid.v5.DNS);
1141
+ const buffer = uuid.v5(identifier, namespace, Buffer.alloc(16));
1142
+ return encode(buffer, 'RFC4648', { padding: false });
1143
+ };
1144
+ /**
1145
+ * Utility class for generating Arc IDs and source IDs
1146
+ *
1147
+ * @example
1148
+ * ```ts
1149
+ * const generator = new IdGenerator(['my-org']);
1150
+ * const arcId = generator.getArcId('123'); // Generates a unique for 'my-org' Arc ID
1151
+ * const sourceId = generator.getSourceId('123', ['my-site']); // Generates 'my-site-123'
1152
+ * ```
1153
+ */
1154
+ class IdGenerator {
1155
+ constructor(namespaces) {
1156
+ if (!namespaces.length) {
1157
+ throw new Error('At least 1 namespace is required');
1158
+ }
1159
+ this.namespace = namespaces.join('-');
1160
+ }
1161
+ getArcId(id) {
1162
+ return generateArcId(id.toString(), this.namespace);
1163
+ }
1164
+ getSourceId(id, prefixes = []) {
1165
+ return [...prefixes, id].join('-');
1166
+ }
1167
+ }
1168
+
1169
+ var Id = /*#__PURE__*/Object.freeze({
1170
+ __proto__: null,
1171
+ IdGenerator: IdGenerator,
1172
+ generateArcId: generateArcId
1173
+ });
1174
+
1175
+ const ArcUtils = {
1176
+ Id,
1177
+ ANS,
1178
+ ContentElements,
1179
+ };
1180
+
1181
+ /**
1182
+ * Base class for all arc entities, it provides common methods and properties
1183
+ * If you want to create a new entity subtype you should extend this class
1184
+ *
1185
+ * Use case: You want to migrate stories from BBC
1186
+ * You define `class BBCStory extends ArcDocument<ANS.AStory>` and implement all abstract methods
1187
+ * Then you can override the specific methods to enrich the story with the data from BBC
1188
+ *
1189
+ * To migrate it call .migrate() method
1190
+ */
1191
+ class Document {
1192
+ constructor() {
1193
+ this.ans = null;
1194
+ this.circulations = [];
1195
+ }
1196
+ async init() {
1197
+ // fetch necessary data and validate it here
1198
+ }
1199
+ async prepare() {
1200
+ await this.init();
1201
+ const payload = await this.payload();
1202
+ const params = await this.params();
1203
+ return { payload, params };
1204
+ }
1205
+ async payload() {
1206
+ this.ans = await this.getAns();
1207
+ this.circulations = await this.getCirculations();
1208
+ return {
1209
+ sourceId: await this.sourceId(),
1210
+ sourceType: await this.sourceType(),
1211
+ ANS: this.ans,
1212
+ circulations: this.circulations,
1213
+ arcAdditionalProperties: this.additionalProperties(),
1214
+ };
1215
+ }
1216
+ async params() {
1217
+ if (!this.websiteId()) {
1218
+ throw new Error('Website is not initialized! get params() should be called after payload()!');
1219
+ }
1220
+ return {
1221
+ website: await this.websiteId(),
1222
+ groupId: await this.groupId(),
1223
+ priority: this.priority(),
1224
+ };
1225
+ }
1226
+ additionalProperties() {
1227
+ return {
1228
+ story: {
1229
+ publish: false,
1230
+ },
1231
+ };
1232
+ }
1233
+ priority() {
1234
+ return 'historical';
1235
+ }
1236
+ getDistributor() {
1237
+ return;
1238
+ }
1239
+ getLanguage() {
1240
+ return 'en-GB';
1241
+ }
1242
+ getComments() {
1243
+ return;
1244
+ }
1245
+ async getSource() {
1246
+ return {
1247
+ name: 'code-store',
1248
+ system: 'code-store',
1249
+ source_id: await this.sourceId(),
1250
+ };
1251
+ }
1252
+ getSubheadlines() {
1253
+ return {
1254
+ basic: '',
1255
+ };
1256
+ }
1257
+ getDescription() {
1258
+ return this.getSubheadlines();
1259
+ }
1260
+ formatDate(date) {
1261
+ if (!date)
1262
+ return;
1263
+ return date.toISOString();
1264
+ }
1265
+ getDisplayDate() {
1266
+ return new Date();
1267
+ }
1268
+ async getContentElements() {
1269
+ return [];
1270
+ }
1271
+ getPublicationDate() {
1272
+ return new Date();
1273
+ }
1274
+ getHeadlines() {
1275
+ return {
1276
+ basic: '',
1277
+ };
1278
+ }
1279
+ getTags() {
1280
+ return;
1281
+ }
1282
+ getSubtype() {
1283
+ return;
1284
+ }
1285
+ getLabel() {
1286
+ return;
1287
+ }
1288
+ getRelatedContent() {
1289
+ return;
1290
+ }
1291
+ async getPromoItems() {
1292
+ return;
1293
+ }
1294
+ getWebskedStatusCode() {
1295
+ return;
1296
+ }
1297
+ getCreditsBy() {
1298
+ return [];
1299
+ }
1300
+ getCirculations() {
1301
+ return [];
1302
+ }
1303
+ getEditorNote() {
1304
+ return;
1305
+ }
1306
+ getContentRestrictions() {
1307
+ return;
1308
+ }
1309
+ getOwnerInformation() {
1310
+ return;
1311
+ }
1312
+ getSyndication() {
1313
+ return;
1314
+ }
1315
+ getSchedulingInformation() {
1316
+ return;
1317
+ }
1318
+ getTaxonomy() {
1319
+ return;
1320
+ }
1321
+ }
1322
+
1323
+ /**
1324
+ * Base class for all arc stories, it provides common methods and properties
1325
+ * If you want to create a new story subtype you should extend this class
1326
+ *
1327
+ * Use case: You want to migrate stories from BBC
1328
+ * You define `class BBCStory extends ArcStory` and implement all abstract methods
1329
+ * Then you need to override the specific methods to enrich the story with the data from BBC
1330
+ *
1331
+ * For example:
1332
+ * To add tag to BBC stories you need to override
1333
+ * protected getTags(): MaybePromise<ArcTypes.Story.Tag[]> {
1334
+ * return [{
1335
+ * slug: 'bbc',
1336
+ * text: 'bbc',
1337
+ * }];
1338
+ * }
1339
+ */
1340
+ class Story extends Document {
1341
+ type() {
1342
+ return 'story';
1343
+ }
1344
+ async getAns() {
1345
+ const id = await this.arcId();
1346
+ const version = this.version();
1347
+ const type = this.type();
1348
+ const publicationDate = await this.getPublicationDate();
1349
+ const displayDate = await this.getDisplayDate();
1350
+ const headlines = this.getHeadlines();
1351
+ const subheadlines = this.getSubheadlines();
1352
+ const description = this.getDescription();
1353
+ const language = this.getLanguage();
1354
+ const tags = await this.getTags();
1355
+ const subtype = await this.getSubtype();
1356
+ const label = await this.getLabel();
1357
+ const by = await this.getCreditsBy();
1358
+ const relatedContent = await this.getRelatedContent();
1359
+ const editorNote = await this.getEditorNote();
1360
+ const distributor = await this.getDistributor();
1361
+ const promoItems = await this.getPromoItems();
1362
+ const contentElements = await this.getContentElements();
1363
+ const webskedStatusCode = await this.getWebskedStatusCode();
1364
+ const websiteId = await this.websiteId();
1365
+ const source = await this.getSource();
1366
+ const comments = await this.getComments();
1367
+ const legacyUrl = await this.legacyUrl();
1368
+ const owner = await this.getOwnerInformation();
1369
+ const syndication = await this.getSyndication();
1370
+ const contentRestrictions = await this.getContentRestrictions();
1371
+ const planning = await this.getSchedulingInformation();
1372
+ const taxonomy = await this.getTaxonomy();
1373
+ const additionalMetaProperties = await this.getMigrationMetaProperties();
1374
+ return {
1375
+ type,
1376
+ _id: id,
1377
+ version,
1378
+ website: websiteId,
1379
+ canonical_website: websiteId,
1380
+ language,
1381
+ subtype,
1382
+ label,
1383
+ editor_note: editorNote,
1384
+ credits: {
1385
+ by,
1386
+ },
1387
+ headlines,
1388
+ subheadlines,
1389
+ description,
1390
+ distributor,
1391
+ planning,
1392
+ promo_items: promoItems,
1393
+ related_content: relatedContent,
1394
+ content_restrictions: contentRestrictions,
1395
+ created_date: this.formatDate(new Date()),
1396
+ first_publish_date: this.formatDate(publicationDate),
1397
+ publish_date: this.formatDate(publicationDate),
1398
+ display_date: this.formatDate(displayDate),
1399
+ source,
1400
+ comments,
1401
+ owner,
1402
+ syndication,
1403
+ taxonomy: {
1404
+ ...taxonomy,
1405
+ tags,
1406
+ },
1407
+ workflow: {
1408
+ status_code: webskedStatusCode,
1409
+ },
1410
+ content_elements: contentElements,
1411
+ additional_properties: {
1412
+ url: legacyUrl,
1413
+ ...additionalMetaProperties,
1414
+ },
1415
+ };
1416
+ }
1417
+ async getMigrationMetaProperties() {
1418
+ return {
1419
+ // used in dashboard for migration
1420
+ migration_source_id: await this.sourceId(),
1421
+ migration_source_type: await this.sourceType(),
1422
+ // used in dashboard to show the original url
1423
+ migration_url: await this.legacyUrl(),
1424
+ migration_group_id: await this.groupId(),
1425
+ };
1426
+ }
1427
+ }
1428
+
1429
+ var index$2 = /*#__PURE__*/Object.freeze({
1430
+ __proto__: null,
1431
+ Document: Document,
1432
+ Story: Story
1433
+ });
1434
+
1435
+ const BLOCK_ELEMENT_TAGS = [
1436
+ 'ADDRESS',
1437
+ 'ARTICLE',
1438
+ 'ASIDE',
1439
+ 'BLOCKQUOTE',
1440
+ 'DETAILS',
1441
+ 'DIV',
1442
+ 'DL',
1443
+ 'FIELDSET',
1444
+ 'FIGCAPTION',
1445
+ 'FIGURE',
1446
+ 'FOOTER',
1447
+ 'FORM',
1448
+ 'H1',
1449
+ 'H2',
1450
+ 'H3',
1451
+ 'H4',
1452
+ 'H5',
1453
+ 'H6',
1454
+ 'HEADER',
1455
+ 'HR',
1456
+ 'LINE',
1457
+ 'MAIN',
1458
+ 'MENU',
1459
+ 'NAV',
1460
+ 'OL',
1461
+ 'P',
1462
+ 'PARAGRAPH',
1463
+ 'PRE',
1464
+ 'SECTION',
1465
+ 'TABLE',
1466
+ 'UL',
1467
+ 'LI',
1468
+ 'BODY',
1469
+ 'HTML',
1470
+ ];
1471
+
1472
+ var html_constants = /*#__PURE__*/Object.freeze({
1473
+ __proto__: null,
1474
+ BLOCK_ELEMENT_TAGS: BLOCK_ELEMENT_TAGS
1475
+ });
1476
+
1477
+ const isTextNode = (node) => {
1478
+ return node instanceof nodeHtmlParser.TextNode;
1479
+ };
1480
+ const isHTMLElement = (node) => {
1481
+ return node instanceof nodeHtmlParser.HTMLElement;
1482
+ };
1483
+ const isCommentNode = (node) => {
1484
+ return node instanceof nodeHtmlParser.CommentNode;
1485
+ };
1486
+ const nodeTagIs = (node, name) => {
1487
+ return isHTMLElement(node) && node.tagName?.toLowerCase() === name.toLowerCase();
1488
+ };
1489
+ const nodeTagIn = (node, names) => {
1490
+ return isHTMLElement(node) && names.includes(node.tagName?.toLowerCase());
1491
+ };
1492
+ const isTextCE = (ce) => {
1493
+ return ce?.type === 'text';
1494
+ };
1495
+ const decodeHTMLEntities = (str) => htmlEntities.decode(str);
1496
+ const htmlToText = (html, parseOptions) => {
1497
+ if (!html)
1498
+ return '';
1499
+ const doc = nodeHtmlParser.parse(html, parseOptions);
1500
+ return decodeHTMLEntities(doc.innerText);
1501
+ };
1502
+ const getHTMLElementAttribute = (e, key) => {
1503
+ const value = e.getAttribute(key);
1504
+ if (value)
1505
+ return value;
1506
+ return new URLSearchParams(e.rawAttrs.replaceAll(' ', '&')).get(key);
1507
+ };
1508
+
1509
+ var html_utils = /*#__PURE__*/Object.freeze({
1510
+ __proto__: null,
1511
+ decodeHTMLEntities: decodeHTMLEntities,
1512
+ getHTMLElementAttribute: getHTMLElementAttribute,
1513
+ htmlToText: htmlToText,
1514
+ isCommentNode: isCommentNode,
1515
+ isHTMLElement: isHTMLElement,
1516
+ isTextCE: isTextCE,
1517
+ isTextNode: isTextNode,
1518
+ nodeTagIn: nodeTagIn,
1519
+ nodeTagIs: nodeTagIs
1520
+ });
1521
+
1522
+ /**
1523
+ * HTMLProcessor is responsible for parsing HTML content into structured content elements.
1524
+ * It provides a flexible way to handle different HTML nodes and wrap text content.
1525
+ *
1526
+ * The processor can be extended with custom handlers for specific node types and
1527
+ * wrappers for text content.
1528
+ *
1529
+ * @example
1530
+ * ```ts
1531
+ * // Create and initialize processor
1532
+ * const processor = new HTMLProcessor();
1533
+ * processor.init();
1534
+ *
1535
+ * // Parse HTML content
1536
+ * const html = '<div><p>Some text</p><img src="image.jpg"></div>';
1537
+ * const elements = await processor.parse(html);
1538
+ * ```
1539
+ *
1540
+ * The processor comes with built-in handlers for common HTML elements like links,
1541
+ * text formatting (i, u, strong), and block elements. Custom handlers can be added
1542
+ * using the `handle()` and `wrap()` methods.
1543
+ */
1544
+ class HTMLProcessor {
1545
+ constructor() {
1546
+ this.parallelProcessing = true;
1547
+ this.handlers = {
1548
+ node: new Map(),
1549
+ wrap: new Map(),
1550
+ };
1551
+ }
1552
+ init() {
1553
+ // wrappers are used to wrap the content of nested text nodes
1554
+ // in a specific way
1555
+ this.wrap('link', (node, text) => {
1556
+ if (nodeTagIn(node, ['a'])) {
1557
+ const attributes = ['href', 'target', 'rel']
1558
+ .map((attr) => [attr, getHTMLElementAttribute(node, attr)])
1559
+ .filter(([_, value]) => value)
1560
+ .map(([key, value]) => `${key}="${value}"`)
1561
+ .join(' ');
1562
+ return {
1563
+ ...text,
1564
+ content: `<a ${attributes}>${text.content}</a>`,
1565
+ };
1566
+ }
1567
+ });
1568
+ this.wrap('i', (node, text) => {
1569
+ if (nodeTagIn(node, ['i'])) {
1570
+ return {
1571
+ ...text,
1572
+ content: `<i>${text.content}</i>`,
1573
+ };
1574
+ }
1575
+ });
1576
+ this.wrap('u', (node, text) => {
1577
+ if (nodeTagIn(node, ['u'])) {
1578
+ return {
1579
+ ...text,
1580
+ content: `<u>${text.content}</u>`,
1581
+ };
1582
+ }
1583
+ });
1584
+ this.wrap('sup/sub', (node, text) => {
1585
+ if (nodeTagIn(node, ['sup', 'sub'])) {
1586
+ return {
1587
+ ...text,
1588
+ content: `<mark class="${node.tagName.toLowerCase()}">${text.content}</mark>`,
1589
+ };
1590
+ }
1591
+ });
1592
+ this.wrap('strong', (node, text) => {
1593
+ if (nodeTagIn(node, ['strong', 'b'])) {
1594
+ return {
1595
+ ...text,
1596
+ content: `<b>${text.content}</b>`,
1597
+ };
1598
+ }
1599
+ });
1600
+ this.wrap('center', (node, text) => {
1601
+ if (nodeTagIn(node, ['center'])) {
1602
+ return {
1603
+ ...text,
1604
+ alignment: 'center',
1605
+ };
1606
+ }
1607
+ });
1608
+ this.wrap('aligned-paragraph', (node, text) => {
1609
+ if (nodeTagIn(node, ['p'])) {
1610
+ const styleAttribute = getHTMLElementAttribute(node, 'style') || '';
1611
+ if (!styleAttribute)
1612
+ return text;
1613
+ if (styleAttribute.includes('text-align: right;')) {
1614
+ return {
1615
+ ...text,
1616
+ alignment: 'right',
1617
+ };
1618
+ }
1619
+ if (styleAttribute.includes('text-align: left;')) {
1620
+ return {
1621
+ ...text,
1622
+ alignment: 'left',
1623
+ };
1624
+ }
1625
+ if (styleAttribute.includes('text-align: center;')) {
1626
+ return {
1627
+ ...text,
1628
+ alignment: 'center',
1629
+ };
1630
+ }
1631
+ return text;
1632
+ }
1633
+ });
1634
+ // handlers are used to handle specific nodes
1635
+ // and return a list of content elements
1636
+ this.handle('default', (node) => {
1637
+ const noTag = isHTMLElement(node) && !node.tagName;
1638
+ if (noTag ||
1639
+ nodeTagIn(node, [
1640
+ 'p',
1641
+ 'a',
1642
+ 'b',
1643
+ 'sup',
1644
+ 'sub',
1645
+ 'span',
1646
+ 'strong',
1647
+ 'em',
1648
+ 'i',
1649
+ 'u',
1650
+ 'section',
1651
+ 'main',
1652
+ 'div',
1653
+ 'li',
1654
+ 'center',
1655
+ ])) {
1656
+ return this.handleNested(node);
1657
+ }
1658
+ });
1659
+ this.handle('headers', (node) => {
1660
+ if (nodeTagIn(node, ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'])) {
1661
+ return this.createHeader(node);
1662
+ }
1663
+ });
1664
+ this.handle('text', (node) => {
1665
+ if (isTextNode(node)) {
1666
+ return this.createText(node);
1667
+ }
1668
+ });
1669
+ this.handle('comment', (node) => {
1670
+ if (isCommentNode(node)) {
1671
+ return this.handleComment(node);
1672
+ }
1673
+ });
1674
+ this.handle('list', async (node) => {
1675
+ if (nodeTagIn(node, ['ul', 'ol'])) {
1676
+ const listType = node.tagName === 'UL' ? 'unordered' : 'ordered';
1677
+ return this.createList(node, listType);
1678
+ }
1679
+ });
1680
+ this.handle('table', (node) => {
1681
+ if (nodeTagIs(node, 'table')) {
1682
+ return this.handleTable(node);
1683
+ }
1684
+ });
1685
+ this.handle('iframe', (node) => {
1686
+ if (nodeTagIs(node, 'iframe')) {
1687
+ return this.handleIframe(node);
1688
+ }
1689
+ });
1690
+ this.handle('img', (node) => {
1691
+ if (nodeTagIs(node, 'img')) {
1692
+ return this.handleImage(node);
1693
+ }
1694
+ });
1695
+ this.handle('br', (node) => {
1696
+ if (nodeTagIs(node, 'br')) {
1697
+ return this.handleBreak(node);
1698
+ }
1699
+ });
1700
+ }
1701
+ handle(name, handler) {
1702
+ if (this.handlers.node.has(name)) {
1703
+ this.warn({ name }, `${name} node handler already set`);
1704
+ }
1705
+ this.handlers.node.set(name, handler);
1706
+ }
1707
+ wrap(name, handler) {
1708
+ if (this.handlers.wrap.has(name)) {
1709
+ this.warn({ name }, `${name} wrap handler already set`);
1710
+ }
1711
+ this.handlers.wrap.set(name, handler);
1712
+ }
1713
+ async parse(html) {
1714
+ const doc = nodeHtmlParser.parse(html, { comment: true });
1715
+ doc.removeWhitespace();
1716
+ const elements = await this.process(doc);
1717
+ const filtered = elements?.filter((e) => e.type !== 'divider');
1718
+ return filtered || [];
1719
+ }
1720
+ addTextAdditionalProperties(c, parent) {
1721
+ const additionalProperties = c.additional_properties || {};
1722
+ const parentNodeIsBlockElement = this.isBlockElement(parent);
1723
+ c.additional_properties = {
1724
+ ...c.additional_properties,
1725
+ isBlockElement: additionalProperties.isBlockElement || parentNodeIsBlockElement,
1726
+ };
1727
+ return c;
1728
+ }
1729
+ /**
1730
+ * Wraps text content elements with additional properties and handlers.
1731
+ * This method iterates through an array of content elements and applies
1732
+ * wrappers to text elements.
1733
+ *
1734
+ * @param node - The HTML node containing the text elements
1735
+ **/
1736
+ wrapChildrenTextNodes(node, elements) {
1737
+ const wrapped = [];
1738
+ const wrappers = [...this.handlers.wrap.values()];
1739
+ for (const c of elements) {
1740
+ if (!isTextCE(c)) {
1741
+ wrapped.push(c);
1742
+ continue;
1743
+ }
1744
+ this.addTextAdditionalProperties(c, node);
1745
+ const handled = wrappers.map((wrapper) => wrapper(node, c)).find(Boolean);
1746
+ wrapped.push(handled || c);
1747
+ }
1748
+ return wrapped;
1749
+ }
1750
+ /**
1751
+ * Handles nested nodes by processing their children and merging text elements.
1752
+ * This method recursively processes the children of a given HTML node and
1753
+ * returns a list of content elements.
1754
+ *
1755
+ * @param node - The HTML node to process
1756
+ **/
1757
+ async handleNested(node) {
1758
+ const children = await this.processChildNodes(node);
1759
+ const filtered = children.filter(Boolean).flat();
1760
+ const merged = this.mergeParagraphs(filtered);
1761
+ const wrapped = this.wrapChildrenTextNodes(node, merged);
1762
+ return wrapped;
1763
+ }
1764
+ async processChildNodes(node) {
1765
+ if (this.parallelProcessing) {
1766
+ return await Promise.all(node.childNodes.map((child) => this.process(child)));
1767
+ }
1768
+ const children = [];
1769
+ for (const child of node.childNodes) {
1770
+ children.push(await this.process(child));
1771
+ }
1772
+ return children;
1773
+ }
1774
+ /**
1775
+ * Processes a single HTML node and converts it into content elements.
1776
+ * This method iterates through registered node handlers and attempts to process the node.
1777
+ * If a handler successfully processes the node, it returns an array of content elements.
1778
+ *
1779
+ * @param node - The HTML node to process
1780
+ * @returns Promise resolving to an array of content elements, or undefined if node cannot be processed
1781
+ */
1782
+ async process(node) {
1783
+ let isKnownNode = false;
1784
+ const elements = [];
1785
+ for (const [name, handler] of this.handlers.node.entries()) {
1786
+ try {
1787
+ const result = await handler(node);
1788
+ if (result) {
1789
+ // if handler returns an array of elements, it means that the node was handled properly, even if there is no elements inside
1790
+ isKnownNode = true;
1791
+ elements.push(...result);
1792
+ break;
1793
+ }
1794
+ }
1795
+ catch (error) {
1796
+ this.warn({ node: node.toString(), error: error.toString(), name }, 'HandlerError');
1797
+ }
1798
+ }
1799
+ if (isKnownNode)
1800
+ return elements;
1801
+ this.warn({ node: node.toString() }, 'UnknownNodeError');
1802
+ }
1803
+ /**
1804
+ * Merges adjacent text content elements into a single paragraph.
1805
+ * This method iterates through an array of content elements and combines
1806
+ * adjacent text elements into a single paragraph.
1807
+ *
1808
+ * @param items - The array of content elements to merge
1809
+ **/
1810
+ mergeParagraphs(items) {
1811
+ const merged = [];
1812
+ let toMerge = [];
1813
+ const merge = () => {
1814
+ if (!toMerge.length)
1815
+ return;
1816
+ const paragraph = toMerge.reduce((acc, p) => {
1817
+ return {
1818
+ ...p,
1819
+ content: acc.content + p.content,
1820
+ };
1821
+ }, { type: 'text', content: '' });
1822
+ merged.push(paragraph);
1823
+ toMerge = [];
1824
+ };
1825
+ for (let i = 0; i < items.length; i++) {
1826
+ const item = items[i];
1827
+ const isBlockElement = item.additional_properties?.isBlockElement;
1828
+ if (isTextCE(item) && !isBlockElement) {
1829
+ toMerge.push(item);
1830
+ }
1831
+ else {
1832
+ merge();
1833
+ merged.push(item);
1834
+ }
1835
+ }
1836
+ merge();
1837
+ return merged;
1838
+ }
1839
+ handleComment(_) {
1840
+ return [];
1841
+ }
1842
+ async handleTable(node) {
1843
+ return [ContentElement.raw_html(node.toString())];
1844
+ }
1845
+ async handleIframe(node) {
1846
+ return [ContentElement.raw_html(node.toString())];
1847
+ }
1848
+ async handleImage(node) {
1849
+ return [ContentElement.raw_html(node.toString())];
1850
+ }
1851
+ async handleBreak(_) {
1852
+ return [ContentElement.divider()];
1853
+ }
1854
+ async createQuote(node) {
1855
+ const items = await this.handleNested(node);
1856
+ return [ContentElement.quote(items)];
1857
+ }
1858
+ async createText(node) {
1859
+ const text = ContentElement.text(node.text);
1860
+ return [text];
1861
+ }
1862
+ filterListItems(items) {
1863
+ return items.filter((i) => ['text', 'list'].includes(i.type));
1864
+ }
1865
+ async createList(node, type) {
1866
+ const items = await this.handleNested(node);
1867
+ return [ContentElement.list(type, this.filterListItems(items))];
1868
+ }
1869
+ async createHeader(node) {
1870
+ const level = +node.tagName.split('H')[1] || 3;
1871
+ return [ContentElement.header(node.innerText, level)];
1872
+ }
1873
+ isBlockElement(node) {
1874
+ if (!isHTMLElement(node))
1875
+ return false;
1876
+ const defaultBlockElements = new Set(BLOCK_ELEMENT_TAGS);
1877
+ return defaultBlockElements.has(node.tagName);
1878
+ }
1879
+ warn(metadata, message) {
1880
+ console.warn(metadata, message);
1881
+ }
1882
+ }
1883
+
1884
+ var index$1 = /*#__PURE__*/Object.freeze({
1885
+ __proto__: null,
1886
+ Constants: html_constants,
1887
+ HTMLProcessor: HTMLProcessor,
1888
+ Utils: html_utils
1889
+ });
1890
+
1891
+ var index = /*#__PURE__*/Object.freeze({
1892
+ __proto__: null,
1893
+ ContentElement: ContentElement,
1894
+ HTML: index$1
1895
+ });
1896
+
1897
+ exports.AnsMapper = index$2;
1898
+ exports.ArcAPI = ArcAPI;
1899
+ exports.ArcError = ArcError;
1900
+ exports.ArcTypes = index$3;
1901
+ exports.ArcUtils = ArcUtils;
1902
+ exports.ContentElements = index;
1903
+ exports.WsClient = WsClient;
1904
+ exports.default = ArcAPI;
1905
+ //# sourceMappingURL=index.cjs.map