@treasure-ai/treasure-deck 2026.11.0 → 2026.11.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.
package/dist/slides.js ADDED
@@ -0,0 +1,610 @@
1
+ import { DeckError } from './parse.js';
2
+ import { resolveLayouts } from './slideslayout.js';
3
+ import { isVideo } from './render.js';
4
+ const empty = () => ({ text: '', runs: [], bullets: [] });
5
+ /** Join rich texts as paragraphs, shifting each one's styles and lists along. */
6
+ function joinRich(parts) {
7
+ const out = empty();
8
+ for (const p of parts) {
9
+ if (!p.text)
10
+ continue;
11
+ if (out.text)
12
+ out.text += '\n';
13
+ const at = out.text.length;
14
+ out.text += p.text;
15
+ out.runs.push(...p.runs.map((r) => ({ ...r, start: r.start + at, end: r.end + at })));
16
+ out.bullets.push(...p.bullets.map((b) => ({ ...b, start: b.start + at, end: b.end + at })));
17
+ }
18
+ return out;
19
+ }
20
+ /** What a slide drops, counted by kind, for one warning per slide. */
21
+ class Skipped {
22
+ counts = new Map();
23
+ add(kind) {
24
+ this.counts.set(kind, (this.counts.get(kind) ?? 0) + 1);
25
+ }
26
+ warning(slide) {
27
+ if (!this.counts.size)
28
+ return undefined;
29
+ const list = [...this.counts].map(([kind, n]) => `${n} ${kind}${n > 1 ? 's' : ''}`).join(', ');
30
+ return `slide ${slide}: skipped ${list} (not supported in Google Slides export yet)`;
31
+ }
32
+ }
33
+ /** Flatten an inline token's children to text with styles. */
34
+ function inline(tokens, skipped, base = {}) {
35
+ const rich = empty();
36
+ const open = [base];
37
+ const style = () => Object.assign({}, ...open);
38
+ const push = (text, extra = {}) => {
39
+ if (!text)
40
+ return;
41
+ const start = rich.text.length;
42
+ rich.text += text;
43
+ const s = { ...style(), ...extra };
44
+ if (Object.values(s).some(Boolean))
45
+ rich.runs.push({ start, end: rich.text.length, ...s });
46
+ };
47
+ for (const t of tokens ?? []) {
48
+ switch (t.type) {
49
+ case 'text':
50
+ push(t.content);
51
+ break;
52
+ case 'code_inline':
53
+ push(t.content, { code: true });
54
+ break;
55
+ case 'softbreak':
56
+ push(' ');
57
+ break;
58
+ // A line break inside a paragraph: Slides' vertical tab.
59
+ case 'hardbreak':
60
+ push('\u000b');
61
+ break;
62
+ case 'strong_open':
63
+ open.push({ bold: true });
64
+ break;
65
+ case 'em_open':
66
+ open.push({ italic: true });
67
+ break;
68
+ case 's_open':
69
+ open.push({ strike: true });
70
+ break;
71
+ case 'link_open': {
72
+ const href = String(t.attrGet('href') ?? '');
73
+ open.push(/^(https?:|mailto:)/.test(href) ? { link: href } : {});
74
+ break;
75
+ }
76
+ case 'strong_close':
77
+ case 'em_close':
78
+ case 's_close':
79
+ case 'link_close':
80
+ open.pop();
81
+ break;
82
+ case 'image':
83
+ skipped.add(isVideo(String(t.attrGet('src') ?? '')) ? 'video' : 'image');
84
+ break;
85
+ case 'deck_icon':
86
+ skipped.add('icon');
87
+ break;
88
+ // Bracketed spans and anything else: their text is in the `text` children.
89
+ default: break;
90
+ }
91
+ }
92
+ return rich;
93
+ }
94
+ /** The blocks of one Markdown fragment's tokens: paragraphs and lists as text, tables as cells. */
95
+ function blocks(tokens, skipped) {
96
+ const out = [];
97
+ // Lists open around paragraphs: the depth of each, and the list collecting the current top-level list's items.
98
+ const lists = [];
99
+ let list;
100
+ let quote = 0;
101
+ const addText = (rich, heading) => {
102
+ if (!rich.text)
103
+ return;
104
+ if (lists.length) {
105
+ rich = { ...rich, text: '\t'.repeat(lists.length - 1) + rich.text, runs: rich.runs.map((r) => ({ ...r, start: r.start + lists.length - 1, end: r.end + lists.length - 1 })) };
106
+ list.push(rich);
107
+ }
108
+ else
109
+ out.push({ kind: 'text', rich, heading });
110
+ };
111
+ for (let i = 0; i < tokens.length; i++) {
112
+ const t = tokens[i];
113
+ switch (t.type) {
114
+ case 'bullet_list_open':
115
+ case 'ordered_list_open':
116
+ if (!lists.length)
117
+ list = [];
118
+ lists.push(t.type === 'ordered_list_open');
119
+ break;
120
+ case 'bullet_list_close':
121
+ case 'ordered_list_close': {
122
+ const ordered = lists.pop();
123
+ if (!lists.length && list) {
124
+ const rich = joinRich(list);
125
+ if (rich.text)
126
+ out.push({ kind: 'text', rich: { ...rich, bullets: [{ start: 0, end: rich.text.length, ordered }] } });
127
+ list = undefined;
128
+ }
129
+ break;
130
+ }
131
+ case 'blockquote_open':
132
+ quote++;
133
+ break;
134
+ case 'blockquote_close':
135
+ quote--;
136
+ break;
137
+ case 'heading_open': {
138
+ const level = Number(t.tag.slice(1));
139
+ addText(inline(tokens[i + 1].children, skipped), level);
140
+ i += 2;
141
+ break;
142
+ }
143
+ case 'paragraph_open':
144
+ addText(inline(tokens[i + 1].children, skipped, quote ? { italic: true } : {}));
145
+ i += 2;
146
+ break;
147
+ case 'fence':
148
+ case 'code_block': {
149
+ if (t.info.trim().split(/\s+/)[0] === 'mermaid') {
150
+ skipped.add('Mermaid diagram');
151
+ break;
152
+ }
153
+ // One paragraph, its lines joined by line breaks: inside a list it stays one item, and its tabs aren't nesting.
154
+ const code = t.content.replace(/\n$/, '').replace(/\n/g, '\u000b');
155
+ if (code)
156
+ addText({ text: code, runs: [{ start: 0, end: code.length, code: true }], bullets: [] });
157
+ break;
158
+ }
159
+ case 'table_open': {
160
+ const cells = [];
161
+ let j = i + 1;
162
+ for (; tokens[j].type !== 'table_close'; j++) {
163
+ const c = tokens[j];
164
+ if (c.type === 'tr_open')
165
+ cells.push([]);
166
+ else if (c.type === 'th_open' || c.type === 'td_open') {
167
+ cells[cells.length - 1].push(inline(tokens[j + 1].children, skipped, c.type === 'th_open' ? { bold: true } : {}));
168
+ }
169
+ }
170
+ i = j;
171
+ if (cells.length)
172
+ out.push({ kind: 'table', cells });
173
+ break;
174
+ }
175
+ default: break;
176
+ }
177
+ }
178
+ return out;
179
+ }
180
+ /** Consecutive text blocks as one text box's text. */
181
+ function merge(bs) {
182
+ const out = [];
183
+ for (const b of bs) {
184
+ const last = out[out.length - 1];
185
+ // A heading in the body is bold; as a slide title it takes the placeholder's style instead.
186
+ const rich = b.kind === 'text' && b.heading ? { ...b.rich, runs: [{ start: 0, end: b.rich.text.length, bold: true }, ...b.rich.runs] } : undefined;
187
+ if (b.kind === 'text') {
188
+ if (last?.kind === 'text')
189
+ last.rich = joinRich([last.rich, rich ?? b.rich]);
190
+ else
191
+ out.push({ kind: 'text', rich: rich ?? b.rich });
192
+ }
193
+ else
194
+ out.push(b);
195
+ }
196
+ return out;
197
+ }
198
+ /** A slide's title, taken out of its blocks: the first block when it's a heading (`title`: any first heading). */
199
+ function takeTitle(bs) {
200
+ const i = bs.findIndex((b) => b.kind === 'text' && b.heading);
201
+ if (i !== 0)
202
+ return undefined;
203
+ const [b] = bs.splice(0, 1);
204
+ return b.kind === 'text' ? b.rich : undefined;
205
+ }
206
+ // Geometry, in EMU, of the default 16:9 page (10 × 5.625 in).
207
+ const EMU_IN = 914400;
208
+ const PAGE_W = 10 * EMU_IN;
209
+ const MARGIN = 0.5 * EMU_IN;
210
+ const BODY_TOP = 1.25 * EMU_IN;
211
+ const BODY_BOTTOM = 5.3 * EMU_IN;
212
+ const GAP = 0.25 * EMU_IN;
213
+ const BODY_PT = 14;
214
+ const LINE = BODY_PT * 1.3 * (EMU_IN / 72);
215
+ const CHAR_W = BODY_PT * 0.5 * (EMU_IN / 72);
216
+ const ROW_H = 0.4 * EMU_IN;
217
+ /** A rough height for a block in a column of the given width, to stack the next one under it. */
218
+ function estimate(b, width) {
219
+ if (b.kind === 'table')
220
+ return b.cells.length * ROW_H;
221
+ const perLine = Math.max(1, Math.floor(width / CHAR_W));
222
+ const lines = b.rich.text.split(/[\n\u000b]/).reduce((n, p) => n + Math.max(1, Math.ceil(p.length / perLine)), 0);
223
+ return lines * LINE + 0.15 * EMU_IN;
224
+ }
225
+ const emu = (magnitude) => ({ magnitude: Math.round(magnitude), unit: 'EMU' });
226
+ const box = (page, x, y, w, h) => ({
227
+ pageObjectId: page,
228
+ size: { width: emu(w), height: emu(h) },
229
+ transform: { scaleX: 1, scaleY: 1, translateX: Math.round(x), translateY: Math.round(y), unit: 'EMU' },
230
+ });
231
+ /** insertText, then its styles, then its lists (last first: making bullets removes the tabs, shifting what follows). */
232
+ export function textRequests(objectId, rich, options = {}) {
233
+ if (!rich.text)
234
+ return [];
235
+ const { cell, fontSize, font, mono = 'Roboto Mono' } = options;
236
+ const where = cell ? { objectId, cellLocation: cell } : { objectId };
237
+ const out = [{ insertText: { ...where, insertionIndex: 0, text: rich.text } }];
238
+ const base = {};
239
+ if (fontSize)
240
+ base.fontSize = { magnitude: fontSize, unit: 'PT' };
241
+ if (font)
242
+ base.fontFamily = font;
243
+ if (Object.keys(base).length)
244
+ out.push({ updateTextStyle: { ...where, textRange: { type: 'ALL' }, style: base, fields: Object.keys(base).join(',') } });
245
+ for (const r of rich.runs) {
246
+ const style = {};
247
+ if (r.bold)
248
+ style.bold = true;
249
+ if (r.italic)
250
+ style.italic = true;
251
+ if (r.strike)
252
+ style.strikethrough = true;
253
+ if (r.code)
254
+ style.fontFamily = mono;
255
+ if (r.link)
256
+ style.link = { url: r.link };
257
+ out.push({ updateTextStyle: { ...where, textRange: { type: 'FIXED_RANGE', startIndex: r.start, endIndex: r.end }, style, fields: Object.keys(style).join(',') } });
258
+ }
259
+ for (const b of [...rich.bullets].reverse()) {
260
+ out.push({
261
+ createParagraphBullets: {
262
+ ...where,
263
+ textRange: { type: 'FIXED_RANGE', startIndex: b.start, endIndex: b.end },
264
+ bulletPreset: b.ordered ? 'NUMBERED_DIGIT_ALPHA_ROMAN' : 'BULLET_DISC_CIRCLE_SQUARE',
265
+ },
266
+ });
267
+ }
268
+ return out;
269
+ }
270
+ /** The requests that make one slide, after the slides before it. */
271
+ function slideRequests(slide, parse, id, skipped, fonts) {
272
+ const mono = fonts?.mono;
273
+ const header = slide.header ? blocks(parse(slide.header), skipped) : [];
274
+ const columns = slide.columns.map((c) => blocks(parse(c.markdown), skipped));
275
+ // The heading in the slide header, else (no header) the first column's leading heading.
276
+ let title = takeTitle(header) ?? (slide.header === undefined ? takeTitle(columns[0]) : undefined);
277
+ if (header.length)
278
+ columns[0].unshift(...header);
279
+ const out = [];
280
+ const titleId = `${id}_title`;
281
+ if (slide.layout === 'title') {
282
+ // Everything after the title line is the subtitle: the `{.subtitle}` and `{.meta}` lines.
283
+ const rest = columns.flat();
284
+ title ??= takeTitle(rest);
285
+ for (const b of rest)
286
+ if (b.kind === 'table')
287
+ skipped.add('table on a title slide');
288
+ const subtitle = joinRich(rest.flatMap((b) => (b.kind === 'text' ? [b.rich] : [])));
289
+ out.push({
290
+ createSlide: {
291
+ objectId: id,
292
+ slideLayoutReference: { predefinedLayout: 'TITLE' },
293
+ placeholderIdMappings: [
294
+ { layoutPlaceholder: { type: 'CENTERED_TITLE', index: 0 }, objectId: titleId },
295
+ { layoutPlaceholder: { type: 'SUBTITLE', index: 0 }, objectId: `${id}_subtitle` },
296
+ ],
297
+ },
298
+ });
299
+ if (title)
300
+ out.push(...textRequests(titleId, title, { mono }));
301
+ out.push(...textRequests(`${id}_subtitle`, subtitle, { mono }));
302
+ return out;
303
+ }
304
+ out.push({
305
+ createSlide: {
306
+ objectId: id,
307
+ slideLayoutReference: { predefinedLayout: slide.layout === 'section' ? 'SECTION_HEADER' : 'TITLE_ONLY' },
308
+ placeholderIdMappings: [{ layoutPlaceholder: { type: 'TITLE', index: 0 }, objectId: titleId }],
309
+ },
310
+ });
311
+ if (title)
312
+ out.push(...textRequests(titleId, title, { mono }));
313
+ // Rows stacked top to bottom, each splitting the body's height evenly; columns side by side by the row's ratio.
314
+ const rows = slide.rows ?? [{ start: 0, ratio: slide.ratio }];
315
+ const rowH = (BODY_BOTTOM - BODY_TOP - GAP * (rows.length - 1)) / rows.length;
316
+ let n = 0;
317
+ rows.forEach((row, r) => {
318
+ const cols = columns.slice(row.start, rows[r + 1]?.start ?? columns.length);
319
+ const ratio = row.ratio?.length === cols.length ? row.ratio : cols.map(() => 1);
320
+ const total = ratio.reduce((a, b) => a + b, 0);
321
+ const usable = PAGE_W - 2 * MARGIN - GAP * (cols.length - 1);
322
+ let x = MARGIN;
323
+ cols.forEach((col, c) => {
324
+ const w = (usable * ratio[c]) / total;
325
+ const top = BODY_TOP + r * (rowH + GAP);
326
+ let y = top;
327
+ for (const b of merge(col)) {
328
+ const h = Math.max(ROW_H, Math.min(estimate(b, w), top + rowH - y));
329
+ const objectId = `${id}_e${++n}`;
330
+ if (b.kind === 'text') {
331
+ out.push({ createShape: { objectId, shapeType: 'TEXT_BOX', elementProperties: box(id, x, y, w, h) } });
332
+ out.push(...textRequests(objectId, b.rich, { fontSize: BODY_PT, font: fonts?.body, mono }));
333
+ }
334
+ else {
335
+ const columnCount = Math.max(...b.cells.map((row) => row.length));
336
+ out.push({ createTable: { objectId, elementProperties: box(id, x, y, w, h), rows: b.cells.length, columns: columnCount } });
337
+ b.cells.forEach((cells, rowIndex) => cells.forEach((cell, columnIndex) => out.push(...textRequests(objectId, cell, { cell: { rowIndex, columnIndex }, fontSize: 12, font: fonts?.body, mono }))));
338
+ }
339
+ y += h + GAP / 2;
340
+ }
341
+ x += w + GAP;
342
+ });
343
+ });
344
+ return out;
345
+ }
346
+ /** A slide's speaker notes (`=== notes`) as rich text; tables as rows of `a | b`. */
347
+ export function slideNotes(built, slide) {
348
+ if (!slide.notes?.trim())
349
+ return undefined;
350
+ const bs = blocks(built.renderer.parse(slide.notes, slide).tokens, new Skipped());
351
+ const rich = joinRich(bs.map((b) => (b.kind === 'text' ? b.rich : { text: b.cells.map((r) => r.map((c) => c.text).join(' | ')).join('\n'), runs: [], bullets: [] })));
352
+ return rich.text ? rich : undefined;
353
+ }
354
+ /** Map a built deck's visible slides to Slides API requests. `prefix` starts every object ID (unique per export). */
355
+ export function planSlides(built, prefix, style) {
356
+ const fonts = style && slidesFonts(style);
357
+ if (!/^[A-Za-z0-9_][A-Za-z0-9_:-]{2,30}$/.test(prefix))
358
+ throw new DeckError(`bad object ID prefix "${prefix}"`);
359
+ const requests = [];
360
+ const notes = [];
361
+ const warnings = [];
362
+ for (const slide of built.deck.slides) {
363
+ if (slide.error) {
364
+ warnings.push(`slide ${slide.number}: skipped (${slide.error.message})`);
365
+ continue;
366
+ }
367
+ const skipped = new Skipped();
368
+ const id = `${prefix}_s${slide.number}`;
369
+ if (/(^|\s)bg=/.test(slide.attrs))
370
+ skipped.add('background image');
371
+ const parse = (src) => {
372
+ const { tokens, panels } = built.renderer.parse(src, slide);
373
+ for (let k = 0; k < panels; k++)
374
+ skipped.add('image');
375
+ return tokens;
376
+ };
377
+ requests.push(...slideRequests(slide, parse, id, skipped, fonts));
378
+ const rich = slideNotes(built, slide);
379
+ if (rich)
380
+ notes.push({ slideId: id, rich });
381
+ const w = skipped.warning(slide.number);
382
+ if (w)
383
+ warnings.push(w);
384
+ }
385
+ return { title: built.title, requests, notes, warnings, style };
386
+ }
387
+ /** The requests that write each slide's speaker notes, given the ID of each slide's speaker-notes shape. */
388
+ export function notesRequests(notes, speakerNotesId) {
389
+ return notes.flatMap((n) => {
390
+ const id = speakerNotesId(n.slideId);
391
+ return id ? textRequests(id, n.rich) : [];
392
+ });
393
+ }
394
+ /** Families of the OS or CSS that Google Slides doesn't have; the next family in the list is used instead. */
395
+ const NOT_IN_SLIDES = /^(-apple-system|BlinkMacSystemFont|SF |SF Pro|SF Mono|Segoe|Helvetica Neue|Hiragino|Noto Sans JP|Noto Serif JP|M PLUS|system-ui|ui-|Menlo|Monaco|Consolas|sans-serif|serif|monospace)/i;
396
+ /** The first family of a CSS font-family list that Google Slides can show, else `fallback`. */
397
+ export function slidesFont(list, fallback) {
398
+ const families = list.split(',').map((f) => f.trim().replace(/^['"]|['"]$/g, '')).filter(Boolean);
399
+ return families.find((f) => !NOT_IN_SLIDES.test(f)) ?? fallback;
400
+ }
401
+ function slidesFonts(style) {
402
+ return {
403
+ display: slidesFont(style.fonts.display, 'Arial'),
404
+ body: slidesFont(style.fonts.body, 'Arial'),
405
+ mono: slidesFont(style.fonts.mono, 'Roboto Mono'),
406
+ };
407
+ }
408
+ const TEXT_PLACEHOLDERS = ['TITLE', 'CENTERED_TITLE', 'SUBTITLE', 'BODY'];
409
+ const EDITABLE_COLORS = ['DARK1', 'LIGHT1', 'DARK2', 'LIGHT2', 'ACCENT1', 'ACCENT2', 'ACCENT3', 'ACCENT4', 'ACCENT5', 'ACCENT6', 'HYPERLINK', 'FOLLOWED_HYPERLINK'];
410
+ /**
411
+ * Put the deck's theme on a presentation's masters and layouts: its colors in the master's color scheme (text,
412
+ * background, accent, links) and background, and its fonts on every title and body placeholder. Slides, and slides
413
+ * people add later, take them from there; title colors go on the title placeholders.
414
+ */
415
+ export function styleRequests(style, masters, layouts) {
416
+ const fonts = slidesFonts(style);
417
+ const out = [];
418
+ const scheme = {
419
+ DARK1: style.text, LIGHT1: style.background, DARK2: style.muted, LIGHT2: style.background,
420
+ ACCENT1: style.accent, HYPERLINK: style.accent, FOLLOWED_HYPERLINK: style.accent,
421
+ };
422
+ for (const m of masters) {
423
+ // Only the first 12 colors can be set, and all 12 at once: the master's own, with the deck's in their place.
424
+ const colors = (m.pageProperties?.colorScheme?.colors ?? [])
425
+ .filter((c) => EDITABLE_COLORS.includes(c.type))
426
+ .map((c) => ({ type: c.type, color: scheme[c.type] ?? c.color }));
427
+ const pageProperties = {};
428
+ if (colors.length)
429
+ pageProperties.colorScheme = { colors };
430
+ if (style.background)
431
+ pageProperties.pageBackgroundFill = { solidFill: { color: { rgbColor: style.background } } };
432
+ const fields = Object.keys(pageProperties);
433
+ if (fields.length)
434
+ out.push({ updatePageProperties: { objectId: m.objectId, pageProperties, fields: fields.join(',') } });
435
+ }
436
+ for (const page of [...masters, ...layouts]) {
437
+ for (const e of page.pageElements ?? []) {
438
+ const type = e.shape?.placeholder?.type;
439
+ if (!type || !TEXT_PLACEHOLDERS.includes(type))
440
+ continue;
441
+ // A placeholder with only its final line break has "no text" to style: Google refuses the request.
442
+ const text = (e.shape?.text?.textElements ?? []).map((t) => t.textRun?.content ?? '').join('');
443
+ if (text.length < 2)
444
+ continue;
445
+ const isTitle = type === 'TITLE' || type === 'CENTERED_TITLE';
446
+ const textStyle = { fontFamily: isTitle ? fonts.display : fonts.body };
447
+ if (isTitle && style.title)
448
+ textStyle.foregroundColor = { opaqueColor: { rgbColor: style.title } };
449
+ out.push({ updateTextStyle: { objectId: e.objectId, textRange: { type: 'ALL' }, style: textStyle, fields: Object.keys(textStyle).join(',') } });
450
+ }
451
+ }
452
+ return out;
453
+ }
454
+ // --- The Slides API ---
455
+ const API = 'https://slides.googleapis.com/v1/presentations';
456
+ /** Requests per batchUpdate. */
457
+ const BATCH = 400;
458
+ async function call(client, method, url, body, contentType) {
459
+ const headers = { Authorization: `Bearer ${client.token}` };
460
+ if (body !== undefined)
461
+ headers['Content-Type'] = contentType ?? 'application/json';
462
+ if (client.quotaProject)
463
+ headers['x-goog-user-project'] = client.quotaProject;
464
+ const payload = body === undefined ? undefined : Buffer.isBuffer(body) ? new Uint8Array(body) : JSON.stringify(body);
465
+ // A call that hangs (a stalled upload) fails after a minute rather than holding the export forever.
466
+ const res = await (client.fetch ?? fetch)(url, { method, headers, body: payload, signal: AbortSignal.timeout(60_000) }).catch((e) => {
467
+ throw new DeckError(`Google ${url.includes('/drive/') ? 'Drive' : 'Slides'} API: ${e.name === 'TimeoutError' ? 'no answer in 60 s' : e.message} (${method} ${url.split('?')[0]})`);
468
+ });
469
+ const text = await res.text();
470
+ if (res.ok)
471
+ return (text ? JSON.parse(text) : {});
472
+ let message = text.slice(0, 500);
473
+ try {
474
+ message = JSON.parse(text).error?.message ?? message;
475
+ }
476
+ catch { /* not JSON */ }
477
+ const api = url.includes('/drive/') ? 'Drive' : 'Slides';
478
+ throw new DeckError(`Google ${api} API: HTTP ${res.status}: ${message}${hint(res.status, message, api)}`);
479
+ }
480
+ /** What to try for an error the Slides or Drive API returns. */
481
+ export function hint(status, message, api = 'Slides') {
482
+ const service = api === 'Drive' ? 'drive.googleapis.com' : 'slides.googleapis.com';
483
+ if (status === 401)
484
+ return '\nThe token was refused: sign in again (gcloud auth login --enable-gdrive-access) or set DECK_GOOGLE_TOKEN.';
485
+ if (status !== 403)
486
+ return '';
487
+ if (/quota project/i.test(message)) {
488
+ return '\nSet GOOGLE_CLOUD_QUOTA_PROJECT to a Google Cloud project of yours with the Slides and Drive APIs enabled (gcloud services enable slides.googleapis.com drive.googleapis.com --project <id>).';
489
+ }
490
+ if (/has not been used|is disabled|SERVICE_DISABLED/i.test(message)) {
491
+ return `\nThe token's OAuth client project doesn't have the ${api} API enabled: enable it there (gcloud services enable ${service} --project <id>), or set GOOGLE_CLOUD_QUOTA_PROJECT to a project that has it, or set DECK_GOOGLE_TOKEN to a token from your own OAuth client.`;
492
+ }
493
+ if (/scope/i.test(message)) {
494
+ if (api === 'Drive')
495
+ return '\nThe token lacks a Drive scope for the pictures (https://www.googleapis.com/auth/drive.file, or drive): sign in with gcloud auth login --enable-gdrive-access, or mint DECK_GOOGLE_TOKEN with one of them.';
496
+ return '\nThe token lacks a Slides scope (https://www.googleapis.com/auth/presentations, drive.file, or drive): sign in with gcloud auth login --enable-gdrive-access, or mint DECK_GOOGLE_TOKEN with one of them.';
497
+ }
498
+ return '';
499
+ }
500
+ const DRIVE = 'https://www.googleapis.com/drive/v3/files';
501
+ const DRIVE_UPLOAD = 'https://www.googleapis.com/upload/drive/v3/files';
502
+ /** Pictures uploaded at once. */
503
+ const UPLOADS = 6;
504
+ /**
505
+ * Put pictures where Google Slides can fetch them: each uploaded to the user's Drive and readable by link, since
506
+ * Slides takes a picture only from a URL it can open. Slides copies a picture when it's inserted, so `remove` deletes
507
+ * them after the batchUpdate.
508
+ */
509
+ async function hostImages(client, images, name) {
510
+ const ids = [];
511
+ const remove = async () => {
512
+ await Promise.all(ids.filter(Boolean).map((id) => call(client, 'DELETE', `${DRIVE}/${id}`).catch(() => undefined)));
513
+ };
514
+ const upload = async (image, i) => {
515
+ const boundary = `deck${Math.random().toString(36).slice(2)}`;
516
+ const meta = JSON.stringify({ name: `${name} ${i + 1}.jpg`, mimeType: 'image/jpeg' });
517
+ const body = Buffer.concat([
518
+ Buffer.from(`--${boundary}\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n${meta}\r\n--${boundary}\r\nContent-Type: image/jpeg\r\n\r\n`),
519
+ image,
520
+ Buffer.from(`\r\n--${boundary}--`),
521
+ ]);
522
+ const { id } = await call(client, 'POST', `${DRIVE_UPLOAD}?uploadType=multipart&fields=id`, body, `multipart/related; boundary=${boundary}`);
523
+ ids[i] = id;
524
+ await call(client, 'POST', `${DRIVE}/${id}/permissions`, { role: 'reader', type: 'anyone' });
525
+ };
526
+ // A few at a time: a deck has dozens of pictures.
527
+ // On a failure the others take no more, and those under way finish first, so every upload made is deleted.
528
+ let next = 0;
529
+ let failed = false;
530
+ const worker = async () => {
531
+ while (!failed && next < images.length) {
532
+ const i = next++;
533
+ await upload(images[i], i).catch((e) => {
534
+ failed = true;
535
+ throw e;
536
+ });
537
+ }
538
+ };
539
+ const results = await Promise.allSettled(Array.from({ length: Math.min(UPLOADS, images.length) }, worker));
540
+ const failure = results.find((r) => r.status === 'rejected');
541
+ if (failure) {
542
+ await remove();
543
+ throw failure.reason;
544
+ }
545
+ return { urls: ids.map((id) => `https://drive.google.com/uc?export=download&id=${id}`), remove };
546
+ }
547
+ /**
548
+ * Make the plan's slides: in a new presentation (whose blank first slide is then removed), or in `presentationId`
549
+ * (after its slides, or instead of them with `replace`). Returns the presentation's edit URL.
550
+ */
551
+ export async function exportSlides(plan, client, options = {}) {
552
+ const presentationId = options.presentationId;
553
+ let id = presentationId;
554
+ let requests = [...plan.requests];
555
+ // A new presentation, or the one to replace: its master takes the deck's theme, its layouts the plan's, and its
556
+ // slides go once the new ones are made.
557
+ let own;
558
+ if (!id) {
559
+ own = await call(client, 'POST', API, { title: plan.title });
560
+ id = own.presentationId;
561
+ }
562
+ else if (options.replace) {
563
+ const element = 'pageElements(objectId,size,shape(placeholder/type,text/textElements/textRun/content))';
564
+ const fields = `slides/objectId,masters(objectId,pageProperties/colorScheme,${element}),layouts(objectId,layoutProperties/name,${element})`;
565
+ own = await call(client, 'GET', `${API}/${encodeURIComponent(id)}?fields=${encodeURIComponent(fields)}`);
566
+ }
567
+ else if (plan.layouts?.length) {
568
+ throw new DeckError('the plan remakes layouts: export it to a new presentation, or with replace');
569
+ }
570
+ if (own) {
571
+ const { setup, requests: filled } = resolveLayouts(plan, own.layouts ?? [], own.masters ?? []);
572
+ requests = [...(plan.style ? styleRequests(plan.style, own.masters ?? [], own.layouts ?? []) : []), ...setup, ...filled];
573
+ for (const s of own.slides ?? [])
574
+ requests.push({ deleteObject: { objectId: s.objectId } });
575
+ }
576
+ const base = `${API}/${encodeURIComponent(id)}`;
577
+ const url = `https://docs.google.com/presentation/d/${id}/edit`;
578
+ let hosted;
579
+ try {
580
+ if (plan.images?.length)
581
+ hosted = await hostImages(client, plan.images, `deck slides ${plan.title}`);
582
+ if (hosted) {
583
+ const urls = hosted.urls;
584
+ requests = JSON.parse(JSON.stringify(requests).replace(/"deck-image:(\d+)"/g, (_, n) => JSON.stringify(urls[Number(n)])));
585
+ }
586
+ // In parts, so a large deck stays under the API's request size.
587
+ for (let i = 0; i < requests.length; i += BATCH) {
588
+ await call(client, 'POST', `${base}:batchUpdate`, { requests: requests.slice(i, i + BATCH) });
589
+ }
590
+ }
591
+ catch (e) {
592
+ // A new presentation exists but isn't filled: say where, so it can be deleted or reused with --presentation.
593
+ if (!presentationId && e instanceof DeckError)
594
+ throw new DeckError(`${e.message}\nThe presentation was created but not filled: ${url}`);
595
+ throw e;
596
+ }
597
+ finally {
598
+ await hosted?.remove();
599
+ }
600
+ if (plan.notes.length) {
601
+ const fields = 'slides(objectId,slideProperties/notesPage/notesProperties/speakerNotesObjectId)';
602
+ const got = await call(client, 'GET', `${base}?fields=${encodeURIComponent(fields)}`);
603
+ const ids = new Map((got.slides ?? []).map((s) => [s.objectId, s.slideProperties?.notesPage?.notesProperties?.speakerNotesObjectId]));
604
+ const notes = notesRequests(plan.notes, (slideId) => ids.get(slideId));
605
+ if (notes.length)
606
+ await call(client, 'POST', `${base}:batchUpdate`, { requests: notes });
607
+ }
608
+ return { id, url };
609
+ }
610
+ //# sourceMappingURL=slides.js.map