@tolki/ts 1.1.1 → 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 +344 -53
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -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
|
|
@@ -1071,9 +1073,7 @@ A unit enum publishes each case name as its value, so `values` returns its case
|
|
|
1071
1073
|
|
|
1072
1074
|
### Bundling
|
|
1073
1075
|
|
|
1074
|
-
An enum nobody uses drops out of your bundle in
|
|
1075
|
-
|
|
1076
|
-
esbuild doesn't follow that mark across files, so it keeps the call unless the call site says it is safe to remove:
|
|
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
1077
|
|
|
1078
1078
|
```typescript
|
|
1079
1079
|
export const Status = /* @__PURE__ */ defineEnum({
|
|
@@ -1083,7 +1083,7 @@ export const Status = /* @__PURE__ */ defineEnum({
|
|
|
1083
1083
|
});
|
|
1084
1084
|
```
|
|
1085
1085
|
|
|
1086
|
-
Rspack also
|
|
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
1087
|
|
|
1088
1088
|
### Vite Plugin
|
|
1089
1089
|
|
|
@@ -1528,15 +1528,37 @@ A specific return type or `Attribute<Get, Set>` generic is always read first, so
|
|
|
1528
1528
|
- Calls something whose return type can't be determined
|
|
1529
1529
|
- Reads another accessor that reads it back, in which case both publish `unknown`
|
|
1530
1530
|
- Can only be typed as `null`, because one side of a `??` or a ternary couldn't be typed
|
|
1531
|
-
- 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
|
|
1532
1531
|
- Returns an API resource
|
|
1533
1532
|
|
|
1534
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.
|
|
1535
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
|
+
|
|
1536
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`.
|
|
1537
1538
|
|
|
1538
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.
|
|
1539
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
|
+
|
|
1540
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.
|
|
1541
1563
|
|
|
1542
1564
|
#### Typing `array` Casts With `@property`
|
|
@@ -2308,7 +2330,7 @@ The [Configuration Reference](https://tolki.abe.dev/ts/configuration-reference.h
|
|
|
2308
2330
|
|
|
2309
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.
|
|
2310
2332
|
|
|
2311
|
-
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.
|
|
2312
2334
|
|
|
2313
2335
|
By default, the package looks for resources in the `app/Http/Resources` directory. To change that, see [Filtering & Excluding](#filtering--excluding).
|
|
2314
2336
|
|
|
@@ -2384,7 +2406,7 @@ The output shows how each kind of value is typed:
|
|
|
2384
2406
|
|
|
2385
2407
|
#### Classes Sharing a Name Across Namespaces
|
|
2386
2408
|
|
|
2387
|
-
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:
|
|
2388
2410
|
|
|
2389
2411
|
```typescript
|
|
2390
2412
|
import type { User as CrmUser } from "../../../crm/models";
|
|
@@ -2855,7 +2877,25 @@ roles: (AsEnum<typeof Role> | never[])[];
|
|
|
2855
2877
|
role_list: (AsEnum<typeof Role> | null)[];
|
|
2856
2878
|
```
|
|
2857
2879
|
|
|
2858
|
-
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:
|
|
2859
2899
|
|
|
2860
2900
|
```php
|
|
2861
2901
|
'audit' => [
|
|
@@ -3069,6 +3109,157 @@ A `@return` docblock that types the key, on `toArray()` or on a method it spread
|
|
|
3069
3109
|
|
|
3070
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.
|
|
3071
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
|
+
|
|
3072
3263
|
### Method Calls, Variables, and Collections
|
|
3073
3264
|
|
|
3074
3265
|
Values you compute in `toArray()` get types too: method calls, property reads on other objects, local variables, and collection chains.
|
|
@@ -5341,14 +5532,15 @@ related: { data: PostResource }[];
|
|
|
5341
5532
|
|
|
5342
5533
|
### Resource Attributes
|
|
5343
5534
|
|
|
5344
|
-
|
|
5535
|
+
Five attributes configure how a resource is published:
|
|
5345
5536
|
|
|
5346
|
-
| Attribute
|
|
5347
|
-
|
|
|
5348
|
-
| `#[TsResource]`
|
|
5349
|
-
| `#[TsCasts]`
|
|
5350
|
-
| `#[TsExtends]`
|
|
5351
|
-
| `#[
|
|
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 |
|
|
5352
5544
|
|
|
5353
5545
|
#### Configuring Resource Generation With `#[TsResource]`
|
|
5354
5546
|
|
|
@@ -5365,13 +5557,14 @@ class UserResource extends JsonResource
|
|
|
5365
5557
|
}
|
|
5366
5558
|
```
|
|
5367
5559
|
|
|
5368
|
-
The attribute takes
|
|
5560
|
+
The attribute takes four optional parameters:
|
|
5369
5561
|
|
|
5370
|
-
| Parameter
|
|
5371
|
-
|
|
|
5372
|
-
| `name`
|
|
5373
|
-
| `model`
|
|
5374
|
-
| `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 |
|
|
5375
5568
|
|
|
5376
5569
|
`name` also sets the output file's name. For example, `#[TsResource(name: 'Address')]` generates `address.ts` instead of `address-resource.ts`.
|
|
5377
5570
|
|
|
@@ -5952,7 +6145,30 @@ export interface ManifestAssembled {
|
|
|
5952
6145
|
|
|
5953
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>[]`.
|
|
5954
6147
|
|
|
5955
|
-
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
|
+
```
|
|
5956
6172
|
|
|
5957
6173
|
#### `when()` and `unless()` From `Conditionable`
|
|
5958
6174
|
|
|
@@ -6419,7 +6635,7 @@ class UserResource extends JsonResource
|
|
|
6419
6635
|
|
|
6420
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()`.
|
|
6421
6637
|
|
|
6422
|
-
|
|
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).
|
|
6423
6639
|
|
|
6424
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).
|
|
6425
6641
|
|
|
@@ -6860,6 +7076,8 @@ There are two ways to add an `extends` clause, and they combine when you use bot
|
|
|
6860
7076
|
- **The `#[TsExtends]` attribute**: applies to one class, and to any class that extends it or uses the trait it's on.
|
|
6861
7077
|
- **The `ts_extends.*` config arrays**: apply to every generated interface of one feature, such as every model.
|
|
6862
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
|
+
|
|
6863
7081
|
### `#[TsExtends]` Attribute
|
|
6864
7082
|
|
|
6865
7083
|
The attribute takes the clause, an optional import path, and an optional list of names to import:
|
|
@@ -6882,11 +7100,11 @@ class TsExtends
|
|
|
6882
7100
|
|
|
6883
7101
|
Each parameter controls one part of the clause:
|
|
6884
7102
|
|
|
6885
|
-
| Parameter | Type | Default | Description
|
|
6886
|
-
| --------- | --------------- | -------- |
|
|
6887
|
-
| `extends` | `string` | required | The TypeScript for the `extends` clause: an interface name, or a generic such as `Pick<X, "a" \| "b">`.
|
|
6888
|
-
| `import` | `?string` | `null` | The path to import the clause's types from. Leave it out for a global type that needs no import.
|
|
6889
|
-
| `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). |
|
|
6890
7108
|
|
|
6891
7109
|
`#[TsExtends]` is repeatable, so you can stack as many as you need. You can put it on any of these:
|
|
6892
7110
|
|
|
@@ -6925,7 +7143,7 @@ export interface Warehouse
|
|
|
6925
7143
|
|
|
6926
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.
|
|
6927
7145
|
|
|
6928
|
-
`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.
|
|
6929
7147
|
|
|
6930
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.
|
|
6931
7149
|
|
|
@@ -7097,6 +7315,69 @@ The package applies these rules in order:
|
|
|
7097
7315
|
2. The same type name from the same path, across different `extends` clauses, gets one import statement.
|
|
7098
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<>`.
|
|
7099
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
|
+
|
|
7100
7381
|
### Configuration Reference
|
|
7101
7382
|
|
|
7102
7383
|
Each `ts_extends` key applies to one feature's interfaces:
|
|
@@ -7689,10 +7970,11 @@ With `inertia.enabled` on (the default), the package builds the file from your m
|
|
|
7689
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`.
|
|
7690
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.
|
|
7691
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.
|
|
7692
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.
|
|
7693
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.
|
|
7694
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`.
|
|
7695
|
-
- **`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()`.
|
|
7696
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.
|
|
7697
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).
|
|
7698
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.
|
|
@@ -7706,8 +7988,6 @@ The signed-in user is typed from the default guard only, so a named guard, such
|
|
|
7706
7988
|
|
|
7707
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[]`.
|
|
7708
7990
|
|
|
7709
|
-
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`.
|
|
7710
|
-
|
|
7711
7991
|
### Anatomy of the Generated File
|
|
7712
7992
|
|
|
7713
7993
|
Given this middleware:
|
|
@@ -8863,16 +9143,22 @@ export const store = annotateRequestPayload<StorePostRequest>()(
|
|
|
8863
9143
|
|
|
8864
9144
|
### Bundling
|
|
8865
9145
|
|
|
8866
|
-
A route nobody uses drops out of your bundle
|
|
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:
|
|
8867
9147
|
|
|
8868
9148
|
```typescript
|
|
8869
|
-
export const
|
|
8870
|
-
|
|
8871
|
-
|
|
8872
|
-
|
|
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
|
+
);
|
|
8873
9159
|
```
|
|
8874
9160
|
|
|
8875
|
-
The
|
|
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.
|
|
8876
9162
|
|
|
8877
9163
|
### Filtering & Excluding Routes
|
|
8878
9164
|
|
|
@@ -9382,6 +9668,8 @@ Inertia's `inertia-config.blade.php` and Vite env's `vite-env.blade.php` have no
|
|
|
9382
9668
|
|
|
9383
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.
|
|
9384
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
|
+
|
|
9385
9673
|
## Analyzer API
|
|
9386
9674
|
|
|
9387
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.
|
|
@@ -9433,7 +9721,7 @@ public function __construct(
|
|
|
9433
9721
|
|
|
9434
9722
|
Each property holds one part of the module you write:
|
|
9435
9723
|
|
|
9436
|
-
- **`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.
|
|
9437
9725
|
- **`typeImports`**: an `import path => list<name>` map of the types that the property types name. Write these as `import type` lines.
|
|
9438
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`.
|
|
9439
9727
|
|
|
@@ -9442,7 +9730,7 @@ Two classes that share an import path merge into one entry, so neither overwrite
|
|
|
9442
9730
|
The three properties agree with each other, so a module that renders all three as they are compiles:
|
|
9443
9731
|
|
|
9444
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.
|
|
9445
|
-
- **`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.
|
|
9446
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`.
|
|
9447
9735
|
|
|
9448
9736
|
#### Method Parameters
|
|
@@ -9467,7 +9755,7 @@ $result = resolve(AstEngine::class)->analyze(App\Http\Resources\PostResource::cl
|
|
|
9467
9755
|
|
|
9468
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.
|
|
9469
9757
|
|
|
9470
|
-
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.
|
|
9471
9759
|
|
|
9472
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()`.
|
|
9473
9761
|
|
|
@@ -9503,6 +9791,8 @@ For example, a `share()` whose docblock declares `filters?: array<string, string
|
|
|
9503
9791
|
|
|
9504
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.
|
|
9505
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
|
+
|
|
9506
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.
|
|
9507
9797
|
|
|
9508
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>`.
|
|
@@ -9625,18 +9915,19 @@ A config file published before model metadata existed has no `model_metadata` bl
|
|
|
9625
9915
|
|
|
9626
9916
|
### Resources (`resources.*`)
|
|
9627
9917
|
|
|
9628
|
-
| Config Key | Type | Default | Description
|
|
9629
|
-
| ---------------------------------- | -------- | ------------------------------ |
|
|
9630
|
-
| `resources.enabled` | `bool` | `true` | Enable or disable resource publishing
|
|
9631
|
-
| `resources.namespace` | `string` | `'resources'` | Not used. The global declaration file names each namespace after the class's PHP namespace, such as `app.http.resources`
|
|
9632
|
-
| `resources.template` | `string` | `laravel-ts-publish::resource` | Blade template for resource TypeScript output
|
|
9633
|
-
| `resources.
|
|
9634
|
-
| `resources.
|
|
9635
|
-
| `resources.
|
|
9636
|
-
| `resources.
|
|
9637
|
-
| `resources.
|
|
9638
|
-
| `resources.
|
|
9639
|
-
| `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 |
|
|
9640
9931
|
|
|
9641
9932
|
### Globals (`globals.*`)
|
|
9642
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/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/utils": "^1.
|
|
44
|
-
"@tolki/types": "^1.
|
|
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
|
},
|