@mindstone/mcp-server-google-workspace 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +43 -5
  2. package/dist/modules/docs/service.d.ts +76 -6
  3. package/dist/modules/docs/service.js +791 -103
  4. package/dist/modules/docs/tabCopy.d.ts +266 -0
  5. package/dist/modules/docs/tabCopy.js +794 -0
  6. package/dist/modules/docs/tabs.d.ts +161 -0
  7. package/dist/modules/docs/tabs.js +416 -0
  8. package/dist/modules/docs/types.d.ts +141 -1
  9. package/dist/modules/drive/service.d.ts +15 -0
  10. package/dist/modules/drive/service.js +77 -2
  11. package/dist/modules/drive/types.d.ts +1 -1
  12. package/dist/modules/sheets/a1Utils.d.ts +13 -0
  13. package/dist/modules/sheets/a1Utils.js +33 -7
  14. package/dist/modules/sheets/formatters.d.ts +33 -2
  15. package/dist/modules/sheets/formatters.js +84 -5
  16. package/dist/modules/sheets/service.d.ts +26 -1
  17. package/dist/modules/sheets/service.js +264 -8
  18. package/dist/modules/sheets/types.d.ts +71 -0
  19. package/dist/modules/sheets/types.js +12 -1
  20. package/dist/modules/sheets/writeGuards.js +2 -2
  21. package/dist/tools/definitions/destructive-overrides.json +8 -0
  22. package/dist/tools/definitions/docs.js +395 -9
  23. package/dist/tools/definitions/drive.js +9 -4
  24. package/dist/tools/definitions/gmail.js +30 -3
  25. package/dist/tools/definitions/open-world-overrides.json +8 -0
  26. package/dist/tools/definitions/sheets.js +177 -1
  27. package/dist/tools/docs-handlers.d.ts +125 -0
  28. package/dist/tools/docs-handlers.js +397 -15
  29. package/dist/tools/gmail-handlers.d.ts +3 -0
  30. package/dist/tools/gmail-handlers.js +19 -5
  31. package/dist/tools/param-normalizer.js +16 -0
  32. package/dist/tools/server.js +35 -3
  33. package/dist/tools/sheets-handlers.d.ts +54 -1
  34. package/dist/tools/sheets-handlers.js +107 -13
  35. package/dist/tools/type-guards.d.ts +89 -0
  36. package/dist/tools/type-guards.js +190 -6
  37. package/dist/tools/types.d.ts +1 -1
  38. package/dist/utils/apiError.d.ts +6 -0
  39. package/dist/utils/apiError.js +12 -0
  40. package/dist/utils/tabPosition.d.ts +20 -0
  41. package/dist/utils/tabPosition.js +19 -0
  42. package/package.json +1 -1
@@ -1,9 +1,14 @@
1
1
  import { google } from 'googleapis';
2
2
  import { BaseGoogleService } from '../../services/base/BaseGoogleService.js';
3
+ import { TabCopyError, copyTabContent } from './tabCopy.js';
4
+ import { computeMoveApiIndex } from '../../utils/tabPosition.js';
3
5
  import { DOCS_SCOPES } from './scopes.js';
4
- import { describeApiError, isAuthHandoffError } from '../../utils/apiError.js';
6
+ import { describeApiError, describeApiErrorUntrusted, isAuthHandoffError } from '../../utils/apiError.js';
7
+ import { wrapUntrustedJsonStrings } from '../../utils/untrusted-content.js';
8
+ import { ALL_TEXT_KEYS, DocsInputError, TAB_READ_TEXT_OPTIONS, TAB_TREE_FIELDS, TRUNCATION_MARKER, assertUniqueTitle, buildAllTabsText, bodyEndIndex, countWords, descendantsOf, extractBodyText, findAnchor, flatParagraphs, flattenTabs, nextParagraphInContainer, normalizeInsertText, paragraphSearchText, requireTabs, resolveTab, siblingsOf, } from './tabs.js';
5
9
  const DEFAULT_MAX_CHARS = 50000;
6
- const TRUNCATION_MARKER = '\n\n[TRUNCATED - document exceeds character limit]';
10
+ /** Cap on `read_workspace_document` with `tab_id` + `return_json` (enveloped size). */
11
+ export const MAX_TAB_JSON_CHARS = 100_000;
7
12
  export class DocsService extends BaseGoogleService {
8
13
  initialized = false;
9
14
  constructor() {
@@ -41,51 +46,43 @@ export class DocsService extends BaseGoogleService {
41
46
  * Extract plain text from document body structure
42
47
  */
43
48
  extractTextFromBody(body) {
44
- if (!body?.content) {
45
- return '';
46
- }
47
- const textParts = [];
48
- for (const element of body.content) {
49
- if (element.paragraph?.elements) {
50
- for (const paragraphElement of element.paragraph.elements) {
51
- if (paragraphElement.textRun?.content) {
52
- textParts.push(paragraphElement.textRun.content);
53
- }
54
- }
55
- }
56
- else if (element.table) {
57
- // Extract text from table cells
58
- for (const row of element.table.tableRows || []) {
59
- for (const cell of row.tableCells || []) {
60
- if (cell.content) {
61
- for (const cellElement of cell.content) {
62
- if (cellElement.paragraph?.elements) {
63
- for (const pe of cellElement.paragraph.elements) {
64
- if (pe.textRun?.content) {
65
- textParts.push(pe.textRun.content);
66
- }
67
- }
68
- }
69
- }
70
- }
71
- }
72
- textParts.push('\n'); // Row separator
73
- }
74
- }
75
- }
76
- return textParts.join('');
49
+ return extractBodyText(body);
77
50
  }
78
51
  /**
79
52
  * Get the end index of the document body for insert operations
80
53
  */
81
54
  getDocumentEndIndex(doc) {
82
- const body = doc.body;
83
- if (!body?.content || body.content.length === 0) {
84
- return 1;
85
- }
86
- // Find the last structural element and get its end index
87
- const lastElement = body.content[body.content.length - 1];
88
- return (lastElement.endIndex ?? 1) - 1; // -1 to insert before final newline
55
+ return bodyEndIndex(doc.body);
56
+ }
57
+ /**
58
+ * Full read of every tab's content, flattened in tree order.
59
+ */
60
+ async readAllTabs(client, documentId) {
61
+ const response = await client.documents.get({ documentId, includeTabsContent: true });
62
+ return { doc: response.data, flat: flattenTabs(requireTabs(response.data)) };
63
+ }
64
+ /**
65
+ * Tree-only read (tab properties, no content).
66
+ */
67
+ async readTabTree(client, documentId) {
68
+ const response = await client.documents.get({
69
+ documentId,
70
+ includeTabsContent: true,
71
+ fields: TAB_TREE_FIELDS,
72
+ });
73
+ return { doc: response.data, flat: flattenTabs(requireTabs(response.data)) };
74
+ }
75
+ toTabInfo(tab, wordCount) {
76
+ return {
77
+ tabId: tab.tabId,
78
+ title: tab.title,
79
+ index: tab.index,
80
+ ...(wordCount !== undefined ? { wordCount } : {}),
81
+ parentTabId: tab.parentTabId,
82
+ nestingLevel: tab.nestingLevel,
83
+ path: tab.path,
84
+ childCount: tab.childCount,
85
+ };
89
86
  }
90
87
  /**
91
88
  * Read a document and return its content
@@ -98,9 +95,27 @@ export class DocsService extends BaseGoogleService {
98
95
  // (Google may return only FULL if both are requested)
99
96
  await this.validateScopes(email, [DOCS_SCOPES.FULL]);
100
97
  const client = await this.getAuthenticatedClient(email, (auth) => google.docs({ version: 'v1', auth }));
101
- const response = await client.documents.get({
102
- documentId,
103
- });
98
+ if (options.tabId !== undefined || options.allTabs) {
99
+ return await this.getDocumentTabs(client, documentId, options);
100
+ }
101
+ if (options.returnJson) {
102
+ // Raw JSON without a tab argument: today's single read (top-level body = first tab).
103
+ const response = await client.documents.get({
104
+ documentId,
105
+ });
106
+ return {
107
+ success: true,
108
+ data: response.data,
109
+ };
110
+ }
111
+ // Text read of the first tab (today's request and extraction) plus a
112
+ // tree-only read, in parallel, for the tab count.
113
+ const [response, tree] = await Promise.all([
114
+ client.documents.get({
115
+ documentId,
116
+ }),
117
+ this.readTabTree(client, documentId),
118
+ ]);
104
119
  const doc = response.data;
105
120
  const maxChars = options.maxChars ?? DEFAULT_MAX_CHARS;
106
121
  // Extract text content
@@ -110,6 +125,7 @@ export class DocsService extends BaseGoogleService {
110
125
  textContent = textContent.substring(0, maxChars) + TRUNCATION_MARKER;
111
126
  truncated = true;
112
127
  }
128
+ const firstTab = tree.flat.find((tab) => tab.nestingLevel === 0);
113
129
  const result = {
114
130
  title: doc.title || 'Untitled',
115
131
  documentId: doc.documentId || documentId,
@@ -117,12 +133,12 @@ export class DocsService extends BaseGoogleService {
117
133
  content: textContent,
118
134
  truncated,
119
135
  revisionId: doc.revisionId || undefined,
120
- // Note: tabCount/tabs not available in googleapis@129
121
- tabCount: 1,
136
+ tabCount: tree.flat.length,
137
+ ...(firstTab ? { shownTab: { tabId: firstTab.tabId, title: firstTab.title } } : {}),
122
138
  };
123
139
  return {
124
140
  success: true,
125
- data: options.returnJson ? doc : result,
141
+ data: result,
126
142
  };
127
143
  }
128
144
  catch (error) {
@@ -130,12 +146,81 @@ export class DocsService extends BaseGoogleService {
130
146
  // into a plain error string would skip the host's auth_required handoff.
131
147
  if (isAuthHandoffError(error))
132
148
  throw error;
149
+ if (error instanceof DocsInputError)
150
+ throw error;
133
151
  return {
134
152
  success: false,
135
153
  error: describeApiError(error),
136
154
  };
137
155
  }
138
156
  }
157
+ /**
158
+ * `tab_id` / `all_tabs` reads: one full `includeTabsContent` read, then the
159
+ * requested tab (text or bounded JSON) or every tab under one text budget.
160
+ */
161
+ async getDocumentTabs(client, documentId, options) {
162
+ if (options.allTabs && options.returnJson) {
163
+ throw new DocsInputError('all_tabs with return_json would return the whole document as raw JSON (often several MB). Use text mode, or tab_id with return_json for one tab.');
164
+ }
165
+ const { doc, flat } = await this.readAllTabs(client, documentId);
166
+ const resolvedId = doc.documentId || documentId;
167
+ const title = doc.title || 'Untitled';
168
+ const maxChars = options.maxChars ?? DEFAULT_MAX_CHARS;
169
+ if (options.allTabs) {
170
+ const { content, truncated } = buildAllTabsText(flat, maxChars);
171
+ const result = {
172
+ title,
173
+ documentId: resolvedId,
174
+ documentUrl: this.constructDocumentUrl(resolvedId),
175
+ content,
176
+ truncated,
177
+ revisionId: doc.revisionId || undefined,
178
+ tabCount: flat.length,
179
+ };
180
+ return { success: true, data: result };
181
+ }
182
+ const tab = resolveTab(flat, options.tabId, { allowDefault: true });
183
+ if (options.returnJson) {
184
+ // One tab only; its sub-tabs are listed by id/title, not inlined.
185
+ const payload = {
186
+ documentId: resolvedId,
187
+ title,
188
+ ...(doc.revisionId ? { revisionId: doc.revisionId } : {}),
189
+ tab: {
190
+ tabProperties: tab.tab.tabProperties,
191
+ documentTab: tab.tab.documentTab ? withNamedRangeList(tab.tab.documentTab) : undefined,
192
+ },
193
+ childTabs: (tab.tab.childTabs ?? []).map((child) => ({
194
+ tabId: child.tabProperties?.tabId ?? '',
195
+ title: child.tabProperties?.title ?? '',
196
+ })),
197
+ };
198
+ // Measure what the handler returns (strings enveloped with the same source).
199
+ const size = JSON.stringify(wrapUntrustedJsonStrings(payload, `google-workspace:docs:document/${documentId}`)).length;
200
+ if (size > MAX_TAB_JSON_CHARS) {
201
+ throw new DocsInputError(`This tab's JSON is ${size} characters, over the ${MAX_TAB_JSON_CHARS} limit for return_json. ` +
202
+ 'Read it as text (omit return_json), or edit it with insert_workspace_document_text or find_and_replace_workspace_document.');
203
+ }
204
+ return { success: true, data: payload };
205
+ }
206
+ let textContent = extractBodyText(tab.tab.documentTab?.body, TAB_READ_TEXT_OPTIONS);
207
+ let truncated = false;
208
+ if (textContent.length > maxChars) {
209
+ textContent = textContent.substring(0, maxChars) + TRUNCATION_MARKER;
210
+ truncated = true;
211
+ }
212
+ const result = {
213
+ title,
214
+ documentId: resolvedId,
215
+ documentUrl: this.constructDocumentUrl(resolvedId),
216
+ content: textContent,
217
+ truncated,
218
+ revisionId: doc.revisionId || undefined,
219
+ tabCount: flat.length,
220
+ requestedTab: { tabId: tab.tabId, title: tab.title, path: tab.path, childCount: tab.childCount },
221
+ };
222
+ return { success: true, data: result };
223
+ }
139
224
  /**
140
225
  * Create a new document with optional initial content
141
226
  */
@@ -196,7 +281,7 @@ export class DocsService extends BaseGoogleService {
196
281
  }
197
282
  }
198
283
  /**
199
- * Append text to the end of a document
284
+ * Append text to the end of a document (the first tab, or `tabId`'s tab)
200
285
  */
201
286
  async appendToDocument(email, options) {
202
287
  try {
@@ -204,6 +289,31 @@ export class DocsService extends BaseGoogleService {
204
289
  this.checkInitialized();
205
290
  await this.validateScopes(email, [DOCS_SCOPES.FULL]);
206
291
  const client = await this.getAuthenticatedClient(email, (auth) => google.docs({ version: 'v1', auth }));
292
+ if (options.tabId !== undefined) {
293
+ const { doc, flat } = await this.readAllTabs(client, options.documentId);
294
+ const tab = resolveTab(flat, options.tabId, { allowDefault: true });
295
+ const endIndex = bodyEndIndex(tab.tab.documentTab?.body);
296
+ await client.documents.batchUpdate({
297
+ documentId: options.documentId,
298
+ requestBody: {
299
+ requests: [
300
+ {
301
+ insertText: {
302
+ location: { index: endIndex, tabId: tab.tabId },
303
+ text: options.text,
304
+ },
305
+ },
306
+ ],
307
+ },
308
+ });
309
+ const result = {
310
+ title: doc.title || 'Untitled',
311
+ documentId: options.documentId,
312
+ documentUrl: this.constructDocumentUrl(options.documentId),
313
+ requestedTab: { tabId: tab.tabId, title: tab.title, path: tab.path },
314
+ };
315
+ return { success: true, data: result };
316
+ }
207
317
  // First get the document to find the end index
208
318
  const docResponse = await client.documents.get({
209
319
  documentId: options.documentId,
@@ -238,6 +348,8 @@ export class DocsService extends BaseGoogleService {
238
348
  // into a plain error string would skip the host's auth_required handoff.
239
349
  if (isAuthHandoffError(error))
240
350
  throw error;
351
+ if (error instanceof DocsInputError)
352
+ throw error;
241
353
  return {
242
354
  success: false,
243
355
  error: describeApiError(error),
@@ -245,7 +357,34 @@ export class DocsService extends BaseGoogleService {
245
357
  }
246
358
  }
247
359
  /**
248
- * Replace entire document content
360
+ * Delete-then-insert requests that replace a body's content.
361
+ */
362
+ buildReplaceRequests(endIndex, content, tabId) {
363
+ // Build requests: delete existing content (if any), then insert new
364
+ const requests = [];
365
+ // Only delete if there's content beyond index 1
366
+ if (endIndex > 1) {
367
+ requests.push({
368
+ deleteContentRange: {
369
+ range: {
370
+ startIndex: 1,
371
+ endIndex: endIndex,
372
+ ...(tabId !== undefined ? { tabId } : {}),
373
+ },
374
+ },
375
+ });
376
+ }
377
+ // Insert new content at start
378
+ requests.push({
379
+ insertText: {
380
+ location: { index: 1, ...(tabId !== undefined ? { tabId } : {}) },
381
+ text: content,
382
+ },
383
+ });
384
+ return requests;
385
+ }
386
+ /**
387
+ * Replace the content of the first tab, or of `tabId`'s tab
249
388
  */
250
389
  async replaceDocument(email, options) {
251
390
  try {
@@ -253,35 +392,31 @@ export class DocsService extends BaseGoogleService {
253
392
  this.checkInitialized();
254
393
  await this.validateScopes(email, [DOCS_SCOPES.FULL]);
255
394
  const client = await this.getAuthenticatedClient(email, (auth) => google.docs({ version: 'v1', auth }));
395
+ if (options.tabId !== undefined) {
396
+ const { doc, flat } = await this.readAllTabs(client, options.documentId);
397
+ const tab = resolveTab(flat, options.tabId, { allowDefault: true });
398
+ const endIndex = bodyEndIndex(tab.tab.documentTab?.body);
399
+ await client.documents.batchUpdate({
400
+ documentId: options.documentId,
401
+ requestBody: { requests: this.buildReplaceRequests(endIndex, options.content, tab.tabId) },
402
+ });
403
+ const result = {
404
+ title: doc.title || 'Untitled',
405
+ documentId: options.documentId,
406
+ documentUrl: this.constructDocumentUrl(options.documentId),
407
+ requestedTab: { tabId: tab.tabId, title: tab.title, path: tab.path },
408
+ };
409
+ return { success: true, data: result };
410
+ }
256
411
  // First get the document to find the content range
257
412
  const docResponse = await client.documents.get({
258
413
  documentId: options.documentId,
259
414
  });
260
415
  const doc = docResponse.data;
261
416
  const endIndex = this.getDocumentEndIndex(doc);
262
- // Build requests: delete existing content (if any), then insert new
263
- const requests = [];
264
- // Only delete if there's content beyond index 1
265
- if (endIndex > 1) {
266
- requests.push({
267
- deleteContentRange: {
268
- range: {
269
- startIndex: 1,
270
- endIndex: endIndex,
271
- },
272
- },
273
- });
274
- }
275
- // Insert new content at start
276
- requests.push({
277
- insertText: {
278
- location: { index: 1 },
279
- text: options.content,
280
- },
281
- });
282
417
  await client.documents.batchUpdate({
283
418
  documentId: options.documentId,
284
- requestBody: { requests },
419
+ requestBody: { requests: this.buildReplaceRequests(endIndex, options.content) },
285
420
  });
286
421
  const result = {
287
422
  title: doc.title || 'Untitled',
@@ -298,6 +433,8 @@ export class DocsService extends BaseGoogleService {
298
433
  // into a plain error string would skip the host's auth_required handoff.
299
434
  if (isAuthHandoffError(error))
300
435
  throw error;
436
+ if (error instanceof DocsInputError)
437
+ throw error;
301
438
  return {
302
439
  success: false,
303
440
  error: describeApiError(error),
@@ -305,7 +442,8 @@ export class DocsService extends BaseGoogleService {
305
442
  }
306
443
  }
307
444
  /**
308
- * Find and replace text throughout the document
445
+ * Find and replace text in every tab, or only in `tabId`'s tab
446
+ * (sub-tabs are separate tabs and are not included).
309
447
  */
310
448
  async findAndReplace(email, options) {
311
449
  try {
@@ -313,6 +451,12 @@ export class DocsService extends BaseGoogleService {
313
451
  this.checkInitialized();
314
452
  await this.validateScopes(email, [DOCS_SCOPES.FULL]);
315
453
  const client = await this.getAuthenticatedClient(email, (auth) => google.docs({ version: 'v1', auth }));
454
+ let target;
455
+ let preRead;
456
+ if (options.tabId !== undefined) {
457
+ preRead = await this.readTabTree(client, options.documentId);
458
+ target = resolveTab(preRead.flat, options.tabId, { allowDefault: true });
459
+ }
316
460
  const response = await client.documents.batchUpdate({
317
461
  documentId: options.documentId,
318
462
  requestBody: {
@@ -324,6 +468,7 @@ export class DocsService extends BaseGoogleService {
324
468
  matchCase: options.matchCase ?? false,
325
469
  },
326
470
  replaceText: options.replaceText,
471
+ ...(target ? { tabsCriteria: { tabIds: [target.tabId] } } : {}),
327
472
  },
328
473
  },
329
474
  ],
@@ -335,18 +480,21 @@ export class DocsService extends BaseGoogleService {
335
480
  if (replies && replies[0]?.replaceAllText?.occurrencesChanged) {
336
481
  occurrencesChanged = replies[0].replaceAllText.occurrencesChanged;
337
482
  }
338
- // Get updated document info
339
- const docResponse = await client.documents.get({
483
+ // Title + tab tree (no content): reuse the pre-read when tab_id was set;
484
+ // otherwise read it now for the "Searched all <n> tabs" note.
485
+ const tree = preRead ?? (await this.readTabTree(client, options.documentId));
486
+ const data = {
487
+ title: tree.doc.title || 'Untitled',
340
488
  documentId: options.documentId,
341
- fields: 'title,documentId',
342
- });
489
+ documentUrl: this.constructDocumentUrl(options.documentId),
490
+ tabCount: tree.flat.length,
491
+ ...(target
492
+ ? { requestedTab: { tabId: target.tabId, title: target.title, path: target.path } }
493
+ : {}),
494
+ };
343
495
  return {
344
496
  success: true,
345
- data: {
346
- title: docResponse.data.title || 'Untitled',
347
- documentId: options.documentId,
348
- documentUrl: this.constructDocumentUrl(options.documentId),
349
- },
497
+ data,
350
498
  occurrencesChanged,
351
499
  };
352
500
  }
@@ -355,6 +503,8 @@ export class DocsService extends BaseGoogleService {
355
503
  // into a plain error string would skip the host's auth_required handoff.
356
504
  if (isAuthHandoffError(error))
357
505
  throw error;
506
+ if (error instanceof DocsInputError)
507
+ throw error;
358
508
  return {
359
509
  success: false,
360
510
  error: describeApiError(error),
@@ -400,8 +550,8 @@ export class DocsService extends BaseGoogleService {
400
550
  }
401
551
  }
402
552
  /**
403
- * List tabs in a document
404
- * Note: Full tab support requires googleapis upgrade. Currently returns single default tab.
553
+ * List every tab in a document (all nesting levels, tree order).
554
+ * Without word counts this is a tree-only read (no tab content fetched).
405
555
  */
406
556
  async listTabs(email, options) {
407
557
  try {
@@ -411,28 +561,20 @@ export class DocsService extends BaseGoogleService {
411
561
  // (Google may return only FULL if both are requested)
412
562
  await this.validateScopes(email, [DOCS_SCOPES.FULL]);
413
563
  const client = await this.getAuthenticatedClient(email, (auth) => google.docs({ version: 'v1', auth }));
414
- const response = await client.documents.get({
415
- documentId: options.documentId,
416
- });
417
- const doc = response.data;
418
- // Since tabs API is not available in googleapis@129,
419
- // return a single "default" tab representing the main document body
420
- let wordCount;
421
- if (options.includeWordCount) {
422
- const text = this.extractTextFromBody(doc.body);
423
- wordCount = text.split(/\s+/).filter((word) => word.length > 0).length;
424
- }
425
- const tabs = [
426
- {
427
- tabId: 'default',
428
- title: doc.title || 'Document',
429
- index: 0,
430
- wordCount,
431
- },
432
- ];
564
+ const { doc, flat } = options.includeWordCount
565
+ ? await this.readAllTabs(client, options.documentId)
566
+ : await this.readTabTree(client, options.documentId);
567
+ const tabs = flat.map((tab) => this.toTabInfo(tab, options.includeWordCount
568
+ ? countWords(extractBodyText(tab.tab.documentTab?.body))
569
+ : undefined));
570
+ const data = {
571
+ documentId: doc.documentId || options.documentId,
572
+ title: doc.title || 'Untitled',
573
+ tabs,
574
+ };
433
575
  return {
434
576
  success: true,
435
- data: tabs,
577
+ data,
436
578
  };
437
579
  }
438
580
  catch (error) {
@@ -440,11 +582,557 @@ export class DocsService extends BaseGoogleService {
440
582
  // into a plain error string would skip the host's auth_required handoff.
441
583
  if (isAuthHandoffError(error))
442
584
  throw error;
585
+ if (error instanceof DocsInputError)
586
+ throw error;
443
587
  return {
444
588
  success: false,
445
589
  error: describeApiError(error),
446
590
  };
447
591
  }
448
592
  }
593
+ /**
594
+ * Initialised, scope-checked Docs client for a write.
595
+ */
596
+ async getWriteClient(email) {
597
+ await this.ensureInitialized();
598
+ this.checkInitialized();
599
+ await this.validateScopes(email, [DOCS_SCOPES.FULL]);
600
+ return this.getAuthenticatedClient(email, (auth) => google.docs({ version: 'v1', auth }));
601
+ }
602
+ /**
603
+ * Shared catch for the tab-management and insert methods: auth handoffs and
604
+ * input errors propagate; API failures become `{ success: false }`.
605
+ */
606
+ toFailure(error) {
607
+ // An expired/revoked grant must keep its reconnect signal — folding it
608
+ // into a plain error string would skip the host's auth_required handoff.
609
+ if (isAuthHandoffError(error))
610
+ throw error;
611
+ if (error instanceof DocsInputError)
612
+ throw error;
613
+ return {
614
+ success: false,
615
+ error: describeApiErrorUntrusted(error, DOCS_API_ERROR_SOURCE),
616
+ };
617
+ }
618
+ toTabRef(tab) {
619
+ return { tabId: tab.tabId, title: tab.title, path: tab.path };
620
+ }
621
+ parentRef(flat, tab) {
622
+ const parent = tab.parentTabId !== null ? flat.find((t) => t.tabId === tab.parentTabId) : undefined;
623
+ return parent ? this.toTabRef(parent) : null;
624
+ }
625
+ /**
626
+ * Add a tab (optionally under a parent, at a 0-based position among its new
627
+ * siblings). Reports the tab as the document shows it after the write.
628
+ */
629
+ async addTab(email, options) {
630
+ try {
631
+ const title = requireTabTitle(options.title);
632
+ const client = await this.getWriteClient(email);
633
+ const { flat } = await this.readTabTree(client, options.documentId);
634
+ assertUniqueTitle(flat, title);
635
+ const parent = options.parentTabId !== undefined
636
+ ? resolveTab(flat, options.parentTabId, { allowDefault: true })
637
+ : null;
638
+ const siblingCount = siblingsOf(flat, parent?.tabId ?? null).length;
639
+ assertTabPosition(options.position, siblingCount);
640
+ const response = await client.documents.batchUpdate({
641
+ documentId: options.documentId,
642
+ requestBody: {
643
+ requests: [
644
+ {
645
+ addDocumentTab: {
646
+ tabProperties: {
647
+ title,
648
+ ...(parent ? { parentTabId: parent.tabId } : {}),
649
+ // No index → the API's default placement (expected: end).
650
+ ...(options.position !== undefined ? { index: options.position } : {}),
651
+ },
652
+ },
653
+ },
654
+ ],
655
+ },
656
+ });
657
+ const newTabId = response.data.replies?.[0]?.addDocumentTab?.tabProperties?.tabId;
658
+ if (!newTabId) {
659
+ throw new Error('Docs API did not return the id of the added tab');
660
+ }
661
+ const after = await this.readTabTree(client, options.documentId);
662
+ const created = after.flat.find((tab) => tab.tabId === newTabId);
663
+ if (!created) {
664
+ throw new Error(`Added tab ${newTabId} is missing from the document's tab list`);
665
+ }
666
+ const data = {
667
+ documentId: options.documentId,
668
+ tab: this.toTabInfo(created),
669
+ parent: this.parentRef(after.flat, created),
670
+ changed: true,
671
+ requestedPosition: options.position ?? siblingCount,
672
+ requestedParentTabId: parent?.tabId ?? null,
673
+ };
674
+ return { success: true, data };
675
+ }
676
+ catch (error) {
677
+ return this.toFailure(error);
678
+ }
679
+ }
680
+ /**
681
+ * Rename and/or move a tab. `position` is the 0-based position the tab should
682
+ * end up at among its destination siblings; the API's before-removal index is
683
+ * computed here. Reports the actual title, parent and position after the write.
684
+ */
685
+ async updateTab(email, options) {
686
+ try {
687
+ if (options.title === undefined &&
688
+ options.parentTabId === undefined &&
689
+ options.position === undefined) {
690
+ throw new DocsInputError('Pass at least one of title, parent_tab_id or position.');
691
+ }
692
+ const newTitle = options.title !== undefined ? requireTabTitle(options.title) : undefined;
693
+ const client = await this.getWriteClient(email);
694
+ const { flat } = await this.readTabTree(client, options.documentId);
695
+ const current = resolveTab(flat, options.tabId, { allowDefault: false });
696
+ const titleChanged = newTitle !== undefined && newTitle !== current.title;
697
+ if (titleChanged) {
698
+ assertUniqueTitle(flat, newTitle, current.tabId);
699
+ }
700
+ // Destination parent first; "same parent" is decided by identity, so
701
+ // parent_tab_id equal to the current parent is a reorder, not a re-parent.
702
+ // There is no move to the top level: Google returns 500 when an update
703
+ // clears parentTabId.
704
+ const destParent = options.parentTabId !== undefined
705
+ ? resolveTab(flat, options.parentTabId, { allowDefault: false }).tabId
706
+ : current.parentTabId;
707
+ if (destParent !== null &&
708
+ (destParent === current.tabId ||
709
+ descendantsOf(flat, current.tabId).some((tab) => tab.tabId === destParent))) {
710
+ throw new DocsInputError('A tab cannot be moved under itself or one of its own sub-tabs.');
711
+ }
712
+ const sameParent = destParent === current.parentTabId;
713
+ const destSiblingCount = siblingsOf(flat, destParent).filter((tab) => tab.tabId !== current.tabId).length;
714
+ assertTabPosition(options.position, destSiblingCount);
715
+ const targetPosition = options.position ?? (sameParent ? current.index : destSiblingCount);
716
+ const positionChanged = !sameParent || targetPosition !== current.index;
717
+ if (!titleChanged && !positionChanged) {
718
+ const data = {
719
+ documentId: options.documentId,
720
+ tab: this.toTabInfo(current),
721
+ parent: this.parentRef(flat, current),
722
+ changed: false,
723
+ requestedPosition: targetPosition,
724
+ requestedParentTabId: destParent,
725
+ };
726
+ return { success: true, data };
727
+ }
728
+ const tabProperties = { tabId: current.tabId };
729
+ const fields = [];
730
+ if (titleChanged) {
731
+ tabProperties.title = newTitle;
732
+ fields.push('title');
733
+ }
734
+ if (!sameParent && destParent !== null) {
735
+ tabProperties.parentTabId = destParent;
736
+ fields.push('parentTabId');
737
+ }
738
+ if (positionChanged) {
739
+ tabProperties.index = computeMoveApiIndex({
740
+ sameParent,
741
+ currentIndex: current.index,
742
+ targetPosition,
743
+ });
744
+ fields.push('index');
745
+ }
746
+ await client.documents.batchUpdate({
747
+ documentId: options.documentId,
748
+ requestBody: {
749
+ requests: [
750
+ {
751
+ updateDocumentTabProperties: {
752
+ tabProperties,
753
+ fields: fields.join(','),
754
+ },
755
+ },
756
+ ],
757
+ },
758
+ });
759
+ const after = await this.readTabTree(client, options.documentId);
760
+ const updated = after.flat.find((tab) => tab.tabId === current.tabId);
761
+ if (!updated) {
762
+ throw new Error(`Updated tab ${current.tabId} is missing from the document's tab list`);
763
+ }
764
+ const data = {
765
+ documentId: options.documentId,
766
+ tab: this.toTabInfo(updated),
767
+ parent: this.parentRef(after.flat, updated),
768
+ changed: true,
769
+ requestedPosition: targetPosition,
770
+ requestedParentTabId: destParent,
771
+ };
772
+ return { success: true, data };
773
+ }
774
+ catch (error) {
775
+ return this.toFailure(error);
776
+ }
777
+ }
778
+ /**
779
+ * Delete a tab and, with it, every sub-tab below it. A tab that has sub-tabs
780
+ * is refused before any write unless the caller passes `deleteSubTabs`.
781
+ */
782
+ async deleteTab(email, options) {
783
+ try {
784
+ const client = await this.getWriteClient(email);
785
+ const { flat } = await this.readTabTree(client, options.documentId);
786
+ const target = resolveTab(flat, options.tabId, { allowDefault: false });
787
+ const descendants = descendantsOf(flat, target.tabId);
788
+ if (descendants.length > 0 && options.deleteSubTabs !== true) {
789
+ const count = descendants.length;
790
+ throw new DocsInputError(`Tab "${target.tabId}" has ${count} sub-tab${count !== 1 ? 's' : ''}, which would be deleted with it. Nothing was deleted. ` +
791
+ 'Check with list_workspace_document_tabs that this is the tab you mean, then pass delete_sub_tabs: true to delete it and all its sub-tabs.');
792
+ }
793
+ await client.documents.batchUpdate({
794
+ documentId: options.documentId,
795
+ requestBody: {
796
+ requests: [{ deleteTab: { tabId: target.tabId } }],
797
+ },
798
+ });
799
+ const after = await this.readTabTree(client, options.documentId);
800
+ if (after.flat.some((tab) => tab.tabId === target.tabId)) {
801
+ throw new Error(`Docs API accepted the delete, but tab ${target.tabId} is still in the document`);
802
+ }
803
+ const data = {
804
+ documentId: options.documentId,
805
+ deleted: this.toTabRef(target),
806
+ descendants: descendants.map((tab) => this.toTabRef(tab)),
807
+ };
808
+ return { success: true, data };
809
+ }
810
+ catch (error) {
811
+ return this.toFailure(error);
812
+ }
813
+ }
814
+ /**
815
+ * Insert plain text into one tab next to a unique anchor: right after it,
816
+ * right before it, or at the start of the paragraph that follows it (in the
817
+ * same container). The inserted text takes the paragraph formatting of where
818
+ * it lands (heading, bullet) but its character style is cleared. The text is
819
+ * first normalised to what Docs stores, so the style-clear range never
820
+ * reaches past it into existing text.
821
+ */
822
+ async insertText(email, options) {
823
+ try {
824
+ if (!INSERT_POSITIONS.includes(options.position)) {
825
+ throw new DocsInputError('position must be "after", "before" or "next_paragraph_start".');
826
+ }
827
+ if (options.text.length === 0) {
828
+ throw new DocsInputError('text must not be empty.');
829
+ }
830
+ const { text, removedChars } = normalizeInsertText(options.text);
831
+ if (text.length === 0) {
832
+ throw new DocsInputError('text has nothing Google Docs can store: it holds only control or private-use characters, which Docs removes.');
833
+ }
834
+ // Filling a slot is the usual reason for next_paragraph_start, so the guard is on there by default.
835
+ const expectEmptyParagraph = options.expectEmptyParagraph ?? options.position === 'next_paragraph_start';
836
+ const client = await this.getWriteClient(email);
837
+ const { flat } = await this.readAllTabs(client, options.documentId);
838
+ // No tab_id = the first tab, like append.
839
+ const tab = resolveTab(flat, options.tabId ?? 'default', { allowDefault: true });
840
+ const body = tab.tab.documentTab?.body;
841
+ const paragraphs = flatParagraphs(body);
842
+ const matches = findAnchor(paragraphs, options.anchorText, options.matchCase);
843
+ if (matches.length === 0) {
844
+ throw new DocsInputError(`Anchor text not found in tab "${tab.tabId}". It must be plain text inside one paragraph (smart chips, people and dates can't be part of it); read the tab with tab_id to copy it exactly, leaving out the "• " and "[H1]"-style markers, which are not document text.`);
845
+ }
846
+ if (matches.length > 1) {
847
+ throw new DocsInputError(`Anchor text found ${matches.length} times in this tab; use a longer anchor that appears once.`);
848
+ }
849
+ const match = matches[0];
850
+ const anchorParagraph = paragraphs[match.paragraphIdx];
851
+ let index;
852
+ let target;
853
+ switch (options.position) {
854
+ case 'after':
855
+ index = anchorParagraph.startIndex + match.offset + options.anchorText.length;
856
+ target = anchorParagraph;
857
+ break;
858
+ case 'before':
859
+ index = anchorParagraph.startIndex + match.offset;
860
+ target = anchorParagraph;
861
+ break;
862
+ case 'next_paragraph_start':
863
+ target = nextParagraphInContainer(body, paragraphs, match.paragraphIdx);
864
+ index = target.startIndex;
865
+ break;
866
+ }
867
+ const targetText = paragraphSearchText(target.paragraph);
868
+ const wasEmpty = targetText === '' || targetText === '\n';
869
+ const bulleted = target.paragraph.bullet != null;
870
+ const namedStyleType = target.paragraph.paragraphStyle?.namedStyleType ?? 'NORMAL_TEXT';
871
+ if (expectEmptyParagraph && !wasEmpty) {
872
+ const visibleChars = targetText.endsWith('\n') ? targetText.length - 1 : targetText.length;
873
+ const guardSource = options.expectEmptyParagraph === true
874
+ ? 'expect_empty_paragraph is set'
875
+ : 'expect_empty_paragraph is on (the default for "next_paragraph_start")';
876
+ throw new DocsInputError(`${guardSource}, but the paragraph the text would land in is not empty: it holds ${visibleChars} character(s), ${bulleted ? 'bulleted' : 'not bulleted'}, style ${namedStyleType}. Nothing was inserted. ` +
877
+ 'Anchor on the line directly above the empty slot (if an instruction line sits between the heading and the slot, anchor on that line), ' +
878
+ 'or pass expect_empty_paragraph: false to insert at the start of this paragraph anyway.');
879
+ }
880
+ await client.documents.batchUpdate({
881
+ documentId: options.documentId,
882
+ requestBody: {
883
+ requests: [
884
+ { insertText: { location: { index, tabId: tab.tabId }, text } },
885
+ {
886
+ // Plain text: keep the paragraph's formatting, drop neighbouring run styles.
887
+ updateTextStyle: {
888
+ range: { startIndex: index, endIndex: index + text.length, tabId: tab.tabId },
889
+ textStyle: {},
890
+ fields: ALL_TEXT_KEYS,
891
+ },
892
+ },
893
+ ],
894
+ },
895
+ });
896
+ const data = {
897
+ documentId: options.documentId,
898
+ tab: this.toTabRef(tab),
899
+ position: options.position,
900
+ index,
901
+ insertedChars: text.length,
902
+ removedChars,
903
+ newParagraphs: text.split('\n').length - 1,
904
+ targetParagraph: { wasEmpty, namedStyleType, bulleted },
905
+ };
906
+ return { success: true, data };
907
+ }
908
+ catch (error) {
909
+ return this.toFailure(error);
910
+ }
911
+ }
912
+ /**
913
+ * Copy one tab's content into another tab of the same document: into a new
914
+ * tab (`newTabTitle`) or into an existing tab, which is cleared first
915
+ * (`targetTabId` + `overwriteExisting`). Every input check, the source read
916
+ * and the per-chip access checks happen before the first write. On a failure
917
+ * after that, a tab this call created is deleted again (best effort); an
918
+ * existing target is left as it is and the error says so. A copy that
919
+ * completes but fails verification is kept, in either mode, and returned
920
+ * with its report (the handler marks it as an error).
921
+ */
922
+ async copyTab(email, options, checkChip) {
923
+ const started = Date.now();
924
+ let client;
925
+ let createdTabId;
926
+ let addTabAttempted = false;
927
+ let destination;
928
+ try {
929
+ const hasTarget = options.targetTabId !== undefined;
930
+ const hasNewTitle = options.newTabTitle !== undefined;
931
+ if (hasTarget === hasNewTitle) {
932
+ throw new DocsInputError('Pass exactly one of target_tab_id (copy into an existing tab) or new_tab_title (copy into a new tab).');
933
+ }
934
+ if (hasTarget && (options.newTabParentId !== undefined || options.newTabPosition !== undefined)) {
935
+ throw new DocsInputError('new_tab_parent_id and new_tab_position only apply with new_tab_title.');
936
+ }
937
+ if (hasTarget && options.overwriteExisting !== true) {
938
+ throw new DocsInputError('Copying into an existing tab clears it first. Pass overwrite_existing: true to confirm, or use new_tab_title to copy into a new tab.');
939
+ }
940
+ const newTitle = hasNewTitle ? requireTabTitle(options.newTabTitle) : undefined;
941
+ client = await this.getWriteClient(email);
942
+ const docsClient = client;
943
+ const { flat } = await this.readTabTree(docsClient, options.documentId);
944
+ const source = resolveTab(flat, options.sourceTabId, { allowDefault: true });
945
+ if (options.targetTabId !== undefined) {
946
+ const target = resolveTab(flat, options.targetTabId, { allowDefault: false });
947
+ if (target.tabId === source.tabId) {
948
+ throw new DocsInputError('source_tab_id and target_tab_id are the same tab; pick a different target.');
949
+ }
950
+ destination = { kind: 'overwrite', tabId: target.tabId };
951
+ }
952
+ else {
953
+ try {
954
+ assertUniqueTitle(flat, newTitle);
955
+ }
956
+ catch (error) {
957
+ if (error instanceof DocsInputError) {
958
+ throw new DocsInputError(`${error.message} If an earlier copy attempt failed, a half-written tab with this title may remain — check list_workspace_document_tabs.`);
959
+ }
960
+ throw error;
961
+ }
962
+ const parent = options.newTabParentId !== undefined
963
+ ? resolveTab(flat, options.newTabParentId, { allowDefault: true })
964
+ : null;
965
+ assertTabPosition(options.newTabPosition, siblingsOf(flat, parent?.tabId ?? null).length);
966
+ destination = {
967
+ kind: 'new',
968
+ title: newTitle,
969
+ parentTabId: parent?.tabId ?? null,
970
+ position: options.newTabPosition,
971
+ };
972
+ }
973
+ const dest = destination;
974
+ let lastFlat = flat;
975
+ const getTab = async (tabId) => {
976
+ const read = await this.readAllTabs(docsClient, options.documentId);
977
+ lastFlat = read.flat;
978
+ const found = read.flat.find((tab) => tab.tabId === tabId);
979
+ if (!found)
980
+ throw new Error(`Tab ${tabId} is missing from the document`);
981
+ return found.tab;
982
+ };
983
+ const result = await copyTabContent({
984
+ getSourceTab: async () => {
985
+ // Committed content only: pending suggestions are left out (PREVIEW_WITHOUT_SUGGESTIONS).
986
+ const response = await docsClient.documents.get({
987
+ documentId: options.documentId,
988
+ includeTabsContent: true,
989
+ suggestionsViewMode: 'PREVIEW_WITHOUT_SUGGESTIONS',
990
+ });
991
+ const found = flattenTabs(requireTabs(response.data)).find((tab) => tab.tabId === source.tabId);
992
+ if (!found)
993
+ throw new Error(`Tab ${source.tabId} is missing from the document`);
994
+ return found.tab;
995
+ },
996
+ getTab,
997
+ batchUpdate: async (requests) => {
998
+ // insertRichLink / updateNamedStyle are missing from the typings, not from the API.
999
+ await docsClient.documents.batchUpdate({
1000
+ documentId: options.documentId,
1001
+ requestBody: { requests: requests },
1002
+ });
1003
+ },
1004
+ checkChip,
1005
+ prepareTarget: async () => {
1006
+ if (dest.kind === 'overwrite')
1007
+ return dest.tabId;
1008
+ addTabAttempted = true;
1009
+ const response = await docsClient.documents.batchUpdate({
1010
+ documentId: options.documentId,
1011
+ requestBody: {
1012
+ requests: [
1013
+ {
1014
+ addDocumentTab: {
1015
+ tabProperties: {
1016
+ title: dest.title,
1017
+ ...(dest.parentTabId !== null ? { parentTabId: dest.parentTabId } : {}),
1018
+ ...(dest.position !== undefined ? { index: dest.position } : {}),
1019
+ },
1020
+ },
1021
+ },
1022
+ ],
1023
+ },
1024
+ });
1025
+ const tabId = response.data.replies?.[0]?.addDocumentTab?.tabProperties?.tabId;
1026
+ if (!tabId)
1027
+ throw new Error('Docs API did not return the id of the added tab');
1028
+ createdTabId = tabId;
1029
+ return tabId;
1030
+ },
1031
+ });
1032
+ const target = lastFlat.find((tab) => tab.tabId === result.targetTabId);
1033
+ const data = {
1034
+ documentId: options.documentId,
1035
+ mode: dest.kind,
1036
+ source: this.toTabRef(source),
1037
+ target: target
1038
+ ? this.toTabRef(target)
1039
+ : { tabId: result.targetTabId, title: '', path: result.targetTabId },
1040
+ requests: result.requests,
1041
+ rounds: result.rounds,
1042
+ durationMs: Date.now() - started,
1043
+ chipsCopied: result.chipsCopied,
1044
+ chipFallbacks: result.chipFallbacks,
1045
+ convertedToText: result.convertedToText,
1046
+ namedStylesCopied: result.namedStylesCopied,
1047
+ notCopied: result.notCopied,
1048
+ notes: result.notes,
1049
+ verification: result.verification,
1050
+ };
1051
+ return { success: true, data };
1052
+ }
1053
+ catch (error) {
1054
+ if (!(error instanceof TabCopyError)) {
1055
+ return this.toFailure(error);
1056
+ }
1057
+ const cause = error.cause;
1058
+ let outcome = '';
1059
+ if (createdTabId && client) {
1060
+ const cleaned = await this.deleteHalfWrittenTab(client, options.documentId, createdTabId);
1061
+ outcome = cleaned
1062
+ ? ` The new tab ${createdTabId} was deleted again, so nothing changed.`
1063
+ : ` The new tab ${createdTabId} could not be deleted and may be partly written; delete it with delete_workspace_document_tab before trying again.`;
1064
+ }
1065
+ else if (destination?.kind === 'new' && addTabAttempted && !hadHttpErrorResponse(cause)) {
1066
+ outcome =
1067
+ ' A new tab may have been created before the error; check list_workspace_document_tabs and delete it if it is there.';
1068
+ }
1069
+ else if (destination?.kind === 'overwrite' && error.wroteContent) {
1070
+ outcome = ` Target tab ${destination.tabId} was cleared and may be partly written; restore it from the document's version history.`;
1071
+ }
1072
+ else if (destination?.kind === 'overwrite' && error.attemptedWrite && !hadHttpErrorResponse(cause)) {
1073
+ outcome = ` Target tab ${destination.tabId} may have been cleared or partly written; check it and restore it from the document's version history if needed.`;
1074
+ }
1075
+ else {
1076
+ outcome = ' Nothing was written to the document.';
1077
+ }
1078
+ // Auth handoffs keep their reconnect signal (after the cleanup attempt).
1079
+ if (isAuthHandoffError(cause))
1080
+ throw cause;
1081
+ if (cause instanceof DocsInputError)
1082
+ throw cause;
1083
+ return {
1084
+ success: false,
1085
+ error: `Copy failed during "${error.phase}": ${describeApiErrorUntrusted(cause, DOCS_API_ERROR_SOURCE)}.${outcome}`,
1086
+ };
1087
+ }
1088
+ }
1089
+ /** Best-effort removal of a tab a failed copy created. True when it is gone. */
1090
+ async deleteHalfWrittenTab(client, documentId, tabId) {
1091
+ try {
1092
+ await client.documents.batchUpdate({
1093
+ documentId,
1094
+ requestBody: { requests: [{ deleteTab: { tabId } }] },
1095
+ });
1096
+ return true;
1097
+ }
1098
+ catch {
1099
+ // Reported to the caller in the copy's error message (the tab may remain).
1100
+ return false;
1101
+ }
1102
+ }
1103
+ }
1104
+ /** Source label for Google error text in tab-operation and copy failures. */
1105
+ const DOCS_API_ERROR_SOURCE = 'google-workspace:docs:api-error';
1106
+ /**
1107
+ * True when the error carries an HTTP client-error status (4xx). A batchUpdate
1108
+ * rejected with one applied nothing (batches are all-or-nothing). Without one
1109
+ * (a 5xx, timeout, dropped connection or missing reply field) the write may
1110
+ * have landed.
1111
+ */
1112
+ function hadHttpErrorResponse(cause) {
1113
+ if (typeof cause !== 'object' || cause === null)
1114
+ return false;
1115
+ const candidate = cause;
1116
+ return [candidate.response?.status, candidate.status, candidate.code].some((value) => typeof value === 'number' && value >= 400 && value < 500);
1117
+ }
1118
+ /** The tab's documentTab with `namedRanges` turned from a name-keyed map into a list (see TabJsonDocumentTab). */
1119
+ function withNamedRangeList(documentTab) {
1120
+ const { namedRanges, ...rest } = documentTab;
1121
+ return namedRanges ? { ...rest, namedRanges: Object.values(namedRanges) } : rest;
1122
+ }
1123
+ const INSERT_POSITIONS = ['after', 'before', 'next_paragraph_start'];
1124
+ function requireTabTitle(title) {
1125
+ const trimmed = title.trim();
1126
+ if (trimmed.length === 0) {
1127
+ throw new DocsInputError('title must not be empty.');
1128
+ }
1129
+ return trimmed;
1130
+ }
1131
+ function assertTabPosition(position, max) {
1132
+ if (position === undefined)
1133
+ return;
1134
+ if (!Number.isInteger(position) || position < 0 || position > max) {
1135
+ throw new DocsInputError(`position must be a whole number from 0 to ${max} (0 = first; the numbers in list outputs start at 1).`);
1136
+ }
449
1137
  }
450
1138
  //# sourceMappingURL=service.js.map