pydocmaker 2.8.2__tar.gz → 2.8.3__tar.gz

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 (82) hide show
  1. {pydocmaker-2.8.2/src/pydocmaker.egg-info → pydocmaker-2.8.3}/PKG-INFO +43 -2
  2. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/README.md +42 -1
  3. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/__init__.py +1 -1
  4. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/backend/ex_typst.py +5 -1
  5. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/backend/pdf_maker_tex.py +5 -2
  6. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/core.py +262 -10
  7. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/templating.py +311 -55
  8. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/util.py +37 -0
  9. {pydocmaker-2.8.2 → pydocmaker-2.8.3/src/pydocmaker.egg-info}/PKG-INFO +43 -2
  10. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker.egg-info/SOURCES.txt +1 -0
  11. pydocmaker-2.8.3/tests/test_attachments.py +367 -0
  12. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/tests/test_templating.py +458 -1
  13. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/tests/test_templating_extensive.py +29 -0
  14. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/LICENSE +0 -0
  15. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/pyproject.toml +0 -0
  16. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/requirements.txt +0 -0
  17. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/setup.cfg +0 -0
  18. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/b64_data.py +0 -0
  19. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/backend/__init__.py +0 -0
  20. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/backend/baseformatter.py +0 -0
  21. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/backend/ex_docx.py +0 -0
  22. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/backend/ex_html.py +0 -0
  23. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/backend/ex_ipynb.py +0 -0
  24. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/backend/ex_markdown.py +0 -0
  25. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/backend/ex_redmine.py +0 -0
  26. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/backend/ex_rich.py +0 -0
  27. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/backend/ex_tex.py +0 -0
  28. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/backend/libreoffice_api.py +0 -0
  29. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/backend/mdx_latex.py +0 -0
  30. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/backend/pandoc_api.py +0 -0
  31. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/backend/pandoc_batch.py +0 -0
  32. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/blocktmpl/__init__.py +0 -0
  33. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/blocktmpl/adapter_base.py +0 -0
  34. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/blocktmpl/adapter_html.py +0 -0
  35. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/blocktmpl/adapter_tex.py +0 -0
  36. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/blocktmpl/adapter_typ.py +0 -0
  37. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/blocktmpl/inference.py +0 -0
  38. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/blocktmpl/markers.py +0 -0
  39. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/blocktmpl/model.py +0 -0
  40. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/blocktmpl/parser.py +0 -0
  41. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/blocktmpl/render.py +0 -0
  42. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/cli.py +0 -0
  43. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/io/__init__.py +0 -0
  44. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/io/html_loader.py +0 -0
  45. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/io/ipynb_loader.py +0 -0
  46. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/param_mapping.py +0 -0
  47. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/templates/base.html +0 -0
  48. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/templates/base.html.j2 +0 -0
  49. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/templates/base.tex +0 -0
  50. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/templates/base.tex.j2 +0 -0
  51. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/templates/base.typ +0 -0
  52. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/templates/base.typ.j2 +0 -0
  53. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/templates/paper.typ.j2 +0 -0
  54. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/templates/report.tex +0 -0
  55. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/templates/report.typ +0 -0
  56. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/templates/report.typ.j2 +0 -0
  57. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker/templates/word_template_with_mergefields.docx +0 -0
  58. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker.egg-info/dependency_links.txt +0 -0
  59. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker.egg-info/entry_points.txt +0 -0
  60. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker.egg-info/requires.txt +0 -0
  61. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/src/pydocmaker.egg-info/top_level.txt +0 -0
  62. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/tests/test_backend_pandoc.py +0 -0
  63. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/tests/test_blocktmpl_inference.py +0 -0
  64. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/tests/test_blocktmpl_integration.py +0 -0
  65. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/tests/test_blocktmpl_parser.py +0 -0
  66. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/tests/test_blocktmpl_render.py +0 -0
  67. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/tests/test_blocktmpl_values.py +0 -0
  68. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/tests/test_cli.py +0 -0
  69. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/tests/test_convert_all.py +0 -0
  70. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/tests/test_core.py +0 -0
  71. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/tests/test_docx_ex.py +0 -0
  72. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/tests/test_ex_html.py +0 -0
  73. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/tests/test_ex_rich.py +0 -0
  74. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/tests/test_ex_tex.py +0 -0
  75. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/tests/test_ex_typst.py +0 -0
  76. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/tests/test_io_html.py +0 -0
  77. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/tests/test_io_ipynb.py +0 -0
  78. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/tests/test_param_mapping.py +0 -0
  79. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/tests/test_pdf_ex.py +0 -0
  80. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/tests/test_pdf_typst.py +0 -0
  81. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/tests/test_snippets.py +0 -0
  82. {pydocmaker-2.8.2 → pydocmaker-2.8.3}/tests/test_util.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pydocmaker
3
- Version: 2.8.2
3
+ Version: 2.8.3
4
4
  Summary: A minimal python document maker to create and show reports (including figures and tables) from within python and export them to markdown, pdf, html, and word.
5
5
  Author: Tobias Glaubach
6
6
  License: MIT License
@@ -77,7 +77,7 @@ A minimal easy to use python document maker to create reports in `pdf`, `md`, `t
77
77
 
78
78
  Full documentation at https://pydocmaker.readthedocs.io/en/latest/
79
79
 
80
- For an **example of a created PDF document** please see `README.pdf` (located within the root folder of this repository) which is this `README.md` file converted to pdf via `pydocmaker` and `typst` with the `report` template.
80
+ For an **example of a created PDF document** please see [README.pdf](https://github.com/TobiasGlaubach/pydocmaker/blob/main/README.pdf) (located within the root folder of this repository) which is this `README.md` file converted to pdf via `pydocmaker` and `typst` with the `report` template.
81
81
 
82
82
  ## Installation
83
83
 
@@ -413,6 +413,47 @@ NOTE for LaTeX templates: parameter names that collide with LaTeX kernel macros
413
413
  shall be displayed in the document body.
414
414
 
415
415
 
416
+ ### Document Attachments
417
+
418
+ Attachments are extra files (e.g. images referenced by a template) that travel with the document
419
+ inside its metadata element (`meta['data']['attachments']`, a `{name: base64-string}` mapping, so
420
+ saved documents stay JSON serializable). On `to_pdf()` / `to_tex()` they are decoded and written
421
+ next to the compiled main file, where templates can reference them by (relative) name:
422
+
423
+ ```python
424
+ import pydocmaker as pyd
425
+
426
+ doc = pyd.Doc().add_text('My Report')
427
+
428
+ # add attachment files (bytes are base64-encoded automatically,
429
+ # data-URI prefixes are stripped)
430
+ doc.set_attachments({'logo.png': pyd.load_file_b64('logo.png')}) # replace all
431
+ doc.update_attachments({'device.png': open('device.png', 'rb').read()}) # merge
432
+ doc.get_attachments() # -> {'logo.png': '...', 'device.png': '...'}
433
+
434
+ # the template then references them by name, e.g. in Typst:
435
+ # #image("logo.png", width: 2cm)
436
+ # or in LaTeX:
437
+ # \includegraphics[width=2cm]{logo.png}
438
+
439
+ doc.to_pdf('myreport.pdf') # logo.png / device.png are shipped with the compile folder
440
+ ```
441
+
442
+ Notes:
443
+
444
+ - `add_attachments` is an alias for `update_attachments` (create-or-merge semantics, like
445
+ `add_meta`); `set_attachments` replaces all existing entries.
446
+ - Attachment names must be safe relative paths: sub folders such as `images/logo.png` work, while
447
+ absolute paths and `..` segments are rejected with a `ValueError` (they would escape the compile
448
+ folder or the zip archive when exporting an untrusted document).
449
+ - Precedence (highest first): explicit `files_to_upload` / `attachments` / `additional_files`
450
+ call arguments, document metadata entries, the template's own asset files
451
+ (see `set_template_to_meta`).
452
+ - Attachments are shipped for the `typst` and `tex` PDF engines and `to_tex()`; the metadata
453
+ template flow (`get_template_from_meta`) picks them up for all template-based exporters.
454
+ - `Doc.set_meta` replaces the whole metadata dict and thereby drops attachments as well.
455
+
456
+
416
457
  ### Install Optional Requirements
417
458
 
418
459
 
@@ -25,7 +25,7 @@ A minimal easy to use python document maker to create reports in `pdf`, `md`, `t
25
25
 
26
26
  Full documentation at https://pydocmaker.readthedocs.io/en/latest/
27
27
 
28
- For an **example of a created PDF document** please see `README.pdf` (located within the root folder of this repository) which is this `README.md` file converted to pdf via `pydocmaker` and `typst` with the `report` template.
28
+ For an **example of a created PDF document** please see [README.pdf](https://github.com/TobiasGlaubach/pydocmaker/blob/main/README.pdf) (located within the root folder of this repository) which is this `README.md` file converted to pdf via `pydocmaker` and `typst` with the `report` template.
29
29
 
30
30
  ## Installation
31
31
 
@@ -361,6 +361,47 @@ NOTE for LaTeX templates: parameter names that collide with LaTeX kernel macros
361
361
  shall be displayed in the document body.
362
362
 
363
363
 
364
+ ### Document Attachments
365
+
366
+ Attachments are extra files (e.g. images referenced by a template) that travel with the document
367
+ inside its metadata element (`meta['data']['attachments']`, a `{name: base64-string}` mapping, so
368
+ saved documents stay JSON serializable). On `to_pdf()` / `to_tex()` they are decoded and written
369
+ next to the compiled main file, where templates can reference them by (relative) name:
370
+
371
+ ```python
372
+ import pydocmaker as pyd
373
+
374
+ doc = pyd.Doc().add_text('My Report')
375
+
376
+ # add attachment files (bytes are base64-encoded automatically,
377
+ # data-URI prefixes are stripped)
378
+ doc.set_attachments({'logo.png': pyd.load_file_b64('logo.png')}) # replace all
379
+ doc.update_attachments({'device.png': open('device.png', 'rb').read()}) # merge
380
+ doc.get_attachments() # -> {'logo.png': '...', 'device.png': '...'}
381
+
382
+ # the template then references them by name, e.g. in Typst:
383
+ # #image("logo.png", width: 2cm)
384
+ # or in LaTeX:
385
+ # \includegraphics[width=2cm]{logo.png}
386
+
387
+ doc.to_pdf('myreport.pdf') # logo.png / device.png are shipped with the compile folder
388
+ ```
389
+
390
+ Notes:
391
+
392
+ - `add_attachments` is an alias for `update_attachments` (create-or-merge semantics, like
393
+ `add_meta`); `set_attachments` replaces all existing entries.
394
+ - Attachment names must be safe relative paths: sub folders such as `images/logo.png` work, while
395
+ absolute paths and `..` segments are rejected with a `ValueError` (they would escape the compile
396
+ folder or the zip archive when exporting an untrusted document).
397
+ - Precedence (highest first): explicit `files_to_upload` / `attachments` / `additional_files`
398
+ call arguments, document metadata entries, the template's own asset files
399
+ (see `set_template_to_meta`).
400
+ - Attachments are shipped for the `typst` and `tex` PDF engines and `to_tex()`; the metadata
401
+ template flow (`get_template_from_meta`) picks them up for all template-based exporters.
402
+ - `Doc.set_meta` replaces the whole metadata dict and thereby drops attachments as well.
403
+
404
+
364
405
  ### Install Optional Requirements
365
406
 
366
407
 
@@ -1,4 +1,4 @@
1
- __version__ = '2.8.2'
1
+ __version__ = '2.8.3'
2
2
 
3
3
 
4
4
  from pydocmaker.core import Doc, construct, constr, buildingblocks, print_to_pdf, make_pdf_from_tex, show_pdf, is_notebook, load_file_b64
@@ -444,6 +444,10 @@ def compile_with_typst(typst_code: Union[str, List[dict]], output: str = None, v
444
444
  if files_to_upload:
445
445
  attachments.update(files_to_upload)
446
446
 
447
+ # guard against path traversal: attachment names must stay relative
448
+ # paths inside the compile folder
449
+ attachments = {util.sanitize_attachment_name(k): v for k, v in attachments.items()}
450
+
447
451
  for k in attachments:
448
452
  if isinstance(attachments[k], str) and os.path.exists(attachments[k]):
449
453
  attachments[k] = Path(attachments[k])
@@ -505,7 +509,7 @@ def convert(doc:List[dict], template = None, template_params=None, ret_attachmen
505
509
 
506
510
  if template is None:
507
511
  template = get_default_template_id('typ')
508
- template_obj, attachments, template_str = handle_template(template, __default_template, tformat='typ', template_engine=template_engine)
512
+ template_obj, attachments, template_str = handle_template(template, __default_template, tformat='typ', template_engine=template_engine, verb=verb)
509
513
 
510
514
 
511
515
  try:
@@ -15,7 +15,7 @@ import shutil
15
15
  import warnings
16
16
  import zipfile
17
17
 
18
- from pydocmaker.util import log
18
+ from pydocmaker.util import log, sanitize_attachment_name
19
19
 
20
20
 
21
21
  # Define a function to test if pdflatex, lualatex, or xelatex is installed
@@ -263,6 +263,9 @@ def make_pdf_from_tex(input_latex_text, attachments_dc=None, docname='', out_for
263
263
  # write all attachments to the folder
264
264
  for filename, file_content_bytes in attachments_dc.items():
265
265
  assert isinstance(filename, str) and isinstance(file_content_bytes, (bytes, str)), f'attachments_dc must only contain path:bytes pairs but given was {filename=} with content type {type(file_content_bytes)}'
266
+ # guard against path traversal: attachment names must stay
267
+ # relative paths inside the compile folder
268
+ filename = sanitize_attachment_name(filename)
266
269
  if verb: log.info(f'Writing file: {filename}')
267
270
  out_path = os.path.join(output_dir, filename)
268
271
  # attachment keys may contain subpaths (e.g. "images/logo.png")
@@ -315,7 +318,7 @@ def make_pdf_from_tex(input_latex_text, attachments_dc=None, docname='', out_for
315
318
  if os.path.exists(output_dir):
316
319
  files_in_dir = os.listdir(output_dir)
317
320
  sep = '\n-'
318
- info_string += f"\The directory '{output_dir}' exists and contains the following files:\n{sep.join(files_in_dir)}"
321
+ info_string += f"\nThe directory '{output_dir}' exists and contains the following files:\n{sep.join(files_in_dir)}"
319
322
  else:
320
323
  info_string += f"\nThe directory {output_dir} does not exist either."
321
324
  if os.path.exists(logfile):
@@ -24,7 +24,7 @@ import jinja2
24
24
 
25
25
 
26
26
 
27
- from .util import flatten_list, split_camel_case, upload_report_to_redmine, CommonJSONEncoder, MyJSONDecoder, limit_len, log, make_png_imageblob, loadfile_str
27
+ from .util import flatten_list, split_camel_case, upload_report_to_redmine, CommonJSONEncoder, MyJSONDecoder, limit_len, log, make_png_imageblob, loadfile_str, sanitize_attachment_name
28
28
 
29
29
  from .backend.ex_html import convert as to_html
30
30
  from .backend.ex_docx import convert as to_docx
@@ -52,6 +52,10 @@ from . import b64_data
52
52
 
53
53
  ALLOWED_ENGINES_PDF = 'tex latex typst typ word libreoffice pandoc'.split()
54
54
 
55
+ #: metadata keys that are reserved for the templating/attachment machinery and
56
+ #: must never be passed to a template as parameters
57
+ RESERVED_META_KEYS = ["template_id", "files_to_upload", "additional_files", "attachments", "template"]
58
+
55
59
  np = None
56
60
  gImage = None
57
61
 
@@ -1013,7 +1017,7 @@ class Doc(UserList):
1013
1017
 
1014
1018
  attachments = meta.pop("files_to_upload", {})
1015
1019
  attachments.update(meta.pop("attachments", {}))
1016
- attachments = {k:base64.b64decode(v) if isinstance(v, str) else v for k, v in attachments.items()}
1020
+ attachments = self._decode_meta_files(attachments)
1017
1021
 
1018
1022
  if template_id is None:
1019
1023
  template_str = meta.pop("template", None)
@@ -1027,7 +1031,8 @@ class Doc(UserList):
1027
1031
 
1028
1032
  try:
1029
1033
  template = DocTemplate.from_tid(template_id, tformat, template_dir)
1030
- template.params = {k:v for k, v in meta.items()}
1034
+ # the reserved metadata keys are never template parameters
1035
+ template.params = {k: v for k, v in meta.items() if k not in RESERVED_META_KEYS}
1031
1036
 
1032
1037
  template.attachments.update(attachments)
1033
1038
  return template
@@ -1197,6 +1202,219 @@ class Doc(UserList):
1197
1202
  self.update_meta(dc)
1198
1203
  return dc
1199
1204
 
1205
+
1206
+ def _attachments_dict(self) -> Dict[str, Any]:
1207
+ """Return the live ``meta['data']['attachments']`` dict of this document.
1208
+
1209
+ Creates the metadata element and the ``attachments`` key if they do
1210
+ not exist yet, so the returned dict can be mutated in place.
1211
+ """
1212
+ meta = self.get_meta()
1213
+ if meta is None:
1214
+ el = constr.meta(data={'attachments': {}})
1215
+ self.add(el)
1216
+ return el['data']['attachments']
1217
+
1218
+ data = meta.get('data')
1219
+ if not isinstance(data, dict):
1220
+ data = {}
1221
+ meta['data'] = data
1222
+
1223
+ atts = data.get('attachments')
1224
+ if atts is None:
1225
+ atts = {}
1226
+ data['attachments'] = atts
1227
+ elif not isinstance(atts, dict):
1228
+ raise TypeError(f'meta["data"]["attachments"] must be a dict but was {type(atts).__name__}')
1229
+ return atts
1230
+
1231
+ @staticmethod
1232
+ def _normalize_attachments(data: Dict[str, Any]) -> Dict[str, Any]:
1233
+ """Normalize attachment names and values for storage in the metadata.
1234
+
1235
+ ``bytes`` values are base64-encoded (so the document stays JSON
1236
+ serializable, exactly like ``set_template_to_meta`` and the CLI store
1237
+ them) and ``data: ...;base64,`` URI prefixes are stripped, so image
1238
+ blobs from ``make_png_imageblob`` or ``image_from_file`` can be given
1239
+ as-is. Names are validated with :func:`sanitize_attachment_name` so
1240
+ untrusted documents cannot smuggle path traversal names in.
1241
+ """
1242
+ out = {}
1243
+ for k, v in data.items():
1244
+ k = sanitize_attachment_name(k)
1245
+ if isinstance(v, (bytes, bytearray)):
1246
+ v = base64.b64encode(bytes(v)).decode('utf-8')
1247
+ elif isinstance(v, str) and v.lstrip().startswith('data:') and ';base64,' in v:
1248
+ v = v.split(';base64,', 1)[-1]
1249
+ out[k] = v
1250
+ return out
1251
+
1252
+ @staticmethod
1253
+ def _decode_meta_files(meta_files: Dict[str, Any]) -> Dict[str, Any]:
1254
+ """Decode metadata attachment entries (base64 strings) to bytes.
1255
+
1256
+ Values that are already bytes (or ``Path`` objects, which the typst
1257
+ backend resolves) are passed through unchanged;
1258
+ ``data: ...;base64,`` URI prefixes on strings are stripped before
1259
+ decoding. Names are validated with :func:`sanitize_attachment_name`
1260
+ so untrusted documents cannot smuggle path traversal names in.
1261
+ """
1262
+ out = {}
1263
+ for k, v in meta_files.items():
1264
+ k = sanitize_attachment_name(k)
1265
+ if isinstance(v, str):
1266
+ if v.lstrip().startswith('data:') and ';base64,' in v:
1267
+ v = v.split(';base64,', 1)[-1]
1268
+ v = base64.b64decode(v)
1269
+ out[k] = v
1270
+ return out
1271
+
1272
+ @staticmethod
1273
+ def _meta_files_and_params(meta: Dict[str, Any], files: Dict[str, Any]) -> Tuple[Dict[str, Any], Dict[str, Any]]:
1274
+ """Load the attachment files from document metadata for exporters.
1275
+
1276
+ This is the shared implementation behind the no-template flows of
1277
+ ``to_pdf`` and ``to_tex`` (with a template, ``get_template_from_meta``
1278
+ already loaded and decoded the metadata attachments into
1279
+ ``mytemplate.attachments``): the ``files_to_upload`` and ``attachments``
1280
+ entries of the metadata are merged (``attachments`` wins) and their
1281
+ base64 values decoded; the already-given ``files`` dict (the explicit
1282
+ call arguments) keeps precedence over the metadata values. The
1283
+ metadata keys reserved for the templating/attachment machinery
1284
+ (``RESERVED_META_KEYS``) are excluded from the returned template
1285
+ params.
1286
+
1287
+ Args:
1288
+ meta: The ``meta['data']`` dict of the document.
1289
+ files: The explicitly given files (e.g. ``files_to_upload`` /
1290
+ ``additional_files`` call arguments), taking precedence.
1291
+
1292
+ Returns:
1293
+ Tuple[dict, dict]: The merged files dict and the filtered params.
1294
+ """
1295
+ meta_files = {**meta.get('files_to_upload', {}), **meta.get('attachments', {})}
1296
+ meta_files = Doc._decode_meta_files(meta_files)
1297
+ files = {**meta_files, **files}
1298
+ params = {k: v for k, v in meta.items() if k not in RESERVED_META_KEYS}
1299
+ return files, params
1300
+
1301
+ def set_attachments(self, *args: Any, **kwargs: Any) -> Dict[str, Any]:
1302
+ """Replaces the document attachments with the provided content.
1303
+
1304
+ Attachments are extra files (e.g. images referenced by a template)
1305
+ stored in the metadata element of the document under
1306
+ ``meta['data']['attachments']`` as a ``{name: base64-string}`` mapping.
1307
+ On export (``to_pdf`` / ``to_tex``) they are decoded and written next
1308
+ to the compiled main file, so templates can reference them by their
1309
+ (relative) name, e.g. ``image("logo.png")`` or
1310
+ ``\\includegraphics{logo.png}``.
1311
+
1312
+ Can be used in two ways::
1313
+
1314
+ .set_attachments({'device.png': 'base64str'})
1315
+ .set_attachments(device_png='base64str')
1316
+
1317
+ ``bytes`` values are base64-encoded automatically and
1318
+ ``data:...;base64,...`` URI prefixes are stripped, so the document
1319
+ stays JSON serializable and the output of ``load_file_b64`` or
1320
+ ``make_png_imageblob`` can be given as-is.
1321
+
1322
+ Names must be safe relative paths: sub folders such as
1323
+ ``images/logo.png`` are allowed (and normalized), while absolute
1324
+ paths and ``..`` segments raise a ``ValueError`` (they would escape
1325
+ the compile folder / zip archive on export; see
1326
+ :func:`pydocmaker.util.sanitize_attachment_name`).
1327
+
1328
+ This method *replaces* all existing attachments -- use
1329
+ ``update_attachments`` to only add or overwrite single entries.
1330
+
1331
+ Args:
1332
+ *args: A single dictionary ``{name: base64-string-or-bytes}``.
1333
+ **kwargs: Additional ``name=base64-string-or-bytes`` pairs.
1334
+
1335
+ Returns:
1336
+ dict: The new attachments content (the live dict inside the
1337
+ metadata element, not a copy).
1338
+ """
1339
+ data = next(iter(args), {})
1340
+ data.update(kwargs)
1341
+
1342
+ atts = self._attachments_dict()
1343
+ atts.clear()
1344
+ atts.update(self._normalize_attachments(data))
1345
+ return atts
1346
+
1347
+
1348
+ def get_attachments(self, default: Optional[Dict[str, Any]] = None) -> Optional[Dict[str, Any]]:
1349
+ """Gets the attachments stored in the metadata of this document.
1350
+
1351
+ Gets the ``meta['data']['attachments']`` content (a
1352
+ ``{name: base64-string}`` mapping). The returned dict is the live
1353
+ object inside the metadata element, not a copy -- mutating it modifies
1354
+ the document.
1355
+
1356
+ Args:
1357
+ default: Value to return if no attachments exist. Defaults to None.
1358
+
1359
+ Returns:
1360
+ dict: The attachments mapping, or default if none exists.
1361
+ """
1362
+ data = self.get_meta(default={}).get('data')
1363
+ if not isinstance(data, dict):
1364
+ return default
1365
+ return data.get('attachments', default)
1366
+
1367
+
1368
+ def update_attachments(self, *args: Any, **kwargs: Any) -> Dict[str, Any]:
1369
+ """Updates the document attachments with the provided content.
1370
+
1371
+ Existing entries with the same name are overwritten, all other
1372
+ entries are kept. If no attachments exist yet, they are created (see
1373
+ ``set_attachments`` for the storage format and accepted value types).
1374
+
1375
+ Examples::
1376
+
1377
+ .update_attachments({'device.png': 'base64str'})
1378
+ .update_attachments(device_png='base64str')
1379
+
1380
+ Args:
1381
+ *args: A single dictionary ``{name: base64-string-or-bytes}``.
1382
+ **kwargs: Additional ``name=base64-string-or-bytes`` pairs.
1383
+
1384
+ Returns:
1385
+ dict: The updated attachments content (the live dict inside the
1386
+ metadata element, not a copy).
1387
+ """
1388
+ data = next(iter(args), {})
1389
+ data.update(kwargs)
1390
+
1391
+ atts = self._attachments_dict()
1392
+ atts.update(self._normalize_attachments(data))
1393
+ return atts
1394
+
1395
+ def add_attachments(self, *args: Any, **kwargs: Any) -> Dict[str, Any]:
1396
+ """Adds attachments to this document (alias for ``update_attachments``).
1397
+
1398
+ Like ``add_meta``, this creates the attachments if none exist yet
1399
+ and merges into existing ones otherwise. See ``set_attachments`` for
1400
+ the storage format and accepted value types.
1401
+
1402
+ Examples::
1403
+
1404
+ .add_attachments({'device.png': 'base64str'})
1405
+ .add_attachments(device_png='base64str')
1406
+
1407
+ Args:
1408
+ *args: A single dictionary ``{name: base64-string-or-bytes}``.
1409
+ **kwargs: Additional ``name=base64-string-or-bytes`` pairs.
1410
+
1411
+ Returns:
1412
+ dict: The attachments content (the live dict inside the metadata
1413
+ element, not a copy).
1414
+ """
1415
+ return self.update_attachments(*args, **kwargs)
1416
+
1417
+
1200
1418
  def set_meta(self, *args: Any, **kwargs: Any) -> Dict[str, Any]:
1201
1419
  """
1202
1420
  Replaces the metadata for this document with the provided content.
@@ -1749,7 +1967,7 @@ class Doc(UserList):
1749
1967
  if not mytemplate is None:
1750
1968
  params_from_meta = mytemplate.params
1751
1969
  else:
1752
- params_from_meta = {k:v for k, v in meta.items() if not k in ["template_id", "files_to_upload", "additional_files"]}
1970
+ params_from_meta = {k:v for k, v in meta.items() if not k in RESERVED_META_KEYS}
1753
1971
  params.update(params_from_meta)
1754
1972
 
1755
1973
  if template_params:
@@ -1805,7 +2023,7 @@ class Doc(UserList):
1805
2023
  if not mytemplate is None and mytemplate.params:
1806
2024
  params_from_meta = mytemplate.params
1807
2025
  else:
1808
- params_from_meta = {k:v for k, v in meta.items() if not k in ["template_id", "files_to_upload", "additional_files", "attachments", "template"]}
2026
+ params_from_meta = {k:v for k, v in meta.items() if not k in RESERVED_META_KEYS}
1809
2027
  params.update(params_from_meta)
1810
2028
 
1811
2029
  if template_params:
@@ -1879,6 +2097,16 @@ class Doc(UserList):
1879
2097
  Raises:
1880
2098
  Warning: If the provided file path does not end with '.zip' or '.pdf', a warning is issued and the file is assumed to be in PDF format.
1881
2099
 
2100
+ Notes:
2101
+ **Attachments:** files stored in the document metadata (``meta['data']['attachments']``,
2102
+ see ``Doc.set_attachments``, base64 encoded) as well as the template asset files
2103
+ (``meta['data']['files_to_upload']``, see ``Doc.set_template_to_meta``) are decoded
2104
+ and written next to the compiled main file, where templates can reference them by
2105
+ (relative) name. Precedence (highest first): explicit ``files_to_upload`` /
2106
+ ``attachments`` / ``additional_files`` call arguments, document metadata entries,
2107
+ the template's own asset files. Attachments are only shipped for the "typst" and
2108
+ "tex" engines.
2109
+
1882
2110
  See Also:
1883
2111
  additional_files (dict, optional): Passed via **kwargs; merged into files_to_upload.
1884
2112
  attachments (dict, optional): Passed via **kwargs; merged into files_to_upload.
@@ -1888,6 +2116,9 @@ class Doc(UserList):
1888
2116
  if files_to_upload is None:
1889
2117
  files_to_upload = {}
1890
2118
 
2119
+ # explicit call arguments: `attachments` and `additional_files` are
2120
+ # aliases merged under `files_to_upload`; they take precedence over
2121
+ # the attachment files stored in the document metadata (loaded below)
1891
2122
  additional_files = kwargs.pop('additional_files', {})
1892
2123
  if additional_files:
1893
2124
  files_to_upload.update(additional_files)
@@ -1896,8 +2127,9 @@ class Doc(UserList):
1896
2127
  if attachments:
1897
2128
  files_to_upload.update(attachments)
1898
2129
 
1899
- params = {}
1900
2130
  meta = self.get_meta(default={}).get('data', {})
2131
+
2132
+ params = {}
1901
2133
  if engine is None:
1902
2134
  engine = determine_engine_from_template(template)
1903
2135
  if not engine is None and verb:
@@ -1923,9 +2155,16 @@ class Doc(UserList):
1923
2155
  template = mytemplate.template
1924
2156
  tformat = mytemplate.tformat
1925
2157
  params_from_meta = mytemplate.params
2158
+ # mytemplate.attachments already contains the (decoded)
2159
+ # attachment files from the document metadata; explicit call
2160
+ # arguments keep precedence
1926
2161
  files_to_upload = {**mytemplate.attachments, **files_to_upload}
1927
2162
  else:
1928
- params_from_meta = {k:v for k, v in meta.items() if not k in ["template_id", "files_to_upload", "additional_files"]}
2163
+ # no template in the metadata: load the metadata attachment files
2164
+ # here (with a template, get_template_from_meta already loaded
2165
+ # and decoded them into mytemplate.attachments); explicit call
2166
+ # arguments keep precedence over the metadata values
2167
+ files_to_upload, params_from_meta = self._meta_files_and_params(meta, files_to_upload)
1929
2168
 
1930
2169
  params.update(params_from_meta)
1931
2170
 
@@ -1968,7 +2207,7 @@ class Doc(UserList):
1968
2207
  if engine.startswith('typ'):
1969
2208
 
1970
2209
  def _to_pdf_typst(*ar, **kw):
1971
- s, attachments = to_typst(*ar, template=template, template_params=params, ret_attachments=True, template_engine=template_engine)
2210
+ s, attachments = to_typst(*ar, template=template, template_params=params, ret_attachments=True, template_engine=template_engine, verb=verb)
1972
2211
 
1973
2212
  on_warning = kw.pop("on_warning", None)
1974
2213
  if on_warning is None:
@@ -2097,6 +2336,9 @@ class Doc(UserList):
2097
2336
  A ".tex"/".latex" suffix writes the plain LaTeX source; anything else
2098
2337
  (including ".zip" and streams) gets the zipped project folder.
2099
2338
  additional_files: Extra files to include in the ZIP (e.g., images, logos).
2339
+ Attachment files stored in the document metadata (see ``Doc.set_attachments``)
2340
+ are included automatically and base64-decoded; these call arguments take
2341
+ precedence over the metadata values.
2100
2342
  template: The LaTeX template (Jinja2) to use. If None, uses one from document metadata.
2101
2343
  do_escape_template_params: Whether to escape LaTeX special chars in template params.
2102
2344
  'auto' (the default) escapes plain-text values for plain Jinja2 LaTeX templates (strings starting
@@ -2123,9 +2365,16 @@ class Doc(UserList):
2123
2365
  template = mytemplate.template
2124
2366
  if not mytemplate is None:
2125
2367
  params_from_meta = mytemplate.params
2368
+ # mytemplate.attachments already contains the (decoded)
2369
+ # attachment files from the document metadata; explicit call
2370
+ # arguments keep precedence
2126
2371
  additional_files = {**mytemplate.attachments, **additional_files}
2127
2372
  else:
2128
- params_from_meta = {k:v for k, v in meta.items() if not k in ["template_id", "files_to_upload", "additional_files"]}
2373
+ # no template in the metadata: load the metadata attachment files
2374
+ # here (with a template, get_template_from_meta already loaded
2375
+ # and decoded them into mytemplate.attachments); explicit call
2376
+ # arguments keep precedence over the metadata values
2377
+ additional_files, params_from_meta = self._meta_files_and_params(meta, additional_files)
2129
2378
  params.update(params_from_meta)
2130
2379
 
2131
2380
  if template_params:
@@ -2156,7 +2405,10 @@ class Doc(UserList):
2156
2405
  zipf.writestr('doc.json', self.to_json())
2157
2406
  zipf.writestr('main.tex', tex)
2158
2407
  for path in files:
2159
- zipf.writestr(path, files[path])
2408
+ # guard against zip-slip: entry names must stay relative
2409
+ # paths inside the archive (no ".." segments, no
2410
+ # absolute paths)
2411
+ zipf.writestr(sanitize_attachment_name(path), files[path])
2160
2412
  in_memory_zip.seek(0)
2161
2413
  m = in_memory_zip.getvalue()
2162
2414