@tolki/ts 1.1.0 → 1.1.2
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.
- package/README.md +457 -53
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/routes.d.ts +4 -0
- package/dist/routes.d.ts.map +1 -1
- package/dist/routes.js +9 -4
- package/dist/vite-plugin.d.ts.map +1 -1
- package/dist/vite-plugin.js +2 -1
- package/package.json +5 -9
package/README.md
CHANGED
|
@@ -449,6 +449,8 @@ The file has one top-level object per feature: `models`, `enums`, `resources`, `
|
|
|
449
449
|
}
|
|
450
450
|
```
|
|
451
451
|
|
|
452
|
+
A resource that publishes as a [discriminated union](https://tolki.abe.dev/ts/api-resources.html#discriminated-unions) lists its shared keys in `properties` and each union of variants in `variants`. One with [`#[TsIntersect]`](https://tolki.abe.dev/ts/extending-interfaces.html#intersecting-a-resource-with-tsintersect) lists each intersected type in `intersections`.
|
|
453
|
+
|
|
452
454
|
Look entries up by fully-qualified name, and read `name` for display. Two classes can share a short name in different namespaces, such as `App\Models\User` and `Crm\Models\User`, and a short-name key would let one overwrite the other.
|
|
453
455
|
|
|
454
456
|
#### Collected Files Manifest
|
|
@@ -861,7 +863,9 @@ export interface PostSummaryResource {
|
|
|
861
863
|
|
|
862
864
|
A backed enum's `->value` publishes its `{Name}Type`, and its `->name` publishes its `{Name}Kind`. A unit enum's `->name` publishes its `{Name}Type`, because its values are its case names.
|
|
863
865
|
|
|
864
|
-
A case you write out can send only its own value, so it publishes that value: `PostStatus::Published->value` publishes `1`, and `PostStatus::Published->name` publishes `'Published'`. A ternary between two cases publishes both values. `PostStatus::from($value)->value` publishes `PostStatusType`, and after `PostStatus::tryFrom()`, `?->value` publishes `PostStatusType | null`. A method you call on a case publishes its return type.
|
|
866
|
+
A case you write out can send only its own value, so it publishes that value: `PostStatus::Published->value` publishes `1`, and `PostStatus::Published->name` publishes `'Published'`. A ternary between two cases publishes both values. Beside a read of the same enum, the alias already holds a case's value, so the value is left out: `$draft ? PostStatus::Draft->value : $this->status->value` publishes `PostStatusType`, not `0 | PostStatusType`. `PostStatus::from($value)->value` publishes `PostStatusType`, and after `PostStatus::tryFrom()`, `?->value` publishes `PostStatusType | null`. A method you call on a case publishes its return type.
|
|
867
|
+
|
|
868
|
+
A `->value` or `->name` read off a method call, `$this->m()`, `$this::m()`, `self::m()`, `static::m()` or `parent::m()`, publishes the value or name of each case that method returns, when neither its return type nor a `@return` tag names a class, as with no return type or `mixed`. When `draft(): mixed` returns `PostStatus::Draft`, `$this->draft()->value` publishes `0`. A method declared `: PostStatus`, or documented `@return PostStatus`, keeps the alias, so the read publishes `PostStatusType`. A `null` the method returns is left out, as it is for any `->` read, so `->value` off a method returning `$draft ? PostStatus::Draft : null` publishes `0`, and `?->value` publishes `0 | null`. A method with no return type that can end without returning a value leaves the read `unknown`.
|
|
865
869
|
|
|
866
870
|
In an API resource, `PostStatus::cases()` publishes a list of the alias. A map over the cases publishes what its callback reads from each case, with or without a type hint:
|
|
867
871
|
|
|
@@ -1067,6 +1071,20 @@ A unit enum publishes each case name as its value, so `values` returns its case
|
|
|
1067
1071
|
|
|
1068
1072
|
`values` and `keys` read the `_cases` list, so they need `enums.metadata_enabled` and return an empty array without it. `defineEnum()` doesn't add `values` or `keys` to the enum. An enum that publishes its own `values()` or `keys()` static method keeps that published value under the name, so `Status.values` is the static method's published output while `values(Status)` returns the case values.
|
|
1069
1073
|
|
|
1074
|
+
### Bundling
|
|
1075
|
+
|
|
1076
|
+
An enum nobody uses drops out of your bundle in every bundler, esbuild included, because the generated file marks its `defineEnum` call `/* @__PURE__ */`. The other runtime utilities are marked as free of side effects, except `from`, which throws on an unknown value and is always kept:
|
|
1077
|
+
|
|
1078
|
+
```typescript
|
|
1079
|
+
export const Status = /* @__PURE__ */ defineEnum({
|
|
1080
|
+
Active: "active",
|
|
1081
|
+
Inactive: "inactive",
|
|
1082
|
+
_cases: ["Active", "Inactive"],
|
|
1083
|
+
});
|
|
1084
|
+
```
|
|
1085
|
+
|
|
1086
|
+
The other examples on this page leave the comment out. A file published by an older version of the package, or by a custom `enums.template`, may not have it, and esbuild then keeps the call. Rspack also keeps the enum when the same module derives a list from it, unless that call is marked too, such as `export const STATUSES = /* @__PURE__ */ values(Status)`. [Bundling and Tree-Shaking](https://tolki.abe.dev/tree-shaking.html) lists every bundler.
|
|
1087
|
+
|
|
1070
1088
|
### Vite Plugin
|
|
1071
1089
|
|
|
1072
1090
|
The `@tolki/ts` package ships a Vite plugin that republishes enums and routes automatically during development. See the [Vite Plugin documentation](https://tolki.abe.dev/ts/vite-plugin.html).
|
|
@@ -1510,15 +1528,37 @@ A specific return type or `Attribute<Get, Set>` generic is always read first, so
|
|
|
1510
1528
|
- Calls something whose return type can't be determined
|
|
1511
1529
|
- Reads another accessor that reads it back, in which case both publish `unknown`
|
|
1512
1530
|
- Can only be typed as `null`, because one side of a `??` or a ternary couldn't be typed
|
|
1513
|
-
- Names two different classes or enums that share a short name, such as `$this->status ?? $this->author?->status` when each `status` is a different `Status` enum
|
|
1514
1531
|
- Returns an API resource
|
|
1515
1532
|
|
|
1516
1533
|
The `null` case keeps a getter from publishing a type that's plainly wrong: `fn ($value, array $attributes) => $attributes['title'] ?? null` publishes `unknown`, not `null`, because its real value is the title.
|
|
1517
1534
|
|
|
1535
|
+
A getter that returns either of two classes or enums that share a short name publishes both, each under its own alias. With `$this->status` an `App\Enums\Status` and `$this->author?->status` an `App\Crm\Enums\Status`, `$this->status ?? $this->author?->status` publishes `EnumsStatusType | CrmStatusType | null`.
|
|
1536
|
+
|
|
1518
1537
|
A getter closure with no native return type takes its type from a `@return` docblock written just before it, so `Attribute::get(/** @return int */ fn () => json_decode($this->stats_json))` publishes `number`. The package reads that docblock only when it can't type what the getter returns, and ignores a vague one, such as `@return mixed`.
|
|
1519
1538
|
|
|
1520
1539
|
A getter that reads an attribute through `getAttribute()` or `getAttributeValue()` with a literal name takes the attribute's type, so `Attribute::get(fn () => $this->getAttribute('title'))` publishes `string`, as `fn () => $this->title` does.
|
|
1521
1540
|
|
|
1541
|
+
A getter that returns an [`EnumResource`](https://tolki.abe.dev/ts/enum-api-resource.html) publishes `AsEnum<typeof X>`, alone or inside the shape it builds, and the model file imports `AsEnum` and the enum's const. A wrap around a nullable column adds `| never[]`, because the model sends the empty resource as `[]`:
|
|
1542
|
+
|
|
1543
|
+
```php
|
|
1544
|
+
protected function statusResource(): Attribute
|
|
1545
|
+
{
|
|
1546
|
+
return Attribute::get(fn () => EnumResource::make($this->status));
|
|
1547
|
+
}
|
|
1548
|
+
|
|
1549
|
+
protected function priorityResource(): Attribute
|
|
1550
|
+
{
|
|
1551
|
+
return Attribute::get(fn () => EnumResource::make($this->priority));
|
|
1552
|
+
}
|
|
1553
|
+
```
|
|
1554
|
+
|
|
1555
|
+
With `priority` nullable, the two accessors publish:
|
|
1556
|
+
|
|
1557
|
+
```typescript
|
|
1558
|
+
status_resource: AsEnum<typeof Status>;
|
|
1559
|
+
priority_resource: AsEnum<typeof Priority> | never[];
|
|
1560
|
+
```
|
|
1561
|
+
|
|
1522
1562
|
Laravel runs an accessor's getter for a `NULL` column too, so an accessor on a nullable column publishes `| null` only where its getter can return `null`. A getter whose native return type is non-null, such as `fn (?string $value): array => …`, publishes no `| null`. One whose native return type allows `null`, such as `: ?array`, always publishes it, even when its `Attribute<…>` docblock leaves the `null` out.
|
|
1523
1563
|
|
|
1524
1564
|
#### Typing `array` Casts With `@property`
|
|
@@ -1669,7 +1709,9 @@ A custom cast without [`#[TsType]`](https://tolki.abe.dev/ts/custom-types.html)
|
|
|
1669
1709
|
- **A bare `array` or `object`, on a cast without the interface**: `get()`'s type, where `get()` returns a value object or an array shape. `?object` and `array|object` work the same way. Over a scalar `get()`, a bare `array` publishes `unknown[] | Record<string, unknown>`.
|
|
1670
1710
|
- **Any other declared type**: that type, such as `string`.
|
|
1671
1711
|
|
|
1672
|
-
Laravel calls `get()` for a `NULL` column too, so a nullable column cast to a class whose `get()` declares a non-null return type publishes no `| null`. For a `coordinate_data` column that may be `NULL`, cast with a `get()` that always returns a `Coordinate`, the model publishes `coordinate_data: { lat: number; lng: number }`. Laravel sends a `null` from `get()` without calling `serialize()`, so a `get()` that declares a nullable return type, or returns `null` itself, adds `| null` to the `serialize()` type.
|
|
1712
|
+
Laravel calls `get()` for a `NULL` column too, so a nullable column cast to a class whose `get()` declares a non-null return type publishes no `| null`. For a `coordinate_data` column that may be `NULL`, cast with a `get()` that always returns a `Coordinate`, the model publishes `coordinate_data: { lat: number; lng: number }`. Laravel sends a `null` from `get()` without calling `serialize()`, so on a nullable column, a `get()` that declares a nullable return type, or returns `null` itself, adds `| null` to the `serialize()` type.
|
|
1713
|
+
|
|
1714
|
+
A `NOT NULL` column never holds a `NULL`, so it publishes the `serialize()` type alone. With a cast whose `get()` returns `?CarbonImmutable` and whose `serialize()` returns `string`, a `NOT NULL` `opens_at` column publishes `opens_at: string`, and a nullable `closes_at` column publishes `closes_at: string | null`. A `Castable` that names the cast publishes the same way, and a `null` that `serialize()` itself declares or returns stays on either column. A `get()` that turns a stored value into `null`, such as an empty string, still sends that `null` from a `NOT NULL` column, which the type leaves out. Type such a column with [`#[TsCasts]`](#tscasts).
|
|
1673
1715
|
|
|
1674
1716
|
When `get()`'s native type is missing or vague, such as a bare `array`, the `@return` docblock sets the type, so `@return list<LegDto>` publishes a list of `LegDto`'s public properties, the shape `json_encode()` writes. A `@return` that names a model, such as `list<User>`, or another class that doesn't publish as an inline shape keeps `unknown[]`. A `get()` that declares neither publishes `unknown`.
|
|
1675
1717
|
|
|
@@ -1846,7 +1888,7 @@ A column or accessor typed as a backed or unit enum publishes in two ways:
|
|
|
1846
1888
|
- **The main interface**: `User` uses the enum's `{Enum}Type` union, which is how Laravel serializes the enum when it converts a model to JSON.
|
|
1847
1889
|
- **A parallel `Resource` interface**: `{Model}Resource` types the same property as [`AsEnum<typeof Enum>`](https://tolki.abe.dev/ts/enums.html#type-reference), and the split template adds `{Model}MutatorsResource` for accessors and `{Model}AllResource`. `AsEnum` is the shape you get once the raw value is a full enum instance, either from `Status.from(user.status)` or from an API resource that serialized the enum with [`EnumResource`](https://tolki.abe.dev/ts/enum-api-resource.html).
|
|
1848
1890
|
|
|
1849
|
-
A property is rewritten only when its type is a single enum or a list of one, either optionally `| null`. A list becomes `AsEnum<typeof Enum>[]`. A shape, or a union with other types, keeps its own type.
|
|
1891
|
+
A property is rewritten only when its type is a single enum or a list of one, either optionally `| null`. A list becomes `AsEnum<typeof Enum>[]`. A shape, or a union with other types, keeps its own type. An accessor that returns an enum's `->value` or `->name` keeps the enum's alias in `{Model}Resource` and `{Model}MutatorsResource`, because it sends the scalar, not the enum. Only an accessor that returns the enum itself takes `AsEnum<typeof Enum>`.
|
|
1850
1892
|
|
|
1851
1893
|
This helper resolves the raw `role` value into the type `UserResource` declares:
|
|
1852
1894
|
|
|
@@ -2288,7 +2330,7 @@ The [Configuration Reference](https://tolki.abe.dev/ts/configuration-reference.h
|
|
|
2288
2330
|
|
|
2289
2331
|
The [Laravel TypeScript Publisher](https://github.com/abetwothree/laravel-ts-publish) generates a TypeScript interface for each of your Laravel [API resources](https://laravel.com/docs/eloquent-resources), the `JsonResource` classes that shape your API's JSON. It reads each resource's `toArray()` method without calling it, and publishes the name, type, and optionality of every property the method returns.
|
|
2290
2332
|
|
|
2291
|
-
Use it when your frontend reads JSON from API resources. Each publish regenerates the interface from `toArray()`, so you don't maintain a second, hand-written type.
|
|
2333
|
+
Use it when your frontend reads JSON from API resources. Each publish regenerates the interface from `toArray()`, so you don't maintain a second, hand-written type. A resource whose keys follow the value of another key it sends publishes a type alias instead, as [Discriminated Unions](#discriminated-unions) describes.
|
|
2292
2334
|
|
|
2293
2335
|
By default, the package looks for resources in the `app/Http/Resources` directory. To change that, see [Filtering & Excluding](#filtering--excluding).
|
|
2294
2336
|
|
|
@@ -2364,7 +2406,7 @@ The output shows how each kind of value is typed:
|
|
|
2364
2406
|
|
|
2365
2407
|
#### Classes Sharing a Name Across Namespaces
|
|
2366
2408
|
|
|
2367
|
-
When two classes in different namespaces share a name, such as `App\Models\User` and `Crm\Models\User`, the generated file imports each one under its own alias. Every occurrence of the name inside a property's type uses the alias of the class it refers to, in source order:
|
|
2409
|
+
When two classes in different namespaces share a name, such as `App\Models\User` and `Crm\Models\User`, the generated file imports each one under its own alias. Every occurrence of the name inside a property's type uses the alias of the class it refers to, in source order. That holds for a model and an API resource that publish one name too, such as an `Address` model beside an `AddressResource` named `Address` with [`#[TsResource]`](#configuring-resource-generation-with-tsresource), and for two enums that share a name, as [`EnumResource`](#enum-properties-with-enumresource) shows:
|
|
2368
2410
|
|
|
2369
2411
|
```typescript
|
|
2370
2412
|
import type { User as CrmUser } from "../../../crm/models";
|
|
@@ -2835,7 +2877,25 @@ roles: (AsEnum<typeof Role> | never[])[];
|
|
|
2835
2877
|
role_list: (AsEnum<typeof Role> | null)[];
|
|
2836
2878
|
```
|
|
2837
2879
|
|
|
2838
|
-
A ternary
|
|
2880
|
+
A ternary, `match` or `when()` publishes each arm as Laravel sends it. A wrapped arm publishes `AsEnum<typeof X>` beside whatever the other arms send, with the import each side needs:
|
|
2881
|
+
|
|
2882
|
+
```php
|
|
2883
|
+
'subject' => $request->boolean('role')
|
|
2884
|
+
? EnumResource::make($this->role)
|
|
2885
|
+
: $this->status,
|
|
2886
|
+
'either_status' => $request->boolean('crm')
|
|
2887
|
+
? EnumResource::make($this->crm_status)
|
|
2888
|
+
: EnumResource::make($this->status),
|
|
2889
|
+
```
|
|
2890
|
+
|
|
2891
|
+
`subject` sends the `Role` object or the bare `Status` value. Two enums that share a class name, here `App\Enums\Status` and `App\Crm\Enums\Status`, each keep their own name:
|
|
2892
|
+
|
|
2893
|
+
```typescript
|
|
2894
|
+
subject: AsEnum<typeof Role> | StatusType;
|
|
2895
|
+
either_status: AsEnum<typeof CrmStatus> | AsEnum<typeof EnumsStatus>;
|
|
2896
|
+
```
|
|
2897
|
+
|
|
2898
|
+
The same holds inside an inline array, where a ternary that wraps only one of its arms keeps both shapes:
|
|
2839
2899
|
|
|
2840
2900
|
```php
|
|
2841
2901
|
'audit' => [
|
|
@@ -3043,8 +3103,163 @@ App\Http\Resources\PostResource: The value on line 31 leaves out `$this->opaqueT
|
|
|
3043
3103
|
|
|
3044
3104
|
Give the method a return type or a `@return` docblock, and its value joins the union again. An inline [`@var`](#typing-a-variable-with-var) that types the variable also removes the warning. `--quiet` hides every warning.
|
|
3045
3105
|
|
|
3106
|
+
Once the value is typed, an empty `[]` beside a list publishes the list alone. With `opaqueTags()` declared `@return list<string>`, `tags` publishes `string[]`.
|
|
3107
|
+
|
|
3108
|
+
A `@return` docblock that types the key, on `toArray()` or on a method it spreads, also types the value left out. The docblock's type takes that value's place beside the values the body types. Under `score: int|string|null`, a `score` whose body types `number | null` and leaves one more value out publishes `number | null | string`. `ts:publish` prints no warning for a value the docblock types. A value it doesn't type, such as one under a `mixed` entry or under a key the docblock doesn't name, still warns. [Return Branches and `@return` Shapes](#return-branches-and-return-shapes) shows an example.
|
|
3109
|
+
|
|
3046
3110
|
`ts:publish` doesn't analyze a class again while the [generation cache](https://tolki.abe.dev/ts/generating-cache.html) holds it. A class the cache serves prints none of these warnings, nor the first-class callable warning above, so run `php artisan ts:publish --fresh` to see every one.
|
|
3047
3111
|
|
|
3112
|
+
### Discriminated Unions
|
|
3113
|
+
|
|
3114
|
+
When a key's value depends on another key the resource also sends, the package publishes one variant for each value of that key, and values that send the same types share one. Checking the key on the frontend then narrows the keys that follow it. Here `status` follows `is_draft`:
|
|
3115
|
+
|
|
3116
|
+
```php
|
|
3117
|
+
final class PostResource extends JsonResource
|
|
3118
|
+
{
|
|
3119
|
+
public function toArray(Request $request): array
|
|
3120
|
+
{
|
|
3121
|
+
return [
|
|
3122
|
+
'id' => $this->id,
|
|
3123
|
+
'is_draft' => $this->is_draft,
|
|
3124
|
+
'status' => $this->is_draft
|
|
3125
|
+
? new DraftStatusResource($this->draft_status)
|
|
3126
|
+
: new PublishedStatusResource($this->status),
|
|
3127
|
+
];
|
|
3128
|
+
}
|
|
3129
|
+
}
|
|
3130
|
+
```
|
|
3131
|
+
|
|
3132
|
+
The resource publishes a type alias instead of an interface. The keys every variant shares come first, and each variant pairs a value of `is_draft` with the `status` it sends:
|
|
3133
|
+
|
|
3134
|
+
```typescript
|
|
3135
|
+
import type { DraftStatusResource, PublishedStatusResource } from ".";
|
|
3136
|
+
|
|
3137
|
+
export type PostResource = {
|
|
3138
|
+
id: number;
|
|
3139
|
+
} & (
|
|
3140
|
+
| { is_draft: true; status: DraftStatusResource }
|
|
3141
|
+
| { is_draft: false; status: PublishedStatusResource }
|
|
3142
|
+
);
|
|
3143
|
+
```
|
|
3144
|
+
|
|
3145
|
+
So a check on `is_draft` narrows `status`:
|
|
3146
|
+
|
|
3147
|
+
```typescript
|
|
3148
|
+
if (!post.is_draft) {
|
|
3149
|
+
post.status; // PublishedStatusResource
|
|
3150
|
+
}
|
|
3151
|
+
```
|
|
3152
|
+
|
|
3153
|
+
#### The Key Other Keys Follow
|
|
3154
|
+
|
|
3155
|
+
The key that decides, the discriminant, is a key the array always sends, written once, whose value is a plain read with a finite set of values:
|
|
3156
|
+
|
|
3157
|
+
- A boolean column or property, nullable or not, such as `$this->is_draft`.
|
|
3158
|
+
- An enum column read directly, such as `$this->priority`, or its `->value` or `->name`.
|
|
3159
|
+
- A value whose type is a union of literals, such as `'draft' | 'live'`.
|
|
3160
|
+
|
|
3161
|
+
A string or number column has no finite set of values, so it never decides. Neither does an enum you wrap in `EnumResource::make()`, a cast such as `(bool) $this->is_draft`, a method call such as `$this->isDraft()`, or a key a conditional method can leave out.
|
|
3162
|
+
|
|
3163
|
+
#### The Forms That Follow It
|
|
3164
|
+
|
|
3165
|
+
A key follows the discriminant when its value is a ternary, a `match`, or `$this->when()` or `$this->unless()` whose condition tests the discriminant. The short ternary `?:` doesn't count. A condition can compare the value with `===`, `!==`, `==`, or `!=` against literals, constants, and enum cases, negate it, join tests of it with `&&`, `||`, or `xor`, and call `is_null()`, `isset()`, `empty()`, or `in_array()` with a constant list. A ternary or `match` nested in an arm is read too.
|
|
3166
|
+
|
|
3167
|
+
Here `Priority` is an int-backed enum whose cases run from `Low = 0` to `Critical = 3`, and `priority` is a nullable column cast to it:
|
|
3168
|
+
|
|
3169
|
+
```php
|
|
3170
|
+
return [
|
|
3171
|
+
'id' => $this->id,
|
|
3172
|
+
'priority' => $this->priority,
|
|
3173
|
+
'badge' => match ($this->priority) {
|
|
3174
|
+
Priority::Low, Priority::Medium => null,
|
|
3175
|
+
Priority::High => $this->title,
|
|
3176
|
+
Priority::Critical => new UserResource($this->user),
|
|
3177
|
+
null => [],
|
|
3178
|
+
},
|
|
3179
|
+
'escalated_at' => $this->when($this->priority === Priority::Critical, $this->updated_at),
|
|
3180
|
+
];
|
|
3181
|
+
```
|
|
3182
|
+
|
|
3183
|
+
Values for which every key sends the same type share one variant, and each enum case is spelled by the value it sends:
|
|
3184
|
+
|
|
3185
|
+
```typescript
|
|
3186
|
+
import type { UserResource } from "..";
|
|
3187
|
+
|
|
3188
|
+
export type PostPriorityResource = {
|
|
3189
|
+
id: number;
|
|
3190
|
+
} & (
|
|
3191
|
+
| { priority: 0 | 1; badge: null; escalated_at?: never }
|
|
3192
|
+
| { priority: 2; badge: string; escalated_at?: never }
|
|
3193
|
+
| { priority: 3; badge: UserResource; escalated_at: string | null }
|
|
3194
|
+
| { priority: null; badge: never[]; escalated_at?: never }
|
|
3195
|
+
);
|
|
3196
|
+
```
|
|
3197
|
+
|
|
3198
|
+
A key a variant leaves out publishes as `escalated_at?: never`, so reading `post.escalated_at` before you narrow still compiles, as `string | null | undefined`. A value whose arm throws, or that a `match` has no arm for, is left out of the variants, because PHP throws there and the resource sends nothing.
|
|
3199
|
+
|
|
3200
|
+
#### Nested Arrays
|
|
3201
|
+
|
|
3202
|
+
A nested array splits the same way, into a union of objects:
|
|
3203
|
+
|
|
3204
|
+
```php
|
|
3205
|
+
'pin' => [
|
|
3206
|
+
'pinned' => $this->is_pinned,
|
|
3207
|
+
'until' => $this->when($this->is_pinned, $this->updated_at),
|
|
3208
|
+
],
|
|
3209
|
+
```
|
|
3210
|
+
|
|
3211
|
+
The key publishes `pin: { pinned: true; until: string | null } | { pinned: false; until?: never }`. A nested array with two discriminants publishes each combination of their variants, up to 16 objects. Past 16, the later discriminant's keys stay flat.
|
|
3212
|
+
|
|
3213
|
+
Nested arrays split everywhere the package reads one, such as Inertia page props and shared data, broadcast events, and [`analyze()`](https://tolki.abe.dev/ts/analyzer-api.html). Only an API resource's top level becomes a type alias. The top level of a page's props or of shared data stays one object type, because Vue's `defineProps<T>()` needs one. See [Inertia](https://tolki.abe.dev/ts/inertia.html).
|
|
3214
|
+
|
|
3215
|
+
#### What Keeps a Key Flat
|
|
3216
|
+
|
|
3217
|
+
A flat key publishes one type for every value, as it would without discriminated unions. These cases keep one key flat, while the other keys that follow the discriminant still split:
|
|
3218
|
+
|
|
3219
|
+
- Its arms send the same type for every value.
|
|
3220
|
+
- Its condition also tests something else, such as `$this->is_pinned && $this->title !== ''`.
|
|
3221
|
+
- The key and its condition spell the read differently, such as `$this->resource->is_pinned` in one and `$this->is_pinned` in the other.
|
|
3222
|
+
- A `merge()`, `mergeWhen()`, or spread writes the key.
|
|
3223
|
+
|
|
3224
|
+
These cases keep every key that follows the discriminant flat:
|
|
3225
|
+
|
|
3226
|
+
- The package can't type an arm of one of those keys, or leaves a value out of one, as [Values Left Out of a Union](#values-left-out-of-a-union) describes.
|
|
3227
|
+
- A `merge()`, `mergeWhen()`, or spread writes the discriminant, or the array merges a value the package can't read.
|
|
3228
|
+
- Code from the first key that reads the discriminant up to the last such key's condition may change the discriminant: a write, a by-reference argument, a mutator or property hook that writes it, a `get` hook on any property the discriminant reads, or a call that may change the model. Calls the package knows only read keep the split: Laravel's resource helpers, unless your resource overrides one they call, such as `when()`, with code that may change the model; Eloquent's own key, attribute, and relation reads such as `getKey()` and `relationLoaded()`, unless your model overrides a method they call with one that returns anything other than a literal, a constant, or an instance property your model declares without a `get` hook; `route()` and `url()`; the `Gate` facade's checks (`allows()`, `denies()`, `check()`, `any()`, and `none()`), which trust your gates and policies not to change the model; a nested resource; and your resource's own methods whose code only reads. Any other method of your model counts as a call that may change it, including a reader your model overrides itself, such as its own `getRouteKeyName()` called directly. Code above the first key that reads the discriminant, or below the last one, also keeps the split. The discriminant's own key is one of those keys.
|
|
3229
|
+
- The discriminant reads another object's property, such as `$this->settings->flag`, and `settings` is typed by an interface, or by a class that isn't `final` and whose `flag` is neither `readonly` nor `final`. That object's own class may give `flag` a `get` hook, so two reads may differ. To keep the split, type `settings` by a `final` class, or declare `flag` `readonly` or `final`. A model's attributes keep it.
|
|
3230
|
+
- `toArray()` builds its array across `return` branches, or in a variable it returns.
|
|
3231
|
+
- A subclass spreads its parent's array with `...parent::toArray($request)`, which publishes the parent's keys flat in the subclass.
|
|
3232
|
+
- The array holds an [interpolated key](#interpolated-keys).
|
|
3233
|
+
- A `#[TsCasts]` entry types the discriminant or a key that follows it, or a `@return` docblock on `toArray()` changes either one's type.
|
|
3234
|
+
|
|
3235
|
+
To link keys the package can't read, write the union yourself and intersect the resource with it, as [`#[TsIntersect]`](https://tolki.abe.dev/ts/extending-interfaces.html#intersecting-a-resource-with-tsintersect) describes.
|
|
3236
|
+
|
|
3237
|
+
#### Turning It Off
|
|
3238
|
+
|
|
3239
|
+
To publish every resource's keys flat, turn the setting off:
|
|
3240
|
+
|
|
3241
|
+
```php
|
|
3242
|
+
// config/ts-publish.php
|
|
3243
|
+
|
|
3244
|
+
'resources' => [
|
|
3245
|
+
'discriminated_unions' => false,
|
|
3246
|
+
],
|
|
3247
|
+
```
|
|
3248
|
+
|
|
3249
|
+
To turn it off for one resource, add `#[TsResource(discriminated: false)]`. `#[TsResource(discriminated: true)]` turns it on for one resource while the setting is off. Both change only the resource's top level, so a nested array still splits.
|
|
3250
|
+
|
|
3251
|
+
PHP doesn't pass attributes down to a subclass. A subclass that inherits its parent's `toArray()` follows the config setting, so give it its own `#[TsResource(discriminated: false)]` too.
|
|
3252
|
+
|
|
3253
|
+
#### Using a Split Resource in Your Own Types
|
|
3254
|
+
|
|
3255
|
+
An interface can't extend a union, so `interface Post extends PostResource {}` fails with TS2312, and so does a published interface whose `#[TsExtends]` names `PostResource`. Write `type Post = PostResource & { … }` instead, or [turn discriminated unions off](#turning-it-off) for the resource.
|
|
3256
|
+
|
|
3257
|
+
An object you build as a `PostResource` must match one variant. `{ ...post, is_draft: false }` compiles only where `post` is already narrowed to a published post, because a draft's `status` doesn't fit the published variant.
|
|
3258
|
+
|
|
3259
|
+
#### Templates You Published
|
|
3260
|
+
|
|
3261
|
+
A copy of the `resource` or `globals` template that you published from an earlier release prints only the shared keys, and leaves out the variants and any `#[TsIntersect]` types. Publish the templates again, as [Publishing and Editing Templates](https://tolki.abe.dev/ts/customizing-the-pipeline.html#publishing-and-editing-templates) describes.
|
|
3262
|
+
|
|
3048
3263
|
### Method Calls, Variables, and Collections
|
|
3049
3264
|
|
|
3050
3265
|
Values you compute in `toArray()` get types too: method calls, property reads on other objects, local variables, and collection chains.
|
|
@@ -4178,7 +4393,7 @@ A variable that starts from `parent::toArray($request)` works the same way. See
|
|
|
4178
4393
|
|
|
4179
4394
|
#### Trait Method Spread
|
|
4180
4395
|
|
|
4181
|
-
Spread a trait method's return into `toArray()` with `...$this->method()`. Its body publishes the same types it would in `toArray()`, and its `@return array{...}` docblock types
|
|
4396
|
+
Spread a trait method's return into `toArray()` with `...$this->method()`. Its body publishes the same types it would in `toArray()`, and its `@return array{...}` docblock types what the body can't:
|
|
4182
4397
|
|
|
4183
4398
|
```php
|
|
4184
4399
|
trait IncludesMorphValue
|
|
@@ -4257,6 +4472,27 @@ trait IncludesExtras
|
|
|
4257
4472
|
|
|
4258
4473
|
A key the body can't type, and that neither the `@return` docblock nor `#[TsCasts]` covers, publishes `unknown`.
|
|
4259
4474
|
|
|
4475
|
+
Keys follow PHP's order, so a later write replaces an earlier one with the same name, whether a key or a spread writes it. Here the resource wraps a value object whose `title` is a `string`, and the second spread replaces the `author` that `credited()` returns:
|
|
4476
|
+
|
|
4477
|
+
```php
|
|
4478
|
+
public function toArray(Request $request): array
|
|
4479
|
+
{
|
|
4480
|
+
return [
|
|
4481
|
+
'byline' => [
|
|
4482
|
+
...$this->credited(),
|
|
4483
|
+
...['author' => $this->resource->title],
|
|
4484
|
+
],
|
|
4485
|
+
];
|
|
4486
|
+
}
|
|
4487
|
+
|
|
4488
|
+
private function credited(): array
|
|
4489
|
+
{
|
|
4490
|
+
return ['id' => 1, 'author' => $this->resource->author];
|
|
4491
|
+
}
|
|
4492
|
+
```
|
|
4493
|
+
|
|
4494
|
+
The property publishes `byline: { id: number; author: string }`. When a spread always writes a key but the package can't type its value, the key publishes `unknown`, not the type it replaced. A spread of a local that sets the key only inside an `if` may leave the earlier value in place, so the key publishes both types. A merge is the exception, because Laravel never lets a merged key replace a key written before the merge, or a key written after the merge replace the merged one. See [Merge Operations](#merge-operations).
|
|
4495
|
+
|
|
4260
4496
|
Trait spreads carry through inheritance. When a parent resource spreads a trait method and a child spreads `...parent::toArray($request)`, the child gets the keys the trait contributed.
|
|
4261
4497
|
|
|
4262
4498
|
#### Bare Method-Call Return
|
|
@@ -4542,12 +4778,67 @@ export interface PostPermissionsResource {
|
|
|
4542
4778
|
|
|
4543
4779
|
Both forms of `@return` count:
|
|
4544
4780
|
|
|
4545
|
-
- **An `array{...}` shape**: each key gets its own type, and a key written `key?:` also becomes optional. A string or number literal type, such as `'draft'|'live'` or `1|2|3`, publishes as written.
|
|
4546
|
-
- **`array<string, V>`**: `V`
|
|
4781
|
+
- **An `array{...}` shape**: each key gets its own type, and a key written `key?:` also becomes optional. A string or number literal type, such as `'draft'|'live'` or `1|2|3`, publishes as written. It also narrows a body type that admits every literal it lists, so `label: 'early'|'late'` over a `string` column publishes `label: 'early' | 'late'`.
|
|
4782
|
+
- **`array<string, V>`**: `V` is the entry for every key, and types each one as a shape's entry would.
|
|
4547
4783
|
|
|
4548
4784
|
`toArray()`'s own `@return array{...}` fills keys the same way.
|
|
4549
4785
|
|
|
4550
|
-
|
|
4786
|
+
Apart from the literal narrowing above, the body wins wherever it's specific, so a stale `@return` can't overwrite a type the package already knows. The docblock types what the body can't, at any depth:
|
|
4787
|
+
|
|
4788
|
+
- a key the body left vague, such as `unknown`, `unknown[]`, or `Record<string, unknown>`
|
|
4789
|
+
- a member or a list element the body couldn't type, inside a key it did type
|
|
4790
|
+
- a value the body [left out of a union](#values-left-out-of-a-union), beside the values it typed
|
|
4791
|
+
- an [interpolated key's](#interpolated-keys) value that the body left `unknown | undefined`
|
|
4792
|
+
|
|
4793
|
+
It keeps any `| null` the body found, and it doesn't add what the body proves Laravel never sends. An entry that only adds `| null` to the body's type, as `label` does below, publishes the body's type. A shape inside a key keeps the keys the body writes: a docblock key the body never writes is left out, unless the docblock marks it `key?:` or the array may hold keys the package can't name, such as a spread of an array with no element type.
|
|
4794
|
+
|
|
4795
|
+
This resource wraps a `ContactSheet` value object, as [Resources That Wrap Other Classes](#resources-that-wrap-other-classes) describes. Its `contacts` property lists `MailRecipient` objects, whose `name` is a `?string`. Its `extras` property is an `array` with no element type, `hint` has no type, and `title` is a `?string`:
|
|
4796
|
+
|
|
4797
|
+
```php
|
|
4798
|
+
/**
|
|
4799
|
+
* @property-read ContactSheet $resource
|
|
4800
|
+
*/
|
|
4801
|
+
class ContactSheetResource extends JsonResource
|
|
4802
|
+
{
|
|
4803
|
+
/**
|
|
4804
|
+
* @return array{
|
|
4805
|
+
* rows: list<array{name: string|null, locale: string}>,
|
|
4806
|
+
* summary: array{label: string|null, count: int|null}
|
|
4807
|
+
* }
|
|
4808
|
+
*/
|
|
4809
|
+
public function toArray(Request $request): array
|
|
4810
|
+
{
|
|
4811
|
+
$sheet = $this->resource;
|
|
4812
|
+
|
|
4813
|
+
return [
|
|
4814
|
+
'rows' => array_map(
|
|
4815
|
+
fn (MailRecipient $r) => [
|
|
4816
|
+
...$sheet->extras,
|
|
4817
|
+
'name' => $r->name,
|
|
4818
|
+
],
|
|
4819
|
+
$sheet->contacts,
|
|
4820
|
+
),
|
|
4821
|
+
'summary' => [
|
|
4822
|
+
'label' => (string) $sheet->title,
|
|
4823
|
+
'count' => $sheet->title !== null
|
|
4824
|
+
? $sheet->hint
|
|
4825
|
+
: null,
|
|
4826
|
+
],
|
|
4827
|
+
];
|
|
4828
|
+
}
|
|
4829
|
+
}
|
|
4830
|
+
```
|
|
4831
|
+
|
|
4832
|
+
Each row takes `locale` from the docblock, because the spread may hold it. `label` keeps the body's `string`, since `(string)` never sends `null`, and `count` takes the docblock's `number` in place of `$sheet->hint`:
|
|
4833
|
+
|
|
4834
|
+
```typescript
|
|
4835
|
+
export interface ContactSheetResource {
|
|
4836
|
+
rows: { name: string | null; locale: string }[];
|
|
4837
|
+
summary: { label: string; count: number | null };
|
|
4838
|
+
}
|
|
4839
|
+
```
|
|
4840
|
+
|
|
4841
|
+
Where a key's value has a different shape on each path, each shape stays its own member of the union, and the docblock adds keys only to a shape that may hold them. Under the same entry as `rows`, a row that one path builds as `['name' => $r->name]`, and another builds with `...$sheet->extras`, publishes `({ name: string | null } | { name: string | null; locale: string })[]`.
|
|
4551
4842
|
|
|
4552
4843
|
A shape value that names a model, an enum, or an API resource keeps it at any depth, and the file imports it. Here `tags` is a nullable column cast to `'array'`, which publishes `unknown[] | null` on its own, and `json_decode()` returns a value the package can't type:
|
|
4553
4844
|
|
|
@@ -4579,7 +4870,7 @@ export interface PostExtrasResource {
|
|
|
4579
4870
|
}
|
|
4580
4871
|
```
|
|
4581
4872
|
|
|
4582
|
-
A spread method's
|
|
4873
|
+
A key that a spread method's `@return` fills because the body left it vague keeps its classes only when you spread the method at the top level of `toArray()`. Spread inside a nested array, as in `'meta' => [...$this->extras()]`, each model, enum, or API resource such a fill names publishes `unknown`. Type such a key with `#[TsCasts]` and an `import`. A key the body typed keeps its classes wherever you spread the method.
|
|
4583
4874
|
|
|
4584
4875
|
A name that isn't a PHP class, such as a type you declare only in TypeScript, publishes as written in a spread method's `@return`. In `toArray()`'s own `@return`, the key stays `unknown`, so type it with `#[TsCasts]`.
|
|
4585
4876
|
|
|
@@ -5241,14 +5532,15 @@ related: { data: PostResource }[];
|
|
|
5241
5532
|
|
|
5242
5533
|
### Resource Attributes
|
|
5243
5534
|
|
|
5244
|
-
|
|
5535
|
+
Five attributes configure how a resource is published:
|
|
5245
5536
|
|
|
5246
|
-
| Attribute
|
|
5247
|
-
|
|
|
5248
|
-
| `#[TsResource]`
|
|
5249
|
-
| `#[TsCasts]`
|
|
5250
|
-
| `#[TsExtends]`
|
|
5251
|
-
| `#[
|
|
5537
|
+
| Attribute | Target | Use it to |
|
|
5538
|
+
| ---------------- | --------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
5539
|
+
| `#[TsResource]` | Resource class | Set the interface name, the backing model, or a description, or turn [discriminated unions](#discriminated-unions) on or off |
|
|
5540
|
+
| `#[TsCasts]` | Resource class, `toArray()`, or a method it spreads | Override property types, or add properties |
|
|
5541
|
+
| `#[TsExtends]` | Resource class | Extend the interface with your own TypeScript types, as [Extending Interfaces](https://tolki.abe.dev/ts/extending-interfaces.html) describes |
|
|
5542
|
+
| `#[TsIntersect]` | Resource class | Intersect the resource's type with your own TypeScript type, as [Intersecting a Resource](https://tolki.abe.dev/ts/extending-interfaces.html#intersecting-a-resource-with-tsintersect) describes |
|
|
5543
|
+
| `#[TsExclude]` | Resource class | Leave the resource out of the output, as [Excluding Content](https://tolki.abe.dev/ts/excluding-content.html) describes |
|
|
5252
5544
|
|
|
5253
5545
|
#### Configuring Resource Generation With `#[TsResource]`
|
|
5254
5546
|
|
|
@@ -5265,13 +5557,14 @@ class UserResource extends JsonResource
|
|
|
5265
5557
|
}
|
|
5266
5558
|
```
|
|
5267
5559
|
|
|
5268
|
-
The attribute takes
|
|
5560
|
+
The attribute takes four optional parameters:
|
|
5269
5561
|
|
|
5270
|
-
| Parameter
|
|
5271
|
-
|
|
|
5272
|
-
| `name`
|
|
5273
|
-
| `model`
|
|
5274
|
-
| `description`
|
|
5562
|
+
| Parameter | Type | Default | Description |
|
|
5563
|
+
| --------------- | --------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
5564
|
+
| `name` | `?string` | Class name | The TypeScript interface name |
|
|
5565
|
+
| `model` | `?class-string` | Resolved automatically | The backing Eloquent model |
|
|
5566
|
+
| `description` | `string` | `''` | A JSDoc comment above the interface |
|
|
5567
|
+
| `discriminated` | `?bool` | `null` | `true` publishes this resource's [discriminated union](#discriminated-unions) and `false` publishes its keys flat, whatever `resources.discriminated_unions` says. `null` follows the config |
|
|
5275
5568
|
|
|
5276
5569
|
`name` also sets the output file's name. For example, `#[TsResource(name: 'Address')]` generates `address.ts` instead of `address-resource.ts`.
|
|
5277
5570
|
|
|
@@ -5800,7 +6093,7 @@ export interface PostScheduled {
|
|
|
5800
6093
|
}
|
|
5801
6094
|
```
|
|
5802
6095
|
|
|
5803
|
-
The body still wins wherever it types a value. The docblock only
|
|
6096
|
+
The body still wins wherever it types a value, so a stale `@return` can't overwrite a type the body already found. The docblock types only what the body can't, at any depth, such as a key the body left `unknown`, a member inside a key it typed, or a value it left out of a union. It follows the same rules as an [API resource's `@return`](https://tolki.abe.dev/ts/api-resources.html#return-branches-and-return-shapes). A `key?:` entry in the docblock makes that key optional.
|
|
5804
6097
|
|
|
5805
6098
|
A spread helper that builds its keys by interpolation, such as `"{$name}_tag"`, adds an index signature to the interface, for example ``[key: `${string}_tag`]: string | undefined``. When the helper's body can't type the values, its `@return array<string, V>` docblock types them. [Interpolated Keys](https://tolki.abe.dev/ts/api-resources.html#interpolated-keys) on the API Resources page describes how the event's `#[TsCasts]` and `extends` clause then apply.
|
|
5806
6099
|
|
|
@@ -5852,7 +6145,30 @@ export interface ManifestAssembled {
|
|
|
5852
6145
|
|
|
5853
6146
|
A query chain that starts at a model is typed step by step, as in [page props](https://tolki.abe.dev/ts/routing.html#what-the-props-expression-can-be). `Post::query()->pluck('id')->first()` publishes `number | null`. A model the chain returns is presented as `Partial<Model>`, as a [model property](#model--enum-aware-properties) is, so `User::find($this->userId)` publishes `Partial<User> | null` and `User::query()->where('id', 1)->get()` publishes `Partial<User>[]`.
|
|
5854
6147
|
|
|
5855
|
-
An `EnumResource` around an enum that may be `null` adds `| never[]`, and so does each element of a `map()` of such wraps, because an event sends the empty resource as `[]
|
|
6148
|
+
An `EnumResource` in `broadcastWith()` publishes `AsEnum<typeof Status>`, as in an [API resource](https://tolki.abe.dev/ts/api-resources.html#enum-properties-with-enumresource), and the event file imports `AsEnum` and the enum's const. One around an enum that may be `null` adds `| never[]`, and so does each element of a `map()` of such wraps, because an event sends the empty resource as `[]`:
|
|
6149
|
+
|
|
6150
|
+
```php
|
|
6151
|
+
public function broadcastWith(): array
|
|
6152
|
+
{
|
|
6153
|
+
return [
|
|
6154
|
+
'status' => EnumResource::make($this->post->status),
|
|
6155
|
+
'visibility' => EnumResource::make($this->post->visibility),
|
|
6156
|
+
];
|
|
6157
|
+
}
|
|
6158
|
+
```
|
|
6159
|
+
|
|
6160
|
+
With `visibility` nullable, the event publishes:
|
|
6161
|
+
|
|
6162
|
+
```typescript
|
|
6163
|
+
import type { AsEnum } from "@tolki/ts";
|
|
6164
|
+
import { Status, Visibility } from "../enums";
|
|
6165
|
+
|
|
6166
|
+
/** @see App\Events\PostPublished */
|
|
6167
|
+
export interface PostPublished {
|
|
6168
|
+
status: AsEnum<typeof Status>;
|
|
6169
|
+
visibility: AsEnum<typeof Visibility> | never[];
|
|
6170
|
+
}
|
|
6171
|
+
```
|
|
5856
6172
|
|
|
5857
6173
|
#### `when()` and `unless()` From `Conditionable`
|
|
5858
6174
|
|
|
@@ -6319,7 +6635,7 @@ class UserResource extends JsonResource
|
|
|
6319
6635
|
|
|
6320
6636
|
Inside another resource, `EnumResource::make($this->status)` and `new EnumResource($this->status)` both publish the property as `AsEnum<typeof Status>`. See [Enum Properties With `EnumResource`](https://tolki.abe.dev/ts/api-resources.html#enum-properties-with-enumresource) on the API Resources page. A bare value sends no object: `'status' => Status::Published->value` publishes that case's own value, `1`. [Reading `->value` and `->name`](https://tolki.abe.dev/ts/enums.html#reading-value-and-name) covers bare values and `cases()`.
|
|
6321
6637
|
|
|
6322
|
-
|
|
6638
|
+
A wrap in [Inertia shared data](https://tolki.abe.dev/ts/inertia.html) publishes the same way. With `enums.use_tolki_package` on (the default), an `EnumResource::make()` returned from your middleware's `share()` publishes as `AsEnum<typeof Role>` in `inertia-config.d.ts`, with `import { type AsEnum } from '@tolki/ts'` and an import of the `Role` const above the declarations. Route page props and [broadcast events](https://tolki.abe.dev/ts/broadcast-events.html) do too. See the `EnumResource` notes in [How the Augmentation File Is Generated](https://tolki.abe.dev/ts/inertia.html#how-the-augmentation-file-is-generated).
|
|
6323
6639
|
|
|
6324
6640
|
`EnumResource` turns off Laravel's resource wrapping (`public static $wrap = ''`), so the response is the flat object shown below, not wrapped in a `data` key. When the enum is `null`, the resource returns `null` instead of an object. As an Inertia page prop or shared value, Inertia sends `[]` instead, so the prop publishes `AsEnum<typeof Status> | never[]`. A broadcast event's payload, and a `map()` of wraps kept as a collection inside another resource, send `[]` too, and publish `| never[]`. See [Enum Properties With `EnumResource`](https://tolki.abe.dev/ts/api-resources.html#enum-properties-with-enumresource).
|
|
6325
6641
|
|
|
@@ -6760,6 +7076,8 @@ There are two ways to add an `extends` clause, and they combine when you use bot
|
|
|
6760
7076
|
- **The `#[TsExtends]` attribute**: applies to one class, and to any class that extends it or uses the trait it's on.
|
|
6761
7077
|
- **The `ts_extends.*` config arrays**: apply to every generated interface of one feature, such as every model.
|
|
6762
7078
|
|
|
7079
|
+
An API resource can also be intersected with a type you write, such as a union an interface can't extend. See [Intersecting a Resource With `#[TsIntersect]`](#intersecting-a-resource-with-tsintersect).
|
|
7080
|
+
|
|
6763
7081
|
### `#[TsExtends]` Attribute
|
|
6764
7082
|
|
|
6765
7083
|
The attribute takes the clause, an optional import path, and an optional list of names to import:
|
|
@@ -6782,11 +7100,11 @@ class TsExtends
|
|
|
6782
7100
|
|
|
6783
7101
|
Each parameter controls one part of the clause:
|
|
6784
7102
|
|
|
6785
|
-
| Parameter | Type | Default | Description
|
|
6786
|
-
| --------- | --------------- | -------- |
|
|
6787
|
-
| `extends` | `string` | required | The TypeScript for the `extends` clause: an interface name, or a generic such as `Pick<X, "a" \| "b">`.
|
|
6788
|
-
| `import` | `?string` | `null` | The path to import the clause's types from. Leave it out for a global type that needs no import.
|
|
6789
|
-
| `types` | `?list<string>` | `null` | The names to import from `import`. When it's `null`, the package reads the names from `extends
|
|
7103
|
+
| Parameter | Type | Default | Description |
|
|
7104
|
+
| --------- | --------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
7105
|
+
| `extends` | `string` | required | The TypeScript for the `extends` clause: an interface name, or a generic such as `Pick<X, "a" \| "b">`. |
|
|
7106
|
+
| `import` | `?string` | `null` | The path to import the clause's types from. Leave it out for a global type that needs no import. |
|
|
7107
|
+
| `types` | `?list<string>` | `null` | The names to import from `import`. When it's `null`, the package reads the names from `extends`. On a model, form request, or broadcast event, that works only when `extends` has no generic in it. On a resource, see [Names a Resource's Clause Imports](#names-a-resources-clause-imports). |
|
|
6790
7108
|
|
|
6791
7109
|
`#[TsExtends]` is repeatable, so you can stack as many as you need. You can put it on any of these:
|
|
6792
7110
|
|
|
@@ -6825,7 +7143,7 @@ export interface Warehouse
|
|
|
6825
7143
|
|
|
6826
7144
|
On a model, the clause goes on the main interface, which holds the columns. The model's `WarehouseAll` interface extends that one, so it gets the clause too.
|
|
6827
7145
|
|
|
6828
|
-
`HasTimestamps` needs no `types` array. When `types` is `null`, the package reads the names to import from the `extends` string itself.
|
|
7146
|
+
`HasTimestamps` needs no `types` array. When `types` is `null`, the package reads the names to import from the `extends` string itself. On a model, form request, or broadcast event, it can't pick the names out of a generic clause, such as `Pick<>`, `Omit<>`, or `Partial<>`, so without `types` the import comes out missing. Always list them in `types` there. A resource reads them, as [Names a Resource's Clause Imports](#names-a-resources-clause-imports) describes.
|
|
6829
7147
|
|
|
6830
7148
|
An entry with no `import` is treated as a global type that's already available, such as one declared in your own global `.d.ts` file.
|
|
6831
7149
|
|
|
@@ -6997,6 +7315,69 @@ The package applies these rules in order:
|
|
|
6997
7315
|
2. The same type name from the same path, across different `extends` clauses, gets one import statement.
|
|
6998
7316
|
3. The same type name from two different paths is aliased everywhere it appears, each with the prefix from its own import path. Every clause that uses it is rewritten to the alias, even inside a generic such as `Pick<>`.
|
|
6999
7317
|
|
|
7318
|
+
### Names a Resource's Clause Imports
|
|
7319
|
+
|
|
7320
|
+
On an API resource, a `#[TsExtends]`, a `#[TsIntersect]`, or a `ts_extends.resources` entry with an `import` and no `types` imports every name its type uses, at any depth. So `#[TsExtends('Pick<Base, "a" | "b">', '@/types/base')]` imports `Base`, and `Record<string, Meta>` imports `Meta`. Three rules decide which of those names the clause imports:
|
|
7321
|
+
|
|
7322
|
+
- **TypeScript's own globals stay unimported**: a name the clause only builds on, inside a generic or an object, gets no import when TypeScript or the DOM declares it, such as `Date`, `Record`, or `Response`. If a type of your own has such a name, such as `Error`, `Event`, `Comment`, `Image`, `Node`, or `Document`, list it in `types`.
|
|
7323
|
+
- **A name the file already imports keeps that import**: a name the clause only builds on that the resource's file already imports, for one of its keys or through a `#[TsCasts]` entry, uses that import.
|
|
7324
|
+
- **A name the clause names whole keeps its own import**: a clause that is one name, such as `Meta` or `Meta[]`, or a name you list in `types`, imports from the clause's path. If a `#[TsCasts]` entry imports the same name from another path, the clause's import is aliased.
|
|
7325
|
+
|
|
7326
|
+
`#[TsExtends]` and `#[TsIntersect]` on one resource share one alias pass, so the same name from two paths across both attributes is aliased as [Naming Conflicts & Aliasing](#naming-conflicts--aliasing) describes. A resource that publishes as a type alias, through [discriminated unions](https://tolki.abe.dev/ts/api-resources.html#discriminated-unions) or `#[TsIntersect]`, joins each `extends` clause with `&`, as in `export type WarehouseResource = BaseResource & { … }`.
|
|
7327
|
+
|
|
7328
|
+
### Intersecting a Resource With `#[TsIntersect]`
|
|
7329
|
+
|
|
7330
|
+
An interface can't extend a union, so `#[TsExtends]` can't relate one key of a resource to another. `#[TsIntersect]` intersects the resource's type with a type you write instead. Use it when the package can't read the link from `toArray()` itself, as [Discriminated Unions](https://tolki.abe.dev/ts/api-resources.html#discriminated-unions) describes. Here `is_draft` comes from a method call, which the package doesn't read as a discriminant:
|
|
7331
|
+
|
|
7332
|
+
```php
|
|
7333
|
+
use AbeTwoThree\LaravelTsPublish\Attributes\TsIntersect;
|
|
7334
|
+
|
|
7335
|
+
#[TsIntersect('PostStatusVariants', '@/types/posts')]
|
|
7336
|
+
final class PostResource extends JsonResource
|
|
7337
|
+
{
|
|
7338
|
+
public function toArray(Request $request): array
|
|
7339
|
+
{
|
|
7340
|
+
return [
|
|
7341
|
+
'id' => $this->id,
|
|
7342
|
+
'is_draft' => $this->isDraft(),
|
|
7343
|
+
'status' => $this->isDraft()
|
|
7344
|
+
? new DraftStatusResource($this->draft_status)
|
|
7345
|
+
: new PublishedStatusResource($this->status),
|
|
7346
|
+
];
|
|
7347
|
+
}
|
|
7348
|
+
}
|
|
7349
|
+
```
|
|
7350
|
+
|
|
7351
|
+
You write the union in your own module:
|
|
7352
|
+
|
|
7353
|
+
```typescript
|
|
7354
|
+
// resources/js/types/posts.ts
|
|
7355
|
+
import type {
|
|
7356
|
+
DraftStatusResource,
|
|
7357
|
+
PublishedStatusResource,
|
|
7358
|
+
} from "@/types/generated/app/http/resources";
|
|
7359
|
+
|
|
7360
|
+
export type PostStatusVariants =
|
|
7361
|
+
| { is_draft: true; status: DraftStatusResource }
|
|
7362
|
+
| { is_draft: false; status: PublishedStatusResource };
|
|
7363
|
+
```
|
|
7364
|
+
|
|
7365
|
+
The resource publishes its keys intersected with your type, so a check on `is_draft` narrows `status`:
|
|
7366
|
+
|
|
7367
|
+
<!-- prettier-ignore -->
|
|
7368
|
+
```typescript
|
|
7369
|
+
import type { PostStatusVariants } from "@/types/posts";
|
|
7370
|
+
import type { DraftStatusResource, PublishedStatusResource } from ".";
|
|
7371
|
+
|
|
7372
|
+
export type PostResource = {
|
|
7373
|
+
id: number;
|
|
7374
|
+
is_draft: boolean;
|
|
7375
|
+
status: DraftStatusResource | PublishedStatusResource;
|
|
7376
|
+
} & (PostStatusVariants);
|
|
7377
|
+
```
|
|
7378
|
+
|
|
7379
|
+
`#[TsIntersect]` takes three parameters like `#[TsExtends]`'s: `type`, an optional `import` path, and an optional `types` list, read as [Names a Resource's Clause Imports](#names-a-resources-clause-imports) describes. It's repeatable, and a parent class or a trait can carry it, in the same order as `#[TsExtends]`. It has no config array. Each intersected type prints after the resource's own keys and any variants, in parentheses.
|
|
7380
|
+
|
|
7000
7381
|
### Configuration Reference
|
|
7001
7382
|
|
|
7002
7383
|
Each `ts_extends` key applies to one feature's interfaces:
|
|
@@ -7589,10 +7970,11 @@ With `inertia.enabled` on (the default), the package builds the file from your m
|
|
|
7589
7970
|
- **`config()`**: `config('some.key')` with a literal key is typed from the live config value, since the package runs inside your booted app. A computed key stays `unknown`.
|
|
7590
7971
|
- **Value helpers**: `now()` and `today()` are typed as `string`, or `Date` under [`timestamps_as_date`](https://tolki.abe.dev/ts/models.html#timestamps-as-date-objects). `str($value)` is typed as `string`, and `str()` with no argument as `Record<string, never>`. `url($path)` is typed as `string` when the path can't be `null`, and stays `unknown` when it can or has no type. `collect([...])` and a bare array literal are both typed as the list or object the array encodes as, such as `string[]` for `['a', 'b']`. `+` on two arrays is typed as PHP's array union, where the left side's keys win.
|
|
7591
7972
|
- **Closures and first-class callables**: Inertia calls a callable prop before it sends it, so closures and first-class callables, such as `fn () => $request->url()` and `now(...)`, are typed from what the call returns. That includes one inside an array that a helper method builds.
|
|
7973
|
+
- **Discriminated unions**: a nested array whose keys follow another key's value publishes one object per variant, where values that send the same types share one, as [Discriminated Unions](https://tolki.abe.dev/ts/api-resources.html#discriminated-unions) describes for API resources. The top level of shared data and of a page's props stays one object type, because Vue's `defineProps<T>()` needs one.
|
|
7592
7974
|
- **Inertia v2 prop wrappers**: `Inertia::defer()`, `optional()`, `lazy()`, `always()`, `merge()` and `deepMerge()` type as the value they wrap, and so does a prop class you construct, such as `new OptionalProp(fn () => …)`. The three a partial reload can leave out, `defer`, `optional` and `lazy`, make the key optional.
|
|
7593
7975
|
- **API resources**: a resource or resource collection is typed as the response Inertia sends for it, as [API Resources in Props](#api-resources-in-props) describes.
|
|
7594
7976
|
- **`EnumResource` props**: a prop that wraps an enum in `EnumResource`, such as `'role' => EnumResource::make(Role::Admin)`, becomes `AsEnum<typeof Role>` when `enums.use_tolki_package` is on (the default), the same as in [API Resources](https://tolki.abe.dev/ts/api-resources.html#enum-properties-with-enumresource). With it off, the key keeps the enum's type alias (`role: RoleType`). The change applies per key, so another key that reads the enum directly keeps `RoleType`.
|
|
7595
|
-
- **`EnumResource` ternaries and `null`**: each arm of a ternary is typed as Laravel sends it. Wrapping two different enums publishes `AsEnum<typeof Role> | AsEnum<typeof Status>`, and a wrap beside a bare case
|
|
7977
|
+
- **`EnumResource` ternaries and `null`**: each arm of a ternary or `match` is typed as Laravel sends it, in page props and shared data alike. Wrapping two different enums publishes `AsEnum<typeof Role> | AsEnum<typeof Status>`, and a wrap beside a bare case publishes `AsEnum<typeof Role> | StatusType`. Two enums that share a class name keep their own names, as in `AsEnum<typeof EnumsStatus> | AsEnum<typeof CrmStatus>`. A wrapped collection beside a bare case publishes `{ data: AsEnum<typeof Status>[] } | StatusType`. A wrap around an enum that may be `null` publishes `AsEnum<typeof Status> | never[]`, because Inertia sends `[]` for it, not `null`. Tell the two apart with `Array.isArray()`.
|
|
7596
7978
|
- **Enum cases**: a bare case, such as `'defaultStatus' => Status::Draft`, is typed as the enum's type alias (`defaultStatus: StatusType`), which matches the value Laravel sends for a backed enum. The file imports the alias for you.
|
|
7597
7979
|
- **Classes with `#[TsType]`**: a value of a class that has or inherits a `#[TsType]` is typed as that type, with its import, in shared data and page props alike. See [Custom Types](https://tolki.abe.dev/ts/custom-types.html).
|
|
7598
7980
|
- **`errors`**: left out. `@inertiajs/core` already types `page.props.errors` as `Errors & ErrorBag`, and [`errorValueType`](#anatomy-of-the-generated-file) sharpens it. A `#[TsCasts]` or `@return` docblock entry named `errors` still adds one if you want it.
|
|
@@ -7606,8 +7988,6 @@ The signed-in user is typed from the default guard only, so a named guard, such
|
|
|
7606
7988
|
|
|
7607
7989
|
In a route's [page props](https://tolki.abe.dev/ts/routing.html#inertia-integration), `getKey()` on a route-bound model publishes the model's key type with no `| null`, because Laravel binds only a saved row. With a `Post $post` action parameter, `'post_id' => $post->getKey()` publishes `post_id: number`. A relation read on the parameter is typed by the models it loads, so `'comments' => $post->comments` publishes `comments: Comment[]`.
|
|
7608
7990
|
|
|
7609
|
-
A few mixes of `EnumResource` arms publish a type that doesn't match what Laravel sends. A wrap beside a bare case of another enum, as in `$cond ? EnumResource::make(Role::Admin) : Status::Draft`, publishes `RoleType | StatusType`, though the first arm sends the `Role` object. A nested ternary over the wraps of three enums can leave a type alias unimported, which fails your build with `TS2304`. Override such a key with a `#[TsCasts]` entry that has an `import`.
|
|
7610
|
-
|
|
7611
7991
|
### Anatomy of the Generated File
|
|
7612
7992
|
|
|
7613
7993
|
Given this middleware:
|
|
@@ -8761,6 +9141,25 @@ export const store = annotateRequestPayload<StorePostRequest>()(
|
|
|
8761
9141
|
);
|
|
8762
9142
|
```
|
|
8763
9143
|
|
|
9144
|
+
### Bundling
|
|
9145
|
+
|
|
9146
|
+
A route nobody uses drops out of your bundle in every bundler, esbuild included, because the generated file writes `/* @__PURE__ */` before every call, including each call of a curried helper. `defineRoute`, `getRouteDefaults` and the other runtime helpers are marked as free of side effects, except `setRouteDefaults`, `addRouteDefault` and `resetRouteDefaults`, which change shared state and are always kept:
|
|
9147
|
+
|
|
9148
|
+
```typescript
|
|
9149
|
+
export const store = /* @__PURE__ */ annotateRequestPayload<StorePostRequest>()(
|
|
9150
|
+
/* @__PURE__ */ annotatePageProps<StorePageProps>()(
|
|
9151
|
+
/* @__PURE__ */ defineRoute({
|
|
9152
|
+
name: "inertia-form-request.store",
|
|
9153
|
+
url: "/inertia-form-request",
|
|
9154
|
+
methods: ["post"] as const,
|
|
9155
|
+
component: "InertiaFormRequest/Success",
|
|
9156
|
+
}),
|
|
9157
|
+
),
|
|
9158
|
+
);
|
|
9159
|
+
```
|
|
9160
|
+
|
|
9161
|
+
The other examples on this page leave the comment out. A file published by an older version of the package, or by a custom `routes.template`, may not have it. Without it, Rolldown, esbuild and webpack keep a curried route, and esbuild keeps every route. [Bundling and Tree-Shaking](https://tolki.abe.dev/tree-shaking.html) lists every bundler.
|
|
9162
|
+
|
|
8764
9163
|
### Filtering & Excluding Routes
|
|
8765
9164
|
|
|
8766
9165
|
These settings leave routes out of the published output:
|
|
@@ -9269,6 +9668,8 @@ Inertia's `inertia-config.blade.php` and Vite env's `vite-env.blade.php` have no
|
|
|
9269
9668
|
|
|
9270
9669
|
Your copies stay as they were when you published them. After you upgrade the package, compare them with the package's new templates and merge the changes. A stale copy can leave out output the new version adds.
|
|
9271
9670
|
|
|
9671
|
+
For example, a `resource` or `globals` copy published before [discriminated unions](https://tolki.abe.dev/ts/api-resources.html#discriminated-unions) prints a split resource's shared keys alone, and leaves out its variants and its `#[TsIntersect]` types. Publish it again, or merge the new template's `variants` and `intersections` blocks into your copy.
|
|
9672
|
+
|
|
9272
9673
|
## Analyzer API
|
|
9273
9674
|
|
|
9274
9675
|
The analysis that the [Laravel TypeScript Publisher](https://github.com/abetwothree/laravel-ts-publish) runs on your classes is also available to your own code. `AstEngine::analyze()` takes a class and a method name. It returns the typed properties that method returns, plus the imports those types need. Use it when your own code needs this package's types without a full publish, such as a custom Artisan command or another package.
|
|
@@ -9320,7 +9721,7 @@ public function __construct(
|
|
|
9320
9721
|
|
|
9321
9722
|
Each property holds one part of the module you write:
|
|
9322
9723
|
|
|
9323
|
-
- **`properties`**: a `list<{name, type, optional, description}>` with one entry per key the method returns. `type` is already a TypeScript type string. `optional` is `true` wherever the code can leave the key out, such as a conditional method or a `mergeWhen()`.
|
|
9724
|
+
- **`properties`**: a `list<{name, type, optional, description}>` with one entry per key the method returns. `type` is already a TypeScript type string. `optional` is `true` wherever the code can leave the key out, such as a conditional method or a `mergeWhen()`. A nested array whose keys follow another key's value comes back as a union of objects, one per variant, as [Discriminated Unions](https://tolki.abe.dev/ts/api-resources.html#discriminated-unions) describes.
|
|
9324
9725
|
- **`typeImports`**: an `import path => list<name>` map of the types that the property types name. Write these as `import type` lines.
|
|
9325
9726
|
- **`valueImports`**: an `import path => list<name>` map of the enum constants that an `AsEnum<typeof X>` wrapper reads. Write these as plain `import` lines, never as `import type`.
|
|
9326
9727
|
|
|
@@ -9329,7 +9730,7 @@ Two classes that share an import path merge into one entry, so neither overwrite
|
|
|
9329
9730
|
The three properties agree with each other, so a module that renders all three as they are compiles:
|
|
9330
9731
|
|
|
9331
9732
|
- **Same-name classes**: two classes with the same short name, such as two `User` models, come back under separate aliases, and the property types use those aliases.
|
|
9332
|
-
- **`EnumResource` properties**:
|
|
9733
|
+
- **`EnumResource` properties**: each `EnumResource` wrap comes back as `AsEnum<typeof X>` where it's read, in a union, a nested key or a list too, and `valueImports` holds exactly the consts the types spell. Two enums that share a class name come back under separate aliases. With `enums.use_tolki_package` off, a wrap comes back as the plain enum type with a type import, and `valueImports` stays empty.
|
|
9333
9734
|
- **No unused imports**: nothing is imported that no property type names. A name counts wherever it appears in a type, even inside a string, template text, or a comment. A method-level `#[TsCasts]` of `"'User' | 'Admin'"` therefore keeps an unused `User` import, which TypeScript reports only under `noUnusedLocals`.
|
|
9334
9735
|
|
|
9335
9736
|
#### Method Parameters
|
|
@@ -9354,7 +9755,7 @@ $result = resolve(AstEngine::class)->analyze(App\Http\Resources\PostResource::cl
|
|
|
9354
9755
|
|
|
9355
9756
|
`analyze()` doesn't use a custom `resources.transformer_class`, so a [`resolveModelClass()` override](https://tolki.abe.dev/ts/customizing-the-pipeline.html#changing-how-a-resource-finds-its-model) doesn't apply here. To choose the model yourself, pass it as the third argument.
|
|
9356
9757
|
|
|
9357
|
-
Every pattern in [API Resources](https://tolki.abe.dev/ts/api-resources.html) gives the same properties, imports, and optionality as a publish. That includes the `when()` family of conditional methods, `EnumResource::make()`, nested and collection resources, `merge()` and `mergeWhen()`, and relation filters such as `$this->author->only([...])`. The exceptions are a `morphTo` union, a collection that publishes as an alias, class-level and model-level `#[TsCasts]`, a `toResource()` guess by naming convention, and the filled index signature of an interpolated key. [What It Cannot Do](#what-it-cannot-do) covers each one.
|
|
9758
|
+
Every pattern in [API Resources](https://tolki.abe.dev/ts/api-resources.html) gives the same properties, imports, and optionality as a publish. That includes the `when()` family of conditional methods, `EnumResource::make()`, nested and collection resources, `merge()` and `mergeWhen()`, and relation filters such as `$this->author->only([...])`. The exceptions are a `morphTo` union, a top-level discriminated union, a collection that publishes as an alias, class-level and model-level `#[TsCasts]`, a `toResource()` guess by naming convention, and the filled index signature of an interpolated key. [What It Cannot Do](#what-it-cannot-do) covers each one.
|
|
9358
9759
|
|
|
9359
9760
|
A [JSON:API resource](https://tolki.abe.dev/ts/api-resources.html#json-api-resources) returns its resource object, the `id`, `type`, `attributes`, and other members a publish writes, even when it declares a `toArray()`.
|
|
9360
9761
|
|
|
@@ -9390,6 +9791,8 @@ For example, a `share()` whose docblock declares `filters?: array<string, string
|
|
|
9390
9791
|
|
|
9391
9792
|
**`morphTo` unions.** `analyze()` can't list the models a `morphTo` relation can hold, because only a publish scans your models for the `morphOne` and `morphMany` relations that point back. The relation is left out of a model's shape, and it comes back `unknown` where a `toArray()` names it. A [`@return MorphTo<A|B, $this>` docblock](https://tolki.abe.dev/ts/models.html#typing-morphto-relations) on the relation method gives both `analyze()` and a publish the union.
|
|
9392
9793
|
|
|
9794
|
+
**A resource's top-level discriminated union.** `analyze()` returns each key of a resource with one type, where `ts:publish` splits the keys that follow another key's value into [variants](https://tolki.abe.dev/ts/api-resources.html#discriminated-unions). `AnalysisResult` has no place for them. A nested array splits in both.
|
|
9795
|
+
|
|
9393
9796
|
**Collections that publish as an alias.** A `ResourceCollection` with no keys beyond its items publishes as a flat alias, `export type X = Y[]`, rather than an interface, when it has `$wrap = null`. After [`JsonResource::withoutWrapping()`](https://tolki.abe.dev/ts/api-resources.html#the-wrap-key-your-app-sets), so does every collection with Laravel's default shape that doesn't redeclare `$wrap`. An alias has no property list or imports to put in an `AnalysisResult`, so all three properties come back empty. `ts:publish` writes the alias.
|
|
9394
9797
|
|
|
9395
9798
|
**Class-level and model-level `#[TsCasts]`.** `analyze()` applies a `#[TsCasts]` on the analyzed method only. `ts:publish` then applies a resource's class-level `#[TsCasts]` and its model's `#[TsCasts]`, types and optionality both. On a `CommentResource` whose class-level casts name `flagged_at` and `metadata`, `analyze()` returns `flagged_at: string | null` and `metadata: unknown[] | null`. The published interface has `flagged_at?: string | null` and `metadata: Record<string, unknown>`.
|
|
@@ -9406,7 +9809,7 @@ Outside those cases, `analyze()` runs the same inference that resources, broadca
|
|
|
9406
9809
|
|
|
9407
9810
|
`analyze()` and `ts:publish` both type the patterns these docs describe, including [a local you write more than once](https://tolki.abe.dev/ts/api-resources.html#local-variables-and-narrowing). Anything else, such as an expression neither can follow or a local that a reference can write, comes back `unknown` rather than a guess.
|
|
9408
9811
|
|
|
9409
|
-
Two cases don't widen to `unknown`. [A conditional's default that can't be typed](https://tolki.abe.dev/ts/api-resources.html#passing-a-default-argument) leaves the value's own type in place. [A union member that can't be typed is left out](https://tolki.abe.dev/ts/api-resources.html#values-left-out-of-a-union), whether it's a ternary or `?:` arm or a value that a parameter's writes join. So `$cond ? $untypable : null` publishes `null`.
|
|
9812
|
+
Two cases don't widen to `unknown`. [A conditional's default that can't be typed](https://tolki.abe.dev/ts/api-resources.html#passing-a-default-argument) leaves the value's own type in place. [A union member that can't be typed is left out](https://tolki.abe.dev/ts/api-resources.html#values-left-out-of-a-union), whether it's a ternary or `?:` arm or a value that a parameter's writes join. So `$cond ? $untypable : null` publishes `null`. Where the method's `@return` types the key that holds it, the docblock's type takes the left-out value's place beside the `null`, as [Values Left Out of a Union](https://tolki.abe.dev/ts/api-resources.html#values-left-out-of-a-union) describes.
|
|
9410
9813
|
|
|
9411
9814
|
### Configuration Reference
|
|
9412
9815
|
|
|
@@ -9512,18 +9915,19 @@ A config file published before model metadata existed has no `model_metadata` bl
|
|
|
9512
9915
|
|
|
9513
9916
|
### Resources (`resources.*`)
|
|
9514
9917
|
|
|
9515
|
-
| Config Key | Type | Default | Description
|
|
9516
|
-
| ---------------------------------- | -------- | ------------------------------ |
|
|
9517
|
-
| `resources.enabled` | `bool` | `true` | Enable or disable resource publishing
|
|
9518
|
-
| `resources.namespace` | `string` | `'resources'` | Not used. The global declaration file names each namespace after the class's PHP namespace, such as `app.http.resources`
|
|
9519
|
-
| `resources.template` | `string` | `laravel-ts-publish::resource` | Blade template for resource TypeScript output
|
|
9520
|
-
| `resources.
|
|
9521
|
-
| `resources.
|
|
9522
|
-
| `resources.
|
|
9523
|
-
| `resources.
|
|
9524
|
-
| `resources.
|
|
9525
|
-
| `resources.
|
|
9526
|
-
| `resources.
|
|
9918
|
+
| Config Key | Type | Default | Description |
|
|
9919
|
+
| ---------------------------------- | -------- | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
9920
|
+
| `resources.enabled` | `bool` | `true` | Enable or disable resource publishing |
|
|
9921
|
+
| `resources.namespace` | `string` | `'resources'` | Not used. The global declaration file names each namespace after the class's PHP namespace, such as `app.http.resources` |
|
|
9922
|
+
| `resources.template` | `string` | `laravel-ts-publish::resource` | Blade template for resource TypeScript output |
|
|
9923
|
+
| `resources.discriminated_unions` | `bool` | `true` | Publish a resource whose keys follow another key's value as a union of variants. See [Discriminated Unions](https://tolki.abe.dev/ts/api-resources.html#discriminated-unions) |
|
|
9924
|
+
| `resources.included` | `array` | `[]` | Only publish these resources (empty = all) |
|
|
9925
|
+
| `resources.excluded` | `array` | `[]` | Exclude these resources from publishing |
|
|
9926
|
+
| `resources.additional_directories` | `array` | `[]` | Extra directories to search for resources |
|
|
9927
|
+
| `resources.collector_class` | `string` | `ResourcesCollector` | Discovers PHP resource classes |
|
|
9928
|
+
| `resources.generator_class` | `string` | `ResourceGenerator` | Orchestrates transforming and writing |
|
|
9929
|
+
| `resources.transformer_class` | `string` | `ResourceTransformer` | Converts PHP resource into TypeScript data |
|
|
9930
|
+
| `resources.writer_class` | `string` | `ResourceWriter` | Writes TypeScript resource files |
|
|
9527
9931
|
|
|
9528
9932
|
### Globals (`globals.*`)
|
|
9529
9933
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export * from './enums';
|
|
2
|
-
export * from './routes';
|
|
1
|
+
export * from './enums.js';
|
|
2
|
+
export * from './routes.js';
|
|
3
3
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC"}
|
package/dist/routes.d.ts
CHANGED
|
@@ -45,6 +45,7 @@ export declare function annotateRequestPayload<TRequestPayload>(): <TMethods ext
|
|
|
45
45
|
* the caller doesn't provide them. Mirrors Laravel's `URL::defaults()`.
|
|
46
46
|
* Accepts a static object or a factory function for lazy evaluation.
|
|
47
47
|
*
|
|
48
|
+
* @sideEffects state - Replaces the module-level route defaults.
|
|
48
49
|
* @param defaults - A record of parameter names to default values, or a factory function.
|
|
49
50
|
*/
|
|
50
51
|
export declare function setRouteDefaults(defaults: Record<string, string | number | boolean> | (() => Record<string, string | number | boolean>)): void;
|
|
@@ -53,6 +54,7 @@ export declare function setRouteDefaults(defaults: Record<string, string | numbe
|
|
|
53
54
|
*
|
|
54
55
|
* If a default already exists for the given parameter name, it is overwritten.
|
|
55
56
|
*
|
|
57
|
+
* @sideEffects state - Updates the module-level route defaults.
|
|
56
58
|
* @param key - The parameter name.
|
|
57
59
|
* @param value - The default value.
|
|
58
60
|
*/
|
|
@@ -65,6 +67,8 @@ export declare function addRouteDefault(key: string, value: string | number | bo
|
|
|
65
67
|
export declare function getRouteDefaults(): Record<string, string | number | boolean>;
|
|
66
68
|
/**
|
|
67
69
|
* Reset route defaults to an empty object (useful for testing).
|
|
70
|
+
*
|
|
71
|
+
* @sideEffects state - Clears the module-level route defaults.
|
|
68
72
|
*/
|
|
69
73
|
export declare function resetRouteDefaults(): void;
|
|
70
74
|
/**
|
package/dist/routes.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACR,iBAAiB,EACjB,cAAc,EACd,mBAAmB,EACnB,YAAY,EACZ,eAAe,EACf,4BAA4B,EAC5B,kBAAkB,EAClB,eAAe,EACf,aAAa,EACb,iBAAiB,EACpB,MAAM,cAAc,CAAC;AAYtB,YAAY,EACR,iBAAiB,EACjB,cAAc,EACd,mBAAmB,EACnB,YAAY,EACZ,eAAe,EACf,4BAA4B,EAC5B,kBAAkB,EAClB,eAAe,EACf,aAAa,EACb,iBAAiB,GACpB,CAAC;AAEF;;;;;;;;;;;;;;;;;GAiBG;
|
|
1
|
+
{"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACR,iBAAiB,EACjB,cAAc,EACd,mBAAmB,EACnB,YAAY,EACZ,eAAe,EACf,4BAA4B,EAC5B,kBAAkB,EAClB,eAAe,EACf,aAAa,EACb,iBAAiB,EACpB,MAAM,cAAc,CAAC;AAYtB,YAAY,EACR,iBAAiB,EACjB,cAAc,EACd,mBAAmB,EACnB,YAAY,EACZ,eAAe,EACf,4BAA4B,EAC5B,kBAAkB,EAClB,eAAe,EACf,aAAa,EACb,iBAAiB,GACpB,CAAC;AAEF;;;;;;;;;;;;;;;;;GAiBG;AAEH,wBAAgB,iBAAiB,CAAC,UAAU,KAAK,CAC7C,QAAQ,SAAS,SAAS,MAAM,EAAE,EAClC,KAAK,SAAS,SAAS,YAAY,EAAE,EACrC,UAAU,SAAS,kBAAkB,GAAG,SAAS,EACjD,kBAAkB,EAClB,uBAAuB,EAEvB,KAAK,EAAE,iBAAiB,CACpB,QAAQ,EACR,KAAK,EACL,UAAU,EACV,kBAAkB,EAClB,uBAAuB,CAC1B,KACA,iBAAiB,CAClB,QAAQ,EACR,KAAK,EACL,UAAU,EACV,UAAU,EACV,uBAAuB,CAC1B,CA8BA;AAED;;;;;;;;;;;;;;;;;GAiBG;AAEH,wBAAgB,sBAAsB,CAAC,eAAe,KAAK,CACvD,QAAQ,SAAS,SAAS,MAAM,EAAE,EAClC,KAAK,SAAS,SAAS,YAAY,EAAE,EACrC,UAAU,SAAS,kBAAkB,GAAG,SAAS,EACjD,UAAU,EACV,uBAAuB,EAEvB,KAAK,EAAE,iBAAiB,CACpB,QAAQ,EACR,KAAK,EACL,UAAU,EACV,UAAU,EACV,uBAAuB,CAC1B,KACA,iBAAiB,CAClB,QAAQ,EACR,KAAK,EACL,UAAU,EACV,UAAU,EACV,eAAe,CAClB,CA8BA;AAiBD;;;;;;;;;GASG;AACH,wBAAgB,gBAAgB,CAC5B,QAAQ,EACF,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,GACzC,CAAC,MAAM,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,CAAC,GACxD,IAAI,CAEN;AAED;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAC3B,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,GACjC,IAAI,CAMN;AAED;;;;GAIG;AAEH,wBAAgB,gBAAgB,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,CAE5E;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,IAAI,IAAI,CAEzC;AA8YD;;;;;;;;;GASG;AAEH,wBAAgB,eAAe,CAC3B,MAAM,EAAE,MAAM,EACd,OAAO,CAAC,EAAE,iBAAiB,GAC5B,iBAAiB,CAWnB;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,wBAAgB,WAAW,CACvB,KAAK,CAAC,QAAQ,SAAS,SAAS,MAAM,EAAE,EACxC,KAAK,CAAC,KAAK,SAAS,SAAS,YAAY,EAAE,GAAG,SAAS,EAAE,EACzD,KAAK,CAAC,UAAU,SAAS,kBAAkB,GAAG,SAAS,GAAG,SAAS,EAEnE,QAAQ,EAAE,aAAa,CAAC,QAAQ,EAAE,KAAK,EAAE,UAAU,CAAC,GACrD,iBAAiB,CAAC,QAAQ,EAAE,KAAK,EAAE,UAAU,CAAC,CAkGhD"}
|
package/dist/routes.js
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import { isArray as e, isBoolean as t, isFunction as n, isNull as r, isNumber as i, isObject as a, isString as o, isUndefined as s } from "@tolki/utils";
|
|
2
2
|
// src/routes.ts
|
|
3
|
+
/* @__NO_SIDE_EFFECTS__ */
|
|
3
4
|
function c() {
|
|
4
|
-
return function(e) {
|
|
5
|
+
return /* @__NO_SIDE_EFFECTS__ */ function(e) {
|
|
5
6
|
return e;
|
|
6
7
|
};
|
|
7
8
|
}
|
|
9
|
+
/* @__NO_SIDE_EFFECTS__ */
|
|
8
10
|
function l() {
|
|
9
|
-
return function(e) {
|
|
11
|
+
return /* @__NO_SIDE_EFFECTS__ */ function(e) {
|
|
10
12
|
return e;
|
|
11
13
|
};
|
|
12
14
|
}
|
|
@@ -21,6 +23,7 @@ function p(e, t) {
|
|
|
21
23
|
[e]: t
|
|
22
24
|
});
|
|
23
25
|
}
|
|
26
|
+
/* @__NO_SIDE_EFFECTS__ */
|
|
24
27
|
function m() {
|
|
25
28
|
return { ...d() };
|
|
26
29
|
}
|
|
@@ -160,6 +163,7 @@ function S(e, t) {
|
|
|
160
163
|
}
|
|
161
164
|
};
|
|
162
165
|
}
|
|
166
|
+
/* @__NO_SIDE_EFFECTS__ */
|
|
163
167
|
function C(e, t) {
|
|
164
168
|
let n = t?.mergeQuery ? "mergeQuery" : "_query", r = t?.[n] ?? {};
|
|
165
169
|
return {
|
|
@@ -170,6 +174,7 @@ function C(e, t) {
|
|
|
170
174
|
}
|
|
171
175
|
};
|
|
172
176
|
}
|
|
177
|
+
/* @__NO_SIDE_EFFECTS__ */
|
|
173
178
|
function w(e) {
|
|
174
179
|
let t = e.args ?? [], n = e.methods[0] ?? "get", r = (...r) => {
|
|
175
180
|
let [i, a] = y(r, t);
|
|
@@ -189,13 +194,13 @@ function w(e) {
|
|
|
189
194
|
return x(b(e.url, i, t, a), n);
|
|
190
195
|
} });
|
|
191
196
|
let a = n !== "get" && n !== "post", s = (...r) => {
|
|
192
|
-
let [i, o] = y(r, t), s = a ? C(n, o) : o;
|
|
197
|
+
let [i, o] = y(r, t), s = a ? /* @__PURE__ */ C(n, o) : o;
|
|
193
198
|
return S(b(e.url, i, t, s), n);
|
|
194
199
|
};
|
|
195
200
|
for (let n of e.methods) {
|
|
196
201
|
let r = n !== "get" && n !== "post";
|
|
197
202
|
Object.assign(s, { [n]: (...i) => {
|
|
198
|
-
let [a, o] = y(i, t), s = r ? C(n, o) : o;
|
|
203
|
+
let [a, o] = y(i, t), s = r ? /* @__PURE__ */ C(n, o) : o;
|
|
199
204
|
return S(b(e.url, a, t, s), n);
|
|
200
205
|
} });
|
|
201
206
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vite-plugin.d.ts","sourceRoot":"","sources":["../src/vite-plugin.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,cAAc,EAAyB,MAAM,cAAc,CAAC;AACrE,OAAO,EAEH,KAAK,MAAM,EAGd,MAAM,MAAM,CAAC;AAId,OAAO,EAAE,cAAc,EAAE,CAAC;AAE1B,MAAM,WAAW,uBAAuB;IACpC;;;;;;;;;;;;OAYG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;;OAIG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;;;OAMG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB;;;;;;;OAOG;IACH,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B;;;;;;;OAOG;IACH,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB;;;;;OAKG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB;;;;;;;;;;;;;;;OAeG;IACH,aAAa,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC;IAC/B;;;;;;;;;;OAUG;IACH,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC;;;;;;;;;;OAUG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;CACnB;AAcD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwDG;
|
|
1
|
+
{"version":3,"file":"vite-plugin.d.ts","sourceRoot":"","sources":["../src/vite-plugin.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,cAAc,EAAyB,MAAM,cAAc,CAAC;AACrE,OAAO,EAEH,KAAK,MAAM,EAGd,MAAM,MAAM,CAAC;AAId,OAAO,EAAE,cAAc,EAAE,CAAC;AAE1B,MAAM,WAAW,uBAAuB;IACpC;;;;;;;;;;;;OAYG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;;OAIG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;;;OAMG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB;;;;;;;OAOG;IACH,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B;;;;;;;OAOG;IACH,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB;;;;;OAKG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB;;;;;;;;;;;;;;;OAeG;IACH,aAAa,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC;IAC/B;;;;;;;;;;OAUG;IACH,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC;;;;;;;;;;OAUG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;CACnB;AAcD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwDG;AAEH,wBAAgB,gBAAgB,CAC5B,OAAO,GAAE,uBAA4B,GACtC,MAAM,CA4PR"}
|
package/dist/vite-plugin.js
CHANGED
|
@@ -5,10 +5,11 @@ import { promisify as r } from "node:util";
|
|
|
5
5
|
import { escapeShellArg as i, escapeWindowsShellArg as a } from "@tolki/utils";
|
|
6
6
|
import { normalizePath as o } from "vite";
|
|
7
7
|
// src/vite-plugin.ts
|
|
8
|
-
var s = r(e);
|
|
8
|
+
var s = /* @__PURE__ */ r(e);
|
|
9
9
|
function c(e) {
|
|
10
10
|
return process.platform === "win32" ? a(e) : i(e);
|
|
11
11
|
}
|
|
12
|
+
/* @__NO_SIDE_EFFECTS__ */
|
|
12
13
|
function l(e = {}) {
|
|
13
14
|
let { command: r = "php artisan ts:publish", filename: i = "laravel-ts-collected-files.json", directory: a = "resources/js/types/data/", runOnDevStart: l = !1, runOnBuildStart: u = !0, reload: d = !0, failOnError: f, sourceCommand: p, onBuildOnlyFunctional: m = !0, quiet: h = !0 } = e, g = p === !1 ? !1 : p ?? `${r} --source={file}`, _, v, y = /* @__PURE__ */ new Map(), b = "", x = !1, S = [], C = "[laravel-ts-publish]", w = async () => {
|
|
14
15
|
y.clear();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tolki/ts",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.2",
|
|
4
4
|
"description": "A set of TypeScript utilities for the Laravel TypeScript Publish PHP package.",
|
|
5
5
|
"author": "Abraham Arango <https://github.com/abetwothree>",
|
|
6
6
|
"license": "MIT",
|
|
@@ -39,9 +39,9 @@
|
|
|
39
39
|
"tolki"
|
|
40
40
|
],
|
|
41
41
|
"dependencies": {
|
|
42
|
-
"@tolki/enum": "^1.2.
|
|
43
|
-
"@tolki/
|
|
44
|
-
"@tolki/
|
|
42
|
+
"@tolki/enum": "^1.2.2",
|
|
43
|
+
"@tolki/utils": "^1.7.0",
|
|
44
|
+
"@tolki/types": "^1.13.0"
|
|
45
45
|
},
|
|
46
46
|
"devDependencies": {
|
|
47
47
|
"vite": "^8.3.5"
|
|
@@ -61,22 +61,18 @@
|
|
|
61
61
|
"exports": {
|
|
62
62
|
".": {
|
|
63
63
|
"types": "./dist/index.d.ts",
|
|
64
|
-
"
|
|
65
|
-
"require": "./dist/index.js"
|
|
64
|
+
"default": "./dist/index.js"
|
|
66
65
|
},
|
|
67
66
|
"./enums": {
|
|
68
67
|
"types": "./dist/enums.d.ts",
|
|
69
|
-
"import": "./dist/enums.js",
|
|
70
68
|
"default": "./dist/enums.js"
|
|
71
69
|
},
|
|
72
70
|
"./routes": {
|
|
73
71
|
"types": "./dist/routes.d.ts",
|
|
74
|
-
"import": "./dist/routes.js",
|
|
75
72
|
"default": "./dist/routes.js"
|
|
76
73
|
},
|
|
77
74
|
"./vite": {
|
|
78
75
|
"types": "./dist/vite-plugin.d.ts",
|
|
79
|
-
"import": "./dist/vite-plugin.js",
|
|
80
76
|
"default": "./dist/vite-plugin.js"
|
|
81
77
|
}
|
|
82
78
|
},
|