@memberjunction/core-entities 6.3.0-edge.0 → 6.3.0-edge.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/custom/AnchoredConversationSecurity.d.ts +10 -1
  3. package/dist/custom/AnchoredConversationSecurity.d.ts.map +1 -1
  4. package/dist/custom/AnchoredConversationSecurity.js +15 -0
  5. package/dist/custom/AnchoredConversationSecurity.js.map +1 -1
  6. package/dist/custom/ArtifactLockValidation.d.ts +28 -0
  7. package/dist/custom/ArtifactLockValidation.d.ts.map +1 -0
  8. package/dist/custom/ArtifactLockValidation.js +867 -0
  9. package/dist/custom/ArtifactLockValidation.js.map +1 -0
  10. package/dist/custom/ArtifactPermissionDelegate.d.ts +267 -0
  11. package/dist/custom/ArtifactPermissionDelegate.d.ts.map +1 -0
  12. package/dist/custom/ArtifactPermissionDelegate.js +1232 -0
  13. package/dist/custom/ArtifactPermissionDelegate.js.map +1 -0
  14. package/dist/custom/ArtifactPreviewSnapshot.d.ts +199 -0
  15. package/dist/custom/ArtifactPreviewSnapshot.d.ts.map +1 -0
  16. package/dist/custom/ArtifactPreviewSnapshot.js +772 -0
  17. package/dist/custom/ArtifactPreviewSnapshot.js.map +1 -0
  18. package/dist/custom/ArtifactSynthesisEngine.d.ts +151 -0
  19. package/dist/custom/ArtifactSynthesisEngine.d.ts.map +1 -0
  20. package/dist/custom/ArtifactSynthesisEngine.js +1124 -0
  21. package/dist/custom/ArtifactSynthesisEngine.js.map +1 -0
  22. package/dist/custom/ConversationWriteAccess.d.ts +27 -0
  23. package/dist/custom/ConversationWriteAccess.d.ts.map +1 -1
  24. package/dist/custom/ConversationWriteAccess.js +53 -0
  25. package/dist/custom/ConversationWriteAccess.js.map +1 -1
  26. package/dist/custom/DocumentLiveBlockEngine.d.ts +612 -0
  27. package/dist/custom/DocumentLiveBlockEngine.d.ts.map +1 -0
  28. package/dist/custom/DocumentLiveBlockEngine.js +2352 -0
  29. package/dist/custom/DocumentLiveBlockEngine.js.map +1 -0
  30. package/dist/custom/MJQueryEntityExtended.d.ts.map +1 -1
  31. package/dist/custom/MJQueryEntityExtended.js +27 -11
  32. package/dist/custom/MJQueryEntityExtended.js.map +1 -1
  33. package/dist/custom/PermissionProviders/ArtifactPermissionProvider.d.ts.map +1 -1
  34. package/dist/custom/PermissionProviders/ArtifactPermissionProvider.js +31 -7
  35. package/dist/custom/PermissionProviders/ArtifactPermissionProvider.js.map +1 -1
  36. package/dist/custom/PermissionProviders/CollectionPermissionProvider.d.ts +3 -4
  37. package/dist/custom/PermissionProviders/CollectionPermissionProvider.d.ts.map +1 -1
  38. package/dist/custom/PermissionProviders/CollectionPermissionProvider.js +334 -47
  39. package/dist/custom/PermissionProviders/CollectionPermissionProvider.js.map +1 -1
  40. package/dist/custom/Permissions/BaseShareEntityExtended.d.ts +19 -3
  41. package/dist/custom/Permissions/BaseShareEntityExtended.d.ts.map +1 -1
  42. package/dist/custom/Permissions/BaseShareEntityExtended.js +139 -13
  43. package/dist/custom/Permissions/BaseShareEntityExtended.js.map +1 -1
  44. package/dist/custom/Permissions/MJArtifactPermissionEntityExtended.d.ts +8 -6
  45. package/dist/custom/Permissions/MJArtifactPermissionEntityExtended.d.ts.map +1 -1
  46. package/dist/custom/Permissions/MJArtifactPermissionEntityExtended.js +93 -41
  47. package/dist/custom/Permissions/MJArtifactPermissionEntityExtended.js.map +1 -1
  48. package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.d.ts +12 -5
  49. package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.d.ts.map +1 -1
  50. package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.js +240 -37
  51. package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.js.map +1 -1
  52. package/dist/custom/SlideDeckEngine.d.ts +427 -0
  53. package/dist/custom/SlideDeckEngine.d.ts.map +1 -0
  54. package/dist/custom/SlideDeckEngine.js +1669 -0
  55. package/dist/custom/SlideDeckEngine.js.map +1 -0
  56. package/dist/custom/SlideDeckPptxEngine.d.ts +25 -0
  57. package/dist/custom/SlideDeckPptxEngine.d.ts.map +1 -0
  58. package/dist/custom/SlideDeckPptxEngine.js +1237 -0
  59. package/dist/custom/SlideDeckPptxEngine.js.map +1 -0
  60. package/dist/custom/SpreadsheetEngine.d.ts +1370 -0
  61. package/dist/custom/SpreadsheetEngine.d.ts.map +1 -0
  62. package/dist/custom/SpreadsheetEngine.js +17580 -0
  63. package/dist/custom/SpreadsheetEngine.js.map +1 -0
  64. package/dist/custom/approvals.d.ts +7 -1
  65. package/dist/custom/approvals.d.ts.map +1 -1
  66. package/dist/custom/approvals.js +8 -1
  67. package/dist/custom/approvals.js.map +1 -1
  68. package/dist/custom/operations/ArtifactComplianceAuditOperation.d.ts +7 -0
  69. package/dist/custom/operations/ArtifactComplianceAuditOperation.d.ts.map +1 -0
  70. package/dist/custom/operations/ArtifactComplianceAuditOperation.js +7 -0
  71. package/dist/custom/operations/ArtifactComplianceAuditOperation.js.map +1 -0
  72. package/dist/custom/operations/ArtifactEvaluateAiFormulaOperation.d.ts +7 -0
  73. package/dist/custom/operations/ArtifactEvaluateAiFormulaOperation.d.ts.map +1 -0
  74. package/dist/custom/operations/ArtifactEvaluateAiFormulaOperation.js +7 -0
  75. package/dist/custom/operations/ArtifactEvaluateAiFormulaOperation.js.map +1 -0
  76. package/dist/custom/operations/ArtifactGuestShareOperations.d.ts +60 -0
  77. package/dist/custom/operations/ArtifactGuestShareOperations.d.ts.map +1 -0
  78. package/dist/custom/operations/ArtifactGuestShareOperations.js +6 -0
  79. package/dist/custom/operations/ArtifactGuestShareOperations.js.map +1 -0
  80. package/dist/custom/operations/SynthesizeArtifactFromSourcesOperation.d.ts +7 -0
  81. package/dist/custom/operations/SynthesizeArtifactFromSourcesOperation.d.ts.map +1 -0
  82. package/dist/custom/operations/SynthesizeArtifactFromSourcesOperation.js +7 -0
  83. package/dist/custom/operations/SynthesizeArtifactFromSourcesOperation.js.map +1 -0
  84. package/dist/custom/typedQuery.d.ts +162 -0
  85. package/dist/custom/typedQuery.d.ts.map +1 -0
  86. package/dist/custom/typedQuery.js +296 -0
  87. package/dist/custom/typedQuery.js.map +1 -0
  88. package/dist/engines/CanonGraphEngine.d.ts +1 -1
  89. package/dist/engines/CanonGraphEngine.d.ts.map +1 -1
  90. package/dist/engines/CanonGraphEngine.js +19 -14
  91. package/dist/engines/CanonGraphEngine.js.map +1 -1
  92. package/dist/engines/EncryptionEngineBase.js +2 -2
  93. package/dist/engines/EncryptionEngineBase.js.map +1 -1
  94. package/dist/engines/QueryEngine.js +2 -2
  95. package/dist/engines/QueryEngine.js.map +1 -1
  96. package/dist/engines/SearchEngineBase.d.ts +17 -3
  97. package/dist/engines/SearchEngineBase.d.ts.map +1 -1
  98. package/dist/engines/SearchEngineBase.js +100 -28
  99. package/dist/engines/SearchEngineBase.js.map +1 -1
  100. package/dist/engines/UserInfoEngine.d.ts +8 -0
  101. package/dist/engines/UserInfoEngine.d.ts.map +1 -1
  102. package/dist/engines/UserInfoEngine.js +50 -3
  103. package/dist/engines/UserInfoEngine.js.map +1 -1
  104. package/dist/engines/conversations.d.ts +54 -2
  105. package/dist/engines/conversations.d.ts.map +1 -1
  106. package/dist/engines/conversations.js +144 -12
  107. package/dist/engines/conversations.js.map +1 -1
  108. package/dist/generated/entities/__mj.d.ts +1076 -25406
  109. package/dist/generated/entities/__mj.d.ts.map +1 -1
  110. package/dist/generated/entities/__mj.js +636 -41542
  111. package/dist/generated/entities/__mj.js.map +1 -1
  112. package/dist/generated/queries/__mj.d.ts +12 -12
  113. package/dist/generated/queries/__mj.d.ts.map +1 -1
  114. package/dist/generated/queries/__mj.js +1 -1
  115. package/dist/generated/queries/__mj.js.map +1 -1
  116. package/dist/generated/remote_operations.d.ts +225 -0
  117. package/dist/generated/remote_operations.d.ts.map +1 -1
  118. package/dist/generated/remote_operations.js +95 -0
  119. package/dist/generated/remote_operations.js.map +1 -1
  120. package/dist/generated/schemas/__mj.d.ts +25489 -0
  121. package/dist/generated/schemas/__mj.d.ts.map +1 -0
  122. package/dist/generated/schemas/__mj.js +41768 -0
  123. package/dist/generated/schemas/__mj.js.map +1 -0
  124. package/dist/generated/schemas.d.ts +2 -0
  125. package/dist/generated/schemas.d.ts.map +1 -0
  126. package/dist/generated/schemas.js +2 -0
  127. package/dist/generated/schemas.js.map +1 -0
  128. package/dist/graph/GraphEngine.d.ts +19 -0
  129. package/dist/graph/GraphEngine.d.ts.map +1 -1
  130. package/dist/graph/GraphEngine.js +90 -0
  131. package/dist/graph/GraphEngine.js.map +1 -1
  132. package/dist/index.d.ts +12 -0
  133. package/dist/index.d.ts.map +1 -1
  134. package/dist/index.js +18 -0
  135. package/dist/index.js.map +1 -1
  136. package/dist/schemas.d.ts +6 -0
  137. package/dist/schemas.d.ts.map +1 -0
  138. package/dist/schemas.js +6 -0
  139. package/dist/schemas.js.map +1 -0
  140. package/package.json +17 -6
@@ -0,0 +1,1669 @@
1
+ import { BaseSingleton, UUIDsEqual } from '@memberjunction/global';
2
+ import { BuildBlockIdentityBinding, ComputeFrozenSnapshotHash, DocumentLiveBlockEngine } from './DocumentLiveBlockEngine.js';
3
+ import { ExportDeckToPptxBytesInternal, ImportDeckFromPptxBytesInternal } from './SlideDeckPptxEngine.js';
4
+ /**
5
+ * Canonical layout catalog for MJ Slides (`§ 5.1`).
6
+ */
7
+ export const SLIDE_LAYOUT_CATALOG = [
8
+ {
9
+ Kind: 'Title',
10
+ Label: 'Title Slide',
11
+ Description: 'Executive cover slide with headline title, subtitle, and presenter callout.',
12
+ Icon: 'fa-solid fa-heading',
13
+ DefaultRegionCount: 1
14
+ },
15
+ {
16
+ Kind: 'SectionHeader',
17
+ Label: 'Section Break',
18
+ Description: 'Bold chapter divider introducing a new strategic topic or agenda section.',
19
+ Icon: 'fa-solid fa-grip-lines',
20
+ DefaultRegionCount: 1
21
+ },
22
+ {
23
+ Kind: 'TitleAndBody',
24
+ Label: 'Title & Body',
25
+ Description: 'Standard content slide with title bar and a full-width rich content or block region.',
26
+ Icon: 'fa-solid fa-align-left',
27
+ DefaultRegionCount: 1
28
+ },
29
+ {
30
+ Kind: 'TwoColumn',
31
+ Label: 'Two Columns',
32
+ Description: 'Side-by-side regions for narrative + diagram, table, or embedded Whiteboard.',
33
+ Icon: 'fa-solid fa-table-columns',
34
+ DefaultRegionCount: 2
35
+ },
36
+ {
37
+ Kind: 'Comparison',
38
+ Label: 'Comparison',
39
+ Description: 'Structured left-vs-right comparison cards with distinct headers and takeaways.',
40
+ Icon: 'fa-solid fa-scale-balanced',
41
+ DefaultRegionCount: 2
42
+ },
43
+ {
44
+ Kind: 'LiveDataSlide',
45
+ Label: 'Live MJ Data & Narrative',
46
+ Description: 'Primary viewer-scoped Live MJ Block (EntityView / SavedQuery) paired with executive insights.',
47
+ Icon: 'fa-solid fa-database',
48
+ DefaultRegionCount: 2
49
+ },
50
+ {
51
+ Kind: 'ChartAndText',
52
+ Label: 'Chart / Visual & Text',
53
+ Description: 'Visual chart or OLE Whiteboard region on the left with key findings on the right.',
54
+ Icon: 'fa-solid fa-chart-column',
55
+ DefaultRegionCount: 2
56
+ },
57
+ {
58
+ Kind: 'BigNumber',
59
+ Label: 'Big Number KPI',
60
+ Description: 'High-impact KPI metric callout paired with supporting context and drivers.',
61
+ Icon: 'fa-solid fa-arrow-trend-up',
62
+ DefaultRegionCount: 2
63
+ },
64
+ {
65
+ Kind: 'Quote',
66
+ Label: 'Executive Quote',
67
+ Description: 'Full-width customer or leadership pull-quote with attribution.',
68
+ Icon: 'fa-solid fa-quote-left',
69
+ DefaultRegionCount: 1
70
+ },
71
+ {
72
+ Kind: 'FullBleedImage',
73
+ Label: 'Full-Bleed Visual',
74
+ Description: 'Edge-to-edge architecture diagram or visual with overlay caption.',
75
+ Icon: 'fa-solid fa-image',
76
+ DefaultRegionCount: 1
77
+ },
78
+ {
79
+ Kind: 'Blank',
80
+ Label: 'Blank / Full Canvas',
81
+ Description: 'Full-bleed region ideal for an interactive embedded OLE Whiteboard canvas.',
82
+ Icon: 'fa-solid fa-chalkboard',
83
+ DefaultRegionCount: 1
84
+ }
85
+ ];
86
+ /**
87
+ * Built-in theme presets for MJ Slides (`§ 5.1`).
88
+ */
89
+ export const SLIDE_DECK_THEME_PRESETS = [
90
+ {
91
+ ThemeID: 'mj-default',
92
+ Name: 'MJ Brand Indigo',
93
+ PrimaryColor: '#4f46e5',
94
+ AccentColor: '#0ea5e9',
95
+ BackgroundColor: '#ffffff',
96
+ SurfaceColor: '#f8fafc',
97
+ TextColor: '#0f172a',
98
+ MutedTextColor: '#475569',
99
+ HeadingFont: 'Inter, system-ui, sans-serif',
100
+ BodyFont: 'Inter, system-ui, sans-serif',
101
+ BrandSeedSource: 'MJ Default Design Tokens'
102
+ },
103
+ {
104
+ ThemeID: 'executive-slate',
105
+ Name: 'Executive Midnight Slate',
106
+ PrimaryColor: '#38bdf8',
107
+ AccentColor: '#818cf8',
108
+ BackgroundColor: '#0f172a',
109
+ SurfaceColor: '#1e293b',
110
+ TextColor: '#f8fafc',
111
+ MutedTextColor: '#cbd5e1',
112
+ HeadingFont: 'Inter, system-ui, sans-serif',
113
+ BodyFont: 'Inter, system-ui, sans-serif',
114
+ BrandSeedSource: 'Executive Dark Suite'
115
+ },
116
+ {
117
+ ThemeID: 'emerald-growth',
118
+ Name: 'Emerald Enterprise Growth',
119
+ PrimaryColor: '#047857',
120
+ AccentColor: '#10b981',
121
+ BackgroundColor: '#ffffff',
122
+ SurfaceColor: '#f0fdf4',
123
+ TextColor: '#064e3b',
124
+ MutedTextColor: '#374151',
125
+ HeadingFont: 'Inter, system-ui, sans-serif',
126
+ BodyFont: 'Inter, system-ui, sans-serif',
127
+ BrandSeedSource: 'Emerald Brand Kit'
128
+ },
129
+ {
130
+ ThemeID: 'crimson-bold',
131
+ Name: 'Crimson Boardroom',
132
+ PrimaryColor: '#b91c1c',
133
+ AccentColor: '#f59e0b',
134
+ BackgroundColor: '#ffffff',
135
+ SurfaceColor: '#fef2f2',
136
+ TextColor: '#111827',
137
+ MutedTextColor: '#4b5563',
138
+ HeadingFont: 'Georgia, serif',
139
+ BodyFont: 'Inter, system-ui, sans-serif',
140
+ BrandSeedSource: 'Crimson Brand Kit'
141
+ }
142
+ ];
143
+ /**
144
+ * Isomorphic engine for parsing, constructing, mutating, theming, and converting
145
+ * MJ Slide Decks (`Presentation` artifacts, `plans/docs-slides-sheets.md § 5`).
146
+ */
147
+ export class SlideDeckEngine extends BaseSingleton {
148
+ constructor() {
149
+ super();
150
+ }
151
+ /** Returns the process-wide singleton instance of {@link SlideDeckEngine}. */
152
+ static get Instance() {
153
+ return super.getInstance();
154
+ }
155
+ /**
156
+ * Returns the built-in theme presets available for slide decks.
157
+ */
158
+ GetThemePresets() {
159
+ return SLIDE_DECK_THEME_PRESETS;
160
+ }
161
+ /**
162
+ * Returns the canonical slide layout catalog.
163
+ */
164
+ GetLayoutCatalog() {
165
+ return SLIDE_LAYOUT_CATALOG;
166
+ }
167
+ /**
168
+ * Validates a CSS property value (color, gradient, font family, or length) against a strict
169
+ * allow-list before interpolating it into a `<style>` block or theme spec.
170
+ * Any value not matching the allow-list returns `fallback`.
171
+ */
172
+ SanitizeCssValue(raw, fallback = '') {
173
+ const trimmed = String(raw ?? '').trim();
174
+ if (!trimmed || trimmed.length > 300) {
175
+ return fallback;
176
+ }
177
+ // Reject any comment delimiters, statement/block delimiters, escapes, or forbidden functions
178
+ if (/[;{}<>\\/*@]/.test(trimmed) || /\b(?:url|image-set|expression|javascript|vbscript)\b/i.test(trimmed)) {
179
+ return fallback;
180
+ }
181
+ // 1. Hex colors (#rgb, #rgba, #rrggbb, #rrggbbaa)
182
+ if (/^#[0-9a-f]{3,8}$/i.test(trimmed)) {
183
+ return trimmed;
184
+ }
185
+ // 2. Functional colors: rgb(), rgba(), hsl(), hsla()
186
+ if (/^(?:rgba?|hsla?)\(\s*[0-9.%\s,/+-]+\s*\)$/i.test(trimmed)) {
187
+ return trimmed;
188
+ }
189
+ // 3. CSS custom property reference: var(--name) or var(--name, #hex)
190
+ if (/^var\(\s*--[a-z0-9_-]+(?:\s*,\s*#[0-9a-f]{3,8})?\s*\)$/i.test(trimmed)) {
191
+ return trimmed;
192
+ }
193
+ // 4. Safe gradients: linear-gradient(...) or radial-gradient(...) with only color/angle/stop tokens
194
+ if (/^(?:linear|radial)-gradient\(\s*[#a-z0-9.%,\s()-]+\s*\)$/i.test(trimmed)) {
195
+ // Verify balanced parentheses (reject unbalanced ')' that could break out of CSS declarations)
196
+ let parenDepth = 0;
197
+ for (let i = 0; i < trimmed.length; i++) {
198
+ const ch = trimmed.charAt(i);
199
+ if (ch === '(') {
200
+ parenDepth++;
201
+ }
202
+ else if (ch === ')') {
203
+ parenDepth--;
204
+ if (parenDepth < 0) {
205
+ return fallback;
206
+ }
207
+ }
208
+ }
209
+ if (parenDepth !== 0) {
210
+ return fallback;
211
+ }
212
+ // Ensure the only nested functions inside a gradient are rgb/rgba/hsl/hsla
213
+ const innerFns = trimmed
214
+ .replace(/^(?:linear|radial)-gradient\(/i, '')
215
+ .match(/[a-z_-]+\s*\(/gi);
216
+ const allInnerSafe = !innerFns || innerFns.every((fn) => /^(?:rgba?|hsla?)\s*\($/i.test(fn));
217
+ if (allInnerSafe) {
218
+ return trimmed;
219
+ }
220
+ return fallback;
221
+ }
222
+ // 5. Font-family stacks, named colors, or simple numeric lengths (no colons, parens, or slashes)
223
+ if (/^[a-z0-9\s,'".%-]+$/i.test(trimmed)) {
224
+ return trimmed;
225
+ }
226
+ return fallback;
227
+ }
228
+ /**
229
+ * Validates an image or logo URL for slides (`ImageUrl` / `Master.LogoUrl`).
230
+ * Allows `https://`, `http://`, same-origin relative `/...` paths (not `//`), and
231
+ * raster `data:image/(png|jpeg|jpg|webp|gif);base64,...` data URLs.
232
+ * Rejects `javascript:`, `vbscript:`, `data:text/html`, `data:image/svg+xml`, and control chars.
233
+ */
234
+ SanitizeImageUrl(raw) {
235
+ const trimmed = String(raw ?? '').trim();
236
+ if (!trimmed || trimmed.length > 1_048_576) {
237
+ return undefined;
238
+ }
239
+ if (/[\u0000-\u001F\u007F]/.test(trimmed)) {
240
+ return undefined;
241
+ }
242
+ if (/^(?:javascript|vbscript|file):/i.test(trimmed)) {
243
+ return undefined;
244
+ }
245
+ if (/^data:/i.test(trimmed)) {
246
+ const safeRasterDataUrl = /^data:image\/(?:png|jpeg|jpg|webp|gif);base64,[A-Za-z0-9+/=]+$/i;
247
+ return safeRasterDataUrl.test(trimmed) ? trimmed : undefined;
248
+ }
249
+ if (trimmed.startsWith('/') && !trimmed.startsWith('//')) {
250
+ return trimmed;
251
+ }
252
+ if (/^https?:\/\/[^\s"'<>]+$/i.test(trimmed)) {
253
+ return trimmed;
254
+ }
255
+ return undefined;
256
+ }
257
+ /**
258
+ * Renders a standalone printable HTML document for `deck` with sanitized CSS theme tokens.
259
+ */
260
+ RenderPrintHtml(deck) {
261
+ const escapeHtml = (str) => String(str ?? '')
262
+ .replace(/&/g, '&amp;')
263
+ .replace(/</g, '&lt;')
264
+ .replace(/>/g, '&gt;')
265
+ .replace(/"/g, '&quot;')
266
+ .replace(/'/g, '&#39;');
267
+ const renderInlineMarkdown = (raw) => {
268
+ const escaped = escapeHtml(raw);
269
+ return escaped
270
+ .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
271
+ .replace(/\*([^*]+)\*/g, '<em>$1</em>')
272
+ .replace(/`([^`]+)`/g, '<code>$1</code>');
273
+ };
274
+ const renderBlockHtml = (region, block) => {
275
+ const snap = block.FrozenSnapshot;
276
+ const titleText = escapeHtml(block.Title || region.Label || block.Kind);
277
+ if (snap && Array.isArray(snap.Columns) && snap.Columns.length > 0 && Array.isArray(snap.Rows)) {
278
+ const headers = snap.Columns.map((col) => `<th>${escapeHtml(col.DisplayName || col.Name)}</th>`).join('');
279
+ const bodyRows = snap.Rows.slice(0, 100)
280
+ .map((row) => {
281
+ const cells = snap.Columns.map((col) => {
282
+ const cellVal = row[col.Name];
283
+ return `<td>${escapeHtml(cellVal === null || cellVal === undefined ? '' : String(cellVal))}</td>`;
284
+ }).join('');
285
+ return `<tr>${cells}</tr>`;
286
+ })
287
+ .join('');
288
+ return `<div class="slide-block" data-block-id="${escapeHtml(block.BlockID)}"><div class="slide-block-title">${titleText}</div><table class="slide-block-table"><thead><tr>${headers}</tr></thead><tbody>${bodyRows}</tbody></table></div>`;
289
+ }
290
+ if (snap?.ArtifactContentSnapshot) {
291
+ return `<div class="slide-block" data-block-id="${escapeHtml(block.BlockID)}"><div class="slide-block-title">${titleText}</div><div class="slide-block-meta">${escapeHtml(snap.ArtifactTypeSnapshot || block.ArtifactType || 'Artifact')} snapshot</div></div>`;
292
+ }
293
+ return `<div class="slide-block slide-block-live" data-block-id="${escapeHtml(block.BlockID)}"><div class="slide-block-title">${titleText}</div><div class="slide-block-meta">${escapeHtml(block.Kind)} (${escapeHtml(block.Mode)})</div></div>`;
294
+ };
295
+ const renderMarkdownContentHtml = (md) => {
296
+ const lines = String(md ?? '').replace(/\r\n/g, '\n').split('\n');
297
+ const out = [];
298
+ let inList = false;
299
+ const closeList = () => {
300
+ if (inList) {
301
+ out.push('</ul>');
302
+ inList = false;
303
+ }
304
+ };
305
+ for (let i = 0; i < lines.length; i++) {
306
+ const trimmed = lines[i].trim();
307
+ if (!trimmed) {
308
+ closeList();
309
+ continue;
310
+ }
311
+ if (/^[-*]\s+/.test(trimmed)) {
312
+ if (!inList) {
313
+ out.push('<ul>');
314
+ inList = true;
315
+ }
316
+ out.push(`<li>${renderInlineMarkdown(trimmed.replace(/^[-*]\s+/, ''))}</li>`);
317
+ continue;
318
+ }
319
+ closeList();
320
+ const headingMatch = /^(#{1,4})\s+(.+)$/.exec(trimmed);
321
+ if (headingMatch) {
322
+ const level = Math.min(4, headingMatch[1].length + 1);
323
+ out.push(`<h${level}>${renderInlineMarkdown(headingMatch[2])}</h${level}>`);
324
+ continue;
325
+ }
326
+ if (trimmed.startsWith('|')) {
327
+ const tableLines = [trimmed];
328
+ while (i + 1 < lines.length && lines[i + 1].trim().startsWith('|')) {
329
+ i++;
330
+ tableLines.push(lines[i].trim());
331
+ }
332
+ const parseRow = (rowLine) => rowLine
333
+ .replace(/^\|/, '')
334
+ .replace(/\|$/, '')
335
+ .split('|')
336
+ .map((c) => c.trim());
337
+ const rows = tableLines
338
+ .filter((tl) => !/^\|[\s:|-]+\|$/.test(tl))
339
+ .map(parseRow);
340
+ if (rows.length > 0) {
341
+ const head = rows[0].map((c) => `<th>${renderInlineMarkdown(c)}</th>`).join('');
342
+ const body = rows
343
+ .slice(1)
344
+ .map((r) => `<tr>${r.map((c) => `<td>${renderInlineMarkdown(c)}</td>`).join('')}</tr>`)
345
+ .join('');
346
+ out.push(`<table><thead><tr>${head}</tr></thead><tbody>${body}</tbody></table>`);
347
+ continue;
348
+ }
349
+ }
350
+ out.push(`<p>${renderInlineMarkdown(trimmed)}</p>`);
351
+ }
352
+ closeList();
353
+ return out.join('');
354
+ };
355
+ const renderRegionHtml = (r) => {
356
+ const block = r.BlockSpec ?? this.parseFirstBlockFromMarkdown(r.MarkdownContent);
357
+ if (r.Kind === 'mj-block' || block) {
358
+ const contentHtml = block
359
+ ? renderBlockHtml(r, block)
360
+ : `<div class="slide-block-meta">${escapeHtml(r.Label)}</div>`;
361
+ return `<div class="slide-region" data-region-id="${escapeHtml(r.RegionID)}" data-region-kind="mj-block">${contentHtml}</div>`;
362
+ }
363
+ if (r.Kind === 'big-number') {
364
+ const valueHtml = r.BigNumberValue
365
+ ? `<div class="big-number-value">${escapeHtml(r.BigNumberValue)}</div>`
366
+ : '';
367
+ const labelHtml = r.BigNumberLabel
368
+ ? `<div class="big-number-label">${escapeHtml(r.BigNumberLabel)}</div>`
369
+ : '';
370
+ const deltaHtml = r.BigNumberDelta
371
+ ? `<div class="big-number-delta">${escapeHtml(r.BigNumberDelta)}</div>`
372
+ : '';
373
+ const fallbackMd = !r.BigNumberValue && r.MarkdownContent
374
+ ? `<div class="big-number-body">${renderMarkdownContentHtml(r.MarkdownContent)}</div>`
375
+ : '';
376
+ return `<div class="slide-region slide-big-number" data-region-id="${escapeHtml(r.RegionID)}">${valueHtml}${labelHtml}${deltaHtml}${fallbackMd}</div>`;
377
+ }
378
+ if (r.Kind === 'quote') {
379
+ const quoteBody = r.MarkdownContent ? `<blockquote>${renderMarkdownContentHtml(r.MarkdownContent)}</blockquote>` : '';
380
+ const attrHtml = r.QuoteAttribution
381
+ ? `<cite class="quote-attribution">${escapeHtml(r.QuoteAttribution)}</cite>`
382
+ : '';
383
+ return `<div class="slide-region slide-quote" data-region-id="${escapeHtml(r.RegionID)}">${quoteBody}${attrHtml}</div>`;
384
+ }
385
+ if (r.Kind === 'image') {
386
+ const safeSrc = this.SanitizeImageUrl(r.ImageUrl);
387
+ const altText = escapeHtml(r.ImageAlt || r.Label || '');
388
+ const imgHtml = safeSrc
389
+ ? `<img class="slide-image" src="${escapeHtml(safeSrc)}" alt="${altText}"/>`
390
+ : `<div class="slide-image-placeholder">${altText || 'Image'}</div>`;
391
+ const captionHtml = r.MarkdownContent ? `<div class="slide-image-caption">${renderMarkdownContentHtml(r.MarkdownContent)}</div>` : '';
392
+ return `<div class="slide-region slide-image-region" data-region-id="${escapeHtml(r.RegionID)}">${imgHtml}${captionHtml}</div>`;
393
+ }
394
+ return `<div class="slide-region" data-region-id="${escapeHtml(r.RegionID)}" data-region-kind="${escapeHtml(r.Kind)}">${renderMarkdownContentHtml(r.MarkdownContent)}</div>`;
395
+ };
396
+ const primary = this.SanitizeCssValue(deck.Theme?.PrimaryColor, '#4f46e5');
397
+ const accent = this.SanitizeCssValue(deck.Theme?.AccentColor, '#0ea5e9');
398
+ const bg = this.SanitizeCssValue(deck.Theme?.BackgroundColor, '#ffffff');
399
+ const surface = this.SanitizeCssValue(deck.Theme?.SurfaceColor, '#f8fafc');
400
+ const text = this.SanitizeCssValue(deck.Theme?.TextColor, '#0f172a');
401
+ const muted = this.SanitizeCssValue(deck.Theme?.MutedTextColor, '#475569');
402
+ const headingFont = this.SanitizeCssValue(deck.Theme?.HeadingFont, 'Inter, system-ui, sans-serif');
403
+ const bodyFont = this.SanitizeCssValue(deck.Theme?.BodyFont, 'Inter, system-ui, sans-serif');
404
+ const safeLogoUrl = this.SanitizeImageUrl(deck.Master?.LogoUrl);
405
+ const visibleSlides = (deck.Slides ?? []).filter((s) => !s.Hidden);
406
+ const dateLabel = deck.Master?.ShowDate ? new Date().toISOString().slice(0, 10) : '';
407
+ const slideBlocks = visibleSlides
408
+ .map((slide, visibleIdx) => {
409
+ const regionsHtml = (slide.Regions ?? []).map(renderRegionHtml).join('');
410
+ const headerParts = [];
411
+ if (safeLogoUrl) {
412
+ headerParts.push(`<img class="slide-master-logo" src="${escapeHtml(safeLogoUrl)}" alt="${escapeHtml(deck.Master?.OrganizationName || 'Logo')}"/>`);
413
+ }
414
+ if (deck.Master?.OrganizationName) {
415
+ headerParts.push(`<span class="slide-master-org">${escapeHtml(deck.Master.OrganizationName)}</span>`);
416
+ }
417
+ if (deck.Master?.HeaderText) {
418
+ headerParts.push(`<span class="slide-master-header-text">${escapeHtml(deck.Master.HeaderText)}</span>`);
419
+ }
420
+ const headerHtml = headerParts.length > 0 ? `<header class="slide-master-header">${headerParts.join('')}</header>` : '';
421
+ const footerParts = [];
422
+ if (deck.Master?.FooterText) {
423
+ footerParts.push(`<span class="slide-master-footer-text">${escapeHtml(deck.Master.FooterText)}</span>`);
424
+ }
425
+ if (dateLabel) {
426
+ footerParts.push(`<span class="slide-master-date">${escapeHtml(dateLabel)}</span>`);
427
+ }
428
+ if (deck.Master?.ShowSlideNumbers) {
429
+ footerParts.push(`<span class="slide-master-number">Slide ${visibleIdx + 1} of ${visibleSlides.length}</span>`);
430
+ }
431
+ const footerHtml = footerParts.length > 0 ? `<footer class="slide-master-footer">${footerParts.join(' ')}</footer>` : '';
432
+ return `<section class="slide-page" data-slide-id="${escapeHtml(slide.SlideID)}">${headerHtml}<h1>${escapeHtml(slide.Title)}</h1>${slide.Subtitle ? `<h2>${escapeHtml(slide.Subtitle)}</h2>` : ''}<div class="slide-regions">${regionsHtml}</div>${footerHtml}</section>`;
433
+ })
434
+ .join('\n');
435
+ return [
436
+ '<!DOCTYPE html>',
437
+ '<html><head><meta charset="utf-8"/>',
438
+ `<title>${escapeHtml(deck.Title)}</title>`,
439
+ '<style>',
440
+ `:root { --slide-primary: ${primary}; --slide-accent: ${accent}; --slide-bg: ${bg}; --slide-surface: ${surface}; --slide-text: ${text}; --slide-muted: ${muted}; --slide-heading-font: ${headingFont}; --slide-body-font: ${bodyFont}; }`,
441
+ 'body { margin: 0; background: var(--slide-bg); color: var(--slide-text); font-family: var(--slide-body-font); }',
442
+ 'h1, h2 { font-family: var(--slide-heading-font); color: var(--slide-primary); }',
443
+ '.slide-page { page-break-after: always; padding: 32px; background: var(--slide-bg); }',
444
+ '.slide-master-header, .slide-master-footer { display: flex; justify-content: space-between; align-items: center; color: var(--slide-muted); font-size: 12px; }',
445
+ '.big-number-value { font-size: 48px; font-weight: 700; color: var(--slide-primary); }',
446
+ '.big-number-label { font-size: 16px; color: var(--slide-muted); }',
447
+ '.big-number-delta { font-size: 14px; color: var(--slide-accent); }',
448
+ '.slide-block-table, table { width: 100%; border-collapse: collapse; margin: 12px 0; }',
449
+ 'th, td { border: 1px solid var(--slide-muted); padding: 6px 8px; text-align: left; font-size: 13px; }',
450
+ '</style></head>',
451
+ `<body>${slideBlocks}</body></html>`
452
+ ].join('\n');
453
+ }
454
+ /**
455
+ * Derives a complete {@link SlideDeckThemeSpec} from organization brand color seeds (`Accept #4`).
456
+ */
457
+ DeriveThemeFromBrandSeeds(seeds) {
458
+ const primary = this.SanitizeCssValue(seeds.PrimaryColor, '#4f46e5');
459
+ const accent = this.SanitizeCssValue(seeds.AccentColor, primary);
460
+ const bg = this.SanitizeCssValue(seeds.BackgroundColor, '#ffffff');
461
+ const isDarkBg = /^#(0|1|2)[0-9a-f]{5}$/i.test(bg);
462
+ const surface = this.SanitizeCssValue(seeds.SurfaceColor, isDarkBg ? '#1e293b' : '#f8fafc');
463
+ const text = this.SanitizeCssValue(seeds.TextColor, isDarkBg ? '#f8fafc' : '#0f172a');
464
+ const muted = isDarkBg ? '#cbd5e1' : '#475569';
465
+ return {
466
+ ThemeID: 'brand-custom',
467
+ Name: seeds.OrganizationName ? `${seeds.OrganizationName} Brand Theme` : 'Organization Brand Theme',
468
+ PrimaryColor: primary,
469
+ AccentColor: accent,
470
+ BackgroundColor: bg,
471
+ SurfaceColor: surface,
472
+ TextColor: text,
473
+ MutedTextColor: muted,
474
+ HeadingFont: this.SanitizeCssValue(seeds.HeadingFont, 'Inter, system-ui, sans-serif'),
475
+ BodyFont: this.SanitizeCssValue(seeds.BodyFont, 'Inter, system-ui, sans-serif'),
476
+ BrandSeedSource: seeds.BrandSeedSource || seeds.OrganizationName || 'Organization Brand Seeds'
477
+ };
478
+ }
479
+ /**
480
+ * Builds the default regions for a given {@link SlideLayoutKind}, preserving existing
481
+ * region content when switching a slide from one layout to another.
482
+ */
483
+ BuildRegionsForLayout(layout, existingRegions = []) {
484
+ const firstExisting = existingRegions[0];
485
+ const secondExisting = existingRegions[1];
486
+ switch (layout) {
487
+ case 'Title':
488
+ return [
489
+ this.mergeOrCreateRegion(firstExisting, {
490
+ RegionID: 'main',
491
+ Label: 'Cover Tagline & Presenter Metadata',
492
+ Kind: 'rich-text',
493
+ MarkdownContent: firstExisting?.MarkdownContent ||
494
+ 'Prepared for Executive Leadership · Real-Time Collaborative Presentation'
495
+ })
496
+ ];
497
+ case 'SectionHeader':
498
+ return [
499
+ this.mergeOrCreateRegion(firstExisting, {
500
+ RegionID: 'main',
501
+ Label: 'Section Overview',
502
+ Kind: 'rich-text',
503
+ MarkdownContent: firstExisting?.MarkdownContent ||
504
+ 'Key objectives, architecture milestones, and governance metrics for this section.'
505
+ })
506
+ ];
507
+ case 'TwoColumn':
508
+ return [
509
+ this.mergeOrCreateRegion(firstExisting, {
510
+ RegionID: 'left',
511
+ Label: 'Left Column',
512
+ Kind: 'rich-text',
513
+ MarkdownContent: firstExisting?.MarkdownContent ||
514
+ '- **Strategic Pillar 1:** Unified metadata governance\n- **Strategic Pillar 2:** Viewer-scoped RLS & FLS security\n- **Strategic Pillar 3:** Real-time Yjs CRDT co-editing'
515
+ }),
516
+ this.mergeOrCreateRegion(secondExisting, {
517
+ RegionID: 'right',
518
+ Label: 'Right Column',
519
+ Kind: 'rich-text',
520
+ MarkdownContent: secondExisting?.MarkdownContent ||
521
+ '- **Execution Cadence:** Quarterly milestone gates\n- **AI Co-Authoring:** `@SlidesAgent` region updates\n- **Export Targets:** Editable `.pptx` & printable `.pdf`'
522
+ })
523
+ ];
524
+ case 'Comparison':
525
+ return [
526
+ this.mergeOrCreateRegion(firstExisting, {
527
+ RegionID: 'left',
528
+ Label: 'Baseline Approach',
529
+ Kind: 'callout',
530
+ CalloutTone: 'WARNING',
531
+ MarkdownContent: firstExisting?.MarkdownContent ||
532
+ '### Legacy Static Decks\n- Manual copy-paste from spreadsheets\n- Stale numbers the moment slides are emailed\n- Zero row-level or field-level security'
533
+ }),
534
+ this.mergeOrCreateRegion(secondExisting, {
535
+ RegionID: 'right',
536
+ Label: 'MJ Collaborative Slides',
537
+ Kind: 'callout',
538
+ CalloutTone: 'TIP',
539
+ MarkdownContent: secondExisting?.MarkdownContent ||
540
+ '### Live Governed Presentations\n- Viewer-scoped `EntityView` & `SavedQuery` blocks\n- Automatic freeze when Presentation Mode starts (`O6`)\n- Inline MS OLE `Whiteboard` architecture diagrams'
541
+ })
542
+ ];
543
+ case 'LiveDataSlide':
544
+ case 'ChartAndText': {
545
+ const defaultBlock = firstExisting?.BlockSpec ?? {
546
+ BlockID: `slide-blk-ev-1`,
547
+ Kind: 'EntityView',
548
+ Mode: 'Live',
549
+ Title: 'Live Portfolio Initiatives (Viewer RLS/FLS)',
550
+ EntityName: 'MJ: Artifacts',
551
+ DisplayMode: 'table'
552
+ };
553
+ const blockDirective = DocumentLiveBlockEngine.Instance.SerializeBlockToMarkdownDirective(defaultBlock);
554
+ return [
555
+ this.mergeOrCreateRegion(firstExisting, {
556
+ RegionID: 'data',
557
+ Label: 'Live MJ Data / Chart Region',
558
+ Kind: firstExisting?.Kind === 'mj-block' ? 'mj-block' : 'mj-block',
559
+ MarkdownContent: firstExisting?.Kind === 'mj-block' && firstExisting.MarkdownContent
560
+ ? firstExisting.MarkdownContent
561
+ : blockDirective,
562
+ BlockSpec: defaultBlock
563
+ }),
564
+ this.mergeOrCreateRegion(secondExisting, {
565
+ RegionID: 'narrative',
566
+ Label: 'Executive Commentary',
567
+ Kind: 'rich-text',
568
+ MarkdownContent: secondExisting?.MarkdownContent ||
569
+ '### Key Takeaways\n- Data refreshes live under each viewer\'s MJ permissions\n- Freezes automatically when Presentation Mode begins (`O6`)\n- Exports as a native table/chart in `.pptx`'
570
+ })
571
+ ];
572
+ }
573
+ case 'BigNumber':
574
+ return [
575
+ this.mergeOrCreateRegion(firstExisting, {
576
+ RegionID: 'kpi',
577
+ Label: 'Headline KPI Metric',
578
+ Kind: 'big-number',
579
+ BigNumberValue: firstExisting?.BigNumberValue || '—',
580
+ BigNumberLabel: firstExisting?.BigNumberLabel || 'Key Performance Indicator',
581
+ BigNumberDelta: firstExisting?.BigNumberDelta || 'Target comparison',
582
+ MarkdownContent: firstExisting?.MarkdownContent || 'Key Performance Indicator — Replace with target metric details.'
583
+ }),
584
+ this.mergeOrCreateRegion(secondExisting, {
585
+ RegionID: 'context',
586
+ Label: 'Metric Context & Drivers',
587
+ Kind: 'rich-text',
588
+ MarkdownContent: secondExisting?.MarkdownContent ||
589
+ '- Zero data-loss Yjs CRDT binary checkpoints in `MJ: Artifact Working States`\n- Cross-instance room relay support\n- Strict viewer-scoped permission enforcement'
590
+ })
591
+ ];
592
+ case 'Quote':
593
+ return [
594
+ this.mergeOrCreateRegion(firstExisting, {
595
+ RegionID: 'quote',
596
+ Label: 'Featured Quote',
597
+ Kind: 'quote',
598
+ QuoteAttribution: firstExisting?.QuoteAttribution || 'Speaker Name, Title',
599
+ MarkdownContent: firstExisting?.MarkdownContent ||
600
+ '"Add a key takeaway or stakeholder quote for this section."'
601
+ })
602
+ ];
603
+ case 'FullBleedImage':
604
+ return [
605
+ this.mergeOrCreateRegion(firstExisting, {
606
+ RegionID: 'visual',
607
+ Label: 'Full-Bleed Visual & Caption',
608
+ Kind: firstExisting?.Kind === 'mj-block' ? 'mj-block' : 'rich-text',
609
+ MarkdownContent: firstExisting?.MarkdownContent ||
610
+ '### Global Multi-Region Topology\nHigh-availability MJAPI cluster with Redis Yjs room relay and SQL Server working-state persistence.'
611
+ })
612
+ ];
613
+ case 'Blank':
614
+ return [
615
+ this.mergeOrCreateRegion(firstExisting, {
616
+ RegionID: 'canvas',
617
+ Label: 'Full Slide Canvas Region',
618
+ Kind: firstExisting?.Kind || 'rich-text',
619
+ MarkdownContent: firstExisting?.MarkdownContent ||
620
+ 'Use `/` or the region toolbar to embed an interactive OLE Whiteboard or Live MJ Block.'
621
+ })
622
+ ];
623
+ case 'TitleAndBody':
624
+ default:
625
+ return [
626
+ this.mergeOrCreateRegion(firstExisting, {
627
+ RegionID: 'main',
628
+ Label: 'Slide Body',
629
+ Kind: firstExisting?.Kind || 'rich-text',
630
+ MarkdownContent: firstExisting?.MarkdownContent ||
631
+ '- **Structured 16:9 Layouts:** Title, Section Break, Title & Body, Two Columns, Comparison, Live Data, Big Number, Quote\n- **Live MJ Blocks:** Viewer-scoped `EntityView`, `SavedQuery`, `DashboardPart`, and `InteractiveComponent`\n- **Inline OLE Artifacts:** Interactive `Whiteboard` diagrams embedded directly in slide regions'
632
+ })
633
+ ];
634
+ }
635
+ }
636
+ /**
637
+ * Creates a default starter {@link SlideDeckSpec} when an empty or new presentation is opened.
638
+ */
639
+ CreateDefaultDeck(title = 'Executive Strategy & Live Operations Deck', deckId = 'deck-default') {
640
+ const defaultTheme = { ...SLIDE_DECK_THEME_PRESETS[0] };
641
+ const slides = [
642
+ {
643
+ SlideID: 'slide-1',
644
+ SlideNumber: 1,
645
+ Layout: 'Title',
646
+ Title: title,
647
+ Subtitle: 'Q4 Architecture, Live Telemetry & Collaborative Governance Review',
648
+ Regions: this.BuildRegionsForLayout('Title'),
649
+ SpeakerNotes: 'Welcome everyone. Today we are reviewing our Q4 live operational metrics and architecture roadmap.',
650
+ Transition: 'fade'
651
+ },
652
+ {
653
+ SlideID: 'slide-2',
654
+ SlideNumber: 2,
655
+ Layout: 'TwoColumn',
656
+ Title: 'Strategic Pillars & Execution Priorities',
657
+ Subtitle: 'Co-authored in real time over Yjs CRDT rooms',
658
+ Regions: this.BuildRegionsForLayout('TwoColumn'),
659
+ SpeakerNotes: 'Highlight how two authors can edit separate slides while a third reorders the deck with zero data loss.',
660
+ Transition: 'slide'
661
+ },
662
+ {
663
+ SlideID: 'slide-3',
664
+ SlideNumber: 3,
665
+ Layout: 'LiveDataSlide',
666
+ Title: 'Live Enterprise Portfolio Telemetry (Viewer RLS/FLS)',
667
+ Subtitle: 'Refreshes on open and freezes automatically when Presentation Mode begins (O6)',
668
+ Regions: this.BuildRegionsForLayout('LiveDataSlide'),
669
+ SpeakerNotes: 'Point out that every viewer sees only rows permitted by their Row-Level and Field-Level Security.',
670
+ Transition: 'fade'
671
+ }
672
+ ];
673
+ return {
674
+ SchemaVersion: '1.0',
675
+ DeckID: deckId,
676
+ Title: title,
677
+ Subtitle: 'MemberJunction Collaborative Presentations',
678
+ AspectRatio: '16:9',
679
+ Theme: defaultTheme,
680
+ Master: {
681
+ HeaderText: '',
682
+ FooterText: '',
683
+ ShowSlideNumbers: true,
684
+ ShowDate: true,
685
+ OrganizationName: 'MemberJunction'
686
+ },
687
+ Slides: slides,
688
+ UpdatedAt: new Date().toISOString()
689
+ };
690
+ }
691
+ /**
692
+ * Parses raw artifact content (either serialized `SlideDeckSpec` JSON or Markdown text)
693
+ * into a normalized {@link SlideDeckSpec}.
694
+ */
695
+ ParseDeckSpec(rawContent, fallbackTitle, fallbackDeckId) {
696
+ const trimmed = (rawContent ?? '').trim();
697
+ if (!trimmed) {
698
+ return this.CreateDefaultDeck(fallbackTitle, fallbackDeckId);
699
+ }
700
+ if (trimmed.startsWith('{')) {
701
+ try {
702
+ const parsed = JSON.parse(trimmed);
703
+ if (parsed && Array.isArray(parsed.Slides) && parsed.Slides.length > 0) {
704
+ return this.normalizeDeckSpec(parsed, fallbackTitle, fallbackDeckId);
705
+ }
706
+ }
707
+ catch {
708
+ // Fall through to Markdown-to-Slides conversion if JSON is malformed
709
+ }
710
+ }
711
+ return this.ConvertMarkdownToSlideDeck(trimmed, fallbackTitle, undefined, fallbackDeckId);
712
+ }
713
+ /**
714
+ * Serializes a {@link SlideDeckSpec} to formatted JSON.
715
+ */
716
+ SerializeDeckSpec(deck) {
717
+ const normalized = this.normalizeDeckSpec(deck, deck.Title, deck.DeckID);
718
+ return JSON.stringify(normalized, null, 2);
719
+ }
720
+ /**
721
+ * Converts a Markdown Document (including headings, bullet lists, callouts, tables,
722
+ * and `:::mj-block` directives for Live MJ Blocks and OLE Whiteboards) into a structured
723
+ * {@link SlideDeckSpec} (`§ 5.2` — *"make a deck from this doc"*).
724
+ */
725
+ ConvertMarkdownToSlideDeck(markdown, deckTitle, theme, deckId = 'deck-from-markdown') {
726
+ const normalizedMd = (markdown ?? '').replace(/\r\n/g, '\n').trim();
727
+ if (!normalizedMd) {
728
+ return this.CreateDefaultDeck(deckTitle, deckId);
729
+ }
730
+ const lines = normalizedMd.split('\n');
731
+ const sections = [];
732
+ let currentSection = null;
733
+ let inBacktickFence = false;
734
+ let inColonFence = false;
735
+ for (const line of lines) {
736
+ const trimmedLine = line.trim();
737
+ if (!inColonFence && trimmedLine.startsWith('```')) {
738
+ inBacktickFence = !inBacktickFence;
739
+ }
740
+ else if (!inBacktickFence && trimmedLine.startsWith(':::')) {
741
+ if (!inColonFence && /^:::[a-zA-Z0-9_-]+/.test(trimmedLine)) {
742
+ inColonFence = true;
743
+ }
744
+ else if (inColonFence && trimmedLine === ':::') {
745
+ inColonFence = false;
746
+ }
747
+ }
748
+ const headingMatch = !inBacktickFence && !inColonFence ? /^(#{1,3})\s+(.+)$/.exec(trimmedLine) : null;
749
+ if (headingMatch) {
750
+ if (currentSection) {
751
+ sections.push(currentSection);
752
+ }
753
+ currentSection = {
754
+ level: headingMatch[1].length,
755
+ heading: headingMatch[2].trim(),
756
+ bodyLines: []
757
+ };
758
+ }
759
+ else {
760
+ if (!currentSection) {
761
+ currentSection = {
762
+ level: 1,
763
+ heading: deckTitle || 'Executive Presentation',
764
+ bodyLines: []
765
+ };
766
+ }
767
+ currentSection.bodyLines.push(line);
768
+ }
769
+ }
770
+ if (currentSection) {
771
+ sections.push(currentSection);
772
+ }
773
+ const resolvedTitle = deckTitle || sections[0]?.heading || 'Executive Presentation';
774
+ const slides = sections.map((sec, idx) => {
775
+ const slideId = `slide-${idx + 1}`;
776
+ const rawBody = sec.bodyLines.join('\n').trim();
777
+ const parsedSegments = DocumentLiveBlockEngine.Instance.ParseMarkdownDirectives(rawBody);
778
+ const parsedBlocks = parsedSegments.filter((seg) => seg.Type === 'mj-block' && Boolean(seg.BlockSpec));
779
+ // Extract speaker notes if marked with `> Speaker Notes:`
780
+ const noteLines = [];
781
+ const contentLines = [];
782
+ for (const bLine of sec.bodyLines) {
783
+ const noteMatch = /^>\s*Speaker Notes:\s*(.+)$/i.exec(bLine.trim());
784
+ if (noteMatch) {
785
+ noteLines.push(noteMatch[1]);
786
+ }
787
+ else {
788
+ contentLines.push(bLine);
789
+ }
790
+ }
791
+ const cleanedBody = contentLines.join('\n').trim();
792
+ if (idx === 0 && sec.level === 1 && parsedBlocks.length === 0) {
793
+ return {
794
+ SlideID: slideId,
795
+ SlideNumber: idx + 1,
796
+ Layout: 'Title',
797
+ Title: sec.heading,
798
+ Subtitle: cleanedBody.split('\n')[0]?.replace(/^[>*-\s]+/, '') || 'Generated from MJ Markdown Document',
799
+ Regions: [
800
+ {
801
+ RegionID: 'main',
802
+ Label: 'Cover Summary',
803
+ Kind: 'rich-text',
804
+ MarkdownContent: cleanedBody || sec.heading
805
+ }
806
+ ],
807
+ SpeakerNotes: noteLines.join('\n') || `Cover slide for ${sec.heading}.`,
808
+ Transition: 'fade'
809
+ };
810
+ }
811
+ if (parsedBlocks.length > 0) {
812
+ const firstBlock = parsedBlocks[0].BlockSpec;
813
+ let strippedNarrative = cleanedBody;
814
+ for (const blockSeg of parsedBlocks) {
815
+ strippedNarrative = strippedNarrative.replace(blockSeg.RawText, () => '');
816
+ }
817
+ strippedNarrative = strippedNarrative.trim();
818
+ const isWhiteboard = firstBlock.Kind === 'Artifact' && firstBlock.ArtifactType === 'Whiteboard';
819
+ const regions = parsedBlocks.map((blockSeg, bIdx) => ({
820
+ RegionID: bIdx === 0 ? 'data' : `data-${bIdx + 1}`,
821
+ Label: blockSeg.BlockSpec.Title || (bIdx === 0 ? 'Embedded MJ Block' : `Embedded MJ Block ${bIdx + 1}`),
822
+ Kind: 'mj-block',
823
+ MarkdownContent: DocumentLiveBlockEngine.Instance.SerializeBlockToMarkdownDirective(blockSeg.BlockSpec),
824
+ BlockSpec: blockSeg.BlockSpec
825
+ }));
826
+ regions.push({
827
+ RegionID: 'narrative',
828
+ Label: 'Key Insights',
829
+ Kind: 'rich-text',
830
+ MarkdownContent: strippedNarrative ||
831
+ `- Live ${firstBlock.Kind} block integrated from source document\n- Viewer-scoped permissions enforced`
832
+ });
833
+ return {
834
+ SlideID: slideId,
835
+ SlideNumber: idx + 1,
836
+ Layout: isWhiteboard ? 'ChartAndText' : 'LiveDataSlide',
837
+ Title: sec.heading,
838
+ Subtitle: firstBlock.Title || `${firstBlock.Kind} Slide`,
839
+ Regions: regions,
840
+ SpeakerNotes: noteLines.join('\n') || `Discuss ${firstBlock.Title || sec.heading}.`,
841
+ Transition: 'slide'
842
+ };
843
+ }
844
+ return {
845
+ SlideID: slideId,
846
+ SlideNumber: idx + 1,
847
+ Layout: sec.level === 1 ? 'SectionHeader' : 'TitleAndBody',
848
+ Title: sec.heading,
849
+ Regions: [
850
+ {
851
+ RegionID: 'main',
852
+ Label: 'Slide Content',
853
+ Kind: cleanedBody.includes('| ---') ? 'table' : 'rich-text',
854
+ MarkdownContent: cleanedBody || `- Key points for ${sec.heading}`
855
+ }
856
+ ],
857
+ SpeakerNotes: noteLines.join('\n') || `Speaker notes for ${sec.heading}.`,
858
+ Transition: 'fade'
859
+ };
860
+ });
861
+ return {
862
+ SchemaVersion: '1.0',
863
+ DeckID: deckId,
864
+ Title: resolvedTitle,
865
+ Subtitle: 'Converted from MJ Markdown Document',
866
+ AspectRatio: '16:9',
867
+ Theme: theme ? { ...theme } : { ...SLIDE_DECK_THEME_PRESETS[0] },
868
+ Master: {
869
+ HeaderText: resolvedTitle,
870
+ FooterText: 'Generated by MJ Slides',
871
+ ShowSlideNumbers: true,
872
+ ShowDate: true,
873
+ OrganizationName: 'MemberJunction'
874
+ },
875
+ Slides: slides,
876
+ UpdatedAt: new Date().toISOString()
877
+ };
878
+ }
879
+ /**
880
+ * Adds a new slide to `deck` with the requested `layout` and optional insertion index.
881
+ */
882
+ AddSlide(deck, options = {}) {
883
+ const layout = options.Layout ?? 'TitleAndBody';
884
+ const slideId = this.mintUniqueSlideId(deck.Slides, options.SlideID);
885
+ const existingBlockIds = this.collectDeckBlockIds(deck.Slides);
886
+ const regions = options.Regions && options.Regions.length > 0
887
+ ? options.Regions.map((r) => ({ ...r }))
888
+ : this.BuildRegionsForLayout(layout).map((r) => r.BlockSpec && existingBlockIds.has(r.BlockSpec.BlockID.toLowerCase())
889
+ ? this.cloneRegionWithFreshBlockIds(r, existingBlockIds)
890
+ : r);
891
+ const newSlide = {
892
+ SlideID: slideId,
893
+ SlideNumber: deck.Slides.length + 1,
894
+ Layout: layout,
895
+ Title: options.Title || `New ${layout} Slide`,
896
+ Subtitle: options.Subtitle,
897
+ Regions: regions,
898
+ SpeakerNotes: options.SpeakerNotes ?? '',
899
+ Transition: 'fade'
900
+ };
901
+ const nextSlides = [...deck.Slides.map((s) => this.cloneSlide(s))];
902
+ if (typeof options.InsertAtIndex === 'number' &&
903
+ options.InsertAtIndex >= 0 &&
904
+ options.InsertAtIndex <= nextSlides.length) {
905
+ nextSlides.splice(options.InsertAtIndex, 0, newSlide);
906
+ }
907
+ else {
908
+ nextSlides.push(newSlide);
909
+ }
910
+ const renumbered = this.renumberSlides(nextSlides);
911
+ const updatedDeck = {
912
+ ...deck,
913
+ Slides: renumbered,
914
+ UpdatedAt: new Date().toISOString()
915
+ };
916
+ const added = renumbered.find((s) => s.SlideID === slideId) ?? newSlide;
917
+ return { Deck: updatedDeck, AddedSlide: added };
918
+ }
919
+ /**
920
+ * Duplicates an existing slide right after its current position, minting a unique `SlideID`
921
+ * and fresh `BlockID`s for any embedded MJ blocks on the duplicated regions (`D6`).
922
+ */
923
+ DuplicateSlide(deck, slideId) {
924
+ const index = deck.Slides.findIndex((s) => s.SlideID === slideId || UUIDsEqual(s.SlideID, slideId));
925
+ if (index < 0) {
926
+ return { Deck: deck, DuplicatedSlide: null };
927
+ }
928
+ const source = deck.Slides[index];
929
+ const copyId = this.mintUniqueSlideId(deck.Slides);
930
+ const usedBlockIds = this.collectDeckBlockIds(deck.Slides);
931
+ const clonedSource = this.cloneSlide(source);
932
+ const copy = {
933
+ ...clonedSource,
934
+ SlideID: copyId,
935
+ Title: `${source.Title} (Copy)`,
936
+ Regions: clonedSource.Regions.map((region) => this.cloneRegionWithFreshBlockIds(region, usedBlockIds))
937
+ };
938
+ const nextSlides = [...deck.Slides.map((s) => this.cloneSlide(s))];
939
+ nextSlides.splice(index + 1, 0, copy);
940
+ const renumbered = this.renumberSlides(nextSlides);
941
+ return {
942
+ Deck: {
943
+ ...deck,
944
+ Slides: renumbered,
945
+ UpdatedAt: new Date().toISOString()
946
+ },
947
+ DuplicatedSlide: renumbered[index + 1] ?? copy
948
+ };
949
+ }
950
+ /**
951
+ * Checks whether an actor is allowed to mutate a slide given its lock settings (`§6.2`).
952
+ */
953
+ CanActorEditSlide(slide, actorUserId, ownerUserId, isEditor = false) {
954
+ if (!slide.Locked) {
955
+ return { Allowed: true };
956
+ }
957
+ const actor = (actorUserId ?? '').trim();
958
+ if (actor && ownerUserId && UUIDsEqual(actor, ownerUserId)) {
959
+ return { Allowed: true };
960
+ }
961
+ if (actor && slide.LockedByUserID && UUIDsEqual(actor, slide.LockedByUserID)) {
962
+ return { Allowed: true };
963
+ }
964
+ if (slide.AllowEditors && isEditor) {
965
+ return { Allowed: true };
966
+ }
967
+ return {
968
+ Allowed: false,
969
+ Reason: `Slide '${slide.SlideID}' is locked (owner-only protection).`
970
+ };
971
+ }
972
+ /**
973
+ * Checks whether an actor is allowed to mutate a region within a slide (`§6.2`).
974
+ */
975
+ CanActorEditRegion(slide, region, actorUserId, ownerUserId, isEditor = false) {
976
+ const slideCheck = this.CanActorEditSlide(slide, actorUserId, ownerUserId, isEditor);
977
+ if (!slideCheck.Allowed) {
978
+ return slideCheck;
979
+ }
980
+ if (!region.Locked) {
981
+ return { Allowed: true };
982
+ }
983
+ const actor = (actorUserId ?? '').trim();
984
+ if (actor && ownerUserId && UUIDsEqual(actor, ownerUserId)) {
985
+ return { Allowed: true };
986
+ }
987
+ if (actor && region.LockedByUserID && UUIDsEqual(actor, region.LockedByUserID)) {
988
+ return { Allowed: true };
989
+ }
990
+ if (region.AllowEditors && isEditor) {
991
+ return { Allowed: true };
992
+ }
993
+ return {
994
+ Allowed: false,
995
+ Reason: `Region '${region.RegionID}' on slide '${slide.SlideID}' is locked (owner-only protection).`
996
+ };
997
+ }
998
+ /**
999
+ * Toggles lock state on a slide (`§6.2`). Only the locker or artifact owner may unlock a locked slide.
1000
+ */
1001
+ SetSlideLock(deck, slideId, locked, actorUserId, allowEditors = false, ownerUserId) {
1002
+ const existing = deck.Slides.find((s) => s.SlideID === slideId || UUIDsEqual(s.SlideID, slideId));
1003
+ if (!existing) {
1004
+ return { Deck: deck, UpdatedSlide: null };
1005
+ }
1006
+ if (existing.Locked) {
1007
+ const canUnlock = this.CanActorEditSlide(existing, actorUserId, ownerUserId, false);
1008
+ if (!canUnlock.Allowed) {
1009
+ throw new Error(canUnlock.Reason);
1010
+ }
1011
+ }
1012
+ let updatedSlide = null;
1013
+ const nextSlides = deck.Slides.map((s) => {
1014
+ if (s.SlideID !== existing.SlideID)
1015
+ return s;
1016
+ updatedSlide = {
1017
+ ...s,
1018
+ Locked: locked,
1019
+ LockedByUserID: locked ? actorUserId : undefined,
1020
+ AllowEditors: locked ? allowEditors : undefined
1021
+ };
1022
+ return updatedSlide;
1023
+ });
1024
+ return {
1025
+ Deck: { ...deck, Slides: nextSlides, UpdatedAt: new Date().toISOString() },
1026
+ UpdatedSlide: updatedSlide
1027
+ };
1028
+ }
1029
+ /**
1030
+ * Toggles lock state on a specific region within a slide (`§6.2`).
1031
+ */
1032
+ SetRegionLock(deck, slideId, regionId, locked, actorUserId, allowEditors = false, ownerUserId) {
1033
+ const slide = deck.Slides.find((s) => s.SlideID === slideId || UUIDsEqual(s.SlideID, slideId));
1034
+ if (!slide) {
1035
+ return { Deck: deck, UpdatedRegion: null };
1036
+ }
1037
+ const region = slide.Regions.find((r) => r.RegionID === regionId);
1038
+ if (!region) {
1039
+ return { Deck: deck, UpdatedRegion: null };
1040
+ }
1041
+ if (region.Locked || slide.Locked) {
1042
+ const check = this.CanActorEditRegion(slide, region, actorUserId, ownerUserId, false);
1043
+ if (!check.Allowed) {
1044
+ throw new Error(check.Reason);
1045
+ }
1046
+ }
1047
+ let updatedRegion = null;
1048
+ const nextSlides = deck.Slides.map((s) => {
1049
+ if (s.SlideID !== slide.SlideID)
1050
+ return s;
1051
+ const nextRegions = s.Regions.map((r) => {
1052
+ if (r.RegionID !== regionId)
1053
+ return r;
1054
+ updatedRegion = {
1055
+ ...r,
1056
+ Locked: locked,
1057
+ LockedByUserID: locked ? actorUserId : undefined,
1058
+ AllowEditors: locked ? allowEditors : undefined
1059
+ };
1060
+ return updatedRegion;
1061
+ });
1062
+ return { ...s, Regions: nextRegions };
1063
+ });
1064
+ return {
1065
+ Deck: { ...deck, Slides: nextSlides, UpdatedAt: new Date().toISOString() },
1066
+ UpdatedRegion: updatedRegion
1067
+ };
1068
+ }
1069
+ /**
1070
+ * Updates a single slide's metadata (`Title`, `Subtitle`, `Layout`, `SpeakerNotes`, `Transition`, `Hidden`)
1071
+ * by `SlideID` without modifying any other slide in the deck (`Accept #3`).
1072
+ */
1073
+ UpdateSlideMetadata(deck, slideId, patch, lockContext) {
1074
+ let updatedSlide = null;
1075
+ const nextSlides = deck.Slides.map((slide) => {
1076
+ if (slide.SlideID !== slideId && !UUIDsEqual(slide.SlideID, slideId)) {
1077
+ return slide;
1078
+ }
1079
+ if (!lockContext?.BypassLock) {
1080
+ const check = this.CanActorEditSlide(slide, lockContext?.ActorUserID, lockContext?.OwnerUserID, lockContext?.IsEditor);
1081
+ if (!check.Allowed) {
1082
+ throw new Error(check.Reason);
1083
+ }
1084
+ if (patch.Layout && patch.Layout !== slide.Layout) {
1085
+ for (const region of slide.Regions) {
1086
+ if (region.Locked) {
1087
+ const regionCheck = this.CanActorEditRegion(slide, region, lockContext?.ActorUserID, lockContext?.OwnerUserID, lockContext?.IsEditor);
1088
+ if (!regionCheck.Allowed) {
1089
+ throw new Error(`Cannot change layout on slide '${slide.SlideID}' because region '${region.RegionID}' is locked (owner-only protection).`);
1090
+ }
1091
+ }
1092
+ }
1093
+ }
1094
+ }
1095
+ const nextLayout = patch.Layout ?? slide.Layout;
1096
+ const nextRegions = patch.Layout && patch.Layout !== slide.Layout
1097
+ ? this.BuildRegionsForLayout(patch.Layout, slide.Regions)
1098
+ : slide.Regions.map((r) => ({ ...r }));
1099
+ updatedSlide = {
1100
+ ...slide,
1101
+ Title: patch.Title !== undefined ? patch.Title : slide.Title,
1102
+ Subtitle: patch.Subtitle !== undefined ? patch.Subtitle : slide.Subtitle,
1103
+ Layout: nextLayout,
1104
+ Regions: nextRegions,
1105
+ SpeakerNotes: patch.SpeakerNotes !== undefined ? patch.SpeakerNotes : slide.SpeakerNotes,
1106
+ Transition: patch.Transition !== undefined ? patch.Transition : slide.Transition,
1107
+ Hidden: patch.Hidden !== undefined ? patch.Hidden : slide.Hidden
1108
+ };
1109
+ return updatedSlide;
1110
+ });
1111
+ if (!updatedSlide) {
1112
+ return { Deck: deck, UpdatedSlide: null };
1113
+ }
1114
+ return {
1115
+ Deck: {
1116
+ ...deck,
1117
+ Slides: nextSlides,
1118
+ UpdatedAt: new Date().toISOString()
1119
+ },
1120
+ UpdatedSlide: updatedSlide
1121
+ };
1122
+ }
1123
+ /**
1124
+ * Updates or inserts a single region (`regionId`) on a target slide (`slideId`) without
1125
+ * touching any other slide or region in the deck (`Accept #3`).
1126
+ */
1127
+ UpsertSlideRegion(deck, slideId, regionPatch, lockContext) {
1128
+ let updatedRegion = null;
1129
+ const nextSlides = deck.Slides.map((slide) => {
1130
+ if (slide.SlideID !== slideId && !UUIDsEqual(slide.SlideID, slideId)) {
1131
+ return slide;
1132
+ }
1133
+ if (!lockContext?.BypassLock) {
1134
+ const slideCheck = this.CanActorEditSlide(slide, lockContext?.ActorUserID, lockContext?.OwnerUserID, lockContext?.IsEditor);
1135
+ if (!slideCheck.Allowed) {
1136
+ throw new Error(slideCheck.Reason);
1137
+ }
1138
+ }
1139
+ const existingIndex = slide.Regions.findIndex((r) => r.RegionID === regionPatch.RegionID);
1140
+ const nextRegions = slide.Regions.map((r) => ({ ...r }));
1141
+ if (existingIndex >= 0) {
1142
+ const current = nextRegions[existingIndex];
1143
+ if (!lockContext?.BypassLock) {
1144
+ const regionCheck = this.CanActorEditRegion(slide, current, lockContext?.ActorUserID, lockContext?.OwnerUserID, lockContext?.IsEditor);
1145
+ if (!regionCheck.Allowed) {
1146
+ throw new Error(regionCheck.Reason);
1147
+ }
1148
+ }
1149
+ const merged = {
1150
+ ...current,
1151
+ ...regionPatch,
1152
+ RegionID: current.RegionID,
1153
+ Label: regionPatch.Label ?? current.Label,
1154
+ Kind: regionPatch.Kind ?? current.Kind,
1155
+ MarkdownContent: regionPatch.MarkdownContent !== undefined ? regionPatch.MarkdownContent : current.MarkdownContent,
1156
+ QuoteAttribution: regionPatch.QuoteAttribution ?? current.QuoteAttribution,
1157
+ CalloutTone: regionPatch.CalloutTone ?? current.CalloutTone,
1158
+ ImageUrl: regionPatch.ImageUrl !== undefined
1159
+ ? this.SanitizeImageUrl(regionPatch.ImageUrl)
1160
+ : this.SanitizeImageUrl(current.ImageUrl),
1161
+ ImageAlt: regionPatch.ImageAlt !== undefined ? regionPatch.ImageAlt : current.ImageAlt
1162
+ };
1163
+ if (merged.BlockSpec && regionPatch.MarkdownContent === undefined) {
1164
+ merged.MarkdownContent = DocumentLiveBlockEngine.Instance.SerializeBlockToMarkdownDirective(merged.BlockSpec);
1165
+ }
1166
+ else if (merged.Kind === 'mj-block' && !merged.BlockSpec) {
1167
+ const firstBlock = this.parseFirstBlockFromMarkdown(merged.MarkdownContent);
1168
+ if (firstBlock) {
1169
+ merged.BlockSpec = firstBlock;
1170
+ }
1171
+ }
1172
+ nextRegions[existingIndex] = merged;
1173
+ updatedRegion = merged;
1174
+ }
1175
+ else {
1176
+ const created = {
1177
+ RegionID: regionPatch.RegionID,
1178
+ Label: regionPatch.Label || regionPatch.RegionID,
1179
+ Kind: regionPatch.Kind || 'rich-text',
1180
+ MarkdownContent: regionPatch.MarkdownContent ?? '',
1181
+ BlockSpec: regionPatch.BlockSpec,
1182
+ BigNumberValue: regionPatch.BigNumberValue,
1183
+ BigNumberLabel: regionPatch.BigNumberLabel,
1184
+ BigNumberDelta: regionPatch.BigNumberDelta,
1185
+ QuoteAttribution: regionPatch.QuoteAttribution,
1186
+ CalloutTone: regionPatch.CalloutTone,
1187
+ ImageUrl: this.SanitizeImageUrl(regionPatch.ImageUrl),
1188
+ ImageAlt: regionPatch.ImageAlt
1189
+ };
1190
+ if (created.BlockSpec && !created.MarkdownContent) {
1191
+ created.MarkdownContent = DocumentLiveBlockEngine.Instance.SerializeBlockToMarkdownDirective(created.BlockSpec);
1192
+ }
1193
+ nextRegions.push(created);
1194
+ updatedRegion = created;
1195
+ }
1196
+ return {
1197
+ ...slide,
1198
+ Regions: nextRegions
1199
+ };
1200
+ });
1201
+ if (!updatedRegion) {
1202
+ return { Deck: deck, UpdatedRegion: null };
1203
+ }
1204
+ return {
1205
+ Deck: {
1206
+ ...deck,
1207
+ Slides: nextSlides,
1208
+ UpdatedAt: new Date().toISOString()
1209
+ },
1210
+ UpdatedRegion: updatedRegion
1211
+ };
1212
+ }
1213
+ /**
1214
+ * Deletes a slide by `slideId` (preserving at least 1 slide in the deck) and renumbers remaining slides.
1215
+ */
1216
+ DeleteSlide(deck, slideId, lockContext) {
1217
+ if (deck.Slides.length <= 1) {
1218
+ return { Deck: deck, Deleted: false };
1219
+ }
1220
+ const target = deck.Slides.find((s) => s.SlideID === slideId || UUIDsEqual(s.SlideID, slideId));
1221
+ if (!target) {
1222
+ return { Deck: deck, Deleted: false };
1223
+ }
1224
+ if (!lockContext?.BypassLock) {
1225
+ const check = this.CanActorEditSlide(target, lockContext?.ActorUserID, lockContext?.OwnerUserID, lockContext?.IsEditor);
1226
+ if (!check.Allowed) {
1227
+ throw new Error(check.Reason);
1228
+ }
1229
+ for (const region of target.Regions) {
1230
+ if (region.Locked) {
1231
+ const regionCheck = this.CanActorEditRegion(target, region, lockContext?.ActorUserID, lockContext?.OwnerUserID, lockContext?.IsEditor);
1232
+ if (!regionCheck.Allowed) {
1233
+ throw new Error(regionCheck.Reason);
1234
+ }
1235
+ }
1236
+ }
1237
+ }
1238
+ const filtered = deck.Slides.filter((s) => s.SlideID !== target.SlideID);
1239
+ return {
1240
+ Deck: {
1241
+ ...deck,
1242
+ Slides: this.renumberSlides(filtered.map((s) => this.cloneSlide(s))),
1243
+ UpdatedAt: new Date().toISOString()
1244
+ },
1245
+ Deleted: true
1246
+ };
1247
+ }
1248
+ /**
1249
+ * Reorders slides according to `orderedSlideIds`. Any slides not mentioned in `orderedSlideIds`
1250
+ * are appended in their existing relative order so no slide is ever lost during concurrent edits (`Accept #1`).
1251
+ */
1252
+ ReorderSlides(deck, orderedSlideIds) {
1253
+ const byId = new Map();
1254
+ for (const s of deck.Slides) {
1255
+ byId.set(s.SlideID, this.cloneSlide(s));
1256
+ }
1257
+ const nextSlides = [];
1258
+ const placedIds = new Set();
1259
+ for (const id of orderedSlideIds) {
1260
+ const match = byId.get(id);
1261
+ if (match && !placedIds.has(match.SlideID)) {
1262
+ nextSlides.push(match);
1263
+ placedIds.add(match.SlideID);
1264
+ }
1265
+ }
1266
+ for (const s of deck.Slides) {
1267
+ if (!placedIds.has(s.SlideID)) {
1268
+ nextSlides.push(this.cloneSlide(s));
1269
+ placedIds.add(s.SlideID);
1270
+ }
1271
+ }
1272
+ return {
1273
+ ...deck,
1274
+ Slides: this.renumberSlides(nextSlides),
1275
+ UpdatedAt: new Date().toISOString()
1276
+ };
1277
+ }
1278
+ /**
1279
+ * Moves a single slide up (`-1`) or down (`+1`) in the deck order.
1280
+ */
1281
+ MoveSlide(deck, slideId, delta) {
1282
+ const idx = deck.Slides.findIndex((s) => s.SlideID === slideId || UUIDsEqual(s.SlideID, slideId));
1283
+ if (idx < 0) {
1284
+ return deck;
1285
+ }
1286
+ const targetIdx = idx + delta;
1287
+ if (targetIdx < 0 || targetIdx >= deck.Slides.length) {
1288
+ return deck;
1289
+ }
1290
+ const ids = deck.Slides.map((s) => s.SlideID);
1291
+ const [moved] = ids.splice(idx, 1);
1292
+ ids.splice(targetIdx, 0, moved);
1293
+ return this.ReorderSlides(deck, ids);
1294
+ }
1295
+ /**
1296
+ * Applies either a named theme preset (`ThemeID`) or organization brand color seeds to `deck` (`Accept #4`).
1297
+ */
1298
+ ApplyTheme(deck, themeOrSeeds) {
1299
+ let resolvedTheme;
1300
+ if (typeof themeOrSeeds === 'string') {
1301
+ const preset = SLIDE_DECK_THEME_PRESETS.find((p) => p.ThemeID.toLowerCase() === themeOrSeeds.trim().toLowerCase() || p.Name.toLowerCase() === themeOrSeeds.trim().toLowerCase());
1302
+ resolvedTheme = preset ? { ...preset } : { ...SLIDE_DECK_THEME_PRESETS[0] };
1303
+ }
1304
+ else if ('ThemeID' in themeOrSeeds && 'SurfaceColor' in themeOrSeeds && 'MutedTextColor' in themeOrSeeds) {
1305
+ resolvedTheme = { ...themeOrSeeds };
1306
+ }
1307
+ else {
1308
+ resolvedTheme = this.DeriveThemeFromBrandSeeds(themeOrSeeds);
1309
+ }
1310
+ return {
1311
+ ...deck,
1312
+ Theme: resolvedTheme,
1313
+ UpdatedAt: new Date().toISOString()
1314
+ };
1315
+ }
1316
+ /**
1317
+ * Freezes all live MJ blocks across `deck` using the viewer's current rendered results (`O6` & `Accept #2`).
1318
+ * Used when entering Presentation Mode (`O6`) and when generating a `.pptx` export (`Accept #2`).
1319
+ */
1320
+ FreezeDeckLiveBlocksForPresentation(deck, blockResultsByBlockId, user, options) {
1321
+ const frozenAt = new Date().toISOString();
1322
+ const frozenByUserId = user?.ID ?? 'presenter';
1323
+ const frozenByUserName = user?.Name ?? 'Presenter';
1324
+ const nextSlides = deck.Slides.map((slide) => {
1325
+ const nextRegions = slide.Regions.map((region) => {
1326
+ const block = this.ExtractRegionBlockSpec(region);
1327
+ if (!block) {
1328
+ return { ...region };
1329
+ }
1330
+ // Preserve existing Frozen snapshots verbatim; never silently resign already-frozen blocks (`S3`).
1331
+ if (block.Mode === 'Frozen' && !options?.ForceRefreshFrozen) {
1332
+ return { ...region };
1333
+ }
1334
+ const result = blockResultsByBlockId.get(block.BlockID);
1335
+ if (!result || !result.Success) {
1336
+ return { ...region };
1337
+ }
1338
+ const snapshotBase = {
1339
+ FrozenAt: frozenAt,
1340
+ FrozenByUserID: frozenByUserId,
1341
+ FrozenByUserName: frozenByUserName,
1342
+ Columns: result.Columns,
1343
+ Rows: result.Rows,
1344
+ TotalRowCount: result.TotalRowCount,
1345
+ ...(result.ArtifactContent !== undefined ? { ArtifactContentSnapshot: result.ArtifactContent } : {}),
1346
+ ...(result.ArtifactType !== undefined ? { ArtifactTypeSnapshot: result.ArtifactType } : {}),
1347
+ SecurityWarningAcknowledged: true,
1348
+ Binding: BuildBlockIdentityBinding(block, options?.ArtifactID)
1349
+ };
1350
+ let snapshotContentHash;
1351
+ try {
1352
+ snapshotContentHash = ComputeFrozenSnapshotHash(snapshotBase, options?.SigningSecret);
1353
+ }
1354
+ catch (err) {
1355
+ if (options?.RequireSignature) {
1356
+ throw err;
1357
+ }
1358
+ }
1359
+ const signedSnapshot = snapshotContentHash
1360
+ ? { ...snapshotBase, SnapshotContentHash: snapshotContentHash }
1361
+ : snapshotBase;
1362
+ const frozenBlock = {
1363
+ ...block,
1364
+ Mode: 'Frozen',
1365
+ FrozenSnapshot: signedSnapshot
1366
+ };
1367
+ return {
1368
+ ...region,
1369
+ Kind: 'mj-block',
1370
+ BlockSpec: frozenBlock,
1371
+ MarkdownContent: DocumentLiveBlockEngine.Instance.SerializeBlockToMarkdownDirective(frozenBlock)
1372
+ };
1373
+ });
1374
+ return {
1375
+ ...slide,
1376
+ Regions: nextRegions
1377
+ };
1378
+ });
1379
+ return {
1380
+ ...deck,
1381
+ Slides: nextSlides,
1382
+ UpdatedAt: frozenAt
1383
+ };
1384
+ }
1385
+ /**
1386
+ * Headlessly exports `deck` to ECMA-376 `.pptx` archive bytes (`NW-4`) with valid DrawingML theme/charts,
1387
+ * stripped XML control chars, hidden-slide filtering, and `4:3` / `16:9` aspect ratio support.
1388
+ */
1389
+ ExportDeckToPptxBytes(deck, options) {
1390
+ return ExportDeckToPptxBytesInternal(deck, {
1391
+ ...options,
1392
+ SanitizeImageUrl: (raw) => this.SanitizeImageUrl(raw)
1393
+ });
1394
+ }
1395
+ /**
1396
+ * Headlessly imports `.pptx` archive bytes into a normalized {@link SlideDeckSpec} (`NW-4`).
1397
+ */
1398
+ ImportDeckFromPptxBytes(pptxBytes, fallbackTitle = 'Imported Presentation') {
1399
+ const parsed = ImportDeckFromPptxBytesInternal(pptxBytes, fallbackTitle);
1400
+ return this.normalizeDeckSpec(parsed, parsed.Title, parsed.DeckID);
1401
+ }
1402
+ /**
1403
+ * Executes all live MJ blocks across every slide region in `deck` for `user` (`Accept #2` & `Accept #5`).
1404
+ */
1405
+ async ExecuteDeckLiveBlocks(deck, provider, user) {
1406
+ const results = {};
1407
+ for (const slide of deck.Slides) {
1408
+ for (const region of slide.Regions) {
1409
+ const block = this.ExtractRegionBlockSpec(region);
1410
+ if (block) {
1411
+ results[block.BlockID] = await DocumentLiveBlockEngine.Instance.ExecuteBlock(block, user, provider);
1412
+ }
1413
+ }
1414
+ }
1415
+ return results;
1416
+ }
1417
+ /**
1418
+ * Extracts the {@link DocumentBlockSpec} from a {@link SlideRegionSpec} if the region hosts an MJ block.
1419
+ */
1420
+ ExtractRegionBlockSpec(region) {
1421
+ if (region.BlockSpec) {
1422
+ return region.BlockSpec;
1423
+ }
1424
+ return this.parseFirstBlockFromMarkdown(region.MarkdownContent ?? '');
1425
+ }
1426
+ parseFirstBlockFromMarkdown(markdown) {
1427
+ const segments = DocumentLiveBlockEngine.Instance.ParseMarkdownDirectives(markdown ?? '');
1428
+ for (const seg of segments) {
1429
+ if (seg.Type === 'mj-block' && seg.BlockSpec) {
1430
+ return seg.BlockSpec;
1431
+ }
1432
+ }
1433
+ return null;
1434
+ }
1435
+ /**
1436
+ * Builds a structured outline summary of `deck` for agent perception (`SlideDeckToolLibrary`)
1437
+ * and slide sorter inspection.
1438
+ */
1439
+ BuildDeckOutline(deck) {
1440
+ return {
1441
+ DeckID: deck.DeckID,
1442
+ Title: deck.Title,
1443
+ AspectRatio: deck.AspectRatio,
1444
+ ThemeName: deck.Theme.Name,
1445
+ ThemeID: deck.Theme.ThemeID,
1446
+ SlideCount: deck.Slides.length,
1447
+ Slides: deck.Slides.map((slide) => {
1448
+ const blockIds = [];
1449
+ for (const r of slide.Regions) {
1450
+ const b = this.ExtractRegionBlockSpec(r);
1451
+ if (b) {
1452
+ blockIds.push(b.BlockID);
1453
+ }
1454
+ }
1455
+ return {
1456
+ SlideID: slide.SlideID,
1457
+ SlideNumber: slide.SlideNumber,
1458
+ Layout: slide.Layout,
1459
+ Title: slide.Title,
1460
+ Subtitle: slide.Subtitle,
1461
+ RegionIDs: slide.Regions.map((r) => r.RegionID),
1462
+ EmbeddedBlockIDs: blockIds,
1463
+ HasSpeakerNotes: Boolean(slide.SpeakerNotes && slide.SpeakerNotes.trim().length > 0),
1464
+ Hidden: Boolean(slide.Hidden)
1465
+ };
1466
+ })
1467
+ };
1468
+ }
1469
+ mergeOrCreateRegion(existing, fallback) {
1470
+ if (!existing) {
1471
+ return { ...fallback };
1472
+ }
1473
+ return {
1474
+ ...fallback,
1475
+ ...existing,
1476
+ RegionID: fallback.RegionID,
1477
+ Label: fallback.Label,
1478
+ MarkdownContent: existing.MarkdownContent || fallback.MarkdownContent
1479
+ };
1480
+ }
1481
+ cloneSlide(slide) {
1482
+ return {
1483
+ ...slide,
1484
+ Regions: slide.Regions.map((r) => ({
1485
+ ...r,
1486
+ BlockSpec: r.BlockSpec ? { ...r.BlockSpec } : undefined
1487
+ }))
1488
+ };
1489
+ }
1490
+ mintUniqueSlideId(existingSlides, requestedId) {
1491
+ const existingLower = new Set(existingSlides.map((s) => s.SlideID.toLowerCase()));
1492
+ if (requestedId && requestedId.trim().length > 0 && !existingLower.has(requestedId.trim().toLowerCase())) {
1493
+ return requestedId.trim();
1494
+ }
1495
+ let candidate = `slide-${generateRandomUuid()}`;
1496
+ while (existingLower.has(candidate.toLowerCase())) {
1497
+ candidate = `slide-${generateRandomUuid()}`;
1498
+ }
1499
+ return candidate;
1500
+ }
1501
+ collectDeckBlockIds(slides) {
1502
+ const used = new Set();
1503
+ for (const slide of slides) {
1504
+ for (const region of slide.Regions) {
1505
+ if (region.BlockSpec?.BlockID) {
1506
+ used.add(region.BlockSpec.BlockID.toLowerCase());
1507
+ }
1508
+ const segments = DocumentLiveBlockEngine.Instance.ParseMarkdownDirectives(region.MarkdownContent ?? '');
1509
+ for (const seg of segments) {
1510
+ if (seg.Type === 'mj-block' && seg.BlockSpec?.BlockID) {
1511
+ used.add(seg.BlockSpec.BlockID.toLowerCase());
1512
+ }
1513
+ }
1514
+ }
1515
+ }
1516
+ return used;
1517
+ }
1518
+ cloneRegionWithFreshBlockIds(region, usedBlockIds) {
1519
+ const mintBlockId = () => {
1520
+ let next = `blk-${generateRandomUuid()}`;
1521
+ while (usedBlockIds.has(next.toLowerCase())) {
1522
+ next = `blk-${generateRandomUuid()}`;
1523
+ }
1524
+ usedBlockIds.add(next.toLowerCase());
1525
+ return next;
1526
+ };
1527
+ let nextMarkdown = region.MarkdownContent ?? '';
1528
+ let nextBlockSpec = region.BlockSpec ? { ...region.BlockSpec } : undefined;
1529
+ const blockIdMap = new Map();
1530
+ if (nextBlockSpec?.BlockID) {
1531
+ const freshId = mintBlockId();
1532
+ blockIdMap.set(nextBlockSpec.BlockID, freshId);
1533
+ nextBlockSpec = { ...nextBlockSpec, BlockID: freshId };
1534
+ }
1535
+ if (nextMarkdown.includes(':::mj-block')) {
1536
+ const segments = DocumentLiveBlockEngine.Instance.ParseMarkdownDirectives(nextMarkdown);
1537
+ const parts = [];
1538
+ for (const seg of segments) {
1539
+ if (seg.Type === 'mj-block' && seg.BlockSpec) {
1540
+ const freshId = blockIdMap.get(seg.BlockSpec.BlockID) ?? mintBlockId();
1541
+ blockIdMap.set(seg.BlockSpec.BlockID, freshId);
1542
+ const clonedSpec = { ...seg.BlockSpec, BlockID: freshId };
1543
+ if (!nextBlockSpec) {
1544
+ nextBlockSpec = clonedSpec;
1545
+ }
1546
+ parts.push(DocumentLiveBlockEngine.Instance.SerializeBlockToMarkdownDirective(clonedSpec));
1547
+ }
1548
+ else {
1549
+ parts.push(seg.RawText);
1550
+ }
1551
+ }
1552
+ nextMarkdown = parts.join('\n');
1553
+ }
1554
+ else if (nextBlockSpec) {
1555
+ nextMarkdown = DocumentLiveBlockEngine.Instance.SerializeBlockToMarkdownDirective(nextBlockSpec);
1556
+ }
1557
+ return {
1558
+ ...region,
1559
+ MarkdownContent: nextMarkdown,
1560
+ BlockSpec: nextBlockSpec
1561
+ };
1562
+ }
1563
+ renumberSlides(slides) {
1564
+ return slides.map((s, idx) => ({
1565
+ ...s,
1566
+ SlideNumber: idx + 1
1567
+ }));
1568
+ }
1569
+ normalizeDeckSpec(raw, fallbackTitle, fallbackDeckId) {
1570
+ const defaultTheme = SLIDE_DECK_THEME_PRESETS[0];
1571
+ const rawSlides = Array.isArray(raw.Slides) ? raw.Slides : [];
1572
+ const normalizedSlides = rawSlides.map((s, idx) => {
1573
+ const layout = s.Layout || 'TitleAndBody';
1574
+ const rawRegions = Array.isArray(s.Regions) && s.Regions.length > 0
1575
+ ? s.Regions.map((r, rIdx) => {
1576
+ const blockSpec = r.BlockSpec ?? (this.parseFirstBlockFromMarkdown(r.MarkdownContent ?? '') || undefined);
1577
+ return {
1578
+ RegionID: r.RegionID || `region-${rIdx + 1}`,
1579
+ Label: r.Label || `Region ${rIdx + 1}`,
1580
+ Kind: blockSpec ? 'mj-block' : (r.Kind || 'rich-text'),
1581
+ MarkdownContent: r.MarkdownContent ??
1582
+ (blockSpec
1583
+ ? DocumentLiveBlockEngine.Instance.SerializeBlockToMarkdownDirective(blockSpec)
1584
+ : ''),
1585
+ BlockSpec: blockSpec,
1586
+ BigNumberValue: r.BigNumberValue,
1587
+ BigNumberLabel: r.BigNumberLabel,
1588
+ BigNumberDelta: r.BigNumberDelta,
1589
+ QuoteAttribution: r.QuoteAttribution,
1590
+ CalloutTone: r.CalloutTone,
1591
+ ImageUrl: this.SanitizeImageUrl(r.ImageUrl),
1592
+ ImageAlt: r.ImageAlt,
1593
+ Locked: r.Locked,
1594
+ LockedByUserID: r.LockedByUserID,
1595
+ AllowEditors: r.AllowEditors
1596
+ };
1597
+ })
1598
+ : this.BuildRegionsForLayout(layout);
1599
+ return {
1600
+ SlideID: s.SlideID || `slide-${idx + 1}`,
1601
+ SlideNumber: idx + 1,
1602
+ Layout: layout,
1603
+ Title: s.Title || `Slide ${idx + 1}`,
1604
+ Subtitle: s.Subtitle,
1605
+ Regions: normalizedSlidesRegions(rawRegions),
1606
+ SpeakerNotes: s.SpeakerNotes ?? '',
1607
+ Transition: s.Transition || 'fade',
1608
+ Hidden: Boolean(s.Hidden),
1609
+ Locked: s.Locked,
1610
+ LockedByUserID: s.LockedByUserID,
1611
+ AllowEditors: s.AllowEditors
1612
+ };
1613
+ });
1614
+ return {
1615
+ SchemaVersion: '1.0',
1616
+ DeckID: raw.DeckID || fallbackDeckId || 'deck-1',
1617
+ Title: raw.Title || fallbackTitle || 'Presentation',
1618
+ Subtitle: raw.Subtitle,
1619
+ AspectRatio: raw.AspectRatio === '4:3' ? '4:3' : '16:9',
1620
+ Theme: raw.Theme
1621
+ ? {
1622
+ ThemeID: raw.Theme.ThemeID || defaultTheme.ThemeID,
1623
+ Name: raw.Theme.Name || defaultTheme.Name,
1624
+ PrimaryColor: this.SanitizeCssValue(raw.Theme.PrimaryColor, defaultTheme.PrimaryColor),
1625
+ AccentColor: this.SanitizeCssValue(raw.Theme.AccentColor, defaultTheme.AccentColor),
1626
+ BackgroundColor: this.SanitizeCssValue(raw.Theme.BackgroundColor, defaultTheme.BackgroundColor),
1627
+ SurfaceColor: this.SanitizeCssValue(raw.Theme.SurfaceColor, defaultTheme.SurfaceColor),
1628
+ TextColor: this.SanitizeCssValue(raw.Theme.TextColor, defaultTheme.TextColor),
1629
+ MutedTextColor: this.SanitizeCssValue(raw.Theme.MutedTextColor, defaultTheme.MutedTextColor),
1630
+ HeadingFont: this.SanitizeCssValue(raw.Theme.HeadingFont, defaultTheme.HeadingFont),
1631
+ BodyFont: this.SanitizeCssValue(raw.Theme.BodyFont, defaultTheme.BodyFont),
1632
+ BrandSeedSource: raw.Theme.BrandSeedSource
1633
+ }
1634
+ : { ...defaultTheme },
1635
+ Master: {
1636
+ HeaderText: raw.Master?.HeaderText ?? '',
1637
+ FooterText: raw.Master?.FooterText ?? '',
1638
+ ShowSlideNumbers: raw.Master?.ShowSlideNumbers ?? true,
1639
+ ShowDate: raw.Master?.ShowDate ?? true,
1640
+ OrganizationName: raw.Master?.OrganizationName ?? 'MemberJunction',
1641
+ LogoUrl: this.SanitizeImageUrl(raw.Master?.LogoUrl)
1642
+ },
1643
+ Slides: normalizedSlides.length > 0 ? normalizedSlides : this.CreateDefaultDeck(fallbackTitle, fallbackDeckId).Slides,
1644
+ UpdatedAt: raw.UpdatedAt || new Date().toISOString()
1645
+ };
1646
+ }
1647
+ }
1648
+ function normalizedSlidesRegions(regions) {
1649
+ return regions.map((r) => ({ ...r }));
1650
+ }
1651
+ function generateRandomUuid() {
1652
+ if (typeof globalThis.crypto !== 'undefined' && typeof globalThis.crypto.randomUUID === 'function') {
1653
+ return globalThis.crypto.randomUUID();
1654
+ }
1655
+ const bytes = new Uint8Array(16);
1656
+ if (typeof globalThis.crypto !== 'undefined' && typeof globalThis.crypto.getRandomValues === 'function') {
1657
+ globalThis.crypto.getRandomValues(bytes);
1658
+ }
1659
+ else {
1660
+ for (let i = 0; i < 16; i++) {
1661
+ bytes[i] = Math.floor(Math.random() * 256);
1662
+ }
1663
+ }
1664
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
1665
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
1666
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
1667
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
1668
+ }
1669
+ //# sourceMappingURL=SlideDeckEngine.js.map