@btst/plugin-cms 0.0.0-stage → 1.0.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 (204) hide show
  1. package/LICENSE.md +17 -0
  2. package/dist/api/getters.cjs +328 -0
  3. package/dist/api/getters.mjs +314 -0
  4. package/dist/api/index.cjs +29 -0
  5. package/dist/api/index.d.cts +209 -0
  6. package/dist/api/index.d.mts +209 -0
  7. package/dist/api/index.d.ts +209 -0
  8. package/dist/api/index.mjs +7 -0
  9. package/dist/api/lifecycle-migrations.cjs +13 -0
  10. package/dist/api/lifecycle-migrations.mjs +11 -0
  11. package/dist/api/mutations.cjs +59 -0
  12. package/dist/api/mutations.mjs +57 -0
  13. package/dist/api/operations.cjs +1769 -0
  14. package/dist/api/operations.mjs +1762 -0
  15. package/dist/api/plugin.cjs +337 -0
  16. package/dist/api/plugin.mjs +331 -0
  17. package/dist/api/query-key-defs.cjs +44 -0
  18. package/dist/api/query-key-defs.mjs +39 -0
  19. package/dist/api/relations.cjs +76 -0
  20. package/dist/api/relations.mjs +70 -0
  21. package/dist/client/components/forms/content-form.cjs +286 -0
  22. package/dist/client/components/forms/content-form.mjs +284 -0
  23. package/dist/client/components/forms/file-upload.cjs +160 -0
  24. package/dist/client/components/forms/file-upload.mjs +158 -0
  25. package/dist/client/components/forms/relation-field.cjs +237 -0
  26. package/dist/client/components/forms/relation-field.mjs +235 -0
  27. package/dist/client/components/index.cjs +14 -0
  28. package/dist/client/components/index.d.cts +20 -0
  29. package/dist/client/components/index.d.mts +20 -0
  30. package/dist/client/components/index.d.ts +20 -0
  31. package/dist/client/components/index.mjs +10 -0
  32. package/dist/client/components/inverse-relations-panel.cjs +272 -0
  33. package/dist/client/components/inverse-relations-panel.mjs +270 -0
  34. package/dist/client/components/loading/dashboard-skeleton.cjs +18 -0
  35. package/dist/client/components/loading/dashboard-skeleton.mjs +16 -0
  36. package/dist/client/components/loading/editor-skeleton.cjs +32 -0
  37. package/dist/client/components/loading/editor-skeleton.mjs +30 -0
  38. package/dist/client/components/loading/list-skeleton.cjs +32 -0
  39. package/dist/client/components/loading/list-skeleton.mjs +30 -0
  40. package/dist/client/components/pages/404-page.cjs +26 -0
  41. package/dist/client/components/pages/404-page.mjs +24 -0
  42. package/dist/client/components/pages/content-editor-page.cjs +84 -0
  43. package/dist/client/components/pages/content-editor-page.internal.cjs +170 -0
  44. package/dist/client/components/pages/content-editor-page.internal.mjs +168 -0
  45. package/dist/client/components/pages/content-editor-page.mjs +82 -0
  46. package/dist/client/components/pages/content-list-page.cjs +49 -0
  47. package/dist/client/components/pages/content-list-page.internal.cjs +334 -0
  48. package/dist/client/components/pages/content-list-page.internal.mjs +332 -0
  49. package/dist/client/components/pages/content-list-page.mjs +47 -0
  50. package/dist/client/components/pages/dashboard-page.cjs +42 -0
  51. package/dist/client/components/pages/dashboard-page.internal.cjs +102 -0
  52. package/dist/client/components/pages/dashboard-page.internal.mjs +100 -0
  53. package/dist/client/components/pages/dashboard-page.mjs +40 -0
  54. package/dist/client/components/shared/default-error.cjs +17 -0
  55. package/dist/client/components/shared/default-error.mjs +15 -0
  56. package/dist/client/components/shared/empty-state.cjs +16 -0
  57. package/dist/client/components/shared/empty-state.mjs +14 -0
  58. package/dist/client/components/shared/page-wrapper.cjs +29 -0
  59. package/dist/client/components/shared/page-wrapper.mjs +27 -0
  60. package/dist/client/constants.cjs +5 -0
  61. package/dist/client/constants.mjs +3 -0
  62. package/dist/client/hooks/cms-hooks.cjs +300 -0
  63. package/dist/client/hooks/cms-hooks.mjs +280 -0
  64. package/dist/client/hooks/cms-resource.cjs +13 -0
  65. package/dist/client/hooks/cms-resource.mjs +11 -0
  66. package/dist/client/hooks/index.cjs +25 -0
  67. package/dist/client/hooks/index.d.cts +693 -0
  68. package/dist/client/hooks/index.d.mts +693 -0
  69. package/dist/client/hooks/index.d.ts +693 -0
  70. package/dist/client/hooks/index.mjs +1 -0
  71. package/dist/client/index.cjs +15 -0
  72. package/dist/client/index.d.cts +654 -0
  73. package/dist/client/index.d.mts +654 -0
  74. package/dist/client/index.d.ts +654 -0
  75. package/dist/client/index.mjs +3 -0
  76. package/dist/client/overrides.cjs +26 -0
  77. package/dist/client/overrides.mjs +24 -0
  78. package/dist/client/plugin.cjs +316 -0
  79. package/dist/client/plugin.mjs +314 -0
  80. package/dist/client.css +3 -0
  81. package/dist/db.cjs +118 -0
  82. package/dist/db.mjs +116 -0
  83. package/dist/permissions.cjs +46 -0
  84. package/dist/permissions.d.cts +42 -0
  85. package/dist/permissions.d.mts +42 -0
  86. package/dist/permissions.d.ts +42 -0
  87. package/dist/permissions.mjs +44 -0
  88. package/dist/query-keys.cjs +229 -0
  89. package/dist/query-keys.d.cts +8 -0
  90. package/dist/query-keys.d.mts +8 -0
  91. package/dist/query-keys.d.ts +8 -0
  92. package/dist/query-keys.mjs +225 -0
  93. package/dist/schemas.cjs +81 -0
  94. package/dist/schemas.mjs +72 -0
  95. package/dist/shared/plugin-cms.BBshPRkb.d.cts +6 -0
  96. package/dist/shared/plugin-cms.BBshPRkb.d.mts +6 -0
  97. package/dist/shared/plugin-cms.BBshPRkb.d.ts +6 -0
  98. package/dist/shared/plugin-cms.DQLAoogy.d.ts +1749 -0
  99. package/dist/shared/plugin-cms.W4Le8D91.d.mts +1749 -0
  100. package/dist/shared/plugin-cms.c-GeWvTf.d.cts +1749 -0
  101. package/dist/style.css +6 -0
  102. package/dist/types.cjs +2 -0
  103. package/dist/types.d.cts +406 -0
  104. package/dist/types.d.mts +406 -0
  105. package/dist/types.d.ts +406 -0
  106. package/dist/types.mjs +1 -0
  107. package/dist/ui/src/components/accordion.cjs +81 -0
  108. package/dist/ui/src/components/accordion.mjs +62 -0
  109. package/dist/ui/src/components/alert-dialog.cjs +157 -0
  110. package/dist/ui/src/components/alert-dialog.mjs +132 -0
  111. package/dist/ui/src/components/auto-form/common/label.cjs +18 -0
  112. package/dist/ui/src/components/auto-form/common/label.mjs +16 -0
  113. package/dist/ui/src/components/auto-form/common/tooltip.cjs +9 -0
  114. package/dist/ui/src/components/auto-form/common/tooltip.mjs +7 -0
  115. package/dist/ui/src/components/auto-form/config.cjs +40 -0
  116. package/dist/ui/src/components/auto-form/config.mjs +37 -0
  117. package/dist/ui/src/components/auto-form/dependencies.cjs +48 -0
  118. package/dist/ui/src/components/auto-form/dependencies.mjs +46 -0
  119. package/dist/ui/src/components/auto-form/fields/array.cjs +266 -0
  120. package/dist/ui/src/components/auto-form/fields/array.mjs +264 -0
  121. package/dist/ui/src/components/auto-form/fields/checkbox.cjs +38 -0
  122. package/dist/ui/src/components/auto-form/fields/checkbox.mjs +36 -0
  123. package/dist/ui/src/components/auto-form/fields/date.cjs +67 -0
  124. package/dist/ui/src/components/auto-form/fields/date.mjs +65 -0
  125. package/dist/ui/src/components/auto-form/fields/enum.cjs +73 -0
  126. package/dist/ui/src/components/auto-form/fields/enum.mjs +71 -0
  127. package/dist/ui/src/components/auto-form/fields/input.cjs +32 -0
  128. package/dist/ui/src/components/auto-form/fields/input.mjs +30 -0
  129. package/dist/ui/src/components/auto-form/fields/number.cjs +31 -0
  130. package/dist/ui/src/components/auto-form/fields/number.mjs +29 -0
  131. package/dist/ui/src/components/auto-form/fields/object.cjs +233 -0
  132. package/dist/ui/src/components/auto-form/fields/object.mjs +217 -0
  133. package/dist/ui/src/components/auto-form/fields/radio-group.cjs +67 -0
  134. package/dist/ui/src/components/auto-form/fields/radio-group.mjs +65 -0
  135. package/dist/ui/src/components/auto-form/fields/switch.cjs +38 -0
  136. package/dist/ui/src/components/auto-form/fields/switch.mjs +36 -0
  137. package/dist/ui/src/components/auto-form/fields/textarea.cjs +31 -0
  138. package/dist/ui/src/components/auto-form/fields/textarea.mjs +29 -0
  139. package/dist/ui/src/components/auto-form/helpers.cjs +270 -0
  140. package/dist/ui/src/components/auto-form/helpers.mjs +259 -0
  141. package/dist/ui/src/components/auto-form/index.cjs +92 -0
  142. package/dist/ui/src/components/auto-form/index.mjs +86 -0
  143. package/dist/ui/src/components/auto-form/stepped-auto-form.cjs +374 -0
  144. package/dist/ui/src/components/auto-form/stepped-auto-form.mjs +368 -0
  145. package/dist/ui/src/components/auto-form/types.cjs +11 -0
  146. package/dist/ui/src/components/auto-form/types.mjs +9 -0
  147. package/dist/ui/src/components/badge.cjs +42 -0
  148. package/dist/ui/src/components/badge.mjs +39 -0
  149. package/dist/ui/src/components/button.cjs +56 -0
  150. package/dist/ui/src/components/button.mjs +53 -0
  151. package/dist/ui/src/components/calendar.cjs +207 -0
  152. package/dist/ui/src/components/calendar.mjs +190 -0
  153. package/dist/ui/src/components/card.cjs +56 -0
  154. package/dist/ui/src/components/card.mjs +51 -0
  155. package/dist/ui/src/components/checkbox.cjs +48 -0
  156. package/dist/ui/src/components/checkbox.mjs +32 -0
  157. package/dist/ui/src/components/command.cjs +78 -0
  158. package/dist/ui/src/components/command.mjs +73 -0
  159. package/dist/ui/src/components/date-picker.cjs +41 -0
  160. package/dist/ui/src/components/date-picker.mjs +39 -0
  161. package/dist/ui/src/components/dialog.cjs +119 -0
  162. package/dist/ui/src/components/dialog.mjs +97 -0
  163. package/dist/ui/src/components/form.cjs +120 -0
  164. package/dist/ui/src/components/form.mjs +98 -0
  165. package/dist/ui/src/components/input.cjs +23 -0
  166. package/dist/ui/src/components/input.mjs +21 -0
  167. package/dist/ui/src/components/label.cjs +39 -0
  168. package/dist/ui/src/components/label.mjs +23 -0
  169. package/dist/ui/src/components/multi-select.cjs +555 -0
  170. package/dist/ui/src/components/multi-select.mjs +540 -0
  171. package/dist/ui/src/components/page-layout.cjs +25 -0
  172. package/dist/ui/src/components/page-layout.mjs +23 -0
  173. package/dist/ui/src/components/page-wrapper.cjs +20 -0
  174. package/dist/ui/src/components/page-wrapper.mjs +18 -0
  175. package/dist/ui/src/components/popover.cjs +60 -0
  176. package/dist/ui/src/components/popover.mjs +42 -0
  177. package/dist/ui/src/components/radio-group.cjs +62 -0
  178. package/dist/ui/src/components/radio-group.mjs +45 -0
  179. package/dist/ui/src/components/select.cjs +161 -0
  180. package/dist/ui/src/components/select.mjs +139 -0
  181. package/dist/ui/src/components/separator.cjs +43 -0
  182. package/dist/ui/src/components/separator.mjs +27 -0
  183. package/dist/ui/src/components/skeleton.cjs +17 -0
  184. package/dist/ui/src/components/skeleton.mjs +15 -0
  185. package/dist/ui/src/components/stack-attribution.cjs +24 -0
  186. package/dist/ui/src/components/stack-attribution.mjs +22 -0
  187. package/dist/ui/src/components/switch.cjs +48 -0
  188. package/dist/ui/src/components/switch.mjs +32 -0
  189. package/dist/ui/src/components/table.cjs +89 -0
  190. package/dist/ui/src/components/table.mjs +82 -0
  191. package/dist/ui/src/components/textarea.cjs +20 -0
  192. package/dist/ui/src/components/textarea.mjs +18 -0
  193. package/dist/ui/src/hooks/use-debounce.cjs +16 -0
  194. package/dist/ui/src/hooks/use-debounce.mjs +14 -0
  195. package/dist/ui/src/hooks/use-route-lifecycle.cjs +31 -0
  196. package/dist/ui/src/hooks/use-route-lifecycle.mjs +29 -0
  197. package/dist/ui/src/lib/schema-converter.cjs +133 -0
  198. package/dist/ui/src/lib/schema-converter.mjs +127 -0
  199. package/dist/ui/src/lib/utils.cjs +10 -0
  200. package/dist/ui/src/lib/utils.mjs +8 -0
  201. package/dist/utils.cjs +19 -0
  202. package/dist/utils.mjs +12 -0
  203. package/package.json +170 -3
  204. package/README.md +0 -3
@@ -0,0 +1,1762 @@
1
+ import { defineOperation, OperationHttpError } from '@btst/stack/plugins/api';
2
+ import { z } from 'zod';
3
+ import { formSchemaToZod } from '../ui/src/lib/schema-converter.mjs';
4
+ import { cmsPermissions } from '../permissions.mjs';
5
+ import { createListContentQuerySchema, DEFAULT_MAX_PAGE_SIZE, contentReadOptionsSchema } from '../schemas.mjs';
6
+ import { slugify } from '../utils.mjs';
7
+ import { serializeContentType, getAllContentItems, getContentItemBySlug, applyContentReadOptions, serializeContentItemWithType, getContentItemsByRelationForType, validateContentReadOptions, CMSContentSelectionError } from './getters.mjs';
8
+ import { syncRelations, extractRelationFields, isNewRelationValue, isExistingRelationValue } from './relations.mjs';
9
+
10
+ function operationContentType(contentType) {
11
+ return { ...contentType };
12
+ }
13
+ function operationContentItem(item) {
14
+ const {
15
+ parsedData,
16
+ contentType,
17
+ _relations,
18
+ ...serializedItem
19
+ } = item;
20
+ return {
21
+ ...serializedItem,
22
+ parsedData,
23
+ ...contentType ? { contentType: operationContentType(contentType) } : {}
24
+ };
25
+ }
26
+ function operationContentList(result, options) {
27
+ return {
28
+ items: result.items.map(
29
+ (item) => applyContentReadOptions(operationContentItem(item), options)
30
+ ),
31
+ total: result.total,
32
+ ...result.limit !== void 0 ? { limit: result.limit } : {},
33
+ ...result.offset !== void 0 ? { offset: result.offset } : {}
34
+ };
35
+ }
36
+ const JSONValueSchema = z.lazy(
37
+ () => z.union([
38
+ z.string(),
39
+ z.number(),
40
+ z.boolean(),
41
+ z.null(),
42
+ z.array(JSONValueSchema),
43
+ z.record(z.string(), JSONValueSchema)
44
+ ])
45
+ );
46
+ const CMSDataSchema = z.record(
47
+ z.string(),
48
+ JSONValueSchema
49
+ );
50
+ const EmptyInputSchema = z.object({});
51
+ const CMSContentTypeParamsSchema = z.object({
52
+ slug: z.string().min(1)
53
+ });
54
+ const CMSContentItemParamsSchema = z.object({
55
+ typeSlug: z.string().min(1),
56
+ id: z.string().min(1)
57
+ });
58
+ const CMSCreateContentItemBodySchema = z.object({
59
+ slug: z.string().min(1),
60
+ data: CMSDataSchema
61
+ });
62
+ const CMSUpdateContentItemBodySchema = z.object({
63
+ slug: z.string().min(1).optional(),
64
+ data: CMSDataSchema.optional()
65
+ });
66
+ const ListContentTypesInputSchema = EmptyInputSchema;
67
+ const GetContentTypeInputSchema = CMSContentTypeParamsSchema;
68
+ const GetContentItemInputSchema = CMSContentItemParamsSchema.extend(
69
+ contentReadOptionsSchema.shape
70
+ );
71
+ const CreateContentItemInputSchema = z.object({
72
+ typeSlug: z.string().min(1),
73
+ body: CMSCreateContentItemBodySchema
74
+ });
75
+ const UpdateContentItemInputSchema = z.object({
76
+ typeSlug: z.string().min(1),
77
+ id: z.string().min(1),
78
+ body: CMSUpdateContentItemBodySchema
79
+ });
80
+ const DeleteContentItemInputSchema = CMSContentItemParamsSchema;
81
+ class CMSOperationError extends OperationHttpError {
82
+ constructor(statusCode, message, code = "CMS_OPERATION_ERROR", issues) {
83
+ super(statusCode, message, code, issues);
84
+ this.name = "CMSOperationError";
85
+ }
86
+ }
87
+ function validateOperationContentReadOptions(contentType, options) {
88
+ try {
89
+ validateContentReadOptions(contentType, options);
90
+ } catch (error) {
91
+ if (error instanceof CMSContentSelectionError) {
92
+ throw new CMSOperationError(
93
+ 400,
94
+ error.message,
95
+ "INVALID_CONTENT_FIELDS",
96
+ [{ path: ["fields"], message: error.message }]
97
+ );
98
+ }
99
+ throw error;
100
+ }
101
+ }
102
+ function normalizeOperationError(error, fallback) {
103
+ if (error instanceof Error) return error;
104
+ return new Error(typeof error === "string" ? error : fallback, {
105
+ cause: error
106
+ });
107
+ }
108
+ async function runBeforeHook(hook, defaultMessage) {
109
+ if (!hook) return;
110
+ try {
111
+ await hook();
112
+ } catch (error) {
113
+ throw new CMSOperationError(
114
+ 403,
115
+ error instanceof Error ? error.message : defaultMessage,
116
+ "HOOK_DENIED"
117
+ );
118
+ }
119
+ }
120
+ function requestFields(context) {
121
+ return {
122
+ ...context.request ? { request: context.request, headers: context.request.headers } : {},
123
+ ...context.identity ? { userId: context.identity.id } : {}
124
+ };
125
+ }
126
+ function createContext(context) {
127
+ return Object.freeze({
128
+ ...context,
129
+ typeSlug: context.facts.contentType,
130
+ body: context.input.body,
131
+ ...requestFields(context)
132
+ });
133
+ }
134
+ function updateContext(context) {
135
+ return Object.freeze({
136
+ ...context,
137
+ typeSlug: context.facts.contentType,
138
+ params: Object.freeze({
139
+ typeSlug: context.facts.contentType,
140
+ id: context.facts.recordId
141
+ }),
142
+ body: context.input.body,
143
+ ...requestFields(context)
144
+ });
145
+ }
146
+ function deleteContext(context) {
147
+ return Object.freeze({
148
+ ...context,
149
+ typeSlug: context.facts.contentType,
150
+ params: Object.freeze({
151
+ typeSlug: context.facts.contentType,
152
+ id: context.facts.recordId
153
+ }),
154
+ ...requestFields(context)
155
+ });
156
+ }
157
+ function genericContext(context, typeSlug) {
158
+ return Object.freeze({
159
+ ...context,
160
+ ...typeSlug ? { typeSlug } : {},
161
+ ...requestFields(context)
162
+ });
163
+ }
164
+ function operationErrorContext(context, error) {
165
+ return Object.freeze({ ...context, error });
166
+ }
167
+ function getContentTypeZodSchema(contentType) {
168
+ return formSchemaToZod(JSON.parse(contentType.jsonSchema));
169
+ }
170
+ async function getContentTypeOrThrow(adapter, ensureSynced, slug, message = "Content type not found") {
171
+ await ensureSynced();
172
+ const contentType = await adapter.findOne({
173
+ model: "contentType",
174
+ where: [{ field: "slug", value: slug, operator: "eq" }]
175
+ });
176
+ if (!contentType) {
177
+ throw new CMSOperationError(404, message, "CONTENT_TYPE_NOT_FOUND");
178
+ }
179
+ return contentType;
180
+ }
181
+ async function getRecordOrThrow(adapter, ensureSynced, typeSlug, id) {
182
+ await ensureSynced();
183
+ const item = await adapter.findOne({
184
+ model: "contentItem",
185
+ where: [{ field: "id", value: id, operator: "eq" }],
186
+ join: { contentType: true }
187
+ });
188
+ if (!item || item.contentType?.slug !== typeSlug) {
189
+ throw new CMSOperationError(
190
+ 404,
191
+ "Content item not found",
192
+ "RECORD_NOT_FOUND"
193
+ );
194
+ }
195
+ return item;
196
+ }
197
+ function recordFacts(item) {
198
+ if (!item.contentType) {
199
+ throw new CMSOperationError(
200
+ 500,
201
+ "Content item is missing its content type",
202
+ "CONTENT_TYPE_JOIN_MISSING"
203
+ );
204
+ }
205
+ return {
206
+ contentType: item.contentType.slug,
207
+ scope: "record",
208
+ recordId: item.id,
209
+ ...item.authorId ? { authorId: item.authorId } : {}
210
+ };
211
+ }
212
+ function collectionFacts(contentType) {
213
+ return { contentType, scope: "collection" };
214
+ }
215
+ function assertRecordFacts(item, facts) {
216
+ if (!facts.recordId || item.id !== facts.recordId || item.contentType?.slug !== facts.contentType || (item.authorId ?? void 0) !== facts.authorId) {
217
+ throw staleRecordError();
218
+ }
219
+ }
220
+ const AFFECTED_ROW_KEYS = [
221
+ "rowCount",
222
+ "affectedRows",
223
+ "rowsAffected",
224
+ "changes",
225
+ "numUpdatedRows"
226
+ ];
227
+ function hasPositiveCount(value) {
228
+ if (typeof value === "number") return Number.isFinite(value) && value > 0;
229
+ if (typeof value === "bigint") return value > 0n;
230
+ return false;
231
+ }
232
+ function didUpdateContentItem(result, expectedId) {
233
+ if (typeof result === "number" || typeof result === "bigint") {
234
+ return hasPositiveCount(result);
235
+ }
236
+ if (!result || typeof result !== "object") return false;
237
+ const record = result;
238
+ if ("count" in record) return hasPositiveCount(record.count);
239
+ if (Array.isArray(result)) {
240
+ return result.length > 0 && didUpdateContentItem(result[0], expectedId);
241
+ }
242
+ for (const key of AFFECTED_ROW_KEYS) {
243
+ if (key in record) return hasPositiveCount(record[key]);
244
+ }
245
+ if ("meta" in record) {
246
+ const meta = record.meta;
247
+ return Boolean(
248
+ meta && typeof meta === "object" && "changes" in meta && hasPositiveCount(meta.changes)
249
+ );
250
+ }
251
+ return record.id === expectedId;
252
+ }
253
+ function staleRecordError() {
254
+ return new CMSOperationError(
255
+ 409,
256
+ "Content item changed while authorization was being evaluated. Retry the operation.",
257
+ "RECORD_STATE_CHANGED"
258
+ );
259
+ }
260
+ function assertRecordSnapshot(current, expected) {
261
+ if (current.id !== expected.id || current.contentTypeId !== expected.contentTypeId || current.contentType?.slug !== expected.contentType?.slug || (current.authorId ?? void 0) !== (expected.authorId ?? void 0) || current.slug !== expected.slug || current.data !== expected.data || current.updatedAt.getTime() !== expected.updatedAt.getTime()) {
262
+ throw staleRecordError();
263
+ }
264
+ }
265
+ async function planRelatedItem(adapter, targetContentType, slug, data, authorId) {
266
+ const validation = getContentTypeZodSchema(targetContentType).safeParse(data);
267
+ if (!validation.success) {
268
+ throw new CMSOperationError(
269
+ 400,
270
+ `Validation failed for new ${targetContentType.slug}`,
271
+ "RELATED_RECORD_VALIDATION_FAILED",
272
+ validation.error.issues
273
+ );
274
+ }
275
+ const existing = await adapter.findOne({
276
+ model: "contentItem",
277
+ where: [
278
+ {
279
+ field: "contentTypeId",
280
+ value: targetContentType.id,
281
+ operator: "eq"
282
+ },
283
+ { field: "slug", value: slug, operator: "eq" }
284
+ ]
285
+ });
286
+ if (existing) {
287
+ throw relatedRecordSlugConflictError();
288
+ }
289
+ const now = /* @__PURE__ */ new Date();
290
+ return {
291
+ id: globalThis.crypto.randomUUID(),
292
+ contentTypeId: targetContentType.id,
293
+ slug,
294
+ data: JSON.stringify(validation.data),
295
+ ...authorId ? { authorId } : {},
296
+ createdAt: now,
297
+ updatedAt: now
298
+ };
299
+ }
300
+ function relatedRecordSlugConflictError() {
301
+ return new CMSOperationError(
302
+ 409,
303
+ "Inline related record could not be created because its slug is unavailable.",
304
+ "RELATED_RECORD_SLUG_CONFLICT"
305
+ );
306
+ }
307
+ async function planRelationsInData(adapter, contentType, data, ensureSynced, authorId) {
308
+ const relationFields = extractRelationFields(contentType);
309
+ const processedData = { ...data };
310
+ const relationIds = {};
311
+ const newItems = [];
312
+ const plannedSlugs = /* @__PURE__ */ new Set();
313
+ for (const [fieldName, relationConfig] of Object.entries(relationFields)) {
314
+ if (!(fieldName in data)) continue;
315
+ const fieldValue = data[fieldName];
316
+ if (!fieldValue) {
317
+ relationIds[fieldName] = [];
318
+ continue;
319
+ }
320
+ const targetContentType = await getContentTypeOrThrow(
321
+ adapter,
322
+ ensureSynced,
323
+ relationConfig.targetType,
324
+ `Target content type "${relationConfig.targetType}" not found for relation field "${fieldName}"`
325
+ );
326
+ const ids = [];
327
+ if (relationConfig.type === "belongsTo") {
328
+ const value = fieldValue;
329
+ if (isNewRelationValue(value)) {
330
+ const item = await resolvePlannedRelatedItem(
331
+ adapter,
332
+ targetContentType,
333
+ value.data,
334
+ authorId,
335
+ plannedSlugs,
336
+ newItems
337
+ );
338
+ ids.push(item.id);
339
+ processedData[fieldName] = { id: item.id };
340
+ } else if (isExistingRelationValue(value)) {
341
+ ids.push(value.id);
342
+ }
343
+ } else {
344
+ const values = Array.isArray(fieldValue) ? fieldValue : [];
345
+ const processedValues = [];
346
+ for (const value of values) {
347
+ if (isNewRelationValue(value)) {
348
+ const item = await resolvePlannedRelatedItem(
349
+ adapter,
350
+ targetContentType,
351
+ value.data,
352
+ authorId,
353
+ plannedSlugs,
354
+ newItems
355
+ );
356
+ ids.push(item.id);
357
+ processedValues.push({ id: item.id });
358
+ } else if (isExistingRelationValue(value)) {
359
+ ids.push(value.id);
360
+ processedValues.push({ id: value.id });
361
+ }
362
+ }
363
+ processedData[fieldName] = processedValues;
364
+ }
365
+ relationIds[fieldName] = ids;
366
+ }
367
+ return { processedData, relationIds, newItems };
368
+ }
369
+ async function resolvePlannedRelatedItem(adapter, targetContentType, data, authorId, plannedSlugs, newItems) {
370
+ const slug = slugify(
371
+ data.slug || data.name || data.title || `item-${Date.now()}`
372
+ );
373
+ const key = `${targetContentType.id}\0${slug}`;
374
+ if (plannedSlugs.has(key)) throw relatedRecordSlugConflictError();
375
+ const planned = await planRelatedItem(
376
+ adapter,
377
+ targetContentType,
378
+ slug,
379
+ data,
380
+ authorId
381
+ );
382
+ plannedSlugs.add(key);
383
+ newItems.push(planned);
384
+ return planned;
385
+ }
386
+ async function applyRelationWritePlan(adapter, plan) {
387
+ for (const item of plan.newItems) {
388
+ const existing = await adapter.findOne({
389
+ model: "contentItem",
390
+ where: [
391
+ {
392
+ field: "contentTypeId",
393
+ value: item.contentTypeId,
394
+ operator: "eq"
395
+ },
396
+ { field: "slug", value: item.slug, operator: "eq" }
397
+ ]
398
+ });
399
+ if (existing) throw staleRecordError();
400
+ await adapter.create({
401
+ model: "contentItem",
402
+ data: item
403
+ });
404
+ }
405
+ }
406
+ function relationFilterSnapshot(sourceContentType, fieldName, relation, targetContentType) {
407
+ return JSON.stringify([
408
+ sourceContentType.id,
409
+ sourceContentType.slug,
410
+ fieldName,
411
+ relation.type,
412
+ targetContentType.id,
413
+ targetContentType.slug
414
+ ]);
415
+ }
416
+ async function deriveRelationFilterAuthorization(adapter, ensureSynced, sourceContentType, fieldName, targetId) {
417
+ const relation = extractRelationFields(sourceContentType)[fieldName];
418
+ if (!relation) {
419
+ throw new CMSOperationError(
420
+ 404,
421
+ `Relation field "${fieldName}" was not found on content type "${sourceContentType.slug}".`,
422
+ "RELATION_FIELD_NOT_FOUND"
423
+ );
424
+ }
425
+ const targetContentType = await getContentTypeOrThrow(
426
+ adapter,
427
+ ensureSynced,
428
+ relation.targetType,
429
+ `Target content type "${relation.targetType}" not found for relation field "${fieldName}"`
430
+ );
431
+ const target = await getRecordOrThrow(
432
+ adapter,
433
+ ensureSynced,
434
+ targetContentType.slug,
435
+ targetId
436
+ );
437
+ const targetFacts = recordFacts(target);
438
+ return {
439
+ permission: cmsPermissions.record.read(targetFacts),
440
+ snapshot: relationFilterSnapshot(
441
+ sourceContentType,
442
+ fieldName,
443
+ relation,
444
+ targetContentType
445
+ ),
446
+ targetFacts
447
+ };
448
+ }
449
+ function relationTargetSnapshot(facts) {
450
+ return JSON.stringify([
451
+ facts.contentType,
452
+ facts.recordId,
453
+ facts.authorId ?? null
454
+ ]);
455
+ }
456
+ async function deriveRelationWriteAuthorization(adapter, contentType, data, ensureSynced, expectedSchemaSnapshot) {
457
+ const permissions = [];
458
+ const snapshot = [];
459
+ const targets = [];
460
+ const seenCreateTargetTypes = /* @__PURE__ */ new Set();
461
+ const seenReadTargets = /* @__PURE__ */ new Set();
462
+ const resolvedRelations = [];
463
+ for (const [fieldName, relationConfig] of Object.entries(
464
+ extractRelationFields(contentType)
465
+ )) {
466
+ if (!(fieldName in data)) continue;
467
+ const value = data[fieldName];
468
+ const values = relationConfig.type === "belongsTo" ? [value] : Array.isArray(value) ? value : [];
469
+ const targetContentType = await getContentTypeOrThrow(
470
+ adapter,
471
+ ensureSynced,
472
+ relationConfig.targetType,
473
+ `Target content type "${relationConfig.targetType}" not found for relation field "${fieldName}"`
474
+ );
475
+ snapshot.push(
476
+ JSON.stringify([
477
+ fieldName,
478
+ relationConfig.type,
479
+ targetContentType.id,
480
+ targetContentType.slug
481
+ ])
482
+ );
483
+ resolvedRelations.push({ values, targetContentType });
484
+ }
485
+ snapshot.sort();
486
+ if (expectedSchemaSnapshot) {
487
+ assertRelationSchemaSnapshot(expectedSchemaSnapshot, snapshot);
488
+ }
489
+ for (const { values, targetContentType } of resolvedRelations) {
490
+ if (values.some(isNewRelationValue) && !seenCreateTargetTypes.has(targetContentType.slug)) {
491
+ seenCreateTargetTypes.add(targetContentType.slug);
492
+ permissions.push(
493
+ cmsPermissions.record.create({ contentType: targetContentType.slug })
494
+ );
495
+ }
496
+ for (const reference of values) {
497
+ if (isNewRelationValue(reference) || !isExistingRelationValue(reference)) {
498
+ continue;
499
+ }
500
+ const target = await getRecordOrThrow(
501
+ adapter,
502
+ ensureSynced,
503
+ targetContentType.slug,
504
+ reference.id
505
+ );
506
+ const facts = recordFacts(target);
507
+ const targetKey = relationTargetSnapshot(facts);
508
+ if (seenReadTargets.has(targetKey)) continue;
509
+ seenReadTargets.add(targetKey);
510
+ targets.push(facts);
511
+ permissions.push(cmsPermissions.record.read(facts));
512
+ }
513
+ }
514
+ return {
515
+ permissions,
516
+ snapshot,
517
+ targets: targets.sort(
518
+ (left, right) => relationTargetSnapshot(left).localeCompare(relationTargetSnapshot(right))
519
+ )
520
+ };
521
+ }
522
+ function assertRelationSchemaSnapshot(authorized, current) {
523
+ if (JSON.stringify(authorized) !== JSON.stringify(current)) {
524
+ throw relationSchemaChangedError();
525
+ }
526
+ }
527
+ function assertRelationWriteAuthorization(authorized, current) {
528
+ assertRelationSchemaSnapshot(authorized.snapshot, current.snapshot);
529
+ if (JSON.stringify(authorized.targets.map(relationTargetSnapshot)) !== JSON.stringify(current.targets.map(relationTargetSnapshot))) {
530
+ throw staleRecordError();
531
+ }
532
+ }
533
+ function relationSchemaChangedError() {
534
+ return new CMSOperationError(
535
+ 409,
536
+ "Content type relations changed while authorization was being evaluated. Retry the operation.",
537
+ "RELATION_SCHEMA_CHANGED"
538
+ );
539
+ }
540
+ async function getPopulatedRelationSnapshot(adapter, sourceId) {
541
+ const relations = await adapter.findMany({
542
+ model: "contentRelation",
543
+ where: [{ field: "sourceId", value: sourceId, operator: "eq" }]
544
+ });
545
+ const targets = [];
546
+ const seenTargets = /* @__PURE__ */ new Set();
547
+ for (const relation of relations) {
548
+ if (seenTargets.has(relation.targetId)) continue;
549
+ const target = await adapter.findOne({
550
+ model: "contentItem",
551
+ where: [
552
+ { field: "id", value: relation.targetId, operator: "eq" }
553
+ ],
554
+ join: { contentType: true }
555
+ });
556
+ if (!target) continue;
557
+ seenTargets.add(target.id);
558
+ targets.push({
559
+ item: serializeContentItemWithType(target),
560
+ facts: recordFacts(target)
561
+ });
562
+ }
563
+ return {
564
+ relationKeys: relations.map((relation) => `${relation.fieldName}\0${relation.targetId}`).sort(),
565
+ targets: targets.sort(
566
+ (left, right) => (left.facts.recordId ?? "").localeCompare(right.facts.recordId ?? "")
567
+ )
568
+ };
569
+ }
570
+ function assertPopulatedRelationSnapshot(authorized, current) {
571
+ const factsKey = (facts) => JSON.stringify([facts.contentType, facts.recordId, facts.authorId ?? null]);
572
+ if (JSON.stringify(authorized.relationKeys) !== JSON.stringify(current.relationKeys) || JSON.stringify(authorized.targets.map(({ facts }) => factsKey(facts))) !== JSON.stringify(current.targets.map(({ facts }) => factsKey(facts)))) {
573
+ throw new CMSOperationError(
574
+ 409,
575
+ "Related content changed while authorization was being evaluated. Retry the operation.",
576
+ "RECORD_STATE_CHANGED"
577
+ );
578
+ }
579
+ }
580
+ function populatedRelationsFromSnapshot(snapshot) {
581
+ const targetsById = new Map(
582
+ snapshot.targets.map((target) => [target.facts.recordId, target.item])
583
+ );
584
+ const populated = {};
585
+ for (const relationKey of snapshot.relationKeys) {
586
+ const [fieldName, targetId] = relationKey.split("\0");
587
+ if (!fieldName || !targetId) continue;
588
+ const target = targetsById.get(targetId);
589
+ if (target) (populated[fieldName] ??= []).push(target);
590
+ }
591
+ return populated;
592
+ }
593
+ function inverseSourceKey(source) {
594
+ return JSON.stringify([
595
+ source.contentTypeId,
596
+ source.contentTypeSlug,
597
+ source.contentTypeName,
598
+ source.fieldName
599
+ ]);
600
+ }
601
+ async function deriveInverseSourceAuthorization(adapter, ensureSynced, targetType) {
602
+ await ensureSynced();
603
+ const permissions = [];
604
+ const sources = [];
605
+ const seenSourceTypes = /* @__PURE__ */ new Set();
606
+ for (const contentType of await adapter.findMany({
607
+ model: "contentType"
608
+ })) {
609
+ for (const [fieldName, relation] of Object.entries(
610
+ extractRelationFields(contentType)
611
+ )) {
612
+ if (relation.type !== "belongsTo" || relation.targetType !== targetType) {
613
+ continue;
614
+ }
615
+ sources.push({
616
+ contentTypeId: contentType.id,
617
+ contentTypeSlug: contentType.slug,
618
+ contentTypeName: contentType.name,
619
+ fieldName
620
+ });
621
+ if (seenSourceTypes.has(contentType.slug)) continue;
622
+ seenSourceTypes.add(contentType.slug);
623
+ permissions.push(
624
+ cmsPermissions.contentType.read({ contentType: contentType.slug })
625
+ );
626
+ }
627
+ }
628
+ sources.sort(
629
+ (left, right) => inverseSourceKey(left).localeCompare(inverseSourceKey(right))
630
+ );
631
+ return {
632
+ permissions,
633
+ snapshot: sources.map(inverseSourceKey),
634
+ sources
635
+ };
636
+ }
637
+ function createCMSOperations(adapter, options) {
638
+ const { ensureSynced, getContentTypesWithCounts, hooks } = options;
639
+ const populatedRelationSnapshots = /* @__PURE__ */ new WeakMap();
640
+ const relationWriteAuthorizationSnapshots = /* @__PURE__ */ new WeakMap();
641
+ const relationFilterAuthorizationSnapshots = /* @__PURE__ */ new WeakMap();
642
+ const inverseSourceAuthorizationSnapshots = /* @__PURE__ */ new WeakMap();
643
+ const inverseTargetAuthorizationSnapshots = /* @__PURE__ */ new WeakMap();
644
+ const contentTypeListSnapshots = /* @__PURE__ */ new WeakMap();
645
+ const assertCurrentRelationWriteAuthorization = async (currentAdapter, authorized, contentTypeSlug, data) => {
646
+ let current;
647
+ try {
648
+ const contentType = await getContentTypeOrThrow(
649
+ currentAdapter,
650
+ ensureSynced,
651
+ contentTypeSlug
652
+ );
653
+ current = await deriveRelationWriteAuthorization(
654
+ currentAdapter,
655
+ contentType,
656
+ data,
657
+ ensureSynced,
658
+ authorized.snapshot
659
+ );
660
+ } catch (error) {
661
+ if (error instanceof CMSOperationError) {
662
+ if (error.code === "CONTENT_TYPE_NOT_FOUND") {
663
+ throw relationSchemaChangedError();
664
+ }
665
+ if (error.code === "RECORD_NOT_FOUND") throw staleRecordError();
666
+ }
667
+ throw error;
668
+ }
669
+ assertRelationWriteAuthorization(authorized, current);
670
+ };
671
+ const recheckRelationWriteAuthorization = async (input, contentTypeSlug, data) => {
672
+ const authorized = relationWriteAuthorizationSnapshots.get(input);
673
+ relationWriteAuthorizationSnapshots.delete(input);
674
+ if (!authorized) {
675
+ throw new CMSOperationError(
676
+ 500,
677
+ "Relation authorization snapshot is unavailable.",
678
+ "AUTHORIZATION_SNAPSHOT_MISSING"
679
+ );
680
+ }
681
+ await assertCurrentRelationWriteAuthorization(
682
+ adapter,
683
+ authorized,
684
+ contentTypeSlug,
685
+ data
686
+ );
687
+ return authorized;
688
+ };
689
+ const recheckInverseSourceAuthorization = async (input, targetType) => {
690
+ const authorized = inverseSourceAuthorizationSnapshots.get(input);
691
+ inverseSourceAuthorizationSnapshots.delete(input);
692
+ if (!authorized) {
693
+ throw new CMSOperationError(
694
+ 500,
695
+ "Inverse relation authorization snapshot is unavailable.",
696
+ "AUTHORIZATION_SNAPSHOT_MISSING"
697
+ );
698
+ }
699
+ const current = await deriveInverseSourceAuthorization(
700
+ adapter,
701
+ ensureSynced,
702
+ targetType
703
+ );
704
+ assertRelationSchemaSnapshot(authorized, current.snapshot);
705
+ return current.sources;
706
+ };
707
+ const recheckRelationFilterAuthorization = async (input, sourceType, fieldName, targetId) => {
708
+ const authorized = relationFilterAuthorizationSnapshots.get(input);
709
+ relationFilterAuthorizationSnapshots.delete(input);
710
+ if (!authorized) {
711
+ throw new CMSOperationError(
712
+ 500,
713
+ "Relation-filter authorization snapshot is unavailable.",
714
+ "AUTHORIZATION_SNAPSHOT_MISSING"
715
+ );
716
+ }
717
+ let sourceContentType;
718
+ try {
719
+ sourceContentType = await getContentTypeOrThrow(
720
+ adapter,
721
+ ensureSynced,
722
+ sourceType
723
+ );
724
+ } catch (error) {
725
+ if (error instanceof CMSOperationError && error.code === "CONTENT_TYPE_NOT_FOUND") {
726
+ throw relationSchemaChangedError();
727
+ }
728
+ throw error;
729
+ }
730
+ const relation = extractRelationFields(sourceContentType)[fieldName];
731
+ if (!relation) throw relationSchemaChangedError();
732
+ let targetContentType;
733
+ try {
734
+ targetContentType = await getContentTypeOrThrow(
735
+ adapter,
736
+ ensureSynced,
737
+ relation.targetType
738
+ );
739
+ } catch (error) {
740
+ if (error instanceof CMSOperationError && error.code === "CONTENT_TYPE_NOT_FOUND") {
741
+ throw relationSchemaChangedError();
742
+ }
743
+ throw error;
744
+ }
745
+ const currentSnapshot = relationFilterSnapshot(
746
+ sourceContentType,
747
+ fieldName,
748
+ relation,
749
+ targetContentType
750
+ );
751
+ if (authorized.snapshot !== currentSnapshot) {
752
+ throw relationSchemaChangedError();
753
+ }
754
+ let target;
755
+ try {
756
+ target = await getRecordOrThrow(
757
+ adapter,
758
+ ensureSynced,
759
+ targetContentType.slug,
760
+ targetId
761
+ );
762
+ } catch (error) {
763
+ if (error instanceof CMSOperationError && error.code === "RECORD_NOT_FOUND") {
764
+ throw staleRecordError();
765
+ }
766
+ throw error;
767
+ }
768
+ const currentFacts = recordFacts(target);
769
+ if (authorized.targetFacts.contentType !== currentFacts.contentType || authorized.targetFacts.recordId !== currentFacts.recordId || authorized.targetFacts.authorId !== currentFacts.authorId) {
770
+ throw staleRecordError();
771
+ }
772
+ return sourceContentType;
773
+ };
774
+ const recheckInverseTargetAuthorization = async (input, targetType, targetId) => {
775
+ const authorized = inverseTargetAuthorizationSnapshots.get(input);
776
+ if (!authorized || authorized.contentType !== targetType || authorized.recordId !== targetId) {
777
+ throw new CMSOperationError(
778
+ 500,
779
+ "Inverse-relation target authorization snapshot is unavailable.",
780
+ "AUTHORIZATION_SNAPSHOT_MISSING"
781
+ );
782
+ }
783
+ const current = await adapter.findOne({
784
+ model: "contentItem",
785
+ where: [{ field: "id", value: targetId, operator: "eq" }],
786
+ join: { contentType: true }
787
+ });
788
+ if (!current) throw staleRecordError();
789
+ assertRecordFacts(current, authorized);
790
+ };
791
+ const listQuerySchema = createListContentQuerySchema(options.maxPageSize);
792
+ const paginationSchema = z.object({
793
+ limit: z.coerce.number().min(1).max(options.maxPageSize ?? DEFAULT_MAX_PAGE_SIZE).optional().default(20),
794
+ offset: z.coerce.number().min(0).optional().default(0)
795
+ });
796
+ const ListContentItemsInputSchema = z.object({
797
+ typeSlug: z.string().min(1),
798
+ query: listQuerySchema
799
+ });
800
+ const ListContentByRelationInputSchema = z.object({
801
+ typeSlug: z.string().min(1),
802
+ query: z.object({ field: z.string().min(1), targetId: z.string().min(1) }).merge(paginationSchema).merge(contentReadOptionsSchema)
803
+ });
804
+ const GetInverseRelationsInputSchema = z.object({
805
+ slug: z.string().min(1),
806
+ query: z.object({ itemId: z.string().min(1).optional() })
807
+ });
808
+ const ListInverseRelationItemsInputSchema = z.object({
809
+ slug: z.string().min(1),
810
+ sourceType: z.string().min(1),
811
+ query: z.object({
812
+ itemId: z.string().min(1),
813
+ fieldName: z.string().min(1)
814
+ }).merge(paginationSchema).merge(contentReadOptionsSchema)
815
+ });
816
+ const notifyError = async (error, operation, context) => {
817
+ await hooks?.onErrorExecuteContentOperation?.(
818
+ normalizeOperationError(error, `CMS ${operation} operation failed.`),
819
+ operation,
820
+ operationErrorContext(context, error)
821
+ );
822
+ };
823
+ const listContentTypes = defineOperation({
824
+ input: ListContentTypesInputSchema,
825
+ permission: cmsPermissions.contentType.read,
826
+ facts: async () => {
827
+ await ensureSynced();
828
+ return {};
829
+ },
830
+ additionalPermissions: async ({ input }) => {
831
+ const contentTypes = await getContentTypesWithCounts();
832
+ contentTypeListSnapshots.set(input, contentTypes);
833
+ return contentTypes.map(
834
+ (contentType) => cmsPermissions.record.read(collectionFacts(contentType.slug))
835
+ );
836
+ },
837
+ execute: ({ input }) => {
838
+ const contentTypes = contentTypeListSnapshots.get(input);
839
+ contentTypeListSnapshots.delete(input);
840
+ if (!contentTypes) {
841
+ throw new CMSOperationError(
842
+ 500,
843
+ "Content-type catalog authorization snapshot is unavailable.",
844
+ "AUTHORIZATION_SNAPSHOT_MISSING"
845
+ );
846
+ }
847
+ return contentTypes.map((contentType) => ({
848
+ ...operationContentType(contentType),
849
+ itemCount: contentType.itemCount
850
+ }));
851
+ },
852
+ onError: ({ error, ...context }) => notifyError(error, "list", genericContext(context))
853
+ });
854
+ const getContentTypeBySlug = defineOperation({
855
+ input: GetContentTypeInputSchema,
856
+ permission: cmsPermissions.contentType.read,
857
+ facts: async ({ input }) => {
858
+ const contentType = await getContentTypeOrThrow(
859
+ adapter,
860
+ ensureSynced,
861
+ input.slug
862
+ );
863
+ return { contentType: contentType.slug };
864
+ },
865
+ execute: async ({ facts }) => operationContentType(
866
+ serializeContentType(
867
+ await getContentTypeOrThrow(
868
+ adapter,
869
+ ensureSynced,
870
+ facts.contentType ?? ""
871
+ )
872
+ )
873
+ ),
874
+ onError: ({ error, ...context }) => notifyError(
875
+ error,
876
+ "get",
877
+ genericContext(context, context.facts.contentType)
878
+ )
879
+ });
880
+ const listContentItems = defineOperation({
881
+ input: ListContentItemsInputSchema,
882
+ permission: cmsPermissions.record.read,
883
+ facts: async ({ input }) => {
884
+ const contentType = await getContentTypeOrThrow(
885
+ adapter,
886
+ ensureSynced,
887
+ input.typeSlug
888
+ );
889
+ if (!input.query.slug) {
890
+ return collectionFacts(contentType.slug);
891
+ }
892
+ const item = await getContentItemBySlug(
893
+ adapter,
894
+ contentType.slug,
895
+ input.query.slug
896
+ );
897
+ const facts = {
898
+ contentType: contentType.slug,
899
+ scope: "record",
900
+ ...item ? {
901
+ recordId: item.id,
902
+ ...item.authorId ? { authorId: item.authorId } : {}
903
+ } : {}
904
+ };
905
+ return facts;
906
+ },
907
+ additionalPermissions: ({ facts }) => [
908
+ cmsPermissions.contentType.read({ contentType: facts.contentType })
909
+ ],
910
+ execute: async ({ input, facts }) => {
911
+ if (input.query.fields !== void 0) {
912
+ validateOperationContentReadOptions(
913
+ await getContentTypeOrThrow(adapter, ensureSynced, facts.contentType),
914
+ input.query
915
+ );
916
+ }
917
+ const result = await getAllContentItems(adapter, facts.contentType, {
918
+ ...input.query,
919
+ view: void 0,
920
+ fields: void 0
921
+ });
922
+ if (facts.scope === "record") {
923
+ if (!facts.recordId) {
924
+ if (result.items.length > 0) throw staleRecordError();
925
+ if (await getContentItemBySlug(
926
+ adapter,
927
+ facts.contentType,
928
+ input.query.slug ?? ""
929
+ )) {
930
+ throw staleRecordError();
931
+ }
932
+ return operationContentList(result, input.query);
933
+ }
934
+ if (result.items.length > 1) throw staleRecordError();
935
+ if (result.items.length === 0) {
936
+ const current = await getContentItemBySlug(
937
+ adapter,
938
+ facts.contentType,
939
+ input.query.slug ?? ""
940
+ );
941
+ if (!current) throw staleRecordError();
942
+ assertRecordFacts(current, facts);
943
+ } else {
944
+ assertRecordFacts(result.items[0], facts);
945
+ }
946
+ }
947
+ return operationContentList(result, input.query);
948
+ },
949
+ onError: ({ error, ...context }) => notifyError(
950
+ error,
951
+ "list",
952
+ genericContext(context, context.facts.contentType)
953
+ )
954
+ });
955
+ const getContentItem = defineOperation({
956
+ input: GetContentItemInputSchema,
957
+ permission: cmsPermissions.record.read,
958
+ facts: async ({ input }) => recordFacts(
959
+ await getRecordOrThrow(adapter, ensureSynced, input.typeSlug, input.id)
960
+ ),
961
+ additionalPermissions: ({ facts }) => [
962
+ cmsPermissions.contentType.read({ contentType: facts.contentType })
963
+ ],
964
+ execute: async ({ input, facts }) => {
965
+ const item = await getRecordOrThrow(
966
+ adapter,
967
+ ensureSynced,
968
+ facts.contentType,
969
+ facts.recordId ?? ""
970
+ );
971
+ assertRecordFacts(item, facts);
972
+ validateOperationContentReadOptions(item.contentType, input);
973
+ return applyContentReadOptions(
974
+ operationContentItem(serializeContentItemWithType(item)),
975
+ input
976
+ );
977
+ },
978
+ onError: ({ error, ...context }) => notifyError(
979
+ error,
980
+ "get",
981
+ genericContext(context, context.facts.contentType)
982
+ )
983
+ });
984
+ const createContentItem = defineOperation({
985
+ input: CreateContentItemInputSchema,
986
+ permission: cmsPermissions.record.create,
987
+ facts: async ({ input }) => ({
988
+ contentType: (await getContentTypeOrThrow(adapter, ensureSynced, input.typeSlug)).slug
989
+ }),
990
+ additionalPermissions: async ({ input, facts }) => {
991
+ const authorization = await deriveRelationWriteAuthorization(
992
+ adapter,
993
+ await getContentTypeOrThrow(adapter, ensureSynced, facts.contentType),
994
+ input.body.data,
995
+ ensureSynced
996
+ );
997
+ relationWriteAuthorizationSnapshots.set(input, authorization);
998
+ return [
999
+ cmsPermissions.contentType.read({ contentType: facts.contentType }),
1000
+ ...authorization.permissions
1001
+ ];
1002
+ },
1003
+ execute: async (context) => {
1004
+ const lifecycleContext = createContext(context);
1005
+ const contentType = await getContentTypeOrThrow(
1006
+ adapter,
1007
+ ensureSynced,
1008
+ context.facts.contentType
1009
+ );
1010
+ const slug = slugify(context.input.body.slug);
1011
+ if (!slug) {
1012
+ throw new CMSOperationError(
1013
+ 400,
1014
+ "Invalid slug: must contain at least one alphanumeric character",
1015
+ "INVALID_SLUG"
1016
+ );
1017
+ }
1018
+ const relationAuthorization = await recheckRelationWriteAuthorization(
1019
+ context.input,
1020
+ contentType.slug,
1021
+ context.input.body.data
1022
+ );
1023
+ const relationPlan = await planRelationsInData(
1024
+ adapter,
1025
+ contentType,
1026
+ context.input.body.data,
1027
+ ensureSynced,
1028
+ context.identity?.id
1029
+ );
1030
+ const validation = getContentTypeZodSchema(contentType).safeParse(
1031
+ relationPlan.processedData
1032
+ );
1033
+ if (!validation.success) {
1034
+ throw new CMSOperationError(
1035
+ 400,
1036
+ "Validation failed",
1037
+ "RECORD_VALIDATION_FAILED",
1038
+ validation.error.issues
1039
+ );
1040
+ }
1041
+ const existing = await adapter.findOne({
1042
+ model: "contentItem",
1043
+ where: [
1044
+ {
1045
+ field: "contentTypeId",
1046
+ value: contentType.id,
1047
+ operator: "eq"
1048
+ },
1049
+ { field: "slug", value: slug, operator: "eq" }
1050
+ ]
1051
+ });
1052
+ if (existing) {
1053
+ throw new CMSOperationError(
1054
+ 409,
1055
+ "Content item with this slug already exists",
1056
+ "DUPLICATE_SLUG"
1057
+ );
1058
+ }
1059
+ const validatedData = validation.data;
1060
+ await runBeforeHook(
1061
+ () => hooks?.onBeforeCreateContent?.(validatedData, lifecycleContext),
1062
+ "Create operation denied"
1063
+ );
1064
+ return adapter.transaction(async (tx) => {
1065
+ await assertCurrentRelationWriteAuthorization(
1066
+ tx,
1067
+ relationAuthorization,
1068
+ contentType.slug,
1069
+ context.input.body.data
1070
+ );
1071
+ const currentDuplicate = await tx.findOne({
1072
+ model: "contentItem",
1073
+ where: [
1074
+ {
1075
+ field: "contentTypeId",
1076
+ value: contentType.id,
1077
+ operator: "eq"
1078
+ },
1079
+ { field: "slug", value: slug, operator: "eq" }
1080
+ ]
1081
+ });
1082
+ if (currentDuplicate) {
1083
+ throw new CMSOperationError(
1084
+ 409,
1085
+ "Content item with this slug already exists",
1086
+ "DUPLICATE_SLUG"
1087
+ );
1088
+ }
1089
+ await applyRelationWritePlan(tx, relationPlan);
1090
+ const item = await tx.create({
1091
+ model: "contentItem",
1092
+ data: {
1093
+ contentTypeId: contentType.id,
1094
+ slug,
1095
+ data: JSON.stringify(validatedData),
1096
+ ...context.identity ? { authorId: context.identity.id } : {},
1097
+ createdAt: /* @__PURE__ */ new Date(),
1098
+ updatedAt: /* @__PURE__ */ new Date()
1099
+ }
1100
+ });
1101
+ await syncRelations(tx, item.id, relationPlan.relationIds);
1102
+ const joined = await getRecordOrThrow(
1103
+ tx,
1104
+ ensureSynced,
1105
+ contentType.slug,
1106
+ item.id
1107
+ );
1108
+ return operationContentItem(serializeContentItemWithType(joined));
1109
+ });
1110
+ },
1111
+ after: async (context) => {
1112
+ const base = createContext(context);
1113
+ const afterCreateContent = hooks?.onAfterCreateContent;
1114
+ await afterCreateContent?.(
1115
+ context.result,
1116
+ Object.freeze({ ...base, result: context.result })
1117
+ );
1118
+ },
1119
+ onError: async ({ error, ...context }) => {
1120
+ await notifyError(error, "create", createContext(context));
1121
+ }
1122
+ });
1123
+ const updateContentItem = defineOperation({
1124
+ input: UpdateContentItemInputSchema,
1125
+ permission: cmsPermissions.record.update,
1126
+ facts: async ({ input }) => {
1127
+ const item = await getRecordOrThrow(
1128
+ adapter,
1129
+ ensureSynced,
1130
+ input.typeSlug,
1131
+ input.id
1132
+ );
1133
+ const facts = recordFacts(item);
1134
+ return {
1135
+ contentType: facts.contentType,
1136
+ recordId: facts.recordId ?? input.id,
1137
+ ...facts.authorId ? { authorId: facts.authorId } : {}
1138
+ };
1139
+ },
1140
+ additionalPermissions: async ({ input, facts }) => {
1141
+ const contentTypePermission = cmsPermissions.contentType.read({
1142
+ contentType: facts.contentType
1143
+ });
1144
+ if (!input.body.data) return [contentTypePermission];
1145
+ const authorization = await deriveRelationWriteAuthorization(
1146
+ adapter,
1147
+ await getContentTypeOrThrow(adapter, ensureSynced, facts.contentType),
1148
+ input.body.data,
1149
+ ensureSynced
1150
+ );
1151
+ relationWriteAuthorizationSnapshots.set(input, authorization);
1152
+ return [contentTypePermission, ...authorization.permissions];
1153
+ },
1154
+ execute: async (context) => {
1155
+ const lifecycleContext = updateContext(context);
1156
+ const contentType = await getContentTypeOrThrow(
1157
+ adapter,
1158
+ ensureSynced,
1159
+ context.facts.contentType
1160
+ );
1161
+ const rawSlug = context.input.body.slug;
1162
+ const slug = rawSlug ? slugify(rawSlug) : void 0;
1163
+ if (rawSlug && !slug) {
1164
+ throw new CMSOperationError(
1165
+ 400,
1166
+ "Invalid slug: must contain at least one alphanumeric character",
1167
+ "INVALID_SLUG"
1168
+ );
1169
+ }
1170
+ const bodyData = context.input.body.data;
1171
+ const relationAuthorization = bodyData ? await recheckRelationWriteAuthorization(
1172
+ context.input,
1173
+ contentType.slug,
1174
+ bodyData
1175
+ ) : void 0;
1176
+ const authorizedRecord = await getRecordOrThrow(
1177
+ adapter,
1178
+ ensureSynced,
1179
+ context.facts.contentType,
1180
+ context.facts.recordId
1181
+ );
1182
+ assertRecordFacts(authorizedRecord, context.facts);
1183
+ if (slug && slug !== authorizedRecord.slug) {
1184
+ const duplicate = await adapter.findOne({
1185
+ model: "contentItem",
1186
+ where: [
1187
+ {
1188
+ field: "contentTypeId",
1189
+ value: contentType.id,
1190
+ operator: "eq"
1191
+ },
1192
+ { field: "slug", value: slug, operator: "eq" }
1193
+ ]
1194
+ });
1195
+ if (duplicate) {
1196
+ throw new CMSOperationError(
1197
+ 409,
1198
+ "Content item with this slug already exists",
1199
+ "DUPLICATE_SLUG"
1200
+ );
1201
+ }
1202
+ }
1203
+ const relationPlan = bodyData ? await planRelationsInData(
1204
+ adapter,
1205
+ contentType,
1206
+ bodyData,
1207
+ ensureSynced,
1208
+ context.identity?.id
1209
+ ) : void 0;
1210
+ const currentData = authorizedRecord.data ? JSON.parse(authorizedRecord.data) : {};
1211
+ const validation = getContentTypeZodSchema(contentType).safeParse({
1212
+ ...currentData,
1213
+ ...relationPlan?.processedData ?? {}
1214
+ });
1215
+ if (!validation.success) {
1216
+ throw new CMSOperationError(
1217
+ 400,
1218
+ "Validation failed",
1219
+ "RECORD_VALIDATION_FAILED",
1220
+ validation.error.issues
1221
+ );
1222
+ }
1223
+ const mergedData = validation.data;
1224
+ await runBeforeHook(
1225
+ () => hooks?.onBeforeUpdateContent?.(
1226
+ context.facts.recordId,
1227
+ mergedData,
1228
+ lifecycleContext
1229
+ ),
1230
+ "Update operation denied"
1231
+ );
1232
+ return adapter.transaction(async (tx) => {
1233
+ if (bodyData && relationAuthorization) {
1234
+ await assertCurrentRelationWriteAuthorization(
1235
+ tx,
1236
+ relationAuthorization,
1237
+ contentType.slug,
1238
+ bodyData
1239
+ );
1240
+ }
1241
+ const current = await getRecordOrThrow(
1242
+ tx,
1243
+ ensureSynced,
1244
+ context.facts.contentType,
1245
+ context.facts.recordId
1246
+ );
1247
+ assertRecordFacts(current, context.facts);
1248
+ assertRecordSnapshot(current, authorizedRecord);
1249
+ if (slug && slug !== current.slug) {
1250
+ const duplicate = await tx.findOne({
1251
+ model: "contentItem",
1252
+ where: [
1253
+ {
1254
+ field: "contentTypeId",
1255
+ value: contentType.id,
1256
+ operator: "eq"
1257
+ },
1258
+ { field: "slug", value: slug, operator: "eq" }
1259
+ ]
1260
+ });
1261
+ if (duplicate) {
1262
+ throw new CMSOperationError(
1263
+ 409,
1264
+ "Content item with this slug already exists",
1265
+ "DUPLICATE_SLUG"
1266
+ );
1267
+ }
1268
+ }
1269
+ if (relationPlan) await applyRelationWritePlan(tx, relationPlan);
1270
+ const update = { updatedAt: /* @__PURE__ */ new Date() };
1271
+ if (slug) update.slug = slug;
1272
+ if (bodyData) update.data = JSON.stringify(mergedData);
1273
+ const matched = await tx.updateMany({
1274
+ model: "contentItem",
1275
+ where: [
1276
+ {
1277
+ field: "id",
1278
+ value: context.facts.recordId,
1279
+ operator: "eq"
1280
+ },
1281
+ {
1282
+ field: "contentTypeId",
1283
+ value: contentType.id,
1284
+ operator: "eq"
1285
+ },
1286
+ {
1287
+ field: "authorId",
1288
+ value: context.facts.authorId ?? null,
1289
+ operator: "eq"
1290
+ },
1291
+ {
1292
+ field: "updatedAt",
1293
+ value: current.updatedAt,
1294
+ operator: "eq"
1295
+ }
1296
+ ],
1297
+ update
1298
+ });
1299
+ if (!didUpdateContentItem(matched, context.facts.recordId)) {
1300
+ throw staleRecordError();
1301
+ }
1302
+ if (relationPlan) {
1303
+ await syncRelations(
1304
+ tx,
1305
+ context.facts.recordId,
1306
+ relationPlan.relationIds
1307
+ );
1308
+ }
1309
+ const updated = await getRecordOrThrow(
1310
+ tx,
1311
+ ensureSynced,
1312
+ context.facts.contentType,
1313
+ context.facts.recordId
1314
+ );
1315
+ return operationContentItem(serializeContentItemWithType(updated));
1316
+ });
1317
+ },
1318
+ after: async (context) => {
1319
+ const base = updateContext(context);
1320
+ const afterUpdateContent = hooks?.onAfterUpdateContent;
1321
+ await afterUpdateContent?.(
1322
+ context.result,
1323
+ Object.freeze({ ...base, result: context.result })
1324
+ );
1325
+ },
1326
+ onError: async ({ error, ...context }) => {
1327
+ await notifyError(error, "update", updateContext(context));
1328
+ }
1329
+ });
1330
+ const deleteContentItem = defineOperation({
1331
+ input: DeleteContentItemInputSchema,
1332
+ permission: cmsPermissions.record.delete,
1333
+ facts: async ({ input }) => {
1334
+ const item = await getRecordOrThrow(
1335
+ adapter,
1336
+ ensureSynced,
1337
+ input.typeSlug,
1338
+ input.id
1339
+ );
1340
+ const facts = recordFacts(item);
1341
+ return {
1342
+ contentType: facts.contentType,
1343
+ recordId: facts.recordId ?? input.id,
1344
+ ...facts.authorId ? { authorId: facts.authorId } : {}
1345
+ };
1346
+ },
1347
+ before: async (context) => {
1348
+ const current = await getRecordOrThrow(
1349
+ adapter,
1350
+ ensureSynced,
1351
+ context.facts.contentType,
1352
+ context.facts.recordId
1353
+ );
1354
+ assertRecordFacts(current, context.facts);
1355
+ await runBeforeHook(
1356
+ () => hooks?.onBeforeDeleteContent?.(
1357
+ context.facts.recordId,
1358
+ deleteContext(context)
1359
+ ),
1360
+ "Delete operation denied"
1361
+ );
1362
+ },
1363
+ execute: async ({ facts }) => adapter.transaction(async (tx) => {
1364
+ const existing = await getRecordOrThrow(
1365
+ tx,
1366
+ ensureSynced,
1367
+ facts.contentType,
1368
+ facts.recordId
1369
+ );
1370
+ assertRecordFacts(existing, facts);
1371
+ const matched = await tx.updateMany({
1372
+ model: "contentItem",
1373
+ where: [
1374
+ { field: "id", value: facts.recordId, operator: "eq" },
1375
+ {
1376
+ field: "contentTypeId",
1377
+ value: existing.contentTypeId,
1378
+ operator: "eq"
1379
+ },
1380
+ {
1381
+ field: "authorId",
1382
+ value: facts.authorId ?? null,
1383
+ operator: "eq"
1384
+ },
1385
+ {
1386
+ field: "updatedAt",
1387
+ value: existing.updatedAt,
1388
+ operator: "eq"
1389
+ }
1390
+ ],
1391
+ update: { updatedAt: /* @__PURE__ */ new Date() }
1392
+ });
1393
+ if (!didUpdateContentItem(matched, facts.recordId)) {
1394
+ throw staleRecordError();
1395
+ }
1396
+ await tx.delete({
1397
+ model: "contentItem",
1398
+ where: [
1399
+ { field: "id", value: facts.recordId, operator: "eq" },
1400
+ {
1401
+ field: "contentTypeId",
1402
+ value: existing.contentTypeId,
1403
+ operator: "eq"
1404
+ }
1405
+ ]
1406
+ });
1407
+ return { success: true };
1408
+ }),
1409
+ after: async (context) => {
1410
+ const base = deleteContext(context);
1411
+ await hooks?.onAfterDeleteContent?.(
1412
+ context.facts.recordId,
1413
+ Object.freeze({ ...base, result: context.result })
1414
+ );
1415
+ },
1416
+ onError: async ({ error, ...context }) => {
1417
+ await notifyError(error, "delete", deleteContext(context));
1418
+ }
1419
+ });
1420
+ const getContentItemPopulated = defineOperation({
1421
+ input: CMSContentItemParamsSchema,
1422
+ permission: cmsPermissions.record.read,
1423
+ facts: async ({ input }) => recordFacts(
1424
+ await getRecordOrThrow(adapter, ensureSynced, input.typeSlug, input.id)
1425
+ ),
1426
+ additionalPermissions: async ({ input, facts }) => {
1427
+ const snapshot = await getPopulatedRelationSnapshot(
1428
+ adapter,
1429
+ facts.recordId ?? ""
1430
+ );
1431
+ populatedRelationSnapshots.set(input, snapshot);
1432
+ const contentTypes = /* @__PURE__ */ new Set([
1433
+ facts.contentType,
1434
+ ...snapshot.targets.map(
1435
+ ({ facts: targetFacts }) => targetFacts.contentType
1436
+ )
1437
+ ]);
1438
+ return [
1439
+ ...[...contentTypes].map(
1440
+ (contentType) => cmsPermissions.contentType.read({ contentType })
1441
+ ),
1442
+ ...snapshot.targets.map(
1443
+ ({ facts: targetFacts }) => cmsPermissions.record.read(targetFacts)
1444
+ )
1445
+ ];
1446
+ },
1447
+ execute: async ({ input, facts }) => {
1448
+ try {
1449
+ const item = await getRecordOrThrow(
1450
+ adapter,
1451
+ ensureSynced,
1452
+ facts.contentType,
1453
+ facts.recordId ?? ""
1454
+ );
1455
+ assertRecordFacts(item, facts);
1456
+ const authorizedSnapshot = populatedRelationSnapshots.get(
1457
+ input
1458
+ );
1459
+ if (!authorizedSnapshot) {
1460
+ throw new CMSOperationError(
1461
+ 500,
1462
+ "Related-content authorization snapshot is unavailable.",
1463
+ "AUTHORIZATION_SNAPSHOT_MISSING"
1464
+ );
1465
+ }
1466
+ const currentSnapshot = await getPopulatedRelationSnapshot(
1467
+ adapter,
1468
+ facts.recordId ?? ""
1469
+ );
1470
+ assertPopulatedRelationSnapshot(authorizedSnapshot, currentSnapshot);
1471
+ const relations = populatedRelationsFromSnapshot(currentSnapshot);
1472
+ return {
1473
+ ...operationContentItem(serializeContentItemWithType(item)),
1474
+ _relations: Object.fromEntries(
1475
+ Object.entries(relations).map(([field, records]) => [
1476
+ field,
1477
+ records.map(operationContentItem)
1478
+ ])
1479
+ )
1480
+ };
1481
+ } finally {
1482
+ populatedRelationSnapshots.delete(input);
1483
+ }
1484
+ },
1485
+ onError: ({ error, ...context }) => notifyError(
1486
+ error,
1487
+ "get",
1488
+ genericContext(context, context.facts.contentType)
1489
+ )
1490
+ });
1491
+ const listContentByRelation = defineOperation({
1492
+ input: ListContentByRelationInputSchema,
1493
+ permission: cmsPermissions.record.read,
1494
+ facts: async ({ input }) => collectionFacts(
1495
+ (await getContentTypeOrThrow(adapter, ensureSynced, input.typeSlug)).slug
1496
+ ),
1497
+ additionalPermissions: async ({ input, facts }) => {
1498
+ const sourceContentType = await getContentTypeOrThrow(
1499
+ adapter,
1500
+ ensureSynced,
1501
+ facts.contentType
1502
+ );
1503
+ const authorization = await deriveRelationFilterAuthorization(
1504
+ adapter,
1505
+ ensureSynced,
1506
+ sourceContentType,
1507
+ input.query.field,
1508
+ input.query.targetId
1509
+ );
1510
+ relationFilterAuthorizationSnapshots.set(input, authorization);
1511
+ return [
1512
+ cmsPermissions.contentType.read({ contentType: facts.contentType }),
1513
+ authorization.permission
1514
+ ];
1515
+ },
1516
+ execute: async ({ input, facts }) => {
1517
+ const sourceContentType = await recheckRelationFilterAuthorization(
1518
+ input,
1519
+ facts.contentType,
1520
+ input.query.field,
1521
+ input.query.targetId
1522
+ );
1523
+ validateOperationContentReadOptions(sourceContentType, input.query);
1524
+ const result = await getContentItemsByRelationForType(
1525
+ adapter,
1526
+ sourceContentType,
1527
+ input.query
1528
+ );
1529
+ return {
1530
+ ...result,
1531
+ items: result.items.map(
1532
+ (item) => applyContentReadOptions(operationContentItem(item), input.query)
1533
+ )
1534
+ };
1535
+ },
1536
+ onError: ({ error, ...context }) => notifyError(
1537
+ error,
1538
+ "list",
1539
+ genericContext(context, context.facts.contentType)
1540
+ )
1541
+ });
1542
+ const getInverseRelations = defineOperation({
1543
+ input: GetInverseRelationsInputSchema,
1544
+ permission: cmsPermissions.contentType.read,
1545
+ facts: async ({ input }) => ({
1546
+ contentType: (await getContentTypeOrThrow(adapter, ensureSynced, input.slug)).slug
1547
+ }),
1548
+ additionalPermissions: async ({ input, facts }) => {
1549
+ const authorization = await deriveInverseSourceAuthorization(
1550
+ adapter,
1551
+ ensureSynced,
1552
+ facts.contentType ?? ""
1553
+ );
1554
+ inverseSourceAuthorizationSnapshots.set(
1555
+ input,
1556
+ authorization.snapshot
1557
+ );
1558
+ const permissions = [...authorization.permissions];
1559
+ if (input.query.itemId) {
1560
+ const targetFacts = recordFacts(
1561
+ await getRecordOrThrow(
1562
+ adapter,
1563
+ ensureSynced,
1564
+ facts.contentType ?? "",
1565
+ input.query.itemId
1566
+ )
1567
+ );
1568
+ inverseTargetAuthorizationSnapshots.set(input, targetFacts);
1569
+ permissions.push(cmsPermissions.record.read(targetFacts));
1570
+ const authorizedSourceTypes = /* @__PURE__ */ new Set();
1571
+ for (const source of authorization.sources) {
1572
+ if (authorizedSourceTypes.has(source.contentTypeSlug)) continue;
1573
+ authorizedSourceTypes.add(source.contentTypeSlug);
1574
+ permissions.push(
1575
+ cmsPermissions.record.read(collectionFacts(source.contentTypeSlug))
1576
+ );
1577
+ }
1578
+ }
1579
+ return permissions;
1580
+ },
1581
+ execute: async ({ input, facts }) => {
1582
+ try {
1583
+ const sources = await recheckInverseSourceAuthorization(
1584
+ input,
1585
+ facts.contentType ?? ""
1586
+ );
1587
+ if (input.query.itemId) {
1588
+ await recheckInverseTargetAuthorization(
1589
+ input,
1590
+ facts.contentType ?? "",
1591
+ input.query.itemId
1592
+ );
1593
+ }
1594
+ const inverseRelations = [];
1595
+ for (const source of sources) {
1596
+ let count = 0;
1597
+ if (input.query.itemId) {
1598
+ const relations = await adapter.findMany({
1599
+ model: "contentRelation",
1600
+ where: [
1601
+ {
1602
+ field: "targetId",
1603
+ value: input.query.itemId,
1604
+ operator: "eq"
1605
+ },
1606
+ {
1607
+ field: "fieldName",
1608
+ value: source.fieldName,
1609
+ operator: "eq"
1610
+ }
1611
+ ]
1612
+ });
1613
+ for (const sourceId of relations.map((value) => value.sourceId)) {
1614
+ const item = await adapter.findOne({
1615
+ model: "contentItem",
1616
+ where: [
1617
+ {
1618
+ field: "id",
1619
+ value: sourceId,
1620
+ operator: "eq"
1621
+ },
1622
+ {
1623
+ field: "contentTypeId",
1624
+ value: source.contentTypeId,
1625
+ operator: "eq"
1626
+ }
1627
+ ]
1628
+ });
1629
+ if (item) count += 1;
1630
+ }
1631
+ }
1632
+ inverseRelations.push({
1633
+ sourceType: source.contentTypeSlug,
1634
+ sourceTypeName: source.contentTypeName,
1635
+ fieldName: source.fieldName,
1636
+ count
1637
+ });
1638
+ }
1639
+ return {
1640
+ inverseRelations: inverseRelations.map((relation) => ({
1641
+ ...relation
1642
+ }))
1643
+ };
1644
+ } finally {
1645
+ inverseTargetAuthorizationSnapshots.delete(input);
1646
+ }
1647
+ },
1648
+ onError: ({ error, ...context }) => notifyError(
1649
+ error,
1650
+ "get",
1651
+ genericContext(context, context.facts.contentType)
1652
+ )
1653
+ });
1654
+ const listInverseRelationItems = defineOperation({
1655
+ input: ListInverseRelationItemsInputSchema,
1656
+ permission: cmsPermissions.record.read,
1657
+ facts: async ({ input }) => {
1658
+ await getContentTypeOrThrow(adapter, ensureSynced, input.slug);
1659
+ const sourceType = await getContentTypeOrThrow(
1660
+ adapter,
1661
+ ensureSynced,
1662
+ input.sourceType
1663
+ );
1664
+ return collectionFacts(sourceType.slug);
1665
+ },
1666
+ additionalPermissions: async ({ input, facts }) => {
1667
+ const authorization = await deriveInverseSourceAuthorization(
1668
+ adapter,
1669
+ ensureSynced,
1670
+ input.slug
1671
+ );
1672
+ const source = authorization.sources.find(
1673
+ (value) => value.contentTypeSlug === facts.contentType && value.fieldName === input.query.fieldName
1674
+ );
1675
+ if (!source) {
1676
+ throw new CMSOperationError(
1677
+ 404,
1678
+ "Inverse relation not found",
1679
+ "INVERSE_RELATION_NOT_FOUND"
1680
+ );
1681
+ }
1682
+ inverseSourceAuthorizationSnapshots.set(
1683
+ input,
1684
+ authorization.snapshot
1685
+ );
1686
+ const targetFacts = recordFacts(
1687
+ await getRecordOrThrow(
1688
+ adapter,
1689
+ ensureSynced,
1690
+ input.slug,
1691
+ input.query.itemId
1692
+ )
1693
+ );
1694
+ inverseTargetAuthorizationSnapshots.set(input, targetFacts);
1695
+ return [
1696
+ cmsPermissions.contentType.read({ contentType: facts.contentType }),
1697
+ cmsPermissions.record.read(targetFacts)
1698
+ ];
1699
+ },
1700
+ execute: async ({ input, facts }) => {
1701
+ try {
1702
+ const sources = await recheckInverseSourceAuthorization(
1703
+ input,
1704
+ input.slug
1705
+ );
1706
+ const source = sources.find(
1707
+ (value) => value.contentTypeSlug === facts.contentType && value.fieldName === input.query.fieldName
1708
+ );
1709
+ if (!source) throw relationSchemaChangedError();
1710
+ await recheckInverseTargetAuthorization(
1711
+ input,
1712
+ input.slug,
1713
+ input.query.itemId
1714
+ );
1715
+ const sourceContentType = await getContentTypeOrThrow(
1716
+ adapter,
1717
+ ensureSynced,
1718
+ facts.contentType
1719
+ );
1720
+ validateOperationContentReadOptions(sourceContentType, input.query);
1721
+ const result = await getContentItemsByRelationForType(
1722
+ adapter,
1723
+ sourceContentType,
1724
+ {
1725
+ field: source.fieldName,
1726
+ targetId: input.query.itemId,
1727
+ limit: input.query.limit,
1728
+ offset: input.query.offset
1729
+ }
1730
+ );
1731
+ return {
1732
+ ...result,
1733
+ items: result.items.map(
1734
+ (item) => applyContentReadOptions(operationContentItem(item), input.query)
1735
+ )
1736
+ };
1737
+ } finally {
1738
+ inverseTargetAuthorizationSnapshots.delete(input);
1739
+ }
1740
+ },
1741
+ onError: ({ error, ...context }) => notifyError(
1742
+ error,
1743
+ "list",
1744
+ genericContext(context, context.facts.contentType)
1745
+ )
1746
+ });
1747
+ return {
1748
+ listContentTypes,
1749
+ getContentTypeBySlug,
1750
+ listContentItems,
1751
+ getContentItem,
1752
+ createContentItem,
1753
+ updateContentItem,
1754
+ deleteContentItem,
1755
+ getContentItemPopulated,
1756
+ listContentByRelation,
1757
+ getInverseRelations,
1758
+ listInverseRelationItems
1759
+ };
1760
+ }
1761
+
1762
+ export { CMSContentItemParamsSchema, CMSContentTypeParamsSchema, CMSCreateContentItemBodySchema, CMSOperationError, CMSUpdateContentItemBodySchema, createCMSOperations };