@prismicio/e2e-tests-utils 1.18.0 → 1.19.0-canary.d349d21

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 (159) hide show
  1. package/README.md +24 -27
  2. package/dist/_virtual/_rolldown/runtime.cjs +23 -0
  3. package/dist/clients/apiClient.cjs +38 -38
  4. package/dist/clients/apiClient.cjs.map +1 -1
  5. package/dist/clients/apiClient.d.cts +30 -0
  6. package/dist/clients/apiClient.d.cts.map +1 -0
  7. package/dist/clients/apiClient.d.ts +23 -23
  8. package/dist/clients/apiClient.d.ts.map +1 -0
  9. package/dist/clients/apiClient.js +38 -38
  10. package/dist/clients/apiClient.js.map +1 -1
  11. package/dist/clients/assetApi.cjs +81 -93
  12. package/dist/clients/assetApi.cjs.map +1 -1
  13. package/dist/clients/assetApi.d.cts +105 -0
  14. package/dist/clients/assetApi.d.cts.map +1 -0
  15. package/dist/clients/assetApi.d.ts +96 -97
  16. package/dist/clients/assetApi.d.ts.map +1 -0
  17. package/dist/clients/assetApi.js +79 -91
  18. package/dist/clients/assetApi.js.map +1 -1
  19. package/dist/clients/authenticationApi.cjs +66 -73
  20. package/dist/clients/authenticationApi.cjs.map +1 -1
  21. package/dist/clients/authenticationApi.d.cts +20 -0
  22. package/dist/clients/authenticationApi.d.cts.map +1 -0
  23. package/dist/clients/authenticationApi.d.ts +18 -13
  24. package/dist/clients/authenticationApi.d.ts.map +1 -0
  25. package/dist/clients/authenticationApi.js +65 -72
  26. package/dist/clients/authenticationApi.js.map +1 -1
  27. package/dist/clients/contentApi.cjs +94 -103
  28. package/dist/clients/contentApi.cjs.map +1 -1
  29. package/dist/clients/contentApi.d.cts +116 -0
  30. package/dist/clients/contentApi.d.cts.map +1 -0
  31. package/dist/clients/contentApi.d.ts +102 -98
  32. package/dist/clients/contentApi.d.ts.map +1 -0
  33. package/dist/clients/contentApi.js +94 -103
  34. package/dist/clients/contentApi.js.map +1 -1
  35. package/dist/clients/coreApi.cjs +154 -145
  36. package/dist/clients/coreApi.cjs.map +1 -1
  37. package/dist/clients/coreApi.d.cts +143 -0
  38. package/dist/clients/coreApi.d.cts.map +1 -0
  39. package/dist/clients/coreApi.d.ts +132 -109
  40. package/dist/clients/coreApi.d.ts.map +1 -0
  41. package/dist/clients/coreApi.js +153 -144
  42. package/dist/clients/coreApi.js.map +1 -1
  43. package/dist/clients/customTypesApi.cjs +90 -99
  44. package/dist/clients/customTypesApi.cjs.map +1 -1
  45. package/dist/clients/customTypesApi.d.cts +46 -0
  46. package/dist/clients/customTypesApi.d.cts.map +1 -0
  47. package/dist/clients/customTypesApi.d.ts +45 -45
  48. package/dist/clients/customTypesApi.d.ts.map +1 -0
  49. package/dist/clients/customTypesApi.js +87 -98
  50. package/dist/clients/customTypesApi.js.map +1 -1
  51. package/dist/clients/integrationFields.cjs +96 -87
  52. package/dist/clients/integrationFields.cjs.map +1 -1
  53. package/dist/clients/integrationFields.d.cts +30 -0
  54. package/dist/clients/integrationFields.d.cts.map +1 -0
  55. package/dist/clients/integrationFields.d.ts +27 -22
  56. package/dist/clients/integrationFields.d.ts.map +1 -0
  57. package/dist/clients/integrationFields.js +93 -86
  58. package/dist/clients/integrationFields.js.map +1 -1
  59. package/dist/clients/manageV2.cjs +154 -171
  60. package/dist/clients/manageV2.cjs.map +1 -1
  61. package/dist/clients/manageV2.d.cts +105 -0
  62. package/dist/clients/manageV2.d.cts.map +1 -0
  63. package/dist/clients/manageV2.d.ts +103 -111
  64. package/dist/clients/manageV2.d.ts.map +1 -0
  65. package/dist/clients/manageV2.js +149 -169
  66. package/dist/clients/manageV2.js.map +1 -1
  67. package/dist/clients/migrationApi.cjs +37 -36
  68. package/dist/clients/migrationApi.cjs.map +1 -1
  69. package/dist/clients/migrationApi.d.cts +48 -0
  70. package/dist/clients/migrationApi.d.cts.map +1 -0
  71. package/dist/clients/migrationApi.d.ts +45 -39
  72. package/dist/clients/migrationApi.d.ts.map +1 -0
  73. package/dist/clients/migrationApi.js +35 -34
  74. package/dist/clients/migrationApi.js.map +1 -1
  75. package/dist/clients/wroom.cjs +101 -122
  76. package/dist/clients/wroom.cjs.map +1 -1
  77. package/dist/clients/wroom.d.cts +48 -0
  78. package/dist/clients/wroom.d.cts.map +1 -0
  79. package/dist/clients/wroom.d.ts +46 -47
  80. package/dist/clients/wroom.d.ts.map +1 -0
  81. package/dist/clients/wroom.js +99 -122
  82. package/dist/clients/wroom.js.map +1 -1
  83. package/dist/index.cjs +13 -15
  84. package/dist/index.d.cts +8 -0
  85. package/dist/index.d.ts +8 -7
  86. package/dist/index.js +5 -14
  87. package/dist/managers/repositories.cjs +159 -169
  88. package/dist/managers/repositories.cjs.map +1 -1
  89. package/dist/managers/repositories.d.cts +67 -0
  90. package/dist/managers/repositories.d.cts.map +1 -0
  91. package/dist/managers/repositories.d.ts +56 -63
  92. package/dist/managers/repositories.d.ts.map +1 -0
  93. package/dist/managers/repositories.js +148 -159
  94. package/dist/managers/repositories.js.map +1 -1
  95. package/dist/managers/repository.cjs +595 -616
  96. package/dist/managers/repository.cjs.map +1 -1
  97. package/dist/managers/repository.d.cts +341 -0
  98. package/dist/managers/repository.d.cts.map +1 -0
  99. package/dist/managers/repository.d.ts +336 -307
  100. package/dist/managers/repository.d.ts.map +1 -0
  101. package/dist/managers/repository.js +595 -616
  102. package/dist/managers/repository.js.map +1 -1
  103. package/dist/types.d.cts +41 -0
  104. package/dist/types.d.cts.map +1 -0
  105. package/dist/types.d.ts +35 -37
  106. package/dist/types.d.ts.map +1 -0
  107. package/dist/utils/cookies.cjs +19 -17
  108. package/dist/utils/cookies.cjs.map +1 -1
  109. package/dist/utils/cookies.js +20 -18
  110. package/dist/utils/cookies.js.map +1 -1
  111. package/dist/utils/envVariableManager.cjs +33 -34
  112. package/dist/utils/envVariableManager.cjs.map +1 -1
  113. package/dist/utils/envVariableManager.js +34 -35
  114. package/dist/utils/envVariableManager.js.map +1 -1
  115. package/dist/utils/log.cjs +18 -19
  116. package/dist/utils/log.cjs.map +1 -1
  117. package/dist/utils/log.js +18 -21
  118. package/dist/utils/log.js.map +1 -1
  119. package/dist/utils/random.cjs +13 -6
  120. package/dist/utils/random.cjs.map +1 -1
  121. package/dist/utils/random.js +13 -6
  122. package/dist/utils/random.js.map +1 -1
  123. package/dist/utils/strings.cjs +13 -7
  124. package/dist/utils/strings.cjs.map +1 -1
  125. package/dist/utils/strings.js +14 -8
  126. package/dist/utils/strings.js.map +1 -1
  127. package/dist/utils/urls.cjs +21 -10
  128. package/dist/utils/urls.cjs.map +1 -1
  129. package/dist/utils/urls.js +22 -12
  130. package/dist/utils/urls.js.map +1 -1
  131. package/package.json +42 -67
  132. package/src/clients/apiClient.ts +16 -21
  133. package/src/clients/assetApi.ts +75 -82
  134. package/src/clients/authenticationApi.ts +54 -27
  135. package/src/clients/contentApi.ts +111 -129
  136. package/src/clients/coreApi.ts +166 -117
  137. package/src/clients/customTypesApi.ts +54 -74
  138. package/src/clients/integrationFields.ts +59 -74
  139. package/src/clients/manageV2.ts +72 -96
  140. package/src/clients/migrationApi.ts +35 -39
  141. package/src/clients/wroom.ts +42 -56
  142. package/src/index.ts +7 -7
  143. package/src/managers/repositories.ts +85 -108
  144. package/src/managers/repository.ts +410 -378
  145. package/src/types.ts +31 -31
  146. package/src/utils/cookies.ts +8 -8
  147. package/src/utils/envVariableManager.ts +15 -15
  148. package/src/utils/log.ts +17 -21
  149. package/src/utils/random.ts +5 -6
  150. package/src/utils/strings.ts +7 -9
  151. package/src/utils/urls.ts +10 -12
  152. package/dist/index.cjs.map +0 -1
  153. package/dist/index.js.map +0 -1
  154. package/dist/utils/cookies.d.ts +0 -8
  155. package/dist/utils/envVariableManager.d.ts +0 -16
  156. package/dist/utils/log.d.ts +0 -5
  157. package/dist/utils/random.d.ts +0 -8
  158. package/dist/utils/strings.d.ts +0 -11
  159. package/dist/utils/urls.d.ts +0 -16
@@ -1,618 +1,597 @@
1
- var __defProp = Object.defineProperty;
2
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
- var __publicField = (obj, key, value) => {
4
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
- return value;
6
- };
7
- import { expect } from "@playwright/test";
8
- import { ContentApiClient } from "../clients/contentApi.js";
9
- import { logger, logHttpResponse } from "../utils/log.js";
1
+ import { logHttpResponse, logger } from "../utils/log.js";
10
2
  import { getRepositoryUrl } from "../utils/urls.js";
11
- class RepositoryManager {
12
- constructor(name, coreApiClient, authApiClient, wroomClient, customTypesApiClient, migrationApiClient, assetApiClient, manageV2Client, integrationFieldsClient) {
13
- __publicField(this, "name");
14
- __publicField(this, "coreApiClient");
15
- __publicField(this, "authApiClient");
16
- __publicField(this, "wroomClient");
17
- __publicField(this, "customTypesApiClient");
18
- __publicField(this, "migrationApiClient");
19
- __publicField(this, "assetApiClient");
20
- __publicField(this, "manageV2Client");
21
- __publicField(this, "integrationFieldsClient");
22
- this.name = name;
23
- this.coreApiClient = coreApiClient;
24
- this.authApiClient = authApiClient;
25
- this.wroomClient = wroomClient;
26
- this.customTypesApiClient = customTypesApiClient;
27
- this.migrationApiClient = migrationApiClient;
28
- this.assetApiClient = assetApiClient;
29
- this.manageV2Client = manageV2Client;
30
- this.integrationFieldsClient = integrationFieldsClient;
31
- }
32
- async configure(config) {
33
- const hasLangConfig = config.defaultLocale || config.locales || config.customLocale;
34
- if (hasLangConfig) {
35
- const languages = await this.coreApiClient.getLanguages();
36
- let updateDefaultLocaleAtTheEnd = false;
37
- if (config.defaultLocale) {
38
- const master = languages.find(({ is_master }) => is_master === true);
39
- if (!master) {
40
- await this.setDefaultLocale(config.defaultLocale, "create");
41
- } else if (master.id !== config.defaultLocale) {
42
- updateDefaultLocaleAtTheEnd = true;
43
- }
44
- }
45
- if (config.locales) {
46
- const localesToAdd = config.locales.filter((id) => !languages.some((language) => language.id === id));
47
- if (localesToAdd.length > 0) {
48
- await this.createLocales(localesToAdd);
49
- }
50
- }
51
- if (config.customLocale) {
52
- if (!languages.find(({ id }) => {
53
- var _a;
54
- return id === ((_a = config.customLocale) == null ? void 0 : _a.lang.id);
55
- })) {
56
- await this.createCustomLocale(config.customLocale);
57
- }
58
- }
59
- if (config.defaultLocale && updateDefaultLocaleAtTheEnd) {
60
- await this.setDefaultLocale(config.defaultLocale, "update");
61
- }
62
- }
63
- if (config.slices) {
64
- await this.createSlices(config.slices);
65
- }
66
- if (config.customTypes) {
67
- await this.createCustomTypes(config.customTypes);
68
- }
69
- if (config.preview) {
70
- await this.createPreview(config.preview);
71
- }
72
- if (config.simulatorURL) {
73
- await this.setSimulatorURL(config.simulatorURL);
74
- }
75
- if (config.rolePerLocal) {
76
- await this.toggleRolePerLocal(true);
77
- }
78
- if (config.customRoles) {
79
- await this.toggleCustomRoles(true);
80
- }
81
- if (config.integrationFields) {
82
- await this.toggleIntegrationFields(true);
83
- await this.setupIntegrationFields(config.integrationFields);
84
- }
85
- }
86
- /** @returns the repository base url, like https://my-repo.prismic.io */
87
- getBaseURL() {
88
- return getRepositoryUrl(this.wroomClient.getBaseURL(), this.name);
89
- }
90
- /** @returns the repository base cdn url, like https://my-repo.cdn.prismic.io */
91
- getBaseCdnURL() {
92
- return getRepositoryUrl(this.wroomClient.getBaseURL(), `${this.name}.cdn`);
93
- }
94
- /**
95
- * @returns a Content Type api client configured to target the repository CDN
96
- * url. Uses Playwright for requests so if your project uses Playwright too,
97
- * any network request will be present in Playwright test reports.
98
- */
99
- getContentApiClient(config) {
100
- return new ContentApiClient(this.getBaseCdnURL(), config);
101
- }
102
- /**
103
- * @returns an instance of the Migration api client, see
104
- * https://prismic.io/docs/migration-api-technical-reference
105
- */
106
- getMigrationApiClient() {
107
- if (!this.migrationApiClient) {
108
- throw "No client found for the migration api. Did you provide a migration api url in the configuration?";
109
- }
110
- return this.migrationApiClient;
111
- }
112
- /**
113
- * @returns an instance of the Asset api client, see
114
- * https://prismic.io/docs/asset-api-technical-reference
115
- */
116
- getAssetApiClient() {
117
- return this.assetApiClient;
118
- }
119
- /** @returns the Wroom commit hash deployed on the current repository */
120
- async getDeployedVersion() {
121
- const response = await this.wroomClient.get(this.name, "underground/834b34f16f451e00f268dd5c8c81d16e3c020275");
122
- return response.data.version;
123
- }
124
- /**
125
- * Set additional standard locales for a repository in Wroom, does not fail if
126
- * the locales already exist.
127
- *
128
- * @param locales - An array of all locales to be added to the repository.
129
- *
130
- * @throws Error if setting the locales fails.
131
- */
132
- async createLocales(locales) {
133
- const profiler = logger.startTimer();
134
- const response = await this.wroomClient.post(this.name, "app/settings/multilanguages", { languages: locales });
135
- const { data, status } = response;
136
- const success = status === 200 || status === 400 && data.includes("already existing languages");
137
- if (!success) {
138
- logHttpResponse(response);
139
- throw new Error(`Could not add locales ${locales.join(", ")}`);
140
- }
141
- profiler.done({ message: `locales '${locales}' created` });
142
- }
143
- /**
144
- * Set additional custom locale for a repository in Wroom, does not fail if
145
- * the locales already exist.
146
- *
147
- * @param locale - The locale to be added to the repository.
148
- *
149
- * @throws Error if setting the locale fails.
150
- */
151
- async createCustomLocale(locale) {
152
- const profiler = logger.startTimer();
153
- const response = await this.wroomClient.post(this.name, "app/settings/multilanguages/custom", locale);
154
- const { data, status } = response;
155
- const success = status === 200 || status === 400 && JSON.stringify(data).includes("code is already used");
156
- if (!success) {
157
- logHttpResponse(response);
158
- throw new Error(`Could not create custom locale ${locale}`);
159
- }
160
- profiler.done({
161
- message: `custom locale ${JSON.stringify(locale)} created`
162
- });
163
- }
164
- failIfNot200(response, msg) {
165
- if (response.status !== 200) {
166
- logHttpResponse(response);
167
- throw new Error(msg);
168
- }
169
- }
170
- /**
171
- * Delete a locale from a repository.
172
- *
173
- * @param locale - locale to remove from the repository configuration.
174
- *
175
- * @throws Error if deleting the locale fails.
176
- */
177
- async deleteLocale(locale) {
178
- const profiler = logger.startTimer();
179
- const response = await this.wroomClient.post(this.name, `app/settings/multilanguages/${locale}/delete`);
180
- this.failIfNot200(response, `Could not delete locale ${locale}`);
181
- profiler.done({ message: `locale '${locale}' deleted` });
182
- }
183
- /**
184
- * Create or update the default (master) locale for a repository in Wroom, the
185
- * locale needs to exist in the repository.
186
- *
187
- * @param locale - The locale to be set as the default.
188
- * @param endpoint - "createMasterLang" to create it, "defineAsMaster" to
189
- * update it.
190
- *
191
- * @throws Error if setting the default locale fails.
192
- */
193
- async setDefaultLocale(locale, action) {
194
- const profiler = logger.startTimer();
195
- const endpoint = {
196
- create: "createMasterLang",
197
- update: "defineAsMaster"
198
- };
199
- const response = await this.wroomClient.post(this.name, `/app/settings/multilanguages/${locale}/${endpoint[action]}`);
200
- const { data, status } = response;
201
- const success = status === 200 || status === 400 && // returns 400 if master lang is already set
202
- JSON.stringify(data).includes("Unable to set as master language");
203
- if (!success) {
204
- logHttpResponse(response);
205
- throw new Error(`Could not set default locale to ${locale}`);
206
- }
207
- profiler.done({ message: `default locale set to '${locale}'` });
208
- }
209
- /**
210
- * Retrieves documents.
211
- *
212
- * @param args - Configure which documents are retrieved.
213
- *
214
- * @returns A paginated set of documents.
215
- */
216
- async getDocuments(args) {
217
- return this.coreApiClient.getDocuments(args);
218
- }
219
- /**
220
- * Creates a release.
221
- *
222
- * @param label - The label for the release.
223
- *
224
- * @returns A Promise that resolves when the release is created.
225
- */
226
- async createRelease(label) {
227
- const profiler = logger.startTimer();
228
- const response = await this.wroomClient.post(this.name, "app/releases", {
229
- label
230
- });
231
- this.failIfNot200(response, `Could not create release ${label}`);
232
- profiler.done({ message: `release '${label}' created` });
233
- return response.data;
234
- }
235
- /**
236
- * Retrieves the migration release.
237
- *
238
- * @returns The migration relese metadata.
239
- */
240
- async getMigrationRelease() {
241
- const releases = await this.coreApiClient.getReleases();
242
- const migrationRelease = releases.find((release) => release.migration);
243
- if (!migrationRelease) {
244
- throw new Error(`The repository does not have a migration release`);
245
- }
246
- return migrationRelease;
247
- }
248
- /**
249
- * Publishes a release.
250
- *
251
- * @param id - The ID of the release.
252
- *
253
- * @returns A Promise that resolves when the release is published and a new
254
- * master ref is available.
255
- */
256
- async publishRelease(id) {
257
- const profiler = logger.startTimer();
258
- const contentApi = this.getContentApiClient();
259
- const masterRef = await contentApi.getMasterRef();
260
- await this.coreApiClient.publishRelease(id);
261
- await expect.poll(async () => contentApi.getMasterRef(), {
262
- timeout: 1e4,
263
- message: "Waiting for new master ref to be available"
264
- }).not.toBe(masterRef);
265
- profiler.done({
266
- message: `release '${id}' published and new master ref available`
267
- });
268
- }
269
- /**
270
- * Deletes a repository release.
271
- *
272
- * @param id - The ID of the release to be deleted.
273
- */
274
- async deleteRelease(id) {
275
- const profiler = logger.startTimer();
276
- const response = await this.wroomClient.post(this.name, `app/releases/${id}/delete`, {});
277
- this.failIfNot200(response, `Could not delete release with id ${id}`);
278
- profiler.done({ message: `release '${id}' deleted` });
279
- }
280
- /**
281
- * Creates a preview for a repository.
282
- *
283
- * @param data - The data for creating the preview.
284
- */
285
- async createPreview(data) {
286
- const profiler = logger.startTimer();
287
- const response = await this.wroomClient.post(this.name, `previews/new`, data);
288
- this.failIfNot200(response, `Could not create preview ${data.name}`);
289
- profiler.done({ message: `preview '${data.name}' created` });
290
- return response.data;
291
- }
292
- /**
293
- * Set the simulator URL (table of slices) for a repository.
294
- *
295
- * @param data - The simulator URL to set.
296
- */
297
- async setSimulatorURL(simulatorURL) {
298
- const profiler = logger.startTimer();
299
- const repository = await this.coreApiClient.getRepository();
300
- await this.coreApiClient.updateRepository({
301
- ...repository,
302
- simulator_url: simulatorURL
303
- });
304
- profiler.done({
305
- message: `simulator preview '${simulatorURL}' created`
306
- });
307
- }
308
- /**
309
- * Deletes a preview from a repository.
310
- *
311
- * @param id - The ID of the preview to be deleted.
312
- */
313
- async deletePreview(id) {
314
- const profiler = logger.startTimer();
315
- const response = await this.wroomClient.post(this.name, `previews/delete/${id}`, {});
316
- this.failIfNot200(response, `Could not delete preview with id ${id}`);
317
- profiler.done({ message: `preview '${id}' deleted` });
318
- }
319
- /**
320
- * Create a webhook.
321
- *
322
- * @returns A Promise that resolves with the webhook id.
323
- */
324
- async createWebhook(name, url, secret, triggers, active) {
325
- const profiler = logger.startTimer();
326
- const response = await this.wroomClient.post(this.name, "app/settings/webhooks/create", {
327
- name,
328
- url,
329
- secret,
330
- active: active ? "on" : "off",
331
- ...triggers
332
- });
333
- this.failIfNot200(response, `Could not create webhook ${name}`);
334
- profiler.done({ message: `webhook '${name}' created` });
335
- return response.data.created;
336
- }
337
- /**
338
- * Deletes a webhook.
339
- *
340
- * @param id - The webhook ID.
341
- */
342
- async deleteWebhook(id) {
343
- const profiler = logger.startTimer();
344
- const response = await this.wroomClient.post(this.name, `app/settings/webhooks/${id}/delete`, {});
345
- this.failIfNot200(response, `Could not delete webhook with id ${id}`);
346
- profiler.done({ message: `webhook '${id}' deleted` });
347
- }
348
- /**
349
- * Create Custom Types using the Custom types api.
350
- *
351
- * @param customTypes -
352
- */
353
- async createCustomTypes(customTypes) {
354
- await this.customTypesApiClient.createCustomTypes(customTypes);
355
- }
356
- async deleteCustomType(customTypeId) {
357
- await this.customTypesApiClient.deleteCustomType(customTypeId);
358
- }
359
- /**
360
- * Create slices using the Custom types api.
361
- *
362
- * @param slices -
363
- */
364
- async createSlices(slices) {
365
- await this.customTypesApiClient.createSlices(slices);
366
- }
367
- /**
368
- * Create an access token to query private items of the Content api.
369
- *
370
- * @param appName - mandatory authorized application name
371
- * @param tokenScope - access token scope. Use "master" to when your content
372
- * api is fully private or "master+releases" to access private releases
373
- */
374
- async createContentAPIToken(appName, tokenScope = "master") {
375
- const profiler = logger.startTimer();
376
- const existingApps = await this.wroomClient.get(this.name, "settings/security/contentapi");
377
- this.failIfNot200(existingApps, `Could not get status of existing applications to generate a content api token`);
378
- let app = existingApps.data.find(({ name, wroom_auths }) => {
379
- return name === appName && wroom_auths.length > 0;
380
- });
381
- if (!app) {
382
- const response = await this.wroomClient.post(this.name, "settings/security/oauthapp", {
383
- app_name: appName
384
- });
385
- this.failIfNot200(response, `Could not create content api app ${appName}`);
386
- app = response.data;
387
- }
388
- let tokenInfo = app.wroom_auths.find(({ scope }) => scope === tokenScope);
389
- if (!tokenInfo) {
390
- const response = await this.wroomClient.post(this.name, "settings/security/authorizations", {
391
- app: app.id,
392
- scope: tokenScope
393
- });
394
- this.failIfNot200(response, `Could not create content api access token for app ${appName} with scope ${tokenScope}`);
395
- tokenInfo = response.data;
396
- }
397
- profiler.done({
398
- message: `content api access token for app '${appName}' created`
399
- });
400
- if (!(tokenInfo == null ? void 0 : tokenInfo.token)) {
401
- throw `Could not create content api access token for app ${appName} with scope ${tokenScope}`;
402
- }
403
- return tokenInfo.token;
404
- }
405
- /** Create a permanent access token to authenticate to Prismic public apis. */
406
- async createPermanentAccessToken() {
407
- const profiler = logger.startTimer();
408
- const token = await this.authApiClient.getMachine2MachineToken(this.name);
409
- profiler.done({
410
- message: `machine2machine token created`
411
- });
412
- return token;
413
- }
414
- /**
415
- * Toggle the Role per Locale workflow
416
- *
417
- * @param enabled - The feature new status
418
- */
419
- async toggleRolePerLocal(enabled) {
420
- const profiler = logger.startTimer();
421
- const response = await this.manageV2Client.toggleRolePerLocal({
422
- repository: this.name,
423
- enabled
424
- });
425
- this.failIfNot200(response, `Could not ${enabled ? "enable" : "disable"} Role per local for ${this.name}`);
426
- profiler.done({
427
- message: `Role per local ${enabled ? "enabled" : "disabled"}`
428
- });
429
- }
430
- /**
431
- * Toggle the Custom Roles workflow
432
- *
433
- * @param enabled - The feature new status
434
- */
435
- async toggleCustomRoles(enabled) {
436
- const profiler = logger.startTimer();
437
- const response = await this.manageV2Client.toggleCustomRoles({
438
- repository: this.name,
439
- enabled
440
- });
441
- this.failIfNot200(response, `Could not ${enabled ? "enable" : "disable"} Custom Roles for ${this.name}`);
442
- profiler.done({
443
- message: `Custom Roles ${enabled ? "enabled" : "disabled"}`
444
- });
445
- }
446
- /**
447
- * Toggle the Integration Fields feature
448
- *
449
- * @param enabled - The feature new status
450
- */
451
- async toggleIntegrationFields(enabled) {
452
- const profiler = logger.startTimer();
453
- const response = await this.manageV2Client.toggleIntegrationFields({
454
- repository: this.name,
455
- enabled
456
- });
457
- this.failIfNot200(response, `Could not ${enabled ? "enable" : "disable"} Integration Fields for ${this.name}`);
458
- profiler.done({
459
- message: `Integration Fields ${enabled ? "enabled" : "disabled"}`
460
- });
461
- }
462
- /**
463
- * Change the Repository Plan
464
- *
465
- * @param {string} newPlanId - The Id of the new Plan to apply
466
- */
467
- async changePlan(newPlanId) {
468
- const profiler = logger.startTimer();
469
- const response = await this.manageV2Client.changePlan({
470
- repository: this.name,
471
- newPlanId,
472
- bypassManualBilling: true
473
- // For now the library does not support Stripe features
474
- });
475
- this.failIfNot200(response, "Could not change the Repository Plan");
476
- profiler.done({
477
- message: `Repository Plan changed to ${newPlanId}`
478
- });
479
- }
480
- /**
481
- * Add a new user to the repository
482
- *
483
- * @param {string} email - The email of the user
484
- */
485
- async addUser(email) {
486
- const profiler = logger.startTimer();
487
- const response = await this.manageV2Client.addUserToRepository({
488
- repository: this.name,
489
- email
490
- });
491
- const { data, status } = response;
492
- const success = status === 200 || status === 409 && JSON.stringify(data).includes("already a member of the repo");
493
- if (!success) {
494
- logHttpResponse(response);
495
- throw new Error(`Could not add a new user ${email} to the repository`);
496
- }
497
- profiler.done({
498
- message: `User ${email} was added to the repository`
499
- });
500
- }
501
- /**
502
- * Remove a user from the repository
503
- *
504
- * @param {string} email - The email of the user
505
- */
506
- async removeUser(email) {
507
- const profiler = logger.startTimer();
508
- const response = await this.manageV2Client.removeUserFromRepository({
509
- repository: this.name,
510
- email
511
- });
512
- this.failIfNot200(response, `Could not remove the user ${email} from the repository`);
513
- profiler.done({
514
- message: `User ${email} was removed from the repository`
515
- });
516
- }
517
- /**
518
- * Update the role of a user in a repository
519
- *
520
- * @param {string} email - The email of the user
521
- * @param {string | Record<string, string>} role - The new Role of the user,
522
- * either a string for basic workflow or an object such as `{ "lang_id":
523
- * "Writer" }`
524
- *
525
- * Example of roles are
526
- *
527
- * - Administrator
528
- * - Writer
529
- * - Contributor
530
- * - Manager (publisher)
531
- */
532
- async updateUserRole(email, role) {
533
- const profiler = logger.startTimer();
534
- const response = typeof role === "string" ? await this.wroomClient.updateRole(this.name, email, role) : await this.wroomClient.updateRolePerLocal(this.name, email, role);
535
- this.failIfNot200(response, `Could not update the ${typeof role === "string" ? "role" : "rolePerLocal"} of the user ${email}`);
536
- profiler.done({
537
- message: `Updated User's ${typeof role === "string" ? "role" : "rolePerLocal"} for user ${email}`
538
- });
539
- }
540
- /**
541
- * Creates a document using the core api. If the Core api format is too
542
- * specific, use the migration api client to create a document with the
543
- * MigrationApiClient. See the `getMigrationApiClient()` method.
544
- *
545
- * @example To create a document by converting it from the Page Builder to
546
- * Core api format
547
- *
548
- * ```js
549
- * import { DocumentLegacy, UIDContentType } from '@prismicio/types-internal/lib/content';
550
- *
551
- * const document = {
552
- * title: 'A new document',
553
- * custom_type_id: 'home-page',
554
- * locale: 'en-gb',
555
- * integration_field_ids: [],
556
- * tags: [],
557
- * data: DocumentLegacy.encode({
558
- * uid: {
559
- * __TYPE__: UIDContentType,
560
- * value: 'home-page',
561
- * },
562
- * })
563
- * }
564
- * await repository.createDocument(document, 'published');
565
- * * ```
566
- * ```
567
- *
568
- * @returns
569
- *
570
- * @param document - in the core api format.
571
- *
572
- * @param status - status of the document, if published, the function will
573
- * wait for a new content api master ref to be created
574
- */
575
- async createDocument(document, status) {
576
- const profiler = logger.startTimer();
577
- const result = await this.coreApiClient.createDraft(document);
578
- let message = `Document created with id '${result.id}'`;
579
- if (status === "published") {
580
- const contentApi = this.getContentApiClient();
581
- const masterRef = await contentApi.getMasterRef();
582
- await this.coreApiClient.publishDraft(result.id);
583
- await expect.poll(async () => contentApi.getMasterRef(), {
584
- timeout: 1e4,
585
- message: "Waiting for new master ref to be available"
586
- }).not.toBe(masterRef);
587
- message += ", status 'published' and new master ref available";
588
- }
589
- profiler.done({
590
- message
591
- });
592
- return result;
593
- }
594
- /**
595
- * Retrieves data for a specific document version.
596
- *
597
- * @param versionId - The document's version ID.
598
- *
599
- * @returns The document's version data.
600
- */
601
- async getDocumentData(versionId) {
602
- return await this.coreApiClient.getDocumentData(versionId);
603
- }
604
- async setupIntegrationFields(integrationFields) {
605
- const profiler = logger.startTimer();
606
- if (!this.integrationFieldsClient) {
607
- throw new Error("Integration Fields client not found. Did you provide a integration fields api url in the configuration?");
608
- }
609
- await this.integrationFieldsClient.setupIntegrationFields(integrationFields);
610
- profiler.done({
611
- message: `Integration Fields setup`
612
- });
613
- }
614
- }
615
- export {
616
- RepositoryManager
3
+ import { ContentApiClient } from "../clients/contentApi.js";
4
+ import { expect } from "@playwright/test";
5
+ //#region src/managers/repository.ts
6
+ /** Utility to manage test data for a Prismic repository */
7
+ var RepositoryManager = class {
8
+ name;
9
+ coreApiClient;
10
+ authApiClient;
11
+ wroomClient;
12
+ customTypesApiClient;
13
+ migrationApiClient;
14
+ assetApiClient;
15
+ manageV2Client;
16
+ integrationFieldsClient;
17
+ constructor(name, coreApiClient, authApiClient, wroomClient, customTypesApiClient, migrationApiClient, assetApiClient, manageV2Client, integrationFieldsClient) {
18
+ this.name = name;
19
+ this.coreApiClient = coreApiClient;
20
+ this.authApiClient = authApiClient;
21
+ this.wroomClient = wroomClient;
22
+ this.customTypesApiClient = customTypesApiClient;
23
+ this.migrationApiClient = migrationApiClient;
24
+ this.assetApiClient = assetApiClient;
25
+ this.manageV2Client = manageV2Client;
26
+ this.integrationFieldsClient = integrationFieldsClient;
27
+ }
28
+ async configure(config) {
29
+ if (config.defaultLocale || config.locales || config.customLocale) {
30
+ const languages = await this.coreApiClient.getLanguages();
31
+ let updateDefaultLocaleAtTheEnd = false;
32
+ if (config.defaultLocale) {
33
+ const master = languages.find(({ is_master }) => is_master === true);
34
+ if (!master) await this.setDefaultLocale(config.defaultLocale, "create");
35
+ else if (master.id !== config.defaultLocale) updateDefaultLocaleAtTheEnd = true;
36
+ }
37
+ if (config.locales) {
38
+ const localesToAdd = config.locales.filter((id) => !languages.some((language) => language.id === id));
39
+ if (localesToAdd.length > 0) await this.createLocales(localesToAdd);
40
+ }
41
+ if (config.customLocale) {
42
+ if (!languages.find(({ id }) => id === config.customLocale?.lang.id)) await this.createCustomLocale(config.customLocale);
43
+ }
44
+ if (config.defaultLocale && updateDefaultLocaleAtTheEnd) await this.setDefaultLocale(config.defaultLocale, "update");
45
+ }
46
+ if (config.slices) await this.createSlices(config.slices);
47
+ if (config.customTypes) await this.createCustomTypes(config.customTypes);
48
+ if (config.preview) await this.createPreview(config.preview);
49
+ if (config.simulatorURL) await this.setSimulatorURL(config.simulatorURL);
50
+ if (config.rolePerLocal) await this.toggleRolePerLocal(true);
51
+ if (config.customRoles) await this.toggleCustomRoles(true);
52
+ if (config.integrationFields) {
53
+ await this.toggleIntegrationFields(true);
54
+ await this.setupIntegrationFields(config.integrationFields);
55
+ }
56
+ }
57
+ /** @returns The repository base url, like https://my-repo.prismic.io */
58
+ getBaseURL() {
59
+ return getRepositoryUrl(this.wroomClient.getBaseURL(), this.name);
60
+ }
61
+ /** @returns The repository base cdn url, like https://my-repo.cdn.prismic.io */
62
+ getBaseCdnURL() {
63
+ return getRepositoryUrl(this.wroomClient.getBaseURL(), `${this.name}.cdn`);
64
+ }
65
+ /**
66
+ * @returns A Content Type api client configured to target the repository CDN url. Uses Playwright
67
+ * for requests so if your project uses Playwright too, any network request will be present in
68
+ * Playwright test reports.
69
+ */
70
+ getContentApiClient(config) {
71
+ return new ContentApiClient(this.getBaseCdnURL(), config);
72
+ }
73
+ /**
74
+ * @returns An instance of the Migration api client, see
75
+ * https://prismic.io/docs/migration-api-technical-reference
76
+ */
77
+ getMigrationApiClient() {
78
+ if (!this.migrationApiClient) throw "No client found for the migration api. Did you provide a migration api url in the configuration?";
79
+ return this.migrationApiClient;
80
+ }
81
+ /**
82
+ * @returns An instance of the Asset api client, see
83
+ * https://prismic.io/docs/asset-api-technical-reference
84
+ */
85
+ getAssetApiClient() {
86
+ return this.assetApiClient;
87
+ }
88
+ /** @returns The Wroom commit hash deployed on the current repository */
89
+ async getDeployedVersion() {
90
+ return (await this.wroomClient.get(this.name, "underground/834b34f16f451e00f268dd5c8c81d16e3c020275")).data.version;
91
+ }
92
+ /**
93
+ * Set additional standard locales for a repository in Wroom, does not fail if the locales already
94
+ * exist.
95
+ *
96
+ * @param locales - An array of all locales to be added to the repository.
97
+ * @throws Error if setting the locales fails.
98
+ */
99
+ async createLocales(locales) {
100
+ const profiler = logger.startTimer();
101
+ const response = await this.wroomClient.post(this.name, "app/settings/multilanguages", { languages: locales });
102
+ const { data, status } = response;
103
+ if (!(status === 200 || status === 400 && data.includes("already existing languages"))) {
104
+ logHttpResponse(response);
105
+ throw new Error(`Could not add locales ${locales.join(", ")}`);
106
+ }
107
+ profiler.done({ message: `locales '${locales}' created` });
108
+ }
109
+ /**
110
+ * Set additional custom locale for a repository in Wroom, does not fail if the locales already
111
+ * exist.
112
+ *
113
+ * @param locale - The locale to be added to the repository.
114
+ * @throws Error if setting the locale fails.
115
+ */
116
+ async createCustomLocale(locale) {
117
+ const profiler = logger.startTimer();
118
+ const response = await this.wroomClient.post(this.name, "app/settings/multilanguages/custom", locale);
119
+ const { data, status } = response;
120
+ if (!(status === 200 || status === 400 && JSON.stringify(data).includes("code is already used"))) {
121
+ logHttpResponse(response);
122
+ throw new Error(`Could not create custom locale ${locale}`);
123
+ }
124
+ profiler.done({ message: `custom locale ${JSON.stringify(locale)} created` });
125
+ }
126
+ failIfNot200(response, msg) {
127
+ if (response.status !== 200) {
128
+ logHttpResponse(response);
129
+ throw new Error(msg);
130
+ }
131
+ }
132
+ /**
133
+ * Delete a locale from a repository.
134
+ *
135
+ * @param locale - Locale to remove from the repository configuration.
136
+ * @throws Error if deleting the locale fails.
137
+ */
138
+ async deleteLocale(locale) {
139
+ const profiler = logger.startTimer();
140
+ const response = await this.wroomClient.post(this.name, `app/settings/multilanguages/${locale}/delete`);
141
+ this.failIfNot200(response, `Could not delete locale ${locale}`);
142
+ profiler.done({ message: `locale '${locale}' deleted` });
143
+ }
144
+ /**
145
+ * Create or update the default (master) locale for a repository in Wroom, the locale needs to
146
+ * exist in the repository.
147
+ *
148
+ * @param locale - The locale to be set as the default.
149
+ * @param endpoint - "createMasterLang" to create it, "defineAsMaster" to update it.
150
+ * @throws Error if setting the default locale fails.
151
+ */
152
+ async setDefaultLocale(locale, action) {
153
+ const profiler = logger.startTimer();
154
+ const response = await this.wroomClient.post(this.name, `/app/settings/multilanguages/${locale}/${{
155
+ create: "createMasterLang",
156
+ update: "defineAsMaster"
157
+ }[action]}`);
158
+ const { data, status } = response;
159
+ if (!(status === 200 || status === 400 && JSON.stringify(data).includes("Unable to set as master language"))) {
160
+ logHttpResponse(response);
161
+ throw new Error(`Could not set default locale to ${locale}`);
162
+ }
163
+ profiler.done({ message: `default locale set to '${locale}'` });
164
+ }
165
+ /**
166
+ * Retrieves documents.
167
+ *
168
+ * @param args - Configure which documents are retrieved.
169
+ * @returns A paginated set of documents.
170
+ */
171
+ async getDocuments(args) {
172
+ return this.coreApiClient.getDocuments(args);
173
+ }
174
+ /**
175
+ * Creates a release.
176
+ *
177
+ * @param label - The label for the release.
178
+ * @returns A Promise that resolves when the release is created.
179
+ */
180
+ async createRelease(label) {
181
+ const profiler = logger.startTimer();
182
+ const response = await this.wroomClient.post(this.name, "app/releases", { label });
183
+ this.failIfNot200(response, `Could not create release ${label}`);
184
+ profiler.done({ message: `release '${label}' created` });
185
+ return response.data;
186
+ }
187
+ /**
188
+ * Retrieves the migration release.
189
+ *
190
+ * @returns The migration relese metadata.
191
+ */
192
+ async getMigrationRelease() {
193
+ const migrationRelease = (await this.coreApiClient.getReleases()).find((release) => release.migration);
194
+ if (!migrationRelease) throw new Error(`The repository does not have a migration release`);
195
+ return migrationRelease;
196
+ }
197
+ /**
198
+ * Publishes a release.
199
+ *
200
+ * @param id - The ID of the release.
201
+ * @returns A Promise that resolves when the release is published and a new master ref is
202
+ * available.
203
+ */
204
+ async publishRelease(id) {
205
+ const profiler = logger.startTimer();
206
+ const contentApi = this.getContentApiClient();
207
+ const masterRef = await contentApi.getMasterRef();
208
+ await this.coreApiClient.publishRelease(id);
209
+ await this.waitForNewMasterRef(contentApi, masterRef);
210
+ profiler.done({ message: `release '${id}' published and new master ref available` });
211
+ }
212
+ /**
213
+ * Deletes a repository release.
214
+ *
215
+ * @param id - The ID of the release to be deleted.
216
+ */
217
+ async deleteRelease(id) {
218
+ const profiler = logger.startTimer();
219
+ const response = await this.wroomClient.post(this.name, `app/releases/${id}/delete`, {});
220
+ this.failIfNot200(response, `Could not delete release with id ${id}`);
221
+ profiler.done({ message: `release '${id}' deleted` });
222
+ }
223
+ /**
224
+ * Creates a preview for a repository.
225
+ *
226
+ * @param data - The data for creating the preview.
227
+ */
228
+ async createPreview(data) {
229
+ const profiler = logger.startTimer();
230
+ const response = await this.wroomClient.post(this.name, `previews/new`, data);
231
+ this.failIfNot200(response, `Could not create preview ${data.name}`);
232
+ profiler.done({ message: `preview '${data.name}' created` });
233
+ return response.data;
234
+ }
235
+ /**
236
+ * Set the simulator URL (table of slices) for a repository.
237
+ *
238
+ * @param data - The simulator URL to set.
239
+ */
240
+ async setSimulatorURL(simulatorURL) {
241
+ const profiler = logger.startTimer();
242
+ const repository = await this.coreApiClient.getRepository();
243
+ await this.coreApiClient.updateRepository({
244
+ ...repository,
245
+ simulator_url: simulatorURL
246
+ });
247
+ profiler.done({ message: `simulator preview '${simulatorURL}' created` });
248
+ }
249
+ /**
250
+ * Deletes a preview from a repository.
251
+ *
252
+ * @param id - The ID of the preview to be deleted.
253
+ */
254
+ async deletePreview(id) {
255
+ const profiler = logger.startTimer();
256
+ const response = await this.wroomClient.post(this.name, `previews/delete/${id}`, {});
257
+ this.failIfNot200(response, `Could not delete preview with id ${id}`);
258
+ profiler.done({ message: `preview '${id}' deleted` });
259
+ }
260
+ /**
261
+ * Create a webhook.
262
+ *
263
+ * @returns A Promise that resolves with the webhook id.
264
+ */
265
+ async createWebhook(name, url, secret, triggers, active) {
266
+ const profiler = logger.startTimer();
267
+ const response = await this.wroomClient.post(this.name, "app/settings/webhooks/create", {
268
+ name,
269
+ url,
270
+ secret,
271
+ active: active ? "on" : "off",
272
+ ...triggers
273
+ });
274
+ this.failIfNot200(response, `Could not create webhook ${name}`);
275
+ profiler.done({ message: `webhook '${name}' created` });
276
+ return response.data.created;
277
+ }
278
+ /**
279
+ * Deletes a webhook.
280
+ *
281
+ * @param id - The webhook ID.
282
+ */
283
+ async deleteWebhook(id) {
284
+ const profiler = logger.startTimer();
285
+ const response = await this.wroomClient.post(this.name, `app/settings/webhooks/${id}/delete`, {});
286
+ this.failIfNot200(response, `Could not delete webhook with id ${id}`);
287
+ profiler.done({ message: `webhook '${id}' deleted` });
288
+ }
289
+ /**
290
+ * Create Custom Types using the Custom types api.
291
+ *
292
+ * @param customTypes
293
+ */
294
+ async createCustomTypes(customTypes) {
295
+ await this.customTypesApiClient.createCustomTypes(customTypes);
296
+ }
297
+ async deleteCustomType(customTypeId) {
298
+ await this.customTypesApiClient.deleteCustomType(customTypeId);
299
+ }
300
+ /**
301
+ * Create slices using the Custom types api.
302
+ *
303
+ * @param slices
304
+ */
305
+ async createSlices(slices) {
306
+ await this.customTypesApiClient.createSlices(slices);
307
+ }
308
+ /**
309
+ * Create an access token to query private items of the Content api.
310
+ *
311
+ * @param appName - Mandatory authorized application name
312
+ * @param tokenScope - Access token scope. Use "master" to when your content api is fully private
313
+ * or "master+releases" to access private releases
314
+ */
315
+ async createContentAPIToken(appName, tokenScope = "master") {
316
+ const profiler = logger.startTimer();
317
+ const existingApps = await this.wroomClient.get(this.name, "settings/security/contentapi");
318
+ this.failIfNot200(existingApps, `Could not get status of existing applications to generate a content api token`);
319
+ let app = existingApps.data.find(({ name, wroom_auths }) => {
320
+ return name === appName && wroom_auths.length > 0;
321
+ });
322
+ if (!app) {
323
+ const response = await this.wroomClient.post(this.name, "settings/security/oauthapp", { app_name: appName });
324
+ this.failIfNot200(response, `Could not create content api app ${appName}`);
325
+ app = response.data;
326
+ }
327
+ let tokenInfo = app.wroom_auths.find(({ scope }) => scope === tokenScope);
328
+ if (!tokenInfo) {
329
+ const response = await this.wroomClient.post(this.name, "settings/security/authorizations", {
330
+ app: app.id,
331
+ scope: tokenScope
332
+ });
333
+ this.failIfNot200(response, `Could not create content api access token for app ${appName} with scope ${tokenScope}`);
334
+ tokenInfo = response.data;
335
+ }
336
+ profiler.done({ message: `content api access token for app '${appName}' created` });
337
+ if (!tokenInfo?.token) throw `Could not create content api access token for app ${appName} with scope ${tokenScope}`;
338
+ return tokenInfo.token;
339
+ }
340
+ /** Create a permanent access token to authenticate to Prismic public apis. */
341
+ async createPermanentAccessToken() {
342
+ const profiler = logger.startTimer();
343
+ const token = await this.authApiClient.getMachine2MachineToken(this.name);
344
+ profiler.done({ message: `machine2machine token created` });
345
+ return token;
346
+ }
347
+ /**
348
+ * Toggle the Role per Locale workflow
349
+ *
350
+ * @param enabled - The feature new status
351
+ */
352
+ async toggleRolePerLocal(enabled) {
353
+ const profiler = logger.startTimer();
354
+ const response = await this.manageV2Client.toggleRolePerLocal({
355
+ repository: this.name,
356
+ enabled
357
+ });
358
+ this.failIfNot200(response, `Could not ${enabled ? "enable" : "disable"} Role per local for ${this.name}`);
359
+ profiler.done({ message: `Role per local ${enabled ? "enabled" : "disabled"}` });
360
+ }
361
+ /**
362
+ * Toggle the Custom Roles workflow
363
+ *
364
+ * @param enabled - The feature new status
365
+ */
366
+ async toggleCustomRoles(enabled) {
367
+ const profiler = logger.startTimer();
368
+ const response = await this.manageV2Client.toggleCustomRoles({
369
+ repository: this.name,
370
+ enabled
371
+ });
372
+ this.failIfNot200(response, `Could not ${enabled ? "enable" : "disable"} Custom Roles for ${this.name}`);
373
+ profiler.done({ message: `Custom Roles ${enabled ? "enabled" : "disabled"}` });
374
+ }
375
+ /**
376
+ * Toggle the Integration Fields feature
377
+ *
378
+ * @param enabled - The feature new status
379
+ */
380
+ async toggleIntegrationFields(enabled) {
381
+ const profiler = logger.startTimer();
382
+ const response = await this.manageV2Client.toggleIntegrationFields({
383
+ repository: this.name,
384
+ enabled
385
+ });
386
+ this.failIfNot200(response, `Could not ${enabled ? "enable" : "disable"} Integration Fields for ${this.name}`);
387
+ profiler.done({ message: `Integration Fields ${enabled ? "enabled" : "disabled"}` });
388
+ }
389
+ /**
390
+ * Change the Repository Plan
391
+ *
392
+ * @param {string} newPlanId - The Id of the new Plan to apply
393
+ */
394
+ async changePlan(newPlanId) {
395
+ const profiler = logger.startTimer();
396
+ const response = await this.manageV2Client.changePlan({
397
+ repository: this.name,
398
+ newPlanId,
399
+ bypassManualBilling: true
400
+ });
401
+ this.failIfNot200(response, "Could not change the Repository Plan");
402
+ profiler.done({ message: `Repository Plan changed to ${newPlanId}` });
403
+ }
404
+ /**
405
+ * Add a new user to the repository
406
+ *
407
+ * @param {string} email - The email of the user
408
+ */
409
+ async addUser(email) {
410
+ const profiler = logger.startTimer();
411
+ const response = await this.manageV2Client.addUserToRepository({
412
+ repository: this.name,
413
+ email
414
+ });
415
+ const { data, status } = response;
416
+ if (!(status === 200 || status === 409 && JSON.stringify(data).includes("already a member of the repo"))) {
417
+ logHttpResponse(response);
418
+ throw new Error(`Could not add a new user ${email} to the repository`);
419
+ }
420
+ profiler.done({ message: `User ${email} was added to the repository` });
421
+ }
422
+ /**
423
+ * Remove a user from the repository
424
+ *
425
+ * @param {string} email - The email of the user
426
+ */
427
+ async removeUser(email) {
428
+ const profiler = logger.startTimer();
429
+ const response = await this.manageV2Client.removeUserFromRepository({
430
+ repository: this.name,
431
+ email
432
+ });
433
+ this.failIfNot200(response, `Could not remove the user ${email} from the repository`);
434
+ profiler.done({ message: `User ${email} was removed from the repository` });
435
+ }
436
+ /**
437
+ * Update the role of a user in a repository
438
+ *
439
+ * @param {string} email - The email of the user
440
+ * @param {string | Record<string, string>} role - The new Role of the user, either a string for
441
+ * basic workflow or an object such as `{ "lang_id": "Writer" }`
442
+ *
443
+ * Example of roles are
444
+ *
445
+ * - Administrator
446
+ * - Writer
447
+ * - Contributor
448
+ * - Manager (publisher)
449
+ */
450
+ async updateUserRole(email, role) {
451
+ const profiler = logger.startTimer();
452
+ const response = typeof role === "string" ? await this.wroomClient.updateRole(this.name, email, role) : await this.wroomClient.updateRolePerLocal(this.name, email, role);
453
+ this.failIfNot200(response, `Could not update the ${typeof role === "string" ? "role" : "rolePerLocal"} of the user ${email}`);
454
+ profiler.done({ message: `Updated User's ${typeof role === "string" ? "role" : "rolePerLocal"} for user ${email}` });
455
+ }
456
+ /**
457
+ * Creates a document using the core api. If the Core api format is too specific, use the
458
+ * migration api client to create a document with the MigrationApiClient. See the
459
+ * `getMigrationApiClient()` method.
460
+ *
461
+ * @example
462
+ * To create a document by converting it from the Page Builder to
463
+ * Core api format
464
+ *
465
+ * ```js
466
+ * import { DocumentLegacy, UIDContentType } from '@prismicio/types-internal/lib/content';
467
+ *
468
+ * const document = {
469
+ * title: 'A new document',
470
+ * custom_type_id: 'home-page',
471
+ * locale: 'en-gb',
472
+ * integration_field_ids: [],
473
+ * tags: [],
474
+ * data: DocumentLegacy.encode({
475
+ * uid: {
476
+ * __TYPE__: UIDContentType,
477
+ * value: 'home-page',
478
+ * },
479
+ * })
480
+ * }
481
+ * await repository.createDocument(document, 'published');
482
+ * * ```
483
+ * ```
484
+ *
485
+ * @returns
486
+ *
487
+ * @param document - in the core api format.
488
+ *
489
+ * @param status - status of the document, if published, the function will
490
+ * wait for a new content api master ref to be created
491
+ */
492
+ async createDocument(document, status) {
493
+ const profiler = logger.startTimer();
494
+ const result = await this.coreApiClient.createDraft(document);
495
+ let message = `Document created with id '${result.id}'`;
496
+ if (status === "published") {
497
+ const contentApi = this.getContentApiClient();
498
+ const masterRef = await contentApi.getMasterRef();
499
+ await this.coreApiClient.publishDraft(result.id);
500
+ await this.waitForNewMasterRef(contentApi, masterRef);
501
+ message += ", status 'published' and new master ref available";
502
+ }
503
+ profiler.done({ message });
504
+ return result;
505
+ }
506
+ /**
507
+ * Updates an existing document using the core api by creating a new draft version on top of the
508
+ * given base version. If the status is published, the function will, unless disabled, wait for a
509
+ * new content api master ref to be created.
510
+ *
511
+ * @param documentId - The id of the document to update.
512
+ * @param data - The new version payload in the core api format.
513
+ * @param baseVersionId - The id of the version the draft is created from.
514
+ * @param status - Status of the new version, if published, the function will wait for a new
515
+ * content api master ref to be created.
516
+ * @param options - Additional options.
517
+ * @param options.skipMasterRefWait - When publishing, skip waiting for a new content api master
518
+ * ref to be available (default false). Set to true to return without waiting for the
519
+ * projection.
520
+ * @returns The updated document, including the new version's id. When publishing, the document is
521
+ * retrieved again after publication so that the returned versions reflect the published state.
522
+ */
523
+ async updateDocument(documentId, data, baseVersionId, status, options = {}) {
524
+ const { skipMasterRefWait = false } = options;
525
+ const profiler = logger.startTimer();
526
+ const draft = await this.coreApiClient.updateDraft(documentId, data, baseVersionId);
527
+ if (status === "draft") {
528
+ profiler.done({ message: `Document '${documentId}' updated` });
529
+ return draft;
530
+ }
531
+ let message = `Document '${documentId}' updated, status 'published'`;
532
+ if (skipMasterRefWait) await this.coreApiClient.publishDraft(documentId);
533
+ else {
534
+ const contentApi = this.getContentApiClient();
535
+ const masterRef = await contentApi.getMasterRef();
536
+ await this.coreApiClient.publishDraft(documentId);
537
+ await this.waitForNewMasterRef(contentApi, masterRef);
538
+ message += " and new master ref available";
539
+ }
540
+ const { results } = await this.coreApiClient.getDocuments({
541
+ documentIds: [documentId],
542
+ limit: 1
543
+ });
544
+ const publishedDocument = results[0];
545
+ if (!publishedDocument) throw new Error(`Could not retrieve document '${documentId}' after publication`);
546
+ profiler.done({ message });
547
+ return publishedDocument;
548
+ }
549
+ /**
550
+ * Unpublishes (archives) a live document using the core api. Unless disabled, waits for a new
551
+ * content api master ref to be available.
552
+ *
553
+ * @param documentId - The id of the document to unpublish.
554
+ * @param options - Additional options.
555
+ * @param options.skipMasterRefWait - Skip waiting for a new content api master ref to be
556
+ * available (default false). Set to true to return without waiting for the projection.
557
+ */
558
+ async unpublishDocument(documentId, options = {}) {
559
+ const { skipMasterRefWait = false } = options;
560
+ const profiler = logger.startTimer();
561
+ if (skipMasterRefWait) {
562
+ await this.coreApiClient.unpublishDocument(documentId);
563
+ profiler.done({ message: `Document '${documentId}' unpublished` });
564
+ return;
565
+ }
566
+ const contentApi = this.getContentApiClient();
567
+ const masterRef = await contentApi.getMasterRef();
568
+ await this.coreApiClient.unpublishDocument(documentId);
569
+ await this.waitForNewMasterRef(contentApi, masterRef);
570
+ profiler.done({ message: `Document '${documentId}' unpublished and new master ref available` });
571
+ }
572
+ /**
573
+ * Retrieves data for a specific document version.
574
+ *
575
+ * @param versionId - The document's version ID.
576
+ * @returns The document's version data.
577
+ */
578
+ async getDocumentData(versionId) {
579
+ return await this.coreApiClient.getDocumentData(versionId);
580
+ }
581
+ async setupIntegrationFields(integrationFields) {
582
+ const profiler = logger.startTimer();
583
+ if (!this.integrationFieldsClient) throw new Error("Integration Fields client not found. Did you provide a integration fields api url in the configuration?");
584
+ await this.integrationFieldsClient.setupIntegrationFields(integrationFields);
585
+ profiler.done({ message: `Integration Fields setup` });
586
+ }
587
+ async waitForNewMasterRef(contentApi, previousMasterRef) {
588
+ await expect.poll(async () => contentApi.getMasterRef(), {
589
+ timeout: 1e4,
590
+ message: "Waiting for new master ref to be available"
591
+ }).not.toBe(previousMasterRef);
592
+ }
617
593
  };
618
- //# sourceMappingURL=repository.js.map
594
+ //#endregion
595
+ export { RepositoryManager };
596
+
597
+ //# sourceMappingURL=repository.js.map