@zeldrisho/pi-web-fetch 0.16.4 → 0.16.5

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.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.16.5] - 2026-11-10
11
+
12
+ ### Fixed
13
+
14
+ - Exclude explicitly hidden elements from the basic HTML extraction fallback.
15
+ - Sanitize unsafe links and event handlers in HTML retained in extracted Markdown.
16
+ - Accept pages whose optional end tags are omitted, such as documentation with unclosed `p`, `li`, and `td` elements, instead of rejecting them as excessively nested.
17
+ - Reject markup whose intervening elements keep an optional end tag open, matching the depth the parser actually builds, so deeply nested pages are refused instead of freezing extraction.
18
+ - Reject deeply nested SVG and MathML markup that uses HTML integration points or slashes in unquoted attribute values to bypass the depth preflight.
19
+
10
20
  ## [0.16.4] - 2026-11-09
11
21
 
12
22
  ### Fixed
@@ -324,7 +334,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
324
334
 
325
335
  - Add bounded public page fetching ([b979496](https://github.com/zeldrisho/pi-packages/commit/b979496b32de1cead172ba570307e4a4a7b3421d))
326
336
 
327
- [Unreleased]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.4...HEAD
337
+ [Unreleased]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.5...HEAD
338
+ [0.16.5]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.4...pi-web-fetch-v0.16.5
328
339
  [0.16.4]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.3...pi-web-fetch-v0.16.4
329
340
  [0.16.3]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.2...pi-web-fetch-v0.16.3
330
341
  [0.16.2]: https://github.com/zeldrisho/pi-packages/compare/pi-web-fetch-v0.16.1...pi-web-fetch-v0.16.2
package/README.md CHANGED
@@ -17,13 +17,13 @@ Use `pi config` to enable or disable the extension, and `pi list` to see configu
17
17
 
18
18
  The `web_fetch` tool accepts public HTTP and HTTPS URLs and supports HTML, Markdown, plain text, JSON, and XML. HTML is converted to Markdown; images are omitted. Minified JavaScript, JSON, and YAML are returned as indented code blocks so long single-line payloads stay readable. URLs with credentials, local or private network targets, unsafe redirects, downloads over 5 MiB, and unsupported content types are rejected.
19
19
 
20
- | Parameter | Description |
21
- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
22
- | `url` | Required page URL. URL fragments can start output at a matching heading or anchor. |
23
- | `query` | Optional; selects matching sections from a long page. Sections remain in source order. |
24
- | `offset` | Optional character offset for continuing through extracted content. With a query and fragment, offsets apply to the fragment-focused view; otherwise, an offset takes precedence over the fragment. |
20
+ | Parameter | Description |
21
+ | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
22
+ | `url` | Required page URL. URL fragments can start output at a matching heading or anchor. |
23
+ | `query` | Optional; selects matching sections from a long page. Sections remain in source order. |
24
+ | `offset` | Optional character offset for continuing through extracted content. With a query and a fragment, offsets apply to the focused view; otherwise an offset takes precedence over the fragment. |
25
25
 
26
- Output is bounded to 6,000 characters by default. For long pages, use the returned `nextOffset` to continue with the same URL and query. Use `query` to focus on matching sections, or omit it to read the complete document. Queries use approximate word matching and relevance selection; dotted or hyphenated identifiers and flags are matched literally. Focus can omit relevant content, so omit the query when completeness matters. Pi's preview is collapsed by default; press `Ctrl+O` to expand it.
26
+ Output is bounded to 6,000 characters by default. For long pages, use the returned `nextOffset` with the same URL and query to continue. Queries use approximate word matching and relevance selection; dotted or hyphenated identifiers and flags are matched literally. Focus can omit relevant content, so omit the query when completeness matters. Pi's preview is collapsed by default; press `Ctrl+O` to expand it.
27
27
 
28
28
  For example, a URL such as `https://github.com/zeldrisho/pi-packages/blob/main/packages/pi-web-fetch/README.md#usage` starts at the matching heading. GitHub `blob` links and bare gists are converted to raw source URLs; repository roots use their README. GitHub directory listings are not supported.
29
29
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zeldrisho/pi-web-fetch",
3
- "version": "0.16.4",
3
+ "version": "0.16.5",
4
4
  "description": "Pi extension for secure, bounded public web page fetching and Markdown extraction",
5
5
  "keywords": [
6
6
  "pi",
@@ -32,7 +32,7 @@
32
32
  "dependencies": {
33
33
  "acorn": "^8.19.0",
34
34
  "acorn-walk": "^8.3.5",
35
- "defuddle": "^0.19.5",
35
+ "defuddle": "^0.19.6",
36
36
  "linkedom": "^0.18.13",
37
37
  "yaml": "^2.9.1"
38
38
  },
@@ -3,10 +3,13 @@ export class AcquisitionAdmission {
3
3
  #active = 0;
4
4
  readonly #waiting: Array<() => void> = [];
5
5
 
6
- constructor(
7
- readonly maxActive: number,
8
- readonly maxWaiting: number,
9
- ) {}
6
+ readonly maxActive: number;
7
+ readonly maxWaiting: number;
8
+
9
+ constructor(maxActive: number, maxWaiting: number) {
10
+ this.maxActive = maxActive;
11
+ this.maxWaiting = maxWaiting;
12
+ }
10
13
 
11
14
  async acquire(signal: AbortSignal): Promise<() => void> {
12
15
  signal.throwIfAborted();
@@ -27,6 +27,93 @@ const VOID_ELEMENTS = new Set([
27
27
  // in particular, linkedom parses nested elements inside <noscript>.
28
28
  const RAW_TEXT_ELEMENTS = new Set(["script", "style", "textarea"]);
29
29
 
30
+ /** Form elements that close each other in linkedom's parser, mirroring htmlparser2. */
31
+ const FORM_ELEMENTS = new Set([
32
+ "input",
33
+ "option",
34
+ "optgroup",
35
+ "select",
36
+ "button",
37
+ "datalist",
38
+ "textarea",
39
+ ]);
40
+
41
+ const P_TAG = new Set(["p"]);
42
+
43
+ /**
44
+ * Start tags that imply an end tag, mapped to the tags they close, mirroring
45
+ * htmlparser2's `openImpliesClose` table used by linkedom. A tag closes only while it
46
+ * is on top of the open-element stack; an intervening element keeps it open.
47
+ */
48
+ const IMPLIED_END_TAGS = new Map<string, ReadonlySet<string>>([
49
+ ["tr", new Set(["tr", "th", "td"])],
50
+ ["th", new Set(["th"])],
51
+ ["td", new Set(["thead", "th", "td"])],
52
+ ["body", new Set(["head", "link", "script"])],
53
+ ["li", new Set(["li"])],
54
+ ["p", P_TAG],
55
+ ["h1", P_TAG],
56
+ ["h2", P_TAG],
57
+ ["h3", P_TAG],
58
+ ["h4", P_TAG],
59
+ ["h5", P_TAG],
60
+ ["h6", P_TAG],
61
+ ["select", FORM_ELEMENTS],
62
+ ["input", FORM_ELEMENTS],
63
+ ["output", FORM_ELEMENTS],
64
+ ["button", FORM_ELEMENTS],
65
+ ["datalist", FORM_ELEMENTS],
66
+ ["textarea", FORM_ELEMENTS],
67
+ ["option", new Set(["option"])],
68
+ ["optgroup", new Set(["optgroup", "option"])],
69
+ ["dd", new Set(["dd", "dt"])],
70
+ ["dt", new Set(["dd", "dt"])],
71
+ ["address", P_TAG],
72
+ ["article", P_TAG],
73
+ ["aside", P_TAG],
74
+ ["blockquote", P_TAG],
75
+ ["details", P_TAG],
76
+ ["div", P_TAG],
77
+ ["dl", P_TAG],
78
+ ["fieldset", P_TAG],
79
+ ["figcaption", P_TAG],
80
+ ["figure", P_TAG],
81
+ ["footer", P_TAG],
82
+ ["form", P_TAG],
83
+ ["header", P_TAG],
84
+ ["hr", P_TAG],
85
+ ["main", P_TAG],
86
+ ["nav", P_TAG],
87
+ ["ol", P_TAG],
88
+ ["pre", P_TAG],
89
+ ["section", P_TAG],
90
+ ["table", P_TAG],
91
+ ["ul", P_TAG],
92
+ ["rt", new Set(["rt", "rp"])],
93
+ ["rp", new Set(["rt", "rp"])],
94
+ ["tbody", new Set(["thead", "tbody"])],
95
+ ["tfoot", new Set(["thead", "tbody"])],
96
+ ] satisfies Array<[string, ReadonlySet<string>]>);
97
+
98
+ /**
99
+ * Elements that open foreign content, where self-closing syntax is honored.
100
+ * In HTML content a trailing `/` is ignored, matching linkedom and the HTML rules.
101
+ */
102
+ const FOREIGN_ROOTS = new Set(["svg", "math"]);
103
+
104
+ /** Foreign-content elements that switch linkedom back to HTML parsing. */
105
+ const HTML_INTEGRATION_ELEMENTS = new Set([
106
+ "mi",
107
+ "mo",
108
+ "mn",
109
+ "ms",
110
+ "mtext",
111
+ "annotation-xml",
112
+ "foreignobject",
113
+ "desc",
114
+ "title",
115
+ ]);
116
+
30
117
  /**
31
118
  * Finds a raw-text end tag in lowercased HTML, starting at the supplied code-unit
32
119
  * offset, without interpreting its body as markup. Returns -1 when none is found.
@@ -49,16 +136,59 @@ function findRawTextEnd(html: string, name: string, from: number): number {
49
136
 
50
137
  /**
51
138
  * Conservatively checks lexical HTML depth in one pass, before creating a DOM.
52
- * Only a matching top-of-stack closing tag reduces depth. Self-closing syntax
53
- * on non-void HTML elements is counted as opening, just as linkedom treats it.
139
+ * Only a matching top-of-stack closing tag reduces depth, plus the implied end tags
140
+ * that linkedom itself applies for optional-end-tag elements; without those, ordinary
141
+ * documents whose `p`, `li`, or `td` end tags are omitted would be refused. An implied
142
+ * close applies only while its tag is on top of the stack, matching linkedom's parser,
143
+ * so an intervening element keeps counting toward depth. Self-closing syntax on non-void
144
+ * HTML elements is counted as opening, just as linkedom treats it, while foreign content
145
+ * (`svg`, `math`) honors it.
54
146
  * Quoted attributes, comments, and raw-text bodies cannot hide nested markup.
55
147
  */
56
148
  export function exceedsConversionDepth(html: string): boolean {
57
149
  // Preserve code-unit positions when normalizing ASCII tag names.
58
150
  const lower = html.replace(/[A-Z]+/g, (match) => match.toLowerCase());
59
151
  const stack: string[] = [];
152
+ // htmlparser2 keeps this flag in parallel with its element stack. Integration points
153
+ // push HTML mode even under SVG or MathML; this must happen before self-closing checks.
154
+ const foreignContexts = [false];
60
155
  let offset = 0;
61
156
 
157
+ const push = (name: string): void => {
158
+ const parentForeign = foreignContexts.at(-1) ?? false;
159
+
160
+ const foreign = FOREIGN_ROOTS.has(name)
161
+ ? true
162
+ : HTML_INTEGRATION_ELEMENTS.has(name)
163
+ ? false
164
+ : parentForeign;
165
+
166
+ stack.push(name);
167
+ foreignContexts.push(foreign);
168
+ };
169
+
170
+ const pop = (): void => {
171
+ if (stack.pop() === undefined) return;
172
+
173
+ foreignContexts.pop();
174
+ };
175
+
176
+ // The scan is charged to the elements it pops, so total work stays linear.
177
+ const closeImplied = (name: string): void => {
178
+ const implied = IMPLIED_END_TAGS.get(name);
179
+
180
+ if (implied === undefined) return;
181
+
182
+ // linkedom closes an implied end tag only while it is on top of its own stack.
183
+ while (stack.length > 0) {
184
+ const top = stack.at(-1);
185
+
186
+ if (top === undefined || !implied.has(top)) return;
187
+
188
+ pop();
189
+ }
190
+ };
191
+
62
192
  while (offset < html.length) {
63
193
  const start = html.indexOf("<", offset);
64
194
 
@@ -121,9 +251,20 @@ export function exceedsConversionDepth(html: string): boolean {
121
251
  if (html[cursor - 1] !== ">") break;
122
252
 
123
253
  if (closing) {
124
- if (stack.at(-1) === name) stack.pop();
254
+ if (stack.at(-1) === name) pop();
125
255
  } else if (!VOID_ELEMENTS.has(name)) {
126
- stack.push(name);
256
+ // Implied closes apply only in HTML mode, matching htmlparser2/linkedom.
257
+ if (!foreignContexts.at(-1)) closeImplied(name);
258
+ push(name);
259
+
260
+ // Self-closing syntax is honored only in foreign mode. An unquoted attribute value
261
+ // can itself end in `/`, so it is not a self-closing marker. Check after push so an
262
+ // HTML integration point such as `<foreignObject/>` remains open as linkedom does.
263
+ if (html[cursor - 2] === "/" && !unquotedValue && foreignContexts.at(-1)) {
264
+ pop();
265
+ offset = cursor;
266
+ continue;
267
+ }
127
268
 
128
269
  if (stack.length > MAX_CONVERSION_DEPTH) return true;
129
270
 
@@ -147,6 +147,23 @@ export function htmlToMarkdownFallback(html: string): string {
147
147
  element.remove();
148
148
  }
149
149
 
150
+ for (const element of document.querySelectorAll("[hidden], [aria-hidden], [style]")) {
151
+ const style = element.getAttribute("style") ?? "";
152
+
153
+ const hiddenStyle =
154
+ /(?:^|;)\s*(?:display\s*:\s*none|visibility\s*:\s*hidden)\s*(?:!important\s*)?(?:;|$)/i.test(
155
+ style,
156
+ );
157
+
158
+ if (
159
+ element.hasAttribute("hidden") ||
160
+ element.getAttribute("aria-hidden")?.trim().toLowerCase() === "true" ||
161
+ hiddenStyle
162
+ ) {
163
+ element.remove();
164
+ }
165
+ }
166
+
150
167
  return document.body.textContent
151
168
  .replace(/[ \t]+\n/g, "\n")
152
169
  .replace(/\n[ \t]+/g, "\n")