@prismicio/client 7.20.0-alpha.0 → 7.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/Client.cjs +111 -95
  2. package/dist/Client.cjs.map +1 -1
  3. package/dist/Client.d.ts +66 -27
  4. package/dist/Client.js +111 -95
  5. package/dist/Client.js.map +1 -1
  6. package/dist/WriteClient.cjs +156 -101
  7. package/dist/WriteClient.cjs.map +1 -1
  8. package/dist/WriteClient.d.ts +2 -26
  9. package/dist/WriteClient.js +156 -101
  10. package/dist/WriteClient.js.map +1 -1
  11. package/dist/errors/InvalidDataError.cjs +7 -0
  12. package/dist/errors/InvalidDataError.cjs.map +1 -0
  13. package/dist/errors/InvalidDataError.d.ts +3 -0
  14. package/dist/errors/InvalidDataError.js +7 -0
  15. package/dist/errors/InvalidDataError.js.map +1 -0
  16. package/dist/errors/ParsingError.cjs.map +1 -1
  17. package/dist/errors/ParsingError.d.ts +6 -4
  18. package/dist/errors/ParsingError.js.map +1 -1
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.ts +3 -3
  21. package/dist/index.js.map +1 -1
  22. package/dist/lib/request.cjs +43 -0
  23. package/dist/lib/request.cjs.map +1 -0
  24. package/dist/lib/request.d.ts +73 -0
  25. package/dist/lib/request.js +43 -0
  26. package/dist/lib/request.js.map +1 -0
  27. package/dist/package.json.cjs +3 -1
  28. package/dist/package.json.cjs.map +1 -1
  29. package/dist/package.json.js +3 -1
  30. package/dist/package.json.js.map +1 -1
  31. package/dist/types/{integration.d.ts → api/integration.d.ts} +1 -1
  32. package/package.json +1 -1
  33. package/src/Client.ts +201 -171
  34. package/src/WriteClient.ts +220 -157
  35. package/src/errors/InvalidDataError.ts +5 -0
  36. package/src/errors/ParsingError.ts +6 -4
  37. package/src/index.ts +13 -11
  38. package/src/lib/request.ts +166 -0
  39. package/src/types/{integration.ts → api/integration.ts} +1 -1
  40. package/dist/BaseClient.cjs +0 -108
  41. package/dist/BaseClient.cjs.map +0 -1
  42. package/dist/BaseClient.d.ts +0 -152
  43. package/dist/BaseClient.js +0 -108
  44. package/dist/BaseClient.js.map +0 -1
  45. package/src/BaseClient.ts +0 -330
@@ -1,5 +1,7 @@
1
1
  import { devMsg } from "./lib/devMsg"
2
2
  import { pLimit } from "./lib/pLimit"
3
+ import type { ResponseLike } from "./lib/request"
4
+ import { type RequestInitLike, request } from "./lib/request"
3
5
  import {
4
6
  resolveMigrationContentRelationship,
5
7
  resolveMigrationDocumentData,
@@ -8,22 +10,15 @@ import {
8
10
  import type {
9
11
  Asset,
10
12
  PatchAssetParams,
11
- PatchAssetResult,
12
13
  PostAssetParams,
13
14
  PostAssetResult,
14
15
  } from "./types/api/asset/asset"
15
16
  import type {
16
17
  AssetTag,
17
18
  GetAssetTagsResult,
18
- PostAssetTagParams,
19
19
  PostAssetTagResult,
20
20
  } from "./types/api/asset/tag"
21
- import type { PutDocumentResult } from "./types/api/migration/document"
22
- import {
23
- type PostDocumentParams,
24
- type PostDocumentResult,
25
- type PutDocumentParams,
26
- } from "./types/api/migration/document"
21
+ import { type PostDocumentResult } from "./types/api/migration/document"
27
22
  import type { PrismicMigrationAsset } from "./types/migration/Asset"
28
23
  import type {
29
24
  MigrationDocument,
@@ -32,15 +27,21 @@ import type {
32
27
  } from "./types/migration/Document"
33
28
  import type { PrismicDocument } from "./types/value/document"
34
29
 
30
+ import { ForbiddenError } from "./errors/ForbiddenError"
31
+ import { InvalidDataError } from "./errors/InvalidDataError"
32
+ import { NotFoundError } from "./errors/NotFoundError"
35
33
  import { PrismicError } from "./errors/PrismicError"
36
34
 
37
- import type { FetchParams, RequestInitLike } from "./BaseClient"
35
+ import { name, version } from "../package.json"
36
+
38
37
  import { Client } from "./Client"
39
- import type { ClientConfig } from "./Client"
38
+ import type { ClientConfig, FetchParams } from "./Client"
40
39
  import type { Migration } from "./Migration"
41
40
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
42
41
  import type { createMigration } from "./createMigration"
43
42
 
43
+ const CLIENT_IDENTIFIER = `${name.replace("@", "").replace("/", "-")}/${version}`
44
+
44
45
  /**
45
46
  * Extracts one or more Prismic document types that match a given Prismic
46
47
  * document type. If no matches are found, no extraction is performed and the
@@ -537,20 +538,24 @@ export class WriteClient<
537
538
  formData.append("alt", alt)
538
539
  }
539
540
 
540
- const asset = await this.fetch<PostAssetResult>(
541
- url.toString(),
542
- this.buildAssetAPIQueryParams({
543
- method: "POST",
544
- body: formData,
545
- params,
546
- }),
547
- )
541
+ const response = await this.#request(url, params, {
542
+ method: "POST",
543
+ body: formData,
544
+ })
545
+ switch (response.status) {
546
+ case 200: {
547
+ const asset = (await response.json()) as PostAssetResult
548
548
 
549
- if (tags && tags.length) {
550
- return this.updateAsset(asset.id, { tags })
551
- }
549
+ if (tags && tags.length) {
550
+ return this.updateAsset(asset.id, { tags })
551
+ }
552
552
 
553
- return asset
553
+ return asset
554
+ }
555
+ default: {
556
+ return await this.#handleAssetAPIError(response)
557
+ }
558
+ }
554
559
  }
555
560
 
556
561
  /**
@@ -582,20 +587,27 @@ export class WriteClient<
582
587
  })
583
588
  }
584
589
 
585
- return this.fetch<PatchAssetResult>(
586
- url.toString(),
587
- this.buildAssetAPIQueryParams<PatchAssetParams>({
588
- method: "PATCH",
589
- body: {
590
- notes,
591
- credits,
592
- alt,
593
- filename,
594
- tags,
595
- },
596
- params,
590
+ const response = await this.#request(url, params, {
591
+ method: "PATCH",
592
+ body: JSON.stringify({
593
+ notes,
594
+ credits,
595
+ alt,
596
+ filename,
597
+ tags,
597
598
  }),
598
- )
599
+ headers: {
600
+ "content-type": "application/json",
601
+ },
602
+ })
603
+ switch (response.status) {
604
+ case 200: {
605
+ return (await response.json()) as Asset
606
+ }
607
+ default: {
608
+ return await this.#handleAssetAPIError(response)
609
+ }
610
+ }
599
611
  }
600
612
 
601
613
  /**
@@ -610,20 +622,7 @@ export class WriteClient<
610
622
  url: string,
611
623
  params: FetchParams = {},
612
624
  ): Promise<Blob> {
613
- const requestInit: RequestInitLike = {
614
- ...this.fetchOptions,
615
- ...params.fetchOptions,
616
- headers: {
617
- ...this.fetchOptions?.headers,
618
- ...params.fetchOptions?.headers,
619
- },
620
- signal:
621
- params.fetchOptions?.signal ||
622
- params.signal ||
623
- this.fetchOptions?.signal,
624
- }
625
-
626
- const res = await this.fetchFn(url, requestInit)
625
+ const res = await this.fetchFn(url, this._buildRequestInit(params))
627
626
 
628
627
  if (!res.ok) {
629
628
  throw new PrismicError("Could not fetch foreign asset", url, undefined)
@@ -696,14 +695,21 @@ export class WriteClient<
696
695
  ): Promise<AssetTag> {
697
696
  const url = new URL("tags", this.assetAPIEndpoint)
698
697
 
699
- return this.fetch<PostAssetTagResult>(
700
- url.toString(),
701
- this.buildAssetAPIQueryParams<PostAssetTagParams>({
702
- method: "POST",
703
- body: { name },
704
- params,
705
- }),
706
- )
698
+ const response = await this.#request(url, params, {
699
+ method: "POST",
700
+ body: JSON.stringify({ name }),
701
+ headers: {
702
+ "content-type": "application/json",
703
+ },
704
+ })
705
+ switch (response.status) {
706
+ case 201: {
707
+ return (await response.json()) as PostAssetTagResult
708
+ }
709
+ default: {
710
+ return await this.#handleAssetAPIError(response)
711
+ }
712
+ }
707
713
  }
708
714
 
709
715
  /**
@@ -716,12 +722,17 @@ export class WriteClient<
716
722
  private async getAssetTags(params?: FetchParams): Promise<AssetTag[]> {
717
723
  const url = new URL("tags", this.assetAPIEndpoint)
718
724
 
719
- const { items } = await this.fetch<GetAssetTagsResult>(
720
- url.toString(),
721
- this.buildAssetAPIQueryParams({ params }),
722
- )
725
+ const response = await this.#request(url, params)
726
+ switch (response.status) {
727
+ case 200: {
728
+ const json = (await response.json()) as GetAssetTagsResult
723
729
 
724
- return items
730
+ return json.items
731
+ }
732
+ default: {
733
+ return await this.#handleAssetAPIError(response)
734
+ }
735
+ }
725
736
  }
726
737
 
727
738
  /**
@@ -749,24 +760,32 @@ export class WriteClient<
749
760
  ): Promise<{ id: string }> {
750
761
  const url = new URL("documents", this.migrationAPIEndpoint)
751
762
 
752
- const result = await this.fetch<PostDocumentResult>(
753
- url.toString(),
754
- this.buildMigrationAPIQueryParams<PostDocumentParams>({
755
- method: "POST",
756
- body: {
757
- title: documentTitle,
758
- type: document.type,
759
- uid: document.uid || undefined,
760
- lang: document.lang,
761
- alternate_language_id: masterLanguageDocumentID,
762
- tags: document.tags,
763
- data: document.data,
764
- },
765
- params,
763
+ const response = await this.#request(url, params, {
764
+ method: "POST",
765
+ body: JSON.stringify({
766
+ title: documentTitle,
767
+ type: document.type,
768
+ uid: document.uid || undefined,
769
+ lang: document.lang,
770
+ alternate_language_id: masterLanguageDocumentID,
771
+ tags: document.tags,
772
+ data: document.data,
766
773
  }),
767
- )
774
+ headers: {
775
+ "content-type": "application/json",
776
+ "x-client": CLIENT_IDENTIFIER,
777
+ },
778
+ })
779
+ switch (response.status) {
780
+ case 201: {
781
+ const json = (await response.json()) as PostDocumentResult
768
782
 
769
- return { id: result.id }
783
+ return { id: json.id }
784
+ }
785
+ default: {
786
+ return await this.#handleMigrationAPIError(response)
787
+ }
788
+ }
770
789
  }
771
790
 
772
791
  /**
@@ -789,101 +808,145 @@ export class WriteClient<
789
808
  ): Promise<void> {
790
809
  const url = new URL(`documents/${id}`, this.migrationAPIEndpoint)
791
810
 
792
- await this.fetch<PutDocumentResult>(
793
- url.toString(),
794
- this.buildMigrationAPIQueryParams({
795
- method: "PUT",
796
- body: {
797
- title: document.documentTitle,
798
- uid: document.uid || undefined,
799
- tags: document.tags,
800
- data: document.data,
801
- },
802
- params,
811
+ const response = await this.#request(url, params, {
812
+ method: "PUT",
813
+ body: JSON.stringify({
814
+ title: document.documentTitle,
815
+ uid: document.uid || undefined,
816
+ tags: document.tags,
817
+ data: document.data,
803
818
  }),
804
- )
819
+ headers: {
820
+ "content-type": "application/json",
821
+ "x-client": CLIENT_IDENTIFIER,
822
+ },
823
+ })
824
+ switch (response.status) {
825
+ case 200: {
826
+ return
827
+ }
828
+ default: {
829
+ await this.#handleMigrationAPIError(response)
830
+ }
831
+ }
805
832
  }
806
833
 
807
834
  /**
808
- * Builds fetch parameters for the Asset API.
809
- *
810
- * @typeParam TBody - Type of the body to send in the fetch request.
811
- *
812
- * @param params - Method, body, and additional fetch parameters.
835
+ * Makes an authenticated HTTP request for write operations using the client's
836
+ * configured fetch function and options.
813
837
  *
814
- * @returns An object that can be fetched to interact with the Asset API.
838
+ * @param url - The URL to request.
839
+ * @param params - Fetch options from the user.
840
+ * @param init - Additional fetch options to merge with the user-provided
841
+ * options.
815
842
  *
816
- * @see Prismic Asset API technical reference: {@link https://prismic.io/docs/asset-api-technical-reference}
843
+ * @returns The response from the fetch request.
817
844
  */
818
- private buildAssetAPIQueryParams<TBody = FormData | Record<string, unknown>>({
819
- method,
820
- body,
821
- params,
822
- }: {
823
- method?: string
824
- body?: TBody
825
- params?: FetchParams
826
- }): FetchParams {
827
- const headers: Record<string, string> = {
828
- ...params?.fetchOptions?.headers,
829
- authorization: `Bearer ${this.writeToken}`,
830
- repository: this.repositoryName,
831
- }
832
-
833
- let _body: FormData | string | undefined
834
- if (body instanceof FormData) {
835
- _body = body
836
- } else if (body) {
837
- _body = JSON.stringify(body)
838
- headers["content-type"] = "application/json"
839
- }
840
-
841
- return {
842
- ...params,
843
- fetchOptions: {
844
- ...params?.fetchOptions,
845
- method,
846
- body: _body,
847
- headers,
845
+ async #request(
846
+ url: URL,
847
+ params?: RequestInitLike,
848
+ init?: RequestInitLike,
849
+ ): Promise<ResponseLike> {
850
+ const baseInit = this._buildRequestInit(params)
851
+
852
+ return await request(
853
+ url,
854
+ {
855
+ ...baseInit,
856
+ ...init,
857
+ headers: {
858
+ ...baseInit.headers,
859
+ ...init?.headers,
860
+ repository: this.repositoryName,
861
+ authorization: `Bearer ${this.writeToken}`,
862
+ },
848
863
  },
849
- }
864
+ this.fetchFn,
865
+ )
850
866
  }
851
867
 
852
868
  /**
853
- * Builds fetch parameters for the Migration API.
869
+ * Handles error responses from the Asset API with comprehensive error
870
+ * parsing.
854
871
  *
855
- * @typeParam TBody - Type of the body to send in the fetch request.
872
+ * @param response - The HTTP response from the Asset API.
856
873
  *
857
- * @param params - Method, body, and additional fetch options.
874
+ * @throws {@link InvalidDataError} For 400 errors.
875
+ * @throws {@link ForbiddenError} For 401 and 403 errors.
876
+ * @throws {@link NotFoundError} For 404 errors.
877
+ * @throws {@link PrismicError} For 500, 503, and other unexpected errors.
878
+ */
879
+ async #handleAssetAPIError(response: ResponseLike): Promise<never> {
880
+ const json = await response.json()
881
+ switch (response.status) {
882
+ case 401:
883
+ case 403:
884
+ throw new ForbiddenError(json.error, response.url, json)
885
+
886
+ case 404:
887
+ throw new NotFoundError(json.error, response.url, json)
888
+
889
+ case 400:
890
+ throw new InvalidDataError(json.error, response.url, json)
891
+
892
+ case 500:
893
+ case 503:
894
+ default:
895
+ throw new PrismicError(json.error, response.url, json)
896
+ }
897
+ }
898
+
899
+ /**
900
+ * Handles error responses from the Migration API with comprehensive error
901
+ * parsing.
858
902
  *
859
- * @returns An object that can be fetched to interact with the Migration API.
903
+ * @param response - The HTTP response from the Migration API.
860
904
  *
861
- * @see Prismic Migration API technical reference: {@link https://prismic.io/docs/migration-api-technical-reference}
905
+ * @throws {@link InvalidDataError} For 400 errors.
906
+ * @throws {@link ForbiddenError} For 401 and 403 errors.
907
+ * @throws {@link NotFoundError} For 404 errors.
908
+ * @throws {@link PrismicError} For 500, and other unexpected errors.
862
909
  */
863
- private buildMigrationAPIQueryParams<
864
- TBody extends PostDocumentParams | PutDocumentParams,
865
- >({
866
- method,
867
- body,
868
- params,
869
- }: {
870
- method?: string
871
- body: TBody
872
- params?: FetchParams
873
- }): FetchParams {
874
- return {
875
- ...params,
876
- fetchOptions: {
877
- ...params?.fetchOptions,
878
- method,
879
- body: JSON.stringify(body),
880
- headers: {
881
- ...params?.fetchOptions?.headers,
882
- "content-type": "application/json",
883
- repository: this.repositoryName,
884
- authorization: `Bearer ${this.writeToken}`,
885
- },
886
- },
910
+ async #handleMigrationAPIError(response: ResponseLike): Promise<never> {
911
+ // Some responses come with a JSON body, some with a text body.
912
+ const text = await response.text()
913
+ let json: unknown
914
+ try {
915
+ json = JSON.parse(text)
916
+ } catch {
917
+ // no-op
918
+ }
919
+
920
+ switch (response.status) {
921
+ case 400:
922
+ if (json) {
923
+ throw new InvalidDataError(
924
+ "Validation failed, check the response property of the error for details",
925
+ response.url,
926
+ json, // `json` has the shape Array<{ property: string, value: unknown, error: string }>
927
+ )
928
+ }
929
+ throw new InvalidDataError(text, response.url, text)
930
+
931
+ case 401:
932
+ throw new ForbiddenError(text, response.url, text)
933
+
934
+ case 403:
935
+ if (json) {
936
+ throw new ForbiddenError(
937
+ (json as { Message: string }).Message,
938
+ response.url,
939
+ json,
940
+ )
941
+ }
942
+ throw new ForbiddenError(text, response.url, text)
943
+
944
+ case 404:
945
+ throw new NotFoundError(text, response.url, text)
946
+
947
+ case 500:
948
+ default:
949
+ throw new PrismicError(text, response.url, text)
887
950
  }
888
951
  }
889
952
  }
@@ -0,0 +1,5 @@
1
+ import { PrismicError } from "./PrismicError"
2
+
3
+ export class InvalidDataError<
4
+ TResponse = undefined,
5
+ > extends PrismicError<TResponse> {}
@@ -3,10 +3,12 @@ import { PrismicError } from "./PrismicError"
3
3
  type ParsingErrorAPIResponse = {
4
4
  type: "parsing-error"
5
5
  message: string
6
- line: number
7
- column: number
8
- id: number
9
- location: string
6
+ pos: {
7
+ line: number
8
+ column: number
9
+ id: number
10
+ location: string
11
+ }
10
12
  }
11
13
 
12
14
  export class ParsingError<
package/src/index.ts CHANGED
@@ -51,16 +51,9 @@ export * as cookie from "./cookie"
51
51
 
52
52
  // General types used to query content from Prismic. These are made public to allow users to better type their projects.
53
53
  export type { CreateClient } from "./createClient"
54
- export type { ClientConfig } from "./Client"
54
+ export type { ClientConfig, HttpRequestLike } from "./Client"
55
55
  export type { CreateWriteClient } from "./createWriteClient"
56
56
  export type { WriteClientConfig, MigrateReporterEvents } from "./WriteClient"
57
- export type {
58
- AbortSignalLike,
59
- FetchLike,
60
- HttpRequestLike,
61
- RequestInitLike,
62
- ResponseLike,
63
- } from "./BaseClient"
64
57
  export type {
65
58
  BuildQueryURLArgs,
66
59
  Ordering,
@@ -68,6 +61,12 @@ export type {
68
61
  Route,
69
62
  } from "./buildQueryURL"
70
63
  export type { CreateMigration } from "./createMigration"
64
+ export type {
65
+ AbortSignalLike,
66
+ FetchLike,
67
+ RequestInitLike,
68
+ ResponseLike,
69
+ } from "./lib/request"
71
70
 
72
71
  //=============================================================================
73
72
  // Helpers - Manipulate content from Prismic.
@@ -377,6 +376,12 @@ export type {
377
376
 
378
377
  export type { Tags } from "./types/api/tags"
379
378
 
379
+ // Integration - Types representing Prismic's integration API.
380
+ export {
381
+ IntegrationAPIItem,
382
+ IntegrationAPIResults,
383
+ } from "./types/api/integration"
384
+
380
385
  // Webhook - Types representing Prismic webhooks.
381
386
  export { WebhookType } from "./types/webhook/types"
382
387
 
@@ -385,6 +390,3 @@ export type { WebhookBody } from "./types/webhook/types"
385
390
  export type { WebhookBodyAPIUpdate } from "./types/webhook/apiUpdate"
386
391
 
387
392
  export type { WebhookBodyTestTrigger } from "./types/webhook/testTrigger"
388
-
389
- // Integration - Types representing integration catalogs.
390
- export { IntegrationAPIItem, IntegrationAPIResults } from "./types/integration"