@cosmicdrift/kumiko-samples 0.405.0 → 0.409.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 (242) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +26 -4
  3. package/packages/bundled-features/src/account-security/feature.ts +9 -1
  4. package/packages/bundled-features/src/admin-shell/changes.json +6 -0
  5. package/packages/bundled-features/src/admin-shell/feature.ts +4 -1
  6. package/packages/bundled-features/src/agent-tools/agent-manifest.ts +1 -0
  7. package/packages/bundled-features/src/agent-tools/changes.json +6 -0
  8. package/packages/bundled-features/src/agent-tools/tool-catalog.ts +1 -0
  9. package/packages/bundled-features/src/agent-tools/types.ts +4 -0
  10. package/packages/bundled-features/src/audit/event-classification.ts +1 -0
  11. package/packages/bundled-features/src/auth-email-password/bootstrap.ts +1 -0
  12. package/packages/bundled-features/src/auth-email-password/errors.ts +18 -66
  13. package/packages/bundled-features/src/auth-email-password/web/auth-client.ts +30 -64
  14. package/packages/bundled-features/src/auth-email-password/web/auth-redirect.ts +2 -2
  15. package/packages/bundled-features/src/auth-email-password/web/confirm-account-unlock-screen.tsx +20 -66
  16. package/packages/bundled-features/src/auth-email-password/web/index.ts +1 -0
  17. package/packages/bundled-features/src/auth-email-password/web/read-path-param.ts +8 -0
  18. package/packages/bundled-features/src/auth-email-password/web/return-path.ts +3 -2
  19. package/packages/bundled-features/src/auth-email-password/web/token-confirm-screen.tsx +97 -0
  20. package/packages/bundled-features/src/auth-email-password/web/verify-email-screen.tsx +20 -68
  21. package/packages/bundled-features/src/auth-foundation/boot-checks.ts +22 -15
  22. package/packages/bundled-features/src/auth-foundation/boot-rules.ts +33 -0
  23. package/packages/bundled-features/src/auth-mfa/errors.ts +12 -42
  24. package/packages/bundled-features/src/auth-mfa/feature-exports.ts +6 -45
  25. package/packages/bundled-features/src/auth-mfa/feature.ts +8 -19
  26. package/packages/bundled-features/src/auth-mfa/web/mfa-client.ts +19 -33
  27. package/packages/bundled-features/src/billing-foundation/consumer-protection/termination-notify.ts +1 -0
  28. package/packages/bundled-features/src/billing-foundation/web/plan-price.ts +20 -7
  29. package/packages/bundled-features/src/cap-counter/stock-cap-guard.ts +1 -0
  30. package/packages/bundled-features/src/channel-in-app/changes.json +7 -0
  31. package/packages/bundled-features/src/channel-in-app/feature.ts +2 -0
  32. package/packages/bundled-features/src/channel-in-app/handlers/read-state-by-keys.query.ts +35 -0
  33. package/packages/bundled-features/src/channel-in-app/in-app-channel.ts +1 -0
  34. package/packages/bundled-features/src/channel-in-app/tables.ts +5 -1
  35. package/packages/bundled-features/src/contact/challenge.ts +41 -0
  36. package/packages/bundled-features/src/contact/changes.json +27 -0
  37. package/packages/bundled-features/src/contact/client/contact-client-source.ts +203 -0
  38. package/packages/bundled-features/src/contact/entity.ts +168 -0
  39. package/packages/bundled-features/src/contact/feature.ts +171 -0
  40. package/packages/bundled-features/src/contact/handlers/access.ts +17 -0
  41. package/packages/bundled-features/src/contact/handlers/attempts.ts +76 -0
  42. package/packages/bundled-features/src/contact/handlers/challenge.query.ts +44 -0
  43. package/packages/bundled-features/src/contact/handlers/forward-request.write.ts +98 -0
  44. package/packages/bundled-features/src/contact/handlers/mark-done.write.ts +40 -0
  45. package/packages/bundled-features/src/contact/handlers/notify-reporter-in-app.write.ts +48 -0
  46. package/packages/bundled-features/src/contact/handlers/open-count.query.ts +15 -0
  47. package/packages/bundled-features/src/contact/handlers/open-count.ts +17 -0
  48. package/packages/bundled-features/src/contact/handlers/replies.query.ts +29 -0
  49. package/packages/bundled-features/src/contact/handlers/reply.write.ts +197 -0
  50. package/packages/bundled-features/src/contact/handlers/report.write.ts +126 -0
  51. package/packages/bundled-features/src/contact/handlers/request-delivery.query.ts +143 -0
  52. package/packages/bundled-features/src/contact/handlers/request-detail.query.ts +50 -0
  53. package/packages/bundled-features/src/contact/handlers/request-list.query.ts +14 -0
  54. package/packages/bundled-features/src/contact/handlers/send-reply-mail.write.ts +124 -0
  55. package/packages/bundled-features/src/contact/handlers/send-test.write.ts +45 -0
  56. package/packages/bundled-features/src/contact/handlers/submit.write.ts +194 -0
  57. package/packages/bundled-features/src/contact/handlers/take-over-uploads.ts +47 -0
  58. package/packages/bundled-features/src/contact/i18n.ts +189 -0
  59. package/packages/bundled-features/src/contact/index.ts +29 -0
  60. package/packages/bundled-features/src/contact/lib.ts +176 -0
  61. package/packages/bundled-features/src/contact/mail.ts +401 -0
  62. package/packages/bundled-features/src/contact/options.ts +95 -0
  63. package/packages/bundled-features/src/contact/panels.ts +28 -0
  64. package/packages/bundled-features/src/contact/payloads.ts +106 -0
  65. package/packages/bundled-features/src/contact/pow.ts +22 -0
  66. package/packages/bundled-features/src/contact/screens.ts +506 -0
  67. package/packages/bundled-features/src/contact/subject.ts +13 -0
  68. package/packages/bundled-features/src/contact/user-agent.ts +39 -0
  69. package/packages/bundled-features/src/contact/user-data-hooks.ts +180 -0
  70. package/packages/bundled-features/src/contact/web/constants.ts +160 -0
  71. package/packages/bundled-features/src/contact/web/index.ts +29 -0
  72. package/packages/bundled-features/src/crypto-shredding/handlers/forget-subject.write.ts +5 -16
  73. package/packages/bundled-features/src/data-retention/changes.json +6 -0
  74. package/packages/bundled-features/src/data-retention/feature.ts +16 -2
  75. package/packages/bundled-features/src/data-retention/index.ts +5 -0
  76. package/packages/bundled-features/src/data-retention/run-retention-cleanup.ts +138 -41
  77. package/packages/bundled-features/src/data-retention/tenant-destruction-hold.ts +196 -0
  78. package/packages/bundled-features/src/delivery/address-opt-out.ts +1 -0
  79. package/packages/bundled-features/src/delivery/changes.json +7 -0
  80. package/packages/bundled-features/src/delivery/channel-context.ts +2 -0
  81. package/packages/bundled-features/src/delivery/delivery-service.ts +29 -5
  82. package/packages/bundled-features/src/delivery/events.ts +2 -0
  83. package/packages/bundled-features/src/delivery/feature.ts +3 -2
  84. package/packages/bundled-features/src/delivery/handlers/attempts-by-keys.query.ts +55 -0
  85. package/packages/bundled-features/src/delivery/handlers/log.query.ts +1 -1
  86. package/packages/bundled-features/src/delivery/jobs.ts +5 -0
  87. package/packages/bundled-features/src/delivery/tables.ts +13 -2
  88. package/packages/bundled-features/src/delivery/types.ts +3 -0
  89. package/packages/bundled-features/src/delivery/unsubscribe-page.ts +2 -0
  90. package/packages/bundled-features/src/delivery/web/delivery-channel-cell.tsx +1 -1
  91. package/packages/bundled-features/src/delivery/web/delivery-error-cell.tsx +1 -1
  92. package/packages/bundled-features/src/delivery/web/delivery-status-cell.tsx +1 -1
  93. package/packages/bundled-features/src/delivery/web/delivery-time-cell.tsx +3 -2
  94. package/packages/bundled-features/src/delivery/web/delivery-type-cell.tsx +1 -1
  95. package/packages/bundled-features/src/delivery/web/public-names.ts +1 -0
  96. package/packages/bundled-features/src/document-ingest-foundation/boot-checks.ts +14 -9
  97. package/packages/bundled-features/src/document-ingest-foundation/boot-rules.ts +22 -0
  98. package/packages/bundled-features/src/document-ingest-foundation/changes.json +6 -0
  99. package/packages/bundled-features/src/document-ingest-foundation/events.ts +17 -0
  100. package/packages/bundled-features/src/document-ingest-foundation/feature.ts +39 -1
  101. package/packages/bundled-features/src/document-ingest-foundation/index.ts +10 -0
  102. package/packages/bundled-features/src/document-ingest-foundation/report-ingest-progress.ts +43 -0
  103. package/packages/bundled-features/src/document-ingest-foundation/tables.ts +43 -0
  104. package/packages/bundled-features/src/files-tenant-data/changes.json +6 -0
  105. package/packages/bundled-features/src/files-tenant-data/hooks.ts +4 -1
  106. package/packages/bundled-features/src/folders/web/folder-manager.tsx +8 -9
  107. package/packages/bundled-features/src/folders/web/folder-section.tsx +1 -1
  108. package/packages/bundled-features/src/form-draft-user-data/index.ts +2 -0
  109. package/packages/bundled-features/src/inbound-mail-foundation/changes.json +13 -0
  110. package/packages/bundled-features/src/inbound-mail-foundation/entities.ts +2 -0
  111. package/packages/bundled-features/src/inbound-mail-foundation/events.ts +2 -0
  112. package/packages/bundled-features/src/inbound-mail-foundation/feature.ts +6 -6
  113. package/packages/bundled-features/src/inbound-mail-foundation/handlers/attach-message-content.write.ts +7 -0
  114. package/packages/bundled-features/src/inbound-mail-foundation/handlers/ingest-message.write.ts +6 -0
  115. package/packages/bundled-features/src/inbound-mail-foundation/handlers/list-messages.query.ts +6 -2
  116. package/packages/bundled-features/src/inbound-mail-foundation/handlers/message-content.query.ts +3 -0
  117. package/packages/bundled-features/src/inbound-mail-foundation/handlers/message-content.ts +19 -0
  118. package/packages/bundled-features/src/inbound-mail-foundation/projection.ts +2 -0
  119. package/packages/bundled-features/src/inbound-mail-foundation/sanitize-inbound-html.ts +150 -0
  120. package/packages/bundled-features/src/inbound-mail-foundation/types.ts +1 -0
  121. package/packages/bundled-features/src/jobs/job-run-logger.ts +24 -25
  122. package/packages/bundled-features/src/ledger/handlers/reports.query.ts +46 -31
  123. package/packages/bundled-features/src/ledger/recurring.ts +1 -0
  124. package/packages/bundled-features/src/notes-history/web/notes-section.tsx +3 -1
  125. package/packages/bundled-features/src/personal-access-tokens/feature.ts +9 -17
  126. package/packages/bundled-features/src/personal-access-tokens/handlers/create.write.ts +2 -7
  127. package/packages/bundled-features/src/secrets/changes.json +6 -0
  128. package/packages/bundled-features/src/secrets/handlers/delete.write.ts +8 -4
  129. package/packages/bundled-features/src/secrets/handlers/list.query.ts +6 -3
  130. package/packages/bundled-features/src/secrets/handlers/set.write.ts +9 -4
  131. package/packages/bundled-features/src/secrets/secret-scope.ts +33 -0
  132. package/packages/bundled-features/src/sessions/changes.json +6 -0
  133. package/packages/bundled-features/src/sessions/feature.ts +21 -18
  134. package/packages/bundled-features/src/sessions/handlers/last-activity-probe.query.ts +53 -0
  135. package/packages/bundled-features/src/sessions/handlers/last-activity-probe.route.ts +39 -0
  136. package/packages/bundled-features/src/sessions/screens.ts +1 -0
  137. package/packages/bundled-features/src/sessions/session-callbacks.ts +13 -12
  138. package/packages/bundled-features/src/sessions/web/i18n.ts +4 -1
  139. package/packages/bundled-features/src/shared/assert-billing-live.ts +14 -0
  140. package/packages/bundled-features/src/shared/collect-extension-options.ts +12 -0
  141. package/packages/bundled-features/src/shared/index.ts +16 -0
  142. package/packages/bundled-features/src/shared/late-bound-slot.ts +19 -0
  143. package/packages/bundled-features/src/shared/mail-locale-templates.ts +7 -1
  144. package/packages/bundled-features/src/shared/price-env-shape.ts +44 -0
  145. package/packages/bundled-features/src/shared/purge-row-file-refs.ts +1 -1
  146. package/packages/bundled-features/src/shared/read-feature-export-fn.ts +16 -0
  147. package/packages/bundled-features/src/shared/signup-handover.ts +3 -4
  148. package/packages/bundled-features/src/shared/tenant-destruction-hold.ts +49 -0
  149. package/packages/bundled-features/src/shared/unprocessable.ts +19 -0
  150. package/packages/bundled-features/src/shared/web/index.ts +3 -0
  151. package/packages/bundled-features/src/subscription-paddle/feature.ts +7 -15
  152. package/packages/bundled-features/src/subscription-paddle/runtime.ts +4 -7
  153. package/packages/bundled-features/src/subscription-stripe/feature.ts +7 -15
  154. package/packages/bundled-features/src/subscription-stripe/runtime.ts +4 -7
  155. package/packages/bundled-features/src/tags/entity.ts +1 -0
  156. package/packages/bundled-features/src/tags/web/tag-chip.tsx +14 -0
  157. package/packages/bundled-features/src/tags/web/tag-filter.tsx +4 -5
  158. package/packages/bundled-features/src/tags/web/tag-manager.tsx +1 -1
  159. package/packages/bundled-features/src/tags/web/tag-section.tsx +3 -6
  160. package/packages/bundled-features/src/tags/web/tags-cell.tsx +4 -5
  161. package/packages/bundled-features/src/template-resolver/compile-document-body.ts +27 -15
  162. package/packages/bundled-features/src/template-resolver/handlers/by-tenant.query.ts +11 -8
  163. package/packages/bundled-features/src/template-resolver/handlers/discard-draft.write.ts +1 -0
  164. package/packages/bundled-features/src/template-resolver/handlers/overview.query.ts +1 -0
  165. package/packages/bundled-features/src/template-resolver/handlers/send-test.write.ts +5 -5
  166. package/packages/bundled-features/src/template-resolver/handlers/toggle-status.write.ts +3 -0
  167. package/packages/bundled-features/src/template-resolver/linked-resources.ts +11 -6
  168. package/packages/bundled-features/src/template-resolver/store-template-resource.ts +15 -12
  169. package/packages/bundled-features/src/template-resolver/web/document-images.ts +6 -6
  170. package/packages/bundled-features/src/template-resolver/web/document-insert-fields.tsx +41 -36
  171. package/packages/bundled-features/src/template-resolver/web/document-schema.ts +11 -12
  172. package/packages/bundled-features/src/template-resolver/web/tiptap-attribute-parse-rule.ts +19 -0
  173. package/packages/bundled-features/src/tenant/i18n.ts +3 -0
  174. package/packages/bundled-features/src/tenant/schema/tenant.ts +1 -0
  175. package/packages/bundled-features/src/tenant/web/member-roles-cell.tsx +1 -1
  176. package/packages/bundled-features/src/tenant/web/member-status-cell.tsx +1 -1
  177. package/packages/bundled-features/src/tenant-inactivity/changes.json +8 -0
  178. package/packages/bundled-features/src/tenant-inactivity/check-inactive-tenants.ts +260 -0
  179. package/packages/bundled-features/src/tenant-inactivity/constants.ts +12 -0
  180. package/packages/bundled-features/src/tenant-inactivity/email-templates.ts +24 -0
  181. package/packages/bundled-features/src/tenant-inactivity/feature.ts +66 -0
  182. package/packages/bundled-features/src/tenant-inactivity/handlers/inactivity-state.query.ts +49 -0
  183. package/packages/bundled-features/src/tenant-inactivity/handlers/keep-account.write.ts +56 -0
  184. package/packages/bundled-features/src/tenant-inactivity/inactivity-plan.ts +187 -0
  185. package/packages/bundled-features/src/tenant-inactivity/index.ts +5 -0
  186. package/packages/bundled-features/src/tenant-inactivity/keep-token.ts +44 -0
  187. package/packages/bundled-features/src/tenant-inactivity/mail-notifications.ts +62 -0
  188. package/packages/bundled-features/src/tenant-inactivity/options.ts +38 -0
  189. package/packages/bundled-features/src/tenant-inactivity/remote-activity.ts +32 -0
  190. package/packages/bundled-features/src/tenant-inactivity/state-store.ts +71 -0
  191. package/packages/bundled-features/src/tenant-inactivity/state-table.ts +50 -0
  192. package/packages/bundled-features/src/tenant-lifecycle/boot-checks.ts +8 -6
  193. package/packages/bundled-features/src/tenant-lifecycle/boot-rules.ts +16 -0
  194. package/packages/bundled-features/src/tenant-lifecycle/changes.json +30 -0
  195. package/packages/bundled-features/src/tenant-lifecycle/constants.ts +6 -0
  196. package/packages/bundled-features/src/tenant-lifecycle/events.ts +2 -0
  197. package/packages/bundled-features/src/tenant-lifecycle/feature.ts +25 -2
  198. package/packages/bundled-features/src/tenant-lifecycle/handlers/request-destruction.write.ts +12 -87
  199. package/packages/bundled-features/src/tenant-lifecycle/index.ts +6 -0
  200. package/packages/bundled-features/src/tenant-lifecycle/request-tenant-destruction.ts +108 -0
  201. package/packages/bundled-features/src/tenant-lifecycle/retention-config-destroy-hooks.ts +62 -0
  202. package/packages/bundled-features/src/tenant-lifecycle/run-tenant-destroy.ts +131 -11
  203. package/packages/bundled-features/src/tenant-lifecycle/stages.ts +39 -4
  204. package/packages/bundled-features/src/tenant-lifecycle/testing.ts +1 -1
  205. package/packages/bundled-features/src/tier-engine/caps-for-tier-from-map.ts +16 -0
  206. package/packages/bundled-features/src/tier-engine/changes.json +6 -0
  207. package/packages/bundled-features/src/tier-engine/compose-app.ts +21 -20
  208. package/packages/bundled-features/src/tier-engine/index.ts +1 -0
  209. package/packages/bundled-features/src/user-data-rights/feature.ts +2 -0
  210. package/packages/bundled-features/src/user-data-rights/run-forget-cleanup.ts +2 -0
  211. package/packages/bundled-features/src/user-data-rights/web/privacy-center-screen.tsx +1 -1
  212. package/packages/bundled-features/src/user-data-rights/zip-path.ts +1 -0
  213. package/packages/bundled-features/src/user-data-rights-defaults/hooks/config-value.userdata-hook.ts +8 -27
  214. package/packages/bundled-features/src/user-data-rights-defaults/hooks/delivery-attempt.userdata-hook.ts +11 -8
  215. package/packages/bundled-features/src/user-data-rights-defaults/hooks/forget-own-rows-delete-hook.ts +42 -0
  216. package/packages/bundled-features/src/user-data-rights-defaults/hooks/notification-preference.userdata-hook.ts +8 -27
  217. package/packages/bundled-features/src/user-profile/handlers/change-email.write.ts +2 -6
  218. package/packages/bundled-features/src/user-profile/web/profile-screen.tsx +2 -3
  219. package/samples/apps/styleguide/src/features/widgets/i18n.ts +6 -0
  220. package/samples/apps/styleguide/src/features/widgets/web/InboxReaderExamples.tsx +158 -0
  221. package/samples/apps/styleguide/src/features/widgets/web/Widgets.tsx +2 -0
  222. package/samples/apps/styleguide/src/features/widgets/web/sample-pdf.ts +28 -0
  223. package/samples/apps/use-all-bundled/feature-manifest.json +134 -2
  224. package/samples/apps/use-all-bundled/kumiko/migrations/0063_contact.rebuild.json +4 -0
  225. package/samples/apps/use-all-bundled/package.json +1 -0
  226. package/samples/apps/use-all-bundled/playwright.config.ts +2 -0
  227. package/samples/apps/use-all-bundled/src/app/client.tsx +3 -0
  228. package/samples/apps/use-all-bundled/src/app/screens-feature.ts +46 -2
  229. package/samples/apps/use-all-bundled/src/run-config.ts +38 -4
  230. package/samples/recipes/contact/README.md +46 -0
  231. package/samples/recipes/contact/package.json +12 -0
  232. package/samples/recipes/contact/src/feature.ts +27 -0
  233. package/samples/recipes/delivery-notifications/src/feature.ts +3 -0
  234. package/samples/recipes/lane-routing/README.md +1 -0
  235. package/samples/recipes/lane-routing/src/feature.ts +8 -0
  236. package/samples/recipes/record-detail-layout/src/feature.ts +9 -1
  237. package/samples/recipes/search/README.md +2 -0
  238. package/samples/recipes/search/src/feature.ts +27 -2
  239. package/samples/recipes/secrets-demo/README.md +1 -0
  240. package/samples/recipes/secrets-demo/src/feature.ts +56 -0
  241. package/samples/recipes/tenant-inactivity/README.md +21 -0
  242. package/samples/recipes/tenant-inactivity/package.json +12 -0
@@ -3,6 +3,7 @@ import type { DbRunner, TenantDb, WhereObject } from "@cosmicdrift/kumiko-framew
3
3
  import {
4
4
  createEventStoreExecutor,
5
5
  createTenantDb,
6
+ fetchOne,
6
7
  selectMany,
7
8
  WritePurposes,
8
9
  } from "@cosmicdrift/kumiko-framework/db";
@@ -16,14 +17,18 @@ import {
16
17
  import {
17
18
  append,
18
19
  loadAggregate,
20
+ type StoredEvent,
19
21
  VersionConflictError,
20
22
  } from "@cosmicdrift/kumiko-framework/event-store";
21
23
  import type { FileProviderResolver } from "@cosmicdrift/kumiko-framework/files";
22
24
  import type { Logger } from "@cosmicdrift/kumiko-framework/logging";
23
25
  import type { SearchAdapter } from "@cosmicdrift/kumiko-framework/search";
24
26
  import { getTemporal } from "@cosmicdrift/kumiko-framework/time";
25
- import { tenantEntity, tenantTable } from "../tenant/index.ts";
27
+ import { tenantHasBlockDeleteRows } from "../data-retention/index.ts";
28
+ import type { TenantDestructionHoldProvider } from "../shared/index.ts";
29
+ import { type TenantLifecycleStatus, tenantEntity, tenantTable } from "../tenant/index.ts";
26
30
  import {
31
+ DESTRUCTION_STAGE_MAX_PENDING_MS,
27
32
  DESTRUCTION_STAGE_MIN_SLICE_MS,
28
33
  DESTRUCTION_STAGE_TICK_BUDGET_MS,
29
34
  TENANT_AGGREGATE_TYPE,
@@ -106,6 +111,33 @@ function isStageContinuation(
106
111
  return lastStageEvent?.type === qualified(TENANT_DESTRUCTION_STAGE_PROGRESSED_EVENT_SHORT);
107
112
  }
108
113
 
114
+ // Stage-started events written before startedAt existed fall back to their append time.
115
+ function currentAttemptStartedAt(
116
+ events: readonly StoredEvent[],
117
+ stageName: string,
118
+ ): Temporal.Instant | undefined {
119
+ const started = events.findLast(
120
+ (event) =>
121
+ event.type === qualified(TENANT_DESTRUCTION_STAGE_STARTED_EVENT_SHORT) &&
122
+ event.payload["stage"] === stageName,
123
+ );
124
+ if (!started) return undefined;
125
+ const startedAt = started.payload["startedAt"];
126
+ return typeof startedAt === "string" ? getTemporal().Instant.from(startedAt) : started.createdAt;
127
+ }
128
+
129
+ function isPendingWindowOpen(
130
+ events: readonly StoredEvent[],
131
+ stageName: string,
132
+ now: Temporal.Instant,
133
+ ): boolean {
134
+ const startedAt = currentAttemptStartedAt(events, stageName);
135
+ return (
136
+ startedAt !== undefined &&
137
+ now.epochMilliseconds - startedAt.epochMilliseconds <= DESTRUCTION_STAGE_MAX_PENDING_MS
138
+ );
139
+ }
140
+
109
141
  function lastEventVersion(events: ReadonlyArray<{ version: number }>): number {
110
142
  const last = events.at(-1);
111
143
  return last?.version ?? 0;
@@ -173,7 +205,11 @@ async function appendTenantStageEventIdempotent(
173
205
  return lastEventVersion(events);
174
206
  }
175
207
 
176
- async function markTenantDestroyFailed(db: DbRunner, tenantId: TenantId): Promise<void> {
208
+ async function setTenantLifecycleStatus(
209
+ db: DbRunner,
210
+ tenantId: TenantId,
211
+ status: TenantLifecycleStatus,
212
+ ): Promise<void> {
177
213
  const user = createSystemUser(tenantId);
178
214
  const scopedDb = createTenantDb({
179
215
  db,
@@ -184,7 +220,7 @@ async function markTenantDestroyFailed(db: DbRunner, tenantId: TenantId): Promis
184
220
  await tenantCrud.update(
185
221
  {
186
222
  id: tenantId,
187
- changes: { status: "destroyFailed" },
223
+ changes: { status },
188
224
  },
189
225
  user,
190
226
  scopedDb,
@@ -193,6 +229,17 @@ async function markTenantDestroyFailed(db: DbRunner, tenantId: TenantId): Promis
193
229
  invalidateTenantLifecycleGate(tenantId);
194
230
  }
195
231
 
232
+ // True while the tenant still owns rows whose blockDelete retention has not run out.
233
+ async function tenantOwnsRetentionHeldRows(args: {
234
+ readonly db: DbRunner;
235
+ readonly registry: Registry;
236
+ readonly tenantId: TenantId;
237
+ readonly now: Temporal.Instant;
238
+ }): Promise<boolean> {
239
+ if (!args.registry.features.has("data-retention")) return false;
240
+ return await tenantHasBlockDeleteRows(args);
241
+ }
242
+
196
243
  async function haltPipelineOnAbandon(args: {
197
244
  readonly db: DbRunner;
198
245
  readonly tenantId: TenantId;
@@ -223,7 +270,7 @@ async function haltPipelineOnAbandon(args: {
223
270
  { stage: args.stage, error: args.error, failedAt: failedAt.toString() },
224
271
  versionAfterAbandon,
225
272
  );
226
- await markTenantDestroyFailed(args.db, args.tenantId);
273
+ await setTenantLifecycleStatus(args.db, args.tenantId, "destroyFailed");
227
274
  }
228
275
 
229
276
  async function maybeAppendDestructionCompleted(
@@ -255,6 +302,8 @@ type StageTickResult = {
255
302
  readonly error?: string;
256
303
  readonly halted?: boolean;
257
304
  readonly progressed?: boolean;
305
+ readonly pending?: boolean;
306
+ readonly held?: boolean;
258
307
  };
259
308
 
260
309
  // `version` differs per caller: the catch path appends against the pre-run
@@ -287,6 +336,41 @@ async function recordFailedStageAttempt(args: {
287
336
  return { done: false, error: args.error };
288
337
  }
289
338
 
339
+ // A tick that neither finishes nor processes anything would otherwise loop forever,
340
+ // because progressed events do not count as attempts. A pending tick still appends a
341
+ // progressed event: without it the next tick would open a new stage-started and the
342
+ // pending window would never close.
343
+ async function recordIdleStageTick(args: {
344
+ readonly db: DbRunner;
345
+ readonly tenantId: TenantId;
346
+ readonly stage: DestructionStage;
347
+ readonly attempt: number;
348
+ readonly pending: boolean;
349
+ readonly events: readonly StoredEvent[];
350
+ readonly now: Temporal.Instant;
351
+ }): Promise<StageTickResult> {
352
+ if (args.pending && isPendingWindowOpen(args.events, args.stage.name, args.now)) {
353
+ await appendTenantStageEvent(
354
+ args.db,
355
+ args.tenantId,
356
+ qualified(TENANT_DESTRUCTION_STAGE_PROGRESSED_EVENT_SHORT),
357
+ { stage: args.stage.name, attempts: args.attempt, processed: 0, pending: true },
358
+ lastEventVersion(args.events),
359
+ );
360
+ return { done: false, pending: true };
361
+ }
362
+ return await recordFailedStageAttempt({
363
+ db: args.db,
364
+ tenantId: args.tenantId,
365
+ stage: args.stage,
366
+ attempt: args.attempt,
367
+ error: args.pending
368
+ ? `stage "${args.stage.name}" still pending after ${DESTRUCTION_STAGE_MAX_PENDING_MS / 60_000} min`
369
+ : `stage "${args.stage.name}" made no progress`,
370
+ version: lastEventVersion(args.events),
371
+ });
372
+ }
373
+
290
374
  export async function runNextDestructionStage(args: {
291
375
  readonly db: DbRunner;
292
376
  readonly registry: Registry;
@@ -298,7 +382,9 @@ export async function runNextDestructionStage(args: {
298
382
  readonly escapeHatchAuditLog?: Logger;
299
383
  readonly actor?: string;
300
384
  readonly deadlineAt?: number;
385
+ readonly now?: Temporal.Instant;
301
386
  }): Promise<StageTickResult> {
387
+ const now = args.now ?? getTemporal().Now.instant();
302
388
  const events = await loadAggregate(args.db, args.tenantId, SYSTEM_TENANT_ID);
303
389
  const { completed, abandoned, attemptsByStage } = replayStageState(events);
304
390
 
@@ -312,6 +398,20 @@ export async function runNextDestructionStage(args: {
312
398
  return { done: isDestructionPipelineComplete(completed) };
313
399
  }
314
400
 
401
+ // Parking is no stage attempt: no stage-started event, no attempt count, no failure.
402
+ if (
403
+ next.name === "tenant-row" &&
404
+ (await tenantOwnsRetentionHeldRows({
405
+ db: args.db,
406
+ registry: args.registry,
407
+ tenantId: args.tenantId,
408
+ now,
409
+ }))
410
+ ) {
411
+ await setTenantLifecycleStatus(args.db, args.tenantId, "destroyHeld");
412
+ return { done: false, held: true };
413
+ }
414
+
315
415
  const priorAttempts = attemptsByStage.get(next.name) ?? 0;
316
416
  const attempt = priorAttempts + 1;
317
417
  const ctx: DestructionStageCtx = {
@@ -325,6 +425,7 @@ export async function runNextDestructionStage(args: {
325
425
  escapeHatchAuditLog: args.escapeHatchAuditLog,
326
426
  actor: args.actor,
327
427
  deadlineAt: args.deadlineAt ?? Date.now() + DESTRUCTION_STAGE_TICK_BUDGET_MS,
428
+ now,
328
429
  };
329
430
 
330
431
  let version = lastEventVersion(events);
@@ -333,7 +434,7 @@ export async function runNextDestructionStage(args: {
333
434
  args.db,
334
435
  args.tenantId,
335
436
  qualified(TENANT_DESTRUCTION_STAGE_STARTED_EVENT_SHORT),
336
- { stage: next.name, attempts: attempt },
437
+ { stage: next.name, attempts: attempt, startedAt: now.toString() },
337
438
  version,
338
439
  stageOutcomeRecorded(events, next.name, TENANT_DESTRUCTION_STAGE_SUCCEEDED_EVENT_SHORT),
339
440
  );
@@ -346,16 +447,15 @@ export async function runNextDestructionStage(args: {
346
447
  // the version fresh instead of trusting the pre-run `version`, or this
347
448
  // append throws VersionConflictError on every stage whose run() writes.
348
449
  const eventsAfterRun = await loadAggregate(args.db, args.tenantId, SYSTEM_TENANT_ID);
349
- // A tick that neither finishes nor processes anything would otherwise loop
350
- // forever, because progressed events do not count as attempts.
351
450
  if (!outcome.done && outcome.processed === 0) {
352
- return await recordFailedStageAttempt({
451
+ return await recordIdleStageTick({
353
452
  db: args.db,
354
453
  tenantId: args.tenantId,
355
454
  stage: next,
356
455
  attempt,
357
- error: `stage "${next.name}" made no progress`,
358
- version: lastEventVersion(eventsAfterRun),
456
+ pending: outcome.pending === true,
457
+ events: eventsAfterRun,
458
+ now,
359
459
  });
360
460
  }
361
461
  if (!outcome.done) {
@@ -416,6 +516,25 @@ export async function hasTenantDestructionWork(
416
516
  return due > 0 || destroying > 0;
417
517
  }
418
518
 
519
+ // A destroyHeld tenant is not sweep work: the daily retention run releases it once its last held row
520
+ // is gone, and the sweep then runs tenant-row as a fresh first attempt.
521
+ export const tenantDestructionHoldProvider: TenantDestructionHoldProvider = {
522
+ async isParked({ db, tenantId }) {
523
+ return (await tenantStatusOf(db, tenantId)) === "destroyHeld";
524
+ },
525
+ async releaseIfFree({ db, registry, tenantId, now }) {
526
+ if ((await tenantStatusOf(db, tenantId)) !== "destroyHeld") return false;
527
+ if (await tenantOwnsRetentionHeldRows({ db, registry, tenantId, now })) return false;
528
+ await setTenantLifecycleStatus(db, tenantId, "destroying");
529
+ return true;
530
+ },
531
+ };
532
+
533
+ async function tenantStatusOf(db: DbRunner, tenantId: TenantId): Promise<string | undefined> {
534
+ const row = await fetchOne<{ status: string }>(db, tenantTable, { id: tenantId });
535
+ return row?.status;
536
+ }
537
+
419
538
  /** Cron entry: start destruction for tenants past grace, then advance stages. */
420
539
  export async function runTenantDestructionSweep(args: {
421
540
  readonly db: DbRunner;
@@ -482,6 +601,7 @@ export async function runTenantDestructionSweep(args: {
482
601
  try {
483
602
  const result = await runNextDestructionStage({
484
603
  deadlineAt: tenantDeadlineAt,
604
+ now,
485
605
  db: args.db,
486
606
  registry: args.registry,
487
607
  tenantId: row.id,
@@ -492,7 +612,7 @@ export async function runTenantDestructionSweep(args: {
492
612
  escapeHatchAuditLog: args.escapeHatchAuditLog,
493
613
  actor: args.actor,
494
614
  });
495
- if (!result.error && !result.halted) advanced++;
615
+ if (!result.error && !result.halted && !result.held) advanced++;
496
616
  } catch (err) {
497
617
  // Isolate the failure to this tenant — an uncaught throw here must not
498
618
  // abort the whole sweep tick and starve every other "destroying" tenant
@@ -1,3 +1,4 @@
1
+ /// <reference types="temporal-polyfill/global" preserve="true" />
1
2
  import {
2
3
  configuredPiiSubjectKms,
3
4
  type SubjectId,
@@ -23,6 +24,7 @@ import {
23
24
  isTenantDataExtensionHooks,
24
25
  isTenantResourceExtensionHooks,
25
26
  type Registry,
27
+ type TenantDataDestroyPhase,
26
28
  type TenantDataHookCtx,
27
29
  type TenantDestroyHookResult,
28
30
  type TenantId,
@@ -39,6 +41,10 @@ import {
39
41
  type SearchAdapter,
40
42
  } from "@cosmicdrift/kumiko-framework/search";
41
43
  import { getTemporal } from "@cosmicdrift/kumiko-framework/time";
44
+ import {
45
+ type DestructionHold,
46
+ holdBlockDeleteRowsForDestruction,
47
+ } from "../data-retention/index.ts";
42
48
  import {
43
49
  tenantEntity,
44
50
  tenantMembershipEntity,
@@ -67,9 +73,15 @@ export type DestructionStageCtx = {
67
73
  readonly actor?: string;
68
74
  // Epoch ms the stage must hand back by returning { done: false }.
69
75
  readonly deadlineAt: number;
76
+ // Sweep clock, so retention cut-offs follow the injected clock instead of wall time.
77
+ readonly now: Temporal.Instant;
70
78
  };
71
79
 
72
- export type StageRunOutcome = { readonly done: boolean; readonly processed: number };
80
+ export type StageRunOutcome = {
81
+ readonly done: boolean;
82
+ readonly processed: number;
83
+ readonly pending?: boolean;
84
+ };
73
85
 
74
86
  const STAGE_DONE: StageRunOutcome = { done: true, processed: 0 };
75
87
 
@@ -97,13 +109,15 @@ function newOutcomeAccumulator(): {
97
109
  outcome: () => StageRunOutcome;
98
110
  } {
99
111
  let allDone = true;
112
+ let pending = false;
100
113
  let processed = 0;
101
114
  return {
102
115
  add: (result) => {
103
116
  if (result?.done === false) allDone = false;
117
+ if (result?.done === false && result.pending === true) pending = true;
104
118
  processed += result?.processed ?? 0;
105
119
  },
106
- outcome: () => ({ done: allDone, processed }),
120
+ outcome: () => ({ done: allDone, processed, pending }),
107
121
  };
108
122
  }
109
123
 
@@ -125,15 +139,33 @@ async function runExtensionDestroyHooks(
125
139
  return total.outcome();
126
140
  }
127
141
 
128
- async function runTenantDataHooks(ctx: DestructionStageCtx): Promise<StageRunOutcome> {
142
+ const NOTHING_HELD: DestructionHold = { entityNames: new Set(), fileRefIds: new Set() };
143
+
144
+ async function runTenantDataHooks(
145
+ ctx: DestructionStageCtx,
146
+ phase: TenantDataDestroyPhase,
147
+ ): Promise<StageRunOutcome> {
129
148
  const usages = ctx.registry.getExtensionUsages(EXT_TENANT_DATA);
130
149
  const total = newOutcomeAccumulator();
150
+ // Rows inside a blockDelete keepFor must outlive the account; their hook is skipped, the rows are
151
+ // anonymized and the fileRefs they point at are handed to the other hooks. Recomputed every tick.
152
+ const hold =
153
+ phase === "app-data" && ctx.registry.features.has("data-retention")
154
+ ? await holdBlockDeleteRowsForDestruction({
155
+ db: ctx.db,
156
+ registry: ctx.registry,
157
+ tenantId: ctx.tenantId,
158
+ now: ctx.now,
159
+ })
160
+ : NOTHING_HELD;
131
161
  for (const usage of usages) {
132
162
  if (!isTenantDataExtensionHooks(usage.options)) {
133
163
  throw new Error(
134
164
  `${EXT_TENANT_DATA} registration for "${usage.entityName}" has no destroy function`,
135
165
  );
136
166
  }
167
+ if ((usage.options["phase"] ?? "app-data") !== phase) continue;
168
+ if (hold.entityNames.has(usage.entityName)) continue;
137
169
  const destroy = usage.options.destroy;
138
170
  const reason = extensionUsageEscapeHatchReason(usage);
139
171
  const report = createEscapeHatchReporter({
@@ -156,6 +188,7 @@ async function runTenantDataHooks(ctx: DestructionStageCtx): Promise<StageRunOut
156
188
  tenantId: ctx.tenantId,
157
189
  deadlineAt: ctx.deadlineAt,
158
190
  fileProviderResolver: ctx.fileProviderResolver,
191
+ heldFileRefIds: hold.fileRefIds,
159
192
  log: ctx.log,
160
193
  };
161
194
  total.add(await destroy(hookCtx));
@@ -239,6 +272,8 @@ async function purgeTenantCache(ctx: DestructionStageCtx): Promise<StageRunOutco
239
272
  }
240
273
 
241
274
  async function tombstoneTenantRow(ctx: DestructionStageCtx): Promise<StageRunOutcome> {
275
+ const lateHooks = await runTenantDataHooks(ctx, "tenant-row");
276
+ if (!lateHooks.done) return lateHooks;
242
277
  const now = getTemporal().Now.instant();
243
278
  const user = createSystemUser(ctx.tenantId);
244
279
  const db = createTenantDb({
@@ -309,7 +344,7 @@ export const DESTRUCTION_STAGES: readonly DestructionStage[] = [
309
344
  {
310
345
  name: "app-data",
311
346
  maxAttempts: 3,
312
- run: runTenantDataHooks,
347
+ run: (ctx) => runTenantDataHooks(ctx, "app-data"),
313
348
  },
314
349
  {
315
350
  name: "subject-keys",
@@ -51,7 +51,7 @@ export async function driveDestructionToCompletion(
51
51
  });
52
52
  const rows = await selectMany(db, tenantTable, { id: tenantId });
53
53
  status = String(rows[0]?.["status"]);
54
- if (status === "destroyed" || status === "destroyFailed") break;
54
+ if (status === "destroyed" || status === "destroyFailed" || status === "destroyHeld") break;
55
55
  }
56
56
  return status;
57
57
  }
@@ -0,0 +1,16 @@
1
+ /** Caps lookup for `TierResolverDeps.capsForTier`: an unknown tier name falls back to the default
2
+ * tier (least-privileged by convention), a name missing from the map is a wiring bug and throws. */
3
+ export function capsForTierFromMap<TTier extends string, TCaps>(
4
+ tierMap: Readonly<Record<TTier, { readonly caps: TCaps }>>,
5
+ isTierName: (value: string) => value is TTier,
6
+ defaultTier: TTier,
7
+ ): (tier: string) => TCaps {
8
+ return (tier) => {
9
+ const name = isTierName(tier) ? tier : defaultTier;
10
+ const def = tierMap[name];
11
+ if (!def) {
12
+ throw new Error(`tier-map: tier "${name}" not in tier map`);
13
+ }
14
+ return def.caps;
15
+ };
16
+ }
@@ -1,4 +1,10 @@
1
1
  [
2
+ {
3
+ "version": "0.408.0",
4
+ "type": "improvement",
5
+ "title": "capsForTierFromMap",
6
+ "detail": "capsForTierFromMap(tierMap, isTierName, defaultTier) returns a capsForTier function for createTierResolver. An unknown tier name falls back to defaultTier; if the map has no entry for the resolved name it throws. Apps with a hand-written capsForTier over their tier map can switch to it."
7
+ },
2
8
  {
3
9
  "version": "0.395.0",
4
10
  "type": "fix",
@@ -88,6 +88,21 @@ export type ComposedApp<TCaps extends Readonly<Record<string, unknown>>> = {
88
88
  * **No production callers, and that is not rot** — see
89
89
  * docs/reference/tier-composition-boot-vs-runtime.md for why.
90
90
  */
91
+ function lookupOrThrow<TValue>(
92
+ map: Readonly<Record<string, TValue>>,
93
+ name: string,
94
+ kind: string,
95
+ knownLabel: string,
96
+ ): TValue {
97
+ const value = map[name];
98
+ if (!value) {
99
+ throw new Error(
100
+ `composeApp: unknown ${kind} "${name}". ${knownLabel}: ${Object.keys(map).join(", ")}`,
101
+ );
102
+ }
103
+ return value;
104
+ }
105
+
91
106
  export function composeApp<TCaps extends Readonly<Record<string, unknown>>>(
92
107
  input: ComposeAppInput<TCaps>,
93
108
  ): ComposedApp<TCaps> {
@@ -99,31 +114,17 @@ export function composeApp<TCaps extends Readonly<Record<string, unknown>>>(
99
114
  );
100
115
  }
101
116
 
102
- const addOnDefs = input.addOns.map((name) => {
103
- const def = input.addOnMap[name];
104
- if (!def) {
105
- throw new Error(
106
- `composeApp: unknown add-on "${name}". Known add-ons: ` +
107
- `${Object.keys(input.addOnMap).join(", ")}`,
108
- );
109
- }
110
- return def;
111
- });
117
+ const addOnDefs = input.addOns.map((name) =>
118
+ lookupOrThrow(input.addOnMap, name, "add-on", "Known add-ons"),
119
+ );
112
120
 
113
121
  const tierFeatureNames = tierDef.features;
114
122
  const addOnFeatureNames = addOnDefs.flatMap((d) => d.features);
115
123
  const allFeatureNames = [...tierFeatureNames, ...addOnFeatureNames];
116
124
 
117
- const additionalFeatures = allFeatureNames.map((name) => {
118
- const feature = input.featureRegistry[name];
119
- if (!feature) {
120
- throw new Error(
121
- `composeApp: unknown feature "${name}". Registered features: ` +
122
- `${Object.keys(input.featureRegistry).join(", ")}`,
123
- );
124
- }
125
- return feature;
126
- });
125
+ const additionalFeatures = allFeatureNames.map((name) =>
126
+ lookupOrThrow(input.featureRegistry, name, "feature", "Registered features"),
127
+ );
127
128
 
128
129
  // Dedupe — a feature listed in both the tier and an add-on should only
129
130
  // mount once. Order-preserving: first occurrence wins.
@@ -8,6 +8,7 @@
8
8
  // - `TierEngineHandlers` / `TierEngineQueries` — qualified handler names
9
9
 
10
10
  export { tierAssignmentAggregateId } from "./aggregate-id.ts";
11
+ export { capsForTierFromMap } from "./caps-for-tier-from-map.ts";
11
12
  export {
12
13
  type AddOnDefinition,
13
14
  type AddOnMap,
@@ -510,6 +510,7 @@ export function createUserDataRightsFeature(opts: UserDataRightsOptions = {}): F
510
510
  // Entry point of the emailed download link; cheap static page, but
511
511
  // anonymous and token-bearing, so bound per-IP probing.
512
512
  rateLimit: { per: "ip+handler", limit: 30, windowSeconds: 60 },
513
+ // guard:dup-ok the few-shot corpus extractor reads httpRoute handlers only when they are inline
513
514
  handler: async (c) => {
514
515
  return c.body(TOKEN_EXCHANGE_PAGE_HTML, 200, {
515
516
  "content-type": "text/html; charset=utf-8",
@@ -525,6 +526,7 @@ export function createUserDataRightsFeature(opts: UserDataRightsOptions = {}): F
525
526
  method: "GET",
526
527
  path: "/user-export/by-token.js",
527
528
  anonymous: true,
529
+ // guard:dup-ok the few-shot corpus extractor reads httpRoute handlers only when they are inline
528
530
  handler: async (c) => {
529
531
  return c.body(TOKEN_EXCHANGE_PAGE_JS, 200, {
530
532
  "content-type": "application/javascript; charset=utf-8",
@@ -220,6 +220,7 @@ export function sanitizeReasonForLog(reason: string): string {
220
220
 
221
221
  // Cross-tenant by design: the due-user and membership reads on the given runner and raw hook
222
222
  // statements must see every tenant, whatever RLS scope the caller (job, operator handler) runs in.
223
+ // guard:dup-ok the single runInSystemRowLevelSecurityScope call with this entry point's own reason
223
224
  export function runForgetCleanup(args: RunForgetCleanupArgs): Promise<RunForgetCleanupResult> {
224
225
  return runInSystemRowLevelSecurityScope(
225
226
  "forget cleanup anonymizes users across all tenants",
@@ -427,6 +428,7 @@ async function processUser(args: {
427
428
  resolveDeleteBytes: resolveForgetFileBytesDeleter(buildStorageProvider),
428
429
  missingStorage: {
429
430
  mode: "skip",
431
+ // guard:dup-ok a one-message log callback; only the shape matches other log callbacks
430
432
  warn: (tenantId) =>
431
433
  // biome-ignore lint/suspicious/noConsole: misconfiguration visibility, same as the fileRef delete hook
432
434
  console.warn(
@@ -19,7 +19,7 @@ import {
19
19
  import { postWithDownload } from "@cosmicdrift/kumiko-renderer/web";
20
20
  import { propertyOf } from "@cosmicdrift/kumiko-types/type-guards";
21
21
  import { type ReactNode, useEffect, useState } from "react";
22
- import { type SectionStatus, StatusBanner } from "../../shared/web/status-banner.tsx";
22
+ import { type SectionStatus, StatusBanner } from "../../shared/web/index.ts";
23
23
  import {
24
24
  EXPORT_JOB_STATUS,
25
25
  type ExportJobStatus,
@@ -85,6 +85,7 @@ function collapseUnsafe(s: string): string {
85
85
  * tenantId and fileRefId have UUID shapes and are safe; fileName is passed
86
86
  * through sanitizeZipFilename. Path traversal is guaranteed to be excluded.
87
87
  */
88
+ // guard:dup-ok one sanitized template-literal path; only the shape matches unrelated string builders
88
89
  export function buildFileRefZipPath(args: {
89
90
  readonly tenantId: TenantId;
90
91
  readonly fileRefId: string;
@@ -1,12 +1,8 @@
1
1
  import { createEventStoreExecutor } from "@cosmicdrift/kumiko-framework/db";
2
- import {
3
- createSystemUser,
4
- type UserDataDeleteHook,
5
- type UserDataExportHook,
6
- } from "@cosmicdrift/kumiko-framework/engine";
2
+ import type { UserDataDeleteHook, UserDataExportHook } from "@cosmicdrift/kumiko-framework/engine";
7
3
  import { configValueEntity, configValuesTable } from "../../config/index.ts";
8
- import { collectErasureFailure, throwIfErasureFailed } from "../../shared/index.ts";
9
4
  import { featureMounted } from "./feature-mounted.ts";
5
+ import { forgetOwnRowsDeleteHook } from "./forget-own-rows-delete-hook.ts";
10
6
 
11
7
  // userData-Hooks for config's USER-scoped rows (userId set). Tenant-/system-
12
8
  // scope rows carry no per-user subject and stay untouched. Event-sourced
@@ -34,24 +30,9 @@ export const configValueExportHook: UserDataExportHook = async (ctx) => {
34
30
  };
35
31
  };
36
32
 
37
- export const configValueDeleteHook: UserDataDeleteHook = async (ctx) => {
38
- // skip: config not mounted — its table doesn't exist, nothing to erase.
39
- if (!featureMounted(ctx, "config")) return;
40
- const systemUser = createSystemUser(ctx.tenantId);
41
- const rows = await ctx.db.selectMany<Record<string, unknown>>(configValuesTable, {
42
- tenantId: ctx.tenantId,
43
- userId: ctx.userId,
44
- });
45
- const failures: string[] = [];
46
- for (const row of rows) {
47
- const id = row["id"]; // @cast-boundary db-row
48
- if (typeof id !== "string") continue;
49
- collectErasureFailure(
50
- await crud.forget({ id }, systemUser, ctx.db),
51
- "config-value",
52
- id,
53
- failures,
54
- );
55
- }
56
- throwIfErasureFailed(failures);
57
- };
33
+ export const configValueDeleteHook: UserDataDeleteHook = forgetOwnRowsDeleteHook({
34
+ featureName: "config",
35
+ entityName: "config-value",
36
+ table: configValuesTable,
37
+ executor: crud,
38
+ });
@@ -22,14 +22,17 @@ export const deliveryAttemptExportHook: UserDataExportHook = async (ctx) => {
22
22
  if (rows.length === 0) return null;
23
23
  return {
24
24
  entity: "delivery-attempt",
25
- rows: rows.map((r) => ({
26
- notificationType: r["notificationType"],
27
- channel: r["channel"],
28
- status: r["status"],
29
- recipientAddress: r["recipientAddress"],
30
- priority: r["priority"],
31
- createdAt: r["createdAt"],
32
- })),
25
+ rows: rows.map(
26
+ // guard:dup-ok export field selection for this entity; only the object-literal shape matches other mappers
27
+ (r) => ({
28
+ notificationType: r["notificationType"],
29
+ channel: r["channel"],
30
+ status: r["status"],
31
+ recipientAddress: r["recipientAddress"],
32
+ priority: r["priority"],
33
+ createdAt: r["createdAt"],
34
+ }),
35
+ ),
33
36
  };
34
37
  };
35
38
 
@@ -0,0 +1,42 @@
1
+ import type { EventStoreExecutor } from "@cosmicdrift/kumiko-framework/db";
2
+ import {
3
+ createSystemUser,
4
+ type UserDataDeleteHook,
5
+ type UserDataHookCtx,
6
+ } from "@cosmicdrift/kumiko-framework/engine";
7
+ import { collectErasureFailure, throwIfErasureFailed } from "../../shared/index.ts";
8
+ import { featureMounted } from "./feature-mounted.ts";
9
+
10
+ type OwnRowsTable = Parameters<UserDataHookCtx["db"]["selectMany"]>[0];
11
+
12
+ // Event-sourced rows owned by the user: forgetting goes through the executor so a rebuild replays
13
+ // the erasure.
14
+ export function forgetOwnRowsDeleteHook(source: {
15
+ readonly featureName: string;
16
+ readonly entityName: string;
17
+ readonly table: OwnRowsTable;
18
+ readonly executor: Pick<EventStoreExecutor, "forget">;
19
+ }): UserDataDeleteHook {
20
+ const { featureName, entityName, table, executor } = source;
21
+ return async (ctx) => {
22
+ // skip: source feature not mounted — its table doesn't exist, nothing to erase.
23
+ if (!featureMounted(ctx, featureName)) return;
24
+ const systemUser = createSystemUser(ctx.tenantId);
25
+ const rows = await ctx.db.selectMany<Record<string, unknown>>(table, {
26
+ tenantId: ctx.tenantId,
27
+ userId: ctx.userId,
28
+ });
29
+ const failures: string[] = [];
30
+ for (const row of rows) {
31
+ const id = row["id"]; // @cast-boundary db-row
32
+ if (typeof id !== "string") continue;
33
+ collectErasureFailure(
34
+ await executor.forget({ id }, systemUser, ctx.db),
35
+ entityName,
36
+ id,
37
+ failures,
38
+ );
39
+ }
40
+ throwIfErasureFailed(failures);
41
+ };
42
+ }