transcript 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.
transcript/purge.py ADDED
@@ -0,0 +1,171 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from copy import deepcopy
5
+ from pathlib import Path
6
+ from typing import Any, Iterable
7
+
8
+ from transcript.builders.scss import CSSClass, SCSS, SCSSComment, SCSSLine, SCSSProp, SCSSRoot, SCSSVariable
9
+ from transcript.core.container import ContainerBase, Fragment
10
+
11
+ CLASS_ATTR_RE = re.compile(
12
+ r"""(?:class|className)\s*=\s*(?:'([^']*)'|"([^"]*)"|`([^`]*)`)""",
13
+ re.IGNORECASE,
14
+ )
15
+ CLASS_TOKEN_RE = re.compile(r'\.([a-zA-Z_][\w-]*)')
16
+ # Potencjalne tokeny utility w tekście (np. w JS stringach)
17
+ BARE_CLASS_RE = re.compile(r'(?<![\w-])([a-zA-Z_][\w-]*(?:/[\w-]+)?)(?![\w-])')
18
+
19
+
20
+ def extract_classes_from_text(text: str) -> set[str]:
21
+ """Wyciąga nazwy klas z atrybutów class / className oraz selektorów."""
22
+ found: set[str] = set()
23
+ for match in CLASS_ATTR_RE.finditer(text):
24
+ value = match.group(1) or match.group(2) or match.group(3) or ''
25
+ found.update(token for token in value.split() if token)
26
+ found.update(CLASS_TOKEN_RE.findall(text))
27
+ return found
28
+
29
+
30
+ def extract_classes_from_paths(
31
+ paths: Iterable[Path],
32
+ *,
33
+ suffixes: tuple[str, ...] = ('.html', '.htm', '.jinja', '.j2', '.js', '.ts', '.jsx', '.tsx', '.vue'),
34
+ ) -> set[str]:
35
+ found: set[str] = set()
36
+ for path in paths:
37
+ if path.is_dir():
38
+ for child in path.rglob('*'):
39
+ if child.is_file() and child.suffix.lower() in suffixes:
40
+ try:
41
+ found |= extract_classes_from_text(child.read_text(encoding='utf-8'))
42
+ except OSError:
43
+ continue
44
+ elif path.is_file():
45
+ try:
46
+ found |= extract_classes_from_text(path.read_text(encoding='utf-8'))
47
+ except OSError:
48
+ continue
49
+ return found
50
+
51
+
52
+ def extract_classes_from_containers(containers: Iterable[ContainerBase]) -> set[str]:
53
+ found: set[str] = set()
54
+ for container in containers:
55
+ found |= extract_classes_from_text(container.build())
56
+ attrs = getattr(container, 'attrs', None)
57
+ if attrs:
58
+ for attr in attrs:
59
+ if getattr(attr, 'name', None) == 'class':
60
+ value = attr.value
61
+ if isinstance(value, str):
62
+ found.update(value.split())
63
+ return found
64
+
65
+
66
+ def selector_class_names(selector: str) -> set[str]:
67
+ return set(CLASS_TOKEN_RE.findall(selector))
68
+
69
+
70
+ def _is_structural(node: Any) -> bool:
71
+ if isinstance(node, (SCSSVariable, SCSSComment, SCSSLine, SCSSProp)):
72
+ return True
73
+ if isinstance(node, SCSS):
74
+ selector = node.selector.strip()
75
+ if selector.startswith('@'):
76
+ return True
77
+ if selector in {'*', 'html', 'body'} or selector.startswith('*,'):
78
+ return True
79
+ if not selector_class_names(selector) and not selector.startswith('&'):
80
+ # selektory tagów / złożone bez klas — zostaw
81
+ return True
82
+ return False
83
+
84
+
85
+ def _rule_matches(node: SCSS, used: set[str], safelist: set[str]) -> bool:
86
+ if _is_structural(node):
87
+ return True
88
+ classes = selector_class_names(node.selector)
89
+ if not classes:
90
+ # &__element / &--mod przy rodzicu — decyzja na poziomie rodzica
91
+ if node.selector.strip().startswith('&'):
92
+ return True
93
+ return True
94
+ allow = used | safelist
95
+ if classes & allow:
96
+ return True
97
+ # BEM: użycie block__element utrzymuje block
98
+ for cls in classes:
99
+ prefix = f'{cls}__'
100
+ mod = f'{cls}--'
101
+ if any(token.startswith(prefix) or token.startswith(mod) for token in allow):
102
+ return True
103
+ return False
104
+
105
+
106
+ def purge_scss(
107
+ root: ContainerBase,
108
+ used_classes: Iterable[str],
109
+ *,
110
+ safelist: Iterable[str] = (),
111
+ ) -> ContainerBase:
112
+ """Zwraca kopię drzewa SCSS bez nieużywanych reguł klas (jak purge Tailwind)."""
113
+ used = set(used_classes)
114
+ safe = set(safelist)
115
+ clone = deepcopy(root)
116
+ _purge_node(clone, used, safe)
117
+ return clone
118
+
119
+
120
+ def _purge_node(node: Any, used: set[str], safelist: set[str]) -> bool:
121
+ """Filtruje ``content`` w miejscu. Zwraca True, jeśli węzeł ma zostać zachowany."""
122
+ if isinstance(node, (SCSSVariable, SCSSComment, SCSSLine, SCSSProp, str)):
123
+ return True
124
+
125
+ if not isinstance(node, ContainerBase):
126
+ return True
127
+
128
+ if isinstance(node, SCSS) and not isinstance(node, (SCSSRoot, Fragment)):
129
+ if not _rule_matches(node, used, safelist):
130
+ return False
131
+
132
+ if hasattr(node, 'content'):
133
+ kept: list[Any] = []
134
+ for child in list(node.content):
135
+ if isinstance(child, ContainerBase):
136
+ if _purge_node(child, used, safelist):
137
+ kept.append(child)
138
+ elif isinstance(child, SCSSProp):
139
+ kept.append(child)
140
+ else:
141
+ kept.append(child)
142
+ node.content = kept
143
+
144
+ if isinstance(node, SCSS) and not isinstance(node, (SCSSRoot, Fragment)):
145
+ # puste @media po purge — usuń
146
+ if node.selector.strip().startswith('@') and not node.content and not getattr(node, 'props', None):
147
+ return False
148
+ if (
149
+ node.selector.strip().startswith('@')
150
+ and not node.content
151
+ and not any(getattr(node, 'props', []) or [])
152
+ ):
153
+ return False
154
+
155
+ if isinstance(node, (SCSSRoot, Fragment, CSSClass, SCSS)):
156
+ props = getattr(node, 'props', None)
157
+ has_props = bool(props and any(props))
158
+ if isinstance(node, (SCSSRoot, Fragment)):
159
+ return True
160
+ if not node.content and not has_props and node.selector.strip().startswith('@'):
161
+ return False
162
+ return True
163
+
164
+
165
+ __all__ = [
166
+ 'extract_classes_from_text',
167
+ 'extract_classes_from_paths',
168
+ 'extract_classes_from_containers',
169
+ 'selector_class_names',
170
+ 'purge_scss',
171
+ ]
transcript/py.typed ADDED
File without changes
@@ -0,0 +1,201 @@
1
+ Metadata-Version: 2.4
2
+ Name: transcript
3
+ Version: 0.4.0
4
+ Summary: Python DSL for composing HTML, Jinja2, SCSS and JavaScript with << / >> data-flow operators
5
+ Author-email: Marcin Kallas <marcin.kallas@gmail.com>
6
+ Maintainer-email: Marcin Kallas <marcin.kallas@gmail.com>
7
+ License-Expression: MIT
8
+ Project-URL: Homepage, https://github.com/itelementsadmin/transcript
9
+ Project-URL: Documentation, https://github.com/itelementsadmin/transcript#readme
10
+ Project-URL: Repository, https://github.com/itelementsadmin/transcript
11
+ Project-URL: Issues, https://github.com/itelementsadmin/transcript/issues
12
+ Project-URL: Changelog, https://github.com/itelementsadmin/transcript/blob/main/CHANGELOG.md
13
+ Keywords: html,scss,css,jinja2,javascript,dsl,codegen,templates,tailwind,bem,static-site
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3 :: Only
21
+ Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
22
+ Classifier: Topic :: Software Development :: Code Generators
23
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
24
+ Classifier: Topic :: Text Processing :: Markup :: HTML
25
+ Classifier: Typing :: Typed
26
+ Requires-Python: >=3.13
27
+ Description-Content-Type: text/markdown
28
+ License-File: LICENSE
29
+ Requires-Dist: python-dotenv>=1.0.0
30
+ Provides-Extra: jinja
31
+ Requires-Dist: jinja2>=3.1.6; extra == "jinja"
32
+ Provides-Extra: preview
33
+ Requires-Dist: websockets>=15.0.1; extra == "preview"
34
+ Requires-Dist: watchdog>=6.0.0; extra == "preview"
35
+ Provides-Extra: ai
36
+ Requires-Dist: langchain>=0.3.27; extra == "ai"
37
+ Requires-Dist: langchain-openai>=0.3.34; extra == "ai"
38
+ Requires-Dist: langchain-google-genai>=2.1.12; extra == "ai"
39
+ Requires-Dist: langchain-ollama>=0.3.9; extra == "ai"
40
+ Requires-Dist: pydantic>=2.11.9; extra == "ai"
41
+ Provides-Extra: dev
42
+ Requires-Dist: pytest>=8.0; extra == "dev"
43
+ Requires-Dist: build>=1.2; extra == "dev"
44
+ Requires-Dist: twine>=5.0; extra == "dev"
45
+ Provides-Extra: docs
46
+ Requires-Dist: mkdocs>=1.6; extra == "docs"
47
+ Requires-Dist: mkdocs-material>=9.5; extra == "docs"
48
+ Provides-Extra: all
49
+ Requires-Dist: transcript[ai,jinja,preview]; extra == "all"
50
+ Dynamic: license-file
51
+
52
+ # transcript
53
+
54
+ Python DSL for composing **HTML**, **Jinja2**, **SCSS** and **JavaScript** as nested code containers.
55
+ Data flows with overloaded operators `<<` (inject) and `>>` (export).
56
+
57
+ [![PyPI version](https://img.shields.io/pypi/v/transcript.svg)](https://pypi.org/project/transcript/)
58
+ [![Python](https://img.shields.io/pypi/pyversions/transcript.svg)](https://pypi.org/project/transcript/)
59
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
60
+
61
+ ## Install
62
+
63
+ ```bash
64
+ pip install transcript
65
+ ```
66
+
67
+ Optional extras:
68
+
69
+ ```bash
70
+ pip install transcript[jinja] # Jinja2 runtime
71
+ pip install transcript[preview] # live preview helpers
72
+ pip install transcript[ai] # LangChain helpers
73
+ pip install transcript[dev] # pytest, build, twine
74
+ pip install transcript[docs] # MkDocs
75
+ pip install transcript[all]
76
+ ```
77
+
78
+ Requires **Python 3.13+**.
79
+
80
+ ## Quick start
81
+
82
+ ```python
83
+ from transcript import Div, File, HTMLArg, P, SCSS
84
+ from transcript.presets import HTML5Document
85
+
86
+ page = HTML5Document(title='Hello', lang='en')
87
+ hero = Div()
88
+ hero << HTMLArg('id', 'top') << P('Built with transcript')
89
+ page.body << hero
90
+
91
+ page >> File('templates/index.html')
92
+ html = page >> str
93
+ ```
94
+
95
+ ## Core ideas
96
+
97
+ Every block (tag, rule, function) is a **container**: opening, body, closing.
98
+
99
+ | Expression | Meaning |
100
+ |---|---|
101
+ | `a << b` | inject block / value into `a` |
102
+ | `a << HTMLArg(...)` / `XMLArg(...)` | set opening-tag attributes |
103
+ | `a << File(...)` | inject file contents |
104
+ | `a << JsonData(...)` | attrs + nested content from JSON |
105
+ | `a << CSSClass('hero')` | add CSS class name to `class` |
106
+ | `a >> str` | export generated code |
107
+ | `a >> File('out.html')` | write to disk |
108
+ | `a >> JsonData()` | serialize structure to JSON |
109
+ | `a >> Renderer()` | push code into a renderer |
110
+
111
+ Reverse the pipeline with `load`:
112
+
113
+ ```python
114
+ from transcript import load
115
+
116
+ data = load('templates/index.html') # JsonData
117
+ tree = load('templates/index.html', as_container=True)
118
+ ```
119
+
120
+ ## SCSS, BEM and Tailwind-like utilities
121
+
122
+ ```python
123
+ from transcript import BEM, CSSClass, Tailwind, tw, Div
124
+
125
+ card = BEM('card', display='grid')
126
+ card << CSSClass('title', font_size='1.25rem') # &__title
127
+ card.modifier('featured') # &--featured
128
+
129
+ Div(class_=tw('flex', 'items-center', 'gap-4', 'p-4', 'bg-white'))
130
+ sheet = Tailwind(utilities=('layout', 'spacing', 'color'))
131
+ ```
132
+
133
+ ## JavaScript
134
+
135
+ ```python
136
+ from transcript import JS, JSFunction, JSLine, File
137
+
138
+ script = JS()
139
+ script << JSFunction('init', 'root', JSLine("root.classList.add('ready')"))
140
+ script >> File('static/app.js')
141
+ ```
142
+
143
+ ## Project generate + purge
144
+
145
+ ```python
146
+ from transcript import Project, JS, tw, Div
147
+ from transcript.presets import HTML5Document
148
+ from transcript.presets.tailwind import Tailwind
149
+
150
+ project = Project('myapp')
151
+ page = HTML5Document(title='App')
152
+ page.body << Div(class_=tw('flex', 'gap-4', 'p-4'))
153
+ project.add('index.html', page)
154
+ project.add('app.scss', Tailwind(utilities=('layout', 'spacing')))
155
+ project.add('app.js', JS())
156
+ project.generate() # writes files; purges unused utility classes
157
+ ```
158
+
159
+ ## Hub (prebuild store)
160
+
161
+ ```python
162
+ from transcript import Hub, JsonData
163
+
164
+ hub = Hub() # TRANSCRIPT_HUB_URL + token/api_key from .env
165
+ block = hub.get('hero-card')
166
+ hub.post(page >> JsonData(), prebuild_id='home')
167
+ ```
168
+
169
+ See [`.env.example`](.env.example) for variable names.
170
+
171
+ ## Documentation
172
+
173
+ Full docs live in [`docs/`](docs/):
174
+
175
+ - [Getting started](docs/getting-started.md)
176
+ - [Operators & IO](docs/operators.md)
177
+ - [HTML & Jinja](docs/html-jinja.md)
178
+ - [SCSS / BEM / Tailwind](docs/scss.md)
179
+ - [JavaScript](docs/javascript.md)
180
+ - [Project & purge](docs/project.md)
181
+ - [Publishing to PyPI](docs/publishing.md)
182
+
183
+ Build the site locally:
184
+
185
+ ```bash
186
+ pip install transcript[docs]
187
+ mkdocs serve
188
+ ```
189
+
190
+ ## Development
191
+
192
+ ```bash
193
+ python -m venv .venv
194
+ .venv\Scripts\activate # Windows
195
+ pip install -e ".[dev]"
196
+ pytest
197
+ ```
198
+
199
+ ## License
200
+
201
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,40 @@
1
+ transcript/__init__.py,sha256=WkL-Ko9ySy0zcXT63XplMDQg2KudzPzO7qFse1DjQq0,3244
2
+ transcript/project.py,sha256=Xw7d7gcg1kv7yW91clg0ToUb6A11rJ1OZ1l8q4-8Ar4,8728
3
+ transcript/purge.py,sha256=3LKaFgl6uJQl1iqGYweioZlVbUqOg1zuWlIzdVQ9Los,6065
4
+ transcript/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ transcript/builders/__init__.py,sha256=7RVgYcxnXNvO2dRaNATK8s_zU08rBBw7belQ_g9hlQQ,49
6
+ transcript/builders/jinja.py,sha256=fcbrWAEqkN0YAYn1mSPuhQ78wOEgF_aVMDiWTj6HnjY,6602
7
+ transcript/builders/js.py,sha256=FYbUI-ZwWt676gjsmniotSeqJUZq6Q7fEbp8SAl0M7U,8307
8
+ transcript/builders/scss.py,sha256=6F6MGsQv-xT0kMXTbg0oX6qLzc9a5FgsRGP8heL0xXk,13132
9
+ transcript/builders/xml.py,sha256=7Rukf5UhOYiLsag8gN0jse88P_2HPuaZPUFpRrsXYmg,5258
10
+ transcript/builders/html/__init__.py,sha256=RUhs-ibfKZHXlDW5nUiKmRMV-vNA6uBoxWz1J3Cja8A,241
11
+ transcript/builders/html/__init__.pyi,sha256=z37ej2dmBN978UdNrnSZRB8RcxX6ToXl-ZxbYH8BIhk,9342
12
+ transcript/builders/html/args.py,sha256=LIIe4gDLuVTwKgH19CicMqRnCgzpouG4djuZ7kRFgA8,701
13
+ transcript/builders/html/attrs.py,sha256=PORl12qILVJhIlF-E8fJAu76TF0DdFmwENJh1gwv26A,6348
14
+ transcript/builders/html/html.py,sha256=-nvlOaLCz-iEbx_ga6TJc2j3Bswp6OoLcZLaEwP6LCQ,2710
15
+ transcript/core/__init__.py,sha256=3pywwbqHRLXsuOe_iViXLJTtZ4fIomTBFHrfmW201m0,448
16
+ transcript/core/ai.py,sha256=BN2kPMPTqlIz_siNfltHjlAMe2H9rAeB1z9mMk4nSVg,4303
17
+ transcript/core/config.py,sha256=lFvI8Y556tAStx65BsKWWQHX-qRRWjjC__UtHewtIPo,791
18
+ transcript/core/container.py,sha256=A3z4-EQ59ZQsffBINnaHZCN9R8N0lADbQjIc7oJv8lQ,3810
19
+ transcript/core/factory.py,sha256=UTfahIFrMBp6VW1J7HPWP8dHhvI60-YzNQv9aVL0ohw,8843
20
+ transcript/core/fingerprint.py,sha256=Mx0yZ1szAgpCipSKHd8yoSDXbbibQKOANPcA4ZLWzpw,9531
21
+ transcript/core/meta.py,sha256=anTVl3T2pQ6kMUZw4COBtLnPlXZJMDAE0lCBEGvta2U,1444
22
+ transcript/core/registers.py,sha256=7AGtcrL7o560Str0W9pC_Rt_uf-w2VNBKQbFPQ3RRqA,1691
23
+ transcript/core/stubs.py,sha256=huw_U3w32VhIJnXc0hweQzidxvvantpSUeILstOS4aA,455
24
+ transcript/io/__init__.py,sha256=qt9NfMzS1Z6S-NhHialpwWVeZp9XvCwO9iFe4McBYEY,444
25
+ transcript/io/file.py,sha256=LXmZNMlO3xMhXFhNi0n7PkJN2uw8Td74EB1_MC-oUNI,1290
26
+ transcript/io/hub.py,sha256=TtOGaatEnXI8x-LOGk4thbC4XP3v0NXYqGVPcyuPhfE,7292
27
+ transcript/io/json_data.py,sha256=CPUOefguNjD4j54NxQU0bKNPLttsNKzeZ3KCYmMoG1M,7307
28
+ transcript/io/load.py,sha256=rDnYHkMmxmWsh1ObKddfhc0ouFTWE5sQChs5UgpNdYo,5414
29
+ transcript/io/renderer.py,sha256=XX3FMC0IBLpvgmbi7hvsviAW9Qcx_vXXZHtQmISH8ok,1609
30
+ transcript/presets/__init__.py,sha256=5lx1-H7Lge89mvTz4PKk_NK7-_L4diHMFwNeRpCSlqE,1590
31
+ transcript/presets/forms.py,sha256=vo3b-ja5LgZuo7bjsrV5kxSWrnmRk9-IqfXD95tWdsc,3772
32
+ transcript/presets/html.py,sha256=6DK6jWuRAJV-oIUSxwNPZ7bDRKOaYjrjIB1u66lWmSo,7284
33
+ transcript/presets/jinja.py,sha256=L1dwHRq3VyscS9wpjbm61crnMd27Pq2gdZLJGpEaTt8,4267
34
+ transcript/presets/scss.py,sha256=yT217QZRuYHEYzJN5Zx7iG9wmwbsSPX0qivx-e--uCA,6565
35
+ transcript/presets/tailwind.py,sha256=NsAWUxRQLmvE2ZtUXiOa3EW-k6bjgT6YU1ms21bdZ5s,14521
36
+ transcript-0.4.0.dist-info/licenses/LICENSE,sha256=2_FV_10yiDpo_IOB272UPuxTZDctaT5QYantFzOybiQ,1091
37
+ transcript-0.4.0.dist-info/METADATA,sha256=DVgYjBZetJXl2z-J__tY70jVsUzJXn2i2DWM51HwO10,6474
38
+ transcript-0.4.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
39
+ transcript-0.4.0.dist-info/top_level.txt,sha256=ficaZcuq111eA4O9HIy4AoYKkrDF4InHpFUaWoPcJMI,11
40
+ transcript-0.4.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Marcin Kallas
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ transcript