@cosmicdrift/kumiko-types 0.326.1 → 0.328.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 (173) hide show
  1. package/dist/action-icon.d.ts +3 -0
  2. package/dist/action-icon.js +51 -0
  3. package/{src/agent-exposure.ts → dist/agent-exposure.d.ts} +8 -15
  4. package/dist/agent-exposure.js +16 -0
  5. package/dist/concurrency-mode.d.ts +1 -0
  6. package/dist/config-scope.d.ts +1 -0
  7. package/dist/config-scope.js +1 -0
  8. package/dist/config.d.ts +234 -0
  9. package/dist/config.js +1 -0
  10. package/dist/cursor-types.d.ts +16 -0
  11. package/dist/cursor-types.js +1 -0
  12. package/dist/db-connection.d.ts +14 -0
  13. package/dist/db-connection.js +1 -0
  14. package/dist/define-handler.d.ts +58 -0
  15. package/dist/define-handler.js +1 -0
  16. package/dist/derivatives-types.d.ts +53 -0
  17. package/dist/derivatives-types.js +3 -0
  18. package/dist/entity-cache.d.ts +16 -0
  19. package/dist/entity-cache.js +1 -0
  20. package/dist/entity-handlers.d.ts +54 -0
  21. package/dist/entity-handlers.js +1 -0
  22. package/dist/entity-table-meta-types.d.ts +44 -0
  23. package/dist/entity-table-meta-types.js +6 -0
  24. package/dist/envelope-cipher-types.d.ts +5 -0
  25. package/dist/envelope-cipher-types.js +1 -0
  26. package/dist/event-store-executor-types.d.ts +86 -0
  27. package/dist/event-store-executor-types.js +1 -0
  28. package/dist/event-store-types.d.ts +37 -0
  29. package/dist/event-store-types.js +7 -0
  30. package/dist/event-type-map.d.ts +8 -0
  31. package/{src/event-type-map.ts → dist/event-type-map.js} +1 -16
  32. package/dist/executor-brand.d.ts +8 -0
  33. package/dist/executor-brand.js +1 -0
  34. package/dist/extension-options-map.d.ts +9 -0
  35. package/dist/extension-options-map.js +4 -0
  36. package/dist/feature.d.ts +518 -0
  37. package/dist/feature.js +1 -0
  38. package/dist/field-icon.d.ts +1 -0
  39. package/dist/field-icon.js +1 -0
  40. package/dist/fields.d.ts +729 -0
  41. package/dist/fields.js +50 -0
  42. package/dist/file-handle-types.d.ts +12 -0
  43. package/dist/file-handle-types.js +1 -0
  44. package/dist/file-provider-resolver-types.d.ts +3 -0
  45. package/dist/file-provider-resolver-types.js +1 -0
  46. package/dist/file-storage-provider-types.d.ts +17 -0
  47. package/dist/file-storage-provider-types.js +1 -0
  48. package/dist/geo-tz.d.ts +17 -0
  49. package/{src/geo-tz.ts → dist/geo-tz.js} +1 -20
  50. package/dist/handlers.d.ts +493 -0
  51. package/dist/handlers.js +49 -0
  52. package/dist/hook-phase.d.ts +1 -0
  53. package/dist/hook-phase.js +1 -0
  54. package/dist/hooks.d.ts +75 -0
  55. package/dist/hooks.js +1 -0
  56. package/dist/http-route.d.ts +52 -0
  57. package/dist/http-route.js +13 -0
  58. package/dist/identifiers.d.ts +8 -0
  59. package/{src/identifiers.ts → dist/identifiers.js} +7 -24
  60. package/dist/index.d.ts +1 -0
  61. package/dist/index.js +1 -0
  62. package/dist/kms-adapter-types.d.ts +68 -0
  63. package/dist/kms-adapter-types.js +49 -0
  64. package/dist/logger.d.ts +7 -0
  65. package/dist/logger.js +1 -0
  66. package/dist/multi-stream-apply-context-types.d.ts +18 -0
  67. package/dist/multi-stream-apply-context-types.js +1 -0
  68. package/dist/nav-icon.d.ts +3 -0
  69. package/dist/nav-icon.js +100 -0
  70. package/dist/nav.d.ts +39 -0
  71. package/dist/nav.js +1 -0
  72. package/dist/observability/index.d.ts +3 -0
  73. package/dist/observability/index.js +2 -0
  74. package/dist/observability/metric.d.ts +34 -0
  75. package/dist/observability/metric.js +3 -0
  76. package/dist/observability/provider.d.ts +24 -0
  77. package/dist/observability/provider.js +4 -0
  78. package/dist/observability/span.d.ts +32 -0
  79. package/dist/observability/span.js +4 -0
  80. package/dist/ownership.d.ts +33 -0
  81. package/dist/ownership.js +5 -0
  82. package/dist/projection.d.ts +38 -0
  83. package/dist/projection.js +1 -0
  84. package/dist/rate-limit-types.d.ts +19 -0
  85. package/dist/rate-limit-types.js +1 -0
  86. package/dist/relations.d.ts +25 -0
  87. package/dist/relations.js +1 -0
  88. package/dist/schema-table-types.d.ts +15 -0
  89. package/{src/schema-table-types.ts → dist/schema-table-types.js} +0 -20
  90. package/dist/screen.d.ts +1265 -0
  91. package/dist/screen.js +3 -0
  92. package/dist/search-adapter.d.ts +32 -0
  93. package/dist/search-adapter.js +1 -0
  94. package/dist/secrets-types.d.ts +52 -0
  95. package/dist/secrets-types.js +30 -0
  96. package/dist/snapshot-types.d.ts +13 -0
  97. package/dist/snapshot-types.js +1 -0
  98. package/dist/step.d.ts +304 -0
  99. package/dist/step.js +11 -0
  100. package/dist/target-ref.d.ts +5 -0
  101. package/{src/target-ref.ts → dist/target-ref.js} +1 -6
  102. package/dist/tenancy-brand.d.ts +6 -0
  103. package/dist/tenancy-brand.js +1 -0
  104. package/dist/tenant-db-types.d.ts +67 -0
  105. package/dist/tenant-db-types.js +5 -0
  106. package/dist/tree-node.d.ts +26 -0
  107. package/dist/tree-node.js +22 -0
  108. package/dist/tz-context.d.ts +48 -0
  109. package/dist/tz-context.js +6 -0
  110. package/dist/websocket-route.d.ts +46 -0
  111. package/dist/websocket-route.js +10 -0
  112. package/dist/where-clause-types.d.ts +20 -0
  113. package/dist/where-clause-types.js +1 -0
  114. package/dist/workspace.d.ts +10 -0
  115. package/dist/workspace.js +1 -0
  116. package/dist/write-error-info-types.d.ts +12 -0
  117. package/dist/write-error-info-types.js +1 -0
  118. package/package.json +362 -119
  119. package/src/changes.json +12 -0
  120. package/src/__tests__/handlers.test.ts +0 -40
  121. package/src/__tests__/plural-forms.test.ts +0 -18
  122. package/src/action-icon.ts +0 -57
  123. package/src/concurrency-mode.ts +0 -5
  124. package/src/config-scope.ts +0 -5
  125. package/src/config.ts +0 -563
  126. package/src/cursor-types.ts +0 -18
  127. package/src/db-connection.ts +0 -25
  128. package/src/define-handler.ts +0 -138
  129. package/src/derivatives-types.ts +0 -106
  130. package/src/entity-cache.ts +0 -35
  131. package/src/entity-handlers.ts +0 -68
  132. package/src/entity-table-meta-types.ts +0 -101
  133. package/src/envelope-cipher-types.ts +0 -6
  134. package/src/event-store-executor-types.ts +0 -163
  135. package/src/event-store-types.ts +0 -85
  136. package/src/executor-brand.ts +0 -19
  137. package/src/extension-options-map.ts +0 -21
  138. package/src/feature.ts +0 -1132
  139. package/src/field-icon.ts +0 -23
  140. package/src/fields.ts +0 -1114
  141. package/src/file-handle-types.ts +0 -20
  142. package/src/file-provider-resolver-types.ts +0 -7
  143. package/src/file-storage-provider-types.ts +0 -54
  144. package/src/handlers.ts +0 -1246
  145. package/src/hook-phase.ts +0 -2
  146. package/src/hooks.ts +0 -170
  147. package/src/http-route.ts +0 -78
  148. package/src/kms-adapter-types.ts +0 -128
  149. package/src/logger.ts +0 -7
  150. package/src/multi-stream-apply-context-types.ts +0 -52
  151. package/src/nav-icon.ts +0 -105
  152. package/src/nav.ts +0 -139
  153. package/src/observability/index.ts +0 -28
  154. package/src/observability/metric.ts +0 -56
  155. package/src/observability/provider.ts +0 -32
  156. package/src/observability/span.ts +0 -58
  157. package/src/ownership.ts +0 -83
  158. package/src/projection.ts +0 -170
  159. package/src/rate-limit-types.ts +0 -32
  160. package/src/relations.ts +0 -52
  161. package/src/screen.ts +0 -1593
  162. package/src/search-adapter.ts +0 -45
  163. package/src/secrets-types.ts +0 -182
  164. package/src/snapshot-types.ts +0 -36
  165. package/src/step.ts +0 -390
  166. package/src/tenancy-brand.ts +0 -9
  167. package/src/tenant-db-types.ts +0 -116
  168. package/src/tree-node.ts +0 -134
  169. package/src/tz-context.ts +0 -63
  170. package/src/where-clause-types.ts +0 -31
  171. package/src/workspace.ts +0 -42
  172. package/src/write-error-info-types.ts +0 -20
  173. /package/{src/index.ts → dist/concurrency-mode.js} +0 -0
package/src/feature.ts DELETED
@@ -1,1132 +0,0 @@
1
- import type * as z from "zod";
2
- import type { ZodType } from "zod";
3
- import type {
4
- ConfigKeyDefinition,
5
- ConfigKeyHandle,
6
- ConfigKeyType,
7
- ConfigSeedDef,
8
- ExtensionSelectorDef,
9
- JobDefinition,
10
- JobHandlerFn,
11
- NotificationDataFn,
12
- NotificationDefinition,
13
- NotificationRecipientFn,
14
- NotificationTemplateFn,
15
- ReferenceDataDef,
16
- RegistrarExtensionDef,
17
- RegistrarExtensionRegistration,
18
- TranslationKeys,
19
- TranslationsDef,
20
- } from "./config";
21
- import type {
22
- QueryHandlerDefinition,
23
- StreamHandlerDefinition,
24
- WriteHandlerDefinition,
25
- } from "./define-handler";
26
- import type { RegisterEntityCrudOptions } from "./entity-handlers";
27
- import type { EntityTableMeta } from "./entity-table-meta-types";
28
- import type { ExtensionOptionsArgs, ExtensionOptionsFor } from "./extension-options-map";
29
- import type { EntityDefinition } from "./fields";
30
- import type {
31
- AccessRule,
32
- AgentHandlerHints,
33
- AuthClaimsFn,
34
- AuthClaimsHookDef,
35
- ClaimKeyDefinition,
36
- ClaimKeyHandle,
37
- ClaimKeyType,
38
- DeclarativeEventMigration,
39
- EntityRef,
40
- EscapeHatchDeclaration,
41
- EventDef,
42
- EventMigrationDef,
43
- EventPiiStance,
44
- EventUpcastFn,
45
- HandlerRef,
46
- NameOrRef,
47
- QualifiedEventName,
48
- QueryHandlerDef,
49
- QueryHandlerFn,
50
- RateLimitDeclaration,
51
- StreamHandlerDef,
52
- StreamHandlerFn,
53
- WriteHandlerDef,
54
- WriteHandlerFn,
55
- } from "./handlers";
56
- import type {
57
- EntityHookMap,
58
- HookMap,
59
- HookPhase,
60
- OwnedFn,
61
- PostDeleteHookFn,
62
- PostQueryHookFn,
63
- PostSaveHookFn,
64
- PreDeleteHookFn,
65
- PreQueryHookFn,
66
- PreSaveHookFn,
67
- SearchPayloadContributorFn,
68
- ValidationHookFn,
69
- } from "./hooks";
70
- import type { HttpRouteDefinition } from "./http-route";
71
- import type { ContentCollectionDefinition, NavDefinition } from "./nav";
72
- import type {
73
- EntityProjectionExtension,
74
- MultiStreamProjectionDefinition,
75
- ProjectionDefinition,
76
- } from "./projection";
77
- import type { EntityRelations, RelationDefinition } from "./relations";
78
- import type { ScreenDefinition } from "./screen";
79
- import type { TreeActionDef, TreeActionsHandle } from "./tree-node";
80
- import type { WorkspaceDefinition } from "./workspace";
81
-
82
- // --- Metrics (declared by features via r.metric()) ---
83
-
84
- export type FeatureMetricType = "counter" | "histogram" | "gauge";
85
-
86
- // The user-facing short form written in a feature. The Framework prefixes it
87
- // with `kumiko_<featureName>_` to produce the fully-qualified Prometheus name.
88
- export type FeatureMetricDef = {
89
- readonly shortName: string;
90
- readonly type: FeatureMetricType;
91
- readonly description?: string;
92
- readonly labels?: readonly string[];
93
- readonly buckets?: readonly number[];
94
- readonly unit?: string;
95
- // When true, Framework auto-adds tenant_id to labels (ctx-driven). Default
96
- // false — cardinality multiplies by tenant count, so opt-in.
97
- readonly tenantLabel?: boolean;
98
- };
99
-
100
- export type MetricOptions = Omit<FeatureMetricDef, "shortName">;
101
-
102
- // --- Secret Keys (declared by features via r.secret()) ---
103
-
104
- // A feature-declared secret. The fully-qualified name is
105
- // `<featureName>:<shortName>` — the Framework prefixes. Ops see the
106
- // qualified name in list / audit; feature code reads it via
107
- // ctx.secrets.get(tenantId, SecretKeys.stripeKey) with the typed handle.
108
- export type SecretKeyDefinition = {
109
- // Short name inside the feature (e.g. "stripe.apiKey"). Qualified to
110
- // `<feature>:<shortName>` at registry-build time.
111
- readonly shortName: string;
112
- // Qualified name — `<feature>:<shortName>`. Set during registry build.
113
- readonly qualifiedName: string;
114
- // i18n label for TenantAdmin UI.
115
- readonly label: { readonly [locale: string]: string };
116
- // Optional redaction function. Takes the plaintext, returns the preview
117
- // shown in list handlers. Default is first-3-chars + bullets.
118
- readonly redact?: (plaintext: string) => string;
119
- // Short human hint shown in UI ("Find this in your Stripe dashboard ...").
120
- readonly hint?: { readonly [locale: string]: string };
121
- // Per-secret scope. v1 only "tenant" — user / system scopes ship in v2.
122
- readonly scope: "tenant";
123
- // Tenant must set this secret before the owning feature works. Surfaced
124
- // by readiness:query:status; keep in sync with the missing-secret throw
125
- // in the feature's build-fn.
126
- readonly required?: boolean;
127
- };
128
-
129
- export type SecretOptions = Omit<SecretKeyDefinition, "shortName" | "qualifiedName">;
130
-
131
- // Typed reference returned by r.secret(). Lets feature code pass a
132
- // strongly-named handle to ctx.secrets.get instead of retyping the
133
- // qualified string. Parallels ConfigKeyHandle from the config system.
134
- export type SecretKeyHandle = {
135
- readonly name: string;
136
- };
137
-
138
- // --- Store tables (declared by features via r.storeTable()) ---
139
- // Post-drizzle-cut: unified with the former r.unmanagedTable() — both
140
- // carried the same reason/audit contract, differing only in whether the
141
- // table value was a legacy Drizzle PgTable (storeTable) or the framework-
142
- // native EntityTableMeta (unmanagedTable, consumed by migrate-runner).
143
- // EntityTableMeta was the forward-compatible shape, so storeTable adopted it.
144
-
145
- /** Options accepted by `r.storeTable()`. The `reason` is required so the
146
- * bypass leaves an audit trail at the registration site — reviewers can
147
- * judge legitimacy without spelunking into history, and a future cleanup
148
- * pass can find candidates for migration to `r.entity()`. */
149
- export type StoreTableOptions = {
150
- /** Why this table needs to bypass the event-sourcing system. Examples:
151
- * "imported from pre-ES system, read-only", "external Stripe webhook
152
- * payload cache, write-only by webhook handler", "denormalised
153
- * projection of a non-Kumiko data source". */
154
- readonly reason: string;
155
- /** Direct-write stores skip the executor, so the executor's PII
156
- * encryption never runs for them — a feature whose meta carries
157
- * piiSubjectFields must encrypt those fields itself before every
158
- * insert/update and declare that here, or boot fails (#820). */
159
- readonly piiEncryptedOnWrite?: true;
160
- };
161
-
162
- /** Per-feature store-table registration. `meta` is the `EntityTableMeta`
163
- * (framework-native shape used by `migrate-runner`). Carries the
164
- * bypass-justification reason but knows nothing about the owning
165
- * feature — that's added when the registry aggregates entries
166
- * cross-feature into `StoreTableDef`. */
167
- export type StoreTableEntry = {
168
- readonly name: string;
169
- readonly meta: EntityTableMeta;
170
- readonly reason: string;
171
- readonly piiEncryptedOnWrite?: true;
172
- };
173
-
174
- /** Registry-aggregated store-table — the per-feature `StoreTableEntry` plus
175
- * the owning feature name. This is what `Registry.getAllStoreTables()`
176
- * exposes to readers (dev-server, ops UIs). */
177
- export type StoreTableDef = StoreTableEntry & {
178
- readonly featureName: string;
179
- };
180
-
181
- // --- UI-Hints (manifest-only, picker/scaffolder metadata) ---
182
-
183
- // Optional, declarative UI metadata declared via `r.uiHints({...})`. Surfaces
184
- // in feature-manifest.json under `feature.uiHints`. Consumers (the picker in
185
- // `create-kumiko-app`, the docs feature-reference) treat absent hints as
186
- // "no special treatment" — bare feature.name + feature.description still work.
187
- //
188
- // Keep this list lean. Anything that already has a home on the feature
189
- // (configKeys.scope/default/encrypted, secretKeys, requires, etc.) lives there.
190
- // Only add fields here that are genuinely UI-only.
191
- // "select"/"text" variants dropped (569/1) — no bundled feature uses anything
192
- // but "boolean" yet and the picker doesn't render them either; re-add once a
193
- // real feature needs them.
194
- export type UiHintOption = {
195
- readonly key: string;
196
- readonly label: string;
197
- readonly type: "boolean";
198
- readonly default: boolean;
199
- };
200
-
201
- export type UiHints = {
202
- // Picker-facing label ("Auth · Email + Password" instead of the bare
203
- // feature-name "auth-email-password").
204
- readonly displayLabel?: string;
205
- // Grouping for the picker. Free-form string; the picker sorts/groups by it.
206
- readonly category?: string;
207
- // Pre-checked in the picker when the user runs `bun create kumiko-app`.
208
- readonly recommended?: boolean;
209
- // Sub-options the picker asks about per-feature (e.g. "Password-Reset-Flow
210
- // on/off"). The scaffolder maps each key to a generator decision; the
211
- // framework doesn't act on them at runtime.
212
- readonly configurableOptions?: readonly UiHintOption[];
213
- };
214
-
215
- // --- Feature Definition (output of defineFeature) ---
216
-
217
- // Ctx passed to r.bootCheck(fn) — the full mounted-feature set, so a check
218
- // can inspect any other feature's shape (entities, PII fields, etc.).
219
- export type BootCheckContext = {
220
- readonly features: readonly FeatureDefinition[];
221
- };
222
- export type BootCheckFn = (ctx: BootCheckContext) => void;
223
-
224
- export type FeatureDefinition = {
225
- readonly name: string;
226
- // Docs-lead paragraph declared via r.describe(). Flows through the
227
- // manifest introspection into the generated feature-reference pages.
228
- readonly description?: string;
229
- readonly systemScope: boolean;
230
- // Set from the setup-callback return — typed via `defineFeature<TExports>`.
231
- // `undefined` for setups that return nothing.
232
- readonly exports?: unknown;
233
- readonly requires: readonly string[];
234
- readonly optionalRequires: readonly string[];
235
- // Read-side projection-tables this feature is allowed to write via
236
- // r.step.unsafeProjectionUpsert / unsafeProjectionDelete. Declared via
237
- // r.requires.projection("table_name"). Hard requirement — boot-error
238
- // if a step targets a non-listed table or one that's already an
239
- // r.entity-registered aggregate-table. See step-vocabulary.md Q10.
240
- readonly requiredProjections: ReadonlySet<string>;
241
- // Tier-2 step kinds opted-in via r.requires.step("webhook.send"). Q9.
242
- readonly requiredSteps: ReadonlySet<string>;
243
- // Declared via r.toggleable({ default }). Presence makes the feature
244
- // operator-switchable via the feature-toggles bundled feature; absence
245
- // means the feature is always-on (e.g. auth, tenant, user — core infra
246
- // that would brick the system if switchable).
247
- readonly toggleableDefault?: boolean;
248
- // Declarative UI metadata for picker/scaffolder tooling. Set via r.uiHints().
249
- // Pure manifest-side info — the framework runtime doesn't read it.
250
- readonly uiHints?: UiHints;
251
- // entities/hooks/entityHooks are optional: defineFeature always
252
- // materializes them, but hand-built definitions at system boundaries
253
- // (test fixtures, partial boots — see registry.test.ts "slot robustness")
254
- // omit them and the registry guards against that. Type follows runtime.
255
- readonly entities?: Readonly<Record<string, EntityDefinition>>;
256
- // Optional backing Drizzle table per entity, declared via the third arg of
257
- // `r.entity(name, def, { table })`. Source of truth for the physical DDL
258
- // when the table carries columns/indexes the field-DSL can't express
259
- // (e.g. secrets' envelope jsonb without default). `collectTableMetas` and
260
- // the registry's implicit-projection use this object instead of the
261
- // field-derived table, so generate + test-push + executor share ONE table.
262
- readonly entityTables?: Readonly<Record<string, unknown>>;
263
- readonly relations: Readonly<Record<string, EntityRelations>>;
264
- readonly writeHandlers: Readonly<Record<string, WriteHandlerDef>>;
265
- readonly queryHandlers: Readonly<Record<string, QueryHandlerDef>>;
266
- readonly streamHandlers: Readonly<Record<string, StreamHandlerDef>>;
267
- readonly translations: TranslationKeys;
268
- readonly hooks?: HookMap;
269
- readonly entityHooks?: EntityHookMap;
270
- // F3 search-payload-extension — per-entity contributors that add flat fields
271
- // to the search-index payload during indexing. Keyed by entityName. Wrapped
272
- // in OwnedFn for feature-toggle filtering (consistent with postQuery-Hooks).
273
- readonly searchPayloadExtensions?: Readonly<
274
- Record<string, readonly OwnedFn<SearchPayloadContributorFn>[]>
275
- >;
276
- readonly configKeys: Readonly<Record<string, ConfigKeyDefinition>>;
277
- readonly configSeeds: readonly ConfigSeedDef[];
278
- readonly jobs: Readonly<Record<string, JobDefinition>>;
279
- readonly registrarExtensions: Readonly<Record<string, RegistrarExtensionDef>>;
280
- readonly extensionUsages: readonly RegistrarExtensionRegistration[];
281
- readonly extensionSelectors: readonly ExtensionSelectorDef[];
282
- /**
283
- * Cross-feature API names this feature exposes via `r.exposesApi(name)`.
284
- * Pure Marker-Deklaration — die echte Implementation wird als
285
- * Query-/Write-Handler unter dem QN-Pattern registriert (z.B.
286
- * `compliance-profiles:query:effective-profile`). Boot-Validator prüft
287
- * dass jedes `r.usesApi(name)` einen passenden Exposer hier findet —
288
- * Tippfehler oder Drop-Refactorings werden zu Boot-Fail statt Runtime-Crash.
289
- */
290
- readonly exposedApis: ReadonlySet<string>;
291
- /**
292
- * Cross-feature API names this feature calls. Pflicht-Boot-Check:
293
- * jeder Eintrag muss in `exposedApis` irgendeines Features auftauchen
294
- * UND das Provider-Feature muss in requires/optionalRequires sein.
295
- */
296
- readonly usedApis: ReadonlySet<string>;
297
- /**
298
- * Boot-time mount-invariant checks declared via `r.bootCheck(fn)`. Run
299
- * once per feature after all other boot-validators, each with a ctx
300
- * exposing the full mounted-feature set — throw to fail the boot with a
301
- * feature-authored message (framework wraps it with `[Feature <name>]`).
302
- */
303
- readonly bootChecks: readonly BootCheckFn[];
304
- readonly referenceData: readonly ReferenceDataDef[];
305
- readonly notifications: Readonly<Record<string, NotificationDefinition>>;
306
- readonly events: Readonly<Record<string, EventDef>>;
307
- // Event schema migrations declared via defineEvent's `migrations` option. Keyed by event
308
- // short-name; each entry carries the step transforms (fromVersion →
309
- // toVersion). The registry stitches these with the defineEvent-declared
310
- // current version and exposes a per-qualified-name upcaster chain.
311
- readonly eventMigrations: Readonly<Record<string, readonly EventMigrationDef[]>>;
312
- readonly configReads: readonly string[];
313
- // Handler → entity mapping inferred from the colon convention
314
- // ("entityName:verb") via tryMapEntity in defineFeature.
315
- readonly handlerEntityMappings: Readonly<Record<string, string>>;
316
- // Metrics declared via r.metric(). Short names — Framework prefixes on boot.
317
- readonly metrics: Readonly<Record<string, FeatureMetricDef>>;
318
- // Secret keys declared via r.secret(). Short names — Framework prefixes to
319
- // "<feature>:<short>" during registry build.
320
- readonly secretKeys: Readonly<Record<string, SecretKeyDefinition>>;
321
- // Projections declared via r.projection(). Keyed by projection name; executor
322
- // looks them up by source-entity at write-time.
323
- readonly projections: Readonly<Record<string, ProjectionDefinition>>;
324
- // Implicit-projection extensions declared via r.extendEntityProjection().
325
- // Keyed by entity name; merged into that entity's implicit projection at
326
- // registry build so rebuildProjection replays the extension's events.
327
- readonly entityProjectionExtensions?: Readonly<
328
- Record<string, readonly EntityProjectionExtension[]>
329
- >;
330
- // Multi-stream projections — cross-aggregate async read-models. Keyed by
331
- // short name; the dispatcher wraps each into an EventConsumer with its
332
- // own cursor.
333
- readonly multiStreamProjections: Readonly<Record<string, MultiStreamProjectionDefinition>>;
334
- // Auth-claims hooks declared via r.authClaims(). Executed at login (and
335
- // switch-tenant) time; their returned records are merged into
336
- // SessionUser.claims under the auto-prefix "<featureName>:<key>".
337
- readonly authClaimsHooks: readonly AuthClaimsFn[];
338
- // Declared claim keys via r.claimKey(). Shorts keyed by their JS-side
339
- // short name, qualified name qualified at registration time.
340
- readonly claimKeys: Readonly<Record<string, ClaimKeyDefinition>>;
341
- // Screen definitions declared via r.screen(). Keyed by the feature-local
342
- // short id; the registry qualifies to "<feature>:screen:<id>" on boot.
343
- // Pure data — ui-core + renderer packages interpret; engine only stores
344
- // and validates entity/field references against the feature's entities.
345
- readonly screens: Readonly<Record<string, ScreenDefinition>>;
346
- // Nav entries declared via r.nav(). Keyed by the feature-local short id;
347
- // registry qualifies to "<feature>:nav:<id>". Flat list — the renderer's
348
- // resolveNavigation assembles the tree from parent refs at mount time.
349
- readonly navs: Readonly<Record<string, NavDefinition>>;
350
- // Workspaces declared via r.workspace(). Keyed by feature-local short id;
351
- // registry qualifies to "<feature>:workspace:<id>". Pure UI metadata —
352
- // shellWorkspaces consumes the resolved per-workspace nav list at mount
353
- // time; engine validates roles + nav refs at boot.
354
- readonly workspaces: Readonly<Record<string, WorkspaceDefinition>>;
355
- // Tree-Actions-Map declared via r.treeActions(). At-most-one per feature
356
- // (only-once-guard at registration). Erased to `Record<string,
357
- // TreeActionDef>` for runtime registry-lookup (Visual-Tree-Component
358
- // dispatching, Pattern-AST consumers). The compile-time-typed surface
359
- // is the registrar's return value (TreeActionsHandle) which the
360
- // feature exports via setup-return — buildTarget consumes the handle,
361
- // not this slot. See visual-tree.md A5 + A7.
362
- readonly treeActions?: Readonly<Record<string, TreeActionDef>>;
363
- // Content collections declared via r.contentCollection(). Keyed by the
364
- // feature-local short id. Each one also produced a nav entry under the
365
- // same id — this slot carries the `kind` the client needs to build the
366
- // matching tree provider, which a NavDefinition has no place for.
367
- readonly contentCollections?: Readonly<Record<string, ContentCollectionDefinition>>;
368
- // HTTP-Routes declared via r.httpRoute(). Index is "METHOD path"
369
- // (z.B. "GET /feed.xml") — eindeutig pro Feature. Die App-Server-
370
- // Boot-Stage iteriert getAllHttpRoutes() und mountet jede Route auf
371
- // den Hono-app (außerhalb /api/*). Pattern symmetrisch zu queryHandlers/
372
- // writeHandlers — Routes leben mit dem Feature, nicht im Bootstrap.
373
- readonly httpRoutes: Readonly<Record<string, HttpRouteDefinition>>;
374
- // Store tables declared via r.storeTable() — bypass the event-sourcing
375
- // system. Keyed by feature-local short name (derived from
376
- // meta.tableName). The registry attaches featureName on aggregation,
377
- // lifting StoreTableEntry → StoreTableDef. `kumiko schema generate`
378
- // aggregates these alongside r.entity()-derived metas to build the
379
- // full schema.
380
- readonly storeTables: Readonly<Record<string, StoreTableEntry>>;
381
- // Optional Zod-schema for env-vars this feature reads at runtime.
382
- // Declared via `r.envSchema(z.object({...}))`. `composeEnvSchema` reads
383
- // this to build one app-wide schema for boot-validation + dry-run
384
- // rendering. Absence means the feature reads no env-vars (or hasn't
385
- // been migrated yet — Sprint-9 migration is add-only per phase).
386
- readonly envSchema?: z.ZodObject<z.ZodRawShape>;
387
- // Factory guarantee: two instances with shallow-equal dedupeOptions are interchangeable.
388
- readonly dedupeOptions?: Readonly<Record<string, unknown>>;
389
- };
390
-
391
- // --- Feature Registrar (the "r" object in defineFeature) ---
392
-
393
- type RefOrRefs = NameOrRef | readonly NameOrRef[];
394
- // Entity-wide hook target — "all query/write handlers of this entity",
395
- // same reach r.entityHook() used to have. Only valid for postSave/
396
- // preDelete/postDelete/postQuery (the same 4 types entityHook covered);
397
- // hook() throws at registration time if used with validation/preSave/
398
- // preQuery.
399
- type HookTarget = RefOrRefs | { readonly allOf: NameOrRef };
400
-
401
- /**
402
- * `TFeature` is the literal feature-name from `defineFeature("foo", ...)` —
403
- * default-`string` keeps every existing usage zero-config. Strict-typed
404
- * features (apps that opt into the literal-name flavour) get propagated
405
- * through to `defineEvent` so the returned `EventDef.name` is a literal
406
- * `${CamelToKebab<TFeature>}:event:${CamelToKebab<TInner>}`. That literal
407
- * threads through `ctx.appendEvent({ type: eventDef.name, ... })`,
408
- * keeping strict-mode alive even when handlers route via `eventDef.name`
409
- * instead of hand-typed string literals.
410
- */
411
- /**
412
- * `r.requires` is a callable+namespace: existing call form takes feature
413
- * names (`r.requires("auth", "tenant")`), the `.projection` extension
414
- * declares read-side projection tables that this feature's pipeline
415
- * steps are allowed to write via `r.step.unsafeProjectionUpsert`.
416
- * Hard-required for any unsafeProjection-* step usage (see Q10).
417
- */
418
- export type RequiresApi = ((...featureNames: string[]) => void) &
419
- // Object-Form — the shape the feature-ast renderer (`render.ts`) emits
420
- // for Designer/AI-generated code. A single object argument with named
421
- // fields is easier to generate correctly than positional args whose
422
- // count/order vary per registrar method.
423
- ((options: { readonly features: readonly string[] }) => void) & {
424
- readonly projection: (tableName: string) => void;
425
- // Tier-2 step opt-in (Q9). Tier-1 implicit, Tier-2 must be declared.
426
- readonly step: (stepKind: string) => void;
427
- };
428
-
429
- export type FeatureRegistrar<TFeature extends string = string> = {
430
- systemScope(): void;
431
- // One-to-three-sentence docs-lead for the feature ("what it does + when
432
- // you need it"). At most once per feature; must be non-empty.
433
- describe(text: string): void;
434
- requires: RequiresApi;
435
- optionalRequires(...featureNames: string[]): void;
436
- optionalRequires(options: { readonly features: readonly string[] }): void;
437
- // Declare the feature as operator-togglable. `default` is the effective
438
- // state when no global-toggle row exists. Must be called at most once per
439
- // feature; calling on an always-on feature (e.g. auth/tenant/user) is a
440
- // bug — and one nothing catches at boot, so don't.
441
- toggleable(options: { default: boolean }): void;
442
- // Picker/scaffolder metadata — see UiHints. At most once per feature.
443
- uiHints(hints: UiHints): void;
444
-
445
- entity(
446
- name: string,
447
- definition: EntityDefinition,
448
- options?: { readonly table?: unknown },
449
- ): EntityRef;
450
- entity(definition: { readonly name: string } & EntityDefinition): EntityRef;
451
-
452
- // Shorthand for registerEntityCrud(r, ...), scoped to this registrar.
453
- crud(entityName: string, entity: EntityDefinition, options?: RegisterEntityCrudOptions): void;
454
-
455
- writeHandler<TName extends string, TSchema extends ZodType>(
456
- def: WriteHandlerDefinition<TName, TSchema>,
457
- ): HandlerRef;
458
- writeHandler<TSchema extends ZodType>(
459
- name: string,
460
- schema: TSchema,
461
- handler: WriteHandlerFn<z.infer<TSchema>>,
462
- options: {
463
- access: AccessRule;
464
- rateLimit?: RateLimitDeclaration;
465
- description?: string;
466
- agent?: AgentHandlerHints;
467
- escapeHatch?: EscapeHatchDeclaration;
468
- },
469
- ): HandlerRef;
470
-
471
- queryHandler<TName extends string, TSchema extends ZodType>(
472
- def: QueryHandlerDefinition<TName, TSchema>,
473
- ): HandlerRef;
474
- queryHandler<TSchema extends ZodType>(
475
- name: string,
476
- schema: TSchema,
477
- handler: QueryHandlerFn<z.infer<TSchema>>,
478
- options: {
479
- access: AccessRule;
480
- rateLimit?: RateLimitDeclaration;
481
- outputSchema?: ZodType;
482
- description?: string;
483
- agent?: AgentHandlerHints;
484
- escapeHatch?: EscapeHatchDeclaration;
485
- },
486
- ): HandlerRef;
487
-
488
- streamHandler<TName extends string, TSchema extends ZodType>(
489
- def: StreamHandlerDefinition<TName, TSchema>,
490
- ): HandlerRef;
491
- streamHandler<TSchema extends ZodType>(
492
- name: string,
493
- schema: TSchema,
494
- handler: StreamHandlerFn<z.infer<TSchema>>,
495
- options: {
496
- access: AccessRule;
497
- rateLimit?: RateLimitDeclaration;
498
- escapeHatch?: EscapeHatchDeclaration;
499
- },
500
- ): HandlerRef;
501
-
502
- relation(entity: NameOrRef, relationName: string, definition: RelationDefinition): void;
503
- // TDef inferred from the literal — keeps the excess-property check
504
- // resolved against the matching RelationDefinition union member instead
505
- // of distributing across all three (which spuriously rejects valid
506
- // combinations when checked directly against the raw union).
507
- relation<TDef extends RelationDefinition>(
508
- definition: { readonly entity: NameOrRef; readonly name: string } & TDef,
509
- ): void;
510
-
511
- hook(type: "validation", target: RefOrRefs, fn: ValidationHookFn): void;
512
- // escapeHatch grants this hook (not the handler) identity-switches beyond its caller — see system-identity-switch.ts.
513
- hook(
514
- type: "preSave",
515
- target: RefOrRefs,
516
- fn: PreSaveHookFn,
517
- options?: { escapeHatch?: EscapeHatchDeclaration },
518
- ): void;
519
- // postSave/preDelete/postDelete/postQuery accept `{ allOf: entityRef }` —
520
- // fires for every write/query handler of that entity, replacing the old
521
- // r.entityHook(type, entity, fn). postQuery's entity-wide form fires for
522
- // ALL query-handlers of the entity (e.g. customFields-bundle merging
523
- // custom-fields-jsonb into every read); no phase semantics there
524
- // (synchronous after handler-execute, before field-access-filter).
525
- hook(
526
- type: "postSave",
527
- target: HookTarget,
528
- fn: PostSaveHookFn,
529
- options?: { phase?: HookPhase; escapeHatch?: EscapeHatchDeclaration },
530
- ): void;
531
- // preDelete always runs in-transaction (it guards the delete — there is no
532
- // meaningful "after" for a pre-hook). No phase option.
533
- hook(
534
- type: "preDelete",
535
- target: HookTarget,
536
- fn: PreDeleteHookFn,
537
- options?: { escapeHatch?: EscapeHatchDeclaration },
538
- ): void;
539
- hook(
540
- type: "postDelete",
541
- target: HookTarget,
542
- fn: PostDeleteHookFn,
543
- options?: { phase?: HookPhase; escapeHatch?: EscapeHatchDeclaration },
544
- ): void;
545
- hook(
546
- type: "preQuery",
547
- target: RefOrRefs,
548
- fn: PreQueryHookFn,
549
- options?: { escapeHatch?: EscapeHatchDeclaration },
550
- ): void;
551
- hook(
552
- type: "postQuery",
553
- target: HookTarget,
554
- fn: PostQueryHookFn,
555
- options?: { escapeHatch?: EscapeHatchDeclaration },
556
- ): void;
557
-
558
- // F3 — Search-Payload-Extension: contributor function adds flat fields to
559
- // an entity's search-index document. Fires synchronously during
560
- // buildSearchDocument indexing. Use-case: custom-fields-bundle merging
561
- // customFields-jsonb-keys flat into search-doc; tags-bundle projecting
562
- // tags-array as searchable. See `SearchPayloadContributorFn`.
563
- searchPayloadExtension(entity: NameOrRef, fn: SearchPayloadContributorFn): void;
564
-
565
- // Single-key form: bare handle, no wrapping record, no seeds (callers
566
- // needing seeds use the multi-key form below).
567
- config<T extends ConfigKeyType>(keyName: string, def: ConfigKeyDefinition<T>): ConfigKeyHandle<T>;
568
-
569
- // Multi-key form: returns a handle map keyed exactly like the input. Pass
570
- // any handle to `ctx.config(handle)` to get the value type narrowed by the
571
- // key's `type`. Optional `seeds` declare boot-time system-rows that are
572
- // written via the event-store executor — idempotent, skipped when the
573
- // stream already exists.
574
- config<TKeys extends Readonly<Record<string, ConfigKeyDefinition<ConfigKeyType>>>>(definition: {
575
- readonly keys: TKeys;
576
- readonly seeds?: Readonly<Record<string, ConfigSeedDef>>;
577
- }): { readonly [K in keyof TKeys]: ConfigKeyHandle<TKeys[K]["type"]> };
578
-
579
- job(name: string, options: Omit<JobDefinition, "name" | "handler">, handler: JobHandlerFn): void;
580
- job(definition: JobDefinition): void;
581
-
582
- notification(
583
- name: string,
584
- definition: {
585
- readonly trigger: { readonly on: NameOrRef };
586
- readonly recipient: NotificationRecipientFn;
587
- readonly data: NotificationDataFn;
588
- readonly templates?: Readonly<Record<string, NotificationTemplateFn>>;
589
- },
590
- ): void;
591
- notification(definition: {
592
- readonly name: string;
593
- readonly trigger: { readonly on: NameOrRef };
594
- readonly recipient: NotificationRecipientFn;
595
- readonly data: NotificationDataFn;
596
- readonly templates?: Readonly<Record<string, NotificationTemplateFn>>;
597
- }): void;
598
-
599
- translations(def: TranslationsDef): void;
600
-
601
- // Register an event payload shape. Returns the qualified def so callers
602
- // can pass `.name` to ctx.appendEvent without hand-building the
603
- // "<feature>:event:<short>" string.
604
- //
605
- // `options.version` declares the CURRENT schema generation. Defaults to 1
606
- // on first registration. When you bump the payload shape, add a step to
607
- // `options.migrations` covering N -> N+1 — the framework refuses to boot
608
- // if the chain from 1 to `version` has gaps. Migrations were formerly a
609
- // separate r.eventMigration() call; folded in here because an event and
610
- // its schema evolution are one lifecycle, not two registrar concepts
611
- // (#1082 step 8) — transforms are pure functions (old payload in, new
612
- // payload out) and run once per read, not once per event persisted, so
613
- // keep them cheap.
614
- //
615
- // `options.piiFields` is a mandatory, explicit PII stance (fw#2558) —
616
- // registration fails without one. Pass a map of payload fields to their
617
- // owning subject via `{ personal: { of: "<ownerField>" } }` (the older
618
- // `{ subjectField: "<ownerField>" }` form still works) for fields carrying
619
- // personal data (encrypted under that user's DEK, crypto-shredding #799),
620
- // or `"none"` to declare the payload holds no personal data. append()
621
- // enforces the resulting catalog on every write path.
622
- //
623
- // When the schema lets the owner field be null/undefined, the stance must
624
- // also say what happens on those writes — `whenAbsent: "tenant"` encrypts
625
- // under the envelope tenant key, `whenAbsent: "plaintext"` acknowledges an
626
- // unshreddable value. Registration fails without one, and an owner that is
627
- // empty at append time with no declared fallback aborts the write (fw#2776).
628
- defineEvent<const TInner extends string, TPayload>(
629
- name: TInner,
630
- schema: ZodType<TPayload>,
631
- options: {
632
- readonly version?: number;
633
- readonly piiFields: EventPiiStance;
634
- readonly migrations?: readonly {
635
- readonly fromVersion: number;
636
- readonly toVersion: number;
637
- readonly transform: EventUpcastFn | DeclarativeEventMigration;
638
- }[];
639
- },
640
- ): EventDef<TPayload, QualifiedEventName<TFeature, TInner>>;
641
-
642
- readsConfig(...qualifiedKeys: string[]): void;
643
- readsConfig(options: { readonly keys: readonly string[] }): void;
644
-
645
- referenceData(
646
- entity: NameOrRef,
647
- data: readonly Record<string, unknown>[],
648
- options?: { upsertKey?: string },
649
- ): void;
650
- referenceData(definition: {
651
- readonly entity: NameOrRef;
652
- readonly data: readonly Record<string, unknown>[];
653
- readonly upsertKey?: string;
654
- }): void;
655
-
656
- extendsRegistrar(name: string, def: RegistrarExtensionDef): void;
657
-
658
- useExtension<N extends string>(
659
- extensionName: N,
660
- entity: NameOrRef,
661
- ...options: ExtensionOptionsArgs<N>
662
- ): void;
663
- useExtension<N extends string>(
664
- definition: { readonly name: N; readonly entity: NameOrRef } & ExtensionOptionsFor<N>,
665
- ): void;
666
-
667
- /**
668
- * Declares which config key selects the active provider under an
669
- * extension point — called by the point-owning foundation (e.g.
670
- * `r.extensionSelector("mailTransport", configKeys.provider)`).
671
- * Readiness gating counts a provider-feature's `required` keys and
672
- * secrets only while that provider is the selected one. Registry-build
673
- * fails on duplicate declarations per extension and on selector keys
674
- * that no mounted feature declares. A masked tenant selector key makes the
675
- * Settings-Hub render one tenant dashboard for the owner: the selector as a
676
- * select of the mounted plugin ids, the selected plugin's config and secrets
677
- * as panels, and plugin features lose their own tenant nav. `config:write:set`
678
- * rejects unknown plugin ids (`""` clears).
679
- */
680
- extensionSelector(extensionName: string, key: { readonly name: string } | string): void;
681
-
682
- /**
683
- * Marker-Deklaration: dieses Feature stellt eine Cross-Feature-API
684
- * unter dem genannten Namen bereit. Die eigentliche Implementation
685
- * wird separat als Query- oder Write-Handler unter dem QN-Pattern
686
- * registriert; `r.exposesApi` ist reine Boot-Check-Surface.
687
- *
688
- * Boot-Validator prüft, dass jedes `r.usesApi(name)` einen passenden
689
- * Exposer findet, dass das Exposer-Feature in requires/optionalRequires
690
- * gelisted ist und dass kein API-Name doppelt exposed wird.
691
- *
692
- * ```ts
693
- * defineFeature("compliance-profiles", (r) => {
694
- * r.exposesApi("compliance.forTenant");
695
- * r.queryHandler({
696
- * name: "compliance:query:for-tenant",
697
- * // ... echte Implementation
698
- * });
699
- * });
700
- * ```
701
- */
702
- exposesApi(apiName: string): void;
703
-
704
- /**
705
- * Declares that this feature calls a cross-feature API. Boot-Validator
706
- * checkt dass irgendein anderes Feature `r.exposesApi(apiName)` macht
707
- * und dass dieses Feature `r.requires/optionalRequires` darauf hat.
708
- *
709
- * ```ts
710
- * defineFeature("user-data-rights", (r) => {
711
- * r.requires("compliance-profiles");
712
- * r.usesApi("compliance.forTenant");
713
- * });
714
- * ```
715
- */
716
- usesApi(apiName: string): void;
717
-
718
- /**
719
- * Declares a boot-time mount-invariant for this feature. `fn` runs once
720
- * at boot with a ctx exposing every mounted feature — throw to fail the
721
- * boot with a clear message. Multiple calls per feature are allowed.
722
- *
723
- * Use for cross-feature invariants that `r.requires` can't express
724
- * because they're conditional (only fail when the feature has a
725
- * specific shape), e.g. "if this feature has PII entities, some
726
- * user-data-hook feature must be mounted" (the prompt-store trap,
727
- * kumiko-enterprise#229 — a UserData feature was written but never
728
- * mounted, and nothing caught it at boot):
729
- *
730
- * ```ts
731
- * defineFeature("prompt-store", (r) => {
732
- * const promptFields = { text: createTextField({ personal: "self", find: "none" }) };
733
- * r.entity("prompt", { fields: promptFields });
734
- * r.bootCheck(({ features }) => {
735
- * // Conditional on this feature's own shape (has a pii field) —
736
- * // r.requires("user-data-hook") can't express that, it would fail
737
- * // even for a prompt-store variant with no PII fields at all.
738
- * const hasPiiField = Object.values(promptFields).some((f) => f.pii);
739
- * const hasUserDataHook = features.some((f) => f.name === "user-data-hook");
740
- * if (hasPiiField && !hasUserDataHook) {
741
- * throw new Error("prompt-store has PII fields but no user-data-hook feature is mounted");
742
- * }
743
- * });
744
- * });
745
- * ```
746
- */
747
- bootCheck(fn: BootCheckFn): void;
748
-
749
- // Declare a metric. Short name (without kumiko_<feature>_ prefix) — Framework
750
- // qualifies it on boot. Validation (snake_case + typ-suffix) runs at boot.
751
- // Usage at runtime: ctx.metrics.inc("created_total", { status: "new" }).
752
- metric(shortName: string, options: MetricOptions): void;
753
- metric(definition: { readonly name: string } & MetricOptions): void;
754
-
755
- // Declare a secret key. Qualified name follows "<feature>:secret:<kebab>"
756
- // via the QN helper. Returns a typed handle so feature code can pass it
757
- // to ctx.secrets.get without retyping the qualified string — same
758
- // ergonomics as r.config's handle.
759
- secret(shortName: string, options: SecretOptions): SecretKeyHandle;
760
- secret(definition: { readonly name: string } & SecretOptions): SecretKeyHandle;
761
-
762
- // Register a projection driven by events of one or more source entities.
763
- // The runtime fires projection.apply[event.type] inside the event-store's
764
- // transaction, so projections stay consistent with the events that feed them.
765
- projection(definition: ProjectionDefinition): void;
766
-
767
- // Register a cross-aggregate async projection. The event-dispatcher owns
768
- // delivery via a dedicated cursor — at-least-once, strictly-ordered by
769
- // events.id. Handlers must be idempotent. Marten's MultiStreamProjection
770
- // equivalent: customer billing summaries, cross-feature audit views,
771
- // saga state machines where a single view spans many aggregate types.
772
- // Omit `table` for pure side-effect handlers (notifications, webhooks,
773
- // external-system sync) — the dispatcher still delivers at-least-once with
774
- // per-consumer ordering and dead-letter behaviour.
775
- multiStreamProjection(definition: MultiStreamProjectionDefinition): void;
776
-
777
- // Merge extra apply handlers (+ extra event sources) into an entity's
778
- // implicit projection so rebuildProjection replays event types a bundled
779
- // extension materializes into the HOST entity's table (custom-fields
780
- // pattern). Rebuild-only: the inline runner skips implicit projections —
781
- // live delivery stays with the extension's own MSP. The entity must be
782
- // declared via r.entity in the SAME feature; unknown entities and
783
- // apply-key collisions fail at registry build.
784
- extendEntityProjection(entityName: string, extension: EntityProjectionExtension): void;
785
-
786
- // Register a function that contributes claims into SessionUser.claims at
787
- // login time. Multiple features (and multiple calls within one feature)
788
- // are allowed; returns are merged. Keys are auto-prefixed with the feature
789
- // name ("<feature>:<key>") — cross-feature collisions are impossible by
790
- // construction. Same-feature duplicate keys follow last-wins.
791
- //
792
- // Hooks run in parallel. If one throws, the error is logged and that
793
- // feature's claims are simply missing from the merged record — login
794
- // still succeeds. This is a deliberate best-effort policy: identity-facts
795
- // are convenience, not access-gates (that's what `roles` + field-access
796
- // rules are for).
797
- authClaims(fn: AuthClaimsFn): void;
798
-
799
- // Declare a claim key. Qualified name follows "<feature>:<shortName>" —
800
- // NO kebab conversion (it would break the claim round-trip, unlike
801
- // r.secret / r.config). Returns a
802
- // typed handle so feature code can pass it to `readClaim(user, handle)`
803
- // without retyping the qualified string and with the right narrowed
804
- // return type.
805
- //
806
- // Declaring claim keys also turns on a runtime check: when the feature's
807
- // r.authClaims hooks return an inner-key not in the declared list, the
808
- // resolver logs a warning (the claim still lands in the JWT — declared
809
- // or not — so strict-mode isn't on; this is typo-drift protection).
810
- claimKey<T extends ClaimKeyType>(
811
- shortName: string,
812
- options: { readonly type: T },
813
- ): ClaimKeyHandle<T>;
814
- claimKey<T extends ClaimKeyType>(definition: {
815
- readonly name: string;
816
- readonly type: T;
817
- }): ClaimKeyHandle<T>;
818
-
819
- // Register a screen. The id is the feature-local short name (kebab-case);
820
- // the registry qualifies to "<feature>:screen:<id>". Boot-validation checks
821
- // that entity-bound screens reference a registered entity and that the
822
- // columns / form-field refs name real fields — cross-feature component-QN
823
- // validation (r.uiComponent) comes in M4/M5. Optional `nav` field is
824
- // sugar for a single nav entry pointing at this screen — equivalent to
825
- // a standalone r.nav({ id: <same id>, screen: "<feature>:screen:<id>", ... }).
826
- screen(definition: ScreenDefinition): void;
827
-
828
- // Register a nav entry. The id is the feature-local short name (kebab-case);
829
- // the registry qualifies to "<feature>:nav:<id>". Boot-validation checks
830
- // that `screen` and `parent` refs exist (cross-feature QNs allowed) and
831
- // that parent chains don't contain cycles.
832
- nav(definition: NavDefinition): void;
833
-
834
- // Register a content collection — a set of template-resources of one kind,
835
- // navigable where it fachlich belongs (mail templates under Mail, not under
836
- // a central "Content" section). Sugar over r.nav(): registers the nav entry
837
- // with `provider: true` under the same id and records the kind so the client
838
- // can wire the tree provider without repeating navId + kind.
839
- //
840
- // Returns the qualified nav name ("<feature>:nav:<id>") — apps that pass the
841
- // collection to a client feature explicitly take it from here instead of
842
- // re-typing the QN.
843
- contentCollection(definition: ContentCollectionDefinition): string;
844
-
845
- // Register a workspace — a persona-/role-scoped UI surface. Pure UI
846
- // composition; the registry qualifies the short id to
847
- // "<feature>:workspace:<id>". Boot-validation checks that any nav refs
848
- // exist, that workspace ids referenced from r.nav() are real, and that
849
- // at most one workspace per app declares `default: true`.
850
- workspace(definition: WorkspaceDefinition): void;
851
-
852
- // Register an HTTP-route owned by this feature. The route is mounted
853
- // outside the dispatcher pipeline (= outside /api/write|query|batch),
854
- // directly on the app — use case: RSS/Atom feeds, OG images, OpenAPI specs.
855
- // Duplicate "method path"-Combinations are rejected per feature at setup
856
- // time; there is no cross-feature check.
857
- // Symmetric to queryHandler/writeHandler — routes live with the feature,
858
- // not in the bootstrap. Escape-hatch for non-feature-bound routes stays
859
- // runProdApp.extraRoutes (declarative list with `entry` tier).
860
- httpRoute(definition: HttpRouteDefinition): void;
861
-
862
- // Declare an "unmanaged" framework-native table that bypasses the
863
- // event-sourcing system. Reserved for legacy-import, read-only caches,
864
- // write-only webhook payload buffers, or read-side projections of
865
- // event-streams (delivery-attempts, job-run-logs) where r.entity()'s
866
- // aggregate-lifecycle assumptions don't fit. The dev-server iterates
867
- // these alongside r.entity() projections at boot so the table exists
868
- // before the first query.
869
- //
870
- // EntityTableMeta carries the same column-shape that r.entity() builds,
871
- // minus the audit-trail + base-columns scaffolding. The `meta` argument
872
- // is the result of `defineUnmanagedTable(...)` / `deriveEntityTableMeta(...)`
873
- // from `@cosmicdrift/kumiko-framework/db`.
874
- //
875
- // The required `reason` string is the marker that justifies the bypass —
876
- // a non-empty string is the contract. If you can't write a reason,
877
- // declare data via `r.entity()` instead.
878
- storeTable(meta: EntityTableMeta, options: StoreTableOptions): void;
879
-
880
- // Register the tree-actions schema for this feature — a map of
881
- // action-name → action-definition (with optional typed args). At-most-
882
- // one call per feature.
883
- //
884
- // Returns a TreeActionsHandle that the feature exports via setup-return
885
- // (Memory `[EventDef-Exports-Pattern]`). The handle carries the
886
- // literal-typed action-map that `buildTarget` consumes for compile-
887
- // time validation:
888
- //
889
- // const handle = r.treeActions({
890
- // edit: { args: { slug: "" as string } },
891
- // list: {},
892
- // });
893
- // return { handle };
894
- //
895
- // Without this typed return, the action-map collapses to
896
- // `Record<string, TreeActionDef>` at the buildTarget call-site and
897
- // every action becomes accept-anything-string. See visual-tree.md A5.
898
- //
899
- // The runtime FeatureDefinition.treeActions slot stores the same map
900
- // as erased Record (registry lookup, Pattern-AST consumers).
901
- treeActions<const TActions extends Record<string, TreeActionDef>>(
902
- actions: TActions,
903
- ): TreeActionsHandle<TFeature, TActions>;
904
-
905
- // Declare the Zod-schema for env-vars this feature reads at runtime.
906
- // At-most-one call per feature. composeEnvSchema reads it across all
907
- // features to build one app-wide schema, which runProdApp parses
908
- // process.env against at boot. App-Authors can also call
909
- // `KUMIKO_DRY_RUN_ENV=human|json|pulumi|k8s` to introspect the
910
- // required env-vars without booting.
911
- //
912
- // Convention: keys are SHOUTING_SNAKE_CASE env-var names. Per-var
913
- // metadata (Pulumi-config-key override, openssl-generator suggestion,
914
- // k8s-secret hints) goes into `.meta({ kumiko: { pulumi: {...} } })`
915
- // — see framework/env/index.ts for the meta-shape.
916
- envSchema(schema: z.ZodObject<z.ZodRawShape>): void;
917
- };
918
-
919
- // --- Registry (created from features) ---
920
-
921
- export type Registry = {
922
- readonly features: ReadonlyMap<string, FeatureDefinition>;
923
-
924
- getFeature(name: string): FeatureDefinition | undefined;
925
- getEntity(name: string): EntityDefinition | undefined;
926
- getAllEntities(): ReadonlyMap<string, EntityDefinition>;
927
- getWriteHandler(name: string): WriteHandlerDef | undefined;
928
- getQueryHandler(name: string): QueryHandlerDef | undefined;
929
- getAllQueryHandlers(): ReadonlyMap<string, QueryHandlerDef>;
930
- getAllWriteHandlers(): ReadonlyMap<string, WriteHandlerDef>;
931
- getStreamHandler(name: string): StreamHandlerDef | undefined;
932
- getAllStreamHandlers(): ReadonlyMap<string, StreamHandlerDef>;
933
- getSearchableFields(entityName: string): readonly string[];
934
- getSortableFields(entityName: string): readonly string[];
935
- getRelations(entityName: string): EntityRelations;
936
- getSearchableReferences(entityName: string): ReadonlyArray<{
937
- fieldName: string;
938
- targetEntityName: string;
939
- labelField: string;
940
- }>;
941
- getSortableReferences(entityName: string): ReadonlyArray<{
942
- fieldName: string;
943
- targetEntityName: string;
944
- labelField: string;
945
- }>;
946
- getIncomingRelations(entityName: string): ReadonlyArray<{
947
- sourceEntity: string;
948
- relationName: string;
949
- relation: RelationDefinition;
950
- }>;
951
- // Hook getters — pass `effectiveFeatures` to drop hooks registered by
952
- // globally-disabled features. Omit the arg to get all hooks (legacy
953
- // callers + places where the feature-toggles feature isn't wired).
954
- getPreSaveHooks(name: string, effectiveFeatures?: ReadonlySet<string>): readonly PreSaveHookFn[];
955
- getPostSaveHooks(
956
- name: string,
957
- phase?: HookPhase,
958
- effectiveFeatures?: ReadonlySet<string>,
959
- ): readonly PostSaveHookFn[];
960
- getPreDeleteHooks(
961
- name: string,
962
- phase?: HookPhase,
963
- effectiveFeatures?: ReadonlySet<string>,
964
- ): readonly PreDeleteHookFn[];
965
- getPostDeleteHooks(
966
- name: string,
967
- phase?: HookPhase,
968
- effectiveFeatures?: ReadonlySet<string>,
969
- ): readonly PostDeleteHookFn[];
970
- getPreQueryHooks(
971
- name: string,
972
- effectiveFeatures?: ReadonlySet<string>,
973
- ): readonly PreQueryHookFn[];
974
- getPostQueryHooks(
975
- name: string,
976
- effectiveFeatures?: ReadonlySet<string>,
977
- ): readonly PostQueryHookFn[];
978
- getEntityPostSaveHooks(
979
- entityName: string,
980
- phase?: HookPhase,
981
- effectiveFeatures?: ReadonlySet<string>,
982
- ): readonly PostSaveHookFn[];
983
- getEntityPreDeleteHooks(
984
- entityName: string,
985
- phase?: HookPhase,
986
- effectiveFeatures?: ReadonlySet<string>,
987
- ): readonly PreDeleteHookFn[];
988
- getEntityPostDeleteHooks(
989
- entityName: string,
990
- phase?: HookPhase,
991
- effectiveFeatures?: ReadonlySet<string>,
992
- ): readonly PostDeleteHookFn[];
993
- getEntityPostQueryHooks(
994
- entityName: string,
995
- effectiveFeatures?: ReadonlySet<string>,
996
- ): readonly PostQueryHookFn[];
997
- // F3 — contributors for an entity's search-doc-payload, fired during
998
- // buildSearchDocument indexing. See `SearchPayloadContributorFn`.
999
- // `effectiveFeatures` filters out contributors owned by feature-toggle-
1000
- // disabled features (parallel to other getters' filtering semantic).
1001
- getSearchPayloadExtensions(
1002
- entityName: string,
1003
- effectiveFeatures?: ReadonlySet<string>,
1004
- ): readonly SearchPayloadContributorFn[];
1005
- getHandlerEntity(qualifiedHandler: string): string | undefined;
1006
- isHandlerSystemScoped(qualifiedHandler: string): boolean;
1007
- // Job counterpart to isHandlerSystemScoped — a job's owning feature is
1008
- // tracked separately (jobFeatureMap) since jobs aren't write/query/stream
1009
- // handlers and don't populate handlerFeatureMap.
1010
- isJobSystemScoped(qualifiedJobName: string): boolean;
1011
- getHandlerFeature(qualifiedHandler: string): string | undefined;
1012
- // True iff at least one registered handler declares a `rateLimit`
1013
- // option. Pre-computed at registry-build so the boot path can skip
1014
- // wiring the RateLimitResolver (and its Lua-script registration on
1015
- // Redis) entirely when nobody opted in. Per-request cost stays zero
1016
- // for apps that don't use the feature.
1017
- hasRateLimitedHandler(): boolean;
1018
- // All metrics from all features, keyed by fully-qualified name
1019
- // (kumiko_<feature>_<shortName>). Consumed at boot to register them on the
1020
- // active Meter.
1021
- getAllMetrics(): ReadonlyMap<string, FeatureMetricDef & { readonly featureName: string }>;
1022
- getAllTranslations(): TranslationKeys;
1023
- getConfigKey(qualifiedKey: string): ConfigKeyDefinition | undefined;
1024
- getAllConfigKeys(): ReadonlyMap<string, ConfigKeyDefinition>;
1025
- getAllConfigSeeds(): readonly ConfigSeedDef[];
1026
- // Feature-declared secrets, aggregated across all registered features.
1027
- // Keyed by qualified name ("<feature>:<shortName>"). Used by the rotation
1028
- // job (to iterate "known" secrets) and admin-UIs to list available keys.
1029
- getAllSecretKeys(): ReadonlyMap<string, SecretKeyDefinition>;
1030
- getSecretKey(qualifiedName: string): SecretKeyDefinition | undefined;
1031
- getJob(qualifiedName: string): JobDefinition | undefined;
1032
- getAllJobs(): ReadonlyMap<string, JobDefinition>;
1033
- getEvent(qualifiedName: string): EventDef | undefined;
1034
-
1035
- // Upcaster chain per qualified event name. Entries describe the current
1036
- // schema version and the step-wise transforms that upgrade older stored
1037
- // payloads. Empty chain when an event has never been migrated (version=1).
1038
- getEventUpcasters(): ReadonlyMap<
1039
- string,
1040
- { readonly currentVersion: number; readonly chain: ReadonlyMap<number, EventUpcastFn> }
1041
- >;
1042
- getExtension(name: string): RegistrarExtensionDef | undefined;
1043
- getExtensionUsages(extensionName: string): readonly RegistrarExtensionRegistration[];
1044
- // Extension point → selector config key, from r.extensionSelector calls.
1045
- getAllExtensionSelectors(): ReadonlyMap<string, string>;
1046
- getAllNotifications(): ReadonlyMap<string, NotificationDefinition>;
1047
- getAllReferenceData(): readonly ReferenceDataDef[];
1048
- // Look up projections by source-entity name. Empty list when no projection
1049
- // feeds off the entity — event-store-executor uses this as the hot-path.
1050
- getProjectionsForSource(entityName: string): readonly ProjectionDefinition[];
1051
- getAllProjections(): ReadonlyMap<string, ProjectionDefinition>;
1052
-
1053
- // All r.storeTable() registrations across all features, keyed by
1054
- // feature-local short name. The dev-server iterates this alongside
1055
- // implicit projections at boot. Cross-feature uniqueness is enforced
1056
- // at registry-build — duplicate names from different features fail
1057
- // the boot, so callers can rely on a flat keyspace.
1058
- getAllStoreTables(): ReadonlyMap<string, StoreTableDef>;
1059
-
1060
- // Multi-stream projections registered via r.multiStreamProjection().
1061
- // Keyed by qualified name. The server wires each into the event-dispatcher
1062
- // as its own EventConsumer with a dedicated cursor.
1063
- getAllMultiStreamProjections(): ReadonlyMap<string, MultiStreamProjectionDefinition>;
1064
- // The feature that registered the given MSP. Used by the event-dispatcher
1065
- // to pause MSP-consumers whose owning feature is globally disabled.
1066
- getMultiStreamProjectionFeature(qualifiedName: string): string | undefined;
1067
-
1068
- // All r.authClaims() hooks across all features, tagged with the declaring
1069
- // feature name so the resolver can apply the auto-prefix. Pre-aggregated
1070
- // at registry-build so the login hot path is a single Map read.
1071
- getAuthClaimsHooks(): readonly AuthClaimsHookDef[];
1072
-
1073
- // Feature-declared claim keys, aggregated across all features. Keyed by
1074
- // qualified name ("<feature>:<short>"). Ops-UI + Boot-Validator use this
1075
- // to introspect what claims the app can produce.
1076
- getAllClaimKeys(): ReadonlyMap<string, ClaimKeyDefinition>;
1077
- getClaimKey(qualifiedName: string): ClaimKeyDefinition | undefined;
1078
-
1079
- // Screens declared via r.screen() across all features. Keyed by qualified
1080
- // name ("<feature>:screen:<id>"). ui-core / renderer consume this to build
1081
- // navigation + screen-tree at mount time.
1082
- getAllScreens(): ReadonlyMap<string, ScreenDefinition>;
1083
- getScreen(qualifiedName: string): ScreenDefinition | undefined;
1084
- // The feature that registered the given screen. Consumed by the nav
1085
- // resolver to gate a nav-entry whose screen belongs to a disabled feature.
1086
- getScreenFeature(qualifiedName: string): string | undefined;
1087
- // All entity-bound screens (entityList / entityEdit) that target the given
1088
- // entity. Pre-grouped so ui-core's view-model builders don't re-filter
1089
- // getAllScreens() on every render. Custom screens have no entity and are
1090
- // never returned here — walk getAllScreens() for those.
1091
- getScreensByEntity(entityName: string): readonly ScreenDefinition[];
1092
-
1093
- // Nav entries declared via r.nav() across all features. Keyed by qualified
1094
- // name ("<feature>:nav:<id>"). Flat list — the renderer's resolveNavigation
1095
- // assembles the tree from parent refs and gates by effective-features.
1096
- getAllNavs(): ReadonlyMap<string, NavDefinition>;
1097
- getNav(qualifiedName: string): NavDefinition | undefined;
1098
- // The feature that registered the given nav entry. Used by the nav
1099
- // resolver to drop entries whose owning feature is globally disabled.
1100
- getNavFeature(qualifiedName: string): string | undefined;
1101
- // Direct children of the given parent nav entry. Empty array when the
1102
- // parent has no children. Pre-grouped for O(1) tree-walk — resolveNavigation
1103
- // recurses with getNavsByParent(child.qn) instead of filtering getAllNavs().
1104
- getNavsByParent(parentQualifiedName: string): readonly NavDefinition[];
1105
- // Nav entries that declare no parent — the roots of the navigation tree.
1106
- // resolveNavigation starts its walk here and descends via getNavsByParent.
1107
- getTopLevelNavs(): readonly NavDefinition[];
1108
-
1109
- // Workspaces declared via r.workspace() across all features. Keyed by
1110
- // qualified name ("<feature>:workspace:<id>"). The active web shell
1111
- // (shellWorkspaces) consumes this to render the switcher.
1112
- getAllWorkspaces(): ReadonlyMap<string, WorkspaceDefinition>;
1113
- getWorkspace(qualifiedName: string): WorkspaceDefinition | undefined;
1114
- // The feature that registered the workspace. Mirrors getNavFeature —
1115
- // lets the resolver drop workspaces whose owning feature is disabled.
1116
- getWorkspaceFeature(qualifiedName: string): string | undefined;
1117
- // Resolved nav QNs that belong to the given workspace. Pre-computed at
1118
- // boot from BOTH r.workspace.nav AND r.nav.workspaces — the shell
1119
- // doesn't have to merge sources at render time.
1120
- getWorkspaceNavs(workspaceQualifiedName: string): readonly string[];
1121
- // The single workspace whose `default: true` is set, if any. Boot
1122
- // validator rejects more than one. Apps without a default fall back to
1123
- // the first workspace the user has access to.
1124
- getDefaultWorkspace(): WorkspaceDefinition | undefined;
1125
-
1126
- // Tree-Actions-Map des Features. Returns the erased Record (compile-
1127
- // time-typed handle wandert über setup-export, nicht hier). Die
1128
- // Content-Tree-Nav nutzt das für Runtime-Action-Lookup beim Klick auf
1129
- // einen TreeNode.target — der Resolver findet das Feature via
1130
- // TargetRef.featureId und holt sich die zugehörige Action-Definition.
1131
- getTreeActions(featureName: string): Readonly<Record<string, TreeActionDef>> | undefined;
1132
- };