Phase 0: Fundament für Inhaus
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 1m14s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 1m12s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 1m7s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 1m19s
CI / PHP 8.3 / mysql:8.0 (pull_request) Successful in 1m32s
CI / PHP 8.4 / mysql:8.0 (pull_request) Successful in 1m22s
CI / PHP 8.4 / mysql:8.4 (pull_request) Successful in 1m32s
CI / PHP 8.3 / mysql:8.4 (pull_request) Successful in 1m35s
CI / Build-Artefakte aktuell (pull_request) Failing after 1m7s

- Laravel 13 mit Filament 5 (Admin), Inertia 3 + Vue 3 + Vuetify 4 (Material 3)
- Anmeldung über Fortify (Login, Passwort vergessen/ändern), keine Selbstregistrierung
- Profil mit Profilbild (WebP in festen Größen), Personenseiten, Header mit Avatar-Menü
- Material-3-Farbschema aus der Primärfarbe, hell/dunkel/System pro Person
- Basis-Branding (Portalname, Logo, Primärfarbe) im Admin unter „Erscheinungsbild“
- Benutzerverwaltung im Admin, Zugang vorläufig über is_admin
- vendor/ (ohne Dev-Pakete) und Frontend-Build mitversioniert, Dev-Pakete in vendor-dev/
- PHPUnit-Tests gegen MySQL/MariaDB, Forgejo-CI-Matrix, Docker-Entwicklungsumgebung
- VERSION, CHANGELOG.md und CONTRIBUTING.md mit Release-Ablauf

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-25 20:35:30 +00:00
parent 7197eaebf2
commit 9c0f8de791
15771 changed files with 1564103 additions and 5 deletions

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) Jonathan Reinink <jonathan@reinink.ca>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,64 @@
{
"name": "inertiajs/inertia-laravel",
"type": "library",
"description": "The Laravel adapter for Inertia.js.",
"keywords": [
"laravel",
"inertia"
],
"license": "MIT",
"authors": [
{
"name": "Jonathan Reinink",
"email": "jonathan@reinink.ca",
"homepage": "https://reinink.ca"
}
],
"autoload": {
"psr-4": {
"Inertia\\": "src"
},
"files": [
"./helpers.php"
]
},
"autoload-dev": {
"psr-4": {
"Inertia\\Tests\\": "tests/"
}
},
"require": {
"php": "^8.2.0",
"ext-json": "*",
"laravel/framework": "^11.35|^12.0|^13.0",
"symfony/console": "^7.0|^8.0"
},
"require-dev": {
"guzzlehttp/guzzle": "^7.15.2|^8.0",
"orchestra/testbench": "^9.2|^10.0|^11.0",
"mockery/mockery": "^1.3.3",
"phpunit/phpunit": "^11.5|^12.0",
"laravel/pint": "^1.16",
"larastan/larastan": "^3.0"
},
"suggest": {
"ext-pcntl": "Recommended when running the Inertia SSR server via the `inertia:start-ssr` artisan command."
},
"conflict": {
"laravel/boost": "<2.5.0"
},
"scripts": {
"test": "phpunit",
"lint": "pint",
"analyze": "phpstan analyze --memory-limit=512M"
},
"extra": {
"laravel": {
"providers": [
"Inertia\\ServiceProvider"
]
}
},
"minimum-stability": "dev",
"prefer-stable": true
}

View file

@ -0,0 +1,220 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Server Side Rendering
|--------------------------------------------------------------------------
|
| These options configures if and how Inertia uses Server Side Rendering
| to pre-render the initial visits made to your application's pages.
|
| You can specify a custom SSR bundle path, or omit it to let Inertia
| try and automatically detect it for you.
|
| Do note that enabling these options will NOT automatically make SSR work,
| as a separate rendering service needs to be available. To learn more,
| please visit https://inertiajs.com/server-side-rendering
|
*/
'ssr' => [
'enabled' => (bool) env('INERTIA_SSR_ENABLED', true),
'runtime' => env('INERTIA_SSR_RUNTIME', 'node'),
'ensure_runtime_exists' => (bool) env('INERTIA_SSR_ENSURE_RUNTIME_EXISTS', false),
'url' => env('INERTIA_SSR_URL', 'http://127.0.0.1:13714'),
'hot_url' => env('INERTIA_SSR_HOT_URL'),
'timeout' => env('INERTIA_SSR_TIMEOUT'),
'ensure_bundle_exists' => (bool) env('INERTIA_SSR_ENSURE_BUNDLE_EXISTS', true),
// 'bundle' => base_path('bootstrap/ssr/ssr.mjs'),
/*
|--------------------------------------------------------------------------
| SSR Error Handling
|--------------------------------------------------------------------------
|
| When SSR rendering fails, Inertia gracefully falls back to client-side
| rendering. Set throw_on_error to true to throw an exception instead.
| This is useful for E2E testing where you want SSR errors to fail loudly.
|
| You can also listen for the Inertia\Ssr\SsrRenderFailed event to handle
| failures in your own way (e.g., logging, error tracking service).
|
*/
'throw_on_error' => (bool) env('INERTIA_SSR_THROW_ON_ERROR', false),
],
/*
|--------------------------------------------------------------------------
| Pages
|--------------------------------------------------------------------------
|
| Set `ensure_pages_exist` to true if you want to enforce that Inertia page
| components exist on disk when rendering a page. This is useful for
| catching missing or misnamed components.
|
| The `paths` and `extensions` options define where to look for page
| components and which file extensions to consider.
|
*/
'pages' => [
'ensure_pages_exist' => false,
'paths' => [
resource_path('js/pages'),
],
'extensions' => [
'js',
'jsx',
'svelte',
'ts',
'tsx',
'vue',
],
],
/*
|--------------------------------------------------------------------------
| Testing
|--------------------------------------------------------------------------
|
| When using `assertInertia`, the assertion attempts to locate the
| component as a file relative to the `pages.paths` AND with any of
| the `pages.extensions` specified above.
|
| You can disable this behavior by setting `ensure_pages_exist`
| to false.
|
*/
'testing' => [
'ensure_pages_exist' => true,
],
/*
|--------------------------------------------------------------------------
| Expose Shared Prop Keys
|--------------------------------------------------------------------------
|
| When enabled, each page response includes a `sharedProps` metadata key
| listing the top-level prop keys that were registered via `Inertia::share`.
| The frontend can use this to carry shared props over during instant visits.
|
*/
'expose_shared_prop_keys' => true,
/*
|--------------------------------------------------------------------------
| Previous URL
|--------------------------------------------------------------------------
|
| Laravel's session middleware doesn't store the previous URL and route for
| Inertia visits, as they are sent as AJAX requests. Enable this option to
| store them for client-side visits as well, excluding partial reloads.
|
*/
'store_previous_url' => false,
/*
|--------------------------------------------------------------------------
| History
|--------------------------------------------------------------------------
|
| Enable `encrypt` to encrypt page data before it is stored in the
| browser's history state, preventing sensitive information from
| being accessible after logout. Can also be enabled per-request
| or via the `inertia.encrypt` middleware.
|
*/
'history' => [
'encrypt' => (bool) env('INERTIA_ENCRYPT_HISTORY', false),
],
/*
|--------------------------------------------------------------------------
| DevTools
|--------------------------------------------------------------------------
|
| Records one entry per request to disk so the DevTools Chrome extension may
| read it back over HTTP. Recording is limited to your local environment.
| See https://inertiajs.com/docs/devtools for the gate and storage options.
|
*/
'devtools' => [
'enabled' => env('INERTIA_DEVTOOLS_ENABLED'),
'except' => ['telescope*', 'horizon*', '_inertia/devtools*'],
'storage' => [
'path' => storage_path('inertia-devtools'),
'ttl' => (int) env('INERTIA_DEVTOOLS_TTL_HOURS', 24),
'prune_interval' => (int) env('INERTIA_DEVTOOLS_PRUNE_INTERVAL_SECONDS', 300),
'limit' => (int) env('INERTIA_DEVTOOLS_LIMIT', 100),
],
'middleware' => ['web'],
'gate' => env('INERTIA_DEVTOOLS_GATE'),
'redact' => [
'keys' => [
'password',
'password_confirmation',
'current_password',
'token',
'_token',
'access_token',
'refresh_token',
'secret',
'client_secret',
'api_key',
],
'headers' => [
'cookie',
'set-cookie',
'authorization',
'proxy-authorization',
'x-xsrf-token',
'x-csrf-token',
],
],
],
];

View file

@ -0,0 +1,41 @@
<?php
use Illuminate\Contracts\Support\Arrayable;
use Inertia\Inertia;
use Inertia\Response;
use Inertia\ResponseFactory;
if (! function_exists('inertia')) {
/**
* Inertia helper.
*
* @param null|string $component
* @param array|Arrayable $props
* @return ($component is null ? ResponseFactory : Response)
*/
function inertia($component = null, $props = [])
{
$instance = Inertia::getFacadeRoot();
if ($component) {
return $instance->render($component, $props);
}
return $instance;
}
}
if (! function_exists('inertia_location')) {
/**
* Inertia location helper.
*
* @param string url
* @return Symfony\Component\HttpFoundation\Response
*/
function inertia_location($url)
{
$instance = Inertia::getFacadeRoot();
return $instance->location($url);
}
}

View file

@ -0,0 +1,5 @@
{
"notPath": [
"src/Inertia.php"
]
}

View file

@ -0,0 +1,26 @@
# Inertia
- Inertia creates fully client-side rendered SPAs without modern SPA complexity, leveraging existing server-side patterns.
- Components live in `{{ $assist->inertia()->pagesDirectory() }}` (unless specified in `vite.config.js`). Use `Inertia::render()` for server-side routing instead of Blade views.
- ALWAYS use `search-docs` tool for version-specific Inertia documentation and updated code examples.
@if($assist->hasPackage(\Laravel\Boost\Support\PackageRegistry::INERTIA_REACT))
- IMPORTANT: Activate `inertia-react-development` when working with Inertia client-side patterns.
@elseif($assist->hasPackage(\Laravel\Boost\Support\PackageRegistry::INERTIA_VUE))
- IMPORTANT: Activate `inertia-vue-development` when working with Inertia Vue client-side patterns.
@elseif($assist->hasPackage(\Laravel\Boost\Support\PackageRegistry::INERTIA_SVELTE))
- IMPORTANT: Activate `inertia-svelte-development` when working with Inertia Svelte client-side patterns.
@endif
# Inertia v3
- Use all Inertia features from v1, v2, and v3. Check the documentation before making changes to ensure the correct approach.
- New v3 features: standalone HTTP requests (`useHttp` hook), optimistic updates with automatic rollback, layout props (`useLayoutProps` hook), instant visits, simplified SSR via `@inertiajs/vite` plugin, custom exception handling for error pages.
- Carried over from v2: deferred props, infinite scroll, merging props, polling, prefetching, once props, flash data.
- When using deferred props, add an empty state with a pulsing or animated skeleton.
- Axios has been removed. Use the built-in XHR client with interceptors, or install Axios separately if needed.
- `Inertia::lazy()` / `LazyProp` has been removed. Use `Inertia::optional()` instead.
- Prop types (`Inertia::optional()`, `Inertia::defer()`, `Inertia::merge()`) work inside nested arrays with dot-notation paths.
- SSR works automatically in Vite dev mode with `@inertiajs/vite` - no separate Node.js server needed during development.
- Event renames: `invalid` is now `httpException`, `exception` is now `networkError`.
- `router.cancel()` replaced by `router.cancelAll()`.
- The `future` configuration namespace has been removed - all v2 future options are now always enabled.

View file

@ -0,0 +1,39 @@
<?php
namespace Inertia;
class AlwaysProp
{
use ResolvesCallables;
/**
* The property value.
*
* Always included in Inertia responses, bypassing partial reload filtering.
*
* @var mixed
*/
protected $value;
/**
* Create a new always property instance. Always properties are included
* in every Inertia response, even during partial reloads when only
* specific props are requested.
*
* @param mixed $value
*/
public function __construct($value)
{
$this->value = $value;
}
/**
* Resolve the property value.
*
* @return mixed
*/
public function __invoke()
{
return $this->resolveCallable($this->value);
}
}

View file

@ -0,0 +1,44 @@
<?php
namespace Inertia\Commands;
use Illuminate\Console\Command;
use Inertia\Ssr\Gateway;
use Inertia\Ssr\HasHealthCheck;
use Symfony\Component\Console\Attribute\AsCommand;
#[AsCommand(name: 'inertia:check-ssr')]
class CheckSsr extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $signature = 'inertia:check-ssr';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Check the Inertia SSR server health status';
/**
* Check the Inertia SSR server health status.
*/
public function handle(Gateway $gateway): int
{
if (! $gateway instanceof HasHealthCheck) {
$this->error('The SSR gateway does not support health checks.');
return self::FAILURE;
}
($check = $gateway->isHealthy())
? $this->info('Inertia SSR server is running.')
: $this->error('Inertia SSR server is not running.');
return $check ? self::SUCCESS : self::FAILURE;
}
}

View file

@ -0,0 +1,74 @@
<?php
namespace Inertia\Commands;
use Illuminate\Console\GeneratorCommand;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Input\InputOption;
#[AsCommand(name: 'inertia:middleware')]
class CreateMiddleware extends GeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'inertia:middleware';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new Inertia middleware';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Middleware';
/**
* Get the stub file for the generator.
*/
protected function getStub(): string
{
return __DIR__.'/../../stubs/middleware.stub';
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
*/
protected function getDefaultNamespace($rootNamespace): string
{
return $rootNamespace.'\Http\Middleware';
}
/**
* Get the console command arguments.
*
* @return array<int, array<int, mixed>>
*/
protected function getArguments(): array
{
return [
['name', InputOption::VALUE_REQUIRED, 'Name of the Middleware that should be created', 'HandleInertiaRequests'],
];
}
/**
* Get the console command options.
*
* @return array<int, array<int, mixed>>
*/
protected function getOptions(): array
{
return [
['force', null, InputOption::VALUE_NONE, 'Create the class even if the Middleware already exists'],
];
}
}

View file

@ -0,0 +1,91 @@
<?php
namespace Inertia\Commands;
use Illuminate\Console\Command;
use Inertia\Ssr\BundleDetector;
use Inertia\Ssr\SsrException;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Process\ExecutableFinder;
use Symfony\Component\Process\Process;
#[AsCommand(name: 'inertia:start-ssr')]
class StartSsr extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $signature = 'inertia:start-ssr {--runtime= : The runtime to use (e.g. `node`, `bun`, or an absolute path)}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Start the Inertia SSR server';
/**
* Start the Inertia SSR server.
*/
public function handle(): int
{
if (! config('inertia.ssr.enabled', true)) {
$this->error('Inertia SSR is not enabled. Enable it via the `inertia.ssr.enabled` config option.');
return self::FAILURE;
}
$bundle = (new BundleDetector)->detect();
$configuredBundle = config('inertia.ssr.bundle');
if ($bundle === null) {
$this->error(
$configuredBundle
? 'Inertia SSR bundle not found at the configured path: "'.$configuredBundle.'"'
: 'Inertia SSR bundle not found. Set the correct Inertia SSR bundle path in your `inertia.ssr.bundle` config.'
);
return self::FAILURE;
} elseif ($configuredBundle && $bundle !== $configuredBundle) {
$this->warn('Inertia SSR bundle not found at the configured path: "'.$configuredBundle.'"');
$this->warn('Using a default bundle instead: "'.$bundle.'"');
}
$runtime = $this->option('runtime') ?? config('inertia.ssr.runtime', 'node');
if (config('inertia.ssr.ensure_runtime_exists', false) && ! (new ExecutableFinder)->find($runtime)) {
$this->error('SSR runtime "'.$runtime.'" could not be found.');
return self::FAILURE;
}
$this->callSilently('inertia:stop-ssr');
$process = app(Process::class, ['command' => [$runtime, $bundle]]);
$process->setTimeout(null);
$process->start();
if (extension_loaded('pcntl')) {
$stop = function () use ($process) {
$process->stop();
};
pcntl_async_signals(true);
pcntl_signal(SIGINT, $stop);
pcntl_signal(SIGQUIT, $stop);
pcntl_signal(SIGTERM, $stop);
}
foreach ($process as $type => $data) {
if ($process::OUT === $type) {
$this->info(trim($data));
} else {
$this->error(trim($data));
report(new SsrException($data));
}
}
return self::SUCCESS;
}
}

View file

@ -0,0 +1,54 @@
<?php
namespace Inertia\Commands;
use Illuminate\Console\Command;
use Inertia\Ssr\HttpGateway;
use Symfony\Component\Console\Attribute\AsCommand;
#[AsCommand(name: 'inertia:stop-ssr')]
class StopSsr extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $signature = 'inertia:stop-ssr {--graceful : Return a successful exit code when the SSR server is not running}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Stop the Inertia SSR server';
/**
* Stop the Inertia SSR server.
*/
public function handle(HttpGateway $gateway): int
{
$url = $gateway->getProductionUrl('/shutdown');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
$errno = curl_errno($ch);
if ($errno === CURLE_GOT_NOTHING) {
$this->info('Inertia SSR server stopped.');
return self::SUCCESS;
}
if ($this->option('graceful') && $errno !== CURLE_OK) {
$this->comment('Inertia SSR server is not running.');
return self::SUCCESS;
}
$this->error('Unable to connect to Inertia SSR server.');
return self::FAILURE;
}
}

View file

@ -0,0 +1,7 @@
<?php
namespace Inertia;
use InvalidArgumentException;
class ComponentNotFoundException extends InvalidArgumentException {}

View file

@ -0,0 +1,20 @@
<?php
namespace Inertia;
use Illuminate\Http\Request;
class Controller
{
/**
* Handle the incoming request and render the Inertia response.
* Renders the component and props defined in the route defaults.
*/
public function __invoke(Request $request): Response
{
return Inertia::render(
$request->route()->defaults['component'],
$request->route()->defaults['props']
);
}
}

View file

@ -0,0 +1,54 @@
<?php
namespace Inertia;
class DeferProp implements Deferrable, IgnoreFirstLoad, Mergeable, Onceable, Rescuable
{
use DefersProps, MergesProps, ResolvesCallables, ResolvesOnce;
/**
* The callback to resolve the property.
*
* Loaded asynchronously after initial page render for performance.
*
* @var callable
*/
protected $callback;
/**
* Indicates if exceptions should be rescued during deferred resolution.
*
* @var bool
*/
protected $rescue;
/**
* Create a new deferred property instance. Deferred properties are excluded
* from the initial page load and only evaluated when requested by the
* frontend, improving initial page performance.
*/
public function __construct(callable $callback, ?string $group = null, bool $rescue = false)
{
$this->callback = $callback;
$this->rescue = $rescue;
$this->defer($group);
}
/**
* Resolve the property value.
*
* @return mixed
*/
public function __invoke()
{
return $this->resolveCallable($this->callback);
}
/**
* Determine if deferred resolution errors should be rescued.
*/
public function shouldRescue(): bool
{
return $this->rescue;
}
}

View file

@ -0,0 +1,18 @@
<?php
namespace Inertia;
interface Deferrable
{
/**
* Determine if this property should be deferred.
*/
public function shouldDefer(): bool;
/**
* Get the defer group for this property.
*
* @return string
*/
public function group();
}

View file

@ -0,0 +1,47 @@
<?php
namespace Inertia;
trait DefersProps
{
/**
* Indicates if the property should be deferred.
*/
protected bool $deferred = false;
/**
* The defer group.
*/
protected ?string $deferGroup = null;
/**
* Mark this property as deferred. Deferred properties are excluded
* from the initial page load and only evaluated when requested by the
* frontend, improving initial page performance.
*/
public function defer(?string $group = null): static
{
$this->deferred = true;
$this->deferGroup = $group;
return $this;
}
/**
* Determine if this property should be deferred.
*/
public function shouldDefer(): bool
{
return $this->deferred;
}
/**
* Get the defer group for this property.
*
* @return string
*/
public function group()
{
return $this->deferGroup ?? 'default';
}
}

View file

@ -0,0 +1,304 @@
<?php
namespace Inertia\DevTools;
use Illuminate\Support\Arr;
use Inertia\DevTools\Data\PropType;
class Collector
{
/** @var array<string, array<string, mixed>> */
protected array $props = [];
/** @var array{file: string, line: int}|null */
protected ?array $renderSource = null;
/** @var array<string, array{file: string, line: int}> */
protected array $shareSources = [];
/** @var array{name: string|null, uri: string, method: string}|null */
protected ?array $route = null;
/** @var array<int, string> */
protected array $sharedKeys = [];
protected ?string $routeAction = null;
/** @var array{file: string, line: int}|null */
protected ?array $actionSource = null;
protected ?string $componentPath = null;
/**
* The resolved page props, kept nested so values may be plucked per prop path.
*
* @var array<string, mixed>
*/
protected array $resolvedProps = [];
public function __construct(protected string $component, protected SourceLocator $sourceLocator) {}
public function setRenderSource(?string $file, ?int $line): void
{
if ($file !== null && $line !== null) {
$this->renderSource = ['file' => $file, 'line' => $line];
}
}
/**
* @param array<string, array{file: string, line: int}> $sources
*/
public function setShareSources(array $sources): void
{
$this->shareSources = $sources;
}
public function setRoute(?string $name, string $uri, string $method): void
{
$this->route = [
'name' => $name,
'uri' => $uri,
'method' => $method,
];
}
/**
* Set which top-level prop keys came from shared props.
*
* @param array<int, string> $keys
*/
public function setSharedKeys(array $keys): void
{
$this->sharedKeys = $keys;
}
/**
* Record a prop's Inertia wrapper type, defer group, and extended metadata.
*/
public function addProp(
string $path,
?PropType $inertiaType = null,
?string $deferGroup = null,
bool $reset = false,
bool $once = false,
?string $mergeDirection = null,
bool $deepMerge = false,
bool $rescued = false,
): void {
$this->props[$path] = [
'shared' => in_array($path, $this->sharedKeys, true),
'inertiaType' => $inertiaType?->value,
];
if ($deferGroup !== null) {
$this->props[$path]['deferGroup'] = $deferGroup;
}
if (isset($this->shareSources[$path])) {
$this->props[$path]['shareSource'] = $this->shareSources[$path];
}
if ($reset) {
$this->props[$path]['reset'] = true;
}
if ($once) {
$this->props[$path]['once'] = true;
}
if ($mergeDirection !== null) {
$this->props[$path]['mergeDirection'] = $mergeDirection;
}
if ($deepMerge) {
$this->props[$path]['deepMerge'] = true;
}
if ($rescued) {
$this->props[$path]['rescued'] = true;
}
}
/**
* Store the route action and resolve its source location.
*/
public function setRouteAction(?string $action, mixed $uses = null): void
{
if ($action === null) {
return;
}
$this->routeAction = $action;
$this->actionSource = $this->sourceLocator->resolveActionSource($action, $uses);
}
/**
* Store the resolved file path of the frontend component.
*/
public function setComponentPath(?string $path): void
{
if ($path !== null) {
$this->componentPath = $path;
}
}
/**
* Store the resolved page props. Values are plucked per prop path when the entry
* is built, so no work is spent flattening props that get pruned.
*
* @param array<string, mixed> $props
*/
public function setResolvedProps(array $props): void
{
$this->resolvedProps = $props;
}
/**
* Scan the render source file to find the line number of each non-shared prop key.
*/
protected function resolveRenderPropLines(): void
{
if ($this->renderSource === null) {
return;
}
$renderProps = collect($this->props)
->reject(fn (array $info) => $info['shared'] || isset($info['shareSource']))
->keys()
->all();
if ($renderProps === []) {
return;
}
foreach ($renderProps as $propKey) {
$line = $this->sourceLocator->findPropKeyLine(
$this->renderSource['file'],
$this->renderSource['line'],
$propKey,
);
if ($line !== null) {
$this->props[$propKey]['renderSource'] = [
'file' => $this->renderSource['file'],
'line' => $line,
];
}
}
}
/**
* Drop deep prop paths that carry no devtools metadata. Every top-level prop is
* kept so nothing disappears from the tree; nested values are rendered from the
* recorded prop values rather than one metadata row per leaf.
*
* @return array<string, array<string, mixed>>
*/
protected function pruneProps(): array
{
return collect($this->props)
->filter(fn (array $meta, string $path) => ! str_contains($path, '.') || $this->propHasMetadata($meta))
->all();
}
/**
* @param array<string, mixed> $meta
*/
protected function propHasMetadata(array $meta): bool
{
return $meta['shared'] === true
|| $meta['inertiaType'] !== null
|| count($meta) > 2;
}
/**
* Pluck the value backing each metadata node. Nested objects are stored once under
* their prop path rather than duplicated as the parent object and every exploded
* child path (e.g. `auth.user` alongside `auth.user.id`, `auth.user.name`).
*
* @param array<int, string> $paths
* @return array<string, mixed>
*/
protected function extractPropValues(array $paths): array
{
if ($this->resolvedProps === []) {
return [];
}
$normalized = $this->normalizePropValues($this->resolvedProps);
$values = [];
foreach ($paths as $path) {
if (Arr::has($normalized, $path)) {
$values[$path] = Arr::get($normalized, $path);
}
}
return $values;
}
/**
* Cast the resolved props to plain arrays and scalars so recorded values match the
* JSON the client received.
*
* @param array<string, mixed> $props
* @return array<string, mixed>
*/
protected function normalizePropValues(array $props): array
{
$encoded = json_encode($props);
if (! is_string($encoded)) {
return $props;
}
return json_decode($encoded, true);
}
/**
* Assemble the final devtools metadata array.
*
* @return array<string, mixed>
*/
public function build(): array
{
$this->resolveRenderPropLines();
$props = $this->pruneProps();
$result = [
'schemaVersion' => 1,
'props' => $props,
'component' => $this->component,
];
if ($this->renderSource !== null) {
$result['renderSource'] = $this->renderSource;
}
if ($this->route !== null) {
$result['route'] = $this->route;
}
if ($this->routeAction !== null) {
$result['route']['action'] = $this->routeAction;
}
if ($this->actionSource !== null) {
$result['route']['actionSource'] = $this->actionSource;
}
if ($this->componentPath !== null) {
$result['componentPath'] = $this->componentPath;
}
$propValues = $this->extractPropValues(array_keys($props));
if ($propValues !== []) {
$result['propValues'] = $propValues;
}
return $result;
}
}

View file

@ -0,0 +1,89 @@
<?php
namespace Inertia\DevTools\Data;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
class IncomingEntry
{
public string $id;
public ?string $tabUuid = null;
public ?string $batchId = null;
public ?string $visitId = null;
public string $timestamp;
public float $utime;
public string $method = 'GET';
public string $url = '';
public ?string $component = null;
public RequestType $requestType = RequestType::Navigate;
public int $status = 0;
public ?string $redirectLocation = null;
public float $serverTimingMs = 0.0;
/** @var array<string, mixed> */
public array $http = ['requestHeaders' => [], 'responseHeaders' => [], 'requestBody' => null, 'responseBody' => null];
/** @var array<string, mixed> */
public array $props = [];
/** @var array<string, mixed> */
public array $propValues = [];
/** @var array{name: ?string, uri: string, action: ?string, actionSource?: array{file: string, line: int}} */
public array $route = ['name' => null, 'uri' => '', 'action' => null];
/** @var array{file: string, line: int}|null */
public ?array $renderSource = null;
public ?string $componentPath = null;
public function __construct(?string $id = null)
{
$this->id = $id ?? (string) Str::ulid();
$this->utime = microtime(true);
$this->timestamp = Carbon::createFromTimestampMs((int) ($this->utime * 1000), 'UTC')->format('Y-m-d\TH:i:s.v\Z');
}
/**
* @return array<string, mixed>
*/
public function toArray(): array
{
return [
'__meta' => [
'id' => $this->id,
'tabUuid' => $this->tabUuid,
'batchId' => $this->batchId,
'timestamp' => $this->timestamp,
'utime' => $this->utime,
'method' => $this->method,
'url' => $this->url,
'component' => $this->component,
'requestType' => $this->requestType->value,
'status' => $this->status,
'redirectLocation' => $this->redirectLocation,
'serverTimingMs' => $this->serverTimingMs,
'visitId' => $this->visitId,
],
'http' => $this->http,
'props' => $this->props,
'propValues' => $this->propValues,
'route' => $this->route,
'renderSource' => $this->renderSource,
'componentPath' => $this->componentPath,
];
}
}

View file

@ -0,0 +1,13 @@
<?php
namespace Inertia\DevTools\Data;
enum PropType: string
{
case Always = 'always';
case Defer = 'defer';
case Optional = 'optional';
case Merge = 'merge';
case Scroll = 'scroll';
case Once = 'once';
}

View file

@ -0,0 +1,15 @@
<?php
namespace Inertia\DevTools\Data;
enum RequestType: string
{
case Navigate = 'navigate';
case Partial = 'partial';
case Deferred = 'deferred';
case Poll = 'poll';
case Prefetch = 'prefetch';
case Initial = 'initial';
case Http = 'http';
case Precognition = 'precognition';
}

View file

@ -0,0 +1,53 @@
<?php
namespace Inertia\DevTools;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
class DevTools
{
/**
* Route default key holding the source location where a Route::inertia() route
* was defined, used as the render source for route-defined renders.
*/
public const RENDER_SOURCE_KEY = '__inertiaDevtoolsRenderSource';
public static function enabled(): bool
{
$configured = config('inertia.devtools.enabled');
if ($configured === null) {
return app()->environment('local');
}
return (bool) $configured;
}
/**
* The recorder to report the request lifecycle to, or null when nothing should be
* recorded. Pass the request wherever one is in hand so excluded paths skip the work.
*/
public static function recorder(?Request $request = null): ?RequestRecorder
{
return static::enabledForRequest($request) ? app(RequestRecorder::class) : null;
}
/**
* Whether the given request should be recorded, defaulting to the current one so callers
* without a request in scope do not have to resolve it themselves.
*/
public static function enabledForRequest(?Request $request = null): bool
{
if (! static::enabled()) {
return false;
}
// Read without the typed config helper: a misconfigured value would throw, and this
// runs inside the app's own request, where recording must never be the thing that
// breaks the response.
$patterns = array_values(array_filter(Arr::wrap(config('inertia.devtools.except', [])), 'is_string'));
return $patterns === [] || ! ($request ?? request())->is(...$patterns);
}
}

View file

@ -0,0 +1,67 @@
<?php
namespace Inertia\DevTools;
use Illuminate\Http\Request;
class DevToolsHeader
{
/**
* Response header stamped on every response with the entry's ULID.
*/
public const DEVTOOLS_ID = 'X-Inertia-Devtools-Id';
/**
* Response header carrying the path the app is served from, set only when it is not
* the origin root. The extension fetches the entry endpoint itself, and knows the
* origin but not where within it the app lives.
*/
public const DEVTOOLS_BASE_PATH = 'X-Inertia-Devtools-Base-Path';
/**
* Response header set on every response, carrying the batch root id. The client
* forwards it as DEVTOOLS_INCOMING_PARENT on the next same-batch request so
* follow-ups (including those after a redirect) attach to the batch root.
*/
public const DEVTOOLS_OUTGOING_PARENT = 'X-Inertia-Devtools-Parent-Out';
/**
* Request header forwarded by the client to stamp the entry's batchId.
*/
public const DEVTOOLS_INCOMING_PARENT = 'X-Inertia-Devtools-Parent';
/**
* Request header carrying the extension-assigned per-tab UUID.
*/
public const DEVTOOLS_TAB = 'X-Inertia-Devtools-Tab';
/**
* Request header carrying the client visit id, used to correlate the recorded
* entry with the browser-side page state in the devtools extension.
*/
public const DEVTOOLS_VISIT = 'X-Inertia-Devtools-Visit';
/**
* Request header the client stamps on a deferred-prop follow-up visit. On the
* wire a deferred fetch is indistinguishable from a manual partial reload, so
* the extension forwards the client's deferred intent for the recorder to read.
*/
public const DEVTOOLS_DEFERRED = 'X-Inertia-Devtools-Deferred';
/**
* Request header the client stamps on a polling visit. On the wire a poll
* tick is indistinguishable from a manual reload or partial, so the
* extension forwards the client's poll intent for the recorder to read.
*/
public const DEVTOOLS_POLL = 'X-Inertia-Devtools-Poll';
/**
* Read a request header, returning null when it is absent or empty.
*/
public static function read(Request $request, string $header): ?string
{
$value = $request->header($header);
return is_string($value) && $value !== '' ? $value : null;
}
}

View file

@ -0,0 +1,82 @@
<?php
namespace Inertia\DevTools;
use Illuminate\Foundation\Http\Events\RequestHandled;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider;
use Inertia\DevTools\Http\Authorize;
use Inertia\DevTools\Http\EntriesController;
use Inertia\DevTools\Http\PreserveFlashData;
use Inertia\DevTools\Http\PreventPreviousUrlTracking;
class DevToolsServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->scoped(EntryStore::class, fn () => new EntryStore);
$this->app->scoped(SourceLocator::class, fn () => new SourceLocator);
$this->app->singleton(EntriesRepository::class, function () {
$path = config('inertia.devtools.storage.path');
return new EntriesRepository(
path: is_string($path) ? $path : storage_path('inertia-devtools'),
autoPruneHours: config()->integer('inertia.devtools.storage.ttl', 24),
);
});
// Scoped: the recorder holds per-request collection state across the lifecycle
// callbacks. It self-disables (every method no-ops) when devtools is off.
$this->app->scoped(RequestRecorder::class, fn () => new RequestRecorder);
// Only requests are recorded, so the entry is flushed once the request has been handled.
// Everything is resolved from the current container because Octane serves each request
// from a clone of the application, and that clone is where the entry was recorded.
$this->app['events']->listen(RequestHandled::class, function () {
if (! DevTools::enabled()) {
return;
}
$repository = app(EntriesRepository::class);
app(EntryStore::class)->flush($repository);
$repository->pruneIfDue();
});
}
public function boot(): void
{
if (! DevTools::enabled()) {
return;
}
$middleware = [
PreventPreviousUrlTracking::class,
...$this->routeMiddleware(),
PreserveFlashData::class,
Authorize::class,
];
Route::middleware($middleware)
->prefix('_inertia/devtools')
->group(function () {
Route::get('entries', [EntriesController::class, 'index']);
Route::get('entries/{id}', [EntriesController::class, 'show']);
});
}
/**
* The middleware the entry endpoints run before they are authorized. Defaults to the
* `web` group so the gate may authorize the user from the session it starts.
*
* @return array<int, mixed>
*/
protected function routeMiddleware(): array
{
return Arr::wrap($this->app['config']->get('inertia.devtools.middleware', ['web']));
}
}

View file

@ -0,0 +1,378 @@
<?php
namespace Inertia\DevTools;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Str;
use InvalidArgumentException;
use Throwable;
class EntriesRepository
{
protected const INDEX_FILE = '_meta.json';
protected const LAST_PRUNE_FILE = '_last_prune';
public function __construct(
protected string $path,
protected int $autoPruneHours = 24,
protected Filesystem $files = new Filesystem,
) {}
/**
* @param array<string, mixed> $data
*/
public function save(string $id, array $data): void
{
if (! $this->isValidEntryId($id)) {
throw new InvalidArgumentException('Invalid Inertia DevTools entry id.');
}
$encoded = json_encode($data, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$this->ensureDirectory();
// Filesystem::replace writes to a temp file and renames it into place, so an interrupted
// write may never leave a half-written entry: readers see the previous file or the new one.
$this->files->replace($this->filePath($id), $encoded);
$this->writeIndexMeta($id, $this->normalizeIndexMeta($data['__meta'] ?? []));
}
/**
* @return array<string, mixed>|null
*/
public function get(string $id): ?array
{
if (! $this->isValidEntryId($id)) {
return null;
}
$file = $this->filePath($id);
if (! $this->files->exists($file)) {
return null;
}
$decoded = $this->readJsonFile($file);
return is_array($decoded) ? $decoded : null;
}
/**
* All recorded entry metadata, newest first.
*
* @return array<int, array<string, mixed>>
*/
public function all(): array
{
return collect($this->readIndex())
->sortByDesc(fn (array $meta) => (string) ($meta['id'] ?? ''))
->values()
->all();
}
public function prune(int $hours): void
{
if (! $this->files->isDirectory($this->path)) {
return;
}
$cutoff = microtime(true) - ($hours * 3600);
$expired = collect($this->readIndex())
->filter(fn (array $meta) => ($meta['utime'] ?? 0) < $cutoff)
->keys()
->all();
$this->deleteEntries($expired);
}
public function enforceTabLimit(string $tabUuid, int $limit): void
{
if ($limit <= 0 || ! $this->files->isDirectory($this->path)) {
return;
}
// Keep the newest $limit entries for the tab; delete everything older.
$drop = collect($this->readIndex())
->where('tabUuid', $tabUuid)
->sortByDesc('id')
->slice($limit)
->keys()
->all();
$this->deleteEntries($drop);
}
public function pruneIfDue(): void
{
$intervalSeconds = config()->integer('inertia.devtools.storage.prune_interval', 300);
if ($intervalSeconds <= 0) {
$this->prune($this->autoPruneHours);
return;
}
$this->ensureDirectory();
$lastPrunedAt = $this->readLastPrunedAt();
if ($lastPrunedAt !== null && (time() - $lastPrunedAt) < $intervalSeconds) {
return;
}
$this->prune($this->autoPruneHours);
$this->writeLastPrunedAt(time());
}
protected function ensureDirectory(): void
{
$this->files->ensureDirectoryExists($this->path, 0700);
$gitignore = $this->path.DIRECTORY_SEPARATOR.'.gitignore';
if ($this->files->missing($gitignore)) {
$this->files->put($gitignore, "*\n");
}
}
protected function filePath(string $id): string
{
return $this->path.DIRECTORY_SEPARATOR.$id.'.json';
}
protected function isValidEntryId(string $id): bool
{
return Str::isUlid($id);
}
protected function indexPath(): string
{
return $this->path.DIRECTORY_SEPARATOR.self::INDEX_FILE;
}
protected function lastPrunePath(): string
{
return $this->path.DIRECTORY_SEPARATOR.self::LAST_PRUNE_FILE;
}
/**
* Normalize an entry's __meta for storage in the index. The full meta is kept so
* the list endpoint may filter and render without reading every entry file; the
* fields the storage layer relies on are coerced to known types.
*
* @param array<string, mixed> $meta
* @return array<string, mixed>
*/
protected function normalizeIndexMeta(array $meta): array
{
return array_merge($meta, [
'id' => (string) ($meta['id'] ?? ''),
'tabUuid' => isset($meta['tabUuid']) && is_string($meta['tabUuid']) && $meta['tabUuid'] !== '' ? $meta['tabUuid'] : null,
'utime' => isset($meta['utime']) ? (float) $meta['utime'] : microtime(true),
]);
}
/**
* @return array<string, array<string, mixed>>
*/
protected function readIndex(): array
{
// A missing or corrupt index (e.g. a write interrupted mid-rewrite) must not lose the
// entries: the per-entry files are the source of truth, so rebuild the index from them.
if ($this->files->missing($this->indexPath())) {
return $this->rebuildIndexFromFiles();
}
$decoded = $this->readJsonFile($this->indexPath());
if (! is_array($decoded)) {
return $this->rebuildIndexFromFiles();
}
return collect($decoded)
->filter(fn ($meta) => is_array($meta))
->map(fn (array $meta) => $this->normalizeIndexMeta($meta))
->all();
}
/**
* @return array<string, array<string, mixed>>
*/
protected function rebuildIndexFromFiles(): array
{
$index = $this->metaFromFiles();
if ($index !== []) {
$this->mutateIndex(fn () => $index);
}
return $index;
}
/**
* Scan the per-entry files and build the index map straight from their `__meta`.
*
* @return array<string, array<string, mixed>>
*/
protected function metaFromFiles(): array
{
return collect($this->jsonFiles())
->map(fn (string $file) => $this->readMeta($file))
->filter(fn (?array $meta) => $meta !== null && (string) ($meta['id'] ?? '') !== '')
->keyBy(fn (array $meta) => (string) $meta['id'])
->map(fn (array $meta) => $this->normalizeIndexMeta($meta))
->all();
}
/**
* @param array<string, mixed> $meta
*/
protected function writeIndexMeta(string $id, array $meta): void
{
$this->mutateIndex(function (array $index) use ($id, $meta) {
$index[$id] = $this->normalizeIndexMeta($meta);
return $index;
});
}
/**
* @param callable(array<string, array<string, mixed>>): array<string, array<string, mixed>> $mutator
*/
protected function mutateIndex(callable $mutator): void
{
$this->ensureDirectory();
$handle = @fopen($this->indexPath(), 'c+');
if ($handle === false) {
return;
}
try {
if (! flock($handle, LOCK_EX)) {
return;
}
$contents = stream_get_contents($handle);
$decoded = is_string($contents) && $contents !== '' ? json_decode($contents, true) : [];
// A corrupt on-disk index would otherwise be treated as empty, so this rewrite would
// drop every prior entry's meta. Reseed from the entry files before applying the change.
$index = is_array($decoded) ? $decoded : $this->metaFromFiles();
$index = $mutator($index);
rewind($handle);
ftruncate($handle, 0);
fwrite($handle, (string) json_encode($index, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
fflush($handle);
flock($handle, LOCK_UN);
} finally {
fclose($handle);
}
}
/**
* Delete entry files and remove them from the index in a single rewrite.
*
* @param array<int, string> $ids
*/
protected function deleteEntries(array $ids): void
{
if ($ids === []) {
return;
}
foreach ($ids as $id) {
if ($this->isValidEntryId($id)) {
$this->files->delete($this->filePath($id));
}
}
$this->mutateIndex(function (array $index) use ($ids) {
foreach ($ids as $id) {
unset($index[$id]);
}
return $index;
});
}
/**
* @return array<string, mixed>|null
*/
protected function readMeta(string $file): ?array
{
$decoded = $this->readJsonFile($file);
if (! is_array($decoded) || ! isset($decoded['__meta']) || ! is_array($decoded['__meta'])) {
return null;
}
return $decoded['__meta'];
}
protected function readLastPrunedAt(): ?int
{
$contents = $this->readLockedTextFile($this->lastPrunePath());
if ($contents === null || ! ctype_digit(trim($contents))) {
return null;
}
return (int) trim($contents);
}
protected function writeLastPrunedAt(int $timestamp): void
{
$this->files->put($this->lastPrunePath(), (string) $timestamp, lock: true);
}
/**
* @return array<string, mixed>|null
*/
protected function readJsonFile(string $file): ?array
{
$contents = $this->readLockedTextFile($file);
if ($contents === null) {
return null;
}
$decoded = json_decode($contents, true);
return is_array($decoded) ? $decoded : null;
}
protected function readLockedTextFile(string $file): ?string
{
if ($this->files->missing($file)) {
return null;
}
try {
// Filesystem::get with a lock takes a shared (LOCK_SH) read lock.
return $this->files->get($file, lock: true);
} catch (Throwable) {
return null;
}
}
/**
* @return iterable<int, string>
*/
protected function jsonFiles(): iterable
{
if (! $this->files->isDirectory($this->path)) {
return;
}
foreach ($this->files->files($this->path) as $file) {
if ($file->getExtension() !== 'json' || $file->getFilename() === self::INDEX_FILE) {
continue;
}
yield $file->getPathname();
}
}
}

View file

@ -0,0 +1,77 @@
<?php
namespace Inertia\DevTools;
use Illuminate\Support\Facades\Log;
use Inertia\DevTools\Data\IncomingEntry;
use Throwable;
class EntryStore
{
use RedactsSensitiveData;
protected const SUPPRESS_SECONDS = 30;
/**
* Deliberately static: a write failure suppresses recording for a short window. Each
* long-lived worker keeps its own breaker, and process-per-request setups reset it.
*/
protected static ?float $suppressedUntil = null;
protected ?IncomingEntry $pending = null;
public function record(IncomingEntry $entry): void
{
$this->pending = $entry;
}
public function current(): ?IncomingEntry
{
return $this->pending;
}
public function reset(): void
{
$this->pending = null;
}
public function flush(EntriesRepository $repo): void
{
$entry = $this->pending;
if ($entry === null) {
return;
}
$this->pending = null;
if (static::$suppressedUntil !== null && microtime(true) < static::$suppressedUntil) {
return;
}
try {
$repo->save($entry->id, $this->redactSensitiveStoragePayload($entry->toArray()));
if ($entry->tabUuid !== null) {
$limit = config()->integer('inertia.devtools.storage.limit', 100);
if ($limit > 0) {
$repo->enforceTabLimit($entry->tabUuid, $limit);
}
}
static::$suppressedUntil = null;
} catch (Throwable $e) {
if (static::$suppressedUntil === null) {
Log::warning('Inertia DevTools: failed to persist entry: '.$e->getMessage());
}
static::$suppressedUntil = microtime(true) + self::SUPPRESS_SECONDS;
}
}
public static function resetCircuitBreaker(): void
{
static::$suppressedUntil = null;
}
}

View file

@ -0,0 +1,36 @@
<?php
namespace Inertia\DevTools\Http;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Symfony\Component\HttpFoundation\Response;
class Authorize
{
public function handle(Request $request, Closure $next): Response
{
if ($this->allows($request)) {
return $next($request);
}
return response()->json(['message' => 'Forbidden.'], 403);
}
/**
* The local environment is always allowed, since a failing gate would lock a developer
* out of their own devtools. Everywhere else access is granted only by the configured
* gate, which decides for the authenticated user.
*/
protected function allows(Request $request): bool
{
if (app()->environment('local')) {
return true;
}
$gate = config('inertia.devtools.gate');
return is_string($gate) && $gate !== '' && Gate::forUser($request->user())->check($gate);
}
}

View file

@ -0,0 +1,59 @@
<?php
namespace Inertia\DevTools\Http;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Inertia\DevTools\EntriesRepository;
class EntriesController
{
public function __construct(protected EntriesRepository $repository) {}
/**
* @return Collection<int, array<string, mixed>>
*/
public function index(Request $request): Collection
{
$component = $request->query('component');
$include = $this->typeList($request->query('type'));
$exclude = $this->typeList($request->query('exclude'));
$offset = max(0, (int) $request->query('offset', 0));
$limit = $request->query('limit');
return collect($this->repository->all())
->when(is_string($component) && $component !== '', fn ($entries) => $entries->where('component', $component))
->when($include !== [], fn ($entries) => $entries->whereIn('requestType', $include))
->when($exclude !== [], fn ($entries) => $entries->whereNotIn('requestType', $exclude))
->when($offset > 0, fn ($entries) => $entries->slice($offset))
->when(is_numeric($limit), fn ($entries) => $entries->take(max(1, (int) $limit)))
->values();
}
/**
* @return array<string, mixed>
*/
public function show(string $id): array
{
if (! Str::isUlid($id)) {
abort(404, 'Not found.');
}
return $this->repository->get($id) ?? abort(404, 'Not found.');
}
/**
* Parse a comma-separated request-type query value into a list.
*
* @return array<int, string>
*/
protected function typeList(mixed $value): array
{
if (! is_string($value) || $value === '') {
return [];
}
return array_values(array_filter(array_map('trim', explode(',', $value))));
}
}

View file

@ -0,0 +1,26 @@
<?php
namespace Inertia\DevTools\Http;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Reflashes the session so the save closing an entry request does not age the flash data. Entries
* are fetched the moment response headers arrive, racing the redirect the app is about to follow,
* so the errors a POST flashed for that redirect would be gone before the page could read them.
*/
class PreserveFlashData
{
public function handle(Request $request, Closure $next): Response
{
$response = $next($request);
if ($request->hasSession()) {
$request->session()->reflash();
}
return $response;
}
}

View file

@ -0,0 +1,22 @@
<?php
namespace Inertia\DevTools\Http;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Marks an entry request as an XHR so the session middleware does not record it as the app's
* previous URL, which would send the app's next `back()` redirect to a devtools endpoint.
* Set here rather than trusted to the caller: `curl` and CLI tooling might not send it.
*/
class PreventPreviousUrlTracking
{
public function handle(Request $request, Closure $next): Response
{
$request->headers->set('X-Requested-With', 'XMLHttpRequest');
return $next($request);
}
}

View file

@ -0,0 +1,513 @@
<?php
namespace Inertia\DevTools;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Inertia\DevTools\Data\IncomingEntry;
use Inertia\DevTools\Data\RequestType;
use Inertia\Support\Header;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
/**
* Builds an {@see IncomingEntry} from a request/response pair plus the per-request
* collector payload. This is pure entry construction: no response mutation, no
* recording. The recorder owns lineage/header/tag concerns and hands the result here.
*/
class IncomingEntryBuilder
{
use RedactsSensitiveData;
protected const RAW_BODY_LIMIT = 256_000;
public function __construct(protected SourceLocator $sourceLocator) {}
public function build(Request $request, SymfonyResponse $response, string $id, ?string $batchId, bool $isPrefetch): IncomingEntry
{
$entry = new IncomingEntry($id);
$entry->tabUuid = DevToolsHeader::read($request, DevToolsHeader::DEVTOOLS_TAB);
$entry->batchId = $batchId;
$entry->visitId = DevToolsHeader::read($request, DevToolsHeader::DEVTOOLS_VISIT);
$entry->method = $request->getMethod();
$entry->url = $request->fullUrl();
$entry->status = $response->getStatusCode();
$entry->requestType = $this->resolveRequestType($request, $response, $isPrefetch);
$entry->redirectLocation = $this->resolveRedirectLocation($response);
$entry->serverTimingMs = $this->elapsedMs($request);
$entry->http = [
'requestHeaders' => $this->redactHeaders($request->headers->all()),
'responseHeaders' => $this->redactHeaders($response->headers->all()),
'requestBody' => $this->captureRequestBody($request),
'responseBody' => $this->captureResponseBody($request, $response),
];
$this->mergeCollectorPayload($entry, $request);
if ($this->routeIsEmpty($entry->route)) {
$entry->route = $this->routeFromRequest($request) ?? $entry->route;
}
if ($entry->renderSource === null) {
$entry->renderSource = $this->renderSourceFromRoute($request);
}
return $entry;
}
protected function mergeCollectorPayload(IncomingEntry $entry, Request $request): void
{
$payload = $request->attributes->get(RequestAttribute::PAYLOAD);
if (! is_array($payload)) {
return;
}
$entry->component = $this->stringValue($payload, 'component') ?? $entry->component;
$entry->props = $this->arrayValue($payload, 'props') ?? $entry->props;
$entry->componentPath = $this->stringValue($payload, 'componentPath') ?? $entry->componentPath;
$propValues = $this->arrayValue($payload, 'propValues');
if ($propValues !== null) {
$entry->propValues = $this->sanitizeForJson($this->redact($propValues, $this->redactKeys()));
}
$entry->route = $this->routePayload($payload) ?? $entry->route;
$entry->renderSource = $this->renderSourcePayload($payload) ?? $entry->renderSource;
}
/**
* @param array<string, mixed> $payload
*/
protected function stringValue(array $payload, string $key): ?string
{
$value = $payload[$key] ?? null;
return is_string($value) ? $value : null;
}
/**
* @param array<string, mixed> $payload
* @return array<string, mixed>|null
*/
protected function arrayValue(array $payload, string $key): ?array
{
$value = $payload[$key] ?? null;
return is_array($value) ? $value : null;
}
/**
* @param array<string, mixed> $payload
* @return array{name: ?string, uri: string, action: ?string, actionSource?: array{file: string, line: int}}|null
*/
protected function routePayload(array $payload): ?array
{
$route = $this->arrayValue($payload, 'route');
if ($route === null) {
return null;
}
$normalized = [
'name' => $route['name'] ?? null,
'uri' => (string) ($route['uri'] ?? ''),
'action' => $route['action'] ?? null,
];
$actionSource = $this->arrayValue($route, 'actionSource');
if ($actionSource !== null) {
$normalized['actionSource'] = [
'file' => (string) ($actionSource['file'] ?? ''),
'line' => (int) ($actionSource['line'] ?? 0),
];
}
return $normalized;
}
/**
* @param array<string, mixed> $payload
* @return array{file: string, line: int}|null
*/
protected function renderSourcePayload(array $payload): ?array
{
$renderSource = $this->arrayValue($payload, 'renderSource');
if ($renderSource === null) {
return null;
}
return [
'file' => (string) ($renderSource['file'] ?? ''),
'line' => (int) ($renderSource['line'] ?? 0),
];
}
protected function resolveRequestType(Request $request, SymfonyResponse $response, ?bool $isPrefetch = null): RequestType
{
$isPrefetch ??= $request->prefetch();
if ($request->header(Header::PRECOGNITION)) {
return RequestType::Precognition;
}
if (! $request->header(Header::INERTIA)) {
return $this->renderedInertiaPage($request) ? RequestType::Initial : RequestType::Http;
}
if ($request->header(DevToolsHeader::DEVTOOLS_DEFERRED)) {
return RequestType::Deferred;
}
if ($request->header(DevToolsHeader::DEVTOOLS_POLL)) {
return RequestType::Poll;
}
if ($request->header(Header::PARTIAL_COMPONENT)) {
return RequestType::Partial;
}
if ($isPrefetch) {
return RequestType::Prefetch;
}
return RequestType::Navigate;
}
/**
* A non-Inertia request that rendered an Inertia page (component present in the
* collector payload) is the app's initial page load. One that rendered no Inertia
* page is a plain HTTP request the app serves alongside Inertia.
*/
protected function renderedInertiaPage(Request $request): bool
{
$payload = $request->attributes->get(RequestAttribute::PAYLOAD);
return is_array($payload)
&& isset($payload['component'])
&& is_string($payload['component'])
&& $payload['component'] !== '';
}
protected function resolveRedirectLocation(SymfonyResponse $response): ?string
{
$inertiaLocation = $response->headers->get(Header::LOCATION);
if (is_string($inertiaLocation) && $inertiaLocation !== '') {
return $inertiaLocation;
}
$status = $response->getStatusCode();
if ($status < 300 || $status >= 400) {
return null;
}
$location = $response->headers->get('Location');
return is_string($location) && $location !== '' ? $location : null;
}
/**
* @return array{status: string, value?: mixed, reason?: string}
*/
protected function captureRequestBody(Request $request): array
{
$writeMethod = in_array($request->getMethod(), ['POST', 'PUT', 'PATCH', 'DELETE'], true);
if ($writeMethod && ! $request->header(Header::INERTIA)) {
return ['status' => 'omitted', 'reason' => 'non-inertia-request'];
}
$redactKeys = $this->redactKeys();
if ($request->isJson()) {
$body = (array) $request->json()->all();
return $body === [] ? ['status' => 'empty'] : $this->captureBodyValue($this->redact($body, $redactKeys));
}
$input = $request->all();
if ($input !== []) {
return $this->captureBodyValue($this->redact($this->summarizeUploads($input), $redactKeys));
}
return $this->captureBodyString($request->getContent() ?: null);
}
/**
* @return array{status: string, value?: mixed, reason?: string}
*/
protected function captureResponseBody(Request $request, SymfonyResponse $response): array
{
$payload = $request->attributes->get(RequestAttribute::PAYLOAD);
if (is_array($payload) && array_key_exists('responseBody', $payload)) {
return $this->captureInertiaResponseBody($payload['responseBody']);
}
return $this->captureRawResponseBody($response);
}
/**
* @return array{status: string, value?: mixed, reason?: string}
*/
protected function captureInertiaResponseBody(mixed $responseBody): array
{
if (is_string($responseBody)) {
return $this->captureBodyString($responseBody);
}
if (is_array($responseBody)) {
return $this->captureBodyValue($this->redact($this->normalizeResponseBody($responseBody), $this->redactKeys()));
}
if ($responseBody === null) {
return ['status' => 'empty'];
}
return $this->captureBodyValue($responseBody);
}
/**
* Cast the page object to the JSON the client received. Resolved props still hold live
* values here (a model, a date, the always-shared `errors` object), and the storage
* pass would replace those object leaves with a marker.
*
* @param array<array-key, mixed> $responseBody
* @return array<array-key, mixed>
*/
protected function normalizeResponseBody(array $responseBody): array
{
$encoded = json_encode($responseBody);
if (! is_string($encoded)) {
return $responseBody;
}
$decoded = json_decode($encoded, true);
return is_array($decoded) ? $decoded : $responseBody;
}
/**
* Capture the body of a non-Inertia response (plain JSON/text endpoints the app
* serves alongside Inertia). Binary, streamed, and oversized bodies are omitted.
*
* @return array{status: string, value?: mixed, reason?: string}
*/
protected function captureRawResponseBody(SymfonyResponse $response): array
{
$contentType = strtolower((string) $response->headers->get('Content-Type', ''));
if (! $this->isTextualContentType($contentType)) {
return ['status' => 'omitted', 'reason' => 'non-textual'];
}
$content = $response->getContent();
if ($content === false) {
return ['status' => 'omitted', 'reason' => 'streamed'];
}
if ($content === '') {
return ['status' => 'empty'];
}
if (strlen($content) > self::RAW_BODY_LIMIT) {
return ['status' => 'omitted', 'reason' => 'too-large'];
}
if (str_contains($contentType, 'json')) {
$decoded = json_decode($content, true);
if (is_array($decoded)) {
return $this->captureBodyValue($this->redact($decoded, $this->redactKeys()));
}
}
return $this->captureBodyString($content);
}
protected function isTextualContentType(string $contentType): bool
{
foreach (['json', 'text/', 'xml', 'javascript'] as $needle) {
if (str_contains($contentType, $needle)) {
return true;
}
}
return false;
}
/**
* @return array{status: string, value?: mixed, reason?: string}
*/
protected function captureBodyValue(mixed $value): array
{
if (! $this->isEncodable($value)) {
return ['status' => 'omitted', 'reason' => 'unserializable'];
}
return ['status' => 'present', 'value' => $value];
}
/**
* Confirm a value survives JSON encoding with the flags the repository persists it
* with. An un-encodable value would otherwise throw at save and drop the entry.
*/
protected function isEncodable(mixed $value): bool
{
return json_encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) !== false;
}
/**
* Replace individual leaf values that cannot be JSON encoded with a marker, keeping
* the surrounding structure intact. Prop values are shared verbatim by the app, so a
* single non-UTF-8 attribute must not fail the whole entry at save.
*
* @param array<array-key, mixed> $data
* @return array<array-key, mixed>
*/
protected function sanitizeForJson(array $data): array
{
return collect($data)
->map(function (mixed $value) {
if (is_array($value)) {
return $this->sanitizeForJson($value);
}
return $this->isEncodable($value) ? $value : '[UNSERIALIZABLE]';
})
->all();
}
/**
* @return array{status: string, value?: string, reason?: string}
*/
protected function captureBodyString(?string $body): array
{
if ($body === null || $body === '') {
return ['status' => 'empty'];
}
if (! mb_check_encoding($body, 'UTF-8')) {
return ['status' => 'omitted', 'reason' => 'binary'];
}
return ['status' => 'present', 'value' => $body];
}
/**
* Replace uploaded files with a lightweight summary so binary contents are never
* serialized into an entry.
*
* @param array<array-key, mixed> $input
* @return array<array-key, mixed>
*/
protected function summarizeUploads(array $input): array
{
return collect($input)
->map(function (mixed $value) {
if ($value instanceof UploadedFile) {
return $this->summarizeUpload($value);
}
return is_array($value) ? $this->summarizeUploads($value) : $value;
})
->all();
}
/**
* @return array{name: ?string, size: ?int, mimeType: ?string}
*/
protected function summarizeUpload(UploadedFile $file): array
{
return [
'name' => $file->getClientOriginalName(),
'size' => $file->isValid() ? $file->getSize() : null,
'mimeType' => $file->getClientMimeType(),
];
}
/**
* Resolve the render source for route-defined renders (Route::inertia), which have
* no user-space render call site. The definition location is captured onto the route
* defaults by the `Route::inertia()` macro when the route is registered.
*
* @return array{file: string, line: int}|null
*/
protected function renderSourceFromRoute(Request $request): ?array
{
$source = $request->route()?->defaults[DevTools::RENDER_SOURCE_KEY] ?? null;
if (! is_array($source) || ! isset($source['file'], $source['line'])) {
return null;
}
return ['file' => (string) $source['file'], 'line' => (int) $source['line']];
}
/**
* @param array{name: ?string, uri: string, action: ?string, actionSource?: array{file: string, line: int}} $route
*/
protected function routeIsEmpty(array $route): bool
{
return ($route['name'] ?? null) === null
&& $route['uri'] === ''
&& ($route['action'] ?? null) === null
&& ! array_key_exists('actionSource', $route);
}
/**
* @return array{name: ?string, uri: string, action: ?string, actionSource?: array{file: string, line: int}}|null
*/
protected function routeFromRequest(Request $request): ?array
{
$route = $request->route();
if ($route === null) {
return null;
}
$normalized = [
'name' => $route->getName(),
'uri' => '/'.ltrim($route->uri(), '/'),
'action' => $route->getActionName(),
];
$actionSource = $this->sourceLocator->resolveActionSource(
$route->getActionName(),
$route->getAction('uses')
);
if ($actionSource !== null) {
$normalized['actionSource'] = $actionSource;
}
return $normalized;
}
protected function elapsedMs(Request $request): float
{
$start = $request->attributes->get(RequestAttribute::START);
if (! is_int($start)) {
return 0.0;
}
return (hrtime(true) - $start) / 1_000_000;
}
/**
* @return array<int|string, mixed>
*/
protected function redactKeys(): array
{
return config()->array('inertia.devtools.redact.keys', []);
}
}

View file

@ -0,0 +1,121 @@
<?php
namespace Inertia\DevTools;
use Illuminate\Http\Request;
use Inertia\AlwaysProp;
use Inertia\DeferProp;
use Inertia\Deferrable;
use Inertia\DevTools\Data\PropType;
use Inertia\Mergeable;
use Inertia\MergeProp;
use Inertia\Onceable;
use Inertia\OnceProp;
use Inertia\OptionalProp;
use Inertia\ScrollProp;
use Inertia\Support\Header;
/**
* Maps Inertia prop wrapper instances to the stable metadata the extension renders.
* Pure classification: returns normalized arrays, never touches the collector or any
* global request singleton (the request is passed in explicitly).
*/
class PropClassifier
{
/**
* @return array{inertiaType: ?PropType, deferGroup: ?string, reset: bool, once: bool, mergeDirection: ?string, deepMerge: bool}
*/
public function classifyResolved(string $path, mixed $prop, Request $request): array
{
// A DeferProp only counts as deferred when it is delivered by a deferred request (the
// auto follow-up load). Resolved on a manual partial reload it behaves like a regular
// prop, so it drops its defer type and group and reads as a plain partial prop.
$isDeferredDelivery = $prop instanceof DeferProp && $this->isDeferredRequest($request);
return [
'inertiaType' => $this->classifyInertiaWrapper($prop, $isDeferredDelivery),
'deferGroup' => $this->deferGroup($prop, $isDeferredDelivery),
'reset' => in_array($path, $this->parseDevToolsHeader($request, Header::RESET), true),
'once' => $prop instanceof Onceable && $prop->shouldResolveOnce(),
'mergeDirection' => $this->mergeDirection($prop),
'deepMerge' => $this->isDeepMerge($prop),
];
}
protected function isDeferredRequest(Request $request): bool
{
return (bool) $request->header(DevToolsHeader::DEVTOOLS_DEFERRED);
}
/**
* The defer group applies to a genuinely deferred DeferProp, and to other deferrable props
* (e.g. ScrollProp) as before. A DeferProp reloaded outside a deferred request carries none.
*/
protected function deferGroup(mixed $prop, bool $isDeferredDelivery): ?string
{
if (! $prop instanceof Deferrable || ! $prop->shouldDefer()) {
return null;
}
if ($prop instanceof DeferProp && ! $isDeferredDelivery) {
return null;
}
return $prop->group();
}
/**
* A prop is a deep merge when it deep-merges nested data (`->deepMerge()`) or matches
* array items on a key (`->matchOn()`) to upsert them rather than blindly appending.
*/
protected function isDeepMerge(mixed $prop): bool
{
return $prop instanceof Mergeable && ($prop->shouldDeepMerge() || count($prop->matchesOn()) > 0);
}
/**
* Resolve how a merge/scroll prop combines with existing client data. Direction is read
* from the prop wrapper (not the page-object arrays) so it survives deep merges, which
* the page object records only under `deepMergeProps` without a direction.
*/
protected function mergeDirection(mixed $prop): ?string
{
if (! $prop instanceof Mergeable || ! $prop->shouldMerge()) {
return null;
}
$prependsNested = count($prop->prependsAtPaths()) > 0;
$appendsNested = count($prop->appendsAtPaths()) > 0;
if ($prop->prependsAtRoot() || ($prependsNested && ! $appendsNested)) {
return 'prepend';
}
return 'append';
}
/**
* Classify an Inertia prop wrapper instance into a stable token the extension
* renders as a type pill.
*/
protected function classifyInertiaWrapper(mixed $prop, bool $isDeferredDelivery): ?PropType
{
return match (true) {
$prop instanceof AlwaysProp => PropType::Always,
$prop instanceof DeferProp => $isDeferredDelivery ? PropType::Defer : null,
$prop instanceof OptionalProp => PropType::Optional,
$prop instanceof MergeProp => PropType::Merge,
$prop instanceof ScrollProp => PropType::Scroll,
$prop instanceof OnceProp => PropType::Once,
default => null,
};
}
/**
* @return array<int, string>
*/
protected function parseDevToolsHeader(Request $request, string $key): array
{
return array_filter(explode(',', (string) $request->header($key, '')));
}
}

View file

@ -0,0 +1,234 @@
<?php
namespace Inertia\DevTools;
use Illuminate\Support\Uri;
use Throwable;
trait RedactsSensitiveData
{
protected const REDACTED = '[REDACTED]';
protected const UNSERIALIZABLE = '[UNSERIALIZABLE]';
/**
* @param array<array-key, mixed> $data
* @param array<array-key, mixed> $keys
* @return array<array-key, mixed>
*/
protected function redact(array $data, array $keys): array
{
$lowered = $this->normalizeSensitiveKeys($keys);
if ($lowered === []) {
return $data;
}
return $this->redactRecursive($data, $lowered);
}
/**
* Final storage pass for entry payloads. Earlier builders redact known request
* surfaces, but this keeps persisted entries private if a future collector path
* adds sensitive data before save.
*
* @param array<string, mixed> $payload
* @return array<string, mixed>
*/
protected function redactSensitiveStoragePayload(array $payload): array
{
$keys = config()->array('inertia.devtools.redact.keys', []);
$payload = $this->redact($payload, $keys);
$payload = $this->redactUrls($payload, $keys);
$payload = $this->redactHeaderBags($payload);
return $this->sanitizeForJsonEncoding($payload);
}
/**
* @param array<array-key, mixed> $data
* @param array<int, string> $loweredKeys
* @return array<array-key, mixed>
*/
protected function redactRecursive(array $data, array $loweredKeys): array
{
return collect($data)
->map(function (mixed $value, mixed $key) use ($loweredKeys) {
if (is_string($key) && in_array(strtolower($key), $loweredKeys, true)) {
return self::REDACTED;
}
return is_array($value) ? $this->redactRecursive($value, $loweredKeys) : $value;
})
->all();
}
/**
* @param array<array-key, mixed> $headers
* @return array<array-key, string>
*/
protected function redactHeaders(array $headers): array
{
$sensitive = $this->normalizeSensitiveKeys(config()->array('inertia.devtools.redact.headers', []));
return collect($headers)
->map(function (mixed $value, mixed $name) use ($sensitive): string {
if (is_string($name) && in_array(strtolower($name), $sensitive, true)) {
return self::REDACTED;
}
return is_array($value) ? implode(', ', $value) : (string) $value;
})
->all();
}
/**
* @param array<array-key, mixed> $keys
* @return array<int, string>
*/
protected function normalizeSensitiveKeys(array $keys): array
{
$normalized = [];
foreach ($keys as $key) {
if (! is_string($key) || $key === '') {
continue;
}
$normalized[] = strtolower($key);
}
return array_values(array_unique($normalized));
}
/**
* @param array<array-key, mixed> $data
* @param array<array-key, mixed> $keys
* @return array<array-key, mixed>
*/
protected function redactUrls(array $data, array $keys): array
{
$lowered = $this->normalizeSensitiveKeys($keys);
if ($lowered === []) {
return $data;
}
return collect($data)
->map(function (mixed $value, mixed $key) use ($lowered) {
if (is_array($value)) {
return $this->redactUrls($value, $lowered);
}
if (is_string($value) && is_string($key) && in_array(strtolower($key), ['url', 'redirectlocation'], true)) {
return $this->redactUrl($value, $lowered);
}
return $value;
})
->all();
}
/**
* Redact sensitive query parameters, preserving scheme, host, path and fragment. The URL
* may be relative or malformed, so an unparseable value is returned unchanged rather
* than throwing: redaction must never break the recorder.
*
* @param array<int, string> $keys
*/
protected function redactUrl(string $url, array $keys): string
{
$lowered = $this->normalizeSensitiveKeys($keys);
if ($lowered === [] || ! str_contains($url, '?')) {
return $url;
}
try {
$uri = Uri::of($url);
$params = $uri->query()->all();
if ($params === []) {
return $url;
}
return $uri->withQuery($this->redactQueryParameters($params, $lowered), merge: false)->value();
} catch (Throwable) {
return $url;
}
}
/**
* Walk the parsed query parameters and replace the value of any sensitive key with the
* redacted marker. A sensitive key redacts its whole subtree; nested keys (e.g. from
* `filter[secret]`) are matched at their own depth.
*
* @param array<array-key, mixed> $params
* @param array<int, string> $loweredKeys
* @return array<array-key, mixed>
*/
protected function redactQueryParameters(array $params, array $loweredKeys): array
{
$result = [];
foreach ($params as $key => $value) {
if (is_string($key) && in_array(strtolower($key), $loweredKeys, true)) {
$result[$key] = self::REDACTED;
continue;
}
$result[$key] = is_array($value) ? $this->redactQueryParameters($value, $loweredKeys) : $value;
}
return $result;
}
/**
* @param array<array-key, mixed> $data
* @return array<array-key, mixed>
*/
protected function redactHeaderBags(array $data): array
{
return collect($data)
->map(function (mixed $value, mixed $key) {
if (! is_array($value)) {
return $value;
}
if (is_string($key) && in_array(strtolower($key), ['requestheaders', 'responseheaders'], true)) {
return $this->redactHeaders($value);
}
return $this->redactHeaderBags($value);
})
->all();
}
/**
* @param array<array-key, mixed> $data
* @return array<array-key, mixed>
*/
protected function sanitizeForJsonEncoding(array $data): array
{
return collect($data)
->map(function (mixed $value) {
if (is_array($value)) {
return $this->sanitizeForJsonEncoding($value);
}
return $this->isJsonEncodable($value) ? $value : self::UNSERIALIZABLE;
})
->all();
}
protected function isJsonEncodable(mixed $value): bool
{
if (is_object($value) || is_resource($value)) {
return false;
}
return json_encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) !== false;
}
}

View file

@ -0,0 +1,23 @@
<?php
namespace Inertia\DevTools;
/**
* Keys for values stashed on the request attribute bag ($request->attributes) during
* the devtools request lifecycle. Unlike DevToolsHeader, these never leave the process:
* they carry state between the recorder, the collector, and the entry builder.
*/
class RequestAttribute
{
/**
* High-resolution start time (hrtime) stamped when the request begins, used to
* compute the entry's server timing.
*/
public const START = 'inertia_devtools_start';
/**
* The collector payload (component, props, propValues, route, sources) captured
* during rendering and merged into the entry.
*/
public const PAYLOAD = 'inertia_devtools_payload';
}

View file

@ -0,0 +1,335 @@
<?php
namespace Inertia\DevTools;
use Illuminate\Http\Request;
use Illuminate\Http\Response as HttpResponse;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Str;
use Inertia\Response;
use Inertia\Support\Header;
use ReflectionMethod;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
use Throwable;
/**
* Records the Inertia request lifecycle for the devtools extension, holding the per-request
* collection state and delegating to {@see SourceLocator}, {@see PropClassifier},
* {@see Collector} and {@see IncomingEntryBuilder}.
*/
class RequestRecorder
{
/**
* @var array<string, array{file: string, line: int}>
*/
protected array $shareSources = [];
protected ?Collector $collector = null;
public function requestStarted(Request $request): void
{
if (! DevTools::enabled()) {
return;
}
$request->attributes->set(RequestAttribute::START, hrtime(true));
}
/**
* Scan the share() method source to resolve per-key line numbers.
*
* @param array<string, mixed> $shared
*/
public function sharedPropsResolved(object $middleware, array $shared): void
{
if (! DevTools::enabledForRequest()) {
return;
}
$reflection = new ReflectionMethod($middleware, 'share');
$locator = app(SourceLocator::class);
$fallback = $locator->shareSourceFallback($reflection);
if ($fallback === null) {
return;
}
foreach (array_keys($shared) as $key) {
$key = (string) $key;
$this->setShareSource([$key], $locator->resolveShareSource($reflection, $key) ?? $fallback);
}
}
/**
* Capture the call site of a share() call and associate it with the given prop keys.
*
* @param array<int, array-key> $keys
*/
public function propsShared(array $keys): void
{
if (! DevTools::enabled()) {
return;
}
$locator = app(SourceLocator::class);
$source = $locator->captureCallerSource();
if ($source === null) {
return;
}
foreach ($keys as $key) {
$key = (string) $key;
$this->shareSources[$key] = [
'file' => $source['file'],
'line' => $locator->findPropKeyLine($source['file'], $source['line'], $key) ?? $source['line'],
];
}
}
/**
* @param array<array-key, mixed> $sharedProps
*/
public function pageRendering(string $component, Response $response, array $sharedProps): void
{
if (! DevTools::enabled()) {
return;
}
$locator = app(SourceLocator::class);
$renderSource = $locator->captureCallerSource();
$collector = new Collector($component, $locator);
if ($renderSource !== null) {
$collector->setRenderSource($renderSource['file'], $renderSource['line']);
}
$collector->setShareSources($this->shareSources);
$collector->setSharedKeys($this->topLevelSharedKeys($sharedProps));
$this->collector = $collector;
}
public function propResolved(string $path, mixed $prop): void
{
$this->recordProp($path, $prop);
}
/**
* Record a deferred prop whose resolver threw but was rescued (`Inertia::defer(rescue: true)`).
* It is skipped from the response props before normal metadata collection, so it needs its
* own hook: capture the defer type/group and flag it rescued, with no resolved value.
*/
public function propRescued(string $path, mixed $prop): void
{
$this->recordProp($path, $prop, rescued: true);
}
protected function recordProp(string $path, mixed $prop, bool $rescued = false): void
{
if ($this->collector === null) {
return;
}
$meta = app(PropClassifier::class)->classifyResolved($path, $prop, app(Request::class));
$this->collector->addProp(
$path,
$meta['inertiaType'],
$meta['deferGroup'],
$meta['reset'],
$meta['once'],
$meta['mergeDirection'],
$meta['deepMerge'],
rescued: $rescued,
);
}
/**
* @param array<string, mixed> $page
* @param array<string, mixed> $resolvedProps
*/
public function pageRendered(Request $request, array $page, array $resolvedProps): void
{
if ($this->collector === null) {
return;
}
$collector = $this->collector;
if ($route = $request->route()) {
$collector->setRoute(
$route->getName(),
'/'.ltrim($route->uri(), '/'),
$request->method(),
);
$collector->setRouteAction($route->getActionName(), $route->getAction('uses'));
}
try {
$collector->setComponentPath(App::make('inertia.view-finder')->find($page['component']));
} catch (Throwable) {
}
$collector->setResolvedProps($resolvedProps);
$payload = $collector->build();
$payload['responseBody'] = $page;
$request->attributes->set(RequestAttribute::PAYLOAD, $payload);
}
public function respondedWith(Request $request, SymfonyResponse $response): void
{
if (! DevTools::enabledForRequest($request)) {
return;
}
try {
$this->recordResponse($request, $response);
} catch (Throwable) {
// Recording is a passive observer: a malformed request, an unserializable
// prop, or a misconfigured redact list must never turn the user's response
// into a 500, so the failure is swallowed and the entry dropped.
}
}
protected function recordResponse(Request $request, SymfonyResponse $response): void
{
$id = (string) Str::ulid();
$isPrefetch = $request->prefetch();
[$batchId, $parentOut] = $this->resolveLineage($request, $id);
$basePath = $request->getBaseUrl();
$response->headers->set(DevToolsHeader::DEVTOOLS_ID, $id);
$response->headers->set(DevToolsHeader::DEVTOOLS_OUTGOING_PARENT, $parentOut);
if ($basePath !== '') {
$response->headers->set(DevToolsHeader::DEVTOOLS_BASE_PATH, $basePath);
}
if ($this->isInitialHtmlResponse($request, $response)) {
$this->injectDevToolsIdTag($response, $id, $basePath);
}
$entry = app(IncomingEntryBuilder::class)->build($request, $response, $id, $batchId, $isPrefetch);
app(EntryStore::class)->record($entry);
}
/**
* Set the source location for the given shared prop keys.
*
* @param array<int, array-key> $keys
* @param array{file: string, line: int} $source
*/
protected function setShareSource(array $keys, array $source): void
{
foreach ($keys as $key) {
$this->shareSources[(string) $key] = $source;
}
}
/**
* Compute the top-level keys of the currently-shared props for DevTools
* shared-vs-render annotations.
*
* @param array<array-key, mixed> $sharedProps
* @return array<int, string>
*/
protected function topLevelSharedKeys(array $sharedProps): array
{
return collect(array_keys($sharedProps))
->map(function (mixed $key): string {
$key = (string) $key;
return str_contains($key, '.') ? strstr($key, '.', true) : $key;
})
->unique()
->values()
->all();
}
/**
* Whether this response is the initial load of an Inertia page. A plain HTML page is
* left alone: the extension reads the tag as devtools being enabled there, and would
* warn about a missing interceptor registry that was never going to appear.
*/
protected function isInitialHtmlResponse(Request $request, SymfonyResponse $response): bool
{
if ($request->header(Header::INERTIA)) {
return false;
}
if (! $response->isOk()) {
return false;
}
$payload = $request->attributes->get(RequestAttribute::PAYLOAD);
if (! is_array($payload) || ($payload['component'] ?? null) === null) {
return false;
}
$contentType = (string) $response->headers->get('Content-Type', '');
return str_contains(strtolower($contentType), 'text/html');
}
/**
* Render the entry id into the page, along with the path the app is mounted on. A panel
* that attaches after the initial load has only the DOM to read, and the entry endpoint
* lives under that same path.
*/
protected function injectDevToolsIdTag(SymfonyResponse $response, string $id, string $basePath): void
{
$content = $response->getContent();
if (! is_string($content) || $content === '' || ! str_contains($content, '</body>')) {
return;
}
$basePathAttribute = $basePath === ''
? ''
: ' data-inertia-devtools-base-path="'.e($basePath).'"';
$tag = '<script data-inertia-devtools-id'.$basePathAttribute.' type="application/json">'.json_encode($id).'</script>';
// Illuminate's setContent() replaces the response's original value with the string it is
// given. For an Inertia page that value is the root view, which is where the testing
// assertions read the page object from, so it is put back.
$original = $response instanceof HttpResponse ? $response->original : null;
$response->setContent(Str::replaceLast('</body>', $tag.'</body>', $content));
if ($response instanceof HttpResponse) {
$response->original = $original;
}
}
protected function resolveOutgoingParentId(bool $isPrefetch, string $id, ?string $batchId): string
{
if ($isPrefetch) {
return $id;
}
return $batchId ?? $id;
}
/**
* @return array{0: ?string, 1: string}
*/
protected function resolveLineage(Request $request, string $id): array
{
$isPrefetch = $request->prefetch();
$batchId = $request->header(Header::INERTIA)
? DevToolsHeader::read($request, DevToolsHeader::DEVTOOLS_INCOMING_PARENT)
: null;
return [$batchId, $this->resolveOutgoingParentId($isPrefetch, $id, $batchId)];
}
}

View file

@ -0,0 +1,246 @@
<?php
namespace Inertia\DevTools;
use Inertia\Controller;
use ReflectionFunctionAbstract;
use ReflectionMethod;
/**
* Resolves source-code locations for devtools: the caller frame of a share()/render()
* call, the line a prop key is defined on, the share() method body, and a route
* action's reflection. Pure lookup, no collector or request state.
*/
class SourceLocator
{
/** @var array<string, array<int, string>|null> */
protected array $fileCache = [];
/**
* Find the first caller frame outside of this package and vendor code.
*
* @return array{file: string, line: int}|null
*/
public function captureCallerSource(): ?array
{
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 20);
$srcDir = dirname(__DIR__);
foreach ($backtrace as $frame) {
if (($frame['class'] ?? null) === Controller::class && $frame['function'] === '__invoke') {
return null;
}
if (! isset($frame['file'], $frame['line'])) {
continue;
}
if (str_starts_with($frame['file'], $srcDir)) {
continue;
}
if (str_contains($frame['file'], DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR)) {
continue;
}
return ['file' => $frame['file'], 'line' => $frame['line']];
}
return null;
}
/**
* Resolve the source location of a shared prop key by scanning the share() method.
*
* @return array{file: string, line: int}|null
*/
public function resolveShareSource(ReflectionMethod $reflection, string $key): ?array
{
$file = $reflection->getDeclaringClass()->getFileName();
$startLine = $reflection->getStartLine();
$endLine = $reflection->getEndLine();
if (! $file || ! $startLine || ! $endLine) {
return null;
}
$line = $this->findPropKeyLine($file, $startLine, $key, $endLine);
if ($line !== null) {
return ['file' => $file, 'line' => $line];
}
if (! $this->methodBodyContains($reflection, 'parent::share(')) {
return null;
}
$parent = $reflection->getDeclaringClass()->getParentClass();
if ($parent === false || ! $parent->hasMethod('share')) {
return null;
}
return $this->resolveShareSource($parent->getMethod('share'), $key);
}
public function methodBodyContains(ReflectionMethod $reflection, string $needle): bool
{
$file = $reflection->getDeclaringClass()->getFileName();
$startLine = $reflection->getStartLine();
$endLine = $reflection->getEndLine();
if (! $file || ! $startLine || ! $endLine) {
return false;
}
$lines = $this->readSourceLines($file);
if ($lines === null) {
return false;
}
for ($i = $startLine - 1; $i < min($endLine, count($lines)); $i++) {
if (str_contains($lines[$i], $needle)) {
return true;
}
}
return false;
}
/**
* Resolve the first plausible line of a share() method body, used as a fallback
* when a specific prop key line cannot be found.
*
* @return array{file: string, line: int}|null
*/
public function shareSourceFallback(ReflectionMethod $reflection): ?array
{
$file = $reflection->getDeclaringClass()->getFileName();
$startLine = $reflection->getStartLine();
$endLine = $reflection->getEndLine();
if (! $file || ! $startLine || ! $endLine) {
return null;
}
$lines = $this->readSourceLines($file);
if ($lines === null) {
return null;
}
for ($i = $startLine - 1; $i < min($endLine, count($lines)); $i++) {
if (str_contains($lines[$i], 'function') || str_contains($lines[$i], 'return [')) {
return ['file' => $file, 'line' => $i + 1];
}
}
return ['file' => $file, 'line' => $startLine];
}
/**
* @return array<int, string>|null
*/
public function readSourceLines(?string $file): ?array
{
if (! $file) {
return null;
}
if (array_key_exists($file, $this->fileCache)) {
return $this->fileCache[$file];
}
if (! is_file($file) || ! is_readable($file)) {
return $this->fileCache[$file] = null;
}
$lines = file($file);
return $this->fileCache[$file] = ($lines === false ? null : $lines);
}
/**
* Find the source line where a prop key is defined in an array literal.
*/
public function findPropKeyLine(string $file, int $startLine, string $key, ?int $endLine = null): ?int
{
$lines = $this->readSourceLines($file);
if ($lines === null) {
return null;
}
$maxScan = min($endLine ?? $startLine + 100, count($lines));
$pattern = "/['\"]".preg_quote($key, '/')."['\"]\s*=>/";
for ($i = $startLine - 1; $i < $maxScan; $i++) {
if (preg_match($pattern, $lines[$i])) {
return $i + 1;
}
}
return null;
}
/**
* Resolve the route action source location when possible.
*
* @return array{file: string, line: int}|null
*/
public function resolveActionSource(?string $action, mixed $uses = null): ?array
{
if ($action === null) {
return null;
}
try {
$reflection = self::reflectAction($action, $uses);
if ($reflection === null) {
return null;
}
$file = $reflection->getFileName();
$line = $reflection->getStartLine();
if ($file && $line) {
return ['file' => $file, 'line' => $line];
}
} catch (\Throwable) {
return null;
}
return null;
}
/**
* Reflect a route action, covering closures, controller methods, array callables,
* and invokable controllers.
*/
protected static function reflectAction(string $action, mixed $uses): ?ReflectionFunctionAbstract
{
if ($uses instanceof \Closure) {
return new \ReflectionFunction($uses);
}
if (is_array($uses) && count($uses) === 2) {
return new ReflectionMethod($uses[0], $uses[1]);
}
if (str_contains($action, '@')) {
[$class, $method] = explode('@', $action, 2);
return new ReflectionMethod($class, $method);
}
if (is_object($uses) && method_exists($uses, '__invoke')) {
return new ReflectionMethod($uses, '__invoke');
}
if (class_exists($action) && method_exists($action, '__invoke')) {
return new ReflectionMethod($action, '__invoke');
}
return null;
}
}

View file

@ -0,0 +1,50 @@
<?php
namespace Inertia;
class Directive
{
/**
* Compile the "@inertia" Blade directive. This directive renders the
* Inertia root element with the page data, handling both client-side
* rendering and SSR fallback scenarios.
*
* @param string $expression
*/
public static function compile($expression = ''): string
{
$id = trim(trim($expression), "\'\"") ?: 'app';
$template = '<?php
$__inertiaSsrResponse = app(\Inertia\Ssr\SsrState::class)->setPage($page)->dispatch();
if ($__inertiaSsrResponse) {
echo $__inertiaSsrResponse->body;
} else {
?><script data-page="'.$id.'" type="application/json">{!! json_encode($page, JSON_HEX_TAG) !!}</script><div id="'.$id.'"></div><?php
}
?>';
return implode(' ', array_map('trim', explode("\n", $template)));
}
/**
* Compile the "@inertiaHead" Blade directive. This directive renders the
* head content for SSR responses, including meta tags, title, and other
* head elements from the server-side render.
*
* @param string $expression
*/
public static function compileHead($expression = ''): string
{
$template = '<?php
$__inertiaSsrResponse = app(\Inertia\Ssr\SsrState::class)->setPage($page)->dispatch();
if ($__inertiaSsrResponse) {
echo $__inertiaSsrResponse->head;
}
?>';
return implode(' ', array_map('trim', explode("\n", $template)));
}
}

View file

@ -0,0 +1,24 @@
<?php
namespace Inertia;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class EncryptHistoryMiddleware
{
/**
* Handle the incoming request and enable history encryption. This middleware
* enables encryption of the browser history state, providing additional
* security for sensitive data in Inertia responses.
*
* @return Response
*/
public function handle(Request $request, Closure $next)
{
Inertia::encryptHistory();
return $next($request);
}
}

View file

@ -0,0 +1,165 @@
<?php
namespace Inertia;
use Illuminate\Contracts\Http\Kernel as KernelContract;
use Illuminate\Contracts\Support\Responsable;
use Illuminate\Http\Request;
use Illuminate\Routing\Router;
use Symfony\Component\HttpFoundation\Response;
use Throwable;
class ExceptionResponse implements Responsable
{
protected ?string $component = null;
/** @var array<string, mixed> */
protected array $props = [];
protected bool $includeSharedData = false;
protected ?string $rootView = null;
/** @var class-string<Middleware>|null */
protected ?string $middlewareClass = null;
public function __construct(
public readonly Throwable $exception,
public readonly Request $request,
public readonly Response $response,
protected readonly Router $router,
protected readonly KernelContract $kernel,
) {}
/**
* @param array<string, mixed> $props
*/
public function render(string $component, array $props = []): static
{
$this->component = $component;
$this->props = $props;
return $this;
}
/**
* @param class-string<Middleware> $middlewareClass
*/
public function usingMiddleware(string $middlewareClass): static
{
$this->middlewareClass = $middlewareClass;
return $this;
}
public function withSharedData(): static
{
$this->includeSharedData = true;
return $this;
}
public function rootView(string $rootView): static
{
$this->rootView = $rootView;
return $this;
}
public function statusCode(): int
{
return $this->response->getStatusCode();
}
/**
* @param Request $request
*/
public function toResponse($request): Response
{
if ($this->component === null) {
return $this->response;
}
$middleware = $this->resolveMiddleware();
if ($middleware) {
Inertia::version(fn () => $middleware->version($this->request));
Inertia::setRootView($this->rootView ?? $middleware->rootView($this->request));
} elseif ($this->rootView) {
Inertia::setRootView($this->rootView);
}
if ($this->includeSharedData && $middleware) {
Inertia::share($middleware->share($this->request));
foreach ($middleware->shareOnce($this->request) as $key => $value) {
if ($value instanceof OnceProp) {
Inertia::share($key, $value);
} else {
Inertia::shareOnce($key, $value);
}
}
}
return Inertia::render($this->component, $this->props)
->toResponse($this->request)
->setStatusCode($this->response->getStatusCode());
}
protected function resolveMiddleware(): ?Middleware
{
if ($this->middlewareClass) {
return app($this->middlewareClass);
}
$class = $this->resolveMiddlewareFromRoute() ?? $this->resolveMiddlewareFromKernel();
if ($class) {
return app($class);
}
return null;
}
/**
* @return class-string<Middleware>|null
*/
protected function resolveMiddlewareFromRoute(): ?string
{
$route = $this->request->route();
if (! $route) {
return null;
}
foreach ($this->router->gatherRouteMiddleware($route) as $middleware) {
if (! is_string($middleware)) {
continue;
}
$class = head(explode(':', $middleware));
if (is_a($class, Middleware::class, true)) {
return $class;
}
}
return null;
}
/**
* @return class-string<Middleware>|null
*/
protected function resolveMiddlewareFromKernel(): ?string
{
foreach ($this->kernel->getMiddlewareGroups() as $group) {
foreach ($group as $middleware) {
if (is_string($middleware) && is_a($middleware, Middleware::class, true)) {
return $middleware;
}
}
}
return null;
}
}

View file

@ -0,0 +1,8 @@
<?php
namespace Inertia;
interface IgnoreFirstLoad
{
//
}

View file

@ -0,0 +1,50 @@
<?php
namespace Inertia;
use Illuminate\Support\Facades\Facade;
/**
* @method static void setRootView(string $name)
* @method static void share(string|array<array-key, mixed>|\Illuminate\Contracts\Support\Arrayable<array-key, mixed>|\Inertia\ProvidesInertiaProperties $key, mixed $value = null)
* @method static mixed getShared(string|null $key = null, mixed $default = null)
* @method static void flushShared()
* @method static void version(\Closure|string|null $version)
* @method static string getVersion()
* @method static void resolveUrlUsing(\Closure|null $urlResolver = null)
* @method static void transformComponentUsing(\Closure|null $componentTransformer = null)
* @method static void clearHistory()
* @method static void preserveFragment()
* @method static void encryptHistory(bool $encrypt = true)
* @method static void disableSsr(\Closure|bool $condition = true)
* @method static void withoutSsr(array<int, string>|string $paths)
* @method static void configureSsrRequestUsing(\Closure|null $callback = null)
* @method static \Inertia\OptionalProp optional(callable $callback)
* @method static \Inertia\DeferProp defer(callable $callback, string $group = 'default', bool $rescue = false)
* @method static \Inertia\MergeProp merge(mixed $value)
* @method static \Inertia\MergeProp deepMerge(mixed $value)
* @method static \Inertia\AlwaysProp always(mixed $value)
* @method static \Inertia\ScrollProp<mixed> scroll(mixed $value, string $wrapper = 'data', \Inertia\ProvidesScrollMetadata|callable|null $metadata = null)
* @method static \Inertia\OnceProp once(callable $value)
* @method static \Inertia\OnceProp shareOnce(string $key, callable $callback)
* @method static \Inertia\Response render(\BackedEnum|\UnitEnum|string $component, array<array-key, mixed>|\Illuminate\Contracts\Support\Arrayable<array-key, mixed>|\Inertia\ProvidesInertiaProperties $props = [])
* @method static \Symfony\Component\HttpFoundation\Response location(string|\Symfony\Component\HttpFoundation\RedirectResponse $url)
* @method static void handleExceptionsUsing(callable $callback)
* @method static \Inertia\ResponseFactory flash(\BackedEnum|\UnitEnum|string|array<string, mixed> $key, mixed $value = null)
* @method static \Illuminate\Http\RedirectResponse back(int $status = 302, array<string, string> $headers = [], mixed $fallback = false)
* @method static array<string, mixed> getFlashed(\Illuminate\Http\Request|null $request = null)
* @method static array<string, mixed> pullFlashed(\Illuminate\Http\Request|null $request = null)
* @method static void macro(string $name, object|callable $macro)
* @method static void mixin(object $mixin, bool $replace = true)
* @method static bool hasMacro(string $name)
* @method static void flushMacros()
*
* @see \Inertia\ResponseFactory
*/
class Inertia extends Facade
{
protected static function getFacadeAccessor(): string
{
return ResponseFactory::class;
}
}

View file

@ -0,0 +1,40 @@
<?php
namespace Inertia;
class MergeProp implements Mergeable, Onceable
{
use MergesProps, ResolvesCallables, ResolvesOnce;
/**
* The property value.
*
* Merged with existing client-side data during partial reloads.
*
* @var mixed
*/
protected $value;
/**
* Create a new merge property instance. Merge properties are combined
* with existing client-side data during partial reloads instead of
* completely replacing the property value.
*
* @param mixed $value
*/
public function __construct($value)
{
$this->value = $value;
$this->merge = true;
}
/**
* Resolve the property value.
*
* @return mixed
*/
public function __invoke()
{
return $this->resolveCallable($this->value);
}
}

View file

@ -0,0 +1,62 @@
<?php
namespace Inertia;
interface Mergeable
{
/**
* Mark the property for merging.
*
* @return static
*/
public function merge();
/**
* Determine if the property should be merged.
*
* @return bool
*/
public function shouldMerge();
/**
* Determine if the property should be deep merged.
*
* @return bool
*/
public function shouldDeepMerge();
/**
* Get the properties to match on for merging.
*
* @return array<int, string>
*/
public function matchesOn();
/**
* Determine if the property should be appended at the root level.
*
* @return bool
*/
public function appendsAtRoot();
/**
* Determine if the property should be prepended at the root level.
*
* @return bool
*/
public function prependsAtRoot();
/**
* Get the paths to append when merging.
*
* @return array<int, string>
*/
public function appendsAtPaths(): array;
/**
* Get the paths to prepend when merging.
*
* @return array<int, string>
*/
public function prependsAtPaths(): array;
}

View file

@ -0,0 +1,194 @@
<?php
namespace Inertia;
use Illuminate\Support\Arr;
trait MergesProps
{
/**
* Indicates if the property should be merged.
*/
protected bool $merge = false;
/**
* Indicates if the property should be deep merged.
*/
protected bool $deepMerge = false;
/**
* The properties to match on for merging.
*
* @var array<int, string>
*/
protected array $matchOn = [];
/**
* Indicates if the property values should be appended or prepended.
*/
protected bool $append = true;
/**
* The paths to append.
*
* @var array<int, string>
*/
protected array $appendsAtPaths = [];
/**
* The paths to prepend.
*
* @var array<int, string>
*/
protected array $prependsAtPaths = [];
/**
* Mark the property for merging.
*/
public function merge(): static
{
$this->merge = true;
return $this;
}
/**
* Mark the property for deep merging.
*/
public function deepMerge(): static
{
$this->deepMerge = true;
return $this->merge();
}
/**
* Set the properties to match on for merging.
*
* @param string|array<int, string> $matchOn
*/
public function matchOn(string|array $matchOn): static
{
$this->matchOn = Arr::wrap($matchOn);
return $this;
}
/**
* Determine if the property should be merged.
*/
public function shouldMerge(): bool
{
return $this->merge;
}
/**
* Determine if the property should be deep merged.
*/
public function shouldDeepMerge(): bool
{
return $this->deepMerge;
}
/**
* Get the properties to match on for merging.
*
* @return array<int, string>
*/
public function matchesOn(): array
{
return $this->matchOn;
}
/**
* Determine if the property should be appended at the root level.
*
* @return bool
*/
public function appendsAtRoot()
{
return $this->append && $this->mergesAtRoot();
}
/**
* Determine if the property should be prepended at the root level.
*
* @return bool
*/
public function prependsAtRoot()
{
return ! $this->append && $this->mergesAtRoot();
}
/**
* Determine if the property merges at the root level.
*/
protected function mergesAtRoot(): bool
{
return count($this->appendsAtPaths) === 0 && count($this->prependsAtPaths) === 0;
}
/**
* Specify that the value should be appended, optionally providing a key to append and a property to match on.
*
* @param bool|string|array<array-key, string> $path
*/
public function append(bool|string|array $path = true, ?string $matchOn = null): static
{
match (true) {
is_bool($path) => $this->append = $path,
is_string($path) => $this->appendsAtPaths[] = $path,
is_array($path) => collect($path)->each(
fn ($value, $key) => is_numeric($key) ? $this->append($value) : $this->append($key, $value)
),
};
if (is_string($path) && $matchOn) {
$this->matchOn([...$this->matchOn, "{$path}.{$matchOn}"]);
}
return $this;
}
/**
* Specify that the value should be prepended, optionally providing a key to prepend and a property to match on.
*
* @param bool|string|array<array-key, string> $path
*/
public function prepend(bool|string|array $path = true, ?string $matchOn = null): static
{
match (true) {
is_bool($path) => $this->append = ! $path,
is_string($path) => $this->prependsAtPaths[] = $path,
is_array($path) => collect($path)->each(
fn ($value, $key) => is_numeric($key) ? $this->prepend($value) : $this->prepend($key, $value)
),
};
if (is_string($path) && $matchOn) {
$this->matchOn([...$this->matchOn, "{$path}.{$matchOn}"]);
}
return $this;
}
/**
* Get the paths to append.
*
* @return array<int, string>
*/
public function appendsAtPaths(): array
{
return $this->appendsAtPaths;
}
/**
* Get the paths to prepend.
*
* @return array<int, string>
*/
public function prependsAtPaths(): array
{
return $this->prependsAtPaths;
}
}

View file

@ -0,0 +1,329 @@
<?php
namespace Inertia;
use Closure;
use Illuminate\Contracts\Session\Session as SessionContract;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Route;
use Illuminate\Session\Store;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\MessageBag;
use Inertia\DevTools\DevTools;
use Inertia\Ssr\ExcludesSsrPaths;
use Inertia\Ssr\Gateway;
use Inertia\Support\Header;
use Inertia\Support\SessionKey;
use Symfony\Component\HttpFoundation\Response;
class Middleware
{
/**
* The root template that's loaded on the first page visit.
*
* @see https://inertiajs.com/server-side-setup#root-template
*
* @var string
*/
protected $rootView = 'app';
/**
* Determines if validation errors should be mapped to a single error message per field.
*
* @var bool
*/
protected $withAllErrors = false;
/**
* The paths that should be excluded from server-side rendering.
*
* @var array<int, string>
*/
protected $withoutSsr = [];
/**
* Determine the current asset version.
*
* @return string|null
*/
public function version(Request $request)
{
if (config('app.asset_url')) {
return hash('xxh128', config('app.asset_url'));
}
if (file_exists($manifest = public_path('build/manifest.json'))) {
return hash_file('xxh128', $manifest);
}
if (file_exists($manifest = public_path('mix-manifest.json'))) {
return hash_file('xxh128', $manifest);
}
return null;
}
/**
* Define the props that are shared by default.
*
* @return array<string, mixed>
*/
public function share(Request $request)
{
return [
'errors' => Inertia::always($this->resolveValidationErrors($request)),
];
}
/**
* Define the props that are shared once and remembered across navigations.
*
* @return array<string, callable|OnceProp>
*/
public function shareOnce(Request $request): array
{
return [];
}
/**
* Set the root template that is loaded on the first page visit.
*
* @return string
*/
public function rootView(Request $request)
{
return $this->rootView;
}
/**
* Define a callback that returns the relative URL.
*
* @return Closure|null
*/
public function urlResolver()
{
return null;
}
/**
* Handle the incoming request.
*
* @return Response
*/
public function handle(Request $request, Closure $next)
{
$recorder = DevTools::recorder($request);
$recorder?->requestStarted($request);
Inertia::version(function () use ($request) {
return $this->version($request);
});
$shared = $this->share($request);
Inertia::share($shared);
$recorder?->sharedPropsResolved($this, $shared);
foreach ($this->shareOnce($request) as $key => $value) {
if ($value instanceof OnceProp) {
Inertia::share($key, $value);
} else {
Inertia::shareOnce($key, $value);
}
}
Inertia::setRootView($this->rootView($request));
if ($urlResolver = $this->urlResolver()) {
Inertia::resolveUrlUsing($urlResolver);
}
$ssrGateway = app(Gateway::class);
if (! empty($this->withoutSsr) && $ssrGateway instanceof ExcludesSsrPaths) {
$ssrGateway->except($this->withoutSsr);
}
$response = $next($request);
$response->headers->set('Vary', Header::INERTIA);
if ($isRedirect = $response->isRedirect()) {
$this->reflash($request);
}
if (! $request->header(Header::INERTIA)) {
$recorder?->respondedWith($request, $response);
return $response;
}
$this->storeCurrentUrl($request, $response);
if ($request->method() === 'GET' && $request->header(Header::VERSION, '') !== Inertia::getVersion()) {
$response = $this->onVersionChange($request, $response);
}
if ($response->isOk() && empty($response->getContent())) {
$response = $this->onEmptyResponse($request, $response);
}
if ($response->getStatusCode() === 302 && in_array($request->method(), ['PUT', 'PATCH', 'DELETE'])) {
$response->setStatusCode(303);
}
if ($isRedirect && $this->redirectHasFragment($response) && ! $request->prefetch()) {
$response = $this->onRedirectWithFragment($request, $response);
}
$recorder?->respondedWith($request, $response);
return $response;
}
/**
* Store the current URL and route as the previous location, which Laravel's
* session middleware skips for Inertia visits.
*/
protected function storeCurrentUrl(Request $request, Response $response): void
{
if (! $this->shouldStoreCurrentUrl($request, $response)) {
return;
}
/** @var Store $session */
$session = $request->session();
$session->setPreviousUrl($request->fullUrl());
$this->storeCurrentRoute($session, $request->route()?->getName());
}
/**
* Store the current route when supported by the Laravel version.
*/
protected function storeCurrentRoute(SessionContract $session, ?string $route): void
{
if (method_exists($session, 'setPreviousRoute')) {
$session->setPreviousRoute($route);
}
}
/**
* Determine if the visit should be stored as the previous location. Partial
* reloads are excluded, since deferred props, polling, and infinite scroll
* requests aren't navigations the user came from.
*/
public function shouldStoreCurrentUrl(Request $request, Response $response): bool
{
if (! config('inertia.store_previous_url', false) ||
! $request->hasSession() ||
! $request->isMethod('GET') ||
! $request->route() instanceof Route ||
! $request->ajax() ||
$request->prefetch() ||
$request->isPrecognitive()) {
return false;
}
return ! $this->isPartialReload($request, $response);
}
/**
* Determine if the request is a partial reload of the component that was rendered.
*/
protected function isPartialReload(Request $request, Response $response): bool
{
if (! $component = $request->header(Header::PARTIAL_COMPONENT)) {
return false;
}
return $response instanceof JsonResponse
&& $component === data_get($response->getOriginalContent(), 'component');
}
/**
* Determine if the redirect response contains a URL fragment.
*/
protected function redirectHasFragment(Response $response): bool
{
return str_contains($response->headers->get('Location', ''), '#');
}
/**
* Reflash the session data for the next request.
*/
protected function reflash(Request $request): void
{
if ($flashed = Inertia::getFlashed($request)) {
$request->session()->flash(SessionKey::FLASH_DATA, $flashed);
}
}
/**
* Handle empty responses.
*/
public function onEmptyResponse(Request $request, Response $response): Response
{
return Redirect::back();
}
/**
* Handle redirects with URL fragments.
*/
public function onRedirectWithFragment(Request $request, Response $response): Response
{
return response('', 409, [
Header::REDIRECT => $response->headers->get('Location'),
]);
}
/**
* Handle version changes.
*/
public function onVersionChange(Request $request, Response $response): Response
{
if ($request->hasSession()) {
/** @var Store $session */
$session = $request->session();
$session->reflash();
}
$response = Inertia::location($request->fullUrl());
$response->headers->set(Header::VERSION, Inertia::getVersion());
return $response;
}
/**
* Resolve validation errors for client-side use.
*
* @return object
*/
public function resolveValidationErrors(Request $request)
{
if (! $request->hasSession() || ! $request->session()->has('errors')) {
return (object) [];
}
/** @var array<string, MessageBag> $bags */
$bags = $request->session()->get('errors')->getBags();
return (object) collect($bags)->map(function ($bag) {
return (object) collect($bag->messages())->map(function ($errors) {
return $this->withAllErrors ? $errors : $errors[0];
})->toArray();
})->pipe(function ($bags) use ($request) {
if ($bags->has('default') && $request->header(Header::ERROR_BAG)) {
return [$request->header(Header::ERROR_BAG) => $bags->get('default')];
}
if ($bags->has('default')) {
return $bags->get('default');
}
return $bags->toArray();
});
}
}

View file

@ -0,0 +1,10 @@
<?php
namespace Inertia\Middleware;
use Inertia\EncryptHistoryMiddleware;
class EncryptHistory extends EncryptHistoryMiddleware
{
//
}

View file

@ -0,0 +1,55 @@
<?php
namespace Inertia\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Defer\DeferredCallbackCollection;
use Inertia\Support\Header;
use Symfony\Component\HttpFoundation\Response;
class EnsureDeferredCallbacksRun
{
/**
* Mark the pending deferred callbacks as always when the client performs the
* redirect itself, since Laravel skips them on the 409 response even
* though the request succeeded.
*/
public function handle(Request $request, Closure $next): Response
{
/** @var Response $response */
$response = $next($request);
if (! $this->isClientRedirect($response)) {
return $response;
}
$callbacks = app(DeferredCallbackCollection::class);
for ($index = 0, $count = count($callbacks); $index < $count; $index++) {
$callbacks[$index]->always();
}
return $response;
}
/**
* Determine if the response instructs the client to perform the redirect itself.
*/
protected function isClientRedirect(Response $response): bool
{
if ($response->getStatusCode() !== 409) {
return false;
}
if ($response->headers->has(Header::REDIRECT)) {
return true;
}
// A location visit caused by an asset version mismatch carries the new version
// and makes the client replay the request, so the callbacks registered by
// that replay run instead.
return $response->headers->has(Header::LOCATION)
&& ! $response->headers->has(Header::VERSION);
}
}

View file

@ -0,0 +1,30 @@
<?php
namespace Inertia\Middleware;
use Closure;
use Illuminate\Http\Request;
use Inertia\Support\Header;
use Symfony\Component\HttpFoundation\Response;
class EnsureGetOnRedirect
{
/**
* Ensure redirects after PUT/PATCH/DELETE requests result in a
* GET request by converting 302 responses to 303.
*/
public function handle(Request $request, Closure $next): Response
{
/** @var Response $response */
$response = $next($request);
if ($response->getStatusCode() === 302
&& $request->header(Header::INERTIA)
&& in_array($request->method(), ['PUT', 'PATCH', 'DELETE'])
) {
$response->setStatusCode(303);
}
return $response;
}
}

View file

@ -0,0 +1,34 @@
<?php
namespace Inertia;
class OnceProp implements Onceable
{
use ResolvesCallables, ResolvesOnce;
/**
* The callback to resolve the property.
*
* @var callable
*/
protected $callback;
/**
* Create a new once property instance.
*/
public function __construct(callable $callback)
{
$this->callback = $callback;
$this->once = true;
}
/**
* Resolve the property value.
*
* @return mixed
*/
public function __invoke()
{
return $this->resolveCallable($this->callback);
}
}

View file

@ -0,0 +1,46 @@
<?php
namespace Inertia;
use BackedEnum;
use DateInterval;
use DateTimeInterface;
use UnitEnum;
interface Onceable
{
/**
* Mark the prop to be resolved only once.
*/
public function once(bool $value = true): static;
/**
* Determine if the prop should be resolved only once.
*/
public function shouldResolveOnce(): bool;
/**
* Determine if the prop was marked as fresh.
*/
public function shouldBeRefreshed(): bool;
/**
* Get the custom key for resolving the once prop.
*/
public function getKey(): ?string;
/**
* Set a custom key for resolving the once prop.
*/
public function as(BackedEnum|UnitEnum|string $key): static;
/**
* Set the expiration for the once prop.
*/
public function until(DateTimeInterface|DateInterval|int $delay): static;
/**
* Get the expiration timestamp in milliseconds for the once prop.
*/
public function expiresAt(): ?int;
}

View file

@ -0,0 +1,37 @@
<?php
namespace Inertia;
class OptionalProp implements IgnoreFirstLoad, Onceable
{
use ResolvesCallables, ResolvesOnce;
/**
* The callback to resolve the property.
*
* Only included when explicitly requested via partial reloads.
*
* @var callable
*/
protected $callback;
/**
* Create a new optional property instance. Optional properties are only
* included when explicitly requested via partial reloads, reducing
* initial payload size and improving performance.
*/
public function __construct(callable $callback)
{
$this->callback = $callback;
}
/**
* Resolve the property value.
*
* @return mixed
*/
public function __invoke()
{
return $this->resolveCallable($this->callback);
}
}

View file

@ -0,0 +1,23 @@
<?php
namespace Inertia;
use Illuminate\Http\Request;
class PropertyContext
{
/**
* Create a new property context instance. The property context provides
* information about the current property being resolved to objects
* implementing ProvidesInertiaProperty.
*
* @param array<string, mixed> $props
*/
public function __construct(
public string $key,
public array $props,
public Request $request
) {
//
}
}

View file

@ -0,0 +1,727 @@
<?php
namespace Inertia;
use Closure;
use GuzzleHttp\Promise\PromiseInterface;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Responsable;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\App;
use Inertia\DevTools\DevTools;
use Inertia\DevTools\RequestRecorder;
use Inertia\Support\Header;
use JsonSerializable;
use Throwable;
class PropsResolver
{
use ResolvesCallables;
/**
* The current request instance.
*
* @var Request
*/
protected $request;
/**
* The component being rendered.
*
* @var string
*/
protected $component;
/**
* Whether this is a partial request for the given component.
*
* @var bool
*/
protected $isPartial;
/**
* Whether this is an Inertia request.
*
* @var bool
*/
protected $isInertia;
/**
* The props to include in the partial response.
*
* @var array<int, string>|null
*/
protected $only;
/**
* The props to exclude from the partial response.
*
* @var array<int, string>|null
*/
protected $except;
/**
* The props that should have their merge state reset.
*
* @var array<int, string>
*/
protected $resetProps;
/**
* The once-props that the client has already loaded.
*
* @var array<int, string>
*/
protected $loadedOnceProps;
/**
* The deferred props grouped by their defer group.
*
* @var array<string, array<int, string>>
*/
protected $deferredProps = [];
/**
* The deferred props that were rescued during resolution.
*
* @var array<int, string>
*/
protected $rescuedProps = [];
/**
* The props that should be appended to existing client-side data.
*
* @var array<int, string>
*/
protected $mergeProps = [];
/**
* The props that should be prepended to existing client-side data.
*
* @var array<int, string>
*/
protected $prependProps = [];
/**
* The props that should be deep merged with existing client-side data.
*
* @var array<int, string>
*/
protected $deepMergeProps = [];
/**
* The key matching strategies for mergeable props.
*
* @var array<int, string>
*/
protected $matchPropsOn = [];
/**
* The scroll pagination metadata for each scroll prop.
*
* @var array<string, array<string, mixed>>
*/
protected $scrollProps = [];
/**
* The once-prop metadata for each once prop.
*
* @var array<string, array<string, mixed>>
*/
protected $onceProps = [];
/**
* The top-level keys of shared props.
*
* @var array<int, string>
*/
protected $sharedPropKeys = [];
/**
* The devtools recorder, resolved only while recording is active. It stays null when
* devtools is disabled so the per-prop resolution loop never touches it, keeping the
* hot path free of recorder calls, container lookups, and prop classification.
*/
protected ?RequestRecorder $recorder = null;
/**
* Create a new props resolver instance.
*/
public function __construct(Request $request, string $component)
{
$this->request = $request;
$this->component = $component;
$this->isPartial = $request->header(Header::PARTIAL_COMPONENT) === $component;
$this->isInertia = (bool) $request->header(Header::INERTIA);
$this->only = $this->parseHeader(Header::PARTIAL_ONLY);
$this->except = $this->parseHeader(Header::PARTIAL_EXCEPT);
$this->resetProps = $this->parseHeader(Header::RESET) ?? [];
$this->loadedOnceProps = $this->parseHeader(Header::EXCEPT_ONCE_PROPS) ?? [];
$this->recorder = DevTools::recorder($request);
}
/**
* Resolve the given shared and page props, collecting their metadata.
*
* @param array<array-key, mixed|ProvidesInertiaProperties> $shared
* @param array<array-key, mixed|ProvidesInertiaProperties> $props
* @return array{array<string, mixed>, array<string, mixed>}
*/
public function resolve(array $shared, array $props): array
{
$props = array_merge($this->resolveSharedProps($shared), $props);
return [
$this->resolveProps($this->unpackDotProps($props)),
$this->buildMetadata(),
];
}
/**
* Resolve shared property providers and collect shared prop keys.
*
* @param array<array-key, mixed|ProvidesInertiaProperties> $shared
* @return array<string, mixed>
*/
protected function resolveSharedProps(array $shared): array
{
$resolved = $this->resolvePropertyProviders($shared);
if (! config('inertia.expose_shared_prop_keys', true)) {
return $resolved;
}
foreach (array_keys($resolved) as $key) {
$this->sharedPropKeys[] = str_contains((string) $key, '.')
? strstr((string) $key, '.', true)
: (string) $key;
}
$this->sharedPropKeys = array_values(array_unique($this->sharedPropKeys));
return $resolved;
}
/**
* Resolve ProvidesInertiaProperties instances into keyed props.
*
* @param array<array-key, mixed> $props
* @return array<string, mixed>
*/
protected function resolvePropertyProviders(array $props): array
{
$context = null;
$result = [];
foreach ($props as $key => $value) {
if (is_numeric($key) && $value instanceof ProvidesInertiaProperties) {
$context ??= new RenderContext($this->component, $this->request);
/** @var array<string, mixed> $provided */
$provided = collect($value->toInertiaProperties($context))->all();
$result = array_merge($result, $provided);
} else {
$result[$key] = $value;
}
}
return $result;
}
/**
* Build the non-empty metadata arrays for the page response.
*
* @return array<string, mixed>
*/
protected function buildMetadata(): array
{
return array_filter([
'sharedProps' => $this->sharedPropKeys,
'mergeProps' => $this->mergeProps,
'prependProps' => $this->prependProps,
'deepMergeProps' => $this->deepMergeProps,
'matchPropsOn' => $this->matchPropsOn,
'deferredProps' => $this->deferredProps,
'rescuedProps' => $this->rescuedProps,
'scrollProps' => $this->scrollProps,
'onceProps' => $this->onceProps,
], fn ($value) => count($value) > 0);
}
/**
* Recursively resolve the props tree, collecting metadata along the way.
*
* @param array<array-key, mixed> $props
* @return array<string, mixed>
*/
protected function resolveProps(array $props, string $prefix = '', bool $parentWasResolved = false): array
{
$props = $this->resolvePropertyProviders($props);
$result = [];
foreach ($props as $key => $value) {
$path = $prefix === '' ? $key : "{$prefix}.{$key}";
$prop = $value;
// On partial requests, we only include props that match the paths
// specified in the request headers. AlwaysProp instances and the
// children of already-resolved values bypass this filter.
if (! $this->shouldIncludeInPartialResponse($prop, $path, $parentWasResolved)) {
continue;
}
// On initial page loads, certain prop types (e.g. DeferProp,
// OptionalProp) are excluded before resolution to avoid
// executing their closures unnecessarily.
if (! $this->isPartial && $this->excludeFromInitialResponse($prop, $path)) {
continue;
}
$value = $this->resolveValue($prop, $path, $props);
if (in_array($path, $this->rescuedProps)) {
$this->recorder?->propRescued((string) $path, $prop);
continue;
}
// A closure may return a prop type instead of a plain value. When
// this happens, we unwrap it one more level so the prop type can
// participate in filtering and metadata collection below.
if ($value !== $prop && $this->isPropType($value)) {
$prop = $value;
// Check again after unwrapping: the resolved prop type may
// itself need to be excluded from the initial response.
if (! $this->isPartial && $this->excludeFromInitialResponse($prop, $path)) {
continue;
}
$value = $this->resolveValue($prop, $path, $props);
}
$this->collectMetadata($prop, $path);
$this->recorder?->propResolved((string) $path, $prop);
// When the resolved value is an array, we recurse into it. If the
// original prop was not already an array (e.g. a closure that
// returned one), its children bypass partial filtering.
$result[$key] = is_array($value)
? $this->resolveProps($value, $path, $parentWasResolved || ! is_array($prop))
: $value;
}
return $result;
}
/**
* Determine if a prop should be included in a partial response. AlwaysProp
* and children of already-resolved values bypass partial filtering.
*/
protected function shouldIncludeInPartialResponse(mixed $prop, string $path, bool $parentWasResolved): bool
{
if (! $this->isPartial || $prop instanceof AlwaysProp || $parentWasResolved) {
return true;
}
return $this->pathMatchesPartialRequest($path);
}
/**
* Determine if the given path matches the current partial request using
* bidirectional prefix matching on the only/except headers.
*/
protected function pathMatchesPartialRequest(string $path): bool
{
if ($this->only !== null && ! $this->matchesOnly($path) && ! $this->leadsToOnly($path)) {
return false;
}
if ($this->except !== null && $this->matchesExcept($path)) {
return false;
}
return true;
}
/**
* Determine if a prop should be excluded from the initial page response.
* Each exclusion type collects its metadata before the prop is removed.
*/
protected function excludeFromInitialResponse(mixed $prop, string $path): bool
{
// OptionalProp and DeferProp implement IgnoreFirstLoad and are never
// sent on the initial page load. They still contribute deferred,
// merge, and once metadata for the client to act on.
if ($prop instanceof IgnoreFirstLoad) {
return $this->excludeIgnoredProp($prop, $path);
}
// ScrollProp and other Deferrable types may be configured to defer
// their initial load. They contribute deferred-group and merge
// metadata so the client knows to request them separately.
if ($prop instanceof Deferrable && $prop->shouldDefer()) {
return $this->excludeDeferredProp($prop, $path);
}
// Once-props that the client has already loaded are excluded on
// subsequent Inertia visits to avoid sending duplicate data.
// The client tracks loaded once-props via the except-once header.
if ($this->isInertia && $this->wasAlreadyLoadedByClient($prop, $path)) {
return $this->excludeAlreadyLoadedProp($prop, $path);
}
return false;
}
/**
* Exclude an IgnoreFirstLoad prop from the initial response while
* collecting its deferred, merge, and once metadata.
*/
protected function excludeIgnoredProp(mixed $prop, string $path): bool
{
if ($prop instanceof Deferrable && $prop->shouldDefer()
&& ! $this->wasAlreadyLoadedByClient($prop, $path)) {
$this->collectDeferredPropMetadata($path, $prop);
}
if ($prop instanceof Mergeable && $prop->shouldMerge()) {
$this->collectMergeableMetadata($path, $prop);
}
if ($prop instanceof Onceable && $prop->shouldResolveOnce()) {
$this->collectOnceMetadata($path, $prop);
}
return true;
}
/**
* Exclude a deferred prop from the initial response while
* collecting its deferred-group and merge metadata.
*/
protected function excludeDeferredProp(Deferrable $prop, string $path): bool
{
$this->collectDeferredPropMetadata($path, $prop);
if ($prop instanceof Mergeable && $prop->shouldMerge()) {
$this->collectMergeableMetadata($path, $prop);
}
return true;
}
/**
* Exclude a once-prop that the client has already loaded while
* preserving its once metadata for the client.
*/
protected function excludeAlreadyLoadedProp(mixed $prop, string $path): bool
{
$this->collectOnceMetadata($path, $prop);
return true;
}
/**
* Determine if a once-prop has already been loaded by the client.
*/
protected function wasAlreadyLoadedByClient(mixed $prop, string $path): bool
{
return $prop instanceof Onceable
&& $prop->shouldResolveOnce()
&& ! $prop->shouldBeRefreshed()
&& in_array($prop->getKey() ?? $path, $this->loadedOnceProps);
}
/**
* Resolve a single prop value through the resolution pipeline.
*
* @param array<string, mixed> $siblings
*/
protected function resolveValue(mixed $value, string $path, array $siblings): mixed
{
if ($value instanceof ScrollProp) {
$value->configureMergeIntent($this->request);
}
$shouldRescue = $value instanceof Rescuable && $value->shouldRescue();
try {
$value = $this->resolveCallable($value);
if ($value instanceof ProvidesInertiaProperty) {
$value = $value->toInertiaProperty(new PropertyContext($path, $siblings, $this->request));
}
if ($value instanceof Arrayable) {
$value = $value->toArray();
}
if ($value instanceof PromiseInterface) {
$value = $value->wait();
}
if ($value instanceof Responsable) {
$response = $value->toResponse($this->request);
if (method_exists($response, 'getData')) {
$value = $response->getData(true);
}
}
if ($value instanceof JsonSerializable) {
$value = $value->jsonSerialize();
}
return $value;
} catch (Throwable $e) {
if (! $shouldRescue) {
throw $e;
}
report($e);
$this->rescuedProps[] = $path;
return null;
}
}
/**
* Determine if the value is a prop type that requires
* further filtering or metadata collection.
*/
protected function isPropType(mixed $value): bool
{
return $value instanceof AlwaysProp
|| $value instanceof Deferrable
|| $value instanceof IgnoreFirstLoad
|| $value instanceof Mergeable
|| $value instanceof Onceable;
}
/**
* Collect metadata for a prop that will be included in the response.
*/
protected function collectMetadata(mixed $prop, string $path): void
{
if ($prop instanceof Mergeable && $prop->shouldMerge()) {
$this->collectMergeableMetadata($path, $prop);
}
if ($prop instanceof ScrollProp) {
$this->collectScrollMetadata($path, $prop);
}
if ($prop instanceof Onceable && $prop->shouldResolveOnce()) {
$this->collectOnceMetadata($path, $prop);
}
}
/**
* Collect the deferred prop and its group.
*/
protected function collectDeferredPropMetadata(string $path, Deferrable $prop): void
{
$this->deferredProps[$prop->group()][] = $path;
}
/**
* Collect the merge strategy for a mergeable prop.
*/
protected function collectMergeableMetadata(string $path, Mergeable $prop): void
{
if (in_array($path, $this->resetProps)) {
return;
}
if ($this->isPartial && ! $this->isIncludedInPartialMetadata($path)) {
return;
}
if ($prop->shouldDeepMerge()) {
$this->deepMergeProps[] = $path;
} elseif ($prop->appendsAtRoot()) {
$this->mergeProps[] = $path;
} elseif ($prop->prependsAtRoot()) {
$this->prependProps[] = $path;
} else {
foreach ($prop->appendsAtPaths() as $appendPath) {
$this->mergeProps[] = "{$path}.{$appendPath}";
}
foreach ($prop->prependsAtPaths() as $prependPath) {
$this->prependProps[] = "{$path}.{$prependPath}";
}
}
foreach ($prop->matchesOn() as $strategy) {
$this->matchPropsOn[] = "{$path}.{$strategy}";
}
}
/**
* Collect scroll pagination metadata.
*
* @param ScrollProp<mixed> $prop
*/
protected function collectScrollMetadata(string $path, ScrollProp $prop): void
{
$this->scrollProps[$path] = [
...$prop->metadata(),
'reset' => in_array($path, $this->resetProps),
];
}
/**
* Collect once-prop metadata.
*/
protected function collectOnceMetadata(string $path, mixed $prop): void
{
if (! $prop instanceof Onceable || ! $prop->shouldResolveOnce()) {
return;
}
if ($this->isPartial && ! $this->isIncludedInPartialMetadata($path)) {
return;
}
$this->onceProps[$prop->getKey() ?? $path] = [
'prop' => $path,
'expiresAt' => $prop->expiresAt(),
];
}
/**
* Determine if the path should contribute metadata during a partial request.
*/
protected function isIncludedInPartialMetadata(string $path): bool
{
if ($this->only !== null && ! $this->matchesOnly($path)) {
return false;
}
if ($this->except !== null && $this->matchesExcept($path)) {
return false;
}
return true;
}
/**
* Determine if the path matches or is a descendant of an "only" filter path.
*/
protected function matchesOnly(string $path): bool
{
foreach ($this->only as $onlyPath) {
if ($path === $onlyPath || str_starts_with($path, "{$onlyPath}.")) {
return true;
}
}
return false;
}
/**
* Determine if the path is an ancestor of an "only" filter path.
*/
protected function leadsToOnly(string $path): bool
{
foreach ($this->only as $onlyPath) {
if (str_starts_with($onlyPath, "{$path}.")) {
return true;
}
}
return false;
}
/**
* Determine if the path matches or is a descendant of an "except" filter path.
*/
protected function matchesExcept(string $path): bool
{
foreach ($this->except as $exceptPath) {
if ($path === $exceptPath || str_starts_with($path, "{$exceptPath}.")) {
return true;
}
}
return false;
}
/**
* Unpack top-level dot-notation keys into nested arrays.
*
* @param array<array-key, mixed> $props
* @return array<array-key, mixed>
*/
protected function unpackDotProps(array $props): array
{
foreach ($props as $key => $value) {
if (! is_string($key) || ! str_contains($key, '.')) {
continue;
}
if ($value instanceof Closure) {
$value = App::call($value);
}
if ($value instanceof Arrayable) {
$value = $value->toArray();
}
$this->ensurePathIsTraversable($props, $key);
Arr::set($props, $key, $value);
unset($props[$key]);
}
return $props;
}
/**
* Resolve closures and Arrayable values along the intermediate segments
* of a dot-notation path so that Arr::set can nest into them.
*
* @param array<array-key, mixed> $props
*/
protected function ensurePathIsTraversable(array &$props, string $dotKey): void
{
$segments = explode('.', $dotKey);
array_pop($segments);
$current = &$props;
foreach ($segments as $segment) {
if (! isset($current[$segment])) {
return;
}
if ($current[$segment] instanceof Closure) {
$current[$segment] = App::call($current[$segment]);
}
if ($current[$segment] instanceof Arrayable) {
$current[$segment] = $current[$segment]->toArray();
}
if (! is_array($current[$segment])) {
return;
}
$current = &$current[$segment];
}
}
/**
* Parse a comma-separated header value into an array.
*
* @return array<int, string>|null
*/
protected function parseHeader(string $key): ?array
{
return array_filter(explode(',', $this->request->header($key, ''))) ?: null;
}
}

View file

@ -0,0 +1,15 @@
<?php
namespace Inertia;
interface ProvidesInertiaProperties
{
/**
* Get the properties to be provided to Inertia. This method allows objects
* to dynamically provide properties that will be serialized and sent
* to the frontend.
*
* @return iterable<string, mixed>
*/
public function toInertiaProperties(RenderContext $context): iterable;
}

View file

@ -0,0 +1,13 @@
<?php
namespace Inertia;
interface ProvidesInertiaProperty
{
/**
* Convert the instance to an Inertia property value. This method is called
* when the object is used as a property value in an Inertia response,
* allowing for custom serialization.
*/
public function toInertiaProperty(PropertyContext $prop): mixed;
}

View file

@ -0,0 +1,26 @@
<?php
namespace Inertia;
interface ProvidesScrollMetadata
{
/**
* Get the page name parameter.
*/
public function getPageName(): string;
/**
* Get the previous page identifier.
*/
public function getPreviousPage(): int|string|null;
/**
* Get the next page identifier.
*/
public function getNextPage(): int|string|null;
/**
* Get the current page identifier.
*/
public function getCurrentPage(): int|string|null;
}

View file

@ -0,0 +1,20 @@
<?php
namespace Inertia;
use Illuminate\Http\Request;
class RenderContext
{
/**
* Create a new render context instance. The render context provides
* information about the current Inertia render operation to objects
* implementing ProvidesInertiaProperties.
*/
public function __construct(
public string $component,
public Request $request
) {
//
}
}

View file

@ -0,0 +1,11 @@
<?php
namespace Inertia;
interface Rescuable
{
/**
* Determine if resolution errors should be rescued.
*/
public function shouldRescue(): bool;
}

View file

@ -0,0 +1,24 @@
<?php
namespace Inertia;
use Illuminate\Support\Facades\App;
trait ResolvesCallables
{
/**
* Call the given value if callable and inject its dependencies.
*/
protected function resolveCallable(mixed $value): mixed
{
return $this->useAsCallable($value) ? App::call($value) : $value;
}
/**
* Determine if the given value is callable, but not a string.
*/
protected function useAsCallable(mixed $value): bool
{
return is_object($value) && is_callable($value);
}
}

View file

@ -0,0 +1,122 @@
<?php
namespace Inertia;
use BackedEnum;
use DateInterval;
use DateTimeInterface;
use Illuminate\Support\InteractsWithTime;
use UnitEnum;
trait ResolvesOnce
{
use InteractsWithTime;
/**
* Indicates if the prop should be resolved only once.
*/
protected bool $once = false;
/**
* Indicates if the prop should be forcefully refreshed.
*/
protected bool $refresh = false;
/**
* The expiration time in seconds.
*/
protected ?int $ttl = null;
/**
* The custom key for resolving the once prop.
*/
protected ?string $key = null;
/**
* Mark the prop to be resolved only once.
*/
public function once(bool $value = true, ?string $as = null, DateTimeInterface|DateInterval|int|null $until = null): static
{
$this->once = $value;
if ($as !== null) {
$this->as($as);
}
if ($until !== null) {
$this->until($until);
}
return $this;
}
/**
* Determine if the prop should be resolved only once.
*/
public function shouldResolveOnce(): bool
{
return $this->once;
}
/**
* Determine if the prop should be forcefully refreshed.
*/
public function shouldBeRefreshed(): bool
{
return $this->refresh;
}
/**
* Get the custom key for resolving the once prop.
*/
public function getKey(): ?string
{
return $this->key;
}
/**
* Set a custom key for resolving the once prop.
*/
public function as(BackedEnum|UnitEnum|string $key): static
{
$this->key = match (true) {
$key instanceof BackedEnum => $key->value,
$key instanceof UnitEnum => $key->name,
default => $key,
};
return $this;
}
/**
* Mark the property to be forcefully sent to the client.
*/
public function fresh(bool $value = true): static
{
$this->refresh = $value;
return $this;
}
/**
* Set the expiration for the once prop.
*/
public function until(DateTimeInterface|DateInterval|int $delay): static
{
$this->ttl = $this->secondsUntil($delay);
return $this;
}
/**
* Get the expiration timestamp in milliseconds for the once prop.
*/
public function expiresAt(): ?int
{
if ($this->ttl === null) {
return null;
}
return $this->availableAt($this->ttl) * 1000;
}
}

View file

@ -0,0 +1,287 @@
<?php
namespace Inertia;
use BackedEnum;
use Closure;
use Illuminate\Contracts\Support\Responsable;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Response as ResponseFactory;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\Macroable;
use Inertia\DevTools\DevTools;
use Inertia\Ssr\SsrState;
use Inertia\Support\Header;
use Inertia\Support\SessionKey;
use UnitEnum;
class Response implements Responsable
{
use Macroable;
/**
* The name of the root component.
*
* @var string
*/
protected $component;
/**
* The page props.
*
* @var array<string, mixed>
*/
protected $props;
/**
* The name of the root view.
*
* @var string
*/
protected $rootView;
/**
* The asset version.
*
* @var string
*/
protected $version;
/**
* Indicates if the browser history should be cleared.
*
* @var bool
*/
protected $clearHistory;
/**
* Indicates if the URL fragment should be preserved across redirects.
*
* @var bool
*/
protected $preserveFragment;
/**
* Indicates if the browser history should be encrypted.
*
* @var bool
*/
protected $encryptHistory;
/**
* The view data.
*
* @var array<string, mixed>
*/
protected $viewData = [];
/**
* The URL resolver callback.
*/
protected ?Closure $urlResolver = null;
/**
* The shared properties (before merge with page props).
*
* @var array<array-key, mixed|ProvidesInertiaProperties>
*/
protected array $sharedProps = [];
/**
* Create a new Inertia response instance.
*
* @param array<array-key, mixed|ProvidesInertiaProperties> $sharedProps
* @param array<array-key, mixed|ProvidesInertiaProperties> $props
*/
public function __construct(
string $component,
array $sharedProps,
array $props,
string $rootView = 'app',
string $version = '',
bool $encryptHistory = false,
?Closure $urlResolver = null,
) {
$this->component = $component;
$this->sharedProps = $sharedProps;
$this->props = $props;
$this->rootView = $rootView;
$this->version = $version;
$this->clearHistory = session()->pull(SessionKey::CLEAR_HISTORY, false);
$this->preserveFragment = session()->pull(SessionKey::PRESERVE_FRAGMENT, false);
$this->encryptHistory = $encryptHistory;
$this->urlResolver = $urlResolver;
}
/**
* Add additional properties to the page.
*
* @param string|array<string, mixed>|ProvidesInertiaProperties $key
* @param mixed $value
* @return $this
*/
public function with($key, $value = null): self
{
if ($key instanceof ProvidesInertiaProperties) {
$this->props[] = $key;
} elseif (is_array($key)) {
$this->props = array_merge($this->props, $key);
} else {
$this->props[$key] = $value;
}
return $this;
}
/**
* Add additional data to the view.
*
* @param string|array<string, mixed> $key
* @param mixed $value
* @return $this
*/
public function withViewData($key, $value = null): self
{
if (is_array($key)) {
$this->viewData = array_merge($this->viewData, $key);
} else {
$this->viewData[$key] = $value;
}
return $this;
}
/**
* Set the root view.
*
* @return $this
*/
public function rootView(string $rootView): self
{
$this->rootView = $rootView;
return $this;
}
/**
* Add flash data to the response.
*
* @param BackedEnum|UnitEnum|string|array<string, mixed> $key
* @return $this
*/
public function flash(BackedEnum|UnitEnum|string|array $key, mixed $value = null): self
{
Inertia::flash($key, $value);
return $this;
}
/**
* Create an HTTP response that represents the object.
*
* @param Request $request
* @return \Symfony\Component\HttpFoundation\Response
*/
public function toResponse($request)
{
$resolver = new PropsResolver($request, $this->component);
[$resolvedProps, $resolvedMetadata] = $resolver->resolve($this->sharedProps, $this->props);
$page = array_merge(
[
'component' => $this->component,
'props' => $resolvedProps,
'url' => $this->getUrl($request),
'version' => $this->version,
],
$resolvedMetadata,
$this->resolveClearHistory($request),
$this->resolveEncryptHistory($request),
$this->resolveFlashData($request),
$this->resolvePreserveFragment($request),
);
DevTools::recorder($request)?->pageRendered($request, $page, $resolvedProps);
if ($request->header(Header::INERTIA)) {
return new JsonResponse($page, 200, [Header::INERTIA => 'true']);
}
App::make(SsrState::class)->setPage($page);
return ResponseFactory::view($this->rootView, $this->viewData + ['page' => $page]);
}
/**
* Resolve the clear history flag.
*
* @return array<string, mixed>
*/
protected function resolveClearHistory(Request $request): array
{
return $this->clearHistory ? ['clearHistory' => true] : [];
}
/**
* Resolve the encrypt history flag.
*
* @return array<string, mixed>
*/
protected function resolveEncryptHistory(Request $request): array
{
return $this->encryptHistory ? ['encryptHistory' => true] : [];
}
/**
* Resolve flash data from the session.
*
* @return array<string, mixed>
*/
protected function resolveFlashData(Request $request): array
{
$flash = Inertia::pullFlashed($request);
return $flash ? ['flash' => $flash] : [];
}
/**
* Resolve the preserve fragment flag from the session.
*
* @return array<string, mixed>
*/
protected function resolvePreserveFragment(Request $request): array
{
return $this->preserveFragment ? ['preserveFragment' => true] : [];
}
/**
* Get the URL from the request while preserving the trailing slash.
*/
protected function getUrl(Request $request): string
{
$urlResolver = $this->urlResolver ?? function (Request $request) {
$url = Str::start(Str::after($request->fullUrl(), $request->getSchemeAndHttpHost()), '/');
$rawUri = Str::before($request->getRequestUri(), '?');
return Str::endsWith($rawUri, '/') ? $this->finishUrlWithTrailingSlash($url) : $url;
};
return App::call($urlResolver, ['request' => $request]);
}
/**
* Ensure the URL has a trailing slash before the query string.
*/
protected function finishUrlWithTrailingSlash(string $url): string
{
// Make sure the relative URL ends with a trailing slash and re-append the query string if it exists.
$urlWithoutQueryWithTrailingSlash = Str::finish(Str::before($url, '?'), '/');
return str_contains($url, '?')
? $urlWithoutQueryWithTrailingSlash.'?'.Str::after($url, '?')
: $urlWithoutQueryWithTrailingSlash;
}
}

View file

@ -0,0 +1,520 @@
<?php
namespace Inertia;
use BackedEnum;
use Closure;
use Illuminate\Contracts\Debug\ExceptionHandler as ExceptionHandlerContract;
use Illuminate\Contracts\Http\Kernel;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request as HttpRequest;
use Illuminate\Routing\Router;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response as BaseResponse;
use Illuminate\Support\Traits\Macroable;
use Inertia\DevTools\DevTools;
use Inertia\Ssr\ConfiguresSsrRequests;
use Inertia\Ssr\DisablesSsr;
use Inertia\Ssr\ExcludesSsrPaths;
use Inertia\Ssr\Gateway;
use Inertia\Support\Header;
use Inertia\Support\SessionKey;
use InvalidArgumentException;
use LogicException;
use Symfony\Component\HttpFoundation\RedirectResponse as SymfonyRedirectResponse;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
use UnitEnum;
class ResponseFactory
{
use Macroable;
/**
* The name of the root view.
*
* @var string
*/
protected $rootView = 'app';
/**
* The shared properties.
*
* @var array<string, mixed>
*/
protected $sharedProps = [];
/**
* The asset version.
*
* @var Closure|string|null
*/
protected $version;
/**
* Indicates if the browser history should be cleared.
*
* @var bool
*/
protected $clearHistory = false;
/**
* Indicates if the browser history should be encrypted.
*
* @var bool|null
*/
protected $encryptHistory;
/**
* The URL resolver callback.
*
* @var Closure|null
*/
protected $urlResolver;
/**
* The component transformer callback.
*
* @var Closure|null
*/
protected $componentTransformer;
/**
* Set the root view template for Inertia responses. This template
* serves as the HTML wrapper that contains the Inertia root element
* where the frontend application will be mounted.
*/
public function setRootView(string $name): void
{
$this->rootView = $name;
}
/**
* Share data across all Inertia responses. This data is automatically
* included with every response, making it ideal for user authentication
* state, flash messages, etc.
*
* @param string|array<array-key, mixed>|Arrayable<array-key, mixed>|ProvidesInertiaProperties $key
* @param mixed $value
*/
public function share($key, $value = null): void
{
if (is_array($key)) {
$this->sharedProps = array_merge($this->sharedProps, $key);
DevTools::recorder()?->propsShared(array_keys($key));
} elseif ($key instanceof Arrayable) {
$resolved = $key->toArray();
$this->sharedProps = array_merge($this->sharedProps, $resolved);
DevTools::recorder()?->propsShared(array_keys($resolved));
} elseif ($key instanceof ProvidesInertiaProperties) {
$this->sharedProps = array_merge($this->sharedProps, [$key]);
} else {
Arr::set($this->sharedProps, $key, $value);
DevTools::recorder()?->propsShared([(string) $key]);
}
}
/**
* Get the shared data for a given key. Returns all shared data if
* no key is provided, or the value for a specific key with an
* optional default fallback.
*
* @param mixed $default
* @return mixed
*/
public function getShared(?string $key = null, $default = null)
{
if ($key) {
return Arr::get($this->sharedProps, $key, $default);
}
return $this->sharedProps;
}
/**
* Flush all shared data.
*
* @return void
*/
public function flushShared()
{
$this->sharedProps = [];
}
/**
* Set the asset version.
*
* @param Closure|string|null $version
*/
public function version($version): void
{
$this->version = $version;
}
/**
* Get the asset version.
*/
public function getVersion(): string
{
$version = $this->version instanceof Closure
? App::call($this->version)
: $this->version;
return (string) $version;
}
/**
* Set the URL resolver.
*/
public function resolveUrlUsing(?Closure $urlResolver = null): void
{
$this->urlResolver = $urlResolver;
}
/**
* Set the component transformer.
*/
public function transformComponentUsing(?Closure $componentTransformer = null): void
{
$this->componentTransformer = $componentTransformer;
}
/**
* Clear the browser history on the next visit.
*/
public function clearHistory(): void
{
session([SessionKey::CLEAR_HISTORY => true]);
}
/**
* Preserve the URL fragment across the next redirect.
*/
public function preserveFragment(): void
{
session([SessionKey::PRESERVE_FRAGMENT => true]);
}
/**
* Encrypt the browser history.
*
* @param bool $encrypt
*/
public function encryptHistory($encrypt = true): void
{
$this->encryptHistory = $encrypt;
}
/**
* Disable server-side rendering, optionally based on a condition.
*/
public function disableSsr(Closure|bool $condition = true): void
{
$gateway = app(Gateway::class);
if (! $gateway instanceof DisablesSsr) {
throw new LogicException('The configured SSR gateway does not support disabling server-side rendering conditionally.');
}
$gateway->disable($condition);
}
/**
* Exclude the given paths from server-side rendering.
*
* @param array<int, string>|string $paths
*/
public function withoutSsr(array|string $paths): void
{
$gateway = app(Gateway::class);
if (! $gateway instanceof ExcludesSsrPaths) {
throw new LogicException('The configured SSR gateway does not support excluding paths from server-side rendering.');
}
$gateway->except($paths);
}
/**
* Configure the HTTP request that is sent to the SSR server.
*/
public function configureSsrRequestUsing(?Closure $callback = null): void
{
$gateway = app(Gateway::class);
if (! $gateway instanceof ConfiguresSsrRequests) {
throw new LogicException('The configured SSR gateway does not support configuring server-side rendering requests.');
}
$gateway->configureRequestUsing($callback);
}
/**
* Create an optional property.
*/
public function optional(callable $callback): OptionalProp
{
return new OptionalProp($callback);
}
/**
* Create a deferred property.
*/
public function defer(callable $callback, string $group = 'default', bool $rescue = false): DeferProp
{
return new DeferProp($callback, $group, $rescue);
}
/**
* Create a merge property.
*
* @param mixed $value
*/
public function merge($value): MergeProp
{
return new MergeProp($value);
}
/**
* Create a deep merge property.
*
* @param mixed $value
*/
public function deepMerge($value): MergeProp
{
return (new MergeProp($value))->deepMerge();
}
/**
* Create an always property.
*
* @param mixed $value
*/
public function always($value): AlwaysProp
{
return new AlwaysProp($value);
}
/**
* Create an scroll property.
*
* @param mixed $value
*
* @template T
*
* @param T $value
* @return ScrollProp<T>
*/
public function scroll($value, string $wrapper = 'data', ProvidesScrollMetadata|callable|null $metadata = null): ScrollProp
{
return new ScrollProp($value, $wrapper, $metadata);
}
/**
* Create an once property.
*/
public function once(callable $value): OnceProp
{
return new OnceProp($value);
}
/**
* Create and share an once property.
*/
public function shareOnce(string $key, callable $callback): OnceProp
{
return tap(new OnceProp($callback), fn ($prop) => $this->share($key, $prop));
}
/**
* Find the component or fail.
*
* @throws ComponentNotFoundException
*/
protected function findComponentOrFail(string $component): void
{
try {
app('inertia.view-finder')->find($component);
} catch (InvalidArgumentException) {
throw new ComponentNotFoundException("Inertia page component [{$component}] not found.");
}
}
/**
* Transform the component name.
*
* @param mixed $component
* @return mixed
*/
protected function transformComponent($component)
{
if (! $this->componentTransformer) {
return $component;
}
return ($this->componentTransformer)($component) ?? $component;
}
/**
* Create an Inertia response.
*
* @param BackedEnum|UnitEnum|string $component
* @param array<array-key, mixed>|Arrayable<array-key, mixed>|ProvidesInertiaProperties $props
*/
public function render($component, $props = []): Response
{
$component = $this->transformComponent($component);
$component = match (true) {
$component instanceof BackedEnum => $component->value,
$component instanceof UnitEnum => $component->name,
default => $component,
};
if (! is_string($component)) {
throw new InvalidArgumentException('Component argument must be of type string or a string BackedEnum');
}
if (config('inertia.pages.ensure_pages_exist', false)) {
$this->findComponentOrFail($component);
}
if ($props instanceof Arrayable) {
$props = $props->toArray();
} elseif ($props instanceof ProvidesInertiaProperties) {
// Will be resolved in Response::resolveResponsableProperties()
$props = [$props];
}
$response = new Response(
$component,
$this->sharedProps,
$props,
$this->rootView,
$this->getVersion(),
$this->encryptHistory ?? config('inertia.history.encrypt', false),
$this->urlResolver,
);
DevTools::recorder()?->pageRendering($component, $response, $this->sharedProps);
return $response;
}
/**
* Create an Inertia location response.
*
* @param string|SymfonyRedirectResponse $url
*/
public function location($url): SymfonyResponse
{
if (Request::inertia()) {
return BaseResponse::make('', 409, [Header::LOCATION => $url instanceof SymfonyRedirectResponse ? $url->getTargetUrl() : $url]);
}
return $url instanceof SymfonyRedirectResponse ? $url : Redirect::away($url);
}
/**
* Register a callback to handle HTTP exceptions for Inertia requests.
*/
public function handleExceptionsUsing(callable $callback): void
{
/** @var mixed $handler */
$handler = app(ExceptionHandlerContract::class);
if (! $handler instanceof ExceptionHandler) {
if (app()->runningInConsole()) {
return;
}
if (! method_exists($handler, 'respondUsing')) {
throw new LogicException('The bound exception handler does not have a `respondUsing` method.');
}
}
/** @var ExceptionHandler $handler */
$handler->respondUsing(function ($response, $e, $request) use ($callback) {
$result = $callback(new ExceptionResponse(
$e,
$request,
$response,
app(Router::class),
app(Kernel::class),
));
if ($result instanceof ExceptionResponse) {
return $result->toResponse($request);
}
return $result ?? $response;
});
}
/**
* Flash data to be included with the next response. Unlike regular props,
* flash data is not persisted in the browser's history state, making it
* ideal for one-time notifications like toasts or highlights.
*
* @param BackedEnum|UnitEnum|string|array<string, mixed> $key
*/
public function flash(BackedEnum|UnitEnum|string|array $key, mixed $value = null): self
{
$flash = $key;
if (! is_array($key)) {
$key = match (true) {
$key instanceof BackedEnum => $key->value,
$key instanceof UnitEnum => $key->name,
default => $key,
};
$flash = [$key => $value];
}
session()->flash(SessionKey::FLASH_DATA, [
...$this->getFlashed(),
...$flash,
]);
return $this;
}
/**
* Create a new redirect response to the previous location.
*
* @param array<string, string> $headers
*/
public function back(int $status = 302, array $headers = [], mixed $fallback = false): RedirectResponse
{
return Redirect::back($status, $headers, $fallback);
}
/**
* Retrieve the flashed data from the session.
*
* @return array<string, mixed>
*/
public function getFlashed(?HttpRequest $request = null): array
{
$request ??= request();
return $request->hasSession() ? $request->session()->get(SessionKey::FLASH_DATA, []) : [];
}
/**
* Retrieve and remove the flashed data from the session.
*
* @return array<string, mixed>
*/
public function pullFlashed(?HttpRequest $request = null): array
{
$request ??= request();
return $request->hasSession() ? $request->session()->pull(SessionKey::FLASH_DATA, []) : [];
}
}

View file

@ -0,0 +1,101 @@
<?php
namespace Inertia;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Pagination\CursorPaginator;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use InvalidArgumentException;
/**
* @implements Arrayable<string, mixed>
*/
class ScrollMetadata implements Arrayable, ProvidesScrollMetadata
{
/**
* Create a new scroll metadata instance.
*/
public function __construct(
protected string $pageName,
protected int|string|null $previousPage = null,
protected int|string|null $nextPage = null,
protected int|string|null $currentPage = null,
) {
//
}
/**
* Create a scroll metadata instance from a Laravel paginator.
*/
public static function fromPaginator(mixed $value): self
{
$paginator = $value instanceof JsonResource ? $value->resource : $value;
if ($paginator instanceof CursorPaginator) {
return new self(
$cursorName = $paginator->getCursorName(),
$paginator->previousCursor()?->encode(),
$paginator->nextCursor()?->encode(),
$paginator->onFirstPage() ? 1 : (CursorPaginator::resolveCurrentCursor($cursorName)?->encode() ?? 1)
);
}
if ($paginator instanceof LengthAwarePaginator || $paginator instanceof Paginator) {
return new self(
$paginator->getPageName(),
$paginator->currentPage() > 1 ? $paginator->currentPage() - 1 : null,
$paginator->hasMorePages() ? $paginator->currentPage() + 1 : null,
$paginator->currentPage(),
);
}
throw new InvalidArgumentException('The given value is not a Laravel paginator instance. Use a custom callback to extract pagination metadata.');
}
/**
* Get the page name parameter.
*/
public function getPageName(): string
{
return $this->pageName;
}
/**
* Get the previous page identifier.
*/
public function getPreviousPage(): int|string|null
{
return $this->previousPage;
}
/**
* Get the next page identifier.
*/
public function getNextPage(): int|string|null
{
return $this->nextPage;
}
/**
* Get the current page identifier.
*/
public function getCurrentPage(): int|string|null
{
return $this->currentPage;
}
/**
* Convert the scroll metadata instance to an array.
*/
public function toArray(): array
{
return [
'pageName' => $this->getPageName(),
'previousPage' => $this->getPreviousPage(),
'nextPage' => $this->getNextPage(),
'currentPage' => $this->getCurrentPage(),
];
}
}

View file

@ -0,0 +1,129 @@
<?php
namespace Inertia;
use Illuminate\Http\Request;
use Inertia\Support\Header;
/**
* Represents a paginated property that can be merged during partial reloads.
*
* This class provides functionality for handling pagination data with merge capabilities,
* allowing paginated content to be appended or prepended during client-side navigation.
*
* @template T
*/
class ScrollProp implements Deferrable, Mergeable
{
use DefersProps, MergesProps, ResolvesCallables;
/**
* The property value.
*
* Merged with existing client-side data during partial reloads.
*
* @var T
*/
protected $value;
/**
* The resolved property value.
*
* @var T
*/
protected $resolved;
/**
* The wrapper key for the data array.
*
* @var string
*/
protected $wrapper;
/**
* The scroll metadata provider.
*
* @var ProvidesScrollMetadata|callable(T): ProvidesScrollMetadata|null
*/
protected $metadata;
/**
* Create a new merge property instance. Merge properties are combined
* with existing client-side data during partial reloads instead of
* completely replacing the property value.
*
* @param T $value
* @param ProvidesScrollMetadata|callable(T): ProvidesScrollMetadata|null $metadata
*/
public function __construct(mixed $value, string $wrapper = 'data', ProvidesScrollMetadata|callable|null $metadata = null)
{
$this->merge = true;
$this->value = $value;
$this->wrapper = $wrapper;
$this->metadata = $metadata;
}
/**
* Configure the merge strategy based on the infinite scroll merge intent header.
*
* The frontend InfiniteScroll component sends its merge intent directly,
* eliminating the need for direction-based logic on the backend.
*/
public function configureMergeIntent(?Request $request = null): static
{
$request ??= request();
return $request->header(Header::INFINITE_SCROLL_MERGE_INTENT) === 'prepend'
? $this->prepend($this->wrapper)
: $this->append($this->wrapper);
}
/**
* Resolve the scroll metadata provider.
*/
protected function resolveMetadataProvider(): ProvidesScrollMetadata
{
if ($this->metadata instanceof ProvidesScrollMetadata) {
return $this->metadata;
}
$value = $this();
if (is_null($this->metadata)) {
return ScrollMetadata::fromPaginator($value);
}
return call_user_func($this->metadata, $value);
}
/**
* Get the pagination meta information.
*
* @return array{pageName: string, previousPage: int|string|null, nextPage: int|string|null, currentPage: int|string|null}
*/
public function metadata(): array
{
$metadataProvider = $this->resolveMetadataProvider();
return [
'pageName' => $metadataProvider->getPageName(),
'previousPage' => $metadataProvider->getPreviousPage(),
'nextPage' => $metadataProvider->getNextPage(),
'currentPage' => $metadataProvider->getCurrentPage(),
];
}
/**
* Resolve the property value.
*
* @return T
*/
public function __invoke()
{
if (isset($this->resolved)) {
return $this->resolved;
}
return $this->resolved = $this->resolveCallable($this->value);
}
}

View file

@ -0,0 +1,199 @@
<?php
namespace Inertia;
use Illuminate\Contracts\Http\Kernel as HttpKernelContract;
use Illuminate\Foundation\Http\Kernel;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Router;
use Illuminate\Support\ServiceProvider as BaseServiceProvider;
use Illuminate\Testing\TestResponse;
use Illuminate\View\FileViewFinder;
use Inertia\DevTools\DevTools;
use Inertia\DevTools\DevToolsServiceProvider;
use Inertia\DevTools\SourceLocator;
use Inertia\Ssr\Gateway;
use Inertia\Ssr\HttpGateway;
use Inertia\Ssr\SsrState;
use Inertia\Support\Header;
use Inertia\Testing\TestResponseMacros;
use LogicException;
class ServiceProvider extends BaseServiceProvider
{
/**
* Register the service provider.
*/
public function register(): void
{
$this->app->singleton(HttpGateway::class);
$this->app->singleton(ResponseFactory::class);
$this->app->scoped(SsrState::class);
$this->app->bind(Gateway::class, HttpGateway::class);
$this->mergeConfigFrom(
__DIR__.'/../config/inertia.php',
'inertia'
);
$this->registerBladeComponents();
$this->registerBladeDirectives();
$this->registerRedirectMacro();
$this->registerRequestMacro();
$this->registerRouterMacro();
$this->registerTestingMacros();
$this->registerMiddleware();
$this->app->register(DevToolsServiceProvider::class);
$this->app->bind('inertia.view-finder', function ($app) {
return new FileViewFinder(
$app['files'],
$app['config']->get('inertia.pages.paths'),
$app['config']->get('inertia.pages.extensions')
);
});
}
/**
* Boot the service provider.
*/
public function boot(): void
{
$this->registerConsoleCommands();
$this->registerRedirectMiddleware();
$this->publishes([
__DIR__.'/../config/inertia.php' => config_path('inertia.php'),
]);
}
/**
* Register the global redirect middleware for Inertia requests.
*/
protected function registerRedirectMiddleware(): void
{
$this->callAfterResolving(HttpKernelContract::class, function ($kernel) {
if ($kernel instanceof Kernel) {
$kernel->pushMiddleware(Middleware\EnsureGetOnRedirect::class);
$kernel->prependMiddleware(Middleware\EnsureDeferredCallbacksRun::class);
}
});
}
/**
* Register Blade components for rendering Inertia head and body content.
*/
protected function registerBladeComponents(): void
{
$this->callAfterResolving('blade.compiler', function ($blade) {
$blade->componentNamespace('Inertia\\View\\Components', 'inertia');
});
}
/**
* Register @inertia and @inertiaHead directives for rendering the Inertia
* root element and SSR head content in Blade templates.
*/
protected function registerBladeDirectives(): void
{
$this->callAfterResolving('blade.compiler', function ($blade) {
$blade->directive('inertia', [Directive::class, 'compile']);
$blade->directive('inertiaHead', [Directive::class, 'compileHead']);
});
}
/**
* Register Artisan commands for managing Inertia middleware creation
* and server-side rendering operations when running in console mode.
*/
protected function registerConsoleCommands(): void
{
if (! $this->app->runningInConsole()) {
return;
}
$this->commands([
Commands\CreateMiddleware::class,
Commands\StartSsr::class,
Commands\StopSsr::class,
Commands\CheckSsr::class,
]);
}
/**
* Add a 'preserveFragment' method to redirect responses that signals
* the frontend to preserve the URL fragment across the redirect.
*/
protected function registerRedirectMacro(): void
{
RedirectResponse::macro('preserveFragment', function () {
inertia()->preserveFragment();
return $this;
});
}
/**
* Add an 'inertia' method to the Request class that returns true
* if the current request is an Inertia request.
*/
protected function registerRequestMacro(): void
{
Request::macro('inertia', function () {
return (bool) $this->header(Header::INERTIA);
});
}
/**
* Register the router macro.
*/
protected function registerRouterMacro(): void
{
/**
* @param array<array-key, mixed> $props
*/
Router::macro('inertia', function ($uri, $component, $props = []) {
$route = $this->match(['GET', 'HEAD'], $uri, '\\'.Controller::class)
->defaults('component', $component)
->defaults('props', $props);
if (DevTools::enabled()) {
$source = app(SourceLocator::class)->captureCallerSource();
if ($source !== null) {
$route->defaults(DevTools::RENDER_SOURCE_KEY, $source);
}
}
return $route;
});
}
/**
* Register the testing macros.
*
* @throws LogicException
*/
protected function registerTestingMacros(): void
{
if (class_exists(TestResponse::class)) {
TestResponse::mixin(new TestResponseMacros);
return;
}
throw new LogicException('Could not detect TestResponse class.');
}
/**
* Register the middleware aliases.
*/
protected function registerMiddleware(): void
{
$this->app['router']->aliasMiddleware(
'inertia.encrypt',
EncryptHistoryMiddleware::class
);
}
}

View file

@ -0,0 +1,26 @@
<?php
namespace Inertia\Ssr;
class BundleDetector
{
/**
* Detect and return the path to the SSR bundle file.
*
* @return string|null
*/
public function detect()
{
return collect([
config('inertia.ssr.bundle'),
base_path('bootstrap/ssr/ssr.js'),
base_path('bootstrap/ssr/app.js'),
base_path('bootstrap/ssr/ssr.mjs'),
base_path('bootstrap/ssr/app.mjs'),
public_path('js/ssr.js'),
public_path('js/app.js'),
])->filter()->first(function ($path) {
return file_exists($path);
});
}
}

View file

@ -0,0 +1,13 @@
<?php
namespace Inertia\Ssr;
use Closure;
interface ConfiguresSsrRequests
{
/**
* Configure the HTTP request that is sent to the SSR server.
*/
public function configureRequestUsing(?Closure $callback = null): void;
}

View file

@ -0,0 +1,13 @@
<?php
namespace Inertia\Ssr;
use Closure;
interface DisablesSsr
{
/**
* Set the condition that determines if SSR should be disabled.
*/
public function disable(Closure|bool $condition): void;
}

View file

@ -0,0 +1,13 @@
<?php
namespace Inertia\Ssr;
interface ExcludesSsrPaths
{
/**
* Exclude the given paths from server-side rendering.
*
* @param array<int, string>|string $paths
*/
public function except(array|string $paths): void;
}

View file

@ -0,0 +1,13 @@
<?php
namespace Inertia\Ssr;
interface Gateway
{
/**
* Dispatch the Inertia page to the SSR engine.
*
* @param array<string, mixed> $page
*/
public function dispatch(array $page): ?Response;
}

View file

@ -0,0 +1,11 @@
<?php
namespace Inertia\Ssr;
interface HasHealthCheck
{
/**
* Determine if the SSR server is healthy and responsive.
*/
public function isHealthy(): bool;
}

View file

@ -0,0 +1,237 @@
<?php
namespace Inertia\Ssr;
use Closure;
use Exception;
use Illuminate\Foundation\Http\Middleware\Concerns\ExcludesPaths;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\StrayRequestException;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Vite;
use Illuminate\Support\Str;
use Inertia\ResolvesCallables;
class HttpGateway implements ConfiguresSsrRequests, DisablesSsr, ExcludesSsrPaths, Gateway, HasHealthCheck
{
use ExcludesPaths;
use ResolvesCallables;
/**
* The paths that should be excluded from server-side rendering.
*
* @var array<int, string>
*/
protected $except = [];
/**
* The condition that determines if SSR is disabled.
*/
protected Closure|bool|null $disabled = null;
/**
* The SSR request configurator callback.
*/
protected ?Closure $requestConfigurator = null;
/**
* Dispatch the Inertia page to the SSR engine via HTTP.
*
* @param array<string, mixed> $page
*/
public function dispatch(array $page, ?Request $request = null): ?Response
{
if (! $this->ssrIsEnabled($request ?? request())) {
return null;
}
$isHot = Vite::isRunningHot();
if (! $isHot && $this->shouldEnsureBundleExists() && ! $this->bundleExists()) {
return null;
}
$url = $isHot
? $this->getHotUrl('/__inertia_ssr')
: $this->getProductionUrl('/render');
try {
$response = $this->pendingRequest()->post($url, $page);
if ($response->failed()) {
$this->handleSsrFailure($page, $response->json());
return null;
}
if (! $data = $response->json()) {
return null;
}
return new Response(
implode("\n", $data['head'] ?? []),
$data['body'] ?? ''
);
} catch (Exception $e) {
if ($e instanceof StrayRequestException || $e instanceof SsrException) {
throw $e;
}
$this->handleSsrFailure($page, [
'error' => $e->getMessage(),
'type' => 'connection',
]);
return null;
}
}
/**
* Set the condition that determines if SSR should be disabled.
*/
public function disable(Closure|bool $condition): void
{
$this->disabled = $condition;
}
/**
* Exclude the given paths from server-side rendering.
*
* @param array<int, string>|string $paths
*/
public function except(array|string $paths): void
{
$this->except = array_merge($this->except, Arr::wrap($paths));
}
/**
* Configure the HTTP request that is sent to the SSR server.
*/
public function configureRequestUsing(?Closure $callback = null): void
{
$this->requestConfigurator = $callback;
}
/**
* Create the pending HTTP request for the SSR server.
*/
protected function pendingRequest(): PendingRequest
{
$request = Http::createPendingRequest();
if ($timeout = config('inertia.ssr.timeout')) {
$request->timeout($timeout);
}
if (! $this->requestConfigurator) {
return $request;
}
return ($this->requestConfigurator)($request) ?? $request;
}
/**
* Handle an SSR rendering failure.
*
* @param array<string, mixed> $page
* @param array<string, mixed>|null $error
*
* @throws SsrException
*/
protected function handleSsrFailure(array $page, ?array $error): void
{
$event = new SsrRenderFailed(
page: $page,
error: $error['error'] ?? 'Unknown SSR error',
type: SsrErrorType::fromString($error['type'] ?? null),
hint: $error['hint'] ?? null,
browserApi: $error['browserApi'] ?? null,
stack: $error['stack'] ?? null,
sourceLocation: $error['sourceLocation'] ?? null,
);
// Dispatch the event so users can listen for SSR failures
SsrRenderFailed::dispatch(
$event->page,
$event->error,
$event->type,
$event->hint,
$event->browserApi,
$event->stack,
$event->sourceLocation,
);
// Throw an exception if configured (useful for E2E testing)
if (config('inertia.ssr.throw_on_error', false)) {
throw SsrException::fromEvent($event);
}
}
/**
* Determine if the SSR feature is enabled.
*/
protected function ssrIsEnabled(Request $request): bool
{
$enabled = $this->disabled !== null
? ! $this->resolveCallable($this->disabled)
: config('inertia.ssr.enabled', true);
return $enabled && ! $this->inExceptArray($request);
}
/**
* Determine if the SSR server is healthy.
*/
public function isHealthy(): bool
{
try {
return $this->pendingRequest()->get($this->getProductionUrl('/health'))->successful();
} catch (Exception $e) {
if ($e instanceof StrayRequestException) {
throw $e;
}
return false;
}
}
/**
* Determine if the bundle existence should be ensured.
*/
protected function shouldEnsureBundleExists(): bool
{
return config('inertia.ssr.ensure_bundle_exists', true);
}
/**
* Check if an SSR bundle exists.
*/
protected function bundleExists(): bool
{
return app(BundleDetector::class)->detect() !== null;
}
/**
* Get the production SSR server URL.
*/
public function getProductionUrl(string $path = '/'): string
{
$path = Str::start($path, '/');
$baseUrl = rtrim(config('inertia.ssr.url', 'http://127.0.0.1:13714'), '/');
return $baseUrl.$path;
}
/**
* Get the Vite hot SSR URL.
*/
protected function getHotUrl(string $path = '/'): string
{
$path = Str::start($path, '/');
$baseUrl = rtrim(trim(config('inertia.ssr.hot_url') ?: file_get_contents(Vite::hotFile())), '/');
return $baseUrl.$path;
}
}

View file

@ -0,0 +1,29 @@
<?php
namespace Inertia\Ssr;
class Response
{
/**
* The HTML head content from server-side rendering.
*
* @var string
*/
public $head;
/**
* The HTML body content from server-side rendering.
*
* @var string
*/
public $body;
/**
* Create a new SSR response instance.
*/
public function __construct(string $head, string $body)
{
$this->head = $head;
$this->body = $body;
}
}

View file

@ -0,0 +1,24 @@
<?php
namespace Inertia\Ssr;
enum SsrErrorType: string
{
case BrowserApi = 'browser-api';
case ComponentResolution = 'component-resolution';
case Render = 'render';
case Connection = 'connection';
case Unknown = 'unknown';
/**
* Create an instance from a string value, defaulting to Unknown.
*/
public static function fromString(?string $value): self
{
if ($value === null) {
return self::Unknown;
}
return self::tryFrom($value) ?? self::Unknown;
}
}

View file

@ -0,0 +1,66 @@
<?php
namespace Inertia\Ssr;
use Exception;
class SsrException extends Exception
{
/**
* Create a new SSR exception from a render failure event.
*/
public static function fromEvent(SsrRenderFailed $event): self
{
$message = sprintf(
'SSR render failed for component [%s]: %s',
$event->component(),
$event->error
);
if ($event->sourceLocation) {
$message .= sprintf(' at %s', $event->sourceLocation);
}
$exception = new self($message);
$exception->event = $event;
return $exception;
}
/**
* The SSR render failed event containing error details.
*/
public ?SsrRenderFailed $event = null;
/**
* Get the component that failed to render.
*/
public function component(): ?string
{
return $this->event?->component();
}
/**
* Get the error type.
*/
public function type(): ?SsrErrorType
{
return $this->event?->type;
}
/**
* Get the hint for fixing the error.
*/
public function hint(): ?string
{
return $this->event?->hint;
}
/**
* Get the source location where the error occurred.
*/
public function sourceLocation(): ?string
{
return $this->event?->sourceLocation;
}
}

View file

@ -0,0 +1,65 @@
<?php
namespace Inertia\Ssr;
use Illuminate\Foundation\Events\Dispatchable;
class SsrRenderFailed
{
use Dispatchable;
/**
* Create a new event instance.
*
* @param array<string, mixed> $page The page data that was being rendered
* @param string $error The error message
* @param SsrErrorType $type The error type
* @param string|null $hint A helpful hint on how to fix the error
* @param string|null $browserApi The browser API that was accessed (if type is browser-api)
* @param string|null $stack The stack trace
* @param string|null $sourceLocation The source location (file:line:column) where the error occurred
*/
public function __construct(
public array $page,
public string $error,
public SsrErrorType $type = SsrErrorType::Unknown,
public ?string $hint = null,
public ?string $browserApi = null,
public ?string $stack = null,
public ?string $sourceLocation = null,
) {}
/**
* Get the component name from the page data.
*/
public function component(): string
{
return $this->page['component'] ?? 'Unknown';
}
/**
* Get the URL from the page data.
*/
public function url(): string
{
return $this->page['url'] ?? '/';
}
/**
* Convert the event to an array for logging.
*
* @return array<string, mixed>
*/
public function toArray(): array
{
return array_filter([
'component' => $this->component(),
'url' => $this->url(),
'error' => $this->error,
'type' => $this->type->value,
'hint' => $this->hint,
'browser_api' => $this->browserApi,
'source_location' => $this->sourceLocation,
]);
}
}

View file

@ -0,0 +1,48 @@
<?php
namespace Inertia\Ssr;
class SsrState
{
/**
* The page data for the current request.
*
* @var array<string, mixed>
*/
public array $page = [];
/**
* The SSR response for the current request.
*/
public ?Response $response = null;
/**
* Whether the SSR gateway has been dispatched.
*/
protected bool $dispatched = false;
/**
* Set the page data for the current request.
*
* @param array<string, mixed> $page
*/
public function setPage(array $page): static
{
$this->page = $page;
return $this;
}
/**
* Dispatch the page to the SSR gateway, or return the cached response.
*/
public function dispatch(): ?Response
{
if (! $this->dispatched) {
$this->dispatched = true;
$this->response = app(Gateway::class)->dispatch($this->page);
}
return $this->response;
}
}

View file

@ -0,0 +1,66 @@
<?php
namespace Inertia\Support;
class Header
{
/**
* The main Inertia request header.
*/
public const INERTIA = 'X-Inertia';
/**
* Header for specifying which error bag to use for validation errors.
*/
public const ERROR_BAG = 'X-Inertia-Error-Bag';
/**
* Header for external redirects.
*/
public const LOCATION = 'X-Inertia-Location';
/**
* Header for hash fragment redirects.
*/
public const REDIRECT = 'X-Inertia-Redirect';
/**
* Header for the current asset version.
*/
public const VERSION = 'X-Inertia-Version';
/**
* Header specifying the component for partial reloads.
*/
public const PARTIAL_COMPONENT = 'X-Inertia-Partial-Component';
/**
* Header for Laravel Precognition validation requests.
*/
public const PRECOGNITION = 'Precognition';
/**
* Header specifying which props to include in partial reloads.
*/
public const PARTIAL_ONLY = 'X-Inertia-Partial-Data';
/**
* Header specifying which props to exclude from partial reloads.
*/
public const PARTIAL_EXCEPT = 'X-Inertia-Partial-Except';
/**
* Header for resetting the page state.
*/
public const RESET = 'X-Inertia-Reset';
/**
* Header for specifying the merge intent when paginating on infinite scroll.
*/
public const INFINITE_SCROLL_MERGE_INTENT = 'X-Inertia-Infinite-Scroll-Merge-Intent';
/**
* Header specifying which once props to exclude from the response.
*/
public const EXCEPT_ONCE_PROPS = 'X-Inertia-Except-Once-Props';
}

View file

@ -0,0 +1,21 @@
<?php
namespace Inertia\Support;
class SessionKey
{
/**
* Session key for clearing the Inertia history.
*/
public const CLEAR_HISTORY = 'inertia.clear_history';
/**
* Session key for flash data.
*/
public const FLASH_DATA = 'inertia.flash_data';
/**
* Session key for preserving the URL fragment.
*/
public const PRESERVE_FRAGMENT = 'inertia.preserve_fragment';
}

View file

@ -0,0 +1,304 @@
<?php
namespace Inertia\Testing;
use Closure;
use Illuminate\Http\Response;
use Illuminate\Support\Arr;
use Illuminate\Testing\Fluent\AssertableJson;
use Illuminate\Testing\TestResponse;
use InvalidArgumentException;
use PHPUnit\Framework\Assert as PHPUnit;
use PHPUnit\Framework\AssertionFailedError;
class AssertableInertia extends AssertableJson
{
/**
* The Inertia component name for this page.
*
* @var string
*/
private $component;
/**
* The current page URL.
*
* @var string
*/
private $url;
/**
* The current asset version.
*
* @var string|null
*/
private $version;
/**
* Whether history state should be encrypted.
*
* @var bool
*/
private $encryptHistory;
/**
* Whether history should be cleared.
*
* @var bool
*/
private $clearHistory;
/**
* The deferred props (if any).
*
* @var array<string, array<int, string>>
*/
private $deferredProps;
/**
* The Flash Data (if any).
*
* @var array<string, mixed>
*/
private $flash;
/**
* Create an AssertableInertia instance from a test response.
*
* @param TestResponse<Response> $response
*/
public static function fromTestResponse(TestResponse $response): self
{
try {
$response->assertViewHas('page');
$page = json_decode(json_encode($response->viewData('page')), true);
PHPUnit::assertIsArray($page);
PHPUnit::assertArrayHasKey('component', $page);
PHPUnit::assertArrayHasKey('props', $page);
PHPUnit::assertArrayHasKey('url', $page);
PHPUnit::assertArrayHasKey('version', $page);
} catch (AssertionFailedError $e) {
PHPUnit::fail('Not a valid Inertia response.');
}
$instance = static::fromArray($page['props']);
$instance->component = $page['component'];
$instance->url = $page['url'];
$instance->version = $page['version'];
$instance->encryptHistory = isset($page['encryptHistory']);
$instance->clearHistory = isset($page['clearHistory']);
$instance->deferredProps = $page['deferredProps'] ?? [];
$instance->flash = $page['flash'] ?? [];
return $instance;
}
/**
* Assert that the page uses the given component.
*
* @param bool|null $shouldExist
*/
public function component(?string $value = null, $shouldExist = null): self
{
PHPUnit::assertSame($value, $this->component, 'Unexpected Inertia page component.');
if ($shouldExist || (is_null($shouldExist) && config('inertia.testing.ensure_pages_exist', true))) {
try {
app('inertia.view-finder')->find($value);
} catch (InvalidArgumentException $exception) {
PHPUnit::fail(sprintf('Inertia page component file [%s] does not exist.', $value));
}
}
return $this;
}
/**
* Assert that the current page URL matches the expected value.
*/
public function url(string $value): self
{
PHPUnit::assertSame($value, $this->url, 'Unexpected Inertia page url.');
return $this;
}
/**
* Assert that the current asset version matches the expected value.
*/
public function version(string $value): self
{
PHPUnit::assertSame($value, $this->version, 'Unexpected Inertia asset version.');
return $this;
}
/**
* Load the deferred props for the given groups and perform assertions on the response.
*
* @param Closure|array<int, string>|string $groupsOrCallback
*/
public function loadDeferredProps(Closure|array|string $groupsOrCallback, ?Closure $callback = null): self
{
$callback = $groupsOrCallback instanceof Closure ? $groupsOrCallback : $callback;
$groups = $groupsOrCallback instanceof Closure ? array_keys($this->deferredProps) : Arr::wrap($groupsOrCallback);
$props = collect($groups)->flatMap(function ($group) {
return $this->deferredProps[$group] ?? [];
})->implode(',');
return $this->reloadOnly($props, $callback);
}
/**
* Reload the Inertia page and perform assertions on the response.
*
* @param array<int, string>|string|null $only
* @param array<int, string>|string|null $except
*/
public function reload(?Closure $callback = null, array|string|null $only = null, array|string|null $except = null): self
{
if (is_array($only)) {
$only = implode(',', $only);
}
if (is_array($except)) {
$except = implode(',', $except);
}
$reloadRequest = new ReloadRequest(
$this->url,
$this->component,
$this->version,
$only,
$except,
);
$assertable = AssertableInertia::fromTestResponse($reloadRequest());
// Make sure we get the same data as the original request.
$assertable->component($this->component);
$assertable->url($this->url);
$assertable->version($this->version);
if ($callback) {
$callback($assertable);
}
return $this;
}
/**
* Reload the Inertia page as a partial request with only the specified props.
*
* @param array<int, string>|string $only
*/
public function reloadOnly(array|string $only, ?Closure $callback = null): self
{
return $this->reload(only: $only, callback: function (AssertableInertia $assertable) use ($only, $callback) {
$props = is_array($only) ? $only : explode(',', $only);
$assertable->hasAll($props);
if ($callback) {
$callback($assertable);
}
});
}
/**
* Reload the Inertia page as a partial request excluding the specified props.
*
* @param array<int, string>|string $except
*/
public function reloadExcept(array|string $except, ?Closure $callback = null): self
{
return $this->reload(except: $except, callback: function (AssertableInertia $assertable) use ($except, $callback) {
$props = is_array($except) ? $except : explode(',', $except);
$assertable->missingAll($props);
if ($callback) {
$callback($assertable);
}
});
}
/**
* Assert that the Flash Data contains the given key, optionally with the expected value.
*/
public function hasFlash(string $key, mixed $expected = null): self
{
func_num_args() > 1
? static::assertFlashHas($this->flash, $key, $expected)
: static::assertFlashHas($this->flash, $key);
return $this;
}
/**
* Assert that the Flash Data does not contain the given key.
*/
public function missingFlash(string $key): self
{
static::assertFlashMissing($this->flash, $key);
return $this;
}
/**
* Assert that the given flash data array contains the given key, optionally with the expected value.
*
* @param array<string, mixed> $flash
*/
public static function assertFlashHas(array $flash, string $key, mixed $expected = null): void
{
PHPUnit::assertTrue(
Arr::has($flash, $key),
sprintf('Inertia Flash Data is missing key [%s].', $key)
);
if (func_num_args() > 2) {
PHPUnit::assertSame(
$expected,
Arr::get($flash, $key),
sprintf('Inertia Flash Data [%s] does not match expected value.', $key)
);
}
}
/**
* Assert that the given flash data array does not contain the given key.
*
* @param array<string, mixed> $flash
*/
public static function assertFlashMissing(array $flash, string $key): void
{
PHPUnit::assertFalse(
Arr::has($flash, $key),
sprintf('Inertia Flash Data has unexpected key [%s].', $key)
);
}
/**
* Convert the instance to an array.
*
* @return array<string, mixed>
*/
public function toArray()
{
return array_merge(
[
'component' => $this->component,
'props' => $this->prop(),
'url' => $this->url,
'version' => $this->version,
'flash' => $this->flash,
],
$this->encryptHistory ? ['encryptHistory' => true] : [],
$this->clearHistory ? ['clearHistory' => true] : [],
);
}
}

View file

@ -0,0 +1,50 @@
<?php
namespace Inertia\Testing;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Testing\Concerns\MakesHttpRequests;
use Illuminate\Http\Response;
use Illuminate\Testing\TestResponse;
use Inertia\Support\Header;
class ReloadRequest
{
use MakesHttpRequests;
/**
* Create a new Inertia reload request instance.
*/
public function __construct(
protected string $url,
protected string $component,
protected string $version,
protected ?string $only = null,
protected ?string $except = null,
protected ?Application $app = null
) {
$this->app ??= app();
}
/**
* Execute the reload request with appropriate Inertia headers.
*
* @return TestResponse<Response>
*/
public function __invoke(): TestResponse
{
$headers = [Header::VERSION => $this->version];
if (! blank($this->only)) {
$headers[Header::PARTIAL_COMPONENT] = $this->component;
$headers[Header::PARTIAL_ONLY] = $this->only;
}
if (! blank($this->except)) {
$headers[Header::PARTIAL_COMPONENT] = $this->component;
$headers[Header::PARTIAL_EXCEPT] = $this->except;
}
return $this->get($this->url, $headers);
}
}

View file

@ -0,0 +1,95 @@
<?php
namespace Inertia\Testing;
use Closure;
use Illuminate\Support\Arr;
use Inertia\Support\SessionKey;
class TestResponseMacros
{
/**
* Register the 'assertInertia' macro for TestResponse.
*
* @return Closure
*/
public function assertInertia()
{
return function (?Closure $callback = null) {
/** @phpstan-ignore-next-line */
$assert = AssertableInertia::fromTestResponse($this);
if (is_null($callback)) {
return $this;
}
$callback($assert);
return $this;
};
}
/**
* Register the 'inertiaPage' macro for TestResponse.
*
* @return Closure
*/
public function inertiaPage()
{
return function () {
/** @phpstan-ignore-next-line */
return AssertableInertia::fromTestResponse($this)->toArray();
};
}
/**
* Register the 'inertiaProps' macro for TestResponse.
*
* @return Closure
*/
public function inertiaProps()
{
return function (?string $propName = null) {
/** @phpstan-ignore-next-line */
$page = AssertableInertia::fromTestResponse($this)->toArray();
return Arr::get($page['props'], $propName);
};
}
/**
* Register the 'assertInertiaFlash' macro for TestResponse.
*
* @return Closure
*/
public function assertInertiaFlash()
{
return function (string $key, mixed $expected = null) {
/** @phpstan-ignore-next-line */
$flash = $this->session()->get(SessionKey::FLASH_DATA, []);
func_num_args() > 1
? AssertableInertia::assertFlashHas($flash, $key, $expected)
: AssertableInertia::assertFlashHas($flash, $key);
return $this;
};
}
/**
* Register the 'assertInertiaFlashMissing' macro for TestResponse.
*
* @return Closure
*/
public function assertInertiaFlashMissing()
{
return function (string $key) {
/** @phpstan-ignore-next-line */
$flash = $this->session()->get(SessionKey::FLASH_DATA, []);
AssertableInertia::assertFlashMissing($flash, $key);
return $this;
};
}
}

View file

@ -0,0 +1,33 @@
<?php
namespace Inertia\View\Components;
use Illuminate\View\Component;
use Inertia\Ssr\Response;
use Inertia\Ssr\SsrState;
class App extends Component
{
public ?Response $response;
public string $pageJson;
public function __construct(
public string $id = 'app',
) {
$state = app(SsrState::class);
$this->response = $state->dispatch();
$this->pageJson = json_encode($state->page, JSON_HEX_TAG);
}
public function render(): string
{
return <<<'blade'
@if($response)
{!! $response->body !!}
@else
<script data-page="{{ $id }}" type="application/json">{!! $pageJson !!}</script><div id="{{ $id }}"></div>
@endif
blade;
}
}

View file

@ -0,0 +1,28 @@
<?php
namespace Inertia\View\Components;
use Illuminate\View\Component;
use Inertia\Ssr\Response;
use Inertia\Ssr\SsrState;
class Head extends Component
{
public ?Response $response;
public function __construct()
{
$this->response = app(SsrState::class)->dispatch();
}
public function render(): string
{
return <<<'blade'
@if($response)
{!! $response->head !!}
@else
{!! $slot !!}
@endif
blade;
}
}

View file

@ -0,0 +1,43 @@
<?php
namespace {{ namespace }};
use Illuminate\Http\Request;
use Inertia\Middleware;
class {{ class }} extends Middleware
{
/**
* The root template that's loaded on the first page visit.
*
* @see https://inertiajs.com/server-side-setup#root-template
*
* @var string
*/
protected $rootView = 'app';
/**
* Determines the current asset version.
*
* @see https://inertiajs.com/asset-versioning
*/
public function version(Request $request): ?string
{
return parent::version($request);
}
/**
* Define the props that are shared by default.
*
* @see https://inertiajs.com/shared-data
*
* @return array<string, mixed>
*/
public function share(Request $request): array
{
return [
...parent::share($request),
//
];
}
}