@mutallip/google-workspace-mcp 0.0.0-stage → 2.8.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 (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +353 -2
  3. package/README.npm.md +28 -0
  4. package/auth/__init__.py +1 -0
  5. package/auth/auth_info_middleware.py +419 -0
  6. package/auth/client_secrets.py +76 -0
  7. package/auth/credential_store.py +598 -0
  8. package/auth/external_oauth_provider.py +369 -0
  9. package/auth/gateway_identity.py +164 -0
  10. package/auth/google_auth.py +1550 -0
  11. package/auth/google_oauth_provider.py +20 -0
  12. package/auth/mcp_session_middleware.py +95 -0
  13. package/auth/oauth21_session_store.py +1332 -0
  14. package/auth/oauth_callback_server.py +466 -0
  15. package/auth/oauth_config.py +693 -0
  16. package/auth/oauth_proxy_config.py +122 -0
  17. package/auth/oauth_responses.py +230 -0
  18. package/auth/oauth_types.py +92 -0
  19. package/auth/permissions.py +330 -0
  20. package/auth/port_resolver.py +153 -0
  21. package/auth/request_identity.py +89 -0
  22. package/auth/scopes.py +369 -0
  23. package/auth/service_decorator.py +1109 -0
  24. package/bin/google-workspace-mcp.cjs +123 -0
  25. package/core/__init__.py +1 -0
  26. package/core/api_enablement.py +108 -0
  27. package/core/attachment_storage.py +496 -0
  28. package/core/camel_case_middleware.py +98 -0
  29. package/core/cli.py +161 -0
  30. package/core/comments.py +609 -0
  31. package/core/config.py +57 -0
  32. package/core/context.py +43 -0
  33. package/core/file_limits.py +632 -0
  34. package/core/gcs_attachment_storage.py +253 -0
  35. package/core/http_utils.py +339 -0
  36. package/core/log_formatter.py +270 -0
  37. package/core/portable_schema_middleware.py +67 -0
  38. package/core/server.py +1192 -0
  39. package/core/startup_ui.py +239 -0
  40. package/core/storage.py +23 -0
  41. package/core/telemetry.py +194 -0
  42. package/core/tool_descriptions.py +19 -0
  43. package/core/tool_registry.py +311 -0
  44. package/core/tool_tier_loader.py +197 -0
  45. package/core/tool_tiers.yaml +179 -0
  46. package/core/toolset_header_middleware.py +67 -0
  47. package/core/utils.py +1537 -0
  48. package/core/valkey_storage.py +271 -0
  49. package/core/warning_filters.py +19 -0
  50. package/fastmcp_server.py +198 -0
  51. package/gappsscript/README.md +512 -0
  52. package/gappsscript/TESTING.md +254 -0
  53. package/gappsscript/__init__.py +0 -0
  54. package/gappsscript/apps_script_tools.py +1940 -0
  55. package/gcalendar/__init__.py +1 -0
  56. package/gcalendar/calendar_helpers.py +1323 -0
  57. package/gcalendar/calendar_tools.py +2252 -0
  58. package/gchat/__init__.py +7 -0
  59. package/gchat/chat_helpers.py +410 -0
  60. package/gchat/chat_tools.py +798 -0
  61. package/gcontacts/__init__.py +1 -0
  62. package/gcontacts/contacts_helpers.py +765 -0
  63. package/gcontacts/contacts_tools.py +1685 -0
  64. package/gdocs/__init__.py +0 -0
  65. package/gdocs/docs_anchors.py +163 -0
  66. package/gdocs/docs_comments.py +89 -0
  67. package/gdocs/docs_helpers.py +2201 -0
  68. package/gdocs/docs_links.py +87 -0
  69. package/gdocs/docs_markdown.py +828 -0
  70. package/gdocs/docs_markdown_writer.py +592 -0
  71. package/gdocs/docs_plain_text.py +463 -0
  72. package/gdocs/docs_structure.py +621 -0
  73. package/gdocs/docs_tables.py +425 -0
  74. package/gdocs/docs_tools.py +3300 -0
  75. package/gdocs/managers/__init__.py +18 -0
  76. package/gdocs/managers/batch_operation_manager.py +1694 -0
  77. package/gdocs/managers/header_footer_manager.py +526 -0
  78. package/gdocs/managers/table_operation_manager.py +488 -0
  79. package/gdocs/managers/validation_manager.py +1504 -0
  80. package/gdocs/operation_schemas.py +594 -0
  81. package/gdrive/__init__.py +0 -0
  82. package/gdrive/drive_helpers.py +1738 -0
  83. package/gdrive/drive_tools.py +3085 -0
  84. package/gforms/__init__.py +3 -0
  85. package/gforms/forms_tools.py +575 -0
  86. package/gmail/__init__.py +1 -0
  87. package/gmail/gmail_helpers.py +2107 -0
  88. package/gmail/gmail_tools.py +4895 -0
  89. package/gmail/gmail_web_mime.py +441 -0
  90. package/gsearch/__init__.py +0 -0
  91. package/gsearch/search_tools.py +253 -0
  92. package/gsheets/__init__.py +31 -0
  93. package/gsheets/sheets_helpers.py +2236 -0
  94. package/gsheets/sheets_tools.py +3280 -0
  95. package/gslides/__init__.py +0 -0
  96. package/gslides/slides_digest.py +390 -0
  97. package/gslides/slides_helpers.py +392 -0
  98. package/gslides/slides_markup.py +770 -0
  99. package/gslides/slides_tools.py +376 -0
  100. package/gtasks/__init__.py +5 -0
  101. package/gtasks/tasks_tools.py +936 -0
  102. package/main.py +1170 -0
  103. package/package.json +43 -4
  104. package/pyproject.toml +173 -0
  105. package/uv.lock +2504 -0
@@ -0,0 +1,2201 @@
1
+ """
2
+ Google Docs Helper Functions
3
+
4
+ This module provides utility functions for common Google Docs operations
5
+ to simplify the implementation of document editing tools.
6
+ """
7
+
8
+ import logging
9
+ from datetime import datetime, timezone as dt_timezone
10
+ from typing import Dict, Any, Optional, List
11
+ from zoneinfo import ZoneInfo
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ VALID_NAMED_STYLE_TYPES = (
16
+ "NORMAL_TEXT",
17
+ "TITLE",
18
+ "SUBTITLE",
19
+ "HEADING_1",
20
+ "HEADING_2",
21
+ "HEADING_3",
22
+ "HEADING_4",
23
+ "HEADING_5",
24
+ "HEADING_6",
25
+ )
26
+
27
+ VALID_SUGGESTIONS_VIEW_MODES = (
28
+ "DEFAULT_FOR_CURRENT_ACCESS",
29
+ "SUGGESTIONS_INLINE",
30
+ "PREVIEW_SUGGESTIONS_ACCEPTED",
31
+ "PREVIEW_WITHOUT_SUGGESTIONS",
32
+ )
33
+
34
+ VALID_WRITE_MODES = (
35
+ "EDIT",
36
+ "SUGGEST",
37
+ )
38
+
39
+ VALID_TEXT_BASELINE_OFFSETS = (
40
+ "NONE",
41
+ "SUPERSCRIPT",
42
+ "SUBSCRIPT",
43
+ )
44
+
45
+ VALID_PARAGRAPH_DIRECTIONS = (
46
+ "LEFT_TO_RIGHT",
47
+ "RIGHT_TO_LEFT",
48
+ )
49
+
50
+ VALID_PARAGRAPH_SPACING_MODES = (
51
+ "NEVER_COLLAPSE",
52
+ "COLLAPSE_LISTS",
53
+ )
54
+
55
+ VALID_DASH_STYLES = (
56
+ "SOLID",
57
+ "DOT",
58
+ "DASH",
59
+ )
60
+
61
+ # Border edge name -> ParagraphStyle/TableCellStyle field. Paragraphs additionally
62
+ # support "between"; table cells do not.
63
+ PARAGRAPH_BORDER_EDGE_MAP = {
64
+ "top": "borderTop",
65
+ "bottom": "borderBottom",
66
+ "left": "borderLeft",
67
+ "right": "borderRight",
68
+ "between": "borderBetween",
69
+ }
70
+
71
+ TABLE_BORDER_EDGE_MAP = {
72
+ "top": "borderTop",
73
+ "bottom": "borderBottom",
74
+ "left": "borderLeft",
75
+ "right": "borderRight",
76
+ }
77
+
78
+ VALID_SECTION_TYPES = (
79
+ "CONTINUOUS",
80
+ "NEXT_PAGE",
81
+ )
82
+
83
+ VALID_CONTENT_DIRECTIONS = (
84
+ "LEFT_TO_RIGHT",
85
+ "RIGHT_TO_LEFT",
86
+ )
87
+
88
+ VALID_COLUMN_SEPARATOR_STYLES = (
89
+ "NONE",
90
+ "BETWEEN_EACH_COLUMN",
91
+ )
92
+
93
+ VALID_DOCUMENT_MODES = (
94
+ "PAGES",
95
+ "PAGELESS",
96
+ )
97
+
98
+ VALID_BULLET_PRESETS = (
99
+ "BULLET_DISC_CIRCLE_SQUARE",
100
+ "BULLET_DIAMONDX_ARROW3D_SQUARE",
101
+ "BULLET_CHECKBOX",
102
+ "BULLET_ARROW_DIAMOND_DISC",
103
+ "BULLET_STAR_CIRCLE_SQUARE",
104
+ "BULLET_ARROW3D_CIRCLE_SQUARE",
105
+ "BULLET_LEFTTRIANGLE_DIAMOND_DISC",
106
+ "BULLET_DIAMONDX_HOLLOWDIAMOND_SQUARE",
107
+ "BULLET_DIAMOND_CIRCLE_SQUARE",
108
+ "NUMBERED_DECIMAL_ALPHA_ROMAN",
109
+ "NUMBERED_DECIMAL_ALPHA_ROMAN_PARENS",
110
+ "NUMBERED_DECIMAL_NESTED",
111
+ "NUMBERED_UPPERALPHA_ALPHA_ROMAN",
112
+ "NUMBERED_UPPERROMAN_UPPERALPHA_DECIMAL",
113
+ "NUMBERED_ZERODECIMAL_ALPHA_ROMAN",
114
+ )
115
+
116
+
117
+ def validate_suggestions_view_mode(suggestions_view_mode: str) -> Optional[str]:
118
+ """Return an error message when suggestions_view_mode is invalid."""
119
+ if suggestions_view_mode in VALID_SUGGESTIONS_VIEW_MODES:
120
+ return None
121
+
122
+ return (
123
+ "Error: suggestions_view_mode must be one of "
124
+ f"{', '.join(VALID_SUGGESTIONS_VIEW_MODES)}, got '{suggestions_view_mode}'"
125
+ )
126
+
127
+
128
+ def validate_write_mode(write_mode: str) -> Optional[str]:
129
+ """Return an error message when write_mode is invalid."""
130
+ if write_mode in VALID_WRITE_MODES:
131
+ return None
132
+
133
+ return (
134
+ "Error: write_mode must be one of "
135
+ f"{', '.join(VALID_WRITE_MODES)}, got '{write_mode}'"
136
+ )
137
+
138
+
139
+ def build_batch_update_body(
140
+ requests: List[Dict[str, Any]], write_mode: str = "EDIT"
141
+ ) -> Dict[str, Any]:
142
+ """Build a documents.batchUpdate body; SUGGEST records requests as suggestions."""
143
+ body: Dict[str, Any] = {"requests": requests}
144
+ if write_mode == "SUGGEST":
145
+ body["writeControl"] = {"writeMode": "SUGGEST"}
146
+ return body
147
+
148
+
149
+ def suggestion_save_error(result: Dict[str, Any], write_mode: str) -> Optional[str]:
150
+ """Return an error when Docs reports a SUGGEST batch failed to save."""
151
+ if write_mode != "SUGGEST":
152
+ return None
153
+ if result.get("commentUpdateState") != "ALL_FAILED_UNKNOWN_REASON":
154
+ return None
155
+
156
+ return (
157
+ "Google Docs did not save these changes as suggestions "
158
+ "(commentUpdateState=ALL_FAILED_UNKNOWN_REASON). The document may have "
159
+ "been edited directly; check its version history before retrying, since "
160
+ "retrying could duplicate the change."
161
+ )
162
+
163
+
164
+ def _build_dimension(value: float, unit: str = "PT") -> Dict[str, Any]:
165
+ """Build a Google Docs Dimension object."""
166
+ return {"magnitude": value, "unit": unit}
167
+
168
+
169
+ def _build_optional_color(color: Optional[str], param_name: str) -> Dict[str, Any]:
170
+ """Build a Google Docs OptionalColor object."""
171
+ rgb = _normalize_color(color, param_name)
172
+ return {"color": {"rgbColor": rgb}}
173
+
174
+
175
+ def _build_location(
176
+ index: Optional[int] = None,
177
+ tab_id: Optional[str] = None,
178
+ segment_id: Optional[str] = None,
179
+ end_of_segment: bool = False,
180
+ ) -> Dict[str, Any]:
181
+ """Build a location or endOfSegmentLocation object."""
182
+ if end_of_segment:
183
+ location: Dict[str, Any] = {}
184
+ if segment_id:
185
+ location["segmentId"] = segment_id
186
+ if tab_id:
187
+ location["tabId"] = tab_id
188
+ return {"endOfSegmentLocation": location}
189
+
190
+ if index is None:
191
+ raise ValueError("index is required unless end_of_segment=True")
192
+
193
+ location = {"index": index}
194
+ if segment_id:
195
+ location["segmentId"] = segment_id
196
+ if tab_id:
197
+ location["tabId"] = tab_id
198
+ return {"location": location}
199
+
200
+
201
+ def _build_range(
202
+ start_index: int,
203
+ end_index: int,
204
+ tab_id: Optional[str] = None,
205
+ segment_id: Optional[str] = None,
206
+ ) -> Dict[str, Any]:
207
+ """Build a Google Docs Range object."""
208
+ range_obj = {"startIndex": start_index, "endIndex": end_index}
209
+ if segment_id:
210
+ range_obj["segmentId"] = segment_id
211
+ if tab_id:
212
+ range_obj["tabId"] = tab_id
213
+ return range_obj
214
+
215
+
216
+ def _normalize_body_start_index(
217
+ start_index: int,
218
+ tab_id: Optional[str] = None,
219
+ segment_id: Optional[str] = None,
220
+ ) -> int:
221
+ """
222
+ Normalize a start index for the main document body.
223
+
224
+ The Docs API reserves body index 0 for the leading section break. A few
225
+ public tools accept start_index=0 as a convenience alias for the first
226
+ writable body position, so normalize that here before building requests.
227
+ """
228
+ if start_index == 0 and tab_id is None and segment_id is None:
229
+ return 1
230
+ return start_index
231
+
232
+
233
+ def _build_tabs_criteria(tab_id: Optional[str]) -> Optional[Dict[str, Any]]:
234
+ """Build Docs tabsCriteria for operations that support tab-scoped selection."""
235
+ if not tab_id:
236
+ return None
237
+ return {"tabIds": [tab_id]}
238
+
239
+
240
+ def _normalize_color(
241
+ color: Optional[str], param_name: str
242
+ ) -> Optional[Dict[str, float]]:
243
+ """
244
+ Normalize a user-supplied color into Docs API rgbColor format.
245
+
246
+ Supports only hex strings in the form "#RRGGBB".
247
+ """
248
+ if color is None:
249
+ return None
250
+
251
+ if not isinstance(color, str):
252
+ raise ValueError(f"{param_name} must be a hex string like '#RRGGBB'")
253
+
254
+ if len(color) != 7 or not color.startswith("#"):
255
+ raise ValueError(f"{param_name} must be a hex string like '#RRGGBB'")
256
+
257
+ hex_color = color[1:]
258
+ if any(c not in "0123456789abcdefABCDEF" for c in hex_color):
259
+ raise ValueError(f"{param_name} must be a hex string like '#RRGGBB'")
260
+
261
+ r = int(hex_color[0:2], 16) / 255
262
+ g = int(hex_color[2:4], 16) / 255
263
+ b = int(hex_color[4:6], 16) / 255
264
+ return {"red": r, "green": g, "blue": b}
265
+
266
+
267
+ def build_text_style(
268
+ bold: bool = None,
269
+ italic: bool = None,
270
+ underline: bool = None,
271
+ strikethrough: bool = None,
272
+ font_size: float = None,
273
+ font_family: str = None,
274
+ font_weight: int = None,
275
+ text_color: str = None,
276
+ background_color: str = None,
277
+ link_url: str = None,
278
+ clear_link: bool = None,
279
+ baseline_offset: str = None,
280
+ small_caps: bool = None,
281
+ ) -> tuple[Dict[str, Any], list[str]]:
282
+ """
283
+ Build text style object for Google Docs API requests.
284
+
285
+ Args:
286
+ bold: Whether text should be bold
287
+ italic: Whether text should be italic
288
+ underline: Whether text should be underlined
289
+ strikethrough: Whether text should be struck through
290
+ font_size: Font size in points
291
+ font_family: Font family name
292
+ font_weight: Font weight (100-900 in steps of 100)
293
+ text_color: Text color as hex string "#RRGGBB"
294
+ background_color: Background (highlight) color as hex string "#RRGGBB"
295
+ link_url: Hyperlink URL (http/https)
296
+ clear_link: Remove hyperlink from the range when True
297
+ baseline_offset: One of NONE, SUPERSCRIPT, SUBSCRIPT
298
+ small_caps: Whether text should use small caps
299
+
300
+ Returns:
301
+ Tuple of (text_style_dict, list_of_field_names)
302
+ """
303
+ text_style = {}
304
+ fields = []
305
+
306
+ if bold is not None:
307
+ text_style["bold"] = bold
308
+ fields.append("bold")
309
+
310
+ if italic is not None:
311
+ text_style["italic"] = italic
312
+ fields.append("italic")
313
+
314
+ if underline is not None:
315
+ text_style["underline"] = underline
316
+ fields.append("underline")
317
+
318
+ if strikethrough is not None:
319
+ text_style["strikethrough"] = strikethrough
320
+ fields.append("strikethrough")
321
+
322
+ if font_size is not None:
323
+ text_style["fontSize"] = {"magnitude": font_size, "unit": "PT"}
324
+ fields.append("fontSize")
325
+
326
+ if font_family is not None or font_weight is not None:
327
+ weighted_font_family: Dict[str, Any] = {}
328
+ if font_family is not None:
329
+ weighted_font_family["fontFamily"] = font_family
330
+ if font_weight is not None:
331
+ weighted_font_family["weight"] = font_weight
332
+ text_style["weightedFontFamily"] = weighted_font_family
333
+ fields.append("weightedFontFamily")
334
+
335
+ if text_color is not None:
336
+ rgb = _normalize_color(text_color, "text_color")
337
+ text_style["foregroundColor"] = {"color": {"rgbColor": rgb}}
338
+ fields.append("foregroundColor")
339
+
340
+ if background_color is not None:
341
+ rgb = _normalize_color(background_color, "background_color")
342
+ text_style["backgroundColor"] = {"color": {"rgbColor": rgb}}
343
+ fields.append("backgroundColor")
344
+
345
+ if link_url is not None and clear_link:
346
+ raise ValueError("link_url and clear_link cannot both be provided")
347
+
348
+ if link_url is not None:
349
+ text_style["link"] = {"url": link_url}
350
+ fields.append("link")
351
+ elif clear_link is True:
352
+ fields.append("link")
353
+
354
+ if baseline_offset is not None:
355
+ baseline_offset_upper = baseline_offset.upper()
356
+ if baseline_offset_upper not in VALID_TEXT_BASELINE_OFFSETS:
357
+ raise ValueError(
358
+ f"baseline_offset must be one of: {', '.join(VALID_TEXT_BASELINE_OFFSETS)}"
359
+ )
360
+ text_style["baselineOffset"] = baseline_offset_upper
361
+ fields.append("baselineOffset")
362
+
363
+ if small_caps is not None:
364
+ text_style["smallCaps"] = small_caps
365
+ fields.append("smallCaps")
366
+
367
+ return text_style, fields
368
+
369
+
370
+ def build_paragraph_style(
371
+ heading_level: int = None,
372
+ alignment: str = None,
373
+ line_spacing: float = None,
374
+ indent_first_line: float = None,
375
+ indent_start: float = None,
376
+ indent_end: float = None,
377
+ space_above: float = None,
378
+ space_below: float = None,
379
+ named_style_type: Optional[str] = None,
380
+ direction: Optional[str] = None,
381
+ keep_lines_together: Optional[bool] = None,
382
+ keep_with_next: Optional[bool] = None,
383
+ avoid_widow_and_orphan: Optional[bool] = None,
384
+ page_break_before: Optional[bool] = None,
385
+ spacing_mode: Optional[str] = None,
386
+ shading_color: Optional[str] = None,
387
+ border_edges: Optional[List[str]] = None,
388
+ border_color: Optional[str] = None,
389
+ border_width: Optional[float] = None,
390
+ border_padding: Optional[float] = None,
391
+ border_dash: Optional[str] = None,
392
+ ) -> tuple[Dict[str, Any], list[str]]:
393
+ """
394
+ Build paragraph style object for Google Docs API requests.
395
+
396
+ Args:
397
+ heading_level: Heading level 0-6 (0 = NORMAL_TEXT, 1-6 = HEADING_N)
398
+ alignment: Text alignment - 'START', 'CENTER', 'END', or 'JUSTIFIED'
399
+ line_spacing: Line spacing multiplier (1.0 = single, 2.0 = double)
400
+ indent_first_line: First line indent in points
401
+ indent_start: Left/start indent in points
402
+ indent_end: Right/end indent in points
403
+ space_above: Space above paragraph in points
404
+ space_below: Space below paragraph in points
405
+ named_style_type: Direct named style (TITLE, SUBTITLE, HEADING_1..6, NORMAL_TEXT).
406
+ Takes precedence over heading_level when both are provided.
407
+ direction: Paragraph content direction - LEFT_TO_RIGHT or RIGHT_TO_LEFT
408
+ keep_lines_together: Keep all lines of the paragraph together if possible
409
+ keep_with_next: Keep paragraph with the next paragraph if possible
410
+ avoid_widow_and_orphan: Avoid widows/orphans for the paragraph
411
+ page_break_before: Always start paragraph on a new page
412
+ spacing_mode: Paragraph spacing mode - NEVER_COLLAPSE or COLLAPSE_LISTS
413
+ shading_color: Paragraph shading/background color as hex string "#RRGGBB"
414
+ border_edges: Border edges to update; omit for all four outer edges
415
+ border_color: Border color as hex string "#RRGGBB"
416
+ border_width: Border width in points
417
+ border_padding: Border padding in points
418
+ border_dash: Border dash style (SOLID, DOT, or DASH)
419
+
420
+ Returns:
421
+ Tuple of (paragraph_style_dict, list_of_field_names)
422
+ """
423
+ paragraph_style = {}
424
+ fields = []
425
+
426
+ if border_edges is not None and not border_edges:
427
+ raise ValueError("border_edges must contain at least one edge")
428
+
429
+ if named_style_type is not None:
430
+ if named_style_type not in VALID_NAMED_STYLE_TYPES:
431
+ raise ValueError(
432
+ f"Invalid named_style_type '{named_style_type}'. "
433
+ f"Must be one of: {', '.join(VALID_NAMED_STYLE_TYPES)}"
434
+ )
435
+ paragraph_style["namedStyleType"] = named_style_type
436
+ fields.append("namedStyleType")
437
+ elif heading_level is not None:
438
+ if heading_level < 0 or heading_level > 6:
439
+ raise ValueError("heading_level must be between 0 (normal text) and 6")
440
+ if heading_level == 0:
441
+ paragraph_style["namedStyleType"] = "NORMAL_TEXT"
442
+ else:
443
+ paragraph_style["namedStyleType"] = f"HEADING_{heading_level}"
444
+ fields.append("namedStyleType")
445
+
446
+ if alignment is not None:
447
+ valid_alignments = ["START", "CENTER", "END", "JUSTIFIED"]
448
+ alignment_upper = alignment.upper()
449
+ if alignment_upper not in valid_alignments:
450
+ raise ValueError(
451
+ f"Invalid alignment '{alignment}'. Must be one of: {valid_alignments}"
452
+ )
453
+ paragraph_style["alignment"] = alignment_upper
454
+ fields.append("alignment")
455
+
456
+ if line_spacing is not None:
457
+ if line_spacing <= 0:
458
+ raise ValueError("line_spacing must be positive")
459
+ paragraph_style["lineSpacing"] = line_spacing * 100
460
+ fields.append("lineSpacing")
461
+
462
+ if indent_first_line is not None:
463
+ paragraph_style["indentFirstLine"] = {
464
+ "magnitude": indent_first_line,
465
+ "unit": "PT",
466
+ }
467
+ fields.append("indentFirstLine")
468
+
469
+ if indent_start is not None:
470
+ paragraph_style["indentStart"] = {"magnitude": indent_start, "unit": "PT"}
471
+ fields.append("indentStart")
472
+
473
+ if indent_end is not None:
474
+ paragraph_style["indentEnd"] = {"magnitude": indent_end, "unit": "PT"}
475
+ fields.append("indentEnd")
476
+
477
+ if space_above is not None:
478
+ paragraph_style["spaceAbove"] = {"magnitude": space_above, "unit": "PT"}
479
+ fields.append("spaceAbove")
480
+
481
+ if space_below is not None:
482
+ paragraph_style["spaceBelow"] = {"magnitude": space_below, "unit": "PT"}
483
+ fields.append("spaceBelow")
484
+
485
+ if direction is not None:
486
+ direction_upper = direction.upper()
487
+ if direction_upper not in VALID_PARAGRAPH_DIRECTIONS:
488
+ raise ValueError(
489
+ f"direction must be one of: {', '.join(VALID_PARAGRAPH_DIRECTIONS)}"
490
+ )
491
+ paragraph_style["direction"] = direction_upper
492
+ fields.append("direction")
493
+
494
+ if keep_lines_together is not None:
495
+ paragraph_style["keepLinesTogether"] = keep_lines_together
496
+ fields.append("keepLinesTogether")
497
+
498
+ if keep_with_next is not None:
499
+ paragraph_style["keepWithNext"] = keep_with_next
500
+ fields.append("keepWithNext")
501
+
502
+ if avoid_widow_and_orphan is not None:
503
+ paragraph_style["avoidWidowAndOrphan"] = avoid_widow_and_orphan
504
+ fields.append("avoidWidowAndOrphan")
505
+
506
+ if page_break_before is not None:
507
+ paragraph_style["pageBreakBefore"] = page_break_before
508
+ fields.append("pageBreakBefore")
509
+
510
+ if spacing_mode is not None:
511
+ spacing_mode_upper = spacing_mode.upper()
512
+ if spacing_mode_upper not in VALID_PARAGRAPH_SPACING_MODES:
513
+ raise ValueError(
514
+ f"spacing_mode must be one of: {', '.join(VALID_PARAGRAPH_SPACING_MODES)}"
515
+ )
516
+ paragraph_style["spacingMode"] = spacing_mode_upper
517
+ fields.append("spacingMode")
518
+
519
+ if shading_color is not None:
520
+ paragraph_style["shading"] = {
521
+ "backgroundColor": _build_optional_color(shading_color, "shading_color")
522
+ }
523
+ fields.append("shading")
524
+
525
+ # ParagraphBorder requires color, width, padding and dashStyle all set.
526
+ if (
527
+ border_color is not None
528
+ or border_width is not None
529
+ or border_padding is not None
530
+ or border_dash is not None
531
+ or border_edges is not None
532
+ ):
533
+ dash = (border_dash or "SOLID").upper()
534
+ if dash not in VALID_DASH_STYLES:
535
+ raise ValueError(
536
+ f"border_dash must be one of {', '.join(VALID_DASH_STYLES)}, got '{border_dash}'"
537
+ )
538
+ para_border = {
539
+ "color": _build_optional_color(
540
+ border_color if border_color is not None else "#000000",
541
+ "border_color",
542
+ ),
543
+ "width": {
544
+ "magnitude": border_width if border_width is not None else 1,
545
+ "unit": "PT",
546
+ },
547
+ "padding": {
548
+ "magnitude": border_padding if border_padding is not None else 4,
549
+ "unit": "PT",
550
+ },
551
+ "dashStyle": dash,
552
+ }
553
+ edge_map = PARAGRAPH_BORDER_EDGE_MAP
554
+ if border_edges is not None:
555
+ selected = []
556
+ for edge in border_edges:
557
+ edge_key = str(edge).strip().lower()
558
+ if edge_key not in edge_map:
559
+ raise ValueError(
560
+ f"border_edges entries must be one of {sorted(edge_map)}, got '{edge}'"
561
+ )
562
+ selected.append(edge_map[edge_key])
563
+ else:
564
+ selected = ["borderTop", "borderBottom", "borderLeft", "borderRight"]
565
+ for border_name in selected:
566
+ paragraph_style[border_name] = dict(para_border)
567
+ fields.append(border_name)
568
+
569
+ return paragraph_style, fields
570
+
571
+
572
+ def build_document_style(
573
+ background_color: Optional[str] = None,
574
+ margin_top: Optional[float] = None,
575
+ margin_bottom: Optional[float] = None,
576
+ margin_left: Optional[float] = None,
577
+ margin_right: Optional[float] = None,
578
+ margin_header: Optional[float] = None,
579
+ margin_footer: Optional[float] = None,
580
+ page_width: Optional[float] = None,
581
+ page_height: Optional[float] = None,
582
+ page_number_start: Optional[int] = None,
583
+ use_even_page_header_footer: Optional[bool] = None,
584
+ use_first_page_header_footer: Optional[bool] = None,
585
+ flip_page_orientation: Optional[bool] = None,
586
+ document_mode: Optional[str] = None,
587
+ ) -> tuple[Dict[str, Any], list[str]]:
588
+ """Build a documentStyle object and explicit field mask."""
589
+ document_style: Dict[str, Any] = {}
590
+ fields: List[str] = []
591
+
592
+ if background_color is not None:
593
+ # DocumentStyle.background wraps an OptionalColor in a Background object.
594
+ document_style["background"] = {
595
+ "color": _build_optional_color(background_color, "background_color")
596
+ }
597
+ fields.append("background")
598
+
599
+ for value, field_name in (
600
+ (margin_top, "marginTop"),
601
+ (margin_bottom, "marginBottom"),
602
+ (margin_left, "marginLeft"),
603
+ (margin_right, "marginRight"),
604
+ (margin_header, "marginHeader"),
605
+ (margin_footer, "marginFooter"),
606
+ ):
607
+ if value is not None:
608
+ document_style[field_name] = _build_dimension(value)
609
+ fields.append(field_name)
610
+
611
+ if page_width is not None or page_height is not None:
612
+ size: Dict[str, Any] = {}
613
+ if page_width is not None:
614
+ size["width"] = _build_dimension(page_width)
615
+ if page_height is not None:
616
+ size["height"] = _build_dimension(page_height)
617
+ document_style["pageSize"] = size
618
+ fields.append("pageSize")
619
+
620
+ if page_number_start is not None:
621
+ document_style["pageNumberStart"] = page_number_start
622
+ fields.append("pageNumberStart")
623
+
624
+ if use_even_page_header_footer is not None:
625
+ document_style["useEvenPageHeaderFooter"] = use_even_page_header_footer
626
+ fields.append("useEvenPageHeaderFooter")
627
+
628
+ if use_first_page_header_footer is not None:
629
+ document_style["useFirstPageHeaderFooter"] = use_first_page_header_footer
630
+ fields.append("useFirstPageHeaderFooter")
631
+
632
+ if flip_page_orientation is not None:
633
+ document_style["flipPageOrientation"] = flip_page_orientation
634
+ fields.append("flipPageOrientation")
635
+
636
+ if document_mode is not None:
637
+ document_mode_upper = document_mode.upper()
638
+ if document_mode_upper not in VALID_DOCUMENT_MODES:
639
+ raise ValueError(
640
+ f"document_mode must be one of: {', '.join(VALID_DOCUMENT_MODES)}"
641
+ )
642
+ document_style["documentFormat"] = {"documentMode": document_mode_upper}
643
+ fields.append("documentFormat")
644
+
645
+ return document_style, fields
646
+
647
+
648
+ def build_section_style(
649
+ margin_top: Optional[float] = None,
650
+ margin_bottom: Optional[float] = None,
651
+ margin_left: Optional[float] = None,
652
+ margin_right: Optional[float] = None,
653
+ margin_header: Optional[float] = None,
654
+ margin_footer: Optional[float] = None,
655
+ page_number_start: Optional[int] = None,
656
+ use_first_page_header_footer: Optional[bool] = None,
657
+ flip_page_orientation: Optional[bool] = None,
658
+ content_direction: Optional[str] = None,
659
+ column_count: Optional[int] = None,
660
+ column_spacing: Optional[float] = None,
661
+ column_separator_style: Optional[str] = None,
662
+ ) -> tuple[Dict[str, Any], list[str]]:
663
+ """Build a sectionStyle object and explicit field mask."""
664
+ section_style: Dict[str, Any] = {}
665
+ fields: List[str] = []
666
+
667
+ for value, field_name in (
668
+ (margin_top, "marginTop"),
669
+ (margin_bottom, "marginBottom"),
670
+ (margin_left, "marginLeft"),
671
+ (margin_right, "marginRight"),
672
+ (margin_header, "marginHeader"),
673
+ (margin_footer, "marginFooter"),
674
+ ):
675
+ if value is not None:
676
+ section_style[field_name] = _build_dimension(value)
677
+ fields.append(field_name)
678
+
679
+ if page_number_start is not None:
680
+ section_style["pageNumberStart"] = page_number_start
681
+ fields.append("pageNumberStart")
682
+
683
+ if use_first_page_header_footer is not None:
684
+ section_style["useFirstPageHeaderFooter"] = use_first_page_header_footer
685
+ fields.append("useFirstPageHeaderFooter")
686
+
687
+ if flip_page_orientation is not None:
688
+ section_style["flipPageOrientation"] = flip_page_orientation
689
+ fields.append("flipPageOrientation")
690
+
691
+ if content_direction is not None:
692
+ content_direction_upper = content_direction.upper()
693
+ if content_direction_upper not in VALID_CONTENT_DIRECTIONS:
694
+ raise ValueError(
695
+ "content_direction must be one of: "
696
+ f"{', '.join(VALID_CONTENT_DIRECTIONS)}"
697
+ )
698
+ section_style["contentDirection"] = content_direction_upper
699
+ fields.append("contentDirection")
700
+
701
+ if column_separator_style is not None:
702
+ column_separator_style_upper = column_separator_style.upper()
703
+ if column_separator_style_upper not in VALID_COLUMN_SEPARATOR_STYLES:
704
+ raise ValueError(
705
+ "column_separator_style must be one of: "
706
+ f"{', '.join(VALID_COLUMN_SEPARATOR_STYLES)}"
707
+ )
708
+ section_style["columnSeparatorStyle"] = column_separator_style_upper
709
+ fields.append("columnSeparatorStyle")
710
+
711
+ if column_count is not None or column_spacing is not None:
712
+ if column_count is None:
713
+ raise ValueError("column_count is required when specifying section columns")
714
+ if column_count < 1 or column_count > 3:
715
+ raise ValueError("column_count must be between 1 and 3")
716
+
717
+ columns = []
718
+ for _ in range(column_count):
719
+ column: Dict[str, Any] = {}
720
+ if column_spacing is not None:
721
+ column["paddingEnd"] = _build_dimension(column_spacing)
722
+ columns.append(column)
723
+ section_style["columnProperties"] = columns
724
+ fields.append("columnProperties")
725
+
726
+ return section_style, fields
727
+
728
+
729
+ def build_table_cell_style(
730
+ background_color: str = None,
731
+ border_color: str = None,
732
+ border_width: float = None,
733
+ padding_top: float = None,
734
+ padding_bottom: float = None,
735
+ padding_left: float = None,
736
+ padding_right: float = None,
737
+ content_alignment: str = None,
738
+ border_edges: Optional[List[str]] = None,
739
+ ) -> tuple[Dict[str, Any], list[str]]:
740
+ """
741
+ Build a table cell style object for Google Docs API requests.
742
+
743
+ Args:
744
+ background_color: Cell background color as hex string "#RRGGBB"
745
+ border_color: Cell border color as hex string "#RRGGBB"
746
+ border_width: Cell border width in points
747
+ padding_top: Top padding in points
748
+ padding_bottom: Bottom padding in points
749
+ padding_left: Left padding in points
750
+ padding_right: Right padding in points
751
+ content_alignment: Vertical content alignment ("TOP", "MIDDLE", "BOTTOM")
752
+ border_edges: Border edges to update; omit for all four edges
753
+
754
+ Returns:
755
+ Tuple of (table_cell_style_dict, list_of_field_names)
756
+ """
757
+ table_cell_style = {}
758
+ fields = []
759
+
760
+ if border_edges is not None and not border_edges:
761
+ raise ValueError("border_edges must contain at least one edge")
762
+
763
+ if border_color is not None or border_width is not None or border_edges is not None:
764
+ # TableCellBorder requires color, width and dashStyle. Default missing
765
+ # members so color-only or width-only calls still form valid borders.
766
+ border_style = {"dashStyle": "SOLID"}
767
+
768
+ border_style["width"] = {
769
+ "magnitude": border_width if border_width is not None else 1,
770
+ "unit": "PT",
771
+ }
772
+
773
+ rgb = _normalize_color(
774
+ border_color if border_color is not None else "#000000", "border_color"
775
+ )
776
+ border_style["color"] = {"color": {"rgbColor": rgb}}
777
+
778
+ edge_map = TABLE_BORDER_EDGE_MAP
779
+ if border_edges is not None:
780
+ selected = []
781
+ for edge in border_edges:
782
+ edge_key = str(edge).strip().lower()
783
+ if edge_key not in edge_map:
784
+ raise ValueError(
785
+ f"border_edges entries must be one of {sorted(edge_map)}, got '{edge}'"
786
+ )
787
+ selected.append(edge_map[edge_key])
788
+ else:
789
+ selected = list(edge_map.values())
790
+
791
+ for border_name in selected:
792
+ table_cell_style[border_name] = border_style.copy()
793
+ fields.append(border_name)
794
+
795
+ if background_color is not None:
796
+ rgb = _normalize_color(background_color, "background_color")
797
+ table_cell_style["backgroundColor"] = {"color": {"rgbColor": rgb}}
798
+ fields.append("backgroundColor")
799
+
800
+ for padding_value, api_key in (
801
+ (padding_top, "paddingTop"),
802
+ (padding_bottom, "paddingBottom"),
803
+ (padding_left, "paddingLeft"),
804
+ (padding_right, "paddingRight"),
805
+ ):
806
+ if padding_value is not None:
807
+ table_cell_style[api_key] = {"magnitude": padding_value, "unit": "PT"}
808
+ fields.append(api_key)
809
+
810
+ if content_alignment is not None:
811
+ table_cell_style["contentAlignment"] = content_alignment.upper()
812
+ fields.append("contentAlignment")
813
+
814
+ return table_cell_style, fields
815
+
816
+
817
+ def create_insert_text_request(
818
+ index: Optional[int],
819
+ text: str,
820
+ tab_id: Optional[str] = None,
821
+ segment_id: Optional[str] = None,
822
+ end_of_segment: bool = False,
823
+ ) -> Dict[str, Any]:
824
+ """
825
+ Create an insertText request for Google Docs API.
826
+
827
+ Args:
828
+ index: Position to insert text
829
+ text: Text to insert
830
+ tab_id: Optional ID of the tab to target
831
+
832
+ Returns:
833
+ Dictionary representing the insertText request
834
+ """
835
+ request = {"insertText": {"text": text}}
836
+ request["insertText"].update(
837
+ _build_location(
838
+ index=index,
839
+ tab_id=tab_id,
840
+ segment_id=segment_id,
841
+ end_of_segment=end_of_segment,
842
+ )
843
+ )
844
+ return request
845
+
846
+
847
+ def create_insert_text_segment_request(
848
+ index: int, text: str, segment_id: str, tab_id: Optional[str] = None
849
+ ) -> Dict[str, Any]:
850
+ """
851
+ Create an insertText request for Google Docs API with segmentId (for headers/footers).
852
+
853
+ Args:
854
+ index: Position to insert text
855
+ text: Text to insert
856
+ segment_id: Segment ID (for targeting headers/footers)
857
+ tab_id: Optional ID of the tab to target
858
+
859
+ Returns:
860
+ Dictionary representing the insertText request with segmentId and optional tabId
861
+ """
862
+ return create_insert_text_request(
863
+ index=index,
864
+ text=text,
865
+ tab_id=tab_id,
866
+ segment_id=segment_id,
867
+ )
868
+
869
+
870
+ def create_delete_range_request(
871
+ start_index: int,
872
+ end_index: int,
873
+ tab_id: Optional[str] = None,
874
+ segment_id: Optional[str] = None,
875
+ ) -> Dict[str, Any]:
876
+ """
877
+ Create a deleteContentRange request for Google Docs API.
878
+
879
+ Args:
880
+ start_index: Start position of content to delete
881
+ end_index: End position of content to delete
882
+ tab_id: Optional ID of the tab to target
883
+
884
+ Returns:
885
+ Dictionary representing the deleteContentRange request
886
+ """
887
+ return {
888
+ "deleteContentRange": {
889
+ "range": _build_range(start_index, end_index, tab_id, segment_id)
890
+ }
891
+ }
892
+
893
+
894
+ def create_format_text_request(
895
+ start_index: int,
896
+ end_index: int,
897
+ bold: bool = None,
898
+ italic: bool = None,
899
+ underline: bool = None,
900
+ strikethrough: bool = None,
901
+ font_size: float = None,
902
+ font_family: str = None,
903
+ font_weight: int = None,
904
+ text_color: str = None,
905
+ background_color: str = None,
906
+ link_url: str = None,
907
+ clear_link: bool = None,
908
+ baseline_offset: str = None,
909
+ small_caps: bool = None,
910
+ tab_id: Optional[str] = None,
911
+ segment_id: Optional[str] = None,
912
+ ) -> Optional[Dict[str, Any]]:
913
+ """
914
+ Create an updateTextStyle request for Google Docs API.
915
+
916
+ Args:
917
+ start_index: Start position of text to format
918
+ end_index: End position of text to format
919
+ bold: Whether text should be bold
920
+ italic: Whether text should be italic
921
+ underline: Whether text should be underlined
922
+ strikethrough: Whether text should be struck through
923
+ font_size: Font size in points
924
+ font_family: Font family name
925
+ text_color: Text color as hex string "#RRGGBB"
926
+ background_color: Background (highlight) color as hex string "#RRGGBB"
927
+ link_url: Hyperlink URL (http/https)
928
+ tab_id: Optional ID of the tab to target
929
+
930
+ Returns:
931
+ Dictionary representing the updateTextStyle request, or None if no styles provided
932
+ """
933
+ text_style, fields = build_text_style(
934
+ bold,
935
+ italic,
936
+ underline,
937
+ strikethrough,
938
+ font_size,
939
+ font_family,
940
+ font_weight,
941
+ text_color,
942
+ background_color,
943
+ link_url,
944
+ clear_link,
945
+ baseline_offset,
946
+ small_caps,
947
+ )
948
+
949
+ if not text_style:
950
+ return None
951
+
952
+ return {
953
+ "updateTextStyle": {
954
+ "range": _build_range(start_index, end_index, tab_id, segment_id),
955
+ "textStyle": text_style,
956
+ "fields": ",".join(fields),
957
+ }
958
+ }
959
+
960
+
961
+ def create_update_paragraph_style_request(
962
+ start_index: int,
963
+ end_index: int,
964
+ heading_level: int = None,
965
+ alignment: str = None,
966
+ line_spacing: float = None,
967
+ indent_first_line: float = None,
968
+ indent_start: float = None,
969
+ indent_end: float = None,
970
+ space_above: float = None,
971
+ space_below: float = None,
972
+ tab_id: Optional[str] = None,
973
+ named_style_type: Optional[str] = None,
974
+ segment_id: Optional[str] = None,
975
+ direction: Optional[str] = None,
976
+ keep_lines_together: Optional[bool] = None,
977
+ keep_with_next: Optional[bool] = None,
978
+ avoid_widow_and_orphan: Optional[bool] = None,
979
+ page_break_before: Optional[bool] = None,
980
+ spacing_mode: Optional[str] = None,
981
+ shading_color: Optional[str] = None,
982
+ border_edges: Optional[List[str]] = None,
983
+ border_color: Optional[str] = None,
984
+ border_width: Optional[float] = None,
985
+ border_padding: Optional[float] = None,
986
+ border_dash: Optional[str] = None,
987
+ ) -> Optional[Dict[str, Any]]:
988
+ """
989
+ Create an updateParagraphStyle request for Google Docs API.
990
+
991
+ Args:
992
+ start_index: Start position of paragraph range. For the main body,
993
+ 0 is accepted as an alias for the first writable position.
994
+ end_index: End position of paragraph range
995
+ heading_level: Heading level 0-6 (0 = NORMAL_TEXT, 1-6 = HEADING_N)
996
+ alignment: Text alignment - 'START', 'CENTER', 'END', or 'JUSTIFIED'
997
+ line_spacing: Line spacing multiplier (1.0 = single, 2.0 = double)
998
+ indent_first_line: First line indent in points
999
+ indent_start: Left/start indent in points
1000
+ indent_end: Right/end indent in points
1001
+ space_above: Space above paragraph in points
1002
+ space_below: Space below paragraph in points
1003
+ tab_id: Optional ID of the tab to target
1004
+ named_style_type: Direct named style (TITLE, SUBTITLE, HEADING_1..6, NORMAL_TEXT)
1005
+
1006
+ Returns:
1007
+ Dictionary representing the updateParagraphStyle request, or None if no styles provided
1008
+ """
1009
+ paragraph_style, fields = build_paragraph_style(
1010
+ heading_level=heading_level,
1011
+ alignment=alignment,
1012
+ line_spacing=line_spacing,
1013
+ indent_first_line=indent_first_line,
1014
+ indent_start=indent_start,
1015
+ indent_end=indent_end,
1016
+ space_above=space_above,
1017
+ space_below=space_below,
1018
+ named_style_type=named_style_type,
1019
+ direction=direction,
1020
+ keep_lines_together=keep_lines_together,
1021
+ keep_with_next=keep_with_next,
1022
+ avoid_widow_and_orphan=avoid_widow_and_orphan,
1023
+ page_break_before=page_break_before,
1024
+ spacing_mode=spacing_mode,
1025
+ shading_color=shading_color,
1026
+ border_edges=border_edges,
1027
+ border_color=border_color,
1028
+ border_width=border_width,
1029
+ border_padding=border_padding,
1030
+ border_dash=border_dash,
1031
+ )
1032
+
1033
+ if not paragraph_style:
1034
+ return None
1035
+
1036
+ normalized_start_index = _normalize_body_start_index(
1037
+ start_index, tab_id, segment_id
1038
+ )
1039
+
1040
+ return {
1041
+ "updateParagraphStyle": {
1042
+ "range": _build_range(
1043
+ normalized_start_index, end_index, tab_id, segment_id
1044
+ ),
1045
+ "paragraphStyle": paragraph_style,
1046
+ "fields": ",".join(fields),
1047
+ }
1048
+ }
1049
+
1050
+
1051
+ def create_find_replace_request(
1052
+ find_text: str,
1053
+ replace_text: str,
1054
+ match_case: bool = False,
1055
+ tab_id: Optional[str] = None,
1056
+ ) -> Dict[str, Any]:
1057
+ """
1058
+ Create a replaceAllText request for Google Docs API.
1059
+
1060
+ Args:
1061
+ find_text: Text to find
1062
+ replace_text: Text to replace with
1063
+ match_case: Whether to match case exactly
1064
+ tab_id: Optional ID of the tab to target
1065
+
1066
+ Returns:
1067
+ Dictionary representing the replaceAllText request
1068
+ """
1069
+ request = {
1070
+ "replaceAllText": {
1071
+ "containsText": {"text": find_text, "matchCase": match_case},
1072
+ "replaceText": replace_text,
1073
+ }
1074
+ }
1075
+ tabs_criteria = _build_tabs_criteria(tab_id)
1076
+ if tabs_criteria:
1077
+ request["replaceAllText"]["tabsCriteria"] = tabs_criteria
1078
+ return request
1079
+
1080
+
1081
+ def create_insert_table_request(
1082
+ index: Optional[int],
1083
+ rows: int,
1084
+ columns: int,
1085
+ tab_id: Optional[str] = None,
1086
+ segment_id: Optional[str] = None,
1087
+ end_of_segment: bool = False,
1088
+ ) -> Dict[str, Any]:
1089
+ """
1090
+ Create an insertTable request for Google Docs API.
1091
+
1092
+ Args:
1093
+ index: Position to insert table
1094
+ rows: Number of rows
1095
+ columns: Number of columns
1096
+ tab_id: Optional ID of the tab to target
1097
+
1098
+ Returns:
1099
+ Dictionary representing the insertTable request
1100
+ """
1101
+ request = {"insertTable": {"rows": rows, "columns": columns}}
1102
+ request["insertTable"].update(
1103
+ _build_location(
1104
+ index=index,
1105
+ tab_id=tab_id,
1106
+ segment_id=segment_id,
1107
+ end_of_segment=end_of_segment,
1108
+ )
1109
+ )
1110
+ return request
1111
+
1112
+
1113
+ def create_update_table_cell_style_request(
1114
+ table_start_index: int,
1115
+ background_color: str = None,
1116
+ border_color: str = None,
1117
+ border_width: float = None,
1118
+ padding_top: float = None,
1119
+ padding_bottom: float = None,
1120
+ padding_left: float = None,
1121
+ padding_right: float = None,
1122
+ content_alignment: str = None,
1123
+ row_index: int = None,
1124
+ column_index: int = None,
1125
+ row_span: int = None,
1126
+ column_span: int = None,
1127
+ tab_id: Optional[str] = None,
1128
+ border_edges: Optional[List[str]] = None,
1129
+ ) -> Optional[Dict[str, Any]]:
1130
+ """
1131
+ Create an updateTableCellStyle request for Google Docs API.
1132
+
1133
+ Args:
1134
+ table_start_index: Start index of the target table
1135
+ background_color: Cell background color as hex string "#RRGGBB"
1136
+ border_color: Cell border color as hex string "#RRGGBB"
1137
+ border_width: Cell border width in points
1138
+ padding_top: Top padding in points
1139
+ padding_bottom: Bottom padding in points
1140
+ padding_left: Left padding in points
1141
+ padding_right: Right padding in points
1142
+ content_alignment: Vertical content alignment ("TOP", "MIDDLE", "BOTTOM")
1143
+ row_index: Optional starting row index for a sub-range
1144
+ column_index: Optional starting column index for a sub-range
1145
+ row_span: Optional row span for a sub-range (defaults to 1)
1146
+ column_span: Optional column span for a sub-range (defaults to 1)
1147
+ tab_id: Optional ID of the tab to target
1148
+
1149
+ Returns:
1150
+ Dictionary representing the updateTableCellStyle request, or None if no
1151
+ style fields were provided
1152
+ """
1153
+ table_cell_style, fields = build_table_cell_style(
1154
+ background_color=background_color,
1155
+ border_color=border_color,
1156
+ border_width=border_width,
1157
+ padding_top=padding_top,
1158
+ padding_bottom=padding_bottom,
1159
+ padding_left=padding_left,
1160
+ padding_right=padding_right,
1161
+ content_alignment=content_alignment,
1162
+ border_edges=border_edges,
1163
+ )
1164
+ if not table_cell_style:
1165
+ return None
1166
+
1167
+ location = {"index": table_start_index}
1168
+ if tab_id:
1169
+ location["tabId"] = tab_id
1170
+
1171
+ request: Dict[str, Any] = {
1172
+ "tableCellStyle": table_cell_style,
1173
+ "fields": ",".join(fields),
1174
+ }
1175
+
1176
+ uses_table_range = any(
1177
+ value is not None for value in (row_index, column_index, row_span, column_span)
1178
+ )
1179
+ if uses_table_range:
1180
+ if row_index is None or column_index is None:
1181
+ raise ValueError(
1182
+ "row_index and column_index are required when targeting a table cell range"
1183
+ )
1184
+
1185
+ request["tableRange"] = {
1186
+ "tableCellLocation": {
1187
+ "tableStartLocation": location,
1188
+ "rowIndex": row_index,
1189
+ "columnIndex": column_index,
1190
+ },
1191
+ "rowSpan": 1 if row_span is None else row_span,
1192
+ "columnSpan": 1 if column_span is None else column_span,
1193
+ }
1194
+ else:
1195
+ request["tableStartLocation"] = location
1196
+
1197
+ return {"updateTableCellStyle": request}
1198
+
1199
+
1200
+ def create_insert_page_break_request(
1201
+ index: Optional[int],
1202
+ tab_id: Optional[str] = None,
1203
+ end_of_segment: bool = False,
1204
+ ) -> Dict[str, Any]:
1205
+ """
1206
+ Create an insertPageBreak request for Google Docs API.
1207
+
1208
+ Args:
1209
+ index: Position to insert page break
1210
+ tab_id: Optional ID of the tab to target
1211
+
1212
+ Returns:
1213
+ Dictionary representing the insertPageBreak request
1214
+ """
1215
+ request = {"insertPageBreak": {}}
1216
+ request["insertPageBreak"].update(
1217
+ _build_location(index=index, tab_id=tab_id, end_of_segment=end_of_segment)
1218
+ )
1219
+ return request
1220
+
1221
+
1222
+ def create_insert_doc_tab_request(
1223
+ title: str, index: int, parent_tab_id: Optional[str] = None
1224
+ ) -> Dict[str, Any]:
1225
+ """
1226
+ Create an addDocumentTab request for Google Docs API.
1227
+
1228
+ Args:
1229
+ title: Title of the new tab
1230
+ index: Position to insert the tab
1231
+ parent_tab_id: Optional ID of the parent tab to nest under
1232
+
1233
+ Returns:
1234
+ Dictionary representing the addDocumentTab request
1235
+ """
1236
+ tab_properties: Dict[str, Any] = {
1237
+ "title": title,
1238
+ "index": index,
1239
+ }
1240
+ if parent_tab_id:
1241
+ tab_properties["parentTabId"] = parent_tab_id
1242
+ return {
1243
+ "addDocumentTab": {
1244
+ "tabProperties": tab_properties,
1245
+ }
1246
+ }
1247
+
1248
+
1249
+ def create_delete_doc_tab_request(tab_id: str) -> Dict[str, Any]:
1250
+ """
1251
+ Create a deleteDocumentTab request for Google Docs API.
1252
+
1253
+ Args:
1254
+ tab_id: ID of the tab to delete
1255
+
1256
+ Returns:
1257
+ Dictionary representing the deleteDocumentTab request
1258
+ """
1259
+ return {"deleteTab": {"tabId": tab_id}}
1260
+
1261
+
1262
+ def create_update_doc_tab_request(tab_id: str, title: str) -> Dict[str, Any]:
1263
+ """
1264
+ Create an updateDocumentTab request for Google Docs API.
1265
+
1266
+ Args:
1267
+ tab_id: ID of the tab to update
1268
+ title: New title for the tab
1269
+
1270
+ Returns:
1271
+ Dictionary representing the updateDocumentTab request
1272
+ """
1273
+ return {
1274
+ "updateDocumentTabProperties": {
1275
+ "tabProperties": {
1276
+ "tabId": tab_id,
1277
+ "title": title,
1278
+ },
1279
+ "fields": "title",
1280
+ }
1281
+ }
1282
+
1283
+
1284
+ def create_insert_image_request(
1285
+ index: Optional[int],
1286
+ image_uri: str,
1287
+ width: int = None,
1288
+ height: int = None,
1289
+ tab_id: Optional[str] = None,
1290
+ segment_id: Optional[str] = None,
1291
+ end_of_segment: bool = False,
1292
+ ) -> Dict[str, Any]:
1293
+ """
1294
+ Create an insertInlineImage request for Google Docs API.
1295
+
1296
+ Args:
1297
+ index: Position to insert image
1298
+ image_uri: URI of the image (Drive URL or public URL)
1299
+ width: Image width in points
1300
+ height: Image height in points
1301
+ tab_id: Optional ID of the tab to target
1302
+
1303
+ Returns:
1304
+ Dictionary representing the insertInlineImage request
1305
+ """
1306
+ request = {"insertInlineImage": {"uri": image_uri}}
1307
+ request["insertInlineImage"].update(
1308
+ _build_location(
1309
+ index=index,
1310
+ tab_id=tab_id,
1311
+ segment_id=segment_id,
1312
+ end_of_segment=end_of_segment,
1313
+ )
1314
+ )
1315
+
1316
+ # Add size properties if specified
1317
+ object_size = {}
1318
+ if width is not None:
1319
+ object_size["width"] = {"magnitude": width, "unit": "PT"}
1320
+ if height is not None:
1321
+ object_size["height"] = {"magnitude": height, "unit": "PT"}
1322
+
1323
+ if object_size:
1324
+ request["insertInlineImage"]["objectSize"] = object_size
1325
+
1326
+ return request
1327
+
1328
+
1329
+ def create_insert_person_request(
1330
+ index: Optional[int],
1331
+ email: str,
1332
+ tab_id: Optional[str] = None,
1333
+ segment_id: Optional[str] = None,
1334
+ end_of_segment: bool = False,
1335
+ ) -> Dict[str, Any]:
1336
+ """Create an insertPerson request that adds a person smart chip for ``email``."""
1337
+ return {
1338
+ "insertPerson": {
1339
+ "personProperties": {"email": email},
1340
+ **_build_location(
1341
+ index=index,
1342
+ tab_id=tab_id,
1343
+ segment_id=segment_id,
1344
+ end_of_segment=end_of_segment,
1345
+ ),
1346
+ }
1347
+ }
1348
+
1349
+
1350
+ def create_dropdown_definition_request(
1351
+ title: str,
1352
+ options: list[dict[str, Any]],
1353
+ dropdown_definition_id: Optional[str] = None,
1354
+ tab_id: Optional[str] = None,
1355
+ ) -> Dict[str, Any]:
1356
+ """Build a tab-scoped native dropdown definition without modifying document text."""
1357
+ choices = []
1358
+ for option in options:
1359
+ choice = {"displayValue": option["display_value"]}
1360
+ if option.get("option_id") is not None:
1361
+ choice["optionId"] = option["option_id"]
1362
+ style = {}
1363
+ for source, target in (
1364
+ ("text_color", "foregroundColor"),
1365
+ ("background_color", "backgroundColor"),
1366
+ ):
1367
+ if option.get(source) is not None:
1368
+ style[target] = _build_optional_color(option[source], source)
1369
+ if style:
1370
+ choice["textStyle"] = style
1371
+ choices.append(choice)
1372
+ definition = {"dropdownDefinitionProperties": {"title": title, "options": choices}}
1373
+ if dropdown_definition_id is not None:
1374
+ definition["dropdownDefinitionId"] = dropdown_definition_id
1375
+ request = {"dropdownDefinition": definition}
1376
+ if tab_id is not None:
1377
+ request["tabId"] = tab_id
1378
+ return {"createDropdownDefinition": request}
1379
+
1380
+
1381
+ def create_insert_dropdown_request(
1382
+ index: Optional[int],
1383
+ dropdown_definition_id: str,
1384
+ selected_option_id: Optional[str] = None,
1385
+ tab_id: Optional[str] = None,
1386
+ segment_id: Optional[str] = None,
1387
+ end_of_segment: bool = False,
1388
+ ) -> Dict[str, Any]:
1389
+ """Insert a native chip referencing a definition in the same tab."""
1390
+ request = {
1391
+ "dropdownDefinitionId": dropdown_definition_id,
1392
+ **_build_location(index, tab_id, segment_id, end_of_segment),
1393
+ }
1394
+ if selected_option_id is not None:
1395
+ request["selectedOptionId"] = selected_option_id
1396
+ return {"insertDropdown": request}
1397
+
1398
+
1399
+ def create_insert_date_request(
1400
+ index: Optional[int],
1401
+ date: str,
1402
+ date_format: Optional[str] = None,
1403
+ time_format: Optional[str] = None,
1404
+ timezone: Optional[str] = None,
1405
+ tab_id: Optional[str] = None,
1406
+ segment_id: Optional[str] = None,
1407
+ end_of_segment: bool = False,
1408
+ ) -> Dict[str, Any]:
1409
+ """Create an insertDate request; a date-only value is sent as noon in ``timezone`` or UTC."""
1410
+ moment = datetime.fromisoformat(date.replace("Z", "+00:00"))
1411
+ if "T" not in date:
1412
+ moment = moment.replace(
1413
+ hour=12, tzinfo=ZoneInfo(timezone) if timezone else dt_timezone.utc
1414
+ )
1415
+ props: Dict[str, Any] = {
1416
+ "timestamp": moment.astimezone(dt_timezone.utc)
1417
+ .isoformat()
1418
+ .replace("+00:00", "Z"),
1419
+ "dateFormat": date_format or "DATE_FORMAT_MONTH_DAY_YEAR_ABBREVIATED",
1420
+ }
1421
+ if time_format:
1422
+ props["timeFormat"] = time_format
1423
+ if timezone:
1424
+ props["timeZoneId"] = timezone
1425
+ return {
1426
+ "insertDate": {
1427
+ "dateElementProperties": props,
1428
+ **_build_location(
1429
+ index=index,
1430
+ tab_id=tab_id,
1431
+ segment_id=segment_id,
1432
+ end_of_segment=end_of_segment,
1433
+ ),
1434
+ }
1435
+ }
1436
+
1437
+
1438
+ def create_bullet_list_request(
1439
+ start_index: int,
1440
+ end_index: int,
1441
+ list_type: str = "UNORDERED",
1442
+ nesting_level: int = None,
1443
+ paragraph_start_indices: Optional[list[int]] = None,
1444
+ doc_tab_id: Optional[str] = None,
1445
+ bullet_preset: Optional[str] = None,
1446
+ segment_id: Optional[str] = None,
1447
+ ) -> list[Dict[str, Any]]:
1448
+ """
1449
+ Create requests to apply bullet list formatting with optional nesting.
1450
+
1451
+ Google Docs infers list nesting from leading tab characters. To set a nested
1452
+ level, this helper inserts literal tab characters before each targeted
1453
+ paragraph, then calls createParagraphBullets. This is a Docs API workaround
1454
+ and does temporarily mutate content/index positions while the batch executes.
1455
+
1456
+ Args:
1457
+ start_index: Start of text range to convert to list
1458
+ end_index: End of text range to convert to list
1459
+ list_type: Type of list ("UNORDERED" or "ORDERED")
1460
+ nesting_level: Nesting level (0-8, where 0 is top level). If None or 0, no tabs added.
1461
+ paragraph_start_indices: Optional paragraph start positions for ranges with
1462
+ multiple paragraphs. If omitted, only start_index is tab-prefixed.
1463
+ doc_tab_id: Optional ID of the tab to target
1464
+
1465
+ Returns:
1466
+ List of request dictionaries (insertText for nesting tabs if needed,
1467
+ then createParagraphBullets)
1468
+ """
1469
+ start_index = _normalize_body_start_index(start_index, doc_tab_id, segment_id)
1470
+
1471
+ if bullet_preset is None:
1472
+ if list_type == "UNORDERED":
1473
+ bullet_preset = "BULLET_DISC_CIRCLE_SQUARE"
1474
+ elif list_type == "CHECKBOX":
1475
+ bullet_preset = "BULLET_CHECKBOX"
1476
+ else:
1477
+ bullet_preset = "NUMBERED_DECIMAL_ALPHA_ROMAN"
1478
+ elif bullet_preset not in VALID_BULLET_PRESETS:
1479
+ raise ValueError(
1480
+ f"bullet_preset must be one of: {', '.join(VALID_BULLET_PRESETS)}"
1481
+ )
1482
+
1483
+ # Validate nesting level
1484
+ if nesting_level is not None:
1485
+ if not isinstance(nesting_level, int):
1486
+ raise ValueError("nesting_level must be an integer between 0 and 8")
1487
+ if nesting_level < 0 or nesting_level > 8:
1488
+ raise ValueError("nesting_level must be between 0 and 8")
1489
+
1490
+ requests = []
1491
+
1492
+ # Insert tabs for nesting if needed (nesting_level > 0).
1493
+ # For multi-paragraph ranges, callers should provide paragraph_start_indices.
1494
+ if nesting_level and nesting_level > 0:
1495
+ tabs = "\t" * nesting_level
1496
+ paragraph_starts = paragraph_start_indices or [start_index]
1497
+ paragraph_starts = sorted(set(paragraph_starts))
1498
+
1499
+ if any(not isinstance(idx, int) for idx in paragraph_starts):
1500
+ raise ValueError("paragraph_start_indices must contain only integers")
1501
+
1502
+ original_start = start_index
1503
+ original_end = end_index
1504
+ inserted_char_count = 0
1505
+
1506
+ for paragraph_start in paragraph_starts:
1507
+ adjusted_start = paragraph_start + inserted_char_count
1508
+ requests.append(
1509
+ create_insert_text_request(
1510
+ adjusted_start,
1511
+ tabs,
1512
+ doc_tab_id,
1513
+ segment_id=segment_id,
1514
+ )
1515
+ )
1516
+ inserted_char_count += nesting_level
1517
+
1518
+ # Keep createParagraphBullets range aligned to the same logical content.
1519
+ start_index += (
1520
+ sum(1 for idx in paragraph_starts if idx < original_start) * nesting_level
1521
+ )
1522
+ end_index += (
1523
+ sum(1 for idx in paragraph_starts if idx < original_end) * nesting_level
1524
+ )
1525
+
1526
+ # Create the bullet list
1527
+ range_obj = _build_range(start_index, end_index, doc_tab_id, segment_id)
1528
+
1529
+ requests.append(
1530
+ {
1531
+ "createParagraphBullets": {
1532
+ "range": range_obj,
1533
+ "bulletPreset": bullet_preset,
1534
+ }
1535
+ }
1536
+ )
1537
+
1538
+ return requests
1539
+
1540
+
1541
+ def create_delete_bullet_list_request(
1542
+ start_index: int,
1543
+ end_index: int,
1544
+ doc_tab_id: Optional[str] = None,
1545
+ segment_id: Optional[str] = None,
1546
+ ) -> Dict[str, Any]:
1547
+ """
1548
+ Create a deleteParagraphBullets request to remove bullet/list formatting.
1549
+
1550
+ Args:
1551
+ start_index: Start of the paragraph range
1552
+ end_index: End of the paragraph range
1553
+ doc_tab_id: Optional ID of the tab to target
1554
+
1555
+ Returns:
1556
+ Dictionary representing the deleteParagraphBullets request
1557
+ """
1558
+ start_index = _normalize_body_start_index(start_index, doc_tab_id, segment_id)
1559
+
1560
+ return {
1561
+ "deleteParagraphBullets": {
1562
+ "range": _build_range(start_index, end_index, doc_tab_id, segment_id),
1563
+ }
1564
+ }
1565
+
1566
+
1567
+ def create_named_range_request(
1568
+ name: str,
1569
+ start_index: int,
1570
+ end_index: int,
1571
+ tab_id: Optional[str] = None,
1572
+ segment_id: Optional[str] = None,
1573
+ ) -> Dict[str, Any]:
1574
+ """Create a createNamedRange request."""
1575
+ return {
1576
+ "createNamedRange": {
1577
+ "name": name,
1578
+ "range": _build_range(start_index, end_index, tab_id, segment_id),
1579
+ }
1580
+ }
1581
+
1582
+
1583
+ def create_delete_named_range_request(
1584
+ named_range_id: Optional[str] = None,
1585
+ named_range_name: Optional[str] = None,
1586
+ tab_id: Optional[str] = None,
1587
+ ) -> Dict[str, Any]:
1588
+ """Create a deleteNamedRange request."""
1589
+ request: Dict[str, Any] = {}
1590
+ if named_range_id is not None:
1591
+ request["namedRangeId"] = named_range_id
1592
+ if named_range_name is not None:
1593
+ request["name"] = named_range_name
1594
+ tabs_criteria = _build_tabs_criteria(tab_id)
1595
+ if tabs_criteria:
1596
+ request["tabsCriteria"] = tabs_criteria
1597
+ return {"deleteNamedRange": request}
1598
+
1599
+
1600
+ def create_replace_named_range_content_request(
1601
+ text: str,
1602
+ named_range_id: Optional[str] = None,
1603
+ named_range_name: Optional[str] = None,
1604
+ tab_id: Optional[str] = None,
1605
+ ) -> Dict[str, Any]:
1606
+ """Create a replaceNamedRangeContent request."""
1607
+ request: Dict[str, Any] = {"text": text}
1608
+ if named_range_id is not None:
1609
+ request["namedRangeId"] = named_range_id
1610
+ if named_range_name is not None:
1611
+ request["namedRangeName"] = named_range_name
1612
+ tabs_criteria = _build_tabs_criteria(tab_id)
1613
+ if tabs_criteria:
1614
+ request["tabsCriteria"] = tabs_criteria
1615
+ return {"replaceNamedRangeContent": request}
1616
+
1617
+
1618
+ def create_insert_section_break_request(
1619
+ index: Optional[int] = None,
1620
+ section_type: str = "NEXT_PAGE",
1621
+ end_of_segment: bool = False,
1622
+ tab_id: Optional[str] = None,
1623
+ ) -> Dict[str, Any]:
1624
+ """Create an insertSectionBreak request."""
1625
+ section_type_upper = section_type.upper()
1626
+ if section_type_upper not in VALID_SECTION_TYPES:
1627
+ raise ValueError(
1628
+ f"section_type must be one of: {', '.join(VALID_SECTION_TYPES)}"
1629
+ )
1630
+ request = {"insertSectionBreak": {"sectionType": section_type_upper}}
1631
+ request["insertSectionBreak"].update(
1632
+ _build_location(index=index, tab_id=tab_id, end_of_segment=end_of_segment)
1633
+ )
1634
+ return request
1635
+
1636
+
1637
+ def create_update_document_style_request(
1638
+ *,
1639
+ tab_id: Optional[str] = None,
1640
+ background_color: Optional[str] = None,
1641
+ margin_top: Optional[float] = None,
1642
+ margin_bottom: Optional[float] = None,
1643
+ margin_left: Optional[float] = None,
1644
+ margin_right: Optional[float] = None,
1645
+ margin_header: Optional[float] = None,
1646
+ margin_footer: Optional[float] = None,
1647
+ page_width: Optional[float] = None,
1648
+ page_height: Optional[float] = None,
1649
+ page_number_start: Optional[int] = None,
1650
+ use_even_page_header_footer: Optional[bool] = None,
1651
+ use_first_page_header_footer: Optional[bool] = None,
1652
+ flip_page_orientation: Optional[bool] = None,
1653
+ document_mode: Optional[str] = None,
1654
+ ) -> Optional[Dict[str, Any]]:
1655
+ """Create an updateDocumentStyle request."""
1656
+ document_style, fields = build_document_style(
1657
+ background_color=background_color,
1658
+ margin_top=margin_top,
1659
+ margin_bottom=margin_bottom,
1660
+ margin_left=margin_left,
1661
+ margin_right=margin_right,
1662
+ margin_header=margin_header,
1663
+ margin_footer=margin_footer,
1664
+ page_width=page_width,
1665
+ page_height=page_height,
1666
+ page_number_start=page_number_start,
1667
+ use_even_page_header_footer=use_even_page_header_footer,
1668
+ use_first_page_header_footer=use_first_page_header_footer,
1669
+ flip_page_orientation=flip_page_orientation,
1670
+ document_mode=document_mode,
1671
+ )
1672
+ if not document_style:
1673
+ return None
1674
+
1675
+ request: Dict[str, Any] = {
1676
+ "updateDocumentStyle": {
1677
+ "documentStyle": document_style,
1678
+ "fields": ",".join(fields),
1679
+ }
1680
+ }
1681
+ if tab_id:
1682
+ request["updateDocumentStyle"]["tabId"] = tab_id
1683
+ return request
1684
+
1685
+
1686
+ def create_update_section_style_request(
1687
+ start_index: int,
1688
+ end_index: int,
1689
+ *,
1690
+ margin_top: Optional[float] = None,
1691
+ margin_bottom: Optional[float] = None,
1692
+ margin_left: Optional[float] = None,
1693
+ margin_right: Optional[float] = None,
1694
+ margin_header: Optional[float] = None,
1695
+ margin_footer: Optional[float] = None,
1696
+ page_number_start: Optional[int] = None,
1697
+ use_first_page_header_footer: Optional[bool] = None,
1698
+ flip_page_orientation: Optional[bool] = None,
1699
+ content_direction: Optional[str] = None,
1700
+ column_count: Optional[int] = None,
1701
+ column_spacing: Optional[float] = None,
1702
+ column_separator_style: Optional[str] = None,
1703
+ ) -> Optional[Dict[str, Any]]:
1704
+ """Create an updateSectionStyle request."""
1705
+ section_style, fields = build_section_style(
1706
+ margin_top=margin_top,
1707
+ margin_bottom=margin_bottom,
1708
+ margin_left=margin_left,
1709
+ margin_right=margin_right,
1710
+ margin_header=margin_header,
1711
+ margin_footer=margin_footer,
1712
+ page_number_start=page_number_start,
1713
+ use_first_page_header_footer=use_first_page_header_footer,
1714
+ flip_page_orientation=flip_page_orientation,
1715
+ content_direction=content_direction,
1716
+ column_count=column_count,
1717
+ column_spacing=column_spacing,
1718
+ column_separator_style=column_separator_style,
1719
+ )
1720
+ if not section_style:
1721
+ return None
1722
+
1723
+ return {
1724
+ "updateSectionStyle": {
1725
+ "range": _build_range(start_index, end_index),
1726
+ "sectionStyle": section_style,
1727
+ "fields": ",".join(fields),
1728
+ }
1729
+ }
1730
+
1731
+
1732
+ def create_create_header_footer_request(
1733
+ section_type: str,
1734
+ header_footer_type: str = "DEFAULT",
1735
+ section_break_index: Optional[int] = None,
1736
+ ) -> Dict[str, Any]:
1737
+ """Create a createHeader/createFooter request."""
1738
+ header_footer_type_upper = header_footer_type.upper()
1739
+ if header_footer_type_upper == "FIRST_PAGE_ONLY":
1740
+ header_footer_type_upper = "DEFAULT"
1741
+
1742
+ request: Dict[str, Any] = {"type": header_footer_type_upper}
1743
+ if section_break_index is not None:
1744
+ request["sectionBreakLocation"] = {"index": section_break_index}
1745
+
1746
+ if section_type == "header":
1747
+ return {"createHeader": request}
1748
+ if section_type == "footer":
1749
+ return {"createFooter": request}
1750
+ raise ValueError("section_type must be 'header' or 'footer'")
1751
+
1752
+
1753
+ def create_insert_table_row_request(
1754
+ table_start_index: int,
1755
+ row_index: int,
1756
+ insert_below: bool = True,
1757
+ tab_id: Optional[str] = None,
1758
+ ) -> Dict[str, Any]:
1759
+ """Build an insertTableRow request."""
1760
+ location: Dict[str, Any] = {"index": table_start_index}
1761
+ if tab_id:
1762
+ location["tabId"] = tab_id
1763
+ return {
1764
+ "insertTableRow": {
1765
+ "tableCellLocation": {
1766
+ "tableStartLocation": location,
1767
+ "rowIndex": row_index,
1768
+ "columnIndex": 0,
1769
+ },
1770
+ "insertBelow": insert_below,
1771
+ }
1772
+ }
1773
+
1774
+
1775
+ def create_delete_table_row_request(
1776
+ table_start_index: int,
1777
+ row_index: int,
1778
+ tab_id: Optional[str] = None,
1779
+ ) -> Dict[str, Any]:
1780
+ """Build a deleteTableRow request."""
1781
+ location: Dict[str, Any] = {"index": table_start_index}
1782
+ if tab_id:
1783
+ location["tabId"] = tab_id
1784
+ return {
1785
+ "deleteTableRow": {
1786
+ "tableCellLocation": {
1787
+ "tableStartLocation": location,
1788
+ "rowIndex": row_index,
1789
+ "columnIndex": 0,
1790
+ }
1791
+ }
1792
+ }
1793
+
1794
+
1795
+ def create_insert_table_column_request(
1796
+ table_start_index: int,
1797
+ column_index: int,
1798
+ insert_right: bool = True,
1799
+ tab_id: Optional[str] = None,
1800
+ ) -> Dict[str, Any]:
1801
+ """Build an insertTableColumn request."""
1802
+ location: Dict[str, Any] = {"index": table_start_index}
1803
+ if tab_id:
1804
+ location["tabId"] = tab_id
1805
+ return {
1806
+ "insertTableColumn": {
1807
+ "tableCellLocation": {
1808
+ "tableStartLocation": location,
1809
+ "rowIndex": 0,
1810
+ "columnIndex": column_index,
1811
+ },
1812
+ "insertRight": insert_right,
1813
+ }
1814
+ }
1815
+
1816
+
1817
+ def create_delete_table_column_request(
1818
+ table_start_index: int,
1819
+ column_index: int,
1820
+ tab_id: Optional[str] = None,
1821
+ ) -> Dict[str, Any]:
1822
+ """Build a deleteTableColumn request."""
1823
+ location: Dict[str, Any] = {"index": table_start_index}
1824
+ if tab_id:
1825
+ location["tabId"] = tab_id
1826
+ return {
1827
+ "deleteTableColumn": {
1828
+ "tableCellLocation": {
1829
+ "tableStartLocation": location,
1830
+ "rowIndex": 0,
1831
+ "columnIndex": column_index,
1832
+ }
1833
+ }
1834
+ }
1835
+
1836
+
1837
+ def _build_table_range(
1838
+ table_start_index: int,
1839
+ row_index: int,
1840
+ column_index: int,
1841
+ row_span: int,
1842
+ column_span: int,
1843
+ tab_id: Optional[str] = None,
1844
+ ) -> Dict[str, Any]:
1845
+ """Build a tableRange object used by merge/unmerge requests."""
1846
+ location: Dict[str, Any] = {"index": table_start_index}
1847
+ if tab_id:
1848
+ location["tabId"] = tab_id
1849
+ return {
1850
+ "tableRange": {
1851
+ "tableCellLocation": {
1852
+ "tableStartLocation": location,
1853
+ "rowIndex": row_index,
1854
+ "columnIndex": column_index,
1855
+ },
1856
+ "rowSpan": row_span,
1857
+ "columnSpan": column_span,
1858
+ }
1859
+ }
1860
+
1861
+
1862
+ def create_merge_table_cells_request(
1863
+ table_start_index: int,
1864
+ row_index: int,
1865
+ column_index: int,
1866
+ row_span: int,
1867
+ column_span: int,
1868
+ tab_id: Optional[str] = None,
1869
+ ) -> Dict[str, Any]:
1870
+ """Build a mergeTableCells request."""
1871
+ return {
1872
+ "mergeTableCells": _build_table_range(
1873
+ table_start_index, row_index, column_index, row_span, column_span, tab_id
1874
+ )
1875
+ }
1876
+
1877
+
1878
+ def create_unmerge_table_cells_request(
1879
+ table_start_index: int,
1880
+ row_index: int,
1881
+ column_index: int,
1882
+ row_span: int,
1883
+ column_span: int,
1884
+ tab_id: Optional[str] = None,
1885
+ ) -> Dict[str, Any]:
1886
+ """Build an unmergeTableCells request."""
1887
+ return {
1888
+ "unmergeTableCells": _build_table_range(
1889
+ table_start_index, row_index, column_index, row_span, column_span, tab_id
1890
+ )
1891
+ }
1892
+
1893
+
1894
+ def create_update_table_column_properties_request(
1895
+ table_start_index: int,
1896
+ column_indices: list,
1897
+ width: float = None,
1898
+ width_type: str = None,
1899
+ tab_id: Optional[str] = None,
1900
+ ) -> Optional[Dict[str, Any]]:
1901
+ """Build an updateTableColumnProperties request. Returns None if no properties set."""
1902
+ location: Dict[str, Any] = {"index": table_start_index}
1903
+ if tab_id:
1904
+ location["tabId"] = tab_id
1905
+
1906
+ properties: Dict[str, Any] = {}
1907
+ fields = []
1908
+
1909
+ if width is not None:
1910
+ properties["width"] = {"magnitude": width, "unit": "PT"}
1911
+ fields.append("width")
1912
+
1913
+ if width_type is not None:
1914
+ properties["widthType"] = width_type
1915
+ fields.append("widthType")
1916
+
1917
+ if not fields:
1918
+ return None
1919
+
1920
+ return {
1921
+ "updateTableColumnProperties": {
1922
+ "tableStartLocation": location,
1923
+ "columnIndices": column_indices,
1924
+ "tableColumnProperties": properties,
1925
+ "fields": ",".join(fields),
1926
+ }
1927
+ }
1928
+
1929
+
1930
+ def create_update_table_row_style_request(
1931
+ table_start_index: int,
1932
+ row_indices: list,
1933
+ min_row_height: float = None,
1934
+ tab_id: Optional[str] = None,
1935
+ ) -> Optional[Dict[str, Any]]:
1936
+ """Build an updateTableRowStyle request. Returns None if no properties set.
1937
+
1938
+ Args:
1939
+ table_start_index: Index of the table's start location.
1940
+ row_indices: Zero-based row indices to style (e.g. [0] for the header row).
1941
+ min_row_height: Minimum row height in points.
1942
+ tab_id: Optional tab ID.
1943
+
1944
+ Note: ``tableHeader`` is exposed on TableRowStyle when reading a document,
1945
+ but it cannot be updated through updateTableRowStyle. The Docs API rejects
1946
+ that field on this request with a 400 error ("Unallowed field: tableHeader").
1947
+ Use create_pin_table_header_rows_request instead.
1948
+
1949
+ Reference:
1950
+ https://developers.google.com/workspace/docs/api/reference/rest/v1/documents/request#UpdateTableRowStyleRequest
1951
+ https://developers.google.com/workspace/docs/api/reference/rest/v1/documents#TableRowStyle
1952
+ """
1953
+ location: Dict[str, Any] = {"index": table_start_index}
1954
+ if tab_id:
1955
+ location["tabId"] = tab_id
1956
+
1957
+ row_style: Dict[str, Any] = {}
1958
+ fields = []
1959
+
1960
+ if min_row_height is not None:
1961
+ row_style["minRowHeight"] = _build_dimension(min_row_height)
1962
+ fields.append("minRowHeight")
1963
+
1964
+ if not fields:
1965
+ return None
1966
+
1967
+ return {
1968
+ "updateTableRowStyle": {
1969
+ "tableStartLocation": location,
1970
+ "rowIndices": row_indices,
1971
+ "tableRowStyle": row_style,
1972
+ "fields": ",".join(fields),
1973
+ }
1974
+ }
1975
+
1976
+
1977
+ def create_pin_table_header_rows_request(
1978
+ table_start_index: int,
1979
+ pinned_header_rows_count: int,
1980
+ tab_id: Optional[str] = None,
1981
+ ) -> Dict[str, Any]:
1982
+ """Build a pinTableHeaderRows request to repeat the leading table rows on each page.
1983
+
1984
+ This is a dedicated Docs API request distinct from updateTableRowStyle. Although
1985
+ TableRowStyle reports whether a row is a header, the writable request sets the
1986
+ number of leading rows to pin for the table as a whole (0 unpins all rows).
1987
+
1988
+ Args:
1989
+ table_start_index: Index of the table's start location.
1990
+ pinned_header_rows_count: Number of leading rows to pin as a repeating header.
1991
+ tab_id: Optional tab ID.
1992
+
1993
+ Reference:
1994
+ https://developers.google.com/workspace/docs/api/reference/rest/v1/documents/request#PinTableHeaderRowsRequest
1995
+ """
1996
+ if pinned_header_rows_count < 0:
1997
+ raise ValueError("pinned_header_rows_count must be non-negative")
1998
+
1999
+ location: Dict[str, Any] = {"index": table_start_index}
2000
+ if tab_id:
2001
+ location["tabId"] = tab_id
2002
+
2003
+ return {
2004
+ "pinTableHeaderRows": {
2005
+ "tableStartLocation": location,
2006
+ "pinnedHeaderRowsCount": pinned_header_rows_count,
2007
+ }
2008
+ }
2009
+
2010
+
2011
+ def validate_operation(operation: Dict[str, Any]) -> tuple[bool, str]:
2012
+ """
2013
+ Validate a batch operation dictionary.
2014
+
2015
+ Args:
2016
+ operation: Operation dictionary to validate
2017
+
2018
+ Returns:
2019
+ Tuple of (is_valid, error_message)
2020
+ """
2021
+ op_type = operation.get("type")
2022
+ if not op_type:
2023
+ return False, "Missing 'type' field"
2024
+
2025
+ # Validate required fields for each operation type
2026
+ required_fields = {
2027
+ "insert_text": ["text"],
2028
+ "delete_text": ["start_index", "end_index"],
2029
+ "replace_text": ["start_index", "end_index", "text"],
2030
+ "format_text": ["start_index", "end_index"],
2031
+ "update_paragraph_style": ["start_index", "end_index"],
2032
+ "update_table_cell_style": ["table_start_index"],
2033
+ "insert_table": ["rows", "columns"],
2034
+ "insert_page_break": [],
2035
+ "insert_section_break": [],
2036
+ "find_replace": ["find_text", "replace_text"],
2037
+ "create_bullet_list": ["start_index", "end_index"],
2038
+ "create_named_range": ["name", "start_index", "end_index"],
2039
+ "replace_named_range_content": ["text"],
2040
+ "delete_named_range": [],
2041
+ "update_document_style": [],
2042
+ "update_section_style": ["start_index", "end_index"],
2043
+ "create_header_footer": ["section_type"],
2044
+ "insert_image": ["image_uri"],
2045
+ "insert_person": ["email"],
2046
+ "create_dropdown_definition": ["title", "options"],
2047
+ "insert_dropdown": ["dropdown_definition_id"],
2048
+ "insert_date": ["date"],
2049
+ "insert_doc_tab": ["title", "index"],
2050
+ "delete_doc_tab": ["tab_id"],
2051
+ "update_doc_tab": ["tab_id", "title"],
2052
+ "insert_table_row": ["table_start_index", "row_index"],
2053
+ "delete_table_row": ["table_start_index", "row_index"],
2054
+ "insert_table_column": ["table_start_index", "column_index"],
2055
+ "delete_table_column": ["table_start_index", "column_index"],
2056
+ "merge_table_cells": [
2057
+ "table_start_index",
2058
+ "row_index",
2059
+ "column_index",
2060
+ "row_span",
2061
+ "column_span",
2062
+ ],
2063
+ "unmerge_table_cells": [
2064
+ "table_start_index",
2065
+ "row_index",
2066
+ "column_index",
2067
+ "row_span",
2068
+ "column_span",
2069
+ ],
2070
+ "update_table_column_properties": ["table_start_index", "column_indices"],
2071
+ "update_table_row_style": ["table_start_index", "row_indices"],
2072
+ "pin_table_header_rows": ["table_start_index", "pinned_header_rows_count"],
2073
+ }
2074
+
2075
+ if op_type not in required_fields:
2076
+ return False, f"Unsupported operation type: {op_type or 'None'}"
2077
+
2078
+ for field in required_fields[op_type]:
2079
+ if field not in operation:
2080
+ return False, f"Missing required field: {field}"
2081
+
2082
+ if op_type in {
2083
+ "insert_text",
2084
+ "insert_table",
2085
+ "insert_page_break",
2086
+ "insert_section_break",
2087
+ "insert_image",
2088
+ "insert_person",
2089
+ "insert_date",
2090
+ "insert_dropdown",
2091
+ }:
2092
+ provided = sum(
2093
+ [operation.get("index") is not None, bool(operation.get("end_of_segment"))]
2094
+ + [
2095
+ operation.get(field) is not None
2096
+ for field in ("after_heading", "before_heading", "anchor_text")
2097
+ ]
2098
+ )
2099
+ if provided != 1:
2100
+ return (
2101
+ False,
2102
+ "Provide exactly one of 'index', 'end_of_segment=true', "
2103
+ "'after_heading', 'before_heading' or 'anchor_text'.",
2104
+ )
2105
+
2106
+ return True, ""
2107
+
2108
+
2109
+ # Unicode OBJECT REPLACEMENT CHARACTER. Stands in for a paragraph element that
2110
+ # occupies a document index but carries no text (inline object, page break,
2111
+ # horizontal rule, footnote reference, ...), so extracted text keeps the same
2112
+ # length as the document range it came from.
2113
+ OBJECT_PLACEHOLDER = "\ufffc"
2114
+
2115
+ TAB_HEADER_FORMAT = "\n--- TAB: {tab_name} (ID: {tab_id}) ---\n"
2116
+
2117
+
2118
+ def utf16_length(text: str) -> int:
2119
+ """Number of Google Docs index units in Unicode text (two for non-BMP characters)."""
2120
+ return len(text.encode("utf-16-le")) // 2
2121
+
2122
+
2123
+ def _paragraph_element_text(element: Dict[str, Any]) -> str:
2124
+ """Text a single paragraph element contributes to index-aligned output.
2125
+
2126
+ A textRun contributes its content verbatim; convert Python search offsets
2127
+ with utf16_length(text[:offset]) before constructing a Docs range. Every
2128
+ other element type is matched by its own index span rather than by name: the Docs API can add
2129
+ element types, and a type this code has not heard of still occupies indices,
2130
+ so deriving the width from startIndex/endIndex keeps alignment correct
2131
+ without a list to maintain.
2132
+ """
2133
+ text_run = element.get("textRun", {})
2134
+ if text_run and "content" in text_run:
2135
+ return text_run["content"]
2136
+
2137
+ span = element.get("endIndex", 0) - element.get("startIndex", 0)
2138
+ return OBJECT_PLACEHOLDER * max(span, 0)
2139
+
2140
+
2141
+ def extract_text_from_elements(
2142
+ elements: List[Dict[str, Any]],
2143
+ tab_name: Optional[str] = None,
2144
+ tab_id: Optional[str] = None,
2145
+ depth: int = 0,
2146
+ ) -> str:
2147
+ """Extract text from Google Docs structural elements, keeping indices aligned.
2148
+
2149
+ Empty paragraphs are preserved: a paragraph whose only content is a newline
2150
+ still occupies an index, so dropping it shifts every subsequent offset and
2151
+ silently corrupts any index computed by searching the result.
2152
+
2153
+ Search offsets are Python code points: use utf16_length(text[:offset])
2154
+ to convert them to Docs UTF-16 units before adding the range start index.
2155
+ A tab header, when requested, must be excluded from that conversion.
2156
+
2157
+ Table cell text is included but is not index-aligned; the table, row and cell
2158
+ structure itself occupies indices that are not represented here.
2159
+ """
2160
+ if depth > 5:
2161
+ return ""
2162
+
2163
+ text_lines = []
2164
+ if tab_name:
2165
+ text_lines.append(TAB_HEADER_FORMAT.format(tab_name=tab_name, tab_id=tab_id))
2166
+
2167
+ for element in elements:
2168
+ if "paragraph" in element:
2169
+ para_elements = element.get("paragraph", {}).get("elements", [])
2170
+ text_lines.append(
2171
+ "".join(_paragraph_element_text(pe) for pe in para_elements)
2172
+ )
2173
+ elif "table" in element:
2174
+ for row in element.get("table", {}).get("tableRows", []):
2175
+ for cell in row.get("tableCells", []):
2176
+ text_lines.append(
2177
+ extract_text_from_elements(
2178
+ cell.get("content", []), depth=depth + 1
2179
+ )
2180
+ )
2181
+
2182
+ return "".join(text_lines)
2183
+
2184
+
2185
+ def process_tab_hierarchy(tab: Dict[str, Any], level: int = 0) -> str:
2186
+ """Extract text from a tab and its nested child tabs, depth-first."""
2187
+ tab_text = ""
2188
+
2189
+ if "documentTab" in tab:
2190
+ props = tab.get("tabProperties", {})
2191
+ tab_title = props.get("title", "Untitled Tab")
2192
+ tab_id = props.get("tabId", "Unknown ID")
2193
+ if level > 0:
2194
+ tab_title = " " * level + f"{tab_title}"
2195
+ tab_body = tab.get("documentTab", {}).get("body", {}).get("content", [])
2196
+ tab_text += extract_text_from_elements(tab_body, tab_title, tab_id)
2197
+
2198
+ for child_tab in tab.get("childTabs", []):
2199
+ tab_text += process_tab_hierarchy(child_tab, level + 1)
2200
+
2201
+ return tab_text