@tiens.nguyen/gu-cli 1.0.902 → 1.0.904

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 (187) hide show
  1. package/NOTICE +18 -0
  2. package/package.json +3 -2
  3. package/skills/core/deep-research/SKILL.md +51 -0
  4. package/skills/core/docx/LICENSE.txt +202 -0
  5. package/skills/core/docx/SKILL.md +97 -0
  6. package/skills/core/docx/scripts/__init__.py +1 -0
  7. package/skills/core/docx/scripts/accept_changes.py +135 -0
  8. package/skills/core/docx/scripts/comment.py +368 -0
  9. package/skills/core/docx/scripts/merge_runs.py +310 -0
  10. package/skills/core/docx/scripts/office/helpers/__init__.py +121 -0
  11. package/skills/core/docx/scripts/office/helpers/pptx_chart.py +283 -0
  12. package/skills/core/docx/scripts/office/helpers/pptx_slide.py +100 -0
  13. package/skills/core/docx/scripts/office/helpers/pptx_theme.py +114 -0
  14. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-chart.xsd +1499 -0
  15. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-chartDrawing.xsd +146 -0
  16. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-diagram.xsd +1085 -0
  17. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-lockedCanvas.xsd +11 -0
  18. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-main.xsd +3081 -0
  19. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-picture.xsd +23 -0
  20. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-spreadsheetDrawing.xsd +185 -0
  21. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-wordprocessingDrawing.xsd +287 -0
  22. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/pml.xsd +1676 -0
  23. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-additionalCharacteristics.xsd +28 -0
  24. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-bibliography.xsd +144 -0
  25. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-commonSimpleTypes.xsd +174 -0
  26. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-customXmlDataProperties.xsd +25 -0
  27. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-customXmlSchemaProperties.xsd +18 -0
  28. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsd +59 -0
  29. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsd +56 -0
  30. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesVariantTypes.xsd +195 -0
  31. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-math.xsd +582 -0
  32. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-relationshipReference.xsd +25 -0
  33. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/sml.xsd +4439 -0
  34. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-main.xsd +570 -0
  35. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-officeDrawing.xsd +509 -0
  36. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-presentationDrawing.xsd +12 -0
  37. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-spreadsheetDrawing.xsd +108 -0
  38. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-wordprocessingDrawing.xsd +96 -0
  39. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/wml.xsd +3646 -0
  40. package/skills/core/docx/scripts/office/schemas/ISO-IEC29500-4_2016/xml.xsd +116 -0
  41. package/skills/core/docx/scripts/office/schemas/ecma/fouth-edition/opc-contentTypes.xsd +42 -0
  42. package/skills/core/docx/scripts/office/schemas/ecma/fouth-edition/opc-coreProperties.xsd +50 -0
  43. package/skills/core/docx/scripts/office/schemas/ecma/fouth-edition/opc-digSig.xsd +49 -0
  44. package/skills/core/docx/scripts/office/schemas/ecma/fouth-edition/opc-relationships.xsd +33 -0
  45. package/skills/core/docx/scripts/office/schemas/mce/mc.xsd +75 -0
  46. package/skills/core/docx/scripts/office/schemas/microsoft/wml-2010.xsd +560 -0
  47. package/skills/core/docx/scripts/office/schemas/microsoft/wml-2012.xsd +67 -0
  48. package/skills/core/docx/scripts/office/schemas/microsoft/wml-2018.xsd +14 -0
  49. package/skills/core/docx/scripts/office/schemas/microsoft/wml-cex-2018.xsd +20 -0
  50. package/skills/core/docx/scripts/office/schemas/microsoft/wml-cid-2016.xsd +13 -0
  51. package/skills/core/docx/scripts/office/schemas/microsoft/wml-sdtdatahash-2020.xsd +4 -0
  52. package/skills/core/docx/scripts/office/schemas/microsoft/wml-symex-2015.xsd +8 -0
  53. package/skills/core/docx/scripts/office/soffice.py +192 -0
  54. package/skills/core/docx/scripts/office/validate.py +210 -0
  55. package/skills/core/docx/scripts/office/validators/__init__.py +15 -0
  56. package/skills/core/docx/scripts/office/validators/base.py +874 -0
  57. package/skills/core/docx/scripts/office/validators/docx.py +519 -0
  58. package/skills/core/docx/scripts/office/validators/pptx.py +549 -0
  59. package/skills/core/docx/scripts/office/validators/redlining.py +461 -0
  60. package/skills/core/docx/scripts/templates/comments.xml +3 -0
  61. package/skills/core/docx/scripts/templates/commentsExtended.xml +3 -0
  62. package/skills/core/docx/scripts/templates/commentsExtensible.xml +3 -0
  63. package/skills/core/docx/scripts/templates/commentsIds.xml +3 -0
  64. package/skills/core/docx/scripts/templates/people.xml +3 -0
  65. package/skills/core/pdf/FORMS.md +294 -0
  66. package/skills/core/pdf/LICENSE.txt +202 -0
  67. package/skills/core/pdf/REFERENCE.md +613 -0
  68. package/skills/core/pdf/SKILL.md +314 -0
  69. package/skills/core/pdf/scripts/check_bounding_boxes.py +65 -0
  70. package/skills/core/pdf/scripts/check_fillable_fields.py +11 -0
  71. package/skills/core/pdf/scripts/convert_pdf_to_images.py +33 -0
  72. package/skills/core/pdf/scripts/create_validation_image.py +37 -0
  73. package/skills/core/pdf/scripts/extract_form_field_info.py +122 -0
  74. package/skills/core/pdf/scripts/extract_form_structure.py +115 -0
  75. package/skills/core/pdf/scripts/fill_fillable_fields.py +98 -0
  76. package/skills/core/pdf/scripts/fill_pdf_form_with_annotations.py +107 -0
  77. package/skills/core/pptx/LICENSE.txt +202 -0
  78. package/skills/core/pptx/SKILL.md +275 -0
  79. package/skills/core/pptx/scripts/__init__.py +0 -0
  80. package/skills/core/pptx/scripts/add_slide.py +463 -0
  81. package/skills/core/pptx/scripts/apply_theme.js +107 -0
  82. package/skills/core/pptx/scripts/clean.py +309 -0
  83. package/skills/core/pptx/scripts/office/helpers/__init__.py +121 -0
  84. package/skills/core/pptx/scripts/office/helpers/pptx_chart.py +283 -0
  85. package/skills/core/pptx/scripts/office/helpers/pptx_slide.py +100 -0
  86. package/skills/core/pptx/scripts/office/helpers/pptx_theme.py +114 -0
  87. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-chart.xsd +1499 -0
  88. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-chartDrawing.xsd +146 -0
  89. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-diagram.xsd +1085 -0
  90. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-lockedCanvas.xsd +11 -0
  91. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-main.xsd +3081 -0
  92. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-picture.xsd +23 -0
  93. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-spreadsheetDrawing.xsd +185 -0
  94. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-wordprocessingDrawing.xsd +287 -0
  95. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/pml.xsd +1676 -0
  96. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-additionalCharacteristics.xsd +28 -0
  97. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-bibliography.xsd +144 -0
  98. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-commonSimpleTypes.xsd +174 -0
  99. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-customXmlDataProperties.xsd +25 -0
  100. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-customXmlSchemaProperties.xsd +18 -0
  101. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsd +59 -0
  102. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsd +56 -0
  103. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesVariantTypes.xsd +195 -0
  104. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-math.xsd +582 -0
  105. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-relationshipReference.xsd +25 -0
  106. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/sml.xsd +4439 -0
  107. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-main.xsd +570 -0
  108. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-officeDrawing.xsd +509 -0
  109. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-presentationDrawing.xsd +12 -0
  110. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-spreadsheetDrawing.xsd +108 -0
  111. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-wordprocessingDrawing.xsd +96 -0
  112. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/wml.xsd +3646 -0
  113. package/skills/core/pptx/scripts/office/schemas/ISO-IEC29500-4_2016/xml.xsd +116 -0
  114. package/skills/core/pptx/scripts/office/schemas/ecma/fouth-edition/opc-contentTypes.xsd +42 -0
  115. package/skills/core/pptx/scripts/office/schemas/ecma/fouth-edition/opc-coreProperties.xsd +50 -0
  116. package/skills/core/pptx/scripts/office/schemas/ecma/fouth-edition/opc-digSig.xsd +49 -0
  117. package/skills/core/pptx/scripts/office/schemas/ecma/fouth-edition/opc-relationships.xsd +33 -0
  118. package/skills/core/pptx/scripts/office/schemas/mce/mc.xsd +75 -0
  119. package/skills/core/pptx/scripts/office/schemas/microsoft/wml-2010.xsd +560 -0
  120. package/skills/core/pptx/scripts/office/schemas/microsoft/wml-2012.xsd +67 -0
  121. package/skills/core/pptx/scripts/office/schemas/microsoft/wml-2018.xsd +14 -0
  122. package/skills/core/pptx/scripts/office/schemas/microsoft/wml-cex-2018.xsd +20 -0
  123. package/skills/core/pptx/scripts/office/schemas/microsoft/wml-cid-2016.xsd +13 -0
  124. package/skills/core/pptx/scripts/office/schemas/microsoft/wml-sdtdatahash-2020.xsd +4 -0
  125. package/skills/core/pptx/scripts/office/schemas/microsoft/wml-symex-2015.xsd +8 -0
  126. package/skills/core/pptx/scripts/office/soffice.py +192 -0
  127. package/skills/core/pptx/scripts/office/validate.py +210 -0
  128. package/skills/core/pptx/scripts/office/validators/__init__.py +15 -0
  129. package/skills/core/pptx/scripts/office/validators/base.py +874 -0
  130. package/skills/core/pptx/scripts/office/validators/docx.py +519 -0
  131. package/skills/core/pptx/scripts/office/validators/pptx.py +549 -0
  132. package/skills/core/pptx/scripts/office/validators/redlining.py +461 -0
  133. package/skills/core/pptx/scripts/slide_text.py +132 -0
  134. package/skills/core/pptx/scripts/thumbnail.py +311 -0
  135. package/skills/core/xlsx/LICENSE.txt +202 -0
  136. package/skills/core/xlsx/SKILL.md +99 -0
  137. package/skills/core/xlsx/scripts/office/helpers/__init__.py +121 -0
  138. package/skills/core/xlsx/scripts/office/helpers/pptx_chart.py +283 -0
  139. package/skills/core/xlsx/scripts/office/helpers/pptx_slide.py +100 -0
  140. package/skills/core/xlsx/scripts/office/helpers/pptx_theme.py +114 -0
  141. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-chart.xsd +1499 -0
  142. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-chartDrawing.xsd +146 -0
  143. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-diagram.xsd +1085 -0
  144. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-lockedCanvas.xsd +11 -0
  145. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-main.xsd +3081 -0
  146. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-picture.xsd +23 -0
  147. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-spreadsheetDrawing.xsd +185 -0
  148. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-wordprocessingDrawing.xsd +287 -0
  149. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/pml.xsd +1676 -0
  150. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-additionalCharacteristics.xsd +28 -0
  151. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-bibliography.xsd +144 -0
  152. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-commonSimpleTypes.xsd +174 -0
  153. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-customXmlDataProperties.xsd +25 -0
  154. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-customXmlSchemaProperties.xsd +18 -0
  155. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsd +59 -0
  156. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsd +56 -0
  157. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesVariantTypes.xsd +195 -0
  158. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-math.xsd +582 -0
  159. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-relationshipReference.xsd +25 -0
  160. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/sml.xsd +4439 -0
  161. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-main.xsd +570 -0
  162. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-officeDrawing.xsd +509 -0
  163. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-presentationDrawing.xsd +12 -0
  164. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-spreadsheetDrawing.xsd +108 -0
  165. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-wordprocessingDrawing.xsd +96 -0
  166. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/wml.xsd +3646 -0
  167. package/skills/core/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/xml.xsd +116 -0
  168. package/skills/core/xlsx/scripts/office/schemas/ecma/fouth-edition/opc-contentTypes.xsd +42 -0
  169. package/skills/core/xlsx/scripts/office/schemas/ecma/fouth-edition/opc-coreProperties.xsd +50 -0
  170. package/skills/core/xlsx/scripts/office/schemas/ecma/fouth-edition/opc-digSig.xsd +49 -0
  171. package/skills/core/xlsx/scripts/office/schemas/ecma/fouth-edition/opc-relationships.xsd +33 -0
  172. package/skills/core/xlsx/scripts/office/schemas/mce/mc.xsd +75 -0
  173. package/skills/core/xlsx/scripts/office/schemas/microsoft/wml-2010.xsd +560 -0
  174. package/skills/core/xlsx/scripts/office/schemas/microsoft/wml-2012.xsd +67 -0
  175. package/skills/core/xlsx/scripts/office/schemas/microsoft/wml-2018.xsd +14 -0
  176. package/skills/core/xlsx/scripts/office/schemas/microsoft/wml-cex-2018.xsd +20 -0
  177. package/skills/core/xlsx/scripts/office/schemas/microsoft/wml-cid-2016.xsd +13 -0
  178. package/skills/core/xlsx/scripts/office/schemas/microsoft/wml-sdtdatahash-2020.xsd +4 -0
  179. package/skills/core/xlsx/scripts/office/schemas/microsoft/wml-symex-2015.xsd +8 -0
  180. package/skills/core/xlsx/scripts/office/soffice.py +192 -0
  181. package/skills/core/xlsx/scripts/office/validate.py +210 -0
  182. package/skills/core/xlsx/scripts/office/validators/__init__.py +15 -0
  183. package/skills/core/xlsx/scripts/office/validators/base.py +874 -0
  184. package/skills/core/xlsx/scripts/office/validators/docx.py +519 -0
  185. package/skills/core/xlsx/scripts/office/validators/pptx.py +549 -0
  186. package/skills/core/xlsx/scripts/office/validators/redlining.py +461 -0
  187. package/skills/core/xlsx/scripts/recalc.py +456 -0
@@ -0,0 +1,463 @@
1
+ """Add a slide to a PPTX: duplicate an existing slide or instantiate a layout.
2
+
3
+ Does all of the package bookkeeping, so the deck stays valid:
4
+ - writes the new ppt/slides/slideN.xml (and its .rels, minus any
5
+ notesSlide reference, so the source's speaker notes aren't shared)
6
+ - registers it in [Content_Types].xml
7
+ - adds a slide relationship with a fresh rId to presentation.xml.rels
8
+ - inserts <p:sldId id="..." r:id="..."/> with a fresh id into
9
+ <p:sldIdLst> — at the end, or after --after SLIDE
10
+ - counts the new slide in docProps/app.xml
11
+
12
+ Works on an unpacked directory (during an editing session) or directly on a
13
+ .pptx/.potx file (extracted to a temp dir, then rezipped atomically; the
14
+ temp dir is discarded, so unpack the output if you still need to edit the
15
+ new slide's content).
16
+
17
+ Usage:
18
+ python add_slide.py unpacked/ slide2.xml # duplicate slide2
19
+ python add_slide.py unpacked/ slideLayout3.xml # new slide from a layout
20
+ python add_slide.py unpacked/ slide2.xml --after slide2.xml
21
+ python add_slide.py deck.pptx slide2.xml # rewrite deck.pptx in place
22
+ python add_slide.py deck.pptx slide2.xml -o out.pptx
23
+
24
+ A duplicated slide still holds the source's content: edit ppt/slides/slideN.xml
25
+ (printed on success) to change it. To list layouts: ls <dir>/ppt/slideLayouts/
26
+ """
27
+
28
+ import argparse
29
+ import posixpath
30
+ import re
31
+ import shutil
32
+ import sys
33
+ from typing import NoReturn
34
+ import tempfile
35
+ import zipfile
36
+ from pathlib import Path
37
+ from xml.parsers.expat import ExpatError
38
+
39
+ import defusedxml.minidom
40
+ from defusedxml.common import DefusedXmlException
41
+
42
+ from office.helpers import opc_target, rezip, safe_extract
43
+
44
+ MINIMAL_SLIDE_XML = '''<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
45
+ <p:sld xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">
46
+ <p:cSld>
47
+ <p:spTree>
48
+ <p:nvGrpSpPr>
49
+ <p:cNvPr id="1" name=""/>
50
+ <p:cNvGrpSpPr/>
51
+ <p:nvPr/>
52
+ </p:nvGrpSpPr>
53
+ <p:grpSpPr>
54
+ <a:xfrm>
55
+ <a:off x="0" y="0"/>
56
+ <a:ext cx="0" cy="0"/>
57
+ <a:chOff x="0" y="0"/>
58
+ <a:chExt cx="0" cy="0"/>
59
+ </a:xfrm>
60
+ </p:grpSpPr>
61
+ </p:spTree>
62
+ </p:cSld>
63
+ <p:clrMapOvr>
64
+ <a:masterClrMapping/>
65
+ </p:clrMapOvr>
66
+ </p:sld>'''
67
+
68
+ SHARED_PART_TYPES = ("chart", "diagramData", "oleObject", "package")
69
+
70
+ NOTES_SLIDE_TYPE_RE = re.compile(r"""Type=["'][^"']*/relationships/notesSlide["']""")
71
+ TAGS_TYPE_RE = re.compile(r"""Type=["'][^"']*/relationships/tags["']""")
72
+ TAGS_CONTENT_TYPE = "application/vnd.openxmlformats-officedocument.presentationml.tags+xml"
73
+ RELATIONSHIP_RE = re.compile(r"<Relationship\b[^>]*?(?:/>|>.*?</Relationship\s*>)", re.DOTALL)
74
+
75
+ SLIDE_ID_MIN = 256
76
+ SLIDE_ID_MAX = 2147483647
77
+
78
+
79
+ def _die(msg: str) -> NoReturn:
80
+ print(f"Error: {msg}", file=sys.stderr)
81
+ sys.exit(1)
82
+
83
+
84
+ def get_next_slide_number(slides_dir: Path) -> int:
85
+ existing = [int(m.group(1)) for f in slides_dir.glob("slide*.xml")
86
+ if (m := re.match(r"slide(\d+)\.xml", f.name))]
87
+ return max(existing) + 1 if existing else 1
88
+
89
+
90
+ def parse_source(source: str) -> tuple[str, str | None]:
91
+ if source.startswith("slideLayout") and source.endswith(".xml"):
92
+ return ("layout", source)
93
+
94
+ return ("slide", None)
95
+
96
+
97
+ def create_slide_from_layout(unpacked_dir: Path, layout_file: str, after: str | None = None) -> str:
98
+ slides_dir = unpacked_dir / "ppt" / "slides"
99
+ rels_dir = slides_dir / "_rels"
100
+ layout_path = unpacked_dir / "ppt" / "slideLayouts" / layout_file
101
+
102
+ if not layout_path.exists():
103
+ _die(f"{layout_path} not found")
104
+
105
+ next_num = get_next_slide_number(slides_dir)
106
+ dest = f"slide{next_num}.xml"
107
+ after_rid = _precheck_registration(unpacked_dir, after, dest)
108
+ slides_dir.mkdir(parents=True, exist_ok=True)
109
+
110
+ (slides_dir / dest).write_text(MINIMAL_SLIDE_XML, encoding="utf-8")
111
+
112
+ rels_dir.mkdir(exist_ok=True)
113
+ rels_xml = f'''<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
114
+ <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
115
+ <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/{layout_file}"/>
116
+ </Relationships>'''
117
+ (rels_dir / f"{dest}.rels").write_text(rels_xml, encoding="utf-8")
118
+
119
+ _register_slide(unpacked_dir, dest, layout_file, after_rid)
120
+ return dest
121
+
122
+
123
+ def duplicate_slide(unpacked_dir: Path, source: str, after: str | None = None) -> str:
124
+ slides_dir = unpacked_dir / "ppt" / "slides"
125
+ rels_dir = slides_dir / "_rels"
126
+ source_slide = slides_dir / source
127
+
128
+ if not source_slide.exists():
129
+ _die(f"{source_slide} not found")
130
+
131
+ next_num = get_next_slide_number(slides_dir)
132
+ dest = f"slide{next_num}.xml"
133
+ after_rid = _precheck_registration(unpacked_dir, after, dest)
134
+
135
+ shutil.copy2(source_slide, slides_dir / dest)
136
+
137
+ source_rels = rels_dir / f"{source}.rels"
138
+ shared_parts: list[str] = []
139
+ if source_rels.exists():
140
+ dest_rels = rels_dir / f"{dest}.rels"
141
+ shutil.copy2(source_rels, dest_rels)
142
+ rels_content = dest_rels.read_text(encoding="utf-8")
143
+ rels_content = RELATIONSHIP_RE.sub(
144
+ lambda m: "" if NOTES_SLIDE_TYPE_RE.search(m.group(0)) else m.group(0),
145
+ rels_content,
146
+ )
147
+ rels_content = RELATIONSHIP_RE.sub(
148
+ lambda m: _with_own_tags_part(unpacked_dir, m.group(0), f"ppt/slides/{dest}")
149
+ if TAGS_TYPE_RE.search(m.group(0)) else m.group(0),
150
+ rels_content,
151
+ )
152
+ dest_rels.write_text(rels_content, encoding="utf-8")
153
+ shared_parts = sorted({
154
+ t for t in re.findall(r'Type="[^"]*/relationships/(\w+)"', rels_content)
155
+ if t in SHARED_PART_TYPES
156
+ })
157
+
158
+ _register_slide(unpacked_dir, dest, source, after_rid)
159
+ if shared_parts:
160
+ print(
161
+ f"Note: {dest} shares its {', '.join(shared_parts)} part(s) with {source} "
162
+ f"(they are referenced, not copied) — editing those parts changes both slides"
163
+ )
164
+ return dest
165
+
166
+
167
+ def _with_own_tags_part(unpacked_dir: Path, relationship: str, slide_part: str) -> str:
168
+ target = re.search(r"""Target=["']([^"']*)["']""", relationship)
169
+ try:
170
+ source = opc_target(target.group(1), slide_part) if target else None
171
+ except ValueError:
172
+ source = None
173
+ if source is None or not (unpacked_dir / source).is_file():
174
+ return relationship
175
+
176
+ tags_dir = (unpacked_dir / source).parent
177
+ content_types_path = unpacked_dir / "[Content_Types].xml"
178
+ content_types = content_types_path.read_text(encoding="utf-8")
179
+ names = [f.name for f in tags_dir.iterdir()] + re.findall(r"""PartName=["'][^"']*/([^/"']+)["']""", content_types)
180
+ taken = [int(m.group(1)) for name in names if (m := re.fullmatch(r"tag(\d{1,9})\.xml", name, re.I))]
181
+ copy = tags_dir / f"tag{max(taken, default=0) + 1}.xml"
182
+ shutil.copy2(unpacked_dir / source, copy)
183
+
184
+ part = copy.relative_to(unpacked_dir).as_posix()
185
+ override = f'<Override PartName="/{part}" ContentType="{TAGS_CONTENT_TYPE}"/>'
186
+ content_types_path.write_text(
187
+ content_types.replace("</Types>", f" {override}\n</Types>"), encoding="utf-8"
188
+ )
189
+ relative = posixpath.relpath(part, posixpath.dirname(slide_part))
190
+ return relationship.replace(target.group(0), f'Target="{relative}"')
191
+
192
+
193
+ def _precheck_registration(unpacked_dir: Path, after: str | None, dest: str) -> str | None:
194
+ pres_path = unpacked_dir / "ppt" / "presentation.xml"
195
+ if not pres_path.exists():
196
+ _die(f"{pres_path} not found — is this an unpacked PPTX?")
197
+ xml = pres_path.read_text(encoding="utf-8")
198
+
199
+ has_slot = (
200
+ "</p:sldIdLst>" in xml
201
+ or re.search(r"<p:sldIdLst\s*/>", xml)
202
+ or "</p:sldMasterIdLst>" in xml
203
+ )
204
+ if not has_slot:
205
+ _die("presentation.xml has no <p:sldIdLst> (or <p:sldMasterIdLst> to anchor a new one)")
206
+
207
+ stale = []
208
+ content_types = unpacked_dir / "[Content_Types].xml"
209
+ if content_types.exists() and f'PartName="/ppt/slides/{dest}"' in content_types.read_text(encoding="utf-8"):
210
+ stale.append("[Content_Types].xml")
211
+ pres_rels = unpacked_dir / "ppt" / "_rels" / "presentation.xml.rels"
212
+ if pres_rels.exists() and _find_slide_relationship(
213
+ pres_rels.read_text(encoding="utf-8"), dest
214
+ ):
215
+ stale.append("presentation.xml.rels")
216
+ if stale:
217
+ _die(
218
+ f"{dest} is still registered in {' and '.join(stale)} but absent from ppt/slides/ — "
219
+ f"run clean.py first"
220
+ )
221
+
222
+ if not after:
223
+ return None
224
+ after_rid = _rid_for_slide(unpacked_dir, after)
225
+ if not re.search(rf'<p:sldId\b[^>]*r:id="{re.escape(after_rid)}"[^>]*>', xml):
226
+ _die(f"{after} ({after_rid}) is not listed in <p:sldIdLst>")
227
+ return after_rid
228
+
229
+
230
+ def _register_slide(unpacked_dir: Path, dest: str, source_desc: str, after_rid: str | None) -> None:
231
+ _add_to_content_types(unpacked_dir, dest)
232
+ rid = _add_to_presentation_rels(unpacked_dir, dest)
233
+ slide_id = _get_next_slide_id(unpacked_dir)
234
+ pos, total = _insert_into_sld_id_lst(unpacked_dir, slide_id, rid, after_rid)
235
+
236
+ _count_slide_in_app_properties(unpacked_dir, pos)
237
+
238
+ print(f"Created ppt/slides/{dest} from {source_desc}")
239
+ print(
240
+ f'Inserted <p:sldId id="{slide_id}" r:id="{rid}"/> into <p:sldIdLst> '
241
+ f"at position {pos} of {total}"
242
+ )
243
+
244
+
245
+ def _count_slide_in_app_properties(unpacked_dir: Path, position: int) -> None:
246
+ path = unpacked_dir / "docProps" / "app.xml"
247
+ if not path.is_file():
248
+ return
249
+ try:
250
+ dom = defusedxml.minidom.parse(str(path))
251
+ slides = _only_child(dom.documentElement, "Slides")
252
+ was = int(slides.firstChild.data)
253
+ if not _add_slide_title(dom, was, position):
254
+ return
255
+ except (AttributeError, LookupError, ValueError, TypeError, OSError, ExpatError, DefusedXmlException):
256
+ return
257
+ slides.firstChild.data = str(was + 1)
258
+ path.write_bytes(dom.toxml(encoding="UTF-8", standalone=dom.standalone))
259
+
260
+
261
+ def _add_slide_title(dom, was: int, position: int) -> bool:
262
+ heading_pairs = _only_child(dom.documentElement, "HeadingPairs")
263
+ titles_of_parts = _only_child(dom.documentElement, "TitlesOfParts")
264
+ if heading_pairs is None and titles_of_parts is None:
265
+ return True
266
+ headings, titles = _only_child(heading_pairs, "vector"), _only_child(titles_of_parts, "vector")
267
+ pairs = [v.getElementsByTagName("*")[0] for v in _elements(headings)]
268
+ names = [n.firstChild.data if n.firstChild else "" for n in pairs[0::2]]
269
+ counts = pairs[1::2]
270
+ sizes = [int(c.firstChild.data) for c in counts]
271
+ entries = _elements(titles)
272
+ consistent = (
273
+ int(headings.getAttribute("size")) == 2 * len(counts) == len(_elements(headings))
274
+ and int(titles.getAttribute("size")) == len(entries) == sum(sizes)
275
+ )
276
+ titled = [i for i, name in enumerate(names) if name == "Slide Titles"]
277
+ as_long = [i for i in titled or range(len(sizes)) if sizes[i] == was > 0]
278
+ if not consistent or len(as_long) != 1:
279
+ return False
280
+ (group,) = as_long
281
+
282
+ title = entries[0].cloneNode(False)
283
+ title.appendChild(dom.createTextNode(f"Slide {was + 1}"))
284
+ at = sum(sizes[:group]) + min(position - 1, was)
285
+ titles.insertBefore(title, entries[at] if at < len(entries) else None)
286
+ titles.setAttribute("size", str(len(entries) + 1))
287
+ counts[group].firstChild.data = str(was + 1)
288
+ return True
289
+
290
+
291
+ def _elements(node) -> list:
292
+ return [c for c in node.childNodes if c.nodeType == c.ELEMENT_NODE]
293
+
294
+
295
+ def _only_child(node, local_name: str):
296
+ found = [c for c in _elements(node) if c.localName == local_name] if node else []
297
+ return found[0] if len(found) == 1 else None
298
+
299
+
300
+ def _add_to_content_types(unpacked_dir: Path, dest: str) -> None:
301
+ content_types_path = unpacked_dir / "[Content_Types].xml"
302
+ content_types = content_types_path.read_text(encoding="utf-8")
303
+
304
+ new_override = f'<Override PartName="/ppt/slides/{dest}" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml"/>'
305
+
306
+ if f'PartName="/ppt/slides/{dest}"' not in content_types:
307
+ content_types = content_types.replace("</Types>", f" {new_override}\n</Types>")
308
+ content_types_path.write_text(content_types, encoding="utf-8")
309
+
310
+
311
+ def _add_to_presentation_rels(unpacked_dir: Path, dest: str) -> str:
312
+ pres_rels_path = unpacked_dir / "ppt" / "_rels" / "presentation.xml.rels"
313
+ pres_rels = pres_rels_path.read_text(encoding="utf-8")
314
+
315
+ existing = _find_slide_relationship(pres_rels, dest)
316
+ if existing:
317
+ return existing
318
+
319
+ pres_xml = (unpacked_dir / "ppt" / "presentation.xml").read_text(encoding="utf-8")
320
+ used = {int(n) for n in re.findall(r'\bId="rId(\d+)"', pres_rels)}
321
+ used |= {int(n) for n in re.findall(r'\br:id="rId(\d+)"', pres_xml)}
322
+ rid = f"rId{max(used) + 1 if used else 1}"
323
+
324
+ new_rel = f'<Relationship Id="{rid}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="slides/{dest}"/>'
325
+ pres_rels = pres_rels.replace("</Relationships>", f" {new_rel}\n</Relationships>")
326
+ pres_rels_path.write_text(pres_rels, encoding="utf-8")
327
+
328
+ return rid
329
+
330
+
331
+ def _find_slide_relationship(pres_rels: str, slide_name: str) -> str | None:
332
+ for m in re.finditer(r"<Relationship\b[^>]*>", pres_rels):
333
+ element = m.group(0)
334
+ if re.search(rf'Target="(?:/ppt/)?slides/{re.escape(slide_name)}"', element):
335
+ id_match = re.search(r'\bId="([^"]+)"', element)
336
+ if id_match:
337
+ return id_match.group(1)
338
+ return None
339
+
340
+
341
+ def _get_next_slide_id(unpacked_dir: Path) -> int:
342
+ pres_content = (unpacked_dir / "ppt" / "presentation.xml").read_text(encoding="utf-8")
343
+ used = {int(m) for m in re.findall(r'<p:sldId[^>]*\bid="(\d+)"', pres_content)}
344
+
345
+ candidate = max((i for i in used if i >= SLIDE_ID_MIN), default=SLIDE_ID_MIN - 1) + 1
346
+ if candidate <= SLIDE_ID_MAX and candidate not in used:
347
+ return candidate
348
+ for i in range(SLIDE_ID_MIN, SLIDE_ID_MAX + 1):
349
+ if i not in used:
350
+ return i
351
+ _die("no slide id available in [256, 2147483647] — the deck is full")
352
+
353
+
354
+ def _insert_into_sld_id_lst(
355
+ unpacked_dir: Path, slide_id: int, rid: str, after_rid: str | None = None
356
+ ) -> tuple[int, int]:
357
+ pres_path = unpacked_dir / "ppt" / "presentation.xml"
358
+ xml = pres_path.read_text(encoding="utf-8")
359
+ entry = f'<p:sldId id="{slide_id}" r:id="{rid}"/>'
360
+
361
+ if f'r:id="{rid}"' in xml:
362
+ _die(f"presentation.xml already references {rid}; refusing to add a duplicate")
363
+
364
+ if after_rid:
365
+ open_tag = re.search(rf'<p:sldId\b[^>]*r:id="{re.escape(after_rid)}"[^>]*>', xml)
366
+ if not open_tag:
367
+ _die(f"{after_rid} is not listed in <p:sldIdLst>")
368
+ end = open_tag.end()
369
+ if not open_tag.group(0).endswith("/>"):
370
+ close = xml.find("</p:sldId>", end)
371
+ if close == -1:
372
+ _die(f"unclosed <p:sldId> for {after_rid} in presentation.xml")
373
+ end = close + len("</p:sldId>")
374
+ xml = xml[:end] + entry + xml[end:]
375
+ elif "</p:sldIdLst>" in xml:
376
+ xml = xml.replace("</p:sldIdLst>", f"{entry}</p:sldIdLst>", 1)
377
+ elif re.search(r"<p:sldIdLst\s*/>", xml):
378
+ xml = re.sub(r"<p:sldIdLst\s*/>", f"<p:sldIdLst>{entry}</p:sldIdLst>", xml, count=1)
379
+ elif "</p:sldMasterIdLst>" in xml:
380
+ xml = xml.replace(
381
+ "</p:sldMasterIdLst>", f"</p:sldMasterIdLst><p:sldIdLst>{entry}</p:sldIdLst>", 1
382
+ )
383
+ else:
384
+ _die("presentation.xml has no <p:sldIdLst> (or <p:sldMasterIdLst> to anchor a new one)")
385
+
386
+ pres_path.write_text(xml, encoding="utf-8")
387
+
388
+ lst = re.search(r"<p:sldIdLst>(.*)</p:sldIdLst>", xml, re.DOTALL)
389
+ entries = re.findall(r"<p:sldId\b[^>]*>", lst.group(1)) if lst else []
390
+ position = next(
391
+ (i for i, e in enumerate(entries, 1) if f'r:id="{rid}"' in e), len(entries)
392
+ )
393
+ return position, len(entries)
394
+
395
+
396
+ def _rid_for_slide(unpacked_dir: Path, slide_name: str) -> str:
397
+ pres_rels_path = unpacked_dir / "ppt" / "_rels" / "presentation.xml.rels"
398
+ rid = _find_slide_relationship(pres_rels_path.read_text(encoding="utf-8"), slide_name)
399
+ if not rid:
400
+ _die(f"{slide_name} has no relationship in presentation.xml.rels")
401
+ return rid
402
+
403
+
404
+ def add_slide(unpacked_dir: Path, source: str, after: str | None = None) -> str:
405
+ source_type, layout_file = parse_source(source)
406
+ if source_type == "layout" and layout_file is not None:
407
+ return create_slide_from_layout(unpacked_dir, layout_file, after)
408
+ return duplicate_slide(unpacked_dir, source, after)
409
+
410
+
411
+ def add_slide_to_package(
412
+ package: Path, source: str, after: str | None = None, output: Path | None = None
413
+ ) -> str:
414
+ out = output or package
415
+ with tempfile.TemporaryDirectory() as tmp:
416
+ tmp_path = Path(tmp)
417
+ with zipfile.ZipFile(package) as zf:
418
+ safe_extract(zf, tmp_path)
419
+ dest = add_slide(tmp_path, source, after)
420
+ rezip(tmp_path, out)
421
+ print(f"Wrote {out} — the new slide is ppt/slides/{dest} inside it (unpack to edit its content)")
422
+ return dest
423
+
424
+
425
+ def main() -> None:
426
+ parser = argparse.ArgumentParser(
427
+ description="Add a slide to a PPTX: duplicate a slide or instantiate a layout. "
428
+ "Registers content types, relationships, and <p:sldIdLst>."
429
+ )
430
+ parser.add_argument("target", help="Unpacked PPTX directory OR a .pptx/.potx file")
431
+ parser.add_argument(
432
+ "source",
433
+ help="slideN.xml to duplicate, or slideLayoutN.xml to create from a layout "
434
+ "(list layouts with: ls <dir>/ppt/slideLayouts/)",
435
+ )
436
+ parser.add_argument(
437
+ "--after",
438
+ metavar="SLIDE",
439
+ help="insert after this slide, e.g. slide2.xml (default: append at the end)",
440
+ )
441
+ parser.add_argument(
442
+ "-o",
443
+ "--output",
444
+ help="output file (only with a .pptx/.potx target; default: rewrite the input in place)",
445
+ )
446
+ args = parser.parse_args()
447
+
448
+ target = Path(args.target)
449
+ if target.is_dir():
450
+ if args.output:
451
+ parser.error("--output is only valid for .pptx/.potx input; a directory is modified in place")
452
+ add_slide(target, args.source, args.after)
453
+ elif target.is_file() and target.suffix.lower() in (".pptx", ".potx"):
454
+ try:
455
+ add_slide_to_package(target, args.source, args.after, Path(args.output) if args.output else None)
456
+ except (OSError, ValueError, zipfile.BadZipFile) as e:
457
+ _die(str(e))
458
+ else:
459
+ _die(f"{target} is neither a directory nor a .pptx/.potx file")
460
+
461
+
462
+ if __name__ == "__main__":
463
+ main()
@@ -0,0 +1,107 @@
1
+ // Give a deck pptxgenjs wrote its own theme colors and theme name. pptxgenjs sets the theme's
2
+ // two fonts (pres.theme) but hard-codes Office's palette, so scheme colors resolve to Office
3
+ // blue and orange until the deck's colors are written into ppt/theme/theme1.xml.
4
+ //
5
+ // const { applyTheme } = require("<this skill's directory>/scripts/apply_theme.js");
6
+ // await pres.writeFile({ fileName: "deck.pptx" });
7
+ // await applyTheme("deck.pptx", {
8
+ // name: "Northwind",
9
+ // colors: { dk1, lt1, dk2, lt2, accent1, accent2, accent3, accent4, accent5, accent6, hlink, folHlink },
10
+ // }); // extra keys (headFontFace, ...) are ignored, and the twelve colors may sit beside name instead
11
+ //
12
+ // node scripts/apply_theme.js deck.pptx theme.json [out.pptx] # the same, from a shell
13
+ //
14
+ // Colors are six hex digits, no "#". The deck is rewritten in place unless a third argument
15
+ // names another file. It throws, changing nothing, if a color anywhere in the deck is not six
16
+ // hex digits, which is what a scheme color passed to a hex-only option turns into.
17
+ //
18
+ // As the step that rewrites the deck after pres.writeFile(), it also handles two faults pptxgenjs writes
19
+ // that make PowerPoint offer to repair the deck: it mends <c:crossesAt val="autoZero"/>, and it
20
+ // throws on a line dash that is not a dash style.
21
+ const fs = require("fs");
22
+
23
+ // jszip comes with pptxgenjs but is not always installed where a bare require("jszip") finds
24
+ // it, so it is loaded from beside pptxgenjs. Both are found the way any require() in this file
25
+ // would find them: from this file's directory upward, then NODE_PATH and Node's global folders.
26
+ // No search starts at the working directory or the calling script's directory.
27
+ function loadJSZip() {
28
+ try {
29
+ return require(require.resolve("jszip", { paths: [require.resolve("pptxgenjs")] }));
30
+ } catch {
31
+ throw new Error(`pptxgenjs and the jszip that comes with it cannot be found from ${__filename}. If pptxgenjs is installed beside your own script, run node with NODE_PATH set to that node_modules folder. Nothing was changed.`);
32
+ }
33
+ }
34
+
35
+ const SLOTS = ["dk1", "lt1", "dk2", "lt2", "accent1", "accent2", "accent3", "accent4", "accent5", "accent6", "hlink", "folHlink"];
36
+ // A name or value from the deck, for an error a model reads: quoted, cut, and with nothing unprintable left raw.
37
+ const shown = (s) => JSON.stringify(String(s).slice(0, 80)).replace(/[\p{C}\u2028\u2029]/gu, (c) => "\\u{" + c.codePointAt(0).toString(16) + "}");
38
+ const DASHES = ["solid", "dot", "dash", "lgDash", "dashDot", "lgDashDot", "lgDashDotDot", "sysDash", "sysDot", "sysDashDot", "sysDashDotDot"];
39
+
40
+ function themeXml(xml, theme) {
41
+ if (!theme || !theme.name) throw new Error("theme.name is required. Nothing was changed.");
42
+ // The name goes into XML attributes: drop control characters, escape & < > and the double quote.
43
+ const name = String(theme.name).replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
44
+ const colors = theme.colors || theme; // { name, colors: {...} }, or flat { name, dk1, ... }
45
+ for (const k of SLOTS) {
46
+ if (!/^[0-9A-Fa-f]{6}$/.test(String(colors[k]))) throw new Error(`theme.colors.${k} is ${JSON.stringify(colors[k])}; it must be six hex digits with no "#" (slots: ${SLOTS.join(" ")}). Nothing was changed.`);
47
+ }
48
+ const scheme = `<a:clrScheme name="${name}">` + SLOTS.map((k) => `<a:${k}><a:srgbClr val="${String(colors[k]).toUpperCase()}"/></a:${k}>`).join("") + "</a:clrScheme>";
49
+ // Function replacements, so a "$" in the name is not read as a replacement pattern.
50
+ // The theme, its color scheme and its font scheme each carry a name; none should still say Office.
51
+ const out = xml
52
+ .replace(/<a:clrScheme\b[\s\S]*?<\/a:clrScheme>/, () => scheme)
53
+ .replace(/(<a:(?:theme|fontScheme)\b[^>]*?\bname=")[^"]*"/g, (_, head) => `${head}${name}"`);
54
+ if (!out.includes(scheme)) throw new Error("ppt/theme/theme1.xml has no <a:clrScheme> to replace; this script expects the theme part pptxgenjs writes. Nothing was changed.");
55
+ return out;
56
+ }
57
+
58
+ async function applyTheme(deckPath, theme, outPath = deckPath) {
59
+ const zip = await loadJSZip().loadAsync(fs.readFileSync(deckPath));
60
+ const part = "ppt/theme/theme1.xml"; // the one theme part pptxgenjs writes; the slide master and the notes master share it
61
+ if (!zip.file(part)) throw new Error(`${deckPath} has no ${part}; this script is for decks pptxgenjs wrote. Nothing was changed.`);
62
+ zip.file(part, themeXml(await zip.file(part).async("string"), theme));
63
+
64
+ // A scheme color given to a hex-only option is written as <a:srgbClr val="bg2"/>, which is
65
+ // not a color. pptxgenjs does not warn; stop here instead.
66
+ for (const name of Object.keys(zip.files)) {
67
+ if (!name.endsWith(".xml")) continue;
68
+ const xml = await zip.file(name).async("string");
69
+ const bad = xml.match(/<a:srgbClr val="((?![0-9A-Fa-f]{6}")[^"]*)"/);
70
+ if (bad) throw new Error(`${shown(name)} has an <a:srgbClr> whose val is ${shown(bad[1])}, not six hex digits. Usually a scheme color was given to an option that takes hex only (valGridLine.color, catGridLine.color, shadow.color, or chartColors / invertedColors on a one-series bar chart). Pass the six-digit hex from your theme object there and rebuild. Nothing was changed.`);
71
+
72
+ // pptxgenjs writes a dash option through unchecked, and an array as "solid,dash".
73
+ const dash = [...xml.matchAll(/<a:prstDash val="([^"]*)"/g)].find((m) => !DASHES.includes(m[1].trim()));
74
+ if (dash) throw new Error(`${shown(name)} has an <a:prstDash> whose val is ${shown(dash[1])}, which is not a dash style, and PowerPoint would offer to repair the deck. Give line.dashType, a chart's lineDash (one word for the whole chart, not an array), catAxisLineStyle or valAxisLineStyle one of: ${DASHES.join(" ")}. Then rebuild. Nothing was changed.`);
75
+
76
+ // pptxgenjs writes valAxisCrossesAt: 0 as <c:crossesAt val="autoZero"/>. <c:crossesAt> takes
77
+ // a number; the word belongs in <c:crosses>, where it means the same: cross at zero.
78
+ if (xml.includes('<c:crossesAt val="autoZero"/>')) zip.file(name, xml.replaceAll('<c:crossesAt val="autoZero"/>', '<c:crosses val="autoZero"/>'));
79
+ }
80
+ // A ZIP entry for a folder ("ppt/slides/") is not a part, and pptxgenjs writes one per folder.
81
+ // A cloud co-editing service reported issues editing decks that carry them. They are dropped
82
+ // here for that reason, not to save space. (zip.remove() would take the folder's files too.)
83
+ for (const name of Object.keys(zip.files)) if (zip.files[name].dir) delete zip.files[name];
84
+
85
+ fs.writeFileSync(outPath, await zip.generateAsync({ type: "nodebuffer", compression: "DEFLATE" }));
86
+ }
87
+
88
+ module.exports = { applyTheme };
89
+
90
+ if (require.main === module) {
91
+ const [deck, themeFile, out] = process.argv.slice(2);
92
+ if (!deck || !themeFile) {
93
+ console.error("usage: node apply_theme.js deck.pptx theme.json [out.pptx]");
94
+ process.exit(2);
95
+ }
96
+ let theme;
97
+ try {
98
+ theme = JSON.parse(fs.readFileSync(themeFile, "utf8"));
99
+ } catch (e) {
100
+ console.error(`Error: cannot read ${themeFile} as JSON (${e.message}). Nothing was changed.`);
101
+ process.exit(1);
102
+ }
103
+ applyTheme(deck, theme, out || deck).then(
104
+ () => console.log(`Theme written to ${out || deck}`),
105
+ (e) => { console.error(`Error: ${e.message}`); process.exit(1); }
106
+ );
107
+ }