{
  "version": 1,
  "format": "json",
  "kind": "generation",
  "output": "<root>/models.py",
  "files": [
    {
      "path": "models.py",
      "content": "# -*- coding: latin-1 -*-\n# Café\n\nfrom __future__ import annotations\n\nfrom pydantic import BaseModel, RootModel\n\n\nclass Item(BaseModel):\n    id: int | None = None\n\n\nclass ItemsGetResponse(RootModel[list[Item]]):\n    root: list[Item]\n"
    },
    {
      "path": "server/README.md",
      "content": "# Café server\n\nGenerated documentation in UTF-8.\n"
    },
    {
      "path": "server/__init__.py",
      "content": "# -*- coding: latin-1 -*-\n# Café\n\n\"\"\"FastAPI server package server, generated by datamodel-code-generator.\"\"\"\n\nfrom ._runtime.server.responses import HTTPResult\nfrom .application import (\n    OperationDependencies,\n    build_router,\n    create_app,\n    serve_source_openapi,\n    validation_error_handler,\n)\n\n__all__ = [\n    \"HTTPResult\",\n    \"OperationDependencies\",\n    \"build_router\",\n    \"create_app\",\n    \"serve_source_openapi\",\n    \"validation_error_handler\",\n]\n"
    },
    {
      "path": "server/_generated/__init__.py",
      "content": "# -*- coding: latin-1 -*-\n# Café\n\n\"\"\"Generated plans of this package.\"\"\"\n"
    },
    {
      "path": "server/_generated/contract.py",
      "content": "# -*- coding: latin-1 -*-\n# Café\n\n\"\"\"Operation plans of this package; regenerate them instead of editing.\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Sequence\nfrom typing import Final, TypedDict\n\nimport models\nfrom fastapi import params\n\nfrom .._runtime.server.responses import Declared, OperationResponses\n\nOperationDependencies = TypedDict(\n    'OperationDependencies',\n    {\n        'list_items': Sequence[params.Depends],\n        'list_users': Sequence[params.Depends],\n    },\n    total=False,\n)\n\n\nclass ListItems:\n    \"\"\"Plans of the list_items operation.\"\"\"\n\n    RESPONSES: Final = OperationResponses(\n        responses={'200': Declared(media_type='application/json', model=models.ItemsGetResponse)},\n    )\n\n\nclass ListUsers:\n    \"\"\"Plans of the list_users operation.\"\"\"\n\n    RESPONSES: Final = OperationResponses(\n        responses={'204': Declared()},\n        primary=204,\n    )\n"
    },
    {
      "path": "server/_generated/openapi.json",
      "content": "{\n \"openapi\": \"3.0.3\",\n \"info\": {\n  \"title\": \"Inline\",\n  \"version\": \"1.0.0\"\n },\n \"paths\": {\n  \"/items\": {\n   \"get\": {\n    \"operationId\": \"listItems\",\n    \"tags\": [\n     \"items\"\n    ],\n    \"responses\": {\n     \"200\": {\n      \"description\": \"Items\",\n      \"content\": {\n       \"application/json\": {\n        \"schema\": {\n         \"type\": \"array\",\n         \"items\": {\n          \"$ref\": \"#/components/schemas/Item\"\n         }\n        }\n       }\n      }\n     }\n    }\n   }\n  },\n  \"/users\": {\n   \"get\": {\n    \"operationId\": \"listUsers\",\n    \"tags\": [\n     \"users\"\n    ],\n    \"responses\": {\n     \"204\": {\n      \"description\": \"None\"\n     }\n    }\n   }\n  }\n },\n \"components\": {\n  \"schemas\": {\n   \"Item\": {\n    \"type\": \"object\",\n    \"properties\": {\n     \"id\": {\n      \"type\": \"integer\"\n     }\n    }\n   }\n  }\n }\n}\n"
    },
    {
      "path": "server/_generated/openapi.py",
      "content": "# -*- coding: latin-1 -*-\n# Café\n\n\"\"\"Serve the source OpenAPI document of the selected operations, which `openapi.json` beside this module holds.\"\"\"\n\nfrom __future__ import annotations\n\nimport json\nfrom importlib.resources import files\nfrom typing import TYPE_CHECKING, Any\n\nfrom .._runtime.server.openapi import serve_openapi\n\nif TYPE_CHECKING:\n    from collections.abc import Mapping\n\n    from fastapi import FastAPI\n\n\ndef document() -> dict[str, Any]:\n    \"\"\"Return a new copy of the source document, read from `openapi.json` beside this module.\n\n    A build that left the file out of the package fails here, on the document's first request.\n    \"\"\"\n    package = __name__.rpartition(\".\")[0]\n    try:\n        text = (files(package) / \"openapi.json\").read_text(encoding=\"utf-8\")\n    except FileNotFoundError as error:\n        msg = (\n            f\"openapi.json of {package} is missing: include _generated/openapi.json\"\n            \" as package data when building the package, such as with setuptools\"\n            \" package-data or MANIFEST.in\"\n        )\n        raise FileNotFoundError(msg) from error\n    loaded: dict[str, Any] = json.loads(text)\n    return loaded\n\n\ndef serve_source_openapi(\n    app: FastAPI,\n    *,\n    prefix: str = \"\",\n    metadata: Mapping[str, Any] | None = None,\n) -> None:\n    \"\"\"Serve the source document instead of FastAPI's, read on its first request.\n\n    Its paths take `prefix`, and the FastAPI settings in `metadata`, such as `title`, replace its own.\n    \"\"\"\n    serve_openapi(app, document, prefix=prefix, metadata=metadata)\n"
    },
    {
      "path": "server/_runtime/__init__.py",
      "content": "# -*- coding: latin-1 -*-\n# Café\n"
    },
    {
      "path": "server/_runtime/server/__init__.py",
      "content": "# -*- coding: latin-1 -*-\n# Café\n\n\"\"\"FastAPI server runtime of a generated package: request adapters, response dispatch, and HTTP results.\"\"\"\n"
    },
    {
      "path": "server/_runtime/server/application.py",
      "content": "# -*- coding: latin-1 -*-\n# Café\n\n\"\"\"Register a generated router's operations on one APIRouter, with the services that implement them.\"\"\"\n\nfrom __future__ import annotations\n\nimport inspect\nimport sys\nfrom collections.abc import Awaitable, Callable, Coroutine, Iterable, Mapping, MutableMapping, Sequence\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Any, Final, NoReturn, TypeAlias, TypeGuard, TypeVar, cast\nfrom urllib.parse import unquote_to_bytes\n\nfrom fastapi import APIRouter\nfrom fastapi.encoders import jsonable_encoder\nfrom fastapi.exceptions import HTTPException, RequestValidationError\nfrom fastapi.params import Depends\nfrom fastapi.routing import APIRoute\nfrom starlette.concurrency import run_in_threadpool\nfrom starlette.responses import JSONResponse\nfrom starlette.routing import Match\nfrom typing_extensions import TypeIs\n\nif TYPE_CHECKING:\n    from starlette.requests import Request\n    from starlette.responses import Response\n    from starlette.types import Receive, Scope, Send\n\nMethodT = TypeVar(\"MethodT\")\n_REQUEST_VALUES: Final = frozenset({\"input\", \"ctx\", \"url\"})\n_LOCATIONS: Final = {\"path\": 0, \"query\": 1, \"header\": 2, \"cookie\": 3}\n\"\"\"The order of FastAPI's records by location; a body comes after every parameter.\"\"\"\n_REJECTED: Final = \"datamodel_code_generator.rejected\"\n_PERCENT: Final = ord(\"%\")\n_SLASH: Final = \"\\udc2f\"\n\"\"\"Stands for an encoded slash while a route matches; no decoded path holds a lone surrogate.\"\"\"\n\n\nclass RawPathRouter(APIRouter):\n    \"\"\"An APIRouter that matches its routes with each slash the raw path encodes kept inside its segment.\n\n    FastAPI matches and handles an included router through these methods, once per request; a path without an encoded\n    slash, or whose raw path does not spell it, goes through them unchanged. So does a path that selects a route the\n    router's user added, such as a mount or a Starlette route, which receives the decoded path as FastAPI routes it.\n    \"\"\"\n\n    def matches(self, scope: Scope) -> tuple[Match, Scope]:\n        \"\"\"Match the routes against the path with its encoded slashes marked.\"\"\"\n        if (marked := self._marked(scope)) is None:\n            return super().matches(scope)\n        _, match, child_scope = marked\n        return match, child_scope\n\n    async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:\n        \"\"\"Select the route by the path with its encoded slashes marked; the route puts the slashes back.\"\"\"\n        if (marked := self._marked(scope)) is None:\n            await super().handle(scope, receive, send)\n            return\n        decoded, scope[\"path\"] = scope[\"path\"], marked[0]\n        try:\n            await super().handle(scope, receive, send)\n        finally:\n            scope[\"path\"] = decoded\n\n    def _marked(self, scope: Scope) -> tuple[str, Match, Scope] | None:\n        \"\"\"Return the marked path and its match, unless it selects a route other than a RawPathRoute.\"\"\"\n        if (path := _segmented(scope)) is None:\n            return None\n        match, child_scope = super().matches({**scope, \"path\": path})\n        if match is not Match.NONE and not isinstance(child_scope.get(\"route\"), RawPathRoute):\n            return None\n        return path, match, child_scope\n\n\ndef malformed_request() -> HTTPException:\n    \"\"\"Return the error for request data that no declared parameter or media form can represent.\"\"\"\n    return HTTPException(status_code=400, detail=\"Invalid request\")\n\n\nclass ParameterReader:\n    \"\"\"A dependency that reads parameters FastAPI cannot: its route reports the records it rejects with FastAPI's.\"\"\"\n\n    __slots__ = ()\n\n\nclass _RejectedReadError(RequestValidationError, AttributeError):\n    \"\"\"The records of a Rejected value raised by reading a parameter value from it, which FastAPI answers with 422.\n\n    It is an AttributeError too, as reading an attribute raises it.\n    \"\"\"\n\n\n@dataclass(frozen=True, slots=True)\nclass Rejected:\n    \"\"\"The records of the parameters a request carries in forms their declarations reject, left by a ParameterReader.\n\n    Whichever raises them first takes them: the route with FastAPI's own records, or the endpoint when FastAPI found\n    none, through `accepted` or by reading a value of the record it stands for, as a route of a custom template that\n    leaves `accepted` out does before it calls the method.\n    \"\"\"\n\n    records: list[dict[str, object]]\n\n    def take(self) -> list[dict[str, object]]:\n        \"\"\"Return the records, leaving none to raise again.\"\"\"\n        records = self.records.copy()\n        self.records.clear()\n        return records\n\n    def __getattr__(self, name: str) -> NoReturn:\n        \"\"\"Raise the records for a parameter value read from the record; a special name is missing, as elsewhere.\"\"\"\n        if name.startswith(\"__\"):\n            raise AttributeError(name)\n        raise _RejectedReadError(self.take())\n\n\ndef reject(scope: MutableMapping[str, Any], records: list[dict[str, object]]) -> Rejected:\n    \"\"\"Leave the records of rejected parameters on a request's scope, and return them as a Rejected value.\"\"\"\n    scope[_REJECTED] = rejected = Rejected(records)\n    return rejected\n\n\nclass RawPathRoute(APIRoute):\n    \"\"\"An APIRoute of a RawPathRouter: it puts the slashes back in the path and its values before the endpoint runs.\n\n    A route with a ParameterReader dependency reports the records the reader leaves with FastAPI's own, and one with\n    header or cookie parameters that FastAPI reads answers 400 for a request whose value of one of them is not ASCII,\n    as a reader answers for the headers and cookies it reads.\n    \"\"\"\n\n    def get_route_handler(self) -> Callable[[Request], Coroutine[Any, Any, Response]]:\n        \"\"\"Return FastAPI's handler, which checks the text of its headers and raises a reader's records with its own.\"\"\"\n        handler = super().get_route_handler()\n        endpoint = self.dependant  # codespell:ignore dependant\n        headers = _names(endpoint.header_params, lower=True)\n        cookies = _names(endpoint.cookie_params, lower=False)\n        readers = any(isinstance(dependency.call, ParameterReader) for dependency in endpoint.dependencies)\n        if not (headers or cookies or readers):\n            return handler\n\n        async def reported(request: Request) -> Response:\n            if (headers or cookies) and not _ascii(request.scope[\"headers\"], headers, cookies):\n                raise malformed_request()\n            try:\n                return await handler(request)\n            except RequestValidationError as error:\n                if not isinstance(left := request.scope.get(_REJECTED), Rejected) or not (records := left.take()):\n                    raise\n                merged = sorted([*error.errors(), *records], key=_location)\n                raise RequestValidationError(merged, body=error.body, endpoint_ctx=error.endpoint_ctx) from None\n\n        return reported\n\n    async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:\n        \"\"\"Restore the decoded path and the path parameter values, then handle the request.\"\"\"\n        if _SLASH in (path := scope[\"path\"]):\n            scope[\"path\"] = path.replace(_SLASH, \"/\")\n            scope[\"path_params\"] = {\n                name: value.replace(_SLASH, \"/\") if isinstance(value, str) else value\n                for name, value in scope[\"path_params\"].items()\n            }\n        await super().handle(scope, receive, send)\n\n\ndef wire_named(names: Mapping[str, str]) -> type[RawPathRoute]:\n    \"\"\"Return a RawPathRoute class whose validation errors locate renamed path placeholders by their wire names.\n\n    FastAPI reads a path parameter by the name its placeholder has in the route path, and locates its records by that\n    name. `names` gives the wire name of each renamed placeholder FastAPI reads; only a request that fails validation\n    looks one up, before any exception handler receives the error.\n    \"\"\"\n\n    class WireNamedRoute(RawPathRoute):\n        def get_route_handler(self) -> Callable[[Request], Coroutine[Any, Any, Response]]:\n            handler = super().get_route_handler()\n\n            async def named(request: Request) -> Response:\n                try:\n                    return await handler(request)\n                except RequestValidationError as error:\n                    for record in error.errors():\n                        match record:\n                            case {\"loc\": (\"path\", str(), *_)} if (wire := names.get(record[\"loc\"][1])) is not None:\n                                record[\"loc\"] = (\"path\", wire, *record[\"loc\"][2:])\n                            case _:\n                                pass\n                    raise\n\n            return named\n\n    return WireNamedRoute\n\n\ndef _names(fields: Iterable[Any], *, lower: bool) -> frozenset[bytes]:\n    \"\"\"Return the names FastAPI reads parameters by, as raw header bytes: header names compare case-insensitively.\"\"\"\n    return frozenset((field.alias.lower() if lower else field.alias).encode(\"latin-1\", \"replace\") for field in fields)\n\n\ndef _ascii(lines: Iterable[tuple[bytes, bytes]], headers: frozenset[bytes], cookies: frozenset[bytes]) -> bool:\n    \"\"\"Return whether the request's values of the named headers and cookies are ASCII, as RFC 9110 and 6265 write them.\n\n    A cookie is found as Starlette finds it: a `;`-separated pair of a `Cookie` header, its name stripped.\n    \"\"\"\n    for name, value in lines:\n        if value.isascii():\n            continue\n        if name in headers or (\n            name == b\"cookie\"\n            and any(\n                separator and key.strip() in cookies and not text.isascii()\n                for key, separator, text in (pair.partition(b\"=\") for pair in value.split(b\";\"))\n            )\n        ):\n            return False\n    return True\n\n\ndef _location(record: Mapping[str, Any]) -> int:\n    \"\"\"Return where a record's location comes in FastAPI's order: path, query, header, and cookie, then the rest.\"\"\"\n    return _LOCATIONS.get((record.get(\"loc\") or (\"\",))[0], len(_LOCATIONS))\n\n\ndef _segmented(scope: Scope) -> str | None:\n    \"\"\"Return the path with the slashes its raw path encodes after the root path marked, or None without any.\"\"\"\n    raw: bytes = scope.get(\"raw_path\") or b\"\"\n    if _PERCENT not in raw or (raw.find(b\"%2F\") < 0 and raw.find(b\"%2f\") < 0):\n        return None\n    path: str = scope[\"path\"]\n    segments = (unquote_to_bytes(segment).decode(errors=\"replace\") for segment in raw.split(b\"/\"))\n    marked = \"/\".join(segment.replace(\"/\", _SLASH) for segment in segments)\n    plain = marked.replace(_SLASH, \"/\")\n    if not path.endswith(plain):\n        return None\n    offset = len(path) - len(plain)\n    root = scope.get(\"root_path\", \"\")\n    start = max(offset, len(root) if path.startswith(root) else 0)\n    tail = marked[start - offset :]\n    if _SLASH not in tail:\n        return None\n    return path[:start] + tail\n\n\ndef _coroutine_function(value: object) -> TypeGuard[Callable[..., Awaitable[object]]]:\n    \"\"\"Return whether calling a value, a function or an object with an async __call__, returns a coroutine.\"\"\"\n    return inspect.iscoroutinefunction(value) or inspect.iscoroutinefunction(getattr(value, \"__call__\", None))  # noqa: B004\n\n\ndef _awaitable(authorize: Callable[..., object]) -> Callable[..., Awaitable[object]]:\n    \"\"\"Return an authorize callback to await: a coroutine function as it is, any other run in the threadpool.\n\n    An awaitable that the other returns is awaited too, so its result or its rejection is the callback's.\n    \"\"\"\n    if _coroutine_function(authorize):\n        return authorize\n\n    async def threaded(requirements: object, credentials: object) -> object:\n        result = await run_in_threadpool(authorize, requirements, credentials)\n        return await result if inspect.isawaitable(result) else result\n\n    return threaded\n\n\n@dataclass(frozen=True, slots=True, kw_only=True)\nclass Wiring:\n    \"\"\"What route adders connect: the services by group, the authorize callback, and operation dependencies.\"\"\"\n\n    services: Mapping[str, Any]\n    authorize: object\n    dependencies: Mapping[str, Sequence[Depends]]\n\n    def authorizer(self) -> Callable[..., Awaitable[object]]:\n        \"\"\"Return the authorize callback to await, which a secured operation needs before it is registered.\"\"\"\n        if not callable(authorize := self.authorize):\n            msg = \"An authorize callback is required because the selected operations use security\"\n            raise TypeError(msg)\n        return _awaitable(authorize)\n\n\nRoute: TypeAlias = tuple[str, Callable[[APIRouter, Wiring], None]]\n\n\nasync def validation_error_handler(  # noqa: RUF029 - Starlette runs a synchronous handler in the threadpool.\n    _: Request, error: Exception\n) -> JSONResponse:\n    \"\"\"Answer 422 with the type, location, and message of each of FastAPI's records, without its input and context.\n\n    The error is the RequestValidationError the handler is registered for; Starlette types every handler's as Exception.\n    \"\"\"\n    errors = cast(\"RequestValidationError\", error).errors()\n    records = [{key: value for key, value in record.items() if key not in _REQUEST_VALUES} for record in errors]\n    return JSONResponse({\"detail\": jsonable_encoder(records)}, status_code=422)\n\n\ndef error_handlers(exception_handlers: Mapping[Any, Any] | None) -> dict[Any, Any]:\n    \"\"\"Return an application's exception handlers: validation_error_handler, under the caller's own handlers.\"\"\"\n    return {RequestValidationError: validation_error_handler, **(exception_handlers or {})}\n\n\ndef checked(\n    method: MethodT, label: str, keywords: tuple[str, ...] | None = None, *, asynchronous: bool = False\n) -> MethodT:\n    \"\"\"Return a service method for its operation, refusing one that its route cannot call as the route calls it.\n\n    A coroutine function where a plain one runs, or the reverse, would skip the method body or fail after it ran, and a\n    signature that does not take the keyword arguments the route passes, `keywords`, would fail on every request:\n    either stops the registration. A wider signature, with defaults or `**kwargs`, takes them. A route of a custom\n    template that names no keywords is not checked for them, and neither is a callable without a signature.\n    \"\"\"\n    if _coroutine_function(method) is not asynchronous:\n        kinds = (\"a coroutine function\", \"a plain method\")\n        found, needed = reversed(kinds) if asynchronous else kinds\n        msg = f\"{label} is {found}, but the operation's handler mode needs {needed}\"\n        raise TypeError(msg)\n    if keywords is None:\n        return method\n    try:\n        signature = _signature(cast(\"Callable[..., object]\", method))\n    except ValueError:\n        return method\n    try:\n        signature.bind(**dict.fromkeys(keywords))\n    except TypeError as error:\n        name = getattr(method, \"__qualname__\", repr(method))\n        passed = \", \".join(keywords) or \"none\"\n        msg = f\"{label}, {name}, cannot take the keyword arguments its route passes ({passed}): {error}\"\n        raise TypeError(msg) from None\n    return method\n\n\ndef _signature(method: Callable[..., object]) -> inspect.Signature:\n    \"\"\"Return a method's own signature, not that of a function it wraps, without evaluating its annotations.\"\"\"\n    if sys.version_info >= (3, 14):  # pragma: >=3.14 cover\n        from annotationlib import Format  # noqa: PLC0415\n\n        return inspect.signature(method, follow_wrapped=False, annotation_format=Format.FORWARDREF)\n    return inspect.signature(method, follow_wrapped=False)  # pragma: <3.14 cover\n\n\ndef missing_implementation(error: ImportError, implementations: Mapping[str, str]) -> None:\n    \"\"\"Raise an error naming what to write when the entrypoint could not import a module or name of yours.\n\n    `implementations` maps each module the entrypoint imports to the class or function it imports from it. Any other\n    import error, such as one in a module that an implementation imports, returns for the caller to re-raise unchanged.\n    Files are named where they are, relative to the working directory when they lie inside it.\n    \"\"\"\n    package = __name__.partition(\"._runtime.\")[0]\n    entrypoint = f\"{package}.main\"\n    root = Path(str(sys.modules[package].__file__)).parent\n    readme = f\"see Next steps in {_shown(root / 'README.md')}\"\n    name = error.name or \"\"\n    if isinstance(error, ModuleNotFoundError):\n        missing = {\n            module: item for module, item in implementations.items() if name in {module, module.rpartition(\".\")[0]}\n        }\n        if not missing:\n            return\n        files = [] if name in missing else [_shown(_file(root, package, name).with_suffix(\"\") / \"__init__.py\")]\n        files.extend(f\"{_shown(_file(root, package, module))} defining {item}\" for module, item in missing.items())\n        msg = (\n            f\"No module named {name!r}: create {', '.join(files)}, which {entrypoint} imports. Generating the \"\n            f\"server again writes missing modules with stubs; {readme}\"\n        )\n    elif (\n        (item := implementations.get(name)) is not None\n        and getattr(error, \"name_from\", item) == item\n        and not hasattr(module := sys.modules.get(name), item)\n    ):\n        where = _shown(Path(str(getattr(module, \"__file__\", None) or _file(root, package, name))))\n        msg = f\"{name} defines no {item}, which {entrypoint} imports: define it in {where}; {readme}\"\n    else:\n        return\n    raise ImportError(msg, name=name) from error\n\n\ndef _file(root: Path, package: str, module: str) -> Path:\n    \"\"\"Return the file a module of the package's parent package would have, beside the package's directory.\"\"\"\n    parent = package.rpartition(\".\")[0]\n    return root.parent.joinpath(*module.removeprefix(f\"{parent}.\" if parent else \"\").split(\".\")).with_suffix(\".py\")\n\n\ndef _shown(path: Path) -> str:\n    \"\"\"Return a path relative to the working directory when it lies inside it.\"\"\"\n    return (path.relative_to(cwd) if path.is_relative_to(cwd := Path.cwd()) else path).as_posix()\n\n\ndef _is_sequence(value: object) -> TypeIs[Sequence[object]]:\n    return isinstance(value, Sequence)\n\n\ndef build(  # noqa: PLR0913\n    routes: tuple[Route, ...],\n    *,\n    services: Mapping[str, Any],\n    authorize: object = None,\n    dependencies: Sequence[Depends],\n    operation_dependencies: Mapping[str, Any] | None,\n    prefix: str,\n) -> APIRouter:\n    \"\"\"Register the routes in order on a new router; each looks its service's method up as it registers.\n\n    The router is a RawPathRouter, so a percent-encoded slash stays inside the path parameter it belongs to.\n\n    The service Protocols and FastAPI check the services and settings. Refused here is what would otherwise drop a\n    dependency or an authorization without an error: a dependency for a method the router does not have, or one\n    that is no sequence of Depends, and, by the secured routes, a missing authorize callback.\n    \"\"\"\n    own = operation_dependencies or {}\n    if unknown := sorted(own.keys() - {name for name, _ in routes}):\n        msg = f\"operation_dependencies names no operation of this router: {', '.join(unknown)}\"\n        raise ValueError(msg)\n    for name, items in own.items():\n        if not (_is_sequence(items) and all(isinstance(item, Depends) for item in items)):\n            msg = f\"operation_dependencies[{name!r}] must be a sequence of Depends(...) values\"\n            raise TypeError(msg)\n    wiring = Wiring(services=services, authorize=authorize, dependencies=own)\n    router = RawPathRouter(prefix=prefix, dependencies=dependencies, route_class=RawPathRoute)\n    for _, add in routes:\n        add(router, wiring)\n    return router\n"
    },
    {
      "path": "server/_runtime/server/openapi.py",
      "content": "# -*- coding: latin-1 -*-\n# Café\n\n\"\"\"Serve a document of the application's own, such as the source OpenAPI document, instead of FastAPI's.\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Any, Final, cast\n\nif TYPE_CHECKING:\n    from collections.abc import Callable, Mapping\n\n    from fastapi import FastAPI\n\n_INFO: Final = {\n    \"title\": \"title\",\n    \"version\": \"version\",\n    \"summary\": \"summary\",\n    \"description\": \"description\",\n    \"terms_of_service\": \"termsOfService\",\n    \"contact\": \"contact\",\n    \"license_info\": \"license\",\n}\n_PATHS: Final = \"#/paths/\"\n_LITERALS: Final = frozenset({\"value\", \"example\", \"default\", \"enum\", \"const\"})\n_ROOT: Final = {\"servers\": \"servers\", \"openapi_tags\": \"tags\", \"openapi_external_docs\": \"externalDocs\"}\n\n\ndef serve_openapi(\n    app: FastAPI,\n    load: Callable[[], dict[str, Any]],\n    *,\n    prefix: str = \"\",\n    metadata: Mapping[str, Any] | None = None,\n) -> None:\n    \"\"\"Make the application's document the one `load` returns, loaded on its first request and kept.\n\n    Its paths take the prefix the routes were included under, as in FastAPI's own document, and so do the references\n    and link operationRefs that name a path. The FastAPI settings in `metadata` that describe the application, such as\n    `title` or `servers`, replace the document's when they are set, as FastAPI leaves unset ones out. FastAPI's\n    documentation endpoints serve it as they serve FastAPI's own, the root path's server included. A document the\n    application built before is dropped.\n    \"\"\"\n    given = metadata or {}\n\n    def openapi() -> dict[str, Any]:\n        if not app.openapi_schema:\n            document = load()\n            if prefix:\n                document = cast(\"dict[str, Any]\", _prefixed(document, prefix))\n                document[\"paths\"] = {f\"{prefix}{path}\": item for path, item in document.get(\"paths\", {}).items()}\n            if info := {key: given[name] for name, key in _INFO.items() if given.get(name)}:\n                document[\"info\"] = {**document.get(\"info\", {}), **info}\n            document.update({key: given[name] for name, key in _ROOT.items() if given.get(name)})\n            app.openapi_schema = document\n        return app.openapi_schema\n\n    app.openapi_schema = None\n    setattr(app, \"openapi\", openapi)  # ruff: ignore[set-attr-with-constant] - FastAPI's documented way to replace the document.\n\n\ndef _prefixed(value: object, prefix: str) -> object:\n    \"\"\"Return a document value whose references and operationRefs into the document's paths name prefixed paths.\n\n    Literal data, such as examples, defaults, and extensions, stays as it is.\n    \"\"\"\n    if isinstance(value, list):\n        return [_prefixed(item, prefix) for item in cast(\"list[object]\", value)]\n    if not isinstance(value, dict):\n        return value\n    prefixed = {\n        key: item if _literal(key, item) else _prefixed(item, prefix)\n        for key, item in cast(\"dict[str, object]\", value).items()\n    }\n    for key in (\"$ref\", \"operationRef\"):\n        if isinstance(ref := prefixed.get(key), str) and ref.startswith(_PATHS):\n            prefixed[key] = _PATHS + prefix.replace(\"~\", \"~0\").replace(\"/\", \"~1\") + ref[len(_PATHS) :]\n    return prefixed\n\n\ndef _literal(key: str, value: object) -> bool:\n    \"\"\"Return whether a member holds literal data: an example value, a default, an enum, a const, or an extension.\n\n    A map of examples holds Example Objects, whose `value` is literal; a list of examples is a schema's.\n    \"\"\"\n    return key in _LITERALS or key.startswith(\"x-\") or (key == \"examples\" and isinstance(value, list))\n"
    },
    {
      "path": "server/_runtime/server/responses.py",
      "content": "# -*- coding: latin-1 -*-\n# Café\n\n\"\"\"HTTP results, and the declared responses an operation sends results and bare values as.\"\"\"\n\nfrom __future__ import annotations\n\nimport inspect\nimport json\nimport re\nfrom collections.abc import Callable, Coroutine, Iterable, Mapping\nfrom dataclasses import dataclass, field\nfrom typing import Final, Generic, Literal, cast\n\nfrom fastapi.encoders import jsonable_encoder\nfrom fastapi.exceptions import ResponseValidationError\nfrom pydantic import TypeAdapter, ValidationError\nfrom starlette.responses import Response\nfrom typing_extensions import TypeIs, TypeVar\n\nBodyT_co = TypeVar(\"BodyT_co\", covariant=True)\n\n_EMPTY_STATUSES: Final = frozenset({204, 205, 304})\n_TOKEN: Final = re.compile(r\"[!#$%&'*+.^_`|~0-9A-Za-z-]+\")\n_HEADER_TEXT: Final = re.compile(r\"(?:[\\x21-\\x7E](?:[\\t\\x20-\\x7E]*[\\x21-\\x7E])?)?\")\n_MIN_CONTENT_STATUS: Final = 200\n_MIN_REDIRECT_STATUS: Final = 300\n_JSON: Final = \"application/json\"\n\n\n@dataclass(frozen=True, slots=True)\nclass HTTPResult(Generic[BodyT_co]):\n    \"\"\"Send one declared response: its status, an optional body of the declared type, and extra headers.\n\n    Without a body, a success response that declares content sends None through its model, as a bare value is sent:\n    `null` where the model accepts null, a validation error where it does not. A response whose JSON accepts null\n    sends `null` on any status, and any other response sends no body.\n    \"\"\"\n\n    status_code: int\n    body: BodyT_co | None = None\n    headers: Mapping[str, str] | None = None\n\n\n@dataclass(frozen=True, slots=True, kw_only=True)\nclass Declared:\n    \"\"\"One declared response: its default media type with that type's kind and charset, and the model its body takes.\n\n    A response that declares no content has no media type; a body sent under it anyway is JSON.\n    `null` says the body is JSON of a type that accepts null, so the response sends None as `null` instead of no body.\n    `dump` writes a JSON body by the model's adapter, for a model whose adapter's own dump leaves out what it holds.\n    The model's adapter is built when the response first sends a body; a concurrent first send builds an equal one.\n    \"\"\"\n\n    media_type: str | None = None\n    kind: Literal[\"json\", \"text\", \"form\", \"multipart\", \"binary\"] = \"json\"\n    charset: str = \"utf-8\"\n    model: object = None\n    null: bool = False\n    dump: Callable[[TypeAdapter[object], object], bytes] | None = None\n    _adapter: TypeAdapter[object] | None = field(default=None, init=False, repr=False, compare=False)\n\n    def adapter(self) -> TypeAdapter[object] | None:\n        \"\"\"Return the adapter of the body model, building and keeping it on first use, or None without a model.\"\"\"\n        if (adapter := self._adapter) is None and (model := self.model) is not None:\n            built: TypeAdapter[object] = TypeAdapter(cast(\"type[object]\", model))\n            object.__setattr__(self, \"_adapter\", built)  # noqa: PLC2801 - Keep the adapter on the frozen value.\n            return built\n        return adapter\n\n    def sends_none(self, status: int) -> bool:\n        \"\"\"Return whether the response sends None as a body: JSON that accepts null, or content of a success status.\"\"\"\n        return self.null or (self.media_type is not None and status < _MIN_REDIRECT_STATUS)\n\n\n_UNDECLARED: Final = Declared()\n\n\n@dataclass(frozen=True, slots=True, kw_only=True)\nclass OperationResponses:\n    \"\"\"An operation's declared responses by status key, and the status of a bare value the route sends itself.\n\n    FastAPI's response_model sends the bare value of an operation without that status. `primary_media` is the media\n    a bare value takes when it is chosen over the default media of the response that declares that status. `bare` is\n    False for an operation without a primary response, which refuses a bare value.\n    \"\"\"\n\n    responses: Mapping[str, Declared]\n    primary: int | None = None\n    primary_media: Declared | None = None\n    head: bool = False\n    bare: bool = True\n\n    def find(self, status: int) -> Declared | None:\n        \"\"\"Return the response that declares a status: exact, then the same status class, then default.\"\"\"\n        responses = self.responses\n        return responses.get(str(status)) or responses.get(f\"{status // 100}XX\") or responses.get(\"default\")\n\n\ndef dispatch(value: object, plan: OperationResponses) -> object:\n    \"\"\"Pass a Response through, send an HTTPResult as its declared response, and leave a bare value to FastAPI.\n\n    An operation whose primary response FastAPI does not send sends a bare value as that response, and an operation\n    without a primary response refuses one.\n    \"\"\"\n    if isinstance(value, Response):\n        return value\n    if _is_result(value):\n        return _respond(value.status_code, value.body, value.headers, plan)\n    if plan.primary is not None:\n        return _respond(plan.primary, value, None, plan, plan.primary_media)\n    if plan.bare:\n        return value\n    msg = \"The method returned a value for an operation without a primary response; return an HTTPResult\"\n    raise _failure(msg)\n\n\ndef _is_result(value: object) -> TypeIs[HTTPResult[object]]:\n    return isinstance(value, HTTPResult)\n\n\ndef _respond(\n    status: int,\n    body: object,\n    headers: Mapping[str, str] | None,\n    plan: OperationResponses,\n    chosen: Declared | None = None,\n) -> Response:\n    \"\"\"Send a body as its declared response, raw bytes of a `text/*` one under its media type without a charset added.\n\n    Starlette labels every `text/*` body without a charset UTF-8, which only text the response encodes itself is.\n    \"\"\"\n    if headers:\n        _check_headers(headers.items())\n    declared = chosen or plan.find(status) or _UNDECLARED\n    if (\n        (body is None and not declared.sends_none(status))\n        or plan.head\n        or status < _MIN_CONTENT_STATUS\n        or status in _EMPTY_STATUSES\n    ):\n        if inspect.isawaitable(body):\n            raise _unawaited(body)\n        return Response(status_code=status, headers=headers)\n    media_type = declared.media_type or _JSON\n    if isinstance(content := _content(declared, body), str):\n        return Response(_encoded(declared, content), status_code=status, media_type=media_type, headers=headers)\n    if declared.kind == \"json\" or not media_type.startswith(\"text/\"):\n        return Response(content, status_code=status, media_type=media_type, headers=headers)\n    response = Response(content, status_code=status, headers=headers)\n    response.headers.setdefault(\"content-type\", media_type)\n    return response\n\n\ndef _check_headers(headers: Iterable[tuple[object, object]]) -> None:\n    \"\"\"Refuse a result's header whose name is not a token or whose value is not header text, as RFC 9110 writes them.\n\n    Header text, as the generated client sends it, is HTAB, SP, and visible ASCII, without whitespace at either end.\n    A result's headers may hold other values than its annotation says, such as bytes.\n    \"\"\"\n    for name, value in headers:\n        if not (isinstance(name, str) and _TOKEN.fullmatch(name)):\n            msg = f\"The response header name {name!r} is not a token\"\n            raise _failure(msg)\n        if not (isinstance(value, str) and _HEADER_TEXT.fullmatch(value)):\n            msg = f\"The {name} response header is not header text\"\n            raise _failure(msg)\n\n\ndef _unawaited(body: object) -> TypeError:\n    \"\"\"Return the error for an awaitable result that a response without a body would drop before it ran.\"\"\"\n    if isinstance(body, Coroutine):\n        body.close()\n    return TypeError(\"The method returned an awaitable for a response without a body; nothing awaited it\")\n\n\ndef _content(declared: Declared, body: object) -> str | bytes:\n    \"\"\"Return the text of a body to encode in the declared charset, or the bytes to send as they are.\n\n    A text body's model writes its value as its JSON text, an enum member as its value.\n    \"\"\"\n    json_media = declared.kind == \"json\"\n    if (adapter := declared.adapter()) is None:\n        payload = _json(jsonable_encoder(body, by_alias=True, exclude_unset=True)) if json_media else body\n    else:\n        try:\n            value = adapter.validate_python(body)\n        except ValidationError as error:\n            raise ResponseValidationError(error.errors(include_url=False)) from error\n        if json_media:\n            if (dump := declared.dump) is None:\n                return adapter.dump_json(value, by_alias=True, exclude_unset=True)\n            return dump(adapter, value)\n        payload = adapter.dump_python(value, mode=\"json\" if declared.kind == \"text\" else \"python\", by_alias=True)\n    if isinstance(payload, (str, bytes)):\n        return payload\n    msg = f\"A {declared.media_type} body must be a string or bytes\"\n    raise _failure(msg)\n\n\ndef _encoded(declared: Declared, text: str) -> bytes:\n    try:\n        return text.encode(declared.charset)\n    except (LookupError, UnicodeError) as error:\n        msg = f\"The text body cannot be encoded as {declared.media_type}\"\n        raise _failure(msg) from error\n\n\ndef _failure(message: str) -> ResponseValidationError:\n    \"\"\"Return the error for a handler result that no declared response accepts.\"\"\"\n    return ResponseValidationError([{\"type\": \"value_error\", \"loc\": (\"response\",), \"msg\": message}])\n\n\ndef _json(value: object) -> str:\n    return json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(\",\", \":\"))\n"
    },
    {
      "path": "server/application.py",
      "content": "# -*- coding: latin-1 -*-\n# Café\n\n\"\"\"Build the router and the application of every selected operation from the services that implement them.\"\"\"\n\nfrom collections.abc import Sequence\nfrom typing import Any, Final\n\nfrom fastapi import APIRouter, FastAPI, params\n\nfrom ._generated.contract import OperationDependencies\nfrom ._generated.openapi import serve_source_openapi\nfrom ._runtime.server.application import build, error_handlers, validation_error_handler\nfrom .routers import items, users\nfrom .services import ItemsService, UsersService\n\nROUTES: Final = (\n    *items.LITERAL_ROUTES,\n    *users.LITERAL_ROUTES,\n    *items.TEMPLATED_ROUTES,\n    *users.TEMPLATED_ROUTES,\n)\nINFO: Final[dict[str, Any]] = {'title': 'Inline', 'version': '1.0.0'}\n\n\ndef build_router(\n    *,\n    items: ItemsService,\n    users: UsersService,\n    dependencies: Sequence[params.Depends] = (),\n    operation_dependencies: OperationDependencies | None = None,\n    prefix: str = \"\",\n) -> APIRouter:\n    \"\"\"Register every operation on a new router, literal paths first.\"\"\"\n    return build(\n        ROUTES,\n        services={'items': items, 'users': users},\n        dependencies=dependencies,\n        operation_dependencies=operation_dependencies,\n        prefix=prefix,\n    )\n\n\ndef create_app(\n    *,\n    items: ItemsService,\n    users: UsersService,\n    operation_dependencies: OperationDependencies | None = None,\n    prefix: str = \"\",\n    source_openapi: bool = True,\n    **fastapi_kwargs: Any,\n) -> FastAPI:\n    \"\"\"Create the application with every operation, passing the other keyword arguments to FastAPI.\n\n    Validation errors leave out the request's values, unless exception_handlers handles RequestValidationError. The\n    application serves the source OpenAPI document of its operations, or FastAPI's own with source_openapi=False.\n    \"\"\"\n    fastapi_kwargs[\"exception_handlers\"] = error_handlers(fastapi_kwargs.get(\"exception_handlers\"))\n    app = FastAPI(**{**INFO, **fastapi_kwargs})\n    app.include_router(\n        build_router(\n            items=items,\n            users=users,\n            operation_dependencies=operation_dependencies,\n            prefix=prefix,\n        )\n    )\n    if source_openapi:\n        serve_source_openapi(app, prefix=prefix, metadata=fastapi_kwargs)\n    return app\n\n\n__all__ = [\n    'OperationDependencies',\n    'build_router',\n    'create_app',\n    'serve_source_openapi',\n    'validation_error_handler',\n]\n"
    },
    {
      "path": "server/main.py",
      "content": "# -*- coding: latin-1 -*-\n# Café\n\n\"\"\"Serve the application with your services: `uvicorn server.main:app`.\n\nGeneration overwrites this module. It imports your implementations from services, as Next steps in README.md\ndescribes, and passes them to create_app; to pass others, such as fakes in tests, call create_app yourself.\n\"\"\"\n\nfrom ._runtime.server.application import missing_implementation\nfrom .application import create_app\n\ntry:\n    from services.items import Items\n    from services.users import Users\nexcept ImportError as error:\n    missing_implementation(\n        error,\n        {\n            'services.items': 'Items',\n            'services.users': 'Users',\n        },\n    )\n    raise\n\napp = create_app(\n    items=Items(),\n    users=Users(),\n)\n"
    },
    {
      "path": "server/py.typed",
      "content": ""
    },
    {
      "path": "server/routers/__init__.py",
      "content": "# -*- coding: latin-1 -*-\n# Café\n\n\"\"\"Router groups of this package.\"\"\"\n"
    },
    {
      "path": "server/routers/items.py",
      "content": "# -*- coding: latin-1 -*-\n# Café\n\n\"\"\"Endpoints of the items operations; regenerate them instead of editing.\"\"\"\n\nfrom collections.abc import Sequence\nfrom typing import Final\n\nimport models\nfrom fastapi import APIRouter, params\n\nfrom .._generated import contract\nfrom .._generated.contract import OperationDependencies\nfrom .._runtime.server.application import Wiring, build, checked\nfrom .._runtime.server.responses import dispatch\nfrom ..services import ItemsService\n\n\ndef _add_list_items(\n    router: APIRouter,\n    wiring: Wiring,\n) -> None:\n    items: ItemsService = wiring.services['items']\n    list_items_handler = checked(\n        items.list_items,\n        'The items.list_items method of GET /items',\n        (),\n    )\n\n    def list_items() -> object:\n        return dispatch(\n            list_items_handler(),\n            contract.ListItems.RESPONSES,\n        )\n\n    router.add_api_route(\n        '/items',\n        list_items,\n        methods=['GET'],\n        status_code=200,\n        response_model=models.ItemsGetResponse,\n        response_model_by_alias=True,\n        response_model_exclude_unset=True,\n        operation_id='listItems',\n        tags=['items'],\n        response_description='Items',\n        dependencies=wiring.dependencies.get('list_items'),\n    )\n\n\nLITERAL_ROUTES: Final = (\n    ('list_items', _add_list_items),\n)\nTEMPLATED_ROUTES: Final = ()\n\n\ndef build_router(\n    *,\n    items: ItemsService,\n    dependencies: Sequence[params.Depends] = (),\n    operation_dependencies: OperationDependencies | None = None,\n    prefix: str = \"\",\n) -> APIRouter:\n    \"\"\"Register the items operations on a new router, literal paths first.\"\"\"\n    return build(\n        (*LITERAL_ROUTES, *TEMPLATED_ROUTES),\n        services={'items': items},\n        dependencies=dependencies,\n        operation_dependencies=operation_dependencies,\n        prefix=prefix,\n    )\n"
    },
    {
      "path": "server/routers/users.py",
      "content": "# -*- coding: latin-1 -*-\n# Café\n\n\"\"\"Endpoints of the users operations; regenerate them instead of editing.\"\"\"\n\nfrom collections.abc import Sequence\nfrom typing import Final\n\nfrom fastapi import APIRouter, params\nfrom fastapi.responses import Response\n\nfrom .._generated import contract\nfrom .._generated.contract import OperationDependencies\nfrom .._runtime.server.application import Wiring, build, checked\nfrom .._runtime.server.responses import dispatch\nfrom ..services import UsersService\n\n\ndef _add_list_users(\n    router: APIRouter,\n    wiring: Wiring,\n) -> None:\n    users: UsersService = wiring.services['users']\n    list_users_handler = checked(\n        users.list_users,\n        'The users.list_users method of GET /users',\n        (),\n    )\n\n    def list_users() -> object:\n        return dispatch(\n            list_users_handler(),\n            contract.ListUsers.RESPONSES,\n        )\n\n    router.add_api_route(\n        '/users',\n        list_users,\n        methods=['GET'],\n        status_code=204,\n        response_model=None,\n        response_class=Response,\n        operation_id='listUsers',\n        tags=['users'],\n        response_description='None',\n        dependencies=wiring.dependencies.get('list_users'),\n    )\n\n\nLITERAL_ROUTES: Final = (\n    ('list_users', _add_list_users),\n)\nTEMPLATED_ROUTES: Final = ()\n\n\ndef build_router(\n    *,\n    users: UsersService,\n    dependencies: Sequence[params.Depends] = (),\n    operation_dependencies: OperationDependencies | None = None,\n    prefix: str = \"\",\n) -> APIRouter:\n    \"\"\"Register the users operations on a new router, literal paths first.\"\"\"\n    return build(\n        (*LITERAL_ROUTES, *TEMPLATED_ROUTES),\n        services={'users': users},\n        dependencies=dependencies,\n        operation_dependencies=operation_dependencies,\n        prefix=prefix,\n    )\n"
    },
    {
      "path": "server/services.py",
      "content": "# -*- coding: latin-1 -*-\n# Café\n\n\"\"\"Service interfaces of this package's router groups; regenerate them instead of editing.\"\"\"\n\nfrom __future__ import annotations\n\nfrom abc import abstractmethod\nfrom typing import Protocol\n\nimport models\nfrom fastapi.responses import Response\n\nfrom ._runtime.server.responses import HTTPResult\n\n\nclass ItemsService(Protocol):\n    \"\"\"Implement the items operations: subclass this Protocol, or give an object its methods.\"\"\"\n\n    @abstractmethod\n    def list_items(\n        self,\n    ) -> models.ItemsGetResponse | HTTPResult[models.ItemsGetResponse] | Response:\n        \"\"\"\n        Handle GET /items.\n        \"\"\"\n\n\nclass UsersService(Protocol):\n    \"\"\"Implement the users operations: subclass this Protocol, or give an object its methods.\"\"\"\n\n    @abstractmethod\n    def list_users(\n        self,\n    ) -> None | HTTPResult[None] | Response:\n        \"\"\"\n        Handle GET /users.\n        \"\"\"\n"
    }
  ],
  "target": {
    "package": "server",
    "dependencies": [
      "fastapi>=0.141.1",
      "pydantic>=2.14.0",
      "typing-extensions>=4.16"
    ],
    "readme": "server/README.md",
    "entrypoint": {
      "app": "server.main:app",
      "path": "server/main.py"
    },
    "implementation": [
      {
        "module": "services.items",
        "name": "Items",
        "path": "services/items.py",
        "created": true
      },
      {
        "module": "services.users",
        "name": "Users",
        "path": "services/users.py",
        "created": true
      }
    ]
  }
}
