@cosmicdrift/kumiko-bundled-features 0.418.0 → 0.420.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 (129) hide show
  1. package/dist/shared/index.d.ts +1 -0
  2. package/dist/shared/index.js +1 -0
  3. package/dist/shared/tenant-scoped-subject.d.ts +11 -0
  4. package/dist/shared/tenant-scoped-subject.js +18 -0
  5. package/dist/signature/feature.js +1 -1
  6. package/dist/signature/grant.d.ts +1 -1
  7. package/dist/signature/grant.js +7 -12
  8. package/dist/signature/png.js +35 -10
  9. package/dist/template-resolver/api.d.ts +2 -0
  10. package/dist/template-resolver/api.js +11 -7
  11. package/dist/template-resolver/compile-document-body.js +9 -11
  12. package/dist/template-resolver/compile-document-styles.d.ts +3 -0
  13. package/dist/template-resolver/compile-document-styles.js +122 -0
  14. package/dist/template-resolver/document-frames.d.ts +4 -0
  15. package/dist/template-resolver/document-frames.js +56 -0
  16. package/dist/template-resolver/document-op-blocks.d.ts +729 -0
  17. package/dist/template-resolver/document-op-blocks.js +521 -0
  18. package/dist/template-resolver/document-ops.d.ts +2743 -37
  19. package/dist/template-resolver/document-ops.js +128 -106
  20. package/dist/template-resolver/document-print-only.d.ts +11 -0
  21. package/dist/template-resolver/document-print-only.js +47 -0
  22. package/dist/template-resolver/document-sanitizer.d.ts +1 -1
  23. package/dist/template-resolver/document-sanitizer.js +29 -13
  24. package/dist/template-resolver/feature.d.ts +3 -0
  25. package/dist/template-resolver/feature.js +14 -1
  26. package/dist/template-resolver/handlers/apply-layout.write.d.ts +29 -0
  27. package/dist/template-resolver/handlers/apply-layout.write.js +118 -0
  28. package/dist/template-resolver/handlers/create-layout.write.d.ts +15 -0
  29. package/dist/template-resolver/handlers/create-layout.write.js +78 -0
  30. package/dist/template-resolver/handlers/document-base.d.ts +2 -2
  31. package/dist/template-resolver/handlers/document-blocks.query.d.ts +10 -3
  32. package/dist/template-resolver/handlers/document-blocks.query.js +13 -8
  33. package/dist/template-resolver/handlers/document-region.d.ts +19 -0
  34. package/dist/template-resolver/handlers/document-region.js +27 -0
  35. package/dist/template-resolver/handlers/failure-reason.d.ts +2 -0
  36. package/dist/template-resolver/handlers/failure-reason.js +12 -0
  37. package/dist/template-resolver/handlers/import-bundle-system.write.js +4 -0
  38. package/dist/template-resolver/handlers/layout-source.query.d.ts +3 -3
  39. package/dist/template-resolver/handlers/layout-source.query.js +6 -2
  40. package/dist/template-resolver/handlers/overview.query.d.ts +8 -0
  41. package/dist/template-resolver/handlers/overview.query.js +12 -6
  42. package/dist/template-resolver/handlers/patch-draft.write.d.ts +1369 -4
  43. package/dist/template-resolver/handlers/patch-draft.write.js +11 -6
  44. package/dist/template-resolver/handlers/publish-templates.write.d.ts +40 -0
  45. package/dist/template-resolver/handlers/publish-templates.write.js +61 -0
  46. package/dist/template-resolver/handlers/set.write.js +4 -1
  47. package/dist/template-resolver/handlers/template-write.js +7 -2
  48. package/dist/template-resolver/handlers/tenant-settings.d.ts +23 -0
  49. package/dist/template-resolver/handlers/tenant-settings.js +101 -0
  50. package/dist/template-resolver/handlers/toggle-status.write.d.ts +14 -9
  51. package/dist/template-resolver/handlers/toggle-status.write.js +11 -7
  52. package/dist/template-resolver/handlers/upsert-system.write.js +15 -9
  53. package/dist/template-resolver/handlers/usage.query.d.ts +14 -0
  54. package/dist/template-resolver/handlers/usage.query.js +80 -12
  55. package/dist/template-resolver/handlers/validate.query.d.ts +2 -0
  56. package/dist/template-resolver/handlers/validate.query.js +10 -0
  57. package/dist/template-resolver/i18n.js +3 -0
  58. package/dist/template-resolver/index.d.ts +7 -2
  59. package/dist/template-resolver/index.js +6 -2
  60. package/dist/template-resolver/layout-regions.d.ts +4 -5
  61. package/dist/template-resolver/layout-regions.js +38 -11
  62. package/dist/template-resolver/print-document.js +3 -1
  63. package/dist/template-resolver/seeding.js +4 -0
  64. package/dist/template-resolver/template-delivery-policy.d.ts +1 -0
  65. package/dist/template-resolver/template-delivery-policy.js +9 -1
  66. package/dist/template-resolver/template-edit-policy.d.ts +5 -1
  67. package/dist/template-resolver/template-edit-policy.js +29 -1
  68. package/dist/template-resolver/template-meta.d.ts +37 -2
  69. package/dist/template-resolver/template-meta.js +27 -5
  70. package/dist/template-resolver/template-preview.js +22 -10
  71. package/dist/template-resolver/template-validation.js +10 -3
  72. package/dist/template-resolver/web/constants.d.ts +7 -1
  73. package/dist/template-resolver/web/constants.js +21 -1
  74. package/dist/template-resolver/web/document-blocks.d.ts +1 -0
  75. package/dist/template-resolver/web/document-blocks.js +2 -0
  76. package/dist/template-resolver/web/document-editor-extensions.d.ts +9 -1
  77. package/dist/template-resolver/web/document-editor-extensions.js +69 -19
  78. package/dist/template-resolver/web/document-editor-fonts.d.ts +10 -0
  79. package/dist/template-resolver/web/document-editor-fonts.js +13 -0
  80. package/dist/template-resolver/web/document-editor.js +3 -1
  81. package/dist/template-resolver/web/document-fonts.d.ts +4 -0
  82. package/dist/template-resolver/web/document-fonts.js +18 -0
  83. package/dist/template-resolver/web/document-frame-control.d.ts +61 -0
  84. package/dist/template-resolver/web/document-frame-control.js +329 -0
  85. package/dist/template-resolver/web/document-frame-node-view.d.ts +4 -0
  86. package/dist/template-resolver/web/document-frame-node-view.js +173 -0
  87. package/dist/template-resolver/web/document-print-decorations.d.ts +12 -0
  88. package/dist/template-resolver/web/document-print-decorations.js +194 -0
  89. package/dist/template-resolver/web/document-print-defaults.d.ts +14 -0
  90. package/dist/template-resolver/web/document-print-defaults.js +25 -0
  91. package/dist/template-resolver/web/document-print-style.d.ts +150 -0
  92. package/dist/template-resolver/web/document-print-style.js +311 -0
  93. package/dist/template-resolver/web/document-repeat-strip.d.ts +8 -0
  94. package/dist/template-resolver/web/document-repeat-strip.js +54 -0
  95. package/dist/template-resolver/web/document-schema.d.ts +5 -0
  96. package/dist/template-resolver/web/document-schema.js +70 -19
  97. package/dist/template-resolver/web/document-style-css.d.ts +62 -0
  98. package/dist/template-resolver/web/document-style-css.js +140 -0
  99. package/dist/template-resolver/web/document-tiptap-bubble.js +83 -10
  100. package/dist/template-resolver/web/document-tiptap-content.d.ts +2 -1
  101. package/dist/template-resolver/web/document-tiptap-content.js +39 -4
  102. package/dist/template-resolver/web/document-tiptap-context.d.ts +6 -2
  103. package/dist/template-resolver/web/document-tiptap-context.js +2 -1
  104. package/dist/template-resolver/web/document-tiptap-editor.d.ts +1 -1
  105. package/dist/template-resolver/web/document-tiptap-editor.js +13 -5
  106. package/dist/template-resolver/web/document-tiptap-helpers.d.ts +62 -3
  107. package/dist/template-resolver/web/document-tiptap-helpers.js +199 -23
  108. package/dist/template-resolver/web/document-tiptap-toolbar-groups.d.ts +16 -0
  109. package/dist/template-resolver/web/document-tiptap-toolbar-groups.js +127 -6
  110. package/dist/template-resolver/web/document-tiptap-toolbar.js +57 -15
  111. package/dist/template-resolver/web/document-toolbar-blocks.d.ts +17 -0
  112. package/dist/template-resolver/web/i18n.js +21 -0
  113. package/dist/template-resolver/web/index.d.ts +8 -2
  114. package/dist/template-resolver/web/index.js +6 -1
  115. package/dist/template-resolver/web/pdf-constants.d.ts +8 -0
  116. package/dist/template-resolver/web/pdf-constants.js +9 -0
  117. package/dist/template-resolver/web/placeholder-text.d.ts +2 -1
  118. package/dist/template-resolver/web/placeholder-text.js +5 -2
  119. package/dist/template-resolver/web/qualified-names.d.ts +7 -0
  120. package/dist/template-resolver/web/qualified-names.js +6 -0
  121. package/dist/template-resolver/web/use-document-tiptap-model.d.ts +6 -2
  122. package/dist/template-resolver/web/use-document-tiptap-model.js +38 -3
  123. package/dist/tenant/company-config.d.ts +6 -0
  124. package/dist/tenant/company-config.js +41 -0
  125. package/dist/tenant/feature.js +11 -0
  126. package/dist/tenant/i18n.js +14 -0
  127. package/package.json +24 -11
  128. package/src/signature/changes.json +6 -0
  129. package/src/template-resolver/changes.json +62 -0
@@ -1,8 +1,8 @@
1
1
  import { getSchema } from "@tiptap/core";
2
2
  import * as z from "zod";
3
+ import { blockFormatSchema, blockInputSchema, blockNode, countBlocks, FORMATTABLE_NODE_TYPES, formatNode, MAX_BODY_BLOCKS, patchIssue, refusePrintStyling, } from "./document-op-blocks.js";
3
4
  import { toVariableDef } from "./template-validation.js";
4
- import { documentBlocksForKind } from "./web/document-blocks.js";
5
- import { DOCUMENT_TEXT_ALIGNMENTS, documentExtensions, isDocumentPlaceholderHref, isDocumentReferenceName, isDocumentResourceKey, } from "./web/document-schema.js";
5
+ import { documentExtensions, isDocumentReferenceName, isDocumentResourceKey, } from "./web/document-schema.js";
6
6
  import { contentToLine, lineToContent, singleLine } from "./web/placeholder-text.js";
7
7
  export const MAX_DOCUMENT_OPS = 50;
8
8
  // Assigning these keys would reach the prototype of the meta object.
@@ -24,6 +24,8 @@ function blockTypeOf(node) {
24
24
  return eachOf(node) === undefined ? "table" : "repeat";
25
25
  case "resource":
26
26
  return "image";
27
+ case "documentFrame":
28
+ return "frame";
27
29
  default:
28
30
  return null;
29
31
  }
@@ -40,9 +42,15 @@ function eachOf(table) {
40
42
  }
41
43
  return undefined;
42
44
  }
45
+ // A line break reads back as "\n"; writing text collapses it again, so a break is set with runs.
46
+ function lineWithBreaks(content) {
47
+ return (content ?? [])
48
+ .map((node) => (node.type === "hardBreak" ? "\n" : contentToLine([node])))
49
+ .join("");
50
+ }
43
51
  function textLinesOf(node) {
44
52
  if (TEXT_BLOCK_TYPES.has(node.type ?? ""))
45
- return [contentToLine(node.content)];
53
+ return [lineWithBreaks(node.content)];
46
54
  return (node.content ?? []).flatMap(textLinesOf);
47
55
  }
48
56
  const NON_TEXT_BLOCK_TYPES = new Set([
@@ -59,6 +67,24 @@ function setOptionalAttrs(block, node) {
59
67
  if (showIf !== undefined)
60
68
  block.showIf = showIf;
61
69
  }
70
+ function setImagePrintAttrs(block, node) {
71
+ const widthMm = node.attrs?.["widthMm"];
72
+ if (typeof widthMm === "number")
73
+ block.widthMm = widthMm;
74
+ if (node.attrs?.["bleed"] === true)
75
+ block.bleed = true;
76
+ const align = stringAttr(node, "align");
77
+ if (align !== undefined)
78
+ block.align = align;
79
+ }
80
+ function setDividerAttrs(block, node) {
81
+ const color = stringAttr(node, "color");
82
+ if (color !== undefined)
83
+ block.color = color;
84
+ const weightPt = node.attrs?.["weightPt"];
85
+ if (typeof weightPt === "number")
86
+ block.weightPt = weightPt;
87
+ }
62
88
  function setTypeSpecificAttrs(block, node) {
63
89
  const level = node.attrs?.["level"];
64
90
  if (block.type === "heading" && typeof level === "number")
@@ -69,12 +95,32 @@ function setTypeSpecificAttrs(block, node) {
69
95
  const alt = stringAttr(node, "alt");
70
96
  if (block.type === "image" && alt !== undefined)
71
97
  block.alt = alt;
98
+ if (block.type === "image")
99
+ setImagePrintAttrs(block, node);
100
+ if (block.type === "divider")
101
+ setDividerAttrs(block, node);
72
102
  const href = stringAttr(node, "href");
73
103
  if (block.type === "button" && href !== undefined)
74
104
  block.href = href;
75
105
  const each = eachOf(node);
76
106
  if (block.type === "repeat" && each !== undefined)
77
107
  block.each = each;
108
+ if (block.type === "frame")
109
+ block.frame = frameBoxOf(node);
110
+ }
111
+ function numberAttr(node, name) {
112
+ const value = node.attrs?.[name];
113
+ return typeof value === "number" ? value : 0;
114
+ }
115
+ function frameBoxOf(node) {
116
+ const preset = stringAttr(node, "preset");
117
+ return {
118
+ xMm: numberAttr(node, "xMm"),
119
+ yMm: numberAttr(node, "yMm"),
120
+ widthMm: numberAttr(node, "widthMm"),
121
+ heightMm: numberAttr(node, "heightMm"),
122
+ ...(preset === undefined ? {} : { preset }),
123
+ };
78
124
  }
79
125
  function blockOf(node, id) {
80
126
  const type = blockTypeOf(node);
@@ -94,27 +140,6 @@ export function documentBlocksOf(doc) {
94
140
  return (doc.content ?? []).flatMap((node, index) => blockOf(node, documentBlockId(index)) ?? []);
95
141
  }
96
142
  const blockIdSchema = z.string().min(1).max(20);
97
- const singleLineText = z.string().max(2000);
98
- const blockInputSchema = z.discriminatedUnion("type", [
99
- z.object({
100
- type: z.literal("paragraph"),
101
- text: singleLineText,
102
- align: z.enum(DOCUMENT_TEXT_ALIGNMENTS).optional(),
103
- }),
104
- z.object({
105
- type: z.literal("heading"),
106
- level: z.number().int().min(1).max(3),
107
- text: singleLineText,
108
- }),
109
- z.object({
110
- type: z.literal("image"),
111
- resource: z.string().min(1).max(200),
112
- alt: z.string().max(500).optional(),
113
- }),
114
- z.object({ type: z.literal("button"), text: singleLineText, href: z.string().max(300) }),
115
- z.object({ type: z.literal("divider") }),
116
- z.object({ type: z.literal("pageBreak") }),
117
- ]);
118
143
  export const documentOpSchema = z.discriminatedUnion("op", [
119
144
  z.object({
120
145
  op: z.literal("insertBlock"),
@@ -128,6 +153,11 @@ export const documentOpSchema = z.discriminatedUnion("op", [
128
153
  replace: z.string().max(2000),
129
154
  }),
130
155
  z.object({ op: z.literal("removeBlock"), blockId: blockIdSchema }),
156
+ z.object({
157
+ op: z.literal("replaceBody"),
158
+ blocks: z.array(blockInputSchema).min(1).max(MAX_BODY_BLOCKS),
159
+ }),
160
+ blockFormatSchema.extend({ op: z.literal("formatBlock"), blockId: blockIdSchema }),
131
161
  z.object({
132
162
  op: z.literal("setResource"),
133
163
  blockId: blockIdSchema,
@@ -142,15 +172,6 @@ export const documentOpSchema = z.discriminatedUnion("op", [
142
172
  }),
143
173
  ]);
144
174
  export const documentOpsSchema = z.array(documentOpSchema).min(1).max(MAX_DOCUMENT_OPS);
145
- function patchIssue(path, code, params) {
146
- const camel = code.replace(/_([a-z])/g, (_match, letter) => letter.toUpperCase());
147
- return {
148
- path,
149
- code,
150
- i18nKey: `templateResolver.errors.patch.${camel}`,
151
- ...(params === undefined ? {} : { params }),
152
- };
153
- }
154
175
  function textNodesIn(nodes) {
155
176
  return nodes.flatMap((node) => (node.type === "text" ? [node] : textNodesIn(node.content ?? [])));
156
177
  }
@@ -183,55 +204,6 @@ function replaceInContent(content, find, replace) {
183
204
  ];
184
205
  });
185
206
  }
186
- function nodeOfInput(input) {
187
- switch (input.type) {
188
- case "paragraph":
189
- return {
190
- type: "paragraph",
191
- ...(input.align === undefined ? {} : { attrs: { textAlign: input.align } }),
192
- content: lineToContent(singleLine(input.text)),
193
- };
194
- case "heading":
195
- return {
196
- type: "heading",
197
- attrs: { level: input.level },
198
- content: lineToContent(singleLine(input.text)),
199
- };
200
- case "image":
201
- return { type: "resource", attrs: { resource: input.resource, alt: input.alt ?? null } };
202
- case "button":
203
- return {
204
- type: "button",
205
- attrs: { href: input.href },
206
- content: lineToContent(singleLine(input.text)),
207
- };
208
- case "divider":
209
- case "pageBreak":
210
- return { type: input.type };
211
- }
212
- }
213
- const TOOLBAR_BLOCK_OF_INPUT = {
214
- image: "image",
215
- button: "button",
216
- divider: "divider",
217
- pageBreak: "pageBreak",
218
- };
219
- function isBlockAllowed(input, kind) {
220
- if (input.type === "paragraph" || input.type === "heading")
221
- return true;
222
- return documentBlocksForKind(kind).includes(TOOLBAR_BLOCK_OF_INPUT[input.type]);
223
- }
224
- function inputIssue(input, path) {
225
- if (input.type === "image" && !isDocumentResourceKey(input.resource)) {
226
- return patchIssue(`${path}.block.resource`, "invalid_resource_key", {
227
- resource: input.resource,
228
- });
229
- }
230
- if (input.type === "button" && !isDocumentPlaceholderHref(input.href)) {
231
- return patchIssue(`${path}.block.href`, "invalid_button_href", { href: input.href });
232
- }
233
- return null;
234
- }
235
207
  let cachedSchema = null;
236
208
  function documentSchema() {
237
209
  cachedSchema ??= getSchema(documentExtensions);
@@ -254,27 +226,67 @@ function lookupEntry(state, blockId, fieldPath) {
254
226
  return { issue: patchIssue(fieldPath, "block_removed", { blockId }) };
255
227
  return { entry };
256
228
  }
257
- function blockInputIssue(op, path, kind) {
258
- if (!isBlockAllowed(op.block, kind)) {
259
- return patchIssue(`${path}.block.type`, "block_not_allowed", { type: op.block.type, kind });
260
- }
261
- if (op.block.type === "paragraph" &&
262
- op.block.align !== undefined &&
263
- !documentBlocksForKind(kind).includes("align")) {
264
- return patchIssue(`${path}.block.align`, "block_not_allowed", { type: "align", kind });
265
- }
266
- return inputIssue(op.block, path);
229
+ function buildBlocks(state, blocks, pathOf) {
230
+ const ctx = { kind: state.kind, region: state.region, issues: [] };
231
+ const nodes = blocks.map((block, index) => blockNode(ctx, pathOf(index), block));
232
+ nodes.forEach((node, index) => {
233
+ const refused = refusePrintStyling(state.kind, node, pathOf(index));
234
+ if (refused !== null)
235
+ ctx.issues.push(refused);
236
+ });
237
+ return { nodes, issues: ctx.issues };
267
238
  }
268
239
  function insertBlockOp(state, op, path) {
269
240
  const anchor = op.after === null ? null : lookupEntry(state, op.after, `${path}.after`);
270
241
  if (anchor !== null && "issue" in anchor)
271
- return anchor.issue;
272
- const invalid = blockInputIssue(op, path, state.kind);
273
- if (invalid !== null)
274
- return invalid;
242
+ return [anchor.issue];
243
+ const built = buildBlocks(state, [op.block], () => `${path}.block`);
244
+ if (built.issues.length > 0)
245
+ return built.issues;
275
246
  const target = anchor === null ? state.insertedAtStart : anchor.entry.insertedAfter;
276
- target.push(nodeOfInput(op.block));
277
- return null;
247
+ target.push(...built.nodes);
248
+ return [];
249
+ }
250
+ function replaceBodyOp(state, op, path) {
251
+ if (countBlocks(op.blocks) > MAX_BODY_BLOCKS) {
252
+ return [patchIssue(`${path}.blocks`, "too_many_blocks", { max: MAX_BODY_BLOCKS })];
253
+ }
254
+ const built = buildBlocks(state, op.blocks, (index) => `${path}.blocks.${index}`);
255
+ if (built.issues.length > 0)
256
+ return built.issues;
257
+ for (const entry of state.entries.values()) {
258
+ entry.removed = true;
259
+ entry.insertedAfter.length = 0;
260
+ }
261
+ state.insertedAtStart.length = 0;
262
+ state.replacement = built.nodes;
263
+ return [];
264
+ }
265
+ function formatBlockOp(state, op, path) {
266
+ const found = lookupEntry(state, op.blockId, `${path}.blockId`);
267
+ if ("issue" in found)
268
+ return [found.issue];
269
+ const { entry } = found;
270
+ if (op.align === undefined && op.style === undefined && op.textStyle === undefined) {
271
+ return [patchIssue(path, "empty_format")];
272
+ }
273
+ if (!FORMATTABLE_NODE_TYPES.has(entry.node.type ?? "")) {
274
+ return [
275
+ patchIssue(`${path}.blockId`, "block_type_mismatch", {
276
+ expected: "paragraph, heading or list",
277
+ actual: entry.node.type ?? "unknown",
278
+ }),
279
+ ];
280
+ }
281
+ const ctx = { kind: state.kind, issues: [] };
282
+ const formatted = formatNode(ctx, path, entry.node, op);
283
+ const refused = refusePrintStyling(state.kind, formatted, path);
284
+ if (refused !== null)
285
+ ctx.issues.push(refused);
286
+ if (ctx.issues.length > 0)
287
+ return ctx.issues;
288
+ entry.node = formatted;
289
+ return [];
278
290
  }
279
291
  function removeBlockOp(state, op, path) {
280
292
  const found = lookupEntry(state, op.blockId, `${path}.blockId`);
@@ -327,7 +339,7 @@ function setResourceOp(state, op, path) {
327
339
  return patchIssue(`${path}.resource`, "invalid_resource_key", { resource: op.resource });
328
340
  }
329
341
  const alt = op.alt === undefined ? (entry.node.attrs?.["alt"] ?? null) : op.alt;
330
- entry.node = { ...entry.node, attrs: { resource: op.resource, alt } };
342
+ entry.node = { ...entry.node, attrs: { ...entry.node.attrs, resource: op.resource, alt } };
331
343
  return null;
332
344
  }
333
345
  function setMetaOp(state, op, path) {
@@ -362,18 +374,25 @@ function applyOp(state, op, path) {
362
374
  switch (op.op) {
363
375
  case "insertBlock":
364
376
  return insertBlockOp(state, op, path);
377
+ case "replaceBody":
378
+ return replaceBodyOp(state, op, path);
379
+ case "formatBlock":
380
+ return formatBlockOp(state, op, path);
365
381
  case "removeBlock":
366
- return removeBlockOp(state, op, path);
382
+ return singleIssue(removeBlockOp(state, op, path));
367
383
  case "replaceText":
368
- return replaceTextOp(state, op, path);
384
+ return singleIssue(replaceTextOp(state, op, path));
369
385
  case "setResource":
370
- return setResourceOp(state, op, path);
386
+ return singleIssue(setResourceOp(state, op, path));
371
387
  case "setMeta":
372
- return setMetaOp(state, op, path);
388
+ return singleIssue(setMetaOp(state, op, path));
373
389
  case "setVariable":
374
- return setVariableOp(state, op, path);
390
+ return singleIssue(setVariableOp(state, op, path));
375
391
  }
376
392
  }
393
+ function singleIssue(issue) {
394
+ return issue === null ? [] : [issue];
395
+ }
377
396
  // Ops address blocks by the ids of the document as it was read, so inserted blocks are
378
397
  // collected per anchor and the list is assembled once at the end.
379
398
  export function applyDocumentOps(input) {
@@ -387,17 +406,20 @@ export function applyDocumentOps(input) {
387
406
  });
388
407
  const state = {
389
408
  kind: input.kind,
409
+ region: input.region,
410
+ replacement: null,
390
411
  entries,
391
412
  insertedAtStart: [],
392
413
  meta: { ...input.meta },
393
414
  variableSchema: { ...input.variableSchema },
394
415
  };
395
- const issues = input.ops.flatMap((op, index) => applyOp(state, op, `ops.${index}`) ?? []);
416
+ const issues = input.ops.flatMap((op, index) => applyOp(state, op, `ops.${index}`));
396
417
  if (issues.length > 0)
397
418
  return { ok: false, issues };
398
419
  const content = [
399
420
  ...state.insertedAtStart,
400
- ...[...entries.values()].flatMap((entry) => entry.removed ? entry.insertedAfter : [entry.node, ...entry.insertedAfter]),
421
+ ...(state.replacement ??
422
+ [...entries.values()].flatMap((entry) => entry.removed ? entry.insertedAfter : [entry.node, ...entry.insertedAfter])),
401
423
  ];
402
424
  const doc = { ...input.doc, content };
403
425
  if (!isValidDocument(doc))
@@ -0,0 +1,11 @@
1
+ import type { Element as ScanElement } from "happy-dom";
2
+ export declare const IMAGES_BLOCK_SELECTOR = "div[data-images]";
3
+ export declare const PRINT_STYLE_SELECTORS: readonly ["div[data-frame]", "span[data-text-style]", "[data-line-height]", "[data-space-before]", "[data-space-after]", "table[data-borders]", "table[data-cell-padding-mm]", "table[data-table-width-mm]", "table[data-table-align]", "tr[data-line-above]", "tr[data-line-below]", "[data-background]", "[data-colwidth]", "img[data-bleed]", "img[data-width-mm]", "img[data-align]", "hr[data-color]", "hr[data-weight-pt]"];
4
+ export type PrintOnlyFeatures = {
5
+ readonly hasImagesBlock: boolean;
6
+ readonly printStyleSelectors: readonly string[];
7
+ };
8
+ export declare function scanPrintOnlyFeatures(body: ScanElement): PrintOnlyFeatures;
9
+ export declare function hasNestedFrame(body: ScanElement): boolean;
10
+ export declare function framesOutsidePage(body: ScanElement): string[];
11
+ export declare function hasFrame(body: ScanElement): boolean;
@@ -0,0 +1,47 @@
1
+ import { readFrameAttributes } from "./web/document-print-style.js";
2
+ import { PDF_MAX_PAGE_EDGE_MM } from "./web/pdf-constants.js";
3
+ export const IMAGES_BLOCK_SELECTOR = "div[data-images]";
4
+ export const PRINT_STYLE_SELECTORS = [
5
+ "div[data-frame]",
6
+ "span[data-text-style]",
7
+ "[data-line-height]",
8
+ "[data-space-before]",
9
+ "[data-space-after]",
10
+ "table[data-borders]",
11
+ "table[data-cell-padding-mm]",
12
+ "table[data-table-width-mm]",
13
+ "table[data-table-align]",
14
+ "tr[data-line-above]",
15
+ "tr[data-line-below]",
16
+ "[data-background]",
17
+ "[data-colwidth]",
18
+ "img[data-bleed]",
19
+ "img[data-width-mm]",
20
+ "img[data-align]",
21
+ "hr[data-color]",
22
+ "hr[data-weight-pt]",
23
+ ];
24
+ export function scanPrintOnlyFeatures(body) {
25
+ return {
26
+ hasImagesBlock: body.querySelector(IMAGES_BLOCK_SELECTOR) !== null,
27
+ printStyleSelectors: PRINT_STYLE_SELECTORS.filter((selector) => body.querySelector(selector) !== null),
28
+ };
29
+ }
30
+ export function hasNestedFrame(body) {
31
+ return Array.from(body.querySelectorAll("div[data-frame]")).some((frame) => frame.parentElement !== body);
32
+ }
33
+ export function framesOutsidePage(body) {
34
+ return Array.from(body.querySelectorAll("div[data-frame]")).flatMap((element) => {
35
+ const frame = readFrameAttributes(element);
36
+ if (frame === null)
37
+ return [];
38
+ const overshootsPage = frame.xMm + frame.widthMm > PDF_MAX_PAGE_EDGE_MM ||
39
+ frame.yMm + frame.heightMm > PDF_MAX_PAGE_EDGE_MM;
40
+ return overshootsPage
41
+ ? [`${frame.xMm}/${frame.yMm} ${frame.widthMm}x${frame.heightMm} mm`]
42
+ : [];
43
+ });
44
+ }
45
+ export function hasFrame(body) {
46
+ return body.querySelector("div[data-frame]") !== null;
47
+ }
@@ -2,7 +2,7 @@ import type { FieldIssue } from "@cosmicdrift/kumiko-framework/errors";
2
2
  import type { JSONContent } from "@tiptap/core";
3
3
  import { type Element as ScanElement } from "happy-dom";
4
4
  import type { ContentFormat } from "./web/constants.ts";
5
- export type DocumentViolationCode = "script_element" | "event_handler_attribute" | "disallowed_link_href" | "relative_link_without_base" | "external_image_source" | "image_without_resource" | "invalid_reference_name" | "embedded_content" | "unsafe_attribute_value" | "images_block_pdf_only" | "button_href_not_placeholder" | "document_requires_html_format" | "layout_requires_mjml_format" | "layout_invalid_structure" | "layout_missing_content_slot" | "layout_source_system_only";
5
+ export type DocumentViolationCode = "script_element" | "event_handler_attribute" | "disallowed_link_href" | "relative_link_without_base" | "external_image_source" | "image_without_resource" | "invalid_reference_name" | "embedded_content" | "unsafe_attribute_value" | "images_block_pdf_only" | "print_style_pdf_only" | "frame_not_top_level" | "frame_outside_page" | "button_href_not_placeholder" | "document_requires_html_format" | "layout_requires_mjml_format" | "layout_invalid_structure" | "layout_missing_content_slot" | "layout_source_system_only";
6
6
  export type DocumentViolation = {
7
7
  readonly code: DocumentViolationCode;
8
8
  readonly detail: string;
@@ -1,9 +1,11 @@
1
1
  import { isOneOf } from "@cosmicdrift/kumiko-types/type-guards";
2
2
  import { generateHTML, generateJSON } from "@tiptap/html/server";
3
3
  import { Window } from "happy-dom";
4
+ import { framesOutsidePage, hasNestedFrame, scanPrintOnlyFeatures } from "./document-print-only.js";
4
5
  import { DOCUMENT_HTML_KINDS } from "./web/constants.js";
5
6
  import { DOCUMENT_CONDITION_ATTRIBUTE, documentExtensions, isAllowedDocumentLinkHref, isAllowedDocumentUrlHref, isDocumentPlaceholderHref, isDocumentReferenceName, isDocumentResourceKey, } from "./web/document-schema.js";
6
7
  import { isDocumentStepKey } from "./web/document-steps.js";
8
+ import { PDF_MAX_PAGE_EDGE_MM } from "./web/pdf-constants.js";
7
9
  export function violation(code, detail, message) {
8
10
  return { code, detail, message };
9
11
  }
@@ -143,6 +145,12 @@ function scanDocumentHtml(html) {
143
145
  for (const element of [body, ...Array.from(body.querySelectorAll("*"))]) {
144
146
  scanElement(element, violations);
145
147
  }
148
+ if (hasNestedFrame(body)) {
149
+ violations.push(violation("frame_not_top_level", "div[data-frame]", "A frame must sit directly in the document body, not inside another block"));
150
+ }
151
+ for (const box of framesOutsidePage(body)) {
152
+ violations.push(violation("frame_outside_page", box, `A frame (${box}) must lie within the largest supported paper size (${PDF_MAX_PAGE_EDGE_MM} mm)`));
153
+ }
146
154
  });
147
155
  return violations;
148
156
  }
@@ -187,20 +195,25 @@ function requiredFormatViolation(kind, contentFormat) {
187
195
  }
188
196
  return null;
189
197
  }
190
- const IMAGES_BLOCK_KIND = "document-pdf";
191
- // The node is part of the shared document model, so a mail body would keep it after the
192
- // rebuild; only a PDF resolves the record's images.
193
- function imagesBlockViolation(input) {
194
- if (input.kind === IMAGES_BLOCK_KIND ||
198
+ const PDF_ONLY_KIND = "document-pdf";
199
+ // These nodes and attributes are part of the shared document model, so a mail body would keep
200
+ // them after the rebuild; only a PDF resolves the record's images and applies print styling.
201
+ function pdfOnlyViolations(input) {
202
+ if (input.kind === PDF_ONLY_KIND ||
195
203
  !isSanitizedBody(input) ||
196
204
  input.contentFormat !== "html" ||
197
205
  input.content === null) {
198
- return null;
206
+ return [];
199
207
  }
200
- const hasImagesBlock = withParsedDocument(input.content, (body) => body.querySelector("div[data-images]") !== null);
201
- return hasImagesBlock
202
- ? violation("images_block_pdf_only", input.kind, `Record images blocks are only allowed in templates of kind ${IMAGES_BLOCK_KIND}`)
203
- : null;
208
+ const found = withParsedDocument(input.content, scanPrintOnlyFeatures);
209
+ return [
210
+ ...(found.hasImagesBlock
211
+ ? [
212
+ violation("images_block_pdf_only", input.kind, `Record images blocks are only allowed in templates of kind ${PDF_ONLY_KIND}`),
213
+ ]
214
+ : []),
215
+ ...found.printStyleSelectors.map((selector) => violation("print_style_pdf_only", selector, `Print styling (${selector}) is only allowed in templates of kind ${PDF_ONLY_KIND}`)),
216
+ ];
204
217
  }
205
218
  // Mails and PDFs have no base address, so compileDocumentBody turns a relative href into "#"; refuse it
206
219
  // on save instead of losing the admin's input silently. Managed pages resolve it against their host.
@@ -218,9 +231,9 @@ export function sanitizeTemplateBody(input) {
218
231
  const formatViolation = requiredFormatViolation(input.kind, input.contentFormat);
219
232
  if (formatViolation !== null)
220
233
  return { ok: false, violations: [formatViolation] };
221
- const imagesViolation = imagesBlockViolation(input);
222
- if (imagesViolation !== null)
223
- return { ok: false, violations: [imagesViolation] };
234
+ const pdfOnly = pdfOnlyViolations(input);
235
+ if (pdfOnly.length > 0)
236
+ return { ok: false, violations: pdfOnly };
224
237
  if (!isSanitizedBody(input) || input.contentFormat !== "html" || input.content === null) {
225
238
  return { ok: true, content: input.content };
226
239
  }
@@ -243,6 +256,9 @@ const VIOLATION_I18N_KEYS = {
243
256
  embedded_content: "templateResolver.errors.document.embeddedContent",
244
257
  unsafe_attribute_value: "templateResolver.errors.document.unsafeAttributeValue",
245
258
  images_block_pdf_only: "templateResolver.errors.document.imagesBlockPdfOnly",
259
+ print_style_pdf_only: "templateResolver.errors.document.printStylePdfOnly",
260
+ frame_not_top_level: "templateResolver.errors.document.frameNotTopLevel",
261
+ frame_outside_page: "templateResolver.errors.document.frameOutsidePage",
246
262
  button_href_not_placeholder: "templateResolver.errors.document.buttonHrefNotPlaceholder",
247
263
  document_requires_html_format: "templateResolver.errors.document.documentRequiresHtmlFormat",
248
264
  layout_requires_mjml_format: "templateResolver.errors.document.layoutRequiresMjmlFormat",
@@ -41,6 +41,9 @@ export declare function createTemplateResolverFeature(opts?: TemplateResolverOpt
41
41
  resourceLinkPdf: import("@cosmicdrift/kumiko-types/handlers").HandlerRef;
42
42
  sendTest: import("@cosmicdrift/kumiko-types/handlers").HandlerRef;
43
43
  patchDraft: import("@cosmicdrift/kumiko-types/handlers").HandlerRef;
44
+ applyLayout: import("@cosmicdrift/kumiko-types/handlers").HandlerRef;
45
+ createLayout: import("@cosmicdrift/kumiko-types/handlers").HandlerRef;
46
+ publishTemplates: import("@cosmicdrift/kumiko-types/handlers").HandlerRef;
44
47
  };
45
48
  queries: {
46
49
  findById: import("@cosmicdrift/kumiko-types/handlers").HandlerRef;
@@ -1,5 +1,6 @@
1
- import { bootRuleError, createSystemConfig, defineFeature, } from "@cosmicdrift/kumiko-framework/engine";
1
+ import { bootRuleError, createSystemConfig, createTenantConfig, defineFeature, } from "@cosmicdrift/kumiko-framework/engine";
2
2
  import { TEMPLATE_RESOLVER_BOOT_RULES } from "./boot-rules.js";
3
+ import { makeApplyLayoutWrite } from "./handlers/apply-layout.write.js";
3
4
  import { makeBodyPreviewQuery } from "./handlers/body-preview.query.js";
4
5
  import { bySlugQuery } from "./handlers/by-slug.query.js";
5
6
  import { byTenantQuery } from "./handlers/by-tenant.query.js";
@@ -7,6 +8,7 @@ import { makeCollectionItemQuery } from "./handlers/collection-item.query.js";
7
8
  import { makeCollectionListQuery } from "./handlers/collection-list.query.js";
8
9
  import { makeCollectionSetWrite } from "./handlers/collection-set.write.js";
9
10
  import { makeCopyLocaleWrite } from "./handlers/copy-locale.write.js";
11
+ import { makeCreateLayoutWrite } from "./handlers/create-layout.write.js";
10
12
  import { diffToSystemQuery } from "./handlers/diff-to-system.query.js";
11
13
  import { makeDiscardDraftSystemWrite, makeDiscardDraftWrite, } from "./handlers/discard-draft.write.js";
12
14
  import { documentBlocksQuery } from "./handlers/document-blocks.query.js";
@@ -19,6 +21,7 @@ import { listQuery } from "./handlers/list.query.js";
19
21
  import { makeOverviewQuery } from "./handlers/overview.query.js";
20
22
  import { makePatchDraftWrite } from "./handlers/patch-draft.write.js";
21
23
  import { previewQuery } from "./handlers/preview.query.js";
24
+ import { makePublishTemplatesWrite } from "./handlers/publish-templates.write.js";
22
25
  import { makeResetToSystemWrite } from "./handlers/reset-to-system.write.js";
23
26
  import { makeResourceLinkPdfWrite } from "./handlers/resource-link-pdf.write.js";
24
27
  import { makeResourceRemoveWrite } from "./handlers/resource-remove.write.js";
@@ -109,6 +112,13 @@ export function createTemplateResolverFeature(opts = {}) {
109
112
  r.config({
110
113
  keys: {
111
114
  resourceMaxBytes: createSystemConfig("number", { default: 2_097_152, bounds: { min: 1 } }),
115
+ // Empty means the built-in default layout.
116
+ defaultPdfLayoutSlug: createTenantConfig("text", {
117
+ default: "",
118
+ pattern: {
119
+ regex: "^(?:[a-z0-9]{1,40}(?:-[a-z0-9]{1,40}){0,5}(?::[a-z0-9]{1,40}(?:-[a-z0-9]{1,40}){0,5}){0,3})?$",
120
+ },
121
+ }),
112
122
  },
113
123
  });
114
124
  r.translations({ keys: TEMPLATE_RESOLVER_I18N });
@@ -138,6 +148,9 @@ export function createTemplateResolverFeature(opts = {}) {
138
148
  resourceLinkPdf: r.writeHandler(makeResourceLinkPdfWrite(policy)),
139
149
  sendTest: r.writeHandler(makeSendTestWrite(policy)),
140
150
  patchDraft: r.writeHandler(makePatchDraftWrite(policy)),
151
+ applyLayout: r.writeHandler(makeApplyLayoutWrite(policy)),
152
+ createLayout: r.writeHandler(makeCreateLayoutWrite(policy)),
153
+ publishTemplates: r.writeHandler(makePublishTemplatesWrite(policy)),
141
154
  };
142
155
  const queries = {
143
156
  findById: r.queryHandler(findByIdQuery),
@@ -0,0 +1,29 @@
1
+ import * as z from "zod";
2
+ import { type TemplateEditPolicy } from "../template-edit-policy.ts";
3
+ declare const templateRefSchema: z.ZodObject<{
4
+ slug: z.ZodString;
5
+ locale: z.ZodString;
6
+ }, z.core.$strip>;
7
+ type TemplateRef = z.infer<typeof templateRefSchema>;
8
+ type SkippedTemplate = TemplateRef & {
9
+ readonly reason: string;
10
+ };
11
+ export declare function makeApplyLayoutWrite(policy: TemplateEditPolicy): import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<"apply-layout", z.ZodObject<{
12
+ layoutSlug: z.ZodString;
13
+ target: z.ZodDiscriminatedUnion<[z.ZodObject<{
14
+ mode: z.ZodLiteral<"all">;
15
+ }, z.core.$strip>, z.ZodObject<{
16
+ mode: z.ZodLiteral<"selected">;
17
+ templates: z.ZodArray<z.ZodObject<{
18
+ slug: z.ZodString;
19
+ locale: z.ZodString;
20
+ }, z.core.$strip>>;
21
+ }, z.core.$strip>], "mode">;
22
+ }, z.core.$strip>, {
23
+ applied: {
24
+ slug: string;
25
+ locale: string;
26
+ }[];
27
+ skipped: SkippedTemplate[];
28
+ }, import("@cosmicdrift/kumiko-types/event-type-map").KumikoEventTypeMap, undefined, undefined>;
29
+ export {};