@cosmicdrift/kumiko-framework 0.159.1 → 0.161.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 (90) 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/auth-middleware.ts +17 -44
  11. package/src/api/auth-routes.ts +6 -2
  12. package/src/api/index.ts +1 -0
  13. package/src/api/routes.ts +57 -0
  14. package/src/api/server.ts +5 -4
  15. package/src/bun-db/query.ts +12 -25
  16. package/src/crypto/kms-adapter.ts +2 -118
  17. package/src/db/__tests__/build-filter-where.test.ts +34 -0
  18. package/src/db/__tests__/event-store-executor-write-verbs.integration.test.ts +91 -0
  19. package/src/db/cursor.ts +1 -18
  20. package/src/db/dialect.ts +8 -19
  21. package/src/db/entity-table-meta-types.ts +2 -92
  22. package/src/db/event-store-executor.ts +4 -96
  23. package/src/db/table-builder.ts +2 -19
  24. package/src/db/tenant-db.ts +6 -55
  25. package/src/engine/__tests__/boot-validator.test.ts +46 -0
  26. package/src/engine/__tests__/codemod-pipeline.test.ts +139 -10
  27. package/src/engine/__tests__/engine.test.ts +28 -0
  28. package/src/engine/__tests__/registry-facade-sweep.test.ts +80 -0
  29. package/src/engine/__tests__/registry.test.ts +40 -0
  30. package/src/engine/__tests__/tier-resolver-extension.test.ts +19 -1
  31. package/src/engine/boot-validator/entity-handler.ts +10 -1
  32. package/src/engine/define-feature.ts +1 -0
  33. package/src/engine/define-handler.ts +1 -0
  34. package/src/engine/feature-ast/__tests__/canonical-form.test.ts +11 -1
  35. package/src/engine/feature-ast/__tests__/parse.test.ts +983 -3
  36. package/src/engine/feature-ast/__tests__/patch.test.ts +168 -0
  37. package/src/engine/feature-ast/__tests__/patcher.test.ts +7 -0
  38. package/src/engine/feature-ast/__tests__/render-roundtrip.test.ts +9 -0
  39. package/src/engine/feature-ast/extractors/handlers.ts +19 -2
  40. package/src/engine/feature-ast/extractors/index.ts +1 -0
  41. package/src/engine/feature-ast/index.ts +2 -0
  42. package/src/engine/feature-ast/parse.ts +3 -0
  43. package/src/engine/feature-ast/patch.ts +2 -0
  44. package/src/engine/feature-ast/patcher.ts +21 -0
  45. package/src/engine/feature-ast/patterns.ts +16 -0
  46. package/src/engine/feature-ast/render.ts +15 -0
  47. package/src/engine/feature-builder-state.ts +3 -0
  48. package/src/engine/feature-entity-handlers.ts +35 -1
  49. package/src/engine/index.ts +3 -0
  50. package/src/engine/pattern-library/__tests__/library.test.ts +9 -0
  51. package/src/engine/pattern-library/library.ts +2 -0
  52. package/src/engine/pattern-library/mixed-schemas.ts +37 -0
  53. package/src/engine/registry-facade.ts +9 -0
  54. package/src/engine/registry-ingest.ts +10 -0
  55. package/src/engine/registry-state.ts +3 -0
  56. package/src/engine/types/config.ts +2 -497
  57. package/src/engine/types/define-handler.ts +2 -94
  58. package/src/engine/types/entity-handlers.ts +2 -30
  59. package/src/engine/types/feature.ts +2 -1021
  60. package/src/engine/types/fields.ts +2 -685
  61. package/src/engine/types/handlers.ts +2 -820
  62. package/src/engine/types/hooks.ts +2 -170
  63. package/src/engine/types/index.ts +44 -36
  64. package/src/engine/types/nav.ts +2 -67
  65. package/src/engine/types/ownership.ts +2 -83
  66. package/src/engine/types/projection.ts +2 -165
  67. package/src/engine/types/screen.ts +2 -747
  68. package/src/engine/types/step.ts +2 -334
  69. package/src/engine/types/workspace.ts +2 -42
  70. package/src/errors/write-error-info.ts +6 -22
  71. package/src/event-store/errors.ts +2 -35
  72. package/src/event-store/event-store.ts +2 -21
  73. package/src/event-store/snapshot.ts +11 -35
  74. package/src/event-store/types.ts +2 -22
  75. package/src/files/provider-resolver.ts +3 -5
  76. package/src/files/types.ts +5 -54
  77. package/src/jobs/__tests__/jobs.integration.test.ts +102 -1
  78. package/src/pipeline/__tests__/dispatcher.test.ts +96 -0
  79. package/src/pipeline/__tests__/lifecycle-pipeline.test.ts +208 -0
  80. package/src/pipeline/dispatch-shared.ts +39 -1
  81. package/src/pipeline/dispatch-stream.ts +74 -0
  82. package/src/pipeline/dispatcher-utils.ts +1 -1
  83. package/src/pipeline/dispatcher.ts +7 -0
  84. package/src/pipeline/multi-stream-apply-context.ts +4 -42
  85. package/src/rate-limit/resolver.ts +10 -30
  86. package/src/secrets/envelope-cipher.ts +4 -6
  87. package/src/secrets/types.ts +2 -177
  88. package/src/stack/request-helper.ts +19 -2
  89. package/src/stack/test-stack.ts +33 -14
  90. package/src/time/tz-context.ts +9 -56
@@ -1,334 +1,2 @@
1
- // Step-Vocabulary Typessee docs/plans/architecture/intern/step-vocabulary.md
2
- //
3
- // M.1 minimal scope:
4
- // - Steps execute against the existing HandlerContext (no per-step subset).
5
- // - steps-accumulator is Record<string, unknown> (no tuple-reduce typing).
6
- // - Resolvers receive the full PipelineCtx as one argument.
7
- //
8
- // Strict typing on appendEvent inside steps is deferred to a later pass
9
- // (see TS-typing notes in the design doc). M.1 uses unsafeAppendEvent
10
- // semantics under the hood for r.step.aggregate.appendEvent.
11
-
12
- import type { EventStoreExecutor } from "../../db/event-store-executor";
13
- import type { WhereObject } from "../../db/query";
14
- import type { KumikoEventTypeMap } from "./event-type-map";
15
- import type { HandlerContext, WriteEvent, WriteResult } from "./handlers";
16
- import type { SaveContext } from "./hooks";
17
- import type { EntityId } from "./identifiers";
18
-
19
- /**
20
- * The kind discriminator for a step instance — matches the step's
21
- * registration name in the step-registry (e.g. "return", "compute",
22
- * "aggregate.create"). Steps register themselves at module-load time
23
- * via defineStep().
24
- */
25
- export type StepKind = string;
26
-
27
- /**
28
- * Pipeline-side context handed to step argument resolvers.
29
- *
30
- * Contains the full HandlerContext (no per-step subset in M.1) plus
31
- * the accumulated `steps` map of prior step results, and a `scope`
32
- * record for forEach/branch-local bindings.
33
- *
34
- * `scope` is `Record<string, unknown>` — sub-step builders (forEach,
35
- * branch) populate it once they land in later M.1 slices. M.1.1 ships
36
- * with `r.step.return` only, which reads `event` and ignores both
37
- * `steps` and `scope`.
38
- */
39
- export type PipelineCtx<
40
- TPayload = unknown,
41
- TMap extends object = KumikoEventTypeMap,
42
- > = HandlerContext<TMap> & {
43
- readonly event: WriteEvent<TPayload>;
44
- readonly steps: Readonly<Record<string, unknown>>;
45
- readonly scope: Readonly<Record<string, unknown>>;
46
- // Workflow-run context — present only when running inside defineWorkflow.
47
- // Tier-3 steps use this to write suspension events onto the correct
48
- // aggregate stream and for the Resume-Loop to re-hydrate state.
49
- readonly workflow?: {
50
- readonly runId: string;
51
- readonly workflowName: string;
52
- /** Current step index in the pipeline — set by the executor before each step. */
53
- readonly stepIndex: number;
54
- /**
55
- * Retry attempt counter for the current workflow.retry step.
56
- * Set by the workflow-engine resume-loop on re-entry; starts at 1.
57
- * Absent (undefined) means first attempt.
58
- */
59
- readonly retryAttempt?: number;
60
- /**
61
- * Q7 Snapshot-at-Start fingerprint of the workflow definition that
62
- * started this run. Propagated into every suspension event payload so
63
- * the resume-loop can detect library-upgrades that changed the closure
64
- * source and surface them as a typed failure instead of running a
65
- * stale-vs-new mix of steps. Optional only for legacy callers; the
66
- * workflow-runner sets it on every newly-started run.
67
- */
68
- readonly definitionFingerprint?: string;
69
- };
70
- };
71
-
72
- /**
73
- * A resolver is either a static value or a function that derives the
74
- * value from the pipeline-context. M.1 keeps the resolver signature
75
- * uniform — every step accepts both forms via a normalise helper.
76
- */
77
- export type StepResolver<T, TPayload = unknown> = T | ((ctx: PipelineCtx<TPayload>) => T);
78
-
79
- /**
80
- * Per-step error strategy. M.1.1 only supports "throw" — the type is
81
- * deliberately narrowed so callers cannot pass an unsupported strategy
82
- * past the type-checker. The doc lists "return" / "skip" / fallback as
83
- * future strategies; each lands together with its own runtime support
84
- * + integration test in a later slice (no untested type expansion).
85
- */
86
- export type StepFailureStrategy = "throw";
87
-
88
- export type StepDef<TArgs = unknown, TResult = unknown> = {
89
- readonly kind: StepKind;
90
- readonly defaultFailureStrategy: StepFailureStrategy;
91
- // Returns the result-key for this step instance, or undefined when the
92
- // step doesn't surface a result. The first-position name on the call
93
- // (e.g. r.step.compute("startedAt", fn) → "startedAt") becomes the key.
94
- readonly resultKey?: (args: TArgs) => string | undefined;
95
- // Sub-pipeline arg-paths — names of `args.<path>` entries that hold a
96
- // readonly StepInstance[] (e.g. branch's `["onTrue", "onFalse"]`, forEach's
97
- // `["do"]`). The boot-validator reads these at registration time so it
98
- // can recurse into nested pipelines without a hardcoded kind-list. Steps
99
- // that don't carry sub-pipelines omit the field. Followup #15 self-
100
- // registration: prevents future sub-step-builders from silently bypassing
101
- // the unsafeProjection allowlist by forgetting to update a central map.
102
- readonly subPaths?: readonly string[];
103
- // Step-vocabulary tier (Q9). Tier-1 implicit, Tier-2+ requires
104
- // r.requires.step("<kind>") in the owning feature. Default 1 (implicit).
105
- // Tier-3 is only available inside defineWorkflow.
106
- readonly tier?: 1 | 2 | 3;
107
- // Runtime: resolve the args against the ctx, perform the work, return
108
- // the value to land in steps.{resultKey}. Thrown errors propagate to
109
- // the dispatcher's catch (M.1.1 supports "throw"-strategy only).
110
- readonly run: (args: TArgs, ctx: PipelineCtx) => Promise<TResult> | TResult;
111
- };
112
-
113
- /**
114
- * An instance of a step in a pipeline — what users build via the
115
- * step-builder (`r.step.compute(...)`). Carries the kind + resolved-or-
116
- * resolver args + the user-chosen onFailure override.
117
- *
118
- * `args` is `unknown` at this layer — the registered StepDef knows the
119
- * concrete shape and casts at run() time. Cross-step type-safety lives
120
- * in the per-step builder factories, not in this central type.
121
- */
122
- export type StepInstance = {
123
- readonly kind: StepKind;
124
- readonly args: unknown;
125
- readonly onFailure?: StepFailureStrategy;
126
- };
127
-
128
- /**
129
- * What `stepsPipeline(closure)` returns. Carries the closure (instead of an
130
- * eagerly-built array) so each handler-call sees a fresh event ref and
131
- * the `r` step-builder is resolved at runtime, not at module-load time.
132
- *
133
- * `__kind: "pipeline"` lets defineWriteHandler distinguish a pipeline-
134
- * form `perform` from accidental other shapes.
135
- *
136
- * `_TData` is a phantom type-parameter — held in constraint position
137
- * only, never referenced in the type body. defineWriteHandler binds it
138
- * via `def.perform: PipelineDef<…, TData>` (the call-site uses TData
139
- * without underscore — phantom-prefix is purely a Biome
140
- * `noUnusedVariables` marker, not user-facing). _TData is NOT inferred
141
- * from the closure body (r.step.return has its own per-call TData), so
142
- * callers must spell it explicitly:
143
- * `stepsPipeline<{ greeting: string }, { echoed: string }>(...)`
144
- * Better DX is a known follow-up — see step-vocabulary.md M.1-Followups.
145
- */
146
- export type PipelineDef<TPayload = unknown, _TData = unknown> = {
147
- readonly __kind: "pipeline";
148
- readonly build: (ctx: PipelineBuildCtx<TPayload>) => readonly StepInstance[];
149
- };
150
-
151
- /**
152
- * Argument bundle passed to the closure inside `stepsPipeline(closure)`.
153
- * Build-time only — no `steps`, no `scope`, no `db`: at build time no
154
- * step has run yet.
155
- *
156
- * The closure is invoked ONCE per handler-call and returns the immutable
157
- * list of step instances. Values inside the closure that depend on prior
158
- * step results MUST go through resolvers (functions) — those receive the
159
- * resolver-side PipelineCtx which carries `steps` + `scope`.
160
- *
161
- * **Closure-body contract:** the closure must produce a deterministic
162
- * step-list that doesn't depend on `event.payload` — branching on payload
163
- * fields belongs inside resolvers (where they fire per-call), not in the
164
- * outer closure body. Boot-validation runs the closure once with a dummy
165
- * empty payload to scan unsafeProjection-* step targets; a closure that
166
- * conditionally builds different step-lists per payload would silently
167
- * skip validation. See validate-projection-allowlist.ts for the
168
- * boot-side mechanics.
169
- */
170
- export type PipelineBuildCtx<TPayload = unknown> = {
171
- readonly event: WriteEvent<TPayload>;
172
- readonly r: StepBuilder;
173
- };
174
-
175
- /**
176
- * Step-builder namespace handed to the pipeline closure. The fields
177
- * grow as M.1 adds more steps. Each is a thin factory that returns a
178
- * StepInstance — the runtime resolution happens later in run().
179
- *
180
- * Why nested under `step`: matches the doc-API surface and leaves room
181
- * for future sibling namespaces (`r.trigger`, `r.transform`) without
182
- * crowding the top-level r.
183
- */
184
- export type StepBuilder = {
185
- readonly step: StepNamespace;
186
- };
187
-
188
- /**
189
- * The collection of step factory functions. Grown incrementally —
190
- * landed: return (M.1.1), compute (M.1.2), unsafeProjectionUpsert
191
- * (M.1.3), aggregate.create (M.1.4). Pending: branch, forEach,
192
- * read.*, aggregate.update, aggregate.appendEvent,
193
- * unsafeProjectionDelete.
194
- */
195
- export type StepNamespace = {
196
- readonly return: <TData>(resolver: StepResolver<WriteResult<TData>>) => StepInstance;
197
- readonly compute: <TResult>(name: string, fn: (ctx: PipelineCtx) => TResult) => StepInstance;
198
- // Inline read-side projection write. Boot-validation enforces the
199
- // table is in the owning feature's r.requires.projection allowlist
200
- // and NOT registered as an aggregate-table via r.entity. See
201
- // step-vocabulary.md "Was unsafeProjection.* überspringt".
202
- readonly unsafeProjectionUpsert: (args: {
203
- readonly table: unknown;
204
- readonly on: readonly string[];
205
- readonly row: StepResolver<Record<string, unknown>>;
206
- }) => StepInstance;
207
- // Sibling: delete row(s) from a read-side projection table. Same
208
- // boot-validation contract as unsafeProjectionUpsert.
209
- readonly unsafeProjectionDelete: (args: {
210
- readonly table: unknown;
211
- readonly where: StepResolver<WhereObject>;
212
- }) => StepInstance;
213
- // Read sub-namespace — thin wrapper on selectMany/fetchOne (bun-db).
214
- // Caller-owned tenant-filter (does NOT auto-inject like ctx.queryProjection does).
215
- readonly read: {
216
- readonly findOne: (
217
- name: string,
218
- opts: {
219
- readonly table: unknown;
220
- readonly where: StepResolver<WhereObject | undefined>;
221
- },
222
- ) => StepInstance;
223
- readonly findMany: (
224
- name: string,
225
- opts: {
226
- readonly table: unknown;
227
- readonly where?: StepResolver<WhereObject | undefined>;
228
- readonly limit?: number;
229
- },
230
- ) => StepInstance;
231
- };
232
- // Aggregate-mutation sub-namespace — wraps the existing event-store-
233
- // executor surface. Every method goes through the full ES pipeline
234
- // (events + projections + lifecycle hooks + audit). The default and
235
- // intended path for domain mutation; contrast with unsafeProjection.*.
236
- readonly aggregate: {
237
- readonly create: (
238
- name: string,
239
- opts: {
240
- readonly executor: EventStoreExecutor;
241
- readonly data: StepResolver<Record<string, unknown>>;
242
- },
243
- ) => StepInstance;
244
- readonly update: (
245
- name: string,
246
- opts: {
247
- readonly executor: EventStoreExecutor;
248
- readonly id: StepResolver<EntityId>;
249
- readonly changes: StepResolver<Record<string, unknown>>;
250
- readonly version?: StepResolver<number | undefined>;
251
- readonly skipOptimisticLock?: boolean;
252
- },
253
- ) => StepInstance;
254
- readonly appendEvent: (args: {
255
- readonly aggregateId: StepResolver<string>;
256
- readonly aggregateType: string;
257
- readonly type: string;
258
- readonly payload: StepResolver<unknown>;
259
- readonly headers?: StepResolver<Readonly<Record<string, string | number | boolean>>>;
260
- }) => StepInstance;
261
- };
262
- // Conditional sub-pipeline. `onTrue` (required) and `onFalse`
263
- // (optional) are static StepInstance arrays; `r` for sub-step builders
264
- // is captured from the outer pipeline closure. Naming-Q14: `onTrue`/
265
- // `onFalse` over `then`/`else` because Biome's noThenProperty lint
266
- // flags `then` as a thenable-trap. Q12: r.step.return inside
267
- // onTrue/onFalse is rejected at build time (would trigger
268
- // discriminated-union TData trap). Q13: no resultKey — branch is
269
- // side-effect-only.
270
- readonly branch: (args: {
271
- readonly if: StepResolver<boolean>;
272
- readonly onTrue: readonly StepInstance[];
273
- readonly onFalse?: readonly StepInstance[];
274
- }) => StepInstance;
275
- // Iterate a sub-pipeline over an array. `as` is required (Q15);
276
- // current item lands under `scope[as]` for resolvers in `do`.
277
- // Sequential only in M.1.6; concurrency is Followup #12.
278
- readonly forEach: <TItem = unknown>(args: {
279
- readonly over: StepResolver<readonly TItem[]>;
280
- readonly as: string;
281
- readonly do: readonly StepInstance[];
282
- readonly concurrency?: 1;
283
- }) => StepInstance;
284
- // Tier-2 namespace. Each builder requires r.requires.step("<kind>")
285
- // in the owning feature; boot-validation enforces.
286
- readonly webhook: {
287
- readonly send: (args: {
288
- readonly url: StepResolver<string>;
289
- readonly method?: "POST" | "PUT" | "PATCH";
290
- readonly headers?: StepResolver<Readonly<Record<string, string>>>;
291
- readonly body?: StepResolver<unknown>;
292
- readonly auth?:
293
- | { readonly kind: "bearer"; readonly secretRef: string }
294
- | { readonly kind: "header"; readonly name: string; readonly secretRef: string };
295
- readonly mode: "deferred";
296
- readonly retry?: { readonly times: number; readonly backoff: "exponential" | "linear" };
297
- }) => StepInstance;
298
- };
299
- readonly mail: {
300
- readonly send: (args: {
301
- readonly to: StepResolver<string | readonly string[]>;
302
- readonly subject: StepResolver<string>;
303
- readonly body: StepResolver<string>;
304
- readonly from?: StepResolver<string>;
305
- readonly mode: "deferred";
306
- }) => StepInstance;
307
- };
308
- readonly callFeature: (
309
- name: string,
310
- opts: {
311
- readonly handler: string;
312
- readonly payload: StepResolver<unknown>;
313
- readonly as?: import("./handlers").SessionUser;
314
- },
315
- ) => StepInstance;
316
- // --- Tier-3 / Workflow-only steps ---
317
- // Only available inside defineWorkflow ({ steps: stepsPipeline(...) }).
318
- // Runtime guard: throws when used inside sync defineWriteHandler.
319
- readonly wait: (args: { readonly for: StepResolver<string> }) => StepInstance;
320
- readonly waitForEvent: (args: {
321
- readonly event: string;
322
- readonly match?: StepResolver<(payload: unknown) => boolean>;
323
- readonly timeout: StepResolver<string>;
324
- }) => StepInstance;
325
- readonly retry: (args: {
326
- readonly times: number;
327
- readonly backoff: "exponential" | "linear";
328
- readonly do: readonly StepInstance[];
329
- }) => StepInstance;
330
- };
331
-
332
- // SaveContext is the result-type of aggregate.create / aggregate.update;
333
- // re-exported for step authors who want to type their resolver bindings.
334
- export type AggregateStepResult = SaveContext;
1
+ // Legacy pathre-exported for callers still importing this module directly.
2
+ export * from "@cosmicdrift/kumiko-types/step";
@@ -1,42 +1,2 @@
1
- import type { AccessRule } from "./handlers";
2
-
3
- // Workspace declaration. A workspace is a persona-/role-scoped UI surface:
4
- // pure UI composition with no backend, DB or auth impact. The engine stores
5
- // these verbatim and the active web shell (shellWorkspaces) renders the
6
- // switcher and filters the nav tree by membership + access.
7
- //
8
- // Membership is computed from two sources, merged at boot:
9
- // 1. r.workspace({ nav: [...] }) — explicit list of nav QNs
10
- // 2. r.nav({ workspaces: [...] }) — nav entry self-assigns to workspaces
11
- // A nav entry that appears in neither source belongs to no workspace and
12
- // only shows up when no workspace is active (legacy / non-workspace apps).
13
- //
14
- // Cross-feature references are allowed: `nav` may point at any registered
15
- // nav QN. The boot validator checks references exist and that workspace
16
- // IDs referenced from r.nav are real.
17
- export type WorkspaceDefinition = {
18
- // Feature author writes the short id ("disposition"); the registry
19
- // overwrites `id` with the qualified name ("bmc:workspace:disposition")
20
- // in its stored copy. Same pattern as NavDefinition / ScreenDefinition.
21
- readonly id: string;
22
- // i18n translation key. Resolved at render time by the renderer's
23
- // useTranslation hook; engine keeps it opaque.
24
- readonly label: string;
25
- // Icon key — whatever the icon registry of the active renderer understands.
26
- // Engine doesn't validate; unknown icons surface as a missing icon on
27
- // screen, not a boot failure (mirrors NavDefinition.icon).
28
- readonly icon?: string;
29
- // Sort weight in the workspace switcher (lower = earlier). Ties broken
30
- // by registration order — features registered later appear lower.
31
- readonly order?: number;
32
- // Role / openToAll gate. Only users matching this rule see the workspace
33
- // in their switcher. Mirrors NavDefinition.access — same semantics across
34
- // the UI surface, so a default-deny app can do `{ roles: [] }`.
35
- readonly access?: AccessRule;
36
- // Explicit nav QNs that belong to this workspace. Merged with any nav
37
- // entries that self-assign via r.nav({ workspaces: [...] }).
38
- readonly nav?: readonly string[];
39
- // Default workspace at login when the user has access to multiple. Boot
40
- // validator rejects more than one default per app.
41
- readonly default?: boolean;
42
- };
1
+ // Legacy path re-exported for callers still importing this module directly.
2
+ export * from "@cosmicdrift/kumiko-types/workspace";
@@ -1,30 +1,14 @@
1
+ import type {
2
+ WriteErrorInfo,
3
+ WriteFailure,
4
+ } from "@cosmicdrift/kumiko-types/write-error-info-types";
1
5
  import { NotFoundError, UnprocessableError } from "./classes";
2
6
  import { KumikoError } from "./kumiko-error";
3
7
  import { FrameworkReasons } from "./reasons";
4
8
  import { buildInvalidTransitionDetails } from "./transition-details";
5
9
 
6
- // Plain, JSON-serializable snapshot of a KumikoError for use on the write-path
7
- // (WriteResult.error, BatchResult.error). The dispatcher stores results under
8
- // an idempotency key — a KumikoError instance wouldn't round-trip through
9
- // JSON, so we keep structural data only and rebuild the instance on demand
10
- // via reraiseAsKumikoError when we need to throw upstream again.
11
- export type WriteErrorInfo = {
12
- readonly code: string;
13
- readonly httpStatus: number;
14
- readonly i18nKey: string;
15
- readonly i18nParams?: Readonly<Record<string, unknown>>;
16
- readonly message: string;
17
- readonly details?: unknown;
18
- };
19
-
20
- // The failure half of WriteResult — `{ isSuccess: false } + error`. Named
21
- // so the three write-failure factories below and WriteResult share one
22
- // shape instead of restating it. Not generic: the error carries zero data,
23
- // so there's nothing for the caller to narrow.
24
- export type WriteFailure = {
25
- readonly isSuccess: false;
26
- readonly error: WriteErrorInfo;
27
- };
10
+ // Legacy types re-exported for callers still importing this module directly.
11
+ export * from "@cosmicdrift/kumiko-types/write-error-info-types";
28
12
 
29
13
  // Convenience for call sites that return a failed WriteResult. Keeps the
30
14
  // pattern `return writeFailure(new NotFoundError(...))` compact so handlers
@@ -1,35 +1,2 @@
1
- // Failure modes of the event-store's append() path. Surfaced as typed
2
- // errors so the executor layer can map them to the framework's
3
- // WriteResult error contract (version_conflict).
4
-
5
- export class VersionConflictError extends Error {
6
- public readonly aggregateId: string;
7
- public readonly expectedVersion: number;
8
- constructor(aggregateId: string, expectedVersion: number) {
9
- super(
10
- `Version conflict on aggregate ${aggregateId}: expected predecessor version ${expectedVersion}`,
11
- );
12
- this.name = "VersionConflictError";
13
- this.aggregateId = aggregateId;
14
- this.expectedVersion = expectedVersion;
15
- }
16
- }
17
-
18
- // Thrown when ctx.appendEvent targets an archived stream. Archived aggregates
19
- // are read-only — restoreStream() makes them writable again. The archive
20
- // state is not carried on the events themselves; it lives on the sparse
21
- // kumiko_archived_streams table. Handlers that need to branch on archive
22
- // state should call ctx.isStreamArchived(id) first.
23
- export class ArchivedStreamError extends Error {
24
- public readonly tenantId: string;
25
- public readonly aggregateId: string;
26
- constructor(tenantId: string, aggregateId: string) {
27
- super(
28
- `Aggregate ${aggregateId} on tenant ${tenantId} is archived — appendEvent is blocked. ` +
29
- `Call restoreStream() to re-open the stream before writing.`,
30
- );
31
- this.name = "ArchivedStreamError";
32
- this.tenantId = tenantId;
33
- this.aggregateId = aggregateId;
34
- }
35
- }
1
+ // Legacy path re-exported for callers still importing this module directly.
2
+ export * from "@cosmicdrift/kumiko-types/event-store-errors";
@@ -1,3 +1,4 @@
1
+ import type { EventMetadata, StoredEvent } from "@cosmicdrift/kumiko-types/event-store-types";
1
2
  import { encryptEventPayloadPii } from "../crypto/event-pii";
2
3
  import type { DbRunner } from "../db";
3
4
  import { isUniqueViolation } from "../db/pg-error";
@@ -15,9 +16,8 @@ import { isStreamArchived } from "./archive";
15
16
  import { VersionConflictError } from "./errors";
16
17
  import { eventsTable } from "./events-schema";
17
18
  import { toStoredEvent } from "./row-to-stored-event";
18
- import type { EventMetadata } from "./types";
19
19
 
20
- export type { EventMetadata } from "./types";
20
+ export type { EventMetadata, StoredEvent } from "@cosmicdrift/kumiko-types/event-store-types";
21
21
 
22
22
  export type EventToAppend = {
23
23
  readonly aggregateId: string;
@@ -31,25 +31,6 @@ export type EventToAppend = {
31
31
  readonly metadata: EventMetadata;
32
32
  };
33
33
 
34
- // Generic über payload-shape. Default = Record<string, unknown> macht
35
- // alle existierenden Konsumenten backwards-compatible. Konkrete Apply-
36
- // Handler / Tests können `StoredEvent<MyEventPayload>` annotieren um
37
- // payload typed zu lesen. Type-Propagation kommt durch r.defineEvent +
38
- // SingleStreamApplyFn<T> in apply-Maps.
39
- export type StoredEvent<TPayload = Record<string, unknown>> = {
40
- readonly id: string;
41
- readonly aggregateId: string;
42
- readonly aggregateType: string;
43
- readonly tenantId: TenantId;
44
- readonly version: number;
45
- readonly type: string;
46
- readonly eventVersion: number;
47
- readonly payload: TPayload;
48
- readonly metadata: EventMetadata;
49
- readonly createdAt: Temporal.Instant;
50
- readonly createdBy: string;
51
- };
52
-
53
34
  type SelectedEvent = {
54
35
  readonly id: bigint;
55
36
  readonly aggregateId: string;
@@ -1,5 +1,10 @@
1
1
  // sql now comes from native dialect
2
2
 
3
+ import type {
4
+ LoadAggregateWithSnapshotOptions,
5
+ LoadAggregateWithSnapshotResult,
6
+ SnapshotReducer,
7
+ } from "@cosmicdrift/kumiko-types/snapshot-types";
3
8
  import type { DbConnection, DbRunner } from "../db/connection";
4
9
  import {
5
10
  index,
@@ -18,7 +23,7 @@ import { tableExists } from "../db/schema-inspection";
18
23
  import type { TenantId } from "../engine/types";
19
24
  import { unsafePushTables } from "../stack";
20
25
  import { isStreamArchived } from "./archive";
21
- import { loadEventsAfterVersion, type StoredEvent } from "./event-store";
26
+ import { loadEventsAfterVersion } from "./event-store";
22
27
 
23
28
  // Marten-aligned snapshot store. A snapshot is a point-in-time materialised
24
29
  // state of an aggregate at a specific version, cached so rehydrating the
@@ -157,40 +162,11 @@ export async function loadLatestSnapshot<
157
162
  };
158
163
  }
159
164
 
160
- // Reducer used to fold events onto a state. Kept narrow and pure — the
161
- // caller supplies the shape and update rules. Mirrors the reducer shape
162
- // feature authors already write for r.projection.apply.
163
- export type SnapshotReducer<TState extends Record<string, unknown>> = (
164
- state: TState,
165
- event: StoredEvent,
166
- ) => TState;
167
-
168
- export type LoadAggregateWithSnapshotResult<TState extends Record<string, unknown>> = {
169
- readonly state: TState;
170
- readonly version: number;
171
- readonly snapshotHit: boolean;
172
- };
173
-
174
- export type LoadAggregateWithSnapshotOptions = {
175
- // Opt-in: include archived streams in the rehydrate. Default false — same
176
- // semantics as loadAggregate / loadAggregateAsOf. Archive check is a
177
- // single indexed lookup, so the cost stays negligible on the hot path.
178
- readonly includeArchived?: boolean;
179
- // Optional upcaster step: every delta event goes through this transform
180
- // BEFORE the reducer sees it. The dispatcher wires this up with
181
- // r.eventMigration so feature code always sees current-version payloads.
182
- // Async to support Marten-style AsyncOnlyEventUpcaster (DB lookups).
183
- readonly upcastEvent?: (event: StoredEvent) => Promise<StoredEvent>;
184
- // Auto-snapshot policy: when the fold applied at least this many delta
185
- // events, persist a fresh snapshot at the folded version (best-effort —
186
- // a failed save never fails the load). Omit to keep snapshotting manual.
187
- readonly snapshotEvery?: number;
188
- // Reducer-shape generation stamped onto saved snapshots (default 1). A
189
- // stored snapshot with a different generation is ignored — full replay
190
- // through the upcaster chain — and restamped on the next auto-save. Bump
191
- // whenever the reducer's state shape changes.
192
- readonly snapshotVersion?: number;
193
- };
165
+ export type {
166
+ LoadAggregateWithSnapshotOptions,
167
+ LoadAggregateWithSnapshotResult,
168
+ SnapshotReducer,
169
+ } from "@cosmicdrift/kumiko-types/snapshot-types";
194
170
 
195
171
  // Snapshot-aware rehydrate. Loads the latest snapshot (if any), applies
196
172
  // events strictly newer than snapshot.version, and returns the fold.
@@ -1,22 +1,2 @@
1
- export type EventMetadata = {
2
- readonly userId: string;
3
- readonly requestId?: string;
4
- // End-to-end business-operation id. Root HTTP requests get it from the
5
- // x-correlation-id header (default: requestId). MSP-applies inherit it
6
- // from the triggering event. Lets you trace "which user click caused
7
- // this email 3 streams later?".
8
- readonly correlationId?: string;
9
- // Stored event id that triggered this write. Null for root commands;
10
- // set to event.id when an MSP-apply runs ctx.appendEvent. Together with
11
- // correlationId forms a causation DAG across aggregate streams.
12
- readonly causationId?: string;
13
- // Marten-conform free key/value space for app-specific metadata that
14
- // doesn't deserve its own EventMetadata field. Examples: A/B-test bucket,
15
- // feature-flag snapshot, geo-region, client SDK version. Persisted into
16
- // events.metadata jsonb (no schema change — it's already a free-form
17
- // jsonb column), survives upcasters untouched, available on every
18
- // StoredEvent.metadata.headers. Framework does not interpret values; the
19
- // app reads them when filtering/auditing. Keep values JSON-primitive
20
- // (string|number|boolean) so JSON serialization stays bulletproof.
21
- readonly headers?: Readonly<Record<string, string | number | boolean>>;
22
- };
1
+ // Legacy path re-exported for callers still importing this module directly.
2
+ export * from "@cosmicdrift/kumiko-types/event-store-types";
@@ -12,11 +12,12 @@
12
12
  // file-foundation re-exports `createFileProviderForTenant` + the plugin types
13
13
  // (moved here from there) so existing imports keep working.
14
14
 
15
+ import type { FileProviderResolver } from "@cosmicdrift/kumiko-types/file-provider-resolver-types";
15
16
  import type { DbConnection } from "../db/connection";
16
17
  import type { TenantDb } from "../db/tenant-db";
17
18
  import { EXT_FILE_PROVIDER, FILE_PROVIDER_CONFIG_KEY } from "../engine/extension-names";
18
19
  import { SYSTEM_USER_ID } from "../engine/system-user";
19
- import type { ConfigAccessor, ConfigAccessorFactory, Registry, TenantId } from "../engine/types";
20
+ import type { ConfigAccessor, ConfigAccessorFactory, Registry } from "../engine/types";
20
21
  import type { SecretsContext } from "../secrets";
21
22
  import type { FileStorageProvider } from "./types";
22
23
 
@@ -120,10 +121,7 @@ export async function createFileProviderForTenant(
120
121
  return usage.options.build(ctx, tenantId);
121
122
  }
122
123
 
123
- // A bound, per-tenant provider resolver. One instance serves all tenants
124
- // (tenantId is the call argument) — the single spine shared by upload routes,
125
- // ctx.files and the GDPR jobs.
126
- export type FileProviderResolver = (tenantId: TenantId) => Promise<FileStorageProvider>;
124
+ export type { FileProviderResolver } from "@cosmicdrift/kumiko-types/file-provider-resolver-types";
127
125
 
128
126
  export type FileProviderResolverDeps = {
129
127
  readonly registry?: Registry;