intentumdiff-python 0.0.1__py3-none-win_amd64.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 (165) hide show
  1. intentumdiff/__init__.py +134 -0
  2. intentumdiff/_differ_gate.py +210 -0
  3. intentumdiff/_differ_presentation.py +786 -0
  4. intentumdiff/_differ_runtime.py +320 -0
  5. intentumdiff/analysis/__init__.py +1 -0
  6. intentumdiff/analysis/compile_commands.py +151 -0
  7. intentumdiff/analysis/cross_file.py +71 -0
  8. intentumdiff/analysis/diagnostics.py +309 -0
  9. intentumdiff/analysis/guardrail_reports.py +254 -0
  10. intentumdiff/analysis/guardrails.py +318 -0
  11. intentumdiff/analysis/invariances.py +1207 -0
  12. intentumdiff/analysis/keyed_profiles.py +25 -0
  13. intentumdiff/analysis/resource_profiles.py +14 -0
  14. intentumdiff/analysis/schema_resolver.py +816 -0
  15. intentumdiff/analysis/text_review.py +46 -0
  16. intentumdiff/analysis/user_schemas.py +430 -0
  17. intentumdiff/assets.py +45 -0
  18. intentumdiff/cache/__init__.py +37 -0
  19. intentumdiff/cache/duckdb_store.py +98 -0
  20. intentumdiff/cache/sqlite_store.py +149 -0
  21. intentumdiff/cache/store.py +190 -0
  22. intentumdiff/cli/__init__.py +199 -0
  23. intentumdiff/cli/_commands.py +2141 -0
  24. intentumdiff/cli/_parser.py +1061 -0
  25. intentumdiff/cli/_shared.py +644 -0
  26. intentumdiff/content_type.py +59 -0
  27. intentumdiff/core/__init__.py +1 -0
  28. intentumdiff/core/commit_differ.py +599 -0
  29. intentumdiff/core/config.py +51 -0
  30. intentumdiff/core/cst_serializer.py +101 -0
  31. intentumdiff/core/diffignore.py +87 -0
  32. intentumdiff/core/index.py +189 -0
  33. intentumdiff/core/indexer.py +792 -0
  34. intentumdiff/core/models.py +837 -0
  35. intentumdiff/differ.py +2195 -0
  36. intentumdiff/github_app.py +287 -0
  37. intentumdiff/intentumdiff_rust_core/__init__.py +7 -0
  38. intentumdiff/intentumdiff_rust_core/ffi.py +8 -0
  39. intentumdiff/intentumdiff_rust_core/intentumdiff_rust_core.dll +0 -0
  40. intentumdiff/invariances/__init__.py +2 -0
  41. intentumdiff/invariances/rules.schema.json +283 -0
  42. intentumdiff/invariances/rules.yaml +349 -0
  43. intentumdiff/live_server.py +1314 -0
  44. intentumdiff/lsp/__init__.py +67 -0
  45. intentumdiff/lsp/client.py +544 -0
  46. intentumdiff/lsp/config.py +96 -0
  47. intentumdiff/lsp/enricher.py +227 -0
  48. intentumdiff/lsp/exceptions.py +27 -0
  49. intentumdiff/lsp/launcher.py +273 -0
  50. intentumdiff/lsp/servers.py +356 -0
  51. intentumdiff/lsp_server/__init__.py +14 -0
  52. intentumdiff/lsp_server/_codelens.py +67 -0
  53. intentumdiff/lsp_server/_diagnostics.py +62 -0
  54. intentumdiff/lsp_server/_handlers.py +175 -0
  55. intentumdiff/lsp_server/server.py +205 -0
  56. intentumdiff/plugins/__init__.py +1 -0
  57. intentumdiff/plugins/adapter.py +397 -0
  58. intentumdiff/plugins/builtins.py +323 -0
  59. intentumdiff/plugins/exceptions.py +93 -0
  60. intentumdiff/plugins/hub.py +1155 -0
  61. intentumdiff/plugins/language_metadata.py +250 -0
  62. intentumdiff/plugins/loader.py +1252 -0
  63. intentumdiff/plugins/registry.py +1079 -0
  64. intentumdiff/plugins/registry.schema.json +99 -0
  65. intentumdiff/plugins/registry_schema.py +280 -0
  66. intentumdiff/plugins/wit/plugin.wit +351 -0
  67. intentumdiff/rust_core.py +2370 -0
  68. intentumdiff/serve/__init__.py +19 -0
  69. intentumdiff/serve/_app.py +485 -0
  70. intentumdiff/serve/_static/index.html +326 -0
  71. intentumdiff/serve/_static/playground.js +567 -0
  72. intentumdiff/sources/__init__.py +1 -0
  73. intentumdiff/sources/base.py +28 -0
  74. intentumdiff/sources/file_source.py +48 -0
  75. intentumdiff/sources/git_source.py +375 -0
  76. intentumdiff/sources/live_buffer_source.py +113 -0
  77. intentumdiff/sources/patch_source.py +126 -0
  78. intentumdiff/sources/string_source.py +44 -0
  79. intentumdiff/testing.py +165 -0
  80. intentumdiff/vcs/__init__.py +37 -0
  81. intentumdiff/vcs/_safe_path.py +50 -0
  82. intentumdiff/vcs/base.py +136 -0
  83. intentumdiff/vcs/git_backend.py +97 -0
  84. intentumdiff/vcs/git_cli.py +100 -0
  85. intentumdiff/vcs/hg_backend.py +94 -0
  86. intentumdiff/vcs/perforce_backend.py +109 -0
  87. intentumdiff/vcs/svn_backend.py +105 -0
  88. intentumdiff/wasm/.gitkeep +2 -0
  89. intentumdiff/wasm/abap_parser.wasm +0 -0
  90. intentumdiff/wasm/adf_parser.wasm +0 -0
  91. intentumdiff/wasm/asciidoc_parser.wasm +0 -0
  92. intentumdiff/wasm/asm_parser.wasm +0 -0
  93. intentumdiff/wasm/assemblyscript_parser.wasm +0 -0
  94. intentumdiff/wasm/astro_parser.wasm +0 -0
  95. intentumdiff/wasm/bash_parser.wasm +0 -0
  96. intentumdiff/wasm/clojure_parser.wasm +0 -0
  97. intentumdiff/wasm/cmake_parser.wasm +0 -0
  98. intentumdiff/wasm/cpp_parser.wasm +0 -0
  99. intentumdiff/wasm/csharp_parser.wasm +0 -0
  100. intentumdiff/wasm/css_parser.wasm +0 -0
  101. intentumdiff/wasm/dart_parser.wasm +0 -0
  102. intentumdiff/wasm/databricks_parser.wasm +0 -0
  103. intentumdiff/wasm/dax_parser.wasm +0 -0
  104. intentumdiff/wasm/delphi_parser.wasm +0 -0
  105. intentumdiff/wasm/dockerfile_parser.wasm +0 -0
  106. intentumdiff/wasm/elixir_parser.wasm +0 -0
  107. intentumdiff/wasm/freebasic_parser.wasm +0 -0
  108. intentumdiff/wasm/generic_parser.wasm +0 -0
  109. intentumdiff/wasm/gitignore_parser.wasm +0 -0
  110. intentumdiff/wasm/go_parser.wasm +0 -0
  111. intentumdiff/wasm/gomod_parser.wasm +0 -0
  112. intentumdiff/wasm/graphql_parser.wasm +0 -0
  113. intentumdiff/wasm/groovy_parser.wasm +0 -0
  114. intentumdiff/wasm/haskell_parser.wasm +0 -0
  115. intentumdiff/wasm/html_parser.wasm +0 -0
  116. intentumdiff/wasm/ini_parser.wasm +0 -0
  117. intentumdiff/wasm/java_parser.wasm +0 -0
  118. intentumdiff/wasm/js_ts_parser.wasm +0 -0
  119. intentumdiff/wasm/json_parser.wasm +0 -0
  120. intentumdiff/wasm/kotlin_parser.wasm +0 -0
  121. intentumdiff/wasm/latex_parser.wasm +0 -0
  122. intentumdiff/wasm/lua_parser.wasm +0 -0
  123. intentumdiff/wasm/make_parser.wasm +0 -0
  124. intentumdiff/wasm/markdown_parser.wasm +0 -0
  125. intentumdiff/wasm/mdx_parser.wasm +0 -0
  126. intentumdiff/wasm/ocaml_parser.wasm +0 -0
  127. intentumdiff/wasm/odin_parser.wasm +0 -0
  128. intentumdiff/wasm/parser_manifest.json +590 -0
  129. intentumdiff/wasm/perl_parser.wasm +0 -0
  130. intentumdiff/wasm/php_parser.wasm +0 -0
  131. intentumdiff/wasm/plsql_parser.wasm +0 -0
  132. intentumdiff/wasm/po_parser.wasm +0 -0
  133. intentumdiff/wasm/postscript_parser.wasm +0 -0
  134. intentumdiff/wasm/powershell_parser.wasm +0 -0
  135. intentumdiff/wasm/proto_parser.wasm +0 -0
  136. intentumdiff/wasm/puppet_parser.wasm +0 -0
  137. intentumdiff/wasm/python_parser.wasm +0 -0
  138. intentumdiff/wasm/qsharp_parser.wasm +0 -0
  139. intentumdiff/wasm/r_parser.wasm +0 -0
  140. intentumdiff/wasm/reasonml_parser.wasm +0 -0
  141. intentumdiff/wasm/ruby_parser.wasm +0 -0
  142. intentumdiff/wasm/rust_parser.wasm +0 -0
  143. intentumdiff/wasm/sas_parser.wasm +0 -0
  144. intentumdiff/wasm/scala_parser.wasm +0 -0
  145. intentumdiff/wasm/scss_parser.wasm +0 -0
  146. intentumdiff/wasm/sql_parser.wasm +0 -0
  147. intentumdiff/wasm/squirrel_parser.wasm +0 -0
  148. intentumdiff/wasm/svelte_parser.wasm +0 -0
  149. intentumdiff/wasm/swift_parser.wasm +0 -0
  150. intentumdiff/wasm/terraform_parser.wasm +0 -0
  151. intentumdiff/wasm/toml_parser.wasm +0 -0
  152. intentumdiff/wasm/tsql_parser.wasm +0 -0
  153. intentumdiff/wasm/vbnet_parser.wasm +0 -0
  154. intentumdiff/wasm/vue_parser.wasm +0 -0
  155. intentumdiff/wasm/wat_parser.wasm +0 -0
  156. intentumdiff/wasm/xml_parser.wasm +0 -0
  157. intentumdiff/wasm/yaml_parser.wasm +0 -0
  158. intentumdiff/wasm/zig_parser.wasm +0 -0
  159. intentumdiff/watcher.py +259 -0
  160. intentumdiff_python-0.0.1.dist-info/METADATA +112 -0
  161. intentumdiff_python-0.0.1.dist-info/RECORD +165 -0
  162. intentumdiff_python-0.0.1.dist-info/WHEEL +4 -0
  163. intentumdiff_python-0.0.1.dist-info/entry_points.txt +80 -0
  164. intentumdiff_python-0.0.1.dist-info/licenses/LICENSE +21 -0
  165. intentumdiff_python-0.0.1.dist-info/sboms/intentumdiff-rust-core.cyclonedx.json +10968 -0
@@ -0,0 +1,19 @@
1
+ """intentumdiff.serve
2
+ ~~~~~~~~~~~~~~~~~~~~~~~
3
+
4
+ HTTP playground and public API for IntentumDiff.
5
+
6
+ Start with::
7
+
8
+ intentumdiff serve [--host HOST] [--port PORT]
9
+
10
+ or create the ASGI app programmatically through the compatibility
11
+ implementation package::
12
+
13
+ from intentumdiff.serve import create_app
14
+ app = create_app()
15
+ """
16
+
17
+ from intentumdiff.serve._app import create_app
18
+
19
+ __all__ = ["create_app"]
@@ -0,0 +1,485 @@
1
+ """intentumdiff.serve._app
2
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3
+
4
+ FastAPI application for the Online Diff Playground and public API.
5
+
6
+ Endpoints
7
+ ---------
8
+ GET / — Monaco-editor web UI (HTML)
9
+ GET /languages — JSON list of all supported language IDs
10
+ POST /diff — Compute semantic diff between two code strings
11
+ GET /api/docs — OpenAPI / Swagger UI (auto-generated by FastAPI)
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import asyncio
17
+ import re
18
+ from pathlib import Path
19
+ from typing import Annotated, Any
20
+
21
+ from fastapi import FastAPI, HTTPException, Request, Response
22
+ from fastapi.middleware.cors import CORSMiddleware
23
+ from fastapi.responses import FileResponse, HTMLResponse
24
+ from fastapi.staticfiles import StaticFiles
25
+ from pydantic import BaseModel, ConfigDict, Field, field_validator
26
+
27
+ from intentumdiff import DiffConfig, SemanticDiffer, StringSource
28
+ from intentumdiff.plugins.exceptions import GrammarNotInstalledError, PluginNotFoundError
29
+
30
+ _MAX_CONTENT_BYTES = 512 * 1024 # 512 KB per pane
31
+ _MAX_REQUEST_BODY_BYTES = 8 * 1024 * 1024 # 8 MB total envelope
32
+ _HTML_PATH = Path(__file__).parent / "_static" / "index.html"
33
+ _STATIC_DIR = Path(__file__).parent / "_static"
34
+ _VENDOR_DIR = _STATIC_DIR / "vendor"
35
+
36
+ # Content-Security-Policy for the playground.
37
+ # worker-src 'self' blob: is required for Monaco web workers.
38
+ # style-src 'unsafe-inline' is required for Monaco inline styles.
39
+ # When Monaco is fully vendored no external origins are needed.
40
+ _CSP = (
41
+ "default-src 'self'; "
42
+ "script-src 'self'; "
43
+ "worker-src 'self' blob:; "
44
+ "connect-src 'self'; "
45
+ "img-src 'self' data:; "
46
+ "style-src 'self' 'unsafe-inline';"
47
+ )
48
+
49
+ # Language IDs: start with alphanumeric, then alphanumeric/hyphen/dot/underscore, max 64 chars.
50
+ _LANG_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,63}$")
51
+ _PLUGIN_ID_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,127}$")
52
+ _MAX_CANDIDATES = 50
53
+ _MAX_CANDIDATE_BYTES = 64
54
+
55
+
56
+ def _request_body_too_large_response() -> Response:
57
+ limit_mb = _MAX_REQUEST_BODY_BYTES // (1024 * 1024)
58
+ return Response(
59
+ f'{{"detail": "Request body too large (max {limit_mb} MB)"}}',
60
+ status_code=413,
61
+ media_type="application/json",
62
+ )
63
+
64
+
65
+ # ---------------------------------------------------------------------------
66
+ # Request / Response models
67
+ # ---------------------------------------------------------------------------
68
+
69
+
70
+ class DiffRequest(BaseModel):
71
+ """Body for POST /diff."""
72
+
73
+ model_config = ConfigDict(extra="forbid")
74
+
75
+ old: Annotated[str, Field(description="Old file content (\u2264 512 KB)")]
76
+ new: Annotated[str, Field(description="New file content (\u2264 512 KB)")]
77
+ filename: str = Field(
78
+ default="code.py",
79
+ description="Filename used for language auto-detection (no path separators).",
80
+ )
81
+ language: str | None = Field(
82
+ default=None,
83
+ description="Explicit language hint — overrides filename-based detection.",
84
+ )
85
+
86
+ plugin_id: str | None = Field(
87
+ default=None,
88
+ description="Opaque parser plugin ID from GET /language-info.",
89
+ )
90
+
91
+ @field_validator("language")
92
+ @classmethod
93
+ def _validate_language(cls, v: str | None) -> str | None:
94
+ if v is not None and not _LANG_RE.fullmatch(v):
95
+ raise ValueError(
96
+ "language must be 1-64 alphanumeric/hyphen/dot/underscore characters"
97
+ )
98
+ return v
99
+
100
+ @field_validator("plugin_id")
101
+ @classmethod
102
+ def _validate_plugin_id(cls, v: str | None) -> str | None:
103
+ if v is not None and not _PLUGIN_ID_RE.fullmatch(v):
104
+ raise ValueError(
105
+ "plugin_id must be 1-128 alphanumeric/hyphen/dot/underscore/colon characters"
106
+ )
107
+ return v
108
+
109
+ @field_validator("old", "new")
110
+ @classmethod
111
+ def _limit_size(cls, v: str) -> str:
112
+ if len(v.encode()) > _MAX_CONTENT_BYTES:
113
+ raise ValueError(
114
+ f"Content exceeds {_MAX_CONTENT_BYTES // 1024} KB limit"
115
+ )
116
+ return v
117
+
118
+ @field_validator("filename")
119
+ @classmethod
120
+ def _no_traversal(cls, v: str) -> str:
121
+ if ".." in v or "/" in v or "\\" in v:
122
+ raise ValueError(
123
+ "filename must be a bare name with no path separators or traversal"
124
+ )
125
+ return v
126
+
127
+
128
+ class DetectRequest(BaseModel):
129
+ """Body for POST /detect."""
130
+
131
+ model_config = ConfigDict(extra="forbid")
132
+
133
+ content: Annotated[str, Field(description="Code snippet to analyse (≤ 512 KB)")]
134
+ candidates: list[str] | None = Field(
135
+ default=None,
136
+ description="Optional shortlist of language IDs from a client-side heuristic.",
137
+ )
138
+ preferred_plugins: dict[str, str] | None = Field(
139
+ default=None,
140
+ description="Optional language -> plugin ID preferences from GET /language-info.",
141
+ )
142
+ plugin_id: str | None = Field(
143
+ default=None,
144
+ description="Optional parser plugin ID from GET /language-info.",
145
+ )
146
+
147
+ @field_validator("content")
148
+ @classmethod
149
+ def _limit_size(cls, v: str) -> str:
150
+ if len(v.encode()) > _MAX_CONTENT_BYTES:
151
+ raise ValueError(
152
+ f"Content exceeds {_MAX_CONTENT_BYTES // 1024} KB limit"
153
+ )
154
+ return v
155
+
156
+ @field_validator("candidates")
157
+ @classmethod
158
+ def _validate_candidates(cls, v: list[str] | None) -> list[str] | None:
159
+ if v is None:
160
+ return v
161
+ if len(v) > _MAX_CANDIDATES:
162
+ raise ValueError(f"candidates list exceeds {_MAX_CANDIDATES} items")
163
+ for item in v:
164
+ if len(item.encode()) > _MAX_CANDIDATE_BYTES:
165
+ raise ValueError(
166
+ f"candidate item exceeds {_MAX_CANDIDATE_BYTES} bytes: {item!r}"
167
+ )
168
+ if not _LANG_RE.fullmatch(item):
169
+ raise ValueError(
170
+ f"invalid candidate language ID {item!r}: must match "
171
+ r"^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,63}$"
172
+ )
173
+ return v
174
+
175
+ @field_validator("preferred_plugins")
176
+ @classmethod
177
+ def _validate_preferred_plugins(
178
+ cls, v: dict[str, str] | None
179
+ ) -> dict[str, str] | None:
180
+ if v is None:
181
+ return v
182
+ if len(v) > _MAX_CANDIDATES:
183
+ raise ValueError(f"preferred_plugins exceeds {_MAX_CANDIDATES} items")
184
+ for language, plugin_id in v.items():
185
+ if not _LANG_RE.fullmatch(language):
186
+ raise ValueError(f"invalid preferred plugin language ID {language!r}")
187
+ if not _PLUGIN_ID_RE.fullmatch(plugin_id):
188
+ raise ValueError(f"invalid preferred plugin ID {plugin_id!r}")
189
+ return v
190
+
191
+ @field_validator("plugin_id")
192
+ @classmethod
193
+ def _validate_plugin_id(cls, v: str | None) -> str | None:
194
+ if v is not None and not _PLUGIN_ID_RE.fullmatch(v):
195
+ raise ValueError(f"invalid plugin ID {v!r}")
196
+ return v
197
+
198
+
199
+ def _supported_languages(differ: Any) -> list[str]:
200
+ """Return supported language IDs for the playground picker."""
201
+ provider = getattr(differ, "supported_languages", None)
202
+ if callable(provider):
203
+ result = provider()
204
+ if isinstance(result, list):
205
+ return sorted({lang for lang in result if isinstance(lang, str)})
206
+ return sorted(
207
+ {lang for parser in differ._registry.parsers for lang in parser.language_ids}
208
+ )
209
+
210
+
211
+ def _language_info(differ: Any) -> list[dict[str, Any]]:
212
+ """Return rich language metadata for the playground."""
213
+ provider = getattr(differ, "language_info", None)
214
+ if callable(provider):
215
+ result = provider()
216
+ if isinstance(result, list):
217
+ return [
218
+ item.model_dump(by_alias=True) if hasattr(item, "model_dump") else item
219
+ for item in result
220
+ if isinstance(item, dict) or hasattr(item, "model_dump")
221
+ ]
222
+ return [
223
+ {
224
+ "language": lang,
225
+ "selectedPluginId": lang,
226
+ "plugins": [
227
+ {
228
+ "languageId": lang,
229
+ "languageName": lang,
230
+ "languageShortName": lang,
231
+ "monacoLanguage": "plaintext",
232
+ "defaultFilename": f"code.{lang}",
233
+ "languageFileExtensions": [],
234
+ "author": "",
235
+ "pluginVersion": "",
236
+ "lastUpdated": "",
237
+ "pluginId": lang,
238
+ "grammarId": lang,
239
+ "priority": 0,
240
+ "isTrusted": False,
241
+ "provenance": "",
242
+ }
243
+ ],
244
+ }
245
+ for lang in _supported_languages(differ)
246
+ ]
247
+
248
+
249
+ # ---------------------------------------------------------------------------
250
+ # App factory
251
+ # ---------------------------------------------------------------------------
252
+
253
+
254
+ def create_app(
255
+ config: DiffConfig | None = None,
256
+ differ: Any | None = None, # SemanticDiffer | test mock
257
+ cors_origins: list[str] | None = None,
258
+ ) -> FastAPI:
259
+ """Create and return the FastAPI playground application.
260
+
261
+ Parameters
262
+ ----------
263
+ config:
264
+ Optional :class:`~intentumdiff.DiffConfig`. Ignored when *differ*
265
+ is supplied directly (useful for tests).
266
+ differ:
267
+ Optional pre-built :class:`~intentumdiff.SemanticDiffer` (or any
268
+ object with a ``.diff(source)`` method). When ``None`` a fresh
269
+ instance is created from *config*.
270
+ cors_origins:
271
+ Explicit list of allowed CORS origins. When ``None`` (default) no
272
+ CORS middleware is added — the API is not usable cross-origin.
273
+ Pass ``["*"]`` only in development environments behind a firewall.
274
+ Never use ``["*"]`` in production facing untrusted networks.
275
+ """
276
+ cfg = config or DiffConfig()
277
+ _differ: Any = differ if differ is not None else SemanticDiffer(cfg)
278
+ _html = _HTML_PATH.read_text(encoding="utf-8")
279
+
280
+ # Semaphore to bound concurrent diff/detect computations.
281
+ _sem = asyncio.Semaphore(8)
282
+
283
+ app = FastAPI(
284
+ title="IntentumDiff Playground",
285
+ description=(
286
+ "Semantic code diff API. "
287
+ "`POST /diff` with `{old, new, language}` → SemanticDiff JSON."
288
+ ),
289
+ version="1.0.0",
290
+ docs_url="/api/docs",
291
+ redoc_url=None,
292
+ )
293
+
294
+ @app.middleware("http")
295
+ async def _limit_body_size(request: Request, call_next): # type: ignore[return]
296
+ cl = request.headers.get("content-length")
297
+ if cl is not None:
298
+ try:
299
+ if int(cl) > _MAX_REQUEST_BODY_BYTES:
300
+ return _request_body_too_large_response()
301
+ except ValueError:
302
+ pass
303
+
304
+ chunks: list[bytes] = []
305
+ total = 0
306
+ async for chunk in request.stream():
307
+ total += len(chunk)
308
+ if total > _MAX_REQUEST_BODY_BYTES:
309
+ return _request_body_too_large_response()
310
+ chunks.append(chunk)
311
+ body = b"".join(chunks)
312
+ sent = False
313
+
314
+ async def receive(): # type: ignore[no-untyped-def]
315
+ nonlocal sent
316
+ if sent:
317
+ return {"type": "http.request", "body": b"", "more_body": False}
318
+ sent = True
319
+ return {"type": "http.request", "body": body, "more_body": False}
320
+
321
+ request._body = body # type: ignore[attr-defined]
322
+ request._receive = receive # type: ignore[attr-defined]
323
+ return await call_next(request)
324
+
325
+ if cors_origins is not None:
326
+ app.add_middleware(
327
+ CORSMiddleware,
328
+ allow_origins=cors_origins,
329
+ allow_methods=["GET", "POST"],
330
+ allow_headers=["Content-Type", "Accept"],
331
+ max_age=600,
332
+ )
333
+
334
+ # Mount vendored static assets (Monaco, etc.).
335
+ # The vendor directory is optional at import time — it is populated by
336
+ # running ``python scripts/vendor_monaco.py`` before serving.
337
+ if _VENDOR_DIR.exists():
338
+ app.mount(
339
+ "/static/vendor",
340
+ StaticFiles(directory=str(_VENDOR_DIR)),
341
+ name="vendor",
342
+ )
343
+
344
+ # ── Routes ───────────────────────────────────────────────────────────────
345
+
346
+ @app.get("/", response_class=HTMLResponse, include_in_schema=False)
347
+ async def index() -> HTMLResponse:
348
+ return HTMLResponse(content=_html, headers={"Content-Security-Policy": _CSP})
349
+
350
+ @app.get("/static/playground.js", include_in_schema=False)
351
+ async def playground_script() -> FileResponse:
352
+ return FileResponse(
353
+ _STATIC_DIR / "playground.js",
354
+ media_type="application/javascript",
355
+ )
356
+
357
+ @app.get("/languages", summary="List supported languages")
358
+ async def languages() -> dict[str, list[str]]:
359
+ """Return all language IDs accepted by the ``/diff`` endpoint."""
360
+ return {"languages": _supported_languages(_differ)}
361
+
362
+ @app.get("/language-info", summary="List language and parser plugin metadata")
363
+ async def language_info() -> dict[str, list[dict[str, Any]]]:
364
+ """Return grouped language/plugin metadata for the playground UI."""
365
+ return {"languages": _language_info(_differ)}
366
+
367
+ @app.post("/diff", summary="Compute semantic diff")
368
+ async def diff(req: DiffRequest) -> Response:
369
+ """Compute a semantic diff between two code strings.
370
+
371
+ Returns a **SemanticDiff** JSON object. The response is stateless —
372
+ no submitted code is stored.
373
+ """
374
+ try:
375
+ async with _sem:
376
+ if req.plugin_id:
377
+ result = await asyncio.to_thread(
378
+ _differ.diff_strings,
379
+ req.old,
380
+ req.new,
381
+ req.filename,
382
+ req.language,
383
+ parser_plugin_id=req.plugin_id,
384
+ )
385
+ else:
386
+ source = StringSource(
387
+ req.old,
388
+ req.new,
389
+ filename=req.filename,
390
+ language_hint=req.language,
391
+ )
392
+ result = await asyncio.to_thread(_differ.diff, source)
393
+ except PluginNotFoundError as exc:
394
+ raise HTTPException(
395
+ status_code=422,
396
+ detail=f"Unknown language: {exc}",
397
+ ) from exc
398
+ except GrammarNotInstalledError as exc:
399
+ raise HTTPException(
400
+ status_code=422,
401
+ detail=str(exc),
402
+ ) from exc
403
+ return Response(
404
+ content=result.model_dump_json(),
405
+ media_type="application/json",
406
+ )
407
+
408
+ # ── Detect endpoint ───────────────────────────────────────────────────
409
+
410
+ @app.post("/detect", summary="Detect language from content")
411
+ async def detect(req: DetectRequest) -> dict:
412
+ """Return ranked language candidates detected by the registered parsers.
413
+
414
+ Each parser's own Wasm ``detect-language`` function is consulted — no
415
+ regex heuristics in Python. The response is stateless.
416
+ """
417
+ try:
418
+ async with _sem:
419
+ if req.plugin_id:
420
+ results = await asyncio.to_thread(
421
+ _differ.detect_all,
422
+ req.content,
423
+ req.candidates,
424
+ req.preferred_plugins,
425
+ req.plugin_id,
426
+ )
427
+ elif req.preferred_plugins:
428
+ results = await asyncio.to_thread(
429
+ _differ.detect_all,
430
+ req.content,
431
+ req.candidates,
432
+ req.preferred_plugins,
433
+ )
434
+ else:
435
+ results = await asyncio.to_thread(
436
+ _differ.detect_all, req.content, req.candidates
437
+ )
438
+ except PluginNotFoundError as exc:
439
+ raise HTTPException(
440
+ status_code=422,
441
+ detail=f"Unknown parser plugin: {exc}",
442
+ ) from exc
443
+ top = results[0].language if results else None
444
+ return {
445
+ "language": top,
446
+ "candidates": [
447
+ {"language": r.language, "confidence": r.confidence}
448
+ for r in results[:3]
449
+ ],
450
+ }
451
+
452
+ @app.get("/example/{language}", summary="Fetch demo old/new example for a language")
453
+ async def example(language: str, plugin_id: str | None = None) -> dict:
454
+ """Return the ``old`` and ``new`` demo snippets for *language*.
455
+
456
+ Each parser plugin supplies its own example via the WIT
457
+ ``playground-example`` function. Returns ``{"old": null, "new": null}``
458
+ for unknown languages so the client can gracefully clear the editors.
459
+ """
460
+ if not _LANG_RE.fullmatch(language):
461
+ raise HTTPException(
462
+ status_code=422,
463
+ detail="Invalid language identifier. "
464
+ "Must be 1-64 alphanumeric/hyphen/dot/underscore characters.",
465
+ )
466
+ if plugin_id is not None and not _PLUGIN_ID_RE.fullmatch(plugin_id):
467
+ raise HTTPException(
468
+ status_code=422,
469
+ detail="Invalid plugin identifier.",
470
+ )
471
+ try:
472
+ if plugin_id:
473
+ ex = await asyncio.to_thread(_differ.playground_example, language, plugin_id)
474
+ else:
475
+ ex = await asyncio.to_thread(_differ.playground_example, language)
476
+ except PluginNotFoundError as exc:
477
+ raise HTTPException(
478
+ status_code=422,
479
+ detail=f"Unknown parser plugin: {exc}",
480
+ ) from exc
481
+ if ex is None:
482
+ return {"old": None, "new": None}
483
+ return {"old": ex["old"], "new": ex["new"]}
484
+
485
+ return app