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,934 @@
1
+ """Recipe pipeline: probe sites, scaffold YAML drafts, promote verified recipes, render catalog.
2
+
3
+ api-everything probe <url_or_site_id> inspect live XHR/fetch JSON calls in Chrome
4
+ api-everything scaffold <name_or_site_id> generate a draft YAML recipe (optional --probe)
5
+ api-everything promote <recipe_name> run N consecutive live checks; mark stable
6
+
7
+ The 100-site developer registry lives in `catalog/sites.yaml` and renders `docs/CATALOG.md`.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+ import json
14
+ import re
15
+ from collections.abc import Awaitable, Callable
16
+ from dataclasses import dataclass, field
17
+ from pathlib import Path
18
+ from typing import Any, Literal
19
+ from urllib.parse import quote, unquote, urlsplit
20
+
21
+ import yaml
22
+ from playwright.async_api import Response
23
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
24
+
25
+ from api_everything.check import (
26
+ CheckResult,
27
+ check_recipes,
28
+ daemon_base_url,
29
+ daemon_is_running,
30
+ )
31
+ from api_everything.check import (
32
+ daemon_runner as make_daemon_runner,
33
+ )
34
+ from api_everything.config import Config
35
+ from api_everything.driver import BrowserDriver, ChromeDriver
36
+ from api_everything.engine import RunResult
37
+ from api_everything.errors import RunError
38
+ from api_everything.hooks import load_hooks
39
+ from api_everything.pool import Pool
40
+ from api_everything.recipe import Recipe, render
41
+ from api_everything.recipe.loader import (
42
+ LoadedRecipes,
43
+ RecipeLoadError,
44
+ bundled_recipes_dir,
45
+ load_recipes,
46
+ )
47
+ from api_everything.recipe.params import PARAM_NAME, PLACEHOLDER, placeholders
48
+ from api_everything.recipe.schema import RECIPE_NAME, SESSION_PROFILE, Expectation
49
+
50
+ CatalogStatus = Literal["stable", "experimental", "candidate", "blocked"]
51
+ CaptureMode = Literal["xhr", "json_endpoint", "unknown"]
52
+
53
+ _SITE_ID = re.compile(r"^[a-z0-9][a-z0-9_-]*$")
54
+ _ENDPOINT = re.compile(r"^[a-z0-9][a-z0-9_-]*$")
55
+
56
+ _NOISE_HOST_PARTS = (
57
+ "google-analytics.com",
58
+ "googletagmanager.com",
59
+ "doubleclick.net",
60
+ "googleadservices.com",
61
+ "cloudflareinsights.com",
62
+ "sentry.io",
63
+ "segment.io",
64
+ "segment.com",
65
+ "mixpanel.com",
66
+ "amplitude.com",
67
+ "hotjar.com",
68
+ "clarity.ms",
69
+ "telemetry.",
70
+ "plausible.io",
71
+ "intercom.io",
72
+ "awswaf.com",
73
+ )
74
+
75
+ _NOISE_PATH_PARTS = (
76
+ "/cdn-cgi/",
77
+ "/i18n/",
78
+ "/translations",
79
+ "/packs/assets/",
80
+ "/telemetry",
81
+ "/analytics",
82
+ "/metrics",
83
+ )
84
+
85
+ _LOW_SIGNAL_PATH_PARTS = (
86
+ "site_metadata",
87
+ "feature_flags",
88
+ "feature-flags",
89
+ "experiments",
90
+ "config.json",
91
+ "manifest.json",
92
+ "getconfig",
93
+ "/config",
94
+ "/geolocation",
95
+ "/_health",
96
+ "/features/",
97
+ )
98
+
99
+ _PREFERRED_LIST_KEYS = ("hits", "items", "results", "data", "records", "entries", "stories")
100
+ _PREFERRED_ITEM_KEYS = ("id", "objectID", "title", "name", "full_name", "slug", "url")
101
+
102
+
103
+ class PipelineError(Exception):
104
+ """A pipeline input, catalog, or file operation failed."""
105
+
106
+
107
+ class SiteEntry(BaseModel):
108
+ """One site in the developer target catalog (`catalog/sites.yaml`)."""
109
+
110
+ model_config = ConfigDict(extra="forbid")
111
+
112
+ id: str
113
+ name: str
114
+ category: str
115
+ url: str
116
+ endpoint: str = "search"
117
+ session: str = "none"
118
+ capture_mode: CaptureMode = "unknown"
119
+ status: CatalogStatus = "candidate"
120
+ recipe: str | None = None
121
+ sample_params: dict[str, str | int | float | bool] = Field(default_factory=dict)
122
+ notes: str = ""
123
+
124
+ @field_validator("id")
125
+ @classmethod
126
+ def _valid_id(cls, value: str) -> str:
127
+ if not _SITE_ID.match(value):
128
+ raise ValueError("site id must be lowercase letters, digits, '-' or '_'")
129
+ return value
130
+
131
+ @field_validator("endpoint")
132
+ @classmethod
133
+ def _valid_endpoint(cls, value: str) -> str:
134
+ if not _ENDPOINT.match(value):
135
+ raise ValueError("endpoint must be lowercase letters, digits, '-' or '_'")
136
+ return value
137
+
138
+ @field_validator("session")
139
+ @classmethod
140
+ def _valid_session(cls, value: str) -> str:
141
+ if value != "none" and not SESSION_PROFILE.match(value):
142
+ raise ValueError("session must be 'none' or 'profile:<name>'")
143
+ return value
144
+
145
+ @field_validator("url")
146
+ @classmethod
147
+ def _valid_url(cls, value: str) -> str:
148
+ if not re.match(r"^https?://[^/?#{}\s]+(?:[/?#]|$)", value):
149
+ raise ValueError("url must start with a literal http(s) scheme and host")
150
+ return value
151
+
152
+ @field_validator("recipe")
153
+ @classmethod
154
+ def _valid_recipe(cls, value: str | None) -> str | None:
155
+ if value is not None and not RECIPE_NAME.match(value):
156
+ raise ValueError("recipe must look like '<site>.<endpoint>'")
157
+ return value
158
+
159
+ @property
160
+ def target_recipe_name(self) -> str:
161
+ return self.recipe or f"{self.id}.{self.endpoint}"
162
+
163
+
164
+ class SiteCatalog(BaseModel):
165
+ """The machine-readable target catalog (`catalog/sites.yaml`)."""
166
+
167
+ model_config = ConfigDict(extra="forbid")
168
+
169
+ schema_version: Literal[1] = 1
170
+ sites: list[SiteEntry] = Field(default_factory=list)
171
+
172
+ def by_id(self, site_id: str) -> SiteEntry | None:
173
+ for entry in self.sites:
174
+ if entry.id == site_id:
175
+ return entry
176
+ return None
177
+
178
+
179
+ @dataclass
180
+ class ProbeHit:
181
+ url: str
182
+ status: int
183
+ resource_type: str
184
+ content_type: str
185
+ shape: str
186
+ keys: list[str] = field(default_factory=list)
187
+ is_noise: bool = False
188
+ suggested_regex: str = ""
189
+ suggested_expect: list[dict[str, Any]] = field(default_factory=list)
190
+ sample_data: Any = None
191
+
192
+
193
+ @dataclass
194
+ class ProbeReport:
195
+ target_url: str
196
+ final_url: str
197
+ document_status: int | None
198
+ blocked: bool
199
+ hits: list[ProbeHit] = field(default_factory=list)
200
+
201
+ @property
202
+ def candidates(self) -> list[ProbeHit]:
203
+ return [h for h in self.hits if not h.is_noise and 200 <= h.status < 300]
204
+
205
+ def to_dict(self) -> dict[str, Any]:
206
+ return {
207
+ "target_url": self.target_url,
208
+ "final_url": self.final_url,
209
+ "document_status": self.document_status,
210
+ "blocked": self.blocked,
211
+ "hits": [
212
+ {
213
+ "url": h.url,
214
+ "status": h.status,
215
+ "resource_type": h.resource_type,
216
+ "content_type": h.content_type,
217
+ "shape": h.shape,
218
+ "keys": h.keys,
219
+ "is_noise": h.is_noise,
220
+ "suggested_regex": h.suggested_regex,
221
+ "suggested_expect": h.suggested_expect,
222
+ }
223
+ for h in self.hits
224
+ ],
225
+ }
226
+
227
+
228
+ def default_catalog_path() -> Path:
229
+ cwd_path = Path.cwd() / "catalog" / "sites.yaml"
230
+ if cwd_path.is_file():
231
+ return cwd_path
232
+ repo_path = Path(__file__).resolve().parents[2] / "catalog" / "sites.yaml"
233
+ if repo_path.is_file():
234
+ return repo_path
235
+ return cwd_path
236
+
237
+
238
+ def default_catalog_doc_path(catalog_path: Path) -> Path:
239
+ return catalog_path.resolve().parent.parent / "docs" / "CATALOG.md"
240
+
241
+
242
+ def _no_dup_yaml_load(text: str) -> Any:
243
+ """Parse YAML while rejecting duplicate mapping keys at every nesting level."""
244
+
245
+ class _NoDupSafeLoader(yaml.SafeLoader):
246
+ pass
247
+
248
+ def _construct_mapping(
249
+ loader: yaml.SafeLoader, node: yaml.MappingNode, deep: bool = False
250
+ ) -> dict[Any, Any]:
251
+ mapping: dict[Any, Any] = {}
252
+ for key_node, value_node in node.value:
253
+ key = loader.construct_object(key_node, deep=deep)
254
+ if key in mapping:
255
+ raise yaml.constructor.ConstructorError(
256
+ "while constructing a mapping",
257
+ node.start_mark,
258
+ f"found duplicate key {key!r}",
259
+ key_node.start_mark,
260
+ )
261
+ mapping[key] = loader.construct_object(value_node, deep=deep)
262
+ return mapping
263
+
264
+ _NoDupSafeLoader.add_constructor(
265
+ yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, _construct_mapping
266
+ )
267
+ return yaml.load(text, Loader=_NoDupSafeLoader)
268
+
269
+
270
+ def load_catalog(path: Path | None = None) -> SiteCatalog:
271
+ catalog_path = path or default_catalog_path()
272
+ if not catalog_path.is_file():
273
+ raise PipelineError(f"catalog file not found: {catalog_path}")
274
+ try:
275
+ raw = _no_dup_yaml_load(catalog_path.read_text())
276
+ except (OSError, yaml.YAMLError) as exc:
277
+ raise PipelineError(f"cannot read catalog {catalog_path}: {exc}") from exc
278
+ if not isinstance(raw, dict):
279
+ raise PipelineError(f"catalog {catalog_path} must contain a mapping at the top level")
280
+ try:
281
+ catalog = SiteCatalog.model_validate(raw)
282
+ except ValidationError as exc:
283
+ problems = [
284
+ f"{'.'.join(str(p) for p in err['loc']) or 'catalog'}: {err['msg']}"
285
+ for err in exc.errors()
286
+ ]
287
+ raise PipelineError("invalid catalog:\n " + "\n ".join(problems)) from exc
288
+ seen: set[str] = set()
289
+ dups: list[str] = []
290
+ for entry in catalog.sites:
291
+ if entry.id in seen:
292
+ dups.append(entry.id)
293
+ seen.add(entry.id)
294
+ if dups:
295
+ raise PipelineError(f"duplicate site id(s) in catalog: {', '.join(sorted(set(dups)))}")
296
+ return catalog
297
+
298
+
299
+ def save_catalog(catalog: SiteCatalog, path: Path) -> None:
300
+ payload = catalog.model_dump(mode="json", exclude_none=True)
301
+ path.parent.mkdir(parents=True, exist_ok=True)
302
+ path.write_text(yaml.safe_dump(payload, sort_keys=False, allow_unicode=True))
303
+
304
+
305
+ def render_catalog_markdown(catalog: SiteCatalog) -> str:
306
+ """Render `docs/CATALOG.md` from `catalog/sites.yaml`."""
307
+ counts: dict[str, int] = {"stable": 0, "experimental": 0, "candidate": 0, "blocked": 0}
308
+ for site in catalog.sites:
309
+ counts[site.status] = counts.get(site.status, 0) + 1
310
+
311
+ lines = [
312
+ f"# Developer Target Catalog ({len(catalog.sites)} Sites)",
313
+ "",
314
+ "Generated from [`catalog/sites.yaml`](../catalog/sites.yaml). "
315
+ f"Total sites: **{len(catalog.sites)}** "
316
+ f"(`stable`: {counts['stable']}, `experimental`: {counts['experimental']}, "
317
+ f"`candidate`: {counts['candidate']}, `blocked`: {counts['blocked']}).",
318
+ "",
319
+ "Use the built-in pipeline to turn any site into a verified recipe:",
320
+ "",
321
+ "```bash",
322
+ "uv run api-everything probe <site-id>",
323
+ "uv run api-everything scaffold <site-id> --probe --out-dir recipes_staging",
324
+ "uv run api-everything promote <site>.<endpoint> --recipes-dir recipes_staging",
325
+ "```",
326
+ "",
327
+ "| # | ID | Site | Category | Status | Mode | Recipe | Notes |",
328
+ "|---|---|---|---|---|---|---|---|",
329
+ ]
330
+ for idx, site in enumerate(catalog.sites, start=1):
331
+ recipe_col = f"`{site.recipe}`" if site.recipe else f"`{site.id}.{site.endpoint}` (planned)"
332
+ notes = site.notes.replace("|", "\\|").replace("\n", " ").strip()
333
+ lines.append(
334
+ f"| {idx} | `{site.id}` | {site.name} | {site.category} | "
335
+ f"`{site.status}` | `{site.capture_mode}` | {recipe_col} | {notes} |"
336
+ )
337
+ lines.append("")
338
+ return "\n".join(lines)
339
+
340
+
341
+ def _is_noise_url(url: str) -> bool:
342
+ parts = urlsplit(url)
343
+ host = (parts.hostname or "").lower()
344
+ path = parts.path.lower()
345
+ return any(part in host for part in _NOISE_HOST_PARTS) or any(
346
+ part in path for part in _NOISE_PATH_PARTS
347
+ )
348
+
349
+
350
+ def suggest_url_regex(url: str, *, path_param_values: list[str] | None = None) -> str:
351
+ """Build an anchored `matcher.url_regex` from a concrete or templated URL."""
352
+ parts = urlsplit(url)
353
+ host = re.escape(parts.netloc)
354
+ raw_path = parts.path or "/"
355
+ pieces: list[str] = []
356
+ pos = 0
357
+ for match in PLACEHOLDER.finditer(raw_path):
358
+ pieces.append(re.escape(raw_path[pos : match.start()]))
359
+ pieces.append(r"[^/?#]+")
360
+ pos = match.end()
361
+ tail = raw_path[pos:]
362
+ if path_param_values and not pieces:
363
+ seg_parts = raw_path.split("/")
364
+ non_empty = [v for v in path_param_values if v]
365
+ values_set = set(non_empty) | {quote(v, safe="") for v in non_empty}
366
+ rebuilt: list[str] = []
367
+ i = 0
368
+ while i < len(seg_parts):
369
+ matched_multi = False
370
+ for val in non_empty:
371
+ if "/" in val:
372
+ val_segs = val.split("/")
373
+ if seg_parts[i : i + len(val_segs)] == val_segs:
374
+ rebuilt.append(r"[^?#]+")
375
+ i += len(val_segs)
376
+ matched_multi = True
377
+ break
378
+ if matched_multi:
379
+ continue
380
+ seg = seg_parts[i]
381
+ if seg and (seg in values_set or unquote(seg) in values_set):
382
+ rebuilt.append(r"[^/?#]+")
383
+ elif seg and any(v in seg for v in values_set):
384
+ val_pat = re.compile(
385
+ "|".join(re.escape(v) for v in sorted(values_set, key=len, reverse=True))
386
+ )
387
+ seg_pieces: list[str] = []
388
+ seg_pos = 0
389
+ for m in val_pat.finditer(seg):
390
+ seg_pieces.append(re.escape(seg[seg_pos : m.start()]))
391
+ seg_pieces.append(r"[^/?#]+")
392
+ seg_pos = m.end()
393
+ seg_pieces.append(re.escape(seg[seg_pos:]))
394
+ rebuilt.append("".join(seg_pieces))
395
+ else:
396
+ rebuilt.append(re.escape(seg))
397
+ i += 1
398
+ return rf"{host}{'/'.join(rebuilt)}(\?|$)"
399
+ pieces.append(re.escape(tail))
400
+ return rf"{host}{''.join(pieces)}(\?|$)"
401
+
402
+
403
+ def _infer_item_expectation(
404
+ data: Any, items: list[Any], prefix: str
405
+ ) -> dict[str, Any] | None:
406
+ if not items or not isinstance(items[0], dict):
407
+ return None
408
+ for key in _PREFERRED_ITEM_KEYS:
409
+ val = items[0].get(key)
410
+ candidate: dict[str, Any] | None = None
411
+ if isinstance(val, str) and val:
412
+ candidate = {"path": f"{prefix}.{key}", "non_empty": True, "type": "string"}
413
+ elif isinstance(val, int) and not isinstance(val, bool):
414
+ candidate = {"path": f"{prefix}.{key}", "type": "integer"}
415
+ if candidate is None:
416
+ continue
417
+ if all(isinstance(item, dict) and key in item for item in items) and not (
418
+ Expectation(**candidate).failures(data)
419
+ ):
420
+ return candidate
421
+ return None
422
+
423
+
424
+ def infer_expectations(data: Any) -> list[dict[str, Any]]:
425
+ """Infer sensible `check.expect` assertions from captured JSON data."""
426
+ if isinstance(data, list):
427
+ if not data:
428
+ return [{"path": "$", "type": "list"}]
429
+ expects: list[dict[str, Any]] = [{"path": "$", "non_empty": True, "type": "list"}]
430
+ item_exp = _infer_item_expectation(data, data, "$[*]")
431
+ if item_exp is not None:
432
+ expects.append(item_exp)
433
+ return expects
434
+
435
+ if isinstance(data, dict):
436
+ for key in _PREFERRED_LIST_KEYS:
437
+ val = data.get(key)
438
+ if isinstance(val, list) and val:
439
+ expects = [{"path": f"$.{key}", "non_empty": True, "type": "list"}]
440
+ item_exp = _infer_item_expectation(data, val, f"$.{key}[*]")
441
+ if item_exp is not None:
442
+ expects.append(item_exp)
443
+ return expects
444
+ for key, val in data.items():
445
+ if isinstance(val, list) and val and re.match(r"^[A-Za-z_][A-Za-z0-9_]*$", key):
446
+ return [{"path": f"$.{key}", "non_empty": True, "type": "list"}]
447
+ for key, val in data.items():
448
+ if isinstance(val, str) and val and re.match(r"^[A-Za-z_][A-Za-z0-9_]*$", key):
449
+ return [{"path": f"$.{key}", "non_empty": True, "type": "string"}]
450
+ if data:
451
+ return [{"path": "$", "non_empty": True, "type": "object"}]
452
+
453
+ return [{"path": "$"}]
454
+
455
+
456
+ def _describe_json(data: Any) -> tuple[str, list[str]]:
457
+ if isinstance(data, dict):
458
+ keys = [str(k) for k in list(data.keys())[:10]]
459
+ return f"object({len(data)} keys)", keys
460
+ if isinstance(data, list):
461
+ keys = (
462
+ [str(k) for k in list(data[0].keys())[:10]]
463
+ if data and isinstance(data[0], dict)
464
+ else []
465
+ )
466
+ return f"list[{len(data)}]", keys
467
+ return type(data).__name__, []
468
+
469
+
470
+ def _same_site(hit_host: str, target_host: str) -> bool:
471
+ if not target_host or not hit_host:
472
+ return False
473
+ return (
474
+ hit_host == target_host
475
+ or hit_host.endswith("." + target_host)
476
+ or target_host.endswith("." + hit_host)
477
+ )
478
+
479
+
480
+ def _hit_sort_key(hit: ProbeHit, *, target_host: str = "") -> tuple[int, int, int, int, int, int]:
481
+ is_api = 0 if not hit.is_noise else 1
482
+ is_2xx = 0 if 200 <= hit.status < 300 else 1
483
+ is_xhr = 0 if hit.resource_type in ("xhr", "fetch") else 1
484
+ hit_parts = urlsplit(hit.url)
485
+ hit_host = (hit_parts.hostname or "").lower()
486
+ same_domain = 0 if _same_site(hit_host, target_host) else 1
487
+ is_low_signal = 1 if any(p in hit_parts.path.lower() for p in _LOW_SIGNAL_PATH_PARTS) else 0
488
+ has_list = (
489
+ 0
490
+ if (
491
+ isinstance(hit.sample_data, list)
492
+ or (
493
+ isinstance(hit.sample_data, dict)
494
+ and any(isinstance(v, list) and v for v in hit.sample_data.values())
495
+ )
496
+ )
497
+ else 1
498
+ )
499
+ return (is_api, is_2xx, is_xhr, is_low_signal, same_domain, has_list)
500
+
501
+
502
+ def resolve_probe_url(
503
+ target: str,
504
+ *,
505
+ catalog: SiteCatalog | None = None,
506
+ params: dict[str, str] | None = None,
507
+ url_override: str | None = None,
508
+ ) -> tuple[str, SiteEntry | None]:
509
+ """Turn a URL, `<site>.<endpoint>`, or catalog site ID into a concrete URL ready for Chrome."""
510
+ entry: SiteEntry | None = None
511
+ url = url_override or target
512
+ if not target.startswith(("http://", "https://")):
513
+ site_id = target.split(".", 1)[0] if "." in target and RECIPE_NAME.match(target) else target
514
+ if catalog is None:
515
+ if url_override is None:
516
+ raise PipelineError(
517
+ f"target {target!r} is not a URL and no catalog is available to look it up"
518
+ )
519
+ else:
520
+ entry = catalog.by_id(site_id)
521
+ if entry is None and url_override is None:
522
+ raise PipelineError(f"unknown site id {target!r} in catalog")
523
+ if url_override is None and entry is not None:
524
+ url = entry.url
525
+
526
+ merged: dict[str, str] = {}
527
+ if entry is not None:
528
+ merged.update({k: str(v) for k, v in entry.sample_params.items()})
529
+ if params:
530
+ merged.update(params)
531
+
532
+ needed = placeholders(url)
533
+ missing = sorted(needed - set(merged))
534
+ if missing:
535
+ for key in missing:
536
+ merged[key] = "ai"
537
+ return render(url, merged, url_encode=True), entry
538
+
539
+
540
+ async def probe_target(
541
+ url: str,
542
+ *,
543
+ wait_ms: int = 2500,
544
+ driver: BrowserDriver | None = None,
545
+ ) -> ProbeReport:
546
+ """Open `url` in Chrome and record every JSON response the page receives."""
547
+ if wait_ms < 0:
548
+ raise PipelineError("--wait-ms must be at least 0")
549
+ own_driver = driver is None
550
+ active_driver = driver or ChromeDriver(headless=True)
551
+ if own_driver:
552
+ try:
553
+ await active_driver.start()
554
+ except Exception as exc:
555
+ raise PipelineError(f"Chrome could not be started: {exc}") from exc
556
+
557
+ raw_tasks: list[asyncio.Task[ProbeHit | None]] = []
558
+ doc_status: int | None = None
559
+ final_url = url
560
+
561
+ async def read_response(resp: Response) -> ProbeHit | None:
562
+ ct = resp.headers.get("content-type", "")
563
+ rtype = resp.request.resource_type
564
+ if "json" not in ct.lower() and rtype not in ("xhr", "fetch"):
565
+ return None
566
+ try:
567
+ body = await asyncio.wait_for(resp.body(), timeout=5.0)
568
+ except Exception:
569
+ return None
570
+ try:
571
+ data = json.loads(body)
572
+ except ValueError:
573
+ return None
574
+ shape, keys = _describe_json(data)
575
+ noise = _is_noise_url(resp.url)
576
+ return ProbeHit(
577
+ url=resp.url,
578
+ status=resp.status,
579
+ resource_type=rtype,
580
+ content_type=ct.split(";")[0].strip(),
581
+ shape=shape,
582
+ keys=keys,
583
+ is_noise=noise,
584
+ suggested_regex=suggest_url_regex(resp.url),
585
+ suggested_expect=infer_expectations(data),
586
+ sample_data=data,
587
+ )
588
+
589
+ def on_response(resp: Response) -> None:
590
+ raw_tasks.append(asyncio.create_task(read_response(resp)))
591
+
592
+ try:
593
+ async with active_driver.lease() as lease:
594
+ page = lease.page
595
+ page.set_default_timeout(15_000)
596
+ page.on("response", on_response)
597
+ try:
598
+ nav_resp = await page.goto(url, wait_until="domcontentloaded")
599
+ if nav_resp is not None:
600
+ doc_status = nav_resp.status
601
+ await page.wait_for_timeout(wait_ms)
602
+ final_url = page.url
603
+ page.remove_listener("response", on_response)
604
+ pending = list(raw_tasks)
605
+ results = await asyncio.gather(*pending, return_exceptions=True)
606
+ except BaseException:
607
+ page.remove_listener("response", on_response)
608
+ pending = list(raw_tasks)
609
+ for task in pending:
610
+ task.cancel()
611
+ if pending:
612
+ await asyncio.gather(*pending, return_exceptions=True)
613
+ raise
614
+ except Exception as exc:
615
+ raise PipelineError(f"probe failed for {url}: {exc}") from exc
616
+ finally:
617
+ if own_driver:
618
+ await active_driver.stop()
619
+
620
+ target_host = (urlsplit(url).hostname or "").lower()
621
+ hits = [item for item in results if isinstance(item, ProbeHit)]
622
+ hits.sort(key=lambda h: _hit_sort_key(h, target_host=target_host))
623
+ blocked = doc_status in (401, 403, 429, 503) and not any(
624
+ not h.is_noise and 200 <= h.status < 300 for h in hits
625
+ )
626
+ return ProbeReport(
627
+ target_url=url,
628
+ final_url=final_url,
629
+ document_status=doc_status,
630
+ blocked=blocked,
631
+ hits=hits,
632
+ )
633
+
634
+
635
+ def parse_kv_params(items: list[str]) -> dict[str, str]:
636
+ parsed: dict[str, str] = {}
637
+ for item in items:
638
+ if "=" not in item:
639
+ raise PipelineError(f"invalid --param {item!r}: expected KEY=VALUE")
640
+ key, value = item.split("=", 1)
641
+ if not PARAM_NAME.match(key):
642
+ raise PipelineError(
643
+ f"invalid parameter name {key!r}: use lowercase letters, digits, '_'"
644
+ )
645
+ parsed[key] = value
646
+ return parsed
647
+
648
+
649
+ def scaffold_recipe(
650
+ target: str,
651
+ *,
652
+ out_dir: Path,
653
+ catalog: SiteCatalog | None = None,
654
+ url: str | None = None,
655
+ url_regex: str | None = None,
656
+ session: str | None = None,
657
+ params: dict[str, str] | None = None,
658
+ probe_report: ProbeReport | None = None,
659
+ overwrite: bool = False,
660
+ ) -> tuple[Path, Recipe]:
661
+ """Generate a validated draft YAML recipe (`status: experimental` until promoted)."""
662
+ entry: SiteEntry | None = None
663
+ if "." in target and RECIPE_NAME.match(target):
664
+ site_id, endpoint = target.split(".", 1)
665
+ if catalog is not None:
666
+ entry = catalog.by_id(site_id)
667
+ elif _SITE_ID.match(target):
668
+ if catalog is None:
669
+ raise PipelineError(
670
+ f"target {target!r} looks like a site id, but no catalog was loaded; "
671
+ "pass '<site>.<endpoint>' or --catalog"
672
+ )
673
+ entry = catalog.by_id(target)
674
+ if entry is None:
675
+ raise PipelineError(f"unknown site id {target!r} in catalog")
676
+ site_id, endpoint = entry.target_recipe_name.split(".", 1)
677
+ else:
678
+ raise PipelineError(
679
+ f"invalid target {target!r}: pass '<site>.<endpoint>' or a catalog site id"
680
+ )
681
+
682
+ recipe_name = f"{site_id}.{endpoint}"
683
+ recipe_url = url or (entry.url if entry else None)
684
+ if not recipe_url:
685
+ raise PipelineError(f"no URL available for {recipe_name}; pass --url")
686
+
687
+ recipe_session = session or (entry.session if entry else "none")
688
+ param_names = sorted(placeholders(recipe_url))
689
+ sample_values: dict[str, str | int | float | bool] = {}
690
+ if entry is not None:
691
+ sample_values.update(entry.sample_params)
692
+ if params:
693
+ sample_values.update(params)
694
+
695
+ declared_params: dict[str, dict[str, Any]] = {}
696
+ check_params: dict[str, str | int | float | bool] = {}
697
+ for pname in param_names:
698
+ declared_params[pname] = {
699
+ "type": "string",
700
+ "max_length": 200,
701
+ "description": f"Parameter {pname} for {recipe_name}.",
702
+ }
703
+ check_params[pname] = sample_values.get(pname, "ai")
704
+
705
+ path_param_names = placeholders(urlsplit(recipe_url).path)
706
+ path_param_values = [str(check_params[p]) for p in path_param_names if p in check_params]
707
+
708
+ chosen_regex = url_regex
709
+ chosen_expect: list[dict[str, Any]] = [{"path": "$", "non_empty": True}]
710
+ if probe_report is not None and probe_report.candidates:
711
+ selected: ProbeHit | None = None
712
+ if url_regex is not None:
713
+ try:
714
+ explicit_pat = re.compile(url_regex)
715
+ except re.error as exc:
716
+ raise PipelineError(f"invalid --matcher regex {url_regex!r}: {exc}") from exc
717
+ for cand in probe_report.candidates:
718
+ if explicit_pat.search(cand.url) is not None:
719
+ selected = cand
720
+ break
721
+ else:
722
+ selected = probe_report.candidates[0]
723
+ chosen_regex = suggest_url_regex(
724
+ selected.url, path_param_values=path_param_values
725
+ )
726
+ if selected is not None and selected.suggested_expect:
727
+ chosen_expect = selected.suggested_expect
728
+ if not chosen_regex:
729
+ chosen_regex = suggest_url_regex(recipe_url)
730
+
731
+ payload: dict[str, Any] = {
732
+ "schema_version": 1,
733
+ "name": recipe_name,
734
+ "recipe_version": "1",
735
+ "status": "experimental",
736
+ "description": (
737
+ entry.notes
738
+ if entry and entry.notes
739
+ else f"Draft recipe for {recipe_name}; run `api-everything promote {recipe_name}`."
740
+ ),
741
+ "session": recipe_session,
742
+ "url": recipe_url,
743
+ "matcher": {"url_regex": chosen_regex},
744
+ "collect": "first",
745
+ "check": {"expect": chosen_expect},
746
+ }
747
+ if declared_params:
748
+ payload["params"] = declared_params
749
+ if check_params:
750
+ payload["check"]["params"] = check_params
751
+
752
+ try:
753
+ recipe = Recipe.model_validate(payload)
754
+ except ValidationError as exc:
755
+ raise PipelineError(f"scaffolded recipe failed validation: {exc}") from exc
756
+
757
+ dest = out_dir / site_id / f"{endpoint}.yaml"
758
+ if dest.exists() and not overwrite:
759
+ raise PipelineError(f"recipe already exists at {dest} (pass --overwrite to replace)")
760
+ header = (
761
+ f"# Draft recipe for {recipe_name} (status: experimental until promoted).\n"
762
+ f"# Verify and promote: api-everything promote {recipe_name}\n"
763
+ )
764
+ try:
765
+ dest.parent.mkdir(parents=True, exist_ok=True)
766
+ dest.write_text(header + yaml.safe_dump(payload, sort_keys=False, allow_unicode=True))
767
+ except OSError as exc:
768
+ raise PipelineError(f"cannot write recipe {dest}: {exc}") from exc
769
+ return dest, recipe
770
+
771
+
772
+ def _set_yaml_status_stable(text: str) -> str:
773
+ status_block = re.compile(
774
+ r"^status:[ \t]*(?:[>|][+-]?[ \t]*(?:\n[ \t]+[^\n]*)*|[^\n]*)",
775
+ flags=re.MULTILINE,
776
+ )
777
+ if status_block.search(text):
778
+ updated = status_block.sub("status: stable", text, count=1)
779
+ elif re.search(r"^name:\s*.*$", text, flags=re.MULTILINE):
780
+ updated = re.sub(
781
+ r"^(name:\s*.*)$", r"\1\nstatus: stable", text, count=1, flags=re.MULTILINE
782
+ )
783
+ else:
784
+ data = yaml.safe_load(text)
785
+ data["status"] = "stable"
786
+ updated = yaml.safe_dump(data, sort_keys=False, allow_unicode=True)
787
+ raw = yaml.safe_load(updated)
788
+ Recipe.model_validate(raw)
789
+ return updated
790
+
791
+
792
+ async def promote_recipe(
793
+ name: str,
794
+ *,
795
+ config: Config,
796
+ recipes_dir: Path | None = None,
797
+ dest_dir: Path | None = None,
798
+ runs: int = 5,
799
+ runner: Callable[[Recipe], Awaitable[RunResult]] | None = None,
800
+ catalog_path: Path | None = None,
801
+ ) -> tuple[Path, list[CheckResult]]:
802
+ """Run a recipe's live check `runs` consecutive times; if all pass, promote to `stable`."""
803
+ if runs < 1:
804
+ raise PipelineError("--runs must be at least 1")
805
+
806
+ catalog: SiteCatalog | None = None
807
+ if catalog_path is not None:
808
+ catalog = load_catalog(catalog_path)
809
+
810
+ source_dirs = (bundled_recipes_dir(), recipes_dir or config.recipes_dir)
811
+ try:
812
+ loaded: LoadedRecipes = load_recipes(
813
+ *source_dirs,
814
+ allow_eval=config.allow_eval,
815
+ eval_in_profiles=config.allow_eval_in_profiles,
816
+ hooks_dir=config.hooks_dir,
817
+ )
818
+ except RecipeLoadError as exc:
819
+ raise PipelineError("\n".join(exc.problems)) from exc
820
+ recipe = loaded.recipes.get(name)
821
+ if recipe is None:
822
+ raise PipelineError(f"unknown recipe {name!r}")
823
+ src_path = loaded.sources[name]
824
+ try:
825
+ src_text = src_path.read_text()
826
+ except OSError as exc:
827
+ raise PipelineError(f"cannot read recipe {src_path}: {exc}") from exc
828
+
829
+ results: list[CheckResult] = []
830
+ if runner is not None:
831
+ for _ in range(runs):
832
+ (res,) = await check_recipes([recipe], runner)
833
+ results.append(res)
834
+ if not res.ok:
835
+ return src_path, results
836
+ else:
837
+ import httpx
838
+
839
+ base_url = daemon_base_url(config)
840
+ use_daemon = False
841
+ can_use_daemon = (
842
+ recipes_dir is None
843
+ and config.recipes_dir is None
844
+ and src_path.is_relative_to(bundled_recipes_dir())
845
+ )
846
+ if can_use_daemon:
847
+ async with httpx.AsyncClient() as client:
848
+ if await daemon_is_running(client, base_url):
849
+ use_daemon = True
850
+ token = config.token.get_secret_value() if config.token else None
851
+ d_runner = make_daemon_runner(client, base_url, token)
852
+ for _ in range(runs):
853
+ (res,) = await check_recipes([recipe], d_runner)
854
+ results.append(res)
855
+ if not res.ok:
856
+ return src_path, results
857
+ if not use_daemon:
858
+ pool = Pool(config)
859
+ hooks = load_hooks(config.hooks_dir, loaded.recipes.values())
860
+ await pool.start()
861
+ try:
862
+
863
+ async def pool_run(target_recipe: Recipe) -> RunResult:
864
+ return await pool.run(
865
+ target_recipe,
866
+ target_recipe.check.params,
867
+ hook=hooks.get(target_recipe.name),
868
+ )
869
+
870
+ for _ in range(runs):
871
+ (res,) = await check_recipes([recipe], pool_run)
872
+ results.append(res)
873
+ if not res.ok:
874
+ return src_path, results
875
+ finally:
876
+ await pool.stop()
877
+
878
+ try:
879
+ current_text = src_path.read_text()
880
+ except OSError as exc:
881
+ raise PipelineError(f"cannot read recipe {src_path}: {exc}") from exc
882
+ if current_text != src_text:
883
+ raise PipelineError(
884
+ f"recipe {src_path} changed while checks were running; rerun promote {name}"
885
+ )
886
+
887
+ updated_text = _set_yaml_status_stable(src_text)
888
+ site, endpoint = name.split(".", 1)
889
+ if dest_dir is not None:
890
+ target_path = dest_dir / site / f"{endpoint}.yaml"
891
+ else:
892
+ target_path = src_path
893
+ try:
894
+ target_path.parent.mkdir(parents=True, exist_ok=True)
895
+ target_path.write_text(updated_text)
896
+ except OSError as exc:
897
+ raise PipelineError(f"cannot write promoted recipe {target_path}: {exc}") from exc
898
+
899
+ if catalog is not None and catalog_path is not None:
900
+ entry = catalog.by_id(site)
901
+ if entry is not None:
902
+ entry.status = "stable"
903
+ entry.recipe = name
904
+ try:
905
+ save_catalog(catalog, catalog_path)
906
+ doc_path = default_catalog_doc_path(catalog_path)
907
+ if doc_path.parent.is_dir():
908
+ doc_path.write_text(render_catalog_markdown(catalog))
909
+ except OSError as exc:
910
+ raise PipelineError(f"cannot update catalog {catalog_path}: {exc}") from exc
911
+
912
+ return target_path, results
913
+
914
+
915
+ __all__ = [
916
+ "PipelineError",
917
+ "ProbeHit",
918
+ "ProbeReport",
919
+ "RunError",
920
+ "SiteCatalog",
921
+ "SiteEntry",
922
+ "default_catalog_doc_path",
923
+ "default_catalog_path",
924
+ "infer_expectations",
925
+ "load_catalog",
926
+ "parse_kv_params",
927
+ "probe_target",
928
+ "promote_recipe",
929
+ "render_catalog_markdown",
930
+ "resolve_probe_url",
931
+ "save_catalog",
932
+ "scaffold_recipe",
933
+ "suggest_url_regex",
934
+ ]