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