flet-cli 1.1.0.dev4__py3-none-any.whl → 1.1.2__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.
@@ -75,15 +75,20 @@ from flet_cli.utils.log_format import annotation_path
75
75
  from flet_cli.utils.merge import merge_dict
76
76
  from flet_cli.utils.plist import is_supported_plist_value, parse_cli_plist_value
77
77
  from flet_cli.utils.project_dependencies import (
78
+ FletVersionConflictError,
78
79
  get_poetry_dependencies,
79
80
  get_project_dependencies,
81
+ pin_flet_dependencies,
82
+ read_requirements,
80
83
  read_requirements_file_text,
84
+ requirements_use_hashes,
81
85
  )
82
86
  from flet_cli.utils.pyproject_toml import load_pyproject_toml
83
87
  from flet_cli.utils.python_versions import (
84
88
  UnsupportedPythonVersionError,
85
89
  resolve_python_version,
86
90
  )
91
+ from flet_cli.utils.web_fonts import defer_web_fonts
87
92
 
88
93
  DEFAULT_TEMPLATE_URL = (
89
94
  "https://github.com/flet-dev/flet/releases/download/"
@@ -1667,6 +1672,15 @@ class BaseBuildCommand(BaseFlutterCommand):
1667
1672
  if checkout:
1668
1673
  details += f' with ref "{template_ref}"'
1669
1674
  console.log(details, style=verbose1_style, markup=False)
1675
+ if not second_pass:
1676
+ # Templates before 1.1.1 shipped a FontManifest.json that
1677
+ # replaced the one Flutter generates, so the fonts of
1678
+ # Dart packages were never loaded. Re-rendering keeps
1679
+ # files the template no longer has; a template that
1680
+ # still has one writes it back.
1681
+ (self.flutter_dir / "web" / "assets" / "FontManifest.json").unlink(
1682
+ missing_ok=True
1683
+ )
1670
1684
  try:
1671
1685
  from cookiecutter.main import cookiecutter
1672
1686
 
@@ -1763,6 +1777,20 @@ class BaseBuildCommand(BaseFlutterCommand):
1763
1777
  pubspec = merge_dict(pubspec, pyproject_pubspec)
1764
1778
  self.save_yaml(self.pubspec_path, pubspec)
1765
1779
 
1780
+ if self.config_platform == "web" and self.template_data.get("no_cdn"):
1781
+ # Declare Roboto before Flutter runs so both build and debug
1782
+ # include it in the generated manifest alongside package fonts.
1783
+ # An app's own Roboto declaration takes precedence.
1784
+ fonts = pubspec.setdefault("flutter", {}).setdefault("fonts", [])
1785
+ if not any(font.get("family") == "Roboto" for font in fonts):
1786
+ fonts.append(
1787
+ {
1788
+ "family": "Roboto",
1789
+ "fonts": [{"asset": "web/assets/fonts/roboto.woff2"}],
1790
+ }
1791
+ )
1792
+ self.save_yaml(self.pubspec_path, pubspec)
1793
+
1766
1794
  # make backup of pubspec.yaml
1767
1795
  shutil.copyfile(self.pubspec_path, f"{self.pubspec_path}.orig")
1768
1796
 
@@ -2139,6 +2167,22 @@ class BaseBuildCommand(BaseFlutterCommand):
2139
2167
  return True
2140
2168
  return False
2141
2169
 
2170
+ def _pin_flet_dependencies(self, dependencies: list[str]) -> list[str]:
2171
+ """
2172
+ Pin the app's Flet packages to the CLI's version, or stop the build.
2173
+
2174
+ Args:
2175
+ dependencies: The app's requirements.
2176
+
2177
+ Returns:
2178
+ The pinned requirements.
2179
+ """
2180
+ try:
2181
+ return pin_flet_dependencies(dependencies, flet.version.flet_version)
2182
+ except FletVersionConflictError as e:
2183
+ self.skip_flutter_doctor = True
2184
+ self.cleanup(1, escape(str(e)))
2185
+
2142
2186
  def _site_packages_missing(self) -> bool:
2143
2187
  """
2144
2188
  Whether any required platform package directory has no package files.
@@ -2477,6 +2521,7 @@ class BaseBuildCommand(BaseFlutterCommand):
2477
2521
  if dev_packages_configured:
2478
2522
  toml_dependencies.append("--no-cache-dir")
2479
2523
 
2524
+ toml_dependencies = self._pin_flet_dependencies(toml_dependencies)
2480
2525
  for toml_dep in toml_dependencies:
2481
2526
  package_args.extend(["-r", toml_dep])
2482
2527
 
@@ -2492,6 +2537,16 @@ class BaseBuildCommand(BaseFlutterCommand):
2492
2537
  )
2493
2538
  hash.update(reqs_txt_contents)
2494
2539
  package_args.extend(["-r", "-r", "-r", str(requirements_txt)])
2540
+
2541
+ # pip reads the file itself, so the pins go next to it. A file
2542
+ # with hashes is only checked: pip rejects requirements that
2543
+ # have no hash.
2544
+ file_dependencies = read_requirements(requirements_txt)
2545
+ pinned_dependencies = self._pin_flet_dependencies(file_dependencies)
2546
+ if not requirements_use_hashes(reqs_txt_contents):
2547
+ for dep in pinned_dependencies:
2548
+ if dep not in file_dependencies:
2549
+ package_args.extend(["-r", dep])
2495
2550
  else:
2496
2551
  package_args.extend(["-r", f"flet=={flet.version.flet_version}"])
2497
2552
 
@@ -4001,6 +4056,7 @@ class BaseBuildCommand(BaseFlutterCommand):
4001
4056
 
4002
4057
  if self.target_platform == "web":
4003
4058
  self.prune_cdn_assets()
4059
+ self.defer_web_fonts()
4004
4060
  if self.assets_path.exists():
4005
4061
  # copy `assets` directory contents to the output directory
4006
4062
  copy_tree(str(self.assets_path), str(self.out_dir))
@@ -4009,6 +4065,20 @@ class BaseBuildCommand(BaseFlutterCommand):
4009
4065
 
4010
4066
  console.log(f"Copied build {self.emojis['checkmark']}")
4011
4067
 
4068
+ def defer_web_fonts(self):
4069
+ """
4070
+ Load the fonts only some controls need on first use, and drop the
4071
+ unused ones (see `flet_cli.utils.web_fonts`).
4072
+ """
4073
+ deferred, unused = defer_web_fonts(self.out_dir)
4074
+ if self.verbose > 0 and (deferred or unused):
4075
+ console.log(
4076
+ f"Fonts loaded on first use: {', '.join(deferred) or 'none'}; "
4077
+ f"removed: {', '.join(unused) or 'none'}",
4078
+ style=verbose1_style,
4079
+ markup=False,
4080
+ )
4081
+
4012
4082
  def prune_cdn_assets(self):
4013
4083
  """
4014
4084
  Remove `canvaskit/` from a CDN-mode web build.
@@ -14,8 +14,12 @@ from flet.utils import (
14
14
  )
15
15
  from flet_cli.commands.base import BaseCommand
16
16
  from flet_cli.utils.project_dependencies import (
17
+ FletVersionConflictError,
17
18
  get_poetry_dependencies,
18
19
  get_project_dependencies,
20
+ override_dependencies,
21
+ pin_flet_dependencies,
22
+ read_requirements,
19
23
  )
20
24
  from flet_cli.utils.pyodide import ensure_pyodide
21
25
  from flet_cli.utils.pyproject_toml import load_pyproject_toml
@@ -214,6 +218,28 @@ class Command(BaseCommand):
214
218
  os.path.basename(script_path),
215
219
  )
216
220
 
221
+ requirements_txt = project_dir.joinpath(reqs_filename)
222
+ deps = (
223
+ get_poetry_dependencies(get_pyproject("tool.poetry.dependencies"))
224
+ or get_project_dependencies(get_pyproject("project.dependencies"))
225
+ or (
226
+ read_requirements(requirements_txt) if requirements_txt.exists() else []
227
+ )
228
+ )
229
+ # The web client installs these from the archive's pyproject.toml, which an
230
+ # app in a subdirectory doesn't have, and without the pins below an
231
+ # extension listed only here would ask for a newer `flet`.
232
+ deps = override_dependencies(
233
+ deps,
234
+ get_project_dependencies(get_pyproject("tool.flet.web.dependencies")) or [],
235
+ )
236
+ try:
237
+ deps = pin_flet_dependencies(deps, flet.version.flet_version)
238
+ except FletVersionConflictError as e:
239
+ print(e)
240
+ sys.exit(1)
241
+ print(f"App dependencies: {deps}")
242
+
217
243
  # delete "dist" directory
218
244
  if options.distpath:
219
245
  dist_dir = Path(options.distpath)
@@ -256,29 +282,6 @@ class Command(BaseCommand):
256
282
  if os.path.exists(assets_dir):
257
283
  copy_tree(assets_dir, str(dist_dir))
258
284
 
259
- deps = []
260
- requirements_txt = project_dir.joinpath(reqs_filename)
261
-
262
- toml_dependencies = get_poetry_dependencies(
263
- get_pyproject("tool.poetry.dependencies")
264
- ) or get_project_dependencies(get_pyproject("project.dependencies"))
265
-
266
- if toml_dependencies:
267
- deps = toml_dependencies
268
- print(f"pyproject.toml dependencies: {deps}")
269
- elif requirements_txt.exists():
270
- with open(requirements_txt, encoding="utf-8") as f:
271
- deps = list(
272
- filter(
273
- lambda dep: not dep.startswith("#"),
274
- [line.rstrip() for line in f],
275
- )
276
- )
277
- print(f"{reqs_filename} dependencies: {deps}")
278
-
279
- if len(deps) == 0:
280
- deps = [f"flet=={flet.version.flet_version}"]
281
-
282
285
  temp_reqs_txt = Path(tempfile.gettempdir()).joinpath(random_string(10))
283
286
  with open(temp_reqs_txt, "w", encoding="utf-8") as f:
284
287
  f.writelines(dep + "\n" for dep in deps)
@@ -1,15 +1,57 @@
1
- """Convert a pyproject.toml file to a requirements.txt file."""
1
+ """Read the Python dependencies of a Flet app and pin its Flet packages."""
2
2
 
3
3
  # Based on: https://pypi.org/project/toml-to-requirements/
4
4
 
5
+ import codecs
5
6
  import os
6
7
  import re
7
8
  import shlex
8
9
  from collections.abc import Iterator
9
10
  from pathlib import Path
10
11
  from typing import Any, Optional
12
+ from urllib.parse import urlparse
13
+ from urllib.request import url2pathname
14
+
15
+ from packaging.requirements import InvalidRequirement, Requirement
16
+ from packaging.specifiers import SpecifierSet
17
+ from packaging.utils import canonicalize_name
18
+
19
+ FLET_PACKAGES = frozenset(
20
+ {
21
+ "flet",
22
+ "flet-ads",
23
+ "flet-audio",
24
+ "flet-audio-recorder",
25
+ "flet-camera",
26
+ "flet-charts",
27
+ "flet-cli",
28
+ "flet-code-editor",
29
+ "flet-color-pickers",
30
+ "flet-datatable2",
31
+ "flet-desktop",
32
+ "flet-flashlight",
33
+ "flet-geolocator",
34
+ "flet-local-auth",
35
+ "flet-lottie",
36
+ "flet-map",
37
+ "flet-mcp",
38
+ "flet-notifications",
39
+ "flet-permission-handler",
40
+ "flet-platform-assets",
41
+ "flet-rive",
42
+ "flet-secure-storage",
43
+ "flet-shadcn-ui",
44
+ "flet-spinkit",
45
+ "flet-video",
46
+ "flet-web",
47
+ "flet-webview",
48
+ }
49
+ )
50
+ """The packages released with `flet`, at its version."""
51
+
11
52
 
12
- from packaging.requirements import Requirement
53
+ class FletVersionConflictError(ValueError):
54
+ """Raised when an app's requirements exclude the version of the Flet CLI."""
13
55
 
14
56
 
15
57
  def _windows_safe(req_str: str) -> str:
@@ -137,8 +179,116 @@ def get_project_dependencies(
137
179
  return sorted(dependencies)
138
180
 
139
181
 
140
- def _requirements_includes(text: str) -> Iterator[str]:
141
- """Yield include paths after pip-style line and option preprocessing."""
182
+ def pin_flet_dependencies(dependencies: list[str], flet_version: str) -> list[str]:
183
+ """
184
+ Pin `flet` and the packages released with it to the version of the Flet CLI.
185
+
186
+ An app runs in a Flet client of the CLI's version, so its Python packages must
187
+ have that version too. A range such as `flet>=1.0` would install the newest
188
+ release instead. The extensions are pinned as well because each one requires
189
+ its own version of `flet` exactly, and `micropip` can't step back to an older
190
+ extension the way pip does.
191
+
192
+ `flet==<flet_version>` is added when no requirement installs `flet` on every
193
+ platform, unless an entry installs a path or URL, which may provide `flet`.
194
+
195
+ Args:
196
+ dependencies: The app's requirements. Pip options are kept as they are.
197
+ flet_version: The version of the Flet CLI.
198
+
199
+ Returns:
200
+ The pinned requirements, or `dependencies` as they are when `flet` itself
201
+ comes from a path or URL, such as the one `dev_packages` sets.
202
+
203
+ Raises:
204
+ FletVersionConflictError: If a requirement without an environment marker
205
+ excludes `flet_version`.
206
+ """
207
+ requirements = [_parse_requirement(dep) for dep in dependencies]
208
+ if any(
209
+ _is_flet_location(dep)
210
+ or (req is not None and canonicalize_name(req.name) == "flet" and req.url)
211
+ for dep, req in zip(dependencies, requirements)
212
+ ):
213
+ return list(dependencies)
214
+
215
+ pinned = []
216
+ installs_flet = False
217
+ may_install_flet = False
218
+ for dep, req in zip(dependencies, requirements):
219
+ if req is None:
220
+ may_install_flet = may_install_flet or not dep.startswith("-")
221
+ elif canonicalize_name(req.name) in FLET_PACKAGES and not req.url:
222
+ if not req.specifier.contains(flet_version, prereleases=True):
223
+ if req.marker is not None:
224
+ # It may not apply to the target, so pip decides.
225
+ pinned.append(dep)
226
+ continue
227
+ raise FletVersionConflictError(
228
+ f"The app requires `{req}`, but this Flet CLI is version "
229
+ f"{flet_version}, and the app runs in a Flet client of that "
230
+ "version. Change the requirement, or use a Flet CLI version "
231
+ "that it allows."
232
+ )
233
+ req.specifier = SpecifierSet(f"=={flet_version}")
234
+ dep = _windows_safe(str(req))
235
+ installs_flet = installs_flet or (
236
+ canonicalize_name(req.name) == "flet" and req.marker is None
237
+ )
238
+ pinned.append(dep)
239
+ if not installs_flet and not may_install_flet:
240
+ pinned.append(f"flet=={flet_version}")
241
+ return pinned
242
+
243
+
244
+ def override_dependencies(dependencies: list[str], overrides: list[str]) -> list[str]:
245
+ """
246
+ Append `overrides` to `dependencies`, replacing requirements of the same packages.
247
+
248
+ Args:
249
+ dependencies: The requirements to override.
250
+ overrides: The requirements that take precedence.
251
+
252
+ Returns:
253
+ The combined requirements.
254
+ """
255
+ names = {
256
+ canonicalize_name(req.name)
257
+ for req in map(_parse_requirement, overrides)
258
+ if req is not None
259
+ }
260
+ kept = [
261
+ dep
262
+ for dep in dependencies
263
+ if (req := _parse_requirement(dep)) is None
264
+ or canonicalize_name(req.name) not in names
265
+ ]
266
+ return kept + overrides
267
+
268
+
269
+ def _parse_requirement(dep: str) -> Optional[Requirement]:
270
+ """Parse a PEP 508 requirement, or return `None` for any other entry."""
271
+ try:
272
+ return Requirement(dep)
273
+ except InvalidRequirement:
274
+ return None
275
+
276
+
277
+ def _is_flet_location(entry: str) -> bool:
278
+ """Whether a path or URL names `flet`: a checkout, wheel, sdist or `#egg=flet`."""
279
+ return bool(
280
+ re.search(
281
+ r"[#&]egg=flet(&|$)"
282
+ r"|[/\\]flet[/\\]?(\[[^\]]*\])?\s*([#?&;]|$)"
283
+ r"|(^|[/\\])flet-\d[^/\\]*\.(whl|tar\.gz|zip)(\[[^\]]*\])?\s*([#?;]|$)",
284
+ entry,
285
+ re.IGNORECASE,
286
+ )
287
+ )
288
+
289
+
290
+ def _requirements_lines(text: str) -> Iterator[str]:
291
+ """Yield the lines of a requirements file, preprocessed the way pip does."""
142
292
  pending = ""
143
293
  for line in [*text.splitlines(), ""]:
144
294
  # Join before stripping comments, as pip does. Comment lines themselves
@@ -148,39 +298,86 @@ def _requirements_includes(text: str) -> Iterator[str]:
148
298
  continue
149
299
  line, pending = pending + line, ""
150
300
  line = re.sub(r"(^|\s+)#.*$", "", line).strip()
151
- if not line.startswith("-"):
301
+ if line:
302
+ yield re.sub(
303
+ r"\$\{([A-Z0-9_]+)\}",
304
+ lambda match: os.environ.get(match[1]) or match[0],
305
+ line,
306
+ )
307
+
308
+
309
+ def _requirements_options(line: str) -> Iterator[tuple[str, str]]:
310
+ """Yield the `-r`, `-c` and `-e` options of a line, as (letter, value) pairs."""
311
+ try:
312
+ options = iter(shlex.split(line))
313
+ except ValueError:
314
+ # Leave malformed options for pip to report during installation.
315
+ return
316
+ for option in options:
317
+ if option in ("-r", "--requirement", "-c", "--constraint", "-e", "--editable"):
318
+ letter, value = option.lstrip("-")[0], next(options, "")
319
+ elif option.startswith(("--requirement=", "--constraint=", "--editable=")):
320
+ letter, value = option[2], option.partition("=")[2]
321
+ elif option.startswith(("-r", "-c", "-e")):
322
+ letter, value = option[1], option[2:]
323
+ else:
152
324
  continue
153
- line = re.sub(
154
- r"\$\{([A-Z0-9_]+)\}",
155
- lambda match: os.environ.get(match[1]) or match[0],
156
- line,
325
+ if value:
326
+ yield letter, value
327
+
328
+
329
+ def _is_remote_url(value: str) -> bool:
330
+ """Whether a value from a requirements file is a URL other than `file:`."""
331
+ return re.match(
332
+ r"^[a-z][a-z0-9+.-]*://", value, re.IGNORECASE
333
+ ) is not None and not value.lower().startswith("file:")
334
+
335
+
336
+ def _requirements_files(path: Path) -> Iterator[tuple[str, bool]]:
337
+ """
338
+ Yield the text of a requirements file and of the files it includes.
339
+
340
+ Includes are relative to the file that includes them. `file:` URLs are read;
341
+ other URLs and missing files are skipped.
342
+
343
+ Args:
344
+ path: The path of the requirements file.
345
+
346
+ Yields:
347
+ The text of a file, and whether it was included as a constraints file.
348
+ """
349
+ visited: set[tuple[Path, bool]] = set()
350
+
351
+ def read(file: Path, constraint: bool) -> Iterator[tuple[str, bool]]:
352
+ key = (file.resolve(), constraint)
353
+ if key in visited or not file.is_file():
354
+ return
355
+ visited.add(key)
356
+ data = file.read_bytes()
357
+ encoding = (
358
+ "utf-16"
359
+ if data.startswith((codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE))
360
+ else "utf-8-sig"
157
361
  )
158
- try:
159
- options = iter(shlex.split(line))
160
- except ValueError:
161
- # Leave malformed options for pip to report during installation.
162
- continue
163
- for option in options:
164
- if option in ("-r", "--requirement", "-c", "--constraint"):
165
- include = next(options, "")
166
- elif option.startswith(("--requirement=", "--constraint=")):
167
- include = option.partition("=")[2]
168
- elif option.startswith(("-r", "-c")):
169
- include = option[2:]
170
- else:
362
+ text = data.decode(encoding, errors="replace").replace("\r\n", "\n")
363
+ yield text, constraint
364
+ for line in _requirements_lines(text):
365
+ if not line.startswith("-"):
171
366
  continue
172
- if include:
173
- yield include
367
+ for letter, value in _requirements_options(line):
368
+ if value.lower().startswith("file:"):
369
+ value = url2pathname(urlparse(value).path)
370
+ if letter != "e" and not _is_remote_url(value):
371
+ yield from read(file.parent / value, letter == "c")
372
+
373
+ yield from read(Path(path), False)
174
374
 
175
375
 
176
376
  def read_requirements_file_text(path: Path) -> str:
177
377
  """
178
378
  Return the text of a `requirements.txt` file and of the files it includes.
179
379
 
180
- Files included with `-r`/`--requirement` or `-c`/`--constraint` are read
181
- too, relative to the file that includes them, so a change to any of them
182
- changes the result. Includes support quoted paths, line continuations and
183
- pip's `${NAME}` environment variables. URLs and missing files are skipped.
380
+ A change to any of the files changes the result.
184
381
 
185
382
  Args:
186
383
  path: The path of the `requirements.txt` file.
@@ -188,21 +385,47 @@ def read_requirements_file_text(path: Path) -> str:
188
385
  Returns:
189
386
  The concatenated text of the file and of the files it includes.
190
387
  """
388
+ return "".join(text for text, _ in _requirements_files(path))
191
389
 
192
- parts: list[str] = []
193
- visited: set[Path] = set()
194
390
 
195
- def read(file: Path) -> None:
196
- resolved = file.resolve()
197
- if resolved in visited or not file.is_file():
198
- return
199
- visited.add(resolved)
200
- text = file.read_text(encoding="utf-8", errors="replace")
201
- parts.append(text)
202
- for include in _requirements_includes(text):
203
- if re.match(r"^[a-z][a-z0-9+.-]*://", include, re.I):
204
- continue
205
- read(file.parent / include)
391
+ def read_requirements(path: Path) -> list[str]:
392
+ """
393
+ Return the requirements of a `requirements.txt` file and of its `-r` includes.
206
394
 
207
- read(Path(path))
208
- return "".join(parts)
395
+ Args:
396
+ path: The path of the `requirements.txt` file.
397
+
398
+ Returns:
399
+ The requirements without their options, the targets of `-e` options, and
400
+ the URLs of `-r` includes, whose requirements can't be read here.
401
+ """
402
+ requirements = []
403
+ for text, constraint in _requirements_files(path):
404
+ if constraint:
405
+ continue
406
+ for line in _requirements_lines(text):
407
+ if line.startswith("-"):
408
+ requirements.extend(
409
+ value
410
+ for letter, value in _requirements_options(line)
411
+ if letter == "e" or (letter == "r" and _is_remote_url(value))
412
+ )
413
+ else:
414
+ requirements.append(re.split(r"\s+-", line, maxsplit=1)[0])
415
+ return requirements
416
+
417
+
418
+ def requirements_use_hashes(text: str) -> bool:
419
+ """
420
+ Whether the text of a requirements file uses hash-checking mode.
421
+
422
+ Args:
423
+ text: The text, as `read_requirements_file_text` returns it.
424
+
425
+ Returns:
426
+ `True` when a line has a `--hash` or `--require-hashes` option.
427
+ """
428
+ return any(
429
+ re.search(r"(^|\s)--(hash|require-hashes)\b", line)
430
+ for line in _requirements_lines(text)
431
+ )
flet_cli/utils/pyodide.py CHANGED
@@ -5,6 +5,10 @@ python_stdlib.zip / pyodide-lock.json / ...) but not the micropip+packaging
5
5
  wheels that `loadPackage("micropip")` needs at runtime. We supplement the core
6
6
  tarball with those two wheels (filenames resolved from pyodide-lock.json) so
7
7
  the bundle works in `--no-cdn` deployments too.
8
+
9
+ Its `python_stdlib.zip` is replaced with the precompiled one Pyodide publishes
10
+ on its CDN (`pyc/python_stdlib.zip`): `.pyc` files instead of sources, so
11
+ Python doesn't compile the modules it imports when the app starts.
8
12
  """
9
13
 
10
14
  from __future__ import annotations
@@ -12,6 +16,7 @@ from __future__ import annotations
12
16
  import json
13
17
  import shutil
14
18
  import tarfile
19
+ import zipfile
15
20
  from collections.abc import Iterable
16
21
  from pathlib import Path
17
22
 
@@ -22,6 +27,10 @@ from flet_cli.utils.template_cache import get_cache_root
22
27
 
23
28
  _GITHUB_TARBALL_URL = "https://github.com/pyodide/pyodide/releases/download/{version}/pyodide-core-{version}.tar.bz2"
24
29
  _CDN_FILE_URL = "https://cdn.jsdelivr.net/pyodide/v{version}/full/{filename}"
30
+ _CDN_PYC_STDLIB_URL = (
31
+ "https://cdn.jsdelivr.net/pyodide/v{version}/pyc/python_stdlib.zip"
32
+ )
33
+ _STDLIB = "python_stdlib.zip"
25
34
 
26
35
  # Wheels that pyodide loads from disk/CDN at runtime via loadPackage().
27
36
  # Without them in dest_dir, `--no-cdn` builds break.
@@ -89,6 +98,12 @@ def _populate_cache(version: str, cache_dir: Path) -> None:
89
98
  if not lock_json.exists():
90
99
  raise RuntimeError(f"pyodide-core-{version} did not contain pyodide-lock.json")
91
100
  with Progress(transient=True) as progress:
101
+ _download(
102
+ _CDN_PYC_STDLIB_URL.format(version=version),
103
+ cache_dir / _STDLIB,
104
+ progress,
105
+ "Downloading precompiled Python standard library...",
106
+ )
92
107
  for wheel in _resolve_runtime_wheel_filenames(
93
108
  lock_json, _EXTRA_RUNTIME_PACKAGES
94
109
  ):
@@ -103,23 +118,54 @@ def _populate_cache(version: str, cache_dir: Path) -> None:
103
118
  )
104
119
 
105
120
 
121
+ def _stdlib_is_compiled(cache_dir: Path) -> bool:
122
+ """Whether `python_stdlib.zip` holds `.pyc` files and no sources."""
123
+ try:
124
+ with zipfile.ZipFile(cache_dir / _STDLIB) as zf:
125
+ names = zf.namelist()
126
+ except (OSError, zipfile.BadZipFile):
127
+ return False
128
+ return any(n.endswith(".pyc") for n in names) and not any(
129
+ n.endswith(".py") for n in names
130
+ )
131
+
132
+
106
133
  def _cache_matches_version(cache_dir: Path, version: str) -> bool:
107
- lock_json = cache_dir / "pyodide-lock.json"
108
- if not lock_json.exists():
134
+ if not _stdlib_is_compiled(cache_dir):
135
+ # Missing, or the source standard library of a cache made before the
136
+ # precompiled one.
109
137
  return False
110
- try:
111
- with lock_json.open("r", encoding="utf-8") as f:
112
- lock = json.load(f)
113
- except (OSError, json.JSONDecodeError):
138
+ if not (cache_dir / "pyodide-lock.json").exists():
114
139
  return False
115
- return lock.get("info", {}).get("version") == version
140
+ return _runtime_version(cache_dir) == version
141
+
142
+
143
+ def _runtime_version(cache_dir: Path) -> str | None:
144
+ """The Pyodide version of a runtime: `package.json`'s `version`, which every
145
+ release has, else `pyodide-lock.json`'s `info.version`, which only 0.27 and
146
+ earlier write."""
147
+ for name, keys in (
148
+ ("package.json", ("version",)),
149
+ ("pyodide-lock.json", ("info", "version")),
150
+ ):
151
+ try:
152
+ with (cache_dir / name).open("r", encoding="utf-8") as f:
153
+ value = json.load(f)
154
+ except (OSError, json.JSONDecodeError):
155
+ continue
156
+ for key in keys:
157
+ value = value.get(key) if isinstance(value, dict) else None
158
+ if isinstance(value, str):
159
+ return value
160
+ return None
116
161
 
117
162
 
118
163
  def ensure_pyodide(version: str, dest_dir: Path) -> None:
119
164
  """Ensure a working Pyodide runtime of `version` exists at `dest_dir`.
120
165
 
121
166
  Cached per version under `~/.flet/cache/pyodide/<version>/`. Idempotent: if
122
- `dest_dir/pyodide-lock.json` already pins `version`, no work is done.
167
+ `dest_dir` already has that version with the precompiled standard library, no
168
+ work is done.
123
169
  """
124
170
 
125
171
  dest_dir = Path(dest_dir)
@@ -0,0 +1,64 @@
1
+ """Fonts of a `flet build web` app that are loaded on first use, or not at all.
2
+
3
+ Flutter web downloads every font in `assets/FontManifest.json` before the
4
+ app's first frame. Some Dart packages bring fonts only a few controls need:
5
+ their families move to `assets/DeferredFontManifest.json` (the same format),
6
+ and the flet package loads them the first time such a control is built
7
+ (`packages/flet/lib/src/utils/deferred_fonts.dart`). Families no Flet control
8
+ uses are left out of the build.
9
+
10
+ Run by `flet build web`, and by CI on Flet's built-in web client (flet-web,
11
+ served by `flet run --web` and copied by `flet publish`).
12
+ """
13
+
14
+ import json
15
+ import re
16
+ from pathlib import Path
17
+
18
+ DEFERRED_FONT_MANIFEST = "DeferredFontManifest.json"
19
+
20
+ # Dart packages whose fonts are loaded on first use:
21
+ # - flutter_math_fork: KaTeX, for math in `Markdown`;
22
+ # - lucide_icons_flutter: Lucide, for flet-shadcn-ui's icons;
23
+ # - shadcn_ui: Geist and Geist Mono, for flet-shadcn-ui's text.
24
+ DEFERRED_FONT_PACKAGES = ("flutter_math_fork", "lucide_icons_flutter", "shadcn_ui")
25
+
26
+ # lucide_icons_flutter's weight variants (2.9 MB): flet-shadcn-ui maps every
27
+ # icon to the regular `Lucide` family.
28
+ UNUSED_FONT_FAMILIES = re.compile(r"packages/lucide_icons_flutter/Lucide\d00")
29
+
30
+
31
+ def defer_web_fonts(web_dir: Path) -> tuple[list[str], list[str]]:
32
+ """
33
+ Split the fonts of the web build in `web_dir`: deferred families go to
34
+ `DeferredFontManifest.json`, unused ones are removed with their files.
35
+
36
+ Returns the deferred and the removed family names. A build without
37
+ `FontManifest.json` is left alone.
38
+ """
39
+
40
+ assets = web_dir / "assets"
41
+ manifest_path = assets / "FontManifest.json"
42
+ if not manifest_path.exists():
43
+ return [], []
44
+
45
+ families = json.loads(manifest_path.read_text(encoding="utf-8"))
46
+ kept, deferred, unused = [], [], []
47
+ for family in families:
48
+ name = family.get("family", "")
49
+ if UNUSED_FONT_FAMILIES.fullmatch(name):
50
+ unused.append(family)
51
+ elif any(name.startswith(f"packages/{p}/") for p in DEFERRED_FONT_PACKAGES):
52
+ deferred.append(family)
53
+ else:
54
+ kept.append(family)
55
+
56
+ manifest_path.write_text(json.dumps(kept), encoding="utf-8")
57
+ (assets / DEFERRED_FONT_MANIFEST).write_text(json.dumps(deferred), encoding="utf-8")
58
+ for family in unused:
59
+ for font in family.get("fonts", []):
60
+ # The manifest's paths are URL-encoded, as Flutter writes them,
61
+ # and so are the file names: `Geist%5Bwght%5D.ttf`.
62
+ (assets / font["asset"]).unlink(missing_ok=True)
63
+
64
+ return [f["family"] for f in deferred], [f["family"] for f in unused]
flet_cli/version.py CHANGED
@@ -1 +1 @@
1
- version = "1.1.0.dev4"
1
+ version = "1.1.2"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: flet-cli
3
- Version: 1.1.0.dev4
3
+ Version: 1.1.2
4
4
  Summary: Flet CLI
5
5
  Author-email: "Appveyor Systems Inc." <hello@flet.dev>
6
6
  License-Expression: Apache-2.0
@@ -9,8 +9,8 @@ Project-URL: Repository, https://github.com/flet-dev/flet
9
9
  Project-URL: Documentation, https://flet.dev/docs
10
10
  Requires-Python: >=3.10
11
11
  Description-Content-Type: text/markdown
12
- Requires-Dist: flet==1.1.0.dev4
13
- Requires-Dist: flet-platform-assets==1.1.0.dev4
12
+ Requires-Dist: flet==1.1.2
13
+ Requires-Dist: flet-platform-assets==1.1.2
14
14
  Requires-Dist: watchdog>=4.0.0
15
15
  Requires-Dist: packaging>=25.0
16
16
  Requires-Dist: qrcode>=7.4.2
@@ -1,5 +1,5 @@
1
1
  flet_cli/cli.py,sha256=TlUPz73bL6rcSQBBH05uAljU9f-ZsuefEKYR-SbdPbE,10115
2
- flet_cli/version.py,sha256=2riRADLE95mZv4R1KF4qPUxM4gH-U0yJYnOaDzNsHs4,23
2
+ flet_cli/version.py,sha256=B6D8nq7L-h3Yrso4-Yz8z9mMwHb_44HH7PbB6duHGH0,18
3
3
  flet_cli/__pyinstaller/__init__.py,sha256=1MZKXQG20CRYCGCPzbbO3o-rUJMKm0q_ck9_jDSuTgU,177
4
4
  flet_cli/__pyinstaller/config.py,sha256=LRzpGt1QzSBWtE3zPWo2nA2Hf3ppMHv0LQnpi-dwGDk,245
5
5
  flet_cli/__pyinstaller/hook-flet.py,sha256=RbiFE8-7VBsY4Dwt7a9-9gW0gUFQGjOLY1-OBsZm_mI,506
@@ -11,7 +11,7 @@ flet_cli/__pyinstaller/win_utils.py,sha256=yZixKh6Pq1ou8oNmhE_j7kuSSjN-BaQSvAhFh
11
11
  flet_cli/__pyinstaller/rthooks/pyi_rth_localhost_fletd.py,sha256=O8lAxkHmNaXaZNzP-3VTuUhuglYwgJtzaeIKQa2neGU,2379
12
12
  flet_cli/commands/base.py,sha256=6MTAuA7kKdaKIZI4AyWPM1TJfFCxmRj7kc7z2h6E_4k,3496
13
13
  flet_cli/commands/build.py,sha256=FCt95Smfyvch8xuvUmgNT7frI_3KKIbnN_YZ_iJs-sk,36725
14
- flet_cli/commands/build_base.py,sha256=grdxa1za8LzobTO7kd6AJSwsZ79KDgp216lihC-FfYM,177179
14
+ flet_cli/commands/build_base.py,sha256=DTLGtQcL1G7P4iwdJEISBy7_fiwaqATck2cCHO-w7xo,180473
15
15
  flet_cli/commands/clean.py,sha256=fIRr1ktoE9wzO0R-lAq985zbCH1dX6Sao5VyXiJxiOY,2250
16
16
  flet_cli/commands/create.py,sha256=i0-DEGlE4mOpP1lGxfuv7Iea131ukdNP5SQupcS8Eug,11317
17
17
  flet_cli/commands/debug.py,sha256=pZH4Lsn9nLET4Zet9XwJweCA8rQyt2fIF-srH5XO7JM,6699
@@ -22,7 +22,7 @@ flet_cli/commands/flutter_base.py,sha256=18H3ofgsnSeCfaZZwPemYLNEtPLr_v46QlP_bVP
22
22
  flet_cli/commands/mcp.py,sha256=AVEnf6YjICqoBQPKqBaHp27KHXxFVjH-IRpAi6dSjcM,2065
23
23
  flet_cli/commands/options.py,sha256=CD7Fw2CtUeuVrtM_oR1_OrAcMKF2EhRUoPuX9_3IsW8,2543
24
24
  flet_cli/commands/pack.py,sha256=nM06iFNwG4nAGXzOM8w0NCfvpNIg7TQdVxQv537Gbko,30377
25
- flet_cli/commands/publish.py,sha256=Ra92AZ3NbBMFAnbJxBafaXvmF-3T2tXGO5V6MiHDYp8,14581
25
+ flet_cli/commands/publish.py,sha256=YHKWND97ONVUu_ZGzU-8bwc9Rl4Cto9tAkgUfJj4vb0,14801
26
26
  flet_cli/commands/run.py,sha256=W96y_bUCOh2TK2w9tfWzbYU5ahS_CBE-vzLVkoNTU4M,29663
27
27
  flet_cli/commands/serve.py,sha256=YrollC80u9JvuXHbI_qQ3wxpjcqpIQwFxdD5nIOeOT4,3143
28
28
  flet_cli/commands/test.py,sha256=lY4EqTyxG7jaE0lt0nCepimHBiPB0OnSY8zIUQxluQA,12875
@@ -44,13 +44,14 @@ flet_cli/utils/macos_sign.py,sha256=lkqHEZieroD5Nj90Cnz_dwMgaT3FJFvxaC8NV2bcP9c,
44
44
  flet_cli/utils/merge.py,sha256=cZcUL1z2iaGjjFifL1KCrEj2ywLR9x6eNtOj1F2Dr6U,780
45
45
  flet_cli/utils/plist.py,sha256=oqBCkeUjUqPIf5y7XaE2seSx64FEs7yc2cukvbjFoSU,1135
46
46
  flet_cli/utils/processes.py,sha256=MIX05itdoYyyE1L2N9NeTciJXk4yzjVMceONhUljwsA,3452
47
- flet_cli/utils/project_dependencies.py,sha256=1eC8ebI_HoEx27peFvfV531l01vbTN0P0wTZm3LjOe4,6711
48
- flet_cli/utils/pyodide.py,sha256=RhumXYuovPxgLbu99pNNhVb9SRvBvhLGiUMtb9WxC5U,5058
47
+ flet_cli/utils/project_dependencies.py,sha256=hIuFC9WX-ypaHwp1dTW6A12LYuVmi2ofpApBYW5ip8c,14386
48
+ flet_cli/utils/pyodide.py,sha256=rfb5vpF22dF6dwf7d0Ggr5d5zXReDgsT0F5DViU-jXE,6749
49
49
  flet_cli/utils/pyproject_toml.py,sha256=o4fAWKXMyK8vdnAO41BLI7Lt3ohMlVdlwrpaifq30Cs,1408
50
50
  flet_cli/utils/python_versions.py,sha256=eYfblWYTD2_PiiAK43euVVg1NaaxsIh_6H8J7CcnbcM,8129
51
51
  flet_cli/utils/template_cache.py,sha256=Lf_iuk30zTfaNFbRmrc8s07w1yE-PYjdovZztoiuPzc,1596
52
- flet_cli-1.1.0.dev4.dist-info/METADATA,sha256=5y8Qcgd3MeBDaYaulrn606g9a80EjIyLeLjspK3ePoQ,1588
53
- flet_cli-1.1.0.dev4.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
54
- flet_cli-1.1.0.dev4.dist-info/entry_points.txt,sha256=UZFR426y3mfr0wgikEFPbZ6wtGwfgykif9Obw6R7Wnc,65
55
- flet_cli-1.1.0.dev4.dist-info/top_level.txt,sha256=4_BPVAJpcNofDe3XMxajlZLBNWzWqKhRynNSBCYTKVQ,9
56
- flet_cli-1.1.0.dev4.dist-info/RECORD,,
52
+ flet_cli/utils/web_fonts.py,sha256=u4EhO2nqtJOfg-SJ9FCTKxg-g9lJXtHCpw0rwC7fjDo,2659
53
+ flet_cli-1.1.2.dist-info/METADATA,sha256=w-BK4b1JpfD2WW9IN7nil8Xb3FQ9rKCslNdzqlaNtRc,1573
54
+ flet_cli-1.1.2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
55
+ flet_cli-1.1.2.dist-info/entry_points.txt,sha256=UZFR426y3mfr0wgikEFPbZ6wtGwfgykif9Obw6R7Wnc,65
56
+ flet_cli-1.1.2.dist-info/top_level.txt,sha256=4_BPVAJpcNofDe3XMxajlZLBNWzWqKhRynNSBCYTKVQ,9
57
+ flet_cli-1.1.2.dist-info/RECORD,,