article 0.1.6__tar.gz → 0.1.7__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 (33) hide show
  1. {article-0.1.6 → article-0.1.7}/PKG-INFO +1 -1
  2. {article-0.1.6 → article-0.1.7}/article/__init__.py +7 -0
  3. article-0.1.7/article/published.py +790 -0
  4. {article-0.1.6 → article-0.1.7}/pyproject.toml +1 -1
  5. article-0.1.7/tests/data/substack_post.html +27 -0
  6. article-0.1.7/tests/test_published.py +231 -0
  7. {article-0.1.6 → article-0.1.7}/.editorconfig +0 -0
  8. {article-0.1.6 → article-0.1.7}/.env.example +0 -0
  9. {article-0.1.6 → article-0.1.7}/.gitattributes +0 -0
  10. {article-0.1.6 → article-0.1.7}/.github/workflows/ci.yml +0 -0
  11. {article-0.1.6 → article-0.1.7}/.gitignore +0 -0
  12. {article-0.1.6 → article-0.1.7}/LICENSE +0 -0
  13. {article-0.1.6 → article-0.1.7}/README.md +0 -0
  14. {article-0.1.6 → article-0.1.7}/article/__main__.py +0 -0
  15. {article-0.1.6 → article-0.1.7}/article/adapters/__init__.py +0 -0
  16. {article-0.1.6 → article-0.1.7}/article/adapters/dev_to.py +0 -0
  17. {article-0.1.6 → article-0.1.7}/article/adapters/hashnode.py +0 -0
  18. {article-0.1.6 → article-0.1.7}/article/adapters/medium.py +0 -0
  19. {article-0.1.6 → article-0.1.7}/article/adapters/substack.py +0 -0
  20. {article-0.1.6 → article-0.1.7}/article/base.py +0 -0
  21. {article-0.1.6 → article-0.1.7}/article/config.py +0 -0
  22. {article-0.1.6 → article-0.1.7}/article/engine.py +0 -0
  23. {article-0.1.6 → article-0.1.7}/article/md_source.py +0 -0
  24. {article-0.1.6 → article-0.1.7}/article/misc/CHANGELOG.md +0 -0
  25. {article-0.1.6 → article-0.1.7}/article/registry.py +0 -0
  26. {article-0.1.6 → article-0.1.7}/article/state.py +0 -0
  27. {article-0.1.6 → article-0.1.7}/article/util.py +0 -0
  28. {article-0.1.6 → article-0.1.7}/examples/article.example.json +0 -0
  29. {article-0.1.6 → article-0.1.7}/tests/conftest.py +0 -0
  30. {article-0.1.6 → article-0.1.7}/tests/test_cli.py +0 -0
  31. {article-0.1.6 → article-0.1.7}/tests/test_pipeline.py +0 -0
  32. {article-0.1.6 → article-0.1.7}/tests/test_substack.py +0 -0
  33. {article-0.1.6 → article-0.1.7}/tests/test_substack_live.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: article
3
- Version: 0.1.6
3
+ Version: 0.1.7
4
4
  Summary: Tools to semi-automate the publication of articles
5
5
  Project-URL: Homepage, https://github.com/thorwhalen/article
6
6
  Project-URL: Repository, https://github.com/thorwhalen/article
@@ -88,6 +88,9 @@ from .engine import (
88
88
  syndicate_secondary,
89
89
  )
90
90
 
91
+ # Read a published post back into ordered items
92
+ from .published import PublishedPost, fetch_published, parse_published
93
+
91
94
  # Importing the adapters package registers all built-in adapters.
92
95
  from . import adapters # noqa: F401 (side-effect: populate the registry)
93
96
 
@@ -138,6 +141,10 @@ __all__ = [
138
141
  "build_engine",
139
142
  "publish_primary",
140
143
  "syndicate_secondary",
144
+ # published posts
145
+ "PublishedPost",
146
+ "fetch_published",
147
+ "parse_published",
141
148
  ]
142
149
 
143
150
  __version__ = "0.1.0"
@@ -0,0 +1,790 @@
1
+ """Read a published post back into ordered items: ``fetch_published(url)``.
2
+
3
+ Turning a published post into another medium (a narrated video, a podcast) needs its
4
+ text and *every image, in order, with its position in the text*, plus each paragraph's
5
+ links. :func:`fetch_published` fetches the page and :func:`parse_published` reads it
6
+ (offline, from saved HTML) into a :class:`PublishedPost`: ordered blocks, each a plain
7
+ ``dict`` with a ``kind`` and an ``index``:
8
+
9
+ - ``heading``: ``level``, ``text``;
10
+ - ``paragraph``, ``quote``: ``text``, ``markdown`` (inline emphasis, links, code),
11
+ ``links`` (``[{"text", "href"}]``), ``footnote_refs`` (the footnote ids it cites);
12
+ - ``list``: ``ordered``, ``items`` (each ``{"text", "markdown", "links"}``);
13
+ - ``image``: ``src`` (the original, with a CDN fetch wrapper removed), ``cdn_src``
14
+ (what the page served), ``alt``, ``caption``, ``href`` (what the image links to),
15
+ ``width``, ``height``, ``follows`` (the ``index`` of the block just above it, or
16
+ ``None``), ``local_file`` (when ``assets_dir`` was given);
17
+ - ``footnote``: ``id``, ``text``, ``markdown``, ``links``;
18
+ - ``table``: ``rows`` (lists of cell texts); ``embed``: ``tag``, ``src`` (an iframe,
19
+ video or audio, which a reader cannot turn into text);
20
+ - ``code``: ``text``; ``divider``.
21
+
22
+ :meth:`PublishedPost.to_markdown` renders the items as the Markdown that
23
+ ``draft-substack`` consumes, so a round trip is possible.
24
+
25
+ Substack is read first (the post body is ``div.body.markup``; images are wrapped by
26
+ its CDN, ``/image/fetch/<options>/<url-encoded original>``); any page with an
27
+ ``<article>`` or a ``<body>`` is read as plain HTML. The reader is the seam for other
28
+ platforms: the page fetch (``get_html=``), the image download (``download=``) and the
29
+ HTML-to-items step (``reader=``, a function ``(root, url) -> items``) are each one
30
+ replaceable argument.
31
+
32
+ Safety: the default fetchers read only ``http(s)`` URLs, refuse hosts that resolve to
33
+ a private, loopback or link-local address (also across redirects), cap what they read
34
+ (:data:`MAX_IMAGE_BYTES`) and accept images only. An image that fails to download gets
35
+ an ``error`` field and the rest carry on. Links with a scheme other than ``http``,
36
+ ``https`` or ``mailto`` are kept as text only.
37
+
38
+ >>> html = '<div class="body markup"><h2>Hi</h2><p>A <a href="https://x.org">link</a>.</p></div>'
39
+ >>> post = parse_published(html, url="https://example.substack.com/p/hi")
40
+ >>> [(i["kind"], i["text"]) for i in post.items]
41
+ [('heading', 'Hi'), ('paragraph', 'A link.')]
42
+ >>> post.items[1]["links"]
43
+ [{'text': 'link', 'href': 'https://x.org'}]
44
+ """
45
+
46
+ from __future__ import annotations
47
+
48
+ import ipaddress
49
+ import json
50
+ import re
51
+ import socket
52
+ from collections.abc import Callable, Iterator
53
+ from dataclasses import dataclass, field
54
+ from html.parser import HTMLParser
55
+ from pathlib import Path
56
+ from typing import Any, Optional
57
+ from urllib.parse import unquote, urljoin, urlparse
58
+
59
+ #: Elements with no end tag, and elements whose content is never part of a post.
60
+ _VOID = {
61
+ "area",
62
+ "base",
63
+ "br",
64
+ "col",
65
+ "embed",
66
+ "hr",
67
+ "img",
68
+ "input",
69
+ "link",
70
+ "meta",
71
+ "source",
72
+ "wbr",
73
+ }
74
+ _SKIP = {
75
+ "script",
76
+ "style",
77
+ "svg",
78
+ "button",
79
+ "form",
80
+ "noscript",
81
+ "template",
82
+ "head",
83
+ "nav",
84
+ "header",
85
+ "footer",
86
+ "aside",
87
+ }
88
+ _EMBEDS = {"iframe", "video", "audio"}
89
+ #: Elements that end an open ``p`` when they start, and the list/table implied ends.
90
+ _CLOSES_P = {
91
+ "p",
92
+ "div",
93
+ "ul",
94
+ "ol",
95
+ "blockquote",
96
+ "pre",
97
+ "table",
98
+ "figure",
99
+ "hr",
100
+ "section",
101
+ "article",
102
+ *{f"h{n}" for n in range(1, 7)},
103
+ }
104
+ _BLOCK_TAGS = _CLOSES_P | {"li", "tr", "td", "th", "figcaption"}
105
+ _ALLOWED_SCHEMES = ("http", "https", "mailto")
106
+ MAX_DEPTH = 100
107
+ MAX_IMAGE_BYTES = 25 * 1024 * 1024
108
+ MAX_PAGE_BYTES = 10 * 1024 * 1024
109
+ MAX_REDIRECTS = 5
110
+ MAX_NAME_CHARS = 100
111
+ #: Class fragments of Substack's widgets (subscribe boxes, share buttons) inside a post body.
112
+ _WIDGET_CLASSES = (
113
+ "subscription-widget",
114
+ "button-wrapper",
115
+ "subscribe-widget",
116
+ "share-dialog",
117
+ )
118
+ _HEADINGS = {f"h{n}": n for n in range(1, 7)}
119
+ _INLINE_MARKS = {
120
+ "strong": "**",
121
+ "b": "**",
122
+ "em": "*",
123
+ "i": "*",
124
+ "code": "`",
125
+ "del": "~~",
126
+ "s": "~~",
127
+ }
128
+ _BLOCKS = {"p", "ul", "ol", "blockquote", "pre", "hr", "figure", "img", *_HEADINGS}
129
+ #: ``https://substackcdn.com/image/fetch/<options>/<url-encoded original>``.
130
+ _CDN_FETCH = re.compile(
131
+ r"/image/fetch/(?:[^/]*/)*?(https?(?:%3A|:)(?:%2F|/)(?:%2F|/).+)$", re.IGNORECASE
132
+ )
133
+ DFLT_TIMEOUT_S = 30
134
+ DFLT_USER_AGENT = "article-fetch-published (+https://github.com/thorwhalen/article)"
135
+
136
+
137
+ @dataclass
138
+ class _Node:
139
+ tag: str
140
+ attrs: dict = field(default_factory=dict)
141
+ children: list = field(default_factory=list) # _Node or str
142
+
143
+ @property
144
+ def classes(self) -> set:
145
+ return set((self.attrs.get("class") or "").split())
146
+
147
+ def find(self, pred) -> Optional["_Node"]:
148
+ for node in self.walk():
149
+ if pred(node):
150
+ return node
151
+ return None
152
+
153
+ def walk(self) -> Iterator["_Node"]:
154
+ pending = [iter(self.children)]
155
+ while pending:
156
+ for child in pending[-1]:
157
+ if isinstance(child, _Node):
158
+ yield child
159
+ pending.append(iter(child.children))
160
+ break
161
+ else:
162
+ pending.pop()
163
+
164
+
165
+ class _TreeBuilder(HTMLParser):
166
+ """A forgiving HTML tree: unclosed tags are closed by their parent's end tag."""
167
+
168
+ def __init__(self):
169
+ super().__init__(convert_charrefs=True)
170
+ self.root = _Node("root")
171
+ self._stack = [self.root]
172
+
173
+ def _close_implied(self, tag):
174
+ top = self._stack[-1].tag
175
+ if tag in _CLOSES_P and top == "p":
176
+ self._stack.pop()
177
+ elif tag == "li":
178
+ for depth in range(len(self._stack) - 1, 0, -1):
179
+ if self._stack[depth].tag == "li":
180
+ del self._stack[depth:]
181
+ break
182
+ if self._stack[depth].tag in ("ul", "ol"):
183
+ break
184
+ elif tag in ("td", "th", "tr") and top in ("td", "th"):
185
+ self._stack.pop()
186
+ if tag == "tr" and self._stack[-1].tag == "tr":
187
+ self._stack.pop()
188
+
189
+ def handle_starttag(self, tag, attrs):
190
+ self._close_implied(tag)
191
+ node = _Node(tag, {k: v or "" for k, v in attrs})
192
+ self._stack[-1].children.append(node)
193
+ if tag not in _VOID and len(self._stack) < MAX_DEPTH:
194
+ self._stack.append(node)
195
+
196
+ def handle_startendtag(self, tag, attrs):
197
+ self._stack[-1].children.append(_Node(tag, {k: v or "" for k, v in attrs}))
198
+
199
+ def handle_endtag(self, tag):
200
+ for depth in range(len(self._stack) - 1, 0, -1):
201
+ if self._stack[depth].tag == tag:
202
+ del self._stack[depth:]
203
+ return
204
+
205
+ def handle_data(self, data):
206
+ self._stack[-1].children.append(data)
207
+
208
+
209
+ def original_image_url(src: str) -> str:
210
+ """The original image behind a Substack CDN fetch wrapper (others come back as they are).
211
+
212
+ >>> original_image_url("https://substackcdn.com/image/fetch/w_1456,c_limit,f_auto/https%3A%2F%2Fbucket.s3.amazonaws.com%2Fpublic%2Fimages%2Fa.png")
213
+ 'https://bucket.s3.amazonaws.com/public/images/a.png'
214
+ >>> original_image_url("https://example.org/a.png")
215
+ 'https://example.org/a.png'
216
+ """
217
+ m = _CDN_FETCH.search(src or "")
218
+ return unquote(m.group(1)) if m else src
219
+
220
+
221
+ def _is_hidden(node: _Node) -> bool:
222
+ return node.tag in _SKIP or any(
223
+ w in cls for cls in node.classes for w in _WIDGET_CLASSES
224
+ )
225
+
226
+
227
+ _MD_SPECIAL = re.compile(r"([\\`*_\[\]<>])")
228
+
229
+
230
+ def _escape(text: str) -> str:
231
+ return _MD_SPECIAL.sub(r"\\\1", text)
232
+
233
+
234
+ def _safe_href(href: str, base: str) -> Optional[str]:
235
+ full = urljoin(base, href.strip())
236
+ scheme = urlparse(full).scheme.lower()
237
+ return full if scheme in _ALLOWED_SCHEMES or (not scheme and full) else None
238
+
239
+
240
+ def _md_href(href: str) -> str:
241
+ return f"<{href}>" if re.search(r"[\s()<>]", href) else href
242
+
243
+
244
+ def _wrap(mark_open: str, inner: str, mark_close: str = "") -> str:
245
+ """``inner`` inside marks, with its edge spaces kept outside them."""
246
+ core = inner.strip()
247
+ if not core:
248
+ return inner
249
+ lead, trail = (
250
+ inner[: len(inner) - len(inner.lstrip())],
251
+ inner[len(inner.rstrip()) :],
252
+ )
253
+ return f"{lead}{mark_open}{core}{mark_close or mark_open}{trail}"
254
+
255
+
256
+ def _inline(node: _Node, base: str, links: list, refs: list) -> tuple[str, str]:
257
+ """``(plain text, inline markdown)`` of a node's content; collects links and footnote refs."""
258
+ plain, md = [], []
259
+ for child in node.children:
260
+ if isinstance(child, str):
261
+ text = re.sub(r"\s+", " ", child)
262
+ plain.append(text)
263
+ md.append(_escape(text))
264
+ continue
265
+ if _is_hidden(child):
266
+ continue
267
+ if child.tag == "br":
268
+ plain.append("\n")
269
+ md.append("\n")
270
+ elif child.tag == "img":
271
+ continue
272
+ elif (
273
+ child.tag in _BLOCK_TAGS
274
+ ): # a paragraph inside a quote, a footnote, an item
275
+ inner_plain, inner_md = _inline(child, base, links, refs)
276
+ plain.append("\n" + inner_plain + "\n")
277
+ md.append("\n" + inner_md + "\n")
278
+ elif child.tag == "a" and "footnote-anchor" in child.classes:
279
+ number = _footnote_id(child)
280
+ refs.append(number)
281
+ md.append(f"[^{number}]")
282
+ elif child.tag == "a" and child.attrs.get("href"):
283
+ inner_plain, inner_md = _inline(child, base, links, refs)
284
+ href = _safe_href(child.attrs["href"], base)
285
+ plain.append(inner_plain)
286
+ if href and inner_plain.strip():
287
+ links.append({"text": inner_plain.strip(), "href": href})
288
+ md.append(_wrap("[", inner_md, f"]({_md_href(href)})"))
289
+ else:
290
+ md.append(inner_md)
291
+ else:
292
+ inner_plain, inner_md = _inline(child, base, links, refs)
293
+ mark = _INLINE_MARKS.get(child.tag, "")
294
+ plain.append(inner_plain)
295
+ if child.tag == "code":
296
+ md.append(_wrap("`", inner_plain))
297
+ else:
298
+ md.append(_wrap(mark, inner_md) if mark else inner_md)
299
+ return "".join(plain), "".join(md)
300
+
301
+
302
+ def _footnote_id(anchor: _Node) -> str:
303
+ href = anchor.attrs.get("href", "") or anchor.attrs.get("id", "")
304
+ m = re.search(r"(\d+)\s*$", href) or re.search(r"(\d+)", _text_of(anchor))
305
+ if m:
306
+ return m.group(1)
307
+ label = re.sub(r"\W+", "", _text_of(anchor))
308
+ return label or "note"
309
+
310
+
311
+ def _text_of(node: _Node) -> str:
312
+ return "".join(
313
+ c if isinstance(c, str) else ("" if _is_hidden(c) else _text_of(c))
314
+ for c in node.children
315
+ )
316
+
317
+
318
+ def _clean(text: str) -> str:
319
+ return re.sub(r"[ \t]+", " ", re.sub(r"\s*\n\s*", "\n", text)).strip()
320
+
321
+
322
+ def _text_block(kind: str, node: _Node, base: str) -> Optional[dict]:
323
+ links, refs = [], []
324
+ plain, md = _inline(node, base, links, refs)
325
+ plain, md = _clean(plain), _clean(md)
326
+ if not plain:
327
+ return None
328
+ block = {"kind": kind, "text": plain, "markdown": md, "links": links}
329
+ if refs:
330
+ block["footnote_refs"] = refs
331
+ return block
332
+
333
+
334
+ def _image(img: _Node, container: _Node, base: str) -> Optional[dict]:
335
+ attrs = {}
336
+ try:
337
+ loaded = json.loads(img.attrs.get("data-attrs") or "{}")
338
+ attrs = loaded if isinstance(loaded, dict) else {}
339
+ except ValueError:
340
+ pass
341
+ cdn_src = img.attrs.get("src") or ""
342
+ data_src = attrs.get("src")
343
+ src = (
344
+ data_src if isinstance(data_src, str) and data_src else ""
345
+ ) or original_image_url(cdn_src)
346
+ if not src:
347
+ return None
348
+ caption_node = container.find(lambda n: n.tag == "figcaption")
349
+ link = container.find(
350
+ lambda n: n.tag == "a" and "image-link" in n.classes and n.attrs.get("href")
351
+ )
352
+ link = link or container.find(
353
+ lambda n: n.tag == "a" and n.attrs.get("href") and n.find(lambda m: m is img)
354
+ )
355
+ alt = attrs.get("alt") if isinstance(attrs.get("alt"), str) else ""
356
+ return {
357
+ "kind": "image",
358
+ "src": urljoin(base, src),
359
+ "cdn_src": cdn_src or None,
360
+ "alt": (img.attrs.get("alt") or alt or "").strip(),
361
+ "caption": _clean(_text_of(caption_node)) if caption_node else "",
362
+ "href": _safe_href(link.attrs["href"], base) if link else None,
363
+ "width": _number(attrs.get("width") or img.attrs.get("width")),
364
+ "height": _number(attrs.get("height") or img.attrs.get("height")),
365
+ }
366
+
367
+
368
+ def _number(value) -> Optional[int]:
369
+ try:
370
+ return int(float(value))
371
+ except (TypeError, ValueError, OverflowError):
372
+ return None
373
+
374
+
375
+ def _images_in(
376
+ node: _Node, base: str, *, container: Optional[_Node] = None
377
+ ) -> Iterator[dict]:
378
+ for img in (n for n in node.walk() if n.tag == "img"):
379
+ block = _image(img, container or node, base)
380
+ if block:
381
+ yield block
382
+
383
+
384
+ def _has_block(node: _Node) -> bool:
385
+ return any(
386
+ n.tag in _BLOCK_TAGS
387
+ or n.tag in _HEADINGS
388
+ or n.tag in ("img", "table", *_EMBEDS)
389
+ for n in node.walk()
390
+ )
391
+
392
+
393
+ def _paragraph_parts(node: _Node, base: str) -> Iterator[dict]:
394
+ """A paragraph's text and images, in the order they sit in it."""
395
+ buffer: list = []
396
+
397
+ def flush():
398
+ if buffer:
399
+ block = _text_block("paragraph", _Node("p", children=list(buffer)), base)
400
+ buffer.clear()
401
+ return [block] if block else []
402
+ return []
403
+
404
+ for child in node.children:
405
+ if isinstance(child, _Node) and (
406
+ child.tag == "img" or any(n.tag == "img" for n in child.walk())
407
+ ):
408
+ yield from flush()
409
+ if child.tag != "img":
410
+ bare = _Node(
411
+ child.tag,
412
+ child.attrs,
413
+ [
414
+ c
415
+ for c in child.children
416
+ if not (isinstance(c, _Node) and c.tag == "img")
417
+ ],
418
+ )
419
+ block = _text_block("paragraph", _Node("p", children=[bare]), base)
420
+ if block:
421
+ yield block
422
+ yield from _images_in(
423
+ child if child.tag != "img" else _Node("x", children=[child]),
424
+ base,
425
+ container=child,
426
+ )
427
+ else:
428
+ buffer.append(child)
429
+ yield from flush()
430
+
431
+
432
+ def _table(node: _Node) -> Optional[dict]:
433
+ rows = [
434
+ [
435
+ _clean(_text_of(c))
436
+ for c in tr.children
437
+ if isinstance(c, _Node) and c.tag in ("td", "th")
438
+ ]
439
+ for tr in node.walk()
440
+ if tr.tag == "tr"
441
+ ]
442
+ rows = [r for r in rows if any(r)]
443
+ return {"kind": "table", "rows": rows} if rows else None
444
+
445
+
446
+ def _blocks(node: _Node, base: str) -> Iterator[dict]:
447
+ loose: list = []
448
+
449
+ def flush():
450
+ parts = (
451
+ list(_paragraph_parts(_Node("p", children=list(loose)), base))
452
+ if any(not isinstance(c, str) or c.strip() for c in loose)
453
+ else []
454
+ )
455
+ loose.clear()
456
+ return parts
457
+
458
+ for child in node.children:
459
+ if isinstance(child, str) or (
460
+ isinstance(child, _Node)
461
+ and not _is_hidden(child)
462
+ and child.tag not in _BLOCK_TAGS
463
+ and child.tag not in _HEADINGS
464
+ and child.tag not in ("img", "table", "pre", *_EMBEDS)
465
+ and not _has_block(child)
466
+ and not child.classes & {"captioned-image-container", "footnote"}
467
+ ):
468
+ loose.append(child)
469
+ continue
470
+ yield from flush()
471
+ if not isinstance(child, _Node) or _is_hidden(child):
472
+ continue
473
+ tag = child.tag
474
+ if tag in _HEADINGS:
475
+ block = _text_block("heading", child, base)
476
+ if block:
477
+ yield {**block, "level": _HEADINGS[tag]}
478
+ yield from _images_in(child, base)
479
+ elif tag == "p":
480
+ yield from _paragraph_parts(child, base)
481
+ elif tag in ("ul", "ol"):
482
+ entries = [
483
+ e
484
+ for li in child.walk()
485
+ if li.tag == "li"
486
+ for e in [_text_block("item", li, base)]
487
+ if e
488
+ ]
489
+ if entries:
490
+ yield {
491
+ "kind": "list",
492
+ "ordered": tag == "ol",
493
+ "items": [
494
+ {
495
+ k: e[k]
496
+ for k in ("text", "markdown", "links", "footnote_refs")
497
+ if k in e
498
+ }
499
+ for e in entries
500
+ ],
501
+ }
502
+ yield from _images_in(child, base)
503
+ elif tag == "blockquote":
504
+ block = _text_block("quote", child, base)
505
+ if block:
506
+ yield block
507
+ yield from _images_in(child, base)
508
+ elif tag == "pre":
509
+ yield {"kind": "code", "text": _text_of(child).strip("\n")}
510
+ elif tag == "hr":
511
+ yield {"kind": "divider"}
512
+ elif tag == "table":
513
+ block = _table(child)
514
+ if block:
515
+ yield block
516
+ elif tag in _EMBEDS:
517
+ src = child.attrs.get("src") or next(
518
+ (
519
+ n.attrs.get("src")
520
+ for n in child.walk()
521
+ if n.tag == "source" and n.attrs.get("src")
522
+ ),
523
+ None,
524
+ )
525
+ if src:
526
+ yield {"kind": "embed", "tag": tag, "src": urljoin(base, src)}
527
+ elif tag == "img":
528
+ block = _image(child, child, base)
529
+ if block:
530
+ yield block
531
+ elif tag == "figure" or "captioned-image-container" in child.classes:
532
+ yield from _images_in(child, base)
533
+ elif "footnote" in child.classes and tag == "div":
534
+ number = child.find(lambda n: "footnote-number" in n.classes)
535
+ content = child.find(lambda n: "footnote-content" in n.classes) or child
536
+ block = _text_block("footnote", content, base)
537
+ if block:
538
+ yield {**block, "id": _footnote_id(number) if number else "note"}
539
+ else:
540
+ yield from _blocks(child, base)
541
+ yield from flush()
542
+
543
+
544
+ def _content_root(root: _Node) -> _Node:
545
+ return (
546
+ root.find(lambda n: {"body", "markup"} <= n.classes)
547
+ or root.find(lambda n: n.tag == "article")
548
+ or root.find(lambda n: n.tag == "body")
549
+ or root
550
+ )
551
+
552
+
553
+ def _read_items(root: _Node, url: str) -> list[dict]:
554
+ return list(_blocks(_content_root(root), url))
555
+
556
+
557
+ def _meta(root: _Node, *names) -> Optional[str]:
558
+ for n in root.walk():
559
+ if n.tag == "meta" and (
560
+ n.attrs.get("property") in names or n.attrs.get("name") in names
561
+ ):
562
+ return (n.attrs.get("content") or "").strip() or None
563
+ return None
564
+
565
+
566
+ @dataclass
567
+ class PublishedPost:
568
+ """A published post: its ``title``, ``url`` and the ordered ``items``."""
569
+
570
+ url: str
571
+ title: Optional[str]
572
+ items: list[dict]
573
+ author: Optional[str] = None
574
+ published: Optional[str] = None
575
+ subtitle: Optional[str] = None
576
+ truncated: bool = False # a paywall cuts the post: only its free part is here
577
+
578
+ def of_kind(self, kind: str) -> list[dict]:
579
+ """The items of one kind, in order."""
580
+ return [i for i in self.items if i["kind"] == kind]
581
+
582
+ @property
583
+ def images(self) -> list[dict]:
584
+ return self.of_kind("image")
585
+
586
+ def to_markdown(self) -> str:
587
+ """The post as Markdown, the form ``draft-substack`` reads.
588
+
589
+ >>> post = PublishedPost("u", "T", [{"kind": "heading", "level": 2, "text": "H", "markdown": "H", "index": 0}])
590
+ >>> post.to_markdown()
591
+ '## H\\n'
592
+ """
593
+ out = []
594
+ for item in self.items:
595
+ kind = item["kind"]
596
+ if kind == "heading":
597
+ out.append(
598
+ "#" * item["level"] + " " + item["markdown"].replace("\n", " ")
599
+ )
600
+ elif kind == "paragraph":
601
+ out.append(_line_start_safe(item["markdown"]))
602
+ elif kind == "quote":
603
+ out.append("\n".join("> " + ln for ln in item["markdown"].splitlines()))
604
+ elif kind == "list":
605
+ out.append(
606
+ "\n".join(
607
+ (f"{n}. " if item["ordered"] else "- ")
608
+ + e["markdown"].replace("\n", " ")
609
+ for n, e in enumerate(item["items"], 1)
610
+ )
611
+ )
612
+ elif kind == "code":
613
+ fence = "`" * max(
614
+ 3,
615
+ 1
616
+ + max((len(r) for r in re.findall(r"`+", item["text"])), default=0),
617
+ )
618
+ out.append(f"{fence}\n{item['text']}\n{fence}")
619
+ elif kind == "divider":
620
+ out.append("---")
621
+ elif kind == "table":
622
+ rows = item["rows"]
623
+ width = max(len(r) for r in rows)
624
+ cells = [
625
+ [_escape(c).replace("|", "\\|") for c in r]
626
+ + [""] * (width - len(r))
627
+ for r in rows
628
+ ]
629
+ out.append(
630
+ "\n".join(
631
+ ["| " + " | ".join(cells[0]) + " |", "|" + " --- |" * width]
632
+ + ["| " + " | ".join(r) + " |" for r in cells[1:]]
633
+ )
634
+ )
635
+ elif kind == "image":
636
+ target = item.get("local_file") or item["src"]
637
+ title = (
638
+ f' "{item["caption"].replace(chr(34), chr(92) + chr(34))}"'
639
+ if item["caption"]
640
+ else ""
641
+ )
642
+ out.append(
643
+ f"![{item['alt'].replace(']', chr(92) + ']')}](<{target}>{title})"
644
+ )
645
+ elif kind == "embed":
646
+ out.append(f"<{item['src']}>")
647
+ elif kind == "footnote":
648
+ out.append(f"[^{item['id']}]: {item['markdown'].replace(chr(10), ' ')}")
649
+ return "\n\n".join(out) + "\n"
650
+
651
+
652
+ def _line_start_safe(markdown: str) -> str:
653
+ """Escape a paragraph's line starts that Markdown would read as a list, heading or quote."""
654
+ return re.sub(
655
+ r"(?m)^(\s*)(\d+)([.)])(?=\s)",
656
+ r"\1\2\\\3",
657
+ re.sub(r"(?m)^(\s*)([#>+\-])(?=\s|#)", r"\1\\\2", markdown),
658
+ )
659
+
660
+
661
+ def parse_published(
662
+ html: str,
663
+ *,
664
+ url: str = "",
665
+ assets_dir: Optional[str | Path] = None,
666
+ download: Optional[Callable[[str], bytes]] = None,
667
+ reader: Callable[[_Node, str], list] = None,
668
+ ) -> PublishedPost:
669
+ """Read a published post's HTML into a :class:`PublishedPost` (no network unless asked).
670
+
671
+ ``reader(root, url) -> items`` replaces the HTML-to-items step (the default reads
672
+ Substack's markup, or any ``<article>``/``<body>``).
673
+
674
+ With ``assets_dir``, each image's original is downloaded there (``download(url) ->
675
+ bytes``, by default an HTTP GET) and the item gets ``local_file``.
676
+ """
677
+ builder = _TreeBuilder()
678
+ builder.feed(html)
679
+ builder.close()
680
+ root = builder.root
681
+ items = list((reader or _read_items)(root, url))
682
+ for index, item in enumerate(items):
683
+ item["index"] = index
684
+ if item["kind"] == "image":
685
+ item["follows"] = index - 1 if index else None
686
+ title_node = root.find(
687
+ lambda n: n.tag == "h1" and "post-title" in n.classes
688
+ ) or root.find(lambda n: n.tag == "h1")
689
+ title = (_clean(_text_of(title_node)) if title_node else None) or _meta(
690
+ root, "og:title", "twitter:title"
691
+ )
692
+ sub = root.find(lambda n: n.tag == "h3" and "subtitle" in n.classes)
693
+ post = PublishedPost(
694
+ url=url,
695
+ title=title,
696
+ items=items,
697
+ author=_meta(root, "author", "article:author"),
698
+ published=_meta(root, "article:published_time"),
699
+ subtitle=_clean(_text_of(sub)) if sub else None,
700
+ truncated=bool(
701
+ root.find(lambda n: "paywall" in n.classes or "paywall-jump" in n.classes)
702
+ ),
703
+ )
704
+ if assets_dir is not None:
705
+ _download_images(post, Path(assets_dir), download or _http_bytes)
706
+ return post
707
+
708
+
709
+ def _check_public_http(url: str) -> None:
710
+ """Refuse anything but http(s) to a public address (private, loopback, link-local)."""
711
+ parts = urlparse(url)
712
+ if parts.scheme not in ("http", "https") or not parts.hostname:
713
+ raise ValueError(f"only http(s) URLs are fetched, got {url!r}")
714
+ for info in socket.getaddrinfo(
715
+ parts.hostname, parts.port or 80, proto=socket.IPPROTO_TCP
716
+ ):
717
+ address = ipaddress.ip_address(info[4][0])
718
+ if not address.is_global:
719
+ raise ValueError(
720
+ f"{parts.hostname} resolves to a non-public address; not fetched"
721
+ )
722
+
723
+
724
+ def _http_get(url: str, *, max_bytes: int, image_only: bool = False):
725
+ """GET with the safety rules: public hosts only (each redirect checked), a byte cap."""
726
+ import httpx
727
+
728
+ headers = {"User-Agent": DFLT_USER_AGENT}
729
+ for _ in range(MAX_REDIRECTS + 1):
730
+ _check_public_http(url)
731
+ with httpx.stream("GET", url, timeout=DFLT_TIMEOUT_S, headers=headers) as reply:
732
+ if reply.is_redirect:
733
+ url = urljoin(url, reply.headers["location"])
734
+ continue
735
+ reply.raise_for_status()
736
+ if image_only and not reply.headers.get("content-type", "").startswith(
737
+ "image/"
738
+ ):
739
+ raise ValueError(f"not an image: {reply.headers.get('content-type')!r}")
740
+ body = bytearray()
741
+ for chunk in reply.iter_bytes():
742
+ body += chunk
743
+ if len(body) > max_bytes:
744
+ raise ValueError(f"more than {max_bytes} bytes; not read further")
745
+ return bytes(body), reply.encoding or "utf-8"
746
+ raise ValueError("too many redirects")
747
+
748
+
749
+ def _http_bytes(url: str) -> bytes:
750
+ return _http_get(url, max_bytes=MAX_IMAGE_BYTES, image_only=True)[0]
751
+
752
+
753
+ def _http_html(url: str) -> str:
754
+ body, encoding = _http_get(url, max_bytes=MAX_PAGE_BYTES)
755
+ return body.decode(encoding, errors="replace")
756
+
757
+
758
+ def _download_images(post: PublishedPost, assets_dir: Path, download) -> None:
759
+ assets_dir.mkdir(parents=True, exist_ok=True)
760
+ for number, image in enumerate(post.images, 1):
761
+ name = (Path(urlparse(image["src"]).path).name or f"image-{number}")[
762
+ -MAX_NAME_CHARS:
763
+ ]
764
+ target = assets_dir / f"{number:03d}-{name}"
765
+ try:
766
+ target.write_bytes(download(image["src"]))
767
+ image["local_file"] = str(target)
768
+ except Exception as error: # one bad image must not lose the post
769
+ image["error"] = f"{type(error).__name__}: {error}"
770
+
771
+
772
+ def fetch_published(
773
+ url: str,
774
+ *,
775
+ assets_dir: Optional[str | Path] = None,
776
+ get_html: Callable[[str], str] = _http_html,
777
+ download: Optional[Callable[[str], bytes]] = None,
778
+ ) -> PublishedPost:
779
+ """Fetch a published post and read it into ordered items.
780
+
781
+ ``assets_dir`` downloads the images there. ``get_html(url) -> str`` and
782
+ ``download(url) -> bytes`` are the network seams (tests and other callers pass their own).
783
+
784
+ >>> post = fetch_published("https://x.substack.com/p/p", get_html=lambda u: "<article><p>Hello</p></article>")
785
+ >>> post.items[0]["text"]
786
+ 'Hello'
787
+ """
788
+ return parse_published(
789
+ get_html(url), url=url, assets_dir=assets_dir, download=download
790
+ )
@@ -6,7 +6,7 @@ build-backend = "hatchling.build"
6
6
 
7
7
  [project]
8
8
  name = "article"
9
- version = "0.1.6"
9
+ version = "0.1.7"
10
10
  description = "Tools to semi-automate the publication of articles"
11
11
  readme = "README.md"
12
12
  requires-python = ">=3.10"
@@ -0,0 +1,27 @@
1
+ <!DOCTYPE html>
2
+ <html><head>
3
+ <title>Paper boats - Example Letters</title>
4
+ <meta property="og:title" content="Paper boats">
5
+ <meta property="og:description" content="A short walk by the stream">
6
+ <meta name="author" content="Ada Example">
7
+ <meta property="article:published_time" content="2026-11-02T08:00:00.000Z">
8
+ <script>var junk = "<p>not content</p>";</script>
9
+ </head><body>
10
+ <div class="header"><h1 class="post-title published">Paper boats</h1><h3 class="subtitle">A short walk by the stream</h3></div>
11
+ <div class="available-content"><div dir="auto" class="body markup">
12
+ <p>We set out at dawn, with <em>nothing</em> but a <strong>notebook</strong> and <a href="https://example.org/map">a map</a>.<a class="footnote-anchor" data-component-name="FootnoteAnchorToDOM" id="footnote-anchor-1" href="#footnote-1" target="_self">1</a></p>
13
+ <div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!aB1!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fboat.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/w_424/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fboat.png 424w"><img src="https://substackcdn.com/image/fetch/$s_!aB1!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fboat.png" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/boat.png&quot;,&quot;height&quot;:600,&quot;width&quot;:900,&quot;type&quot;:&quot;image/png&quot;}" alt="A folded boat on water" width="900" height="600" class="sizing-normal"></picture></div></a><figcaption class="image-caption">The first boat, <a href="https://example.org/boat">launched</a> at 6:12.</figcaption></figure></div>
14
+ <h2 class="header-anchor-post">Part one</h2>
15
+ <div class="subscription-widget-wrap"><div class="subscription-widget"><p>Subscribe now</p><button>Subscribe</button></div></div>
16
+ <p>Second paragraph.<br>With a line break.</p>
17
+ <blockquote><p>Water finds its level.</p></blockquote>
18
+ <ul><li>one <a href="/relative">link</a></li><li>two</li></ul>
19
+ <ol><li>first</li><li>second</li></ol>
20
+ <hr>
21
+ <pre><code>print("boat")</code></pre>
22
+ <div class="captioned-image-container"><figure><a class="image-link" href="https://substackcdn.com/image/fetch/w_1456/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fstream.jpg"><img src="https://substackcdn.com/image/fetch/w_1456,c_limit/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fstream.jpg" alt=""></a></figure></div>
23
+ <p>The end.</p>
24
+ <div class="footnote" data-component-name="FootnoteToDOM"><a id="footnote-1" href="#footnote-anchor-1" class="footnote-number" contenteditable="false" target="_self">1</a><div class="footnote-content"><p>See <a href="https://example.org/notes">the notes</a>.</p></div></div>
25
+ </div></div>
26
+ <div class="footer"><p>Share this post</p></div>
27
+ </body></html>
@@ -0,0 +1,231 @@
1
+ """fetch_published: a saved Substack post becomes ordered items, offline."""
2
+
3
+ from pathlib import Path
4
+
5
+ import pytest
6
+
7
+ import article
8
+ from article.published import fetch_published, original_image_url, parse_published
9
+
10
+ HTML = (Path(__file__).parent / "data" / "substack_post.html").read_text()
11
+ URL = "https://example.substack.com/p/paper-boats"
12
+
13
+
14
+ @pytest.fixture
15
+ def post():
16
+ return parse_published(HTML, url=URL)
17
+
18
+
19
+ def test_items_come_in_page_order_with_indexes(post):
20
+ kinds = [i["kind"] for i in post.items]
21
+ assert kinds == [
22
+ "paragraph", "image", "heading", "paragraph", "quote",
23
+ "list", "list", "divider", "code", "image", "paragraph", "footnote",
24
+ ]
25
+ assert [i["index"] for i in post.items] == list(range(len(kinds)))
26
+
27
+
28
+ def test_page_chrome_widgets_and_scripts_are_not_content(post):
29
+ text = " ".join(i.get("text", "") for i in post.items)
30
+ for junk in ("Subscribe", "Share this post", "not content"):
31
+ assert junk not in text
32
+
33
+
34
+ def test_title_and_metadata(post):
35
+ assert post.title == "Paper boats" and post.subtitle == "A short walk by the stream"
36
+ assert post.author == "Ada Example" and post.published.startswith("2026-11-02")
37
+
38
+
39
+ def test_paragraph_text_markdown_links_and_footnote_refs(post):
40
+ first = post.items[0]
41
+ assert first["text"].startswith("We set out at dawn, with nothing but a notebook and a map.")
42
+ assert "*nothing*" in first["markdown"] and "**notebook**" in first["markdown"]
43
+ assert "[a map](https://example.org/map)" in first["markdown"]
44
+ assert first["links"] == [{"text": "a map", "href": "https://example.org/map"}]
45
+ assert first["footnote_refs"] == ["1"] and "[^1]" in first["markdown"]
46
+
47
+
48
+ def test_images_carry_original_alt_caption_size_and_position(post):
49
+ boat, stream = post.images
50
+ assert boat["src"] == "https://substack-post-media.s3.amazonaws.com/public/images/boat.png"
51
+ assert boat["cdn_src"].startswith("https://substackcdn.com/image/fetch/")
52
+ assert boat["alt"] == "A folded boat on water" and boat["caption"] == "The first boat, launched at 6:12."
53
+ assert (boat["width"], boat["height"]) == (900, 600)
54
+ assert boat["href"].startswith("https://substackcdn.com/")
55
+ assert boat["follows"] == 0 and post.items[boat["follows"]]["kind"] == "paragraph"
56
+ # no data-attrs: the original is decoded from the CDN wrapper
57
+ assert stream["src"] == "https://substack-post-media.s3.amazonaws.com/public/images/stream.jpg"
58
+ assert stream["alt"] == "" and stream["caption"] == "" and stream["follows"] == 8
59
+
60
+
61
+ def test_headings_lists_quote_code_divider(post):
62
+ by_kind = {i["kind"]: i for i in post.items}
63
+ assert (by_kind["heading"]["level"], by_kind["heading"]["text"]) == (2, "Part one")
64
+ assert by_kind["quote"]["text"] == "Water finds its level."
65
+ lists = post.of_kind("list")
66
+ assert lists[0]["ordered"] is False and len(lists[0]["items"]) == 2
67
+ assert [e["text"] for e in lists[1]["items"]] == ["first", "second"] and lists[1]["ordered"]
68
+ assert by_kind["code"]["text"] == 'print("boat")'
69
+
70
+
71
+ def test_relative_links_resolve_against_the_post_url(post):
72
+ link = post.of_kind("list")[0]["items"][0]["links"][0]
73
+ assert link["href"] == "https://example.substack.com/relative"
74
+
75
+
76
+ def test_line_break_in_a_paragraph(post):
77
+ assert post.items[3]["text"] == "Second paragraph.\nWith a line break."
78
+
79
+
80
+ def test_footnote_item(post):
81
+ note = post.items[-1]
82
+ assert note["kind"] == "footnote" and note["id"] == "1"
83
+ assert note["text"] == "See the notes." and note["links"][0]["href"] == "https://example.org/notes"
84
+
85
+
86
+ def test_to_markdown_is_what_draft_substack_reads(post):
87
+ from article.adapters.substack import preflight
88
+
89
+ md = post.to_markdown()
90
+ assert md.startswith("We set out at dawn")
91
+ assert '![A folded boat on water](<https://substack-post-media.s3.amazonaws.com/public/images/boat.png> "The first boat, launched at 6:12.")' in md
92
+ assert "## Part one" in md and "> Water finds its level." in md
93
+ assert "1. first\n2. second" in md and "- one" in md and "---" in md
94
+ assert "[^1]: See [the notes](https://example.org/notes)." in md
95
+ checked, _ = preflight(md) # draft-substack's own checks accept it
96
+ assert "boat.png" in checked
97
+
98
+
99
+ def test_fetch_uses_the_seams_and_downloads_images(tmp_path):
100
+ seen = []
101
+ post = fetch_published(
102
+ URL,
103
+ assets_dir=tmp_path,
104
+ get_html=lambda url: seen.append(url) or HTML,
105
+ download=lambda url: seen.append(url) or b"IMG:" + url.encode(),
106
+ )
107
+ assert seen[0] == URL and len(seen) == 3
108
+ first = Path(post.images[0]["local_file"])
109
+ assert first.parent == tmp_path and first.name == "001-boat.png"
110
+ assert first.read_bytes().startswith(b"IMG:https://substack-post-media")
111
+ assert str(first) in post.to_markdown()
112
+
113
+
114
+ def test_plain_html_without_substack_markup():
115
+ post = parse_published("<html><body><article><h1>T</h1><p>Hi</p></article></body></html>")
116
+ assert post.title == "T" and [i["text"] for i in post.items] == ["T", "Hi"]
117
+
118
+
119
+ def test_empty_and_broken_html_do_not_raise():
120
+ assert parse_published("").items == []
121
+ assert parse_published("<p>unclosed <b>bold").items[0]["text"] == "unclosed bold"
122
+
123
+
124
+ def test_original_image_url_leaves_other_urls_alone():
125
+ assert original_image_url("") == "" and original_image_url("a.png") == "a.png"
126
+
127
+
128
+ def test_the_package_exports_it():
129
+ assert article.fetch_published is fetch_published
130
+
131
+
132
+ def _items(html):
133
+ return parse_published(html, url="https://x.org/p").items
134
+
135
+
136
+ def test_emphasis_and_links_keep_the_spaces_around_them():
137
+ (p,) = _items("<p>with<em> nothing </em>but <a href='/a'> a map </a>end</p>")
138
+ assert p["markdown"] == "with *nothing* but [a map](https://x.org/a) end"
139
+
140
+
141
+ def test_implied_end_tags_do_not_glue_paragraphs_or_items():
142
+ items = _items("<p>a<p>b<ul><li>x<li>y</ul>")
143
+ assert [i["kind"] for i in items] == ["paragraph", "paragraph", "list"]
144
+ assert [e["text"] for e in items[2]["items"]] == ["x", "y"]
145
+
146
+
147
+ def test_text_directly_in_a_div_and_multi_paragraph_quotes_survive():
148
+ items = _items("<div>loose words <b>here</b><p>then a paragraph</p></div><blockquote><p>one.</p><p>two.</p></blockquote>")
149
+ assert [i["text"] for i in items] == ["loose words here", "then a paragraph", "one.\ntwo."]
150
+
151
+
152
+ def test_tables_and_embeds_become_items():
153
+ items = _items("<table><tr><th>a</th><th>b</th></tr><tr><td>1</td><td>2</td></tr></table><iframe src='https://player.example/v/1'></iframe>")
154
+ assert items[0] == {"kind": "table", "rows": [["a", "b"], ["1", "2"]], "index": 0}
155
+ assert items[1]["kind"] == "embed" and items[1]["src"] == "https://player.example/v/1"
156
+ md = parse_published("<table><tr><th>a</th></tr><tr><td>1</td></tr></table>").to_markdown()
157
+ assert md.startswith("| a |\n| --- |\n| 1 |")
158
+
159
+
160
+ def test_every_image_is_kept_in_place_in_figures_paragraphs_and_lists():
161
+ items = _items(
162
+ "<p>before <img src='https://x.org/1.png'> after</p>"
163
+ "<figure><img src='https://x.org/2.png'><img src='https://x.org/3.png'><figcaption>cap</figcaption></figure>"
164
+ "<ul><li>item <img src='https://x.org/4.png'></li></ul>"
165
+ )
166
+ assert [(i["kind"], i.get("src", i.get("text"))) for i in items] == [
167
+ ("paragraph", "before"), ("image", "https://x.org/1.png"), ("paragraph", "after"),
168
+ ("image", "https://x.org/2.png"), ("image", "https://x.org/3.png"),
169
+ ("list", None), ("image", "https://x.org/4.png"),
170
+ ]
171
+
172
+
173
+ def test_hostile_data_attrs_fall_back_to_the_src():
174
+ for attrs in ("[1]", '{"src": 5}', "null", "not json", '{"width": "wide"}'):
175
+ (img,) = [i for i in _items(f"<img src='https://x.org/a.png' data-attrs='{attrs}'>")]
176
+ assert img["src"] == "https://x.org/a.png"
177
+
178
+
179
+ def test_markdown_metacharacters_in_text_are_escaped_and_fences_grow():
180
+ post = parse_published("<p>2026. A year</p><p># not a heading</p><p>a*b_c [x]</p><pre>```\ncode\n```</pre>")
181
+ md = post.to_markdown()
182
+ assert "2026\\. A year" in md and "\\# not a heading" in md and "a\\*b\\_c \\[x\\]" in md
183
+ assert "````\n```\ncode\n```\n````" in md
184
+
185
+
186
+ def test_unsafe_link_schemes_keep_the_text_only():
187
+ (p,) = _items("<p><a href='javascript:alert(1)'>click</a> <a href='https://x.org/a b(1)'>ok</a></p>")
188
+ assert p["text"] == "click ok" and [l["href"] for l in p["links"]] == ["https://x.org/a b(1)"]
189
+ assert "javascript" not in p["markdown"] and "<https://x.org/a b(1)>" in p["markdown"]
190
+
191
+
192
+ def test_footnote_ids_are_never_empty_or_a_length():
193
+ post = parse_published("<p>t<a class='footnote-anchor' href='#fn'>*</a></p><div class='footnote'><a class='footnote-number'>*</a><div class='footnote-content'><p>n</p></div></div>")
194
+ ids = {i["id"] for i in post.of_kind("footnote")} | set(post.items[0]["footnote_refs"])
195
+ assert ids == {"note"} # a bare "*" anchor: a stable label, the same on both ends
196
+
197
+
198
+ def test_a_paywall_marks_the_post_truncated():
199
+ assert parse_published("<div class='body markup'><p>free</p></div><div class='paywall'></div>").truncated
200
+ assert not parse_published("<p>x</p>").truncated
201
+
202
+
203
+ def test_nav_header_footer_are_not_content_on_plain_pages():
204
+ post = parse_published("<body><nav>Menu</nav><article><p>Body</p></article><footer>Copyright</footer></body>")
205
+ assert [i["text"] for i in post.items] == ["Body"]
206
+
207
+
208
+ def test_very_deep_html_does_not_blow_the_stack():
209
+ deep = "<div>" * 3000 + "<p>deep</p>" + "</div>" * 3000
210
+ assert parse_published(deep).items[0]["text"] == "deep"
211
+
212
+
213
+ def test_a_custom_reader_replaces_the_html_step():
214
+ post = parse_published("<p>x</p>", reader=lambda root, url: [{"kind": "divider"}])
215
+ assert post.items == [{"kind": "divider", "index": 0}]
216
+
217
+
218
+ def test_a_failed_download_is_recorded_not_raised(tmp_path):
219
+ def download(url):
220
+ raise OSError("boom")
221
+
222
+ post = parse_published("<img src='https://x.org/a.png'>", assets_dir=tmp_path, download=download)
223
+ assert "boom" in post.images[0]["error"] and "local_file" not in post.images[0]
224
+
225
+
226
+ def test_the_default_fetchers_refuse_non_public_targets():
227
+ from article.published import _check_public_http
228
+
229
+ for url in ("file:///etc/passwd", "http://127.0.0.1/x", "http://169.254.169.254/latest", "ftp://x.org/a"):
230
+ with pytest.raises(ValueError):
231
+ _check_public_http(url)
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes