Skip to content

Tooling, Codegen, Deploy & Doctor Reference

API reference for litestar_vite.codegen, litestar_vite.scaffolding, litestar_vite.doctor, and litestar_vite.deploy.


Unified Asset & Schema Export

ExportResult

Result of the export operation.

Attributes:

Name Type Description
exported_fileslist[str]

Files that were written (content changed).

unchanged_fileslist[str]

Files that were skipped (content unchanged).

openapi_schemadict[str, Any] | None

The OpenAPI schema dict (for downstream use).

asyncapi_schemadict[str, Any] | None

The AsyncAPI schema dict (for downstream use).

export_integration_assets

export_integration_assets(app, config, *, serializer=None)

Export all integration artifacts with deterministic output.

This is the single source of truth for code generation. Both CLI commands and Plugin startup should call this function to ensure byte-identical output.

OpenAPI schema, route metadata, route definitions, and Inertia page prop artifacts require an active OpenAPIPlugin configuration. AsyncAPI export requires a registered AsyncAPIPlugin (litestar-asyncapi) on the application and generate_channels=True.

The export order is critical: 1. Register Inertia page prop types in OpenAPI schema (mutates schema_dict) 2. Export openapi.json (now includes session prop types) 3. Export routes.json (uses schema for component refs) 4. Export routes.ts (if enabled) 5. Export inertia-pages.json (if enabled) 6. Export asyncapi.json (if enabled and AsyncAPIPlugin is registered)

Parameters:

Name Type Description Default
app Litestar

The Litestar application instance.

required
config ViteConfig

The ViteConfig instance.

required
serializer Callable[[Any], bytes] | None

Optional custom serializer for OpenAPI schema encoding.

None

Returns:

Type Description
ExportResult

ExportResult with lists of exported and unchanged files.

typegen_outputs_requested

typegen_outputs_requested(types_config)

Return whether the typegen config asks for any generated artifact.

encode_deterministic_json

encode_deterministic_json(data, *, indent=2, serializer=None)

Encode JSON with sorted keys for deterministic output.

This is a wrapper that ensures all nested dict keys are sorted before serialization, producing byte-identical output for the same input data regardless of insertion order.

Parameters:

Name Type Description Default
data dict[str, Any]

Dictionary to encode.

required
indent int

Indentation level for formatting.

2
serializer Callable[[Any], bytes] | None

Optional custom serializer function. If not provided, uses litestar's default encode_json.

None

Returns:

Type Description
bytes

Formatted JSON bytes with sorted keys.

strip_timestamp_for_comparison

strip_timestamp_for_comparison(content)

Remove generatedAt and other timestamp fields for content comparison.

This allows comparing file content while ignoring fields that change on every generation (like timestamps).

Parameters:

Name Type Description Default
content bytes

JSON content as bytes.

required

Returns:

Type Description
bytes

JSON content with timestamp fields removed, sorted keys.

write_if_changed

write_if_changed(
    path, content, *, normalize_for_comparison=None, encoding="utf-8"
)

Write content to file only if it differs from the existing content.

Uses hash comparison to avoid unnecessary writes that would trigger file watchers and unnecessary rebuilds. Optionally normalizes content before comparison (e.g., to strip timestamps).

Parameters:

Name Type Description Default
path Path

The file path to write to.

required
content bytes | str

The content to write (bytes or str).

required
normalize_for_comparison Callable[[bytes], bytes] | None

Optional callback to normalize content before comparison (e.g., strip timestamps). The file is written with the original content, not the normalized version.

None
encoding str

Encoding for string content.

'utf-8'

Returns:

Type Description
bool

True if file was written (content changed), False if skipped (unchanged).


Route & Inertia Page Metadata Extraction

RouteMetadata

Extracted metadata for a single Litestar route exported to routes.json and routes.ts.

Attributes:

Name Type Description
namestr

Unique route name used by the Ziggy-style route() helper.

pathstr

Normalized URL path pattern with {param} placeholders.

methodslist[str]

HTTP methods (['GET', 'POST', ...]) supported by the route.

methodstr

Primary HTTP method ('get', 'post', etc.) for the route.

paramsdict[str, str]

Mapping of URL path parameter names to TypeScript type strings.

query_paramsdict[str, str]

Mapping of query parameter names to TypeScript type strings.

componentstr | None

Associated Inertia page component name when the route is an Inertia handler.

protocolLiteral['http', 'websocket']

Route transport protocol ('http' or 'websocket').

channel_keystr | None

Associated AsyncAPI WebSocket channel key when protocol='websocket'.

extract_route_metadata

extract_route_metadata(
    app, *, only=None, exclude=None, openapi_schema=None, asyncapi_schema=None
)

Extract route metadata from a Litestar application.

Note

openapi_schema is used to resolve accurate type component references. If not provided, it will be generated from the application automatically.

Returns:

Type Description
list[RouteMetadata]

A list of RouteMetadata objects.

generate_routes_json

generate_routes_json(
    app,
    *,
    only=None,
    exclude=None,
    include_components=False,
    openapi_schema=None,
    asyncapi_schema=None,
    routes_metadata=None,
)

Generate Ziggy-compatible routes JSON.

The output is deterministic: routes are sorted by name to produce byte-identical output for the same input data.

Returns:

Type Description
dict[str, Any]

A Ziggy-compatible routes payload as a dictionary with sorted keys.

generate_routes_ts

generate_routes_ts(
    app,
    *,
    only=None,
    exclude=None,
    openapi_schema=None,
    asyncapi_schema=None,
    global_route=False,
    routes_metadata=None,
)

Generate typed routes TypeScript file (Ziggy-style).

The output is deterministic: routes are sorted by name to produce byte-identical output for the same input data.

Returns:

Type Description
str

The generated TypeScript source.

InertiaPageMetadata

Metadata for a single Inertia page component and its extracted prop types.

Attributes:

Name Type Description
componentstr

Inertia page component name (for example, 'Dashboard' or 'Users/Index').

route_pathstr

URL path pattern associated with the Inertia route handler.

props_typestr | None

Inferred Python return type name for the page props.

schema_refstr | None

OpenAPI $ref reference for the page props schema when registered.

handler_namestr | None

Python function or method name of the route handler.

ts_typestr | None

Direct TypeScript type expression for inline or non-OpenAPI return types.

custom_typeslist[str]

Custom schema/type names referenced by the handler's return annotation.

wrap_with_contentbool

Whether the prop payload is wrapped inside a top-level content property.

extract_inertia_pages

extract_inertia_pages(
    app, *, openapi_schema=None, fallback_type="unknown", openapi_support=None
)

Extract Inertia page metadata from an application.

When multiple handlers map to the same component, GET handlers are preferred since Inertia pages are typically loaded via GET requests.

Parameters:

Name Type Description Default
app Litestar

Litestar application instance.

required
openapi_schema dict[str, Any] | None

Optional OpenAPI schema dict.

None
fallback_type str

TypeScript fallback type for unknown types.

'unknown'
openapi_support OpenAPISupport | None

Optional shared OpenAPISupport instance. If not provided, a new one will be created. Sharing improves determinism and performance.

None

Returns:

Type Description
list[InertiaPageMetadata]

List of InertiaPageMetadata for each discovered page.

generate_inertia_pages_json

generate_inertia_pages_json(
    app,
    *,
    openapi_schema=None,
    include_default_auth=True,
    include_default_flash=True,
    inertia_config=None,
    types_config=None,
)

Generate Inertia pages metadata JSON.

The output is deterministic: all dict keys are sorted alphabetically to produce byte-identical output for the same input data.

A single OpenAPISupport instance is shared across both page extraction and shared props building to ensure consistent schema registration and naming. This eliminates non-determinism from split schema registries.

Returns:

Type Description
dict[str, Any]

An Inertia pages metadata payload as a dictionary with sorted keys.


AsyncAPI Normalization & Export

ASYNCAPI_DOCS_DEFAULT_PATH

ASYNCAPI_DOCS_DEFAULT_PATH = '/asyncapi'

asyncapi_docs_paths

asyncapi_docs_paths(app)

Return reserved AsyncAPI documentation route prefixes.

When an AsyncAPI plugin is registered, returns a deduplicated tuple containing the default AsyncAPI documentation path ('/asyncapi') and any custom documentation path configured on the plugin. When no plugin is registered, returns an empty tuple.

Parameters:

Name Type Description Default
app Litestar

The Litestar application instance.

required

Returns:

Type Description
tuple[str, ...]

Tuple of reserved documentation path strings.

find_asyncapi_plugin

find_asyncapi_plugin(app)

Find an AsyncAPI plugin registered on the Litestar application.

Queries Litestar's plugin registry for a registered AsyncAPIPlugin, guarded by ASYNCAPI_INSTALLED.

Parameters:

Name Type Description Default
app Litestar

The Litestar application instance.

required

Returns:

Type Description
Any | None

The registered AsyncAPI plugin instance if found, otherwise None.

resolve_asyncapi_document

resolve_asyncapi_document(app, title=None, version=None)

Resolve and normalize the AsyncAPI document from a registered AsyncAPIPlugin.

Queries the Litestar application for a registered AsyncAPIPlugin via find_asyncapi_plugin. When present, retrieves the schema from the plugin via get_asyncapi_schema (or get_asyncapi_json if a non-dict is returned) and normalizes channel keys and operation references for frontend code generation. When no AsyncAPIPlugin is registered, returns None.

Parameters:

Name Type Description Default
app Litestar

The Litestar application instance.

required
title str | None

Optional title override for the AsyncAPI document.

None
version str | None

Optional version override for the AsyncAPI document.

None

Returns:

Type Description
dict[str, Any] | None

Normalized AsyncAPI document dictionary when AsyncAPIPlugin is registered,

dict[str, Any] | None

otherwise None.

normalize_asyncapi_document

normalize_asyncapi_document(document)

Normalize an AsyncAPI document into a consistent internal shape.

Guarantees that:

  1. The asyncapi version string is present ('3.0.0' or '3.1.0').
  2. Channels are re-keyed into collision-safe litestar-vite format using _ChannelKeyAllocator with protocol-aware source selection.
  3. Every channel has an explicit bindings dictionary with protocol markers.
  4. Operation channel and message $ref pointers match the allocated channel keys.
  5. Root document metadata, servers, and components are preserved intact.

Parameters:

Name Type Description Default
document dict[str, Any]

Raw AsyncAPI document dictionary.

required

Returns:

Type Description
dict[str, Any]

A normalized AsyncAPI document dictionary.

export_asyncapi

export_asyncapi(
    *, app, types_config, serializer=None, result, asyncapi_schema=None
)

Export AsyncAPI schema to file when AsyncAPIPlugin is registered.

Parameters:

Name Type Description Default
app Litestar

The Litestar application instance.

required
types_config TypeGenConfig

The type generation configuration.

required
serializer Callable[[Any], bytes] | None

Optional custom serializer for JSON encoding.

None
result ExportResult

ExportResult accumulator for exported or unchanged files.

required
asyncapi_schema dict[str, Any] | None

Optional pre-resolved AsyncAPI document dictionary.

None

ChannelKeyAllocator

Allocate collision-safe channel keys across realtime sources.

Attributes:

Name Type Description
assigneddict[tuple[str, str], str]

Previously allocated channel keys keyed by (normalized_address, source).

takenset[str]

Set of channel keys already claimed in the current document.

allocate
allocate(normalized_address, source)

Allocate a unique channel key for a given route address and source.

Two different sources at the same address deliberately receive different channel keys to prevent collisions and ensure intact operations.

Parameters:

Name Type Description Default
normalized_address str

The normalized route address string.

required
source str

Realtime source identifier ('websocket', 'channels', or 'sse').

required

Returns:

Type Description
str

Collision-safe unique channel key.

channel_key_base

channel_key_base(normalized_address)

Build a deterministic base channel key from a route address.

Strips the leading slash, splits on slash, drops empty segments, applies _slug_segment to each, and joins with double underscores. An empty result returns 'root'.

Parameters:

Name Type Description Default
normalized_address str

The normalized route path.

required

Returns:

Type Description
str

Deterministic base channel key.

extract_ws_server_url

extract_ws_server_url(asyncapi_schema)

Extract a default WebSocket server base URL from an AsyncAPI document's servers map.

Selects wss when the server protocol is wss or https, and ws when the server protocol is ws or http. Returns an empty string when no server with a valid host is configured.

Parameters:

Name Type Description Default
asyncapi_schema dict[str, Any] | None

Normalized AsyncAPI document dictionary, if available.

required

Returns:

Type Description
str

WebSocket base URL string (e.g. "wss://api.example.com/ws") or "".


Project Scaffolding

FrameworkTemplate

Configuration metadata for a built-in frontend framework scaffolding template.

Attributes:

Name Type Description
namestr

Human-readable display name for the template.

typeFrameworkType

FrameworkType enum identifier for the template.

descriptionstr

Concise description shown in the CLI template selector.

vite_pluginstr | None

Vite framework plugin package name imported in vite.config.ts, if any.

dependencieslist[str]

Runtime NPM package names added to package.json dependencies.

dev_dependencieslist[str]

Development NPM package names added to package.json devDependencies.

fileslist[str]

Relative file paths rendered by generate_project for this template.

uses_typescriptbool

Whether the template uses TypeScript by default.

has_ssrbool

Whether the template supports server-side rendering (SSR).

inertia_compatiblebool

Whether the template uses Inertia.js v2 page routing.

uses_vitebool

Whether the template builds with Vite (False for external CLI frameworks like Angular CLI).

resource_dirstr

Default frontend source directory name for the template.

TemplateContext

Context variables used when rendering frontend project scaffolding templates.

Attributes:

Name Type Description
project_namestr

Name of the project being scaffolded.

frameworkFrameworkTemplate

Selected frontend FrameworkTemplate definition.

use_typescriptbool

Generate TypeScript configuration and .ts/.tsx entrypoints.

use_tailwindbool

Include Tailwind CSS v4 dependencies and Vite plugin configuration.

vite_portint

TCP port configured for the Vite development server.

litestar_portint

TCP port configured for the Litestar ASGI server.

asset_urlstr

Base URL prefix for static and compiled assets.

resource_dirstr

Frontend source directory relative to base_dir.

bundle_dirstr

Compiled bundle output directory relative to base_dir.

static_dirstr

Static public directory relative to base_dir.

base_dirstr

Target directory where scaffolded files are written.

enable_ssrbool

Include server-side rendering (SSR) entrypoints and configuration.

enable_inertiabool

Configure the project for Inertia.js v2 hybrid rendering.

enable_typesbool

Enable automatic OpenAPI and route TypeScript code generation.

generate_zodbool

Enable Zod schema generation in TypeGenConfig.

generate_clientbool

Enable @hey-api/openapi-ts SDK client generation in TypeGenConfig.

extradict[str, Any]

Additional custom template context variables.

has_dependency
has_dependency(package_name)

Check whether the selected framework declares a package dependency.

has_dev_dependency
has_dev_dependency(package_name)

Check whether the selected framework declares a dev dependency.

to_dict
to_dict()

Convert context to dictionary for Jinja2 rendering.

Returns:

Type Description
dict[str, Any]

Dictionary of template variables.

get_available_templates

get_available_templates()

Get all available framework templates.

Returns:

Type Description
list[FrameworkTemplate]

List of available FrameworkTemplate instances.

generate_project

generate_project(output_dir, context, *, overwrite=False)

Generate project files from templates.

Parameters:

Name Type Description Default
output_dir Path

Directory to generate files in.

required
context TemplateContext

Template context with configuration.

required
overwrite bool

Whether to overwrite existing files.

False

Returns:

Type Description
list[Path]

List of generated file paths.


Diagnostics (litestar_vite.doctor) & CDN Deploy

ViteDoctor

Diagnose and fix Vite configuration issues.

Attributes:

Name Type Description
issueslist[DoctorIssue]
Default: []
vite_config_pathPath | None
Default: None
parsed_configParsedViteConfig | None
Default: None
bridge_pathPath | None
Default: None
bridge_configdict[str, Any] | None
Default: None
run
run(fix=False, no_prompt=False, *, show_config=False, runtime_checks=False)

Run diagnostics and optionally fix issues.

When fix=True, auto-fixable issues may be applied and the checks will be run again to produce an accurate final status.

Returns:

Type Description
bool

True if healthy (after fixes), False if issues remain.

DoctorIssue

Diagnostic issue detected by ViteDoctor when inspecting Python and Vite configuration.

Attributes:

Name Type Description
checkstr

Name of the diagnostic check that raised the issue.

severityLiteral['error', 'warning']

Issue severity ('error' or 'warning').

messagestr

Human-readable explanation of the configuration mismatch or problem.

fix_hintstr

Actionable remediation guidance for resolving the issue.

auto_fixablebool

Whether litestar assets doctor --fix can automatically patch this issue.

contextdict[str, Any] | None

Optional structured context values used by automatic fixers.

ViteDeployer

Deploy built Vite assets to a remote fsspec backend.

Attributes:

Name Type Description
fsAbstractFileSystem

Filesystem for deployment operations.

collect_local_files
collect_local_files()

Collect local files to publish.

Returns:

Type Description
dict[str, FileInfo]

Mapping of relative paths to file metadata.

collect_remote_files
collect_remote_files()

Collect remote files from the target storage.

Returns:

Type Description
dict[str, FileInfo]

Mapping of relative remote paths to file metadata.

compute_diff
compute_diff(local, remote, delete_orphaned)

Compute which files to upload or delete.

Parameters:

Name Type Description Default
local dict[str, FileInfo]

Local files keyed by relative path.

required
remote dict[str, FileInfo]

Remote files keyed by relative path.

required
delete_orphaned bool

Whether to remove remote-only files.

required

Returns:

Type Description
SyncPlan

SyncPlan listing upload and delete actions.

sync
sync(*, dry_run=False, on_progress=None)

Sync local bundle to remote storage.

Uploads modified or missing local assets and removes remote orphaned assets when configured. S3-compatible backends (s3, s3a) receive the PascalCase 'ContentType' parameter required by boto3, while other backends (such as GCS or Azure Blob Storage) receive the lowercase 'content_type' parameter.

Parameters:

Name Type Description Default
dry_run bool

When True, compute the plan without uploading or deleting.

False
on_progress Callable[[str, str], None] | None

Optional callback receiving an action and path for each step.

None

Returns:

Type Description
SyncResult

SyncResult summarizing the deployment.

FileInfo

Lightweight file metadata used for CDN deployment sync planning.

Attributes:

Name Type Description
pathstr

Relative file path within the bundle or remote storage directory.

sizeint

File size in bytes.

mtimefloat

Last-modified POSIX timestamp in seconds.

SyncPlan

Computed differential upload and deletion plan for CDN deployment.

Attributes:

Name Type Description
to_uploadlist[str]

Relative paths of local bundle files scheduled for upload.

to_deletelist[str]

Relative paths of orphaned remote files scheduled for deletion.

SyncResult

Summary of a completed or dry-run CDN deployment synchronization.

Attributes:

Name Type Description
uploadedlist[str]

Relative paths of files uploaded to remote storage.

deletedlist[str]

Relative paths of orphaned files removed from remote storage.

uploaded_bytesint

Total bytes uploaded across all transferred files.

deleted_bytesint

Total bytes reclaimed from deleted remote files.

dry_runbool

Whether the synchronization ran in dry-run preview mode without mutating storage.