@cosmicdrift/kumiko-framework 0.410.0 → 0.412.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 (68) hide show
  1. package/agents/api/framework-db.md +1 -1
  2. package/agents/api/framework-engine.md +50 -1
  3. package/agents/api/framework-errors.md +2 -0
  4. package/agents/api/framework-ui-types.md +10 -0
  5. package/agents/api/renderer-web.md +113 -10
  6. package/agents/api/types.md +30 -0
  7. package/agents/api.md +3 -3
  8. package/agents/boot-rules.md +4 -0
  9. package/agents/examples/api-docs.md +702 -0
  10. package/agents/examples/realtime-sse.md +37 -2
  11. package/agents/examples/record-detail-layout.md +35 -2
  12. package/agents/examples/wizard-form.md +96 -5
  13. package/agents/examples.md +1 -0
  14. package/agents/features.md +6 -0
  15. package/agents/widgets.md +6 -0
  16. package/dist/api/auth-middleware.d.ts +1 -0
  17. package/dist/api/index.d.ts +3 -0
  18. package/dist/api/index.js +3 -0
  19. package/dist/api/pat-auth-reject.d.ts +7 -0
  20. package/dist/api/pat-auth-reject.js +7 -0
  21. package/dist/api/server-middleware.js +2 -1
  22. package/dist/compliance/sub-processors.js +2 -2
  23. package/dist/config/index.d.ts +25 -0
  24. package/dist/config/index.js +28 -1
  25. package/dist/db/event-store-executor-read-paging.d.ts +1 -0
  26. package/dist/db/event-store-executor-read-paging.js +2 -1
  27. package/dist/db/queries/session-advisory-lock.js +3 -0
  28. package/dist/db/read-gate-clause.js +26 -7
  29. package/dist/db/table-builder.d.ts +1 -2
  30. package/dist/engine/boot-validator/boot-rules.d.ts +20 -0
  31. package/dist/engine/boot-validator/list-table-options.js +1 -0
  32. package/dist/engine/boot-validator/screens-forms-layout-rules.d.ts +15 -0
  33. package/dist/engine/boot-validator/screens-forms-layout-rules.js +15 -0
  34. package/dist/engine/boot-validator/screens-forms.d.ts +1 -1
  35. package/dist/engine/boot-validator/screens-forms.js +60 -3
  36. package/dist/engine/boot-validator/screens-kind-projection-detail-rules.d.ts +5 -0
  37. package/dist/engine/boot-validator/screens-kind-projection-detail-rules.js +5 -0
  38. package/dist/engine/boot-validator/screens-kind-projection-detail.js +19 -0
  39. package/dist/engine/boot-validator/screens-lists.js +2 -2
  40. package/dist/engine/define-feature.js +3 -0
  41. package/dist/engine/entity-list-runtime-options.js +12 -0
  42. package/dist/engine/factories.d.ts +2 -0
  43. package/dist/engine/feature-builder-state.d.ts +2 -1
  44. package/dist/engine/feature-builder-state.js +1 -0
  45. package/dist/engine/index.d.ts +5 -2
  46. package/dist/engine/index.js +4 -1
  47. package/dist/engine/project-app-schema-for-roles.js +11 -10
  48. package/dist/engine/registry-facade.js +13 -0
  49. package/dist/engine/screen-helpers.d.ts +1 -0
  50. package/dist/engine/screen-helpers.js +1 -1
  51. package/dist/engine/webhook-contracts.d.ts +12 -0
  52. package/dist/engine/webhook-contracts.js +172 -0
  53. package/dist/engine/webhook-events.d.ts +34 -0
  54. package/dist/engine/webhook-events.js +71 -0
  55. package/dist/errors/docs-url.js +2 -19
  56. package/dist/errors/error-codes.d.ts +20 -0
  57. package/dist/errors/error-codes.js +19 -0
  58. package/dist/errors/index.d.ts +2 -0
  59. package/dist/errors/index.js +1 -0
  60. package/dist/i18n/required-surface-keys.d.ts +4 -0
  61. package/dist/i18n/required-surface-keys.js +15 -0
  62. package/dist/pipeline/context-services.d.ts +1 -0
  63. package/dist/pipeline/context-services.js +1 -0
  64. package/dist/pipeline/handler-context-scope.js +5 -1
  65. package/dist/pipeline/user-live-signals.d.ts +5 -0
  66. package/dist/pipeline/user-live-signals.js +20 -0
  67. package/package.json +3 -3
  68. package/src/changes.json +78 -0
@@ -0,0 +1,172 @@
1
+ import * as z from "zod";
2
+ import { DEFAULT_CURRENCIES } from "./field-helpers.js";
3
+ import { personalFieldNames } from "./personal-data-fields.js";
4
+ import { fieldToZod } from "./schema-builder.js";
5
+ const ENTITY_VERBS = ["created", "updated", "deleted"];
6
+ const CONTRACT_VERSION = 1;
7
+ // money and locatedTimestamp are stored as several flat columns (amount plus currency, instant
8
+ // plus zone); the event shape of such a field is not mapped yet, so they stay out instead of
9
+ // being described wrongly.
10
+ const COMPOUND_FIELD_TYPES = new Set([
11
+ "money",
12
+ "locatedTimestamp",
13
+ ]);
14
+ function isEncryptedText(field) {
15
+ return (field.type === "text" || field.type === "longText") && field.encrypted === true;
16
+ }
17
+ function isSecretText(field) {
18
+ return field.type === "text" && field.writeOnly === true;
19
+ }
20
+ function isSensitive(field) {
21
+ return "sensitive" in field && field.sensitive === true;
22
+ }
23
+ // A webhook leaves the system: credentials, client addresses, restricted-read fields and system-written
24
+ // plaintext fields stay out even when not personal. `allowPlaintext` is a plain string, hence the patterns.
25
+ const NEVER_RELEASED_NAME = /hash|secret|token|password|passcode|totp|recovery|salt|storagekey|fromip|useragent/i;
26
+ const CREDENTIAL_REASON = /credential|hash|secret|token/i;
27
+ function plaintextReason(field) {
28
+ return "allowPlaintext" in field && typeof field.allowPlaintext === "string"
29
+ ? field.allowPlaintext
30
+ : undefined;
31
+ }
32
+ function hasRestrictedAccess(field, mode) {
33
+ return "access" in field && field.access?.[mode] !== undefined;
34
+ }
35
+ function isCredentialOrInternal(name, field) {
36
+ const reason = plaintextReason(field);
37
+ return (hasRestrictedAccess(field, "read") ||
38
+ (reason !== undefined && hasRestrictedAccess(field, "write")) ||
39
+ NEVER_RELEASED_NAME.test(name) ||
40
+ (reason !== undefined && CREDENTIAL_REASON.test(reason)));
41
+ }
42
+ function releasableFields(entity, excludedFields) {
43
+ const personal = personalFieldNames(entity, false);
44
+ return Object.entries(entity.fields).filter(([name, field]) => !personal.has(name) &&
45
+ !excludedFields.has(name) &&
46
+ !COMPOUND_FIELD_TYPES.has(field.type) &&
47
+ !isEncryptedText(field) &&
48
+ !isSecretText(field) &&
49
+ !isSensitive(field) &&
50
+ !isCredentialOrInternal(name, field));
51
+ }
52
+ function isAlwaysPresent(field) {
53
+ return (("required" in field && field.required === true) ||
54
+ ("default" in field && field.default !== undefined));
55
+ }
56
+ function fieldShape(fields, presence) {
57
+ return Object.fromEntries(fields.map(([name, field]) => {
58
+ const schema = fieldToZod(field, DEFAULT_CURRENCIES, { applyDefaults: false });
59
+ const required = presence === "as-declared" && isAlwaysPresent(field);
60
+ return [name, required ? schema : schema.nullable().optional()];
61
+ }));
62
+ }
63
+ // The executor appends `changes` and `previous` (the whole pre-update row, which always has `id`)
64
+ // on update and `{ previous }` on delete; create appends the flat fields without `id`. Receivers
65
+ // need the id, so the contract carries it on the top level; `toEntityWebhookPayload` takes it from
66
+ // the event's aggregate id.
67
+ function payloadFor(verb, fields) {
68
+ const row = z.object({ id: z.uuid(), ...fieldShape(fields, "optional") });
69
+ if (verb === "created")
70
+ return z.object({ id: z.uuid(), ...fieldShape(fields, "as-declared") });
71
+ if (verb === "updated")
72
+ return z.object({
73
+ id: z.uuid(),
74
+ changes: z.object(fieldShape(fields, "optional")),
75
+ previous: row,
76
+ });
77
+ return z.object({ id: z.uuid(), previous: row });
78
+ }
79
+ const VERB_DESCRIPTION = {
80
+ created: "was created",
81
+ updated: "was updated",
82
+ deleted: "was deleted",
83
+ };
84
+ function entityContract(entityName, verb, entity, excludedFields) {
85
+ return {
86
+ qn: `${entityName}.${verb}`,
87
+ wireName: `${entityName}.${verb}`,
88
+ description: `A ${entityName} ${VERB_DESCRIPTION[verb]}.`,
89
+ payload: payloadFor(verb, releasableFields(entity, excludedFields)),
90
+ version: CONTRACT_VERSION,
91
+ origin: "entity",
92
+ entity: entityName,
93
+ verb,
94
+ };
95
+ }
96
+ function excludedFieldsByEntity(features) {
97
+ const byEntity = new Map();
98
+ for (const feature of features) {
99
+ for (const [handlerName, handler] of Object.entries(feature.writeHandlers)) {
100
+ const entityName = feature.handlerEntityMappings[handlerName];
101
+ if (entityName === undefined || handler.excludedFields === undefined)
102
+ continue;
103
+ const names = byEntity.get(entityName) ?? new Set();
104
+ for (const field of handler.excludedFields)
105
+ names.add(field);
106
+ byEntity.set(entityName, names);
107
+ }
108
+ }
109
+ return byEntity;
110
+ }
111
+ function entityVerbOf(qualifiedName) {
112
+ const dot = qualifiedName.lastIndexOf(".");
113
+ if (dot <= 0)
114
+ return undefined;
115
+ const verb = ENTITY_VERBS.find((candidate) => candidate === qualifiedName.slice(dot + 1));
116
+ return verb === undefined ? undefined : { entity: qualifiedName.slice(0, dot), verb };
117
+ }
118
+ /** Works on the feature list so a boot check, which has no registry, resolves the same contracts. */
119
+ export function createWebhookContractResolver(features) {
120
+ const declared = new Map();
121
+ const entities = new Map();
122
+ for (const feature of features) {
123
+ for (const def of Object.values(feature.webhookEvents ?? {})) {
124
+ declared.set(def.qn, { ...def, origin: "declared" });
125
+ }
126
+ for (const [name, entity] of Object.entries(feature.entities ?? {}))
127
+ entities.set(name, entity);
128
+ }
129
+ const excluded = excludedFieldsByEntity(features);
130
+ const derived = new Map();
131
+ return {
132
+ get(qualifiedName) {
133
+ const own = declared.get(qualifiedName);
134
+ if (own !== undefined)
135
+ return own;
136
+ if (!derived.has(qualifiedName)) {
137
+ const target = entityVerbOf(qualifiedName);
138
+ const entity = target === undefined ? undefined : entities.get(target.entity);
139
+ derived.set(qualifiedName, target === undefined || entity === undefined || entity.webhookEvents !== true
140
+ ? undefined
141
+ : entityContract(target.entity, target.verb, entity, excluded.get(target.entity) ?? new Set()));
142
+ }
143
+ return derived.get(qualifiedName);
144
+ },
145
+ declared() {
146
+ return [...declared.values()].sort((a, b) => (a.qn < b.qn ? -1 : a.qn > b.qn ? 1 : 0));
147
+ },
148
+ };
149
+ }
150
+ /** Receivers tell events apart by wire name, so two contracts must never share one. */
151
+ export function assertUniqueWebhookWireNames(features) {
152
+ const qnByWireName = new Map();
153
+ const claim = (wireName, qn) => {
154
+ const existing = qnByWireName.get(wireName);
155
+ if (existing !== undefined && existing !== qn) {
156
+ throw new Error(`Webhook wire name "${wireName}" is used by both "${existing}" and "${qn}"; give one of them another wireName.`);
157
+ }
158
+ qnByWireName.set(wireName, qn);
159
+ };
160
+ for (const feature of features) {
161
+ for (const def of Object.values(feature.webhookEvents ?? {}))
162
+ claim(def.wireName, def.qn);
163
+ }
164
+ for (const feature of features) {
165
+ for (const [name, entity] of Object.entries(feature.entities ?? {})) {
166
+ if (entity.webhookEvents !== true)
167
+ continue;
168
+ for (const verb of ENTITY_VERBS)
169
+ claim(`${name}.${verb}`, `${name}.${verb}`);
170
+ }
171
+ }
172
+ }
@@ -0,0 +1,34 @@
1
+ import type { WebhookEventContract, WebhookEventHandle } from "@cosmicdrift/kumiko-types/feature";
2
+ import { ZodObject } from "zod";
3
+ import type { FeatureBuilderState } from "./feature-builder-state.ts";
4
+ export type WebhookPayloadIssue = {
5
+ readonly path: string;
6
+ readonly message: string;
7
+ };
8
+ export type WebhookPayloadResult = {
9
+ readonly ok: true;
10
+ readonly payload: Record<string, unknown>;
11
+ } | {
12
+ readonly ok: false;
13
+ readonly issues: readonly WebhookPayloadIssue[];
14
+ };
15
+ /** Delivery sends the returned payload, never the input: zod strips keys the contract does not
16
+ * declare, so a field added to the source row cannot leak into a webhook by accident. */
17
+ export declare function parseWebhookPayload(contract: Pick<WebhookEventContract, "payload">, payload: unknown): WebhookPayloadResult;
18
+ /** Maps a stored entity lifecycle event to the contract's payload: the aggregate id joins the
19
+ * event payload, and the contract parse drops every field it does not release, personal ones
20
+ * included, even when the event payload carries them. */
21
+ export declare function toEntityWebhookPayload(contract: Pick<WebhookEventContract, "payload" | "verb">, event: {
22
+ readonly aggregateId: string;
23
+ readonly payload: Readonly<Record<string, unknown>>;
24
+ }): WebhookPayloadResult;
25
+ export declare function formatWebhookPayloadIssues(issues: readonly WebhookPayloadIssue[]): string;
26
+ export declare function buildWebhookEventMethods(state: FeatureBuilderState, featureName: string): {
27
+ defineWebhookEvent(definition: {
28
+ readonly name: string;
29
+ readonly description: string;
30
+ readonly payload: ZodObject;
31
+ readonly version: number;
32
+ readonly wireName?: string;
33
+ }): WebhookEventHandle;
34
+ };
@@ -0,0 +1,71 @@
1
+ import { ZodObject } from "zod";
2
+ import { isObjectArgument, throwObjectArgumentRequired } from "./object-form.js";
3
+ import { isKebabSegment, toKebab } from "./qualified-name.js";
4
+ /** Delivery sends the returned payload, never the input: zod strips keys the contract does not
5
+ * declare, so a field added to the source row cannot leak into a webhook by accident. */
6
+ export function parseWebhookPayload(contract, payload) {
7
+ const parsed = contract.payload.safeParse(payload);
8
+ if (parsed.success)
9
+ return { ok: true, payload: parsed.data };
10
+ return {
11
+ ok: false,
12
+ issues: parsed.error.issues.map((issue) => ({
13
+ path: issue.path.map(String).join("."),
14
+ message: issue.message,
15
+ })),
16
+ };
17
+ }
18
+ /** Maps a stored entity lifecycle event to the contract's payload: the aggregate id joins the
19
+ * event payload, and the contract parse drops every field it does not release, personal ones
20
+ * included, even when the event payload carries them. */
21
+ export function toEntityWebhookPayload(contract, event) {
22
+ const { aggregateId, payload } = event;
23
+ const shaped = contract.verb === "created"
24
+ ? { ...payload, id: aggregateId }
25
+ : { id: aggregateId, changes: payload["changes"], previous: payload["previous"] };
26
+ return parseWebhookPayload(contract, shaped);
27
+ }
28
+ export function formatWebhookPayloadIssues(issues) {
29
+ return issues
30
+ .map((issue) => `${issue.path === "" ? "(root)" : issue.path}: ${issue.message}`)
31
+ .join("; ");
32
+ }
33
+ export function buildWebhookEventMethods(state, featureName) {
34
+ return {
35
+ defineWebhookEvent(definition) {
36
+ if (!isObjectArgument(definition))
37
+ throwObjectArgumentRequired(featureName, "defineWebhookEvent");
38
+ const { name, description, payload, version } = definition;
39
+ const where = `[Feature ${featureName}] defineWebhookEvent`;
40
+ if (typeof name !== "string" || !isKebabSegment(name)) {
41
+ throw new Error(`${where}: name must be kebab-case, got ${JSON.stringify(name)}`);
42
+ }
43
+ if (typeof description !== "string" || description.trim() === "") {
44
+ throw new Error(`${where}("${name}"): description must be a non-empty sentence`);
45
+ }
46
+ if (!(payload instanceof ZodObject)) {
47
+ throw new Error(`${where}("${name}"): payload must be a zod object schema`);
48
+ }
49
+ if (!Number.isInteger(version) || version < 1) {
50
+ throw new Error(`${where}("${name}"): version must be a positive integer`);
51
+ }
52
+ if (definition.wireName !== undefined &&
53
+ (typeof definition.wireName !== "string" || definition.wireName.trim() === "")) {
54
+ throw new Error(`${where}("${name}"): wireName must be a non-empty string`);
55
+ }
56
+ const wireName = definition.wireName?.trim() ?? name;
57
+ const qn = `${toKebab(featureName)}:${name}`;
58
+ if (state.webhookEvents[qn] !== undefined) {
59
+ throw new Error(`${where}("${name}"): already registered in this feature`);
60
+ }
61
+ state.webhookEvents[qn] = {
62
+ qn,
63
+ wireName,
64
+ description: description.trim(),
65
+ payload,
66
+ version,
67
+ };
68
+ return { name: qn, payload, version };
69
+ },
70
+ };
71
+ }
@@ -1,3 +1,4 @@
1
+ import { frameworkErrorHttpStatus } from "./error-codes.js";
1
2
  import { AgentReasons, FrameworkReasons } from "./reasons.js";
2
3
  const DEFAULT_DOCS_BASE_URL = "https://docs.kumiko.rocks";
3
4
  const REASON_SLUG_RE = /^[a-z0-9_.-]+$/;
@@ -6,25 +7,7 @@ const frameworkReasons = new Set([
6
7
  ...Object.values(AgentReasons),
7
8
  ]);
8
9
  // Codes of the built-in error classes: only these have a framework docs page.
9
- const frameworkErrorCodes = new Set([
10
- "validation_error",
11
- "feature_disabled",
12
- "access_denied",
13
- "unauthenticated",
14
- "not_found",
15
- "conflict",
16
- "version_conflict",
17
- "precondition_failed",
18
- "record_locked",
19
- "idempotent_replay",
20
- "unique_violation",
21
- "unprocessable",
22
- "unconfigured",
23
- "internal_error",
24
- "member_read_timeout",
25
- "rate_limited",
26
- "rate_limit_unavailable",
27
- ]);
10
+ const frameworkErrorCodes = new Set(Object.keys(frameworkErrorHttpStatus));
28
11
  function reasonOf(err) {
29
12
  if (!err.details || typeof err.details !== "object")
30
13
  return undefined;
@@ -0,0 +1,20 @@
1
+ export declare const frameworkErrorHttpStatus: {
2
+ readonly validation_error: 400;
3
+ readonly feature_disabled: 403;
4
+ readonly access_denied: 403;
5
+ readonly unauthenticated: 401;
6
+ readonly not_found: 404;
7
+ readonly conflict: 409;
8
+ readonly version_conflict: 409;
9
+ readonly precondition_failed: 409;
10
+ readonly record_locked: 409;
11
+ readonly idempotent_replay: 409;
12
+ readonly unique_violation: 409;
13
+ readonly unprocessable: 422;
14
+ readonly unconfigured: 422;
15
+ readonly internal_error: 500;
16
+ readonly member_read_timeout: 504;
17
+ readonly rate_limited: 429;
18
+ readonly rate_limit_unavailable: 503;
19
+ };
20
+ export type FrameworkErrorCode = keyof typeof frameworkErrorHttpStatus;
@@ -0,0 +1,19 @@
1
+ export const frameworkErrorHttpStatus = {
2
+ validation_error: 400,
3
+ feature_disabled: 403,
4
+ access_denied: 403,
5
+ unauthenticated: 401,
6
+ not_found: 404,
7
+ conflict: 409,
8
+ version_conflict: 409,
9
+ precondition_failed: 409,
10
+ record_locked: 409,
11
+ idempotent_replay: 409,
12
+ unique_violation: 409,
13
+ unprocessable: 422,
14
+ unconfigured: 422,
15
+ internal_error: 500,
16
+ member_read_timeout: 504,
17
+ rate_limited: 429,
18
+ rate_limit_unavailable: 503,
19
+ };
@@ -1,6 +1,8 @@
1
1
  export type { FieldIssue } from "./classes.ts";
2
2
  export { AccessDeniedError, ConflictError, FeatureDisabledError, InternalError, NotFoundError, RateLimitError, UnconfiguredError, UniqueViolationError, UnprocessableError, ValidationError, VersionConflictError, } from "./classes.ts";
3
3
  export type { ErrorDocsConfig } from "./docs-url.ts";
4
+ export type { FrameworkErrorCode } from "./error-codes.ts";
5
+ export { frameworkErrorHttpStatus } from "./error-codes.ts";
4
6
  export { isKumikoError, KumikoError } from "./kumiko-error.ts";
5
7
  export { FrameworkReasons } from "./reasons.ts";
6
8
  export { subjectErasedConflict } from "./subject-erased.ts";
@@ -1,4 +1,5 @@
1
1
  export { AccessDeniedError, ConflictError, FeatureDisabledError, InternalError, NotFoundError, RateLimitError, UnconfiguredError, UniqueViolationError, UnprocessableError, ValidationError, VersionConflictError, } from "./classes.js";
2
+ export { frameworkErrorHttpStatus } from "./error-codes.js";
2
3
  export { isKumikoError, KumikoError } from "./kumiko-error.js";
3
4
  export { FrameworkReasons } from "./reasons.js";
4
5
  export { subjectErasedConflict } from "./subject-erased.js";
@@ -14,6 +14,10 @@ export declare const PROJECTION_DETAIL_ENTITY = "__projection-detail__";
14
14
  export declare const WRITE_FORM_SECTION_ENTITY = "__write-form-section__";
15
15
  export declare function fieldLabelKey(featureName: string, entityName: string, fieldName: string): string;
16
16
  export declare function handlerTitleKey(handlerQn: string): string;
17
+ export declare function handlerDescriptionKey(handlerQn: string): string;
18
+ export declare function webhookEventDescriptionKey(webhookEventQn: string): string;
19
+ /** `fieldPath` is the payload row name as the docs list it, nested fields dotted. */
20
+ export declare function webhookEventFieldKey(webhookEventQn: string, fieldPath: string): string;
17
21
  export declare function handlerFieldLabelKey(handlerQn: string, fieldName: string): string;
18
22
  export declare function booleanFacetOptionKeys(featureName: string, entityName: string, fieldName: string): readonly string[];
19
23
  export declare function selectFacetOptionKey(featureName: string, entityName: string, fieldName: string, value: string): string;
@@ -16,6 +16,21 @@ export function fieldLabelKey(featureName, entityName, fieldName) {
16
16
  export function handlerTitleKey(handlerQn) {
17
17
  return `${handlerQn}:title`;
18
18
  }
19
+ export function handlerDescriptionKey(handlerQn) {
20
+ return `${handlerQn}:description`;
21
+ }
22
+ // `feature:name` becomes `feature:webhook:name`, so the keys never collide with handler keys.
23
+ function webhookEventKeyBase(webhookEventQn) {
24
+ const separator = webhookEventQn.indexOf(":");
25
+ return `${webhookEventQn.slice(0, separator)}:webhook:${webhookEventQn.slice(separator + 1)}`;
26
+ }
27
+ export function webhookEventDescriptionKey(webhookEventQn) {
28
+ return `${webhookEventKeyBase(webhookEventQn)}:description`;
29
+ }
30
+ /** `fieldPath` is the payload row name as the docs list it, nested fields dotted. */
31
+ export function webhookEventFieldKey(webhookEventQn, fieldPath) {
32
+ return `${webhookEventKeyBase(webhookEventQn)}:field:${fieldPath}`;
33
+ }
19
34
  export function handlerFieldLabelKey(handlerQn, fieldName) {
20
35
  return `${handlerQn}:field:${fieldName}`;
21
36
  }
@@ -3,6 +3,7 @@ type ServiceKey = Exclude<keyof ContextServices, "extensions">;
3
3
  export declare const APP_CONTEXT_KEY_ROLES: {
4
4
  readonly redis: "service";
5
5
  readonly cacheSync: "service";
6
+ readonly userLiveSignals: "service";
6
7
  readonly jobRunner: "service";
7
8
  readonly searchAdapter: "service";
8
9
  readonly entityCache: "service";
@@ -3,6 +3,7 @@
3
3
  export const APP_CONTEXT_KEY_ROLES = {
4
4
  redis: "service",
5
5
  cacheSync: "service",
6
+ userLiveSignals: "service",
6
7
  jobRunner: "service",
7
8
  searchAdapter: "service",
8
9
  entityCache: "service",
@@ -3,6 +3,7 @@ import { requestContext } from "../api/request-context.js";
3
3
  import { createFallbackLogger } from "../logging/utils.js";
4
4
  import { createEscapeHatchReporter } from "../observability/escape-hatch-report.js";
5
5
  import { resolveDbSource, } from "./dispatch-shared.js";
6
+ import { createUserLiveSignals } from "./user-live-signals.js";
6
7
  export function resolveHandlerContextScope(input) {
7
8
  const { ctx, type, user, origin, tx, transactionScope } = input;
8
9
  const { registry, appContext: context } = ctx;
@@ -69,8 +70,11 @@ export function buildPreSave(scope, finalContext) {
69
70
  }
70
71
  // Services the dispatcher resolves itself instead of copying from the boot context.
71
72
  export function buildRuntimeServices(scope) {
72
- const { effectiveFeatures, jobRunner, cacheSync } = scope.ctx;
73
+ const { effectiveFeatures, jobRunner, cacheSync, sseBroker } = scope.ctx;
73
74
  return {
75
+ ...(sseBroker && {
76
+ userLiveSignals: createUserLiveSignals(sseBroker, scope.user.tenantId, scope.context.log ?? createFallbackLogger("dispatcher")),
77
+ }),
74
78
  // One resolver for the lifecycle pipeline, MSP runner and ctx.hasFeature.
75
79
  ...(effectiveFeatures && { effectiveFeatures }),
76
80
  ...(cacheSync && { cacheSync }),
@@ -0,0 +1,5 @@
1
+ import type { UserLiveSignals } from "@cosmicdrift/kumiko-types/handlers";
2
+ import type { TenantId } from "@cosmicdrift/kumiko-types/identifiers";
3
+ import type { SseBroker } from "../api/sse-broker.ts";
4
+ import type { Logger } from "../logging/types.ts";
5
+ export declare function createUserLiveSignals(sseBroker: SseBroker, tenantId: TenantId, log: Pick<Logger, "warn">): UserLiveSignals;
@@ -0,0 +1,20 @@
1
+ import { tenantChannel } from "../engine/constants.js";
2
+ // The tenant is fixed to the caller's own: a handler can address users, never another tenant's channel.
3
+ // Frames carry `data.userId` and no aggregateType, so sse-route delivers each only to its addressee.
4
+ export function createUserLiveSignals(sseBroker, tenantId, log) {
5
+ return {
6
+ async push(userIds, signal) {
7
+ await Promise.all([...new Set(userIds)].map(async (userId) => {
8
+ try {
9
+ await sseBroker.pushToChannel(tenantChannel(tenantId), {
10
+ type: signal.type,
11
+ data: { userId, entity: signal.entity, id: signal.id },
12
+ });
13
+ }
14
+ catch (err) {
15
+ log.warn(`live signal "${signal.type}" could not be pushed`, { err });
16
+ }
17
+ }));
18
+ },
19
+ };
20
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cosmicdrift/kumiko-framework",
3
- "version": "0.410.0",
3
+ "version": "0.412.0",
4
4
  "description": "Framework core — engine, pipeline, API, DB, and every other bit that makes Kumiko go.",
5
5
  "license": "MIT",
6
6
  "author": "Marc Frost <marc@cosmicdriftgamestudio.com>",
@@ -203,7 +203,7 @@
203
203
  "./package.json": "./package.json"
204
204
  },
205
205
  "dependencies": {
206
- "@cosmicdrift/kumiko-types": "0.410.0",
206
+ "@cosmicdrift/kumiko-types": "0.412.0",
207
207
  "bullmq": "^5.81.5",
208
208
  "hono": "^4.13.14",
209
209
  "i18next": "^26.5.12",
@@ -225,7 +225,7 @@
225
225
  }
226
226
  },
227
227
  "devDependencies": {
228
- "@cosmicdrift/kumiko-testing": "0.410.0",
228
+ "@cosmicdrift/kumiko-testing": "0.412.0",
229
229
  "bun-types": "^1.4.4",
230
230
  "fflate": "^0.8.3",
231
231
  "meilisearch": "^0.62.0",
package/src/changes.json CHANGED
@@ -1,4 +1,82 @@
1
1
  [
2
+ {
3
+ "version": "0.412.0",
4
+ "type": "fix",
5
+ "title": "readGate.fileOwner counts read-model entities as file owners",
6
+ "detail": "A document whose file is attached to a projection entity (for example a mail attachment owned by `inbound-message`) was invisible to everyone but the framework system user, because only `r.entity` entities were owner candidates. Read-model entities with a file field now count, with the same rules as entities (no parentRef, no readGate, uuid ids, tenant scope, soft delete) plus two fail-closed conditions: the viewer's roles must pass the access rule of the read model's `<source>:detail` query, and the entity must declare `access.read`, since its queries filter rows by hand and the gate can only reproduce `access.read`. A read model without `access.read` never makes a document visible. `ParentVisibilityOption` has the optional `readModelEntities` map (entity and projection table) for this; `resolveTable`, link and parentRef gates are unchanged."
7
+ },
8
+ {
9
+ "version": "0.412.0",
10
+ "type": "fix",
11
+ "title": "Scaleway Key Manager and Transactional Email listed as active sub-processor",
12
+ "detail": "The `KUMIKO_SUB_PROCESSORS` entry \"Platform key custody (Key Manager) and Transactional Email Delivery\" moves from `status: \"planned\"` to `\"active\"` (`addedAt` 2026-11-01), so `getActiveSubProcessors()` and the generated privacy texts name it. Transactional mail of the Kumiko apps now goes through Scaleway TEM; the Brevo entry stays until that account is closed, because Brevo still holds the logs of mail it sent."
13
+ },
14
+ {
15
+ "version": "0.412.0",
16
+ "type": "improvement",
17
+ "title": "entity webhook events need `webhookEvents: true` on the entity",
18
+ "detail": "`<entity>.created`, `.updated` and `.deleted` get a derived webhook contract only for entities that set `webhookEvents: true`, so bundle system entities such as `config-value` or `tenant-secret` can never be released through a token scope. Without the flag the entity has no contract and a scope that lists its events fails at boot, with a message naming the entity and the option. Add `webhookEvents: true` to every entity whose events a scope lists; the field exclusions still apply."
19
+ },
20
+ {
21
+ "version": "0.412.0",
22
+ "type": "improvement",
23
+ "title": "r.defineWebhookEvent takes an optional wireName",
24
+ "detail": "`wireName` is the event name receivers see in the delivered webhook, for example `incident.created` for the contract `publicstatus:incident-created`. It defaults to the unqualified `name`, must not be empty, and is `entity.verb` for derived entity contracts. `WebhookEventContract` and `WebhookEventDef` carry it."
25
+ },
26
+ {
27
+ "version": "0.412.0",
28
+ "type": "improvement",
29
+ "title": "r.defineWebhookEvent declares a public webhook event contract",
30
+ "detail": "`r.defineWebhookEvent({ name, description, payload, version })` registers a contract under `<feature>:<name>`, separate from `r.defineEvent`, so an internal event is never released by accident. `registry.getWebhookEventContract(qn)` also returns the contract derived for an entity event (`ticket.created`, `ticket.updated`, `ticket.deleted`): every payload carries the entity `id`, created adds the releasable fields, updated adds `changes` and `previous`, deleted adds `previous`; `toEntityWebhookPayload(contract, event)` maps a stored entity event (aggregate id plus payload) to that shape and drops everything the contract does not release; personal fields, the CRUD `excludedFields`, money and located timestamp fields and encrypted, write-only or sensitive text fields are left out. `registry.getWebhookEventContracts()` lists the declared ones sorted by name. `parseWebhookPayload(contract, payload)` validates a payload and strips unknown keys. New exports: `WebhookEventContract`, `WebhookEventHandle`, `parseWebhookPayload`, `toEntityWebhookPayload`."
31
+ },
32
+ {
33
+ "version": "0.411.0",
34
+ "type": "fix",
35
+ "title": "Qualified listScreenId and navigate targets survive role projection",
36
+ "detail": "`projectAppSchemaForRoles` looked up `listScreenId` and navigate `screen` by the raw value, so a `<feature>:screen:<id>` reference never matched and the breadcrumb parent was dropped. A qualified reference is now checked against the exact screen it names (never through the short-id index, which could land on another feature's same-named screen and keep a reference to a hidden screen); bare ids still resolve through the short-id index. The original value stays in the projected schema. Applies to all apps."
37
+ },
38
+ {
39
+ "version": "0.411.0",
40
+ "type": "improvement",
41
+ "title": "List table option compactHeader",
42
+ "detail": "`table: { compactHeader: true }` on an entityList, projectionList or relatedList renders the header row in 12px semibold. `ResultTable` takes `compactHeader` too. Wired through the boot validator, `useListTable` and `DataTable` (`compactHeader` prop). Default unchanged."
43
+ },
44
+ {
45
+ "version": "0.411.0",
46
+ "type": "improvement",
47
+ "title": "Edit layout hideRequiredMarker",
48
+ "detail": "`layout: { hideRequiredMarker: true }` on an entityEdit, actionForm or projectionDetail hides the asterisk after required field labels. Default shown."
49
+ },
50
+ {
51
+ "version": "0.411.0",
52
+ "type": "improvement",
53
+ "title": "projectionDetail header actions per tab",
54
+ "detail": "A projectionDetail header action takes `showOnTabs: [\"<tab id>\"]` and is shown only while one of those tabs is active (needs `layout.mode: \"tabs\"`). The boot validator rejects empty lists, unknown tab ids and a missing tabs mode."
55
+ },
56
+ {
57
+ "version": "0.411.0",
58
+ "type": "improvement",
59
+ "title": "Wizard step rail texts and up-next card",
60
+ "detail": "Wizard steps in the rail show the section `subtitle` (opt-in, no fallback to `description`); a completed step shows the value of the new optional `summaryField`. `wizard.aside.finishDescription` adds a finish card with description on the last step. The up-next card shows the next step's `upNextHint`, else `subtitle`, only. Extension sections accept `subtitle`, `description` and `summaryField` too; on an `actionForm`, `summaryField` and `wizard.submitDisabledWhen` may name a field of its `fields` (such a summary shows the raw value unformatted, meant for text and number fields), and `wizard.saveAndCloseOnCreate` also shows \"Save and close\" on the last step next to the submit."
61
+ },
62
+ {
63
+ "version": "0.411.0",
64
+ "type": "improvement",
65
+ "title": "Wizard footer options",
66
+ "detail": "`layout.wizard.saveAndCloseOnCreate` shows \"Save and close\" in create mode. `layout.wizard.submitDisabledWhen` is a field condition that disables the submit buttons and blocks the submit. After a create, extension sections are saved with the id of the new entity. The boot validator rejects these options outside wizard mode and unknown fields. `submitDisabledWhen` is UI-only; enforce the rule in a validation hook."
67
+ },
68
+ {
69
+ "version": "0.411.0",
70
+ "type": "improvement",
71
+ "title": "Wizard step upNextHint",
72
+ "detail": "Fields and extension sections in a wizard accept `upNextHint`; the up-next card shows it under the next step's title, falling back to `subtitle`."
73
+ },
74
+ {
75
+ "version": "0.411.0",
76
+ "type": "fix",
77
+ "title": "Advisory-lock waiters no longer time out",
78
+ "detail": "`withSessionAdvisoryLock` waits for the lock without the pool's statement_timeout (it is reset before the connection returns to the pool). A replica waiting for a peer, for example during boot seeds, no longer crashes with 57014."
79
+ },
2
80
  {
3
81
  "version": "0.410.0",
4
82
  "type": "improvement",