@cosmicdrift/kumiko-framework 0.165.0 → 0.165.1

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 (147) hide show
  1. package/package.json +5 -3
  2. package/src/__tests__/consumer-cli.integration.test.ts +32 -0
  3. package/src/__tests__/schema-cli.integration.test.ts +1 -1
  4. package/src/api/__tests__/api.test.ts +267 -19
  5. package/src/api/__tests__/auth-middleware-anonymous-access-boot.test.ts +40 -0
  6. package/src/api/__tests__/auth-routes-invalid-body-invite.test.ts +16 -0
  7. package/src/api/__tests__/auth-routes-mfa-preauth-confirm.test.ts +2 -1
  8. package/src/api/__tests__/auth-routes-mfa-preauth-enable-start.test.ts +64 -1
  9. package/src/api/__tests__/auth-routes-trusted-proxy.test.ts +146 -0
  10. package/src/api/__tests__/batch.integration.test.ts +21 -2
  11. package/src/api/__tests__/jwt.test.ts +52 -2
  12. package/src/api/__tests__/redis-login-rate-limiter.integration.test.ts +72 -0
  13. package/src/api/__tests__/sse-broker.test.ts +57 -0
  14. package/src/api/__tests__/sse-route.test.ts +4 -0
  15. package/src/api/auth-routes.ts +178 -33
  16. package/src/api/index.ts +1 -0
  17. package/src/api/jwt.ts +22 -1
  18. package/src/api/routes.ts +103 -35
  19. package/src/api/server.ts +26 -2
  20. package/src/api/sse-broker.ts +39 -0
  21. package/src/bun-db/index.ts +1 -0
  22. package/src/bun-db/query.ts +12 -3
  23. package/src/consumer-cli.ts +60 -13
  24. package/src/db/__tests__/event-store-executor-write-verbs.integration.test.ts +14 -1
  25. package/src/db/__tests__/located-timestamp.test.ts +19 -0
  26. package/src/db/__tests__/migrate-runner.test.ts +61 -0
  27. package/src/db/__tests__/replay-migration-sql.test.ts +131 -2
  28. package/src/db/__tests__/tenant-db-where-merge.test.ts +6 -2
  29. package/src/db/api.ts +2 -2
  30. package/src/db/bun-provider.ts +2 -2
  31. package/src/db/connection.ts +6 -3
  32. package/src/db/dialect.ts +1 -6
  33. package/src/db/entity-table-meta-types.ts +1 -1
  34. package/src/db/event-store-executor-context.ts +2 -3
  35. package/src/db/event-store-executor-read.ts +2 -3
  36. package/src/db/event-store-executor-write.ts +8 -0
  37. package/src/db/index.ts +8 -1
  38. package/src/db/located-timestamp.ts +4 -0
  39. package/src/db/migrate-runner.ts +107 -11
  40. package/src/db/pg-error.ts +8 -0
  41. package/src/db/postgres-provider.ts +2 -2
  42. package/src/db/queries/__tests__/event-store-idempotency-index.integration.test.ts +80 -0
  43. package/src/db/queries/ddl.ts +45 -0
  44. package/src/db/queries/event-store.ts +97 -5
  45. package/src/db/queries/test-stack.ts +4 -30
  46. package/src/db/reference-data.ts +2 -3
  47. package/src/db/replay-migration-sql.ts +114 -12
  48. package/src/db/tenant-db.ts +2 -4
  49. package/src/engine/__tests__/engine.test.ts +30 -0
  50. package/src/engine/__tests__/schema-builder.test.ts +18 -0
  51. package/src/engine/__tests__/store-table.test.ts +2 -2
  52. package/src/engine/boot-validator/nav.ts +5 -0
  53. package/src/engine/constants.ts +32 -6
  54. package/src/engine/create-app.ts +11 -0
  55. package/src/engine/effective-features.ts +12 -2
  56. package/src/engine/extensions/user-data.ts +12 -4
  57. package/src/engine/feature-ui-extensions.ts +2 -2
  58. package/src/engine/hook-helpers.ts +3 -1
  59. package/src/engine/index.ts +1 -1
  60. package/src/engine/ownership.ts +4 -3
  61. package/src/engine/registry-ingest.ts +14 -14
  62. package/src/engine/registry-state.ts +4 -1
  63. package/src/engine/schema-builder.ts +1 -0
  64. package/src/engine/steps/__tests__/duration-utils.test.ts +20 -0
  65. package/src/engine/steps/_duration-utils.ts +2 -0
  66. package/src/engine/steps/unsafe-projection-upsert.ts +1 -4
  67. package/src/engine/types/config.ts +1 -1
  68. package/src/engine/types/define-handler.ts +1 -1
  69. package/src/engine/types/entity-handlers.ts +1 -1
  70. package/src/engine/types/event-type-map.ts +1 -1
  71. package/src/engine/types/feature.ts +1 -1
  72. package/src/engine/types/fields.ts +1 -1
  73. package/src/engine/types/handlers.ts +1 -1
  74. package/src/engine/types/hooks.ts +1 -1
  75. package/src/engine/types/http-route.ts +1 -1
  76. package/src/engine/types/nav.ts +1 -1
  77. package/src/engine/types/ownership.ts +1 -1
  78. package/src/engine/types/projection.ts +1 -1
  79. package/src/engine/types/relations.ts +1 -1
  80. package/src/engine/types/screen.ts +1 -1
  81. package/src/engine/types/step.ts +1 -1
  82. package/src/engine/types/target-ref.ts +1 -1
  83. package/src/engine/types/tree-node.ts +1 -1
  84. package/src/engine/types/workspace.ts +1 -1
  85. package/src/engine/validate-projection-allowlist.ts +5 -5
  86. package/src/errors/classes.ts +21 -0
  87. package/src/errors/index.ts +1 -0
  88. package/src/errors/write-error-info.ts +6 -2
  89. package/src/event-store/__tests__/admin-api.integration.test.ts +27 -1
  90. package/src/event-store/__tests__/event-store.integration.test.ts +32 -0
  91. package/src/event-store/__tests__/unscoped-stream-primitives.guard.test.ts +22 -4
  92. package/src/event-store/admin-api.ts +11 -4
  93. package/src/event-store/event-store.ts +19 -4
  94. package/src/event-store/types.ts +1 -1
  95. package/src/files/__tests__/build-storage-key.test.ts +28 -0
  96. package/src/files/__tests__/local-provider.test.ts +31 -0
  97. package/src/files/__tests__/write-stream.test.ts +3 -3
  98. package/src/files/index.ts +1 -1
  99. package/src/files/local-provider.ts +6 -1
  100. package/src/files/types.ts +8 -1
  101. package/src/jobs/__tests__/jobs.integration.test.ts +167 -7
  102. package/src/jobs/job-runner.ts +41 -11
  103. package/src/logging/types.ts +1 -1
  104. package/src/observability/index.ts +1 -0
  105. package/src/observability/standard-metrics.ts +35 -2
  106. package/src/observability/types/index.ts +1 -1
  107. package/src/observability/types/metric.ts +1 -1
  108. package/src/observability/types/provider.ts +1 -1
  109. package/src/observability/types/span.ts +1 -1
  110. package/src/pipeline/__tests__/dispatcher.test.ts +151 -0
  111. package/src/pipeline/__tests__/event-consumer-state.integration.test.ts +31 -0
  112. package/src/pipeline/__tests__/event-dispatcher-rearm.integration.test.ts +83 -0
  113. package/src/pipeline/__tests__/lifecycle-pipeline.test.ts +107 -97
  114. package/src/pipeline/dispatch-shared.ts +59 -6
  115. package/src/pipeline/dispatch-stream.ts +43 -11
  116. package/src/pipeline/dispatcher.ts +7 -1
  117. package/src/pipeline/event-consumer-state.ts +16 -13
  118. package/src/pipeline/event-dispatcher-delivery.ts +20 -6
  119. package/src/pipeline/event-dispatcher.ts +22 -0
  120. package/src/pipeline/index.ts +2 -0
  121. package/src/pipeline/system-hooks.ts +87 -0
  122. package/src/rate-limit/__tests__/resolver.integration.test.ts +18 -0
  123. package/src/rate-limit/resolver.ts +6 -2
  124. package/src/schema-cli.ts +24 -12
  125. package/src/search/__tests__/reindex-entity.integration.test.ts +24 -1
  126. package/src/search/reindex-entity.ts +31 -2
  127. package/src/search/types.ts +1 -1
  128. package/src/stack/__tests__/setup-test-stack-jobs.integration.test.ts +6 -2
  129. package/src/stack/db.ts +2 -1
  130. package/src/stack/push-entity-projection-tables.ts +2 -1
  131. package/src/stack/request-helper.ts +20 -1
  132. package/src/stack/table-helpers.ts +6 -4
  133. package/src/stack/test-stack.ts +18 -15
  134. package/src/testing/__tests__/late-bound.test.ts +7 -0
  135. package/src/testing/__tests__/wait-for.test.ts +6 -0
  136. package/src/testing/file-provider-contract.ts +26 -6
  137. package/src/testing/index.ts +1 -0
  138. package/src/testing/late-bound.ts +5 -3
  139. package/src/testing/wait-for.ts +3 -0
  140. package/src/testing/without-ambient-temporal.ts +14 -0
  141. package/src/time/__tests__/polyfill-reinstall.test.ts +17 -0
  142. package/src/time/geo-tz.ts +1 -1
  143. package/src/time/polyfill.ts +28 -39
  144. package/src/time/tz-context.ts +30 -24
  145. package/src/utils/__tests__/safe-json-temporal.test.ts +14 -0
  146. package/src/utils/safe-json.ts +3 -2
  147. package/src/engine/__tests__/registry-facade-sweep.test.ts +0 -80
@@ -12,6 +12,23 @@
12
12
  import type { Snapshot } from "./migrate-generator";
13
13
  import { loadMigrationsFromDir } from "./migrate-runner";
14
14
 
15
+ // Migration files comment out destructive ops (DROP TABLE/COLUMN) as
16
+ // `-- DESTRUCTIVE: <stmt>; -- uncomment + ensure backup` so the real
17
+ // migrate-runner never executes them unattended. For replay purposes the
18
+ // snapshot represents the INTENDED end state, so a commented-out drop must
19
+ // still count as applied here — otherwise a table/column the snapshot
20
+ // already omits shows up as "unexpected" forever. splitSqlStatements (the
21
+ // real runner's splitter) strips `--`-comments outright, which would erase
22
+ // these markers before they ever reach applyStatement.
23
+ const DESTRUCTIVE_MARKER = /^--\s*DESTRUCTIVE:\s*(.+?;)/i;
24
+
25
+ function expandDestructiveMarkers(sqlText: string): string {
26
+ return sqlText
27
+ .split("\n")
28
+ .map((line) => DESTRUCTIVE_MARKER.exec(line.trim())?.[1] ?? line)
29
+ .join("\n");
30
+ }
31
+
15
32
  export type ReplayedTable = {
16
33
  readonly columns: ReadonlySet<string>;
17
34
  };
@@ -39,28 +56,67 @@ function splitTopLevel(body: string): readonly string[] {
39
56
  return parts;
40
57
  }
41
58
 
59
+ // Identifiers in hand-written migrations aren't always quoted (the generator
60
+ // always quotes, but the header explicitly invites hand-editing) — optional
61
+ // quotes so `CREATE TABLE foo (...)` parses the same as `CREATE TABLE "foo" (...)`.
62
+ const IDENT = `"?([^"\\s(;,.]+)"?`;
63
+
42
64
  function parseColumnNames(body: string): Set<string> {
43
65
  const columns = new Set<string>();
44
66
  for (const part of splitTopLevel(body)) {
45
67
  const trimmed = part.trim();
46
- if (/^CONSTRAINT\b/i.test(trimmed)) continue; // composite-PK line, not a column
47
- const match = trimmed.match(/^"([^"]+)"/);
68
+ if (/^(CONSTRAINT|PRIMARY|UNIQUE|CHECK|FOREIGN|EXCLUDE|LIKE)\b/i.test(trimmed)) continue; // table-constraint or LIKE clause, not a column
69
+ const match = trimmed.match(new RegExp(`^${IDENT}`));
48
70
  if (match?.[1] !== undefined) columns.add(match[1]);
49
71
  }
50
72
  return columns;
51
73
  }
52
74
 
53
- function applyStatement(schema: Map<string, { columns: Set<string> }>, statement: string): void {
75
+ // Clauses that can appear inside an ALTER TABLE body which do NOT change the
76
+ // table/column shape this replay tracks (presence only, not types/
77
+ // constraints/RLS/ownership) — recognized explicitly so they don't fall
78
+ // through to the fail-loud check as "unparsed". Deliberately does NOT
79
+ // include RENAME TO / RENAME COLUMN: those DO change identity in a way this
80
+ // replay can't track, so they must keep failing loud.
81
+ const SHAPE_NEUTRAL_ALTER_CLAUSE_RE = new RegExp(
82
+ [
83
+ `ALTER COLUMN\\s+${IDENT}\\s+TYPE\\b`, // #1085 int/bigint-catchup fixes
84
+ `ALTER COLUMN\\s+${IDENT}\\s+(SET|DROP)\\s+NOT NULL\\b`,
85
+ `ALTER COLUMN\\s+${IDENT}\\s+(SET DEFAULT\\b|DROP DEFAULT\\b)`,
86
+ `(ADD|DROP)\\s+CONSTRAINT\\s+${IDENT}`,
87
+ `\\b(ENABLE|DISABLE)\\s+ROW LEVEL SECURITY\\b`,
88
+ `^OWNER TO\\b`,
89
+ ].join("|"),
90
+ "gi",
91
+ );
92
+
93
+ function applyStatement(
94
+ schema: Map<string, { columns: Set<string> }>,
95
+ statement: string,
96
+ context: { readonly file: string },
97
+ ): void {
54
98
  const create = statement.match(
55
- /^CREATE TABLE\s+(?:IF NOT EXISTS\s+)?"([^"]+)"\s*\(([\s\S]*)\);?\s*$/i,
99
+ new RegExp(`^CREATE TABLE\\s+(IF NOT EXISTS\\s+)?${IDENT}\\s*\\(([\\s\\S]*)\\);?\\s*$`, "i"),
56
100
  );
57
- if (create?.[1] !== undefined && create[2] !== undefined) {
58
- schema.set(create[1], { columns: parseColumnNames(create[2]) });
101
+ if (create?.[2] !== undefined && create[3] !== undefined) {
102
+ const hasIfNotExists = create[1] !== undefined;
103
+ // A real Postgres CREATE TABLE IF NOT EXISTS is a no-op when the table
104
+ // already exists — treating it as an overwrite here loses any columns
105
+ // an earlier ALTER TABLE added in between (0001 CREATE, 0002 ALTER ADD
106
+ // COLUMN, 0003 an accidental copy-paste of 0001) and reports a false
107
+ // column-drift for exactly the copy-paste bug this replay exists to
108
+ // catch. A bare CREATE TABLE (no IF NOT EXISTS) still overwrites — the
109
+ // explicit recreate path (migrate-generator.ts) always DROPs first, so
110
+ // reaching a second CREATE for the same name there is itself already
111
+ // the bug the replay should surface via the resulting drift.
112
+ if (!(hasIfNotExists && schema.has(create[2]))) {
113
+ schema.set(create[2], { columns: parseColumnNames(create[3]) });
114
+ }
59
115
  // skip: CREATE TABLE fully handled above, no other clause can also match
60
116
  return;
61
117
  }
62
118
 
63
- const dropTable = statement.match(/^DROP TABLE\s+(?:IF EXISTS\s+)?"([^"]+)"/i);
119
+ const dropTable = statement.match(new RegExp(`^DROP TABLE\\s+(?:IF EXISTS\\s+)?${IDENT}`, "i"));
64
120
  if (dropTable?.[1] !== undefined) {
65
121
  schema.delete(dropTable[1]);
66
122
  // skip: DROP TABLE fully handled above, no other clause can also match
@@ -73,29 +129,75 @@ function applyStatement(schema: Map<string, { columns: Set<string> }>, statement
73
129
  // instead of matching only the first clause, in statement order so an
74
130
  // add-then-drop of the same column (unusual, but not impossible) resolves
75
131
  // correctly.
76
- const alterTable = statement.match(/^ALTER TABLE\s+"([^"]+)"\s+([\s\S]*?);?\s*$/i);
132
+ const alterTable = statement.match(
133
+ new RegExp(`^ALTER TABLE\\s+${IDENT}\\s+([\\s\\S]*?);?\\s*$`, "i"),
134
+ );
77
135
  const alterTableName = alterTable?.[1];
78
136
  const alterBody = alterTable?.[2];
79
137
  if (alterTableName !== undefined && alterBody !== undefined) {
80
138
  const table = schema.get(alterTableName) ?? { columns: new Set<string>() };
81
139
  schema.set(alterTableName, table);
82
- const clauseRe = /(ADD|DROP)\s+COLUMN\s+(?:IF (?:NOT )?EXISTS\s+)?"([^"]+)"/gi;
140
+ const clauseRe = new RegExp(
141
+ `(ADD|DROP)\\s+COLUMN\\s+(?:IF (?:NOT )?EXISTS\\s+)?${IDENT}`,
142
+ "gi",
143
+ );
144
+ let matchedAClause = false;
83
145
  for (const [, verb, name] of alterBody.matchAll(clauseRe)) {
84
146
  if (verb === undefined || name === undefined) continue;
147
+ matchedAClause = true;
85
148
  if (verb.toUpperCase() === "ADD") table.columns.add(name);
86
149
  else table.columns.delete(name);
87
150
  }
151
+ // Shape-neutral clauses (ALTER COLUMN TYPE, SET/DROP NOT NULL, SET/DROP
152
+ // DEFAULT, ADD/DROP CONSTRAINT, ENABLE/DISABLE ROW LEVEL SECURITY, OWNER
153
+ // TO) — none add/remove/rename a column, so this replay (which only
154
+ // tracks column presence) correctly has nothing to do for them.
155
+ if (alterBody.match(SHAPE_NEUTRAL_ALTER_CLAUSE_RE)) matchedAClause = true;
156
+ // An ALTER TABLE that matched the outer "ALTER TABLE <name> <body>" shape
157
+ // but whose body contains no recognized clause (e.g. RENAME TO/RENAME
158
+ // COLUMN, which DO change identity) would otherwise silently no-op here
159
+ // — fall through to the fail-loud check below instead of returning, so
160
+ // it's reported rather than vanishing.
161
+ // skip: at least one recognized clause matched — this ALTER TABLE is
162
+ // fully handled, nothing left to do.
163
+ if (matchedAClause) return;
88
164
  }
89
165
  // else: CREATE INDEX and everything else don't change the table/column
90
- // shape this replay tracks.
166
+ // shape this replay tracks — but a statement that clearly INTENDED to
167
+ // touch a table's shape (starts with CREATE/ALTER/DROP TABLE) and matched
168
+ // none of the recognized patterns above must fail loud, not vanish
169
+ // silently. Concretely this is RENAME TO / RENAME COLUMN (identity change
170
+ // this replay can't track) or genuinely unparsed hand-written DDL — either
171
+ // way a misleading missing-table/column-drift report is worse than
172
+ // pointing at the actual unparsed statement.
173
+ if (/^(CREATE|ALTER|DROP)\s+TABLE\b/i.test(statement)) {
174
+ const prefix = statement.slice(0, 200).replace(/\s+/g, " ").trim();
175
+ throw new Error(
176
+ `replayMigrationsDir: unparsed table-DDL statement in ${context.file} — ` +
177
+ `starts with CREATE/ALTER/DROP TABLE but matched none of the replay's ` +
178
+ `recognized patterns (CREATE TABLE, DROP TABLE, ALTER TABLE ADD/DROP ` +
179
+ `COLUMN, ALTER COLUMN ... TYPE, SET/DROP NOT NULL, SET/DROP DEFAULT, ` +
180
+ `ADD/DROP CONSTRAINT, ENABLE/DISABLE ROW LEVEL SECURITY, OWNER TO — ` +
181
+ `optionally-quoted identifiers). Likely RENAME TO/RENAME COLUMN (real ` +
182
+ `identity change, not trackable here) or genuinely unparsed hand-written ` +
183
+ `DDL. Statement: ${prefix}${statement.length > 200 ? "…" : ""}`,
184
+ );
185
+ }
91
186
  }
92
187
 
93
188
  // Reads `<migrationsDir>/*.sql` in sequence order and replays every
94
189
  // CREATE/ALTER/DROP TABLE statement to reconstruct the resulting schema.
190
+ // Reuses the real runner's file-discovery + statement-splitting
191
+ // (loadMigrationsFromDir) instead of a second copy, so any future change to
192
+ // sub-directory handling, numeric sort order, or the .sql filter can't
193
+ // silently drift between the runner and this replay (#1522/9).
95
194
  export function replayMigrationsDir(migrationsDir: string): ReplayedSchema {
96
195
  const schema = new Map<string, { columns: Set<string> }>();
97
- for (const migration of loadMigrationsFromDir(migrationsDir)) {
98
- for (const statement of migration.statements) applyStatement(schema, statement);
196
+ const migrations = loadMigrationsFromDir(migrationsDir, expandDestructiveMarkers);
197
+ for (const migration of migrations) {
198
+ for (const statement of migration.statements) {
199
+ applyStatement(schema, statement, { file: migration.id });
200
+ }
99
201
  }
100
202
  return schema;
101
203
  }
@@ -1,4 +1,4 @@
1
- import type { SchemaTable } from "@cosmicdrift/kumiko-types/schema-table-types";
1
+ import { KUMIKO_NAME_SYMBOL, type SchemaTable } from "@cosmicdrift/kumiko-types/schema-table-types";
2
2
  import type { TenantDb, TenantDbMode } from "@cosmicdrift/kumiko-types/tenant-db-types";
3
3
  import {
4
4
  asEntityTableMeta,
@@ -24,10 +24,8 @@ export function castTenantRows<T>(rows: readonly Record<string, unknown>[]): rea
24
24
  return rows as unknown as readonly T[];
25
25
  }
26
26
 
27
- const KUMIKO_NAME_SYMBOL = Symbol.for("kumiko:schema:Name");
28
-
29
27
  function tableNameOf(table: Table): string {
30
- const sym = (table as unknown as Record<symbol, unknown>)[KUMIKO_NAME_SYMBOL];
28
+ const sym = table[KUMIKO_NAME_SYMBOL];
31
29
  return typeof sym === "string" ? sym : "<unknown>";
32
30
  }
33
31
 
@@ -739,6 +739,36 @@ describe("createApp", () => {
739
739
  ).not.toThrow();
740
740
  });
741
741
 
742
+ test("validates stream handler roles against app-defined roles (#1442)", () => {
743
+ const feature = defineFeature("admin", (r) => {
744
+ r.streamHandler("admin.tail", z.object({}), async function* () {}, {
745
+ access: { roles: ["SuperAdmin"] },
746
+ });
747
+ });
748
+
749
+ expect(() =>
750
+ createApp({
751
+ roles: ["Admin", "User"] as const,
752
+ features: [feature],
753
+ }),
754
+ ).toThrow(/unknown role.*SuperAdmin/i);
755
+ });
756
+
757
+ test("passes when stream handler roles are valid (#1442)", () => {
758
+ const feature = defineFeature("admin", (r) => {
759
+ r.streamHandler("admin.tail", z.object({}), async function* () {}, {
760
+ access: { roles: ["Admin"] },
761
+ });
762
+ });
763
+
764
+ expect(() =>
765
+ createApp({
766
+ roles: ["Admin", "User"] as const,
767
+ features: [feature],
768
+ }),
769
+ ).not.toThrow();
770
+ });
771
+
742
772
  test("createApp returns registry", () => {
743
773
  const feature = defineFeature("test", () => {});
744
774
  const app = createApp({ roles: ["Admin"] as const, features: [feature] });
@@ -113,6 +113,24 @@ describe("buildInsertSchema", () => {
113
113
  valid: { age: 25 },
114
114
  invalid: { age: "old" },
115
115
  },
116
+ {
117
+ name: "number field rejects below min",
118
+ fields: { age: createNumberField({ min: 0 }) },
119
+ valid: { age: 0 },
120
+ invalid: { age: -1 },
121
+ },
122
+ {
123
+ name: "number field rejects above max",
124
+ fields: { age: createNumberField({ max: 100 }) },
125
+ valid: { age: 100 },
126
+ invalid: { age: 101 },
127
+ },
128
+ {
129
+ name: "number field min+max bounds",
130
+ fields: { age: createNumberField({ min: 1, max: 10 }) },
131
+ valid: { age: 5 },
132
+ invalid: { age: 11 },
133
+ },
116
134
  {
117
135
  name: "date field",
118
136
  fields: { born: createDateField() },
@@ -142,7 +142,7 @@ describe("createRegistry — storeTable aggregation", () => {
142
142
  r.storeTable(probeMeta, { reason: "second" });
143
143
  });
144
144
  expect(() => createRegistry([featA, featB])).toThrow(
145
- /Raw-table "rt_probe" registered by both feature "a" and "b"/,
145
+ /Store-table "rt_probe" registered by both feature "a" and "b"/,
146
146
  );
147
147
  });
148
148
 
@@ -177,7 +177,7 @@ describe("createRegistry — storeTable aggregation", () => {
177
177
 
178
178
  // Entity registered first, then the colliding store table.
179
179
  expect(() => createRegistry([entityFeature, tableFeature])).toThrow(
180
- new RegExp(`Raw-table "${physical}".*collides with the physical table of entity "widget"`),
180
+ new RegExp(`Store-table "${physical}".*collides with the physical table of entity "widget"`),
181
181
  );
182
182
 
183
183
  // Order-independent: store table registered first, then the entity.
@@ -115,6 +115,11 @@ export function collectKnownRoles(features: readonly FeatureDefinition[]): Set<s
115
115
  for (const r of def.access.roles) roles.add(r);
116
116
  }
117
117
  }
118
+ for (const def of Object.values(f.streamHandlers)) {
119
+ if (def.access && "roles" in def.access) {
120
+ for (const r of def.access.roles) roles.add(r);
121
+ }
122
+ }
118
123
  }
119
124
  return roles;
120
125
  }
@@ -1,3 +1,6 @@
1
+ import type { ConcurrencyMode } from "@cosmicdrift/kumiko-types/concurrency-mode";
2
+ import type { ConfigScope } from "@cosmicdrift/kumiko-types/config-scope";
3
+ import type { OnDeleteStrategy as OnDeleteStrategyType } from "@cosmicdrift/kumiko-types/relations";
1
4
  import type { TenantId } from "./types/identifiers";
2
5
 
3
6
  // All framework constants as `as const` objects with inferred union types.
@@ -47,14 +50,23 @@ export const LifecycleHookTypes = {
47
50
  export type LifecycleHookType = (typeof LifecycleHookTypes)[keyof typeof LifecycleHookTypes];
48
51
 
49
52
  // --- Config Scopes ---
53
+ // Value object satisfies the canonical ConfigScope union from kumiko-types —
54
+ // a scope added here without a matching kumiko-types member is now a
55
+ // compile error instead of silent drift (#1423/#1439).
50
56
 
51
57
  export const ConfigScopes = {
52
58
  system: "system",
53
59
  tenant: "tenant",
54
60
  user: "user",
55
- } as const;
61
+ } as const satisfies Record<string, ConfigScope>;
62
+
63
+ export type { ConfigScope };
56
64
 
57
- export type ConfigScope = (typeof ConfigScopes)[keyof typeof ConfigScopes];
65
+ // Reverse direction: a member added only to kumiko-types' ConfigScope
66
+ // (not to ConfigScopes above) would otherwise pass the `satisfies` check
67
+ // above unnoticed — this line forces exhaustiveness the other way too.
68
+ const _configScopeExhaustive: Record<ConfigScope, unknown> = ConfigScopes;
69
+ void _configScopeExhaustive;
58
70
 
59
71
  // --- On Delete Strategies ---
60
72
 
@@ -63,11 +75,13 @@ export const OnDeleteStrategies = {
63
75
  restrict: "restrict",
64
76
  setNull: "setNull",
65
77
  nothing: "nothing",
66
- } as const;
78
+ } as const satisfies Record<OnDeleteStrategyType, OnDeleteStrategyType>;
67
79
 
68
- export type OnDeleteStrategy = (typeof OnDeleteStrategies)[keyof typeof OnDeleteStrategies];
80
+ export type OnDeleteStrategy = OnDeleteStrategyType;
69
81
 
70
82
  // --- Concurrency Modes ---
83
+ // Value object satisfies the canonical ConcurrencyMode union from
84
+ // kumiko-types — same drift-guard as ConfigScopes above.
71
85
 
72
86
  export const ConcurrencyModes = {
73
87
  parallel: "parallel",
@@ -75,12 +89,24 @@ export const ConcurrencyModes = {
75
89
  replace: "replace",
76
90
  sequential: "sequential",
77
91
  debounce: "debounce",
78
- } as const;
92
+ } as const satisfies Record<string, ConcurrencyMode>;
79
93
 
80
- export type ConcurrencyMode = (typeof ConcurrencyModes)[keyof typeof ConcurrencyModes];
94
+ export type { ConcurrencyMode };
95
+
96
+ // Reverse-direction exhaustiveness guard — see the ConfigScope one above.
97
+ const _concurrencyModeExhaustive: Record<ConcurrencyMode, unknown> = ConcurrencyModes;
98
+ void _concurrencyModeExhaustive;
81
99
 
82
100
  // --- SSE Channels ---
83
101
 
84
102
  export function tenantChannel(tenantId: TenantId): string {
85
103
  return `tenant:${tenantId}`;
86
104
  }
105
+
106
+ // Access-invalidation channel key for a single user's live streams. Both
107
+ // the subscribe side (dispatch-stream.ts) and the publish side (session-
108
+ // revoke / tenant-membership consumers, issue #1559/#1560) must derive the
109
+ // key through this helper — never build the string inline on either side.
110
+ export function userAccessChannel(userId: string): string {
111
+ return `user:${userId}:access`;
112
+ }
@@ -53,6 +53,17 @@ export function createApp(config: AppConfig): App {
53
53
  }
54
54
  }
55
55
  }
56
+ for (const handler of Object.values(feature.streamHandlers)) {
57
+ if (handler.access && "roles" in handler.access) {
58
+ for (const role of handler.access.roles) {
59
+ if (!validRoles.has(role)) {
60
+ throw new Error(
61
+ `Unknown role "${role}" in stream handler "${handler.name}" of feature "${feature.name}". Valid roles: ${config.roles.join(", ")}`,
62
+ );
63
+ }
64
+ }
65
+ }
66
+ }
56
67
  for (const [key, keyDef] of Object.entries(feature.configKeys)) {
57
68
  for (const role of [...keyDef.access.read, ...keyDef.access.write]) {
58
69
  if (!systemRoles.has(role) && !validRoles.has(role)) {
@@ -1,4 +1,4 @@
1
- import type { Registry } from "./types";
1
+ import type { FeatureDefinition, Registry } from "./types";
2
2
 
3
3
  // Callback that returns the current global-toggle override for a feature.
4
4
  // `true` = explicit global row says enabled.
@@ -11,6 +11,16 @@ import type { Registry } from "./types";
11
11
  // a Map lookup to keep compute() allocation-light.
12
12
  export type ToggleReader = (featureName: string) => boolean | undefined;
13
13
 
14
+ // A feature is toggleable iff it declared r.toggleable() at define-time
15
+ // (toggleableDefault set). Non-toggleable features are always-on and ignore
16
+ // overrides entirely — used here, by compose-tier-resolver, and by
17
+ // tier-engine's always-on set to agree on the same rule.
18
+ export function isToggleableFeature(
19
+ feature: FeatureDefinition,
20
+ ): feature is FeatureDefinition & { toggleableDefault: boolean } {
21
+ return feature.toggleableDefault !== undefined;
22
+ }
23
+
14
24
  // Compute the set of effectively-enabled features for the current call.
15
25
  //
16
26
  // Rules (AND-combined, any false wins):
@@ -35,7 +45,7 @@ export function computeEffectiveFeatures(
35
45
  // Raw enablement, before cascade.
36
46
  const raw = new Map<string, boolean>();
37
47
  for (const feature of registry.features.values()) {
38
- if (feature.toggleableDefault === undefined) {
48
+ if (!isToggleableFeature(feature)) {
39
49
  raw.set(feature.name, true);
40
50
  continue;
41
51
  }
@@ -150,14 +150,22 @@ export type UserDataExportHook = (ctx: UserDataHookCtx) => Promise<UserDataExpor
150
150
  * `{status:"incomplete", reason}` to signal a partial success to the
151
151
  * cleanup runner (e.g. an external provider call failed) without
152
152
  * throwing/rolling back the sub-transaction. Existing `void` returners
153
- * stay valid unchanged.
153
+ * stay valid unchanged — including ones explicitly typed
154
+ * `Promise<void>` (an explicitly-annotated hook, unlike a contextually-
155
+ * typed arrow literal, needs `void` in the union itself: `void` is not
156
+ * assignable to `undefined`).
154
157
  */
158
+ // Intentional: void (not undefined) is required here so an explicitly-typed
159
+ // `Promise<void>` hook stays assignable (see UserDataDeleteHook's doc
160
+ // comment above).
161
+ export type UserDataDeleteHookResult =
162
+ // biome-ignore lint/suspicious/noConfusingVoidType: see comment above
163
+ void | { readonly status: "ok" } | { readonly status: "incomplete"; readonly reason: string };
164
+
155
165
  export type UserDataDeleteHook = (
156
166
  ctx: UserDataHookCtx,
157
167
  strategy: UserDataDeleteStrategy,
158
- ) => Promise<
159
- undefined | { readonly status: "ok" } | { readonly status: "incomplete"; readonly reason: string }
160
- >;
168
+ ) => Promise<UserDataDeleteHookResult>;
161
169
 
162
170
  /**
163
171
  * Komplette Hook-Tafel für EXT_USER_DATA. Sprint 2 user-data-rights
@@ -426,14 +426,14 @@ export function buildUiExtensionsMethods<TName extends string>(
426
426
  // EntityTableMeta uses snake_case for tableName (matches Postgres
427
427
  // convention); we just guard against truly broken input.
428
428
  throw new Error(
429
- `[Feature ${name}] Raw-table name "${tableName}" must be a ` +
429
+ `[Feature ${name}] Store-table name "${tableName}" must be a ` +
430
430
  `valid identifier (lowercase letters, digits, underscores; start with a letter).`,
431
431
  );
432
432
  }
433
433
  if (state.storeTables[tableName]) {
434
434
  throw new Error(
435
435
  `[Feature ${name}] r.storeTable("${tableName}") already registered. ` +
436
- `Raw-table names must be unique per feature.`,
436
+ `Store-table names must be unique per feature.`,
437
437
  );
438
438
  }
439
439
  // `read_` is reserved for r.entity()/r.projection() (managed,
@@ -8,7 +8,9 @@
8
8
  // are logged but don't affect the write. Use for: external systems
9
9
  // (SSE broadcast, search index, email, webhooks).
10
10
 
11
+ import type { HookPhase } from "@cosmicdrift/kumiko-types/hook-phase";
12
+
11
13
  export const HookPhases = {
12
14
  inTransaction: "inTransaction",
13
15
  afterCommit: "afterCommit",
14
- } as const;
16
+ } as const satisfies Record<HookPhase, HookPhase>;
@@ -52,7 +52,7 @@ export { defineStep, getStep, listStepKinds } from "./define-step";
52
52
  export type { WorkflowDefinition, WorkflowInput, WorkflowTrigger } from "./define-workflow";
53
53
  export { computeDefinitionFingerprint, defineWorkflow } from "./define-workflow";
54
54
  export type { ToggleReader } from "./effective-features";
55
- export { computeEffectiveFeatures } from "./effective-features";
55
+ export { computeEffectiveFeatures, isToggleableFeature } from "./effective-features";
56
56
  export {
57
57
  createEntityExecutor,
58
58
  defineEntityCreateHandler,
@@ -17,6 +17,10 @@
17
17
  // Construction: use the `from(ref, column?)` helper. It returns a FromRule
18
18
  // ready to drop into an access map.
19
19
 
20
+ import {
21
+ KUMIKO_COLUMNS_SYMBOL,
22
+ KUMIKO_NAME_SYMBOL,
23
+ } from "@cosmicdrift/kumiko-types/schema-table-types";
20
24
  import { toSnakeCase } from "../db/table-builder";
21
25
  import type { SessionUser } from "./types";
22
26
 
@@ -221,9 +225,6 @@ export function userCanCreateFieldRow(
221
225
  const PASS_CLAUSE: OwnershipClause = { kind: "pass" };
222
226
  const EMPTY_CLAUSE: OwnershipClause = { kind: "empty" };
223
227
 
224
- const KUMIKO_NAME_SYMBOL = Symbol.for("kumiko:schema:Name");
225
- const KUMIKO_COLUMNS_SYMBOL = Symbol.for("kumiko:schema:Columns");
226
-
227
228
  function tableNameOf(table: unknown): string {
228
229
  if (table !== null && typeof table === "object") {
229
230
  const sym = (table as Record<symbol, unknown>)[KUMIKO_NAME_SYMBOL];
@@ -20,7 +20,7 @@ export function populateFeatureCore(state: RegistryState, feature: FeatureDefini
20
20
  state.entityMap.set(name, entity);
21
21
  const physical = resolveTableName(name, entity, feature.name);
22
22
  const clash = state.physicalTableOwners.get(physical);
23
- if (clash?.kind === "raw") {
23
+ if (clash?.kind === "store") {
24
24
  throw new Error(
25
25
  `Entity "${name}" (feature "${feature.name}") has physical table "${physical}" which ` +
26
26
  `collides with r.storeTable("${physical}") (feature "${clash.featureName}"). ` +
@@ -317,37 +317,37 @@ export function populateProjectionsAndTables(
317
317
  // statements that target the same physical table name. Two features
318
318
  // registering the same physical tableName would also race two CREATE
319
319
  // TABLE statements via migrate-runner.
320
- for (const [rawName, rawDef] of Object.entries(feature.storeTables ?? {})) {
321
- const existing = state.storeTableMap.get(rawName);
320
+ for (const [storeName, storeDef] of Object.entries(feature.storeTables ?? {})) {
321
+ const existing = state.storeTableMap.get(storeName);
322
322
  if (existing) {
323
323
  throw new Error(
324
- `Raw-table "${rawName}" registered by both feature "${existing.featureName}" and ` +
324
+ `Store-table "${storeName}" registered by both feature "${existing.featureName}" and ` +
325
325
  `"${feature.name}". Pick a feature-prefixed name to disambiguate.`,
326
326
  );
327
327
  }
328
- const physicalClash = state.physicalTableOwners.get(rawName);
328
+ const physicalClash = state.physicalTableOwners.get(storeName);
329
329
  if (physicalClash?.kind === "entity") {
330
330
  throw new Error(
331
- `Raw-table "${rawName}" (feature "${feature.name}") collides with the physical ` +
331
+ `Store-table "${storeName}" (feature "${feature.name}") collides with the physical ` +
332
332
  `table of entity "${physicalClash.owner}" (feature "${physicalClash.featureName}"). ` +
333
- `Pick a different tableName — both would emit CREATE TABLE "${rawName}".`,
333
+ `Pick a different tableName — both would emit CREATE TABLE "${storeName}".`,
334
334
  );
335
335
  }
336
- const piiFields = rawDef.meta.piiSubjectFields ?? [];
337
- if (piiFields.length > 0 && !rawDef.piiEncryptedOnWrite) {
336
+ const piiFields = storeDef.meta.piiSubjectFields ?? [];
337
+ if (piiFields.length > 0 && !storeDef.piiEncryptedOnWrite) {
338
338
  throw new Error(
339
- `Raw-table "${rawName}" (feature "${feature.name}") has PII-annotated fields ` +
339
+ `Store-table "${storeName}" (feature "${feature.name}") has PII-annotated fields ` +
340
340
  `(${piiFields.join(", ")}) but direct writes bypass the executor's PII encryption. ` +
341
341
  `Encrypt those fields before every insert/update (encryptPiiFieldValues) and declare ` +
342
342
  `{ piiEncryptedOnWrite: true }, or drop the subject annotations.`,
343
343
  );
344
344
  }
345
- state.physicalTableOwners.set(rawName, {
346
- kind: "raw",
347
- owner: rawName,
345
+ state.physicalTableOwners.set(storeName, {
346
+ kind: "store",
347
+ owner: storeName,
348
348
  featureName: feature.name,
349
349
  });
350
- state.storeTableMap.set(rawName, { ...rawDef, featureName: feature.name });
350
+ state.storeTableMap.set(storeName, { ...storeDef, featureName: feature.name });
351
351
  }
352
352
  }
353
353
 
@@ -202,7 +202,10 @@ export type RegistryState = {
202
202
  multiStreamProjectionMap: Map<string, MultiStreamProjectionDefinition>;
203
203
  multiStreamProjectionFeatureMap: Map<string, string>;
204
204
  storeTableMap: Map<string, StoreTableDef>;
205
- physicalTableOwners: Map<string, { kind: "entity" | "raw"; owner: string; featureName: string }>;
205
+ physicalTableOwners: Map<
206
+ string,
207
+ { kind: "entity" | "store"; owner: string; featureName: string }
208
+ >;
206
209
  authClaimsHooks: AuthClaimsHookDef[];
207
210
  claimKeyMap: Map<string, ClaimKeyDefinition>;
208
211
  screenMap: Map<string, ScreenDefinition>;
@@ -97,6 +97,7 @@ export function fieldToZod(field: FieldDefinition, currencies: readonly string[]
97
97
  let schema = z.number();
98
98
  if (field.integer) schema = schema.int();
99
99
  if (field.min !== undefined) schema = schema.min(field.min);
100
+ if (field.max !== undefined) schema = schema.max(field.max);
100
101
  return field.default !== undefined ? schema.default(field.default) : schema;
101
102
  }
102
103
  case "decimal": {
@@ -0,0 +1,20 @@
1
+ // kumiko-framework#1525: addDuration must not rely on globalThis.Temporal —
2
+ // it's a pure free function called from step handlers before boot may have
3
+ // run ensureTemporalPolyfill() on every code path.
4
+
5
+ import { describe, expect, test } from "bun:test";
6
+ import { addDuration } from "../_duration-utils";
7
+
8
+ describe("addDuration — kumiko-framework#1525: no ambient Temporal global", () => {
9
+ test("adds a duration without relying on globalThis.Temporal", () => {
10
+ const savedGlobal = (globalThis as { Temporal?: unknown }).Temporal;
11
+ delete (globalThis as { Temporal?: unknown }).Temporal;
12
+ try {
13
+ const result = addDuration("2026-01-01T00:00:00Z", "P1DT1H");
14
+ expect(result).toBe("2026-01-02T01:00:00Z");
15
+ } finally {
16
+ if (savedGlobal === undefined) delete (globalThis as { Temporal?: unknown }).Temporal;
17
+ else (globalThis as { Temporal?: unknown }).Temporal = savedGlobal;
18
+ }
19
+ });
20
+ });
@@ -2,6 +2,8 @@
2
2
  // Accepts "P1D", "PT1H", "P1Y2M3DT4H5M6S" etc.
3
3
  // Uses approximate calendar math (365d/year, 30d/month). See #23.
4
4
 
5
+ import { Temporal } from "temporal-polyfill";
6
+
5
7
  export function addDuration(baseIso: string, duration: string): string {
6
8
  const pattern = /^P(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/;
7
9
  const match = duration.match(pattern);
@@ -11,6 +11,7 @@
11
11
  // rejected by boot-validation — domain mutation MUST go through
12
12
  // r.step.aggregate.*.
13
13
 
14
+ import { KUMIKO_COLUMNS_SYMBOL } from "@cosmicdrift/kumiko-types/schema-table-types";
14
15
  import { extractTableName } from "../../db";
15
16
  import { executeRawQuery } from "../../db/queries/raw-sql";
16
17
  import { defineStep } from "../define-step";
@@ -23,10 +24,6 @@ type UnsafeProjectionUpsertArgs = {
23
24
  readonly row: StepResolver<Record<string, unknown>>;
24
25
  };
25
26
 
26
- // @cast-boundary drizzle-bridge — reads column snake_case names from
27
- // drizzle Symbol-based metadata without importing drizzle-orm.
28
- const KUMIKO_COLUMNS_SYMBOL = Symbol.for("kumiko:schema:Columns");
29
-
30
27
  function resolveColumnName(table: unknown, field: string): string {
31
28
  if (typeof table !== "object" || table === null) return field;
32
29
  const cols = (table as Record<symbol, unknown>)[KUMIKO_COLUMNS_SYMBOL];
@@ -1,2 +1,2 @@
1
1
  // Legacy path — re-exported for callers still importing this module directly.
2
- export * from "@cosmicdrift/kumiko-types/config";
2
+ export type * from "@cosmicdrift/kumiko-types/config";