@nixxie-cms/core 1.0.3 → 1.1.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 (202) hide show
  1. package/CHANGES-1.1.md +134 -0
  2. package/context/dist/nixxie-cms-core-context.cjs.js +4 -3
  3. package/context/dist/nixxie-cms-core-context.esm.js +3 -2
  4. package/dist/declarations/src/access.d.ts +2 -2
  5. package/dist/declarations/src/access.d.ts.map +1 -1
  6. package/dist/declarations/src/admin-ui/components/Navigation.d.ts +2 -2
  7. package/dist/declarations/src/admin-ui/components/Navigation.d.ts.map +1 -1
  8. package/dist/declarations/src/admin-ui/context.d.ts +6 -6
  9. package/dist/declarations/src/admin-ui/context.d.ts.map +1 -1
  10. package/dist/declarations/src/admin-ui/utils/Fields.d.ts +3 -3
  11. package/dist/declarations/src/admin-ui/utils/Fields.d.ts.map +1 -1
  12. package/dist/declarations/src/admin-ui/utils/filters.d.ts +5 -5
  13. package/dist/declarations/src/admin-ui/utils/filters.d.ts.map +1 -1
  14. package/dist/declarations/src/admin-ui/utils/useCreateItem.d.ts +3 -3
  15. package/dist/declarations/src/admin-ui/utils/useCreateItem.d.ts.map +1 -1
  16. package/dist/declarations/src/admin-ui/utils/utils.d.ts +2 -2
  17. package/dist/declarations/src/admin-ui/utils/utils.d.ts.map +1 -1
  18. package/dist/declarations/src/context.d.ts +1 -1
  19. package/dist/declarations/src/context.d.ts.map +1 -1
  20. package/dist/declarations/src/fields/types/bigInt/index.d.ts +3 -3
  21. package/dist/declarations/src/fields/types/bigInt/index.d.ts.map +1 -1
  22. package/dist/declarations/src/fields/types/bytes/index.d.ts +3 -3
  23. package/dist/declarations/src/fields/types/bytes/index.d.ts.map +1 -1
  24. package/dist/declarations/src/fields/types/calendarDay/index.d.ts +3 -3
  25. package/dist/declarations/src/fields/types/calendarDay/index.d.ts.map +1 -1
  26. package/dist/declarations/src/fields/types/checkbox/index.d.ts +3 -3
  27. package/dist/declarations/src/fields/types/checkbox/index.d.ts.map +1 -1
  28. package/dist/declarations/src/fields/types/decimal/index.d.ts +3 -3
  29. package/dist/declarations/src/fields/types/decimal/index.d.ts.map +1 -1
  30. package/dist/declarations/src/fields/types/file/index.d.ts +4 -4
  31. package/dist/declarations/src/fields/types/file/index.d.ts.map +1 -1
  32. package/dist/declarations/src/fields/types/float/index.d.ts +3 -3
  33. package/dist/declarations/src/fields/types/float/index.d.ts.map +1 -1
  34. package/dist/declarations/src/fields/types/image/index.d.ts +4 -4
  35. package/dist/declarations/src/fields/types/image/index.d.ts.map +1 -1
  36. package/dist/declarations/src/fields/types/integer/index.d.ts +3 -3
  37. package/dist/declarations/src/fields/types/integer/index.d.ts.map +1 -1
  38. package/dist/declarations/src/fields/types/json/index.d.ts +3 -3
  39. package/dist/declarations/src/fields/types/json/index.d.ts.map +1 -1
  40. package/dist/declarations/src/fields/types/multiselect/index.d.ts +3 -3
  41. package/dist/declarations/src/fields/types/multiselect/index.d.ts.map +1 -1
  42. package/dist/declarations/src/fields/types/multiselect/views/index.d.ts.map +1 -1
  43. package/dist/declarations/src/fields/types/password/index.d.ts +3 -3
  44. package/dist/declarations/src/fields/types/password/index.d.ts.map +1 -1
  45. package/dist/declarations/src/fields/types/relationship/index.d.ts +8 -8
  46. package/dist/declarations/src/fields/types/relationship/index.d.ts.map +1 -1
  47. package/dist/declarations/src/fields/types/relationship/views/ComboboxMany.d.ts +3 -3
  48. package/dist/declarations/src/fields/types/relationship/views/ComboboxMany.d.ts.map +1 -1
  49. package/dist/declarations/src/fields/types/relationship/views/ComboboxSingle.d.ts +3 -3
  50. package/dist/declarations/src/fields/types/relationship/views/ComboboxSingle.d.ts.map +1 -1
  51. package/dist/declarations/src/fields/types/relationship/views/index.d.ts +3 -3
  52. package/dist/declarations/src/fields/types/relationship/views/index.d.ts.map +1 -1
  53. package/dist/declarations/src/fields/types/relationship/views/types.d.ts +3 -3
  54. package/dist/declarations/src/fields/types/relationship/views/types.d.ts.map +1 -1
  55. package/dist/declarations/src/fields/types/select/index.d.ts +3 -3
  56. package/dist/declarations/src/fields/types/select/index.d.ts.map +1 -1
  57. package/dist/declarations/src/fields/types/text/index.d.ts +3 -3
  58. package/dist/declarations/src/fields/types/text/index.d.ts.map +1 -1
  59. package/dist/declarations/src/fields/types/timestamp/index.d.ts +3 -3
  60. package/dist/declarations/src/fields/types/timestamp/index.d.ts.map +1 -1
  61. package/dist/declarations/src/fields/types/virtual/index.d.ts +7 -7
  62. package/dist/declarations/src/fields/types/virtual/index.d.ts.map +1 -1
  63. package/dist/declarations/src/helpers.d.ts +249 -13
  64. package/dist/declarations/src/helpers.d.ts.map +1 -1
  65. package/dist/declarations/src/index.d.ts +9 -4
  66. package/dist/declarations/src/index.d.ts.map +1 -1
  67. package/dist/declarations/src/internal-unstable/admin-ui/pages/ListPage/index.d.ts.map +1 -1
  68. package/dist/declarations/src/lib/admin-meta.d.ts +11 -11
  69. package/dist/declarations/src/lib/admin-meta.d.ts.map +1 -1
  70. package/dist/declarations/src/lib/core/access-control.d.ts +18 -18
  71. package/dist/declarations/src/lib/core/access-control.d.ts.map +1 -1
  72. package/dist/declarations/src/lib/core/cascade.d.ts +47 -0
  73. package/dist/declarations/src/lib/core/cascade.d.ts.map +1 -0
  74. package/dist/declarations/src/lib/core/initialise-lists.d.ts +27 -24
  75. package/dist/declarations/src/lib/core/initialise-lists.d.ts.map +1 -1
  76. package/dist/declarations/src/lib/env.d.ts +9 -0
  77. package/dist/declarations/src/lib/env.d.ts.map +1 -0
  78. package/dist/declarations/src/lib/system.d.ts +1 -1
  79. package/dist/declarations/src/lib/system.d.ts.map +1 -1
  80. package/dist/declarations/src/list-features.d.ts +162 -0
  81. package/dist/declarations/src/list-features.d.ts.map +1 -0
  82. package/dist/declarations/src/schema.d.ts +24 -23
  83. package/dist/declarations/src/schema.d.ts.map +1 -1
  84. package/dist/declarations/src/session.d.ts +75 -0
  85. package/dist/declarations/src/session.d.ts.map +1 -1
  86. package/dist/declarations/src/types/admin-meta.d.ts +11 -11
  87. package/dist/declarations/src/types/admin-meta.d.ts.map +1 -1
  88. package/dist/declarations/src/types/config/access-control.d.ts +42 -42
  89. package/dist/declarations/src/types/config/access-control.d.ts.map +1 -1
  90. package/dist/declarations/src/types/config/fields.d.ts +19 -19
  91. package/dist/declarations/src/types/config/fields.d.ts.map +1 -1
  92. package/dist/declarations/src/types/config/hooks.d.ts +131 -131
  93. package/dist/declarations/src/types/config/hooks.d.ts.map +1 -1
  94. package/dist/declarations/src/types/config/index.d.ts +171 -8
  95. package/dist/declarations/src/types/config/index.d.ts.map +1 -1
  96. package/dist/declarations/src/types/config/lists.d.ts +146 -108
  97. package/dist/declarations/src/types/config/lists.d.ts.map +1 -1
  98. package/dist/declarations/src/types/context.d.ts +349 -47
  99. package/dist/declarations/src/types/context.d.ts.map +1 -1
  100. package/dist/declarations/src/types/next-fields.d.ts +28 -28
  101. package/dist/declarations/src/types/next-fields.d.ts.map +1 -1
  102. package/dist/declarations/src/types/type-info.d.ts +3 -3
  103. package/dist/declarations/src/types/type-info.d.ts.map +1 -1
  104. package/dist/{express-7559ca2d.esm.js → express-0abbce07.esm.js} +6 -6
  105. package/dist/{express-455ae20c.cjs.js → express-7ca6f76a.cjs.js} +6 -6
  106. package/dist/{index-15c8f81e.esm.js → index-5d8b0b4e.esm.js} +363 -183
  107. package/dist/index-6055753b.cjs.js +393 -0
  108. package/dist/{index-42045902.cjs.js → index-ac29f382.cjs.js} +363 -185
  109. package/dist/index-f1703b7b.esm.js +386 -0
  110. package/dist/nixxie-cms-core.cjs.js +1387 -30
  111. package/dist/nixxie-cms-core.esm.js +1361 -24
  112. package/dist/{non-null-graphql-add6bb3d.cjs.js → non-null-graphql-4a44c122.cjs.js} +1 -1
  113. package/dist/{non-null-graphql-a84ed64d.esm.js → non-null-graphql-8c5feaae.esm.js} +1 -1
  114. package/dist/{resolve-hooks-165a9ce2.cjs.js → resolve-hooks-10a5f84c.cjs.js} +240 -6
  115. package/dist/{resolve-hooks-6813a045.esm.js → resolve-hooks-9e676794.esm.js} +238 -7
  116. package/dist/{system-03e49e4f.esm.js → system-4d2a2648.esm.js} +32 -7
  117. package/dist/{system-a321642d.cjs.js → system-69e1a285.cjs.js} +32 -7
  118. package/fields/dist/nixxie-cms-core-fields.cjs.js +29 -576
  119. package/fields/dist/nixxie-cms-core-fields.esm.js +18 -565
  120. package/fields/types/bytes/dist/nixxie-cms-core-fields-types-bytes.cjs.js +4 -2
  121. package/fields/types/bytes/dist/nixxie-cms-core-fields-types-bytes.esm.js +4 -2
  122. package/fields/types/multiselect/views/dist/nixxie-cms-core-fields-types-multiselect-views.cjs.js +1 -6
  123. package/fields/types/multiselect/views/dist/nixxie-cms-core-fields-types-multiselect-views.esm.js +1 -6
  124. package/fields/types/password/dist/nixxie-cms-core-fields-types-password.cjs.js +4 -2
  125. package/fields/types/password/dist/nixxie-cms-core-fields-types-password.esm.js +4 -2
  126. package/internal-unstable/artifacts/dist/nixxie-cms-core-internal-unstable-artifacts.cjs.js +4 -3
  127. package/internal-unstable/artifacts/dist/nixxie-cms-core-internal-unstable-artifacts.esm.js +4 -3
  128. package/package.json +4 -4
  129. package/scripts/cli/dist/nixxie-cms-core-scripts-cli.cjs.js +4 -3
  130. package/scripts/cli/dist/nixxie-cms-core-scripts-cli.esm.js +4 -3
  131. package/scripts/dist/nixxie-cms-core-scripts.cjs.js +4 -3
  132. package/scripts/dist/nixxie-cms-core-scripts.esm.js +4 -3
  133. package/session/dist/nixxie-cms-core-session.cjs.js +286 -0
  134. package/session/dist/nixxie-cms-core-session.esm.js +279 -1
  135. package/src/access.ts +25 -25
  136. package/src/admin-ui/admin-meta-graphql.ts +5 -5
  137. package/src/admin-ui/components/CreateButtonLink.tsx +46 -46
  138. package/src/admin-ui/components/Navigation.tsx +3 -3
  139. package/src/admin-ui/context.tsx +6 -6
  140. package/src/admin-ui/utils/Fields.tsx +241 -241
  141. package/src/admin-ui/utils/actionData.ts +36 -36
  142. package/src/admin-ui/utils/filters.ts +148 -148
  143. package/src/admin-ui/utils/useCreateItem.ts +171 -171
  144. package/src/admin-ui/utils/utils.tsx +127 -127
  145. package/src/context.ts +1 -1
  146. package/src/fields/non-null-graphql.ts +115 -115
  147. package/src/fields/types/bigInt/index.ts +6 -6
  148. package/src/fields/types/bytes/index.ts +6 -6
  149. package/src/fields/types/calendarDay/index.ts +18 -19
  150. package/src/fields/types/checkbox/index.ts +6 -6
  151. package/src/fields/types/decimal/index.ts +6 -6
  152. package/src/fields/types/file/index.ts +8 -8
  153. package/src/fields/types/float/index.ts +6 -6
  154. package/src/fields/types/image/index.ts +8 -8
  155. package/src/fields/types/integer/index.ts +6 -6
  156. package/src/fields/types/json/index.ts +5 -5
  157. package/src/fields/types/multiselect/index.ts +7 -7
  158. package/src/fields/types/multiselect/views/index.tsx +149 -151
  159. package/src/fields/types/password/index.ts +6 -6
  160. package/src/fields/types/relationship/index.ts +13 -13
  161. package/src/fields/types/relationship/views/ComboboxMany.tsx +110 -110
  162. package/src/fields/types/relationship/views/ComboboxSingle.tsx +115 -115
  163. package/src/fields/types/relationship/views/ContextualActions.tsx +139 -139
  164. package/src/fields/types/relationship/views/index.tsx +492 -492
  165. package/src/fields/types/relationship/views/types.ts +46 -46
  166. package/src/fields/types/relationship/views/useApolloQuery.ts +185 -185
  167. package/src/fields/types/relationship/views/useFilter.tsx +109 -109
  168. package/src/fields/types/select/index.ts +6 -6
  169. package/src/fields/types/text/index.ts +6 -6
  170. package/src/fields/types/timestamp/index.ts +23 -21
  171. package/src/fields/types/virtual/index.ts +11 -11
  172. package/src/helpers.ts +773 -42
  173. package/src/index.ts +66 -24
  174. package/src/internal-unstable/admin-ui/pages/ItemPage/common.tsx +4 -4
  175. package/src/internal-unstable/admin-ui/pages/ItemPage/index.tsx +5 -5
  176. package/src/internal-unstable/admin-ui/pages/ListPage/index.tsx +8 -8
  177. package/src/lib/admin-meta.ts +369 -369
  178. package/src/lib/context/createContext.ts +5 -0
  179. package/src/lib/core/access-control.ts +434 -434
  180. package/src/lib/core/cascade.ts +236 -0
  181. package/src/lib/core/initialise-lists.ts +49 -33
  182. package/src/lib/core/mutations/index.ts +7 -0
  183. package/src/lib/core/mutations/nested-mutation-many-input-resolvers.ts +145 -145
  184. package/src/lib/core/mutations/nested-mutation-one-input-resolvers.ts +71 -71
  185. package/src/lib/core/queries/output-field.ts +178 -178
  186. package/src/lib/env.ts +50 -0
  187. package/src/lib/id-field.ts +2 -2
  188. package/src/lib/system.ts +221 -207
  189. package/src/lib/typescript-schema-printer.ts +227 -227
  190. package/src/list-features.ts +476 -0
  191. package/src/schema.ts +91 -22
  192. package/src/session.ts +225 -0
  193. package/src/types/admin-meta.ts +218 -218
  194. package/src/types/config/access-control.ts +186 -186
  195. package/src/types/config/fields.ts +96 -96
  196. package/src/types/config/hooks.ts +529 -529
  197. package/src/types/config/index.ts +185 -7
  198. package/src/types/config/lists.ts +606 -565
  199. package/src/types/context.ts +426 -55
  200. package/src/types/next-fields.ts +31 -31
  201. package/src/types/type-info.ts +38 -38
  202. package/src/types/type-tests.ts +21 -21
@@ -1,19 +1,112 @@
1
- import { i as idFieldType, m as merge } from './resolve-hooks-6813a045.esm.js';
2
- import { t as timestamp, r as relationship } from './index-15c8f81e.esm.js';
1
+ import { i as idFieldType, m as merge } from './resolve-hooks-9e676794.esm.js';
2
+ export { p as previewDelete } from './resolve-hooks-9e676794.esm.js';
3
+ import { randomBytes } from 'node:crypto';
4
+ import { t as timestamp, a as text, j as json } from './index-f1703b7b.esm.js';
5
+ import { r as relationship, s as select, i as integer } from './index-5d8b0b4e.esm.js';
3
6
  export { g, a as gWithContext, g as graphql } from './next-fields-9bf04ed8.esm.js';
4
7
  import 'pluralize';
5
8
  import '@graphql-ts/schema';
6
9
  import '@graphql-ts/extend';
7
10
  import 'graphql';
8
- import './non-null-graphql-a84ed64d.esm.js';
11
+ import 'node:async_hooks';
12
+ import './non-null-graphql-8c5feaae.esm.js';
9
13
  import 'node:path';
10
14
  import './admin-meta-14c60fec.esm.js';
15
+ import './utils-0cc426c8.esm.js';
11
16
  import 'decimal.js';
12
17
  import 'graphql-upload/GraphQLUpload.js';
13
18
 
19
+ function normalise(spec) {
20
+ if (Array.isArray(spec)) {
21
+ return Object.fromEntries(spec.map(name => [name, {}]));
22
+ }
23
+ return spec;
24
+ }
25
+
26
+ /**
27
+ * Validate `env` (default `process.env`) against a spec. Applies `default`s to the env
28
+ * object for unset variables, then throws one aggregated error listing every missing or
29
+ * malformed variable. Called automatically when the config declares `env`, and exported
30
+ * for standalone use.
31
+ */
32
+ function validateEnv(spec, env = process.env) {
33
+ const problems = [];
34
+ for (const [name, requirement] of Object.entries(normalise(spec))) {
35
+ let value = env[name];
36
+ if ((value === undefined || value === '') && requirement.default !== undefined) {
37
+ env[name] = requirement.default;
38
+ value = requirement.default;
39
+ }
40
+ const describe = requirement.description ? ` — ${requirement.description}` : '';
41
+ if (value === undefined || value === '') {
42
+ if (requirement.required !== false) {
43
+ problems.push(` • ${name} is not set${describe}`);
44
+ }
45
+ continue;
46
+ }
47
+ if (requirement.pattern && !requirement.pattern.test(value)) {
48
+ problems.push(` • ${name} does not match ${requirement.pattern}${describe}`);
49
+ }
50
+ }
51
+ if (problems.length) {
52
+ throw new Error(`Environment validation failed (${problems.length} problem${problems.length === 1 ? '' : 's'}):\n` + problems.join('\n'));
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Fold `config.plugins` into the config: merge plugin collections (key conflicts throw),
58
+ * run each plugin's `extendConfig`, and chain plugin `onConnect`s before `db.onConnect`.
59
+ */
60
+ function applyPlugins(config) {
61
+ var _config$plugins;
62
+ const plugins = (_config$plugins = config.plugins) !== null && _config$plugins !== void 0 ? _config$plugins : [];
63
+ if (!plugins.length) return config;
64
+ const seen = new Set();
65
+ for (const plugin of plugins) {
66
+ if (!plugin.name) throw new Error('Every plugin must have a `name`');
67
+ if (seen.has(plugin.name)) throw new Error(`Duplicate plugin name "${plugin.name}"`);
68
+ seen.add(plugin.name);
69
+ }
70
+ let next = {
71
+ ...config,
72
+ collections: {
73
+ ...config.collections
74
+ }
75
+ };
76
+ for (const plugin of plugins) {
77
+ for (const [key, collection] of Object.entries((_plugin$collections = plugin.collections) !== null && _plugin$collections !== void 0 ? _plugin$collections : {})) {
78
+ var _plugin$collections;
79
+ if (key in next.collections) {
80
+ throw new Error(`Plugin "${plugin.name}" adds the collection "${key}", but a collection with that key already exists`);
81
+ }
82
+ next.collections[key] = collection;
83
+ }
84
+ if (plugin.extendConfig) {
85
+ next = plugin.extendConfig(next);
86
+ if (!next) {
87
+ throw new Error(`Plugin "${plugin.name}".extendConfig must return the config`);
88
+ }
89
+ }
90
+ }
91
+ const onConnects = plugins.flatMap(plugin => plugin.onConnect ? [plugin.onConnect] : []);
92
+ if (onConnects.length) {
93
+ const userOnConnect = next.db.onConnect;
94
+ next = {
95
+ ...next,
96
+ db: {
97
+ ...next.db,
98
+ onConnect: async context => {
99
+ for (const fn of onConnects) await fn(context);
100
+ await (userOnConnect === null || userOnConnect === void 0 ? void 0 : userOnConnect(context));
101
+ }
102
+ }
103
+ };
104
+ }
105
+ return next;
106
+ }
14
107
  function listsWithDefaults(config, defaultIdField) {
15
108
  // some error checking
16
- for (const [listKey, list] of Object.entries(config.lists)) {
109
+ for (const [listKey, list] of Object.entries(config.collections)) {
17
110
  var _list$db;
18
111
  if (list.fields.id) {
19
112
  throw new Error(`"fields.id" is reserved by Nixxie, use "db.idField" for the "${listKey}" list`);
@@ -23,7 +116,7 @@ function listsWithDefaults(config, defaultIdField) {
23
116
  }
24
117
  }
25
118
  return Object.fromEntries([...function* () {
26
- for (const [listKey, list] of Object.entries(config.lists)) {
119
+ for (const [listKey, list] of Object.entries(config.collections)) {
27
120
  var _list$db$idField, _list$db2;
28
121
  yield [listKey, {
29
122
  listKey,
@@ -32,6 +125,7 @@ function listsWithDefaults(config, defaultIdField) {
32
125
  defaultIsOrderable: true,
33
126
  // TODO: move to access control?
34
127
  isSingleton: false,
128
+ cascade: [],
35
129
  ...list,
36
130
  db: {
37
131
  ...list.db
@@ -75,8 +169,10 @@ async function noop() {}
75
169
  function identity(x) {
76
170
  return x;
77
171
  }
78
- function config(config) {
79
- var _config$db, _config$db$url, _config$db$idField, _config$server, _config$server2, _config$server$cors, _config$server3, _config$types$path, _config$types, _config$db$shadowData, _config$db2, _config$db$extendPris, _config$db3, _config$db$extendPris2, _config$db4, _config$db$onConnect, _config$db$prismaClie, _config$db5, _config$db$prismaSche, _config$db6, _config$db$idField2, _config$db7, _config$db$enableLogg, _config$graphql$path, _config$graphql, _config$graphql$playg, _config$graphql2, _config$graphql$schem, _config$graphql3, _config$graphql$exten, _config$graphql4, _config$server$maxFil, _config$server4, _config$server$extend, _config$server5, _config$server$extend2, _config$server6, _config$telemetry, _config$ui$basePath, _config$ui, _config$ui$isAccessAl, _config$ui2, _config$ui$isDisabled, _config$ui3, _config$ui$getAdditio, _config$ui4, _config$ui$pageMiddle, _config$ui5, _config$ui$publicPage, _config$ui6;
172
+ function buildConfig(config) {
173
+ var _config$db, _config$db$url, _config$db$idField, _config$server, _config$server2, _config$server$cors, _config$server3, _config, _config2, _config$types$path, _config$types, _config$db$shadowData, _config$db2, _config$db$extendPris, _config$db3, _config$db$extendPris2, _config$db4, _config$db$onConnect, _config$db$prismaClie, _config$db5, _config$db$prismaSche, _config$db6, _config$db$idField2, _config$db7, _config$db$enableLogg, _config$graphql$path, _config$graphql, _config$graphql$playg, _config$graphql2, _config$graphql$schem, _config$graphql3, _config$graphql$exten, _config$graphql4, _config$server$maxFil, _config$server4, _config$server$extend, _config$server5, _config$server$extend2, _config$server6, _config$telemetry, _config$ui$basePath, _config$ui, _config$ui$isAccessAl, _config$ui2, _config$ui$isDisabled, _config$ui3, _config$ui$getAdditio, _config$ui4, _config$ui$pageMiddle, _config$ui5, _config$ui$publicPage, _config$ui6;
174
+ if (config.env) validateEnv(config.env);
175
+ config = applyPlugins(config);
80
176
  if (!['postgresql', 'sqlite', 'mysql'].includes(config.db.provider)) {
81
177
  throw new TypeError(`"db.provider" only supports "sqlite", "postgresql" or "mysql"`);
82
178
  }
@@ -93,10 +189,10 @@ function config(config) {
93
189
  const httpOptions = {
94
190
  port: 3000
95
191
  };
96
- if (config !== null && config !== void 0 && config.server && 'port' in config.server) {
192
+ if ((_config = config) !== null && _config !== void 0 && _config.server && 'port' in config.server) {
97
193
  httpOptions.port = config.server.port;
98
194
  }
99
- if (config !== null && config !== void 0 && config.server && 'options' in config.server && config.server.options) {
195
+ if ((_config2 = config) !== null && _config2 !== void 0 && _config2.server && 'options' in config.server && config.server.options) {
100
196
  Object.assign(httpOptions, config.server.options);
101
197
  }
102
198
  return {
@@ -144,6 +240,11 @@ function config(config) {
144
240
  search: config.search,
145
241
  notifications: config.notifications,
146
242
  ai: config.ai,
243
+ versioning: config.versioning,
244
+ workflow: config.workflow,
245
+ apiKeys: config.apiKeys,
246
+ logger: config.logger,
247
+ backup: config.backup,
147
248
  telemetry: (_config$telemetry = config.telemetry) !== null && _config$telemetry !== void 0 ? _config$telemetry : true,
148
249
  ui: {
149
250
  ...config.ui,
@@ -157,7 +258,7 @@ function config(config) {
157
258
  };
158
259
  }
159
260
  let i = 0;
160
- function group(config) {
261
+ function fieldGroup(config) {
161
262
  var _config$description;
162
263
  const keys = Object.keys(config.fields);
163
264
  if (keys.some(key => key.startsWith('__group'))) {
@@ -173,18 +274,408 @@ function group(config) {
173
274
  ...config.fields
174
275
  }; // TODO: FIXME, see initialise-lists.ts:getListsWithInitialisedFields
175
276
  }
176
- function list(listConfig) {
277
+ function collection(listConfig) {
177
278
  return {
178
279
  ...listConfig
179
280
  };
180
281
  }
181
- function action(action) {
282
+ function createAction(action) {
182
283
  return {
183
284
  ...action,
184
285
  ___defineActionsWithActionFunction: true
185
286
  };
186
287
  }
187
288
 
289
+ /**
290
+ * Declarative collection features compiled into hooks + access-control filters by
291
+ * `defineCollection()`: computed fields, constraints, default filters, state machines,
292
+ * policies, events, search indexing and version snapshots.
293
+ *
294
+ * Everything here builds on the public hook/access surface — no resolver internals —
295
+ * so the features compose with mixins and user hooks via the same merge pipeline.
296
+ */
297
+
298
+ // ── Option types ──
299
+
300
+ /**
301
+ * Persisted derived fields, recalculated on every create/update after all other
302
+ * `resolveInput` hooks have run. The target keys must be real fields on the collection
303
+ * (unlike `virtual()` fields, computed values are stored — so they can be filtered and
304
+ * sorted). `merged` is the item's prospective state (existing values + this write).
305
+ *
306
+ * @example
307
+ * computed: { total: ({ merged }) => merged.price * merged.quantity }
308
+ */
309
+
310
+ /**
311
+ * Data-integrity rules checked before every create/update.
312
+ *
313
+ * - `uniqueTogether`: compound uniqueness over scalar fields (e.g. `[['tenant', 'slug']]`).
314
+ * Checked with a query, so add a DB index for hot paths.
315
+ * - `checks`: named cross-field rules; return an error message to reject the write.
316
+ *
317
+ * @example
318
+ * constraints: {
319
+ * uniqueTogether: [['translationKey', 'locale']],
320
+ * checks: { dates: ({ merged }) => merged.endDate <= merged.startDate ? 'endDate must be after startDate' : undefined },
321
+ * }
322
+ */
323
+
324
+ /**
325
+ * A where-filter automatically ANDed into every query/update/delete — including the
326
+ * Admin UI, which respects access filters. This is what makes `withSoftDelete()` real:
327
+ *
328
+ * @example
329
+ * defaultFilter: { deletedAt: null }
330
+ * @example
331
+ * defaultFilter: ({ session }) => session?.data?.isAdmin ? true : { status: { equals: 'published' } }
332
+ */
333
+
334
+ /**
335
+ * Enforce legal status transitions on a select field at the mutation layer.
336
+ *
337
+ * @example
338
+ * stateMachine: {
339
+ * field: 'status',
340
+ * transitions: { draft: ['review'], review: ['published', 'draft'], published: ['archived'] },
341
+ * guards: { 'review->published': ({ session }) => session?.data?.role === 'editor' || 'Only editors can publish' },
342
+ * }
343
+ */
344
+
345
+ /** One row-level access rule: the first rule whose `when` matches decides the filter. */
346
+
347
+ /**
348
+ * Declarative row-level access: per operation, rules are evaluated in order and the
349
+ * first matching `when` supplies the filter; no match means no access. ANDed with any
350
+ * explicit `access.filter` you also configure. Pairs naturally with @nixxie-cms/rbac.
351
+ *
352
+ * @example
353
+ * policies: {
354
+ * query: [
355
+ * { when: s => s?.data?.role === 'admin', filter: true },
356
+ * { when: s => !!s, filter: s => ({ author: { id: { equals: s.itemId } } }) },
357
+ * ],
358
+ * }
359
+ */
360
+
361
+ /**
362
+ * Emit lifecycle events through `context.services.webhooks` after every write:
363
+ * `<prefix>.created` / `.updated` / `.deleted` (prefix defaults to the list key).
364
+ * No-op when the webhooks service is not configured.
365
+ */
366
+
367
+ /**
368
+ * Keep a search index in sync through `context.services.search`: documents are indexed
369
+ * after create/update and removed after delete. No-op when search is not configured.
370
+ */
371
+
372
+ /**
373
+ * Snapshot every create/update into `context.services.versioning` (resource = list key).
374
+ * No-op when versioning is not configured.
375
+ */
376
+
377
+ // ── Compilation to hooks ──
378
+
379
+ const mergedView = args => {
380
+ var _args$item, _args$resolvedData;
381
+ return {
382
+ ...((_args$item = args.item) !== null && _args$item !== void 0 ? _args$item : {}),
383
+ ...((_args$resolvedData = args.resolvedData) !== null && _args$resolvedData !== void 0 ? _args$resolvedData : {})
384
+ };
385
+ };
386
+ function computedHooks(computed) {
387
+ return {
388
+ resolveInput: async args => {
389
+ const out = {
390
+ ...args.resolvedData
391
+ };
392
+ for (const [field, fn] of Object.entries(computed)) {
393
+ var _args$item2;
394
+ out[field] = await fn({
395
+ operation: args.operation,
396
+ resolvedData: out,
397
+ merged: {
398
+ ...((_args$item2 = args.item) !== null && _args$item2 !== void 0 ? _args$item2 : {}),
399
+ ...out
400
+ },
401
+ item: args.item,
402
+ context: args.context
403
+ });
404
+ }
405
+ return out;
406
+ }
407
+ };
408
+ }
409
+ function constraintsHooks(constraints) {
410
+ return {
411
+ validate: async args => {
412
+ const {
413
+ operation,
414
+ addValidationError
415
+ } = args;
416
+ if (operation === 'delete') return;
417
+ const merged = mergedView(args);
418
+ for (const tuple of (_constraints$uniqueTo = constraints.uniqueTogether) !== null && _constraints$uniqueTo !== void 0 ? _constraints$uniqueTo : []) {
419
+ var _constraints$uniqueTo;
420
+ const values = tuple.map(field => merged[field]);
421
+ // Incomplete tuples (a NULL member) are not checked — same semantics as SQL unique indexes.
422
+ if (values.some(value => value === undefined || value === null)) continue;
423
+ const where = {};
424
+ tuple.forEach((field, i) => where[field] = {
425
+ equals: values[i]
426
+ });
427
+ try {
428
+ const clashes = await args.context.sudo().db[args.listKey].findMany({
429
+ where,
430
+ take: 2
431
+ });
432
+ const other = clashes.find(clash => !args.item || String(clash.id) !== String(args.item.id));
433
+ if (other) {
434
+ addValidationError(`Another item already exists with the same ${tuple.join(' + ')}`);
435
+ }
436
+ } catch (err) {
437
+ // A malformed tuple (unknown/non-scalar field) should fail loudly, not silently pass.
438
+ addValidationError(`uniqueTogether check for (${tuple.join(', ')}) failed: ${err instanceof Error ? err.message : err}`);
439
+ }
440
+ }
441
+ for (const check of Object.values((_constraints$checks = constraints.checks) !== null && _constraints$checks !== void 0 ? _constraints$checks : {})) {
442
+ var _constraints$checks;
443
+ const message = await check({
444
+ operation: args.operation,
445
+ resolvedData: args.resolvedData,
446
+ merged,
447
+ item: args.item,
448
+ context: args.context
449
+ });
450
+ if (typeof message === 'string' && message.length > 0) addValidationError(message);
451
+ }
452
+ }
453
+ };
454
+ }
455
+ function stateMachineHooks(machine) {
456
+ const {
457
+ field,
458
+ transitions,
459
+ guards = {}
460
+ } = machine;
461
+ const initial = machine.initial === undefined ? undefined : Array.isArray(machine.initial) ? machine.initial : [machine.initial];
462
+ return {
463
+ validate: async args => {
464
+ var _transitions$previous;
465
+ const {
466
+ operation,
467
+ resolvedData,
468
+ item,
469
+ addValidationError
470
+ } = args;
471
+ if (operation === 'delete') return;
472
+ const next = resolvedData === null || resolvedData === void 0 ? void 0 : resolvedData[field];
473
+ if (next === undefined) return;
474
+ if (operation === 'create') {
475
+ if (initial && next != null && !initial.includes(next)) {
476
+ addValidationError(`"${field}" cannot start as "${next}" (allowed: ${initial.join(', ')})`);
477
+ }
478
+ return;
479
+ }
480
+ const previous = item === null || item === void 0 ? void 0 : item[field];
481
+ if (next === previous) return;
482
+ const allowed = (_transitions$previous = transitions[previous]) !== null && _transitions$previous !== void 0 ? _transitions$previous : [];
483
+ if (!allowed.includes(next)) {
484
+ addValidationError(`"${field}" cannot change from "${previous}" to "${next}"` + (allowed.length ? ` (allowed: ${allowed.join(', ')})` : ' (no transitions from this state)'));
485
+ return;
486
+ }
487
+ const guard = guards[`${previous}->${next}`];
488
+ if (guard) {
489
+ var _args$context;
490
+ const verdict = await guard({
491
+ item,
492
+ resolvedData,
493
+ context: args.context,
494
+ session: (_args$context = args.context) === null || _args$context === void 0 ? void 0 : _args$context.session
495
+ });
496
+ if (verdict !== true) {
497
+ addValidationError(typeof verdict === 'string' ? verdict : `"${field}" transition "${previous}" → "${next}" was blocked`);
498
+ }
499
+ }
500
+ }
501
+ };
502
+ }
503
+ const pastTense = {
504
+ create: 'created',
505
+ update: 'updated',
506
+ delete: 'deleted'
507
+ };
508
+ function eventsHooks(events) {
509
+ var _options$operations;
510
+ const options = events === true ? {} : events;
511
+ const operations = (_options$operations = options.operations) !== null && _options$operations !== void 0 ? _options$operations : ['create', 'update', 'delete'];
512
+ return {
513
+ afterOperation: async args => {
514
+ var _args$context2;
515
+ if (!operations.includes(args.operation)) return;
516
+ const webhooks = (_args$context2 = args.context) === null || _args$context2 === void 0 || (_args$context2 = _args$context2.services) === null || _args$context2 === void 0 ? void 0 : _args$context2.webhooks;
517
+ if (!webhooks) return;
518
+ try {
519
+ var _args$item3, _options$prefix;
520
+ const subject = (_args$item3 = args.item) !== null && _args$item3 !== void 0 ? _args$item3 : args.originalItem;
521
+ const event = `${(_options$prefix = options.prefix) !== null && _options$prefix !== void 0 ? _options$prefix : args.listKey}.${pastTense[args.operation]}`;
522
+ const payload = options.payload ? await options.payload(args) : {
523
+ listKey: args.listKey,
524
+ id: (subject === null || subject === void 0 ? void 0 : subject.id) != null ? String(subject.id) : undefined,
525
+ item: subject
526
+ };
527
+ await webhooks.trigger(event, payload);
528
+ } catch (err) {
529
+ console.error(`[nixxie] events: failed to emit for ${args.listKey}:`, err);
530
+ }
531
+ }
532
+ };
533
+ }
534
+
535
+ /** Copy the indexable scalar values off an item (used when `fields` is not specified). */
536
+ function scalarDocument(item) {
537
+ const doc = {};
538
+ for (const [key, value] of Object.entries(item)) {
539
+ if (key.startsWith('__')) continue;
540
+ if (value === null) doc[key] = null;else if (value instanceof Date) doc[key] = value.toISOString();else if (['string', 'number', 'boolean'].includes(typeof value)) doc[key] = value;
541
+ }
542
+ return doc;
543
+ }
544
+ function searchableHooks(searchable) {
545
+ const options = searchable === true ? {} : searchable;
546
+ return {
547
+ afterOperation: async args => {
548
+ var _args$context3, _options$index;
549
+ const search = (_args$context3 = args.context) === null || _args$context3 === void 0 || (_args$context3 = _args$context3.services) === null || _args$context3 === void 0 ? void 0 : _args$context3.search;
550
+ if (!search) return;
551
+ const indexName = (_options$index = options.index) !== null && _options$index !== void 0 ? _options$index : String(args.listKey).toLowerCase();
552
+ try {
553
+ if (args.operation === 'delete') {
554
+ await search.remove(indexName, String(args.originalItem.id));
555
+ return;
556
+ }
557
+ const item = args.item;
558
+ const picked = options.fields ? Object.fromEntries(options.fields.map(field => [field, item[field] instanceof Date ? item[field].toISOString() : item[field]])) : scalarDocument(item);
559
+ await search.index(indexName, {
560
+ ...picked,
561
+ id: String(item.id)
562
+ });
563
+ } catch (err) {
564
+ console.error(`[nixxie] searchable: failed to sync index "${indexName}":`, err);
565
+ }
566
+ }
567
+ };
568
+ }
569
+ function versionedHooks(versioned) {
570
+ const options = versioned === true ? {} : versioned;
571
+ return {
572
+ afterOperation: async args => {
573
+ var _args$context4;
574
+ if (args.operation === 'delete') return;
575
+ const versioning = (_args$context4 = args.context) === null || _args$context4 === void 0 || (_args$context4 = _args$context4.services) === null || _args$context4 === void 0 ? void 0 : _args$context4.versioning;
576
+ if (!versioning) return;
577
+ try {
578
+ var _args$context5, _options$label;
579
+ const session = (_args$context5 = args.context) === null || _args$context5 === void 0 ? void 0 : _args$context5.session;
580
+ await versioning.snapshot({
581
+ resource: args.listKey,
582
+ resourceId: String(args.item.id),
583
+ data: scalarSafe(args.item),
584
+ label: (_options$label = options.label) === null || _options$label === void 0 ? void 0 : _options$label.call(options, args),
585
+ actor: (session === null || session === void 0 ? void 0 : session.itemId) != null ? {
586
+ id: String(session.itemId)
587
+ } : undefined
588
+ });
589
+ } catch (err) {
590
+ console.error(`[nixxie] versioned: failed to snapshot ${args.listKey}:`, err);
591
+ }
592
+ }
593
+ };
594
+ }
595
+
596
+ /** Snapshot-safe clone: keeps JSON-representable values, ISO-stringifies dates. */
597
+ function scalarSafe(item) {
598
+ const out = {};
599
+ for (const [key, value] of Object.entries(item)) {
600
+ if (value instanceof Date) out[key] = value.toISOString();else if (typeof value === 'bigint') out[key] = value.toString();else if (typeof value !== 'function' && typeof value !== 'symbol') out[key] = value;
601
+ }
602
+ return out;
603
+ }
604
+
605
+ /** Compile the declarative features into hook fragments, in a deliberate order. */
606
+ function compileFeatureHooks(features) {
607
+ const hooks = [];
608
+ if (features.computed) hooks.push(computedHooks(features.computed));
609
+ if (features.constraints) hooks.push(constraintsHooks(features.constraints));
610
+ if (features.stateMachine) hooks.push(stateMachineHooks(features.stateMachine));
611
+ if (features.events) hooks.push(eventsHooks(features.events));
612
+ if (features.searchable) hooks.push(searchableHooks(features.searchable));
613
+ if (features.versioned) hooks.push(versionedHooks(features.versioned));
614
+ return hooks;
615
+ }
616
+
617
+ // ── Compilation to access filters ──
618
+
619
+ /** AND two access filters; `true`/missing means unrestricted, `false` wins outright. */
620
+ function andFilters(a, b) {
621
+ if (a === undefined) return b;
622
+ return async args => {
623
+ const ra = typeof a === 'function' ? await a(args) : a;
624
+ const rb = typeof b === 'function' ? await b(args) : b;
625
+ if (ra === false || rb === false) return false;
626
+ if (ra === true) return rb;
627
+ if (rb === true) return ra;
628
+ return {
629
+ AND: [ra, rb]
630
+ };
631
+ };
632
+ }
633
+ function policyFilter(rules) {
634
+ return ({
635
+ session
636
+ }) => {
637
+ for (const rule of rules) {
638
+ if (!rule.when(session)) continue;
639
+ return typeof rule.filter === 'function' ? rule.filter(session) : rule.filter;
640
+ }
641
+ return false;
642
+ };
643
+ }
644
+
645
+ /**
646
+ * Merge `defaultFilter` and `policies` into an access-control object. Existing filters
647
+ * are preserved and ANDed with the feature filters.
648
+ */
649
+ function applyAccessFeatures(access, features) {
650
+ var _access$filter;
651
+ const {
652
+ defaultFilter,
653
+ policies
654
+ } = features;
655
+ if (!defaultFilter && !policies) return access;
656
+ const filter = {
657
+ ...((_access$filter = access === null || access === void 0 ? void 0 : access.filter) !== null && _access$filter !== void 0 ? _access$filter : {})
658
+ };
659
+ for (const operation of ['query', 'update', 'delete']) {
660
+ let merged = filter[operation];
661
+ if (defaultFilter) {
662
+ merged = andFilters(merged, typeof defaultFilter === 'function' ? args => defaultFilter({
663
+ session: args.session,
664
+ context: args.context
665
+ }) : defaultFilter);
666
+ }
667
+ const rules = policies === null || policies === void 0 ? void 0 : policies[operation];
668
+ if (rules !== null && rules !== void 0 && rules.length) {
669
+ merged = andFilters(merged, policyFilter(rules));
670
+ }
671
+ if (merged !== undefined) filter[operation] = merged;
672
+ }
673
+ return {
674
+ ...(access !== null && access !== void 0 ? access : {}),
675
+ filter
676
+ };
677
+ }
678
+
188
679
  // ================================================================
189
680
  // Validators — use inside field `validation` config
190
681
  // ================================================================
@@ -236,6 +727,72 @@ const validators = {
236
727
  }
237
728
  };
238
729
 
730
+ // ================================================================
731
+ // Access presets — readable shorthands for common access patterns
732
+ // ================================================================
733
+ //
734
+ // Spelling out an access-control object on every list gets repetitive. In
735
+ // practice 90% of lists fall into a handful of patterns, so we name them.
736
+ // Anything more bespoke can still drop down to a raw access object.
737
+
738
+ const isSignedIn = ({
739
+ session
740
+ }) => !!session;
741
+ const accessPresets = {
742
+ public: () => true,
743
+ authenticated: {
744
+ operation: {
745
+ query: isSignedIn,
746
+ create: isSignedIn,
747
+ update: isSignedIn,
748
+ delete: isSignedIn
749
+ }
750
+ },
751
+ publicReadAuthenticatedWrite: {
752
+ operation: {
753
+ query: () => true,
754
+ create: isSignedIn,
755
+ update: isSignedIn,
756
+ delete: isSignedIn
757
+ }
758
+ },
759
+ readOnly: {
760
+ operation: {
761
+ query: () => true,
762
+ create: () => false,
763
+ update: () => false,
764
+ delete: () => false
765
+ }
766
+ },
767
+ owner(field = 'user') {
768
+ const scopeToOwner = ({
769
+ session
770
+ }) => {
771
+ if (!(session !== null && session !== void 0 && session.itemId)) return false;
772
+ return {
773
+ [field]: {
774
+ id: {
775
+ equals: session.itemId
776
+ }
777
+ }
778
+ };
779
+ };
780
+ return {
781
+ operation: {
782
+ query: isSignedIn,
783
+ create: isSignedIn,
784
+ update: isSignedIn,
785
+ delete: isSignedIn
786
+ },
787
+ filter: {
788
+ query: scopeToOwner,
789
+ update: scopeToOwner,
790
+ delete: scopeToOwner
791
+ }
792
+ };
793
+ }
794
+ };
795
+
239
796
  // ================================================================
240
797
  // Mixin system
241
798
  // ================================================================
@@ -391,6 +948,760 @@ function withAudit(userListKey = 'User') {
391
948
  };
392
949
  }
393
950
 
951
+ /**
952
+ * Turn an arbitrary string into a URL-safe slug. Pure, dependency-free.
953
+ */
954
+ function slugify(input) {
955
+ return input.toString().normalize('NFKD').replace(/[̀-ͯ]/g, '') // strip accents
956
+ .toLowerCase().trim().replace(/[^a-z0-9]+/g, '-') // non-alphanumerics → dashes
957
+ .replace(/^-+|-+$/g, ''); // trim leading/trailing dashes
958
+ }
959
+
960
+ /**
961
+ * Adds a URL-friendly `slug` field that is auto-generated from another field
962
+ * (e.g. `title`) when left blank, and normalised when provided.
963
+ *
964
+ * Solves a perennial papercut: there's no built-in slug field, so everyone
965
+ * re-implements the same `resolveInput` hook by hand.
966
+ *
967
+ * @example
968
+ * defineCollection({ mixins: [withSlug({ from: 'title' })], fields: { title: text() } })
969
+ */
970
+ function withSlug(opts = {
971
+ from: 'title'
972
+ }) {
973
+ var _opts$field, _opts$isIndexed;
974
+ const fieldKey = (_opts$field = opts.field) !== null && _opts$field !== void 0 ? _opts$field : 'slug';
975
+ const from = opts.from;
976
+ return {
977
+ fields: {
978
+ [fieldKey]: text({
979
+ isIndexed: (_opts$isIndexed = opts.isIndexed) !== null && _opts$isIndexed !== void 0 ? _opts$isIndexed : 'unique',
980
+ ui: {
981
+ description: `URL slug — auto-generated from "${from}" when left blank.`
982
+ }
983
+ })
984
+ },
985
+ hooks: {
986
+ resolveInput: ({
987
+ resolvedData,
988
+ inputData
989
+ }) => {
990
+ var _from;
991
+ const provided = resolvedData[fieldKey];
992
+ if (typeof provided === 'string' && provided.length > 0) {
993
+ return {
994
+ ...resolvedData,
995
+ [fieldKey]: slugify(provided)
996
+ };
997
+ }
998
+ const source = (_from = inputData === null || inputData === void 0 ? void 0 : inputData[from]) !== null && _from !== void 0 ? _from : resolvedData === null || resolvedData === void 0 ? void 0 : resolvedData[from];
999
+ if (typeof source === 'string' && source.length > 0) {
1000
+ return {
1001
+ ...resolvedData,
1002
+ [fieldKey]: slugify(source)
1003
+ };
1004
+ }
1005
+ return resolvedData;
1006
+ }
1007
+ }
1008
+ };
1009
+ }
1010
+
1011
+ /**
1012
+ * Adds a draft → published → archived workflow: a `status` select plus a
1013
+ * `publishedAt` timestamp that is stamped automatically the first time an item
1014
+ * transitions to `published`.
1015
+ *
1016
+ * Publishing is otherwise left entirely to the developer; this bakes in the
1017
+ * common content lifecycle so a blog/news/docs list works out of the box.
1018
+ */
1019
+ function withPublishing(opts = {}) {
1020
+ var _opts$defaultStatus;
1021
+ const defaultStatus = (_opts$defaultStatus = opts.defaultStatus) !== null && _opts$defaultStatus !== void 0 ? _opts$defaultStatus : 'draft';
1022
+ return {
1023
+ fields: {
1024
+ status: select({
1025
+ type: 'enum',
1026
+ options: [{
1027
+ label: 'Draft',
1028
+ value: 'draft'
1029
+ }, {
1030
+ label: 'Published',
1031
+ value: 'published'
1032
+ }, {
1033
+ label: 'Archived',
1034
+ value: 'archived'
1035
+ }],
1036
+ defaultValue: defaultStatus,
1037
+ ui: {
1038
+ displayMode: 'segmented-control'
1039
+ }
1040
+ }),
1041
+ publishedAt: timestamp({
1042
+ ui: {
1043
+ createView: {
1044
+ fieldMode: 'hidden'
1045
+ },
1046
+ itemView: {
1047
+ fieldMode: 'read'
1048
+ },
1049
+ listView: {
1050
+ fieldMode: 'read'
1051
+ }
1052
+ }
1053
+ })
1054
+ },
1055
+ hooks: {
1056
+ resolveInput: ({
1057
+ resolvedData,
1058
+ item
1059
+ }) => {
1060
+ var _status;
1061
+ const nextStatus = (_status = resolvedData.status) !== null && _status !== void 0 ? _status : item === null || item === void 0 ? void 0 : item.status;
1062
+ const alreadyPublished = item === null || item === void 0 ? void 0 : item.publishedAt;
1063
+ const incomingPublishedAt = resolvedData.publishedAt;
1064
+ if (nextStatus === 'published' && !alreadyPublished && incomingPublishedAt == null) {
1065
+ return {
1066
+ ...resolvedData,
1067
+ publishedAt: new Date().toISOString()
1068
+ };
1069
+ }
1070
+ return resolvedData;
1071
+ }
1072
+ }
1073
+ };
1074
+ }
1075
+
1076
+ /**
1077
+ * Adds standard SEO metadata fields, grouped together in the Admin UI.
1078
+ * Drop-in for any content list that needs search/social previews.
1079
+ */
1080
+ function withSEO() {
1081
+ return {
1082
+ fields: {
1083
+ metaTitle: text({
1084
+ ui: {
1085
+ description: 'Title used by search engines and social previews.'
1086
+ }
1087
+ }),
1088
+ metaDescription: text({
1089
+ ui: {
1090
+ displayMode: 'textarea',
1091
+ description: 'Short summary (~155 characters).'
1092
+ }
1093
+ }),
1094
+ ogImage: text({
1095
+ ui: {
1096
+ description: 'Absolute URL to the social sharing image.'
1097
+ }
1098
+ })
1099
+ }
1100
+ };
1101
+ }
1102
+
1103
+ /**
1104
+ * Adds an integer `order` field for manual sorting/drag-ordering of items.
1105
+ */
1106
+ function withSortable(opts = {}) {
1107
+ var _opts$field2;
1108
+ const fieldKey = (_opts$field2 = opts.field) !== null && _opts$field2 !== void 0 ? _opts$field2 : 'order';
1109
+ return {
1110
+ fields: {
1111
+ [fieldKey]: integer({
1112
+ defaultValue: 0,
1113
+ ui: {
1114
+ description: 'Manual sort position (lower comes first).'
1115
+ }
1116
+ })
1117
+ }
1118
+ };
1119
+ }
1120
+
1121
+ /**
1122
+ * Adds self-referential `parent` / `children` relationships for tree-shaped content
1123
+ * (categories, menus, pages), with cycle prevention: an item can never be moved under
1124
+ * one of its own descendants.
1125
+ *
1126
+ * @param listKey - The key of the collection this mixin is applied to (needed for the
1127
+ * self-referencing relationship and ancestor checks).
1128
+ *
1129
+ * @example
1130
+ * defineCollection({ mixins: [withTreeStructure('Category')], fields: { name: text() } })
1131
+ */
1132
+ function withTreeStructure(listKey, opts = {}) {
1133
+ var _opts$parentField, _opts$childrenField;
1134
+ const parentField = (_opts$parentField = opts.parentField) !== null && _opts$parentField !== void 0 ? _opts$parentField : 'parent';
1135
+ const childrenField = (_opts$childrenField = opts.childrenField) !== null && _opts$childrenField !== void 0 ? _opts$childrenField : 'children';
1136
+ return {
1137
+ fields: {
1138
+ [parentField]: relationship({
1139
+ ref: `${listKey}.${childrenField}`,
1140
+ ui: {
1141
+ description: 'Parent item in the tree (leave empty for a root item).'
1142
+ }
1143
+ }),
1144
+ [childrenField]: relationship({
1145
+ ref: `${listKey}.${parentField}`,
1146
+ many: true,
1147
+ ui: {
1148
+ displayMode: 'count',
1149
+ itemView: {
1150
+ fieldMode: 'read'
1151
+ }
1152
+ }
1153
+ })
1154
+ },
1155
+ hooks: {
1156
+ validate: async args => {
1157
+ var _parentOp$connect;
1158
+ const {
1159
+ operation,
1160
+ resolvedData,
1161
+ item,
1162
+ context,
1163
+ addValidationError
1164
+ } = args;
1165
+ if (operation !== 'update') return;
1166
+ const parentOp = resolvedData === null || resolvedData === void 0 ? void 0 : resolvedData[parentField];
1167
+ const newParentId = parentOp === null || parentOp === void 0 || (_parentOp$connect = parentOp.connect) === null || _parentOp$connect === void 0 ? void 0 : _parentOp$connect.id;
1168
+ if (newParentId == null) return;
1169
+ if (String(newParentId) === String(item.id)) {
1170
+ addValidationError(`"${parentField}" cannot point at the item itself`);
1171
+ return;
1172
+ }
1173
+ // Walk up from the new parent — finding the item means we'd create a cycle.
1174
+ const sudo = context.sudo();
1175
+ let cursor = newParentId;
1176
+ for (let depth = 0; depth < 100 && cursor != null; depth++) {
1177
+ var _ancestor$parentField, _ancestor$parentField2;
1178
+ const ancestor = await sudo.query[listKey].findOne({
1179
+ where: {
1180
+ id: String(cursor)
1181
+ },
1182
+ query: `id ${parentField} { id }`
1183
+ });
1184
+ if (!ancestor) return;
1185
+ cursor = (_ancestor$parentField = (_ancestor$parentField2 = ancestor[parentField]) === null || _ancestor$parentField2 === void 0 ? void 0 : _ancestor$parentField2.id) !== null && _ancestor$parentField !== void 0 ? _ancestor$parentField : null;
1186
+ if (cursor != null && String(cursor) === String(item.id)) {
1187
+ addValidationError(`"${parentField}" would create a cycle — the new parent is a descendant of this item`);
1188
+ return;
1189
+ }
1190
+ }
1191
+ }
1192
+ }
1193
+ };
1194
+ }
1195
+
1196
+ /**
1197
+ * Multi-tenancy: adds a required `tenant` relationship that is auto-assigned from the
1198
+ * session on create. Combine with `tenantAccessFilter()` in the collection's
1199
+ * `access.filter` rules to scope every query/update/delete to the session's tenant.
1200
+ *
1201
+ * @example
1202
+ * defineCollection({
1203
+ * mixins: [withTenant({ ref: 'Tenant' })],
1204
+ * access: {
1205
+ * filter: {
1206
+ * query: tenantAccessFilter(),
1207
+ * update: tenantAccessFilter(),
1208
+ * delete: tenantAccessFilter(),
1209
+ * },
1210
+ * },
1211
+ * fields: { ... },
1212
+ * })
1213
+ */
1214
+ function withTenant(opts = {}) {
1215
+ var _opts$ref, _opts$field3, _opts$getTenantId;
1216
+ const ref = (_opts$ref = opts.ref) !== null && _opts$ref !== void 0 ? _opts$ref : 'Tenant';
1217
+ const field = (_opts$field3 = opts.field) !== null && _opts$field3 !== void 0 ? _opts$field3 : 'tenant';
1218
+ const getTenantId = (_opts$getTenantId = opts.getTenantId) !== null && _opts$getTenantId !== void 0 ? _opts$getTenantId : defaultGetTenantId;
1219
+ return {
1220
+ fields: {
1221
+ [field]: relationship({
1222
+ ref,
1223
+ ui: {
1224
+ createView: {
1225
+ fieldMode: 'hidden'
1226
+ },
1227
+ itemView: {
1228
+ fieldMode: 'read'
1229
+ }
1230
+ }
1231
+ })
1232
+ },
1233
+ hooks: {
1234
+ resolveInput: ({
1235
+ operation,
1236
+ resolvedData,
1237
+ context
1238
+ }) => {
1239
+ if (operation !== 'create') return resolvedData;
1240
+ if (resolvedData[field]) return resolvedData;
1241
+ const tenantId = getTenantId(context.session);
1242
+ if (!tenantId) return resolvedData;
1243
+ return {
1244
+ ...resolvedData,
1245
+ [field]: {
1246
+ connect: {
1247
+ id: tenantId
1248
+ }
1249
+ }
1250
+ };
1251
+ },
1252
+ validate: async args => {
1253
+ const {
1254
+ operation,
1255
+ resolvedData,
1256
+ addValidationError
1257
+ } = args;
1258
+ if (opts.optional || operation !== 'create') return;
1259
+ if (!(resolvedData !== null && resolvedData !== void 0 && resolvedData[field])) {
1260
+ addValidationError(`"${field}" is required — no tenant found on the session`);
1261
+ }
1262
+ }
1263
+ }
1264
+ };
1265
+ }
1266
+ function defaultGetTenantId(session) {
1267
+ var _session$data$tenant$, _session$data;
1268
+ return (_session$data$tenant$ = session === null || session === void 0 || (_session$data = session.data) === null || _session$data === void 0 || (_session$data = _session$data.tenant) === null || _session$data === void 0 ? void 0 : _session$data.id) !== null && _session$data$tenant$ !== void 0 ? _session$data$tenant$ : session === null || session === void 0 ? void 0 : session.tenantId;
1269
+ }
1270
+
1271
+ /**
1272
+ * Access-control filter companion to `withTenant()`: limits matched items to the
1273
+ * session's tenant. Returns `false` (no access) when the session has no tenant.
1274
+ */
1275
+ function tenantAccessFilter(opts = {}) {
1276
+ var _opts$field4, _opts$getTenantId2;
1277
+ const field = (_opts$field4 = opts.field) !== null && _opts$field4 !== void 0 ? _opts$field4 : 'tenant';
1278
+ const getTenantId = (_opts$getTenantId2 = opts.getTenantId) !== null && _opts$getTenantId2 !== void 0 ? _opts$getTenantId2 : defaultGetTenantId;
1279
+ return ({
1280
+ session
1281
+ }) => {
1282
+ const tenantId = getTenantId(session);
1283
+ if (!tenantId) return false;
1284
+ return {
1285
+ [field]: {
1286
+ id: {
1287
+ equals: tenantId
1288
+ }
1289
+ }
1290
+ };
1291
+ };
1292
+ }
1293
+
1294
+ /**
1295
+ * Adds `publishAt` / `unpublishAt` timestamps for scheduled publishing. Composes with
1296
+ * `withPublishing()` (which provides the `status` field). The schedule is enacted by
1297
+ * `applyScheduledPublishing()` — run it from a cron job:
1298
+ *
1299
+ * @example
1300
+ * jobs: createJobs({ jobs: [{
1301
+ * name: 'scheduled-publishing',
1302
+ * schedule: '* * * * *',
1303
+ * handler: async () => { await applyScheduledPublishing(getContext(), 'Post') },
1304
+ * }]})
1305
+ */
1306
+ function withScheduledPublishing() {
1307
+ return {
1308
+ fields: {
1309
+ publishAt: timestamp({
1310
+ ui: {
1311
+ description: 'Automatically publish at this time (requires the scheduled-publishing job).'
1312
+ }
1313
+ }),
1314
+ unpublishAt: timestamp({
1315
+ ui: {
1316
+ description: 'Automatically archive at this time (requires the scheduled-publishing job).'
1317
+ }
1318
+ })
1319
+ }
1320
+ };
1321
+ }
1322
+
1323
+ /**
1324
+ * Enact `withScheduledPublishing()` schedules for one collection: publishes drafts whose
1325
+ * `publishAt` has passed and archives published items whose `unpublishAt` has passed.
1326
+ * Designed to be called from a cron job (see `withScheduledPublishing`).
1327
+ */
1328
+ async function applyScheduledPublishing(context, listKey, opts = {}) {
1329
+ var _opts$statusField, _opts$draftValue, _opts$publishedValue, _opts$archivedValue;
1330
+ const statusField = (_opts$statusField = opts.statusField) !== null && _opts$statusField !== void 0 ? _opts$statusField : 'status';
1331
+ const draftValue = (_opts$draftValue = opts.draftValue) !== null && _opts$draftValue !== void 0 ? _opts$draftValue : 'draft';
1332
+ const publishedValue = (_opts$publishedValue = opts.publishedValue) !== null && _opts$publishedValue !== void 0 ? _opts$publishedValue : 'published';
1333
+ const archivedValue = (_opts$archivedValue = opts.archivedValue) !== null && _opts$archivedValue !== void 0 ? _opts$archivedValue : 'archived';
1334
+ const sudo = context.sudo();
1335
+ const now = new Date();
1336
+ const toPublish = await sudo.db[listKey].findMany({
1337
+ where: {
1338
+ [statusField]: {
1339
+ equals: draftValue
1340
+ },
1341
+ publishAt: {
1342
+ lte: now
1343
+ }
1344
+ }
1345
+ });
1346
+ for (const item of toPublish) {
1347
+ await sudo.db[listKey].updateOne({
1348
+ where: {
1349
+ id: String(item.id)
1350
+ },
1351
+ data: {
1352
+ [statusField]: publishedValue
1353
+ }
1354
+ });
1355
+ }
1356
+ const toArchive = await sudo.db[listKey].findMany({
1357
+ where: {
1358
+ [statusField]: {
1359
+ equals: publishedValue
1360
+ },
1361
+ unpublishAt: {
1362
+ lte: now
1363
+ }
1364
+ }
1365
+ });
1366
+ for (const item of toArchive) {
1367
+ await sudo.db[listKey].updateOne({
1368
+ where: {
1369
+ id: String(item.id)
1370
+ },
1371
+ data: {
1372
+ [statusField]: archivedValue
1373
+ }
1374
+ });
1375
+ }
1376
+ return {
1377
+ published: toPublish.length,
1378
+ archived: toArchive.length
1379
+ };
1380
+ }
1381
+
1382
+ /**
1383
+ * i18n: adds a `locale` select plus a shared `translationKey` that groups an item with
1384
+ * its translations (auto-generated on create when blank). Query an item's variants with
1385
+ * `{ translationKey: { equals }, locale: { not: ... } }` — and once compound uniqueness
1386
+ * is configured, pair (`translationKey`, `locale`) should be unique.
1387
+ *
1388
+ * @example
1389
+ * defineCollection({ mixins: [withLocale({ locales: ['en', 'ur', 'ar'] })], fields: { ... } })
1390
+ */
1391
+ function withLocale(opts) {
1392
+ var _opts$locales, _opts$groupField, _opts$defaultLocale;
1393
+ if (!((_opts$locales = opts.locales) !== null && _opts$locales !== void 0 && _opts$locales.length)) throw new Error('withLocale requires at least one locale');
1394
+ const groupField = (_opts$groupField = opts.groupField) !== null && _opts$groupField !== void 0 ? _opts$groupField : 'translationKey';
1395
+ const defaultLocale = (_opts$defaultLocale = opts.defaultLocale) !== null && _opts$defaultLocale !== void 0 ? _opts$defaultLocale : opts.locales[0];
1396
+ return {
1397
+ fields: {
1398
+ locale: select({
1399
+ type: 'enum',
1400
+ options: opts.locales.map(locale => ({
1401
+ label: locale,
1402
+ value: locale
1403
+ })),
1404
+ defaultValue: defaultLocale,
1405
+ validation: {
1406
+ isRequired: true
1407
+ }
1408
+ }),
1409
+ [groupField]: text({
1410
+ isIndexed: true,
1411
+ ui: {
1412
+ description: 'Shared id linking this item with its translations.',
1413
+ createView: {
1414
+ fieldMode: 'hidden'
1415
+ },
1416
+ itemView: {
1417
+ fieldMode: 'read'
1418
+ }
1419
+ }
1420
+ })
1421
+ },
1422
+ hooks: {
1423
+ resolveInput: ({
1424
+ operation,
1425
+ resolvedData
1426
+ }) => {
1427
+ if (operation !== 'create') return resolvedData;
1428
+ if (resolvedData[groupField]) return resolvedData;
1429
+ return {
1430
+ ...resolvedData,
1431
+ [groupField]: randomBytes(8).toString('hex')
1432
+ };
1433
+ }
1434
+ }
1435
+ };
1436
+ }
1437
+
1438
+ /**
1439
+ * Editorial approval: adds an approval status + a `pendingChanges` buffer where proposed
1440
+ * edits wait for review instead of going live. Drive it with `submitForApproval()`,
1441
+ * `approveChanges()` and `rejectChanges()` from custom mutations or the Admin UI.
1442
+ */
1443
+ function withApproval() {
1444
+ return {
1445
+ fields: {
1446
+ approvalStatus: select({
1447
+ type: 'enum',
1448
+ options: [{
1449
+ label: 'None',
1450
+ value: 'none'
1451
+ }, {
1452
+ label: 'Pending',
1453
+ value: 'pending'
1454
+ }, {
1455
+ label: 'Approved',
1456
+ value: 'approved'
1457
+ }, {
1458
+ label: 'Rejected',
1459
+ value: 'rejected'
1460
+ }],
1461
+ defaultValue: 'none',
1462
+ ui: {
1463
+ createView: {
1464
+ fieldMode: 'hidden'
1465
+ },
1466
+ itemView: {
1467
+ fieldMode: 'read'
1468
+ }
1469
+ }
1470
+ }),
1471
+ pendingChanges: json({
1472
+ ui: {
1473
+ createView: {
1474
+ fieldMode: 'hidden'
1475
+ },
1476
+ itemView: {
1477
+ fieldMode: 'hidden'
1478
+ },
1479
+ listView: {
1480
+ fieldMode: 'hidden'
1481
+ }
1482
+ }
1483
+ }),
1484
+ approvalSubmittedAt: timestamp({
1485
+ ui: {
1486
+ createView: {
1487
+ fieldMode: 'hidden'
1488
+ },
1489
+ itemView: {
1490
+ fieldMode: 'read'
1491
+ }
1492
+ }
1493
+ }),
1494
+ approvalReviewedAt: timestamp({
1495
+ ui: {
1496
+ createView: {
1497
+ fieldMode: 'hidden'
1498
+ },
1499
+ itemView: {
1500
+ fieldMode: 'read'
1501
+ }
1502
+ }
1503
+ })
1504
+ }
1505
+ };
1506
+ }
1507
+
1508
+ /** Park proposed changes on an item for review (see `withApproval`). */
1509
+ async function submitForApproval(context, args) {
1510
+ await context.sudo().db[args.listKey].updateOne({
1511
+ where: {
1512
+ id: args.itemId
1513
+ },
1514
+ data: {
1515
+ pendingChanges: args.changes,
1516
+ approvalStatus: 'pending',
1517
+ approvalSubmittedAt: new Date().toISOString()
1518
+ }
1519
+ });
1520
+ }
1521
+
1522
+ /**
1523
+ * Apply an item's `pendingChanges` (running normal hooks/validation) and mark it
1524
+ * approved. The buffered changes must be a valid update input for the collection.
1525
+ */
1526
+ async function approveChanges(context, args) {
1527
+ const sudo = context.sudo();
1528
+ const item = await sudo.query[args.listKey].findOne({
1529
+ where: {
1530
+ id: args.itemId
1531
+ },
1532
+ query: 'id pendingChanges approvalStatus'
1533
+ });
1534
+ if (!(item !== null && item !== void 0 && item.pendingChanges)) throw new Error('approveChanges: the item has no pending changes');
1535
+ await sudo.db[args.listKey].updateOne({
1536
+ where: {
1537
+ id: args.itemId
1538
+ },
1539
+ data: {
1540
+ ...item.pendingChanges,
1541
+ pendingChanges: null,
1542
+ approvalStatus: 'approved',
1543
+ approvalReviewedAt: new Date().toISOString()
1544
+ }
1545
+ });
1546
+ }
1547
+
1548
+ /** Discard an item's `pendingChanges` and mark it rejected. */
1549
+ async function rejectChanges(context, args) {
1550
+ await context.sudo().db[args.listKey].updateOne({
1551
+ where: {
1552
+ id: args.itemId
1553
+ },
1554
+ data: {
1555
+ pendingChanges: null,
1556
+ approvalStatus: 'rejected',
1557
+ approvalReviewedAt: new Date().toISOString()
1558
+ }
1559
+ });
1560
+ }
1561
+
1562
+ /**
1563
+ * Adds an `expiresAt` timestamp for content with a shelf life. Pair with
1564
+ * `purgeExpired()` in a cron job to physically remove (or just count) expired items.
1565
+ */
1566
+ function withExpiry(opts = {}) {
1567
+ var _opts$field5;
1568
+ const field = (_opts$field5 = opts.field) !== null && _opts$field5 !== void 0 ? _opts$field5 : 'expiresAt';
1569
+ return {
1570
+ fields: {
1571
+ [field]: timestamp({
1572
+ ui: {
1573
+ description: 'After this time the item is considered expired.'
1574
+ }
1575
+ })
1576
+ }
1577
+ };
1578
+ }
1579
+
1580
+ /**
1581
+ * Delete every item whose expiry has passed (runs normal delete hooks). Returns the
1582
+ * number deleted. Designed for a cron job; see `withExpiry`.
1583
+ */
1584
+ async function purgeExpired(context, listKey, opts = {}) {
1585
+ var _opts$field6;
1586
+ const field = (_opts$field6 = opts.field) !== null && _opts$field6 !== void 0 ? _opts$field6 : 'expiresAt';
1587
+ const sudo = context.sudo();
1588
+ const expired = await sudo.db[listKey].findMany({
1589
+ where: {
1590
+ [field]: {
1591
+ lte: new Date()
1592
+ }
1593
+ }
1594
+ });
1595
+ for (const item of expired) {
1596
+ await sudo.db[listKey].deleteOne({
1597
+ where: {
1598
+ id: String(item.id)
1599
+ }
1600
+ });
1601
+ }
1602
+ return expired.length;
1603
+ }
1604
+
1605
+ /**
1606
+ * Adds a read-only `viewCount` integer. Increment it with `recordView()` — a direct,
1607
+ * race-safe Prisma increment that bypasses hooks (a view is not an editorial change).
1608
+ */
1609
+ function withViewCount(opts = {}) {
1610
+ var _opts$field7;
1611
+ const field = (_opts$field7 = opts.field) !== null && _opts$field7 !== void 0 ? _opts$field7 : 'viewCount';
1612
+ return {
1613
+ fields: {
1614
+ [field]: integer({
1615
+ defaultValue: 0,
1616
+ ui: {
1617
+ createView: {
1618
+ fieldMode: 'hidden'
1619
+ },
1620
+ itemView: {
1621
+ fieldMode: 'read'
1622
+ }
1623
+ }
1624
+ })
1625
+ }
1626
+ };
1627
+ }
1628
+
1629
+ /** Increment an item's view counter (see `withViewCount`). */
1630
+ async function recordView(context, listKey, itemId, opts = {}) {
1631
+ var _opts$field8, _context$prisma;
1632
+ const field = (_opts$field8 = opts.field) !== null && _opts$field8 !== void 0 ? _opts$field8 : 'viewCount';
1633
+ const model = (_context$prisma = context.prisma) === null || _context$prisma === void 0 ? void 0 : _context$prisma[listKey[0].toLowerCase() + listKey.slice(1)];
1634
+ if (!model) throw new Error(`recordView: collection "${listKey}" was not found in the Prisma client`);
1635
+ await model.update({
1636
+ where: {
1637
+ id: itemId
1638
+ },
1639
+ data: {
1640
+ [field]: {
1641
+ increment: 1
1642
+ }
1643
+ }
1644
+ });
1645
+ }
1646
+
1647
+ /**
1648
+ * Companion to cascade rules: sweep records whose to-one relationship points at
1649
+ * nothing (e.g. rows that pre-date a cascade rule, or were orphaned by `setNull`).
1650
+ * Runs normal delete hooks (so cascade rules fire too). Designed for a cron job.
1651
+ *
1652
+ * @example
1653
+ * jobs: createJobs({ jobs: [{
1654
+ * name: 'orphan-cleanup',
1655
+ * schedule: '0 4 * * *',
1656
+ * handler: async () => { await cleanupOrphans(getContext(), { collection: 'Comment', field: 'post' }) },
1657
+ * }]})
1658
+ */
1659
+ async function cleanupOrphans(context, options) {
1660
+ var _options$softDeleteFi;
1661
+ const {
1662
+ collection,
1663
+ field,
1664
+ action = 'delete'
1665
+ } = options;
1666
+ const softDeleteField = (_options$softDeleteFi = options.softDeleteField) !== null && _options$softDeleteFi !== void 0 ? _options$softDeleteFi : 'deletedAt';
1667
+ const sudo = context.sudo();
1668
+ const where = action === 'softDelete' ? {
1669
+ [field]: null,
1670
+ [softDeleteField]: null
1671
+ } : {
1672
+ [field]: null
1673
+ };
1674
+ let total = 0;
1675
+ for (;;) {
1676
+ const orphans = await sudo.db[collection].findMany({
1677
+ where,
1678
+ take: 100
1679
+ });
1680
+ if (!orphans.length) break;
1681
+ for (const orphan of orphans) {
1682
+ if (action === 'delete') {
1683
+ await sudo.db[collection].deleteOne({
1684
+ where: {
1685
+ id: String(orphan.id)
1686
+ }
1687
+ });
1688
+ } else {
1689
+ await sudo.db[collection].updateOne({
1690
+ where: {
1691
+ id: String(orphan.id)
1692
+ },
1693
+ data: {
1694
+ [softDeleteField]: new Date().toISOString()
1695
+ }
1696
+ });
1697
+ }
1698
+ total++;
1699
+ }
1700
+ if (orphans.length < 100) break;
1701
+ }
1702
+ return total;
1703
+ }
1704
+
394
1705
  /**
395
1706
  * Factory for building reusable field group mixins.
396
1707
  *
@@ -409,14 +1720,14 @@ function createMixin(fields, hooks) {
409
1720
  }
410
1721
 
411
1722
  // ================================================================
412
- // defineList — a typed wrapper around list() with mixin support
1723
+ // defineCollection — a typed wrapper around list() with mixin support
413
1724
  // ================================================================
414
1725
 
415
1726
  /**
416
1727
  * Defines a list with optional mixins for reusable field groups and hooks.
417
1728
  *
418
1729
  * @example
419
- * export const Post = defineList({
1730
+ * export const Post = defineCollection({
420
1731
  * mixins: [withTimestamps()],
421
1732
  * fields: {
422
1733
  * title: text({ validation: validators.required }),
@@ -424,9 +1735,18 @@ function createMixin(fields, hooks) {
424
1735
  * },
425
1736
  * })
426
1737
  */
427
- function defineList(config) {
1738
+ function defineCollection(config) {
428
1739
  const {
429
1740
  mixins = [],
1741
+ access,
1742
+ computed,
1743
+ constraints,
1744
+ defaultFilter,
1745
+ stateMachine,
1746
+ policies,
1747
+ events,
1748
+ searchable,
1749
+ versioned,
430
1750
  ...listConfig
431
1751
  } = config;
432
1752
  const mixinFields = {};
@@ -435,9 +1755,26 @@ function defineList(config) {
435
1755
  if (mixin.fields) Object.assign(mixinFields, mixin.fields);
436
1756
  if (mixin.hooks) mixinHooksList.push(mixin.hooks);
437
1757
  }
438
- const mergedHooks = mergeMixinHooks(mixinHooksList, listConfig.hooks);
439
- return list({
1758
+
1759
+ // Feature hooks run AFTER mixin + user hooks so computed fields and constraint checks
1760
+ // observe the final resolved data, and events/search/version snapshots fire last.
1761
+ const featureHooks = compileFeatureHooks({
1762
+ computed,
1763
+ constraints,
1764
+ stateMachine,
1765
+ events,
1766
+ searchable,
1767
+ versioned
1768
+ });
1769
+ const mergedHooks = mergeMixinHooks(mixinHooksList, listConfig.hooks, featureHooks);
1770
+ const baseAccess = access !== null && access !== void 0 ? access : accessPresets.public;
1771
+ const finalAccess = applyAccessFeatures(baseAccess, {
1772
+ defaultFilter,
1773
+ policies
1774
+ });
1775
+ return collection({
440
1776
  ...listConfig,
1777
+ access: finalAccess,
441
1778
  fields: {
442
1779
  ...mixinFields,
443
1780
  ...listConfig.fields
@@ -482,13 +1819,13 @@ function mergeResolveInput(a, b) {
482
1819
  }
483
1820
 
484
1821
  /**
485
- * Merge mixin hooks with the list's own hooks. Each Keystone hook may be either a function or a
1822
+ * Merge mixin hooks with the list's own hooks. Each list hook may be either a function or a
486
1823
  * `{ create, update, delete }` object — `merge` (from resolve-hooks) handles both forms for the
487
1824
  * void hooks, and `mergeResolveInput` handles the data-threading `resolveInput` hook.
488
1825
  */
489
- function mergeMixinHooks(mixinHooks, listHooks) {
490
- if (mixinHooks.length === 0) return listHooks !== null && listHooks !== void 0 ? listHooks : {};
491
- const all = [...mixinHooks, ...(listHooks ? [listHooks] : [])];
1826
+ function mergeMixinHooks(mixinHooks, listHooks, featureHooks = []) {
1827
+ if (mixinHooks.length === 0 && featureHooks.length === 0) return listHooks !== null && listHooks !== void 0 ? listHooks : {};
1828
+ const all = [...mixinHooks, ...(listHooks ? [listHooks] : []), ...featureHooks];
492
1829
  const merged = {};
493
1830
  for (const hooks of all) {
494
1831
  merged.resolveInput = mergeResolveInput(merged.resolveInput, hooks.resolveInput);
@@ -514,7 +1851,7 @@ function mergeMixinHooks(mixinHooks, listHooks) {
514
1851
  * })
515
1852
  */
516
1853
  function defineConfig(nixxieConfig) {
517
- return config(nixxieConfig);
1854
+ return buildConfig(nixxieConfig);
518
1855
  }
519
1856
 
520
1857
  // ================================================================
@@ -525,7 +1862,7 @@ function defineConfig(nixxieConfig) {
525
1862
  * Defines a list action. Typed alias for `action()`.
526
1863
  */
527
1864
  function defineAction(actionConfig) {
528
- return action(actionConfig);
1865
+ return createAction(actionConfig);
529
1866
  }
530
1867
 
531
- export { action, config, createMixin, defineAction, defineConfig, defineList, group, list, validators, withAudit, withSoftDelete, withTimestamps };
1868
+ export { accessPresets, applyScheduledPublishing, approveChanges, cleanupOrphans, collection, createAction, createMixin, defineAction, defineCollection, defineConfig, fieldGroup, purgeExpired, recordView, rejectChanges, submitForApproval, tenantAccessFilter, validateEnv, validators, withApproval, withAudit, withExpiry, withLocale, withPublishing, withSEO, withScheduledPublishing, withSlug, withSoftDelete, withSortable, withTenant, withTimestamps, withTreeStructure, withViewCount };