@sonicjs-cms/core 2.18.1 → 3.0.0-beta.10

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 (232) hide show
  1. package/README.md +52 -52
  2. package/dist/admin-documents-form.template-DDSH6ROU.js +6 -0
  3. package/dist/{admin-layout-catalyst.template-UMTIN66R.js.map → admin-documents-form.template-DDSH6ROU.js.map} +1 -1
  4. package/dist/admin-documents-form.template-LSZKGA5J.cjs +19 -0
  5. package/dist/{admin-layout-catalyst.template-HFD37TY5.cjs.map → admin-documents-form.template-LSZKGA5J.cjs.map} +1 -1
  6. package/dist/{filter-bar.template-DlVYMk-T.d.cts → admin-layout-catalyst.template-DrwDUfsE.d.cts} +25 -1
  7. package/dist/{filter-bar.template-DlVYMk-T.d.ts → admin-layout-catalyst.template-DrwDUfsE.d.ts} +25 -1
  8. package/dist/admin-layout-catalyst.template-KDHKVLXR.cjs +21 -0
  9. package/dist/admin-layout-catalyst.template-KDHKVLXR.cjs.map +1 -0
  10. package/dist/admin-layout-catalyst.template-YQ4EMF2J.js +7 -0
  11. package/dist/admin-layout-catalyst.template-YQ4EMF2J.js.map +1 -0
  12. package/dist/app-Bo0X1OWX.d.ts +1268 -0
  13. package/dist/app-Do66yCcV.d.cts +1268 -0
  14. package/dist/cache-DDARE4QE.js +4 -0
  15. package/dist/cache-DDARE4QE.js.map +1 -0
  16. package/dist/cache-LVYS4BPL.cjs +33 -0
  17. package/dist/cache-LVYS4BPL.cjs.map +1 -0
  18. package/dist/chunk-2CB4KY7I.cjs +771 -0
  19. package/dist/chunk-2CB4KY7I.cjs.map +1 -0
  20. package/dist/{chunk-ABB34XUS.cjs → chunk-3KYKEXV7.cjs} +667 -19
  21. package/dist/chunk-3KYKEXV7.cjs.map +1 -0
  22. package/dist/chunk-4BTBSXMR.cjs +912 -0
  23. package/dist/chunk-4BTBSXMR.cjs.map +1 -0
  24. package/dist/{chunk-55RDMDOP.js → chunk-5V62WT6M.js} +181 -57
  25. package/dist/chunk-5V62WT6M.js.map +1 -0
  26. package/dist/{chunk-XXDFQERJ.js → chunk-6OC6MF3C.js} +7192 -9806
  27. package/dist/chunk-6OC6MF3C.js.map +1 -0
  28. package/dist/chunk-AI663NBO.js +821 -0
  29. package/dist/chunk-AI663NBO.js.map +1 -0
  30. package/dist/chunk-ALDRXTUO.js +273 -0
  31. package/dist/chunk-ALDRXTUO.js.map +1 -0
  32. package/dist/{chunk-TFNTM3OA.js → chunk-ATUPB6MN.js} +645 -15
  33. package/dist/chunk-ATUPB6MN.js.map +1 -0
  34. package/dist/chunk-BLMTL57B.js +767 -0
  35. package/dist/chunk-BLMTL57B.js.map +1 -0
  36. package/dist/{chunk-4ZSNJDLS.cjs → chunk-CRGUD4KC.cjs} +9 -9
  37. package/dist/chunk-CRGUD4KC.cjs.map +1 -0
  38. package/dist/chunk-F67UK75A.cjs +158 -0
  39. package/dist/chunk-F67UK75A.cjs.map +1 -0
  40. package/dist/chunk-GCDZZNIN.js +192 -0
  41. package/dist/chunk-GCDZZNIN.js.map +1 -0
  42. package/dist/chunk-HIKBY7MS.cjs +70 -0
  43. package/dist/chunk-HIKBY7MS.cjs.map +1 -0
  44. package/dist/chunk-IDCZBF35.js +1186 -0
  45. package/dist/chunk-IDCZBF35.js.map +1 -0
  46. package/dist/chunk-IESEVHXL.js +66 -0
  47. package/dist/chunk-IESEVHXL.js.map +1 -0
  48. package/dist/chunk-IGADDMXH.js +387 -0
  49. package/dist/chunk-IGADDMXH.js.map +1 -0
  50. package/dist/chunk-IHTXB7AT.cjs +276 -0
  51. package/dist/chunk-IHTXB7AT.cjs.map +1 -0
  52. package/dist/chunk-IVPRUGTY.js +242 -0
  53. package/dist/chunk-IVPRUGTY.js.map +1 -0
  54. package/dist/{chunk-SQ6FNXU2.cjs → chunk-IXUHXTHW.cjs} +2 -151
  55. package/dist/chunk-IXUHXTHW.cjs.map +1 -0
  56. package/dist/chunk-J6JTWD2A.cjs +100 -0
  57. package/dist/chunk-J6JTWD2A.cjs.map +1 -0
  58. package/dist/chunk-JEQ7FLOD.cjs +199 -0
  59. package/dist/chunk-JEQ7FLOD.cjs.map +1 -0
  60. package/dist/{chunk-ON5ZMSU4.js → chunk-JQISFW6U.js} +3 -3
  61. package/dist/chunk-JQISFW6U.js.map +1 -0
  62. package/dist/chunk-K25XHMM3.js +566 -0
  63. package/dist/chunk-K25XHMM3.js.map +1 -0
  64. package/dist/{chunk-UYJ6TJHX.cjs → chunk-K623Q6WD.cjs} +181 -56
  65. package/dist/chunk-K623Q6WD.cjs.map +1 -0
  66. package/dist/chunk-MUNO67TT.cjs +1219 -0
  67. package/dist/chunk-MUNO67TT.cjs.map +1 -0
  68. package/dist/chunk-N32OWET6.cjs +327 -0
  69. package/dist/chunk-N32OWET6.cjs.map +1 -0
  70. package/dist/chunk-NUKJ54GA.cjs +245 -0
  71. package/dist/chunk-NUKJ54GA.cjs.map +1 -0
  72. package/dist/{chunk-XWIA3HVX.js → chunk-OBA2RYZN.js} +6 -1249
  73. package/dist/chunk-OBA2RYZN.js.map +1 -0
  74. package/dist/chunk-PMGOBS6X.cjs +408 -0
  75. package/dist/chunk-PMGOBS6X.cjs.map +1 -0
  76. package/dist/{chunk-OHYBNCVL.cjs → chunk-PXNTCCPE.cjs} +10 -1256
  77. package/dist/chunk-PXNTCCPE.cjs.map +1 -0
  78. package/dist/chunk-PYVFXCSD.js +1828 -0
  79. package/dist/chunk-PYVFXCSD.js.map +1 -0
  80. package/dist/{chunk-MGFRZO24.js → chunk-QZGABF2M.js} +3 -149
  81. package/dist/chunk-QZGABF2M.js.map +1 -0
  82. package/dist/{chunk-T3Q5V33G.cjs → chunk-R4ILO3W6.cjs} +876 -829
  83. package/dist/chunk-R4ILO3W6.cjs.map +1 -0
  84. package/dist/chunk-RMRJGMDE.js +323 -0
  85. package/dist/chunk-RMRJGMDE.js.map +1 -0
  86. package/dist/chunk-RNZFGN4R.js +88 -0
  87. package/dist/chunk-RNZFGN4R.js.map +1 -0
  88. package/dist/chunk-RQ6N3FTV.js +900 -0
  89. package/dist/chunk-RQ6N3FTV.js.map +1 -0
  90. package/dist/{chunk-SXXTQETM.cjs → chunk-TO6EY4P7.cjs} +8722 -11323
  91. package/dist/chunk-TO6EY4P7.cjs.map +1 -0
  92. package/dist/chunk-V464XBYS.js +154 -0
  93. package/dist/chunk-V464XBYS.js.map +1 -0
  94. package/dist/chunk-YA3TJ65D.cjs +575 -0
  95. package/dist/chunk-YA3TJ65D.cjs.map +1 -0
  96. package/dist/chunk-YP7GW2G5.cjs +866 -0
  97. package/dist/chunk-YP7GW2G5.cjs.map +1 -0
  98. package/dist/{collection-config-B4PG-AaF.d.cts → collection-config-JgHOpFCG.d.cts} +30 -2
  99. package/dist/{collection-config-B4PG-AaF.d.ts → collection-config-JgHOpFCG.d.ts} +30 -2
  100. package/dist/config-HFXANXCC.js +6 -0
  101. package/dist/config-HFXANXCC.js.map +1 -0
  102. package/dist/config-ON6FNMYX.cjs +19 -0
  103. package/dist/config-ON6FNMYX.cjs.map +1 -0
  104. package/dist/define-plugin-BzNHc1ZI.d.ts +1321 -0
  105. package/dist/define-plugin-IWDKYaVm.d.cts +1321 -0
  106. package/dist/document-projection-TDWRJX3Z.cjs +13 -0
  107. package/dist/document-projection-TDWRJX3Z.cjs.map +1 -0
  108. package/dist/document-projection-YYMC6I4U.js +4 -0
  109. package/dist/document-projection-YYMC6I4U.js.map +1 -0
  110. package/dist/index.cjs +13737 -4327
  111. package/dist/index.cjs.map +1 -1
  112. package/dist/index.d.cts +331 -493
  113. package/dist/index.d.ts +331 -493
  114. package/dist/index.js +13456 -4068
  115. package/dist/index.js.map +1 -1
  116. package/dist/middleware.cjs +38 -32
  117. package/dist/middleware.d.cts +69 -7
  118. package/dist/middleware.d.ts +69 -7
  119. package/dist/middleware.js +9 -3
  120. package/dist/migrations-2XHQEGOQ.cjs +13 -0
  121. package/dist/{migrations-IYNTWDC6.cjs.map → migrations-2XHQEGOQ.cjs.map} +1 -1
  122. package/dist/migrations-PE3CDVSM.js +4 -0
  123. package/dist/{migrations-R337UD46.js.map → migrations-PE3CDVSM.js.map} +1 -1
  124. package/dist/{plugin-bootstrap-DfVerYV4.d.cts → plugin-bootstrap-B8ThJU21.d.cts} +4315 -1661
  125. package/dist/{plugin-bootstrap-P_ciLp_C.d.ts → plugin-bootstrap-qu8hJgUt.d.ts} +4315 -1661
  126. package/dist/plugins.cjs +171 -12
  127. package/dist/plugins.d.cts +36 -2
  128. package/dist/plugins.d.ts +36 -2
  129. package/dist/plugins.js +5 -2
  130. package/dist/rbac-O73MFKDA.js +5 -0
  131. package/dist/rbac-O73MFKDA.js.map +1 -0
  132. package/dist/rbac-VONLJJKB.cjs +14 -0
  133. package/dist/rbac-VONLJJKB.cjs.map +1 -0
  134. package/dist/routes.cjs +42 -46
  135. package/dist/routes.d.cts +56 -146
  136. package/dist/routes.d.ts +56 -146
  137. package/dist/routes.js +18 -10
  138. package/dist/services.cjs +43 -76
  139. package/dist/services.d.cts +93 -55
  140. package/dist/services.d.ts +93 -55
  141. package/dist/services.js +6 -3
  142. package/dist/{telemetry-B9vIV4wh.d.cts → telemetry-Cku1ax74.d.cts} +1 -1
  143. package/dist/{telemetry-B9vIV4wh.d.ts → telemetry-Cku1ax74.d.ts} +1 -1
  144. package/dist/templates.cjs +17 -29
  145. package/dist/templates.d.cts +2 -89
  146. package/dist/templates.d.ts +2 -89
  147. package/dist/templates.js +3 -3
  148. package/dist/types-Dea1eNxU.d.cts +286 -0
  149. package/dist/types-Dea1eNxU.d.ts +286 -0
  150. package/dist/types.d.cts +2 -2
  151. package/dist/types.d.ts +2 -2
  152. package/dist/utils.cjs +21 -20
  153. package/dist/utils.d.cts +2 -2
  154. package/dist/utils.d.ts +2 -2
  155. package/dist/utils.js +3 -2
  156. package/migrations/0001_core.sql +184 -0
  157. package/migrations/0002_documents.sql +163 -0
  158. package/package.json +12 -7
  159. package/dist/admin-layout-catalyst.template-HFD37TY5.cjs +0 -17
  160. package/dist/admin-layout-catalyst.template-UMTIN66R.js +0 -7
  161. package/dist/app-C9esKLmh.d.cts +0 -112
  162. package/dist/app-C9esKLmh.d.ts +0 -112
  163. package/dist/chunk-4R3NOOL3.js +0 -2217
  164. package/dist/chunk-4R3NOOL3.js.map +0 -1
  165. package/dist/chunk-4ZSNJDLS.cjs.map +0 -1
  166. package/dist/chunk-55RDMDOP.js.map +0 -1
  167. package/dist/chunk-635JAMSE.cjs +0 -653
  168. package/dist/chunk-635JAMSE.cjs.map +0 -1
  169. package/dist/chunk-ABB34XUS.cjs.map +0 -1
  170. package/dist/chunk-C54YUA23.cjs +0 -2219
  171. package/dist/chunk-C54YUA23.cjs.map +0 -1
  172. package/dist/chunk-DSUJ5YQH.cjs +0 -722
  173. package/dist/chunk-DSUJ5YQH.cjs.map +0 -1
  174. package/dist/chunk-EW5NOBVU.js +0 -1783
  175. package/dist/chunk-EW5NOBVU.js.map +0 -1
  176. package/dist/chunk-EXNEW5US.js +0 -648
  177. package/dist/chunk-EXNEW5US.js.map +0 -1
  178. package/dist/chunk-I2H5NGJQ.js +0 -692
  179. package/dist/chunk-I2H5NGJQ.js.map +0 -1
  180. package/dist/chunk-MGFRZO24.js.map +0 -1
  181. package/dist/chunk-OHYBNCVL.cjs.map +0 -1
  182. package/dist/chunk-ON5ZMSU4.js.map +0 -1
  183. package/dist/chunk-QFWHAFEO.js +0 -1843
  184. package/dist/chunk-QFWHAFEO.js.map +0 -1
  185. package/dist/chunk-SQ6FNXU2.cjs.map +0 -1
  186. package/dist/chunk-SXXTQETM.cjs.map +0 -1
  187. package/dist/chunk-T3Q5V33G.cjs.map +0 -1
  188. package/dist/chunk-TFNTM3OA.js.map +0 -1
  189. package/dist/chunk-UYJ6TJHX.cjs.map +0 -1
  190. package/dist/chunk-WAEQXGCX.cjs +0 -1898
  191. package/dist/chunk-WAEQXGCX.cjs.map +0 -1
  192. package/dist/chunk-XWIA3HVX.js.map +0 -1
  193. package/dist/chunk-XXDFQERJ.js.map +0 -1
  194. package/dist/migrations-IYNTWDC6.cjs +0 -13
  195. package/dist/migrations-R337UD46.js +0 -4
  196. package/dist/plugin-manager-BoM3Q7o7.d.cts +0 -328
  197. package/dist/plugin-manager-Efx9RyDX.d.ts +0 -328
  198. package/migrations/001_initial_schema.sql +0 -170
  199. package/migrations/002_faq_plugin.sql +0 -86
  200. package/migrations/003_stage5_enhancements.sql +0 -121
  201. package/migrations/004_stage6_user_management.sql +0 -183
  202. package/migrations/005_stage7_workflow_automation.sql +0 -294
  203. package/migrations/006_plugin_system.sql +0 -155
  204. package/migrations/007_demo_login_plugin.sql +0 -23
  205. package/migrations/008_fix_slug_validation.sql +0 -22
  206. package/migrations/009_system_logging.sql +0 -57
  207. package/migrations/011_config_managed_collections.sql +0 -15
  208. package/migrations/012_testimonials_plugin.sql +0 -80
  209. package/migrations/013_code_examples_plugin.sql +0 -177
  210. package/migrations/014_fix_plugin_registry.sql +0 -88
  211. package/migrations/015_add_remaining_plugins.sql +0 -89
  212. package/migrations/016_remove_duplicate_cache_plugin.sql +0 -17
  213. package/migrations/017_auth_configurable_fields.sql +0 -49
  214. package/migrations/018_settings_table.sql +0 -23
  215. package/migrations/019_remove_blog_posts_collection.sql +0 -15
  216. package/migrations/020_add_email_plugin.sql +0 -22
  217. package/migrations/021_add_magic_link_auth_plugin.sql +0 -42
  218. package/migrations/022_add_tinymce_plugin.sql +0 -25
  219. package/migrations/023_add_easy_mdx_plugin.sql +0 -25
  220. package/migrations/024_add_quill_editor_plugin.sql +0 -25
  221. package/migrations/025_add_easymde_plugin.sql +0 -25
  222. package/migrations/026_add_otp_login.sql +0 -42
  223. package/migrations/027_fix_slug_field_type.sql +0 -18
  224. package/migrations/028_fix_slug_field_type_in_schemas.sql +0 -30
  225. package/migrations/029_add_forms_system.sql +0 -184
  226. package/migrations/030_add_turnstile_to_forms.sql +0 -14
  227. package/migrations/031_ai_search_plugin.sql +0 -45
  228. package/migrations/032_user_profiles.sql +0 -37
  229. package/migrations/033_form_content_integration.sql +0 -19
  230. package/migrations/034_security_audit_plugin.sql +0 -27
  231. package/migrations/035_user_profiles_data_column.sql +0 -16
  232. package/migrations/036_analytics_events.sql +0 -22
@@ -0,0 +1,767 @@
1
+ import { DocumentProjection, nanoid } from './chunk-GCDZZNIN.js';
2
+
3
+ // src/services/documents.ts
4
+ var DEFAULT_MAX_VERSIONS = 50;
5
+ function documentSecondsToMs(ts) {
6
+ return ts == null ? null : ts * 1e3;
7
+ }
8
+ function rowToDocument(row) {
9
+ return {
10
+ id: row.id,
11
+ rootId: row.root_id,
12
+ typeId: row.type_id,
13
+ typeVersion: row.type_version,
14
+ versionOfId: row.version_of_id,
15
+ versionNumber: row.version_number,
16
+ isCurrentDraft: row.is_current_draft === 1,
17
+ isPublished: row.is_published === 1,
18
+ status: row.status,
19
+ parentRootId: row.parent_root_id,
20
+ slug: row.slug,
21
+ path: row.path,
22
+ title: row.title,
23
+ zone: row.zone,
24
+ sortOrder: row.sort_order,
25
+ visible: row.visible === 1,
26
+ publishedAt: row.published_at,
27
+ scheduledAt: row.scheduled_at,
28
+ expiresAt: row.expires_at,
29
+ deletedAt: row.deleted_at,
30
+ tenantId: row.tenant_id,
31
+ locale: row.locale,
32
+ translationGroupId: row.translation_group_id,
33
+ data: JSON.parse(row.data),
34
+ metadata: JSON.parse(row.metadata),
35
+ ownerId: row.owner_id,
36
+ createdBy: row.created_by,
37
+ updatedBy: row.updated_by,
38
+ createdAt: row.created_at,
39
+ updatedAt: row.updated_at
40
+ };
41
+ }
42
+ var DocumentsService = class {
43
+ constructor(db, opts = {}) {
44
+ this.db = db;
45
+ this.opts = opts;
46
+ this.projection = new DocumentProjection(db);
47
+ this.tenantId = opts.tenantId ?? "default";
48
+ this.versioning = opts.versioning ?? false;
49
+ }
50
+ projection;
51
+ tenantId;
52
+ versioning;
53
+ // ─── Create ───────────────────────────────────────────────────────────────
54
+ async create(input, createdBy) {
55
+ const now = Math.floor(Date.now() / 1e3);
56
+ const id = nanoid();
57
+ const publish = input.publishOnCreate ?? false;
58
+ const createdAt = input.createdAt ?? now;
59
+ const updatedAt = input.updatedAt ?? now;
60
+ const doc = {
61
+ id,
62
+ rootId: id,
63
+ typeId: input.typeId,
64
+ typeVersion: this.opts.typeSchemaVersion ?? 1,
65
+ versionOfId: null,
66
+ versionNumber: 1,
67
+ isCurrentDraft: true,
68
+ isPublished: publish,
69
+ status: publish ? "published" : "draft",
70
+ parentRootId: input.parentRootId ?? "",
71
+ slug: input.slug ?? null,
72
+ path: null,
73
+ title: input.title ?? null,
74
+ zone: input.zone ?? null,
75
+ sortOrder: input.sortOrder ?? 0,
76
+ visible: input.visible ?? true,
77
+ publishedAt: publish ? createdAt : null,
78
+ scheduledAt: input.scheduledAt ?? null,
79
+ expiresAt: input.expiresAt ?? null,
80
+ deletedAt: null,
81
+ // Tenant comes from the service scope unless the caller passes one explicitly. Never trust a
82
+ // request-body tenant: route handlers must override with the resolved request-context tenant.
83
+ tenantId: input.tenantId ?? this.tenantId,
84
+ locale: input.locale ?? "default",
85
+ translationGroupId: "",
86
+ data: input.data ?? {},
87
+ metadata: input.metadata ?? {},
88
+ ownerId: input.ownerId ?? null,
89
+ createdBy: createdBy ?? null,
90
+ updatedBy: createdBy ?? null,
91
+ createdAt,
92
+ updatedAt
93
+ };
94
+ const insertDoc = this.db.prepare(
95
+ `INSERT INTO documents (id, root_id, type_id, type_version, version_of_id, version_number,
96
+ is_current_draft, is_published, status, parent_root_id, slug, path, title, zone,
97
+ sort_order, visible, published_at, scheduled_at, expires_at, deleted_at,
98
+ tenant_id, locale, translation_group_id, data, metadata,
99
+ owner_id, created_by, updated_by, created_at, updated_at)
100
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`
101
+ ).bind(
102
+ doc.id,
103
+ doc.rootId,
104
+ doc.typeId,
105
+ doc.typeVersion,
106
+ null,
107
+ 1,
108
+ 1,
109
+ publish ? 1 : 0,
110
+ doc.status,
111
+ doc.parentRootId,
112
+ doc.slug,
113
+ null,
114
+ doc.title,
115
+ doc.zone,
116
+ doc.sortOrder,
117
+ doc.visible ? 1 : 0,
118
+ doc.publishedAt,
119
+ doc.scheduledAt,
120
+ doc.expiresAt,
121
+ null,
122
+ doc.tenantId,
123
+ doc.locale,
124
+ "",
125
+ JSON.stringify(doc.data),
126
+ JSON.stringify(doc.metadata),
127
+ doc.ownerId,
128
+ doc.createdBy,
129
+ doc.updatedBy,
130
+ createdAt,
131
+ updatedAt
132
+ );
133
+ const derivedInserts = this.projection.buildDerivedInsertStatements(doc, this.opts.queryableFields ?? [], now);
134
+ await this.db.batch([insertDoc, ...derivedInserts]);
135
+ return doc;
136
+ }
137
+ // ─── Save new draft ───────────────────────────────────────────────────────
138
+ // Atomically: demote previous draft → delete its derived rows (if not published) →
139
+ // insert new draft → materialize derived rows → prune excess versions.
140
+ async saveDraft(rootId, input, updatedBy) {
141
+ const now = Math.floor(Date.now() / 1e3);
142
+ const newId = nanoid();
143
+ const prevDraftRow = await this.db.prepare("SELECT * FROM documents WHERE root_id = ? AND tenant_id = ? AND is_current_draft = 1").bind(rootId, this.tenantId).first();
144
+ if (!prevDraftRow) throw new Error(`No current draft found for root ${rootId}`);
145
+ const prevDraft = rowToDocument(prevDraftRow);
146
+ const mergedData = { ...prevDraft.data, ...input.data ?? {} };
147
+ const mergedMeta = { ...prevDraft.metadata, ...input.metadata ?? {} };
148
+ const newDoc = {
149
+ ...prevDraft,
150
+ id: newId,
151
+ rootId,
152
+ typeVersion: this.opts.typeSchemaVersion ?? prevDraft.typeVersion,
153
+ versionOfId: prevDraft.id,
154
+ versionNumber: 0,
155
+ // computed by SQL below
156
+ isCurrentDraft: true,
157
+ isPublished: false,
158
+ status: "draft",
159
+ slug: input.slug !== void 0 ? input.slug ?? null : prevDraft.slug,
160
+ title: input.title !== void 0 ? input.title ?? null : prevDraft.title,
161
+ zone: input.zone !== void 0 ? input.zone ?? null : prevDraft.zone,
162
+ sortOrder: input.sortOrder ?? prevDraft.sortOrder,
163
+ visible: input.visible ?? prevDraft.visible,
164
+ scheduledAt: input.scheduledAt !== void 0 ? input.scheduledAt : prevDraft.scheduledAt,
165
+ expiresAt: input.expiresAt !== void 0 ? input.expiresAt : prevDraft.expiresAt,
166
+ data: mergedData,
167
+ metadata: mergedMeta,
168
+ updatedBy: updatedBy ?? prevDraft.updatedBy,
169
+ updatedAt: now,
170
+ createdAt: now
171
+ };
172
+ const prevIsPublished = prevDraftRow.is_published === 1;
173
+ if (!this.versioning && !prevIsPublished) {
174
+ return this.updateInPlace(prevDraft, input, now, updatedBy);
175
+ }
176
+ const statements = [
177
+ // 1. Demote previous current draft FIRST (unique index: never two current drafts mid-batch).
178
+ this.db.prepare("UPDATE documents SET is_current_draft = 0, updated_at = ? WHERE id = ? AND tenant_id = ?").bind(now, prevDraft.id, this.tenantId),
179
+ // 2. If the previous draft was not also the published row, delete its derived rows.
180
+ ...!prevIsPublished ? this.projection.buildDerivedDeleteStatements(prevDraft.id) : [],
181
+ // 3. Insert new draft. version_number derived in SQL (COALESCE(MAX)+1 from existing rows).
182
+ // R5 arithmetic — keep balanced: 30 columns = 5 leading '?' + 1 version_number subquery
183
+ // + 3 literals (1,0,'draft') + 21 trailing '?'. Total placeholders: 5 + 1 (subquery
184
+ // root_id) + 21 = 27, which MUST equal the 27 .bind() args below. Do not change one side
185
+ // without recounting the other.
186
+ this.db.prepare(
187
+ `INSERT INTO documents (id, root_id, type_id, type_version, version_of_id, version_number,
188
+ is_current_draft, is_published, status, parent_root_id, slug, path, title, zone,
189
+ sort_order, visible, published_at, scheduled_at, expires_at, deleted_at,
190
+ tenant_id, locale, translation_group_id, data, metadata,
191
+ owner_id, created_by, updated_by, created_at, updated_at)
192
+ SELECT ?,?,?,?,?,
193
+ (SELECT COALESCE(MAX(version_number), 0) + 1 FROM documents WHERE root_id = ?),
194
+ 1,0,'draft',?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?
195
+ WHERE 1=1`
196
+ ).bind(
197
+ newId,
198
+ rootId,
199
+ newDoc.typeId,
200
+ newDoc.typeVersion,
201
+ prevDraft.id,
202
+ rootId,
203
+ newDoc.parentRootId,
204
+ newDoc.slug,
205
+ null,
206
+ newDoc.title,
207
+ newDoc.zone,
208
+ newDoc.sortOrder,
209
+ newDoc.visible ? 1 : 0,
210
+ null,
211
+ newDoc.scheduledAt,
212
+ newDoc.expiresAt,
213
+ null,
214
+ newDoc.tenantId,
215
+ newDoc.locale,
216
+ newDoc.translationGroupId,
217
+ JSON.stringify(newDoc.data),
218
+ JSON.stringify(newDoc.metadata),
219
+ newDoc.ownerId,
220
+ newDoc.createdBy,
221
+ newDoc.updatedBy,
222
+ now,
223
+ now
224
+ ),
225
+ // 4. Materialize derived rows for new draft.
226
+ ...this.projection.buildDerivedInsertStatements(newDoc, this.opts.queryableFields ?? [], now)
227
+ ];
228
+ const maxVersions = this.opts.maxVersionsPerRoot ?? DEFAULT_MAX_VERSIONS;
229
+ statements.push(
230
+ this.db.prepare(
231
+ `DELETE FROM documents WHERE root_id = ? AND tenant_id = ? AND is_current_draft = 0 AND is_published = 0
232
+ AND id NOT IN (
233
+ SELECT id FROM documents WHERE root_id = ? AND tenant_id = ? AND is_current_draft = 0 AND is_published = 0
234
+ ORDER BY version_number DESC LIMIT ?
235
+ )
236
+ AND id NOT IN (SELECT version_of_id FROM documents WHERE version_of_id IS NOT NULL AND root_id = ? AND tenant_id = ?)`
237
+ ).bind(rootId, this.tenantId, rootId, this.tenantId, maxVersions, rootId, this.tenantId)
238
+ );
239
+ await this.db.batch(statements);
240
+ const saved = await this.db.prepare("SELECT * FROM documents WHERE id = ?").bind(newId).first();
241
+ return rowToDocument(saved);
242
+ }
243
+ // In-place draft update (versioning off). Mutates the existing draft row; preserves id/root_id/
244
+ // version_number/version_of_id and the is_current_draft/is_published flags. Rebuilds derived rows.
245
+ async updateInPlace(prevDraft, input, now, updatedBy) {
246
+ const mergedData = { ...prevDraft.data, ...input.data ?? {} };
247
+ const mergedMeta = { ...prevDraft.metadata, ...input.metadata ?? {} };
248
+ const updated = {
249
+ ...prevDraft,
250
+ slug: input.slug !== void 0 ? input.slug ?? null : prevDraft.slug,
251
+ title: input.title !== void 0 ? input.title ?? null : prevDraft.title,
252
+ zone: input.zone !== void 0 ? input.zone ?? null : prevDraft.zone,
253
+ sortOrder: input.sortOrder ?? prevDraft.sortOrder,
254
+ visible: input.visible ?? prevDraft.visible,
255
+ scheduledAt: input.scheduledAt !== void 0 ? input.scheduledAt : prevDraft.scheduledAt,
256
+ expiresAt: input.expiresAt !== void 0 ? input.expiresAt : prevDraft.expiresAt,
257
+ data: mergedData,
258
+ metadata: mergedMeta,
259
+ updatedBy: updatedBy ?? prevDraft.updatedBy,
260
+ updatedAt: now
261
+ };
262
+ const statements = [
263
+ // R5: 11 SET '?' + 2 WHERE '?' (id, tenant_id) = 13 binds, matching .bind() below.
264
+ this.db.prepare(
265
+ `UPDATE documents SET
266
+ slug = ?, title = ?, zone = ?, sort_order = ?, visible = ?,
267
+ scheduled_at = ?, expires_at = ?, data = ?, metadata = ?, updated_by = ?, updated_at = ?
268
+ WHERE id = ? AND tenant_id = ?`
269
+ ).bind(
270
+ updated.slug,
271
+ updated.title,
272
+ updated.zone,
273
+ updated.sortOrder,
274
+ updated.visible ? 1 : 0,
275
+ updated.scheduledAt,
276
+ updated.expiresAt,
277
+ JSON.stringify(updated.data),
278
+ JSON.stringify(updated.metadata),
279
+ updated.updatedBy,
280
+ now,
281
+ updated.id,
282
+ this.tenantId
283
+ ),
284
+ // R7: derived rows track the new data — delete then reinsert for this row.
285
+ ...this.projection.buildDerivedDeleteStatements(updated.id),
286
+ ...this.projection.buildDerivedInsertStatements(updated, this.opts.queryableFields ?? [], now)
287
+ ];
288
+ await this.db.batch(statements);
289
+ const saved = await this.db.prepare("SELECT * FROM documents WHERE id = ?").bind(updated.id).first();
290
+ return rowToDocument(saved);
291
+ }
292
+ // ─── Publish ──────────────────────────────────────────────────────────────
293
+ async publish(documentId, publishedBy) {
294
+ const now = Math.floor(Date.now() / 1e3);
295
+ const targetRow = await this.db.prepare("SELECT * FROM documents WHERE id = ? AND tenant_id = ?").bind(documentId, this.tenantId).first();
296
+ if (!targetRow) throw new Error(`Document ${documentId} not found`);
297
+ const prevPublishedRow = await this.db.prepare("SELECT * FROM documents WHERE root_id = ? AND tenant_id = ? AND is_published = 1 AND id != ?").bind(targetRow.root_id, this.tenantId, documentId).first();
298
+ const statements = [];
299
+ if (prevPublishedRow) {
300
+ if (!this.versioning && prevPublishedRow.is_current_draft !== 1) {
301
+ statements.push(this.db.prepare("UPDATE documents SET version_of_id = NULL WHERE version_of_id = ? AND tenant_id = ?").bind(prevPublishedRow.id, this.tenantId));
302
+ statements.push(...this.projection.buildDerivedDeleteStatements(prevPublishedRow.id));
303
+ statements.push(this.db.prepare("DELETE FROM documents WHERE id = ? AND tenant_id = ?").bind(prevPublishedRow.id, this.tenantId));
304
+ } else {
305
+ statements.push(
306
+ this.db.prepare("UPDATE documents SET is_published = 0, updated_at = ? WHERE id = ?").bind(now, prevPublishedRow.id)
307
+ );
308
+ if (prevPublishedRow.is_current_draft !== 1) {
309
+ statements.push(...this.projection.buildDerivedDeleteStatements(prevPublishedRow.id));
310
+ }
311
+ }
312
+ }
313
+ statements.push(
314
+ this.db.prepare(
315
+ `UPDATE documents SET is_published = 1, status = 'published', published_at = ?, updated_at = ?, updated_by = ? WHERE id = ?`
316
+ ).bind(now, now, publishedBy ?? null, documentId)
317
+ );
318
+ if (targetRow.is_current_draft !== 1) {
319
+ const targetDoc = rowToDocument(targetRow);
320
+ statements.push(...this.projection.buildDerivedInsertStatements(targetDoc, this.opts.queryableFields ?? [], now));
321
+ }
322
+ await this.db.batch(statements);
323
+ const saved = await this.db.prepare("SELECT * FROM documents WHERE id = ?").bind(documentId).first();
324
+ return rowToDocument(saved);
325
+ }
326
+ // ─── Unpublish ────────────────────────────────────────────────────────────
327
+ async unpublish(documentId) {
328
+ const now = Math.floor(Date.now() / 1e3);
329
+ const row = await this.db.prepare("SELECT * FROM documents WHERE id = ? AND tenant_id = ?").bind(documentId, this.tenantId).first();
330
+ if (!row) throw new Error(`Document ${documentId} not found`);
331
+ if (!row.is_published) throw new Error(`Document ${documentId} is not published`);
332
+ const statements = [
333
+ this.db.prepare(`UPDATE documents SET is_published = 0, status = 'draft', updated_at = ? WHERE id = ?`).bind(now, documentId)
334
+ ];
335
+ if (row.is_current_draft !== 1) {
336
+ statements.push(...this.projection.buildDerivedDeleteStatements(documentId));
337
+ }
338
+ await this.db.batch(statements);
339
+ const saved = await this.db.prepare("SELECT * FROM documents WHERE id = ?").bind(documentId).first();
340
+ return rowToDocument(saved);
341
+ }
342
+ // ─── Soft delete ──────────────────────────────────────────────────────────
343
+ async softDelete(documentId) {
344
+ const now = Math.floor(Date.now() / 1e3);
345
+ await this.db.prepare("UPDATE documents SET deleted_at = ?, updated_at = ? WHERE id = ? AND tenant_id = ?").bind(now, now, documentId, this.tenantId).run();
346
+ }
347
+ // ─── Hard erase (PII types) ───────────────────────────────────────────────
348
+ // Deletes every version row for a root plus all derived data, in dependency order.
349
+ async erase(rootId, tenantId) {
350
+ const result = await this.db.prepare("SELECT id FROM documents WHERE root_id = ? AND tenant_id = ?").bind(rootId, tenantId).all();
351
+ const docIds = (result.results ?? []).map((r) => r.id);
352
+ if (docIds.length === 0) return;
353
+ const statements = [];
354
+ for (const id of docIds) {
355
+ statements.push(this.db.prepare("DELETE FROM document_facets WHERE document_id = ?").bind(id));
356
+ statements.push(this.db.prepare("DELETE FROM document_references WHERE from_document_id = ?").bind(id));
357
+ }
358
+ statements.push(this.db.prepare("DELETE FROM document_permissions WHERE root_id = ? AND tenant_id = ?").bind(rootId, tenantId));
359
+ for (const id of docIds) {
360
+ statements.push(this.db.prepare("DELETE FROM documents WHERE id = ?").bind(id));
361
+ }
362
+ await this.db.batch(statements);
363
+ }
364
+ };
365
+
366
+ // src/services/rbac.ts
367
+ var TENANT = "default";
368
+ var T_ROLE = "rbac_role";
369
+ var T_VERB = "rbac_verb";
370
+ var T_USER_ROLES = "rbac_user_roles";
371
+ var SYSTEM_RESOURCES = [
372
+ { key: "*", label: "All resources", group: "system" },
373
+ { key: "portal", label: "Admin Portal", group: "system" },
374
+ { key: "dashboard", label: "Dashboard", group: "system" },
375
+ { key: "rbac", label: "Roles & Permissions", group: "system" },
376
+ { key: "documents", label: "Documents", group: "system" },
377
+ { key: "document_types", label: "Document Types", group: "system" },
378
+ { key: "email", label: "Email Management", group: "system" },
379
+ { key: "users", label: "Users", group: "system" },
380
+ { key: "settings", label: "Settings", group: "system" },
381
+ { key: "logs", label: "Logs", group: "system" }
382
+ ];
383
+ var RbacService = class _RbacService {
384
+ constructor(db, kv) {
385
+ this.db = db;
386
+ this.kv = kv;
387
+ }
388
+ // Precedence for projecting the user's RBAC roles back onto the legacy
389
+ // users.role compat column (highest privilege first). Only `admin` is
390
+ // hardcoded as a seeded role — `editor` is listed here purely so that if an
391
+ // administrator chooses to recreate a role named `editor`, legacy code that
392
+ // still gates on the `editor` label keeps working.
393
+ static LEGACY_ROLE_PRECEDENCE = ["admin", "editor"];
394
+ _docs;
395
+ // ── Document access helpers ──────────────────────────────────────────────────
396
+ docs() {
397
+ if (!this._docs) {
398
+ this._docs = new DocumentsService(this.db, { tenantId: TENANT, maxVersionsPerRoot: 1, queryableFields: [] });
399
+ }
400
+ return this._docs;
401
+ }
402
+ parse(row) {
403
+ let data;
404
+ try {
405
+ data = JSON.parse(row.data);
406
+ } catch {
407
+ data = {};
408
+ }
409
+ return { id: row.id, rootId: row.root_id, slug: row.slug ?? "", data };
410
+ }
411
+ async listDocs(typeId) {
412
+ const res = await this.db.prepare(
413
+ `SELECT id, root_id, slug, data FROM documents
414
+ WHERE type_id = ? AND tenant_id = ? AND is_current_draft = 1 AND deleted_at IS NULL`
415
+ ).bind(typeId, TENANT).all();
416
+ return (res.results ?? []).map((r) => this.parse(r));
417
+ }
418
+ async getDoc(typeId, slug) {
419
+ const row = await this.db.prepare(
420
+ `SELECT id, root_id, slug, data FROM documents
421
+ WHERE type_id = ? AND tenant_id = ? AND slug = ? AND is_current_draft = 1 AND deleted_at IS NULL`
422
+ ).bind(typeId, TENANT, slug).first();
423
+ return row ? this.parse(row) : null;
424
+ }
425
+ async upsertDoc(typeId, slug, data, title) {
426
+ const existing = await this.db.prepare(
427
+ `SELECT root_id FROM documents
428
+ WHERE type_id = ? AND tenant_id = ? AND slug = ? AND is_current_draft = 1 AND deleted_at IS NULL`
429
+ ).bind(typeId, TENANT, slug).first();
430
+ const payload = data;
431
+ if (existing?.root_id) {
432
+ await this.docs().saveDraft(existing.root_id, { data: payload, title });
433
+ } else {
434
+ await this.docs().create({
435
+ typeId,
436
+ tenantId: TENANT,
437
+ locale: "default",
438
+ parentRootId: "",
439
+ slug,
440
+ title,
441
+ sortOrder: 0,
442
+ visible: true,
443
+ data: payload,
444
+ metadata: {},
445
+ ownerId: null,
446
+ publishOnCreate: false
447
+ });
448
+ }
449
+ }
450
+ async deleteDoc(typeId, slug) {
451
+ const doc = await this.getDoc(typeId, slug);
452
+ if (doc) await this.docs().softDelete(doc.id);
453
+ }
454
+ roleToRow(d) {
455
+ return {
456
+ id: d.slug,
457
+ name: d.data.name,
458
+ display_name: d.data.displayName,
459
+ description: d.data.description ?? null,
460
+ is_system: d.data.isSystem ? 1 : 0
461
+ };
462
+ }
463
+ // ── Reads ────────────────────────────────────────────────────────────────────
464
+ async getRoles() {
465
+ const docs = await this.listDocs(T_ROLE);
466
+ return docs.map((d) => this.roleToRow(d)).sort((a, b) => b.is_system - a.is_system || a.name.localeCompare(b.name));
467
+ }
468
+ async getVerbs() {
469
+ const docs = await this.listDocs(T_VERB);
470
+ return docs.map((d) => ({
471
+ id: d.slug,
472
+ name: d.data.name,
473
+ description: d.data.description ?? null,
474
+ is_system: d.data.isSystem ? 1 : 0,
475
+ sort_order: d.data.sortOrder ?? 100
476
+ })).sort((a, b) => a.sort_order - b.sort_order || a.name.localeCompare(b.name));
477
+ }
478
+ /** System resources + one `document_type:<name>` per active document type. */
479
+ async getResources() {
480
+ const types = (await this.db.prepare("SELECT name, display_name FROM document_types WHERE is_active = 1 ORDER BY name").all()).results;
481
+ const documentTypeResources = [
482
+ { key: "document_type:*", label: "All document types", group: "document_type" },
483
+ ...types.map((t) => ({
484
+ key: `document_type:${t.name}`,
485
+ label: t.display_name || t.name,
486
+ group: "document_type"
487
+ }))
488
+ ];
489
+ return [...SYSTEM_RESOURCES, ...documentTypeResources];
490
+ }
491
+ async getGrants() {
492
+ const roles = await this.listDocs(T_ROLE);
493
+ const out = [];
494
+ for (const r of roles) {
495
+ for (const g of r.data.grants ?? []) {
496
+ out.push({ role_id: r.slug, resource: g.resource, verb: g.verb, scope: g.scope === "own" ? "own" : "any" });
497
+ }
498
+ }
499
+ return out;
500
+ }
501
+ async getRolesForUser(userId) {
502
+ const ur = await this.getDoc(T_USER_ROLES, userId);
503
+ const roleIds = new Set(ur?.data.roleIds ?? []);
504
+ if (roleIds.size === 0) return [];
505
+ const roles = await this.listDocs(T_ROLE);
506
+ return roles.filter((r) => roleIds.has(r.slug)).map((d) => this.roleToRow(d));
507
+ }
508
+ /** Grants attached to a set of role ids (from the embedded role grants). */
509
+ async grantsForRoleIds(roleIds) {
510
+ if (roleIds.length === 0) return [];
511
+ const want = new Set(roleIds);
512
+ const roles = await this.listDocs(T_ROLE);
513
+ const out = [];
514
+ for (const r of roles) {
515
+ if (!want.has(r.slug)) continue;
516
+ for (const g of r.data.grants ?? []) {
517
+ out.push({ resource: g.resource, verb: g.verb, scope: g.scope === "own" ? "own" : "any" });
518
+ }
519
+ }
520
+ return out;
521
+ }
522
+ /** Does a single grant row satisfy the requested (resource, verb)? */
523
+ grantMatches(g, resource, verb) {
524
+ const resourceOk = g.resource === "*" || g.resource === resource || g.resource === "document_type:*" && resource.startsWith("document_type:");
525
+ if (!resourceOk) return false;
526
+ return g.verb === "*" || g.verb === verb || g.verb === "manage";
527
+ }
528
+ strongestScope(scopes) {
529
+ if (scopes.includes("any")) return "any";
530
+ if (scopes.includes("own")) return "own";
531
+ return "none";
532
+ }
533
+ /** Can the user perform `verb` on `resource`? Reads the live grant matrix. */
534
+ async can(userId, resource, verb) {
535
+ return await this.getPermissionScope(userId, resource, verb) !== "none";
536
+ }
537
+ /** Highest scope granted to the user for `resource:verb`. */
538
+ async getPermissionScope(userId, resource, verb) {
539
+ const ur = await this.getDoc(T_USER_ROLES, userId);
540
+ const grants = await this.grantsForRoleIds(ur?.data.roleIds ?? []);
541
+ return this.strongestScope(
542
+ grants.filter((g) => this.grantMatches(g, resource, verb)).map((g) => g.scope === "own" ? "own" : "any")
543
+ );
544
+ }
545
+ /** Flattened, human-readable permission list for a user. Cached in KV for 60 s. */
546
+ async permissionsForUser(userId) {
547
+ if (this.kv) {
548
+ const cached = await this.kv.get(`rbac:perms:${userId}`);
549
+ if (cached !== null) return JSON.parse(cached);
550
+ }
551
+ const ur = await this.getDoc(T_USER_ROLES, userId);
552
+ const roleIds = ur?.data.roleIds ?? [];
553
+ if (roleIds.length === 0) return [];
554
+ const grants = await this.grantsForRoleIds(roleIds);
555
+ const resources = await this.getResources();
556
+ const verbs = await this.getVerbs();
557
+ const out = /* @__PURE__ */ new Set();
558
+ for (const r of resources) {
559
+ for (const v of verbs) {
560
+ if (grants.some((g) => this.grantMatches(g, r.key, v.name))) out.add(`${r.key}:${v.name}`);
561
+ }
562
+ }
563
+ const result = [...out].sort();
564
+ if (this.kv) {
565
+ await this.kv.put(`rbac:perms:${userId}`, JSON.stringify(result), { expirationTtl: 60 });
566
+ }
567
+ return result;
568
+ }
569
+ // ── Mutations ──────────────────────────────────────────────────────────────
570
+ async createRole(name, displayName, description = "") {
571
+ const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, "-");
572
+ const id = `role-${slug}`;
573
+ await this.upsertDoc(
574
+ T_ROLE,
575
+ id,
576
+ { name: name.toLowerCase(), displayName, description, isSystem: false, grants: [] },
577
+ displayName
578
+ );
579
+ }
580
+ async deleteRole(roleId) {
581
+ const role = await this.getDoc(T_ROLE, roleId);
582
+ if (!role || role.data.isSystem) return;
583
+ await this.deleteDoc(T_ROLE, roleId);
584
+ }
585
+ /**
586
+ * Update a role's display name and description. The `name` (slug) can only be
587
+ * changed for custom roles — system role names are referenced by the legacy
588
+ * mapping, so they stay fixed.
589
+ */
590
+ async updateRole(roleId, displayName, description = "", name) {
591
+ const role = await this.getDoc(T_ROLE, roleId);
592
+ if (!role) return;
593
+ const next = { ...role.data, displayName, description };
594
+ if (!role.data.isSystem && name) {
595
+ next.name = name.toLowerCase().replace(/[^a-z0-9]+/g, "-");
596
+ }
597
+ await this.upsertDoc(T_ROLE, roleId, next, displayName);
598
+ }
599
+ /** Update displayName + portal access in a single write to avoid double-saveDraft FK issues. */
600
+ async updateRoleAndPortalAccess(roleId, displayName, name, portalEnabled, description) {
601
+ const role = await this.getDoc(T_ROLE, roleId);
602
+ if (!role) return;
603
+ const next = { ...role.data, displayName, description: description ?? role.data.description ?? "" };
604
+ if (!role.data.isSystem && name) {
605
+ next.name = name.toLowerCase().replace(/[^a-z0-9]+/g, "-");
606
+ }
607
+ const grants = (next.grants ?? []).filter((g) => !(g.resource === "portal" && g.verb === "access"));
608
+ if (portalEnabled) grants.push({ resource: "portal", verb: "access", scope: "any" });
609
+ next.grants = grants;
610
+ await this.upsertDoc(T_ROLE, roleId, next, displayName);
611
+ }
612
+ async createVerb(name, description = "") {
613
+ const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, "-");
614
+ const id = `verb-${slug}`;
615
+ await this.upsertDoc(
616
+ T_VERB,
617
+ id,
618
+ { name: name.toLowerCase(), description, isSystem: false, sortOrder: 100 },
619
+ name
620
+ );
621
+ }
622
+ async deleteVerb(verbId) {
623
+ const verb = await this.getDoc(T_VERB, verbId);
624
+ if (!verb || verb.data.isSystem) return;
625
+ await this.deleteDoc(T_VERB, verbId);
626
+ }
627
+ /** Replace all grants for one role with the supplied (resource, verb, scope) rows. */
628
+ async setRoleGrants(roleId, pairs) {
629
+ const role = await this.getDoc(T_ROLE, roleId);
630
+ if (!role) return;
631
+ const grants = pairs.map((p) => ({ resource: p.resource, verb: p.verb, scope: p.scope === "own" ? "own" : "any" }));
632
+ await this.upsertDoc(T_ROLE, roleId, { ...role.data, grants }, role.data.displayName);
633
+ }
634
+ /**
635
+ * Count active users (optionally excluding one) who hold BOTH an effective
636
+ * portal:access grant and an effective rbac:manage grant — the users who could
637
+ * recover from a permission lockout. Powers the self-lockout guard.
638
+ */
639
+ async countPortalAdmins(excludeUserId) {
640
+ const active = (await this.db.prepare("SELECT id FROM auth_user WHERE is_active = 1").all()).results;
641
+ const activeIds = new Set(active.map((u) => u.id));
642
+ const roles = await this.listDocs(T_ROLE);
643
+ const grantsByRole = new Map(roles.map((r) => [r.slug, r.data.grants ?? []]));
644
+ const userRoles = await this.listDocs(T_USER_ROLES);
645
+ let count = 0;
646
+ for (const ur of userRoles) {
647
+ const userId = ur.slug;
648
+ if (!activeIds.has(userId)) continue;
649
+ if (excludeUserId && userId === excludeUserId) continue;
650
+ let portal = false;
651
+ let rbac = false;
652
+ for (const rid of ur.data.roleIds ?? []) {
653
+ for (const g of grantsByRole.get(rid) ?? []) {
654
+ if (this.grantMatches(g, "portal", "access")) portal = true;
655
+ if (this.grantMatches(g, "rbac", "manage")) rbac = true;
656
+ }
657
+ }
658
+ if (portal && rbac) count++;
659
+ }
660
+ return count;
661
+ }
662
+ /**
663
+ * Replace a user's RBAC role assignments. The `rbac_user_roles` document is the
664
+ * single source of truth for authorization; the legacy `auth_user.role` column
665
+ * is kept as a derived projection (highest-precedence system role, else
666
+ * 'viewer') so the two never diverge.
667
+ */
668
+ async setUserRoles(userId, roleIds) {
669
+ const allRoles = await this.listDocs(T_ROLE);
670
+ const byId = new Map(allRoles.map((r) => [r.slug, r.data]));
671
+ const names = roleIds.map((id) => byId.get(id)?.name).filter((n) => !!n);
672
+ const primaryRole = _RbacService.LEGACY_ROLE_PRECEDENCE.find((r) => names.includes(r)) || "viewer";
673
+ const newGrants = [];
674
+ for (const id of roleIds) for (const g of byId.get(id)?.grants ?? []) newGrants.push(g);
675
+ const userWillBeAdmin = newGrants.some((g) => this.grantMatches(g, "portal", "access")) && newGrants.some((g) => this.grantMatches(g, "rbac", "manage"));
676
+ if (!userWillBeAdmin && await this.countPortalAdmins(userId) === 0) {
677
+ throw new Error(
678
+ "Refusing to update roles: this would leave no user able to manage Roles & Permissions and access the portal. Grant another user portal access + Roles & Permissions first."
679
+ );
680
+ }
681
+ await this.upsertDoc(T_USER_ROLES, userId, { roleIds }, null);
682
+ await this.db.prepare("UPDATE auth_user SET role = ?, updated_at = ? WHERE id = ?").bind(primaryRole, Date.now(), userId).run();
683
+ if (this.kv) await this.kv.delete(`rbac:perms:${userId}`);
684
+ }
685
+ async setRolePortalAccess(roleId, enabled) {
686
+ const role = await this.getDoc(T_ROLE, roleId);
687
+ if (!role) return;
688
+ const grants = (role.data.grants ?? []).filter((g) => !(g.resource === "portal" && g.verb === "access"));
689
+ if (enabled) grants.push({ resource: "portal", verb: "access", scope: "any" });
690
+ await this.upsertDoc(T_ROLE, roleId, { ...role.data, grants }, role.data.displayName);
691
+ }
692
+ // ── Bootstrap helpers ────────────────────────────────────────────────────────
693
+ /**
694
+ * Seed the system roles, verbs, and their grants as documents. Idempotent —
695
+ * existing roles/verbs (by slug) are left untouched. Replaces the INSERT OR
696
+ * IGNORE seeds that lived in migration 0001. Call at bootstrap, after the rbac
697
+ * document types are registered.
698
+ */
699
+ async ensureSystemRbacSeed() {
700
+ const roles = [
701
+ {
702
+ id: "role-admin",
703
+ name: "admin",
704
+ displayName: "Administrator",
705
+ description: "Full access to everything",
706
+ isSystem: true,
707
+ grants: [
708
+ { resource: "*", verb: "manage" },
709
+ { resource: "portal", verb: "access" },
710
+ { resource: "rbac", verb: "manage" },
711
+ { resource: "document_types", verb: "manage" },
712
+ { resource: "email", verb: "manage" },
713
+ { resource: "users", verb: "manage" }
714
+ ]
715
+ },
716
+ {
717
+ id: "role-editor",
718
+ name: "editor",
719
+ displayName: "Editor",
720
+ description: "Manage documents across all types",
721
+ isSystem: false,
722
+ grants: [
723
+ { resource: "portal", verb: "access" },
724
+ { resource: "documents", verb: "manage" },
725
+ { resource: "document_type:*", verb: "read" },
726
+ { resource: "document_type:*", verb: "create" },
727
+ { resource: "document_type:*", verb: "update" },
728
+ { resource: "document_type:*", verb: "delete" },
729
+ { resource: "settings", verb: "read" }
730
+ ]
731
+ }
732
+ ];
733
+ const verbs = [
734
+ { id: "verb-access", name: "access", description: "Enter or use a portal/resource", isSystem: true, sortOrder: 5 },
735
+ { id: "verb-read", name: "read", description: "View a resource", isSystem: true, sortOrder: 10 },
736
+ { id: "verb-create", name: "create", description: "Create a resource", isSystem: true, sortOrder: 20 },
737
+ { id: "verb-update", name: "update", description: "Edit a resource", isSystem: true, sortOrder: 30 },
738
+ { id: "verb-delete", name: "delete", description: "Remove a resource", isSystem: true, sortOrder: 40 },
739
+ { id: "verb-manage", name: "manage", description: "Full control (implies all verbs)", isSystem: true, sortOrder: 50 }
740
+ ];
741
+ for (const r of roles) {
742
+ if (await this.getDoc(T_ROLE, r.id)) continue;
743
+ const { id, ...data } = r;
744
+ await this.upsertDoc(T_ROLE, id, data, r.displayName);
745
+ }
746
+ for (const v of verbs) {
747
+ if (await this.getDoc(T_VERB, v.id)) continue;
748
+ const { id, ...data } = v;
749
+ await this.upsertDoc(T_VERB, id, data, v.name);
750
+ }
751
+ }
752
+ /** Assign a role to a user by role name (e.g. 'admin'), preserving existing roles. */
753
+ async addUserRoleByName(userId, roleName) {
754
+ const roles = await this.listDocs(T_ROLE);
755
+ const role = roles.find((r) => r.data.name === roleName.toLowerCase());
756
+ if (!role) return;
757
+ const ur = await this.getDoc(T_USER_ROLES, userId);
758
+ const roleIds = new Set(ur?.data.roleIds ?? []);
759
+ if (roleIds.has(role.slug)) return;
760
+ roleIds.add(role.slug);
761
+ await this.setUserRoles(userId, [...roleIds]);
762
+ }
763
+ };
764
+
765
+ export { DocumentsService, RbacService, documentSecondsToMs };
766
+ //# sourceMappingURL=chunk-BLMTL57B.js.map
767
+ //# sourceMappingURL=chunk-BLMTL57B.js.map