readwebform 0.4.0__py3-none-any.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,63 @@
1
+ """
2
+ readwebform - A command-line utility for gathering structured user input through temporary web forms.
3
+
4
+ Copyright (c) 2025 Vlad Lasky (github@vladlasky.com)
5
+ Licensed under the MIT License.
6
+
7
+ Programmatic Usage:
8
+
9
+ from readwebform import read_webform
10
+
11
+ # Simple HTML form - URL printed to stderr, open browser manually
12
+ result = read_webform('<form><input name="email" type="email"><button>Submit</button></form>')
13
+ if result.success:
14
+ print(f"Email: {result.fields['email']}")
15
+
16
+ # Or with auto-launch browser
17
+ result = read_webform(html, launch_browser=True)
18
+
19
+ # Declarative with Field dataclass (recommended - provides IDE autocompletion)
20
+ from readwebform import read_webform_fields, Field
21
+
22
+ result = read_webform_fields([
23
+ Field(name='email', type='email', label='Email', required=True),
24
+ Field(name='age', type='number', label='Age', min=0, max=120)
25
+ ], launch_browser=True)
26
+ if result.success:
27
+ print(f"Email: {result.fields['email']}, Age: {result.fields['age']}")
28
+
29
+ # Dicts also work (backward compatible)
30
+ result = read_webform_fields([
31
+ {'name': 'email', 'type': 'email', 'label': 'Email', 'required': True},
32
+ {'name': 'age', 'type': 'number', 'label': 'Age'}
33
+ ])
34
+ """
35
+
36
+ try:
37
+ from importlib.metadata import PackageNotFoundError
38
+ from importlib.metadata import version as _pkg_version
39
+ try:
40
+ __version__ = _pkg_version("readwebform")
41
+ except PackageNotFoundError:
42
+ __version__ = "0.4.0"
43
+ except ImportError: # pragma: no cover
44
+ __version__ = "0.4.0"
45
+ __author__ = "Vlad Lasky"
46
+ __email__ = "github@vladlasky.com"
47
+
48
+ # High-level API (recommended)
49
+ from readwebform.api import Field, FormResult, UploadedFile, read_webform, read_webform_fields
50
+
51
+ # Low-level API (for advanced use)
52
+ from readwebform.server import FormServer
53
+
54
+ __all__ = [
55
+ 'Field',
56
+ 'FormResult',
57
+ # Low-level API
58
+ 'FormServer',
59
+ 'UploadedFile',
60
+ # High-level API
61
+ 'read_webform',
62
+ 'read_webform_fields',
63
+ ]
@@ -0,0 +1,10 @@
1
+ """
2
+ Allow readwebform to be executed as a module: python -m readwebform
3
+ """
4
+
5
+ import sys
6
+
7
+ from readwebform.cli import main
8
+
9
+ if __name__ == '__main__':
10
+ sys.exit(main())
readwebform/api.py ADDED
@@ -0,0 +1,335 @@
1
+ """
2
+ High-level Python API for readwebform.
3
+ """
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Any, Literal, Optional, Union
7
+
8
+ from .forms import generate_form_html_from_dicts
9
+ from .parser import inject_csrf_token, validate_html, wrap_html_fragment
10
+ from .server import FormServer
11
+
12
+ # Valid field types
13
+ FieldType = Literal[
14
+ 'text', 'email', 'password', 'number', 'date', 'url', 'tel', 'search',
15
+ 'time', 'datetime-local', 'month', 'week', 'range', 'color', 'hidden',
16
+ 'textarea', 'select', 'checkbox', 'radio', 'file'
17
+ ]
18
+
19
+
20
+ @dataclass
21
+ class Field:
22
+ """
23
+ Type-safe field specification for declarative form building.
24
+
25
+ Provides IDE autocompletion and type checking for field definitions.
26
+
27
+ Example:
28
+ fields = [
29
+ Field(name='email', type='email', label='Email Address', required=True),
30
+ Field(name='age', type='number', label='Age', min=0, max=120),
31
+ Field(name='country', type='select', label='Country', options=['US', 'UK', 'CA'], value='UK'),
32
+ Field(name='plan', type='radio', label='Plan', options=['free', 'pro']),
33
+ Field(name='notify', type='checkbox', label='Email me', checked=True),
34
+ ]
35
+
36
+ ``value`` pre-fills the field: the text of an input or textarea, the
37
+ selected option(s) of a select or radio group, or the submitted value of
38
+ a checkbox (use ``checked`` to tick it).
39
+ result = read_webform_fields(fields)
40
+ """
41
+ name: str
42
+ type: FieldType
43
+ label: Optional[str] = None
44
+ required: bool = False
45
+ placeholder: Optional[str] = None
46
+ min: Optional[Union[int, float, str]] = None
47
+ max: Optional[Union[int, float, str]] = None
48
+ step: Optional[Union[int, float]] = None
49
+ rows: Optional[int] = None
50
+ cols: Optional[int] = None
51
+ options: Optional[list[str]] = None
52
+ accept: Optional[str] = None
53
+ multiple: bool = False
54
+ pattern: Optional[str] = None
55
+ value: Optional[Union[str, int, float, list[str]]] = None
56
+ checked: bool = False
57
+ minlength: Optional[int] = None
58
+ maxlength: Optional[int] = None
59
+
60
+ def to_dict(self) -> dict[str, Any]:
61
+ """Convert Field to dictionary format for internal use."""
62
+ result: dict[str, Any] = {'name': self.name, 'type': self.type}
63
+
64
+ if self.label is not None:
65
+ result['label'] = self.label
66
+ if self.required:
67
+ result['required'] = True
68
+ if self.placeholder is not None:
69
+ result['placeholder'] = self.placeholder
70
+ if self.min is not None:
71
+ result['min'] = self.min
72
+ if self.max is not None:
73
+ result['max'] = self.max
74
+ if self.step is not None:
75
+ result['step'] = self.step
76
+ if self.rows is not None:
77
+ result['rows'] = self.rows
78
+ if self.cols is not None:
79
+ result['cols'] = self.cols
80
+ if self.options is not None:
81
+ result['options'] = self.options
82
+ if self.accept is not None:
83
+ result['accept'] = self.accept
84
+ if self.multiple:
85
+ result['multiple'] = True
86
+ if self.pattern is not None:
87
+ result['pattern'] = self.pattern
88
+ if self.value is not None:
89
+ result['value'] = self.value
90
+ if self.checked:
91
+ result['checked'] = True
92
+ if self.minlength is not None:
93
+ result['minlength'] = self.minlength
94
+ if self.maxlength is not None:
95
+ result['maxlength'] = self.maxlength
96
+
97
+ return result
98
+
99
+
100
+ @dataclass(frozen=True)
101
+ class UploadedFile:
102
+ """
103
+ Metadata for an uploaded file.
104
+
105
+ Provides type-safe access to file upload information.
106
+ This dataclass is immutable (frozen).
107
+
108
+ Attributes:
109
+ filename: Original filename from the upload
110
+ path: Local filesystem path where the file was saved
111
+ size: Size of the uploaded file in bytes
112
+ content_type: MIME type of the file (e.g., 'application/pdf')
113
+
114
+ Example:
115
+ if result.success and 'document' in result.files:
116
+ doc = result.files['document']
117
+ print(f"Saved {doc.filename} ({doc.size} bytes) to {doc.path}")
118
+ print(f"Content type: {doc.content_type}")
119
+ with open(doc.path, 'rb') as f:
120
+ content = f.read()
121
+ """
122
+ filename: str
123
+ path: str
124
+ size: int
125
+ content_type: str
126
+
127
+
128
+ @dataclass
129
+ class FormResult:
130
+ """
131
+ Result of form submission.
132
+
133
+ Attributes:
134
+ success: True if form was submitted successfully, False on timeout/error
135
+ fields: Dictionary of field name -> value. Repeated fields (checkbox
136
+ groups, multi-selects) are lists of strings. None if not success.
137
+ files: Dictionary of file field name -> UploadedFile, or a list of
138
+ UploadedFile for ``<input type="file" multiple>``. None if no files.
139
+ error: Error description if success is False (e.g., 'timeout', 'cancelled')
140
+
141
+ Example:
142
+ result = read_webform(html, timeout=60)
143
+ if result.success:
144
+ print(f"Got email: {result.fields['email']}")
145
+ else:
146
+ print(f"Form failed: {result.error}")
147
+ """
148
+ success: bool
149
+ fields: Optional[dict[str, Union[str, list[str]]]] = None
150
+ files: Optional[dict[str, Union[UploadedFile, list[UploadedFile]]]] = None
151
+ error: Optional[str] = None
152
+
153
+
154
+ def read_webform(
155
+ html: str,
156
+ timeout: int = 300,
157
+ launch_browser: bool = False,
158
+ browser_path: Optional[str] = None,
159
+ max_file_size: Optional[int] = None,
160
+ max_total_size: Optional[int] = None,
161
+ reset_timeout_on_error: bool = True,
162
+ host: str = '127.0.0.1',
163
+ port: Optional[int] = None,
164
+ cert_file: Optional[str] = None,
165
+ key_file: Optional[str] = None,
166
+ url_file: Optional[str] = None,
167
+ upload_dir: Optional[str] = None,
168
+ url_host: Optional[str] = None
169
+ ) -> FormResult:
170
+ """
171
+ Display a web form and wait for user submission.
172
+
173
+ Args:
174
+ html: HTML form content (fragment or complete document)
175
+ timeout: Maximum seconds to wait for submission (default: 300)
176
+ launch_browser: Whether to open the browser (default: False). Unlike the
177
+ CLI, the API never opens a browser unless this is True.
178
+ browser_path: Path to specific browser executable (None = system default)
179
+ max_file_size: Maximum individual file upload size in bytes
180
+ max_total_size: Maximum total upload size in bytes
181
+ reset_timeout_on_error: Whether to reset timeout on errors (default: True)
182
+ host: IPv4 or IPv6 address to bind to (default: '127.0.0.1')
183
+ port: Port to bind to (None = auto-select)
184
+ cert_file: Path to a PEM certificate to serve HTTPS (requires key_file)
185
+ key_file: Path to the PEM private key for cert_file
186
+ url_file: If given, the form URL is written to this file once listening
187
+ upload_dir: Directory for uploaded files (default: a temporary directory
188
+ created on first upload and removed if left empty)
189
+ url_host: Host to put in the form URL (default: the bind host, or a
190
+ best-effort guess of this machine's address for a wildcard bind)
191
+
192
+ Returns:
193
+ FormResult with success flag, fields dict, and files dict
194
+
195
+ Example:
196
+ result = read_webform('<form><input name="email" type="email"><button>Submit</button></form>',
197
+ launch_browser=True)
198
+ if result.success:
199
+ print(f"Email: {result.fields['email']}")
200
+ """
201
+ # Validate HTML has exactly one form
202
+ valid, error_msg = validate_html(html)
203
+ if not valid:
204
+ return FormResult(success=False, error=f'invalid_html: {error_msg}')
205
+
206
+ # Wrap if fragment
207
+ html = wrap_html_fragment(html)
208
+
209
+ # Create server
210
+ server = FormServer(
211
+ html=html,
212
+ host=host,
213
+ port=port,
214
+ max_file_size=max_file_size,
215
+ max_total_size=max_total_size,
216
+ timeout=timeout,
217
+ reset_timeout_on_error=reset_timeout_on_error,
218
+ cert_file=cert_file,
219
+ key_file=key_file,
220
+ upload_dir=upload_dir,
221
+ url_host=url_host
222
+ )
223
+
224
+ # Inject CSRF token
225
+ html_with_csrf = inject_csrf_token(html, server.csrf_token, server.endpoint)
226
+ server.html = html_with_csrf
227
+
228
+ # Serve form and optionally launch browser
229
+ # Browser is launched inside serve() AFTER server is bound (fixes race condition)
230
+ try:
231
+ # Empty string for browser_path means system default
232
+ launch_path = (browser_path or '') if launch_browser else None
233
+ success, form_data, file_metadata, cancelled = server.serve(
234
+ launch_browser_path=launch_path, url_file=url_file)
235
+ except OSError as e:
236
+ return FormResult(success=False, error=f'bind_error: {e}')
237
+ except Exception as e:
238
+ return FormResult(success=False, error=f'server_error: {e}')
239
+
240
+ # Handle cancellation
241
+ if cancelled:
242
+ return FormResult(success=False, error='cancelled')
243
+
244
+ # Convert to result object
245
+ if success:
246
+ # Convert file metadata dicts to UploadedFile objects
247
+ uploaded_files: dict[str, Union[UploadedFile, list[UploadedFile]]] = {}
248
+ for name, meta in (file_metadata or {}).items():
249
+ if isinstance(meta, list):
250
+ uploaded_files[name] = [UploadedFile(**m) for m in meta]
251
+ else:
252
+ uploaded_files[name] = UploadedFile(**meta)
253
+
254
+ return FormResult(
255
+ success=True,
256
+ fields=form_data.fields if form_data else {},
257
+ files=uploaded_files if uploaded_files else None,
258
+ error=None
259
+ )
260
+ else:
261
+ return FormResult(success=False, error='timeout')
262
+
263
+
264
+ def read_webform_fields(
265
+ fields: list[Union[Field, dict[str, Any]]],
266
+ title: Optional[str] = None,
267
+ text: Optional[str] = None,
268
+ timeout: int = 300,
269
+ launch_browser: bool = False,
270
+ browser_path: Optional[str] = None,
271
+ add_cancel_button: bool = True,
272
+ cancel_label: str = 'Cancel',
273
+ submit_label: str = 'Submit',
274
+ **kwargs
275
+ ) -> FormResult:
276
+ """
277
+ Display a form built from field specifications and wait for user submission.
278
+
279
+ Args:
280
+ fields: List of field specifications. Each can be either:
281
+ - A Field dataclass instance (recommended, provides IDE support)
282
+ - A dict with the same keys as Field (name, type, label, required,
283
+ placeholder, value, checked, min, max, step, rows, cols, options, ...)
284
+ title: Page title (optional)
285
+ text: Instructional text above form (optional)
286
+ timeout: Maximum seconds to wait (default: 300)
287
+ launch_browser: Whether to open browser (default: False)
288
+ browser_path: Path to specific browser (optional)
289
+ add_cancel_button: Whether to add cancel button (default: True)
290
+ cancel_label: Label for the cancel button (default: 'Cancel')
291
+ submit_label: Label for the submit button (default: 'Submit')
292
+ **kwargs: Additional arguments passed to read_webform()
293
+
294
+ Returns:
295
+ FormResult with success flag, fields dict, and files dict
296
+
297
+ Example using Field dataclass:
298
+ result = read_webform_fields([
299
+ Field(name='email', type='email', label='Email', required=True),
300
+ Field(name='age', type='number', label='Age', min=0, max=120)
301
+ ], launch_browser=True)
302
+
303
+ Example using dicts (backward compatible):
304
+ result = read_webform_fields([
305
+ {'name': 'email', 'type': 'email', 'label': 'Email', 'required': True},
306
+ {'name': 'age', 'type': 'number', 'label': 'Age', 'min': 0, 'max': 120}
307
+ ], launch_browser=True)
308
+ """
309
+ # Convert Field objects to dicts for internal processing
310
+ field_dicts = []
311
+ for f in fields:
312
+ if isinstance(f, Field):
313
+ field_dicts.append(f.to_dict())
314
+ else:
315
+ field_dicts.append(f)
316
+
317
+ # Generate HTML from fields
318
+ html = generate_form_html_from_dicts(
319
+ field_dicts,
320
+ title=title,
321
+ text=text,
322
+ add_submit=True,
323
+ add_cancel=add_cancel_button,
324
+ cancel_label=cancel_label,
325
+ submit_label=submit_label
326
+ )
327
+
328
+ # Use read_webform
329
+ return read_webform(
330
+ html=html,
331
+ timeout=timeout,
332
+ launch_browser=launch_browser,
333
+ browser_path=browser_path,
334
+ **kwargs
335
+ )
readwebform/browser.py ADDED
@@ -0,0 +1,115 @@
1
+ """
2
+ Cross-platform browser launching for readwebform.
3
+
4
+ The CLI's contract is that stdout carries only the JSON result, so anything
5
+ a browser process prints must never reach our stdout. Browsers are therefore
6
+ always started from a child process whose standard streams point at the null
7
+ device: a custom browser directly, the system default browser through a
8
+ short-lived Python child that calls ``webbrowser.open``. Nothing in this
9
+ process's file descriptors is touched.
10
+ """
11
+
12
+ import os
13
+ import subprocess
14
+ import sys
15
+ import webbrowser
16
+ from typing import Optional
17
+
18
+ _DEFAULT_LAUNCHER = (
19
+ 'import sys, webbrowser\n'
20
+ 'sys.exit(0 if webbrowser.open(sys.argv[1]) else 1)\n'
21
+ )
22
+
23
+ # How long to wait for a launcher child to report an immediate failure (no
24
+ # browser found, bad executable). Background browsers hand off within this
25
+ # time; a child still running afterwards is treated as success so the caller
26
+ # is not held up. Reporting is therefore best effort. Terminal browsers
27
+ # (lynx, w3m) need a tty and are not supported by --launch-browser: the URL
28
+ # is always printed to stderr for manual use.
29
+ _LAUNCH_WAIT = 1.0
30
+
31
+
32
+ def gui_available() -> bool:
33
+ """
34
+ Guess whether a browser can be opened on a desktop the user is looking at.
35
+
36
+ False in CI (``CI`` set), over SSH (``SSH_CONNECTION``/``SSH_TTY`` set), when
37
+ ``READWEBFORM_NO_BROWSER`` is set, and on Unix without ``DISPLAY`` or
38
+ ``WAYLAND_DISPLAY``. True on macOS and Windows otherwise.
39
+ """
40
+ env = os.environ
41
+ if env.get('CI') or env.get('READWEBFORM_NO_BROWSER'):
42
+ return False
43
+ if env.get('SSH_CONNECTION') or env.get('SSH_TTY'):
44
+ return False
45
+ if sys.platform in ('darwin', 'win32', 'cygwin'):
46
+ return True
47
+ return bool(env.get('DISPLAY') or env.get('WAYLAND_DISPLAY'))
48
+
49
+
50
+ def launch_browser(url: str, browser_path: Optional[str] = None) -> bool:
51
+ """
52
+ Open a URL in a browser.
53
+
54
+ Args:
55
+ url: URL to open
56
+ browser_path: Optional path to a browser executable (None = system default)
57
+
58
+ Returns:
59
+ True if the launch appears to have succeeded, False otherwise
60
+ """
61
+ try:
62
+ if browser_path:
63
+ return _launch_custom_browser(url, browser_path)
64
+ return _launch_default_browser(url)
65
+ except Exception as e:
66
+ print(f'Warning: Failed to launch browser: {e}', file=sys.stderr)
67
+ return False
68
+
69
+
70
+ def _spawn_detached(argv: list) -> subprocess.Popen:
71
+ """Start argv with stdin/stdout/stderr on the null device, in its own session."""
72
+ return subprocess.Popen(
73
+ argv,
74
+ stdin=subprocess.DEVNULL,
75
+ stdout=subprocess.DEVNULL,
76
+ stderr=subprocess.DEVNULL,
77
+ start_new_session=True,
78
+ )
79
+
80
+
81
+ def _launch_default_browser(url: str) -> bool:
82
+ """Open the URL with the system default browser via an isolated child."""
83
+ if not sys.executable:
84
+ # No interpreter path (unusual embedding); fall back to in-process
85
+ return webbrowser.open(url)
86
+
87
+ try:
88
+ proc = _spawn_detached([sys.executable, '-I', '-c', _DEFAULT_LAUNCHER, url])
89
+ except OSError as e:
90
+ print(f'Warning: Failed to start browser launcher: {e}', file=sys.stderr)
91
+ return False
92
+
93
+ try:
94
+ return proc.wait(timeout=_LAUNCH_WAIT) == 0
95
+ except subprocess.TimeoutExpired:
96
+ return True # still running: treat as launched
97
+
98
+
99
+ def _launch_custom_browser(url: str, browser_path: str) -> bool:
100
+ """
101
+ Open the URL with a specific browser executable.
102
+
103
+ Reporting is best effort: a launcher that fails within _LAUNCH_WAIT is
104
+ reported; one that fails later is not observed.
105
+ """
106
+ try:
107
+ # No shell (prevents injection); the child's output cannot reach our stdout
108
+ proc = _spawn_detached([browser_path, url])
109
+ except Exception as e:
110
+ print(f'Warning: Failed to launch {browser_path}: {e}', file=sys.stderr)
111
+ return False
112
+ try:
113
+ return proc.wait(timeout=_LAUNCH_WAIT) == 0
114
+ except subprocess.TimeoutExpired:
115
+ return True # still running: treat as launched