@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,6 +1,7 @@
1
- import { DEFAULT_LIST_LIMIT, entityListSchema, MAX_LIST_LIMIT, } from "@cosmicdrift/kumiko-framework/engine";
1
+ import { DEFAULT_LIST_LIMIT, entityListSchema, isUuid, MAX_LIST_LIMIT, } from "@cosmicdrift/kumiko-framework/engine";
2
2
  import { AccessDeniedError } from "@cosmicdrift/kumiko-framework/errors";
3
3
  import { requestExecutor } from "./entity.js";
4
+ import { openListCursor, sealListCursor } from "./list-cursor-seal.js";
4
5
  function allFilters(payload) {
5
6
  return [...(payload.filter === undefined ? [] : [payload.filter]), ...(payload.filters ?? [])];
6
7
  }
@@ -23,7 +24,26 @@ function subjectKey(subject) {
23
24
  const MAX_BASE_PAGES_PER_ANSWER = 10;
24
25
  // authorizeSubject usually queries the database; a page of 200 subjects must not take the whole pool.
25
26
  const SUBJECT_CHECKS_IN_PARALLEL = 10;
26
- export function scopeRequestList(base, scope) {
27
+ async function openFirstQuery(query, payload, user, cursorSecret) {
28
+ const { cursor: sealedCursor, ...payloadWithoutCursor } = payload;
29
+ if (sealedCursor === undefined)
30
+ return query;
31
+ const openedCursor = await openListCursor(sealedCursor, user, cursorSecret);
32
+ if (openedCursor === null)
33
+ throw new AccessDeniedError();
34
+ return { ...query, payload: { ...payloadWithoutCursor, cursor: openedCursor } };
35
+ }
36
+ async function sealedPage(page, visibleRows, nextCursor, user, cursorSecret) {
37
+ // `total` would count requests of foreign subjects. The base cursor names the last base row,
38
+ // which may belong to a foreign subject, so the user only gets it sealed.
39
+ const { total: _total, rows: _rows, nextCursor: _baseCursor, ...rest } = page;
40
+ return {
41
+ ...rest,
42
+ rows: visibleRows,
43
+ nextCursor: typeof nextCursor === "string" ? await sealListCursor(nextCursor, user, cursorSecret) : null,
44
+ };
45
+ }
46
+ export function scopeRequestList(base, scope, cursorSecret) {
27
47
  return {
28
48
  ...base,
29
49
  handler: async (query, ctx) => {
@@ -32,14 +52,16 @@ export function scopeRequestList(base, scope) {
32
52
  return base.handler(query, ctx);
33
53
  const payload = entityListSchema.parse(query.payload);
34
54
  // Group counts would include requests of foreign subjects, and an offset counts base rows,
35
- // not the rows this user sees; the screen pages by cursor.
36
- if (payload.aggregate !== undefined || (payload.offset ?? 0) > 0) {
55
+ // not the rows this user sees; the screen pages by cursor. limit 0 would hand out a cursor
56
+ // without checking a row.
57
+ if (payload.aggregate !== undefined || (payload.offset ?? 0) > 0 || payload.limit === 0) {
37
58
  throw new AccessDeniedError();
38
59
  }
39
60
  const limit = payload.limit ?? DEFAULT_LIST_LIMIT;
40
61
  const verdicts = new Map();
41
62
  const visibleRows = [];
42
- let page = await base.handler(query, ctx);
63
+ const firstQuery = await openFirstQuery(query, payload, user, cursorSecret);
64
+ let page = await base.handler(firstQuery, ctx);
43
65
  for (let fetched = 1;; fetched++) {
44
66
  if (!isRowsPage(page))
45
67
  throw new Error("signature request list did not return a rows page");
@@ -58,9 +80,7 @@ export function scopeRequestList(base, scope) {
58
80
  typeof nextCursor !== "string" ||
59
81
  fetched >= MAX_BASE_PAGES_PER_ANSWER ||
60
82
  verdicts.size >= MAX_LIST_LIMIT) {
61
- // `total` would count requests of foreign subjects; the cursor continues after the last base page.
62
- const { total: _total, rows: _rows, ...rest } = page;
63
- return { ...rest, rows: visibleRows };
83
+ return sealedPage(page, visibleRows, nextCursor, user, cursorSecret);
64
84
  }
65
85
  page = await base.handler({
66
86
  ...query,
@@ -103,6 +123,8 @@ export function scopeSignerList(base, scope) {
103
123
  typeof requestFilter.value !== "string") {
104
124
  throw new AccessDeniedError();
105
125
  }
126
+ if (!isUuid(requestFilter.value))
127
+ return emptyPage(payload);
106
128
  const request = await requestExecutor.detail({ id: requestFilter.value }, user, ctx.db);
107
129
  if (request === null || !(await scope.allowsRequest(ctx, user, request))) {
108
130
  return emptyPage(payload);
@@ -4,7 +4,7 @@ import { requestExecutor } from "./entity.js";
4
4
  import { discardGeneratedFile, PDF_MIME_TYPE, readTenantFile, sha256Hex, storeGeneratedFile, } from "./files.js";
5
5
  import { instantOrNull, isPastInstant, listSigners, } from "./lib.js";
6
6
  import { appendPdfPages, buildSignaturePageHtml, DEFAULT_SIGNATURE_PAGE_LABELS, } from "./signature-page.js";
7
- import { SIGNATURE_METHOD, SIGNATURE_REQUEST_STATUS, SignatureInternalHandlers, } from "./web/constants.js";
7
+ import { SIGNATURE_FAILURE_REASON, SIGNATURE_METHOD, SIGNATURE_REQUEST_STATUS, SignatureInternalHandlers, } from "./web/constants.js";
8
8
  // Equals the executor's MAX_LIST_LIMIT.
9
9
  const SWEEP_PAGE_SIZE = 200;
10
10
  // Keyset-paged, so rows that leave the status while the sweep works on them cannot shift the next page.
@@ -47,21 +47,38 @@ async function signaturePageEntries(ctx, signers) {
47
47
  }
48
48
  return entries;
49
49
  }
50
- // Appends the signature page to the unchanged original. A renderer outage throws, the request
51
- // stays all-signed and the next run tries again.
50
+ async function failRequest(ctx, request, reason) {
51
+ const failed = await ctx.dispatch.write(SignatureInternalHandlers.fail, {
52
+ requestId: request.id,
53
+ reason,
54
+ });
55
+ if (!failed.isSuccess) {
56
+ ctx.obs.log.error("[signature:sweep] marking the request failed was rejected", {
57
+ requestId: request.id,
58
+ reason,
59
+ error: failed.error,
60
+ });
61
+ return;
62
+ }
63
+ if (propertyOf(failed.data, "failed") === true) {
64
+ ctx.obs.log.warn("[signature:sweep] request cannot be completed, marked failed", {
65
+ requestId: request.id,
66
+ reason,
67
+ });
68
+ }
69
+ }
70
+ // Appends the signature page to the unchanged original. A missing or changed original or a
71
+ // missing signature image can never heal and ends the request as failed. A renderer outage
72
+ // throws, the request stays all-signed and the next run tries again.
52
73
  async function finalizeRequest(ctx, opts, request) {
53
74
  const original = await readTenantFile(ctx, ctx.systemUser.tenantId, request.documentFileId);
54
75
  if (original === null || sha256Hex(original.content) !== request.documentSha256) {
55
- ctx.obs.log.warn("[signature:sweep] original document missing or changed, not completing", {
56
- requestId: request.id,
57
- });
76
+ await failRequest(ctx, request, SIGNATURE_FAILURE_REASON.DocumentChanged);
58
77
  return;
59
78
  }
60
79
  const entries = await signaturePageEntries(ctx, await listSigners(ctx, ctx.systemUser, request.id));
61
80
  if (entries === null) {
62
- ctx.obs.log.warn("[signature:sweep] signature image missing, not completing", {
63
- requestId: request.id,
64
- });
81
+ await failRequest(ctx, request, SIGNATURE_FAILURE_REASON.SignatureImageMissing);
65
82
  return;
66
83
  }
67
84
  const html = buildSignaturePageHtml({
@@ -11,6 +11,7 @@ export declare const SIGNATURE_REQUEST_STATUS: {
11
11
  readonly Completed: "completed";
12
12
  readonly Declined: "declined";
13
13
  readonly Expired: "expired";
14
+ readonly Failed: "failed";
14
15
  readonly Cancelled: "cancelled";
15
16
  };
16
17
  export type SignatureRequestStatus = (typeof SIGNATURE_REQUEST_STATUS)[keyof typeof SIGNATURE_REQUEST_STATUS];
@@ -48,11 +49,18 @@ export declare const SIGNATURE_EVENT_SHORT: {
48
49
  readonly completed: "completed";
49
50
  readonly declined: "declined";
50
51
  readonly expired: "expired";
52
+ readonly failed: "failed";
51
53
  };
54
+ export declare const SIGNATURE_FAILURE_REASON: {
55
+ readonly DocumentChanged: "document-changed";
56
+ readonly SignatureImageMissing: "signature-image-missing";
57
+ };
58
+ export type SignatureFailureReason = (typeof SIGNATURE_FAILURE_REASON)[keyof typeof SIGNATURE_FAILURE_REASON];
52
59
  export declare const SignatureEvents: {
53
60
  readonly completed: "signature:event:completed";
54
61
  readonly declined: "signature:event:declined";
55
62
  readonly expired: "signature:event:expired";
63
+ readonly failed: "signature:event:failed";
56
64
  };
57
65
  export declare const SIGNATURE_INVALID_LINK_REASON = "invalid_or_expired_link";
58
66
  export declare const SIGNATURE_INVALID_IMAGE_REASON = "invalid_signature_image";
@@ -65,5 +73,6 @@ export declare const SignatureInternalHandlers: {
65
73
  readonly linkDecline: "signature:write:link-decline";
66
74
  readonly finish: "signature:write:finish";
67
75
  readonly expire: "signature:write:expire";
76
+ readonly fail: "signature:write:fail";
68
77
  readonly reconcile: "signature:write:reconcile";
69
78
  };
@@ -11,6 +11,7 @@ export const SIGNATURE_REQUEST_STATUS = {
11
11
  Completed: "completed",
12
12
  Declined: "declined",
13
13
  Expired: "expired",
14
+ Failed: "failed",
14
15
  Cancelled: "cancelled",
15
16
  };
16
17
  export const SIGNATURE_SIGNER_STATUS = {
@@ -45,11 +46,17 @@ export const SIGNATURE_EVENT_SHORT = {
45
46
  completed: "completed",
46
47
  declined: "declined",
47
48
  expired: "expired",
49
+ failed: "failed",
50
+ };
51
+ export const SIGNATURE_FAILURE_REASON = {
52
+ DocumentChanged: "document-changed",
53
+ SignatureImageMissing: "signature-image-missing",
48
54
  };
49
55
  export const SignatureEvents = {
50
56
  completed: `${SIGNATURE_FEATURE}:event:${SIGNATURE_EVENT_SHORT.completed}`,
51
57
  declined: `${SIGNATURE_FEATURE}:event:${SIGNATURE_EVENT_SHORT.declined}`,
52
58
  expired: `${SIGNATURE_FEATURE}:event:${SIGNATURE_EVENT_SHORT.expired}`,
59
+ failed: `${SIGNATURE_FEATURE}:event:${SIGNATURE_EVENT_SHORT.failed}`,
53
60
  };
54
61
  // Every link rejection (forged, expired, revoked, used up, already signed) carries this reason, so
55
62
  // a caller cannot tell the cases apart.
@@ -64,5 +71,6 @@ export const SignatureInternalHandlers = {
64
71
  linkDecline: `${SIGNATURE_FEATURE}:write:link-decline`,
65
72
  finish: `${SIGNATURE_FEATURE}:write:finish`,
66
73
  expire: `${SIGNATURE_FEATURE}:write:expire`,
74
+ fail: `${SIGNATURE_FEATURE}:write:fail`,
67
75
  reconcile: `${SIGNATURE_FEATURE}:write:reconcile`,
68
76
  };
@@ -111,6 +111,8 @@ export function createStripeCheckoutSession(runtime, { paymentInvoiceCreation =
111
111
  ...(mode === "subscription"
112
112
  ? { subscription_data: { metadata } }
113
113
  : {
114
+ // Session metadata too: a 100% promotion code completes without a PaymentIntent.
115
+ metadata,
114
116
  payment_intent_data: { metadata },
115
117
  invoice_creation: { enabled: paymentInvoiceCreation },
116
118
  // Without a customer, Stripe's default "if_required" makes a guest
@@ -300,9 +300,11 @@ function dropPaidSession(event, session, reason) {
300
300
  async function parsePaymentEvent(event, stripe) {
301
301
  const session = event.data.object; // @cast-boundary engine-bridge
302
302
  // mode !== "payment" excludes subscription-checkout sessions (same event types);
303
- // payment_status !== "paid" excludes an unpaid/expired session. Null here — not an
304
- // error — maps to foundation's 200 "ignored", same as the subscription-path's filters.
305
- if (session.mode !== "payment" || session.payment_status !== "paid") {
303
+ // any status but paid / no_payment_required (a 100% promotion code) excludes an
304
+ // unpaid/expired session. Null here — not an error — maps to foundation's 200 "ignored",
305
+ // same as the subscription-path's filters.
306
+ if (session.mode !== "payment" ||
307
+ (session.payment_status !== "paid" && session.payment_status !== "no_payment_required")) {
306
308
  return null;
307
309
  }
308
310
  // Lazy-fetch with expand: the raw webhook payload carries neither
@@ -321,21 +323,20 @@ async function parsePaymentEvent(event, stripe) {
321
323
  return null;
322
324
  throw transientProviderRejection(error);
323
325
  }
324
- // Tenant-resolution: mode:"payment" checkout sessions carry tenantId on
325
- // the PaymentIntent's OWN metadata (plugin-methods.ts sets it via
326
- // payment_intent_data.metadata), NOT on session-level metadata —
327
- // session.metadata is unset for this mode. Reading it off the expanded,
328
- // Stripe-verified PaymentIntent (not a freely-choosable payload field) is
329
- // what keeps tenant-attribution trustworthy: the webhook signature proves
330
- // this whole object chain came from Stripe, and the metadata itself was
331
- // set by our own backend at checkout-creation time.
326
+ // Tenant-resolution: plugin-methods.ts sets tenantId on the PaymentIntent metadata and on the
327
+ // session metadata. A 100% promotion code creates no PaymentIntent, so the session metadata
328
+ // is only read then. Both are set by our own backend at checkout-creation time and reach us
329
+ // through the signature-verified webhook chain, not as a freely-choosable payload field.
332
330
  const paymentIntent = expanded.payment_intent;
333
- if (!paymentIntent || typeof paymentIntent === "string") {
334
- // Not expanded (Stripe-API-drift) or absent — no verified tenant-claim
331
+ if (typeof paymentIntent === "string" ||
332
+ (paymentIntent === null && session.payment_status === "paid")) {
333
+ // Not expanded (Stripe-API-drift) or absent on a paid session — no verified tenant-claim
335
334
  // to trust.
336
335
  return dropPaidSession(event, session, "payment_intent_not_expanded");
337
336
  }
338
- const tenantId = paymentIntent.metadata?.["tenantId"];
337
+ const tenantId = paymentIntent
338
+ ? paymentIntent.metadata?.["tenantId"]
339
+ : expanded.metadata?.["tenantId"];
339
340
  if (!tenantId || tenantId.length === 0) {
340
341
  return dropPaidSession(event, session, "missing_tenant_id");
341
342
  }
@@ -348,9 +349,9 @@ async function parsePaymentEvent(event, stripe) {
348
349
  // customer, which Stripe sets independently of the session-level field.
349
350
  const sessionCustomer = expanded.customer;
350
351
  const providerCustomerId = (typeof sessionCustomer === "string" ? sessionCustomer : sessionCustomer?.id) ??
351
- (typeof paymentIntent.customer === "string"
352
+ (typeof paymentIntent?.customer === "string"
352
353
  ? paymentIntent.customer
353
- : paymentIntent.customer?.id);
354
+ : paymentIntent?.customer?.id);
354
355
  if (!providerCustomerId) {
355
356
  return dropPaidSession(event, session, "missing_customer");
356
357
  }
@@ -1,5 +1,6 @@
1
1
  import { isOneOf } from "@cosmicdrift/kumiko-types/type-guards";
2
2
  import { isResourceImageContentType } from "../shared/index.js";
3
+ import { appendStyle, applyDocumentPrintStyles } from "./compile-document-styles.js";
3
4
  import { rewriteStepsBlock } from "./compile-steps-block.js";
4
5
  import { conditionScopeElement, withParsedDocument } from "./document-sanitizer.js";
5
6
  import { DOCUMENT_CONDITION_ATTRIBUTE, DOCUMENT_TEXT_ALIGNMENTS, isAllowedDocumentUrlHref, isDocumentPlaceholderHref, isDocumentReferenceName, isDocumentResourceKey, } from "./web/document-schema.js";
@@ -170,11 +171,6 @@ const MAIL_HEADING_STYLES = {
170
171
  h2: "margin:0 0 12px 0;font-size:24px;line-height:1.2;font-weight:700;letter-spacing:-0.02em;color:#0B0D12",
171
172
  h3: "margin:20px 0 8px 0;font-size:17px;line-height:1.3;font-weight:600;color:#0B0D12",
172
173
  };
173
- // Appended after an existing style (data-align) so the alignment survives.
174
- function appendStyle(element, style) {
175
- const existing = element.getAttribute("style");
176
- element.setAttribute("style", existing === null ? style : `${existing};${style}`);
177
- }
178
174
  function collectUniqueValidAttributes(html, selector, attribute, isValid) {
179
175
  return withParsedDocument(html, (root) => {
180
176
  const values = new Set();
@@ -228,7 +224,7 @@ function rewriteAlignment(element) {
228
224
  const align = element.getAttribute("data-align");
229
225
  element.removeAttribute("data-align");
230
226
  if (isOneOf(DOCUMENT_TEXT_ALIGNMENTS, align))
231
- element.setAttribute("style", `text-align:${align}`);
227
+ appendStyle(element, `text-align:${align}`);
232
228
  }
233
229
  function rewriteResourceImage(element, resourceSrc, maxWidthPx, maxHeightPx) {
234
230
  const key = element.getAttribute("data-resource") ?? "";
@@ -299,6 +295,7 @@ export function compileDocumentBodyToHandlebars(html, variables, options = {}) {
299
295
  const scrubbed = html.replaceAll(EXPRESSION_OPEN, "").replaceAll(EXPRESSION_CLOSE, "");
300
296
  const compiled = withParsedDocument(scrubbed, (root) => {
301
297
  stripScriptsAndActiveContent(root, options);
298
+ applyDocumentPrintStyles(root);
302
299
  if (options.alignmentAsInlineStyle === true)
303
300
  applyAlignmentInlineStyles(root);
304
301
  if (options.headingAsInlineStyle === true)
@@ -0,0 +1,3 @@
1
+ import type { Element as ScanElement } from "happy-dom";
2
+ export declare function appendStyle(element: ScanElement, style: string): void;
3
+ export declare function applyDocumentPrintStyles(root: ScanElement): void;
@@ -0,0 +1,84 @@
1
+ import { readBlockStyleAttributes, readCellBackground, readColwidth, readFrameAttributes, readTextStyleAttributes, } from "./web/document-print-style.js";
2
+ import { documentBlockStyleCss, documentCellStyleCss, documentFrameCss, documentTextStyleCss, } from "./web/document-style-css.js";
3
+ // Appended after an existing style (data-align) so the alignment survives.
4
+ export function appendStyle(element, style) {
5
+ if (style === "")
6
+ return;
7
+ const existing = element.getAttribute("style");
8
+ element.setAttribute("style", existing === null ? style : `${existing};${style}`);
9
+ }
10
+ function addClass(element, className) {
11
+ const existing = element.getAttribute("class");
12
+ element.setAttribute("class", existing === null ? className : `${existing} ${className}`);
13
+ }
14
+ function roundPercent(value) {
15
+ return Math.round(value * 100) / 100;
16
+ }
17
+ // Percentages sum to exactly 100 so the table keeps the full content width.
18
+ function columnPercentages(widths) {
19
+ const total = widths.reduce((sum, width) => sum + width, 0);
20
+ const percentages = widths.map((width) => roundPercent((width / total) * 100));
21
+ const last = percentages.length - 1;
22
+ const others = percentages.slice(0, last).reduce((sum, value) => sum + value, 0);
23
+ percentages[last] = roundPercent(100 - others);
24
+ return percentages;
25
+ }
26
+ function firstRowColumnWidths(table) {
27
+ const firstRow = Array.from(table.querySelectorAll("tr")).find((row) => row.closest("table") === table);
28
+ if (firstRow === undefined)
29
+ return null;
30
+ const widths = [];
31
+ for (const cell of Array.from(firstRow.children)) {
32
+ const colwidth = readColwidth(cell);
33
+ const span = Number(cell.getAttribute("colspan") ?? 1);
34
+ if (colwidth === null || colwidth.length !== span)
35
+ return null;
36
+ widths.push(...colwidth);
37
+ }
38
+ return widths.length > 0 ? widths : null;
39
+ }
40
+ function insertColgroup(table, widths) {
41
+ const document = table.ownerDocument;
42
+ const colgroup = document.createElement("colgroup");
43
+ for (const percentage of columnPercentages(widths)) {
44
+ const col = document.createElement("col");
45
+ col.setAttribute("style", `width:${percentage}%`);
46
+ colgroup.append(col);
47
+ }
48
+ table.insertBefore(colgroup, table.firstChild);
49
+ }
50
+ function applyFrames(root) {
51
+ for (const frame of Array.from(root.querySelectorAll("div[data-frame]"))) {
52
+ const box = readFrameAttributes(frame);
53
+ if (box === null) {
54
+ frame.replaceWith(...Array.from(frame.childNodes));
55
+ continue;
56
+ }
57
+ addClass(frame, "kumiko-frame");
58
+ appendStyle(frame, documentFrameCss(box));
59
+ }
60
+ }
61
+ function applyTables(root) {
62
+ for (const table of Array.from(root.querySelectorAll("table"))) {
63
+ if (table.getAttribute("data-borders") === "none")
64
+ addClass(table, "kumiko-table-plain");
65
+ const widths = firstRowColumnWidths(table);
66
+ if (widths !== null)
67
+ insertColgroup(table, widths);
68
+ }
69
+ for (const cell of Array.from(root.querySelectorAll("td, th"))) {
70
+ appendStyle(cell, documentCellStyleCss({ background: readCellBackground(cell) }));
71
+ }
72
+ }
73
+ // Runs before the placeholder rewrites: a rich text block host copies its paragraph's
74
+ // attributes, so the style has to be on the paragraph by then.
75
+ export function applyDocumentPrintStyles(root) {
76
+ applyFrames(root);
77
+ applyTables(root);
78
+ for (const span of Array.from(root.querySelectorAll("span[data-text-style]"))) {
79
+ appendStyle(span, documentTextStyleCss(readTextStyleAttributes(span)));
80
+ }
81
+ for (const block of Array.from(root.querySelectorAll("p, h1, h2, h3"))) {
82
+ appendStyle(block, documentBlockStyleCss(readBlockStyleAttributes(block)));
83
+ }
84
+ }
@@ -0,0 +1,3 @@
1
+ import { type DocumentFrameAttributes } from "./web/document-print-style.ts";
2
+ export declare function readTopLevelFrames(html: string): readonly DocumentFrameAttributes[];
3
+ export declare function flattenFramesForPreview(compiledHtml: string): string;
@@ -0,0 +1,19 @@
1
+ // Server-only (happy-dom). Frames are read from the stored body for page planning, and flattened
2
+ // for the editor preview, which shows the body outside a page where absolute coordinates mean nothing.
3
+ import { withParsedDocument } from "./document-sanitizer.js";
4
+ import { readFrameAttributes } from "./web/document-print-style.js";
5
+ const PREVIEW_FRAME_STYLE = "margin:8px 0;padding:6px;border:1px dashed #9ca3af;white-space:pre-line";
6
+ export function readTopLevelFrames(html) {
7
+ return withParsedDocument(html, (body) => Array.from(body.children).flatMap((child) => {
8
+ const frame = child.matches("div[data-frame]") ? readFrameAttributes(child) : null;
9
+ return frame === null ? [] : [frame];
10
+ }));
11
+ }
12
+ export function flattenFramesForPreview(compiledHtml) {
13
+ return withParsedDocument(compiledHtml, (body) => {
14
+ for (const frame of Array.from(body.querySelectorAll("div.kumiko-frame"))) {
15
+ frame.setAttribute("style", PREVIEW_FRAME_STYLE);
16
+ }
17
+ return body.innerHTML;
18
+ });
19
+ }