@cosmicdrift/kumiko-bundled-features 0.417.0 → 0.419.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 (154) hide show
  1. package/dist/agent-tools/api-docs/schema-fields.js +9 -0
  2. package/dist/auth-email-password/index.d.ts +2 -1
  3. package/dist/auth-email-password/index.js +2 -1
  4. package/dist/auth-email-password/signup-activation.js +2 -1
  5. package/dist/auth-email-password/signup-token-store.d.ts +1 -6
  6. package/dist/auth-email-password/signup-token-store.js +0 -5
  7. package/dist/cap-counter/stock-cap-guard.d.ts +9 -2
  8. package/dist/cap-counter/stock-cap-guard.js +9 -11
  9. package/dist/document-ingest-foundation/feature.js +5 -1
  10. package/dist/document-ingest-foundation/report-ingest-progress.js +19 -6
  11. package/dist/signature/entity.d.ts +8 -6
  12. package/dist/signature/entity.js +3 -1
  13. package/dist/signature/feature.js +11 -4
  14. package/dist/signature/handlers/lifecycle.write.d.ts +9 -0
  15. package/dist/signature/handlers/lifecycle.write.js +23 -1
  16. package/dist/signature/handlers/request.write.d.ts +1 -1
  17. package/dist/signature/i18n.js +1 -0
  18. package/dist/signature/list-cursor-seal.d.ts +3 -0
  19. package/dist/signature/list-cursor-seal.js +44 -0
  20. package/dist/signature/options.d.ts +2 -2
  21. package/dist/signature/payloads.d.ts +17 -1
  22. package/dist/signature/payloads.js +11 -2
  23. package/dist/signature/png.js +23 -3
  24. package/dist/signature/subject-queries.d.ts +1 -1
  25. package/dist/signature/subject-queries.js +30 -8
  26. package/dist/signature/sweep.js +26 -9
  27. package/dist/signature/web/constants.d.ts +9 -0
  28. package/dist/signature/web/constants.js +8 -0
  29. package/dist/subscription-stripe/plugin-methods.js +2 -0
  30. package/dist/subscription-stripe/verify-webhook.js +17 -16
  31. package/dist/template-resolver/compile-document-body.js +3 -6
  32. package/dist/template-resolver/compile-document-styles.d.ts +3 -0
  33. package/dist/template-resolver/compile-document-styles.js +84 -0
  34. package/dist/template-resolver/document-frames.d.ts +3 -0
  35. package/dist/template-resolver/document-frames.js +19 -0
  36. package/dist/template-resolver/document-op-blocks.d.ts +495 -0
  37. package/dist/template-resolver/document-op-blocks.js +430 -0
  38. package/dist/template-resolver/document-ops.d.ts +1809 -37
  39. package/dist/template-resolver/document-ops.js +97 -104
  40. package/dist/template-resolver/document-print-only.d.ts +10 -0
  41. package/dist/template-resolver/document-print-only.js +24 -0
  42. package/dist/template-resolver/document-sanitizer.d.ts +1 -1
  43. package/dist/template-resolver/document-sanitizer.js +24 -13
  44. package/dist/template-resolver/feature.d.ts +3 -0
  45. package/dist/template-resolver/feature.js +14 -1
  46. package/dist/template-resolver/handlers/apply-layout.write.d.ts +29 -0
  47. package/dist/template-resolver/handlers/apply-layout.write.js +118 -0
  48. package/dist/template-resolver/handlers/create-layout.write.d.ts +15 -0
  49. package/dist/template-resolver/handlers/create-layout.write.js +78 -0
  50. package/dist/template-resolver/handlers/document-base.d.ts +2 -2
  51. package/dist/template-resolver/handlers/document-blocks.query.d.ts +10 -3
  52. package/dist/template-resolver/handlers/document-blocks.query.js +13 -8
  53. package/dist/template-resolver/handlers/document-region.d.ts +19 -0
  54. package/dist/template-resolver/handlers/document-region.js +27 -0
  55. package/dist/template-resolver/handlers/failure-reason.d.ts +2 -0
  56. package/dist/template-resolver/handlers/failure-reason.js +12 -0
  57. package/dist/template-resolver/handlers/import-bundle-system.write.js +4 -0
  58. package/dist/template-resolver/handlers/layout-source.query.d.ts +3 -3
  59. package/dist/template-resolver/handlers/layout-source.query.js +6 -2
  60. package/dist/template-resolver/handlers/overview.query.d.ts +8 -0
  61. package/dist/template-resolver/handlers/overview.query.js +12 -6
  62. package/dist/template-resolver/handlers/patch-draft.write.d.ts +905 -4
  63. package/dist/template-resolver/handlers/patch-draft.write.js +10 -6
  64. package/dist/template-resolver/handlers/publish-templates.write.d.ts +40 -0
  65. package/dist/template-resolver/handlers/publish-templates.write.js +61 -0
  66. package/dist/template-resolver/handlers/set.write.js +4 -1
  67. package/dist/template-resolver/handlers/template-write.js +7 -2
  68. package/dist/template-resolver/handlers/tenant-settings.d.ts +17 -0
  69. package/dist/template-resolver/handlers/tenant-settings.js +91 -0
  70. package/dist/template-resolver/handlers/toggle-status.write.d.ts +14 -9
  71. package/dist/template-resolver/handlers/toggle-status.write.js +11 -7
  72. package/dist/template-resolver/handlers/upsert-system.write.js +15 -9
  73. package/dist/template-resolver/handlers/usage.query.d.ts +14 -0
  74. package/dist/template-resolver/handlers/usage.query.js +80 -12
  75. package/dist/template-resolver/handlers/validate.query.d.ts +2 -0
  76. package/dist/template-resolver/handlers/validate.query.js +10 -0
  77. package/dist/template-resolver/i18n.js +3 -0
  78. package/dist/template-resolver/index.d.ts +7 -2
  79. package/dist/template-resolver/index.js +6 -2
  80. package/dist/template-resolver/layout-regions.d.ts +4 -5
  81. package/dist/template-resolver/layout-regions.js +38 -11
  82. package/dist/template-resolver/print-document.js +3 -1
  83. package/dist/template-resolver/seeding.js +4 -0
  84. package/dist/template-resolver/template-delivery-policy.d.ts +1 -0
  85. package/dist/template-resolver/template-delivery-policy.js +9 -1
  86. package/dist/template-resolver/template-edit-policy.d.ts +5 -1
  87. package/dist/template-resolver/template-edit-policy.js +29 -1
  88. package/dist/template-resolver/template-meta.d.ts +27 -2
  89. package/dist/template-resolver/template-meta.js +21 -5
  90. package/dist/template-resolver/template-preview.js +8 -8
  91. package/dist/template-resolver/template-validation.js +10 -3
  92. package/dist/template-resolver/web/constants.d.ts +7 -1
  93. package/dist/template-resolver/web/constants.js +21 -1
  94. package/dist/template-resolver/web/document-blocks.d.ts +1 -0
  95. package/dist/template-resolver/web/document-blocks.js +2 -0
  96. package/dist/template-resolver/web/document-editor-extensions.d.ts +9 -1
  97. package/dist/template-resolver/web/document-editor-extensions.js +27 -2
  98. package/dist/template-resolver/web/document-editor-fonts.d.ts +10 -0
  99. package/dist/template-resolver/web/document-editor-fonts.js +13 -0
  100. package/dist/template-resolver/web/document-fonts.d.ts +4 -0
  101. package/dist/template-resolver/web/document-fonts.js +18 -0
  102. package/dist/template-resolver/web/document-frame-control.d.ts +61 -0
  103. package/dist/template-resolver/web/document-frame-control.js +329 -0
  104. package/dist/template-resolver/web/document-frame-node-view.d.ts +4 -0
  105. package/dist/template-resolver/web/document-frame-node-view.js +173 -0
  106. package/dist/template-resolver/web/document-print-decorations.d.ts +12 -0
  107. package/dist/template-resolver/web/document-print-decorations.js +147 -0
  108. package/dist/template-resolver/web/document-print-defaults.d.ts +14 -0
  109. package/dist/template-resolver/web/document-print-defaults.js +25 -0
  110. package/dist/template-resolver/web/document-print-style.d.ts +71 -0
  111. package/dist/template-resolver/web/document-print-style.js +199 -0
  112. package/dist/template-resolver/web/document-repeat-strip.d.ts +8 -0
  113. package/dist/template-resolver/web/document-repeat-strip.js +78 -0
  114. package/dist/template-resolver/web/document-schema.js +23 -9
  115. package/dist/template-resolver/web/document-style-css.d.ts +29 -0
  116. package/dist/template-resolver/web/document-style-css.js +76 -0
  117. package/dist/template-resolver/web/document-tiptap-bubble.js +13 -3
  118. package/dist/template-resolver/web/document-tiptap-content.d.ts +2 -1
  119. package/dist/template-resolver/web/document-tiptap-content.js +36 -4
  120. package/dist/template-resolver/web/document-tiptap-context.d.ts +6 -2
  121. package/dist/template-resolver/web/document-tiptap-context.js +2 -1
  122. package/dist/template-resolver/web/document-tiptap-editor.d.ts +1 -1
  123. package/dist/template-resolver/web/document-tiptap-editor.js +13 -5
  124. package/dist/template-resolver/web/document-tiptap-helpers.d.ts +30 -1
  125. package/dist/template-resolver/web/document-tiptap-helpers.js +103 -2
  126. package/dist/template-resolver/web/document-tiptap-toolbar-groups.d.ts +5 -0
  127. package/dist/template-resolver/web/document-tiptap-toolbar-groups.js +89 -6
  128. package/dist/template-resolver/web/document-tiptap-toolbar.js +45 -8
  129. package/dist/template-resolver/web/document-toolbar-blocks.d.ts +17 -0
  130. package/dist/template-resolver/web/i18n.js +19 -0
  131. package/dist/template-resolver/web/index.d.ts +8 -2
  132. package/dist/template-resolver/web/index.js +6 -1
  133. package/dist/template-resolver/web/pdf-constants.d.ts +3 -0
  134. package/dist/template-resolver/web/pdf-constants.js +3 -0
  135. package/dist/template-resolver/web/qualified-names.d.ts +7 -0
  136. package/dist/template-resolver/web/qualified-names.js +6 -0
  137. package/dist/template-resolver/web/use-document-tiptap-model.d.ts +6 -2
  138. package/dist/template-resolver/web/use-document-tiptap-model.js +38 -3
  139. package/dist/tenant/company-config.d.ts +6 -0
  140. package/dist/tenant/company-config.js +41 -0
  141. package/dist/tenant/feature.js +11 -0
  142. package/dist/tenant/i18n.js +14 -0
  143. package/dist/tenant-inactivity/handlers/keep-account.write.js +5 -2
  144. package/dist/tenant-lifecycle/run-tenant-destroy.js +65 -33
  145. package/package.json +16 -11
  146. package/src/agent-tools/changes.json +6 -0
  147. package/src/cap-counter/changes.json +6 -0
  148. package/src/channel-whatsapp/changes.json +1 -1
  149. package/src/document-ingest-foundation/changes.json +6 -0
  150. package/src/signature/changes.json +18 -0
  151. package/src/subscription-paddle/changes.json +1 -1
  152. package/src/subscription-stripe/changes.json +6 -0
  153. package/src/template-resolver/changes.json +38 -0
  154. package/src/tenant-lifecycle/changes.json +6 -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
  }
@@ -75,6 +77,22 @@ function setTypeSpecificAttrs(block, node) {
75
77
  const each = eachOf(node);
76
78
  if (block.type === "repeat" && each !== undefined)
77
79
  block.each = each;
80
+ if (block.type === "frame")
81
+ block.frame = frameBoxOf(node);
82
+ }
83
+ function numberAttr(node, name) {
84
+ const value = node.attrs?.[name];
85
+ return typeof value === "number" ? value : 0;
86
+ }
87
+ function frameBoxOf(node) {
88
+ const preset = stringAttr(node, "preset");
89
+ return {
90
+ xMm: numberAttr(node, "xMm"),
91
+ yMm: numberAttr(node, "yMm"),
92
+ widthMm: numberAttr(node, "widthMm"),
93
+ heightMm: numberAttr(node, "heightMm"),
94
+ ...(preset === undefined ? {} : { preset }),
95
+ };
78
96
  }
79
97
  function blockOf(node, id) {
80
98
  const type = blockTypeOf(node);
@@ -94,27 +112,6 @@ export function documentBlocksOf(doc) {
94
112
  return (doc.content ?? []).flatMap((node, index) => blockOf(node, documentBlockId(index)) ?? []);
95
113
  }
96
114
  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
115
  export const documentOpSchema = z.discriminatedUnion("op", [
119
116
  z.object({
120
117
  op: z.literal("insertBlock"),
@@ -128,6 +125,11 @@ export const documentOpSchema = z.discriminatedUnion("op", [
128
125
  replace: z.string().max(2000),
129
126
  }),
130
127
  z.object({ op: z.literal("removeBlock"), blockId: blockIdSchema }),
128
+ z.object({
129
+ op: z.literal("replaceBody"),
130
+ blocks: z.array(blockInputSchema).min(1).max(MAX_BODY_BLOCKS),
131
+ }),
132
+ blockFormatSchema.extend({ op: z.literal("formatBlock"), blockId: blockIdSchema }),
131
133
  z.object({
132
134
  op: z.literal("setResource"),
133
135
  blockId: blockIdSchema,
@@ -142,15 +144,6 @@ export const documentOpSchema = z.discriminatedUnion("op", [
142
144
  }),
143
145
  ]);
144
146
  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
147
  function textNodesIn(nodes) {
155
148
  return nodes.flatMap((node) => (node.type === "text" ? [node] : textNodesIn(node.content ?? [])));
156
149
  }
@@ -183,55 +176,6 @@ function replaceInContent(content, find, replace) {
183
176
  ];
184
177
  });
185
178
  }
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
179
  let cachedSchema = null;
236
180
  function documentSchema() {
237
181
  cachedSchema ??= getSchema(documentExtensions);
@@ -254,27 +198,67 @@ function lookupEntry(state, blockId, fieldPath) {
254
198
  return { issue: patchIssue(fieldPath, "block_removed", { blockId }) };
255
199
  return { entry };
256
200
  }
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);
201
+ function buildBlocks(state, blocks, pathOf) {
202
+ const ctx = { kind: state.kind, issues: [] };
203
+ const nodes = blocks.map((block, index) => blockNode(ctx, pathOf(index), block));
204
+ nodes.forEach((node, index) => {
205
+ const refused = refusePrintStyling(state.kind, node, pathOf(index));
206
+ if (refused !== null)
207
+ ctx.issues.push(refused);
208
+ });
209
+ return { nodes, issues: ctx.issues };
267
210
  }
268
211
  function insertBlockOp(state, op, path) {
269
212
  const anchor = op.after === null ? null : lookupEntry(state, op.after, `${path}.after`);
270
213
  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;
214
+ return [anchor.issue];
215
+ const built = buildBlocks(state, [op.block], () => `${path}.block`);
216
+ if (built.issues.length > 0)
217
+ return built.issues;
275
218
  const target = anchor === null ? state.insertedAtStart : anchor.entry.insertedAfter;
276
- target.push(nodeOfInput(op.block));
277
- return null;
219
+ target.push(...built.nodes);
220
+ return [];
221
+ }
222
+ function replaceBodyOp(state, op, path) {
223
+ if (countBlocks(op.blocks) > MAX_BODY_BLOCKS) {
224
+ return [patchIssue(`${path}.blocks`, "too_many_blocks", { max: MAX_BODY_BLOCKS })];
225
+ }
226
+ const built = buildBlocks(state, op.blocks, (index) => `${path}.blocks.${index}`);
227
+ if (built.issues.length > 0)
228
+ return built.issues;
229
+ for (const entry of state.entries.values()) {
230
+ entry.removed = true;
231
+ entry.insertedAfter.length = 0;
232
+ }
233
+ state.insertedAtStart.length = 0;
234
+ state.replacement = built.nodes;
235
+ return [];
236
+ }
237
+ function formatBlockOp(state, op, path) {
238
+ const found = lookupEntry(state, op.blockId, `${path}.blockId`);
239
+ if ("issue" in found)
240
+ return [found.issue];
241
+ const { entry } = found;
242
+ if (op.align === undefined && op.style === undefined && op.textStyle === undefined) {
243
+ return [patchIssue(path, "empty_format")];
244
+ }
245
+ if (!FORMATTABLE_NODE_TYPES.has(entry.node.type ?? "")) {
246
+ return [
247
+ patchIssue(`${path}.blockId`, "block_type_mismatch", {
248
+ expected: "paragraph, heading or list",
249
+ actual: entry.node.type ?? "unknown",
250
+ }),
251
+ ];
252
+ }
253
+ const ctx = { kind: state.kind, issues: [] };
254
+ const formatted = formatNode(ctx, path, entry.node, op);
255
+ const refused = refusePrintStyling(state.kind, formatted, path);
256
+ if (refused !== null)
257
+ ctx.issues.push(refused);
258
+ if (ctx.issues.length > 0)
259
+ return ctx.issues;
260
+ entry.node = formatted;
261
+ return [];
278
262
  }
279
263
  function removeBlockOp(state, op, path) {
280
264
  const found = lookupEntry(state, op.blockId, `${path}.blockId`);
@@ -362,18 +346,25 @@ function applyOp(state, op, path) {
362
346
  switch (op.op) {
363
347
  case "insertBlock":
364
348
  return insertBlockOp(state, op, path);
349
+ case "replaceBody":
350
+ return replaceBodyOp(state, op, path);
351
+ case "formatBlock":
352
+ return formatBlockOp(state, op, path);
365
353
  case "removeBlock":
366
- return removeBlockOp(state, op, path);
354
+ return singleIssue(removeBlockOp(state, op, path));
367
355
  case "replaceText":
368
- return replaceTextOp(state, op, path);
356
+ return singleIssue(replaceTextOp(state, op, path));
369
357
  case "setResource":
370
- return setResourceOp(state, op, path);
358
+ return singleIssue(setResourceOp(state, op, path));
371
359
  case "setMeta":
372
- return setMetaOp(state, op, path);
360
+ return singleIssue(setMetaOp(state, op, path));
373
361
  case "setVariable":
374
- return setVariableOp(state, op, path);
362
+ return singleIssue(setVariableOp(state, op, path));
375
363
  }
376
364
  }
365
+ function singleIssue(issue) {
366
+ return issue === null ? [] : [issue];
367
+ }
377
368
  // Ops address blocks by the ids of the document as it was read, so inserted blocks are
378
369
  // collected per anchor and the list is assembled once at the end.
379
370
  export function applyDocumentOps(input) {
@@ -387,17 +378,19 @@ export function applyDocumentOps(input) {
387
378
  });
388
379
  const state = {
389
380
  kind: input.kind,
381
+ replacement: null,
390
382
  entries,
391
383
  insertedAtStart: [],
392
384
  meta: { ...input.meta },
393
385
  variableSchema: { ...input.variableSchema },
394
386
  };
395
- const issues = input.ops.flatMap((op, index) => applyOp(state, op, `ops.${index}`) ?? []);
387
+ const issues = input.ops.flatMap((op, index) => applyOp(state, op, `ops.${index}`));
396
388
  if (issues.length > 0)
397
389
  return { ok: false, issues };
398
390
  const content = [
399
391
  ...state.insertedAtStart,
400
- ...[...entries.values()].flatMap((entry) => entry.removed ? entry.insertedAfter : [entry.node, ...entry.insertedAfter]),
392
+ ...(state.replacement ??
393
+ [...entries.values()].flatMap((entry) => entry.removed ? entry.insertedAfter : [entry.node, ...entry.insertedAfter])),
401
394
  ];
402
395
  const doc = { ...input.doc, content };
403
396
  if (!isValidDocument(doc))
@@ -0,0 +1,10 @@
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]", "[data-background]", "[data-colwidth]", "img[data-bleed]"];
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 hasFrame(body: ScanElement): boolean;
@@ -0,0 +1,24 @@
1
+ export const IMAGES_BLOCK_SELECTOR = "div[data-images]";
2
+ export const PRINT_STYLE_SELECTORS = [
3
+ "div[data-frame]",
4
+ "span[data-text-style]",
5
+ "[data-line-height]",
6
+ "[data-space-before]",
7
+ "[data-space-after]",
8
+ "table[data-borders]",
9
+ "[data-background]",
10
+ "[data-colwidth]",
11
+ "img[data-bleed]",
12
+ ];
13
+ export function scanPrintOnlyFeatures(body) {
14
+ return {
15
+ hasImagesBlock: body.querySelector(IMAGES_BLOCK_SELECTOR) !== null,
16
+ printStyleSelectors: PRINT_STYLE_SELECTORS.filter((selector) => body.querySelector(selector) !== null),
17
+ };
18
+ }
19
+ export function hasNestedFrame(body) {
20
+ return Array.from(body.querySelectorAll("div[data-frame]")).some((frame) => frame.parentElement !== body);
21
+ }
22
+ export function hasFrame(body) {
23
+ return body.querySelector("div[data-frame]") !== null;
24
+ }
@@ -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" | "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,6 +1,7 @@
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 { 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";
@@ -143,6 +144,9 @@ function scanDocumentHtml(html) {
143
144
  for (const element of [body, ...Array.from(body.querySelectorAll("*"))]) {
144
145
  scanElement(element, violations);
145
146
  }
147
+ if (hasNestedFrame(body)) {
148
+ violations.push(violation("frame_not_top_level", "div[data-frame]", "A frame must sit directly in the document body, not inside another block"));
149
+ }
146
150
  });
147
151
  return violations;
148
152
  }
@@ -187,20 +191,25 @@ function requiredFormatViolation(kind, contentFormat) {
187
191
  }
188
192
  return null;
189
193
  }
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 ||
194
+ const PDF_ONLY_KIND = "document-pdf";
195
+ // These nodes and attributes are part of the shared document model, so a mail body would keep
196
+ // them after the rebuild; only a PDF resolves the record's images and applies print styling.
197
+ function pdfOnlyViolations(input) {
198
+ if (input.kind === PDF_ONLY_KIND ||
195
199
  !isSanitizedBody(input) ||
196
200
  input.contentFormat !== "html" ||
197
201
  input.content === null) {
198
- return null;
202
+ return [];
199
203
  }
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;
204
+ const found = withParsedDocument(input.content, scanPrintOnlyFeatures);
205
+ return [
206
+ ...(found.hasImagesBlock
207
+ ? [
208
+ violation("images_block_pdf_only", input.kind, `Record images blocks are only allowed in templates of kind ${PDF_ONLY_KIND}`),
209
+ ]
210
+ : []),
211
+ ...found.printStyleSelectors.map((selector) => violation("print_style_pdf_only", selector, `Print styling (${selector}) is only allowed in templates of kind ${PDF_ONLY_KIND}`)),
212
+ ];
204
213
  }
205
214
  // Mails and PDFs have no base address, so compileDocumentBody turns a relative href into "#"; refuse it
206
215
  // on save instead of losing the admin's input silently. Managed pages resolve it against their host.
@@ -218,9 +227,9 @@ export function sanitizeTemplateBody(input) {
218
227
  const formatViolation = requiredFormatViolation(input.kind, input.contentFormat);
219
228
  if (formatViolation !== null)
220
229
  return { ok: false, violations: [formatViolation] };
221
- const imagesViolation = imagesBlockViolation(input);
222
- if (imagesViolation !== null)
223
- return { ok: false, violations: [imagesViolation] };
230
+ const pdfOnly = pdfOnlyViolations(input);
231
+ if (pdfOnly.length > 0)
232
+ return { ok: false, violations: pdfOnly };
224
233
  if (!isSanitizedBody(input) || input.contentFormat !== "html" || input.content === null) {
225
234
  return { ok: true, content: input.content };
226
235
  }
@@ -243,6 +252,8 @@ const VIOLATION_I18N_KEYS = {
243
252
  embedded_content: "templateResolver.errors.document.embeddedContent",
244
253
  unsafe_attribute_value: "templateResolver.errors.document.unsafeAttributeValue",
245
254
  images_block_pdf_only: "templateResolver.errors.document.imagesBlockPdfOnly",
255
+ print_style_pdf_only: "templateResolver.errors.document.printStylePdfOnly",
256
+ frame_not_top_level: "templateResolver.errors.document.frameNotTopLevel",
246
257
  button_href_not_placeholder: "templateResolver.errors.document.buttonHrefNotPlaceholder",
247
258
  document_requires_html_format: "templateResolver.errors.document.documentRequiresHtmlFormat",
248
259
  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 {};
@@ -0,0 +1,118 @@
1
+ import { defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
2
+ import { ValidationError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
3
+ import * as z from "zod";
4
+ import { createTemplateResolverApi, TemplateNotFoundError } from "../api.js";
5
+ import { refuseTemplateEdit, templateEditAccess, } from "../template-edit-policy.js";
6
+ import { resolveTemplateVariables } from "../template-validation.js";
7
+ import { DEFAULT_PDF_LAYOUT_SLUG_CONFIG_KEY, FALLBACK_LOCALE, MAX_SELECTED_TEMPLATES, } from "../web/constants.js";
8
+ import { ConfigHandlers, TemplateResolverErrors } from "../web/qualified-names.js";
9
+ import { loadDocumentBase } from "./document-base.js";
10
+ import { failureReason } from "./failure-reason.js";
11
+ import { localeSchema, templateSlugSchema } from "./shared.js";
12
+ import { writeTemplateRow } from "./template-write.js";
13
+ const templateRefSchema = z.object({ slug: templateSlugSchema, locale: localeSchema });
14
+ async function applyLayoutToDraft(ctx, user, layoutSlug, { slug, locale }) {
15
+ const loaded = await loadDocumentBase(ctx, user, { slug, kind: "document-pdf", locale });
16
+ if (loaded === null)
17
+ return { slug, locale, reason: TemplateResolverErrors.notFound };
18
+ const written = await writeTemplateRow({
19
+ ctx,
20
+ user,
21
+ tenantId: user.tenantId,
22
+ scope: "tenant",
23
+ status: "draft",
24
+ variables: resolveTemplateVariables(ctx.registry, slug, loaded.variableSchema),
25
+ payload: {
26
+ slug,
27
+ kind: "document-pdf",
28
+ locale,
29
+ content: loaded.content,
30
+ contentFormat: "html",
31
+ variableSchema: loaded.variableSchema,
32
+ meta: { ...loaded.meta, layoutSlug },
33
+ title: loaded.title,
34
+ folder: loaded.folder,
35
+ parentTemplateId: loaded.parentTemplateId,
36
+ },
37
+ expectedVersion: loaded.base.scope === "tenant" ? loaded.base.version : null,
38
+ });
39
+ return written.isSuccess ? null : { slug, locale, reason: failureReason(written) };
40
+ }
41
+ export function makeApplyLayoutWrite(policy) {
42
+ return defineWriteHandler({
43
+ name: "apply-layout",
44
+ schema: z.object({
45
+ layoutSlug: templateSlugSchema,
46
+ target: z.discriminatedUnion("mode", [
47
+ z.object({ mode: z.literal("all") }),
48
+ z.object({
49
+ mode: z.literal("selected"),
50
+ templates: z.array(templateRefSchema).min(1).max(MAX_SELECTED_TEMPLATES),
51
+ }),
52
+ ]),
53
+ }),
54
+ access: templateEditAccess(policy.tenantEditable),
55
+ description: "Applies a PDF layout to the caller's PDF templates without copying it. Mode all sets the tenant's default PDF layout, which every PDF template that names no layout of its own follows; mode selected saves a tenant draft per listed template and locale that names the layout (text and placeholders stay as they are, a system template gets its own tenant version first) and returns the ones it refused or could not write in skipped with the reason. Nothing is published; use publish-templates for that. The caller needs the right to edit the layout, and for selected also each template. Returns applied and skipped (both empty for mode all).",
56
+ handler: async (event, ctx) => {
57
+ const { layoutSlug, target } = event.payload;
58
+ const refused = refuseTemplateEdit(policy, event.user, {
59
+ slug: layoutSlug,
60
+ kind: "pdf-layout",
61
+ });
62
+ if (refused !== null)
63
+ return refused;
64
+ try {
65
+ await createTemplateResolverApi(ctx.db, ctx.registry).resolveLayout({
66
+ tenantId: event.user.tenantId,
67
+ slug: layoutSlug,
68
+ kind: "pdf-layout",
69
+ locale: FALLBACK_LOCALE,
70
+ });
71
+ }
72
+ catch (e) {
73
+ if (!(e instanceof TemplateNotFoundError))
74
+ throw e;
75
+ return writeFailure(new ValidationError({
76
+ fields: [
77
+ {
78
+ path: "layoutSlug",
79
+ code: TemplateResolverErrors.layoutNotPublished,
80
+ i18nKey: "templateResolver.errors.layout_not_published",
81
+ },
82
+ ],
83
+ }, { i18nKey: "templateResolver.errors.layout_not_published" }));
84
+ }
85
+ const applied = [];
86
+ const skipped = [];
87
+ if (target.mode === "all") {
88
+ const pointer = await ctx.dispatch.write(ConfigHandlers.set, {
89
+ key: DEFAULT_PDF_LAYOUT_SLUG_CONFIG_KEY,
90
+ value: layoutSlug,
91
+ });
92
+ if (!pointer.isSuccess)
93
+ return pointer;
94
+ return {
95
+ isSuccess: true,
96
+ data: { applied, skipped },
97
+ };
98
+ }
99
+ const seen = new Set();
100
+ for (const ref of target.templates) {
101
+ const key = `${ref.slug}\u0000${ref.locale}`;
102
+ if (seen.has(key))
103
+ continue;
104
+ seen.add(key);
105
+ if (refuseTemplateEdit(policy, event.user, { slug: ref.slug, kind: "document-pdf" })) {
106
+ skipped.push({ ...ref, reason: TemplateResolverErrors.templateNotTenantEditable });
107
+ continue;
108
+ }
109
+ const skip = await applyLayoutToDraft(ctx, event.user, layoutSlug, ref);
110
+ if (skip === null)
111
+ applied.push(ref);
112
+ else
113
+ skipped.push(skip);
114
+ }
115
+ return { isSuccess: true, data: { applied, skipped } };
116
+ },
117
+ });
118
+ }
@@ -0,0 +1,15 @@
1
+ import * as z from "zod";
2
+ import { type TemplateEditPolicy } from "../template-edit-policy.ts";
3
+ export declare function makeCreateLayoutWrite(policy: TemplateEditPolicy): import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<"create-layout", z.ZodObject<{
4
+ name: z.ZodString;
5
+ title: z.ZodString;
6
+ locale: z.ZodString;
7
+ }, z.core.$strip>, {
8
+ slug: string;
9
+ locale: string;
10
+ kind: "pdf-layout";
11
+ base: {
12
+ scope: "tenant";
13
+ version: number;
14
+ };
15
+ }, import("@cosmicdrift/kumiko-types/event-type-map").KumikoEventTypeMap, undefined, undefined>;