@orieljs/framework 0.1.0-alpha.14 → 0.1.0-alpha.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/dist/{chunk-X4N74JDO.js → chunk-3QHTNAMZ.js} +6 -4
  2. package/dist/{chunk-X4N74JDO.js.map → chunk-3QHTNAMZ.js.map} +1 -1
  3. package/dist/{chunk-BKA5F3TH.js → chunk-6AXJB4CD.js} +5 -1
  4. package/dist/chunk-6AXJB4CD.js.map +1 -0
  5. package/dist/{chunk-UBSIBGXR.js → chunk-MG4YEWMV.js} +1351 -497
  6. package/dist/chunk-MG4YEWMV.js.map +1 -0
  7. package/dist/{chunk-4NCMY3ZS.js → chunk-YNDMTTWL.js} +121 -8
  8. package/dist/chunk-YNDMTTWL.js.map +1 -0
  9. package/dist/contracts.d.ts +112 -1
  10. package/dist/contracts.js +5 -1
  11. package/dist/{index.d-lffxurFs.d.ts → index.d-DA-Iu2a2.d.ts} +39 -2
  12. package/dist/index.d.ts +2838 -2101
  13. package/dist/index.js +1805 -647
  14. package/dist/index.js.map +1 -1
  15. package/dist/{jsx-runtime-Bc5KJzwb.d.ts → jsx-runtime-CenT41Y0.d.ts} +1 -1
  16. package/dist/jsx-runtime.d.ts +2 -2
  17. package/dist/jsx-runtime.js +3 -3
  18. package/dist/{testing-CVpo7aRl.d.ts → testing-B8J_HhF4.d.ts} +6 -2
  19. package/dist/testing.d.ts +2 -2
  20. package/dist/testing.js +3 -3
  21. package/docs/authentication.md +45 -3
  22. package/docs/authorization.md +2 -4
  23. package/docs/cache.md +29 -5
  24. package/docs/configuration.md +84 -7
  25. package/docs/console.md +41 -2
  26. package/docs/container.md +4 -0
  27. package/docs/csrf.md +2 -2
  28. package/docs/database.md +27 -2
  29. package/docs/deployment.md +42 -18
  30. package/docs/eloquent-factories.md +7 -3
  31. package/docs/eloquent-mutators.md +2 -1
  32. package/docs/eloquent-observers.md +2 -0
  33. package/docs/eloquent-relationships.md +34 -1
  34. package/docs/eloquent-resources.md +253 -0
  35. package/docs/eloquent.md +47 -0
  36. package/docs/errors.md +12 -3
  37. package/docs/events.md +3 -1
  38. package/docs/export.md +3 -3
  39. package/docs/facades.md +1 -0
  40. package/docs/helpers.md +33 -2
  41. package/docs/inertia.md +11 -1
  42. package/docs/installation.md +6 -2
  43. package/docs/laravel.md +71 -0
  44. package/docs/lifecycle.md +9 -5
  45. package/docs/live.md +88 -8
  46. package/docs/mail.md +32 -5
  47. package/docs/middleware.md +20 -12
  48. package/docs/navigation.json +12 -0
  49. package/docs/notifications.md +22 -0
  50. package/docs/pagination.md +4 -0
  51. package/docs/passwords.md +4 -6
  52. package/docs/providers.md +4 -6
  53. package/docs/queues.md +70 -2
  54. package/docs/requests.md +42 -3
  55. package/docs/responses.md +9 -5
  56. package/docs/routing.md +118 -7
  57. package/docs/scheduling.md +27 -0
  58. package/docs/session.md +2 -2
  59. package/docs/starter-kits.md +26 -7
  60. package/docs/storage.md +10 -4
  61. package/docs/testing.md +10 -2
  62. package/docs/two-factor.md +38 -4
  63. package/docs/upgrade.md +182 -0
  64. package/docs/validation.md +70 -9
  65. package/docs/views.md +1 -0
  66. package/docs/vite.md +20 -1
  67. package/package.json +43 -35
  68. package/dist/chunk-4NCMY3ZS.js.map +0 -1
  69. package/dist/chunk-BKA5F3TH.js.map +0 -1
  70. package/dist/chunk-UBSIBGXR.js.map +0 -1
@@ -0,0 +1,71 @@
1
+ # Oriel for Laravel developers
2
+
3
+ Oriel follows Laravel's structure, names and docs, so most of what you know carries over: routes, controllers,
4
+ middleware, Eloquent, migrations, queues, mail and the rest work the way their Laravel pages say. This page gathers
5
+ what is different because Oriel is TypeScript, and what isn't in Oriel yet.
6
+
7
+ ## On the first day
8
+
9
+ | In Laravel | In Oriel |
10
+ | --- | --- |
11
+ | Constructor injection: `__construct(AppleMusic $apple)` | `inject()` in a field: `readonly #apple = inject(AppleMusic)`, as [the container](container.md#injecting-with-inject) shows |
12
+ | `$request->user()` | `await request().user()`: finding the user is a database query, so it returns a promise |
13
+ | `Route::group(...)` | `Route.group()` returns a promise, settled when its callback has run: await it when the callback is `async` ([route groups](routing.md#route-groups)) |
14
+ | A route that returns `null` answers an empty 200 | It answers an empty 204, "No Content" ([responses](responses.md)) |
15
+ | `config([...])`, `app()->bind()` and `View::share()` in a request | Change it for every later and concurrent request, as the app answers them all from one process; in `local` they log a warning ([configuration](configuration.md#accessing-configuration-values)) |
16
+ | `now()` is a Carbon instance | `now()` is a `Date` ([helpers](helpers.md#now)) |
17
+ | `$post->author` | `post.getRelation('author')` after `with('author')` or `load('author')`, or `await post.author().first()` ([relationships](eloquent-relationships.md#relationship-methods-vs-reading-a-relation)) |
18
+ | Blade templates | TSX views, or a React, Vue, Svelte, Solid or Angular page through Inertia ([views](views.md)) |
19
+ | Livewire's `wire:` attributes | [Live](live.md)'s `o:` attributes: `o:click`, `o:model`, `o:navigate`… |
20
+
21
+ ## Error names
22
+
23
+ Laravel's `*Exception` classes are `*Error` in Oriel, as JavaScript names its errors: `ModelNotFoundError`,
24
+ `AuthenticationError`, `AuthorizationError`, `TokenMismatchError`, `ThrottleRequestsError`, `NotFoundHttpError`,
25
+ `MethodNotAllowedHttpError`, `QueryError`, `InvalidSignatureError`, `MassAssignmentError`, `RelationNotFoundError`,
26
+ `MaxAttemptsExceededError`, `BindingResolutionError`, `LockTimeoutError`, `DecryptError`, `MissingAppKeyError`,
27
+ `ItemNotFoundError` and `MultipleItemsFoundError`. Symfony's `RouteNotFoundException` is `RouteNotDefinedError`.
28
+
29
+ Three keep Laravel's names, since you throw them yourself: `ValidationException`, `HttpException` and
30
+ `HttpResponseException`. [Errors](errors.md) covers reporting and rendering them.
31
+
32
+ ## Commands Oriel doesn't have
33
+
34
+ `node oriel list` shows the commands an app has ([console](console.md#available-commands)). Of the ones a Laravel deploy
35
+ script or a first week reaches for, these aren't there:
36
+
37
+ | Laravel | In Oriel |
38
+ | --- | --- |
39
+ | `optimize`, `config:cache`, `route:cache`, `view:cache`, `event:cache`, and their `:clear` | Nothing to cache: drop them from your deploy script. Oriel reads its config and routes as code when the app starts |
40
+ | `auth:clear-resets` | The token repository's `deleteExpired()`, in a scheduled task ([deleting expired tokens](passwords.md#deleting-expired-tokens)) |
41
+ | `vendor:publish` | Write the config file yourself: each package's page shows its keys |
42
+ | `make:component`, `make:exception`, `make:enum` | Write the file: a view component is a function in `resources/views/components`, an error a class that extends `Error`, an enum a TypeScript `enum` or a union |
43
+ | `db:show` | Your database's own client |
44
+ | `model:prune` | A [scheduled task](scheduling.md) that deletes the rows |
45
+ | `queue:prune-failed` | `queue:flush` empties the failed jobs; a scheduled query deletes old ones |
46
+
47
+ ## New in alpha.16, as in Laravel
48
+
49
+ - [CORS](routing.md#cross-origin-resource-sharing-cors): `api/*` routes answer cross-origin requests, as in Laravel 11.
50
+ - [Maintenance mode](configuration.md#maintenance-mode): `down` and `up`.
51
+ - [Global options](console.md#global-options) on every command: `--env`, `--quiet`, `--no-interaction`, `--version`…
52
+ - [`cache:clear`](cache.md#removing-items-from-the-cache) and `cache:forget`.
53
+ - [Named rate limiters](routing.md#defining-rate-limiters): `RateLimiter.for()` and `throttle:<name>`.
54
+ - Form requests' [`prepareForValidation()`](validation.md#preparing-input-for-validation),
55
+ [`after()` and `stopOnFirstFailure`](validation.md#additional-checks-and-stopping-early), and
56
+ [`safe()`](validation.md#working-with-validated-input).
57
+ - [Jobs dispatched after the commit](queues.md#jobs-and-database-transactions), and
58
+ [`DB.afterCommit()`](database.md#running-code-after-the-commit).
59
+ - The framework's events: [job events](queues.md#job-events), [mail events](mail.md#mail-events),
60
+ [notification events](notifications.md#notification-events) and [scheduled task events](scheduling.md#events).
61
+ - [API resources](eloquent-resources.md): `JsonResource` and `ResourceCollection`.
62
+ - In the browser starter kits, [two-factor authentication](starter-kits.md#two-factor-authentication) and
63
+ [password confirmation](authentication.md#password-confirmation).
64
+
65
+ ## More differences
66
+
67
+ Each page names its own differences from Laravel in a note. The pages with the most are
68
+ [console](console.md), [validation](validation.md), [mail](mail.md), [helpers](helpers.md), [cache](cache.md),
69
+ [middleware](middleware.md), [Eloquent relationships](eloquent-relationships.md) and [database](database.md).
70
+ [Live](live.md#differences-from-livewire) lists how it differs from Livewire, and the
71
+ [upgrade guide](upgrade.md) what changed between Oriel's releases.
package/docs/lifecycle.md CHANGED
@@ -65,10 +65,10 @@ request, then it shuts down, and the process exits with the command's exit code.
65
65
  ### Service providers
66
66
 
67
67
  Service providers set up every part of the framework: the database, the queue, validation, routing and the rest.
68
- `create()` calls each provider's `register()`, in order. The framework has 22, registered first, in this order:
68
+ `create()` calls each provider's `register()`, in order. The framework has 24, registered first, in this order:
69
69
  Pipeline, Encryption, Cookie, Session, Hashing, Log, Event, Cache, Filesystem, Database, Queue, Bus, Mail,
70
- Notifications, Validation, Auth, View, Inertia, Live, Routing, Http and Console (each one's class is its name followed
71
- by `ServiceProvider`). Each may rely on the ones before it. Yours come next, in the order `bootstrap/providers.ts`
70
+ Notifications, Validation, Auth, View, Inertia, Live, Routing, Http, Console, Ide and Vercel (each one's class is its
71
+ name followed by `ServiceProvider`). Each may rely on the ones before it. Yours come next, in the order `bootstrap/providers.ts`
72
72
  lists them.
73
73
 
74
74
  `create()` registers the providers but doesn't boot them. The app boots once, the first time something needs it:
@@ -106,7 +106,9 @@ Application.configure({ basePath: '.' })
106
106
 
107
107
  `app.handle()` opens a request scope, and the kernel binds the request in it: everything resolved for this request,
108
108
  such as the request, its session and its cookie jar, lives in the scope and is dropped with it. The global middleware
109
- run first: `TrimStrings`, `ConvertEmptyStringsToNull`, and those you add with
109
+ run first: `RenameClasses`, outermost, which renames the classes of a [scrambled](vite.md#class-name-scrambling) build
110
+ in the pages that leave, then `HandleCors`, which answers [CORS](routing.md#cross-origin-resource-sharing-cors) on the
111
+ API's paths, `TrimStrings`, `ConvertEmptyStringsToNull`, and those you add with
110
112
  [`withMiddleware()`](middleware.md#global-middleware).
111
113
 
112
114
  The router then finds the route. A path no route matches is a 404, and a path whose routes don't take the request's
@@ -141,7 +143,9 @@ The server writes the response, and then the app terminates the request, still i
141
143
  2. the `terminating()` callbacks run, in the order they were added. One of them is the framework's: it runs the jobs
142
144
  you dispatched with [`dispatchAfterResponse()`](queues.md#running-a-job-now).
143
145
 
144
- On Node, this starts once the response is written; on Bun, right after the response is handed to the server.
146
+ On Node, this starts once the response is written; on Bun, right after the response is handed to the server. On
147
+ Vercel, the function hands this work to Vercel's `waitUntil()` and returns at once, so the visitor's connection is
148
+ free while it runs (see [What changes on Vercel](deployment.md#what-changes-on-vercel)).
145
149
 
146
150
  Register a terminating callback in a service provider. It receives no arguments:
147
151
 
package/docs/live.md CHANGED
@@ -796,7 +796,8 @@ rather than an `o:` directive.
796
796
  > [!WARNING]
797
797
  > Every upload must also pass `live.temporary_file_upload.rules`, which allow 12 MB. A request body larger than
798
798
  > `http.max_body_size`, 8 MB, gets a 413, and the field gets "The photo failed to upload.". To accept files up to the
799
- > rule's size, raise `max_body_size` in `config/http.ts`.
799
+ > rule's size, raise `max_body_size` in `config/http.ts`. On Vercel, a function takes request bodies up to 4.5 MB
800
+ > whatever `max_body_size` says, so larger files need another way in ([Live uploads](storage.md#live-uploads)).
800
801
 
801
802
  ## Navigating
802
803
 
@@ -846,9 +847,11 @@ action redirects: then it is there on the next page.
846
847
 
847
848
  ## Middleware on updates
848
849
 
849
- Each update runs the `auth`, `verified`, `guest` and `can` middleware of the route that rendered the page again, with
850
- that route's parameters, before the component's actions. A user who signed out in another tab gets a 401, and one who
851
- lost an ability a 403. The list is `live.persistent_middleware`.
850
+ Each update runs the `auth`, `verified`, `guest`, `can` and `password.confirm` middleware of the route that rendered
851
+ the page again, with that route's parameters, before the component's actions. A user who signed out in another tab gets
852
+ a 401, one who lost an ability a 403, and one whose [password confirmation](authentication.md#password-confirmation)
853
+ ran out a 423. On a 401 or a 423 the page reloads, so its middleware sends the browser to log in or to confirm the
854
+ password. The list is `live.persistent_middleware`.
852
855
 
853
856
  ## Announcing status messages
854
857
 
@@ -901,6 +904,81 @@ the region to text: its children are taken out for 100 ms, so a button in it wou
901
904
  A component has `get(name)`, `set(name, value)`, which sends the value with the next request, `call(method, params)`,
902
905
  with the arguments in an array, `call('publish', [5])`, which resolves with the action's return value, and `commit()`.
903
906
 
907
+ ## Live in an Inertia app
908
+
909
+ An [Inertia](inertia.md) app can have Live pages too, as a Laravel app can have Livewire pages beside Inertia's. Each
910
+ page is one or the other: the Inertia pages keep their root view and client, and the Live pages get a layout and a
911
+ client of their own.
912
+
913
+ Add `@orieljs/live-client` to the app, and give Vite a second input that starts it:
914
+
915
+ ```ts title="resources/js/live.ts"
916
+ import { Live } from '@orieljs/live-client'
917
+
918
+ Live.start()
919
+ ```
920
+
921
+ ```ts title="vite.config.ts"
922
+ import { oriel } from '@orieljs/vite'
923
+ import { defineConfig } from 'vite'
924
+
925
+ export default defineConfig({
926
+ plugins: [oriel({ framework: 'react', input: ['resources/css/app.css', 'resources/js/app.tsx', 'resources/js/live.ts'] })],
927
+ })
928
+ ```
929
+
930
+ The Live pages' layout loads that input with `vite()`, and the Inertia root view doesn't, so neither page runs the
931
+ other's client. Name the layout in `config/live.ts`, or on a component with `static layout`:
932
+
933
+ ```tsx title="resources/views/components/layouts/live.tsx"
934
+ import { vite, type Renderable } from '@orieljs/framework'
935
+
936
+ export default function LiveLayout({ title, children }: { title?: string; children?: Renderable }) {
937
+ return (
938
+ <html lang="en">
939
+ <head>
940
+ <meta charset="utf-8" />
941
+ <title>{title}</title>
942
+ {vite(['resources/css/app.css', 'resources/js/live.ts'])}
943
+ </head>
944
+ <body>{children}</body>
945
+ </html>
946
+ )
947
+ }
948
+ ```
949
+
950
+ ```ts title="config/live.ts"
951
+ export default {
952
+ layout: 'components.layouts.live',
953
+ }
954
+ ```
955
+
956
+ A component's route sits beside the Inertia ones:
957
+
958
+ ```ts title="routes/web.ts"
959
+ // @filename: app/Live/Counter.tsx
960
+ import { Component } from '@orieljs/framework'
961
+ export default class Counter extends Component {
962
+ render() {
963
+ return <p />
964
+ }
965
+ }
966
+ // ---cut---
967
+ import { Route } from '@orieljs/framework'
968
+ import Counter from '../app/Live/Counter'
969
+
970
+ Route.inertia('/', 'Welcome')
971
+ Route.get('/counter', Counter).middleware('auth')
972
+ ```
973
+
974
+ Both kinds of page share the session, so a user signs in once. The Inertia middleware's shared props reach the
975
+ Inertia pages only; a Live component reads what it needs itself, such as `request().user()`. Live's updates go through
976
+ the `web` group, the Inertia middleware with them, which lets them pass, as they aren't Inertia visits.
977
+
978
+ To go from an Inertia page to a Live page, use a plain `<a>`: the browser loads the page in full. Inertia's `<Link>`
979
+ expects an Inertia response, which a Live page isn't. From a Live page, `o:navigate` to an Inertia page loads it in
980
+ full too: the Inertia root view's `vite()` tags track another entry, so Live doesn't swap it in.
981
+
904
982
  ## Configuration
905
983
 
906
984
  Live's settings are under `live`. A new app has no `config/live.ts`; add one to change them:
@@ -910,7 +988,7 @@ Live's settings are under `live`. A new app has no `config/live.ts`; add one to
910
988
  | `class_path` | `app/Live` | The folder whose components are registered at boot |
911
989
  | `layout` | `components.layouts.app` | The layout of full-page components |
912
990
  | `lazy_placeholder` | none | The view lazy components show before they load |
913
- | `persistent_middleware` | `auth`, `verified`, `guest`, `can` | The page route's middleware each update runs again |
991
+ | `persistent_middleware` | `auth`, `verified`, `guest`, `can`, `password.confirm` | The page route's middleware each update runs again |
914
992
  | `temporary_file_upload.disk` | Your default disk | Where uploads wait until they are stored |
915
993
  | `temporary_file_upload.directory` | `live-tmp` | The folder on that disk |
916
994
  | `temporary_file_upload.rules` | `required`, `file`, `max:12288` | The rules every upload must pass |
@@ -927,6 +1005,8 @@ tests](live-tests.md) covers it.
927
1005
  ## Differences from Livewire
928
1006
 
929
1007
  > [!NOTE]
930
- > Live has no Alpine.js, `wire:stream`, `#[Url]` query-string binding, `#[Reactive]`, `#[Modelable]`, form objects or
931
- > JavaScript hooks (`Livewire.hook()`). `temporaryUrl()` previews don't answer range requests, which Safari needs to
932
- > play a `<video>`.
1008
+ > Livewire bundles Alpine.js; Live doesn't, but works beside it: a morph keeps an Alpine component's state (through
1009
+ > `Alpine.cloneNode()`, as Livewire's does), and an Alpine `$dispatch` event reaches the Live components that listen for
1010
+ > it. Live has no `wire:stream`, `#[Url]` query-string binding, `#[Reactive]`, `#[Modelable]`, form objects, JavaScript
1011
+ > hooks (`Livewire.hook()`), `#[Validate]` attributes or `validateOnly()`, and `o:navigate` has no progress bar and no
1012
+ > `@persist`. `temporaryUrl()` previews don't answer range requests, which Safari needs to play a `<video>`.
package/docs/mail.md CHANGED
@@ -5,8 +5,8 @@ it to the log, or queues it for a worker.
5
5
 
6
6
  ## Introduction
7
7
 
8
- Oriel sends mail with [Nodemailer](https://nodemailer.com), which comes with the framework. A new app writes every
9
- mail to its log instead of sending it, so you can work on your mail before you set up a mail server.
8
+ Oriel sends mail over SMTP with [Nodemailer](https://nodemailer.com), which a new app lists in its dependencies. A new
9
+ app writes every mail to its log instead of sending it, so you can work on your mail before you set up a mail server.
10
10
 
11
11
  ### Configuration
12
12
 
@@ -23,6 +23,7 @@ export default {
23
23
  transport: 'smtp',
24
24
  host: env('MAIL_HOST', '127.0.0.1'),
25
25
  port: Number(env('MAIL_PORT', 2525)),
26
+ encryption: env('MAIL_ENCRYPTION'),
26
27
  username: env('MAIL_USERNAME'),
27
28
  password: env('MAIL_PASSWORD'),
28
29
  },
@@ -37,13 +38,17 @@ export default {
37
38
  Oriel has four transports:
38
39
 
39
40
  - `smtp` sends the mail to an SMTP server: `host`, `port`, and `username` and `password` when the server asks for
40
- them. Add `encryption: 'ssl'` for a server that speaks TLS from the start (usually port 465), or
41
- `encryption: 'tls'` to require STARTTLS.
41
+ them. On port 465 it speaks TLS from the start, and elsewhere it uses STARTTLS when the server offers it, with no
42
+ setting. `encryption` (`MAIL_ENCRYPTION`) overrides that: `'ssl'` for TLS from the start on another port, `'tls'` to
43
+ refuse a server that doesn't offer STARTTLS.
42
44
  - `log` writes each mail to your log, through the channel `channel` names, or your default channel.
43
45
  - `array` keeps the mails in memory, in the app's process, and sends nothing.
44
46
  - `failover` tries the mailers of its `mailers` list in turn (see [Failover configuration](#failover-configuration)).
45
47
 
46
- To send real mail, set `MAIL_MAILER=smtp` and the `MAIL_*` variables of your mail server in `.env`.
48
+ To send real mail, set `MAIL_MAILER=smtp` and the `MAIL_*` variables of your mail server in `.env`. The `smtp`
49
+ transport sends through `nodemailer`, which a new app lists in its dependencies; an app made before 0.1.0-alpha.16
50
+ installs it with `npm install nodemailer`. It's loaded when the first mail goes out, so an app that only logs its mail
51
+ never needs it.
47
52
 
48
53
  > [!NOTE]
49
54
  > Laravel also has transports for Mailgun, Postmark, Resend, Amazon SES and `sendmail`, and a `roundrobin` mailer.
@@ -532,6 +537,28 @@ Route.get('/mailable', async () => {
532
537
  > Laravel renders a mailable you return from a route. Oriel sends a returned mailable as JSON, like any other object,
533
538
  > so render it first, as above.
534
539
 
540
+ ## Mail events
541
+
542
+ Each message dispatches two [events](events.md), as in Laravel: `MessageSending` before it goes, and `MessageSent`
543
+ once the transport has taken it. Each has the `message` (its addresses, subject, HTML and text, which a
544
+ `MessageSending` listener may change) and `data.mailable`; `MessageSent` has what the transport returned, `sent`. A
545
+ `MessageSending` listener that returns `false` stops the message, and `sendNow()` then resolves `undefined`:
546
+
547
+ ```ts title="app/Providers/AppServiceProvider.ts"
548
+ import { Event, MessageSending, ServiceProvider } from '@orieljs/framework'
549
+
550
+ export class AppServiceProvider extends ServiceProvider {
551
+ override boot(): void {
552
+ Event.listen(MessageSending, (event: MessageSending) => {
553
+ if (event.message.to.some((address) => address.address.endsWith('@example.test'))) return false
554
+ return undefined
555
+ })
556
+ }
557
+ }
558
+ ```
559
+
560
+ A queued mailable dispatches them on the worker, when it's sent. `Mail.fake()` sends nothing, so it dispatches neither.
561
+
535
562
  ## Testing
536
563
 
537
564
  `Mail.fake()` swaps the mailer for a fake that sends nothing and records each mail. Its assertions check what your
@@ -36,7 +36,8 @@ To let the request pass, call `next(request)` and return what it returns. Think
36
36
  passes through on its way to your route: each layer can examine the request and turn it away.
37
37
 
38
38
  `handle()` returns a `Response`, so turn a redirect into one with its `toResponse(request)`, or throw: `abort(403)`
39
- ends the request with a 403.
39
+ ends the request with a 403. A middleware that returns nothing is an error, a 500 "Middleware must return a Response.":
40
+ return what `next(request)` gives.
40
41
 
41
42
  #### Middleware and responses
42
43
 
@@ -112,9 +113,12 @@ Application.configure({ basePath: '.' }).withMiddleware((middleware) => {
112
113
  })
113
114
  ```
114
115
 
115
- `append()` adds it at the end of the global list, and `prepend()` at the start. The list starts with `TrimStrings`,
116
- which trims every text input except `password`, `password_confirmation` and `current_password`, and
117
- `ConvertEmptyStringsToNull`, which turns empty inputs into `null`.
116
+ `append()` adds it at the end of the global list, and `prepend()` at the start. The list starts with `HandleCors`, which
117
+ answers [CORS](routing.md#cross-origin-resource-sharing-cors) on `api/*`, then `TrimStrings`, which trims every text
118
+ input except `password`, `password_confirmation` and `current_password`, and `ConvertEmptyStringsToNull`, which turns
119
+ empty inputs into `null`. `remove()` takes a middleware out of the list, and `trimStrings()` and
120
+ `convertEmptyStringsToNull()` give those two their exceptions, as
121
+ [Requests](requests.md#input-trimming-and-normalization) shows.
118
122
 
119
123
  Laravel's global list also checks trusted proxies and the size of the body. In Oriel these aren't middleware: the
120
124
  request applies them from `config/http.ts`, as [Requests](requests.md) explains.
@@ -231,13 +235,16 @@ they own.
231
235
  | Alias | Middleware | What it does |
232
236
  | --- | --- | --- |
233
237
  | `auth` | `Authenticate` | Lets signed-in users through. A guest gets a 401 for JSON, or a redirect to the login page. `auth:token` names the guard; with several, the first that has a user wins |
238
+ | `auth.session` | `AuthenticateSession` | Signs a session out once the user's password changed elsewhere, on every session driver (see [invalidating sessions on other devices](authentication.md#invalidating-sessions-on-other-devices)) |
234
239
  | `cache.headers` | `SetCacheHeaders` | Sets `Cache-Control` on GET and HEAD responses, as `cache.headers:public;max_age=3600;s_maxage=86400;etag` (`etag` adds an ETag and answers 304 when it matches); a response that sets a cookie is left alone, so a CDN never stores one visitor's page |
235
240
  | `can` | `Authorize` | Checks an ability with the gate, as `can:update,post`; a parameter that names a route parameter passes the bound model. A denial is a 403 |
236
241
  | `guest` | `RedirectIfAuthenticated` | Lets guests through, and redirects signed-in users |
237
242
  | `inertia.encrypt` | `EncryptHistory` | Encrypts the browser history state of the Inertia pages behind it |
243
+ | `password.confirm` | `RequirePassword` | Wants the password confirmed within `auth.password_timeout` seconds: JSON gets a 423, a page a redirect to the `password.confirm` route (see [password confirmation](authentication.md#password-confirmation)) |
238
244
  | `precognitive` | `HandlePrecognitiveRequests` | Answers a precognitive request once its data is validated (see [precognitive requests](#precognitive-requests)) |
239
245
  | `signed` | `ValidateSignature` | Wants a valid, unexpired signed URL, else a 403; `signed:relative` checks a URL signed without its host |
240
- | `throttle` | `ThrottleRequests` | Limits a client's requests in a window of minutes, as `throttle:60,1` for 60 a minute (see [rate limiting](routing.md#rate-limiting)) |
246
+ | `throttle` | `ThrottleRequests` | Limits a client's requests in a window of minutes, as `throttle:60,1` for 60 a minute, or by a limiter `RateLimiter.for()` names, as `throttle:api` (see [rate limiting](routing.md#rate-limiting)) |
247
+ | `two-factor.challenge` | `TwoFactorChallenge` | Lets only a login waiting for its second factor through; anyone else is sent to log in (see [two-factor login](two-factor.md#the-challenge-page)) |
241
248
  | `verified` | `EnsureEmailIsVerified` | Wants a verified email address: JSON gets a 403, a page a redirect to the `verification.notice` route, or the route you name, as `verified:profile.edit` |
242
249
 
243
250
  #### Redirecting guests and signed-in users
@@ -263,15 +270,14 @@ group first, then its own. Among a route's middleware, the same middleware with
263
270
  it first appears.
264
271
 
265
272
  Within a route's middleware, the `web` and `api` groups' middleware and `auth` and `guest` run first, keeping their
266
- order. Then route model binding runs, then everything else. So `can:update,post` sees the bound `Post`, and a guest
267
- is redirected before any database lookup. `throttle` is among everything else, so it runs after binding: a throttled
268
- route with a model parameter looks the model up before it counts the request, and a missing model is a 404 that isn't
269
- counted.
273
+ order, then `throttle`. Then route model binding runs, then everything else. So `can:update,post` sees the bound
274
+ `Post`, a guest is redirected before any database lookup, and a throttled request is refused before its model is looked
275
+ up: a request for a missing model counts toward the limit, as in Laravel.
270
276
 
271
277
  > [!NOTE]
272
278
  > Laravel sorts route middleware by a priority list, which `priority()` changes. Oriel keeps only the part of it that
273
- > route model binding needs, the session and the signed-in user before the lookup, and has no `priority()`: when two
274
- > of your middleware depend on each other, list them in that order.
279
+ > route model binding needs, the session, the signed-in user and `throttle` before the lookup, and has no
280
+ > `priority()`: when two of your middleware depend on each other, list them in that order.
275
281
 
276
282
  ## Middleware parameters
277
283
 
@@ -360,7 +366,9 @@ Angular forms don't offer it.
360
366
  - When the data passes, the request ends there: a 204 with a `Precognition-Success: true` header.
361
367
  - When it fails, the usual 422 with the errors.
362
368
 
363
- A `Precognition-Validate-Only: name,email` header limits the check to those fields. Every response of the route varies
369
+ A `Precognition-Validate-Only: name,email` header limits the check to those fields. A `*` in one stands for one segment,
370
+ as in Laravel 12: `items.*.name` checks the rules for `items.0.name`, `items.1.name` and `items.*.name`, while
371
+ `items.0.name` doesn't check a rule written `items.*.name`. Every response of the route varies
364
372
  on `Precognition`, and a precognitive one carries a `Precognition: true` header.
365
373
 
366
374
  ```ts
@@ -7,6 +7,14 @@
7
7
  "slug": "installation",
8
8
  "title": "Installation"
9
9
  },
10
+ {
11
+ "slug": "laravel",
12
+ "title": "Oriel for Laravel developers"
13
+ },
14
+ {
15
+ "slug": "upgrade",
16
+ "title": "Upgrade guide"
17
+ },
10
18
  {
11
19
  "slug": "configuration",
12
20
  "title": "Configuration"
@@ -221,6 +229,10 @@
221
229
  "slug": "eloquent-mutators",
222
230
  "title": "Accessors and casts"
223
231
  },
232
+ {
233
+ "slug": "eloquent-resources",
234
+ "title": "API resources"
235
+ },
224
236
  {
225
237
  "slug": "eloquent-factories",
226
238
  "title": "Factories"
@@ -223,3 +223,25 @@ await notification.markAsUnread()
223
223
 
224
224
  `Notification.extend(name, factory)` adds a channel: an object with `send(notifiable, notification)`. List its name in
225
225
  `via()`.
226
+
227
+ ## Notification events
228
+
229
+ Each channel a notification goes through dispatches Laravel's [events](events.md): `NotificationSending` before it
230
+ sends, and `NotificationSent` after, with what the channel returned as `response`. Each has the `notifiable`, the
231
+ `notification` and the `channel`'s name. A `NotificationSending` listener that returns `false` skips that channel, and
232
+ the others still send. A channel that throws dispatches `NotificationFailed`, with the error as `data.exception`, and
233
+ the error goes on as before:
234
+
235
+ ```ts title="app/Providers/AppServiceProvider.ts"
236
+ import { Event, NotificationSent, ServiceProvider } from '@orieljs/framework'
237
+
238
+ export class AppServiceProvider extends ServiceProvider {
239
+ override boot(): void {
240
+ Event.listen(NotificationSent, (event: NotificationSent) => {
241
+ console.log(`${event.notification.constructor.name} sent by ${event.channel}`)
242
+ })
243
+ }
244
+ }
245
+ ```
246
+
247
+ A queued notification dispatches them on the worker, when its job runs.
@@ -141,6 +141,10 @@ methods describe the page:
141
141
  | `cursor()`, `nextCursor()`, `previousCursor()` | The cursors (`cursorPaginate()` only) |
142
142
  | `getCollection()`, `through(fn)` | The items as a collection, and a paginator of the items passed through `fn` |
143
143
 
144
+ An Eloquent query's `getCollection()` is the models' [Eloquent collection](eloquent-collections.md), as in Laravel, so
145
+ `load()` and `modelKeys()` work on a page; a query builder's is a plain `Collection`. After `through()`, the items are
146
+ in a plain `Collection` unless the function returned models.
147
+
144
148
  ### In views
145
149
 
146
150
  Oriel's views are TSX, so there is no `links()` that prints the links for you. `linkCollection()` gives them as objects,
package/docs/passwords.md CHANGED
@@ -22,12 +22,10 @@ per email address, with the token and when it was made. A new token for an addre
22
22
 
23
23
  ### Configuring trusted hosts
24
24
 
25
- > [!WARNING]
26
- > The reset link in the mail starts with the scheme and host of the request that asked for it, as Laravel's does.
27
- > Laravel can restrict the hosts it answers (`trustHosts()`); Oriel can't. Have your web server or proxy answer only
28
- > your app's own host names, or build the link from `APP_URL` yourself, as
29
- > [Reset link customization](#reset-link-customization) shows, so that a request with a forged `Host` header can't
30
- > send your users a link to another site.
25
+ The reset link in the mail starts with the scheme and host of the request that asked for it, as Laravel's does. So
26
+ that a request with a forged `Host` header can't send your users a link to another site, answer only your own hosts
27
+ with [`trustHosts()`](requests.md#configuring-trusted-hosts), have your web server or proxy answer only them, or build
28
+ the link from `APP_URL` yourself, as [Reset link customization](#reset-link-customization) shows.
31
29
 
32
30
  ## Routing
33
31
 
package/docs/providers.md CHANGED
@@ -9,7 +9,7 @@ Service providers are the central place of your app's setup. Your own app, and e
9
9
  through them. Setting up here means registering things: bindings in the [service container](container.md), event
10
10
  listeners, view composers, route patterns and bindings.
11
11
 
12
- Oriel uses 22 service providers of its own, for the mailer, the queue, the cache and the rest. [Request
12
+ Oriel uses 24 service providers of its own, for the mailer, the queue, the cache and the rest. [Request
13
13
  lifecycle](lifecycle.md#service-providers) lists them, and shows where providers fit in how your app starts. Your own
14
14
  providers are listed in `bootstrap/providers.ts`. This page shows how to write them and register them.
15
15
 
@@ -42,11 +42,9 @@ export class RiakServiceProvider extends ServiceProvider {
42
42
  }
43
43
  ```
44
44
 
45
- `make:provider` doesn't register the provider: add it to `bootstrap/providers.ts` yourself, as [Registering
46
- providers](#registering-providers) shows. `--force` overwrites a provider that exists.
47
-
48
- > [!NOTE]
49
- > Laravel's `make:provider` adds the new provider to `bootstrap/providers.php` for you. Oriel's writes the class only.
45
+ `make:provider` also registers the provider: it imports it in `bootstrap/providers.ts` and adds it at the end of the
46
+ list, as Laravel's does with `bootstrap/providers.php` (see [Registering providers](#registering-providers)). When it
47
+ can't find the list there, it says what to add. `--force` overwrites a provider that exists, without listing it twice.
50
48
 
51
49
  ### The register method
52
50
 
package/docs/queues.md CHANGED
@@ -24,8 +24,11 @@ export default {
24
24
  ```
25
25
 
26
26
  The `sync` driver runs each job straight away, in the same process, which is handy in tests; `redis` reads its server
27
- from `database.redis` in `config/database.ts`. Within a connection, jobs go onto named **queues**, so a worker can run
28
- the urgent ones first. Without a name, a job goes onto the connection's `queue`, here `default`.
27
+ from `database.redis` in `config/database.ts`, and needs Oriel's Redis client, `ioredis`, which you install yourself
28
+ (`npm install ioredis`). Within a connection, jobs go onto named **queues**, so a worker can run
29
+ the urgent ones first. Without a name, a job goes onto the connection's `queue`, here `default`. `after_commit` holds
30
+ jobs dispatched inside a database transaction until it commits (see
31
+ [Jobs and database transactions](#jobs-and-database-transactions)).
29
32
 
30
33
  ## Creating jobs
31
34
 
@@ -126,6 +129,39 @@ await ProcessPodcast.dispatchSync(podcast)
126
129
  ProcessPodcast.dispatchAfterResponse(podcast)
127
130
  ```
128
131
 
132
+ ### Jobs and database transactions
133
+
134
+ A job dispatched inside a database transaction can reach the worker before the transaction commits, and the worker
135
+ then can't find the rows the job is about, or reads them as they were. With `after_commit: true` on the connection in
136
+ `config/queue.ts`, a job dispatched inside a transaction is pushed only once the transaction commits, the outermost one
137
+ when they're nested, and is dropped if it rolls back: a `DB.transaction()`, or one `DB.beginTransaction()` opened,
138
+ until `DB.commit()` or `DB.rollBack()`. Outside a transaction, it's pushed at once, and so it is inside the transaction
139
+ `RefreshDatabase` opens around a test. A new app has it off:
140
+
141
+ ```ts
142
+ declare const podcast: Podcast
143
+ // ---cut---
144
+ await DB.transaction(async () => {
145
+ await podcast.update({ title: 'Episode 1, remastered' })
146
+
147
+ await ProcessPodcast.dispatch(podcast)
148
+ })
149
+ ```
150
+
151
+ `afterCommit()` and `beforeCommit()` decide for one dispatch, whatever the connection says, and a job class decides
152
+ for itself with an `afterCommit` field set to `true` or `false`:
153
+
154
+ ```ts
155
+ declare const podcast: Podcast
156
+ // ---cut---
157
+ await ProcessPodcast.dispatch(podcast).afterCommit()
158
+ await ProcessPodcast.dispatch(podcast).beforeCommit()
159
+ ```
160
+
161
+ Queued listeners, mail and notifications wait in the same way, with the field on the listener, the mailable or the
162
+ notification. Inside the transaction, the dispatch resolves with an empty job ID, since nothing is queued yet, and a
163
+ unique job that's dropped frees its lock. The waiting is [`DB.afterCommit()`](database.md#running-code-after-the-commit)'s.
164
+
129
165
  ### Choosing the queue and the connection
130
166
 
131
167
  ```ts
@@ -306,6 +342,12 @@ process manager such as systemd or Supervisor, and after each deploy run `node o
306
342
  worker to stop after its current job so the process manager starts it again on the new code
307
343
  ([Deployment](deployment.md#queue-workers) shows a Supervisor program).
308
344
 
345
+ A queued job stores the names of the classes it carries, and the worker finds them again in `app/Jobs`, `app/Events`,
346
+ `app/Listeners`, `app/Mail` and `app/Notifications`. A class keeps its own name, unless two classes there share it, an
347
+ `OrderShipped` event and an `OrderShipped` mailable: then each is stored by its folder, `Events.OrderShipped` and
348
+ `Mail.OrderShipped`. Your app and its workers find the same names, so deploy them together, and restart the workers
349
+ when you add a class whose name another one already has.
350
+
309
351
  `queue:restart` leaves its signal in your default cache store, which each worker reads after every job. While the
310
352
  cache can't be read, a worker goes on working and reports the error once per outage; it sees the next signal once
311
353
  the cache is back.
@@ -328,3 +370,29 @@ node oriel queue:flush
328
370
  ```
329
371
 
330
372
  `queue:clear` deletes the jobs still waiting on a queue: `node oriel queue:clear redis --queue=emails`.
373
+
374
+ ## Job events
375
+
376
+ The queue dispatches Laravel's job events through the [event dispatcher](events.md):
377
+
378
+ - `JobQueued` once a job is on a queue, with its `connectionName`, `queue`, `id`, `job`, `payload` and `delay`;
379
+ - `JobProcessing` before a worker runs a job, and `JobProcessed` after one that ran without failing, each with the
380
+ `connectionName` and the `job`;
381
+ - `JobFailed` when a job has failed for good, with the `exception` too. An attempt that's released for a retry
382
+ dispatches none.
383
+
384
+ The `sync` queue runs a job at once, so it dispatches `JobProcessing`, `JobProcessed` and `JobFailed`, and no
385
+ `JobQueued`. `Queue.before()`, `Queue.after()` and `Queue.failing()` listen for the last three, in a service
386
+ provider's `boot()`:
387
+
388
+ ```ts title="app/Providers/AppServiceProvider.ts"
389
+ import { Log, Queue, ServiceProvider } from '@orieljs/framework'
390
+
391
+ export class AppServiceProvider extends ServiceProvider {
392
+ override boot(): void {
393
+ Queue.failing((event) => {
394
+ void Log.error(`${event.job.payload().displayName} failed on ${event.connectionName}`, { error: String(event.exception) })
395
+ })
396
+ }
397
+ }
398
+ ```