@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,32 +1,28 @@
1
- import { expect } from "@playwright/test";
2
- import { AxiosResponse } from "axios";
3
-
4
- import {
5
- CustomType,
6
- SharedSlice,
7
- } from "@prismicio/types-internal/lib/customtypes";
8
-
9
- import { IntegrationFieldConfig } from "../types";
10
-
11
- import { AssetApiClient } from "../clients/assetApi";
12
- import { AuthenticationApiClient } from "../clients/authenticationApi";
13
- import { ContentApiClient } from "../clients/contentApi";
14
- import {
1
+ import { expect } from "@playwright/test"
2
+ import type { DynamicCustomTypeModel, SharedSliceModel } from "@prismicio/types-internal"
3
+ import type { AxiosResponse } from "axios"
4
+
5
+ import type { AssetApiClient } from "../clients/assetApi"
6
+ import type { AuthenticationApiClient } from "../clients/authenticationApi"
7
+ import { ContentApiClient } from "../clients/contentApi"
8
+ import type {
15
9
  CoreApiClient,
16
10
  CoreApiDocumentCreationPayload,
17
11
  CoreApiDocumentCreationResponse,
18
12
  CoreApiDocumentData,
19
13
  CoreApiDocumentsPayload,
20
14
  CoreApiDocumentsResponse,
15
+ CoreApiDocumentUpdatePayload,
21
16
  Release,
22
- } from "../clients/coreApi";
23
- import { CustomTypesApiClient } from "../clients/customTypesApi";
24
- import { IntegrationFieldsClient } from "../clients/integrationFields";
25
- import { ManageV2Client } from "../clients/manageV2";
26
- import { MigrationApiClient } from "../clients/migrationApi";
27
- import { WroomClient } from "../clients/wroom";
28
- import { logHttpResponse, logger } from "../utils/log";
29
- import { getRepositoryUrl } from "../utils/urls";
17
+ } from "../clients/coreApi"
18
+ import type { CustomTypesApiClient } from "../clients/customTypesApi"
19
+ import type { IntegrationFieldsClient } from "../clients/integrationFields"
20
+ import type { ManageV2Client } from "../clients/manageV2"
21
+ import type { MigrationApiClient } from "../clients/migrationApi"
22
+ import type { WroomClient } from "../clients/wroom"
23
+ import type { IntegrationFieldConfig } from "../types"
24
+ import { logHttpResponse, logger } from "../utils/log"
25
+ import { getRepositoryUrl } from "../utils/urls"
30
26
 
31
27
  /** Utility to manage test data for a Prismic repository */
32
28
  export class RepositoryManager {
@@ -39,25 +35,22 @@ export class RepositoryManager {
39
35
  private readonly migrationApiClient: MigrationApiClient | undefined,
40
36
  private readonly assetApiClient: AssetApiClient,
41
37
  private readonly manageV2Client: ManageV2Client,
42
- private readonly integrationFieldsClient:
43
- | IntegrationFieldsClient
44
- | undefined,
38
+ private readonly integrationFieldsClient: IntegrationFieldsClient | undefined,
45
39
  ) {}
46
40
 
47
41
  async configure(config: RepositoryConfig): Promise<void> {
48
- const hasLangConfig =
49
- config.defaultLocale || config.locales || config.customLocale;
42
+ const hasLangConfig = config.defaultLocale || config.locales || config.customLocale
50
43
  if (hasLangConfig) {
51
- const languages = await this.coreApiClient.getLanguages();
52
- let updateDefaultLocaleAtTheEnd = false;
44
+ const languages = await this.coreApiClient.getLanguages()
45
+ let updateDefaultLocaleAtTheEnd = false
53
46
  // if no locale exists on repo, the master locale needs to be set first
54
47
  if (config.defaultLocale) {
55
- const master = languages.find(({ is_master }) => is_master === true);
48
+ const master = languages.find(({ is_master }) => is_master === true)
56
49
  if (!master) {
57
- await this.setDefaultLocale(config.defaultLocale, "create");
50
+ await this.setDefaultLocale(config.defaultLocale, "create")
58
51
  } else if (master.id !== config.defaultLocale) {
59
52
  // update the master lang at the end, after it is created.
60
- updateDefaultLocaleAtTheEnd = true;
53
+ updateDefaultLocaleAtTheEnd = true
61
54
  }
62
55
  }
63
56
 
@@ -65,258 +58,238 @@ export class RepositoryManager {
65
58
  // No need to add default locale and already existing languages
66
59
  const localesToAdd = config.locales.filter(
67
60
  (id) => !languages.some((language) => language.id === id),
68
- );
61
+ )
69
62
  if (localesToAdd.length > 0) {
70
- await this.createLocales(localesToAdd);
63
+ await this.createLocales(localesToAdd)
71
64
  }
72
65
  }
73
66
 
74
67
  if (config.customLocale) {
75
68
  if (!languages.find(({ id }) => id === config.customLocale?.lang.id)) {
76
- await this.createCustomLocale(config.customLocale);
69
+ await this.createCustomLocale(config.customLocale)
77
70
  }
78
71
  }
79
72
 
80
73
  if (config.defaultLocale && updateDefaultLocaleAtTheEnd) {
81
- await this.setDefaultLocale(config.defaultLocale, "update");
74
+ await this.setDefaultLocale(config.defaultLocale, "update")
82
75
  }
83
76
  }
84
77
 
85
78
  if (config.slices) {
86
- await this.createSlices(config.slices);
79
+ await this.createSlices(config.slices)
87
80
  }
88
81
 
89
82
  if (config.customTypes) {
90
- await this.createCustomTypes(config.customTypes);
83
+ await this.createCustomTypes(config.customTypes)
91
84
  }
92
85
 
93
86
  if (config.preview) {
94
- await this.createPreview(config.preview);
87
+ await this.createPreview(config.preview)
95
88
  }
96
89
 
97
90
  if (config.simulatorURL) {
98
- await this.setSimulatorURL(config.simulatorURL);
91
+ await this.setSimulatorURL(config.simulatorURL)
99
92
  }
100
93
 
101
94
  if (config.rolePerLocal) {
102
- await this.toggleRolePerLocal(true);
95
+ await this.toggleRolePerLocal(true)
103
96
  }
104
97
 
105
98
  if (config.customRoles) {
106
- await this.toggleCustomRoles(true);
99
+ await this.toggleCustomRoles(true)
107
100
  }
108
101
 
109
102
  if (config.integrationFields) {
110
- await this.toggleIntegrationFields(true);
111
- await this.setupIntegrationFields(config.integrationFields);
103
+ await this.toggleIntegrationFields(true)
104
+ await this.setupIntegrationFields(config.integrationFields)
112
105
  }
113
106
  }
114
107
 
115
- /** @returns the repository base url, like https://my-repo.prismic.io */
108
+ /** @returns The repository base url, like https://my-repo.prismic.io */
116
109
  getBaseURL(): string {
117
- return getRepositoryUrl(this.wroomClient.getBaseURL(), this.name);
110
+ return getRepositoryUrl(this.wroomClient.getBaseURL(), this.name)
118
111
  }
119
112
 
120
- /** @returns the repository base cdn url, like https://my-repo.cdn.prismic.io */
113
+ /** @returns The repository base cdn url, like https://my-repo.cdn.prismic.io */
121
114
  getBaseCdnURL(): string {
122
- return getRepositoryUrl(this.wroomClient.getBaseURL(), `${this.name}.cdn`);
115
+ return getRepositoryUrl(this.wroomClient.getBaseURL(), `${this.name}.cdn`)
123
116
  }
124
117
 
125
118
  /**
126
- * @returns a Content Type api client configured to target the repository CDN
127
- * url. Uses Playwright for requests so if your project uses Playwright too,
128
- * any network request will be present in Playwright test reports.
119
+ * @returns A Content Type api client configured to target the repository CDN url. Uses Playwright
120
+ * for requests so if your project uses Playwright too, any network request will be present in
121
+ * Playwright test reports.
129
122
  */
130
- getContentApiClient(config?: {
131
- version?: "v1" | "v2";
132
- accessToken?: string;
133
- }): ContentApiClient {
134
- return new ContentApiClient(this.getBaseCdnURL(), config);
123
+ getContentApiClient(config?: { version?: "v1" | "v2"; accessToken?: string }): ContentApiClient {
124
+ return new ContentApiClient(this.getBaseCdnURL(), config)
135
125
  }
136
126
 
137
127
  /**
138
- * @returns an instance of the Migration api client, see
128
+ * @returns An instance of the Migration api client, see
139
129
  * https://prismic.io/docs/migration-api-technical-reference
140
130
  */
141
131
  getMigrationApiClient(): MigrationApiClient {
142
132
  if (!this.migrationApiClient) {
143
- throw "No client found for the migration api. Did you provide a migration api url in the configuration?";
133
+ throw "No client found for the migration api. Did you provide a migration api url in the configuration?"
144
134
  }
145
135
 
146
- return this.migrationApiClient;
136
+ return this.migrationApiClient
147
137
  }
148
138
 
149
139
  /**
150
- * @returns an instance of the Asset api client, see
140
+ * @returns An instance of the Asset api client, see
151
141
  * https://prismic.io/docs/asset-api-technical-reference
152
142
  */
153
143
  getAssetApiClient(): AssetApiClient {
154
- return this.assetApiClient;
144
+ return this.assetApiClient
155
145
  }
156
146
 
157
- /** @returns the Wroom commit hash deployed on the current repository */
147
+ /** @returns The Wroom commit hash deployed on the current repository */
158
148
  async getDeployedVersion(): Promise<string | undefined> {
159
149
  const response = await this.wroomClient.get(
160
150
  this.name,
161
151
  "underground/834b34f16f451e00f268dd5c8c81d16e3c020275",
162
- );
152
+ )
163
153
 
164
154
  // Somehow axios directly parses the text response `Prismic version: <commit hash> into a version attribute
165
- return response.data.version;
155
+ return response.data.version
166
156
  }
167
157
 
168
158
  /**
169
- * Set additional standard locales for a repository in Wroom, does not fail if
170
- * the locales already exist.
159
+ * Set additional standard locales for a repository in Wroom, does not fail if the locales already
160
+ * exist.
171
161
  *
172
162
  * @param locales - An array of all locales to be added to the repository.
173
- *
174
163
  * @throws Error if setting the locales fails.
175
164
  */
176
165
  async createLocales(locales: string[]): Promise<void> {
177
- const profiler = logger.startTimer();
166
+ const profiler = logger.startTimer()
178
167
 
179
- const response = await this.wroomClient.post(
180
- this.name,
181
- "app/settings/multilanguages",
182
- { languages: locales },
183
- );
168
+ const response = await this.wroomClient.post(this.name, "app/settings/multilanguages", {
169
+ languages: locales,
170
+ })
184
171
 
185
- const { data, status } = response;
172
+ const { data, status } = response
186
173
  const success =
187
- status === 200 ||
188
- (status === 400 &&
189
- (data as string).includes("already existing languages"));
174
+ status === 200 || (status === 400 && (data as string).includes("already existing languages"))
190
175
  if (!success) {
191
- logHttpResponse(response);
192
- throw new Error(`Could not add locales ${locales.join(", ")}`);
176
+ logHttpResponse(response)
177
+ throw new Error(`Could not add locales ${locales.join(", ")}`)
193
178
  }
194
- profiler.done({ message: `locales '${locales}' created` });
179
+ profiler.done({ message: `locales '${locales}' created` })
195
180
  }
196
181
 
197
182
  /**
198
- * Set additional custom locale for a repository in Wroom, does not fail if
199
- * the locales already exist.
183
+ * Set additional custom locale for a repository in Wroom, does not fail if the locales already
184
+ * exist.
200
185
  *
201
186
  * @param locale - The locale to be added to the repository.
202
- *
203
187
  * @throws Error if setting the locale fails.
204
188
  */
205
189
  async createCustomLocale(locale: CustomLocale): Promise<void> {
206
- const profiler = logger.startTimer();
190
+ const profiler = logger.startTimer()
207
191
 
208
192
  const response = await this.wroomClient.post(
209
193
  this.name,
210
194
  "app/settings/multilanguages/custom",
211
195
  locale,
212
- );
196
+ )
213
197
 
214
- const { data, status } = response;
198
+ const { data, status } = response
215
199
  const success =
216
- status === 200 ||
217
- (status === 400 && JSON.stringify(data).includes("code is already used"));
200
+ status === 200 || (status === 400 && JSON.stringify(data).includes("code is already used"))
218
201
  if (!success) {
219
- logHttpResponse(response);
220
- throw new Error(`Could not create custom locale ${locale}`);
202
+ logHttpResponse(response)
203
+ throw new Error(`Could not create custom locale ${locale}`)
221
204
  }
222
205
  profiler.done({
223
206
  message: `custom locale ${JSON.stringify(locale)} created`,
224
- });
207
+ })
225
208
  }
226
209
 
227
210
  private failIfNot200(response: AxiosResponse, msg: string) {
228
211
  if (response.status !== 200) {
229
- logHttpResponse(response);
230
- throw new Error(msg);
212
+ logHttpResponse(response)
213
+ throw new Error(msg)
231
214
  }
232
215
  }
233
216
 
234
217
  /**
235
218
  * Delete a locale from a repository.
236
219
  *
237
- * @param locale - locale to remove from the repository configuration.
238
- *
220
+ * @param locale - Locale to remove from the repository configuration.
239
221
  * @throws Error if deleting the locale fails.
240
222
  */
241
223
  async deleteLocale(locale: string): Promise<void> {
242
- const profiler = logger.startTimer();
224
+ const profiler = logger.startTimer()
243
225
 
244
226
  const response = await this.wroomClient.post(
245
227
  this.name,
246
228
  `app/settings/multilanguages/${locale}/delete`,
247
- );
248
- this.failIfNot200(response, `Could not delete locale ${locale}`);
249
- profiler.done({ message: `locale '${locale}' deleted` });
229
+ )
230
+ this.failIfNot200(response, `Could not delete locale ${locale}`)
231
+ profiler.done({ message: `locale '${locale}' deleted` })
250
232
  }
251
233
 
252
234
  /**
253
- * Create or update the default (master) locale for a repository in Wroom, the
254
- * locale needs to exist in the repository.
235
+ * Create or update the default (master) locale for a repository in Wroom, the locale needs to
236
+ * exist in the repository.
255
237
  *
256
238
  * @param locale - The locale to be set as the default.
257
- * @param endpoint - "createMasterLang" to create it, "defineAsMaster" to
258
- * update it.
259
- *
239
+ * @param endpoint - "createMasterLang" to create it, "defineAsMaster" to update it.
260
240
  * @throws Error if setting the default locale fails.
261
241
  */
262
- async setDefaultLocale(
263
- locale: string,
264
- action: "create" | "update",
265
- ): Promise<void> {
266
- const profiler = logger.startTimer();
242
+ async setDefaultLocale(locale: string, action: "create" | "update"): Promise<void> {
243
+ const profiler = logger.startTimer()
267
244
 
268
245
  const endpoint = {
269
246
  create: "createMasterLang",
270
247
  update: "defineAsMaster",
271
- };
248
+ }
272
249
  const response = await this.wroomClient.post(
273
250
  this.name,
274
251
  `/app/settings/multilanguages/${locale}/${endpoint[action]}`,
275
- );
252
+ )
276
253
 
277
- const { data, status } = response;
254
+ const { data, status } = response
278
255
  const success =
279
256
  status === 200 ||
280
257
  (status === 400 &&
281
258
  // returns 400 if master lang is already set
282
- JSON.stringify(data).includes("Unable to set as master language"));
259
+ JSON.stringify(data).includes("Unable to set as master language"))
283
260
  if (!success) {
284
- logHttpResponse(response);
285
- throw new Error(`Could not set default locale to ${locale}`);
261
+ logHttpResponse(response)
262
+ throw new Error(`Could not set default locale to ${locale}`)
286
263
  }
287
- profiler.done({ message: `default locale set to '${locale}'` });
264
+ profiler.done({ message: `default locale set to '${locale}'` })
288
265
  }
289
266
 
290
267
  /**
291
268
  * Retrieves documents.
292
269
  *
293
270
  * @param args - Configure which documents are retrieved.
294
- *
295
271
  * @returns A paginated set of documents.
296
272
  */
297
- async getDocuments(
298
- args: CoreApiDocumentsPayload,
299
- ): Promise<CoreApiDocumentsResponse> {
300
- return this.coreApiClient.getDocuments(args);
273
+ async getDocuments(args: CoreApiDocumentsPayload): Promise<CoreApiDocumentsResponse> {
274
+ return this.coreApiClient.getDocuments(args)
301
275
  }
302
276
 
303
277
  /**
304
278
  * Creates a release.
305
279
  *
306
280
  * @param label - The label for the release.
307
- *
308
281
  * @returns A Promise that resolves when the release is created.
309
282
  */
310
283
  async createRelease(label: string): Promise<{ id: string }> {
311
- const profiler = logger.startTimer();
284
+ const profiler = logger.startTimer()
312
285
 
313
286
  const response = await this.wroomClient.post(this.name, "app/releases", {
314
287
  label,
315
- });
316
- this.failIfNot200(response, `Could not create release ${label}`);
317
- profiler.done({ message: `release '${label}' created` });
288
+ })
289
+ this.failIfNot200(response, `Could not create release ${label}`)
290
+ profiler.done({ message: `release '${label}' created` })
318
291
 
319
- return response.data;
292
+ return response.data
320
293
  }
321
294
 
322
295
  /**
@@ -325,39 +298,33 @@ export class RepositoryManager {
325
298
  * @returns The migration relese metadata.
326
299
  */
327
300
  async getMigrationRelease(): Promise<Release> {
328
- const releases = await this.coreApiClient.getReleases();
329
- const migrationRelease = releases.find((release) => release.migration);
301
+ const releases = await this.coreApiClient.getReleases()
302
+ const migrationRelease = releases.find((release) => release.migration)
330
303
  if (!migrationRelease) {
331
- throw new Error(`The repository does not have a migration release`);
304
+ throw new Error(`The repository does not have a migration release`)
332
305
  }
333
306
 
334
- return migrationRelease;
307
+ return migrationRelease
335
308
  }
336
309
 
337
310
  /**
338
311
  * Publishes a release.
339
312
  *
340
313
  * @param id - The ID of the release.
341
- *
342
- * @returns A Promise that resolves when the release is published and a new
343
- * master ref is available.
314
+ * @returns A Promise that resolves when the release is published and a new master ref is
315
+ * available.
344
316
  */
345
317
  async publishRelease(id: string): Promise<void> {
346
- const profiler = logger.startTimer();
318
+ const profiler = logger.startTimer()
347
319
 
348
- const contentApi = this.getContentApiClient();
349
- const masterRef = await contentApi.getMasterRef();
350
- await this.coreApiClient.publishRelease(id);
351
- await expect
352
- .poll(async () => contentApi.getMasterRef(), {
353
- timeout: 10_000,
354
- message: "Waiting for new master ref to be available",
355
- })
356
- .not.toBe(masterRef);
320
+ const contentApi = this.getContentApiClient()
321
+ const masterRef = await contentApi.getMasterRef()
322
+ await this.coreApiClient.publishRelease(id)
323
+ await this.waitForNewMasterRef(contentApi, masterRef)
357
324
 
358
325
  profiler.done({
359
326
  message: `release '${id}' published and new master ref available`,
360
- });
327
+ })
361
328
  }
362
329
 
363
330
  /**
@@ -366,16 +333,12 @@ export class RepositoryManager {
366
333
  * @param id - The ID of the release to be deleted.
367
334
  */
368
335
  async deleteRelease(id: string): Promise<void> {
369
- const profiler = logger.startTimer();
336
+ const profiler = logger.startTimer()
370
337
 
371
- const response = await this.wroomClient.post(
372
- this.name,
373
- `app/releases/${id}/delete`,
374
- {},
375
- );
338
+ const response = await this.wroomClient.post(this.name, `app/releases/${id}/delete`, {})
376
339
 
377
- this.failIfNot200(response, `Could not delete release with id ${id}`);
378
- profiler.done({ message: `release '${id}' deleted` });
340
+ this.failIfNot200(response, `Could not delete release with id ${id}`)
341
+ profiler.done({ message: `release '${id}' deleted` })
379
342
  }
380
343
 
381
344
  /**
@@ -384,18 +347,14 @@ export class RepositoryManager {
384
347
  * @param data - The data for creating the preview.
385
348
  */
386
349
  async createPreview(data: Preview): Promise<void> {
387
- const profiler = logger.startTimer();
350
+ const profiler = logger.startTimer()
388
351
 
389
- const response = await this.wroomClient.post(
390
- this.name,
391
- `previews/new`,
392
- data,
393
- );
352
+ const response = await this.wroomClient.post(this.name, `previews/new`, data)
394
353
 
395
- this.failIfNot200(response, `Could not create preview ${data.name}`);
396
- profiler.done({ message: `preview '${data.name}' created` });
354
+ this.failIfNot200(response, `Could not create preview ${data.name}`)
355
+ profiler.done({ message: `preview '${data.name}' created` })
397
356
 
398
- return response.data;
357
+ return response.data
399
358
  }
400
359
 
401
360
  /**
@@ -404,17 +363,17 @@ export class RepositoryManager {
404
363
  * @param data - The simulator URL to set.
405
364
  */
406
365
  async setSimulatorURL(simulatorURL: string): Promise<void> {
407
- const profiler = logger.startTimer();
366
+ const profiler = logger.startTimer()
408
367
 
409
- const repository = await this.coreApiClient.getRepository();
368
+ const repository = await this.coreApiClient.getRepository()
410
369
  await this.coreApiClient.updateRepository({
411
370
  ...repository,
412
371
  simulator_url: simulatorURL,
413
- });
372
+ })
414
373
 
415
374
  profiler.done({
416
375
  message: `simulator preview '${simulatorURL}' created`,
417
- });
376
+ })
418
377
  }
419
378
 
420
379
  /**
@@ -423,16 +382,12 @@ export class RepositoryManager {
423
382
  * @param id - The ID of the preview to be deleted.
424
383
  */
425
384
  async deletePreview(id: string): Promise<void> {
426
- const profiler = logger.startTimer();
385
+ const profiler = logger.startTimer()
427
386
 
428
- const response = await this.wroomClient.post(
429
- this.name,
430
- `previews/delete/${id}`,
431
- {},
432
- );
387
+ const response = await this.wroomClient.post(this.name, `previews/delete/${id}`, {})
433
388
 
434
- this.failIfNot200(response, `Could not delete preview with id ${id}`);
435
- profiler.done({ message: `preview '${id}' deleted` });
389
+ this.failIfNot200(response, `Could not delete preview with id ${id}`)
390
+ profiler.done({ message: `preview '${id}' deleted` })
436
391
  }
437
392
 
438
393
  /**
@@ -445,32 +400,28 @@ export class RepositoryManager {
445
400
  url: string,
446
401
  secret: string,
447
402
  triggers: {
448
- documentsPublished?: boolean;
449
- documentsUnpublished?: boolean;
450
- releasesCreated?: boolean;
451
- releasesUpdated?: boolean;
452
- tagsCreated?: boolean;
453
- tagsDeleted?: boolean;
403
+ documentsPublished?: boolean
404
+ documentsUnpublished?: boolean
405
+ releasesCreated?: boolean
406
+ releasesUpdated?: boolean
407
+ tagsCreated?: boolean
408
+ tagsDeleted?: boolean
454
409
  },
455
410
  active: boolean,
456
411
  ): Promise<string> {
457
- const profiler = logger.startTimer();
412
+ const profiler = logger.startTimer()
458
413
 
459
- const response = await this.wroomClient.post(
460
- this.name,
461
- "app/settings/webhooks/create",
462
- {
463
- name,
464
- url,
465
- secret,
466
- active: active ? "on" : "off",
467
- ...triggers,
468
- },
469
- );
470
- this.failIfNot200(response, `Could not create webhook ${name}`);
471
- profiler.done({ message: `webhook '${name}' created` });
414
+ const response = await this.wroomClient.post(this.name, "app/settings/webhooks/create", {
415
+ name,
416
+ url,
417
+ secret,
418
+ active: active ? "on" : "off",
419
+ ...triggers,
420
+ })
421
+ this.failIfNot200(response, `Could not create webhook ${name}`)
422
+ profiler.done({ message: `webhook '${name}' created` })
472
423
 
473
- return response.data.created;
424
+ return response.data.created
474
425
  }
475
426
 
476
427
  /**
@@ -479,120 +430,118 @@ export class RepositoryManager {
479
430
  * @param id - The webhook ID.
480
431
  */
481
432
  async deleteWebhook(id: string): Promise<void> {
482
- const profiler = logger.startTimer();
433
+ const profiler = logger.startTimer()
483
434
 
484
435
  const response = await this.wroomClient.post(
485
436
  this.name,
486
437
  `app/settings/webhooks/${id}/delete`,
487
438
  {},
488
- );
439
+ )
489
440
 
490
- this.failIfNot200(response, `Could not delete webhook with id ${id}`);
491
- profiler.done({ message: `webhook '${id}' deleted` });
441
+ this.failIfNot200(response, `Could not delete webhook with id ${id}`)
442
+ profiler.done({ message: `webhook '${id}' deleted` })
492
443
  }
493
444
 
494
445
  /**
495
446
  * Create Custom Types using the Custom types api.
496
447
  *
497
- * @param customTypes -
448
+ * @param customTypes
498
449
  */
499
- async createCustomTypes(customTypes: CustomType[]): Promise<void> {
500
- await this.customTypesApiClient.createCustomTypes(customTypes);
450
+ async createCustomTypes(customTypes: DynamicCustomTypeModel[]): Promise<void> {
451
+ await this.customTypesApiClient.createCustomTypes(customTypes)
501
452
  }
502
453
 
503
454
  async deleteCustomType(customTypeId: string): Promise<void> {
504
- await this.customTypesApiClient.deleteCustomType(customTypeId);
455
+ await this.customTypesApiClient.deleteCustomType(customTypeId)
505
456
  }
506
457
 
507
458
  /**
508
459
  * Create slices using the Custom types api.
509
460
  *
510
- * @param slices -
461
+ * @param slices
511
462
  */
512
- async createSlices(slices: SharedSlice[]): Promise<void> {
513
- await this.customTypesApiClient.createSlices(slices);
463
+ async createSlices(slices: SharedSliceModel[]): Promise<void> {
464
+ await this.customTypesApiClient.createSlices(slices)
514
465
  }
515
466
 
516
467
  /**
517
468
  * Create an access token to query private items of the Content api.
518
469
  *
519
- * @param appName - mandatory authorized application name
520
- * @param tokenScope - access token scope. Use "master" to when your content
521
- * api is fully private or "master+releases" to access private releases
470
+ * @param appName - Mandatory authorized application name
471
+ * @param tokenScope - Access token scope. Use "master" to when your content api is fully private
472
+ * or "master+releases" to access private releases
522
473
  */
523
474
  async createContentAPIToken(
524
475
  appName: string,
525
476
  tokenScope: "master" | "master+releases" = "master",
526
477
  ): Promise<string> {
527
- const profiler = logger.startTimer();
478
+ const profiler = logger.startTimer()
528
479
  type AuthorizedAppResponse = {
529
- id: string;
530
- name: string;
531
- wroom_auths: { token: string; scope: "master" | "master+releases" }[];
532
- };
533
- const existingApps: AxiosResponse<AuthorizedAppResponse[]> =
534
- await this.wroomClient.get(this.name, "settings/security/contentapi");
480
+ id: string
481
+ name: string
482
+ wroom_auths: { token: string; scope: "master" | "master+releases" }[]
483
+ }
484
+ const existingApps: AxiosResponse<AuthorizedAppResponse[]> = await this.wroomClient.get(
485
+ this.name,
486
+ "settings/security/contentapi",
487
+ )
535
488
 
536
489
  this.failIfNot200(
537
490
  existingApps,
538
491
  `Could not get status of existing applications to generate a content api token`,
539
- );
492
+ )
540
493
  let app = existingApps.data.find(({ name, wroom_auths }) => {
541
- return name === appName && wroom_auths.length > 0;
542
- });
494
+ return name === appName && wroom_auths.length > 0
495
+ })
543
496
 
544
497
  if (!app) {
545
- const response: AxiosResponse<AuthorizedAppResponse> =
546
- await this.wroomClient.post(this.name, "settings/security/oauthapp", {
498
+ const response: AxiosResponse<AuthorizedAppResponse> = await this.wroomClient.post(
499
+ this.name,
500
+ "settings/security/oauthapp",
501
+ {
547
502
  app_name: appName,
548
- });
503
+ },
504
+ )
549
505
 
550
- this.failIfNot200(
551
- response,
552
- `Could not create content api app ${appName}`,
553
- );
554
- app = response.data;
506
+ this.failIfNot200(response, `Could not create content api app ${appName}`)
507
+ app = response.data
555
508
  }
556
509
 
557
- let tokenInfo = app.wroom_auths.find(({ scope }) => scope === tokenScope);
510
+ let tokenInfo = app.wroom_auths.find(({ scope }) => scope === tokenScope)
558
511
  if (!tokenInfo) {
559
- const response = await this.wroomClient.post(
560
- this.name,
561
- "settings/security/authorizations",
562
- {
563
- app: app.id,
564
- scope: tokenScope,
565
- },
566
- );
512
+ const response = await this.wroomClient.post(this.name, "settings/security/authorizations", {
513
+ app: app.id,
514
+ scope: tokenScope,
515
+ })
567
516
  this.failIfNot200(
568
517
  response,
569
518
  `Could not create content api access token for app ${appName} with scope ${tokenScope}`,
570
- );
571
- tokenInfo = response.data;
519
+ )
520
+ tokenInfo = response.data
572
521
  }
573
522
 
574
523
  profiler.done({
575
524
  message: `content api access token for app '${appName}' created`,
576
- });
525
+ })
577
526
 
578
527
  if (!tokenInfo?.token) {
579
- throw `Could not create content api access token for app ${appName} with scope ${tokenScope}`;
528
+ throw `Could not create content api access token for app ${appName} with scope ${tokenScope}`
580
529
  }
581
530
 
582
- return tokenInfo.token;
531
+ return tokenInfo.token
583
532
  }
584
533
 
585
534
  /** Create a permanent access token to authenticate to Prismic public apis. */
586
535
  async createPermanentAccessToken(): Promise<string> {
587
- const profiler = logger.startTimer();
536
+ const profiler = logger.startTimer()
588
537
 
589
- const token = await this.authApiClient.getMachine2MachineToken(this.name);
538
+ const token = await this.authApiClient.getMachine2MachineToken(this.name)
590
539
 
591
540
  profiler.done({
592
541
  message: `machine2machine token created`,
593
- });
542
+ })
594
543
 
595
- return token;
544
+ return token
596
545
  }
597
546
 
598
547
  /**
@@ -601,22 +550,20 @@ export class RepositoryManager {
601
550
  * @param enabled - The feature new status
602
551
  */
603
552
  async toggleRolePerLocal(enabled: boolean): Promise<void> {
604
- const profiler = logger.startTimer();
553
+ const profiler = logger.startTimer()
605
554
 
606
555
  const response = await this.manageV2Client.toggleRolePerLocal({
607
556
  repository: this.name,
608
557
  enabled: enabled,
609
- });
558
+ })
610
559
 
611
560
  this.failIfNot200(
612
561
  response,
613
- `Could not ${enabled ? "enable" : "disable"} Role per local for ${
614
- this.name
615
- }`,
616
- );
562
+ `Could not ${enabled ? "enable" : "disable"} Role per local for ${this.name}`,
563
+ )
617
564
  profiler.done({
618
565
  message: `Role per local ${enabled ? "enabled" : "disabled"}`,
619
- });
566
+ })
620
567
  }
621
568
 
622
569
  /**
@@ -625,22 +572,20 @@ export class RepositoryManager {
625
572
  * @param enabled - The feature new status
626
573
  */
627
574
  async toggleCustomRoles(enabled: boolean): Promise<void> {
628
- const profiler = logger.startTimer();
575
+ const profiler = logger.startTimer()
629
576
 
630
577
  const response = await this.manageV2Client.toggleCustomRoles({
631
578
  repository: this.name,
632
579
  enabled: enabled,
633
- });
580
+ })
634
581
 
635
582
  this.failIfNot200(
636
583
  response,
637
- `Could not ${enabled ? "enable" : "disable"} Custom Roles for ${
638
- this.name
639
- }`,
640
- );
584
+ `Could not ${enabled ? "enable" : "disable"} Custom Roles for ${this.name}`,
585
+ )
641
586
  profiler.done({
642
587
  message: `Custom Roles ${enabled ? "enabled" : "disabled"}`,
643
- });
588
+ })
644
589
  }
645
590
 
646
591
  /**
@@ -649,22 +594,20 @@ export class RepositoryManager {
649
594
  * @param enabled - The feature new status
650
595
  */
651
596
  async toggleIntegrationFields(enabled: boolean): Promise<void> {
652
- const profiler = logger.startTimer();
597
+ const profiler = logger.startTimer()
653
598
 
654
599
  const response = await this.manageV2Client.toggleIntegrationFields({
655
600
  repository: this.name,
656
601
  enabled: enabled,
657
- });
602
+ })
658
603
 
659
604
  this.failIfNot200(
660
605
  response,
661
- `Could not ${enabled ? "enable" : "disable"} Integration Fields for ${
662
- this.name
663
- }`,
664
- );
606
+ `Could not ${enabled ? "enable" : "disable"} Integration Fields for ${this.name}`,
607
+ )
665
608
  profiler.done({
666
609
  message: `Integration Fields ${enabled ? "enabled" : "disabled"}`,
667
- });
610
+ })
668
611
  }
669
612
 
670
613
  /**
@@ -673,18 +616,18 @@ export class RepositoryManager {
673
616
  * @param {string} newPlanId - The Id of the new Plan to apply
674
617
  */
675
618
  async changePlan(newPlanId: string): Promise<void> {
676
- const profiler = logger.startTimer();
619
+ const profiler = logger.startTimer()
677
620
 
678
621
  const response = await this.manageV2Client.changePlan({
679
622
  repository: this.name,
680
623
  newPlanId: newPlanId,
681
624
  bypassManualBilling: true, // For now the library does not support Stripe features
682
- });
625
+ })
683
626
 
684
- this.failIfNot200(response, "Could not change the Repository Plan");
627
+ this.failIfNot200(response, "Could not change the Repository Plan")
685
628
  profiler.done({
686
629
  message: `Repository Plan changed to ${newPlanId}`,
687
- });
630
+ })
688
631
  }
689
632
 
690
633
  /**
@@ -693,25 +636,24 @@ export class RepositoryManager {
693
636
  * @param {string} email - The email of the user
694
637
  */
695
638
  async addUser(email: string): Promise<void> {
696
- const profiler = logger.startTimer();
639
+ const profiler = logger.startTimer()
697
640
 
698
641
  const response = await this.manageV2Client.addUserToRepository({
699
642
  repository: this.name,
700
643
  email: email,
701
- });
644
+ })
702
645
 
703
- const { data, status } = response;
646
+ const { data, status } = response
704
647
  const success =
705
648
  status === 200 ||
706
- (status === 409 &&
707
- JSON.stringify(data).includes("already a member of the repo"));
649
+ (status === 409 && JSON.stringify(data).includes("already a member of the repo"))
708
650
  if (!success) {
709
- logHttpResponse(response);
710
- throw new Error(`Could not add a new user ${email} to the repository`);
651
+ logHttpResponse(response)
652
+ throw new Error(`Could not add a new user ${email} to the repository`)
711
653
  }
712
654
  profiler.done({
713
655
  message: `User ${email} was added to the repository`,
714
- });
656
+ })
715
657
  }
716
658
 
717
659
  /**
@@ -720,29 +662,25 @@ export class RepositoryManager {
720
662
  * @param {string} email - The email of the user
721
663
  */
722
664
  async removeUser(email: string): Promise<void> {
723
- const profiler = logger.startTimer();
665
+ const profiler = logger.startTimer()
724
666
 
725
667
  const response = await this.manageV2Client.removeUserFromRepository({
726
668
  repository: this.name,
727
669
  email: email,
728
- });
670
+ })
729
671
 
730
- this.failIfNot200(
731
- response,
732
- `Could not remove the user ${email} from the repository`,
733
- );
672
+ this.failIfNot200(response, `Could not remove the user ${email} from the repository`)
734
673
  profiler.done({
735
674
  message: `User ${email} was removed from the repository`,
736
- });
675
+ })
737
676
  }
738
677
 
739
678
  /**
740
679
  * Update the role of a user in a repository
741
680
  *
742
681
  * @param {string} email - The email of the user
743
- * @param {string | Record<string, string>} role - The new Role of the user,
744
- * either a string for basic workflow or an object such as `{ "lang_id":
745
- * "Writer" }`
682
+ * @param {string | Record<string, string>} role - The new Role of the user, either a string for
683
+ * basic workflow or an object such as `{ "lang_id": "Writer" }`
746
684
  *
747
685
  * Example of roles are
748
686
  *
@@ -751,150 +689,244 @@ export class RepositoryManager {
751
689
  * - Contributor
752
690
  * - Manager (publisher)
753
691
  */
754
- async updateUserRole(
755
- email: string,
756
- role: string | Record<string, string>,
757
- ): Promise<void> {
758
- const profiler = logger.startTimer();
692
+ async updateUserRole(email: string, role: string | Record<string, string>): Promise<void> {
693
+ const profiler = logger.startTimer()
759
694
 
760
695
  const response =
761
696
  typeof role === "string"
762
697
  ? await this.wroomClient.updateRole(this.name, email, role)
763
- : await this.wroomClient.updateRolePerLocal(this.name, email, role);
698
+ : await this.wroomClient.updateRolePerLocal(this.name, email, role)
764
699
 
765
700
  this.failIfNot200(
766
701
  response,
767
702
  `Could not update the ${
768
703
  typeof role === "string" ? "role" : "rolePerLocal"
769
704
  } of the user ${email}`,
770
- );
705
+ )
771
706
  profiler.done({
772
707
  message: `Updated User's ${
773
708
  typeof role === "string" ? "role" : "rolePerLocal"
774
709
  } for user ${email}`,
775
- });
710
+ })
776
711
  }
777
712
 
778
713
  /**
779
- * Creates a document using the core api. If the Core api format is too
780
- * specific, use the migration api client to create a document with the
781
- * MigrationApiClient. See the `getMigrationApiClient()` method.
782
- *
783
- * @example To create a document by converting it from the Page Builder to
784
- * Core api format
785
- *
786
- * ```js
787
- * import { DocumentLegacy, UIDContentType } from '@prismicio/types-internal/lib/content';
788
- *
789
- * const document = {
790
- * title: 'A new document',
791
- * custom_type_id: 'home-page',
792
- * locale: 'en-gb',
793
- * integration_field_ids: [],
794
- * tags: [],
795
- * data: DocumentLegacy.encode({
796
- * uid: {
797
- * __TYPE__: UIDContentType,
798
- * value: 'home-page',
799
- * },
800
- * })
801
- * }
802
- * await repository.createDocument(document, 'published');
803
- * * ```
804
- * ```
805
- *
806
- * @returns
807
- *
808
- * @param document - in the core api format.
809
- *
810
- * @param status - status of the document, if published, the function will
811
- * wait for a new content api master ref to be created
714
+ * Creates a document using the core api. If the Core api format is too specific, use the
715
+ * migration api client to create a document with the MigrationApiClient. See the
716
+ * `getMigrationApiClient()` method.
717
+ *
718
+ * @example
719
+ * To create a document by converting it from the Page Builder to
720
+ * Core api format
721
+ *
722
+ * ```js
723
+ * import { DocumentLegacy, UIDContentType } from '@prismicio/types-internal/lib/content';
724
+ *
725
+ * const document = {
726
+ * title: 'A new document',
727
+ * custom_type_id: 'home-page',
728
+ * locale: 'en-gb',
729
+ * integration_field_ids: [],
730
+ * tags: [],
731
+ * data: DocumentLegacy.encode({
732
+ * uid: {
733
+ * __TYPE__: UIDContentType,
734
+ * value: 'home-page',
735
+ * },
736
+ * })
737
+ * }
738
+ * await repository.createDocument(document, 'published');
739
+ * * ```
740
+ * ```
741
+ *
742
+ * @returns
743
+ *
744
+ * @param document - in the core api format.
745
+ *
746
+ * @param status - status of the document, if published, the function will
747
+ * wait for a new content api master ref to be created
812
748
  */
813
749
  async createDocument(
814
750
  document: CoreApiDocumentCreationPayload,
815
751
  status: "draft" | "published",
816
752
  ): Promise<CoreApiDocumentCreationResponse> {
817
- const profiler = logger.startTimer();
818
- const result = await this.coreApiClient.createDraft(document);
753
+ const profiler = logger.startTimer()
754
+ const result = await this.coreApiClient.createDraft(document)
819
755
 
820
- let message = `Document created with id '${result.id}'`;
756
+ let message = `Document created with id '${result.id}'`
821
757
  if (status === "published") {
822
- const contentApi = this.getContentApiClient();
823
- const masterRef = await contentApi.getMasterRef();
824
- await this.coreApiClient.publishDraft(result.id);
825
- await expect
826
- .poll(async () => contentApi.getMasterRef(), {
827
- timeout: 10_000,
828
- message: "Waiting for new master ref to be available",
829
- })
830
- .not.toBe(masterRef);
831
- message += ", status 'published' and new master ref available";
758
+ const contentApi = this.getContentApiClient()
759
+ const masterRef = await contentApi.getMasterRef()
760
+ await this.coreApiClient.publishDraft(result.id)
761
+ await this.waitForNewMasterRef(contentApi, masterRef)
762
+ message += ", status 'published' and new master ref available"
832
763
  }
833
764
  profiler.done({
834
765
  message,
835
- });
766
+ })
836
767
 
837
- return result;
768
+ return result
769
+ }
770
+
771
+ /**
772
+ * Updates an existing document using the core api by creating a new draft version on top of the
773
+ * given base version. If the status is published, the function will, unless disabled, wait for a
774
+ * new content api master ref to be created.
775
+ *
776
+ * @param documentId - The id of the document to update.
777
+ * @param data - The new version payload in the core api format.
778
+ * @param baseVersionId - The id of the version the draft is created from.
779
+ * @param status - Status of the new version, if published, the function will wait for a new
780
+ * content api master ref to be created.
781
+ * @param options - Additional options.
782
+ * @param options.skipMasterRefWait - When publishing, skip waiting for a new content api master
783
+ * ref to be available (default false). Set to true to return without waiting for the
784
+ * projection.
785
+ * @returns The updated document, including the new version's id. When publishing, the document is
786
+ * retrieved again after publication so that the returned versions reflect the published state.
787
+ */
788
+ async updateDocument(
789
+ documentId: string,
790
+ data: CoreApiDocumentUpdatePayload,
791
+ baseVersionId: string,
792
+ status: "draft" | "published",
793
+ options: { skipMasterRefWait?: boolean } = {},
794
+ ): Promise<CoreApiDocumentCreationResponse> {
795
+ const { skipMasterRefWait = false } = options
796
+ const profiler = logger.startTimer()
797
+ const draft = await this.coreApiClient.updateDraft(documentId, data, baseVersionId)
798
+
799
+ if (status === "draft") {
800
+ profiler.done({ message: `Document '${documentId}' updated` })
801
+
802
+ return draft
803
+ }
804
+
805
+ let message = `Document '${documentId}' updated, status 'published'`
806
+ if (skipMasterRefWait) {
807
+ await this.coreApiClient.publishDraft(documentId)
808
+ } else {
809
+ const contentApi = this.getContentApiClient()
810
+ const masterRef = await contentApi.getMasterRef()
811
+ await this.coreApiClient.publishDraft(documentId)
812
+ await this.waitForNewMasterRef(contentApi, masterRef)
813
+ message += " and new master ref available"
814
+ }
815
+
816
+ const { results } = await this.coreApiClient.getDocuments({
817
+ documentIds: [documentId],
818
+ limit: 1,
819
+ })
820
+ const publishedDocument = results[0]
821
+ if (!publishedDocument) {
822
+ throw new Error(`Could not retrieve document '${documentId}' after publication`)
823
+ }
824
+
825
+ profiler.done({
826
+ message,
827
+ })
828
+
829
+ return publishedDocument
830
+ }
831
+
832
+ /**
833
+ * Unpublishes (archives) a live document using the core api. Unless disabled, waits for a new
834
+ * content api master ref to be available.
835
+ *
836
+ * @param documentId - The id of the document to unpublish.
837
+ * @param options - Additional options.
838
+ * @param options.skipMasterRefWait - Skip waiting for a new content api master ref to be
839
+ * available (default false). Set to true to return without waiting for the projection.
840
+ */
841
+ async unpublishDocument(
842
+ documentId: string,
843
+ options: { skipMasterRefWait?: boolean } = {},
844
+ ): Promise<void> {
845
+ const { skipMasterRefWait = false } = options
846
+ const profiler = logger.startTimer()
847
+
848
+ if (skipMasterRefWait) {
849
+ await this.coreApiClient.unpublishDocument(documentId)
850
+ profiler.done({ message: `Document '${documentId}' unpublished` })
851
+
852
+ return
853
+ }
854
+
855
+ const contentApi = this.getContentApiClient()
856
+ const masterRef = await contentApi.getMasterRef()
857
+ await this.coreApiClient.unpublishDocument(documentId)
858
+ await this.waitForNewMasterRef(contentApi, masterRef)
859
+
860
+ profiler.done({
861
+ message: `Document '${documentId}' unpublished and new master ref available`,
862
+ })
838
863
  }
839
864
 
840
865
  /**
841
866
  * Retrieves data for a specific document version.
842
867
  *
843
868
  * @param versionId - The document's version ID.
844
- *
845
869
  * @returns The document's version data.
846
870
  */
847
871
  async getDocumentData(versionId: string): Promise<CoreApiDocumentData> {
848
- return await this.coreApiClient.getDocumentData(versionId);
872
+ return await this.coreApiClient.getDocumentData(versionId)
849
873
  }
850
874
 
851
- async setupIntegrationFields(
852
- integrationFields: IntegrationFieldConfig[],
853
- ): Promise<void> {
854
- const profiler = logger.startTimer();
875
+ async setupIntegrationFields(integrationFields: IntegrationFieldConfig[]): Promise<void> {
876
+ const profiler = logger.startTimer()
855
877
 
856
878
  if (!this.integrationFieldsClient) {
857
879
  throw new Error(
858
880
  "Integration Fields client not found. Did you provide a integration fields api url in the configuration?",
859
- );
881
+ )
860
882
  }
861
883
 
862
- await this.integrationFieldsClient.setupIntegrationFields(
863
- integrationFields,
864
- );
884
+ await this.integrationFieldsClient.setupIntegrationFields(integrationFields)
865
885
  profiler.done({
866
886
  message: `Integration Fields setup`,
867
- });
887
+ })
888
+ }
889
+
890
+ private async waitForNewMasterRef(
891
+ contentApi: ContentApiClient,
892
+ previousMasterRef: string,
893
+ ): Promise<void> {
894
+ await expect
895
+ .poll(async () => contentApi.getMasterRef(), {
896
+ timeout: 10_000,
897
+ message: "Waiting for new master ref to be available",
898
+ })
899
+ .not.toBe(previousMasterRef)
868
900
  }
869
901
  }
870
902
 
871
903
  export type RepositoryConfig = {
872
- customLocale?: CustomLocale;
873
- locales?: string[];
874
- defaultLocale?: string;
875
- slices?: SharedSlice[];
876
- customTypes?: CustomType[];
877
- preview?: Preview;
878
- simulatorURL?: string;
879
- rolePerLocal?: boolean;
880
- customRoles?: boolean;
881
- integrationFields?: IntegrationFieldConfig[];
882
- };
904
+ customLocale?: CustomLocale
905
+ locales?: string[]
906
+ defaultLocale?: string
907
+ slices?: SharedSliceModel[]
908
+ customTypes?: DynamicCustomTypeModel[]
909
+ preview?: Preview
910
+ simulatorURL?: string
911
+ rolePerLocal?: boolean
912
+ customRoles?: boolean
913
+ integrationFields?: IntegrationFieldConfig[]
914
+ }
883
915
 
884
916
  export type Preview = {
885
- name: string;
886
- websiteURL: string;
887
- resolverPath: string;
888
- };
917
+ name: string
918
+ websiteURL: string
919
+ resolverPath: string
920
+ }
889
921
 
890
922
  export type CustomLocale = {
891
923
  lang: {
892
- label: string;
893
- id: string;
894
- useStandardAnalyzer?: boolean;
895
- };
924
+ label: string
925
+ id: string
926
+ useStandardAnalyzer?: boolean
927
+ }
896
928
  region: {
897
- label: string;
898
- id: string;
899
- };
900
- };
929
+ label: string
930
+ id: string
931
+ }
932
+ }