@cosmicdrift/kumiko-bundled-features 0.422.0 → 0.424.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 (117) hide show
  1. package/dist/auth-email-password/handlers/login.write.d.ts +10 -1
  2. package/dist/auth-email-password/handlers/login.write.js +29 -0
  3. package/dist/auth-email-password/index.d.ts +1 -0
  4. package/dist/auth-email-password/index.js +1 -0
  5. package/dist/channel-push/push-channel.d.ts +2 -6
  6. package/dist/document-draft/entity.d.ts +320 -0
  7. package/dist/document-draft/entity.js +98 -0
  8. package/dist/document-draft/feature.d.ts +3 -0
  9. package/dist/document-draft/feature.js +42 -0
  10. package/dist/document-draft/handlers/blocks.query.d.ts +28 -0
  11. package/dist/document-draft/handlers/blocks.query.js +48 -0
  12. package/dist/document-draft/handlers/by-subject.query.d.ts +16 -0
  13. package/dist/document-draft/handlers/by-subject.query.js +42 -0
  14. package/dist/document-draft/handlers/create.write.d.ts +17 -0
  15. package/dist/document-draft/handlers/create.write.js +83 -0
  16. package/dist/document-draft/handlers/discard.write.d.ts +8 -0
  17. package/dist/document-draft/handlers/discard.write.js +27 -0
  18. package/dist/document-draft/handlers/finalize.write.d.ts +21 -0
  19. package/dist/document-draft/handlers/finalize.write.js +73 -0
  20. package/dist/document-draft/handlers/patch.write.d.ts +1420 -0
  21. package/dist/document-draft/handlers/patch.write.js +65 -0
  22. package/dist/document-draft/handlers/revise.write.d.ts +12 -0
  23. package/dist/document-draft/handlers/revise.write.js +39 -0
  24. package/dist/document-draft/handlers/save.write.d.ts +12 -0
  25. package/dist/document-draft/handlers/save.write.js +40 -0
  26. package/dist/document-draft/i18n.d.ts +6 -0
  27. package/dist/document-draft/i18n.js +20 -0
  28. package/dist/document-draft/index.d.ts +5 -0
  29. package/dist/document-draft/index.js +3 -0
  30. package/dist/document-draft/lib.d.ts +13 -0
  31. package/dist/document-draft/lib.js +42 -0
  32. package/dist/document-draft/options.d.ts +35 -0
  33. package/dist/document-draft/options.js +1 -0
  34. package/dist/document-draft/payloads.d.ts +1440 -0
  35. package/dist/document-draft/payloads.js +35 -0
  36. package/dist/document-draft/screens/editor-screen.d.ts +3 -0
  37. package/dist/document-draft/screens/editor-screen.js +13 -0
  38. package/dist/document-draft/user-data.d.ts +13 -0
  39. package/dist/document-draft/user-data.js +43 -0
  40. package/dist/document-draft/web/client-plugin.d.ts +7 -0
  41. package/dist/document-draft/web/client-plugin.js +13 -0
  42. package/dist/document-draft/web/constants.d.ts +41 -0
  43. package/dist/document-draft/web/constants.js +42 -0
  44. package/dist/document-draft/web/editor-screen.d.ts +2 -0
  45. package/dist/document-draft/web/editor-screen.js +181 -0
  46. package/dist/document-draft/web/i18n.d.ts +99 -0
  47. package/dist/document-draft/web/i18n.js +52 -0
  48. package/dist/document-draft/web/index.d.ts +3 -0
  49. package/dist/document-draft/web/index.js +3 -0
  50. package/dist/shared/index.d.ts +1 -0
  51. package/dist/shared/index.js +1 -0
  52. package/dist/shared/subject-scope.d.ts +21 -0
  53. package/dist/signature/feature.js +1 -1
  54. package/dist/signature/handlers/cancel.write.d.ts +1 -1
  55. package/dist/signature/handlers/issue-link.write.d.ts +1 -1
  56. package/dist/signature/handlers/request.write.d.ts +1 -1
  57. package/dist/signature/handlers/revoke-link.write.d.ts +1 -1
  58. package/dist/signature/handlers/sign-in-person.write.d.ts +1 -1
  59. package/dist/signature/options.d.ts +2 -1
  60. package/dist/signature/subject-queries.d.ts +1 -1
  61. package/dist/template-resolver/api.d.ts +3 -1
  62. package/dist/template-resolver/boot-rules.d.ts +5 -0
  63. package/dist/template-resolver/boot-rules.js +5 -0
  64. package/dist/template-resolver/feature.d.ts +2 -0
  65. package/dist/template-resolver/feature.js +15 -1
  66. package/dist/template-resolver/handlers/create-variant.write.d.ts +17 -0
  67. package/dist/template-resolver/handlers/create-variant.write.js +112 -0
  68. package/dist/template-resolver/handlers/document-base.d.ts +1 -0
  69. package/dist/template-resolver/handlers/document-base.js +2 -0
  70. package/dist/template-resolver/handlers/overview.query.d.ts +6 -0
  71. package/dist/template-resolver/handlers/overview.query.js +29 -3
  72. package/dist/template-resolver/handlers/patch-draft.write.js +9 -1
  73. package/dist/template-resolver/handlers/template-write.d.ts +8 -2
  74. package/dist/template-resolver/handlers/template-write.js +87 -12
  75. package/dist/template-resolver/handlers/toggle-status.write.js +26 -5
  76. package/dist/template-resolver/handlers/upsert-tenant.write.js +1 -0
  77. package/dist/template-resolver/handlers/variants.query.d.ts +11 -0
  78. package/dist/template-resolver/handlers/variants.query.js +62 -0
  79. package/dist/template-resolver/i18n.js +1 -0
  80. package/dist/template-resolver/index.d.ts +5 -1
  81. package/dist/template-resolver/index.js +5 -1
  82. package/dist/template-resolver/seeding.d.ts +2 -0
  83. package/dist/template-resolver/seeding.js +12 -1
  84. package/dist/template-resolver/template-delivery-policy.d.ts +13 -4
  85. package/dist/template-resolver/template-delivery-policy.js +38 -2
  86. package/dist/template-resolver/template-edit-policy.d.ts +3 -0
  87. package/dist/template-resolver/template-edit-policy.js +2 -2
  88. package/dist/template-resolver/template-meta.d.ts +1 -0
  89. package/dist/template-resolver/template-meta.js +1 -0
  90. package/dist/template-resolver/template-variants.d.ts +11 -0
  91. package/dist/template-resolver/template-variants.js +43 -0
  92. package/dist/template-resolver/web/document-tiptap-content.js +7 -2
  93. package/dist/template-resolver/web/document-tiptap-toolbar.js +8 -4
  94. package/dist/template-resolver/web/i18n.js +22 -0
  95. package/dist/template-resolver/web/index.d.ts +1 -0
  96. package/dist/template-resolver/web/index.js +1 -0
  97. package/dist/template-resolver/web/qualified-names.d.ts +5 -0
  98. package/dist/template-resolver/web/qualified-names.js +5 -0
  99. package/dist/template-resolver/web/system-placeholders.d.ts +4 -0
  100. package/dist/template-resolver/web/system-placeholders.js +13 -0
  101. package/dist/tenant/handlers/update-member-roles.write.js +1 -1
  102. package/dist/tenant/i18n.js +0 -1
  103. package/dist/tenant-inactivity/constants.d.ts +1 -1
  104. package/dist/tenant-inactivity/constants.js +1 -1
  105. package/dist/tenant-lifecycle/constants.d.ts +1 -1
  106. package/dist/tenant-lifecycle/constants.js +1 -1
  107. package/package.json +27 -11
  108. package/src/channel-push/changes.json +8 -1
  109. package/src/document-draft/changes.json +8 -0
  110. package/src/helpdesk/changes.json +6 -0
  111. package/src/signature/changes.json +6 -0
  112. package/src/template-resolver/changes.json +30 -0
  113. package/src/tenant/changes.json +7 -0
  114. package/src/tenant-inactivity/changes.json +7 -0
  115. package/src/tenant-lifecycle/changes.json +7 -0
  116. package/dist/signature/subject-scope.d.ts +0 -11
  117. /package/dist/{signature → shared}/subject-scope.js +0 -0
@@ -1,5 +1,5 @@
1
1
  import { type AccessRule } from "@cosmicdrift/kumiko-framework/engine";
2
- import type { SubjectScope } from "../subject-scope.ts";
2
+ import type { SubjectScope } from "../../shared/index.ts";
3
3
  export type RequestSignatureData = {
4
4
  readonly requestId: string;
5
5
  readonly signerIds: readonly string[];
@@ -1,5 +1,5 @@
1
1
  import { type AccessRule } from "@cosmicdrift/kumiko-framework/engine";
2
- import type { SubjectScope } from "../subject-scope.ts";
2
+ import type { SubjectScope } from "../../shared/index.ts";
3
3
  export declare function createRevokeLinkHandler(access: AccessRule, scope: SubjectScope): import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<"revoke-link", import("zod").ZodObject<{
4
4
  signerId: import("zod").ZodUUID;
5
5
  }, import("zod/v4/core").$strip>, {
@@ -1,5 +1,5 @@
1
1
  import { type AccessRule } from "@cosmicdrift/kumiko-framework/engine";
2
- import type { SubjectScope } from "../subject-scope.ts";
2
+ import type { SubjectScope } from "../../shared/index.ts";
3
3
  export type SignInPersonData = {
4
4
  readonly requestStatus: string;
5
5
  };
@@ -1,6 +1,7 @@
1
1
  import type { AccessRule, HandlerContext, SessionUser } from "@cosmicdrift/kumiko-framework/engine";
2
2
  import type { RateLimitDeclaration } from "@cosmicdrift/kumiko-types/handlers";
3
3
  import type { PdfOptions } from "../renderer-foundation/index.ts";
4
+ import type { SubjectScopeContext } from "../shared/index.ts";
4
5
  import type { SignatureRetention } from "./entity.ts";
5
6
  export type RenderSignatureHtmlToPdf = (html: string, options?: PdfOptions) => Promise<Uint8Array>;
6
7
  export type SignatureLinkDelivery = {
@@ -18,7 +19,7 @@ export type SignatureSubject = {
18
19
  readonly subjectType: string;
19
20
  readonly subjectId: string;
20
21
  };
21
- export type AuthorizeSignatureSubject = (ctx: HandlerContext, user: SessionUser, subject: SignatureSubject) => Promise<boolean>;
22
+ export type AuthorizeSignatureSubject = (ctx: SubjectScopeContext, user: SessionUser, subject: SignatureSubject) => Promise<boolean>;
22
23
  export type SignatureOptions = {
23
24
  /** How long requests and signers are kept, data-retention keepFor syntax, counted from creation. */
24
25
  readonly retention: SignatureRetention;
@@ -1,5 +1,5 @@
1
1
  import { type QueryHandlerDef } from "@cosmicdrift/kumiko-framework/engine";
2
- import type { SubjectScope } from "./subject-scope.ts";
2
+ import type { SubjectScope } from "../shared/index.ts";
3
3
  export declare function scopeRequestList(base: QueryHandlerDef, scope: SubjectScope, cursorSecret: string): QueryHandlerDef;
4
4
  export declare function scopeRequestDetail(base: QueryHandlerDef, scope: SubjectScope): QueryHandlerDef;
5
5
  export declare function scopeSignerList(base: QueryHandlerDef, scope: SubjectScope): QueryHandlerDef;
@@ -82,7 +82,9 @@ export type TemplateResolverApi = {
82
82
  readonly resolveLayout: (args: ResolveLayoutRequest) => Promise<TemplateResource>;
83
83
  };
84
84
  export declare function createTemplateResolverApi(db: DbRunner | TenantDb, registry: Registry): TemplateResolverApi;
85
- type DeliveredRowKey = Pick<TemplateResourceRow, "tenantId" | "kind" | "slug">;
85
+ type DeliveredRowKey = Pick<TemplateResourceRow, "tenantId" | "kind" | "slug"> & {
86
+ readonly meta?: string | null;
87
+ };
86
88
  export declare function isRowDelivered(db: DbRunner | TenantDb, policy: TemplateDeliveryPolicy, row: DeliveredRowKey): Promise<boolean>;
87
89
  export declare function isRowDeliveredTo(db: DbRunner | TenantDb, policy: TemplateDeliveryPolicy, user: {
88
90
  readonly roles: readonly string[];
@@ -14,4 +14,9 @@ export declare const TEMPLATE_RESOLVER_BOOT_RULES: {
14
14
  readonly summary: "Each tenantEditable entry has a non-empty slug and at least one access role.";
15
15
  readonly fix: "Give the entry a slug and roles.";
16
16
  };
17
+ readonly tenantEditableVariantsNeedPdf: {
18
+ readonly id: "template-resolver/tenant-editable-variants-need-pdf";
19
+ readonly summary: "Only tenantEditable entries of kind document-pdf may set variants.";
20
+ readonly fix: "Remove variants from the entry or change its kind to document-pdf.";
21
+ };
17
22
  };
@@ -14,4 +14,9 @@ export const TEMPLATE_RESOLVER_BOOT_RULES = {
14
14
  summary: "Each tenantEditable entry has a non-empty slug and at least one access role.",
15
15
  fix: "Give the entry a slug and roles.",
16
16
  },
17
+ tenantEditableVariantsNeedPdf: {
18
+ id: "template-resolver/tenant-editable-variants-need-pdf",
19
+ summary: "Only tenantEditable entries of kind document-pdf may set variants.",
20
+ fix: "Remove variants from the entry or change its kind to document-pdf.",
21
+ },
17
22
  };
@@ -44,6 +44,7 @@ export declare function createTemplateResolverFeature(opts?: TemplateResolverOpt
44
44
  applyLayout: import("@cosmicdrift/kumiko-types/handlers").HandlerRef;
45
45
  createLayout: import("@cosmicdrift/kumiko-types/handlers").HandlerRef;
46
46
  publishTemplates: import("@cosmicdrift/kumiko-types/handlers").HandlerRef;
47
+ createVariant: import("@cosmicdrift/kumiko-types/handlers").HandlerRef;
47
48
  };
48
49
  queries: {
49
50
  findById: import("@cosmicdrift/kumiko-types/handlers").HandlerRef;
@@ -62,6 +63,7 @@ export declare function createTemplateResolverFeature(opts?: TemplateResolverOpt
62
63
  documentBlocks: import("@cosmicdrift/kumiko-types/handlers").HandlerRef;
63
64
  exportBundle: import("@cosmicdrift/kumiko-types/handlers").HandlerRef;
64
65
  sendTestStatus: import("@cosmicdrift/kumiko-types/handlers").HandlerRef;
66
+ variants: import("@cosmicdrift/kumiko-types/handlers").HandlerRef;
65
67
  };
66
68
  treeHandle: import("@cosmicdrift/kumiko-types/tree-node").TreeActionsHandle<"template-resolver", {
67
69
  readonly edit: {
@@ -9,6 +9,7 @@ import { makeCollectionListQuery } from "./handlers/collection-list.query.js";
9
9
  import { makeCollectionSetWrite } from "./handlers/collection-set.write.js";
10
10
  import { makeCopyLocaleWrite } from "./handlers/copy-locale.write.js";
11
11
  import { makeCreateLayoutWrite } from "./handlers/create-layout.write.js";
12
+ import { makeCreateVariantWrite } from "./handlers/create-variant.write.js";
12
13
  import { diffToSystemQuery } from "./handlers/diff-to-system.query.js";
13
14
  import { makeDiscardDraftSystemWrite, makeDiscardDraftWrite, } from "./handlers/discard-draft.write.js";
14
15
  import { documentBlocksQuery } from "./handlers/document-blocks.query.js";
@@ -36,8 +37,10 @@ import { upsertSystemWrite } from "./handlers/upsert-system.write.js";
36
37
  import { makeUpsertTenantWrite } from "./handlers/upsert-tenant.write.js";
37
38
  import { makeUsageQuery } from "./handlers/usage.query.js";
38
39
  import { validateQuery } from "./handlers/validate.query.js";
40
+ import { variantsQuery } from "./handlers/variants.query.js";
39
41
  import { TEMPLATE_RESOLVER_I18N } from "./i18n.js";
40
42
  import { templateResourceEntity } from "./table.js";
43
+ import { VARIANT_KIND } from "./template-variants.js";
41
44
  import { userContentEntryEntity } from "./user-content-table.js";
42
45
  import { DEFAULT_COLLECTION_ACCESS, isCollectionRefusedKind } from "./web/constants.js";
43
46
  function assertCollectionKindsAllowed(collections) {
@@ -64,6 +67,11 @@ function assertTenantEditableValid(entries) {
64
67
  message: `template-resolver: tenantEditable entry of kind "${entry.kind}" has an empty slug`,
65
68
  });
66
69
  }
70
+ if (entry.variants === true && entry.kind !== VARIANT_KIND) {
71
+ throw bootRuleError(TEMPLATE_RESOLVER_BOOT_RULES.tenantEditableVariantsNeedPdf, {
72
+ message: `template-resolver: tenantEditable entry "${key}" sets variants, which only document-pdf templates support`,
73
+ });
74
+ }
67
75
  if (entry.access.roles.length === 0) {
68
76
  throw bootRuleError(TEMPLATE_RESOLVER_BOOT_RULES.tenantEditableInvalidEntry, {
69
77
  message: `template-resolver: tenantEditable entry "${entry.kind}/${entry.slug}" has no roles in access`,
@@ -85,7 +93,11 @@ export function createTemplateResolverFeature(opts = {}) {
85
93
  assertTenantEditableValid(tenantEditable);
86
94
  const policy = { tenantEditable };
87
95
  const deliveryPolicy = {
88
- tenantEditable: tenantEditable.map(({ kind, slug }) => ({ kind, slug })),
96
+ tenantEditable: tenantEditable.map(({ kind, slug, variants }) => ({
97
+ kind,
98
+ slug,
99
+ ...(variants === true && { variants }),
100
+ })),
89
101
  collectionKinds: collections
90
102
  .filter((c) => c.ownership !== "user" && c.access !== undefined)
91
103
  .map((c) => c.kind),
@@ -151,6 +163,7 @@ export function createTemplateResolverFeature(opts = {}) {
151
163
  applyLayout: r.writeHandler(makeApplyLayoutWrite(policy)),
152
164
  createLayout: r.writeHandler(makeCreateLayoutWrite(policy)),
153
165
  publishTemplates: r.writeHandler(makePublishTemplatesWrite(policy)),
166
+ createVariant: r.writeHandler(makeCreateVariantWrite(policy)),
154
167
  };
155
168
  const queries = {
156
169
  findById: r.queryHandler(findByIdQuery),
@@ -169,6 +182,7 @@ export function createTemplateResolverFeature(opts = {}) {
169
182
  documentBlocks: r.queryHandler(documentBlocksQuery),
170
183
  exportBundle: r.queryHandler(exportBundleQuery),
171
184
  sendTestStatus: r.queryHandler(makeSendTestStatusQuery(policy)),
185
+ variants: r.queryHandler(variantsQuery),
172
186
  };
173
187
  for (const collection of collections) {
174
188
  r.contentCollection({
@@ -0,0 +1,17 @@
1
+ import * as z from "zod";
2
+ import { type TemplateEditPolicy } from "../template-edit-policy.ts";
3
+ export declare function makeCreateVariantWrite(policy: TemplateEditPolicy): import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<"create-variant", z.ZodObject<{
4
+ baseSlug: z.ZodString;
5
+ name: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodLiteral<"">]>>;
6
+ title: z.ZodString;
7
+ locale: z.ZodDefault<z.ZodString>;
8
+ }, z.core.$strip>, {
9
+ slug: string;
10
+ locale: string;
11
+ kind: "document-pdf";
12
+ title: string;
13
+ base: {
14
+ scope: "tenant";
15
+ version: number;
16
+ };
17
+ }, import("@cosmicdrift/kumiko-types/event-type-map").KumikoEventTypeMap, undefined, undefined>;
@@ -0,0 +1,112 @@
1
+ import { fetchOne } from "@cosmicdrift/kumiko-framework/db";
2
+ import { defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
3
+ import { NotFoundError, ValidationError, writeFailure, } from "@cosmicdrift/kumiko-framework/errors";
4
+ import * as z from "zod";
5
+ import { patchIssue } from "../document-op-blocks.js";
6
+ import { templateResourcesTable } from "../table.js";
7
+ import { refuseTemplateEdit, templateEditAccess, } from "../template-edit-policy.js";
8
+ import { resolveTemplateVariables } from "../template-validation.js";
9
+ import { VARIANT_KIND, variantNameFromTitle, variantNameSchema, variantSlug, } from "../template-variants.js";
10
+ import { FALLBACK_LOCALE } from "../web/constants.js";
11
+ import { TemplateResolverErrors } from "../web/qualified-names.js";
12
+ import { loadDocumentBase } from "./document-base.js";
13
+ import { localeSchema, templateSlugSchema, titleSchema } from "./shared.js";
14
+ import { writeTemplateRow } from "./template-write.js";
15
+ function variantsNotEnabled(policy, baseSlug) {
16
+ const entry = policy.tenantEditable.find((candidate) => candidate.kind === VARIANT_KIND && candidate.slug === baseSlug);
17
+ if (entry?.variants === true)
18
+ return null;
19
+ return writeFailure(new ValidationError({
20
+ fields: [
21
+ patchIssue("baseSlug", TemplateResolverErrors.variantsNotEnabled, { slug: baseSlug }),
22
+ ],
23
+ }));
24
+ }
25
+ function variantNameInvalid() {
26
+ return writeFailure(new ValidationError({
27
+ fields: [patchIssue("name", TemplateResolverErrors.variantNameInvalid)],
28
+ }));
29
+ }
30
+ export function makeCreateVariantWrite(policy) {
31
+ return defineWriteHandler({
32
+ name: "create-variant",
33
+ schema: z.object({
34
+ baseSlug: templateSlugSchema,
35
+ // A form sends an untouched text field as "": same as no name, the title then supplies it.
36
+ name: z.union([variantNameSchema, z.literal("")]).optional(),
37
+ title: titleSchema,
38
+ locale: localeSchema.default(FALLBACK_LOCALE),
39
+ }),
40
+ access: templateEditAccess(policy.tenantEditable),
41
+ agent: { risk: "low", effect: "proposal" },
42
+ description: "Creates a variant of a PDF document template of the caller's tenant (a second version of the same document, e.g. a rental contract for commercial use) as a draft under the slug <baseSlug>:<name> (name is kebab-case, at most 40 characters, and is derived from the title when omitted; locale defaults to de) with the given title. The draft starts as a copy of the base template as the caller sees it (content, variables, linked images and settings including the layout); the variables stay those of the base and cannot be changed on the variant. It fails with variants_not_enabled when the app did not allow variants for the base template (this also applies to a TenantAdmin) and with variant_exists when the tenant already has that slug. Returns the variant slug, locale, kind, title and base ({scope, version}) for the next call. Next steps: change the text with patch-draft (kind document-pdf, the returned slug), then let a person publish it with publish-templates; a variant needs the same required placeholders as its base before it can be published. The variants query lists the published variants of a base.",
43
+ handler: async (event, ctx) => {
44
+ const { baseSlug, title, locale } = event.payload;
45
+ const name = event.payload.name || variantNameFromTitle(title);
46
+ if (!variantNameSchema.safeParse(name).success)
47
+ return variantNameInvalid();
48
+ const refused = refuseTemplateEdit(policy, event.user, {
49
+ slug: baseSlug,
50
+ kind: VARIANT_KIND,
51
+ });
52
+ if (refused !== null)
53
+ return refused;
54
+ const disabled = variantsNotEnabled(policy, baseSlug);
55
+ if (disabled !== null)
56
+ return disabled;
57
+ const slug = variantSlug(baseSlug, name);
58
+ if (!templateSlugSchema.safeParse(slug).success)
59
+ return variantNameInvalid();
60
+ const existing = await fetchOne(ctx.db, templateResourcesTable, {
61
+ tenantId: event.user.tenantId,
62
+ slug,
63
+ kind: VARIANT_KIND,
64
+ locale,
65
+ });
66
+ if (existing !== undefined) {
67
+ return writeFailure(new ValidationError({
68
+ fields: [patchIssue("name", TemplateResolverErrors.variantExists, { slug })],
69
+ }));
70
+ }
71
+ const loaded = await loadDocumentBase(ctx, event.user, {
72
+ slug: baseSlug,
73
+ kind: VARIANT_KIND,
74
+ locale,
75
+ });
76
+ if (loaded === null)
77
+ return writeFailure(new NotFoundError("template-resource", baseSlug));
78
+ const written = await writeTemplateRow({
79
+ linkedResources: loaded.linkedResources ?? "{}",
80
+ ctx,
81
+ user: event.user,
82
+ tenantId: event.user.tenantId,
83
+ scope: "tenant",
84
+ status: "draft",
85
+ variables: resolveTemplateVariables(ctx.registry, slug, loaded.variableSchema),
86
+ payload: {
87
+ slug,
88
+ kind: VARIANT_KIND,
89
+ locale,
90
+ content: loaded.content,
91
+ contentFormat: "html",
92
+ variableSchema: loaded.variableSchema,
93
+ meta: { ...loaded.meta, variantOf: baseSlug },
94
+ title,
95
+ },
96
+ expectedVersion: null,
97
+ });
98
+ if (!written.isSuccess)
99
+ return written;
100
+ return {
101
+ isSuccess: true,
102
+ data: {
103
+ slug,
104
+ locale,
105
+ kind: VARIANT_KIND,
106
+ title,
107
+ base: { scope: "tenant", version: written.data.version },
108
+ },
109
+ };
110
+ },
111
+ });
112
+ }
@@ -15,6 +15,7 @@ export type LoadedDocument = {
15
15
  readonly title: string | null;
16
16
  readonly folder: string | null;
17
17
  readonly parentTemplateId: string | null;
18
+ readonly linkedResources: string | null;
18
19
  };
19
20
  export declare function loadDocumentBase(ctx: HandlerContext, user: SessionUser, where: {
20
21
  readonly slug: string;
@@ -34,6 +34,7 @@ export async function loadDocumentBase(ctx, user, where) {
34
34
  title: working.title,
35
35
  folder: working.folder,
36
36
  parentTemplateId: working.parentTemplateId,
37
+ linkedResources: own.linkedResources,
37
38
  };
38
39
  }
39
40
  const system = await fetchOne(ctx.db, templateResourcesTable, {
@@ -57,5 +58,6 @@ export async function loadDocumentBase(ctx, user, where) {
57
58
  title: system.title,
58
59
  folder: system.folder,
59
60
  parentTemplateId: String(system.id),
61
+ linkedResources: system.linkedResources,
60
62
  };
61
63
  }
@@ -40,6 +40,12 @@ export type OverviewRow = {
40
40
  readonly modifiedAt: string;
41
41
  readonly usedBy: readonly OverviewUsage[];
42
42
  readonly usedByCount: number;
43
+ /** Locale of the row the overview shows (German first); a row action that acts on one locale starts from it. */
44
+ readonly locale: string;
45
+ /** Base slug when this row is a variant of a PDF template. */
46
+ readonly variantOf: string | null;
47
+ /** The app allows variants of this PDF template, so "create variant" applies to the row. */
48
+ readonly variantsEnabled: boolean;
43
49
  /** SystemAdmin only, system-origin rows: tenants overriding this template; total is null without the tenant feature. */
44
50
  readonly overriddenBy?: {
45
51
  readonly active: number;
@@ -8,6 +8,7 @@ import { activeSinceOf, activeVersionOf, draftViewerTenantId, isHiddenSystemDraf
8
8
  import { mayEditTemplate, templateEditAccess, } from "../template-edit-policy.js";
9
9
  import { isSystemOnlyTemplateHiddenFrom } from "../template-system-only.js";
10
10
  import { collectTemplateUsage } from "../template-usage.js";
11
+ import { readVariantOf, VARIANT_KIND } from "../template-variants.js";
11
12
  import { DEFAULT_MAIL_LAYOUT_SLUG, FALLBACK_LOCALE, } from "../web/constants.js";
12
13
  import { TemplateResolverQueries } from "../web/qualified-names.js";
13
14
  import { storedRecord } from "./template-gates.js";
@@ -147,7 +148,15 @@ function versionFieldsOf(user, preferred, groupRows) {
147
148
  systemVersion: systemSameLocale === undefined ? null : activeVersionOf(systemSameLocale),
148
149
  };
149
150
  }
150
- function buildDrafts(groups, user, policy, defaultPdfLayoutSlug) {
151
+ function variantFieldsOf(preferred, variantBaseSlugs) {
152
+ const isPdf = preferred.kind === VARIANT_KIND;
153
+ return {
154
+ locale: preferred.locale,
155
+ variantOf: isPdf ? readVariantOf(storedRecord(preferred.meta)) : null,
156
+ variantsEnabled: isPdf && variantBaseSlugs.has(preferred.slug),
157
+ };
158
+ }
159
+ function buildDrafts(groups, user, policy, defaultPdfLayoutSlug, variantBaseSlugs) {
151
160
  const layoutSlugByDocument = new Map();
152
161
  const drafts = [];
153
162
  for (const [id, groupRows] of groups) {
@@ -180,6 +189,7 @@ function buildDrafts(groups, user, policy, defaultPdfLayoutSlug) {
180
189
  lockedOverrideId: effective.lockedOverrideId,
181
190
  canResetLockedOverride: effective.lockedOverrideId !== null,
182
191
  modifiedAt: modifiedAtOf(preferred),
192
+ ...variantFieldsOf(preferred, variantBaseSlugs),
183
193
  });
184
194
  }
185
195
  return { drafts, layoutSlugByDocument };
@@ -236,6 +246,19 @@ const filterSchema = z.object({
236
246
  op: z.literal("in"),
237
247
  value: z.array(z.string()),
238
248
  });
249
+ // A variant follows its base in the list, so the designer reads them as one group; a variant whose
250
+ // base the filter dropped keeps its sorted place. Slugs repeat across kinds (a mail and a PDF may
251
+ // share one), so only PDF rows count as a base.
252
+ function variantsUnderTheirBase(rows) {
253
+ const isPdfBase = (row) => row.kind === VARIANT_KIND && row.variantOf === null;
254
+ const baseSlugs = new Set(rows.filter(isPdfBase).map((row) => row.slug));
255
+ const isGrouped = (row) => row.variantOf !== null && baseSlugs.has(row.variantOf);
256
+ return rows
257
+ .filter((row) => !isGrouped(row))
258
+ .flatMap((row) => isPdfBase(row)
259
+ ? [row, ...rows.filter((r) => isGrouped(r) && r.variantOf === row.slug)]
260
+ : [row]);
261
+ }
239
262
  export function makeOverviewQuery(policy) {
240
263
  return defineQueryHandler({
241
264
  name: "overview",
@@ -263,7 +286,9 @@ export function makeOverviewQuery(policy) {
263
286
  }
264
287
  const visibleRows = rows.filter((row) => isRowVisibleToCaller(policy, query.user, ctx.registry, row));
265
288
  const deliveryPolicy = deliveryPolicyOf(ctx.registry);
266
- const { drafts, layoutSlugByDocument } = buildDrafts(groupBySlugAndKind(visibleRows), query.user, deliveryPolicy, await defaultPdfLayoutSlug(ctx, query.user.tenantId));
289
+ const { drafts, layoutSlugByDocument } = buildDrafts(groupBySlugAndKind(visibleRows), query.user, deliveryPolicy, await defaultPdfLayoutSlug(ctx, query.user.tenantId), new Set(policy.tenantEditable
290
+ .filter((entry) => entry.kind === VARIANT_KIND && entry.variants === true)
291
+ .map((entry) => entry.slug)));
267
292
  const effectiveLayouts = effectiveMailLayoutSlugs(visibleRows, deliveryPolicy);
268
293
  const rowsWithUsage = drafts.map((draft) => withUsage(draft, layoutSlugByDocument, ctx.registry, effectiveLayouts));
269
294
  const overviewRows = isSystemAdmin(query.user)
@@ -276,9 +301,10 @@ export function makeOverviewQuery(policy) {
276
301
  const sortField = payload.sort !== undefined && isSortField(payload.sort) ? payload.sort : "modifiedAt";
277
302
  const direction = (payload.sortDirection ?? "desc") === "desc" ? -1 : 1;
278
303
  filtered.sort((a, b) => direction * compareBy(sortField, a, b, shownTitle) || a.id.localeCompare(b.id));
304
+ const ordered = variantsUnderTheirBase(filtered);
279
305
  const offset = payload.offset ?? 0;
280
306
  return {
281
- rows: filtered.slice(offset, offset + payload.limit),
307
+ rows: ordered.slice(offset, offset + payload.limit),
282
308
  nextCursor: null,
283
309
  total: filtered.length,
284
310
  truncated,
@@ -1,10 +1,12 @@
1
1
  import { defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
2
2
  import { NotFoundError, ValidationError, VersionConflictError, writeFailure, } from "@cosmicdrift/kumiko-framework/errors";
3
3
  import * as z from "zod";
4
+ import { patchIssue } from "../document-op-blocks.js";
4
5
  import { applyDocumentOps, documentOpsSchema } from "../document-ops.js";
5
6
  import { parseDocumentJson, serializeDocumentJson } from "../document-sanitizer.js";
6
7
  import { refuseTemplateEdit, templateEditAccess, } from "../template-edit-policy.js";
7
8
  import { resolveTemplateVariables } from "../template-validation.js";
9
+ import { readVariantOf } from "../template-variants.js";
8
10
  import { loadDocumentBase } from "./document-base.js";
9
11
  import { contentWithEditedHtml, documentTargetShape, editableHtmlOf, regionIssue, } from "./document-region.js";
10
12
  import { localeSchema, templateSlugSchema } from "./shared.js";
@@ -28,7 +30,7 @@ export function makePatchDraftWrite(policy) {
28
30
  }),
29
31
  access: templateEditAccess(policy.tenantEditable),
30
32
  agent: { risk: "low", effect: "proposal" },
31
- description: 'Changes a mail template, a PDF document template (kind document-pdf) or one region of a PDF layout (kind pdf-layout with region header, signature or footer; a tenant edits its own layouts under the slug tenant-layout-<name>, created with create-layout) with structured operations instead of a full rewrite and saves the result as the caller\'s tenant draft (never published, an active version keeps being served until publish). Never send raw HTML: every block goes through the same checks as the editor. Block forms: paragraph and heading {text} or {runs:[{text,bold,italic,underline,font,sizePt,color,dateStyle (short prints a date placeholder in that run as 15.01.2026, long is the default 15. January 2026; both follow the document locale)}]} with optional align, style {lineHeight,spaceBeforePt,spaceAfterPt} and textStyle {font,sizePt,color}; list {ordered,items:[text or runs]}; table {borders:"none",cellPaddingMm (0 to 10, padding inside every cell),widthMm (0.1 to 210, table width),align:left|center|right (placement of a table narrower than the text area),columnWidthsPx,header:{cells:[{text|runs,background,align}]},rows:[{cells,lineAbove:{color #rrggbb,weightPt 0.25 to 4},lineBelow:{...}}],repeat:{each:<list variable>,row},rowsAfterRepeat:[{cells,lineAbove,lineBelow}]} (a row line is a rule on the top or bottom edge of that row; it beats tableLineColor there and works on the header, repeat and rowsAfterRepeat rows too) (repeat is the row printed once per list entry; header repeats on every page; rowsAfterRepeat are printed once below the repeated rows, e.g. total lines, and need a repeat); a run is {text,bold,italic,underline,font,sizePt,color} or {hardBreak:true}, which starts a new line inside the paragraph or table cell, e.g. a description followed by a small grey second line; frame {xMm,yMm,widthMm,heightMm,preset:address|text,reserveFlow,blocks} only in document-pdf, at the top level (the DIN address window is x20 y45 w85 h45 with preset address); image {resource,alt,widthMm (0.1 to 210, printed width; without it the image keeps its natural size, in a layout region at most 20 mm high),align:left|center|right,bleed (true runs the image from paper edge to paper edge, flush with the top in a header and with the bottom in a footer; only in the header or footer region of a pdf-layout, refused elsewhere with bleed_not_allowed)}; button {text,href} mails only; divider {color #rrggbb,weightPt 0.25 to 4}; pageBreak PDF only. Fonts, sizes, colors (#rrggbb), line spacing, borders, backgrounds and frames are print styling: PDF only, a mail refuses them with print_style_not_allowed. Operations: insertBlock after a block id (null = at the start), replaceBody {blocks} (replaces the whole content, at most 300 blocks including the ones inside frames; read ids no longer apply afterwards), formatBlock {blockId,align,style,textStyle} on a paragraph, heading or list, replaceText inside one block (the text must occur exactly once within one formatting run and cannot contain a {{placeholder}}: a find across a formatting change fails with text_spans_formatting, a find with a placeholder with placeholder_not_replaceable, and the formatting of the replaced text is kept), removeBlock, setResource on an image block, setMeta (flat merge, null removes a key; layout keys are listed with create-layout) and setVariable (adds, replaces or with null removes a variable definition; refused when a notification declares the variables). Block ids and base come from document-blocks and refer to the state that was read; if the template changed since, the call fails with version_conflict and nothing is written. A patch that removes a required placeholder is refused. A TenantAdmin may patch only templates the app lists in tenantEditable, otherwise SystemAdmin only. Returns the written row.',
33
+ description: 'Changes a mail template, a PDF document template (kind document-pdf) or one region of a PDF layout (kind pdf-layout with region header, signature or footer; a tenant edits its own layouts under the slug tenant-layout-<name>, created with create-layout) with structured operations instead of a full rewrite and saves the result as the caller\'s tenant draft (never published, an active version keeps being served until publish). Never send raw HTML: every block goes through the same checks as the editor. Block forms: paragraph and heading {text} or {runs:[{text,bold,italic,underline,font,sizePt,color,dateStyle (short prints a date placeholder in that run as 15.01.2026, long is the default 15. January 2026; both follow the document locale)}]} with optional align, style {lineHeight,spaceBeforePt,spaceAfterPt} and textStyle {font,sizePt,color}; list {ordered,items:[text or runs]}; table {borders:"none",cellPaddingMm (0 to 10, padding inside every cell),widthMm (0.1 to 210, table width),align:left|center|right (placement of a table narrower than the text area),columnWidthsPx,header:{cells:[{text|runs,background,align}]},rows:[{cells,lineAbove:{color #rrggbb,weightPt 0.25 to 4},lineBelow:{...}}],repeat:{each:<list variable>,row},rowsAfterRepeat:[{cells,lineAbove,lineBelow}]} (a row line is a rule on the top or bottom edge of that row; it beats tableLineColor there and works on the header, repeat and rowsAfterRepeat rows too) (repeat is the row printed once per list entry; header repeats on every page; rowsAfterRepeat are printed once below the repeated rows, e.g. total lines, and need a repeat); a run is {text,bold,italic,underline,font,sizePt,color} or {hardBreak:true}, which starts a new line inside the paragraph or table cell, e.g. a description followed by a small grey second line; frame {xMm,yMm,widthMm,heightMm,preset:address|text,reserveFlow,blocks} only in document-pdf, at the top level (the DIN address window is x20 y45 w85 h45 with preset address); image {resource,alt,widthMm (0.1 to 210, printed width; without it the image keeps its natural size, in a layout region at most 20 mm high),align:left|center|right,bleed (true runs the image from paper edge to paper edge, flush with the top in a header and with the bottom in a footer; only in the header or footer region of a pdf-layout, refused elsewhere with bleed_not_allowed)}; button {text,href} mails only; divider {color #rrggbb,weightPt 0.25 to 4}; pageBreak PDF only. Fonts, sizes, colors (#rrggbb), line spacing, borders, backgrounds and frames are print styling: PDF only, a mail refuses them with print_style_not_allowed. Operations: insertBlock after a block id (null = at the start), replaceBody {blocks} (replaces the whole content, at most 300 blocks including the ones inside frames; read ids no longer apply afterwards), formatBlock {blockId,align,style,textStyle} on a paragraph, heading or list, replaceText inside one block (the text must occur exactly once within one formatting run and cannot contain a {{placeholder}}: a find across a formatting change fails with text_spans_formatting, a find with a placeholder with placeholder_not_replaceable, and the formatting of the replaced text is kept), removeBlock, setResource on an image block, setMeta (flat merge, null removes a key; layout keys are listed with create-layout) and setVariable (adds, replaces or with null removes a variable definition; refused when a notification declares the variables and on a variant, which keeps the variables of its base with variables_inherited_from_base; the variantOf setting of a variant cannot be changed). Section titles should be heading blocks, not bold paragraphs: on print a heading stays with the block that follows it instead of ending a page on its own. Block ids and base come from document-blocks and refer to the state that was read; if the template changed since, the call fails with version_conflict and nothing is written. A patch that removes a required placeholder is refused. A TenantAdmin may patch only templates the app lists in tenantEditable, otherwise SystemAdmin only. Returns the written row.',
32
34
  handler: async (event, ctx) => {
33
35
  const { slug, kind, region, locale, base, ops } = event.payload;
34
36
  const misplacedRegion = regionIssue(kind, region);
@@ -57,6 +59,9 @@ export function makePatchDraftWrite(policy) {
57
59
  params: { slug },
58
60
  });
59
61
  }
62
+ if (variableOpIndex !== -1 && readVariantOf(loaded.meta) !== null) {
63
+ return validationFailure(patchIssue(`ops.${variableOpIndex}`, "variables_inherited_from_base", { slug }));
64
+ }
60
65
  const applied = applyDocumentOps({
61
66
  doc: parseDocumentJson(editableHtmlOf(kind, region, loaded.content)),
62
67
  meta: loaded.meta,
@@ -67,6 +72,9 @@ export function makePatchDraftWrite(policy) {
67
72
  });
68
73
  if (!applied.ok)
69
74
  return writeFailure(new ValidationError({ fields: applied.issues }));
75
+ if (readVariantOf(applied.meta) !== readVariantOf(loaded.meta)) {
76
+ return validationFailure(patchIssue("ops", "variant_of_immutable", { slug }));
77
+ }
70
78
  const content = contentWithEditedHtml(kind, region, loaded.content, serializeDocumentJson(applied.doc));
71
79
  const draftOf = (draftContent, meta, variableSchema) => validateTemplateDraft(ctx, event.user, {
72
80
  slug,
@@ -1,7 +1,7 @@
1
- import { type HandlerContext, type Registry, type SessionUser, type TemplateVariables, type TenantId, type WriteResult } from "@cosmicdrift/kumiko-framework/engine";
1
+ import { type HandlerContext, type Registry, type SessionUser, type TemplateVariables, type TenantId, type TenantWriteTarget, type WriteResult } from "@cosmicdrift/kumiko-framework/engine";
2
2
  import { type WriteFailure } from "@cosmicdrift/kumiko-framework/errors";
3
3
  import type { TemplateWriteScope } from "../layout-regions.ts";
4
- import type { TemplateValidation } from "../template-validation.ts";
4
+ import { type TemplateValidation } from "../template-validation.ts";
5
5
  import type { ContentFormat, TemplateKind } from "../web/constants.ts";
6
6
  import { type TemplateWriteInput, type TemplateWriteResult } from "./template-gates.ts";
7
7
  export type TemplateRowPayload = {
@@ -20,6 +20,7 @@ export type WrittenTemplateRow = {
20
20
  readonly id: string;
21
21
  readonly slug: string;
22
22
  readonly isNew: boolean;
23
+ readonly version: number;
23
24
  readonly validation: TemplateValidation | null;
24
25
  };
25
26
  export type TemplateRowWrite = {
@@ -30,6 +31,10 @@ export type TemplateRowWrite = {
30
31
  readonly status: "draft" | "active";
31
32
  readonly variables: TemplateVariables;
32
33
  readonly payload: TemplateRowPayload;
34
+ /** Stored linkedResources JSON for a row that is created; an update never touches them. */
35
+ readonly linkedResources?: string;
36
+ /** The caller typed this schema itself (upsert); a variant then must match its base instead of being re-synced. */
37
+ readonly explicitVariableSchema?: true;
33
38
  /** The row version the edit was made against; null means no own row may exist yet. */
34
39
  readonly expectedVersion?: number | null;
35
40
  };
@@ -45,4 +50,5 @@ export type GatedTemplateWrite = {
45
50
  readonly failure: WriteFailure;
46
51
  };
47
52
  export declare function gateTemplateWrite(input: TemplateWriteInput, status: "draft" | "active"): GatedTemplateWrite;
53
+ export declare function baseVariableSchemaOf(db: TenantWriteTarget["db"], tenantId: string, baseSlug: string, locale: string): Promise<unknown>;
48
54
  export declare function writeTemplateRow(args: TemplateRowWrite): Promise<WriteResult<WrittenTemplateRow>>;