@prismicio/client 7.6.0 → 7.7.0

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 (161) hide show
  1. package/dist/_node_modules/hast-util-whitespace/lib/index.cjs +11 -0
  2. package/dist/_node_modules/hast-util-whitespace/lib/index.cjs.map +1 -0
  3. package/dist/_node_modules/hast-util-whitespace/lib/index.js +11 -0
  4. package/dist/_node_modules/hast-util-whitespace/lib/index.js.map +1 -0
  5. package/dist/buildQueryURL.cjs.map +1 -1
  6. package/dist/buildQueryURL.js.map +1 -1
  7. package/dist/createClient.cjs +1 -4
  8. package/dist/createClient.cjs.map +1 -1
  9. package/dist/createClient.js +1 -4
  10. package/dist/createClient.js.map +1 -1
  11. package/dist/errors/PrismicError.cjs +1 -4
  12. package/dist/errors/PrismicError.cjs.map +1 -1
  13. package/dist/errors/PrismicError.js +1 -4
  14. package/dist/errors/PrismicError.js.map +1 -1
  15. package/dist/errors/PrismicRichTextError.cjs +6 -0
  16. package/dist/errors/PrismicRichTextError.cjs.map +1 -0
  17. package/dist/errors/PrismicRichTextError.d.ts +2 -0
  18. package/dist/errors/PrismicRichTextError.js +6 -0
  19. package/dist/errors/PrismicRichTextError.js.map +1 -0
  20. package/dist/errors/PrismicRichTextSerializerError.cjs +7 -0
  21. package/dist/errors/PrismicRichTextSerializerError.cjs.map +1 -0
  22. package/dist/errors/PrismicRichTextSerializerError.d.ts +3 -0
  23. package/dist/errors/PrismicRichTextSerializerError.js +7 -0
  24. package/dist/errors/PrismicRichTextSerializerError.js.map +1 -0
  25. package/dist/filter.cjs.map +1 -1
  26. package/dist/filter.js.map +1 -1
  27. package/dist/getGraphQLEndpoint.cjs.map +1 -1
  28. package/dist/getGraphQLEndpoint.js.map +1 -1
  29. package/dist/getRepositoryEndpoint.cjs.map +1 -1
  30. package/dist/getRepositoryEndpoint.js.map +1 -1
  31. package/dist/getRepositoryName.cjs.map +1 -1
  32. package/dist/getRepositoryName.js.map +1 -1
  33. package/dist/getToolbarSrc.cjs.map +1 -1
  34. package/dist/getToolbarSrc.js.map +1 -1
  35. package/dist/helpers/asDate.cjs.map +1 -1
  36. package/dist/helpers/asDate.d.ts +1 -1
  37. package/dist/helpers/asDate.js.map +1 -1
  38. package/dist/helpers/asHTML.cjs +1 -1
  39. package/dist/helpers/asHTML.cjs.map +1 -1
  40. package/dist/helpers/asHTML.js +1 -1
  41. package/dist/helpers/asHTML.js.map +1 -1
  42. package/dist/helpers/asImagePixelDensitySrcSet.cjs.map +1 -1
  43. package/dist/helpers/asImagePixelDensitySrcSet.js.map +1 -1
  44. package/dist/helpers/asImageSrc.cjs.map +1 -1
  45. package/dist/helpers/asImageSrc.js.map +1 -1
  46. package/dist/helpers/asImageWidthSrcSet.cjs.map +1 -1
  47. package/dist/helpers/asImageWidthSrcSet.d.ts +2 -2
  48. package/dist/helpers/asImageWidthSrcSet.js.map +1 -1
  49. package/dist/helpers/asLink.cjs.map +1 -1
  50. package/dist/helpers/asLink.js.map +1 -1
  51. package/dist/helpers/asLinkAttrs.cjs.map +1 -1
  52. package/dist/helpers/asLinkAttrs.d.ts +1 -21
  53. package/dist/helpers/asLinkAttrs.js.map +1 -1
  54. package/dist/helpers/asText.cjs.map +1 -1
  55. package/dist/helpers/asText.js.map +1 -1
  56. package/dist/helpers/documentToLinkField.cjs +1 -0
  57. package/dist/helpers/documentToLinkField.cjs.map +1 -1
  58. package/dist/helpers/documentToLinkField.d.ts +1 -1
  59. package/dist/helpers/documentToLinkField.js +1 -0
  60. package/dist/helpers/documentToLinkField.js.map +1 -1
  61. package/dist/helpers/isFilled.cjs.map +1 -1
  62. package/dist/helpers/isFilled.d.ts +20 -66
  63. package/dist/helpers/isFilled.js.map +1 -1
  64. package/dist/helpers/mapSliceZone.cjs.map +1 -1
  65. package/dist/helpers/mapSliceZone.js.map +1 -1
  66. package/dist/helpers/unstable_htmlAsRichText.cjs +11 -0
  67. package/dist/helpers/unstable_htmlAsRichText.cjs.map +1 -0
  68. package/dist/helpers/unstable_htmlAsRichText.d.ts +81 -0
  69. package/dist/helpers/unstable_htmlAsRichText.js +11 -0
  70. package/dist/helpers/unstable_htmlAsRichText.js.map +1 -0
  71. package/dist/helpers/unstable_markdownAsRichText.cjs +12 -0
  72. package/dist/helpers/unstable_markdownAsRichText.cjs.map +1 -0
  73. package/dist/helpers/unstable_markdownAsRichText.d.ts +30 -0
  74. package/dist/helpers/unstable_markdownAsRichText.js +12 -0
  75. package/dist/helpers/unstable_markdownAsRichText.js.map +1 -0
  76. package/dist/index.cjs +8 -0
  77. package/dist/index.cjs.map +1 -1
  78. package/dist/index.d.ts +6 -1
  79. package/dist/index.js +9 -1
  80. package/dist/index.js.map +1 -1
  81. package/dist/isRepositoryEndpoint.cjs.map +1 -1
  82. package/dist/isRepositoryEndpoint.js.map +1 -1
  83. package/dist/lib/RichTextFieldBuilder.cjs +112 -0
  84. package/dist/lib/RichTextFieldBuilder.cjs.map +1 -0
  85. package/dist/lib/RichTextFieldBuilder.d.ts +35 -0
  86. package/dist/lib/RichTextFieldBuilder.js +112 -0
  87. package/dist/lib/RichTextFieldBuilder.js.map +1 -0
  88. package/dist/lib/castThunk.d.ts +1 -1
  89. package/dist/lib/escapeHTML.cjs.map +1 -1
  90. package/dist/lib/escapeHTML.js.map +1 -1
  91. package/dist/lib/filterRichTextField.cjs +88 -0
  92. package/dist/lib/filterRichTextField.cjs.map +1 -0
  93. package/dist/lib/filterRichTextField.d.ts +12 -0
  94. package/dist/lib/filterRichTextField.js +88 -0
  95. package/dist/lib/filterRichTextField.js.map +1 -0
  96. package/dist/lib/findRef.cjs.map +1 -1
  97. package/dist/lib/findRef.js.map +1 -1
  98. package/dist/lib/getPreviewCookie.cjs.map +1 -1
  99. package/dist/lib/getPreviewCookie.js.map +1 -1
  100. package/dist/lib/hastSerializerHelpers.cjs +96 -0
  101. package/dist/lib/hastSerializerHelpers.cjs.map +1 -0
  102. package/dist/lib/hastSerializerHelpers.d.ts +28 -0
  103. package/dist/lib/hastSerializerHelpers.js +96 -0
  104. package/dist/lib/hastSerializerHelpers.js.map +1 -0
  105. package/dist/lib/hastToRichText.cjs +165 -0
  106. package/dist/lib/hastToRichText.cjs.map +1 -0
  107. package/dist/lib/hastToRichText.d.ts +30 -0
  108. package/dist/lib/hastToRichText.js +165 -0
  109. package/dist/lib/hastToRichText.js.map +1 -0
  110. package/dist/lib/rehypeRichText.cjs +59 -0
  111. package/dist/lib/rehypeRichText.cjs.map +1 -0
  112. package/dist/lib/rehypeRichText.d.ts +66 -0
  113. package/dist/lib/rehypeRichText.js +59 -0
  114. package/dist/lib/rehypeRichText.js.map +1 -0
  115. package/dist/lib/serializerHelpers.cjs.map +1 -1
  116. package/dist/lib/serializerHelpers.d.ts +1 -1
  117. package/dist/lib/serializerHelpers.js.map +1 -1
  118. package/dist/package.json.cjs +1 -1
  119. package/dist/package.json.js +1 -1
  120. package/dist/richtext/asText.cjs.map +1 -1
  121. package/dist/richtext/asText.js.map +1 -1
  122. package/dist/richtext/asTree.cjs.map +1 -1
  123. package/dist/richtext/asTree.js.map +1 -1
  124. package/dist/richtext/composeSerializers.cjs.map +1 -1
  125. package/dist/richtext/composeSerializers.js.map +1 -1
  126. package/dist/richtext/serialize.cjs.map +1 -1
  127. package/dist/richtext/serialize.js.map +1 -1
  128. package/dist/richtext/types.cjs.map +1 -1
  129. package/dist/richtext/types.d.ts +3 -3
  130. package/dist/richtext/types.js.map +1 -1
  131. package/dist/richtext/wrapMapSerializer.cjs.map +1 -1
  132. package/dist/richtext/wrapMapSerializer.js.map +1 -1
  133. package/dist/types/model/richText.d.ts +2 -0
  134. package/dist/types/value/embed.cjs.map +1 -1
  135. package/dist/types/value/embed.js.map +1 -1
  136. package/dist/types/value/richText.cjs.map +1 -1
  137. package/dist/types/value/richText.d.ts +8 -1
  138. package/dist/types/value/richText.js.map +1 -1
  139. package/package.json +33 -21
  140. package/src/createClient.ts +4 -3
  141. package/src/errors/PrismicRichTextError.ts +1 -0
  142. package/src/errors/PrismicRichTextSerializerError.ts +3 -0
  143. package/src/helpers/asHTML.ts +21 -19
  144. package/src/helpers/asImagePixelDensitySrcSet.ts +14 -13
  145. package/src/helpers/asImageWidthSrcSet.ts +16 -15
  146. package/src/helpers/asLinkAttrs.ts +4 -4
  147. package/src/helpers/mapSliceZone.ts +20 -19
  148. package/src/helpers/unstable_htmlAsRichText.ts +121 -0
  149. package/src/helpers/unstable_markdownAsRichText.ts +52 -0
  150. package/src/index.ts +10 -0
  151. package/src/lib/RichTextFieldBuilder.ts +164 -0
  152. package/src/lib/filterRichTextField.ts +159 -0
  153. package/src/lib/hastSerializerHelpers.ts +153 -0
  154. package/src/lib/hastToRichText.ts +294 -0
  155. package/src/lib/rehypeRichText.ts +183 -0
  156. package/src/richtext/types.ts +3 -2
  157. package/src/types/model/richText.ts +4 -0
  158. package/src/types/value/embed.ts +1 -1
  159. package/src/types/value/geoPoint.ts +1 -1
  160. package/src/types/value/richText.ts +10 -1
  161. package/src/types/value/title.ts +1 -1
@@ -18,20 +18,21 @@ const DEFAULT_WIDTHS = [640, 828, 1200, 2048, 3840];
18
18
  */
19
19
  type AsImageWidthSrcSetReturnType<
20
20
  Field extends ImageFieldImage | null | undefined,
21
- > = Field extends ImageFieldImage<"filled">
22
- ? {
23
- /**
24
- * The image field's image URL with Imgix URL parameters (if given).
25
- */
26
- src: string;
21
+ > =
22
+ Field extends ImageFieldImage<"filled">
23
+ ? {
24
+ /**
25
+ * The image field's image URL with Imgix URL parameters (if given).
26
+ */
27
+ src: string;
27
28
 
28
- /**
29
- * A width-based `srcset` attribute value for the image field's image with
30
- * Imgix URL parameters (if given).
31
- */
32
- srcset: string;
33
- }
34
- : null;
29
+ /**
30
+ * A width-based `srcset` attribute value for the image field's image
31
+ * with Imgix URL parameters (if given).
32
+ */
33
+ srcset: string;
34
+ }
35
+ : null;
35
36
 
36
37
  /**
37
38
  * Configuration for `asImageWidthSrcSet()`.
@@ -130,11 +131,11 @@ export const asImageWidthSrcSet = <
130
131
  widths: [thumbnail.dimensions.width],
131
132
  });
132
133
  }),
133
- ].join(", ")
134
+ ].join(", ")
134
135
  : buildWidthSrcSet(field.url, {
135
136
  ...imgixParams,
136
137
  widths,
137
- }),
138
+ }),
138
139
  } as AsImageWidthSrcSetReturnType<Field>;
139
140
  } else {
140
141
  return null as AsImageWidthSrcSetReturnType<Field>;
@@ -58,12 +58,12 @@ type AsLinkAttrsReturnType<
58
58
  | undefined;
59
59
  target?: string;
60
60
  rel?: string;
61
- }
61
+ }
62
62
  : {
63
63
  href?: undefined;
64
64
  target?: undefined;
65
65
  rel?: undefined;
66
- };
66
+ };
67
67
 
68
68
  /**
69
69
  * Resolves any type of link field or Prismic document to a set of link
@@ -120,8 +120,8 @@ export const asLinkAttrs = <
120
120
  const rel = config.rel
121
121
  ? config.rel({ href, isExternal, target })
122
122
  : isExternal
123
- ? "noreferrer"
124
- : undefined;
123
+ ? "noreferrer"
124
+ : undefined;
125
125
 
126
126
  return {
127
127
  href,
@@ -22,8 +22,8 @@ type AnyFunction = (...args: any[]) => any;
22
22
  type ExtractSliceType<TSlice extends SliceLike> = TSlice extends SliceLikeRestV2
23
23
  ? TSlice["slice_type"]
24
24
  : TSlice extends SliceLikeGraphQL
25
- ? TSlice["type"]
26
- : never;
25
+ ? TSlice["type"]
26
+ : never;
27
27
 
28
28
  /**
29
29
  * The minimum required properties to represent a Prismic Slice from the Prismic
@@ -160,13 +160,14 @@ export type SliceMapper<
160
160
  type ResolveLazySliceMapperModule<
161
161
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
162
162
  TSliceMapper extends SliceMapper<any, any> | LazyModule<SliceMapper>,
163
- > = TSliceMapper extends LazyModule<SliceMapper>
164
- ? Awaited<ReturnType<TSliceMapper>> extends {
165
- default: unknown;
166
- }
167
- ? Awaited<ReturnType<TSliceMapper>>["default"]
168
- : Awaited<ReturnType<TSliceMapper>>
169
- : TSliceMapper;
163
+ > =
164
+ TSliceMapper extends LazyModule<SliceMapper>
165
+ ? Awaited<ReturnType<TSliceMapper>> extends {
166
+ default: unknown;
167
+ }
168
+ ? Awaited<ReturnType<TSliceMapper>>["default"]
169
+ : Awaited<ReturnType<TSliceMapper>>
170
+ : TSliceMapper;
170
171
 
171
172
  /**
172
173
  * Transforms a Slice into its mapped version.
@@ -194,18 +195,18 @@ type MapSliceLike<
194
195
  : TSliceLike
195
196
  : TSliceLike
196
197
  : TSliceLike extends SliceLikeGraphQL
197
- ? TSliceLike["type"] extends keyof TSliceMappers
198
- ? TSliceMappers[TSliceLike["type"]] extends AnyFunction
199
- ? SliceLikeGraphQL<TSliceLike["type"]> &
200
- MappedSliceLike &
201
- Awaited<
202
- ReturnType<
203
- ResolveLazySliceMapperModule<TSliceMappers[TSliceLike["type"]]>
198
+ ? TSliceLike["type"] extends keyof TSliceMappers
199
+ ? TSliceMappers[TSliceLike["type"]] extends AnyFunction
200
+ ? SliceLikeGraphQL<TSliceLike["type"]> &
201
+ MappedSliceLike &
202
+ Awaited<
203
+ ReturnType<
204
+ ResolveLazySliceMapperModule<TSliceMappers[TSliceLike["type"]]>
205
+ >
204
206
  >
205
- >
207
+ : TSliceLike
206
208
  : TSliceLike
207
- : TSliceLike
208
- : never;
209
+ : never;
209
210
 
210
211
  /**
211
212
  * Transforms a Slice Zone using a set of mapping functions, one for each type
@@ -0,0 +1,121 @@
1
+ import { Element } from "hast";
2
+ import rehypeParse from "rehype-parse";
3
+ import { unified } from "unified";
4
+
5
+ import { RTPartialInlineNode } from "../lib/RichTextFieldBuilder";
6
+ import { RehypeRichTextConfig, rehypeRichText } from "../lib/rehypeRichText";
7
+
8
+ import {
9
+ RTInlineNode,
10
+ RTNode,
11
+ RichTextField,
12
+ RichTextNodeTypes,
13
+ } from "../types/value/richText";
14
+
15
+ // Used for TSDocs only.
16
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
17
+ import type { HTMLRichTextMapSerializer, asHTML } from "./asHTML";
18
+
19
+ /**
20
+ * A shorthand definition for {@link RichTextHTMLMapSerializer} rich text node
21
+ * types.
22
+ *
23
+ * @remarks
24
+ * The `label` rich text node type is not available as is. Use an object
25
+ * containing your label name to convert to label nodes instead. For example:
26
+ * `u: { label: "underline" }`
27
+ * @remarks
28
+ * The `span` rich text node type is not available as it is not relevant in the
29
+ * context of going from HTML to Prismic rich text.
30
+ */
31
+ export type RichTextHTMLMapSerializerShorthand =
32
+ | Exclude<RichTextNodeTypes, "label" | "span">
33
+ | { label: string };
34
+
35
+ /**
36
+ * The payload provided to a {@link RichTextHTMLMapSerializerFunction}.
37
+ */
38
+ type RichTextHTMLMapSerializerFunctionPayload = {
39
+ /**
40
+ * The hast {@link Element} node to serialize.
41
+ */
42
+ node: Element;
43
+
44
+ /**
45
+ * Additional context information to help with the serialization.
46
+ */
47
+ context: {
48
+ /**
49
+ * The list type of the last list node encountered if any.
50
+ */
51
+ listType?: "group-list-item" | "group-o-list-item";
52
+ };
53
+ };
54
+
55
+ /**
56
+ * Serializes a hast {@link Element} node to a
57
+ * {@link RichTextHTMLMapSerializerShorthand} or a rich text node.
58
+ *
59
+ * @remarks
60
+ * Serializing to a rich text node directly is not recommended and is only
61
+ * available as an escape hatch. Prefer returning a
62
+ * {@link RichTextHTMLMapSerializerShorthand} instead.
63
+ */
64
+ export type RichTextHTMLMapSerializerFunction = (
65
+ payload: RichTextHTMLMapSerializerFunctionPayload,
66
+ ) =>
67
+ | RichTextHTMLMapSerializerShorthand
68
+ | RTNode
69
+ | RTInlineNode
70
+ | RTPartialInlineNode
71
+ | undefined;
72
+
73
+ /**
74
+ * Serializes a hast {@link Element} node matching the given HTML tag name or CSS
75
+ * selector to a Prismic rich text node.
76
+ *
77
+ * @remarks
78
+ * This serializer is used to serialize HTML to Prismic rich text. When
79
+ * serializing Prismic rich text to HTML with {@link asHTML}, use the
80
+ * {@link HTMLRichTextMapSerializer} type instead.
81
+ */
82
+ export type RichTextHTMLMapSerializer = Record<
83
+ string,
84
+ RichTextHTMLMapSerializerShorthand | RichTextHTMLMapSerializerFunction
85
+ >;
86
+
87
+ /**
88
+ * Configuration that determines the output of {@link htmlAsRichText}.
89
+ */
90
+ export type HTMLAsRichTextConfig = RehypeRichTextConfig;
91
+
92
+ /**
93
+ * The return type of {@link htmlAsRichText}.
94
+ */
95
+ type HTMLAsRichTextReturnType = {
96
+ result: RichTextField;
97
+ warnings: string[];
98
+ };
99
+
100
+ /**
101
+ * Converts an HTML string to a rich text field.
102
+ *
103
+ * @param html - An HTML string.
104
+ * @param config - Configuration that determines the output the function.
105
+ *
106
+ * @returns `html` as rich text.
107
+ *
108
+ * @experimental Names and implementations may change in the future.
109
+ * `unstable_htmlAsRichText()` does not follow SemVer.
110
+ */
111
+ export const unstable_htmlAsRichText = (
112
+ html: string,
113
+ config?: HTMLAsRichTextConfig,
114
+ ): HTMLAsRichTextReturnType => {
115
+ const { result, messages } = unified()
116
+ .use(rehypeParse, { emitParseErrors: true, missingDoctype: 0 })
117
+ .use(rehypeRichText, config)
118
+ .processSync(html);
119
+
120
+ return { result, warnings: messages.map((message) => message.toString()) };
121
+ };
@@ -0,0 +1,52 @@
1
+ import remarkParse from "remark-parse";
2
+ import remarkRehype from "remark-rehype";
3
+ import { unified } from "unified";
4
+
5
+ import { RehypeRichTextConfig, rehypeRichText } from "../lib/rehypeRichText";
6
+
7
+ import { RichTextField } from "../types/value/richText";
8
+
9
+ // Used for TSDocs only.
10
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
11
+ import type { unstable_htmlAsRichText } from "./unstable_htmlAsRichText";
12
+
13
+ /**
14
+ * Configuration that determines the output of {@link markdownAsRichText}.
15
+ */
16
+ export type MarkdownAsRichTextConfig = RehypeRichTextConfig;
17
+
18
+ /**
19
+ * The return type of {@link markdownAsRichText}.
20
+ */
21
+ type MarkdownAsRichTextReturnType = {
22
+ result: RichTextField;
23
+ warnings: string[];
24
+ };
25
+
26
+ /**
27
+ * Converts a markdown string to a rich text field.
28
+ *
29
+ * @remarks
30
+ * To convert markdown to a rich text field, this function first converts it to
31
+ * HTML. It's essentially a sugar above {@link unstable_htmlAsRichText}.
32
+ *
33
+ * @param markdown - A markdown string.
34
+ * @param config - Configuration that determines the output of the function.
35
+ *
36
+ * @returns `markdown` as rich text.
37
+ *
38
+ * @experimental Names and implementations may change in the future.
39
+ * `unstable_markdownAsRichText()` does not follow SemVer.
40
+ */
41
+ export const unstable_markdownAsRichText = (
42
+ markdown: string,
43
+ config?: MarkdownAsRichTextConfig,
44
+ ): MarkdownAsRichTextReturnType => {
45
+ const { result, messages } = unified()
46
+ .use(remarkParse)
47
+ .use(remarkRehype)
48
+ .use(rehypeRichText, config)
49
+ .processSync(markdown);
50
+
51
+ return { result, warnings: messages.map((message) => message.toString()) };
52
+ };
package/src/index.ts CHANGED
@@ -80,6 +80,8 @@ export { mapSliceZone, unstable_mapSliceZone };
80
80
 
81
81
  // Conversion helper.
82
82
  export { documentToLinkField } from "./helpers/documentToLinkField";
83
+ export { unstable_htmlAsRichText } from "./helpers/unstable_htmlAsRichText";
84
+ export { unstable_markdownAsRichText } from "./helpers/unstable_markdownAsRichText";
83
85
 
84
86
  export type { LinkResolverFunction } from "./helpers/asLink";
85
87
  export type { AsLinkAttrsConfig } from "./helpers/asLinkAttrs";
@@ -101,10 +103,13 @@ export type {
101
103
  };
102
104
  export type { HTMLRichTextSerializer } from "./helpers/asHTML";
103
105
 
106
+ export type { RichTextHTMLMapSerializer } from "./helpers/unstable_htmlAsRichText";
107
+
104
108
  //=============================================================================
105
109
  // Errors - Custom errors for Prismic APIs.
106
110
  //=============================================================================
107
111
 
112
+ // Client Errors
108
113
  export { PrismicError } from "./errors/PrismicError";
109
114
  export { ForbiddenError } from "./errors/ForbiddenError";
110
115
  export { NotFoundError } from "./errors/NotFoundError";
@@ -114,6 +119,10 @@ export { PreviewTokenExpiredError } from "./errors/PreviewTokenExpired";
114
119
  export { ParsingError } from "./errors/ParsingError";
115
120
  export { RepositoryNotFoundError } from "./errors/RepositoryNotFoundError";
116
121
 
122
+ // Rich Text Errors
123
+ export { PrismicRichTextError } from "./errors/PrismicRichTextError";
124
+ export { PrismicRichTextSerializerError } from "./errors/PrismicRichTextSerializerError";
125
+
117
126
  //=============================================================================
118
127
  // Types - Types representing Prismic content, models, and API payloads.
119
128
  //=============================================================================
@@ -171,6 +180,7 @@ export type {
171
180
  RTBlockNode,
172
181
  RTInlineNode,
173
182
  RTAnyNode,
183
+ RichTextNodeTypes,
174
184
  } from "./types/value/richText";
175
185
  export type { TitleField } from "./types/value/title";
176
186
 
@@ -0,0 +1,164 @@
1
+ import {
2
+ RTInlineNode,
3
+ RTLinkNode,
4
+ RTNode,
5
+ RTTextNode,
6
+ RichTextField,
7
+ } from "../types/value/richText";
8
+
9
+ import { PrismicRichTextError } from "../errors/PrismicRichTextError";
10
+
11
+ /**
12
+ * Omits keys from a type, distributing the operation over a union.
13
+ *
14
+ * Taken from the `type-fest` package.
15
+ *
16
+ * @see https://github.com/sindresorhus/type-fest/blob/8a45ba048767aaffcebc7d190172d814a739feb0/source/distributed-omit.d.ts
17
+ */
18
+ type DistributedOmit<
19
+ ObjectType,
20
+ KeyType extends keyof ObjectType,
21
+ > = ObjectType extends unknown ? Omit<ObjectType, KeyType> : never;
22
+
23
+ /**
24
+ * An inline node without its `start` and `end` properties.
25
+ */
26
+ export type RTPartialInlineNode = DistributedOmit<
27
+ RTInlineNode,
28
+ "start" | "end"
29
+ >;
30
+
31
+ export class RichTextFieldBuilder {
32
+ #nodes: RTNode[] = [];
33
+
34
+ get #last(): RTNode | undefined {
35
+ return this.#nodes[this.#nodes.length - 1];
36
+ }
37
+
38
+ appendNode(node: RTNode): void {
39
+ this.cleanupLast();
40
+
41
+ this.#nodes.push(node);
42
+ }
43
+
44
+ appendTextNode(
45
+ type: RTTextNode["type"],
46
+ direction: "ltr" | "rtl" = "ltr",
47
+ ): void {
48
+ this.appendNode({
49
+ type,
50
+ text: "",
51
+ spans: [],
52
+ direction,
53
+ });
54
+ }
55
+
56
+ appendSpan(span: RTInlineNode): void;
57
+ appendSpan(partialSpan: RTPartialInlineNode, length: number): void;
58
+ appendSpan(
59
+ spanOrPartialSpan: RTInlineNode | RTPartialInlineNode,
60
+ length?: number,
61
+ ): void {
62
+ if (!this.isTextNode(this.#last)) {
63
+ throw new PrismicRichTextError("Cannot add span to non-text last node");
64
+ }
65
+
66
+ let span: RTInlineNode;
67
+ if ("start" in spanOrPartialSpan && "end" in spanOrPartialSpan) {
68
+ span = spanOrPartialSpan;
69
+ } else {
70
+ const lastLength = this.#last.text.length;
71
+
72
+ span = {
73
+ ...spanOrPartialSpan,
74
+ start: lastLength,
75
+ end: lastLength + length!,
76
+ };
77
+ }
78
+
79
+ let lastIdenticalSpanIndex = -1;
80
+ for (let i = this.#last.spans.length - 1; i >= 0; i--) {
81
+ const lastSpan = this.#last.spans[i];
82
+
83
+ if (span.type === "strong" || span.type === "em") {
84
+ if (lastSpan.type === span.type) {
85
+ lastIdenticalSpanIndex = i;
86
+ break;
87
+ }
88
+ } else if (span.type === "label") {
89
+ if (
90
+ lastSpan.type === "label" &&
91
+ lastSpan.data.label === span.data.label
92
+ ) {
93
+ lastIdenticalSpanIndex = i;
94
+ break;
95
+ }
96
+ } else if (span.type === "hyperlink") {
97
+ if (lastSpan.type === "hyperlink") {
98
+ // Check that all data fields are the same. Since it's not a
99
+ // deep equal operation, this doesn't guarantee a perfect
100
+ // match with content relationship.
101
+ const isSameLink = (
102
+ Object.entries(span.data) as [keyof RTLinkNode["data"], unknown][]
103
+ ).every(([key, value]) => lastSpan.data[key] === value);
104
+
105
+ if (isSameLink) {
106
+ lastIdenticalSpanIndex = i;
107
+ break;
108
+ }
109
+ }
110
+ }
111
+ }
112
+
113
+ // Prefer to extend the last span of the same type end
114
+ // position if it ends at the start of the new span.
115
+ if (this.#last.spans[lastIdenticalSpanIndex]?.end === span.start) {
116
+ this.#last.spans[lastIdenticalSpanIndex].end = span.end;
117
+ } else {
118
+ this.#last.spans.push(span);
119
+ }
120
+ }
121
+
122
+ appendText(text: string): void {
123
+ if (!this.isTextNode(this.#last)) {
124
+ throw new PrismicRichTextError(
125
+ "Cannot append text to non-text last node",
126
+ );
127
+ }
128
+
129
+ if (this.#last.text) {
130
+ this.#last.text += text;
131
+ } else {
132
+ this.#last.text = text.trimStart();
133
+ }
134
+ }
135
+
136
+ build(): RichTextField {
137
+ // Ensure that the last text node is trimmed.
138
+ this.cleanupLast();
139
+
140
+ // Because `RichTextField` is defined as a non-empty
141
+ // array, we have to cast `RTNode[]` to `RichTextField`.
142
+ return this.#nodes as RichTextField;
143
+ }
144
+
145
+ /**
146
+ * Cleans up the current last node.
147
+ */
148
+ private cleanupLast(): void {
149
+ if (this.isTextNode(this.#last)) {
150
+ this.#last.text = this.#last.text.trimEnd();
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Determines if a node is a text node.
156
+ *
157
+ * @param node - rich text node to check.
158
+ *
159
+ * @returns `true` if `node` is a text node, `false` otherwise.
160
+ */
161
+ private isTextNode(node?: RTNode): node is RTTextNode {
162
+ return !!node && node.type !== "image" && node.type !== "embed";
163
+ }
164
+ }
@@ -0,0 +1,159 @@
1
+ import { CustomTypeModelRichTextField } from "../types/model/richText";
2
+ import { LinkType } from "../types/value/link";
3
+ import {
4
+ RTImageNode,
5
+ RTNode,
6
+ RTTextNode,
7
+ RichTextField,
8
+ RichTextNodeType,
9
+ RichTextNodeTypes,
10
+ } from "../types/value/richText";
11
+ import { TitleField } from "../types/value/title";
12
+
13
+ /**
14
+ * Get allowed nodes types from a rich text or title field custom type model.
15
+ *
16
+ * @param model - A rich text or title field custom type model.
17
+ *
18
+ * @returns An array of allowed nodes types.
19
+ */
20
+ const getAllowedNodeTypes = (
21
+ model: CustomTypeModelRichTextField,
22
+ ): RichTextNodeTypes[] => {
23
+ const allowedNodeTypes: RichTextNodeTypes[] = []; // An empty array means no nodes are allowed by default.
24
+
25
+ if (model.config) {
26
+ if ("multi" in model.config && model.config.multi) {
27
+ allowedNodeTypes.push(
28
+ ...(model.config.multi.split(",") as RichTextNodeTypes[]),
29
+ );
30
+ } else if ("single" in model.config && model.config.single) {
31
+ allowedNodeTypes.push(
32
+ ...(model.config.single.split(",") as RichTextNodeTypes[]),
33
+ );
34
+ }
35
+
36
+ if (model.config.labels?.length) {
37
+ allowedNodeTypes.push("label");
38
+ }
39
+ }
40
+
41
+ return allowedNodeTypes;
42
+ };
43
+
44
+ /**
45
+ * Filter an image node based on given model.
46
+ *
47
+ * @param node - An image node to filter.
48
+ * @param model - A rich text or title field custom type model.
49
+ *
50
+ * @returns A filtered image node based on the given model.
51
+ */
52
+ const filterImageNode = (
53
+ node: RTImageNode,
54
+ model: CustomTypeModelRichTextField,
55
+ ): RTImageNode => {
56
+ if (
57
+ !model.config?.allowTargetBlank &&
58
+ node.linkTo?.link_type === LinkType.Web
59
+ ) {
60
+ return {
61
+ ...node,
62
+ linkTo: {
63
+ ...node.linkTo,
64
+ target: undefined,
65
+ },
66
+ };
67
+ }
68
+
69
+ return node;
70
+ };
71
+
72
+ /**
73
+ * Filter a text node based on given model.
74
+ *
75
+ * @param node - A text node to filter.
76
+ * @param model - A rich text or title field custom type model.
77
+ * @param allowedNodeTypes - An array of allowed nodes types.
78
+ *
79
+ * @returns A filtered text node based on the given model.
80
+ */
81
+ const filterTextNode = (
82
+ node: RTTextNode,
83
+ model: CustomTypeModelRichTextField,
84
+ allowedNodeTypes: RichTextNodeTypes[],
85
+ ): RTTextNode => {
86
+ const filteredNode: RTTextNode = {
87
+ ...node,
88
+ spans: [],
89
+ };
90
+
91
+ for (let i = 0; i < node.spans.length; i++) {
92
+ const span = node.spans[i];
93
+
94
+ if (allowedNodeTypes.includes(span.type)) {
95
+ if (span.type === RichTextNodeType.hyperlink) {
96
+ if (
97
+ !model.config?.allowTargetBlank &&
98
+ span.data.link_type === LinkType.Web
99
+ ) {
100
+ filteredNode.spans.push({
101
+ ...span,
102
+ data: {
103
+ ...span.data,
104
+ target: undefined,
105
+ },
106
+ });
107
+ } else {
108
+ filteredNode.spans.push(span);
109
+ }
110
+ } else if (span.type === RichTextNodeType.label) {
111
+ if (model.config?.labels?.includes(span.data.label)) {
112
+ filteredNode.spans.push(span);
113
+ }
114
+ } else {
115
+ filteredNode.spans.push(span);
116
+ }
117
+ }
118
+ }
119
+
120
+ return filteredNode;
121
+ };
122
+
123
+ /**
124
+ * Filter a rich text field based on given model.
125
+ *
126
+ * @param richTextField - A rich text or title field from Prismic.
127
+ * @param model - A rich text or title field custom type model.
128
+ *
129
+ * @returns A rich text or title field filtered based on the given model.
130
+ */
131
+ export const filterRichTextField = <Field extends RichTextField | TitleField>(
132
+ richTextField: Field,
133
+ model: CustomTypeModelRichTextField,
134
+ ): Field => {
135
+ const nodes: RTNode[] = [];
136
+
137
+ const allowedNodeTypes = getAllowedNodeTypes(model);
138
+
139
+ for (
140
+ let i = 0;
141
+ // Only process the first node if it's a "single" node rich text type
142
+ i < (model.config && "multi" in model.config ? richTextField.length : 1);
143
+ i++
144
+ ) {
145
+ const node = richTextField[i];
146
+
147
+ if (allowedNodeTypes.includes(node.type)) {
148
+ if (node.type === RichTextNodeType.image) {
149
+ nodes.push(filterImageNode(node, model));
150
+ } else if (node.type === RichTextNodeType.embed) {
151
+ nodes.push(node);
152
+ } else {
153
+ nodes.push(filterTextNode(node, model, allowedNodeTypes));
154
+ }
155
+ }
156
+ }
157
+
158
+ return nodes as Field;
159
+ };