api-everything 0.5.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.
Files changed (281) hide show
  1. api_everything/__init__.py +3 -0
  2. api_everything/__main__.py +8 -0
  3. api_everything/check.py +168 -0
  4. api_everything/chrome_cmd.py +131 -0
  5. api_everything/cli.py +803 -0
  6. api_everything/config.py +321 -0
  7. api_everything/delivery.py +518 -0
  8. api_everything/delivery_git.py +94 -0
  9. api_everything/driver/__init__.py +37 -0
  10. api_everything/driver/attach.py +95 -0
  11. api_everything/driver/base.py +80 -0
  12. api_everything/driver/chrome.py +127 -0
  13. api_everything/driver/profile.py +84 -0
  14. api_everything/engine.py +381 -0
  15. api_everything/errors.py +23 -0
  16. api_everything/hooks.py +52 -0
  17. api_everything/login.py +95 -0
  18. api_everything/mcp_bridge.py +249 -0
  19. api_everything/metrics.py +87 -0
  20. api_everything/mock_site/__init__.py +5 -0
  21. api_everything/mock_site/__main__.py +18 -0
  22. api_everything/mock_site/app.py +262 -0
  23. api_everything/pipeline.py +934 -0
  24. api_everything/pool.py +553 -0
  25. api_everything/ratelimit.py +67 -0
  26. api_everything/recipe/__init__.py +6 -0
  27. api_everything/recipe/actions.py +56 -0
  28. api_everything/recipe/jsonpath.py +22 -0
  29. api_everything/recipe/loader.py +142 -0
  30. api_everything/recipe/params.py +120 -0
  31. api_everything/recipe/schema.py +235 -0
  32. api_everything/recipes/alignmentforum/feed.yaml +15 -0
  33. api_everything/recipes/alpine_docs/search.yaml +32 -0
  34. api_everything/recipes/angular_docs/search.yaml +32 -0
  35. api_everything/recipes/anthropic_status/summary.yaml +17 -0
  36. api_everything/recipes/apis_guru/providers.yaml +15 -0
  37. api_everything/recipes/arbeitnow/jobs.yaml +20 -0
  38. api_everything/recipes/arin_rdap/ip.yaml +24 -0
  39. api_everything/recipes/artifacthub/browse.yaml +22 -0
  40. api_everything/recipes/artifacthub/search.yaml +24 -0
  41. api_everything/recipes/astro_docs/search.yaml +32 -0
  42. api_everything/recipes/atlassian_status/summary.yaml +17 -0
  43. api_everything/recipes/babel_docs/search.yaml +32 -0
  44. api_everything/recipes/binance/price.yaml +24 -0
  45. api_everything/recipes/bugzilla/bugs.yaml +24 -0
  46. api_everything/recipes/bundlephobia/size.yaml +24 -0
  47. api_everything/recipes/caddy_docs/search.yaml +32 -0
  48. api_everything/recipes/caniuse/search.yaml +24 -0
  49. api_everything/recipes/capacitor_docs/search.yaml +32 -0
  50. api_everything/recipes/cdnjs/library.yaml +22 -0
  51. api_everything/recipes/cdnjs/search.yaml +27 -0
  52. api_everything/recipes/certspotter/issuances.yaml +27 -0
  53. api_everything/recipes/cheerio_docs/search.yaml +32 -0
  54. api_everything/recipes/circleci_status/summary.yaml +17 -0
  55. api_everything/recipes/cisa_kev/catalog.yaml +17 -0
  56. api_everything/recipes/civitai/models.yaml +26 -0
  57. api_everything/recipes/cloudflare_status/summary.yaml +17 -0
  58. api_everything/recipes/cncf_landscape/projects.yaml +20 -0
  59. api_everything/recipes/cncf_landscape/ui.yaml +18 -0
  60. api_everything/recipes/coinbase/rates.yaml +24 -0
  61. api_everything/recipes/coingecko/trending.yaml +17 -0
  62. api_everything/recipes/conda_forge/package.yaml +25 -0
  63. api_everything/recipes/crates/categories.yaml +15 -0
  64. api_everything/recipes/crates/downloads.yaml +22 -0
  65. api_everything/recipes/crates/keywords.yaml +15 -0
  66. api_everything/recipes/crates/reverse_deps.yaml +22 -0
  67. api_everything/recipes/crates/search.yaml +24 -0
  68. api_everything/recipes/crates/summary.yaml +15 -0
  69. api_everything/recipes/crates/user.yaml +22 -0
  70. api_everything/recipes/crates/versions.yaml +22 -0
  71. api_everything/recipes/crossref/works.yaml +24 -0
  72. api_everything/recipes/cve_org/record.yaml +24 -0
  73. api_everything/recipes/debian_sources/search.yaml +24 -0
  74. api_everything/recipes/deps_dev/npm_spa.yaml +22 -0
  75. api_everything/recipes/deps_dev/package.yaml +23 -0
  76. api_everything/recipes/devdocs/index.yaml +18 -0
  77. api_everything/recipes/devto/articles.yaml +26 -0
  78. api_everything/recipes/devto/latest.yaml +18 -0
  79. api_everything/recipes/devto/tags.yaml +18 -0
  80. api_everything/recipes/devto/top.yaml +18 -0
  81. api_everything/recipes/digitalocean_status/summary.yaml +17 -0
  82. api_everything/recipes/digitalocean_status/ui.yaml +15 -0
  83. api_everything/recipes/discord_status/summary.yaml +17 -0
  84. api_everything/recipes/dns_google/resolve.yaml +24 -0
  85. api_everything/recipes/drizzle_docs/search.yaml +32 -0
  86. api_everything/recipes/echojs/latest.yaml +17 -0
  87. api_everything/recipes/ecosystems/package.yaml +25 -0
  88. api_everything/recipes/endoflife/product.yaml +24 -0
  89. api_everything/recipes/epss/score.yaml +24 -0
  90. api_everything/recipes/exchangerate/latest.yaml +24 -0
  91. api_everything/recipes/firefox_addons/search.yaml +26 -0
  92. api_everything/recipes/fly_status/summary.yaml +17 -0
  93. api_everything/recipes/formik_docs/search.yaml +32 -0
  94. api_everything/recipes/frankfurter/rates.yaml +24 -0
  95. api_everything/recipes/gcp_status/incidents.yaml +20 -0
  96. api_everything/recipes/github/explore.yaml +35 -0
  97. api_everything/recipes/github/gists.yaml +18 -0
  98. api_everything/recipes/github/issues.yaml +30 -0
  99. api_everything/recipes/github/license.yaml +23 -0
  100. api_everything/recipes/github/org.yaml +22 -0
  101. api_everything/recipes/github/releases.yaml +30 -0
  102. api_everything/recipes/github/repo.yaml +28 -0
  103. api_everything/recipes/github/user.yaml +22 -0
  104. api_everything/recipes/github_advisories/list.yaml +20 -0
  105. api_everything/recipes/github_status/summary.yaml +17 -0
  106. api_everything/recipes/github_status/ui.yaml +15 -0
  107. api_everything/recipes/gitlab/issues.yaml +24 -0
  108. api_everything/recipes/gitlab/repo.yaml +21 -0
  109. api_everything/recipes/gitlab/search.yaml +26 -0
  110. api_everything/recipes/go_proxy/latest.yaml +24 -0
  111. api_everything/recipes/grafana_status/summary.yaml +17 -0
  112. api_everything/recipes/hackage/versions.yaml +24 -0
  113. api_everything/recipes/hackernews/ask.yaml +18 -0
  114. api_everything/recipes/hackernews/front_page.yaml +18 -0
  115. api_everything/recipes/hackernews/item.yaml +21 -0
  116. api_everything/recipes/hackernews/jobs.yaml +18 -0
  117. api_everything/recipes/hackernews/latest.yaml +25 -0
  118. api_everything/recipes/hackernews/search.yaml +34 -0
  119. api_everything/recipes/hackernews/show.yaml +18 -0
  120. api_everything/recipes/hashicorp_releases/list.yaml +27 -0
  121. api_everything/recipes/hashicorp_status/summary.yaml +17 -0
  122. api_everything/recipes/helm_docs/search.yaml +32 -0
  123. api_everything/recipes/heroku_status/current.yaml +17 -0
  124. api_everything/recipes/hexpm/search.yaml +27 -0
  125. api_everything/recipes/hf_papers/daily.yaml +20 -0
  126. api_everything/recipes/himalayas/jobs.yaml +17 -0
  127. api_everything/recipes/homebrew/cask.yaml +22 -0
  128. api_everything/recipes/homebrew/formula.yaml +26 -0
  129. api_everything/recipes/hono_docs/search.yaml +32 -0
  130. api_everything/recipes/httpbin/json.yaml +17 -0
  131. api_everything/recipes/httpbin/uuid.yaml +15 -0
  132. api_everything/recipes/huggingface/datasets.yaml +25 -0
  133. api_everything/recipes/huggingface/model_info.yaml +27 -0
  134. api_everything/recipes/huggingface/models.yaml +28 -0
  135. api_everything/recipes/huggingface/spaces.yaml +25 -0
  136. api_everything/recipes/inspirehep/papers.yaml +24 -0
  137. api_everything/recipes/ionic_docs/search.yaml +32 -0
  138. api_everything/recipes/ipify/ipv4.yaml +17 -0
  139. api_everything/recipes/ipwho/lookup.yaml +24 -0
  140. api_everything/recipes/jest_docs/search.yaml +32 -0
  141. api_everything/recipes/jsdelivr/gh.yaml +27 -0
  142. api_everything/recipes/jsdelivr/npm.yaml +24 -0
  143. api_everything/recipes/jsr/search.yaml +27 -0
  144. api_everything/recipes/launchdarkly_status/summary.yaml +17 -0
  145. api_everything/recipes/lemmy/hot.yaml +17 -0
  146. api_everything/recipes/lesswrong/feed.yaml +17 -0
  147. api_everything/recipes/llamaindex_docs/search.yaml +32 -0
  148. api_everything/recipes/lobsters/hottest.yaml +20 -0
  149. api_everything/recipes/luma/category.yaml +22 -0
  150. api_everything/recipes/luma/events.yaml +17 -0
  151. api_everything/recipes/mastodon/explore.yaml +26 -0
  152. api_everything/recipes/mastodon/tag.yaml +23 -0
  153. api_everything/recipes/mastodon/trends_tags.yaml +18 -0
  154. api_everything/recipes/mdn/search.yaml +24 -0
  155. api_everything/recipes/metacpan/search.yaml +24 -0
  156. api_everything/recipes/microlink/preview.yaml +24 -0
  157. api_everything/recipes/mikro_orm_docs/search.yaml +32 -0
  158. api_everything/recipes/mock/items.yaml +35 -0
  159. api_everything/recipes/mongodb_status/summary.yaml +17 -0
  160. api_everything/recipes/nager_date/holidays.yaml +32 -0
  161. api_everything/recipes/neon_docs/search.yaml +32 -0
  162. api_everything/recipes/nestjs_docs/search.yaml +32 -0
  163. api_everything/recipes/netlify_status/summary.yaml +17 -0
  164. api_everything/recipes/nextjs_docs/search.yaml +32 -0
  165. api_everything/recipes/nodejs_dist/releases.yaml +17 -0
  166. api_everything/recipes/npm/dist_tags.yaml +22 -0
  167. api_everything/recipes/npm/package.yaml +25 -0
  168. api_everything/recipes/npm/search.yaml +25 -0
  169. api_everything/recipes/npm_downloads/weekly.yaml +24 -0
  170. api_everything/recipes/npm_status/summary.yaml +17 -0
  171. api_everything/recipes/npmtrends/compare.yaml +22 -0
  172. api_everything/recipes/nuget/search.yaml +27 -0
  173. api_everything/recipes/nuxt_docs/search.yaml +32 -0
  174. api_everything/recipes/nvd/cve.yaml +22 -0
  175. api_everything/recipes/nvd/cves.yaml +24 -0
  176. api_everything/recipes/open_elevation/lookup.yaml +29 -0
  177. api_everything/recipes/openai_status/summary.yaml +17 -0
  178. api_everything/recipes/opencollective/search.yaml +22 -0
  179. api_everything/recipes/openfda/events.yaml +17 -0
  180. api_everything/recipes/openlibrary/search.yaml +24 -0
  181. api_everything/recipes/openmeteo/forecast.yaml +17 -0
  182. api_everything/recipes/openrouter/models.yaml +20 -0
  183. api_everything/recipes/openstreetmap/geocode.yaml +27 -0
  184. api_everything/recipes/openstreetmap/reverse.yaml +27 -0
  185. api_everything/recipes/osv/vuln.yaml +24 -0
  186. api_everything/recipes/packagist/search.yaml +27 -0
  187. api_everything/recipes/peps/list.yaml +17 -0
  188. api_everything/recipes/pinia_docs/search.yaml +32 -0
  189. api_everything/recipes/pkg_go_dev/browse.yaml +15 -0
  190. api_everything/recipes/pkg_go_dev/package.yaml +25 -0
  191. api_everything/recipes/playwright_docs/search.yaml +32 -0
  192. api_everything/recipes/pnpm_docs/search.yaml +32 -0
  193. api_everything/recipes/pokeapi/pokemon.yaml +24 -0
  194. api_everything/recipes/posthog_docs/search.yaml +32 -0
  195. api_everything/recipes/postman_echo/get.yaml +24 -0
  196. api_everything/recipes/postman_status/summary.yaml +17 -0
  197. api_everything/recipes/preact_docs/search.yaml +32 -0
  198. api_everything/recipes/pubdev/search.yaml +24 -0
  199. api_everything/recipes/pubmed/search.yaml +24 -0
  200. api_everything/recipes/puppeteer_docs/search.yaml +32 -0
  201. api_everything/recipes/pypi/package.yaml +24 -0
  202. api_everything/recipes/pypi/version.yaml +27 -0
  203. api_everything/recipes/quay/search.yaml +27 -0
  204. api_everything/recipes/quora/answers.yaml +46 -0
  205. api_everything/recipes/qwik_docs/search.yaml +32 -0
  206. api_everything/recipes/ray_docs/search.yaml +32 -0
  207. api_everything/recipes/rdap/domain.yaml +24 -0
  208. api_everything/recipes/react_docs/search.yaml +32 -0
  209. api_everything/recipes/react_hook_form_docs/search.yaml +32 -0
  210. api_everything/recipes/reactrouter_docs/search.yaml +32 -0
  211. api_everything/recipes/reddit/search.yaml +48 -0
  212. api_everything/recipes/reddit_status/summary.yaml +17 -0
  213. api_everything/recipes/remoteok/jobs.yaml +17 -0
  214. api_everything/recipes/render_status/summary.yaml +17 -0
  215. api_everything/recipes/repology/project.yaml +24 -0
  216. api_everything/recipes/ripe_stat/prefix.yaml +24 -0
  217. api_everything/recipes/rollup_docs/search.yaml +32 -0
  218. api_everything/recipes/rsbuild_docs/search.yaml +32 -0
  219. api_everything/recipes/rubygems/gem.yaml +22 -0
  220. api_everything/recipes/rubygems/search.yaml +27 -0
  221. api_everything/recipes/sendgrid_status/summary.yaml +17 -0
  222. api_everything/recipes/sequelize_docs/search.yaml +32 -0
  223. api_everything/recipes/shodan_internetdb/host.yaml +24 -0
  224. api_everything/recipes/shopify_status/summary.yaml +17 -0
  225. api_everything/recipes/sigstore_rekor/log.yaml +17 -0
  226. api_everything/recipes/slack_status/current.yaml +17 -0
  227. api_everything/recipes/spdx/licenses.yaml +17 -0
  228. api_everything/recipes/stackexchange/sites.yaml +20 -0
  229. api_everything/recipes/stackoverflow/answers.yaml +15 -0
  230. api_everything/recipes/stackoverflow/questions.yaml +18 -0
  231. api_everything/recipes/stackoverflow/search.yaml +27 -0
  232. api_everything/recipes/stackoverflow/tags.yaml +18 -0
  233. api_everything/recipes/strapi_docs/search.yaml +32 -0
  234. api_everything/recipes/strawberry_docs/search.yaml +32 -0
  235. api_everything/recipes/stripe_status/current.yaml +17 -0
  236. api_everything/recipes/substack/explore.yaml +22 -0
  237. api_everything/recipes/substack/search.yaml +31 -0
  238. api_everything/recipes/sunrise_sunset/times.yaml +29 -0
  239. api_everything/recipes/supabase_status/summary.yaml +17 -0
  240. api_everything/recipes/swr_docs/search.yaml +32 -0
  241. api_everything/recipes/tanstack_docs/search.yaml +32 -0
  242. api_everything/recipes/tc39/proposals.yaml +20 -0
  243. api_everything/recipes/techempower/results.yaml +15 -0
  244. api_everything/recipes/temporal_docs/search.yaml +32 -0
  245. api_everything/recipes/terraform_registry/browse.yaml +25 -0
  246. api_everything/recipes/terraform_registry/search.yaml +24 -0
  247. api_everything/recipes/testing_library_docs/search.yaml +32 -0
  248. api_everything/recipes/tvmaze/shows.yaml +24 -0
  249. api_everything/recipes/twilio_status/summary.yaml +17 -0
  250. api_everything/recipes/upstash_docs/search.yaml +32 -0
  251. api_everything/recipes/valibot_docs/search.yaml +32 -0
  252. api_everything/recipes/vercel_status/summary.yaml +17 -0
  253. api_everything/recipes/vercel_status/ui.yaml +15 -0
  254. api_everything/recipes/vue_docs/search.yaml +32 -0
  255. api_everything/recipes/w3c/specs.yaml +17 -0
  256. api_everything/recipes/wayback/available.yaml +24 -0
  257. api_everything/recipes/webdriverio_docs/search.yaml +32 -0
  258. api_everything/recipes/webpack_docs/search.yaml +32 -0
  259. api_everything/recipes/wikidata/entity.yaml +22 -0
  260. api_everything/recipes/wikidata/search.yaml +24 -0
  261. api_everything/recipes/wikimedia_commons/search.yaml +25 -0
  262. api_everything/recipes/wikipedia/search.yaml +25 -0
  263. api_everything/recipes/wikipedia/summary.yaml +33 -0
  264. api_everything/recipes/wordpress_plugins/search.yaml +24 -0
  265. api_everything/recipes/wordpress_themes/search.yaml +24 -0
  266. api_everything/recipes/worldbank/indicator.yaml +17 -0
  267. api_everything/recipes/zenodo/records.yaml +24 -0
  268. api_everything/recipes/zippopotam/in.yaml +22 -0
  269. api_everything/recipes/zippopotam/lookup.yaml +29 -0
  270. api_everything/recipes/zoom_status/summary.yaml +17 -0
  271. api_everything/record.py +327 -0
  272. api_everything/record_session.py +364 -0
  273. api_everything/repair.py +717 -0
  274. api_everything/repair_ai.py +194 -0
  275. api_everything/runlog.py +61 -0
  276. api_everything/server.py +323 -0
  277. api_everything-0.5.0.dist-info/METADATA +363 -0
  278. api_everything-0.5.0.dist-info/RECORD +281 -0
  279. api_everything-0.5.0.dist-info/WHEEL +4 -0
  280. api_everything-0.5.0.dist-info/entry_points.txt +2 -0
  281. api_everything-0.5.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,518 @@
1
+ """Recipe delivery: fetch shared recipes from git, show what would change, apply what you approve.
2
+
3
+ `api-everything recipes pull | diff | apply | remove`. Applied recipes live in `community_dir`,
4
+ a managed folder loaded between the bundled recipes and your own, so a recipe of yours with the
5
+ same name always wins and `apply` never edits your `recipes_dir`.
6
+
7
+ Trust model, plainly: a pulled recipe decides which pages your browser opens, and a logged-in
8
+ one does that as you. So nothing is applied without approval, risky changes need you to type the
9
+ recipe's name, recipes using `eval` are never applied, and recipes naming a hook are refused
10
+ (hooks are local code). Nothing here verifies who wrote a recipe: the protection is that you
11
+ chose the source and approved the diff.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import difflib
17
+ import hashlib
18
+ import json
19
+ import os
20
+ import re
21
+ import tempfile
22
+ import unicodedata
23
+ from collections.abc import Callable
24
+ from dataclasses import dataclass, field
25
+ from pathlib import Path
26
+ from typing import Any
27
+
28
+ import yaml
29
+
30
+ from api_everything.config import Config, RecipeSource
31
+ from api_everything.delivery_git import (
32
+ DeliveryError,
33
+ checkout_dir,
34
+ display_url,
35
+ head_commit,
36
+ sync,
37
+ )
38
+ from api_everything.recipe import Recipe
39
+ from api_everything.recipe.loader import (
40
+ LoadedRecipes,
41
+ RecipeLoadError,
42
+ bundled_recipes_dir,
43
+ load_recipe_file,
44
+ load_recipes,
45
+ )
46
+ from api_everything.recipe.schema import RECIPE_NAME
47
+
48
+ MAX_FILE_BYTES = 64 * 1024
49
+ MAX_FILES = 500
50
+ LOCK_NAME = ".lock.json"
51
+ SHOWN_LINES = 120
52
+
53
+ Ask = Callable[[str], str]
54
+ Say = Callable[[str], None]
55
+
56
+
57
+ # --- what is in a source ---------------------------------------------------------------------
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class Incoming:
62
+ """One recipe file found in a source. `text` is exactly what would be written."""
63
+
64
+ name: str
65
+ text: str
66
+ recipe: Recipe | None
67
+ problem: str | None # why it is refused, if it is
68
+ source: str
69
+
70
+
71
+ def inspect_checkout(root: Path, source_label: str) -> list[Incoming]:
72
+ """Every `recipes/<site>/<endpoint>.yaml` in a checkout, validated. Nothing is executed."""
73
+ base = root / "recipes"
74
+ if not base.is_dir():
75
+ raise DeliveryError(f"{source_label} has no recipes/ folder")
76
+ found: list[Incoming] = []
77
+ paths: list[Path] = []
78
+ for site_dir in sorted(base.iterdir()):
79
+ if site_dir.is_dir() and not site_dir.is_symlink():
80
+ paths.extend(sorted(site_dir.glob("*.yaml")))
81
+ if len(paths) > MAX_FILES:
82
+ raise DeliveryError(f"{source_label} has more than {MAX_FILES} recipe files")
83
+ for path in paths:
84
+ site = path.parent.name
85
+ name = f"{site}.{path.stem}"
86
+ found.append(_inspect_file(path, site, name, source_label))
87
+ return found
88
+
89
+
90
+ def _has_hidden_characters(text: str) -> bool:
91
+ """Control characters (other than newline, tab) or invisible formatting such as bidi marks."""
92
+ return any(
93
+ unicodedata.category(c) in ("Cc", "Cf") and c not in "\n\t\r" for c in text
94
+ )
95
+
96
+
97
+ def _clean(text: str) -> str:
98
+ """Make text from a repository safe to print: no terminal escapes, no text-direction tricks."""
99
+ return "".join(
100
+ "?" if unicodedata.category(c) in ("Cc", "Cf") and c not in "\n\t" else c for c in text
101
+ )
102
+
103
+
104
+ def _refuse(name: str, source: str, problem: str, text: str = "") -> Incoming:
105
+ # `name` comes from a path in the repository and `problem` may quote its content.
106
+ return Incoming(_clean(name), text, None, _clean(problem), source)
107
+
108
+
109
+ def _inspect_file(path: Path, site: str, name: str, source: str) -> Incoming:
110
+ if path.is_symlink():
111
+ return _refuse(name, source, "is a symbolic link; links are never followed")
112
+ try:
113
+ size = path.stat().st_size
114
+ if size > MAX_FILE_BYTES:
115
+ return _refuse(name, source, f"is {size} bytes; the limit is {MAX_FILE_BYTES}")
116
+ text = path.read_text(encoding="utf-8")
117
+ except (OSError, UnicodeDecodeError) as exc:
118
+ return _refuse(name, source, f"cannot be read as text ({type(exc).__name__})")
119
+ if _has_hidden_characters(text): # before parsing: hostile text is never even loaded
120
+ return _refuse(name, source, "contains control or text-direction characters")
121
+ try:
122
+ raw = yaml.safe_load(text)
123
+ except yaml.YAMLError:
124
+ return _refuse(name, source, "is not valid YAML", text)
125
+ if isinstance(raw, dict) and raw.get("hook") is not None:
126
+ why = "names a hook; hooks are local code and are never delivered"
127
+ return _refuse(name, source, why, text)
128
+ # Validate the very text that would be written, in a scratch folder, with the real loader.
129
+ with tempfile.TemporaryDirectory() as scratch:
130
+ copy = Path(scratch) / site / path.name
131
+ copy.parent.mkdir()
132
+ copy.write_text(text, encoding="utf-8")
133
+ recipe, problems = load_recipe_file(copy, site, allow_eval=True)
134
+ if recipe is None:
135
+ prefix = f"{copy}: "
136
+ detail = "; ".join(p.removeprefix(prefix) for p in problems)
137
+ return _refuse(name, source, f"is not a valid recipe: {detail}", text)
138
+ odd = unusual_url(recipe)
139
+ if odd is not None:
140
+ return _refuse(
141
+ name, source,
142
+ "has a URL whose host part is not a plain scheme://host[:port] "
143
+ f"(browsers and programs can read it differently): {_clean(odd)}",
144
+ text,
145
+ )
146
+ return Incoming(recipe.name, text, recipe, None, source)
147
+
148
+
149
+ # --- comparing with what is installed --------------------------------------------------------
150
+
151
+
152
+ # A plain ASCII `scheme://host[:port]`. Browsers read `\` as `/` and `user@host` as a login, so
153
+ # `https://evil.example\@shop.example.com/x` goes to evil.example in Chrome while Python's URL
154
+ # parser reports shop.example.com. Anything that is not this plain shape is refused.
155
+ _ORIGIN = re.compile(
156
+ r"^(https?)://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(?::(\d{1,5}))?(?:[/?#]|$)"
157
+ )
158
+
159
+
160
+ def origin_of(url: str) -> str | None:
161
+ """`scheme://host[:port]` for a plain URL, or None when the authority is unusual."""
162
+ match = _ORIGIN.match(url)
163
+ if match is None:
164
+ return None
165
+ scheme, host, port = match.groups()
166
+ return f"{scheme}://{host.lower()}" + (f":{port}" if port else "")
167
+
168
+
169
+ def urls_of(recipe: Recipe) -> list[str]:
170
+ urls = [recipe.url]
171
+ for action in recipe.actions:
172
+ url = getattr(action, "url", None)
173
+ if url:
174
+ urls.append(url)
175
+ return urls
176
+
177
+
178
+ def unusual_url(recipe: Recipe) -> str | None:
179
+ """The first URL in the recipe whose host part is not a plain scheme://host[:port]."""
180
+ for url in urls_of(recipe):
181
+ if origin_of(url) is None:
182
+ return url
183
+ return None
184
+
185
+
186
+ def origins_of(recipe: Recipe) -> set[str]:
187
+ return {o for o in (origin_of(u) for u in urls_of(recipe)) if o}
188
+
189
+
190
+ def _actions_of(recipe: Recipe | None) -> list[Any]:
191
+ return [a.model_dump(mode="json") for a in recipe.actions] if recipe else []
192
+
193
+
194
+ def risk_flags(new: Recipe, old: Recipe | None, *, edited_locally: bool = False) -> list[str]:
195
+ """Why a change needs the recipe's name typed, not just a yes. Empty means it is routine."""
196
+ flags: list[str] = []
197
+ new_origins = sorted(origins_of(new) - (origins_of(old) if old else set()))
198
+ if new_origins:
199
+ flags.append(f"opens a site it did not before: {', '.join(new_origins)}")
200
+ # Any change to a logged-in recipe is not routine: it runs as the user's account.
201
+ if new.session != "none" or (old is not None and old.session != "none"):
202
+ flags.append(f"runs as your logged-in account ({new.session})")
203
+ if new.actions and _actions_of(new) != _actions_of(old):
204
+ flags.append("adds or changes actions (clicks, typing, navigation)")
205
+ if edited_locally:
206
+ flags.append("replaces a copy you edited by hand")
207
+ return flags
208
+
209
+
210
+ @dataclass
211
+ class Change:
212
+ incoming: Incoming
213
+ kind: str # new | changed | unchanged | rejected | blocked
214
+ flags: list[str] = field(default_factory=list)
215
+ diff: str = ""
216
+ shadowed: bool = False # you have your own recipe with this name, which wins
217
+
218
+ @property
219
+ def name(self) -> str:
220
+ return self.incoming.name
221
+
222
+
223
+ def _same_recipe(a: str, b: str) -> bool:
224
+ try:
225
+ return yaml.safe_load(a) == yaml.safe_load(b)
226
+ except yaml.YAMLError:
227
+ return False
228
+
229
+
230
+ def unified_diff(old: str, new: str, name: str) -> str:
231
+ lines = difflib.unified_diff(
232
+ old.splitlines(), new.splitlines(), f"installed {name}", f"incoming {name}", lineterm=""
233
+ )
234
+ return "\n".join(lines)
235
+
236
+
237
+ @dataclass
238
+ class Layers:
239
+ baseline: LoadedRecipes # bundled + applied: what `apply` would replace
240
+ user: LoadedRecipes | None # your own recipes, which override both
241
+ lock: dict[str, Any]
242
+
243
+
244
+ def load_layers(config: Config) -> Layers:
245
+ community = config.community_dir.expanduser()
246
+ dirs: list[Path | None] = [bundled_recipes_dir()]
247
+ if community.is_dir():
248
+ dirs.append(community)
249
+ try:
250
+ # The configured hooks folder is needed, or any of your recipes that names a hook
251
+ # would make every comparison fail as "invalid".
252
+ common: dict[str, Any] = {
253
+ "allow_eval": True, "eval_in_profiles": _Any(), "hooks_dir": config.hooks_dir,
254
+ }
255
+ baseline = load_recipes(*dirs, **common)
256
+ user = (
257
+ load_recipes(config.recipes_dir, **common)
258
+ if config.recipes_dir and config.recipes_dir.expanduser().is_dir()
259
+ else None
260
+ )
261
+ except RecipeLoadError as exc:
262
+ raise DeliveryError(
263
+ "an installed recipe is invalid, so nothing can be compared:\n "
264
+ + "\n ".join(exc.problems)
265
+ + "\nFix it, or run `api-everything recipes remove NAME` for an applied one."
266
+ ) from exc
267
+ return Layers(baseline, user, read_lock(config))
268
+
269
+
270
+ class _Any:
271
+ def __contains__(self, item: object) -> bool:
272
+ return True
273
+
274
+
275
+ def classify(incoming: Incoming, layers: Layers, config: Config) -> Change:
276
+ if incoming.problem is not None or incoming.recipe is None:
277
+ return Change(incoming, "rejected")
278
+ recipe = incoming.recipe
279
+ shadowed = bool(layers.user and recipe.name in layers.user.recipes)
280
+ if recipe.uses_eval:
281
+ return Change(incoming, "blocked", shadowed=shadowed)
282
+ old = layers.baseline.recipes.get(recipe.name)
283
+ old_text = layers.baseline.sources[recipe.name].read_text() if old else None
284
+ if old is not None and old_text is not None and _same_recipe(old_text, incoming.text):
285
+ return Change(incoming, "unchanged", shadowed=shadowed)
286
+ applied = _applied_path(config, recipe.name)
287
+ recorded = layers.lock.get("recipes", {}).get(recipe.name, {}).get("sha256")
288
+ edited = bool(
289
+ applied.is_file()
290
+ and recorded is not None
291
+ and _sha256(applied.read_text(encoding="utf-8")) != recorded
292
+ )
293
+ flags = risk_flags(recipe, old, edited_locally=edited)
294
+ diff = unified_diff(old_text, incoming.text, recipe.name) if old_text is not None else ""
295
+ return Change(incoming, "new" if old is None else "changed", flags, diff, shadowed)
296
+
297
+
298
+ # --- the lock file ---------------------------------------------------------------------------
299
+
300
+
301
+ def _sha256(text: str) -> str:
302
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
303
+
304
+
305
+ def _lock_path(config: Config) -> Path:
306
+ return config.community_dir.expanduser() / LOCK_NAME
307
+
308
+
309
+ def read_lock(config: Config) -> dict[str, Any]:
310
+ try:
311
+ data = json.loads(_lock_path(config).read_text())
312
+ except (OSError, ValueError):
313
+ return {"version": 1, "sources": {}, "recipes": {}}
314
+ if not isinstance(data, dict):
315
+ return {"version": 1, "sources": {}, "recipes": {}}
316
+ data.setdefault("sources", {})
317
+ data.setdefault("recipes", {})
318
+ return data
319
+
320
+
321
+ def _atomic_write(path: Path, text: str) -> None:
322
+ path.parent.mkdir(parents=True, exist_ok=True)
323
+ fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".tmp-", suffix=".part")
324
+ try:
325
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
326
+ handle.write(text)
327
+ os.replace(tmp, path)
328
+ except BaseException:
329
+ Path(tmp).unlink(missing_ok=True)
330
+ raise
331
+
332
+
333
+ def write_lock(config: Config, lock: dict[str, Any]) -> None:
334
+ _atomic_write(_lock_path(config), json.dumps(lock, indent=2, sort_keys=True) + "\n")
335
+
336
+
337
+ def _applied_path(config: Config, name: str) -> Path:
338
+ site, endpoint = name.split(".", 1)
339
+ return config.community_dir.expanduser() / site / f"{endpoint}.yaml"
340
+
341
+
342
+ # --- reading what pull fetched ---------------------------------------------------------------
343
+
344
+
345
+ def _incoming(config: Config) -> list[tuple[RecipeSource, str, list[Incoming]]]:
346
+ """Inspect every configured source's cached checkout (run `pull` first)."""
347
+ if not config.recipe_sources:
348
+ raise DeliveryError("no recipe sources are configured (recipe_sources is empty)")
349
+ out = []
350
+ for source in config.recipe_sources:
351
+ root = checkout_dir(source, config.sources_dir)
352
+ if not (root / ".git").is_dir():
353
+ raise DeliveryError(
354
+ f"{display_url(source.git)} has not been pulled yet: "
355
+ "run `api-everything recipes pull`"
356
+ )
357
+ out.append((source, head_commit(root), inspect_checkout(root, display_url(source.git))))
358
+ return out
359
+
360
+
361
+ def _all_changes(config: Config) -> tuple[list[Change], dict[str, str]]:
362
+ layers = load_layers(config)
363
+ changes: list[Change] = []
364
+ commits: dict[str, str] = {}
365
+ seen: dict[str, str] = {}
366
+ for source, commit, incoming in _incoming(config):
367
+ label = display_url(source.git)
368
+ commits[label] = commit
369
+ for item in incoming:
370
+ if item.name in seen:
371
+ why = f"is also provided by {seen[item.name]}"
372
+ changes.append(Change(Incoming(item.name, item.text, None, why, label), "rejected"))
373
+ continue
374
+ seen[item.name] = label
375
+ changes.append(classify(item, layers, config))
376
+ return changes, commits
377
+
378
+
379
+ # --- the commands ----------------------------------------------------------------------------
380
+
381
+
382
+ def _summary(changes: list[Change]) -> str:
383
+ counts = {k: sum(1 for c in changes if c.kind == k) for k in
384
+ ("new", "changed", "unchanged", "blocked", "rejected")}
385
+ return (
386
+ f"{counts['new']} new, {counts['changed']} changed, {counts['unchanged']} unchanged, "
387
+ f"{counts['blocked']} not applicable (eval), {counts['rejected']} refused"
388
+ )
389
+
390
+
391
+ def pull(config: Config, say: Say) -> int:
392
+ """Fetch every source. Read-only for everything you use: nothing is applied."""
393
+ if not config.recipe_sources:
394
+ raise DeliveryError("no recipe sources are configured (recipe_sources is empty)")
395
+ lock = read_lock(config)
396
+ for source in config.recipe_sources:
397
+ label = display_url(source.git)
398
+ say(f"Fetching {label} ({source.ref}) ...")
399
+ _, commit = sync(source, config.sources_dir)
400
+ lock["sources"][label] = {"ref": source.ref, "commit": commit}
401
+ say(f" at commit {commit[:12]}")
402
+ write_lock(config, lock)
403
+ changes, _ = _all_changes(config)
404
+ say(f"Found: {_summary(changes)}.")
405
+ if any(c.kind in ("new", "changed") for c in changes):
406
+ say("Run `api-everything recipes diff` to see them, then `recipes apply`.")
407
+ return 0
408
+
409
+
410
+ def _show(change: Change, say: Say, *, full: bool) -> None:
411
+ """Print a change. `apply` always shows every line: approval must cover what is written."""
412
+ tag = " (your own recipe of this name takes priority)" if change.shadowed else ""
413
+ say(f"\n== {change.name}: {change.kind}{tag}")
414
+ for flag in change.flags:
415
+ say(f" ! {flag}")
416
+ body = change.diff if change.kind == "changed" else change.incoming.text
417
+ lines = body.splitlines()
418
+ for line in lines if full else lines[:SHOWN_LINES]:
419
+ say(f" {line}")
420
+ if not full and len(lines) > SHOWN_LINES:
421
+ say(f" ... {len(lines) - SHOWN_LINES} more lines (`apply` shows every line)")
422
+
423
+
424
+ def _report_others(changes: list[Change], say: Say) -> None:
425
+ for c in changes:
426
+ if c.kind == "blocked":
427
+ say(
428
+ f"\n{c.name}: uses eval (custom JavaScript), so it is never applied by this "
429
+ "command. Copy it into your own recipes by hand if you trust it."
430
+ )
431
+ elif c.kind == "rejected":
432
+ say(f"\n{c.name}: refused, {c.incoming.problem}")
433
+
434
+
435
+ def diff(config: Config, names: list[str], say: Say) -> int:
436
+ changes, _ = _all_changes(config)
437
+ wanted = _select(changes, names)
438
+ shown = [c for c in wanted if c.kind in ("new", "changed")]
439
+ for change in shown:
440
+ _show(change, say, full=False)
441
+ _report_others([c for c in wanted if c.kind in ("blocked", "rejected")], say)
442
+ say(f"\n{_summary(wanted)}.")
443
+ return 0
444
+
445
+
446
+ def _select(changes: list[Change], names: list[str]) -> list[Change]:
447
+ if not names:
448
+ return changes
449
+ known = {c.name for c in changes}
450
+ missing = [n for n in names if n not in known]
451
+ if missing:
452
+ raise DeliveryError(f"the sources have no recipe named {', '.join(missing)}")
453
+ return [c for c in changes if c.name in names]
454
+
455
+
456
+ def apply(config: Config, names: list[str], *, yes: bool, ask: Ask, say: Say) -> int:
457
+ changes, commits = _all_changes(config)
458
+ wanted = _select(changes, names)
459
+ lock = read_lock(config)
460
+ applied: list[str] = []
461
+ for change in (c for c in wanted if c.kind in ("new", "changed")):
462
+ _show(change, say, full=True)
463
+ if change.flags:
464
+ if yes:
465
+ say(f" skipped: needs your approval ({'; '.join(change.flags)})")
466
+ continue
467
+ answer = ask(f"Type {change.name} to apply it, or press Enter to skip: ").strip()
468
+ approved = answer == change.name
469
+ else:
470
+ approved = yes or ask("Apply this? [y/N]: ").strip().lower() in ("y", "yes")
471
+ if not approved:
472
+ say(" skipped")
473
+ continue
474
+ _write_applied(config, lock, change, commits)
475
+ write_lock(config, lock) # per recipe: an interrupt leaves no applied file unrecorded
476
+ applied.append(change.name)
477
+ say(f" applied to {_applied_path(config, change.name)}")
478
+ _report_others([c for c in wanted if c.kind in ("blocked", "rejected")], say)
479
+ if applied:
480
+ say(
481
+ f"\nApplied {len(applied)} recipe(s): {', '.join(applied)}.\n"
482
+ "Restart `api-everything serve` (and any MCP bridge) to load them, and run "
483
+ f"`api-everything check {' '.join(applied)}` to try them."
484
+ )
485
+ else:
486
+ say("\nNothing was applied.")
487
+ return 0
488
+
489
+
490
+ def _write_applied(
491
+ config: Config, lock: dict[str, Any], change: Change, commits: dict[str, str]
492
+ ) -> None:
493
+ text = change.incoming.text
494
+ _atomic_write(_applied_path(config, change.name), text)
495
+ lock["recipes"][change.name] = {
496
+ "sha256": _sha256(text),
497
+ "source": change.incoming.source,
498
+ "commit": commits.get(change.incoming.source, ""),
499
+ }
500
+
501
+
502
+ def remove(config: Config, name: str, say: Say) -> int:
503
+ if not RECIPE_NAME.match(name):
504
+ raise DeliveryError(f"{name!r} is not a recipe name (expected site.endpoint)")
505
+ path = _applied_path(config, name)
506
+ lock = read_lock(config)
507
+ if not path.is_file():
508
+ raise DeliveryError(f"{name} was not applied from a source (nothing in {path.parent})")
509
+ path.unlink()
510
+ with_site = path.parent
511
+ if with_site.is_dir() and not any(with_site.iterdir()):
512
+ with_site.rmdir()
513
+ lock["recipes"].pop(name, None)
514
+ write_lock(config, lock)
515
+ say(f"Removed {name} from the applied recipes.")
516
+ if name in load_recipes(bundled_recipes_dir()).recipes:
517
+ say("The bundled version of it is active again after a restart.")
518
+ return 0
@@ -0,0 +1,94 @@
1
+ """The git side of recipe delivery: keep a shallow clone of each source up to date.
2
+
3
+ Only `git` is used, so a source can be any repository the user's own git can reach (their
4
+ credentials, SSH keys and credential helpers apply). Nothing from the repository is executed:
5
+ no hooks, no submodules, no `ext::` transport, and prompts for passwords are off so a scheduled
6
+ run fails instead of hanging.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import os
13
+ import shutil
14
+ import subprocess
15
+ from pathlib import Path
16
+ from urllib.parse import urlsplit
17
+
18
+ from api_everything.config import RecipeSource
19
+
20
+ GIT_TIMEOUT_SECONDS = 120
21
+ _SAFE = [
22
+ "-c", "protocol.ext.allow=never",
23
+ "-c", "core.hooksPath=/dev/null",
24
+ "-c", "core.fsmonitor=false",
25
+ ]
26
+
27
+
28
+ class DeliveryError(Exception):
29
+ """Delivery cannot continue. The message says what to do."""
30
+
31
+
32
+ def display_url(url: str) -> str:
33
+ """The address with any `user:password@` removed, safe to print."""
34
+ parts = urlsplit(url)
35
+ if parts.username or parts.password:
36
+ host = parts.hostname or ""
37
+ host = f"{host}:{parts.port}" if parts.port else host
38
+ return parts._replace(netloc=host).geturl()
39
+ return url
40
+
41
+
42
+ def checkout_dir(source: RecipeSource, sources_dir: Path) -> Path:
43
+ key = hashlib.sha256(f"{source.git}\n{source.ref}".encode()).hexdigest()[:16]
44
+ return sources_dir.expanduser() / key
45
+
46
+
47
+ def _git(args: list[str], *, cwd: Path | None = None) -> str:
48
+ if shutil.which("git") is None:
49
+ raise DeliveryError("git is required for recipe delivery but was not found on PATH")
50
+ env = dict(os.environ, GIT_TERMINAL_PROMPT="0", GIT_OPTIONAL_LOCKS="0")
51
+ # ssh would otherwise stop to ask for a passphrase or host-key confirmation: fail instead.
52
+ env.setdefault("GIT_SSH_COMMAND", "ssh -o BatchMode=yes")
53
+ try:
54
+ done = subprocess.run( # noqa: S603 - a fixed argument list, no shell
55
+ ["git", *_SAFE, *args],
56
+ cwd=cwd,
57
+ env=env,
58
+ capture_output=True,
59
+ text=True,
60
+ timeout=GIT_TIMEOUT_SECONDS,
61
+ check=False,
62
+ )
63
+ except subprocess.TimeoutExpired as exc:
64
+ raise DeliveryError(f"git took longer than {GIT_TIMEOUT_SECONDS}s and was stopped") from exc
65
+ if done.returncode != 0:
66
+ lines = [ln for ln in done.stderr.strip().splitlines() if ln.strip()]
67
+ reason = lines[-1] if lines else f"exit code {done.returncode}"
68
+ raise DeliveryError(reason)
69
+ return done.stdout.strip()
70
+
71
+
72
+ def head_commit(checkout: Path) -> str:
73
+ return _git(["rev-parse", "HEAD"], cwd=checkout)
74
+
75
+
76
+ def sync(source: RecipeSource, sources_dir: Path) -> tuple[Path, str]:
77
+ """Clone or update the source and return (its folder, the commit now checked out)."""
78
+ target = checkout_dir(source, sources_dir)
79
+ where = display_url(source.git)
80
+ try:
81
+ if (target / ".git").is_dir():
82
+ fetch = ["fetch", "--depth", "1", "--no-tags", "--no-recurse-submodules"]
83
+ _git([*fetch, "origin", source.ref], cwd=target)
84
+ _git(["checkout", "--detach", "--force", "FETCH_HEAD"], cwd=target)
85
+ else:
86
+ target.parent.mkdir(parents=True, exist_ok=True)
87
+ if target.exists():
88
+ shutil.rmtree(target)
89
+ clone = ["clone", "--depth", "1", "--no-tags", "--single-branch"]
90
+ _git([*clone, "--no-recurse-submodules", "--branch", source.ref, "--", source.git,
91
+ str(target)])
92
+ return target, head_commit(target)
93
+ except DeliveryError as exc:
94
+ raise DeliveryError(f"could not fetch {where} ({source.ref}): {exc}") from exc
@@ -0,0 +1,37 @@
1
+ """Browser drivers: sources of Playwright browsers behind one interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Literal
6
+
7
+ from api_everything.driver.attach import BrowserNotRunning, ChromeAttachDriver
8
+ from api_everything.driver.base import BrowserDriver, Lease
9
+ from api_everything.driver.chrome import (
10
+ CHROMIUM_INSTALL_COMMAND,
11
+ BrowserNotInstalled,
12
+ ChromeDriver,
13
+ ChromiumDriver,
14
+ )
15
+ from api_everything.driver.profile import ChromeProfileDriver
16
+
17
+ BrowserChoice = Literal["chrome", "chromium"]
18
+
19
+
20
+ def shared_driver_class(browser: BrowserChoice) -> type[ChromeDriver]:
21
+ """The driver class for the shared (`session: none`) lane, from the `browser` setting."""
22
+ return ChromiumDriver if browser == "chromium" else ChromeDriver
23
+
24
+
25
+ __all__ = [
26
+ "CHROMIUM_INSTALL_COMMAND",
27
+ "BrowserChoice",
28
+ "BrowserDriver",
29
+ "BrowserNotInstalled",
30
+ "BrowserNotRunning",
31
+ "ChromeAttachDriver",
32
+ "ChromeDriver",
33
+ "ChromeProfileDriver",
34
+ "ChromiumDriver",
35
+ "Lease",
36
+ "shared_driver_class",
37
+ ]