@cosmicdrift/kumiko-samples 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 (90) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +11 -1
  3. package/packages/bundled-features/src/shared/index.ts +6 -0
  4. package/packages/bundled-features/src/shared/tenant-scoped-subject.ts +28 -0
  5. package/packages/bundled-features/src/signature/changes.json +6 -0
  6. package/packages/bundled-features/src/signature/feature.ts +1 -1
  7. package/packages/bundled-features/src/signature/grant.ts +13 -14
  8. package/packages/bundled-features/src/signature/png.ts +33 -12
  9. package/packages/bundled-features/src/template-resolver/api.ts +17 -7
  10. package/packages/bundled-features/src/template-resolver/changes.json +62 -0
  11. package/packages/bundled-features/src/template-resolver/compile-document-body.ts +10 -9
  12. package/packages/bundled-features/src/template-resolver/compile-document-styles.ts +170 -0
  13. package/packages/bundled-features/src/template-resolver/document-frames.ts +68 -0
  14. package/packages/bundled-features/src/template-resolver/document-op-blocks.ts +682 -0
  15. package/packages/bundled-features/src/template-resolver/document-ops.ts +170 -128
  16. package/packages/bundled-features/src/template-resolver/document-print-only.ts +65 -0
  17. package/packages/bundled-features/src/template-resolver/document-sanitizer.ts +53 -19
  18. package/packages/bundled-features/src/template-resolver/feature.ts +15 -0
  19. package/packages/bundled-features/src/template-resolver/handlers/apply-layout.write.ts +137 -0
  20. package/packages/bundled-features/src/template-resolver/handlers/create-layout.write.ts +87 -0
  21. package/packages/bundled-features/src/template-resolver/handlers/document-base.ts +2 -2
  22. package/packages/bundled-features/src/template-resolver/handlers/document-blocks.query.ts +13 -8
  23. package/packages/bundled-features/src/template-resolver/handlers/document-region.ts +47 -0
  24. package/packages/bundled-features/src/template-resolver/handlers/failure-reason.ts +13 -0
  25. package/packages/bundled-features/src/template-resolver/handlers/import-bundle-system.write.ts +3 -0
  26. package/packages/bundled-features/src/template-resolver/handlers/layout-source.query.ts +17 -5
  27. package/packages/bundled-features/src/template-resolver/handlers/overview.query.ts +16 -4
  28. package/packages/bundled-features/src/template-resolver/handlers/patch-draft.write.ts +20 -6
  29. package/packages/bundled-features/src/template-resolver/handlers/publish-templates.write.ts +69 -0
  30. package/packages/bundled-features/src/template-resolver/handlers/set.write.ts +7 -0
  31. package/packages/bundled-features/src/template-resolver/handlers/template-write.ts +15 -3
  32. package/packages/bundled-features/src/template-resolver/handlers/tenant-settings.ts +159 -0
  33. package/packages/bundled-features/src/template-resolver/handlers/toggle-status.write.ts +25 -10
  34. package/packages/bundled-features/src/template-resolver/handlers/upsert-system.write.ts +7 -3
  35. package/packages/bundled-features/src/template-resolver/handlers/usage.query.ts +131 -18
  36. package/packages/bundled-features/src/template-resolver/handlers/validate.query.ts +10 -0
  37. package/packages/bundled-features/src/template-resolver/i18n.ts +3 -0
  38. package/packages/bundled-features/src/template-resolver/index.ts +39 -0
  39. package/packages/bundled-features/src/template-resolver/layout-regions.ts +54 -16
  40. package/packages/bundled-features/src/template-resolver/print-document.ts +3 -1
  41. package/packages/bundled-features/src/template-resolver/seeding.ts +4 -0
  42. package/packages/bundled-features/src/template-resolver/template-delivery-policy.ts +11 -1
  43. package/packages/bundled-features/src/template-resolver/template-edit-policy.ts +37 -1
  44. package/packages/bundled-features/src/template-resolver/template-meta.ts +31 -6
  45. package/packages/bundled-features/src/template-resolver/template-preview.ts +29 -9
  46. package/packages/bundled-features/src/template-resolver/template-validation.ts +10 -3
  47. package/packages/bundled-features/src/template-resolver/web/constants.ts +33 -0
  48. package/packages/bundled-features/src/template-resolver/web/document-blocks.ts +5 -0
  49. package/packages/bundled-features/src/template-resolver/web/document-editor-extensions.ts +93 -25
  50. package/packages/bundled-features/src/template-resolver/web/document-editor-fonts.ts +13 -0
  51. package/packages/bundled-features/src/template-resolver/web/document-editor.tsx +4 -1
  52. package/packages/bundled-features/src/template-resolver/web/document-fonts.ts +21 -0
  53. package/packages/bundled-features/src/template-resolver/web/document-frame-control.ts +428 -0
  54. package/packages/bundled-features/src/template-resolver/web/document-frame-node-view.tsx +207 -0
  55. package/packages/bundled-features/src/template-resolver/web/document-print-decorations.ts +246 -0
  56. package/packages/bundled-features/src/template-resolver/web/document-print-defaults.ts +59 -0
  57. package/packages/bundled-features/src/template-resolver/web/document-print-style.ts +381 -0
  58. package/packages/bundled-features/src/template-resolver/web/document-repeat-strip.ts +80 -0
  59. package/packages/bundled-features/src/template-resolver/web/document-schema.ts +87 -19
  60. package/packages/bundled-features/src/template-resolver/web/document-style-css.ts +214 -0
  61. package/packages/bundled-features/src/template-resolver/web/document-tiptap-bubble.tsx +185 -16
  62. package/packages/bundled-features/src/template-resolver/web/document-tiptap-content.tsx +70 -7
  63. package/packages/bundled-features/src/template-resolver/web/document-tiptap-context.ts +13 -1
  64. package/packages/bundled-features/src/template-resolver/web/document-tiptap-editor.tsx +25 -4
  65. package/packages/bundled-features/src/template-resolver/web/document-tiptap-helpers.ts +276 -23
  66. package/packages/bundled-features/src/template-resolver/web/document-tiptap-toolbar-groups.tsx +449 -10
  67. package/packages/bundled-features/src/template-resolver/web/document-tiptap-toolbar.tsx +108 -17
  68. package/packages/bundled-features/src/template-resolver/web/document-toolbar-blocks.ts +20 -0
  69. package/packages/bundled-features/src/template-resolver/web/fontsource-css.d.ts +2 -0
  70. package/packages/bundled-features/src/template-resolver/web/i18n.ts +32 -0
  71. package/packages/bundled-features/src/template-resolver/web/index.ts +38 -0
  72. package/packages/bundled-features/src/template-resolver/web/pdf-constants.ts +16 -0
  73. package/packages/bundled-features/src/template-resolver/web/placeholder-text.ts +6 -3
  74. package/packages/bundled-features/src/template-resolver/web/qualified-names.ts +7 -0
  75. package/packages/bundled-features/src/template-resolver/web/use-document-tiptap-model.ts +74 -5
  76. package/packages/bundled-features/src/tenant/company-config.ts +48 -0
  77. package/packages/bundled-features/src/tenant/feature.ts +11 -0
  78. package/packages/bundled-features/src/tenant/i18n.ts +14 -0
  79. package/samples/apps/ui-walkthrough/src/app/auth-constants.ts +51 -0
  80. package/samples/apps/ui-walkthrough/src/app/seed-print-editor-tenants.ts +118 -0
  81. package/samples/apps/ui-walkthrough/src/app/seed-templates.ts +2 -0
  82. package/samples/apps/ui-walkthrough/src/app/server.ts +9 -1
  83. package/samples/apps/ui-walkthrough/src/app/template-seed-data.ts +27 -1
  84. package/samples/apps/ui-walkthrough/src/features/rental/i18n.ts +8 -0
  85. package/samples/apps/ui-walkthrough/src/features/rental/screens.ts +1 -0
  86. package/samples/apps/ui-walkthrough/src/run-config.ts +1 -0
  87. package/samples/apps/use-all-bundled/feature-manifest.json +236 -0
  88. package/samples/recipes/pdf-letterhead/README.md +23 -0
  89. package/samples/recipes/pdf-letterhead/package.json +12 -0
  90. package/samples/recipes/pdf-letterhead/src/letterhead.ts +92 -0
@@ -1,13 +1,24 @@
1
1
  import type { FieldIssue } from "@cosmicdrift/kumiko-framework/errors";
2
2
  import { getSchema, type JSONContent } from "@tiptap/core";
3
3
  import * as z from "zod";
4
+ import {
5
+ type BlockInput,
6
+ type BuildContext,
7
+ blockFormatSchema,
8
+ blockInputSchema,
9
+ blockNode,
10
+ countBlocks,
11
+ FORMATTABLE_NODE_TYPES,
12
+ formatNode,
13
+ MAX_BODY_BLOCKS,
14
+ patchIssue,
15
+ refusePrintStyling,
16
+ } from "./document-op-blocks.ts";
17
+ import type { LayoutRegionName } from "./layout-regions.ts";
4
18
  import { toVariableDef } from "./template-validation.ts";
5
- import type { DocumentHtmlKind } from "./web/constants.ts";
6
- import { documentBlocksForKind } from "./web/document-blocks.ts";
19
+ import type { DocumentOpsKind } from "./web/constants.ts";
7
20
  import {
8
- DOCUMENT_TEXT_ALIGNMENTS,
9
21
  documentExtensions,
10
- isDocumentPlaceholderHref,
11
22
  isDocumentReferenceName,
12
23
  isDocumentResourceKey,
13
24
  } from "./web/document-schema.ts";
@@ -24,6 +35,7 @@ export type DocumentBlockType =
24
35
  | "list"
25
36
  | "table"
26
37
  | "repeat"
38
+ | "frame"
27
39
  | "image"
28
40
  | "button"
29
41
  | "divider"
@@ -40,8 +52,21 @@ export type DocumentBlock = {
40
52
  readonly showIf?: string;
41
53
  readonly resource?: string;
42
54
  readonly alt?: string;
55
+ readonly widthMm?: number;
56
+ readonly bleed?: boolean;
57
+ readonly color?: string;
58
+ readonly weightPt?: number;
43
59
  readonly href?: string;
44
60
  readonly each?: string;
61
+ readonly frame?: FrameBox;
62
+ };
63
+
64
+ export type FrameBox = {
65
+ readonly xMm: number;
66
+ readonly yMm: number;
67
+ readonly widthMm: number;
68
+ readonly heightMm: number;
69
+ readonly preset?: string;
45
70
  };
46
71
 
47
72
  const TEXT_BLOCK_TYPES: ReadonlySet<string> = new Set(["paragraph", "heading", "button"]);
@@ -62,6 +87,8 @@ function blockTypeOf(node: JSONContent): DocumentBlockType | null {
62
87
  return eachOf(node) === undefined ? "table" : "repeat";
63
88
  case "resource":
64
89
  return "image";
90
+ case "documentFrame":
91
+ return "frame";
65
92
  default:
66
93
  return null;
67
94
  }
@@ -80,8 +107,15 @@ function eachOf(table: JSONContent): string | undefined {
80
107
  return undefined;
81
108
  }
82
109
 
110
+ // A line break reads back as "\n"; writing text collapses it again, so a break is set with runs.
111
+ function lineWithBreaks(content: readonly JSONContent[] | undefined): string {
112
+ return (content ?? [])
113
+ .map((node) => (node.type === "hardBreak" ? "\n" : contentToLine([node])))
114
+ .join("");
115
+ }
116
+
83
117
  function textLinesOf(node: JSONContent): string[] {
84
- if (TEXT_BLOCK_TYPES.has(node.type ?? "")) return [contentToLine(node.content)];
118
+ if (TEXT_BLOCK_TYPES.has(node.type ?? "")) return [lineWithBreaks(node.content)];
85
119
  return (node.content ?? []).flatMap(textLinesOf);
86
120
  }
87
121
 
@@ -101,6 +135,21 @@ function setOptionalAttrs(block: MutableBlock, node: JSONContent): void {
101
135
  if (showIf !== undefined) block.showIf = showIf;
102
136
  }
103
137
 
138
+ function setImagePrintAttrs(block: MutableBlock, node: JSONContent): void {
139
+ const widthMm: unknown = node.attrs?.["widthMm"];
140
+ if (typeof widthMm === "number") block.widthMm = widthMm;
141
+ if (node.attrs?.["bleed"] === true) block.bleed = true;
142
+ const align = stringAttr(node, "align");
143
+ if (align !== undefined) block.align = align;
144
+ }
145
+
146
+ function setDividerAttrs(block: MutableBlock, node: JSONContent): void {
147
+ const color = stringAttr(node, "color");
148
+ if (color !== undefined) block.color = color;
149
+ const weightPt: unknown = node.attrs?.["weightPt"];
150
+ if (typeof weightPt === "number") block.weightPt = weightPt;
151
+ }
152
+
104
153
  function setTypeSpecificAttrs(block: MutableBlock, node: JSONContent): void {
105
154
  const level: unknown = node.attrs?.["level"];
106
155
  if (block.type === "heading" && typeof level === "number") block.level = level;
@@ -108,10 +157,29 @@ function setTypeSpecificAttrs(block: MutableBlock, node: JSONContent): void {
108
157
  if (block.type === "image" && resource !== undefined) block.resource = resource;
109
158
  const alt = stringAttr(node, "alt");
110
159
  if (block.type === "image" && alt !== undefined) block.alt = alt;
160
+ if (block.type === "image") setImagePrintAttrs(block, node);
161
+ if (block.type === "divider") setDividerAttrs(block, node);
111
162
  const href = stringAttr(node, "href");
112
163
  if (block.type === "button" && href !== undefined) block.href = href;
113
164
  const each = eachOf(node);
114
165
  if (block.type === "repeat" && each !== undefined) block.each = each;
166
+ if (block.type === "frame") block.frame = frameBoxOf(node);
167
+ }
168
+
169
+ function numberAttr(node: JSONContent, name: string): number {
170
+ const value: unknown = node.attrs?.[name];
171
+ return typeof value === "number" ? value : 0;
172
+ }
173
+
174
+ function frameBoxOf(node: JSONContent): FrameBox {
175
+ const preset = stringAttr(node, "preset");
176
+ return {
177
+ xMm: numberAttr(node, "xMm"),
178
+ yMm: numberAttr(node, "yMm"),
179
+ widthMm: numberAttr(node, "widthMm"),
180
+ heightMm: numberAttr(node, "heightMm"),
181
+ ...(preset === undefined ? {} : { preset }),
182
+ };
115
183
  }
116
184
 
117
185
  function blockOf(node: JSONContent, id: string): DocumentBlock | null {
@@ -133,30 +201,8 @@ export function documentBlocksOf(doc: JSONContent): DocumentBlock[] {
133
201
  }
134
202
 
135
203
  const blockIdSchema = z.string().min(1).max(20);
136
- const singleLineText = z.string().max(2000);
137
204
 
138
- const blockInputSchema = z.discriminatedUnion("type", [
139
- z.object({
140
- type: z.literal("paragraph"),
141
- text: singleLineText,
142
- align: z.enum(DOCUMENT_TEXT_ALIGNMENTS).optional(),
143
- }),
144
- z.object({
145
- type: z.literal("heading"),
146
- level: z.number().int().min(1).max(3),
147
- text: singleLineText,
148
- }),
149
- z.object({
150
- type: z.literal("image"),
151
- resource: z.string().min(1).max(200),
152
- alt: z.string().max(500).optional(),
153
- }),
154
- z.object({ type: z.literal("button"), text: singleLineText, href: z.string().max(300) }),
155
- z.object({ type: z.literal("divider") }),
156
- z.object({ type: z.literal("pageBreak") }),
157
- ]);
158
-
159
- export type BlockInput = z.infer<typeof blockInputSchema>;
205
+ export type { BlockInput };
160
206
 
161
207
  export const documentOpSchema = z.discriminatedUnion("op", [
162
208
  z.object({
@@ -171,6 +217,11 @@ export const documentOpSchema = z.discriminatedUnion("op", [
171
217
  replace: z.string().max(2000),
172
218
  }),
173
219
  z.object({ op: z.literal("removeBlock"), blockId: blockIdSchema }),
220
+ z.object({
221
+ op: z.literal("replaceBody"),
222
+ blocks: z.array(blockInputSchema).min(1).max(MAX_BODY_BLOCKS),
223
+ }),
224
+ blockFormatSchema.extend({ op: z.literal("formatBlock"), blockId: blockIdSchema }),
174
225
  z.object({
175
226
  op: z.literal("setResource"),
176
227
  blockId: blockIdSchema,
@@ -193,7 +244,8 @@ export type DocumentOpsInput = {
193
244
  readonly doc: JSONContent;
194
245
  readonly meta: Readonly<Record<string, unknown>>;
195
246
  readonly variableSchema: Readonly<Record<string, unknown>>;
196
- readonly kind: DocumentHtmlKind;
247
+ readonly kind: DocumentOpsKind;
248
+ readonly region?: LayoutRegionName | undefined;
197
249
  readonly ops: readonly DocumentOp[];
198
250
  };
199
251
 
@@ -208,20 +260,6 @@ export type DocumentOpsResult =
208
260
 
209
261
  type Entry = { node: JSONContent; removed: boolean; readonly insertedAfter: JSONContent[] };
210
262
 
211
- function patchIssue(
212
- path: string,
213
- code: string,
214
- params?: Readonly<Record<string, unknown>>,
215
- ): FieldIssue {
216
- const camel = code.replace(/_([a-z])/g, (_match, letter: string) => letter.toUpperCase());
217
- return {
218
- path,
219
- code,
220
- i18nKey: `templateResolver.errors.patch.${camel}`,
221
- ...(params === undefined ? {} : { params }),
222
- };
223
- }
224
-
225
263
  function textNodesIn(nodes: readonly JSONContent[]): JSONContent[] {
226
264
  return nodes.flatMap((node) => (node.type === "text" ? [node] : textNodesIn(node.content ?? [])));
227
265
  }
@@ -263,58 +301,6 @@ function replaceInContent(
263
301
  });
264
302
  }
265
303
 
266
- function nodeOfInput(input: BlockInput): JSONContent {
267
- switch (input.type) {
268
- case "paragraph":
269
- return {
270
- type: "paragraph",
271
- ...(input.align === undefined ? {} : { attrs: { textAlign: input.align } }),
272
- content: lineToContent(singleLine(input.text)),
273
- };
274
- case "heading":
275
- return {
276
- type: "heading",
277
- attrs: { level: input.level },
278
- content: lineToContent(singleLine(input.text)),
279
- };
280
- case "image":
281
- return { type: "resource", attrs: { resource: input.resource, alt: input.alt ?? null } };
282
- case "button":
283
- return {
284
- type: "button",
285
- attrs: { href: input.href },
286
- content: lineToContent(singleLine(input.text)),
287
- };
288
- case "divider":
289
- case "pageBreak":
290
- return { type: input.type };
291
- }
292
- }
293
-
294
- const TOOLBAR_BLOCK_OF_INPUT = {
295
- image: "image",
296
- button: "button",
297
- divider: "divider",
298
- pageBreak: "pageBreak",
299
- } as const;
300
-
301
- function isBlockAllowed(input: BlockInput, kind: DocumentHtmlKind): boolean {
302
- if (input.type === "paragraph" || input.type === "heading") return true;
303
- return documentBlocksForKind(kind).includes(TOOLBAR_BLOCK_OF_INPUT[input.type]);
304
- }
305
-
306
- function inputIssue(input: BlockInput, path: string): FieldIssue | null {
307
- if (input.type === "image" && !isDocumentResourceKey(input.resource)) {
308
- return patchIssue(`${path}.block.resource`, "invalid_resource_key", {
309
- resource: input.resource,
310
- });
311
- }
312
- if (input.type === "button" && !isDocumentPlaceholderHref(input.href)) {
313
- return patchIssue(`${path}.block.href`, "invalid_button_href", { href: input.href });
314
- }
315
- return null;
316
- }
317
-
318
304
  let cachedSchema: ReturnType<typeof getSchema> | null = null;
319
305
 
320
306
  function documentSchema(): ReturnType<typeof getSchema> {
@@ -332,7 +318,9 @@ function isValidDocument(doc: JSONContent): boolean {
332
318
  }
333
319
 
334
320
  type OpState = {
335
- readonly kind: DocumentHtmlKind;
321
+ readonly kind: DocumentOpsKind;
322
+ readonly region: LayoutRegionName | undefined;
323
+ replacement: JSONContent[] | null;
336
324
  readonly entries: Map<string, Entry>;
337
325
  readonly insertedAtStart: JSONContent[];
338
326
  readonly meta: Record<string, unknown>;
@@ -350,32 +338,75 @@ function lookupEntry(state: OpState, blockId: string, fieldPath: string): EntryL
350
338
 
351
339
  type InsertBlockOp = Extract<DocumentOp, { op: "insertBlock" }>;
352
340
 
353
- function blockInputIssue(
354
- op: InsertBlockOp,
341
+ function buildBlocks(
342
+ state: OpState,
343
+ blocks: readonly BlockInput[],
344
+ pathOf: (index: number) => string,
345
+ ): { readonly nodes: JSONContent[]; readonly issues: FieldIssue[] } {
346
+ const ctx: BuildContext = { kind: state.kind, region: state.region, issues: [] };
347
+ const nodes = blocks.map((block, index) => blockNode(ctx, pathOf(index), block));
348
+ nodes.forEach((node, index) => {
349
+ const refused = refusePrintStyling(state.kind, node, pathOf(index));
350
+ if (refused !== null) ctx.issues.push(refused);
351
+ });
352
+ return { nodes, issues: ctx.issues };
353
+ }
354
+
355
+ function insertBlockOp(state: OpState, op: InsertBlockOp, path: string): FieldIssue[] {
356
+ const anchor = op.after === null ? null : lookupEntry(state, op.after, `${path}.after`);
357
+ if (anchor !== null && "issue" in anchor) return [anchor.issue];
358
+ const built = buildBlocks(state, [op.block], () => `${path}.block`);
359
+ if (built.issues.length > 0) return built.issues;
360
+ const target = anchor === null ? state.insertedAtStart : anchor.entry.insertedAfter;
361
+ target.push(...built.nodes);
362
+ return [];
363
+ }
364
+
365
+ function replaceBodyOp(
366
+ state: OpState,
367
+ op: Extract<DocumentOp, { op: "replaceBody" }>,
355
368
  path: string,
356
- kind: DocumentHtmlKind,
357
- ): FieldIssue | null {
358
- if (!isBlockAllowed(op.block, kind)) {
359
- return patchIssue(`${path}.block.type`, "block_not_allowed", { type: op.block.type, kind });
369
+ ): FieldIssue[] {
370
+ if (countBlocks(op.blocks) > MAX_BODY_BLOCKS) {
371
+ return [patchIssue(`${path}.blocks`, "too_many_blocks", { max: MAX_BODY_BLOCKS })];
360
372
  }
361
- if (
362
- op.block.type === "paragraph" &&
363
- op.block.align !== undefined &&
364
- !documentBlocksForKind(kind).includes("align")
365
- ) {
366
- return patchIssue(`${path}.block.align`, "block_not_allowed", { type: "align", kind });
373
+ const built = buildBlocks(state, op.blocks, (index) => `${path}.blocks.${index}`);
374
+ if (built.issues.length > 0) return built.issues;
375
+ for (const entry of state.entries.values()) {
376
+ entry.removed = true;
377
+ entry.insertedAfter.length = 0;
367
378
  }
368
- return inputIssue(op.block, path);
379
+ state.insertedAtStart.length = 0;
380
+ state.replacement = built.nodes;
381
+ return [];
369
382
  }
370
383
 
371
- function insertBlockOp(state: OpState, op: InsertBlockOp, path: string): FieldIssue | null {
372
- const anchor = op.after === null ? null : lookupEntry(state, op.after, `${path}.after`);
373
- if (anchor !== null && "issue" in anchor) return anchor.issue;
374
- const invalid = blockInputIssue(op, path, state.kind);
375
- if (invalid !== null) return invalid;
376
- const target = anchor === null ? state.insertedAtStart : anchor.entry.insertedAfter;
377
- target.push(nodeOfInput(op.block));
378
- return null;
384
+ function formatBlockOp(
385
+ state: OpState,
386
+ op: Extract<DocumentOp, { op: "formatBlock" }>,
387
+ path: string,
388
+ ): FieldIssue[] {
389
+ const found = lookupEntry(state, op.blockId, `${path}.blockId`);
390
+ if ("issue" in found) return [found.issue];
391
+ const { entry } = found;
392
+ if (op.align === undefined && op.style === undefined && op.textStyle === undefined) {
393
+ return [patchIssue(path, "empty_format")];
394
+ }
395
+ if (!FORMATTABLE_NODE_TYPES.has(entry.node.type ?? "")) {
396
+ return [
397
+ patchIssue(`${path}.blockId`, "block_type_mismatch", {
398
+ expected: "paragraph, heading or list",
399
+ actual: entry.node.type ?? "unknown",
400
+ }),
401
+ ];
402
+ }
403
+ const ctx: BuildContext = { kind: state.kind, issues: [] };
404
+ const formatted = formatNode(ctx, path, entry.node, op);
405
+ const refused = refusePrintStyling(state.kind, formatted, path);
406
+ if (refused !== null) ctx.issues.push(refused);
407
+ if (ctx.issues.length > 0) return ctx.issues;
408
+ entry.node = formatted;
409
+ return [];
379
410
  }
380
411
 
381
412
  function removeBlockOp(
@@ -444,7 +475,7 @@ function setResourceOp(
444
475
  return patchIssue(`${path}.resource`, "invalid_resource_key", { resource: op.resource });
445
476
  }
446
477
  const alt = op.alt === undefined ? (entry.node.attrs?.["alt"] ?? null) : op.alt;
447
- entry.node = { ...entry.node, attrs: { resource: op.resource, alt } };
478
+ entry.node = { ...entry.node, attrs: { ...entry.node.attrs, resource: op.resource, alt } };
448
479
  return null;
449
480
  }
450
481
 
@@ -484,23 +515,31 @@ function setVariableOp(
484
515
  return null;
485
516
  }
486
517
 
487
- function applyOp(state: OpState, op: DocumentOp, path: string): FieldIssue | null {
518
+ function applyOp(state: OpState, op: DocumentOp, path: string): FieldIssue[] {
488
519
  switch (op.op) {
489
520
  case "insertBlock":
490
521
  return insertBlockOp(state, op, path);
522
+ case "replaceBody":
523
+ return replaceBodyOp(state, op, path);
524
+ case "formatBlock":
525
+ return formatBlockOp(state, op, path);
491
526
  case "removeBlock":
492
- return removeBlockOp(state, op, path);
527
+ return singleIssue(removeBlockOp(state, op, path));
493
528
  case "replaceText":
494
- return replaceTextOp(state, op, path);
529
+ return singleIssue(replaceTextOp(state, op, path));
495
530
  case "setResource":
496
- return setResourceOp(state, op, path);
531
+ return singleIssue(setResourceOp(state, op, path));
497
532
  case "setMeta":
498
- return setMetaOp(state, op, path);
533
+ return singleIssue(setMetaOp(state, op, path));
499
534
  case "setVariable":
500
- return setVariableOp(state, op, path);
535
+ return singleIssue(setVariableOp(state, op, path));
501
536
  }
502
537
  }
503
538
 
539
+ function singleIssue(issue: FieldIssue | null): FieldIssue[] {
540
+ return issue === null ? [] : [issue];
541
+ }
542
+
504
543
  // Ops address blocks by the ids of the document as it was read, so inserted blocks are
505
544
  // collected per anchor and the list is assembled once at the end.
506
545
  export function applyDocumentOps(input: DocumentOpsInput): DocumentOpsResult {
@@ -514,19 +553,22 @@ export function applyDocumentOps(input: DocumentOpsInput): DocumentOpsResult {
514
553
  });
515
554
  const state: OpState = {
516
555
  kind: input.kind,
556
+ region: input.region,
557
+ replacement: null,
517
558
  entries,
518
559
  insertedAtStart: [],
519
560
  meta: { ...input.meta },
520
561
  variableSchema: { ...input.variableSchema },
521
562
  };
522
- const issues = input.ops.flatMap((op, index) => applyOp(state, op, `ops.${index}`) ?? []);
563
+ const issues = input.ops.flatMap((op, index) => applyOp(state, op, `ops.${index}`));
523
564
  if (issues.length > 0) return { ok: false, issues };
524
565
 
525
566
  const content = [
526
567
  ...state.insertedAtStart,
527
- ...[...entries.values()].flatMap((entry) =>
528
- entry.removed ? entry.insertedAfter : [entry.node, ...entry.insertedAfter],
529
- ),
568
+ ...(state.replacement ??
569
+ [...entries.values()].flatMap((entry) =>
570
+ entry.removed ? entry.insertedAfter : [entry.node, ...entry.insertedAfter],
571
+ )),
530
572
  ];
531
573
  const doc: JSONContent = { ...input.doc, content };
532
574
  if (!isValidDocument(doc)) return { ok: false, issues: [patchIssue("ops", "invalid_document")] };
@@ -0,0 +1,65 @@
1
+ // Server-only (happy-dom). Features of the shared document model that only a PDF can render:
2
+ // a mail body would keep them through the rebuild, so every other kind refuses them on write.
3
+ import type { Element as ScanElement } from "happy-dom";
4
+ import { readFrameAttributes } from "./web/document-print-style.ts";
5
+ import { PDF_MAX_PAGE_EDGE_MM } from "./web/pdf-constants.ts";
6
+
7
+ export const IMAGES_BLOCK_SELECTOR = "div[data-images]";
8
+
9
+ export const PRINT_STYLE_SELECTORS = [
10
+ "div[data-frame]",
11
+ "span[data-text-style]",
12
+ "[data-line-height]",
13
+ "[data-space-before]",
14
+ "[data-space-after]",
15
+ "table[data-borders]",
16
+ "table[data-cell-padding-mm]",
17
+ "table[data-table-width-mm]",
18
+ "table[data-table-align]",
19
+ "tr[data-line-above]",
20
+ "tr[data-line-below]",
21
+ "[data-background]",
22
+ "[data-colwidth]",
23
+ "img[data-bleed]",
24
+ "img[data-width-mm]",
25
+ "img[data-align]",
26
+ "hr[data-color]",
27
+ "hr[data-weight-pt]",
28
+ ] as const;
29
+
30
+ export type PrintOnlyFeatures = {
31
+ readonly hasImagesBlock: boolean;
32
+ readonly printStyleSelectors: readonly string[];
33
+ };
34
+
35
+ export function scanPrintOnlyFeatures(body: ScanElement): PrintOnlyFeatures {
36
+ return {
37
+ hasImagesBlock: body.querySelector(IMAGES_BLOCK_SELECTOR) !== null,
38
+ printStyleSelectors: PRINT_STYLE_SELECTORS.filter(
39
+ (selector) => body.querySelector(selector) !== null,
40
+ ),
41
+ };
42
+ }
43
+
44
+ export function hasNestedFrame(body: ScanElement): boolean {
45
+ return Array.from(body.querySelectorAll("div[data-frame]")).some(
46
+ (frame) => frame.parentElement !== body,
47
+ );
48
+ }
49
+
50
+ export function framesOutsidePage(body: ScanElement): string[] {
51
+ return Array.from(body.querySelectorAll("div[data-frame]")).flatMap((element) => {
52
+ const frame = readFrameAttributes(element);
53
+ if (frame === null) return [];
54
+ const overshootsPage =
55
+ frame.xMm + frame.widthMm > PDF_MAX_PAGE_EDGE_MM ||
56
+ frame.yMm + frame.heightMm > PDF_MAX_PAGE_EDGE_MM;
57
+ return overshootsPage
58
+ ? [`${frame.xMm}/${frame.yMm} ${frame.widthMm}x${frame.heightMm} mm`]
59
+ : [];
60
+ });
61
+ }
62
+
63
+ export function hasFrame(body: ScanElement): boolean {
64
+ return body.querySelector("div[data-frame]") !== null;
65
+ }
@@ -5,6 +5,7 @@ import { isOneOf } from "@cosmicdrift/kumiko-types/type-guards";
5
5
  import type { JSONContent } from "@tiptap/core";
6
6
  import { generateHTML, generateJSON } from "@tiptap/html/server";
7
7
  import { type Element as ScanElement, Window } from "happy-dom";
8
+ import { framesOutsidePage, hasNestedFrame, scanPrintOnlyFeatures } from "./document-print-only.ts";
8
9
  import type { ContentFormat } from "./web/constants.ts";
9
10
  import { DOCUMENT_HTML_KINDS } from "./web/constants.ts";
10
11
  import {
@@ -17,6 +18,7 @@ import {
17
18
  isDocumentResourceKey,
18
19
  } from "./web/document-schema.ts";
19
20
  import { isDocumentStepKey } from "./web/document-steps.ts";
21
+ import { PDF_MAX_PAGE_EDGE_MM } from "./web/pdf-constants.ts";
20
22
 
21
23
  export type DocumentViolationCode =
22
24
  | "script_element"
@@ -29,6 +31,9 @@ export type DocumentViolationCode =
29
31
  | "embedded_content"
30
32
  | "unsafe_attribute_value"
31
33
  | "images_block_pdf_only"
34
+ | "print_style_pdf_only"
35
+ | "frame_not_top_level"
36
+ | "frame_outside_page"
32
37
  | "button_href_not_placeholder"
33
38
  | "document_requires_html_format"
34
39
  | "layout_requires_mjml_format"
@@ -262,6 +267,24 @@ function scanDocumentHtml(html: string): DocumentViolation[] {
262
267
  for (const element of [body, ...Array.from(body.querySelectorAll("*"))]) {
263
268
  scanElement(element, violations);
264
269
  }
270
+ if (hasNestedFrame(body)) {
271
+ violations.push(
272
+ violation(
273
+ "frame_not_top_level",
274
+ "div[data-frame]",
275
+ "A frame must sit directly in the document body, not inside another block",
276
+ ),
277
+ );
278
+ }
279
+ for (const box of framesOutsidePage(body)) {
280
+ violations.push(
281
+ violation(
282
+ "frame_outside_page",
283
+ box,
284
+ `A frame (${box}) must lie within the largest supported paper size (${PDF_MAX_PAGE_EDGE_MM} mm)`,
285
+ ),
286
+ );
287
+ }
265
288
  });
266
289
  return violations;
267
290
  }
@@ -330,30 +353,38 @@ function requiredFormatViolation(
330
353
  return null;
331
354
  }
332
355
 
333
- const IMAGES_BLOCK_KIND = "document-pdf";
356
+ const PDF_ONLY_KIND = "document-pdf";
334
357
 
335
- // The node is part of the shared document model, so a mail body would keep it after the
336
- // rebuild; only a PDF resolves the record's images.
337
- function imagesBlockViolation(input: SanitizeBodyInput): DocumentViolation | null {
358
+ // These nodes and attributes are part of the shared document model, so a mail body would keep
359
+ // them after the rebuild; only a PDF resolves the record's images and applies print styling.
360
+ function pdfOnlyViolations(input: SanitizeBodyInput): DocumentViolation[] {
338
361
  if (
339
- input.kind === IMAGES_BLOCK_KIND ||
362
+ input.kind === PDF_ONLY_KIND ||
340
363
  !isSanitizedBody(input) ||
341
364
  input.contentFormat !== "html" ||
342
365
  input.content === null
343
366
  ) {
344
- return null;
367
+ return [];
345
368
  }
346
- const hasImagesBlock = withParsedDocument(
347
- input.content,
348
- (body) => body.querySelector("div[data-images]") !== null,
349
- );
350
- return hasImagesBlock
351
- ? violation(
352
- "images_block_pdf_only",
353
- input.kind,
354
- `Record images blocks are only allowed in templates of kind ${IMAGES_BLOCK_KIND}`,
355
- )
356
- : null;
369
+ const found = withParsedDocument(input.content, scanPrintOnlyFeatures);
370
+ return [
371
+ ...(found.hasImagesBlock
372
+ ? [
373
+ violation(
374
+ "images_block_pdf_only",
375
+ input.kind,
376
+ `Record images blocks are only allowed in templates of kind ${PDF_ONLY_KIND}`,
377
+ ),
378
+ ]
379
+ : []),
380
+ ...found.printStyleSelectors.map((selector) =>
381
+ violation(
382
+ "print_style_pdf_only",
383
+ selector,
384
+ `Print styling (${selector}) is only allowed in templates of kind ${PDF_ONLY_KIND}`,
385
+ ),
386
+ ),
387
+ ];
357
388
  }
358
389
 
359
390
  // Mails and PDFs have no base address, so compileDocumentBody turns a relative href into "#"; refuse it
@@ -378,8 +409,8 @@ function relativeLinkViolations(html: string): DocumentViolation[] {
378
409
  export function sanitizeTemplateBody(input: SanitizeBodyInput): SanitizeBodyResult {
379
410
  const formatViolation = requiredFormatViolation(input.kind, input.contentFormat);
380
411
  if (formatViolation !== null) return { ok: false, violations: [formatViolation] };
381
- const imagesViolation = imagesBlockViolation(input);
382
- if (imagesViolation !== null) return { ok: false, violations: [imagesViolation] };
412
+ const pdfOnly = pdfOnlyViolations(input);
413
+ if (pdfOnly.length > 0) return { ok: false, violations: pdfOnly };
383
414
  if (!isSanitizedBody(input) || input.contentFormat !== "html" || input.content === null) {
384
415
  return { ok: true, content: input.content };
385
416
  }
@@ -402,6 +433,9 @@ const VIOLATION_I18N_KEYS: Readonly<Record<DocumentViolationCode, string>> = {
402
433
  embedded_content: "templateResolver.errors.document.embeddedContent",
403
434
  unsafe_attribute_value: "templateResolver.errors.document.unsafeAttributeValue",
404
435
  images_block_pdf_only: "templateResolver.errors.document.imagesBlockPdfOnly",
436
+ print_style_pdf_only: "templateResolver.errors.document.printStylePdfOnly",
437
+ frame_not_top_level: "templateResolver.errors.document.frameNotTopLevel",
438
+ frame_outside_page: "templateResolver.errors.document.frameOutsidePage",
405
439
  button_href_not_placeholder: "templateResolver.errors.document.buttonHrefNotPlaceholder",
406
440
  document_requires_html_format: "templateResolver.errors.document.documentRequiresHtmlFormat",
407
441
  layout_requires_mjml_format: "templateResolver.errors.document.layoutRequiresMjmlFormat",