{
  "version": 1,
  "format": "json",
  "kind": "generation",
  "output": "<root>/models",
  "files": [
    {
      "path": "__init__.py",
      "content": "# generated by datamodel-codegen:\n#   filename:  modular.yaml\n\nfrom __future__ import annotations\n\nfrom pydantic import RootModel\n\nfrom . import store\n\n\nclass OrdersGetResponse(RootModel[list[store.Order]]):\n    root: list[store.Order]\n"
    },
    {
      "path": "pets.py",
      "content": "# generated by datamodel-codegen:\n#   filename:  modular.yaml\n\nfrom __future__ import annotations\n\nfrom pydantic import BaseModel\n\n\nclass Pet(BaseModel):\n    name: str | None = None\n"
    },
    {
      "path": "server/README.md",
      "content": "# Modular\n\nThe `models.server` package serves the Modular API with FastAPI.\ndatamodel-code-generator generated it from the OpenAPI document, together with the `models` models of the `pydantic_v2.BaseModel` backend.\nGeneration overwrites every file of the package, as it does the models: keep your code outside the package, in the `models.services` modules of [Next steps](#next-steps), and regenerate the package instead of editing it; see [Regenerating](#regenerating).\n\nFastAPI server generation is experimental.\nThe server supports the `pydantic_v2.BaseModel` and `pydantic_v2.dataclass` model backends, while client generation supports all five.\n\n## Next steps\n\n`main.py` serves the application: it imports your implementation of each router group from the `models.services` package beside this package, and passes them to `create_app`.\nGeneration writes each of these modules that is missing, with a stub for each method that raises `NotImplementedError`, and never overwrites or deletes one.\n\n| Module | File | Defines |\n| --- | --- | --- |\n| `models.services.store` | `../services/store.py` | `class Store(StoreService)` |\n\nThe file paths are relative to this README.\nReplace each stub with your code, then run the application with an ASGI server, from the directory that holds the top-level package (add `--app-dir src` for a `src` layout):\n\n```console\nuv add uvicorn\nuv run uvicorn models.server.main:app --reload\n```\n\n`fastapi dev` runs it too: `uv add \"fastapi[standard]\"`, then `uv run fastapi dev --entrypoint models.server.main:app` from the same directory, or `uv run --directory src fastapi dev --entrypoint models.server.main:app` for a `src` layout.\nTo pass other instances, such as fakes in tests, call `create_app` yourself; see [Implementing the services](#implementing-the-services).\n\n### `models.services.store`\n\n```python\n\"\"\"Implement StoreService of models.server.services; models.server.main imports Store from this module.\n\ndatamodel-code-generator wrote this module once, with a stub for each method, and never overwrites it. Generating the\nserver again updates the Protocol, so type checkers point at the methods to change.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport models\nfrom fastapi.responses import Response\nfrom models.server import HTTPResult\nfrom models.server.services import StoreService\n\n\nclass Store(StoreService):\n    \"\"\"Implement the store operations.\"\"\"\n\n    def list_orders(\n        self,\n    ) -> models.OrdersGetResponse | HTTPResult[models.OrdersGetResponse] | Response:\n        \"\"\"\n        Handle GET /orders.\n        \"\"\"\n        raise NotImplementedError\n```\n\n## Dependencies\n\nThe package needs these distributions at run time:\n\n- `fastapi>=0.141.1`\n- `pydantic>=2.14.0`\n- `typing-extensions>=4.16`\n\nAdd them to your project with the command each generation prints:\n\n```console\nuv add \"fastapi>=0.141.1\" \"pydantic>=2.14.0\" \"typing-extensions>=4.16\"\n```\n\nRunning the application also needs an ASGI server: `uvicorn`, or `fastapi[standard]` for `fastapi dev`, as in [Next steps](#next-steps).\n\n## Operations\n\n| Service | Method | HTTP method | Path | Operation reference |\n| --- | --- | --- | --- | --- |\n| `StoreService` | `list_orders` | GET | `/orders` | `/paths/~1orders/get` |\n\n`operation_dependencies` takes the method names, the keys of `OperationDependencies`; the per-operation generation settings, such as `--server-handler-modes`, take the operation references.\n\n## Implementing the services\n\n`services.py` declares a Protocol for each router group, with an abstract method for each operation of the group.\nA method takes the operation's arguments as keywords, with `None` for an optional parameter or body the request omits, and returns the value to send, an `HTTPResult` with another declared status, headers, or both, or a `Response` sent as it is.\n`main.py` passes an instance of each group's class to `create_app` under the group's name.\nSubclass the Protocol, so that type checkers report a missing or mismatched method and Python refuses to create an instance while a method is missing; any other object with the same methods is checked where you pass it.\nThe package looks each method up when it registers the routes, and refuses a coroutine function where the operation's handler mode needs a plain method, or the reverse, and a method that cannot take the keyword arguments of its operation; type checkers check their types.\n\nCall `create_app` yourself to pass other instances.\nTests pass fakes, as this pytest test does with FastAPI's `TestClient`, which needs `httpx2`: each fake subclasses your class of its group and overrides the methods the test calls.\nAn application that builds its services with arguments, such as a database pool or settings, calls `create_app` in a module of its own and runs that module's application instead of `main.py`'s.\n\n```python\nfrom fastapi.testclient import TestClient\n\nfrom models.server import create_app\nfrom models.services.store import Store\n\n\nclass FakeStore(Store):\n    \"\"\"Override the methods the test calls, such as `list_orders`.\"\"\"\n\n\ndef test_app() -> None:\n    with TestClient(create_app(store=FakeStore())) as client:\n        ...\n```\n\n`create_app` passes its other keyword arguments, such as `lifespan`, `middleware`, or `dependencies`, to `FastAPI`, over the title, version, and other metadata of the source document.\nTo keep your own `FastAPI` application, include the router:\n\n```python\nfrom fastapi import FastAPI\n\nfrom models.server import build_router\nfrom models.services.store import Store\n\napp = FastAPI()\napp.include_router(build_router(store=Store()))\n```\n\n## Served OpenAPI document\n\n`create_app` serves the part of the source document the selected operations use, which generation writes into `_generated/openapi.json`; the application reads it on the first request for it.\n`_generated/openapi.json` is package data, so a distribution that holds the package must include it: Hatchling, uv_build, poetry-core, pdm-backend, and flit_core include it by default, while setuptools needs it in `package-data` or `MANIFEST.in`.\n`create_app(..., source_openapi=False)` serves FastAPI's own document instead, built from the routes and the models they declare, in which an optional parameter or request body is `anyOf` of its type and `null`.\nAn application of your own that includes `build_router(...)` serves FastAPI's document unless it calls `serve_source_openapi(app)`, imported from `models.server`.\n\n## Validation\n\nThe models are the contract: FastAPI validates parameters, bodies, and responses with the generated model types, so the model generation settings decide how strictly a value follows the OpenAPI document.\nParameter styles, parameter types, and media types that FastAPI cannot read, such as deepObject parameters or cookie arrays, strict integers, numbers, and booleans, text and binary bodies, and multipart forms, pass through generated adapters.\nAn adapter parses the HTTP syntax, then validates the value with the model's `TypeAdapter`; it answers `400` for malformed syntax, `415` for an undeclared media type, and `422`, with FastAPI's error records, for an invalid value.\nA repeated single value is taken as FastAPI takes it, by adapters too: the last query value, cookie, form field, and object member, and the first header.\nA cookie parameter with a single value arrives as the request sent it, without percent-decoding.\nAdapters accept integers and numbers as JSON writes them and booleans as `true` or `false`, which is fewer spellings than FastAPI accepts for the parameters it reads.\n\n## Production settings\n\nA request that fails validation answers `422` with FastAPI's `{\"detail\": [...]}` records.\n`create_app` keeps the `type`, `loc`, and `msg` of each record and leaves out the `input` and `ctx` FastAPI adds, and pydantic's `url`, so the response does not return the rejected value as such.\n`loc` and `msg` are pydantic's and can still hold text the client chose: a mapping key or an unexpected field name, a discriminator tag, or the message of a validator of your own.\nAn application of your own that includes `build_router(...)` keeps FastAPI's records; register the same handler with `app.add_exception_handler(RequestValidationError, validation_error_handler)`, importing `validation_error_handler` from `models.server`.\nTo send other error bodies, pass FastAPI's `exception_handlers` to `create_app`; its entry for `RequestValidationError` replaces the package's.\nA result that fails its response model answers `500` without details, and the error, with the values, goes to the server log, as in any FastAPI application.\n`create_app(..., docs_url=None, redoc_url=None, openapi_url=None)` removes `/docs`, `/redoc`, and `/openapi.json`.\nThe `server` response header belongs to the ASGI server, not to the application: uvicorn leaves it out with `--no-server-header`.\n\n## Regenerating\n\nRun the same generation again whenever the OpenAPI document changes; the `--check` option reports the files it would change without writing them.\nGeneration overwrites every generated file, restoring any you edited or deleted, and never deletes one: delete the modules of removed operations yourself, which `--check` lists as extra files.\nWhen an operation is added, removed, or changed, its method in `services.py` changes with it, so type checkers point at the implementations to update, and Python refuses to create an instance of a subclass that lacks a new method.\nGeneration writes only the missing modules of `models.services`: a new router group gets its module with stubs, and the module of a renamed or removed group stays for you to move or delete.\nThe `models.services` package belongs to this server alone, as the docstring of its `__init__.py` records: generation refuses another server package beside this one, in a later run or in the same batch, since that package would import its implementations from it too, whatever the docstring says.\nPut each server package under a parent package of its own.\nA server package renamed or moved within the parent package, or spelled from another import root, takes the package over while no other generated server package is beside it, and generation rewrites the docstring to name it, as `--check` reports and a notice says.\nAfter a take-over, the modules of `models.services` still import the server package they were written for, as in `from <old package>.services import ...`: update those imports to `models.server` yourself, since generation never rewrites them.\nEach generation prints the `uv add` command that adds the runtime dependencies of the package to your project;\nrun it again when a new version of datamodel-code-generator changes them.\n"
    },
    {
      "path": "server/__init__.py",
      "content": "# generated by datamodel-codegen:\n#   filename:  modular.yaml\n\n\"\"\"FastAPI server package models.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": "# generated by datamodel-codegen:\n#   filename:  modular.yaml\n\n\"\"\"Generated plans of this package.\"\"\"\n"
    },
    {
      "path": "server/_generated/contract.py",
      "content": "# generated by datamodel-codegen:\n#   filename:  modular.yaml\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_orders': Sequence[params.Depends]\n    },\n    total=False,\n)\n\n\nclass ListOrders:\n    \"\"\"Plans of the list_orders operation.\"\"\"\n\n    RESPONSES: Final = OperationResponses(\n        responses={'200': Declared(media_type='application/json', model=models.OrdersGetResponse)},\n    )\n"
    },
    {
      "path": "server/_generated/openapi.json",
      "content": "{\n \"openapi\": \"3.1.0\",\n \"info\": {\n  \"title\": \"Modular\",\n  \"version\": \"1.0.0\"\n },\n \"paths\": {\n  \"/orders\": {\n   \"get\": {\n    \"operationId\": \"listOrders\",\n    \"tags\": [\n     \"store\"\n    ],\n    \"responses\": {\n     \"200\": {\n      \"description\": \"Orders\",\n      \"content\": {\n       \"application/json\": {\n        \"schema\": {\n         \"type\": \"array\",\n         \"items\": {\n          \"$ref\": \"#/components/schemas/store.Order\"\n         }\n        }\n       }\n      }\n     }\n    }\n   }\n  }\n },\n \"components\": {\n  \"schemas\": {\n   \"store.Order\": {\n    \"type\": \"object\",\n    \"properties\": {\n     \"pet\": {\n      \"$ref\": \"#/components/schemas/pets.Pet\"\n     }\n    }\n   },\n   \"pets.Pet\": {\n    \"type\": \"object\",\n    \"properties\": {\n     \"name\": {\n      \"type\": \"string\"\n     }\n    }\n   }\n  }\n }\n}\n"
    },
    {
      "path": "server/_generated/openapi.py",
      "content": "# generated by datamodel-codegen:\n#   filename:  modular.yaml\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": "# generated by datamodel-codegen:\n#   filename:  modular.yaml\n"
    },
    {
      "path": "server/_runtime/server/__init__.py",
      "content": "# generated by datamodel-codegen:\n#   filename:  modular.yaml\n\n\"\"\"FastAPI server runtime of a generated package: request adapters, response dispatch, and HTTP results.\"\"\"\n"
    },
    {
      "path": "server/_runtime/server/application.py",
      "content": "# generated by datamodel-codegen:\n#   filename:  modular.yaml\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": "# generated by datamodel-codegen:\n#   filename:  modular.yaml\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": "# generated by datamodel-codegen:\n#   filename:  modular.yaml\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": "# generated by datamodel-codegen:\n#   filename:  modular.yaml\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 store\nfrom .services import StoreService\n\nROUTES: Final = (\n    *store.LITERAL_ROUTES,\n    *store.TEMPLATED_ROUTES,\n)\nINFO: Final[dict[str, Any]] = {'title': 'Modular', 'version': '1.0.0'}\n\n\ndef build_router(\n    *,\n    store: StoreService,\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={'store': store},\n        dependencies=dependencies,\n        operation_dependencies=operation_dependencies,\n        prefix=prefix,\n    )\n\n\ndef create_app(\n    *,\n    store: StoreService,\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            store=store,\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": "# generated by datamodel-codegen:\n#   filename:  modular.yaml\n\n\"\"\"Serve the application with your services: `uvicorn models.server.main:app`.\n\nGeneration overwrites this module. It imports your implementations from models.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 models.services.store import Store\nexcept ImportError as error:\n    missing_implementation(\n        error,\n        {\n            'models.services.store': 'Store',\n        },\n    )\n    raise\n\napp = create_app(\n    store=Store(),\n)\n"
    },
    {
      "path": "server/py.typed",
      "content": ""
    },
    {
      "path": "server/routers/__init__.py",
      "content": "# generated by datamodel-codegen:\n#   filename:  modular.yaml\n\n\"\"\"Router groups of this package.\"\"\"\n"
    },
    {
      "path": "server/routers/store.py",
      "content": "# generated by datamodel-codegen:\n#   filename:  modular.yaml\n\n\"\"\"Endpoints of the store 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 StoreService\n\n\ndef _add_list_orders(\n    router: APIRouter,\n    wiring: Wiring,\n) -> None:\n    store: StoreService = wiring.services['store']\n    list_orders_handler = checked(\n        store.list_orders,\n        'The store.list_orders method of GET /orders',\n        (),\n    )\n\n    def list_orders() -> object:\n        return dispatch(\n            list_orders_handler(),\n            contract.ListOrders.RESPONSES,\n        )\n\n    router.add_api_route(\n        '/orders',\n        list_orders,\n        methods=['GET'],\n        status_code=200,\n        response_model=models.OrdersGetResponse,\n        response_model_by_alias=True,\n        response_model_exclude_unset=True,\n        operation_id='listOrders',\n        tags=['store'],\n        response_description='Orders',\n        dependencies=wiring.dependencies.get('list_orders'),\n    )\n\n\nLITERAL_ROUTES: Final = (\n    ('list_orders', _add_list_orders),\n)\nTEMPLATED_ROUTES: Final = ()\n\n\ndef build_router(\n    *,\n    store: StoreService,\n    dependencies: Sequence[params.Depends] = (),\n    operation_dependencies: OperationDependencies | None = None,\n    prefix: str = \"\",\n) -> APIRouter:\n    \"\"\"Register the store operations on a new router, literal paths first.\"\"\"\n    return build(\n        (*LITERAL_ROUTES, *TEMPLATED_ROUTES),\n        services={'store': store},\n        dependencies=dependencies,\n        operation_dependencies=operation_dependencies,\n        prefix=prefix,\n    )\n"
    },
    {
      "path": "server/services.py",
      "content": "# generated by datamodel-codegen:\n#   filename:  modular.yaml\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 StoreService(Protocol):\n    \"\"\"Implement the store operations: subclass this Protocol, or give an object its methods.\"\"\"\n\n    @abstractmethod\n    def list_orders(\n        self,\n    ) -> models.OrdersGetResponse | HTTPResult[models.OrdersGetResponse] | Response:\n        \"\"\"\n        Handle GET /orders.\n        \"\"\"\n"
    },
    {
      "path": "store.py",
      "content": "# generated by datamodel-codegen:\n#   filename:  modular.yaml\n\nfrom __future__ import annotations\n\nfrom pydantic import BaseModel\n\nfrom . import pets\n\n\nclass Order(BaseModel):\n    pet: pets.Pet | None = None\n"
    }
  ],
  "target": {
    "package": "models.server",
    "dependencies": [
      "fastapi>=0.141.1",
      "pydantic>=2.14.0",
      "typing-extensions>=4.16"
    ],
    "readme": "server/README.md",
    "entrypoint": {
      "app": "models.server.main:app",
      "path": "server/main.py"
    },
    "implementation": [
      {
        "module": "models.services.store",
        "name": "Store",
        "path": "services/store.py",
        "created": true
      }
    ]
  }
}
