pyxsql 1.0.0__cp313-cp313-win32.whl

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.
@@ -0,0 +1,580 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyxsql
3
+ Version: 1.0.0
4
+ Summary: SQL-style querying for static HTML with a deterministic node model.
5
+ Author: BORANN CHANRATHNAK
6
+ License: Apache License
7
+ Version 2.0, January 2004
8
+ http://www.apache.org/licenses/
9
+
10
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
11
+
12
+ 1. Definitions.
13
+
14
+ "License" shall mean the terms and conditions for use, reproduction,
15
+ and distribution as defined by Sections 1 through 9 of this document.
16
+
17
+ "Licensor" shall mean the copyright owner or entity authorized by
18
+ the copyright owner that is granting the License.
19
+
20
+ "Legal Entity" shall mean the union of the acting entity and all
21
+ other entities that control, are controlled by, or are under common
22
+ control with that entity. For the purposes of this definition,
23
+ "control" means (i) the power, direct or indirect, to cause the
24
+ direction or management of such entity, whether by contract or
25
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
26
+ outstanding shares, or (iii) beneficial ownership of such entity.
27
+
28
+ "You" (or "Your") shall mean an individual or Legal Entity
29
+ exercising permissions granted by this License.
30
+
31
+ "Source" form shall mean the preferred form for making modifications,
32
+ including but not limited to software source code, documentation
33
+ source, and configuration files.
34
+
35
+ "Object" form shall mean any form resulting from mechanical
36
+ transformation or translation of a Source form, including but
37
+ not limited to compiled object code, generated documentation,
38
+ and conversions to other media types.
39
+
40
+ "Work" shall mean the work of authorship, whether in Source or
41
+ Object form, made available under the License, as indicated by a
42
+ copyright notice that is included in or attached to the work
43
+ (an example is provided in the Appendix below).
44
+
45
+ "Derivative Works" shall mean any work, whether in Source or Object
46
+ form, that is based on (or derived from) the Work and for which the
47
+ editorial revisions, annotations, elaborations, or other modifications
48
+ represent, as a whole, an original work of authorship. For the purposes
49
+ of this License, Derivative Works shall not include works that remain
50
+ separable from, or merely link (or bind by name) to the interfaces of,
51
+ the Work and Derivative Works thereof.
52
+
53
+ "Contribution" shall mean any work of authorship, including
54
+ the original version of the Work and any modifications or additions
55
+ to that Work or Derivative Works thereof, that is intentionally
56
+ submitted to Licensor for inclusion in the Work by the copyright owner
57
+ or by an individual or Legal Entity authorized to submit on behalf of
58
+ the copyright owner. For the purposes of this definition, "submitted"
59
+ means any form of electronic, verbal, or written communication sent
60
+ to the Licensor or its representatives, including but not limited to
61
+ communication on electronic mailing lists, source code control systems,
62
+ and issue tracking systems that are managed by, or on behalf of, the
63
+ Licensor for the purpose of discussing and improving the Work, but
64
+ excluding communication that is conspicuously marked or otherwise
65
+ designated in writing by the copyright owner as "Not a Contribution."
66
+
67
+ "Contributor" shall mean Licensor and any individual or Legal Entity
68
+ on behalf of whom a Contribution has been received by Licensor and
69
+ subsequently incorporated within the Work.
70
+
71
+ 2. Grant of Copyright License. Subject to the terms and conditions of
72
+ this License, each Contributor hereby grants to You a perpetual,
73
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
74
+ copyright license to reproduce, prepare Derivative Works of,
75
+ publicly display, publicly perform, sublicense, and distribute the
76
+ Work and such Derivative Works in Source or Object form.
77
+
78
+ 3. Grant of Patent License. Subject to the terms and conditions of
79
+ this License, each Contributor hereby grants to You a perpetual,
80
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
81
+ (except as stated in this section) patent license to make, have made,
82
+ use, offer to sell, sell, import, and otherwise transfer the Work,
83
+ where such license applies only to those patent claims licensable
84
+ by such Contributor that are necessarily infringed by their
85
+ Contribution(s) alone or by combination of their Contribution(s)
86
+ with the Work to which such Contribution(s) was submitted. If You
87
+ institute patent litigation against any entity (including a
88
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
89
+ or a Contribution incorporated within the Work constitutes direct
90
+ or contributory patent infringement, then any patent licenses
91
+ granted to You under this License for that Work shall terminate
92
+ as of the date such litigation is filed.
93
+
94
+ 4. Redistribution. You may reproduce and distribute copies of the
95
+ Work or Derivative Works thereof in any medium, with or without
96
+ modifications, and in Source or Object form, provided that You
97
+ meet the following conditions:
98
+
99
+ (a) You must give any other recipients of the Work or
100
+ Derivative Works a copy of this License; and
101
+
102
+ (b) You must cause any modified files to carry prominent notices
103
+ stating that You changed the files; and
104
+
105
+ (c) You must retain, in the Source form of any Derivative Works
106
+ that You distribute, all copyright, patent, trademark, and
107
+ attribution notices from the Source form of the Work,
108
+ excluding those notices that do not pertain to any part of
109
+ the Derivative Works; and
110
+
111
+ (d) If the Work includes a "NOTICE" text file as part of its
112
+ distribution, then any Derivative Works that You distribute must
113
+ include a readable copy of the attribution notices contained
114
+ within such NOTICE file, excluding those notices that do not
115
+ pertain to any part of the Derivative Works, in at least one
116
+ of the following places: within a NOTICE text file distributed
117
+ as part of the Derivative Works; within the Source form or
118
+ documentation, if provided along with the Derivative Works; or,
119
+ within a display generated by the Derivative Works, if and
120
+ wherever such third-party notices normally appear. The contents
121
+ of the NOTICE file are for informational purposes only and
122
+ do not modify the License. You may add Your own attribution
123
+ notices within Derivative Works that You distribute, alongside
124
+ or as an addendum to the NOTICE text from the Work, provided
125
+ that such additional attribution notices cannot be construed
126
+ as modifying the License.
127
+
128
+ You may add Your own copyright statement to Your modifications and
129
+ may provide additional or different license terms and conditions
130
+ for use, reproduction, or distribution of Your modifications, or
131
+ for any such Derivative Works as a whole, provided Your use,
132
+ reproduction, and distribution of the Work otherwise complies with
133
+ the conditions stated in this License.
134
+
135
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
136
+ any Contribution intentionally submitted for inclusion in the Work
137
+ by You to the Licensor shall be under the terms and conditions of
138
+ this License, without any additional terms or conditions.
139
+ Notwithstanding the above, nothing herein shall supersede or modify
140
+ the terms of any separate license agreement you may have executed
141
+ with Licensor regarding such Contributions.
142
+
143
+ 6. Trademarks. This License does not grant permission to use the trade
144
+ names, trademarks, service marks, or product names of the Licensor,
145
+ except as required for reasonable and customary use in describing the
146
+ origin of the Work and reproducing the content of the NOTICE file.
147
+
148
+ 7. Disclaimer of Warranty. Unless required by applicable law or
149
+ agreed to in writing, Licensor provides the Work (and each
150
+ Contributor provides its Contributions) on an "AS IS" BASIS,
151
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
152
+ implied, including, without limitation, any warranties or conditions
153
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
154
+ PARTICULAR PURPOSE. You are solely responsible for determining the
155
+ appropriateness of using or redistributing the Work and assume any
156
+ risks associated with Your exercise of permissions under this License.
157
+
158
+ 8. Limitation of Liability. In no event and under no legal theory,
159
+ whether in tort (including negligence), contract, or otherwise,
160
+ unless required by applicable law (such as deliberate and grossly
161
+ negligent acts) or agreed to in writing, shall any Contributor be
162
+ liable to You for damages, including any direct, indirect, special,
163
+ incidental, or consequential damages of any character arising as a
164
+ result of this License or out of the use or inability to use the
165
+ Work (including but not limited to damages for loss of goodwill,
166
+ work stoppage, computer failure or malfunction, or any and all
167
+ other commercial damages or losses), even if such Contributor
168
+ has been advised of the possibility of such damages.
169
+
170
+ 9. Accepting Warranty or Additional Liability. While redistributing
171
+ the Work or Derivative Works thereof, You may choose to offer,
172
+ and charge a fee for, acceptance of support, warranty, indemnity,
173
+ or other liability obligations and/or rights consistent with this
174
+ License. However, in accepting such obligations, You may act only
175
+ on Your own behalf and on Your sole responsibility, not on behalf
176
+ of any other Contributor, and only if You agree to indemnify,
177
+ defend, and hold each Contributor harmless for any liability
178
+ incurred by, or claims asserted against, such Contributor by reason
179
+ of your accepting any such warranty or additional liability.
180
+
181
+ END OF TERMS AND CONDITIONS
182
+
183
+ Copyright 2025 BORANN CHANRATHNAK
184
+
185
+ Licensed under the Apache License, Version 2.0 (the "License");
186
+ you may not use this file except in compliance with the License.
187
+ You may obtain a copy of the License at
188
+
189
+ http://www.apache.org/licenses/LICENSE-2.0
190
+
191
+ Unless required by applicable law or agreed to in writing, software
192
+ distributed under the License is distributed on an "AS IS" BASIS,
193
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
194
+ See the License for the specific language governing permissions and
195
+ limitations under the License.
196
+
197
+ Classifier: Programming Language :: Python :: 3
198
+ Classifier: Programming Language :: C++
199
+ Classifier: License :: OSI Approved :: Apache Software License
200
+ Classifier: Operating System :: OS Independent
201
+ Requires-Python: >=3.9
202
+ Description-Content-Type: text/markdown
203
+ License-File: LICENSE
204
+ Provides-Extra: test
205
+ Requires-Dist: pytest>=7.4.0; extra == "test"
206
+ Dynamic: license-file
207
+
208
+ # XSQL Documentation (v1.0.0)
209
+
210
+ XSQL is a SQL-style query language for static HTML. It treats each HTML element
211
+ as a row in a node table and lets you filter by tag and attributes. The project
212
+ has now flourished to v1.0.0 as an offline-first C++20 tool.
213
+
214
+ ## Quick Start
215
+
216
+ Build:
217
+ ```
218
+ ./build.sh
219
+ ```
220
+
221
+ Run on a file:
222
+ ```
223
+ ./build/xsql --query "SELECT a FROM doc WHERE attributes.id = 'login'" --input ./data/index.html
224
+ ```
225
+
226
+ Interactive mode:
227
+ ```
228
+ ./build/xsql --interactive --input ./data/index.html
229
+ ```
230
+
231
+ ## Python API (xsql package)
232
+
233
+ ```python
234
+ import xsql
235
+
236
+ doc = xsql.load("data/index.html")
237
+ print(xsql.summarize(doc))
238
+ rows = xsql.execute("SELECT a FROM document WHERE attributes.href IS NOT NULL")
239
+
240
+ doc = xsql.load("https://example.com", allow_network=True)
241
+ rows = xsql.execute("SELECT title FROM document")
242
+ ```
243
+
244
+ Install:
245
+ ```
246
+ pip install pyxsql
247
+ ```
248
+
249
+ Security Notes:
250
+ - Network access is disabled by default; enable with `allow_network=True`.
251
+ - Private/localhost targets are blocked unless `allow_private_network=True`.
252
+ - File reads are confined to `base_dir` when provided.
253
+ - Downloads are capped by `max_bytes`, and query output by `max_results`.
254
+
255
+ ## Build on Linux/macOS/Windows
256
+
257
+ Linux (Ubuntu/Debian):
258
+ ```
259
+ sudo apt-get update
260
+ sudo apt-get install -y build-essential cmake ninja-build pkg-config bison flex
261
+ ./build.sh
262
+ ```
263
+
264
+ macOS (Homebrew):
265
+ ```
266
+ brew install cmake ninja pkg-config bison flex
267
+ ./build.sh
268
+ ```
269
+
270
+ Windows (PowerShell, MSVC):
271
+ ```
272
+ cmake -S . -B build -DCMAKE_TOOLCHAIN_FILE=C:\vcpkg\scripts\buildsystems\vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows
273
+ cmake --build build --config Release
274
+ ```
275
+
276
+ Optional dependencies via vcpkg:
277
+ ```
278
+ vcpkg install nlohmann-json libxml2 curl arrow[parquet]
279
+ ```
280
+
281
+ If you do not want Parquet, configure with `-DXSQL_WITH_ARROW=OFF`.
282
+
283
+ ## Python Build & Tests
284
+
285
+ Create a virtual environment and install the editable package:
286
+ ```
287
+ python3 -m venv xsql_venv
288
+ source ./xsql_venv/bin/activate
289
+ pip install -U pip
290
+ pip install -e .[test]
291
+ ```
292
+
293
+ Run Python tests:
294
+ ```
295
+ pytest -v python/tests
296
+ ```
297
+
298
+ Shorthand:
299
+ ```
300
+ ./test_python.sh
301
+ ```
302
+
303
+ ## CLI Usage
304
+
305
+ ```
306
+ ./build/xsql --query "<query>" --input <path>
307
+ ./build/xsql --query-file <file> --input <path>
308
+ ./build/xsql --interactive [--input <path>]
309
+ ./build/xsql --mode duckbox|json|plain
310
+ ./build/xsql --highlight on|off
311
+ ./build/xsql --color=disabled
312
+ ```
313
+
314
+ Notes:
315
+ - `--input` is required unless reading HTML from stdin.
316
+ - Colors are auto-disabled when stdout is not a TTY.
317
+ - Default output mode is `duckbox` (table-style).
318
+ - `--highlight` only affects duckbox headers (auto-disabled when not a TTY).
319
+ - `TO CSV()` / `TO PARQUET()` write files instead of printing results.
320
+
321
+ ## Interactive Mode (REPL)
322
+
323
+ Commands:
324
+ - `.help`: show help
325
+ - `.load <path|url>` / `:load <path|url>`: load input (path or URL)
326
+ - `.mode duckbox|json|plain`: set output mode
327
+ - `.display_mode more|less`: control JSON truncation
328
+ - `.max_rows <n|inf>`: set duckbox max rows (`inf` = unlimited)
329
+ - `.summarize [doc|path|url]`: list all tags and counts for the active input or target
330
+ - `.quit` / `.q` / `:quit` / `:exit`: exit the REPL
331
+
332
+ Keys:
333
+ - Up/Down: history (max 5 entries)
334
+ - Left/Right: move cursor
335
+ - Ctrl+L: clear screen
336
+
337
+ ## Data Model
338
+
339
+ Each HTML element becomes a row with fields:
340
+ - `node_id` (int64)
341
+ - `tag` (string)
342
+ - `attributes` (map<string,string>)
343
+ - `parent_id` (int64 or null)
344
+ - `source_uri` (string)
345
+
346
+ ## Query Language
347
+
348
+ ### Basic Form
349
+ ```
350
+ SELECT <tag_list> FROM <source> [WHERE <expr>] [LIMIT <n>]
351
+ [TO LIST() | TO TABLE() | TO CSV('file.csv') | TO PARQUET('file.parquet')]
352
+ ```
353
+
354
+ ### Source
355
+ ```
356
+ FROM document
357
+ FROM 'path.html'
358
+ FROM 'https://example.com' (URL fetching requires libcurl)
359
+ FROM doc (alias for document)
360
+ FROM document AS doc
361
+ ```
362
+
363
+ ### Tags
364
+ ```
365
+ SELECT div
366
+ SELECT div,span
367
+ SELECT *
368
+ ```
369
+
370
+ Exclude columns:
371
+ ```
372
+ SELECT * EXCLUDE source_uri FROM doc
373
+ SELECT * EXCLUDE (source_uri, tag) FROM doc
374
+ ```
375
+
376
+ ### WHERE Expressions
377
+ Supported operators:
378
+ - `=`
379
+ - `IN`
380
+ - `<>` / `!=`
381
+ - `IS NULL` / `IS NOT NULL`
382
+ - `~` (regex, ECMAScript)
383
+ - `AND`, `OR`
384
+
385
+ Attribute references:
386
+ ```
387
+ attributes.id = 'main'
388
+ parent.attributes.class = 'menu'
389
+ child.attributes.href <> ''
390
+ ancestor.attributes.id = 'root'
391
+ descendant.attributes.class IN ('nav','top')
392
+ ```
393
+
394
+ Field references:
395
+ ```
396
+ text <> ''
397
+ tag = 'div'
398
+ parent.tag = 'section'
399
+ child.tag = 'a'
400
+ ancestor.text ~ 'error|warning'
401
+ ```
402
+
403
+ Shorthand attribute filters:
404
+ ```
405
+ title = "Menu"
406
+ doc.title = "Menu"
407
+ ```
408
+
409
+ ### Aliases
410
+ Alias the source and qualify attribute filters:
411
+ ```
412
+ SELECT a FROM document AS d WHERE d.attributes.id = 'login'
413
+ ```
414
+
415
+ ### Projections
416
+ Project a field from a tag:
417
+ ```
418
+ SELECT a.parent_id FROM doc
419
+ SELECT link.href FROM doc
420
+ SELECT a.attributes FROM doc
421
+ SELECT div(node_id, tag, parent_id) FROM doc
422
+ ```
423
+
424
+ Supported base fields:
425
+ - `node_id`, `tag`, `parent_id`, `source_uri`, `attributes`
426
+
427
+ Attribute value projection:
428
+ - `SELECT link.href FROM doc` returns the `href` value
429
+
430
+ Function projection:
431
+ - `SELECT inner_html(div) FROM doc` returns the raw inner HTML for each `div`
432
+ - `SELECT inner_html(div, 1) FROM doc` keeps only tags up to depth 1 (drops deeper tags)
433
+ - `SELECT trim(inner_html(div)) FROM doc` trims leading/trailing whitespace
434
+ - `SELECT TEXT(div) FROM doc WHERE tag = 'div'` returns descendant text for each `div`
435
+
436
+ Notes:
437
+ - `TEXT()` and `INNER_HTML()` require a `WHERE` clause with a non-tag filter (e.g., attributes or parent).
438
+ - `attributes IS NULL` matches elements with no attributes.
439
+
440
+ ### TO LIST()
441
+ Output a JSON list for a single projected column:
442
+ ```
443
+ SELECT link.href FROM doc WHERE attributes.rel = "preload" TO LIST()
444
+ ```
445
+
446
+ ### TO TABLE()
447
+ Extract an HTML `<table>` into rows (array of arrays):
448
+ ```
449
+ SELECT table FROM doc TO TABLE()
450
+ ```
451
+
452
+ If multiple tables match, the output is a list of objects:
453
+ ```
454
+ [{ "node_id": 123, "rows": [[...], ...] }, ...]
455
+ ```
456
+
457
+ Note: `TO LIST()` always returns JSON output. `TO TABLE()` uses duckbox by default and JSON in `--mode json|plain`.
458
+
459
+ ### TO CSV()
460
+ Write any rectangular result to a CSV file:
461
+ ```
462
+ SELECT a.href, a.text FROM doc WHERE attributes.href IS NOT NULL TO CSV('links.csv')
463
+ ```
464
+
465
+ ### TO PARQUET()
466
+ Write any rectangular result to a Parquet file (requires Apache Arrow feature):
467
+ ```
468
+ SELECT * FROM doc TO PARQUET('nodes.parquet')
469
+ ```
470
+
471
+ Note: `TO CSV()` and `TO PARQUET()` write files and do not print the result set.
472
+ If you `SELECT table ... TO CSV(...)`, XSQL exports the HTML table rows directly.
473
+
474
+ ### LIMIT
475
+ ```
476
+ SELECT a FROM doc LIMIT 5
477
+ ```
478
+
479
+ ### COUNT()
480
+ Minimal aggregate:
481
+ ```
482
+ SELECT COUNT(a) FROM doc
483
+ SELECT COUNT(*) FROM doc
484
+ SELECT COUNT(link) FROM doc WHERE attributes.rel = "preload"
485
+ ```
486
+
487
+ ### Regex
488
+ Use `~` with ECMAScript regex:
489
+ ```
490
+ SELECT a FROM doc WHERE attributes.href ~ '.*\\.pdf$'
491
+ ```
492
+
493
+ ## Examples
494
+
495
+ Select by id:
496
+ ```
497
+ SELECT ul FROM doc WHERE attributes.id = 'countries';
498
+ ```
499
+
500
+ Parent attribute filter:
501
+ ```
502
+ SELECT table FROM doc WHERE parent.attributes.id = 'table-01';
503
+ ```
504
+
505
+ Descendant attribute filter:
506
+ ```
507
+ SELECT div FROM doc WHERE descendant.attributes.class = 'card';
508
+ ```
509
+
510
+ Extract href list:
511
+ ```
512
+ SELECT link.href FROM doc WHERE attributes.rel = "preload" TO LIST();
513
+ ```
514
+
515
+ Export to CSV:
516
+ ```
517
+ SELECT a.href, a.text FROM doc WHERE attributes.href IS NOT NULL TO CSV('links.csv');
518
+ ```
519
+
520
+ Export to Parquet:
521
+ ```
522
+ SELECT * FROM doc TO PARQUET('nodes.parquet');
523
+ ```
524
+
525
+ Order results:
526
+ ```
527
+ SELECT div FROM doc ORDER BY node_id DESC;
528
+ ```
529
+ ```
530
+ SELECT * FROM doc ORDER BY tag, parent_id LIMIT 10;
531
+ ```
532
+
533
+ Summarize tags:
534
+ ```
535
+ SELECT summarize(*) FROM doc;
536
+ ```
537
+
538
+ Top tags:
539
+ ```
540
+ SELECT summarize(*) FROM doc ORDER BY count DESC LIMIT 5;
541
+ ```
542
+
543
+ Filter by parent node id:
544
+ ```
545
+ SELECT span FROM doc WHERE parent_id = 1;
546
+ ```
547
+
548
+ Filter by node id:
549
+ ```
550
+ SELECT span FROM doc WHERE node_id = 1;
551
+ ```
552
+
553
+ Match elements with no attributes:
554
+ ```
555
+ SELECT div FROM doc WHERE attributes IS NULL;
556
+ ```
557
+
558
+ ## Known Limitations (v0.1)
559
+
560
+ - No XPath or positional predicates.
561
+ - `ORDER BY` is limited to `node_id`, `tag`, `text`, or `parent_id`.
562
+ - No `GROUP BY` or joins.
563
+ - No XML mode (HTML only).
564
+ - URL fetching requires libcurl.
565
+ - Default output is duckbox tables; JSON output is available via `--mode json`.
566
+ - `TO PARQUET()` requires Apache Arrow support at build time.
567
+
568
+ ## Build Dependencies
569
+
570
+ Optional:
571
+ - `nlohmann/json` for pretty JSON output (vcpkg recommended).
572
+ - `libxml2` for robust HTML parsing (fallback to naive parser if missing).
573
+ - `libcurl` for URL fetching.
574
+ - `apache-arrow` (Arrow/Parquet) for `TO PARQUET()` export.
575
+
576
+ ## Troubleshooting
577
+
578
+ - If you see `No input loaded` in REPL, run `:load <path|url>`.
579
+ - If a query fails with `Expected FROM`, include a `FROM` clause.
580
+ - If output is compact JSON, ensure `nlohmann/json` is linked via vcpkg.
@@ -0,0 +1,12 @@
1
+ pyxsql-1.0.0.dist-info/licenses/LICENSE,sha256=px6L0kBMsqHVBArERkmFyUELFcRWoeNo543SSrrZbpo,10845
2
+ xsql/__init__.py,sha256=Yr_1yuWpsnqoyUAJT7lb8Ggz3_LF6GmDsm_8pkQblCM,4133
3
+ xsql/_core.cp313-win32.pyd,sha256=Ao28DX3rUekezu8zez2eFKB9w0_YLpDtThHBhLqMvg4,280064
4
+ xsql/_core.cpp,sha256=lXU-vAEKcnWfyTwiM5_evlOSbNkvWWVjF1_Tckao0Oc,2887
5
+ xsql/_loader.py,sha256=i7TfyVVAYWXpjGrXKbbUro6neR5mujS58GGWQU8PvuA,5415
6
+ xsql/_security.py,sha256=ztH9c85IKRmSCz6Tq-4hKo8ZmGBKiW5RfPcUzaMwoNA,2562
7
+ xsql/_summary.py,sha256=m1NsL3Y4QS0fmkuLCI2o722MmwdazTC4PXwPPUFpDsg,1202
8
+ xsql/_types.py,sha256=j7mXDCUfyE5sirZFP0jzpBMpB76y9plowc6LMdKfA7M,868
9
+ pyxsql-1.0.0.dist-info/METADATA,sha256=EcK7YtxZ-yl_ym40UhmScjMd26TDNHOYvh8xp_p93Zc,21846
10
+ pyxsql-1.0.0.dist-info/WHEEL,sha256=0ABLuJ37exXk5N_efmYNs2NU9NK1K2Qlod_6bYkofEA,97
11
+ pyxsql-1.0.0.dist-info/top_level.txt,sha256=1W3QSZQ6L-T6Jmonfe0IRGC7DRYRwIOaX9wKcV53RHQ,5
12
+ pyxsql-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: false
4
+ Tag: cp313-cp313-win32
5
+
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2025 BORANN CHANRATHNAK
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
@@ -0,0 +1 @@
1
+ xsql
xsql/__init__.py ADDED
@@ -0,0 +1,120 @@
1
+ """Python interface for XSQL query execution with safety-first defaults."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict, Optional
6
+
7
+ from ._loader import load_html_source
8
+ from ._security import FetchPolicy
9
+ from ._summary import summarize_document
10
+ from ._types import Document, ExportSink, QueryResult, TableResult
11
+
12
+ try:
13
+ from . import _core
14
+ except Exception as exc: # pragma: no cover - surfaced in import-time errors.
15
+ _core = None
16
+ _core_import_error = exc
17
+ else:
18
+ _core_import_error = None
19
+
20
+ doc: Optional[Document] = None
21
+
22
+
23
+ def _require_core() -> None:
24
+ if _core is None:
25
+ raise RuntimeError("xsql native module is unavailable") from _core_import_error
26
+
27
+
28
+ def load(
29
+ source: Any,
30
+ *,
31
+ base_dir: Optional[str] = None,
32
+ allow_network: bool = False,
33
+ allow_private_network: bool = False,
34
+ timeout: int = 10,
35
+ max_bytes: int = 5_000_000,
36
+ ) -> Document:
37
+ """Loads HTML into a module-level Document for reuse across queries.
38
+
39
+ This function MUST be treated as not thread-safe because it mutates xsql.doc.
40
+ It performs IO for file/URL sources and enforces size/network limits.
41
+ """
42
+
43
+ policy = FetchPolicy(
44
+ allow_network=allow_network,
45
+ allow_private_network=allow_private_network,
46
+ timeout=timeout,
47
+ max_bytes=max_bytes,
48
+ )
49
+ html, origin = load_html_source(source, base_dir=base_dir, policy=policy)
50
+ document = Document(html=html, source=origin)
51
+ globals()["doc"] = document
52
+ return document
53
+
54
+
55
+ def summarize(doc: Document, *, max_nodes_preview: int = 50) -> Dict[str, object]:
56
+ """Summarizes a document by tags and attribute keys without executing scripts.
57
+
58
+ The summary MUST avoid disclosing paths beyond the provided document source.
59
+ It performs parsing but does not execute or fetch external resources.
60
+ """
61
+
62
+ return summarize_document(doc, max_nodes_preview)
63
+
64
+
65
+ def execute(
66
+ query: str,
67
+ *,
68
+ source: Any = None,
69
+ doc: Optional[Document] = None,
70
+ params: Optional[Dict[str, Any]] = None,
71
+ allow_network: bool = False,
72
+ base_dir: Optional[str] = None,
73
+ timeout: int = 10,
74
+ max_bytes: int = 5_000_000,
75
+ max_results: int = 10_000,
76
+ ) -> QueryResult:
77
+ """Executes an XSQL query against a document or source with safety limits.
78
+
79
+ The query MUST be executed without eval/exec and respects max_results limits.
80
+ It may read files or URLs when a source is provided and allow_network permits it.
81
+ """
82
+
83
+ _require_core()
84
+ if params:
85
+ raise ValueError("params are not supported by XSQL execution")
86
+ active = doc or globals().get("doc")
87
+ if active is None:
88
+ if source is None:
89
+ raise ValueError("No document loaded; provide doc or source")
90
+ policy = FetchPolicy(
91
+ allow_network=allow_network,
92
+ allow_private_network=False,
93
+ timeout=timeout,
94
+ max_bytes=max_bytes,
95
+ )
96
+ html, origin = load_html_source(source, base_dir=base_dir, policy=policy)
97
+ active = Document(html=html, source=origin)
98
+ raw = _core.execute_from_document(active.html, query)
99
+ rows = raw.get("rows", [])
100
+ tables = []
101
+ for table in raw.get("tables", []):
102
+ tables.append(TableResult(node_id=table["node_id"], rows=table["rows"]))
103
+ if len(rows) > max_results:
104
+ raise ValueError("Query result exceeds max_results")
105
+ total_table_rows = sum(len(table.rows) for table in tables)
106
+ if total_table_rows > max_results:
107
+ raise ValueError("Table result exceeds max_results")
108
+ export = raw.get("export_sink", {})
109
+ export_sink = ExportSink(kind=export.get("kind", "none"), path=export.get("path", ""))
110
+ return QueryResult(
111
+ columns=raw.get("columns", []),
112
+ rows=rows,
113
+ tables=tables,
114
+ to_list=raw.get("to_list", False),
115
+ to_table=raw.get("to_table", False),
116
+ export_sink=export_sink,
117
+ )
118
+
119
+
120
+ __all__ = ["Document", "QueryResult", "TableResult", "ExportSink", "doc", "load", "summarize", "execute"]
Binary file
xsql/_core.cpp ADDED
@@ -0,0 +1,86 @@
1
+ #include <pybind11/pybind11.h>
2
+ #include <pybind11/stl.h>
3
+
4
+ #include "xsql/xsql.h"
5
+
6
+ namespace py = pybind11;
7
+
8
+ namespace {
9
+
10
+ py::dict attributes_to_dict(const std::unordered_map<std::string, std::string>& attrs) {
11
+ py::dict out;
12
+ for (const auto& kv : attrs) {
13
+ out[py::str(kv.first)] = py::str(kv.second);
14
+ }
15
+ return out;
16
+ }
17
+
18
+ py::object field_value(const xsql::QueryResultRow& row, const std::string& field) {
19
+ if (field == "node_id") return py::int_(row.node_id);
20
+ if (field == "count") return py::int_(row.node_id);
21
+ if (field == "tag") return py::str(row.tag);
22
+ if (field == "text") return py::str(row.text);
23
+ if (field == "inner_html") return py::str(row.inner_html);
24
+ if (field == "parent_id") {
25
+ if (row.parent_id.has_value()) return py::int_(*row.parent_id);
26
+ return py::none();
27
+ }
28
+ if (field == "source_uri") return py::str(row.source_uri);
29
+ if (field == "attributes") return attributes_to_dict(row.attributes);
30
+ auto it = row.attributes.find(field);
31
+ if (it == row.attributes.end()) return py::none();
32
+ return py::str(it->second);
33
+ }
34
+
35
+ py::dict row_to_dict(const xsql::QueryResultRow& row, const std::vector<std::string>& columns) {
36
+ py::dict out;
37
+ for (const auto& col : columns) {
38
+ out[py::str(col)] = field_value(row, col);
39
+ }
40
+ return out;
41
+ }
42
+
43
+ } // namespace
44
+
45
+ PYBIND11_MODULE(_core, m) {
46
+ m.doc() = "Native bindings for XSQL query execution.";
47
+
48
+ m.def("execute_from_document",
49
+ [](const std::string& html, const std::string& query) {
50
+ xsql::QueryResult result = xsql::execute_query_from_document(html, query);
51
+ py::dict out;
52
+ out["columns"] = result.columns;
53
+ py::list rows;
54
+ for (const auto& row : result.rows) {
55
+ rows.append(row_to_dict(row, result.columns));
56
+ }
57
+ out["rows"] = rows;
58
+ py::list tables;
59
+ for (const auto& table : result.tables) {
60
+ py::dict table_obj;
61
+ table_obj["node_id"] = table.node_id;
62
+ table_obj["rows"] = table.rows;
63
+ tables.append(table_obj);
64
+ }
65
+ out["tables"] = tables;
66
+ out["to_list"] = result.to_list;
67
+ out["to_table"] = result.to_table;
68
+ py::dict export_sink;
69
+ switch (result.export_sink.kind) {
70
+ case xsql::QueryResult::ExportSink::Kind::Csv:
71
+ export_sink["kind"] = "csv";
72
+ break;
73
+ case xsql::QueryResult::ExportSink::Kind::Parquet:
74
+ export_sink["kind"] = "parquet";
75
+ break;
76
+ default:
77
+ export_sink["kind"] = "none";
78
+ break;
79
+ }
80
+ export_sink["path"] = result.export_sink.path;
81
+ out["export_sink"] = export_sink;
82
+ return out;
83
+ },
84
+ py::arg("html"),
85
+ py::arg("query"));
86
+ }
xsql/_loader.py ADDED
@@ -0,0 +1,147 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import pathlib
5
+ import re
6
+ import urllib.request
7
+ from html.parser import HTMLParser
8
+ from typing import Optional, Tuple, Union
9
+ from urllib.error import HTTPError, URLError
10
+
11
+ from ._security import FetchPolicy, apply_redirect, is_url, normalize_path, validate_url_target
12
+
13
+ _HTML_HINT = re.compile(r"<[^>]+>")
14
+ _MAX_NODES = 100_000
15
+ _ALLOWED_CONTENT_TYPES = {
16
+ "text/html",
17
+ "application/xhtml+xml",
18
+ "application/xml",
19
+ "text/xml",
20
+ }
21
+
22
+
23
+ class _NodeCountingParser(HTMLParser):
24
+ """Counts HTML start tags to cap parser growth before execution."""
25
+
26
+ def __init__(self, max_nodes: int) -> None:
27
+ super().__init__(convert_charrefs=True)
28
+ self.max_nodes = max_nodes
29
+ self.count = 0
30
+
31
+ def handle_starttag(self, tag: str, attrs) -> None:
32
+ self.count += 1
33
+ if self.count > self.max_nodes:
34
+ raise ValueError("HTML exceeds maximum node limit")
35
+
36
+
37
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
38
+ """Disables automatic redirect handling so each hop can be validated."""
39
+
40
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
41
+ return None
42
+
43
+
44
+ def _enforce_max_nodes(html: str, max_nodes: int) -> None:
45
+ parser = _NodeCountingParser(max_nodes)
46
+ parser.feed(html)
47
+
48
+
49
+ def _read_bytes_limited(path: str, max_bytes: int) -> bytes:
50
+ size = os.path.getsize(path)
51
+ if size > max_bytes:
52
+ raise ValueError("File exceeds maximum allowed size")
53
+ with open(path, "rb") as handle:
54
+ data = handle.read(max_bytes + 1)
55
+ if len(data) > max_bytes:
56
+ raise ValueError("File exceeds maximum allowed size")
57
+ return data
58
+
59
+
60
+ def _decode_html(data: bytes) -> str:
61
+ return data.decode("utf-8", errors="replace")
62
+
63
+
64
+ def _validate_content_type(content_type: Optional[str]) -> None:
65
+ if not content_type:
66
+ return
67
+ content_main = content_type.split(";", 1)[0].strip().lower()
68
+ if content_main not in _ALLOWED_CONTENT_TYPES:
69
+ raise ValueError("Unsupported content-type for HTML fetch")
70
+
71
+
72
+ def _fetch_url(url: str, policy: FetchPolicy) -> Tuple[str, str]:
73
+ if not policy.allow_network:
74
+ raise ValueError("Network access is disabled by default")
75
+ validate_url_target(url, policy.allow_private_network)
76
+ current = url
77
+ opener = urllib.request.build_opener(_NoRedirect)
78
+ for _ in range(policy.max_redirects + 1):
79
+ try:
80
+ request = urllib.request.Request(current, headers={"User-Agent": "xsql-python/1.0"})
81
+ with opener.open(request, timeout=policy.timeout) as response:
82
+ if 300 <= response.status < 400:
83
+ location = response.headers.get("Location")
84
+ if not location:
85
+ raise ValueError("Redirect response missing Location header")
86
+ current = apply_redirect(current, location)
87
+ validate_url_target(current, policy.allow_private_network)
88
+ continue
89
+ _validate_content_type(response.headers.get("Content-Type"))
90
+ data = response.read(policy.max_bytes + 1)
91
+ if len(data) > policy.max_bytes:
92
+ raise ValueError("Downloaded HTML exceeds max_bytes")
93
+ return _decode_html(data), current
94
+ except HTTPError as err:
95
+ if 300 <= err.code < 400:
96
+ location = err.headers.get("Location")
97
+ if not location:
98
+ raise ValueError("Redirect response missing Location header") from err
99
+ current = apply_redirect(current, location)
100
+ validate_url_target(current, policy.allow_private_network)
101
+ continue
102
+ raise ValueError(f"HTTP error {err.code}") from err
103
+ except URLError as err:
104
+ raise ValueError("Failed to fetch URL") from err
105
+ raise ValueError("Too many redirects")
106
+
107
+
108
+ def load_html_source(
109
+ source: Union[str, bytes, pathlib.Path],
110
+ *,
111
+ base_dir: Optional[str],
112
+ policy: FetchPolicy,
113
+ ) -> Tuple[str, str]:
114
+ """Loads HTML from a local path, URL, or raw HTML string."""
115
+
116
+ if isinstance(source, bytes):
117
+ if len(source) > policy.max_bytes:
118
+ raise ValueError("HTML exceeds maximum allowed size")
119
+ html = _decode_html(source)
120
+ _enforce_max_nodes(html, _MAX_NODES)
121
+ return html, "document"
122
+
123
+ if isinstance(source, pathlib.Path):
124
+ source = str(source)
125
+
126
+ if not isinstance(source, str):
127
+ raise TypeError("source must be str, bytes, or Path")
128
+
129
+ if is_url(source):
130
+ html, final_url = _fetch_url(source, policy)
131
+ _enforce_max_nodes(html, _MAX_NODES)
132
+ return html, final_url
133
+
134
+ if os.path.exists(source):
135
+ path = normalize_path(source, base_dir)
136
+ data = _read_bytes_limited(path, policy.max_bytes)
137
+ html = _decode_html(data)
138
+ _enforce_max_nodes(html, _MAX_NODES)
139
+ return html, source
140
+
141
+ if _HTML_HINT.search(source):
142
+ if len(source.encode("utf-8", errors="replace")) > policy.max_bytes:
143
+ raise ValueError("HTML exceeds maximum allowed size")
144
+ _enforce_max_nodes(source, _MAX_NODES)
145
+ return source, "document"
146
+
147
+ raise ValueError("Source is ambiguous; pass bytes for raw HTML")
xsql/_security.py ADDED
@@ -0,0 +1,79 @@
1
+ from __future__ import annotations
2
+
3
+ import ipaddress
4
+ import os
5
+ import socket
6
+ from dataclasses import dataclass
7
+ from typing import Iterable, Optional, Tuple
8
+ from urllib.parse import urlparse, urljoin
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class FetchPolicy:
13
+ """Defines network and resource limits for fetching HTML content."""
14
+
15
+ allow_network: bool
16
+ allow_private_network: bool
17
+ timeout: int
18
+ max_bytes: int
19
+ max_redirects: int = 3
20
+
21
+
22
+ _PRIVATE_NETS = [
23
+ ipaddress.ip_network("127.0.0.0/8"),
24
+ ipaddress.ip_network("10.0.0.0/8"),
25
+ ipaddress.ip_network("172.16.0.0/12"),
26
+ ipaddress.ip_network("192.168.0.0/16"),
27
+ ipaddress.ip_network("169.254.0.0/16"),
28
+ ipaddress.ip_network("::1/128"),
29
+ ipaddress.ip_network("fc00::/7"),
30
+ ipaddress.ip_network("fe80::/10"),
31
+ ]
32
+
33
+
34
+ def is_url(source: str) -> bool:
35
+ """Detects http/https URLs to avoid ambiguous HTML interpretation."""
36
+
37
+ parsed = urlparse(source)
38
+ return parsed.scheme in {"http", "https"} and bool(parsed.netloc)
39
+
40
+
41
+ def resolve_host(host: str) -> Iterable[ipaddress._BaseAddress]:
42
+ """Resolves hostnames to IP addresses for SSRF filtering."""
43
+
44
+ infos = socket.getaddrinfo(host, None)
45
+ for family, _, _, _, sockaddr in infos:
46
+ if family == socket.AF_INET:
47
+ yield ipaddress.ip_address(sockaddr[0])
48
+ elif family == socket.AF_INET6:
49
+ yield ipaddress.ip_address(sockaddr[0])
50
+
51
+
52
+ def validate_url_target(url: str, allow_private: bool) -> None:
53
+ """Blocks localhost/private targets unless explicitly allowed."""
54
+
55
+ parsed = urlparse(url)
56
+ if parsed.scheme not in {"http", "https"}:
57
+ raise ValueError("Only http/https URLs are allowed")
58
+ if not parsed.hostname:
59
+ raise ValueError("URL must include a hostname")
60
+ for addr in resolve_host(parsed.hostname):
61
+ if any(addr in net for net in _PRIVATE_NETS) and not allow_private:
62
+ raise ValueError("URL points to a private or localhost address")
63
+
64
+
65
+ def normalize_path(path: str, base_dir: Optional[str]) -> str:
66
+ """Normalizes and confines file paths when base_dir is provided."""
67
+
68
+ real = os.path.realpath(path)
69
+ if base_dir:
70
+ base = os.path.realpath(base_dir)
71
+ if os.path.commonpath([real, base]) != base:
72
+ raise ValueError("Path escapes the configured base_dir")
73
+ return real
74
+
75
+
76
+ def apply_redirect(url: str, location: str) -> str:
77
+ """Resolves redirect targets while preserving relative locations."""
78
+
79
+ return urljoin(url, location)
xsql/_summary.py ADDED
@@ -0,0 +1,38 @@
1
+ from __future__ import annotations
2
+
3
+ from collections import Counter
4
+ from html.parser import HTMLParser
5
+ from typing import Dict, List, Tuple
6
+
7
+ from ._types import Document
8
+
9
+
10
+ class _SummaryParser(HTMLParser):
11
+ """Collects tag and attribute statistics without executing scripts."""
12
+
13
+ def __init__(self) -> None:
14
+ super().__init__(convert_charrefs=True)
15
+ self.tag_counts: Counter[str] = Counter()
16
+ self.attr_counts: Counter[str] = Counter()
17
+ self.total_nodes = 0
18
+
19
+ def handle_starttag(self, tag: str, attrs) -> None:
20
+ self.total_nodes += 1
21
+ self.tag_counts[tag] += 1
22
+ for key, _ in attrs:
23
+ if key:
24
+ self.attr_counts[key] += 1
25
+
26
+
27
+ def summarize_document(doc: Document, max_nodes_preview: int) -> Dict[str, object]:
28
+ """Produces a deterministic summary of tag and attribute usage."""
29
+
30
+ parser = _SummaryParser()
31
+ parser.feed(doc.html)
32
+ tags = parser.tag_counts.most_common(max_nodes_preview)
33
+ attrs = parser.attr_counts.most_common(max_nodes_preview)
34
+ return {
35
+ "total_nodes": parser.total_nodes,
36
+ "tag_counts": tags,
37
+ "attribute_keys": attrs,
38
+ }
xsql/_types.py ADDED
@@ -0,0 +1,40 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any, Dict, List, Optional
5
+
6
+
7
+ @dataclass(frozen=True)
8
+ class Document:
9
+ """Represents a parsed HTML document snapshot for deterministic queries."""
10
+
11
+ html: str
12
+ source: str
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class ExportSink:
17
+ """Captures export intent attached to a query result."""
18
+
19
+ kind: str
20
+ path: str
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class TableResult:
25
+ """Holds rows extracted from an HTML <table> node."""
26
+
27
+ node_id: int
28
+ rows: List[List[Optional[str]]]
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class QueryResult:
33
+ """Carries rows/tables plus metadata from executing an XSQL query."""
34
+
35
+ columns: List[str]
36
+ rows: List[Dict[str, Any]]
37
+ tables: List[TableResult]
38
+ to_list: bool
39
+ to_table: bool
40
+ export_sink: ExportSink