id
int64
0
886
original_context
stringlengths
648
56.6k
modified_context
stringlengths
587
47.6k
omitted_context
sequencelengths
0
19
omitted_index
sequencelengths
0
19
metadata
dict
0
diff --git a/src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php b/src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php index 09fbf4829e7..25549425b7c 100644 --- a/src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php +++ b/src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php @@ -107,7 +107,7 @@ public function restoreModel($value) { return $this->getQueryForModelRestoration( (new $value->class)->setConnection($value->connection), $value->id - )->useWritePdo()->firstOrFail()->load($value->relations ?? []); + )->useWritePdo()->firstOrFail()->loadMissing($value->relations ?? []); } /** diff --git a/tests/Integration/Queue/ModelSerializationTest.php b/tests/Integration/Queue/ModelSerializationTest.php index bd3b401c657..e13cbb4ec29 100644 --- a/tests/Integration/Queue/ModelSerializationTest.php +++ b/tests/Integration/Queue/ModelSerializationTest.php @@ -31,6 +31,8 @@ protected function setUp(): void { parent::setUp(); + Model::preventLazyLoading(false); + Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('email'); @@ -161,6 +163,28 @@ public function testItReloadsRelationships() $this->assertEquals($unSerialized->order->getRelations(), $order->getRelations()); } + public function testItReloadsRelationshipsOnlyOnce() + { + $order = tap(ModelSerializationTestCustomOrder::create(), function (ModelSerializationTestCustomOrder $order) { + $order->wasRecentlyCreated = false; + }); + + $product1 = Product::create(); + $product2 = Product::create(); + + Line::create(['order_id' => $order->id, 'product_id' => $product1->id]); + Line::create(['order_id' => $order->id, 'product_id' => $product2->id]); + + $order->load('line', 'lines', 'products'); + + $this->expectsDatabaseQueryCount(4); + + $serialized = serialize(new ModelRelationSerializationTestClass($order)); + $unSerialized = unserialize($serialized); + + $this->assertEquals($unSerialized->order->getRelations(), $order->getRelations()); + } + public function testItReloadsNestedRelationships() { $order = tap(Order::create(), function (Order $order) { @@ -433,6 +457,29 @@ public function newCollection(array $models = []) } } +class ModelSerializationTestCustomOrder extends Model +{ + public $table = 'orders'; + public $guarded = []; + public $timestamps = false; + public $with = ['line', 'lines', 'products']; + + public function line() + { + return $this->hasOne(Line::class, 'order_id'); + } + + public function lines() + { + return $this->hasMany(Line::class, 'order_id'); + } + + public function products() + { + return $this->belongsToMany(Product::class, 'lines', 'order_id'); + } +} + class Order extends Model { public $guarded = [];
diff --git a/src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php b/src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php index 09fbf4829e7..25549425b7c 100644 --- a/src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php +++ b/src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php @@ -107,7 +107,7 @@ public function restoreModel($value) return $this->getQueryForModelRestoration( (new $value->class)->setConnection($value->connection), $value->id - )->useWritePdo()->firstOrFail()->load($value->relations ?? []); + )->useWritePdo()->firstOrFail()->loadMissing($value->relations ?? []); /** diff --git a/tests/Integration/Queue/ModelSerializationTest.php b/tests/Integration/Queue/ModelSerializationTest.php index bd3b401c657..e13cbb4ec29 100644 --- a/tests/Integration/Queue/ModelSerializationTest.php +++ b/tests/Integration/Queue/ModelSerializationTest.php @@ -31,6 +31,8 @@ protected function setUp(): void parent::setUp(); + Model::preventLazyLoading(false); Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('email'); @@ -161,6 +163,28 @@ public function testItReloadsRelationships() $this->assertEquals($unSerialized->order->getRelations(), $order->getRelations()); + public function testItReloadsRelationshipsOnlyOnce() + $order = tap(ModelSerializationTestCustomOrder::create(), function (ModelSerializationTestCustomOrder $order) { + $order->wasRecentlyCreated = false; + }); + $product1 = Product::create(); + $product2 = Product::create(); + Line::create(['order_id' => $order->id, 'product_id' => $product1->id]); + $order->load('line', 'lines', 'products'); + $this->expectsDatabaseQueryCount(4); + $unSerialized = unserialize($serialized); + $this->assertEquals($unSerialized->order->getRelations(), $order->getRelations()); public function testItReloadsNestedRelationships() $order = tap(Order::create(), function (Order $order) { @@ -433,6 +457,29 @@ public function newCollection(array $models = []) } +class ModelSerializationTestCustomOrder extends Model +{ + public $table = 'orders'; + public $guarded = []; + public $with = ['line', 'lines', 'products']; + public function line() + return $this->hasOne(Line::class, 'order_id'); + public function lines() + return $this->hasMany(Line::class, 'order_id'); + public function products() + return $this->belongsToMany(Product::class, 'lines', 'order_id'); +} class Order extends Model { public $guarded = [];
[ "+ Line::create(['order_id' => $order->id, 'product_id' => $product2->id]);", "+ $serialized = serialize(new ModelRelationSerializationTestClass($order));", "+ public $timestamps = false;" ]
[ 40, 46, 63 ]
{ "additions": 48, "author": "AndrewMast", "deletions": 1, "html_url": "https://github.com/laravel/framework/pull/55547", "issue_id": 55547, "merged_at": "2025-04-25T15:21:17Z", "omission_probability": 0.1, "pr_number": 55547, "repo": "laravel/framework", "title": "[12.x] Fix double query in model relation serialization", "total_changes": 49 }
1
diff --git a/src/Illuminate/Database/Eloquent/Collection.php b/src/Illuminate/Database/Eloquent/Collection.php index 05ec0d345a1..1c9dad35263 100755 --- a/src/Illuminate/Database/Eloquent/Collection.php +++ b/src/Illuminate/Database/Eloquent/Collection.php @@ -761,7 +761,7 @@ public function withRelationshipAutoloading() foreach ($this as $model) { if (! $model->hasRelationAutoloadCallback()) { - $model->autoloadRelationsUsing($callback); + $model->autoloadRelationsUsing($callback, $this); } } diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php index fc211e179a5..4b193d8d87a 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php @@ -46,6 +46,13 @@ trait HasRelationships */ protected $relationAutoloadCallback = null; + /** + * The relationship autoloader callback context. + * + * @var mixed + */ + protected $relationAutoloadContext = null; + /** * The many to many relationship methods. * @@ -118,10 +125,16 @@ public function hasRelationAutoloadCallback() */ public function autoloadRelationsUsing(Closure $callback, $context = null) { + // Prevent circular relation autoloading... + if ($context && $this->relationAutoloadContext === $context) { + return $this; + } + $this->relationAutoloadCallback = $callback; + $this->relationAutoloadContext = $context; foreach ($this->relations as $key => $value) { - $this->propagateRelationAutoloadCallbackToRelation($key, $value, $context); + $this->propagateRelationAutoloadCallbackToRelation($key, $value); } return $this; @@ -163,10 +176,9 @@ protected function invokeRelationAutoloadCallbackFor($key, $tuples) * * @param string $key * @param mixed $models - * @param mixed $context * @return void */ - protected function propagateRelationAutoloadCallbackToRelation($key, $models, $context = null) + protected function propagateRelationAutoloadCallbackToRelation($key, $models) { if (! $this->hasRelationAutoloadCallback() || ! $models) { return; @@ -183,10 +195,7 @@ protected function propagateRelationAutoloadCallbackToRelation($key, $models, $c $callback = fn (array $tuples) => $this->invokeRelationAutoloadCallbackFor($key, $tuples); foreach ($models as $model) { - // Check if relation autoload contexts are different to avoid circular relation autoload... - if ((is_null($context) || $context !== $model) && is_object($model) && method_exists($model, 'autoloadRelationsUsing')) { - $model->autoloadRelationsUsing($callback, $context); - } + $model->autoloadRelationsUsing($callback, $this->relationAutoloadContext); } } @@ -1111,7 +1120,7 @@ public function setRelation($relation, $value) { $this->relations[$relation] = $value; - $this->propagateRelationAutoloadCallbackToRelation($relation, $value, $this); + $this->propagateRelationAutoloadCallbackToRelation($relation, $value); return $this; } diff --git a/tests/Integration/Database/EloquentModelRelationAutoloadTest.php b/tests/Integration/Database/EloquentModelRelationAutoloadTest.php index a3f8a5f882f..03f1d7ca611 100644 --- a/tests/Integration/Database/EloquentModelRelationAutoloadTest.php +++ b/tests/Integration/Database/EloquentModelRelationAutoloadTest.php @@ -61,6 +61,8 @@ public function testRelationAutoloadForCollection() $this->assertCount(2, DB::getQueryLog()); $this->assertCount(3, $likes); $this->assertTrue($posts[0]->comments[0]->relationLoaded('likes')); + + DB::disableQueryLog(); } public function testRelationAutoloadForSingleModel() @@ -84,6 +86,8 @@ public function testRelationAutoloadForSingleModel() $this->assertCount(2, DB::getQueryLog()); $this->assertCount(2, $likes); $this->assertTrue($post->comments[0]->relationLoaded('likes')); + + DB::disableQueryLog(); } public function testRelationAutoloadWithSerialization() @@ -109,6 +113,50 @@ public function testRelationAutoloadWithSerialization() $this->assertCount(2, DB::getQueryLog()); Model::automaticallyEagerLoadRelationships(false); + + DB::disableQueryLog(); + } + + public function testRelationAutoloadWithCircularRelations() + { + $post = Post::create(); + $comment1 = $post->comments()->create(['parent_id' => null]); + $comment2 = $post->comments()->create(['parent_id' => $comment1->id]); + $post->likes()->create(); + + DB::enableQueryLog(); + + $post->withRelationshipAutoloading(); + $comment = $post->comments->first(); + $comment->setRelation('post', $post); + + $this->assertCount(1, $post->likes); + + $this->assertCount(2, DB::getQueryLog()); + + DB::disableQueryLog(); + } + + public function testRelationAutoloadWithChaperoneRelations() + { + Model::automaticallyEagerLoadRelationships(); + + $post = Post::create(); + $comment1 = $post->comments()->create(['parent_id' => null]); + $comment2 = $post->comments()->create(['parent_id' => $comment1->id]); + $post->likes()->create(); + + DB::enableQueryLog(); + + $post->load('commentsWithChaperone'); + + $this->assertCount(1, $post->likes); + + $this->assertCount(2, DB::getQueryLog()); + + Model::automaticallyEagerLoadRelationships(false); + + DB::disableQueryLog(); } public function testRelationAutoloadVariousNestedMorphRelations() @@ -163,6 +211,8 @@ public function testRelationAutoloadVariousNestedMorphRelations() $this->assertCount(2, $videos); $this->assertTrue($videoLike->relationLoaded('likeable')); $this->assertTrue($videoLike->likeable->relationLoaded('commentable')); + + DB::disableQueryLog(); } } @@ -197,6 +247,11 @@ public function comments() return $this->morphMany(Comment::class, 'commentable'); } + public function commentsWithChaperone() + { + return $this->morphMany(Comment::class, 'commentable')->chaperone(); + } + public function likes() { return $this->morphMany(Like::class, 'likeable');
diff --git a/src/Illuminate/Database/Eloquent/Collection.php b/src/Illuminate/Database/Eloquent/Collection.php index 05ec0d345a1..1c9dad35263 100755 --- a/src/Illuminate/Database/Eloquent/Collection.php +++ b/src/Illuminate/Database/Eloquent/Collection.php @@ -761,7 +761,7 @@ public function withRelationshipAutoloading() foreach ($this as $model) { if (! $model->hasRelationAutoloadCallback()) { } diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php index fc211e179a5..4b193d8d87a 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php @@ -46,6 +46,13 @@ trait HasRelationships protected $relationAutoloadCallback = null; + /** + * The relationship autoloader callback context. + * + * @var mixed + */ + protected $relationAutoloadContext = null; /** * The many to many relationship methods. @@ -118,10 +125,16 @@ public function hasRelationAutoloadCallback() public function autoloadRelationsUsing(Closure $callback, $context = null) + // Prevent circular relation autoloading... + if ($context && $this->relationAutoloadContext === $context) { + return $this; $this->relationAutoloadCallback = $callback; + $this->relationAutoloadContext = $context; foreach ($this->relations as $key => $value) { - $this->propagateRelationAutoloadCallbackToRelation($key, $value, $context); + $this->propagateRelationAutoloadCallbackToRelation($key, $value); @@ -163,10 +176,9 @@ protected function invokeRelationAutoloadCallbackFor($key, $tuples) * @param string $key * @param mixed $models - * @param mixed $context * @return void - protected function propagateRelationAutoloadCallbackToRelation($key, $models, $context = null) + protected function propagateRelationAutoloadCallbackToRelation($key, $models) if (! $this->hasRelationAutoloadCallback() || ! $models) { return; @@ -183,10 +195,7 @@ protected function propagateRelationAutoloadCallbackToRelation($key, $models, $c $callback = fn (array $tuples) => $this->invokeRelationAutoloadCallbackFor($key, $tuples); foreach ($models as $model) { - // Check if relation autoload contexts are different to avoid circular relation autoload... - if ((is_null($context) || $context !== $model) && is_object($model) && method_exists($model, 'autoloadRelationsUsing')) { - $model->autoloadRelationsUsing($callback, $context); - } + $model->autoloadRelationsUsing($callback, $this->relationAutoloadContext); @@ -1111,7 +1120,7 @@ public function setRelation($relation, $value) $this->relations[$relation] = $value; - $this->propagateRelationAutoloadCallbackToRelation($relation, $value, $this); + $this->propagateRelationAutoloadCallbackToRelation($relation, $value); diff --git a/tests/Integration/Database/EloquentModelRelationAutoloadTest.php b/tests/Integration/Database/EloquentModelRelationAutoloadTest.php index a3f8a5f882f..03f1d7ca611 100644 --- a/tests/Integration/Database/EloquentModelRelationAutoloadTest.php +++ b/tests/Integration/Database/EloquentModelRelationAutoloadTest.php @@ -61,6 +61,8 @@ public function testRelationAutoloadForCollection() $this->assertCount(3, $likes); $this->assertTrue($posts[0]->comments[0]->relationLoaded('likes')); public function testRelationAutoloadForSingleModel() @@ -84,6 +86,8 @@ public function testRelationAutoloadForSingleModel() $this->assertCount(2, $likes); $this->assertTrue($post->comments[0]->relationLoaded('likes')); public function testRelationAutoloadWithSerialization() @@ -109,6 +113,50 @@ public function testRelationAutoloadWithSerialization() Model::automaticallyEagerLoadRelationships(false); + public function testRelationAutoloadWithCircularRelations() + $post->withRelationshipAutoloading(); + $comment = $post->comments->first(); + $comment->setRelation('post', $post); + public function testRelationAutoloadWithChaperoneRelations() + Model::automaticallyEagerLoadRelationships(); + $post->load('commentsWithChaperone'); + Model::automaticallyEagerLoadRelationships(false); public function testRelationAutoloadVariousNestedMorphRelations() @@ -163,6 +211,8 @@ public function testRelationAutoloadVariousNestedMorphRelations() $this->assertCount(2, $videos); $this->assertTrue($videoLike->relationLoaded('likeable')); $this->assertTrue($videoLike->likeable->relationLoaded('commentable')); } @@ -197,6 +247,11 @@ public function comments() return $this->morphMany(Comment::class, 'commentable'); + public function commentsWithChaperone() + return $this->morphMany(Comment::class, 'commentable')->chaperone(); public function likes() return $this->morphMany(Like::class, 'likeable');
[ "- $model->autoloadRelationsUsing($callback);", "+ $model->autoloadRelationsUsing($callback, $this);", "+ }" ]
[ 8, 9, 38 ]
{ "additions": 73, "author": "litvinchuk", "deletions": 9, "html_url": "https://github.com/laravel/framework/pull/55542", "issue_id": 55542, "merged_at": "2025-04-25T15:59:34Z", "omission_probability": 0.1, "pr_number": 55542, "repo": "laravel/framework", "title": "[12.x] Improve circular relation check in Automatic Relation Loading", "total_changes": 82 }
2
diff --git a/src/Illuminate/Database/Eloquent/Factories/BelongsToManyRelationship.php b/src/Illuminate/Database/Eloquent/Factories/BelongsToManyRelationship.php index da004c83bc74..fd350e6fce6c 100644 --- a/src/Illuminate/Database/Eloquent/Factories/BelongsToManyRelationship.php +++ b/src/Illuminate/Database/Eloquent/Factories/BelongsToManyRelationship.php @@ -50,7 +50,9 @@ public function __construct($factory, $pivot, $relationship) */ public function createFor(Model $model) { - Collection::wrap($this->factory instanceof Factory ? $this->factory->create([], $model) : $this->factory)->each(function ($attachable) use ($model) { + $relationship = $model->{$this->relationship}(); + + Collection::wrap($this->factory instanceof Factory ? $this->factory->prependState($relationship->getQuery()->pendingAttributes)->create([], $model) : $this->factory)->each(function ($attachable) use ($model) { $model->{$this->relationship}()->attach( $attachable, is_callable($this->pivot) ? call_user_func($this->pivot, $model) : $this->pivot diff --git a/src/Illuminate/Database/Eloquent/Factories/Factory.php b/src/Illuminate/Database/Eloquent/Factories/Factory.php index ffe9018e67f0..a52d840f421e 100644 --- a/src/Illuminate/Database/Eloquent/Factories/Factory.php +++ b/src/Illuminate/Database/Eloquent/Factories/Factory.php @@ -530,6 +530,21 @@ public function state($state) ]); } + /** + * Prepend a new state transformation to the model definition. + * + * @param (callable(array<string, mixed>, TModel|null): array<string, mixed>)|array<string, mixed> $state + * @return static + */ + public function prependState($state) + { + return $this->newInstance([ + 'states' => $this->states->prepend( + is_callable($state) ? $state : fn () => $state, + ), + ]); + } + /** * Set a single model attribute. * diff --git a/src/Illuminate/Database/Eloquent/Factories/Relationship.php b/src/Illuminate/Database/Eloquent/Factories/Relationship.php index 4024f1c929c0..e23bc99d78b0 100644 --- a/src/Illuminate/Database/Eloquent/Factories/Relationship.php +++ b/src/Illuminate/Database/Eloquent/Factories/Relationship.php @@ -49,13 +49,15 @@ public function createFor(Model $parent) $this->factory->state([ $relationship->getMorphType() => $relationship->getMorphClass(), $relationship->getForeignKeyName() => $relationship->getParentKey(), - ])->create([], $parent); + ])->prependState($relationship->getQuery()->pendingAttributes)->create([], $parent); } elseif ($relationship instanceof HasOneOrMany) { $this->factory->state([ $relationship->getForeignKeyName() => $relationship->getParentKey(), - ])->create([], $parent); + ])->prependState($relationship->getQuery()->pendingAttributes)->create([], $parent); } elseif ($relationship instanceof BelongsToMany) { - $relationship->attach($this->factory->create([], $parent)); + $relationship->attach( + $this->factory->prependState($relationship->getQuery()->pendingAttributes)->create([], $parent) + ); } } diff --git a/tests/Database/DatabaseEloquentFactoryTest.php b/tests/Database/DatabaseEloquentFactoryTest.php index b0860d236b03..da5467794d77 100644 --- a/tests/Database/DatabaseEloquentFactoryTest.php +++ b/tests/Database/DatabaseEloquentFactoryTest.php @@ -850,6 +850,62 @@ public function test_factory_global_model_resolver() $this->assertEquals(FactoryTestGuessModelFactory::new()->modelName(), FactoryTestGuessModel::class); } + public function test_factory_model_has_many_relationship_has_pending_attributes() + { + FactoryTestUser::factory()->has(new FactoryTestPostFactory(), 'postsWithFooBarBazAsTitle')->create(); + + $this->assertEquals('foo bar baz', FactoryTestPost::first()->title); + } + + public function test_factory_model_has_many_relationship_has_pending_attributes_override() + { + FactoryTestUser::factory()->has((new FactoryTestPostFactory())->state(['title' => 'other title']), 'postsWithFooBarBazAsTitle')->create(); + + $this->assertEquals('other title', FactoryTestPost::first()->title); + } + + public function test_factory_model_has_one_relationship_has_pending_attributes() + { + FactoryTestUser::factory()->has(new FactoryTestPostFactory(), 'postWithFooBarBazAsTitle')->create(); + + $this->assertEquals('foo bar baz', FactoryTestPost::first()->title); + } + + public function test_factory_model_has_one_relationship_has_pending_attributes_override() + { + FactoryTestUser::factory()->has((new FactoryTestPostFactory())->state(['title' => 'other title']), 'postWithFooBarBazAsTitle')->create(); + + $this->assertEquals('other title', FactoryTestPost::first()->title); + } + + public function test_factory_model_belongs_to_many_relationship_has_pending_attributes() + { + FactoryTestUser::factory()->has(new FactoryTestRoleFactory(), 'rolesWithFooBarBazAsName')->create(); + + $this->assertEquals('foo bar baz', FactoryTestRole::first()->name); + } + + public function test_factory_model_belongs_to_many_relationship_has_pending_attributes_override() + { + FactoryTestUser::factory()->has((new FactoryTestRoleFactory())->state(['name' => 'other name']), 'rolesWithFooBarBazAsName')->create(); + + $this->assertEquals('other name', FactoryTestRole::first()->name); + } + + public function test_factory_model_morph_many_relationship_has_pending_attributes() + { + (new FactoryTestPostFactory())->has(new FactoryTestCommentFactory(), 'commentsWithFooBarBazAsBody')->create(); + + $this->assertEquals('foo bar baz', FactoryTestComment::first()->body); + } + + public function test_factory_model_morph_many_relationship_has_pending_attributes_override() + { + (new FactoryTestPostFactory())->has((new FactoryTestCommentFactory())->state(['body' => 'other body']), 'commentsWithFooBarBazAsBody')->create(); + + $this->assertEquals('other body', FactoryTestComment::first()->body); + } + /** * Get a database connection instance. * @@ -895,11 +951,26 @@ public function posts() return $this->hasMany(FactoryTestPost::class, 'user_id'); } + public function postsWithFooBarBazAsTitle() + { + return $this->hasMany(FactoryTestPost::class, 'user_id')->withAttributes(['title' => 'foo bar baz']); + } + + public function postWithFooBarBazAsTitle() + { + return $this->hasOne(FactoryTestPost::class, 'user_id')->withAttributes(['title' => 'foo bar baz']); + } + public function roles() { return $this->belongsToMany(FactoryTestRole::class, 'role_user', 'user_id', 'role_id')->withPivot('admin'); } + public function rolesWithFooBarBazAsName() + { + return $this->belongsToMany(FactoryTestRole::class, 'role_user', 'user_id', 'role_id')->withPivot('admin')->withAttributes(['name' => 'foo bar baz']); + } + public function factoryTestRoles() { return $this->belongsToMany(FactoryTestRole::class, 'role_user', 'user_id', 'role_id')->withPivot('admin'); @@ -944,6 +1015,11 @@ public function comments() { return $this->morphMany(FactoryTestComment::class, 'commentable'); } + + public function commentsWithFooBarBazAsBody() + { + return $this->morphMany(FactoryTestComment::class, 'commentable')->withAttributes(['body' => 'foo bar baz']); + } } class FactoryTestCommentFactory extends Factory
diff --git a/src/Illuminate/Database/Eloquent/Factories/BelongsToManyRelationship.php b/src/Illuminate/Database/Eloquent/Factories/BelongsToManyRelationship.php index da004c83bc74..fd350e6fce6c 100644 --- a/src/Illuminate/Database/Eloquent/Factories/BelongsToManyRelationship.php +++ b/src/Illuminate/Database/Eloquent/Factories/BelongsToManyRelationship.php @@ -50,7 +50,9 @@ public function __construct($factory, $pivot, $relationship) */ public function createFor(Model $model) - Collection::wrap($this->factory instanceof Factory ? $this->factory->create([], $model) : $this->factory)->each(function ($attachable) use ($model) { + $relationship = $model->{$this->relationship}(); + Collection::wrap($this->factory instanceof Factory ? $this->factory->prependState($relationship->getQuery()->pendingAttributes)->create([], $model) : $this->factory)->each(function ($attachable) use ($model) { $model->{$this->relationship}()->attach( $attachable, is_callable($this->pivot) ? call_user_func($this->pivot, $model) : $this->pivot diff --git a/src/Illuminate/Database/Eloquent/Factories/Factory.php b/src/Illuminate/Database/Eloquent/Factories/Factory.php index ffe9018e67f0..a52d840f421e 100644 --- a/src/Illuminate/Database/Eloquent/Factories/Factory.php +++ b/src/Illuminate/Database/Eloquent/Factories/Factory.php @@ -530,6 +530,21 @@ public function state($state) ]); + /** + * Prepend a new state transformation to the model definition. + * + * @param (callable(array<string, mixed>, TModel|null): array<string, mixed>)|array<string, mixed> $state + * @return static + */ + public function prependState($state) + return $this->newInstance([ + is_callable($state) ? $state : fn () => $state, + ), + ]); * Set a single model attribute. diff --git a/src/Illuminate/Database/Eloquent/Factories/Relationship.php b/src/Illuminate/Database/Eloquent/Factories/Relationship.php index 4024f1c929c0..e23bc99d78b0 100644 --- a/src/Illuminate/Database/Eloquent/Factories/Relationship.php +++ b/src/Illuminate/Database/Eloquent/Factories/Relationship.php @@ -49,13 +49,15 @@ public function createFor(Model $parent) $relationship->getMorphType() => $relationship->getMorphClass(), } elseif ($relationship instanceof HasOneOrMany) { } elseif ($relationship instanceof BelongsToMany) { - $relationship->attach($this->factory->create([], $parent)); + $relationship->attach( + $this->factory->prependState($relationship->getQuery()->pendingAttributes)->create([], $parent) + ); } diff --git a/tests/Database/DatabaseEloquentFactoryTest.php b/tests/Database/DatabaseEloquentFactoryTest.php index b0860d236b03..da5467794d77 100644 --- a/tests/Database/DatabaseEloquentFactoryTest.php +++ b/tests/Database/DatabaseEloquentFactoryTest.php @@ -850,6 +850,62 @@ public function test_factory_global_model_resolver() $this->assertEquals(FactoryTestGuessModelFactory::new()->modelName(), FactoryTestGuessModel::class); + public function test_factory_model_has_many_relationship_has_pending_attributes() + FactoryTestUser::factory()->has(new FactoryTestPostFactory(), 'postsWithFooBarBazAsTitle')->create(); + public function test_factory_model_has_many_relationship_has_pending_attributes_override() + FactoryTestUser::factory()->has((new FactoryTestPostFactory())->state(['title' => 'other title']), 'postsWithFooBarBazAsTitle')->create(); + public function test_factory_model_has_one_relationship_has_pending_attributes() + FactoryTestUser::factory()->has(new FactoryTestPostFactory(), 'postWithFooBarBazAsTitle')->create(); + FactoryTestUser::factory()->has((new FactoryTestPostFactory())->state(['title' => 'other title']), 'postWithFooBarBazAsTitle')->create(); + public function test_factory_model_belongs_to_many_relationship_has_pending_attributes() + FactoryTestUser::factory()->has(new FactoryTestRoleFactory(), 'rolesWithFooBarBazAsName')->create(); + $this->assertEquals('foo bar baz', FactoryTestRole::first()->name); + public function test_factory_model_belongs_to_many_relationship_has_pending_attributes_override() + FactoryTestUser::factory()->has((new FactoryTestRoleFactory())->state(['name' => 'other name']), 'rolesWithFooBarBazAsName')->create(); + $this->assertEquals('other name', FactoryTestRole::first()->name); + public function test_factory_model_morph_many_relationship_has_pending_attributes() + $this->assertEquals('foo bar baz', FactoryTestComment::first()->body); + public function test_factory_model_morph_many_relationship_has_pending_attributes_override() + $this->assertEquals('other body', FactoryTestComment::first()->body); * Get a database connection instance. @@ -895,11 +951,26 @@ public function posts() return $this->hasMany(FactoryTestPost::class, 'user_id'); + public function postsWithFooBarBazAsTitle() + return $this->hasMany(FactoryTestPost::class, 'user_id')->withAttributes(['title' => 'foo bar baz']); + public function postWithFooBarBazAsTitle() public function roles() + public function rolesWithFooBarBazAsName() + return $this->belongsToMany(FactoryTestRole::class, 'role_user', 'user_id', 'role_id')->withPivot('admin')->withAttributes(['name' => 'foo bar baz']); public function factoryTestRoles() @@ -944,6 +1015,11 @@ public function comments() return $this->morphMany(FactoryTestComment::class, 'commentable'); + public function commentsWithFooBarBazAsBody() + return $this->morphMany(FactoryTestComment::class, 'commentable')->withAttributes(['body' => 'foo bar baz']); } class FactoryTestCommentFactory extends Factory
[ "+ 'states' => $this->states->prepend(", "+ public function test_factory_model_has_one_relationship_has_pending_attributes_override()", "+ (new FactoryTestPostFactory())->has(new FactoryTestCommentFactory(), 'commentsWithFooBarBazAsBody')->create();", "+ (new FactoryTestPostFactory())->has((new FactoryTestCommentFactory())->state(['body' => 'other body']), 'commentsWithFooBarBazAsBody')->create();", "+ return $this->hasOne(FactoryTestPost::class, 'user_id')->withAttributes(['title' => 'foo bar baz']);" ]
[ 32, 93, 116, 123, 142 ]
{ "additions": 99, "author": "gdebrauwer", "deletions": 4, "html_url": "https://github.com/laravel/framework/pull/55558", "issue_id": 55558, "merged_at": "2025-04-25T15:08:46Z", "omission_probability": 0.1, "pr_number": 55558, "repo": "laravel/framework", "title": "[12.x] Use pendingAttributes of relationships when creating relationship models via model factories", "total_changes": 103 }
3
diff --git a/src/Illuminate/Mail/resources/views/html/panel.blade.php b/src/Illuminate/Mail/resources/views/html/panel.blade.php index 812db7c08e77..2975a60a021e 100644 --- a/src/Illuminate/Mail/resources/views/html/panel.blade.php +++ b/src/Illuminate/Mail/resources/views/html/panel.blade.php @@ -4,7 +4,7 @@ <table width="100%" cellpadding="0" cellspacing="0" role="presentation"> <tr> <td class="panel-item"> -{!! Illuminate\Mail\Markdown::parse($slot) !!} +{{ Illuminate\Mail\Markdown::parse($slot) }} </td> </tr> </table> diff --git a/src/Illuminate/Support/EncodedHtmlString.php b/src/Illuminate/Support/EncodedHtmlString.php index 18928e75b633..a25115740277 100644 --- a/src/Illuminate/Support/EncodedHtmlString.php +++ b/src/Illuminate/Support/EncodedHtmlString.php @@ -2,8 +2,19 @@ namespace Illuminate\Support; +use BackedEnum; +use Illuminate\Contracts\Support\DeferringDisplayableValue; +use Illuminate\Contracts\Support\Htmlable; + class EncodedHtmlString extends HtmlString { + /** + * The HTML string. + * + * @var \Illuminate\Contracts\Support\DeferringDisplayableValue|\Illuminate\Contracts\Support\Htmlable|\BackedEnum|string|int|float|null + */ + protected $html; + /** * The callback that should be used to encode the HTML strings. * @@ -14,7 +25,7 @@ class EncodedHtmlString extends HtmlString /** * Create a new encoded HTML string instance. * - * @param string $html + * @param \Illuminate\Contracts\Support\DeferringDisplayableValue|\Illuminate\Contracts\Support\Htmlable|\BackedEnum|string|int|float|null $html * @param bool $doubleEncode * @return void */ @@ -48,9 +59,23 @@ public static function convert($value, bool $withQuote = true, bool $doubleEncod #[\Override] public function toHtml() { + $value = $this->html; + + if ($value instanceof DeferringDisplayableValue) { + $value = $value->resolveDisplayableValue(); + } + + if ($value instanceof Htmlable) { + return $value->toHtml(); + } + + if ($value instanceof BackedEnum) { + $value = $value->value; + } + return (static::$encodeUsingFactory ?? function ($value, $doubleEncode) { return static::convert($value, doubleEncode: $doubleEncode); - })($this->html, $this->doubleEncode); + })($value, $this->doubleEncode); } /** diff --git a/tests/Integration/Mail/Fixtures/table-with-template.blade.php b/tests/Integration/Mail/Fixtures/table-with-template.blade.php new file mode 100644 index 000000000000..3a4ec4c6260e --- /dev/null +++ b/tests/Integration/Mail/Fixtures/table-with-template.blade.php @@ -0,0 +1,12 @@ +<x-mail::message subcopy="This is a subcopy"> + +<x-mail::table> +*Hi* {{ $user->name }} + +| Laravel | Table | Example | +| ------------- | :-----------: | ------------: | +| Col 2 is | Centered | $10 | +| Col 3 is | Right-Aligned | $20 | +</x-mail::table> + +</x-mail::message> diff --git a/tests/Integration/Mail/MailableWithSecuredEncodingTest.php b/tests/Integration/Mail/MailableWithSecuredEncodingTest.php index a84fd487c20d..9feb03886335 100644 --- a/tests/Integration/Mail/MailableWithSecuredEncodingTest.php +++ b/tests/Integration/Mail/MailableWithSecuredEncodingTest.php @@ -116,6 +116,56 @@ public function build() $mailable->assertSeeInHtml($expected, false); } + #[WithMigration] + #[DataProvider('markdownEncodedTemplateDataProvider')] + public function testItCanAssertMarkdownEncodedStringUsingTemplateWithTable($given, $expected) + { + $user = UserFactory::new()->create([ + 'name' => $given, + ]); + + $mailable = new class($user) extends Mailable + { + public $theme = 'taylor'; + + public function __construct(public User $user) + { + // + } + + public function build() + { + return $this->markdown('table-with-template'); + } + }; + + $mailable->assertSeeInHtml($expected, false); + $mailable->assertSeeInHtml('<p>This is a subcopy</p>', false); + $mailable->assertSeeInHtml(<<<'TABLE' +<table> +<thead> +<tr> +<th>Laravel</th> +<th align="center">Table</th> +<th align="right">Example</th> +</tr> +</thead> +<tbody> +<tr> +<td>Col 2 is</td> +<td align="center">Centered</td> +<td align="right">$10</td> +</tr> +<tr> +<td>Col 3 is</td> +<td align="center">Right-Aligned</td> +<td align="right">$20</td> +</tr> +</tbody> +</table> +TABLE, false); + } + public static function markdownEncodedTemplateDataProvider() { yield ['[Laravel](https://laravel.com)', '<em>Hi</em> [Laravel](https://laravel.com)']; diff --git a/tests/Integration/Mail/MailableWithoutSecuredEncodingTest.php b/tests/Integration/Mail/MailableWithoutSecuredEncodingTest.php index 52db775cefae..aea392c520ca 100644 --- a/tests/Integration/Mail/MailableWithoutSecuredEncodingTest.php +++ b/tests/Integration/Mail/MailableWithoutSecuredEncodingTest.php @@ -116,6 +116,56 @@ public function build() $mailable->assertSeeInHtml($expected, false); } + #[WithMigration] + #[DataProvider('markdownEncodedTemplateDataProvider')] + public function testItCanAssertMarkdownEncodedStringUsingTemplateWithTable($given, $expected) + { + $user = UserFactory::new()->create([ + 'name' => $given, + ]); + + $mailable = new class($user) extends Mailable + { + public $theme = 'taylor'; + + public function __construct(public User $user) + { + // + } + + public function build() + { + return $this->markdown('table-with-template'); + } + }; + + $mailable->assertSeeInHtml($expected, false); + $mailable->assertSeeInHtml('<p>This is a subcopy</p>', false); + $mailable->assertSeeInHtml(<<<'TABLE' +<table> +<thead> +<tr> +<th>Laravel</th> +<th align="center">Table</th> +<th align="right">Example</th> +</tr> +</thead> +<tbody> +<tr> +<td>Col 2 is</td> +<td align="center">Centered</td> +<td align="right">$10</td> +</tr> +<tr> +<td>Col 3 is</td> +<td align="center">Right-Aligned</td> +<td align="right">$20</td> +</tr> +</tbody> +</table> +TABLE, false); + } + public static function markdownEncodedTemplateDataProvider() { yield ['[Laravel](https://laravel.com)', '<p><em>Hi</em> <a href="https://laravel.com">Laravel</a></p>']; diff --git a/tests/Integration/Mail/MarkdownParserTest.php b/tests/Integration/Mail/MarkdownParserTest.php index 7ff74ae21eb3..16910e79fd18 100644 --- a/tests/Integration/Mail/MarkdownParserTest.php +++ b/tests/Integration/Mail/MarkdownParserTest.php @@ -76,6 +76,11 @@ public static function markdownEncodedDataProvider() '<p>Visit &lt;span&gt;https://laravel.com/docs&lt;/span&gt; to browse the documentation</p>', ]; + yield [ + new EncodedHtmlString(new HtmlString('Visit <span>https://laravel.com/docs</span> to browse the documentation')), + '<p>Visit <span>https://laravel.com/docs</span> to browse the documentation</p>', + ]; + yield [ '![Welcome to Laravel](https://laravel.com/assets/img/welcome/background.svg)<br />'.new EncodedHtmlString('Visit <span>https://laravel.com/docs</span> to browse the documentation'), '<p><img src="https://laravel.com/assets/img/welcome/background.svg" alt="Welcome to Laravel" /><br />Visit &lt;span&gt;https://laravel.com/docs&lt;/span&gt; to browse the documentation</p>',
diff --git a/src/Illuminate/Mail/resources/views/html/panel.blade.php b/src/Illuminate/Mail/resources/views/html/panel.blade.php index 812db7c08e77..2975a60a021e 100644 --- a/src/Illuminate/Mail/resources/views/html/panel.blade.php +++ b/src/Illuminate/Mail/resources/views/html/panel.blade.php @@ -4,7 +4,7 @@ <table width="100%" cellpadding="0" cellspacing="0" role="presentation"> <tr> <td class="panel-item"> -{!! Illuminate\Mail\Markdown::parse($slot) !!} +{{ Illuminate\Mail\Markdown::parse($slot) }} </td> </tr> </table> diff --git a/src/Illuminate/Support/EncodedHtmlString.php b/src/Illuminate/Support/EncodedHtmlString.php index 18928e75b633..a25115740277 100644 --- a/src/Illuminate/Support/EncodedHtmlString.php +++ b/src/Illuminate/Support/EncodedHtmlString.php @@ -2,8 +2,19 @@ namespace Illuminate\Support; +use BackedEnum; +use Illuminate\Contracts\Support\DeferringDisplayableValue; +use Illuminate\Contracts\Support\Htmlable; class EncodedHtmlString extends HtmlString { + /** + * The HTML string. + * + * @var \Illuminate\Contracts\Support\DeferringDisplayableValue|\Illuminate\Contracts\Support\Htmlable|\BackedEnum|string|int|float|null + */ * The callback that should be used to encode the HTML strings. @@ -14,7 +25,7 @@ class EncodedHtmlString extends HtmlString * Create a new encoded HTML string instance. - * @param string $html + * @param \Illuminate\Contracts\Support\DeferringDisplayableValue|\Illuminate\Contracts\Support\Htmlable|\BackedEnum|string|int|float|null $html * @param bool $doubleEncode * @return void */ @@ -48,9 +59,23 @@ public static function convert($value, bool $withQuote = true, bool $doubleEncod #[\Override] public function toHtml() + $value = $this->html; + if ($value instanceof DeferringDisplayableValue) { + $value = $value->resolveDisplayableValue(); + if ($value instanceof Htmlable) { + return $value->toHtml(); + if ($value instanceof BackedEnum) { + $value = $value->value; return (static::$encodeUsingFactory ?? function ($value, $doubleEncode) { return static::convert($value, doubleEncode: $doubleEncode); - })($this->html, $this->doubleEncode); + })($value, $this->doubleEncode); diff --git a/tests/Integration/Mail/Fixtures/table-with-template.blade.php b/tests/Integration/Mail/Fixtures/table-with-template.blade.php new file mode 100644 index 000000000000..3a4ec4c6260e --- /dev/null +++ b/tests/Integration/Mail/Fixtures/table-with-template.blade.php @@ -0,0 +1,12 @@ +<x-mail::message subcopy="This is a subcopy"> +<x-mail::table> +*Hi* {{ $user->name }} +| ------------- | :-----------: | ------------: | +| Col 2 is | Centered | $10 | +| Col 3 is | Right-Aligned | $20 | +</x-mail::table> +</x-mail::message> diff --git a/tests/Integration/Mail/MailableWithSecuredEncodingTest.php b/tests/Integration/Mail/MailableWithSecuredEncodingTest.php index a84fd487c20d..9feb03886335 100644 --- a/tests/Integration/Mail/MailableWithSecuredEncodingTest.php +++ b/tests/Integration/Mail/MailableWithSecuredEncodingTest.php yield ['[Laravel](https://laravel.com)', '<em>Hi</em> [Laravel](https://laravel.com)']; diff --git a/tests/Integration/Mail/MailableWithoutSecuredEncodingTest.php b/tests/Integration/Mail/MailableWithoutSecuredEncodingTest.php index 52db775cefae..aea392c520ca 100644 --- a/tests/Integration/Mail/MailableWithoutSecuredEncodingTest.php +++ b/tests/Integration/Mail/MailableWithoutSecuredEncodingTest.php yield ['[Laravel](https://laravel.com)', '<p><em>Hi</em> <a href="https://laravel.com">Laravel</a></p>']; diff --git a/tests/Integration/Mail/MarkdownParserTest.php b/tests/Integration/Mail/MarkdownParserTest.php index 7ff74ae21eb3..16910e79fd18 100644 --- a/tests/Integration/Mail/MarkdownParserTest.php +++ b/tests/Integration/Mail/MarkdownParserTest.php @@ -76,6 +76,11 @@ public static function markdownEncodedDataProvider() '<p>Visit &lt;span&gt;https://laravel.com/docs&lt;/span&gt; to browse the documentation</p>', ]; + yield [ + new EncodedHtmlString(new HtmlString('Visit <span>https://laravel.com/docs</span> to browse the documentation')), + '<p>Visit <span>https://laravel.com/docs</span> to browse the documentation</p>', + ]; yield [ '![Welcome to Laravel](https://laravel.com/assets/img/welcome/background.svg)<br />'.new EncodedHtmlString('Visit <span>https://laravel.com/docs</span> to browse the documentation'), '<p><img src="https://laravel.com/assets/img/welcome/background.svg" alt="Welcome to Laravel" /><br />Visit &lt;span&gt;https://laravel.com/docs&lt;/span&gt; to browse the documentation</p>',
[ "+ protected $html;", "+| Laravel | Table | Example |" ]
[ 32, 82 ]
{ "additions": 145, "author": "jbraband", "deletions": 3, "html_url": "https://github.com/laravel/framework/pull/55543", "issue_id": 55543, "merged_at": "2025-04-25T08:31:51Z", "omission_probability": 0.1, "pr_number": 55543, "repo": "laravel/framework", "title": "[11.x] Fix `EncodedHtmlString` to ignore instance of `HtmlString`", "total_changes": 148 }
4
diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php index fc211e179a5..b27b7110909 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php @@ -1088,7 +1088,11 @@ public function relationLoaded($key) if ($nestedRelation !== null) { $relatedModels = is_iterable($relatedModels = $this->$relation) ? $relatedModels - : [$relatedModels]; + : array_filter([$relatedModels]); + + if (count($relatedModels) === 0) { + return false; + } foreach ($relatedModels as $related) { if (! $related->relationLoaded($nestedRelation)) { diff --git a/tests/Integration/Database/EloquentModelRelationLoadedTest.php b/tests/Integration/Database/EloquentModelRelationLoadedTest.php index 548a50d1195..265926d9cd4 100644 --- a/tests/Integration/Database/EloquentModelRelationLoadedTest.php +++ b/tests/Integration/Database/EloquentModelRelationLoadedTest.php @@ -135,6 +135,21 @@ public function testWhenParentRelationIsASingleInstance() $this->assertTrue($model->relationLoaded('two.one')); $this->assertTrue($model->two->one->is($one)); } + + public function testWhenRelationIsNull() + { + $one = One::query()->create(); + $two = $one->twos()->create(); + $three = $two->threes()->create(); + + $model = Three::query() + ->with('one.twos') + ->find($three->id); + + $this->assertTrue($model->relationLoaded('one')); + $this->assertNull($model->one); + $this->assertFalse($model->relationLoaded('one.twos')); + } } class One extends Model
diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php index fc211e179a5..b27b7110909 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php @@ -1088,7 +1088,11 @@ public function relationLoaded($key) if ($nestedRelation !== null) { $relatedModels = is_iterable($relatedModels = $this->$relation) ? $relatedModels - : [$relatedModels]; + : array_filter([$relatedModels]); + if (count($relatedModels) === 0) { + return false; + } foreach ($relatedModels as $related) { if (! $related->relationLoaded($nestedRelation)) { diff --git a/tests/Integration/Database/EloquentModelRelationLoadedTest.php b/tests/Integration/Database/EloquentModelRelationLoadedTest.php index 548a50d1195..265926d9cd4 100644 --- a/tests/Integration/Database/EloquentModelRelationLoadedTest.php +++ b/tests/Integration/Database/EloquentModelRelationLoadedTest.php @@ -135,6 +135,21 @@ public function testWhenParentRelationIsASingleInstance() $this->assertTrue($model->relationLoaded('two.one')); $this->assertTrue($model->two->one->is($one)); } + { + $one = One::query()->create(); + $two = $one->twos()->create(); + $three = $two->threes()->create(); + $model = Three::query() + ->with('one.twos') + ->find($three->id); + $this->assertTrue($model->relationLoaded('one')); + $this->assertNull($model->one); + $this->assertFalse($model->relationLoaded('one.twos')); + } } class One extends Model
[ "+ public function testWhenRelationIsNull()" ]
[ 26 ]
{ "additions": 20, "author": "rodrigopedra", "deletions": 1, "html_url": "https://github.com/laravel/framework/pull/55531", "issue_id": 55531, "merged_at": "2025-04-24T14:05:39Z", "omission_probability": 0.1, "pr_number": 55531, "repo": "laravel/framework", "title": "[12.x] Address Model@relationLoaded when relation is null", "total_changes": 21 }
5
diff --git a/src/Illuminate/Mail/Markdown.php b/src/Illuminate/Mail/Markdown.php index e8ec2defc4c4..54c9c2ece372 100644 --- a/src/Illuminate/Mail/Markdown.php +++ b/src/Illuminate/Mail/Markdown.php @@ -69,9 +69,25 @@ public function render($view, array $data = [], $inliner = null) $contents = $bladeCompiler->usingEchoFormat( 'new \Illuminate\Support\EncodedHtmlString(%s)', function () use ($view, $data) { - return $this->view->replaceNamespace( - 'mail', $this->htmlComponentPaths() - )->make($view, $data)->render(); + EncodedHtmlString::encodeUsing(function ($value) { + $replacements = [ + '[' => '\[', + '<' => '&lt;', + '>' => '&gt;', + ]; + + return str_replace(array_keys($replacements), array_values($replacements), $value); + }); + + try { + $contents = $this->view->replaceNamespace( + 'mail', $this->htmlComponentPaths() + )->make($view, $data)->render(); + } finally { + EncodedHtmlString::flushState(); + } + + return $contents; } ); @@ -84,7 +100,7 @@ function () use ($view, $data) { } return new HtmlString(($inliner ?: new CssToInlineStyles)->convert( - $contents, $this->view->make($theme, $data)->render() + str_replace('\[', '[', $contents), $this->view->make($theme, $data)->render() )); } @@ -112,10 +128,15 @@ public function renderText($view, array $data = []) * Parse the given Markdown text into HTML. * * @param string $text + * @param bool $encoded * @return \Illuminate\Support\HtmlString */ - public static function parse($text) + public static function parse($text, bool $encoded = false) { + if ($encoded === false) { + return new HtmlString(static::converter()->convert($text)->getContent()); + } + EncodedHtmlString::encodeUsing(function ($value) { $replacements = [ '[' => '\[', diff --git a/src/Illuminate/Mail/resources/views/html/button.blade.php b/src/Illuminate/Mail/resources/views/html/button.blade.php index 4a9bf7d00495..050e969d2130 100644 --- a/src/Illuminate/Mail/resources/views/html/button.blade.php +++ b/src/Illuminate/Mail/resources/views/html/button.blade.php @@ -12,7 +12,7 @@ <table border="0" cellpadding="0" cellspacing="0" role="presentation"> <tr> <td> -<a href="{{ $url }}" class="button button-{{ $color }}" target="_blank" rel="noopener">{{ $slot }}</a> +<a href="{{ $url }}" class="button button-{{ $color }}" target="_blank" rel="noopener">{!! $slot !!}</a> </td> </tr> </table> diff --git a/src/Illuminate/Mail/resources/views/html/header.blade.php b/src/Illuminate/Mail/resources/views/html/header.blade.php index 56197f8d23f3..c47a260c56b2 100644 --- a/src/Illuminate/Mail/resources/views/html/header.blade.php +++ b/src/Illuminate/Mail/resources/views/html/header.blade.php @@ -5,7 +5,7 @@ @if (trim($slot) === 'Laravel') <img src="https://laravel.com/img/notification-logo.png" class="logo" alt="Laravel Logo"> @else -{{ $slot }} +{!! $slot !!} @endif </a> </td> diff --git a/src/Illuminate/Mail/resources/views/html/layout.blade.php b/src/Illuminate/Mail/resources/views/html/layout.blade.php index d31a01de8630..0fa6b82f72b2 100644 --- a/src/Illuminate/Mail/resources/views/html/layout.blade.php +++ b/src/Illuminate/Mail/resources/views/html/layout.blade.php @@ -23,7 +23,7 @@ } } </style> -{{ $head ?? '' }} +{!! $head ?? '' !!} </head> <body> @@ -31,7 +31,7 @@ <tr> <td align="center"> <table class="content" width="100%" cellpadding="0" cellspacing="0" role="presentation"> -{{ $header ?? '' }} +{!! $header ?? '' !!} <!-- Email Body --> <tr> @@ -40,16 +40,16 @@ <!-- Body content --> <tr> <td class="content-cell"> -{{ Illuminate\Mail\Markdown::parse($slot) }} +{!! Illuminate\Mail\Markdown::parse($slot) !!} -{{ $subcopy ?? '' }} +{!! $subcopy ?? '' !!} </td> </tr> </table> </td> </tr> -{{ $footer ?? '' }} +{!! $footer ?? '' !!} </table> </td> </tr> diff --git a/src/Illuminate/Mail/resources/views/html/message.blade.php b/src/Illuminate/Mail/resources/views/html/message.blade.php index 1a874fc26de5..f1e815f32a41 100644 --- a/src/Illuminate/Mail/resources/views/html/message.blade.php +++ b/src/Illuminate/Mail/resources/views/html/message.blade.php @@ -7,13 +7,13 @@ </x-slot:header> {{-- Body --}} -{{ $slot }} +{!! $slot !!} {{-- Subcopy --}} @isset($subcopy) <x-slot:subcopy> <x-mail::subcopy> -{{ $subcopy }} +{!! $subcopy !!}} </x-mail::subcopy> </x-slot:subcopy> @endisset diff --git a/src/Illuminate/Mail/resources/views/html/panel.blade.php b/src/Illuminate/Mail/resources/views/html/panel.blade.php index 2975a60a021e..812db7c08e77 100644 --- a/src/Illuminate/Mail/resources/views/html/panel.blade.php +++ b/src/Illuminate/Mail/resources/views/html/panel.blade.php @@ -4,7 +4,7 @@ <table width="100%" cellpadding="0" cellspacing="0" role="presentation"> <tr> <td class="panel-item"> -{{ Illuminate\Mail\Markdown::parse($slot) }} +{!! Illuminate\Mail\Markdown::parse($slot) !!} </td> </tr> </table> diff --git a/tests/Integration/Mail/Fixtures/message-with-template.blade.php b/tests/Integration/Mail/Fixtures/message-with-template.blade.php new file mode 100644 index 000000000000..9c53cef7e1bb --- /dev/null +++ b/tests/Integration/Mail/Fixtures/message-with-template.blade.php @@ -0,0 +1,4 @@ +@component('mail::message') +*Hi* {{ $user->name }} + +@endcomponent diff --git a/tests/Integration/Mail/MailableTest.php b/tests/Integration/Mail/MailableTest.php index 339ebb2422d7..4ff0f539b6ad 100644 --- a/tests/Integration/Mail/MailableTest.php +++ b/tests/Integration/Mail/MailableTest.php @@ -2,14 +2,20 @@ namespace Illuminate\Tests\Integration\Mail; +use Illuminate\Foundation\Auth\User; +use Illuminate\Foundation\Testing\LazilyRefreshDatabase; use Illuminate\Mail\Mailable; use Illuminate\Mail\Mailables\Content; use Illuminate\Mail\Mailables\Envelope; +use Orchestra\Testbench\Attributes\WithMigration; +use Orchestra\Testbench\Factories\UserFactory; use Orchestra\Testbench\TestCase; use PHPUnit\Framework\Attributes\DataProvider; class MailableTest extends TestCase { + use LazilyRefreshDatabase; + /** {@inheritdoc} */ #[\Override] protected function defineEnvironment($app) @@ -69,4 +75,55 @@ public static function markdownEncodedDataProvider() 'My message is: Visit &lt;span&gt;https://laravel.com/docs&lt;/span&gt; to browse the documentation', ]; } + + #[WithMigration] + #[DataProvider('markdownEncodedTemplateDataProvider')] + public function testItCanAssertMarkdownEncodedStringUsingTemplate($given, $expected) + { + $user = UserFactory::new()->create([ + 'name' => $given, + ]); + + $mailable = new class($user) extends Mailable + { + public $theme = 'taylor'; + + public function __construct(public User $user) + { + // + } + + public function build() + { + return $this->markdown('message-with-template'); + } + }; + + $mailable->assertSeeInHtml($expected, false); + } + + public static function markdownEncodedTemplateDataProvider() + { + yield ['[Laravel](https://laravel.com)', '<em>Hi</em> [Laravel](https://laravel.com)']; + + yield [ + '![Welcome to Laravel](https://laravel.com/assets/img/welcome/background.svg)', + '<em>Hi</em> ![Welcome to Laravel](https://laravel.com/assets/img/welcome/background.svg)', + ]; + + yield [ + 'Visit https://laravel.com/docs to browse the documentation', + '<em>Hi</em> Visit https://laravel.com/docs to browse the documentation', + ]; + + yield [ + 'Visit <https://laravel.com/docs> to browse the documentation', + '<em>Hi</em> Visit &lt;https://laravel.com/docs&gt; to browse the documentation', + ]; + + yield [ + 'Visit <span>https://laravel.com/docs</span> to browse the documentation', + '<em>Hi</em> Visit &lt;span&gt;https://laravel.com/docs&lt;/span&gt; to browse the documentation', + ]; + } } diff --git a/tests/Integration/Mail/MarkdownParserTest.php b/tests/Integration/Mail/MarkdownParserTest.php index d21602c9ad00..6669fe038ba3 100644 --- a/tests/Integration/Mail/MarkdownParserTest.php +++ b/tests/Integration/Mail/MarkdownParserTest.php @@ -24,7 +24,7 @@ public function testItCanParseMarkdownString($given, $expected) #[DataProvider('markdownEncodedDataProvider')] public function testItCanParseMarkdownEncodedString($given, $expected) { - tap(Markdown::parse($given), function ($html) use ($expected) { + tap(Markdown::parse($given, encoded: true), function ($html) use ($expected) { $this->assertInstanceOf(HtmlString::class, $html); $this->assertStringEqualsStringIgnoringLineEndings($expected.PHP_EOL, (string) $html);
diff --git a/src/Illuminate/Mail/Markdown.php b/src/Illuminate/Mail/Markdown.php index e8ec2defc4c4..54c9c2ece372 100644 --- a/src/Illuminate/Mail/Markdown.php +++ b/src/Illuminate/Mail/Markdown.php @@ -69,9 +69,25 @@ public function render($view, array $data = [], $inliner = null) $contents = $bladeCompiler->usingEchoFormat( 'new \Illuminate\Support\EncodedHtmlString(%s)', function () use ($view, $data) { - return $this->view->replaceNamespace( - 'mail', $this->htmlComponentPaths() - )->make($view, $data)->render(); + EncodedHtmlString::encodeUsing(function ($value) { + $replacements = [ + '[' => '\[', + '<' => '&lt;', + '>' => '&gt;', + ]; + return str_replace(array_keys($replacements), array_values($replacements), $value); + }); + try { + 'mail', $this->htmlComponentPaths() + )->make($view, $data)->render(); + } finally { + EncodedHtmlString::flushState(); } ); @@ -84,7 +100,7 @@ function () use ($view, $data) { } return new HtmlString(($inliner ?: new CssToInlineStyles)->convert( - $contents, $this->view->make($theme, $data)->render() )); @@ -112,10 +128,15 @@ public function renderText($view, array $data = []) * Parse the given Markdown text into HTML. * * @param string $text + * @param bool $encoded * @return \Illuminate\Support\HtmlString */ - public static function parse($text) + public static function parse($text, bool $encoded = false) + if ($encoded === false) { + return new HtmlString(static::converter()->convert($text)->getContent()); EncodedHtmlString::encodeUsing(function ($value) { $replacements = [ '[' => '\[', diff --git a/src/Illuminate/Mail/resources/views/html/button.blade.php b/src/Illuminate/Mail/resources/views/html/button.blade.php index 4a9bf7d00495..050e969d2130 100644 --- a/src/Illuminate/Mail/resources/views/html/button.blade.php +++ b/src/Illuminate/Mail/resources/views/html/button.blade.php @@ -12,7 +12,7 @@ <table border="0" cellpadding="0" cellspacing="0" role="presentation"> <td> -<a href="{{ $url }}" class="button button-{{ $color }}" target="_blank" rel="noopener">{{ $slot }}</a> +<a href="{{ $url }}" class="button button-{{ $color }}" target="_blank" rel="noopener">{!! $slot !!}</a> diff --git a/src/Illuminate/Mail/resources/views/html/header.blade.php b/src/Illuminate/Mail/resources/views/html/header.blade.php index 56197f8d23f3..c47a260c56b2 100644 --- a/src/Illuminate/Mail/resources/views/html/header.blade.php +++ b/src/Illuminate/Mail/resources/views/html/header.blade.php @@ -5,7 +5,7 @@ @if (trim($slot) === 'Laravel') <img src="https://laravel.com/img/notification-logo.png" class="logo" alt="Laravel Logo"> @else @endif </a> diff --git a/src/Illuminate/Mail/resources/views/html/layout.blade.php b/src/Illuminate/Mail/resources/views/html/layout.blade.php index d31a01de8630..0fa6b82f72b2 100644 --- a/src/Illuminate/Mail/resources/views/html/layout.blade.php +++ b/src/Illuminate/Mail/resources/views/html/layout.blade.php @@ -23,7 +23,7 @@ </style> -{{ $head ?? '' }} +{!! $head ?? '' !!} </head> <body> @@ -31,7 +31,7 @@ <td align="center"> <table class="content" width="100%" cellpadding="0" cellspacing="0" role="presentation"> -{{ $header ?? '' }} +{!! $header ?? '' !!} <!-- Email Body --> @@ -40,16 +40,16 @@ <!-- Body content --> <td class="content-cell"> -{{ $subcopy ?? '' }} +{!! $subcopy ?? '' !!} -{{ $footer ?? '' }} +{!! $footer ?? '' !!} diff --git a/src/Illuminate/Mail/resources/views/html/message.blade.php b/src/Illuminate/Mail/resources/views/html/message.blade.php index 1a874fc26de5..f1e815f32a41 100644 --- a/src/Illuminate/Mail/resources/views/html/message.blade.php +++ b/src/Illuminate/Mail/resources/views/html/message.blade.php @@ -7,13 +7,13 @@ </x-slot:header> {{-- Body --}} {{-- Subcopy --}} @isset($subcopy) <x-slot:subcopy> <x-mail::subcopy> -{{ $subcopy }} +{!! $subcopy !!}} </x-mail::subcopy> </x-slot:subcopy> @endisset diff --git a/src/Illuminate/Mail/resources/views/html/panel.blade.php b/src/Illuminate/Mail/resources/views/html/panel.blade.php index 2975a60a021e..812db7c08e77 100644 --- a/src/Illuminate/Mail/resources/views/html/panel.blade.php +++ b/src/Illuminate/Mail/resources/views/html/panel.blade.php @@ -4,7 +4,7 @@ <table width="100%" cellpadding="0" cellspacing="0" role="presentation"> <td class="panel-item"> diff --git a/tests/Integration/Mail/Fixtures/message-with-template.blade.php b/tests/Integration/Mail/Fixtures/message-with-template.blade.php new file mode 100644 index 000000000000..9c53cef7e1bb --- /dev/null +++ b/tests/Integration/Mail/Fixtures/message-with-template.blade.php @@ -0,0 +1,4 @@ +@component('mail::message') +*Hi* {{ $user->name }} +@endcomponent diff --git a/tests/Integration/Mail/MailableTest.php b/tests/Integration/Mail/MailableTest.php index 339ebb2422d7..4ff0f539b6ad 100644 --- a/tests/Integration/Mail/MailableTest.php +++ b/tests/Integration/Mail/MailableTest.php @@ -2,14 +2,20 @@ namespace Illuminate\Tests\Integration\Mail; +use Illuminate\Foundation\Auth\User; +use Illuminate\Foundation\Testing\LazilyRefreshDatabase; use Illuminate\Mail\Mailable; use Illuminate\Mail\Mailables\Content; use Illuminate\Mail\Mailables\Envelope; +use Orchestra\Testbench\Attributes\WithMigration; +use Orchestra\Testbench\Factories\UserFactory; use Orchestra\Testbench\TestCase; use PHPUnit\Framework\Attributes\DataProvider; class MailableTest extends TestCase { + use LazilyRefreshDatabase; /** {@inheritdoc} */ #[\Override] protected function defineEnvironment($app) @@ -69,4 +75,55 @@ public static function markdownEncodedDataProvider() 'My message is: Visit &lt;span&gt;https://laravel.com/docs&lt;/span&gt; to browse the documentation', ]; + #[WithMigration] + #[DataProvider('markdownEncodedTemplateDataProvider')] + public function testItCanAssertMarkdownEncodedStringUsingTemplate($given, $expected) + $user = UserFactory::new()->create([ + 'name' => $given, + ]); + $mailable = new class($user) extends Mailable + { + public $theme = 'taylor'; + public function __construct(public User $user) + // + return $this->markdown('message-with-template'); + }; + $mailable->assertSeeInHtml($expected, false); + public static function markdownEncodedTemplateDataProvider() + yield ['[Laravel](https://laravel.com)', '<em>Hi</em> [Laravel](https://laravel.com)']; + '![Welcome to Laravel](https://laravel.com/assets/img/welcome/background.svg)', + '<em>Hi</em> ![Welcome to Laravel](https://laravel.com/assets/img/welcome/background.svg)', + 'Visit https://laravel.com/docs to browse the documentation', + '<em>Hi</em> Visit https://laravel.com/docs to browse the documentation', + 'Visit <https://laravel.com/docs> to browse the documentation', + '<em>Hi</em> Visit &lt;https://laravel.com/docs&gt; to browse the documentation', + 'Visit <span>https://laravel.com/docs</span> to browse the documentation', + '<em>Hi</em> Visit &lt;span&gt;https://laravel.com/docs&lt;/span&gt; to browse the documentation', diff --git a/tests/Integration/Mail/MarkdownParserTest.php b/tests/Integration/Mail/MarkdownParserTest.php index d21602c9ad00..6669fe038ba3 100644 --- a/tests/Integration/Mail/MarkdownParserTest.php +++ b/tests/Integration/Mail/MarkdownParserTest.php @@ -24,7 +24,7 @@ public function testItCanParseMarkdownString($given, $expected) #[DataProvider('markdownEncodedDataProvider')] public function testItCanParseMarkdownEncodedString($given, $expected) - tap(Markdown::parse($given), function ($html) use ($expected) { + tap(Markdown::parse($given, encoded: true), function ($html) use ($expected) { $this->assertInstanceOf(HtmlString::class, $html); $this->assertStringEqualsStringIgnoringLineEndings($expected.PHP_EOL, (string) $html);
[ "+ $contents = $this->view->replaceNamespace(", "+ }", "+ return $contents;", "+ str_replace('\\[', '[', $contents), $this->view->make($theme, $data)->render()", "+ }", "+ public function build()" ]
[ 22, 27, 29, 38, 54, 217 ]
{ "additions": 98, "author": "crynobone", "deletions": 16, "html_url": "https://github.com/laravel/framework/pull/55149", "issue_id": 55149, "merged_at": "2025-03-24T14:53:50Z", "omission_probability": 0.1, "pr_number": 55149, "repo": "laravel/framework", "title": "[11.x] Fix `Illuminate\\Support\\EncodedHtmlString` from causing breaking change", "total_changes": 114 }
6
diff --git a/src/Illuminate/Bus/Dispatcher.php b/src/Illuminate/Bus/Dispatcher.php index 32f917d796a6..0107b9e5acd4 100644 --- a/src/Illuminate/Bus/Dispatcher.php +++ b/src/Illuminate/Bus/Dispatcher.php @@ -51,6 +51,13 @@ class Dispatcher implements QueueingDispatcher */ protected $queueResolver; + /** + * Indicates if dispatching after response is disabled. + * + * @var bool + */ + protected $allowsDispatchingAfterResponses = true; + /** * Create a new command dispatcher instance. * @@ -252,6 +259,12 @@ protected function pushCommandToQueue($queue, $command) */ public function dispatchAfterResponse($command, $handler = null) { + if (! $this->allowsDispatchingAfterResponses) { + $this->dispatchSync($command); + + return; + } + $this->container->terminating(function () use ($command, $handler) { $this->dispatchSync($command, $handler); }); @@ -282,4 +295,28 @@ public function map(array $map) return $this; } + + /** + * Allow dispatching after responses. + * + * @return $this + */ + public function withDispatchingAfterResponses() + { + $this->allowsDispatchingAfterResponses = true; + + return $this; + } + + /** + * Disable dispatching after responses. + * + * @return $this + */ + public function withoutDispatchingAfterResponses() + { + $this->allowsDispatchingAfterResponses = false; + + return $this; + } } diff --git a/tests/Integration/Queue/JobDispatchingTest.php b/tests/Integration/Queue/JobDispatchingTest.php index ebef0f344318..eddfd83c23c1 100644 --- a/tests/Integration/Queue/JobDispatchingTest.php +++ b/tests/Integration/Queue/JobDispatchingTest.php @@ -10,6 +10,7 @@ use Illuminate\Queue\Events\JobQueued; use Illuminate\Queue\Events\JobQueueing; use Illuminate\Queue\InteractsWithQueue; +use Illuminate\Support\Facades\Bus; use Illuminate\Support\Facades\Config; use Orchestra\Testbench\Attributes\WithMigration; @@ -165,6 +166,37 @@ public function testQueueMayBeNullForJobQueueingAndJobQueuedEvent() $this->assertNull($events[3]->queue); } + public function testCanDisableDispatchingAfterResponse() + { + Job::dispatchAfterResponse('test'); + + $this->assertFalse(Job::$ran); + + $this->app->terminate(); + + $this->assertTrue(Job::$ran); + + Bus::withoutDispatchingAfterResponses(); + + Job::$ran = false; + Job::dispatchAfterResponse('test'); + + $this->assertTrue(Job::$ran); + + $this->app->terminate(); + + Bus::withDispatchingAfterResponses(); + + Job::$ran = false; + Job::dispatchAfterResponse('test'); + + $this->assertFalse(Job::$ran); + + $this->app->terminate(); + + $this->assertTrue(Job::$ran); + } + /** * Helpers. */
diff --git a/src/Illuminate/Bus/Dispatcher.php b/src/Illuminate/Bus/Dispatcher.php index 32f917d796a6..0107b9e5acd4 100644 --- a/src/Illuminate/Bus/Dispatcher.php +++ b/src/Illuminate/Bus/Dispatcher.php @@ -51,6 +51,13 @@ class Dispatcher implements QueueingDispatcher protected $queueResolver; + * Indicates if dispatching after response is disabled. + * @var bool + protected $allowsDispatchingAfterResponses = true; * Create a new command dispatcher instance. * @@ -252,6 +259,12 @@ protected function pushCommandToQueue($queue, $command) public function dispatchAfterResponse($command, $handler = null) { + if (! $this->allowsDispatchingAfterResponses) { + $this->dispatchSync($command); + return; + } $this->container->terminating(function () use ($command, $handler) { $this->dispatchSync($command, $handler); }); @@ -282,4 +295,28 @@ public function map(array $map) return $this; + * Allow dispatching after responses. + public function withDispatchingAfterResponses() + $this->allowsDispatchingAfterResponses = true; + * Disable dispatching after responses. + public function withoutDispatchingAfterResponses() + $this->allowsDispatchingAfterResponses = false; } diff --git a/tests/Integration/Queue/JobDispatchingTest.php b/tests/Integration/Queue/JobDispatchingTest.php index ebef0f344318..eddfd83c23c1 100644 --- a/tests/Integration/Queue/JobDispatchingTest.php +++ b/tests/Integration/Queue/JobDispatchingTest.php @@ -10,6 +10,7 @@ use Illuminate\Queue\Events\JobQueued; use Illuminate\Queue\Events\JobQueueing; use Illuminate\Queue\InteractsWithQueue; +use Illuminate\Support\Facades\Bus; use Illuminate\Support\Facades\Config; use Orchestra\Testbench\Attributes\WithMigration; @@ -165,6 +166,37 @@ public function testQueueMayBeNullForJobQueueingAndJobQueuedEvent() $this->assertNull($events[3]->queue); + public function testCanDisableDispatchingAfterResponse() + Bus::withoutDispatchingAfterResponses(); + Bus::withDispatchingAfterResponses(); * Helpers.
[]
[]
{ "additions": 69, "author": "gdebrauwer", "deletions": 0, "html_url": "https://github.com/laravel/framework/pull/55456", "issue_id": 55456, "merged_at": "2025-04-24T19:45:06Z", "omission_probability": 0.1, "pr_number": 55456, "repo": "laravel/framework", "title": "[12.x] Option to disable dispatchAfterResponse in a test", "total_changes": 69 }
7
diff --git a/src/Illuminate/Notifications/NotificationSender.php b/src/Illuminate/Notifications/NotificationSender.php index c7e75fd851b2..46ef9e88cf15 100644 --- a/src/Illuminate/Notifications/NotificationSender.php +++ b/src/Illuminate/Notifications/NotificationSender.php @@ -6,11 +6,13 @@ use Illuminate\Contracts\Translation\HasLocalePreference; use Illuminate\Database\Eloquent\Collection as EloquentCollection; use Illuminate\Database\Eloquent\Model; +use Illuminate\Notifications\Events\NotificationFailed; use Illuminate\Notifications\Events\NotificationSending; use Illuminate\Notifications\Events\NotificationSent; use Illuminate\Support\Collection; use Illuminate\Support\Str; use Illuminate\Support\Traits\Localizable; +use Throwable; class NotificationSender { @@ -44,6 +46,13 @@ class NotificationSender */ protected $locale; + /** + * Indicates whether a NotificationFailed event has been dispatched. + * + * @var bool + */ + protected $failedEventWasDispatched = false; + /** * Create a new notification sender instance. * @@ -58,6 +67,8 @@ public function __construct($manager, $bus, $events, $locale = null) $this->events = $events; $this->locale = $locale; $this->manager = $manager; + + $this->events->listen(NotificationFailed::class, fn () => $this->failedEventWasDispatched = true); } /** @@ -144,7 +155,19 @@ protected function sendToNotifiable($notifiable, $id, $notification, $channel) return; } - $response = $this->manager->driver($channel)->send($notifiable, $notification); + try { + $response = $this->manager->driver($channel)->send($notifiable, $notification); + } catch (Throwable $exception) { + if (! $this->failedEventWasDispatched) { + $this->events->dispatch( + new NotificationFailed($notifiable, $notification, $channel, ['exception' => $exception]) + ); + } + + $this->failedEventWasDispatched = false; + + throw $exception; + } $this->events->dispatch( new NotificationSent($notifiable, $notification, $channel, $response) diff --git a/tests/Notifications/NotificationChannelManagerTest.php b/tests/Notifications/NotificationChannelManagerTest.php index efcce081aeee..4b272db8399f 100644 --- a/tests/Notifications/NotificationChannelManagerTest.php +++ b/tests/Notifications/NotificationChannelManagerTest.php @@ -2,17 +2,20 @@ namespace Illuminate\Tests\Notifications; +use Exception; use Illuminate\Bus\Queueable; use Illuminate\Container\Container; use Illuminate\Contracts\Bus\Dispatcher as Bus; use Illuminate\Contracts\Events\Dispatcher; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\ChannelManager; +use Illuminate\Notifications\Events\NotificationFailed; use Illuminate\Notifications\Events\NotificationSending; use Illuminate\Notifications\Events\NotificationSent; use Illuminate\Notifications\Notifiable; use Illuminate\Notifications\Notification; use Illuminate\Notifications\SendQueuedNotifications; +use Illuminate\Support\Collection; use Mockery as m; use PHPUnit\Framework\TestCase; @@ -34,6 +37,7 @@ public function testNotificationCanBeDispatchedToDriver() Container::setInstance($container); $manager = m::mock(ChannelManager::class.'[driver]', [$container]); $manager->shouldReceive('driver')->andReturn($driver = m::mock()); + $events->shouldReceive('listen')->once(); $events->shouldReceive('until')->with(m::type(NotificationSending::class))->andReturn(true); $driver->shouldReceive('send')->once(); $events->shouldReceive('dispatch')->with(m::type(NotificationSent::class)); @@ -49,6 +53,7 @@ public function testNotificationNotSentOnHalt() $container->instance(Dispatcher::class, $events = m::mock()); Container::setInstance($container); $manager = m::mock(ChannelManager::class.'[driver]', [$container]); + $events->shouldReceive('listen')->once(); $events->shouldReceive('until')->once()->with(m::type(NotificationSending::class))->andReturn(false); $events->shouldReceive('until')->with(m::type(NotificationSending::class))->andReturn(true); $manager->shouldReceive('driver')->once()->andReturn($driver = m::mock()); @@ -66,6 +71,7 @@ public function testNotificationNotSentWhenCancelled() $container->instance(Dispatcher::class, $events = m::mock()); Container::setInstance($container); $manager = m::mock(ChannelManager::class.'[driver]', [$container]); + $events->shouldReceive('listen')->once(); $events->shouldReceive('until')->with(m::type(NotificationSending::class))->andReturn(true); $manager->shouldNotReceive('driver'); $events->shouldNotReceive('dispatch'); @@ -81,6 +87,7 @@ public function testNotificationSentWhenNotCancelled() $container->instance(Dispatcher::class, $events = m::mock()); Container::setInstance($container); $manager = m::mock(ChannelManager::class.'[driver]', [$container]); + $events->shouldReceive('listen')->once(); $events->shouldReceive('until')->with(m::type(NotificationSending::class))->andReturn(true); $manager->shouldReceive('driver')->once()->andReturn($driver = m::mock()); $driver->shouldReceive('send')->once(); @@ -89,6 +96,56 @@ public function testNotificationSentWhenNotCancelled() $manager->send([new NotificationChannelManagerTestNotifiable], new NotificationChannelManagerTestNotCancelledNotification); } + public function testNotificationNotSentWhenFailed() + { + $this->expectException(Exception::class); + + $container = new Container; + $container->instance('config', ['app.name' => 'Name', 'app.logo' => 'Logo']); + $container->instance(Bus::class, $bus = m::mock()); + $container->instance(Dispatcher::class, $events = m::mock()); + Container::setInstance($container); + $manager = m::mock(ChannelManager::class.'[driver]', [$container]); + $manager->shouldReceive('driver')->andReturn($driver = m::mock()); + $driver->shouldReceive('send')->andThrow(new Exception()); + $events->shouldReceive('listen')->once(); + $events->shouldReceive('until')->with(m::type(NotificationSending::class))->andReturn(true); + $events->shouldReceive('dispatch')->once()->with(m::type(NotificationFailed::class)); + $events->shouldReceive('dispatch')->never()->with(m::type(NotificationSent::class)); + + $manager->send(new NotificationChannelManagerTestNotifiable, new NotificationChannelManagerTestNotification); + } + + public function testNotificationFailedDispatchedOnlyOnceWhenFailed() + { + $this->expectException(Exception::class); + + $container = new Container; + $container->instance('config', ['app.name' => 'Name', 'app.logo' => 'Logo']); + $container->instance(Bus::class, $bus = m::mock()); + $container->instance(Dispatcher::class, $events = m::mock(Dispatcher::class)); + Container::setInstance($container); + $manager = m::mock(ChannelManager::class.'[driver]', [$container]); + $manager->shouldReceive('driver')->andReturn($driver = m::mock()); + $driver->shouldReceive('send')->andReturnUsing(function ($notifiable, $notification) use ($events) { + $events->dispatch(new NotificationFailed($notifiable, $notification, 'test')); + throw new Exception(); + }); + $listeners = new Collection(); + $events->shouldReceive('until')->with(m::type(NotificationSending::class))->andReturn(true); + $events->shouldReceive('listen')->once()->andReturnUsing(function ($event, $callback) use ($listeners) { + $listeners->push($callback); + }); + $events->shouldReceive('dispatch')->once()->with(m::type(NotificationFailed::class))->andReturnUsing(function ($event) use ($listeners) { + foreach ($listeners as $listener) { + $listener($event); + } + }); + $events->shouldReceive('dispatch')->never()->with(m::type(NotificationSent::class)); + + $manager->send(new NotificationChannelManagerTestNotifiable, new NotificationChannelManagerTestNotification); + } + public function testNotificationCanBeQueued() { $container = new Container; @@ -98,6 +155,7 @@ public function testNotificationCanBeQueued() $bus->shouldReceive('dispatch')->with(m::type(SendQueuedNotifications::class)); Container::setInstance($container); $manager = m::mock(ChannelManager::class.'[driver]', [$container]); + $events->shouldReceive('listen')->once(); $manager->send([new NotificationChannelManagerTestNotifiable], new NotificationChannelManagerTestQueuedNotification); } diff --git a/tests/Notifications/NotificationSenderTest.php b/tests/Notifications/NotificationSenderTest.php index 4770fc96cd17..6e3a9954938c 100644 --- a/tests/Notifications/NotificationSenderTest.php +++ b/tests/Notifications/NotificationSenderTest.php @@ -30,6 +30,7 @@ public function testItCanSendQueuedNotificationsWithAStringVia() $bus = m::mock(BusDispatcher::class); $bus->shouldReceive('dispatch'); $events = m::mock(EventDispatcher::class); + $events->shouldReceive('listen')->once(); $sender = new NotificationSender($manager, $bus, $events); @@ -43,6 +44,7 @@ public function testItCanSendNotificationsWithAnEmptyStringVia() $bus = m::mock(BusDispatcher::class); $bus->shouldNotReceive('dispatch'); $events = m::mock(EventDispatcher::class); + $events->shouldReceive('listen')->once(); $sender = new NotificationSender($manager, $bus, $events); @@ -56,6 +58,7 @@ public function testItCannotSendNotificationsViaDatabaseForAnonymousNotifiables( $bus = m::mock(BusDispatcher::class); $bus->shouldNotReceive('dispatch'); $events = m::mock(EventDispatcher::class); + $events->shouldReceive('listen')->once(); $sender = new NotificationSender($manager, $bus, $events); @@ -72,6 +75,7 @@ public function testItCanSendQueuedNotificationsThroughMiddleware() return $job->middleware[0] instanceof TestNotificationMiddleware; }); $events = m::mock(EventDispatcher::class); + $events->shouldReceive('listen')->once(); $sender = new NotificationSender($manager, $bus, $events); @@ -99,6 +103,7 @@ public function testItCanSendQueuedMultiChannelNotificationsThroughDifferentMidd return empty($job->middleware); }); $events = m::mock(EventDispatcher::class); + $events->shouldReceive('listen')->once(); $sender = new NotificationSender($manager, $bus, $events); @@ -122,6 +127,7 @@ public function testItCanSendQueuedWithViaConnectionsNotifications() }); $events = m::mock(EventDispatcher::class); + $events->shouldReceive('listen')->once(); $sender = new NotificationSender($manager, $bus, $events);
diff --git a/src/Illuminate/Notifications/NotificationSender.php b/src/Illuminate/Notifications/NotificationSender.php index c7e75fd851b2..46ef9e88cf15 100644 --- a/src/Illuminate/Notifications/NotificationSender.php +++ b/src/Illuminate/Notifications/NotificationSender.php @@ -6,11 +6,13 @@ use Illuminate\Contracts\Translation\HasLocalePreference; use Illuminate\Database\Eloquent\Collection as EloquentCollection; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Collection; use Illuminate\Support\Str; use Illuminate\Support\Traits\Localizable; +use Throwable; class NotificationSender { @@ -44,6 +46,13 @@ class NotificationSender */ protected $locale; + /** + * Indicates whether a NotificationFailed event has been dispatched. + * + * @var bool + */ + protected $failedEventWasDispatched = false; * Create a new notification sender instance. * @@ -58,6 +67,8 @@ public function __construct($manager, $bus, $events, $locale = null) $this->events = $events; $this->locale = $locale; $this->manager = $manager; + $this->events->listen(NotificationFailed::class, fn () => $this->failedEventWasDispatched = true); @@ -144,7 +155,19 @@ protected function sendToNotifiable($notifiable, $id, $notification, $channel) return; } - $response = $this->manager->driver($channel)->send($notifiable, $notification); + try { + $response = $this->manager->driver($channel)->send($notifiable, $notification); + } catch (Throwable $exception) { + if (! $this->failedEventWasDispatched) { + $this->events->dispatch( + new NotificationFailed($notifiable, $notification, $channel, ['exception' => $exception]) + ); + $this->failedEventWasDispatched = false; + throw $exception; + } $this->events->dispatch( new NotificationSent($notifiable, $notification, $channel, $response) diff --git a/tests/Notifications/NotificationChannelManagerTest.php b/tests/Notifications/NotificationChannelManagerTest.php index efcce081aeee..4b272db8399f 100644 --- a/tests/Notifications/NotificationChannelManagerTest.php +++ b/tests/Notifications/NotificationChannelManagerTest.php @@ -2,17 +2,20 @@ namespace Illuminate\Tests\Notifications; +use Exception; use Illuminate\Bus\Queueable; use Illuminate\Container\Container; use Illuminate\Contracts\Bus\Dispatcher as Bus; use Illuminate\Contracts\Events\Dispatcher; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\ChannelManager; use Illuminate\Notifications\Notifiable; use Illuminate\Notifications\Notification; use Illuminate\Notifications\SendQueuedNotifications; +use Illuminate\Support\Collection; use Mockery as m; use PHPUnit\Framework\TestCase; @@ -34,6 +37,7 @@ public function testNotificationCanBeDispatchedToDriver() $manager->shouldReceive('driver')->andReturn($driver = m::mock()); $events->shouldReceive('dispatch')->with(m::type(NotificationSent::class)); @@ -49,6 +53,7 @@ public function testNotificationNotSentOnHalt() $events->shouldReceive('until')->once()->with(m::type(NotificationSending::class))->andReturn(false); @@ -66,6 +71,7 @@ public function testNotificationNotSentWhenCancelled() $manager->shouldNotReceive('driver'); $events->shouldNotReceive('dispatch'); @@ -81,6 +87,7 @@ public function testNotificationSentWhenNotCancelled() @@ -89,6 +96,56 @@ public function testNotificationSentWhenNotCancelled() $manager->send([new NotificationChannelManagerTestNotifiable], new NotificationChannelManagerTestNotCancelledNotification); + $container->instance(Dispatcher::class, $events = m::mock()); + $driver->shouldReceive('send')->andThrow(new Exception()); + $events->shouldReceive('dispatch')->once()->with(m::type(NotificationFailed::class)); + public function testNotificationFailedDispatchedOnlyOnceWhenFailed() + $driver->shouldReceive('send')->andReturnUsing(function ($notifiable, $notification) use ($events) { + $events->dispatch(new NotificationFailed($notifiable, $notification, 'test')); + throw new Exception(); + $listeners = new Collection(); + $events->shouldReceive('listen')->once()->andReturnUsing(function ($event, $callback) use ($listeners) { + $listeners->push($callback); + $events->shouldReceive('dispatch')->once()->with(m::type(NotificationFailed::class))->andReturnUsing(function ($event) use ($listeners) { + $listener($event); public function testNotificationCanBeQueued() { $container = new Container; @@ -98,6 +155,7 @@ public function testNotificationCanBeQueued() $bus->shouldReceive('dispatch')->with(m::type(SendQueuedNotifications::class)); $manager->send([new NotificationChannelManagerTestNotifiable], new NotificationChannelManagerTestQueuedNotification); diff --git a/tests/Notifications/NotificationSenderTest.php b/tests/Notifications/NotificationSenderTest.php index 4770fc96cd17..6e3a9954938c 100644 --- a/tests/Notifications/NotificationSenderTest.php +++ b/tests/Notifications/NotificationSenderTest.php @@ -30,6 +30,7 @@ public function testItCanSendQueuedNotificationsWithAStringVia() $bus->shouldReceive('dispatch'); @@ -43,6 +44,7 @@ public function testItCanSendNotificationsWithAnEmptyStringVia() @@ -56,6 +58,7 @@ public function testItCannotSendNotificationsViaDatabaseForAnonymousNotifiables( @@ -72,6 +75,7 @@ public function testItCanSendQueuedNotificationsThroughMiddleware() return $job->middleware[0] instanceof TestNotificationMiddleware; @@ -99,6 +103,7 @@ public function testItCanSendQueuedMultiChannelNotificationsThroughDifferentMidd return empty($job->middleware); @@ -122,6 +127,7 @@ public function testItCanSendQueuedWithViaConnectionsNotifications()
[ "+ public function testNotificationNotSentWhenFailed()", "+ $container->instance(Dispatcher::class, $events = m::mock(Dispatcher::class));", "+ foreach ($listeners as $listener) {" ]
[ 123, 150, 164 ]
{ "additions": 88, "author": "rodrigopedra", "deletions": 1, "html_url": "https://github.com/laravel/framework/pull/55507", "issue_id": 55507, "merged_at": "2025-04-24T19:24:00Z", "omission_probability": 0.1, "pr_number": 55507, "repo": "laravel/framework", "title": "[12.x] Dispatch NotificationFailed when sending fails", "total_changes": 89 }
8
diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php index 79a2f5d98cd..6893c1284e3 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php @@ -1072,7 +1072,28 @@ public function getRelation($relation) */ public function relationLoaded($key) { - return array_key_exists($key, $this->relations); + if (array_key_exists($key, $this->relations)) { + return true; + } + + [$relation, $nestedRelation] = array_replace( + [null, null], + explode('.', $key, 2), + ); + + if (! array_key_exists($relation, $this->relations)) { + return false; + } + + if ($nestedRelation !== null) { + foreach ($this->$relation as $related) { + if (! $related->relationLoaded($nestedRelation)) { + return false; + } + } + } + + return true; } /** diff --git a/tests/Integration/Database/EloquentModelRelationLoadedTest.php b/tests/Integration/Database/EloquentModelRelationLoadedTest.php new file mode 100644 index 00000000000..06a0a740d3b --- /dev/null +++ b/tests/Integration/Database/EloquentModelRelationLoadedTest.php @@ -0,0 +1,168 @@ +<?php + +namespace Illuminate\Tests\Integration\Database\EloquentModelRelationLoadedTest; + +use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Relations\BelongsTo; +use Illuminate\Database\Eloquent\Relations\HasMany; +use Illuminate\Database\Schema\Blueprint; +use Illuminate\Support\Facades\Schema; +use Illuminate\Tests\Integration\Database\DatabaseTestCase; + +class EloquentModelRelationLoadedTest extends DatabaseTestCase +{ + protected function afterRefreshingDatabase() + { + Schema::create('ones', function (Blueprint $table) { + $table->increments('id'); + }); + + Schema::create('twos', function (Blueprint $table) { + $table->increments('id'); + $table->integer('one_id'); + }); + + Schema::create('threes', function (Blueprint $table) { + $table->increments('id'); + $table->integer('two_id'); + $table->integer('one_id')->nullable(); + }); + } + + public function testWhenRelationIsInvalid() + { + $one = One::query()->create(); + $one->twos()->create(); + + $model = One::query() + ->with('twos') + ->find($one->id); + + $this->assertFalse($model->relationLoaded('.')); + $this->assertFalse($model->relationLoaded('invalid')); + } + + public function testWhenNestedRelationIsInvalid() + { + $one = One::query()->create(); + $one->twos()->create(); + + $model = One::query() + ->with('twos') + ->find($one->id); + + $this->assertFalse($model->relationLoaded('twos.')); + $this->assertFalse($model->relationLoaded('twos.invalid')); + } + + public function testWhenRelationNotLoaded() + { + $one = One::query()->create(); + $one->twos()->create(); + + $model = One::query()->find($one->id); + + $this->assertFalse($model->relationLoaded('twos')); + } + + public function testWhenRelationLoaded() + { + $one = One::query()->create(); + $one->twos()->create(); + + $model = One::query() + ->with('twos') + ->find($one->id); + + $this->assertTrue($model->relationLoaded('twos')); + } + + public function testWhenChildRelationIsNotLoaded() + { + $one = One::query()->create(); + $two = $one->twos()->create(); + $two->threes()->create(); + + $model = One::query() + ->with('twos') + ->find($one->id); + + $this->assertTrue($model->relationLoaded('twos')); + $this->assertFalse($model->relationLoaded('twos.threes')); + } + + public function testWhenChildRelationIsLoaded() + { + $one = One::query()->create(); + $two = $one->twos()->create(); + $two->threes()->create(); + + $model = One::query() + ->with('twos.threes') + ->find($one->id); + + $this->assertTrue($model->relationLoaded('twos')); + $this->assertTrue($model->relationLoaded('twos.threes')); + } + + public function testWhenChildRecursiveRelationIsLoaded() + { + $one = One::query()->create(); + $two = $one->twos()->create(); + $two->threes()->create(['one_id' => $one->id]); + + $model = One::query() + ->with('twos.threes.one') + ->find($one->id); + + $this->assertTrue($model->relationLoaded('twos')); + $this->assertTrue($model->relationLoaded('twos.threes')); + $this->assertTrue($model->relationLoaded('twos.threes.one')); + } +} + +class One extends Model +{ + public $table = 'ones'; + public $timestamps = false; + protected $guarded = []; + + public function twos(): HasMany + { + return $this->hasMany(Two::class, 'one_id'); + } +} + +class Two extends Model +{ + public $table = 'twos'; + public $timestamps = false; + protected $guarded = []; + + public function one(): BelongsTo + { + return $this->belongsTo(One::class, 'one_id'); + } + + public function threes(): HasMany + { + return $this->hasMany(Three::class, 'two_id'); + } +} + +class Three extends Model +{ + public $table = 'threes'; + public $timestamps = false; + protected $guarded = []; + + public function one(): BelongsTo + { + return $this->belongsTo(One::class, 'one_id'); + } + + public function two(): BelongsTo + { + return $this->belongsTo(Two::class, 'two_id'); + } +}
diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php index 79a2f5d98cd..6893c1284e3 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php @@ -1072,7 +1072,28 @@ public function getRelation($relation) */ public function relationLoaded($key) { - return array_key_exists($key, $this->relations); + if (array_key_exists($key, $this->relations)) { + return true; + [$relation, $nestedRelation] = array_replace( + [null, null], + explode('.', $key, 2), + ); + return false; + if ($nestedRelation !== null) { + foreach ($this->$relation as $related) { + if (! $related->relationLoaded($nestedRelation)) { + } + return true; } /** diff --git a/tests/Integration/Database/EloquentModelRelationLoadedTest.php b/tests/Integration/Database/EloquentModelRelationLoadedTest.php new file mode 100644 index 00000000000..06a0a740d3b --- /dev/null +++ b/tests/Integration/Database/EloquentModelRelationLoadedTest.php @@ -0,0 +1,168 @@ +<?php +namespace Illuminate\Tests\Integration\Database\EloquentModelRelationLoadedTest; +use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Relations\BelongsTo; +use Illuminate\Database\Eloquent\Relations\HasMany; +use Illuminate\Database\Schema\Blueprint; +use Illuminate\Tests\Integration\Database\DatabaseTestCase; +class EloquentModelRelationLoadedTest extends DatabaseTestCase + protected function afterRefreshingDatabase() + Schema::create('ones', function (Blueprint $table) { + Schema::create('twos', function (Blueprint $table) { + $table->integer('one_id'); + Schema::create('threes', function (Blueprint $table) { + $table->integer('two_id'); + $table->integer('one_id')->nullable(); + public function testWhenRelationIsInvalid() + $this->assertFalse($model->relationLoaded('.')); + public function testWhenNestedRelationIsInvalid() + $this->assertFalse($model->relationLoaded('twos.')); + public function testWhenRelationNotLoaded() + $model = One::query()->find($one->id); + $this->assertFalse($model->relationLoaded('twos')); + public function testWhenRelationLoaded() + public function testWhenChildRelationIsNotLoaded() + $this->assertFalse($model->relationLoaded('twos.threes')); + public function testWhenChildRelationIsLoaded() + ->with('twos.threes') + public function testWhenChildRecursiveRelationIsLoaded() + $two->threes()->create(['one_id' => $one->id]); + ->with('twos.threes.one') + $this->assertTrue($model->relationLoaded('twos.threes.one')); +class One extends Model + public $table = 'ones'; + public function twos(): HasMany + return $this->hasMany(Two::class, 'one_id'); +class Two extends Model + public $table = 'twos'; + public function threes(): HasMany + return $this->hasMany(Three::class, 'two_id'); +class Three extends Model + public $table = 'threes'; + public function two(): BelongsTo + return $this->belongsTo(Two::class, 'two_id');
[ "+ if (! array_key_exists($relation, $this->relations)) {", "+ return false;", "+ }", "+use Illuminate\\Support\\Facades\\Schema;", "+ $this->assertFalse($model->relationLoaded('invalid'));", "+ $this->assertFalse($model->relationLoaded('twos.invalid'));" ]
[ 18, 25, 26, 48, 81, 94 ]
{ "additions": 190, "author": "tmsperera", "deletions": 1, "html_url": "https://github.com/laravel/framework/pull/55471", "issue_id": 55471, "merged_at": "2025-04-21T14:32:31Z", "omission_probability": 0.1, "pr_number": 55471, "repo": "laravel/framework", "title": "[12.x] Support nested relations on `relationLoaded` method", "total_changes": 191 }
9
diff --git a/src/Illuminate/View/Compilers/Compiler.php b/src/Illuminate/View/Compilers/Compiler.php index dbd349e69e2..1e61eae9593 100755 --- a/src/Illuminate/View/Compilers/Compiler.php +++ b/src/Illuminate/View/Compilers/Compiler.php @@ -44,6 +44,13 @@ abstract class Compiler */ protected $compiledExtension = 'php'; + /** + * Indicates if view cache timestamps should be checked. + * + * @var bool + */ + protected $shouldCheckTimestamps; + /** * Create a new compiler instance. * @@ -51,6 +58,7 @@ abstract class Compiler * @param string $cachePath * @param string $basePath * @param bool $shouldCache + * @param bool $shouldCheckTimestamps * @param string $compiledExtension * * @throws \InvalidArgumentException @@ -61,6 +69,7 @@ public function __construct( $basePath = '', $shouldCache = true, $compiledExtension = 'php', + $shouldCheckTimestamps = true, ) { if (! $cachePath) { throw new InvalidArgumentException('Please provide a valid cache path.'); @@ -71,6 +80,7 @@ public function __construct( $this->basePath = $basePath; $this->shouldCache = $shouldCache; $this->compiledExtension = $compiledExtension; + $this->shouldCheckTimestamps = $shouldCheckTimestamps; } /** @@ -107,6 +117,10 @@ public function isExpired($path) return true; } + if (! $this->shouldCheckTimestamps) { + return false; + } + try { return $this->files->lastModified($path) >= $this->files->lastModified($compiled); diff --git a/src/Illuminate/View/ViewServiceProvider.php b/src/Illuminate/View/ViewServiceProvider.php index 41cd8b93c9a..2ef3d31177b 100755 --- a/src/Illuminate/View/ViewServiceProvider.php +++ b/src/Illuminate/View/ViewServiceProvider.php @@ -100,6 +100,7 @@ public function registerBladeCompiler() $app['config']->get('view.relative_hash', false) ? $app->basePath() : '', $app['config']->get('view.cache', true), $app['config']->get('view.compiled_extension', 'php'), + $app['config']->get('view.check_cache_timestamps', true), ), function ($blade) { $blade->component('dynamic-component', DynamicComponent::class); }); diff --git a/tests/View/ViewBladeCompilerTest.php b/tests/View/ViewBladeCompilerTest.php index ed59a62fbbe..b26693489c8 100644 --- a/tests/View/ViewBladeCompilerTest.php +++ b/tests/View/ViewBladeCompilerTest.php @@ -51,10 +51,17 @@ public function testIsExpiredReturnsFalseWhenUseCacheIsTrueAndNoFileModification public function testIsExpiredReturnsTrueWhenUseCacheIsFalse() { - $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__, $basePath = '', $useCache = false); + $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__, shouldCache: false); $this->assertTrue($compiler->isExpired('foo')); } + public function testIsExpiredReturnsFalseWhenIgnoreCacheTimestampsIsTrue() + { + $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__, shouldCheckTimestamps: false); + $files->shouldReceive('exists')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php')->andReturn(true); + $this->assertFalse($compiler->isExpired('foo')); + } + public function testCompilePathIsProperlyCreated() { $compiler = new BladeCompiler($this->getFiles(), __DIR__);
diff --git a/src/Illuminate/View/Compilers/Compiler.php b/src/Illuminate/View/Compilers/Compiler.php index dbd349e69e2..1e61eae9593 100755 --- a/src/Illuminate/View/Compilers/Compiler.php +++ b/src/Illuminate/View/Compilers/Compiler.php @@ -44,6 +44,13 @@ abstract class Compiler */ protected $compiledExtension = 'php'; + /** + * Indicates if view cache timestamps should be checked. + * @var bool + */ + protected $shouldCheckTimestamps; * Create a new compiler instance. @@ -51,6 +58,7 @@ abstract class Compiler * @param string $cachePath * @param string $basePath * @param bool $shouldCache + * @param bool $shouldCheckTimestamps * @param string $compiledExtension * @throws \InvalidArgumentException @@ -61,6 +69,7 @@ public function __construct( $basePath = '', $shouldCache = true, $compiledExtension = 'php', + $shouldCheckTimestamps = true, ) { if (! $cachePath) { throw new InvalidArgumentException('Please provide a valid cache path.'); @@ -71,6 +80,7 @@ public function __construct( $this->basePath = $basePath; $this->shouldCache = $shouldCache; $this->compiledExtension = $compiledExtension; @@ -107,6 +117,10 @@ public function isExpired($path) return true; } + if (! $this->shouldCheckTimestamps) { try { return $this->files->lastModified($path) >= $this->files->lastModified($compiled); diff --git a/src/Illuminate/View/ViewServiceProvider.php b/src/Illuminate/View/ViewServiceProvider.php index 41cd8b93c9a..2ef3d31177b 100755 --- a/src/Illuminate/View/ViewServiceProvider.php +++ b/src/Illuminate/View/ViewServiceProvider.php @@ -100,6 +100,7 @@ public function registerBladeCompiler() $app['config']->get('view.relative_hash', false) ? $app->basePath() : '', $app['config']->get('view.cache', true), $app['config']->get('view.compiled_extension', 'php'), + $app['config']->get('view.check_cache_timestamps', true), ), function ($blade) { $blade->component('dynamic-component', DynamicComponent::class); }); diff --git a/tests/View/ViewBladeCompilerTest.php b/tests/View/ViewBladeCompilerTest.php index ed59a62fbbe..b26693489c8 100644 --- a/tests/View/ViewBladeCompilerTest.php +++ b/tests/View/ViewBladeCompilerTest.php @@ -51,10 +51,17 @@ public function testIsExpiredReturnsFalseWhenUseCacheIsTrueAndNoFileModification public function testIsExpiredReturnsTrueWhenUseCacheIsFalse() - $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__, $basePath = '', $useCache = false); + $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__, shouldCache: false); $this->assertTrue($compiler->isExpired('foo')); + public function testIsExpiredReturnsFalseWhenIgnoreCacheTimestampsIsTrue() + { + $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__, shouldCheckTimestamps: false); + $files->shouldReceive('exists')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php')->andReturn(true); + $this->assertFalse($compiler->isExpired('foo')); public function testCompilePathIsProperlyCreated() $compiler = new BladeCompiler($this->getFiles(), __DIR__);
[ "+ *", "+ $this->shouldCheckTimestamps = $shouldCheckTimestamps;", "+ return false;", "+ }", "+ }" ]
[ 10, 38, 47, 48, 83 ]
{ "additions": 23, "author": "pizkaz", "deletions": 1, "html_url": "https://github.com/laravel/framework/pull/55536", "issue_id": 55536, "merged_at": "2025-04-24T14:29:34Z", "omission_probability": 0.1, "pr_number": 55536, "repo": "laravel/framework", "title": "Add config option to ignore view cache timestamps", "total_changes": 24 }
10
diff --git a/src/Illuminate/Queue/BeanstalkdQueue.php b/src/Illuminate/Queue/BeanstalkdQueue.php index d1f64e98249..56e9c4e0664 100755 --- a/src/Illuminate/Queue/BeanstalkdQueue.php +++ b/src/Illuminate/Queue/BeanstalkdQueue.php @@ -125,7 +125,7 @@ public function later($delay, $job, $data = '', $queue = null) { return $this->enqueueUsing( $job, - $this->createPayload($job, $this->getQueue($queue), $data), + $this->createPayload($job, $this->getQueue($queue), $data, $delay), $queue, $delay, function ($payload, $queue, $delay) { diff --git a/src/Illuminate/Queue/DatabaseQueue.php b/src/Illuminate/Queue/DatabaseQueue.php index 0e6163a2c26..41d04e2b001 100644 --- a/src/Illuminate/Queue/DatabaseQueue.php +++ b/src/Illuminate/Queue/DatabaseQueue.php @@ -126,7 +126,7 @@ public function later($delay, $job, $data = '', $queue = null) { return $this->enqueueUsing( $job, - $this->createPayload($job, $this->getQueue($queue), $data), + $this->createPayload($job, $this->getQueue($queue), $data, $delay), $queue, $delay, function ($payload, $queue, $delay) { diff --git a/src/Illuminate/Queue/Queue.php b/src/Illuminate/Queue/Queue.php index a5f831957b0..49b3cdda6f2 100755 --- a/src/Illuminate/Queue/Queue.php +++ b/src/Illuminate/Queue/Queue.php @@ -2,6 +2,7 @@ namespace Illuminate\Queue; +use Carbon\Carbon; use Closure; use DateTimeInterface; use Illuminate\Bus\UniqueLock; @@ -97,17 +98,24 @@ public function bulk($jobs, $data = '', $queue = null) * @param \Closure|string|object $job * @param string $queue * @param mixed $data + * @param \DateTimeInterface|\DateInterval|int|null $delay * @return string * * @throws \Illuminate\Queue\InvalidPayloadException */ - protected function createPayload($job, $queue, $data = '') + protected function createPayload($job, $queue, $data = '', $delay = null) { if ($job instanceof Closure) { $job = CallQueuedClosure::create($job); } - $payload = json_encode($value = $this->createPayloadArray($job, $queue, $data), \JSON_UNESCAPED_UNICODE); + $value = $this->createPayloadArray($job, $queue, $data); + + $value['delay'] = isset($delay) + ? $this->secondsUntil($delay) + : null; + + $payload = json_encode($value, \JSON_UNESCAPED_UNICODE); if (json_last_error() !== JSON_ERROR_NONE) { throw new InvalidPayloadException( @@ -156,6 +164,7 @@ protected function createObjectPayload($job, $queue) 'commandName' => $job, 'command' => $job, ], + 'createdAt' => Carbon::now()->getTimestamp(), ]); $command = $this->jobShouldBeEncrypted($job) && $this->container->bound(Encrypter::class) @@ -277,6 +286,7 @@ protected function createStringPayload($job, $queue, $data) 'backoff' => null, 'timeout' => null, 'data' => $data, + 'createdAt' => Carbon::now()->getTimestamp(), ]); } diff --git a/src/Illuminate/Queue/RedisQueue.php b/src/Illuminate/Queue/RedisQueue.php index e8d6d77c7a5..84cfbde358c 100644 --- a/src/Illuminate/Queue/RedisQueue.php +++ b/src/Illuminate/Queue/RedisQueue.php @@ -192,7 +192,7 @@ public function later($delay, $job, $data = '', $queue = null) { return $this->enqueueUsing( $job, - $this->createPayload($job, $this->getQueue($queue), $data), + $this->createPayload($job, $this->getQueue($queue), $data, $delay), $queue, $delay, function ($payload, $queue, $delay) { diff --git a/src/Illuminate/Queue/SqsQueue.php b/src/Illuminate/Queue/SqsQueue.php index 0d74b8dda43..a128be81109 100755 --- a/src/Illuminate/Queue/SqsQueue.php +++ b/src/Illuminate/Queue/SqsQueue.php @@ -128,7 +128,7 @@ public function later($delay, $job, $data = '', $queue = null) { return $this->enqueueUsing( $job, - $this->createPayload($job, $queue ?: $this->default, $data), + $this->createPayload($job, $queue ?: $this->default, $data, $delay), $queue, $delay, function ($payload, $queue, $delay) { diff --git a/tests/Queue/QueueBeanstalkdQueueTest.php b/tests/Queue/QueueBeanstalkdQueueTest.php index ba34a706930..dfa4eace4a1 100755 --- a/tests/Queue/QueueBeanstalkdQueueTest.php +++ b/tests/Queue/QueueBeanstalkdQueueTest.php @@ -2,6 +2,7 @@ namespace Illuminate\Tests\Queue; +use Carbon\Carbon; use Illuminate\Container\Container; use Illuminate\Queue\BeanstalkdQueue; use Illuminate\Queue\Jobs\BeanstalkdJob; @@ -38,6 +39,9 @@ public function testPushProperlyPushesJobOntoBeanstalkd() { $uuid = Str::uuid(); + $time = Carbon::now(); + Carbon::setTestNow($time); + Str::createUuidsUsing(function () use ($uuid) { return $uuid; }); @@ -46,13 +50,14 @@ public function testPushProperlyPushesJobOntoBeanstalkd() $pheanstalk = $this->queue->getPheanstalk(); $pheanstalk->shouldReceive('useTube')->once()->with(m::type(TubeName::class)); $pheanstalk->shouldReceive('useTube')->once()->with(m::type(TubeName::class)); - $pheanstalk->shouldReceive('put')->twice()->with(json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data']]), 1024, 0, 60); + $pheanstalk->shouldReceive('put')->twice()->with(json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'delay' => null]), 1024, 0, 60); $this->queue->push('foo', ['data'], 'stack'); $this->queue->push('foo', ['data']); $this->container->shouldHaveReceived('bound')->with('events')->times(4); + Carbon::setTestNow(); Str::createUuidsNormally(); } @@ -64,17 +69,21 @@ public function testDelayedPushProperlyPushesJobOntoBeanstalkd() return $uuid; }); + $time = Carbon::now(); + Carbon::setTestNow($time); + $this->setQueue('default', 60); $pheanstalk = $this->queue->getPheanstalk(); $pheanstalk->shouldReceive('useTube')->once()->with(m::type(TubeName::class)); $pheanstalk->shouldReceive('useTube')->once()->with(m::type(TubeName::class)); - $pheanstalk->shouldReceive('put')->twice()->with(json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data']]), Pheanstalk::DEFAULT_PRIORITY, 5, Pheanstalk::DEFAULT_TTR); + $pheanstalk->shouldReceive('put')->twice()->with(json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'delay' => 5]), Pheanstalk::DEFAULT_PRIORITY, 5, Pheanstalk::DEFAULT_TTR); $this->queue->later(5, 'foo', ['data'], 'stack'); $this->queue->later(5, 'foo', ['data']); $this->container->shouldHaveReceived('bound')->with('events')->times(4); + Carbon::setTestNow(); Str::createUuidsNormally(); } diff --git a/tests/Queue/QueueDatabaseQueueUnitTest.php b/tests/Queue/QueueDatabaseQueueUnitTest.php index 3714b99a80b..9702a4d6695 100644 --- a/tests/Queue/QueueDatabaseQueueUnitTest.php +++ b/tests/Queue/QueueDatabaseQueueUnitTest.php @@ -2,6 +2,7 @@ namespace Illuminate\Tests\Queue; +use Carbon\Carbon; use Illuminate\Container\Container; use Illuminate\Database\Connection; use Illuminate\Queue\DatabaseQueue; @@ -69,6 +70,9 @@ public function testDelayedPushProperlyPushesJobOntoDatabase() return $uuid; }); + $time = Carbon::now(); + Carbon::setTestNow($time); + $queue = $this->getMockBuilder(DatabaseQueue::class) ->onlyMethods(['currentTime']) ->setConstructorArgs([$database = m::mock(Connection::class), 'table', 'default']) @@ -76,9 +80,9 @@ public function testDelayedPushProperlyPushesJobOntoDatabase() $queue->expects($this->any())->method('currentTime')->willReturn('time'); $queue->setContainer($container = m::spy(Container::class)); $database->shouldReceive('table')->with('table')->andReturn($query = m::mock(stdClass::class)); - $query->shouldReceive('insertGetId')->once()->andReturnUsing(function ($array) use ($uuid) { + $query->shouldReceive('insertGetId')->once()->andReturnUsing(function ($array) use ($uuid, $time) { $this->assertSame('default', $array['queue']); - $this->assertSame(json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data']]), $array['payload']); + $this->assertSame(json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'delay' => 10]), $array['payload']); $this->assertEquals(0, $array['attempts']); $this->assertNull($array['reserved_at']); $this->assertIsInt($array['available_at']); @@ -88,6 +92,7 @@ public function testDelayedPushProperlyPushesJobOntoDatabase() $container->shouldHaveReceived('bound')->with('events')->twice(); + Carbon::setTestNow(); Str::createUuidsNormally(); } @@ -130,22 +135,25 @@ public function testBulkBatchPushesOntoDatabase() return $uuid; }); + $time = Carbon::now(); + Carbon::setTestNow($time); + $database = m::mock(Connection::class); $queue = $this->getMockBuilder(DatabaseQueue::class)->onlyMethods(['currentTime', 'availableAt'])->setConstructorArgs([$database, 'table', 'default'])->getMock(); $queue->expects($this->any())->method('currentTime')->willReturn('created'); $queue->expects($this->any())->method('availableAt')->willReturn('available'); $database->shouldReceive('table')->with('table')->andReturn($query = m::mock(stdClass::class)); - $query->shouldReceive('insert')->once()->andReturnUsing(function ($records) use ($uuid) { + $query->shouldReceive('insert')->once()->andReturnUsing(function ($records) use ($uuid, $time) { $this->assertEquals([[ 'queue' => 'queue', - 'payload' => json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data']]), + 'payload' => json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'delay' => null]), 'attempts' => 0, 'reserved_at' => null, 'available_at' => 'available', 'created_at' => 'created', ], [ 'queue' => 'queue', - 'payload' => json_encode(['uuid' => $uuid, 'displayName' => 'bar', 'job' => 'bar', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data']]), + 'payload' => json_encode(['uuid' => $uuid, 'displayName' => 'bar', 'job' => 'bar', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'delay' => null]), 'attempts' => 0, 'reserved_at' => null, 'available_at' => 'available', @@ -155,6 +163,7 @@ public function testBulkBatchPushesOntoDatabase() $queue->bulk(['foo', 'bar'], ['data'], 'queue'); + Carbon::setTestNow(); Str::createUuidsNormally(); } diff --git a/tests/Queue/QueueRedisQueueTest.php b/tests/Queue/QueueRedisQueueTest.php index 007f743653d..7ea0bfdbe07 100644 --- a/tests/Queue/QueueRedisQueueTest.php +++ b/tests/Queue/QueueRedisQueueTest.php @@ -27,16 +27,20 @@ public function testPushProperlyPushesJobOntoRedis() return $uuid; }); + $time = Carbon::now(); + Carbon::setTestNow($time); + $queue = $this->getMockBuilder(RedisQueue::class)->onlyMethods(['getRandomId'])->setConstructorArgs([$redis = m::mock(Factory::class), 'default'])->getMock(); $queue->expects($this->once())->method('getRandomId')->willReturn('foo'); $queue->setContainer($container = m::spy(Container::class)); $redis->shouldReceive('connection')->once()->andReturn($redis); - $redis->shouldReceive('eval')->once()->with(LuaScripts::push(), 2, 'queues:default', 'queues:default:notify', json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'id' => 'foo', 'attempts' => 0])); + $redis->shouldReceive('eval')->once()->with(LuaScripts::push(), 2, 'queues:default', 'queues:default:notify', json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'id' => 'foo', 'attempts' => 0, 'delay' => null])); $id = $queue->push('foo', ['data']); $this->assertSame('foo', $id); $container->shouldHaveReceived('bound')->with('events')->twice(); + Carbon::setTestNow(); Str::createUuidsNormally(); } @@ -48,11 +52,14 @@ public function testPushProperlyPushesJobOntoRedisWithCustomPayloadHook() return $uuid; }); + $time = Carbon::now(); + Carbon::setTestNow($time); + $queue = $this->getMockBuilder(RedisQueue::class)->onlyMethods(['getRandomId'])->setConstructorArgs([$redis = m::mock(Factory::class), 'default'])->getMock(); $queue->expects($this->once())->method('getRandomId')->willReturn('foo'); $queue->setContainer($container = m::spy(Container::class)); $redis->shouldReceive('connection')->once()->andReturn($redis); - $redis->shouldReceive('eval')->once()->with(LuaScripts::push(), 2, 'queues:default', 'queues:default:notify', json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'custom' => 'taylor', 'id' => 'foo', 'attempts' => 0])); + $redis->shouldReceive('eval')->once()->with(LuaScripts::push(), 2, 'queues:default', 'queues:default:notify', json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'custom' => 'taylor', 'id' => 'foo', 'attempts' => 0, 'delay' => null])); Queue::createPayloadUsing(function ($connection, $queue, $payload) { return ['custom' => 'taylor']; @@ -64,6 +71,7 @@ public function testPushProperlyPushesJobOntoRedisWithCustomPayloadHook() Queue::createPayloadUsing(null); + Carbon::setTestNow(); Str::createUuidsNormally(); } @@ -75,11 +83,14 @@ public function testPushProperlyPushesJobOntoRedisWithTwoCustomPayloadHook() return $uuid; }); + $time = Carbon::now(); + Carbon::setTestNow($time); + $queue = $this->getMockBuilder(RedisQueue::class)->onlyMethods(['getRandomId'])->setConstructorArgs([$redis = m::mock(Factory::class), 'default'])->getMock(); $queue->expects($this->once())->method('getRandomId')->willReturn('foo'); $queue->setContainer($container = m::spy(Container::class)); $redis->shouldReceive('connection')->once()->andReturn($redis); - $redis->shouldReceive('eval')->once()->with(LuaScripts::push(), 2, 'queues:default', 'queues:default:notify', json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'custom' => 'taylor', 'bar' => 'foo', 'id' => 'foo', 'attempts' => 0])); + $redis->shouldReceive('eval')->once()->with(LuaScripts::push(), 2, 'queues:default', 'queues:default:notify', json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'custom' => 'taylor', 'bar' => 'foo', 'id' => 'foo', 'attempts' => 0, 'delay' => null])); Queue::createPayloadUsing(function ($connection, $queue, $payload) { return ['custom' => 'taylor']; @@ -95,6 +106,7 @@ public function testPushProperlyPushesJobOntoRedisWithTwoCustomPayloadHook() Queue::createPayloadUsing(null); + Carbon::setTestNow(); Str::createUuidsNormally(); } @@ -106,6 +118,9 @@ public function testDelayedPushProperlyPushesJobOntoRedis() return $uuid; }); + $time = Carbon::now(); + Carbon::setTestNow($time); + $queue = $this->getMockBuilder(RedisQueue::class)->onlyMethods(['availableAt', 'getRandomId'])->setConstructorArgs([$redis = m::mock(Factory::class), 'default'])->getMock(); $queue->setContainer($container = m::spy(Container::class)); $queue->expects($this->once())->method('getRandomId')->willReturn('foo'); @@ -115,13 +130,14 @@ public function testDelayedPushProperlyPushesJobOntoRedis() $redis->shouldReceive('zadd')->once()->with( 'queues:default:delayed', 2, - json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'id' => 'foo', 'attempts' => 0]) + json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'id' => 'foo', 'attempts' => 0, 'delay' => 1]) ); $id = $queue->later(1, 'foo', ['data']); $this->assertSame('foo', $id); $container->shouldHaveReceived('bound')->with('events')->twice(); + Carbon::setTestNow(); Str::createUuidsNormally(); } @@ -133,22 +149,24 @@ public function testDelayedPushWithDateTimeProperlyPushesJobOntoRedis() return $uuid; }); - $date = Carbon::now(); + $time = $date = Carbon::now(); + Carbon::setTestNow($time); $queue = $this->getMockBuilder(RedisQueue::class)->onlyMethods(['availableAt', 'getRandomId'])->setConstructorArgs([$redis = m::mock(Factory::class), 'default'])->getMock(); $queue->setContainer($container = m::spy(Container::class)); $queue->expects($this->once())->method('getRandomId')->willReturn('foo'); - $queue->expects($this->once())->method('availableAt')->with($date)->willReturn(2); + $queue->expects($this->once())->method('availableAt')->with($date)->willReturn(5); $redis->shouldReceive('connection')->once()->andReturn($redis); $redis->shouldReceive('zadd')->once()->with( 'queues:default:delayed', - 2, - json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'id' => 'foo', 'attempts' => 0]) + 5, + json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'id' => 'foo', 'attempts' => 0, 'delay' => 5]) ); - $queue->later($date, 'foo', ['data']); + $queue->later($date->addSeconds(5), 'foo', ['data']); $container->shouldHaveReceived('bound')->with('events')->twice(); + Carbon::setTestNow(); Str::createUuidsNormally(); } }
diff --git a/src/Illuminate/Queue/BeanstalkdQueue.php b/src/Illuminate/Queue/BeanstalkdQueue.php index d1f64e98249..56e9c4e0664 100755 --- a/src/Illuminate/Queue/BeanstalkdQueue.php +++ b/src/Illuminate/Queue/BeanstalkdQueue.php @@ -125,7 +125,7 @@ public function later($delay, $job, $data = '', $queue = null) diff --git a/src/Illuminate/Queue/DatabaseQueue.php b/src/Illuminate/Queue/DatabaseQueue.php index 0e6163a2c26..41d04e2b001 100644 --- a/src/Illuminate/Queue/DatabaseQueue.php +++ b/src/Illuminate/Queue/DatabaseQueue.php @@ -126,7 +126,7 @@ public function later($delay, $job, $data = '', $queue = null) diff --git a/src/Illuminate/Queue/Queue.php b/src/Illuminate/Queue/Queue.php index a5f831957b0..49b3cdda6f2 100755 --- a/src/Illuminate/Queue/Queue.php +++ b/src/Illuminate/Queue/Queue.php namespace Illuminate\Queue; use Closure; use DateTimeInterface; use Illuminate\Bus\UniqueLock; @@ -97,17 +98,24 @@ public function bulk($jobs, $data = '', $queue = null) * @param \Closure|string|object $job * @param string $queue * @param mixed $data + * @param \DateTimeInterface|\DateInterval|int|null $delay * @return string * * @throws \Illuminate\Queue\InvalidPayloadException */ - protected function createPayload($job, $queue, $data = '') + protected function createPayload($job, $queue, $data = '', $delay = null) if ($job instanceof Closure) { $job = CallQueuedClosure::create($job); } - $payload = json_encode($value = $this->createPayloadArray($job, $queue, $data), \JSON_UNESCAPED_UNICODE); + $value = $this->createPayloadArray($job, $queue, $data); + $value['delay'] = isset($delay) + ? $this->secondsUntil($delay) + : null; + $payload = json_encode($value, \JSON_UNESCAPED_UNICODE); if (json_last_error() !== JSON_ERROR_NONE) { throw new InvalidPayloadException( @@ -156,6 +164,7 @@ protected function createObjectPayload($job, $queue) 'commandName' => $job, 'command' => $job, ], $command = $this->jobShouldBeEncrypted($job) && $this->container->bound(Encrypter::class) @@ -277,6 +286,7 @@ protected function createStringPayload($job, $queue, $data) 'backoff' => null, 'timeout' => null, 'data' => $data, diff --git a/src/Illuminate/Queue/RedisQueue.php b/src/Illuminate/Queue/RedisQueue.php index e8d6d77c7a5..84cfbde358c 100644 --- a/src/Illuminate/Queue/RedisQueue.php +++ b/src/Illuminate/Queue/RedisQueue.php @@ -192,7 +192,7 @@ public function later($delay, $job, $data = '', $queue = null) diff --git a/src/Illuminate/Queue/SqsQueue.php b/src/Illuminate/Queue/SqsQueue.php index 0d74b8dda43..a128be81109 100755 --- a/src/Illuminate/Queue/SqsQueue.php +++ b/src/Illuminate/Queue/SqsQueue.php @@ -128,7 +128,7 @@ public function later($delay, $job, $data = '', $queue = null) - $this->createPayload($job, $queue ?: $this->default, $data), diff --git a/tests/Queue/QueueBeanstalkdQueueTest.php b/tests/Queue/QueueBeanstalkdQueueTest.php index ba34a706930..dfa4eace4a1 100755 --- a/tests/Queue/QueueBeanstalkdQueueTest.php +++ b/tests/Queue/QueueBeanstalkdQueueTest.php use Illuminate\Queue\BeanstalkdQueue; use Illuminate\Queue\Jobs\BeanstalkdJob; @@ -38,6 +39,9 @@ public function testPushProperlyPushesJobOntoBeanstalkd() $uuid = Str::uuid(); Str::createUuidsUsing(function () use ($uuid) { @@ -46,13 +50,14 @@ public function testPushProperlyPushesJobOntoBeanstalkd() - $pheanstalk->shouldReceive('put')->twice()->with(json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data']]), 1024, 0, 60); + $pheanstalk->shouldReceive('put')->twice()->with(json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'delay' => null]), 1024, 0, 60); $this->queue->push('foo', ['data'], 'stack'); $this->queue->push('foo', ['data']); @@ -64,17 +69,21 @@ public function testDelayedPushProperlyPushesJobOntoBeanstalkd() $this->setQueue('default', 60); - $pheanstalk->shouldReceive('put')->twice()->with(json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data']]), Pheanstalk::DEFAULT_PRIORITY, 5, Pheanstalk::DEFAULT_TTR); + $pheanstalk->shouldReceive('put')->twice()->with(json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'delay' => 5]), Pheanstalk::DEFAULT_PRIORITY, 5, Pheanstalk::DEFAULT_TTR); $this->queue->later(5, 'foo', ['data'], 'stack'); $this->queue->later(5, 'foo', ['data']); diff --git a/tests/Queue/QueueDatabaseQueueUnitTest.php b/tests/Queue/QueueDatabaseQueueUnitTest.php index 3714b99a80b..9702a4d6695 100644 --- a/tests/Queue/QueueDatabaseQueueUnitTest.php +++ b/tests/Queue/QueueDatabaseQueueUnitTest.php use Illuminate\Database\Connection; use Illuminate\Queue\DatabaseQueue; @@ -69,6 +70,9 @@ public function testDelayedPushProperlyPushesJobOntoDatabase() $queue = $this->getMockBuilder(DatabaseQueue::class) ->onlyMethods(['currentTime']) ->setConstructorArgs([$database = m::mock(Connection::class), 'table', 'default']) @@ -76,9 +80,9 @@ public function testDelayedPushProperlyPushesJobOntoDatabase() $queue->expects($this->any())->method('currentTime')->willReturn('time'); - $query->shouldReceive('insertGetId')->once()->andReturnUsing(function ($array) use ($uuid) { $this->assertSame('default', $array['queue']); - $this->assertSame(json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data']]), $array['payload']); + $this->assertSame(json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'delay' => 10]), $array['payload']); $this->assertEquals(0, $array['attempts']); $this->assertNull($array['reserved_at']); $this->assertIsInt($array['available_at']); @@ -88,6 +92,7 @@ public function testDelayedPushProperlyPushesJobOntoDatabase() @@ -130,22 +135,25 @@ public function testBulkBatchPushesOntoDatabase() $database = m::mock(Connection::class); $queue = $this->getMockBuilder(DatabaseQueue::class)->onlyMethods(['currentTime', 'availableAt'])->setConstructorArgs([$database, 'table', 'default'])->getMock(); $queue->expects($this->any())->method('currentTime')->willReturn('created'); $queue->expects($this->any())->method('availableAt')->willReturn('available'); - $query->shouldReceive('insert')->once()->andReturnUsing(function ($records) use ($uuid) { + $query->shouldReceive('insert')->once()->andReturnUsing(function ($records) use ($uuid, $time) { $this->assertEquals([[ - 'payload' => json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data']]), 'created_at' => 'created', ], [ - 'payload' => json_encode(['uuid' => $uuid, 'displayName' => 'bar', 'job' => 'bar', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data']]), + 'payload' => json_encode(['uuid' => $uuid, 'displayName' => 'bar', 'job' => 'bar', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'delay' => null]), @@ -155,6 +163,7 @@ public function testBulkBatchPushesOntoDatabase() $queue->bulk(['foo', 'bar'], ['data'], 'queue'); diff --git a/tests/Queue/QueueRedisQueueTest.php b/tests/Queue/QueueRedisQueueTest.php index 007f743653d..7ea0bfdbe07 100644 --- a/tests/Queue/QueueRedisQueueTest.php +++ b/tests/Queue/QueueRedisQueueTest.php @@ -27,16 +27,20 @@ public function testPushProperlyPushesJobOntoRedis() - $redis->shouldReceive('eval')->once()->with(LuaScripts::push(), 2, 'queues:default', 'queues:default:notify', json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'id' => 'foo', 'attempts' => 0])); + $redis->shouldReceive('eval')->once()->with(LuaScripts::push(), 2, 'queues:default', 'queues:default:notify', json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'id' => 'foo', 'attempts' => 0, 'delay' => null])); $id = $queue->push('foo', ['data']); @@ -48,11 +52,14 @@ public function testPushProperlyPushesJobOntoRedisWithCustomPayloadHook() - $redis->shouldReceive('eval')->once()->with(LuaScripts::push(), 2, 'queues:default', 'queues:default:notify', json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'custom' => 'taylor', 'id' => 'foo', 'attempts' => 0])); + $redis->shouldReceive('eval')->once()->with(LuaScripts::push(), 2, 'queues:default', 'queues:default:notify', json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'custom' => 'taylor', 'id' => 'foo', 'attempts' => 0, 'delay' => null])); @@ -64,6 +71,7 @@ public function testPushProperlyPushesJobOntoRedisWithCustomPayloadHook() @@ -75,11 +83,14 @@ public function testPushProperlyPushesJobOntoRedisWithTwoCustomPayloadHook() - $redis->shouldReceive('eval')->once()->with(LuaScripts::push(), 2, 'queues:default', 'queues:default:notify', json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'custom' => 'taylor', 'bar' => 'foo', 'id' => 'foo', 'attempts' => 0])); + $redis->shouldReceive('eval')->once()->with(LuaScripts::push(), 2, 'queues:default', 'queues:default:notify', json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'custom' => 'taylor', 'bar' => 'foo', 'id' => 'foo', 'attempts' => 0, 'delay' => null])); @@ -95,6 +106,7 @@ public function testPushProperlyPushesJobOntoRedisWithTwoCustomPayloadHook() @@ -106,6 +118,9 @@ public function testDelayedPushProperlyPushesJobOntoRedis() @@ -115,13 +130,14 @@ public function testDelayedPushProperlyPushesJobOntoRedis() 2, + json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'id' => 'foo', 'attempts' => 0, 'delay' => 1]) $id = $queue->later(1, 'foo', ['data']); @@ -133,22 +149,24 @@ public function testDelayedPushWithDateTimeProperlyPushesJobOntoRedis() - $date = Carbon::now(); + $time = $date = Carbon::now(); - $queue->expects($this->once())->method('availableAt')->with($date)->willReturn(2); + $queue->expects($this->once())->method('availableAt')->with($date)->willReturn(5); - 2, + 5, + $queue->later($date->addSeconds(5), 'foo', ['data']); }
[ "+ $this->createPayload($job, $queue ?: $this->default, $data, $delay),", "+ $query->shouldReceive('insertGetId')->once()->andReturnUsing(function ($array) use ($uuid, $time) {", "+ 'payload' => json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'delay' => null]),", "+ json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'id' => 'foo', 'attempts' => 0, 'delay' => 5])", "- $queue->later($date, 'foo', ['data']);" ]
[ 103, 195, 227, 366, 369 ]
{ "additions": 68, "author": "taylorotwell", "deletions": 22, "html_url": "https://github.com/laravel/framework/pull/55529", "issue_id": 55529, "merged_at": "2025-04-24T14:15:22Z", "omission_probability": 0.1, "pr_number": 55529, "repo": "laravel/framework", "title": "Add payload creation and original delay info to job payload", "total_changes": 90 }
11
diff --git a/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php b/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php index 4142572207af..7451491cbaf9 100755 --- a/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php +++ b/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php @@ -436,6 +436,34 @@ public function createManyQuietly(iterable $records) return Model::withoutEvents(fn () => $this->createMany($records)); } + /** + * Create a Collection of new instances of the related model, allowing mass-assignment. + * + * @param iterable $records + * @return \Illuminate\Database\Eloquent\Collection<int, TRelatedModel> + */ + public function forceCreateMany(iterable $records) + { + $instances = $this->related->newCollection(); + + foreach ($records as $record) { + $instances->push($this->forceCreate($record)); + } + + return $instances; + } + + /** + * Create a Collection of new instances of the related model, allowing mass-assignment and without raising any events to the parent model. + * + * @param iterable $records + * @return \Illuminate\Database\Eloquent\Collection<int, TRelatedModel> + */ + public function forceCreateManyQuietly(iterable $records) + { + return Model::withoutEvents(fn () => $this->forceCreateMany($records)); + } + /** * Set the foreign ID for creating a related model. *
diff --git a/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php b/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php index 4142572207af..7451491cbaf9 100755 --- a/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php +++ b/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php @@ -436,6 +436,34 @@ public function createManyQuietly(iterable $records) return Model::withoutEvents(fn () => $this->createMany($records)); } + * Create a Collection of new instances of the related model, allowing mass-assignment. + public function forceCreateMany(iterable $records) + $instances = $this->related->newCollection(); + foreach ($records as $record) { + $instances->push($this->forceCreate($record)); + } + * Create a Collection of new instances of the related model, allowing mass-assignment and without raising any events to the parent model. + public function forceCreateManyQuietly(iterable $records) + return Model::withoutEvents(fn () => $this->forceCreateMany($records)); /** * Set the foreign ID for creating a related model. *
[ "+ return $instances;" ]
[ 22 ]
{ "additions": 28, "author": "onlime", "deletions": 0, "html_url": "https://github.com/laravel/framework/pull/55262", "issue_id": 55262, "merged_at": "2025-04-04T16:27:04Z", "omission_probability": 0.1, "pr_number": 55262, "repo": "laravel/framework", "title": "[12.x] Add createMany mass-assignment variants to `HasOneOrMany` relation", "total_changes": 28 }
12
diff --git a/src/Illuminate/View/Compilers/BladeCompiler.php b/src/Illuminate/View/Compilers/BladeCompiler.php index 48e5d734d90f..b17bde52bce7 100644 --- a/src/Illuminate/View/Compilers/BladeCompiler.php +++ b/src/Illuminate/View/Compilers/BladeCompiler.php @@ -193,7 +193,17 @@ public function compile($path = null) $compiledPath = $this->getCompiledPath($this->getPath()) ); - $this->files->put($compiledPath, $contents); + if (! $this->files->exists($compiledPath)) { + $this->files->put($compiledPath, $contents); + + return; + } + + $compiledHash = $this->files->hash($compiledPath, 'sha256'); + + if ($compiledHash !== hash('sha256', $contents)) { + $this->files->put($compiledPath, $contents); + } } } diff --git a/tests/View/ViewBladeCompilerTest.php b/tests/View/ViewBladeCompilerTest.php index c3955945e8ff..e69de4a3f46d 100644 --- a/tests/View/ViewBladeCompilerTest.php +++ b/tests/View/ViewBladeCompilerTest.php @@ -66,17 +66,42 @@ public function testCompileCompilesFileAndReturnsContents() $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World'); $files->shouldReceive('exists')->once()->with(__DIR__)->andReturn(true); + $files->shouldReceive('exists')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php')->andReturn(false); $files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php', 'Hello World<?php /**PATH foo ENDPATH**/ ?>'); $compiler->compile('foo'); } public function testCompileCompilesFileAndReturnsContentsCreatingDirectory() { + $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); + $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World'); + $files->shouldReceive('exists')->once()->with(__DIR__)->andReturn(true); + $files->shouldReceive('exists')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php')->andReturn(false); + $files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php', 'Hello World<?php /**PATH foo ENDPATH**/ ?>'); + $compiler->compile('foo'); + } + + public function testCompileUpdatesCacheIfChanged() + { + $compiledPath = __DIR__.'/'.hash('xxh128', 'v2foo').'.php'; + $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); + $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World'); + $files->shouldReceive('exists')->once()->with(__DIR__)->andReturn(true); + $files->shouldReceive('exists')->once()->with($compiledPath)->andReturn(true); + $files->shouldReceive('hash')->once()->with($compiledPath, 'sha256')->andReturn(hash('sha256', 'outdated content')); + $files->shouldReceive('put')->once()->with($compiledPath, 'Hello World<?php /**PATH foo ENDPATH**/ ?>'); + $compiler->compile('foo'); + } + + public function testCompileKeepsCacheIfUnchanged() + { + $compiledPath = __DIR__.'/'.hash('xxh128', 'v2foo').'.php'; $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World'); $files->shouldReceive('exists')->once()->with(__DIR__)->andReturn(false); $files->shouldReceive('makeDirectory')->once()->with(__DIR__, 0777, true, true); - $files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php', 'Hello World<?php /**PATH foo ENDPATH**/ ?>'); + $files->shouldReceive('exists')->once()->with($compiledPath)->andReturn(true); + $files->shouldReceive('hash')->once()->with($compiledPath, 'sha256')->andReturn(hash('sha256', 'Hello World<?php /**PATH foo ENDPATH**/ ?>')); $compiler->compile('foo'); } @@ -85,6 +110,7 @@ public function testCompileCompilesAndGetThePath() $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World'); $files->shouldReceive('exists')->once()->with(__DIR__)->andReturn(true); + $files->shouldReceive('exists')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php')->andReturn(false); $files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php', 'Hello World<?php /**PATH foo ENDPATH**/ ?>'); $compiler->compile('foo'); $this->assertSame('foo', $compiler->getPath()); @@ -102,6 +128,7 @@ public function testCompileWithPathSetBefore() $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World'); $files->shouldReceive('exists')->once()->with(__DIR__)->andReturn(true); + $files->shouldReceive('exists')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php')->andReturn(false); $files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php', 'Hello World<?php /**PATH foo ENDPATH**/ ?>'); // set path before compilation $compiler->setPath('foo'); @@ -132,6 +159,7 @@ public function testIncludePathToTemplate($content, $compiled) $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); $files->shouldReceive('get')->once()->with('foo')->andReturn($content); $files->shouldReceive('exists')->once()->with(__DIR__)->andReturn(true); + $files->shouldReceive('exists')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php')->andReturn(false); $files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php', $compiled); $compiler->compile('foo'); @@ -187,6 +215,7 @@ public function testDontIncludeEmptyPath() $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); $files->shouldReceive('get')->once()->with('')->andReturn('Hello World'); $files->shouldReceive('exists')->once()->with(__DIR__)->andReturn(true); + $files->shouldReceive('exists')->once()->with(__DIR__.'/'.hash('xxh128', 'v2').'.php')->andReturn(false); $files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2').'.php', 'Hello World'); $compiler->setPath(''); $compiler->compile(); @@ -197,6 +226,7 @@ public function testDontIncludeNullPath() $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); $files->shouldReceive('get')->once()->with(null)->andReturn('Hello World'); $files->shouldReceive('exists')->once()->with(__DIR__)->andReturn(true); + $files->shouldReceive('exists')->once()->with(__DIR__.'/'.hash('xxh128', 'v2').'.php')->andReturn(false); $files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2').'.php', 'Hello World'); $compiler->setPath(null); $compiler->compile();
diff --git a/src/Illuminate/View/Compilers/BladeCompiler.php b/src/Illuminate/View/Compilers/BladeCompiler.php index 48e5d734d90f..b17bde52bce7 100644 --- a/src/Illuminate/View/Compilers/BladeCompiler.php +++ b/src/Illuminate/View/Compilers/BladeCompiler.php @@ -193,7 +193,17 @@ public function compile($path = null) $compiledPath = $this->getCompiledPath($this->getPath()) ); - $this->files->put($compiledPath, $contents); + if (! $this->files->exists($compiledPath)) { + return; + if ($compiledHash !== hash('sha256', $contents)) { } diff --git a/tests/View/ViewBladeCompilerTest.php b/tests/View/ViewBladeCompilerTest.php index c3955945e8ff..e69de4a3f46d 100644 --- a/tests/View/ViewBladeCompilerTest.php +++ b/tests/View/ViewBladeCompilerTest.php @@ -66,17 +66,42 @@ public function testCompileCompilesFileAndReturnsContents() public function testCompileCompilesFileAndReturnsContentsCreatingDirectory() { + $files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php', 'Hello World<?php /**PATH foo ENDPATH**/ ?>'); + public function testCompileUpdatesCacheIfChanged() + $files->shouldReceive('hash')->once()->with($compiledPath, 'sha256')->andReturn(hash('sha256', 'outdated content')); + $files->shouldReceive('put')->once()->with($compiledPath, 'Hello World<?php /**PATH foo ENDPATH**/ ?>'); + public function testCompileKeepsCacheIfUnchanged() $files->shouldReceive('exists')->once()->with(__DIR__)->andReturn(false); $files->shouldReceive('makeDirectory')->once()->with(__DIR__, 0777, true, true); - $files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php', 'Hello World<?php /**PATH foo ENDPATH**/ ?>'); + $files->shouldReceive('hash')->once()->with($compiledPath, 'sha256')->andReturn(hash('sha256', 'Hello World<?php /**PATH foo ENDPATH**/ ?>')); @@ -85,6 +110,7 @@ public function testCompileCompilesAndGetThePath() $this->assertSame('foo', $compiler->getPath()); @@ -102,6 +128,7 @@ public function testCompileWithPathSetBefore() // set path before compilation $compiler->setPath('foo'); @@ -132,6 +159,7 @@ public function testIncludePathToTemplate($content, $compiled) $files->shouldReceive('get')->once()->with('foo')->andReturn($content); $files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php', $compiled); @@ -187,6 +215,7 @@ public function testDontIncludeEmptyPath() $files->shouldReceive('get')->once()->with('')->andReturn('Hello World'); $compiler->setPath(''); @@ -197,6 +226,7 @@ public function testDontIncludeNullPath() $files->shouldReceive('get')->once()->with(null)->andReturn('Hello World'); $compiler->setPath(null);
[ "+ $compiledHash = $this->files->hash($compiledPath, 'sha256');" ]
[ 15 ]
{ "additions": 42, "author": "pizkaz", "deletions": 2, "html_url": "https://github.com/laravel/framework/pull/55450", "issue_id": 55450, "merged_at": "2025-04-21T14:13:20Z", "omission_probability": 0.1, "pr_number": 55450, "repo": "laravel/framework", "title": "Update compiled views only if they actually changed", "total_changes": 44 }
13
diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php index 6893c1284e3..fc211e179a5 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php @@ -1086,7 +1086,11 @@ public function relationLoaded($key) } if ($nestedRelation !== null) { - foreach ($this->$relation as $related) { + $relatedModels = is_iterable($relatedModels = $this->$relation) + ? $relatedModels + : [$relatedModels]; + + foreach ($relatedModels as $related) { if (! $related->relationLoaded($nestedRelation)) { return false; } diff --git a/tests/Integration/Database/EloquentModelRelationLoadedTest.php b/tests/Integration/Database/EloquentModelRelationLoadedTest.php index 06a0a740d3b..548a50d1195 100644 --- a/tests/Integration/Database/EloquentModelRelationLoadedTest.php +++ b/tests/Integration/Database/EloquentModelRelationLoadedTest.php @@ -119,6 +119,22 @@ public function testWhenChildRecursiveRelationIsLoaded() $this->assertTrue($model->relationLoaded('twos.threes')); $this->assertTrue($model->relationLoaded('twos.threes.one')); } + + public function testWhenParentRelationIsASingleInstance() + { + $one = One::query()->create(); + $two = $one->twos()->create(); + $three = $two->threes()->create(); + + $model = Three::query() + ->with('two.one') + ->find($three->id); + + $this->assertTrue($model->relationLoaded('two')); + $this->assertTrue($model->two->is($two)); + $this->assertTrue($model->relationLoaded('two.one')); + $this->assertTrue($model->two->one->is($one)); + } } class One extends Model
diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php index 6893c1284e3..fc211e179a5 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php @@ -1086,7 +1086,11 @@ public function relationLoaded($key) } if ($nestedRelation !== null) { - foreach ($this->$relation as $related) { + ? $relatedModels + : [$relatedModels]; + foreach ($relatedModels as $related) { if (! $related->relationLoaded($nestedRelation)) { return false; } diff --git a/tests/Integration/Database/EloquentModelRelationLoadedTest.php b/tests/Integration/Database/EloquentModelRelationLoadedTest.php index 06a0a740d3b..548a50d1195 100644 --- a/tests/Integration/Database/EloquentModelRelationLoadedTest.php +++ b/tests/Integration/Database/EloquentModelRelationLoadedTest.php @@ -119,6 +119,22 @@ public function testWhenChildRecursiveRelationIsLoaded() $this->assertTrue($model->relationLoaded('twos.threes')); $this->assertTrue($model->relationLoaded('twos.threes.one')); } + public function testWhenParentRelationIsASingleInstance() + $one = One::query()->create(); + $two = $one->twos()->create(); + $three = $two->threes()->create(); + $model = Three::query() + ->with('two.one') + ->find($three->id); + $this->assertTrue($model->relationLoaded('two.one')); + $this->assertTrue($model->two->one->is($one)); + } } class One extends Model
[ "+ $relatedModels = is_iterable($relatedModels = $this->$relation)", "+ {", "+ $this->assertTrue($model->relationLoaded('two'));", "+ $this->assertTrue($model->two->is($two));" ]
[ 9, 27, 36, 37 ]
{ "additions": 21, "author": "rodrigopedra", "deletions": 1, "html_url": "https://github.com/laravel/framework/pull/55519", "issue_id": 55519, "merged_at": "2025-04-23T13:13:45Z", "omission_probability": 0.1, "pr_number": 55519, "repo": "laravel/framework", "title": "[12.x] Ensure related models is iterable on `HasRelationships@relationLoaded()`", "total_changes": 22 }
14
diff --git a/src/Illuminate/Testing/AssertableJsonString.php b/src/Illuminate/Testing/AssertableJsonString.php index 0bf221bea0da..d089ab071dc3 100644 --- a/src/Illuminate/Testing/AssertableJsonString.php +++ b/src/Illuminate/Testing/AssertableJsonString.php @@ -12,6 +12,8 @@ use Illuminate\Testing\Assert as PHPUnit; use JsonSerializable; +use function Illuminate\Support\enum_value; + class AssertableJsonString implements ArrayAccess, Countable { /** @@ -238,7 +240,7 @@ public function assertPath($path, $expect) if ($expect instanceof Closure) { PHPUnit::assertTrue($expect($this->json($path))); } else { - PHPUnit::assertSame($expect, $this->json($path)); + PHPUnit::assertSame(enum_value($expect), $this->json($path)); } return $this; diff --git a/tests/Testing/TestResponseTest.php b/tests/Testing/TestResponseTest.php index 9de88ddff3f3..cae497bdd133 100644 --- a/tests/Testing/TestResponseTest.php +++ b/tests/Testing/TestResponseTest.php @@ -1437,6 +1437,27 @@ public function testAssertJsonPathWithClosureCanFail() $response->assertJsonPath('data.foo', fn ($value) => $value === null); } + public function testAssertJsonPathWithEnum() + { + $response = TestResponse::fromBaseResponse(new Response([ + 'data' => ['status' => 'booked'], + ])); + + $response->assertJsonPath('data.status', TestStatus::Booked); + } + + public function testAssertJsonPathWithEnumCanFail() + { + $response = TestResponse::fromBaseResponse(new Response([ + 'data' => ['status' => 'failed'], + ])); + + $this->expectException(AssertionFailedError::class); + $this->expectExceptionMessage('Failed asserting that two strings are identical.'); + + $response->assertJsonPath('data.status', TestStatus::Booked); + } + public function testAssertJsonPathCanonicalizing() { $response = TestResponse::fromBaseResponse(new Response(new JsonSerializableSingleResourceStub)); @@ -2954,3 +2975,8 @@ class AnotherTestModel extends Model { protected $guarded = []; } + +enum TestStatus: string +{ + case Booked = 'booked'; +}
diff --git a/src/Illuminate/Testing/AssertableJsonString.php b/src/Illuminate/Testing/AssertableJsonString.php index 0bf221bea0da..d089ab071dc3 100644 --- a/src/Illuminate/Testing/AssertableJsonString.php +++ b/src/Illuminate/Testing/AssertableJsonString.php @@ -12,6 +12,8 @@ use Illuminate\Testing\Assert as PHPUnit; use JsonSerializable; class AssertableJsonString implements ArrayAccess, Countable /** @@ -238,7 +240,7 @@ public function assertPath($path, $expect) if ($expect instanceof Closure) { PHPUnit::assertTrue($expect($this->json($path))); } else { - PHPUnit::assertSame($expect, $this->json($path)); + PHPUnit::assertSame(enum_value($expect), $this->json($path)); } return $this; diff --git a/tests/Testing/TestResponseTest.php b/tests/Testing/TestResponseTest.php index 9de88ddff3f3..cae497bdd133 100644 --- a/tests/Testing/TestResponseTest.php +++ b/tests/Testing/TestResponseTest.php @@ -1437,6 +1437,27 @@ public function testAssertJsonPathWithClosureCanFail() $response->assertJsonPath('data.foo', fn ($value) => $value === null); } + public function testAssertJsonPathWithEnum() + public function testAssertJsonPathWithEnumCanFail() + 'data' => ['status' => 'failed'], + $this->expectException(AssertionFailedError::class); + $this->expectExceptionMessage('Failed asserting that two strings are identical.'); public function testAssertJsonPathCanonicalizing() { $response = TestResponse::fromBaseResponse(new Response(new JsonSerializableSingleResourceStub)); @@ -2954,3 +2975,8 @@ class AnotherTestModel extends Model protected $guarded = []; } +enum TestStatus: string +{ + case Booked = 'booked'; +}
[ "+use function Illuminate\\Support\\enum_value;", "+ 'data' => ['status' => 'booked']," ]
[ 8, 33 ]
{ "additions": 29, "author": "azim-kordpour", "deletions": 1, "html_url": "https://github.com/laravel/framework/pull/55516", "issue_id": 55516, "merged_at": "2025-04-23T13:17:11Z", "omission_probability": 0.1, "pr_number": 55516, "repo": "laravel/framework", "title": "[12.x] Add Enum support for assertJsonPath in AssertableJsonString.php", "total_changes": 30 }
15
diff --git a/src/Illuminate/Database/MigrationServiceProvider.php b/src/Illuminate/Database/MigrationServiceProvider.php index cab266bb2f9..037106c7357 100755 --- a/src/Illuminate/Database/MigrationServiceProvider.php +++ b/src/Illuminate/Database/MigrationServiceProvider.php @@ -82,6 +82,8 @@ protected function registerMigrator() return new Migrator($repository, $app['db'], $app['files'], $app['events']); }); + + $this->app->bind(Migrator::class, fn ($app) => $app['migrator']); } /** @@ -220,7 +222,7 @@ protected function registerMigrateStatusCommand() public function provides() { return array_merge([ - 'migrator', 'migration.repository', 'migration.creator', + 'migrator', 'migration.repository', 'migration.creator', Migrator::class, ], array_values($this->commands)); } } diff --git a/tests/Integration/Database/MigrationServiceProviderTest.php b/tests/Integration/Database/MigrationServiceProviderTest.php new file mode 100644 index 00000000000..6da602074f3 --- /dev/null +++ b/tests/Integration/Database/MigrationServiceProviderTest.php @@ -0,0 +1,16 @@ +<?php + +namespace Illuminate\Tests\Integration\Database; + +use Illuminate\Database\Migrations\Migrator; + +class MigrationServiceProviderTest extends DatabaseTestCase +{ + public function testContainerCanBuildMigrator() + { + $fromString = $this->app->make('migrator'); + $fromClass = $this->app->make(Migrator::class); + + $this->assertSame($fromString, $fromClass); + } +}
diff --git a/src/Illuminate/Database/MigrationServiceProvider.php b/src/Illuminate/Database/MigrationServiceProvider.php index cab266bb2f9..037106c7357 100755 --- a/src/Illuminate/Database/MigrationServiceProvider.php +++ b/src/Illuminate/Database/MigrationServiceProvider.php @@ -82,6 +82,8 @@ protected function registerMigrator() return new Migrator($repository, $app['db'], $app['files'], $app['events']); }); + $this->app->bind(Migrator::class, fn ($app) => $app['migrator']); /** @@ -220,7 +222,7 @@ protected function registerMigrateStatusCommand() public function provides() { return array_merge([ - 'migrator', 'migration.repository', 'migration.creator', + 'migrator', 'migration.repository', 'migration.creator', Migrator::class, ], array_values($this->commands)); } diff --git a/tests/Integration/Database/MigrationServiceProviderTest.php b/tests/Integration/Database/MigrationServiceProviderTest.php new file mode 100644 index 00000000000..6da602074f3 --- /dev/null +++ b/tests/Integration/Database/MigrationServiceProviderTest.php @@ -0,0 +1,16 @@ +<?php +namespace Illuminate\Tests\Integration\Database; +use Illuminate\Database\Migrations\Migrator; +class MigrationServiceProviderTest extends DatabaseTestCase +{ + public function testContainerCanBuildMigrator() + $fromString = $this->app->make('migrator'); + $fromClass = $this->app->make(Migrator::class); + $this->assertSame($fromString, $fromClass); + } +}
[ "+ {" ]
[ 37 ]
{ "additions": 19, "author": "cosmastech", "deletions": 1, "html_url": "https://github.com/laravel/framework/pull/55501", "issue_id": 55501, "merged_at": "2025-04-22T13:50:14Z", "omission_probability": 0.1, "pr_number": 55501, "repo": "laravel/framework", "title": "[12.x] Allow Container to build `Migrator` from class name", "total_changes": 20 }
16
diff --git a/src/Illuminate/Cache/MemoizedStore.php b/src/Illuminate/Cache/MemoizedStore.php index 9888810de6d7..d899ef09d609 100644 --- a/src/Illuminate/Cache/MemoizedStore.php +++ b/src/Illuminate/Cache/MemoizedStore.php @@ -75,12 +75,17 @@ public function many(array $keys) }); } - $result = [ - ...$memoized, - ...$retrieved, - ]; + $result = []; - return array_replace(array_flip($keys), $result); + foreach ($keys as $key) { + if (array_key_exists($key, $memoized)) { + $result[$key] = $memoized[$key]; + } else { + $result[$key] = $retrieved[$key]; + } + } + + return $result; } /** diff --git a/tests/Integration/Cache/MemoizedStoreTest.php b/tests/Integration/Cache/MemoizedStoreTest.php index e599f83225d0..028688b262e2 100644 --- a/tests/Integration/Cache/MemoizedStoreTest.php +++ b/tests/Integration/Cache/MemoizedStoreTest.php @@ -89,6 +89,33 @@ public function test_it_can_memoize_when_retrieving_mulitple_values() $this->assertSame(['name.0' => 'Tim', 'name.1' => 'Taylor'], $memoized); } + public function test_it_uses_correct_keys_for_getMultiple() + { + $data = [ + 'a' => 'string-value', + '1.1' => 'float-value', + '1' => 'integer-value-as-string', + 2 => 'integer-value', + ]; + Cache::putMany($data); + + $memoValue = Cache::memo()->many(['a', '1.1', '1', 2]); + $cacheValue = Cache::many(['a', '1.1', '1', 2]); + + $this->assertSame([ + 'a' => 'string-value', + '1.1' => 'float-value', + '1' => 'integer-value-as-string', + 2 => 'integer-value', + ], $cacheValue); + $this->assertSame($cacheValue, $memoValue); + + // ensure correct on the second memoized retrieval + $memoValue = Cache::memo()->many(['a', '1.1', '1', 2]); + + $this->assertSame($cacheValue, $memoValue); + } + public function test_null_values_are_memoized_when_retrieving_mulitple_values() { $live = Cache::getMultiple(['name.0', 'name.1']);
diff --git a/src/Illuminate/Cache/MemoizedStore.php b/src/Illuminate/Cache/MemoizedStore.php index 9888810de6d7..d899ef09d609 100644 --- a/src/Illuminate/Cache/MemoizedStore.php +++ b/src/Illuminate/Cache/MemoizedStore.php @@ -75,12 +75,17 @@ public function many(array $keys) }); } - $result = [ - ...$memoized, - ...$retrieved, - ]; + $result = []; - return array_replace(array_flip($keys), $result); + foreach ($keys as $key) { + if (array_key_exists($key, $memoized)) { + $result[$key] = $memoized[$key]; + } else { + $result[$key] = $retrieved[$key]; + } + } + return $result; /** diff --git a/tests/Integration/Cache/MemoizedStoreTest.php b/tests/Integration/Cache/MemoizedStoreTest.php index e599f83225d0..028688b262e2 100644 --- a/tests/Integration/Cache/MemoizedStoreTest.php +++ b/tests/Integration/Cache/MemoizedStoreTest.php @@ -89,6 +89,33 @@ public function test_it_can_memoize_when_retrieving_mulitple_values() $this->assertSame(['name.0' => 'Tim', 'name.1' => 'Taylor'], $memoized); + public function test_it_uses_correct_keys_for_getMultiple() + { + $data = [ + ]; + Cache::putMany($data); + $cacheValue = Cache::many(['a', '1.1', '1', 2]); + ], $cacheValue); + // ensure correct on the second memoized retrieval + } public function test_null_values_are_memoized_when_retrieving_mulitple_values() { $live = Cache::getMultiple(['name.0', 'name.1']);
[ "+ $this->assertSame([" ]
[ 48 ]
{ "additions": 37, "author": "bmckay959", "deletions": 5, "html_url": "https://github.com/laravel/framework/pull/55503", "issue_id": 55503, "merged_at": "2025-04-22T13:45:35Z", "omission_probability": 0.1, "pr_number": 55503, "repo": "laravel/framework", "title": "Bugfix for Cache::memo()->many() returning the wrong value with an integer key type", "total_changes": 42 }
17
diff --git a/src/Illuminate/Broadcasting/BroadcastEvent.php b/src/Illuminate/Broadcasting/BroadcastEvent.php index c4da0faab220..7c03641ace53 100644 --- a/src/Illuminate/Broadcasting/BroadcastEvent.php +++ b/src/Illuminate/Broadcasting/BroadcastEvent.php @@ -50,6 +50,13 @@ class BroadcastEvent implements ShouldQueue */ public $maxExceptions; + /** + * Indicates if the job should be deleted when models are missing. + * + * @var bool + */ + public $deleteWhenMissingModels; + /** * Create a new job handler instance. * @@ -63,6 +70,7 @@ public function __construct($event) $this->backoff = property_exists($event, 'backoff') ? $event->backoff : null; $this->afterCommit = property_exists($event, 'afterCommit') ? $event->afterCommit : null; $this->maxExceptions = property_exists($event, 'maxExceptions') ? $event->maxExceptions : null; + $this->deleteWhenMissingModels = property_exists($event, 'deleteWhenMissingModels') ? $event->deleteWhenMissingModels : null; } /** diff --git a/src/Illuminate/Events/CallQueuedListener.php b/src/Illuminate/Events/CallQueuedListener.php index e78a4c4e2c5f..13f33e338304 100644 --- a/src/Illuminate/Events/CallQueuedListener.php +++ b/src/Illuminate/Events/CallQueuedListener.php @@ -82,6 +82,13 @@ class CallQueuedListener implements ShouldQueue */ public $shouldBeEncrypted = false; + /** + * Indicates if the job should be deleted when models are missing. + * + * @var bool + */ + public $deleteWhenMissingModels; + /** * Create a new job instance. * diff --git a/src/Illuminate/Events/Dispatcher.php b/src/Illuminate/Events/Dispatcher.php index ee409586efc8..bfea9a47e353 100755 --- a/src/Illuminate/Events/Dispatcher.php +++ b/src/Illuminate/Events/Dispatcher.php @@ -677,6 +677,7 @@ protected function propagateListenerOptions($listener, $job) $job->timeout = $listener->timeout ?? null; $job->failOnTimeout = $listener->failOnTimeout ?? false; $job->tries = $listener->tries ?? null; + $job->deleteWhenMissingModels = $listener->deleteWhenMissingModels ?? false; $job->through(array_merge( method_exists($listener, 'middleware') ? $listener->middleware(...$data) : [],
diff --git a/src/Illuminate/Broadcasting/BroadcastEvent.php b/src/Illuminate/Broadcasting/BroadcastEvent.php index c4da0faab220..7c03641ace53 100644 --- a/src/Illuminate/Broadcasting/BroadcastEvent.php +++ b/src/Illuminate/Broadcasting/BroadcastEvent.php @@ -50,6 +50,13 @@ class BroadcastEvent implements ShouldQueue public $maxExceptions; * Create a new job handler instance. @@ -63,6 +70,7 @@ public function __construct($event) $this->backoff = property_exists($event, 'backoff') ? $event->backoff : null; $this->afterCommit = property_exists($event, 'afterCommit') ? $event->afterCommit : null; $this->maxExceptions = property_exists($event, 'maxExceptions') ? $event->maxExceptions : null; + $this->deleteWhenMissingModels = property_exists($event, 'deleteWhenMissingModels') ? $event->deleteWhenMissingModels : null; } diff --git a/src/Illuminate/Events/CallQueuedListener.php b/src/Illuminate/Events/CallQueuedListener.php index e78a4c4e2c5f..13f33e338304 100644 --- a/src/Illuminate/Events/CallQueuedListener.php +++ b/src/Illuminate/Events/CallQueuedListener.php @@ -82,6 +82,13 @@ class CallQueuedListener implements ShouldQueue public $shouldBeEncrypted = false; * Create a new job instance. diff --git a/src/Illuminate/Events/Dispatcher.php b/src/Illuminate/Events/Dispatcher.php index ee409586efc8..bfea9a47e353 100755 --- a/src/Illuminate/Events/Dispatcher.php +++ b/src/Illuminate/Events/Dispatcher.php @@ -677,6 +677,7 @@ protected function propagateListenerOptions($listener, $job) $job->timeout = $listener->timeout ?? null; $job->failOnTimeout = $listener->failOnTimeout ?? false; $job->tries = $listener->tries ?? null; + $job->deleteWhenMissingModels = $listener->deleteWhenMissingModels ?? false; $job->through(array_merge( method_exists($listener, 'middleware') ? $listener->middleware(...$data) : [],
[]
[]
{ "additions": 16, "author": "L3o-pold", "deletions": 0, "html_url": "https://github.com/laravel/framework/pull/55508", "issue_id": 55508, "merged_at": "2025-04-22T13:44:53Z", "omission_probability": 0.1, "pr_number": 55508, "repo": "laravel/framework", "title": "Allow Listeners to dynamically specify deleteWhenMissingModels", "total_changes": 16 }
18
diff --git a/src/Illuminate/Contracts/Validation/InvokableRule.php b/src/Illuminate/Contracts/Validation/InvokableRule.php index bed9ed567fb4..17c296446945 100644 --- a/src/Illuminate/Contracts/Validation/InvokableRule.php +++ b/src/Illuminate/Contracts/Validation/InvokableRule.php @@ -14,7 +14,7 @@ interface InvokableRule * * @param string $attribute * @param mixed $value - * @param \Closure(string, ?string = null): \Illuminate\Translation\PotentiallyTranslatedString $fail + * @param \Closure(string, ?string=): \Illuminate\Translation\PotentiallyTranslatedString $fail * @return void */ public function __invoke(string $attribute, mixed $value, Closure $fail); diff --git a/src/Illuminate/Contracts/Validation/ValidationRule.php b/src/Illuminate/Contracts/Validation/ValidationRule.php index c687b26a2d98..6829372b3714 100644 --- a/src/Illuminate/Contracts/Validation/ValidationRule.php +++ b/src/Illuminate/Contracts/Validation/ValidationRule.php @@ -11,7 +11,7 @@ interface ValidationRule * * @param string $attribute * @param mixed $value - * @param \Closure(string, ?string = null): \Illuminate\Translation\PotentiallyTranslatedString $fail + * @param \Closure(string, ?string=): \Illuminate\Translation\PotentiallyTranslatedString $fail * @return void */ public function validate(string $attribute, mixed $value, Closure $fail): void; diff --git a/src/Illuminate/Foundation/Console/stubs/rule.implicit.stub b/src/Illuminate/Foundation/Console/stubs/rule.implicit.stub index e04915bf5852..fa23cdfc2139 100644 --- a/src/Illuminate/Foundation/Console/stubs/rule.implicit.stub +++ b/src/Illuminate/Foundation/Console/stubs/rule.implicit.stub @@ -17,7 +17,7 @@ class {{ class }} implements ValidationRule /** * Run the validation rule. * - * @param \Closure(string, ?string = null): \Illuminate\Translation\PotentiallyTranslatedString $fail + * @param \Closure(string, ?string=): \Illuminate\Translation\PotentiallyTranslatedString $fail */ public function validate(string $attribute, mixed $value, Closure $fail): void { diff --git a/src/Illuminate/Foundation/Console/stubs/rule.stub b/src/Illuminate/Foundation/Console/stubs/rule.stub index 7b54420895b4..bc1d35139247 100644 --- a/src/Illuminate/Foundation/Console/stubs/rule.stub +++ b/src/Illuminate/Foundation/Console/stubs/rule.stub @@ -10,7 +10,7 @@ class {{ class }} implements ValidationRule /** * Run the validation rule. * - * @param \Closure(string, ?string = null): \Illuminate\Translation\PotentiallyTranslatedString $fail + * @param \Closure(string, ?string=): \Illuminate\Translation\PotentiallyTranslatedString $fail */ public function validate(string $attribute, mixed $value, Closure $fail): void { diff --git a/types/Contracts/Validation/ValidationRule.php b/types/Contracts/Validation/ValidationRule.php new file mode 100644 index 000000000000..565a7d972340 --- /dev/null +++ b/types/Contracts/Validation/ValidationRule.php @@ -0,0 +1,13 @@ +<?php + +use Illuminate\Contracts\Validation\ValidationRule; + +use function PHPStan\Testing\assertType; + +new class implements ValidationRule +{ + public function validate(string $attribute, mixed $value, Closure $fail): void + { + assertType('Closure(string, string|null=): Illuminate\Translation\PotentiallyTranslatedString', $fail); + } +};
diff --git a/src/Illuminate/Contracts/Validation/InvokableRule.php b/src/Illuminate/Contracts/Validation/InvokableRule.php index bed9ed567fb4..17c296446945 100644 --- a/src/Illuminate/Contracts/Validation/InvokableRule.php +++ b/src/Illuminate/Contracts/Validation/InvokableRule.php @@ -14,7 +14,7 @@ interface InvokableRule public function __invoke(string $attribute, mixed $value, Closure $fail); diff --git a/src/Illuminate/Contracts/Validation/ValidationRule.php b/src/Illuminate/Contracts/Validation/ValidationRule.php index c687b26a2d98..6829372b3714 100644 --- a/src/Illuminate/Contracts/Validation/ValidationRule.php +++ b/src/Illuminate/Contracts/Validation/ValidationRule.php @@ -11,7 +11,7 @@ interface ValidationRule public function validate(string $attribute, mixed $value, Closure $fail): void; diff --git a/src/Illuminate/Foundation/Console/stubs/rule.implicit.stub b/src/Illuminate/Foundation/Console/stubs/rule.implicit.stub index e04915bf5852..fa23cdfc2139 100644 --- a/src/Illuminate/Foundation/Console/stubs/rule.implicit.stub +++ b/src/Illuminate/Foundation/Console/stubs/rule.implicit.stub @@ -17,7 +17,7 @@ class {{ class }} implements ValidationRule diff --git a/src/Illuminate/Foundation/Console/stubs/rule.stub b/src/Illuminate/Foundation/Console/stubs/rule.stub index 7b54420895b4..bc1d35139247 100644 --- a/src/Illuminate/Foundation/Console/stubs/rule.stub +++ b/src/Illuminate/Foundation/Console/stubs/rule.stub @@ -10,7 +10,7 @@ class {{ class }} implements ValidationRule diff --git a/types/Contracts/Validation/ValidationRule.php b/types/Contracts/Validation/ValidationRule.php new file mode 100644 index 000000000000..565a7d972340 --- /dev/null +++ b/types/Contracts/Validation/ValidationRule.php @@ -0,0 +1,13 @@ +<?php +use Illuminate\Contracts\Validation\ValidationRule; +new class implements ValidationRule +{ + public function validate(string $attribute, mixed $value, Closure $fail): void + { + assertType('Closure(string, string|null=): Illuminate\Translation\PotentiallyTranslatedString', $fail); + }
[ "+use function PHPStan\\Testing\\assertType;", "+};" ]
[ 62, 70 ]
{ "additions": 17, "author": "axlon", "deletions": 4, "html_url": "https://github.com/laravel/framework/pull/52870", "issue_id": 52870, "merged_at": "2024-09-22T15:08:08Z", "omission_probability": 0.1, "pr_number": 52870, "repo": "laravel/framework", "title": "[11.x] Fix validation rule type hints", "total_changes": 21 }
19
diff --git a/src/Illuminate/Cache/Events/CacheFlushFailed.php b/src/Illuminate/Cache/Events/CacheFlushFailed.php new file mode 100644 index 000000000000..7d987e9de82c --- /dev/null +++ b/src/Illuminate/Cache/Events/CacheFlushFailed.php @@ -0,0 +1,45 @@ +<?php + +namespace Illuminate\Cache\Events; + +class CacheFlushFailed +{ + /** + * The name of the cache store. + * + * @var string|null + */ + public $storeName; + + /** + * The tags that were assigned to the key. + * + * @var array + */ + public $tags; + + /** + * Create a new event instance. + * + * @param string|null $storeName + * @return void + */ + public function __construct($storeName, array $tags = []) + { + $this->storeName = $storeName; + $this->tags = $tags; + } + + /** + * Set the tags for the cache event. + * + * @param array $tags + * @return $this + */ + public function setTags($tags) + { + $this->tags = $tags; + + return $this; + } +} diff --git a/src/Illuminate/Cache/Events/CacheFlushed.php b/src/Illuminate/Cache/Events/CacheFlushed.php index fb0275f06e50..5f942afdd1af 100644 --- a/src/Illuminate/Cache/Events/CacheFlushed.php +++ b/src/Illuminate/Cache/Events/CacheFlushed.php @@ -11,14 +11,35 @@ class CacheFlushed */ public $storeName; + /** + * The tags that were assigned to the key. + * + * @var array + */ + public $tags; + /** * Create a new event instance. * * @param string|null $storeName * @return void */ - public function __construct($storeName) + public function __construct($storeName, array $tags = []) { $this->storeName = $storeName; + $this->tags = $tags; + } + + /** + * Set the tags for the cache event. + * + * @param array $tags + * @return $this + */ + public function setTags($tags) + { + $this->tags = $tags; + + return $this; } } diff --git a/src/Illuminate/Cache/Events/CacheFlushing.php b/src/Illuminate/Cache/Events/CacheFlushing.php index 21054c8b718a..905f016143d7 100644 --- a/src/Illuminate/Cache/Events/CacheFlushing.php +++ b/src/Illuminate/Cache/Events/CacheFlushing.php @@ -11,14 +11,35 @@ class CacheFlushing */ public $storeName; + /** + * The tags that were assigned to the key. + * + * @var array + */ + public $tags; + /** * Create a new event instance. * * @param string|null $storeName * @return void */ - public function __construct($storeName) + public function __construct($storeName, array $tags = []) { $this->storeName = $storeName; + $this->tags = $tags; + } + + /** + * Set the tags for the cache event. + * + * @param array $tags + * @return $this + */ + public function setTags($tags) + { + $this->tags = $tags; + + return $this; } } diff --git a/src/Illuminate/Cache/RedisTaggedCache.php b/src/Illuminate/Cache/RedisTaggedCache.php index 8846844b413d..69053266d33d 100644 --- a/src/Illuminate/Cache/RedisTaggedCache.php +++ b/src/Illuminate/Cache/RedisTaggedCache.php @@ -2,6 +2,9 @@ namespace Illuminate\Cache; +use Illuminate\Cache\Events\CacheFlushed; +use Illuminate\Cache\Events\CacheFlushing; + class RedisTaggedCache extends TaggedCache { /** @@ -105,9 +108,13 @@ public function forever($key, $value) */ public function flush() { + $this->event(new CacheFlushing($this->getName())); + $this->flushValues(); $this->tags->flush(); + $this->event(new CacheFlushed($this->getName())); + return true; } diff --git a/src/Illuminate/Cache/Repository.php b/src/Illuminate/Cache/Repository.php index da22ea7d4a8f..3eb6f700ed01 100755 --- a/src/Illuminate/Cache/Repository.php +++ b/src/Illuminate/Cache/Repository.php @@ -7,6 +7,7 @@ use Closure; use DateTimeInterface; use Illuminate\Cache\Events\CacheFlushed; +use Illuminate\Cache\Events\CacheFlushFailed; use Illuminate\Cache\Events\CacheFlushing; use Illuminate\Cache\Events\CacheHit; use Illuminate\Cache\Events\CacheMissed; @@ -584,6 +585,8 @@ public function clear(): bool if ($result) { $this->event(new CacheFlushed($this->getName())); + } else { + $this->event(new CacheFlushFailed($this->getName())); } return $result; diff --git a/src/Illuminate/Cache/TaggedCache.php b/src/Illuminate/Cache/TaggedCache.php index 62adff972249..d2f17e667735 100644 --- a/src/Illuminate/Cache/TaggedCache.php +++ b/src/Illuminate/Cache/TaggedCache.php @@ -2,6 +2,8 @@ namespace Illuminate\Cache; +use Illuminate\Cache\Events\CacheFlushed; +use Illuminate\Cache\Events\CacheFlushing; use Illuminate\Contracts\Cache\Store; class TaggedCache extends Repository @@ -77,8 +79,12 @@ public function decrement($key, $value = 1) */ public function flush() { + $this->event(new CacheFlushing($this->getName())); + $this->tags->reset(); + $this->event(new CacheFlushed($this->getName())); + return true; } @@ -104,7 +110,7 @@ public function taggedItemKey($key) /** * Fire an event for this cache instance. * - * @param \Illuminate\Cache\Events\CacheEvent $event + * @param object $event * @return void */ protected function event($event) diff --git a/tests/Cache/CacheEventsTest.php b/tests/Cache/CacheEventsTest.php index 77a9173506eb..e0c747d0ca7d 100755 --- a/tests/Cache/CacheEventsTest.php +++ b/tests/Cache/CacheEventsTest.php @@ -4,6 +4,7 @@ use Illuminate\Cache\ArrayStore; use Illuminate\Cache\Events\CacheFlushed; +use Illuminate\Cache\Events\CacheFlushFailed; use Illuminate\Cache\Events\CacheFlushing; use Illuminate\Cache\Events\CacheHit; use Illuminate\Cache\Events\CacheMissed; @@ -242,7 +243,7 @@ public function testFlushTriggersEvents() $this->assertTrue($repository->clear()); } - public function testFlushFailureDoesNotDispatchEvent() + public function testFlushFailureDoesDispatchEvent() { $dispatcher = $this->getDispatcher(); @@ -258,6 +259,12 @@ public function testFlushFailureDoesNotDispatchEvent() 'storeName' => 'array', ]) ); + + $dispatcher->shouldReceive('dispatch')->once()->with( + $this->assertEventMatches(CacheFlushFailed::class, [ + 'storeName' => 'array', + ]) + ); $this->assertFalse($repository->clear()); }
diff --git a/src/Illuminate/Cache/Events/CacheFlushFailed.php b/src/Illuminate/Cache/Events/CacheFlushFailed.php new file mode 100644 index 000000000000..7d987e9de82c --- /dev/null +++ b/src/Illuminate/Cache/Events/CacheFlushFailed.php @@ -0,0 +1,45 @@ +<?php +namespace Illuminate\Cache\Events; +class CacheFlushFailed +{ + * The name of the cache store. + * @var string|null + public $storeName; + * @param string|null $storeName + * @return void + $this->storeName = $storeName; +} diff --git a/src/Illuminate/Cache/Events/CacheFlushed.php b/src/Illuminate/Cache/Events/CacheFlushed.php index fb0275f06e50..5f942afdd1af 100644 --- a/src/Illuminate/Cache/Events/CacheFlushed.php +++ b/src/Illuminate/Cache/Events/CacheFlushed.php @@ -11,14 +11,35 @@ class CacheFlushed diff --git a/src/Illuminate/Cache/Events/CacheFlushing.php b/src/Illuminate/Cache/Events/CacheFlushing.php index 21054c8b718a..905f016143d7 100644 --- a/src/Illuminate/Cache/Events/CacheFlushing.php +++ b/src/Illuminate/Cache/Events/CacheFlushing.php @@ -11,14 +11,35 @@ class CacheFlushing diff --git a/src/Illuminate/Cache/RedisTaggedCache.php b/src/Illuminate/Cache/RedisTaggedCache.php index 8846844b413d..69053266d33d 100644 --- a/src/Illuminate/Cache/RedisTaggedCache.php +++ b/src/Illuminate/Cache/RedisTaggedCache.php @@ -2,6 +2,9 @@ class RedisTaggedCache extends TaggedCache { @@ -105,9 +108,13 @@ public function forever($key, $value) $this->flushValues(); $this->tags->flush(); diff --git a/src/Illuminate/Cache/Repository.php b/src/Illuminate/Cache/Repository.php index da22ea7d4a8f..3eb6f700ed01 100755 --- a/src/Illuminate/Cache/Repository.php +++ b/src/Illuminate/Cache/Repository.php @@ -7,6 +7,7 @@ use Closure; use DateTimeInterface; @@ -584,6 +585,8 @@ public function clear(): bool if ($result) { $this->event(new CacheFlushed($this->getName())); + $this->event(new CacheFlushFailed($this->getName())); } return $result; diff --git a/src/Illuminate/Cache/TaggedCache.php b/src/Illuminate/Cache/TaggedCache.php index 62adff972249..d2f17e667735 100644 --- a/src/Illuminate/Cache/TaggedCache.php +++ b/src/Illuminate/Cache/TaggedCache.php @@ -2,6 +2,8 @@ use Illuminate\Contracts\Cache\Store; class TaggedCache extends Repository @@ -77,8 +79,12 @@ public function decrement($key, $value = 1) $this->tags->reset(); @@ -104,7 +110,7 @@ public function taggedItemKey($key) * Fire an event for this cache instance. - * @param \Illuminate\Cache\Events\CacheEvent $event + * @param object $event protected function event($event) diff --git a/tests/Cache/CacheEventsTest.php b/tests/Cache/CacheEventsTest.php index 77a9173506eb..e0c747d0ca7d 100755 --- a/tests/Cache/CacheEventsTest.php +++ b/tests/Cache/CacheEventsTest.php @@ -4,6 +4,7 @@ use Illuminate\Cache\ArrayStore; @@ -242,7 +243,7 @@ public function testFlushTriggersEvents() $this->assertTrue($repository->clear()); - public function testFlushFailureDoesNotDispatchEvent() + public function testFlushFailureDoesDispatchEvent() $dispatcher = $this->getDispatcher(); @@ -258,6 +259,12 @@ public function testFlushFailureDoesNotDispatchEvent() 'storeName' => 'array', ]) ); + $dispatcher->shouldReceive('dispatch')->once()->with( + $this->assertEventMatches(CacheFlushFailed::class, [ + 'storeName' => 'array', + ]) + ); $this->assertFalse($repository->clear());
[ "+ * Create a new event instance.", "+ } else {" ]
[ 27, 177 ]
{ "additions": 114, "author": "erikn69", "deletions": 4, "html_url": "https://github.com/laravel/framework/pull/55405", "issue_id": 55405, "merged_at": "2025-04-18T14:50:25Z", "omission_probability": 0.1, "pr_number": 55405, "repo": "laravel/framework", "title": "[12.x] Fix adding `setTags` method on new cache flush events", "total_changes": 118 }
20
diff --git a/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php b/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php index 454d79379195..8de013a1a38a 100644 --- a/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php +++ b/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php @@ -470,21 +470,10 @@ protected function detachUsingCustomClass($ids) { $results = 0; - if (! empty($this->pivotWheres) || - ! empty($this->pivotWhereIns) || - ! empty($this->pivotWhereNulls)) { - $records = $this->getCurrentlyAttachedPivotsForIds($ids); + $records = $this->getCurrentlyAttachedPivotsForIds($ids); - foreach ($records as $record) { - $results += $record->delete(); - } - } else { - foreach ($this->parseIds($ids) as $id) { - $results += $this->newPivot([ - $this->foreignPivotKey => $this->parent->{$this->parentKey}, - $this->relatedPivotKey => $id, - ], true)->delete(); - } + foreach ($records as $record) { + $results += $record->delete(); } return $results; diff --git a/tests/Integration/Database/EloquentBelongsToManyTest.php b/tests/Integration/Database/EloquentBelongsToManyTest.php index 3f00341da5a1..c104e0e05026 100644 --- a/tests/Integration/Database/EloquentBelongsToManyTest.php +++ b/tests/Integration/Database/EloquentBelongsToManyTest.php @@ -336,6 +336,49 @@ public function testDetachMethod() $this->assertCount(0, $post->tags); } + public function testDetachMethodWithCustomPivot() + { + $post = Post::create(['title' => Str::random()]); + + $tag = Tag::create(['name' => Str::random()]); + $tag2 = Tag::create(['name' => Str::random()]); + $tag3 = Tag::create(['name' => Str::random()]); + $tag4 = Tag::create(['name' => Str::random()]); + $tag5 = Tag::create(['name' => Str::random()]); + Tag::create(['name' => Str::random()]); + Tag::create(['name' => Str::random()]); + + $post->tagsWithCustomPivot()->attach(Tag::all()); + + $this->assertEquals(Tag::pluck('name'), $post->tags->pluck('name')); + + $post->tagsWithCustomPivot()->detach($tag->id); + $post->load('tagsWithCustomPivot'); + $this->assertEquals( + Tag::whereNotIn('id', [$tag->id])->pluck('name'), + $post->tagsWithCustomPivot->pluck('name') + ); + + $post->tagsWithCustomPivot()->detach([$tag2->id, $tag3->id]); + $post->load('tagsWithCustomPivot'); + $this->assertEquals( + Tag::whereNotIn('id', [$tag->id, $tag2->id, $tag3->id])->pluck('name'), + $post->tagsWithCustomPivot->pluck('name') + ); + + $post->tagsWithCustomPivot()->detach(new Collection([$tag4, $tag5])); + $post->load('tagsWithCustomPivot'); + $this->assertEquals( + Tag::whereNotIn('id', [$tag->id, $tag2->id, $tag3->id, $tag4->id, $tag5->id])->pluck('name'), + $post->tagsWithCustomPivot->pluck('name') + ); + + $this->assertCount(2, $post->tagsWithCustomPivot); + $post->tagsWithCustomPivot()->detach(); + $post->load('tagsWithCustomPivot'); + $this->assertCount(0, $post->tagsWithCustomPivot); + } + public function testFirstMethod() { $post = Post::create(['title' => Str::random()]);
diff --git a/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php b/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php index 454d79379195..8de013a1a38a 100644 --- a/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php +++ b/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php @@ -470,21 +470,10 @@ protected function detachUsingCustomClass($ids) $results = 0; - if (! empty($this->pivotWheres) || - ! empty($this->pivotWhereIns) || - ! empty($this->pivotWhereNulls)) { - $records = $this->getCurrentlyAttachedPivotsForIds($ids); + $records = $this->getCurrentlyAttachedPivotsForIds($ids); - foreach ($records as $record) { - $results += $record->delete(); - } else { - $results += $this->newPivot([ - $this->foreignPivotKey => $this->parent->{$this->parentKey}, - $this->relatedPivotKey => $id, - ], true)->delete(); + foreach ($records as $record) { + $results += $record->delete(); } return $results; diff --git a/tests/Integration/Database/EloquentBelongsToManyTest.php b/tests/Integration/Database/EloquentBelongsToManyTest.php index 3f00341da5a1..c104e0e05026 100644 --- a/tests/Integration/Database/EloquentBelongsToManyTest.php +++ b/tests/Integration/Database/EloquentBelongsToManyTest.php @@ -336,6 +336,49 @@ public function testDetachMethod() $this->assertCount(0, $post->tags); } + public function testDetachMethodWithCustomPivot() + { + $post = Post::create(['title' => Str::random()]); + $tag = Tag::create(['name' => Str::random()]); + $tag2 = Tag::create(['name' => Str::random()]); + $tag3 = Tag::create(['name' => Str::random()]); + $tag4 = Tag::create(['name' => Str::random()]); + $tag5 = Tag::create(['name' => Str::random()]); + $this->assertEquals(Tag::pluck('name'), $post->tags->pluck('name')); + $post->tagsWithCustomPivot()->detach($tag->id); + $post->tagsWithCustomPivot()->detach([$tag2->id, $tag3->id]); + Tag::whereNotIn('id', [$tag->id, $tag2->id, $tag3->id])->pluck('name'), + $post->tagsWithCustomPivot()->detach(new Collection([$tag4, $tag5])); + Tag::whereNotIn('id', [$tag->id, $tag2->id, $tag3->id, $tag4->id, $tag5->id])->pluck('name'), + $this->assertCount(2, $post->tagsWithCustomPivot); + $post->tagsWithCustomPivot()->detach(); + $this->assertCount(0, $post->tagsWithCustomPivot); + } public function testFirstMethod() $post = Post::create(['title' => Str::random()]);
[ "- foreach ($this->parseIds($ids) as $id) {", "+ $post->tagsWithCustomPivot()->attach(Tag::all());", "+ Tag::whereNotIn('id', [$tag->id])->pluck('name')," ]
[ 18, 49, 56 ]
{ "additions": 46, "author": "amir9480", "deletions": 14, "html_url": "https://github.com/laravel/framework/pull/55490", "issue_id": 55490, "merged_at": "2025-04-21T14:27:56Z", "omission_probability": 0.1, "pr_number": 55490, "repo": "laravel/framework", "title": "[12.x] Fix many to many detach without IDs broken with custom pivot class", "total_changes": 60 }
21
diff --git a/tests/Integration/Session/DatabaseSessionHandlerTest.php b/tests/Integration/Session/DatabaseSessionHandlerTest.php new file mode 100644 index 000000000000..b6e5856d6067 --- /dev/null +++ b/tests/Integration/Session/DatabaseSessionHandlerTest.php @@ -0,0 +1,113 @@ +<?php + +namespace Illuminate\Tests\Integration\Session; + +use Illuminate\Session\DatabaseSessionHandler; +use Illuminate\Support\Carbon; +use Illuminate\Tests\Integration\Database\DatabaseTestCase; +use Orchestra\Testbench\Attributes\WithMigration; + +#[WithMigration('session')] +class DatabaseSessionHandlerTest extends DatabaseTestCase +{ + public function test_basic_read_write_functionality() + { + $connection = $this->app['db']->connection(); + $handler = new DatabaseSessionHandler($connection, 'sessions', 1); + $handler->setContainer($this->app); + + // read non-existing session id: + $this->assertEquals('', $handler->read('invalid_session_id')); + + // open and close: + $this->assertTrue($handler->open('', '')); + $this->assertTrue($handler->close()); + + // write and read: + $this->assertTrue($handler->write('valid_session_id_2425', json_encode(['foo' => 'bar']))); + $this->assertEquals(['foo' => 'bar'], json_decode($handler->read('valid_session_id_2425'), true)); + $this->assertEquals(1, $connection->table('sessions')->count()); + + $session = $connection->table('sessions')->first(); + $this->assertNotNull($session->user_agent); + $this->assertNotNull($session->ip_address); + + // re-write and read: + $this->assertTrue($handler->write('valid_session_id_2425', json_encode(['over' => 'ride']))); + $this->assertEquals(['over' => 'ride'], json_decode($handler->read('valid_session_id_2425'), true)); + $this->assertEquals(1, $connection->table('sessions')->count()); + + // handler object writes only one session id: + $this->assertTrue($handler->write('other_id', 'data')); + $this->assertEquals(1, $connection->table('sessions')->count()); + + $handler->setExists(false); + $this->assertTrue($handler->write('other_id', 'data')); + $this->assertEquals(2, $connection->table('sessions')->count()); + + // read expired: + Carbon::setTestNow(Carbon::now()->addMinutes(2)); + $this->assertEquals('', $handler->read('valid_session_id_2425')); + + // rewriting an expired session-id, makes it live: + $this->assertTrue($handler->write('valid_session_id_2425', json_encode(['come' => 'alive']))); + $this->assertEquals(['come' => 'alive'], json_decode($handler->read('valid_session_id_2425'), true)); + } + + public function test_garbage_collector() + { + $connection = $this->app['db']->connection(); + + $handler = new DatabaseSessionHandler($connection, 'sessions', 1, $this->app); + $handler->write('simple_id_1', 'abcd'); + $this->assertEquals(0, $handler->gc(1)); + + Carbon::setTestNow(Carbon::now()->addSeconds(2)); + + $handler = new DatabaseSessionHandler($connection, 'sessions', 1, $this->app); + $handler->write('simple_id_2', 'abcd'); + $this->assertEquals(1, $handler->gc(2)); + $this->assertEquals(1, $connection->table('sessions')->count()); + + Carbon::setTestNow(Carbon::now()->addSeconds(2)); + + $this->assertEquals(1, $handler->gc(1)); + $this->assertEquals(0, $connection->table('sessions')->count()); + } + + public function test_destroy() + { + $connection = $this->app['db']->connection(); + $handler1 = new DatabaseSessionHandler($connection, 'sessions', 1, $this->app); + $handler2 = clone $handler1; + + $handler1->write('id_1', 'some data'); + $handler2->write('id_2', 'some data'); + + // destroy invalid session-id: + $this->assertEquals(true, $handler1->destroy('invalid_session_id')); + // nothing deleted: + $this->assertEquals(2, $connection->table('sessions')->count()); + + // destroy valid session-id: + $this->assertEquals(true, $handler2->destroy('id_1')); + // only one row is deleted: + $this->assertEquals(1, $connection->table('sessions')->where('id', 'id_2')->count()); + } + + public function test_it_can_work_without_container() + { + $connection = $this->app['db']->connection(); + $handler = new DatabaseSessionHandler($connection, 'sessions', 1); + + // write and read: + $this->assertTrue($handler->write('session_id', 'some data')); + $this->assertEquals('some data', $handler->read('session_id')); + $this->assertEquals(1, $connection->table('sessions')->count()); + + $session = $connection->table('sessions')->first(); + $this->assertNull($session->user_agent); + $this->assertNull($session->ip_address); + $this->assertNull($session->user_id); + } +}
diff --git a/tests/Integration/Session/DatabaseSessionHandlerTest.php b/tests/Integration/Session/DatabaseSessionHandlerTest.php new file mode 100644 index 000000000000..b6e5856d6067 --- /dev/null +++ b/tests/Integration/Session/DatabaseSessionHandlerTest.php @@ -0,0 +1,113 @@ +<?php +namespace Illuminate\Tests\Integration\Session; +use Illuminate\Session\DatabaseSessionHandler; +use Illuminate\Support\Carbon; +use Orchestra\Testbench\Attributes\WithMigration; +#[WithMigration('session')] +class DatabaseSessionHandlerTest extends DatabaseTestCase +{ + public function test_basic_read_write_functionality() + $handler->setContainer($this->app); + // read non-existing session id: + $this->assertEquals('', $handler->read('invalid_session_id')); + // open and close: + $this->assertTrue($handler->open('', '')); + $this->assertTrue($handler->close()); + $this->assertTrue($handler->write('valid_session_id_2425', json_encode(['foo' => 'bar']))); + $this->assertEquals(['foo' => 'bar'], json_decode($handler->read('valid_session_id_2425'), true)); + $this->assertNotNull($session->user_agent); + $this->assertNotNull($session->ip_address); + // re-write and read: + $this->assertTrue($handler->write('valid_session_id_2425', json_encode(['over' => 'ride']))); + $this->assertEquals(['over' => 'ride'], json_decode($handler->read('valid_session_id_2425'), true)); + // handler object writes only one session id: + $handler->setExists(false); + // read expired: + Carbon::setTestNow(Carbon::now()->addMinutes(2)); + $this->assertEquals('', $handler->read('valid_session_id_2425')); + // rewriting an expired session-id, makes it live: + $this->assertTrue($handler->write('valid_session_id_2425', json_encode(['come' => 'alive']))); + public function test_garbage_collector() + $handler->write('simple_id_1', 'abcd'); + $this->assertEquals(0, $handler->gc(1)); + $handler->write('simple_id_2', 'abcd'); + $this->assertEquals(1, $handler->gc(2)); + $this->assertEquals(1, $handler->gc(1)); + $this->assertEquals(0, $connection->table('sessions')->count()); + public function test_destroy() + $handler1 = new DatabaseSessionHandler($connection, 'sessions', 1, $this->app); + $handler2 = clone $handler1; + $handler1->write('id_1', 'some data'); + $handler2->write('id_2', 'some data'); + // destroy invalid session-id: + $this->assertEquals(true, $handler1->destroy('invalid_session_id')); + // nothing deleted: + // destroy valid session-id: + $this->assertEquals(true, $handler2->destroy('id_1')); + // only one row is deleted: + $this->assertEquals(1, $connection->table('sessions')->where('id', 'id_2')->count()); + public function test_it_can_work_without_container() + $this->assertTrue($handler->write('session_id', 'some data')); + $this->assertEquals('some data', $handler->read('session_id')); + $this->assertNull($session->user_agent); + $this->assertNull($session->ip_address); +}
[ "+use Illuminate\\Tests\\Integration\\Database\\DatabaseTestCase;", "+ $this->assertEquals(['come' => 'alive'], json_decode($handler->read('valid_session_id_2425'), true));", "+ $this->assertNull($session->user_id);" ]
[ 12, 59, 116 ]
{ "additions": 113, "author": "imanghafoori1", "deletions": 0, "html_url": "https://github.com/laravel/framework/pull/55485", "issue_id": 55485, "merged_at": "2025-04-21T14:19:05Z", "omission_probability": 0.1, "pr_number": 55485, "repo": "laravel/framework", "title": "[12.x] Add tests for `DatabaseSessionHandler`", "total_changes": 113 }
22
diff --git a/tests/Session/FileSessionHandlerTest.php b/tests/Session/FileSessionHandlerTest.php new file mode 100644 index 000000000000..ba27b7019ade --- /dev/null +++ b/tests/Session/FileSessionHandlerTest.php @@ -0,0 +1,138 @@ +<?php + +namespace Illuminate\Tests\Session; + +use Illuminate\Filesystem\Filesystem; +use Illuminate\Session\FileSessionHandler; +use Illuminate\Support\Carbon; +use Mockery; +use PHPUnit\Framework\TestCase; + +use function Illuminate\Filesystem\join_paths; + +class FileSessionHandlerTest extends TestCase +{ + protected $files; + + protected $sessionHandler; + + protected function setUp(): void + { + // Create a mock for the Filesystem class + $this->files = Mockery::mock(Filesystem::class); + + // Initialize the FileSessionHandler with the mocked Filesystem + $this->sessionHandler = new FileSessionHandler($this->files, '/path/to/sessions', 30); + } + + protected function tearDown(): void + { + Mockery::close(); + } + + public function test_open() + { + $this->assertTrue($this->sessionHandler->open('/path/to/sessions', 'session_name')); + } + + public function test_close() + { + $this->assertTrue($this->sessionHandler->close()); + } + + public function test_read_returns_data_when_file_exists_and_is_valid() + { + $sessionId = 'session_id'; + $path = '/path/to/sessions/'.$sessionId; + Carbon::setTestNow(Carbon::parse('2025-02-02 01:30:00')); + // Set up expectations + $this->files->shouldReceive('isFile')->with($path)->andReturn(true); + + $minutesAgo30 = Carbon::parse('2025-02-02 01:00:00')->getTimestamp(); + $this->files->shouldReceive('lastModified')->with($path)->andReturn($minutesAgo30); + $this->files->shouldReceive('sharedGet')->with($path)->once()->andReturn('session_data'); + + $result = $this->sessionHandler->read($sessionId); + + $this->assertEquals('session_data', $result); + } + + public function test_read_returns_data_when_file_exists_but_expired() + { + $sessionId = 'session_id'; + $path = '/path/to/sessions/'.$sessionId; + Carbon::setTestNow(Carbon::parse('2025-02-02 01:30:01')); + // Set up expectations + $this->files->shouldReceive('isFile')->with($path)->andReturn(true); + + $minutesAgo30 = Carbon::parse('2025-02-02 01:00:00')->getTimestamp(); + $this->files->shouldReceive('lastModified')->with($path)->andReturn($minutesAgo30); + $this->files->shouldReceive('sharedGet')->never(); + + $result = $this->sessionHandler->read($sessionId); + + $this->assertEquals('', $result); + } + + public function test_read_returns_empty_string_when_file_does_not_exist() + { + $sessionId = 'non_existing_session_id'; + $path = '/path/to/sessions/'.$sessionId; + + // Set up expectations + $this->files->shouldReceive('isFile')->with($path)->andReturn(false); + + $result = $this->sessionHandler->read($sessionId); + + $this->assertEquals('', $result); + } + + public function test_write_stores_data() + { + $sessionId = 'session_id'; + $data = 'session_data'; + + // Set up expectations + $this->files->shouldReceive('put')->with('/path/to/sessions/'.$sessionId, $data, true)->once()->andReturn(null); + + $result = $this->sessionHandler->write($sessionId, $data); + + $this->assertTrue($result); + } + + public function test_destroy_deletes_session_file() + { + $sessionId = 'session_id'; + + // Set up expectations + $this->files->shouldReceive('delete')->with('/path/to/sessions/'.$sessionId)->once()->andReturn(null); + + $result = $this->sessionHandler->destroy($sessionId); + + $this->assertTrue($result); + } + + public function test_gc_deletes_old_session_files() + { + $session = new FileSessionHandler($this->files, join_paths(__DIR__, 'tmp'), 30); + // Set up expectations for Filesystem + $this->files->shouldReceive('delete')->with(join_paths(__DIR__, 'tmp', 'a2'))->once()->andReturn(false); + $this->files->shouldReceive('delete')->with(join_paths(__DIR__, 'tmp', 'a3'))->once()->andReturn(true); + + mkdir(__DIR__.'/tmp'); + touch(__DIR__.'/tmp/a1', time() - 3); // last modified: 3 sec ago + touch(__DIR__.'/tmp/a2', time() - 5); // last modified: 5 sec ago + touch(__DIR__.'/tmp/a3', time() - 7); // last modified: 7 sec ago + + // act: + $count = $session->gc(5); + + $this->assertEquals(2, $count); + + unlink(__DIR__.'/tmp/a1'); + unlink(__DIR__.'/tmp/a2'); + unlink(__DIR__.'/tmp/a3'); + + rmdir(__DIR__.'/tmp'); + } +}
diff --git a/tests/Session/FileSessionHandlerTest.php b/tests/Session/FileSessionHandlerTest.php new file mode 100644 index 000000000000..ba27b7019ade --- /dev/null +++ b/tests/Session/FileSessionHandlerTest.php @@ -0,0 +1,138 @@ +<?php +namespace Illuminate\Tests\Session; +use Illuminate\Filesystem\Filesystem; +use Illuminate\Session\FileSessionHandler; +use Mockery; +use PHPUnit\Framework\TestCase; +use function Illuminate\Filesystem\join_paths; +class FileSessionHandlerTest extends TestCase +{ + protected $files; + protected $sessionHandler; + protected function setUp(): void + $this->files = Mockery::mock(Filesystem::class); + // Initialize the FileSessionHandler with the mocked Filesystem + $this->sessionHandler = new FileSessionHandler($this->files, '/path/to/sessions', 30); + protected function tearDown(): void + Mockery::close(); + public function test_open() + $this->assertTrue($this->sessionHandler->open('/path/to/sessions', 'session_name')); + public function test_close() + $this->assertTrue($this->sessionHandler->close()); + public function test_read_returns_data_when_file_exists_and_is_valid() + $this->files->shouldReceive('sharedGet')->with($path)->once()->andReturn('session_data'); + $this->assertEquals('session_data', $result); + public function test_read_returns_data_when_file_exists_but_expired() + Carbon::setTestNow(Carbon::parse('2025-02-02 01:30:01')); + $this->files->shouldReceive('sharedGet')->never(); + public function test_read_returns_empty_string_when_file_does_not_exist() + $sessionId = 'non_existing_session_id'; + $this->files->shouldReceive('isFile')->with($path)->andReturn(false); + public function test_write_stores_data() + $data = 'session_data'; + $this->files->shouldReceive('put')->with('/path/to/sessions/'.$sessionId, $data, true)->once()->andReturn(null); + $this->files->shouldReceive('delete')->with('/path/to/sessions/'.$sessionId)->once()->andReturn(null); + $result = $this->sessionHandler->destroy($sessionId); + public function test_gc_deletes_old_session_files() + $session = new FileSessionHandler($this->files, join_paths(__DIR__, 'tmp'), 30); + // Set up expectations for Filesystem + $this->files->shouldReceive('delete')->with(join_paths(__DIR__, 'tmp', 'a2'))->once()->andReturn(false); + mkdir(__DIR__.'/tmp'); + touch(__DIR__.'/tmp/a1', time() - 3); // last modified: 3 sec ago + touch(__DIR__.'/tmp/a2', time() - 5); // last modified: 5 sec ago + touch(__DIR__.'/tmp/a3', time() - 7); // last modified: 7 sec ago + $count = $session->gc(5); + unlink(__DIR__.'/tmp/a1'); + unlink(__DIR__.'/tmp/a2'); + unlink(__DIR__.'/tmp/a3'); + rmdir(__DIR__.'/tmp'); +}
[ "+use Illuminate\\Support\\Carbon;", "+ // Create a mock for the Filesystem class", "+ Carbon::setTestNow(Carbon::parse('2025-02-02 01:30:00'));", "+ $result = $this->sessionHandler->write($sessionId, $data);", "+ public function test_destroy_deletes_session_file()", "+ $this->files->shouldReceive('delete')->with(join_paths(__DIR__, 'tmp', 'a3'))->once()->andReturn(true);", "+ // act:", "+ $this->assertEquals(2, $count);" ]
[ 12, 26, 52, 103, 108, 125, 132, 135 ]
{ "additions": 138, "author": "imanghafoori1", "deletions": 0, "html_url": "https://github.com/laravel/framework/pull/55484", "issue_id": 55484, "merged_at": "2025-04-21T14:18:01Z", "omission_probability": 0.1, "pr_number": 55484, "repo": "laravel/framework", "title": "[12.x] Add tests for `FileSessionHandler`", "total_changes": 138 }
23
diff --git a/tests/Session/CacheBasedSessionHandlerTest.php b/tests/Session/CacheBasedSessionHandlerTest.php new file mode 100644 index 000000000000..af6cf68fdc01 --- /dev/null +++ b/tests/Session/CacheBasedSessionHandlerTest.php @@ -0,0 +1,89 @@ +<?php + +namespace Illuminate\Tests\Session; + +use Illuminate\Contracts\Cache\Repository as CacheContract; +use Illuminate\Session\CacheBasedSessionHandler; +use Mockery; +use PHPUnit\Framework\TestCase; + +class CacheBasedSessionHandlerTest extends TestCase +{ + protected $cacheMock; + + protected $sessionHandler; + + protected function setUp(): void + { + parent::setUp(); + $this->cacheMock = Mockery::mock(CacheContract::class); + $this->sessionHandler = new CacheBasedSessionHandler(cache: $this->cacheMock, minutes: 10); + } + + protected function tearDown(): void + { + Mockery::close(); + parent::tearDown(); + } + + public function test_open() + { + $result = $this->sessionHandler->open('path', 'session_name'); + $this->assertTrue($result); + } + + public function test_close() + { + $result = $this->sessionHandler->close(); + $this->assertTrue($result); + } + + public function test_read_returns_data_from_cache() + { + $this->cacheMock->shouldReceive('get')->once()->with('session_id', '')->andReturn('session_data'); + + $data = $this->sessionHandler->read(sessionId: 'session_id'); + $this->assertEquals('session_data', $data); + } + + public function test_read_returns_empty_string_if_no_data() + { + $this->cacheMock->shouldReceive('get')->once()->with('some_id', '')->andReturn(''); + + $data = $this->sessionHandler->read(sessionId: 'some_id'); + $this->assertEquals('', $data); + } + + public function test_write_stores_data_in_cache() + { + $this->cacheMock->shouldReceive('put')->once()->with('session_id', 'session_data', 600) // 10 minutes in seconds + ->andReturn(true); + + $result = $this->sessionHandler->write(sessionId: 'session_id', data: 'session_data'); + + $this->assertTrue($result); + } + + public function test_destroy_removes_data_from_cache() + { + $this->cacheMock->shouldReceive('forget')->once()->with('session_id')->andReturn(true); + + $result = $this->sessionHandler->destroy(sessionId: 'session_id'); + + $this->assertTrue($result); + } + + public function test_gc_returns_zero() + { + $result = $this->sessionHandler->gc(lifetime: 120); + + $this->assertEquals(0, $result); + } + + public function test_get_cache_returns_cache_instance() + { + $cacheInstance = $this->sessionHandler->getCache(); + + $this->assertSame($this->cacheMock, $cacheInstance); + } +}
diff --git a/tests/Session/CacheBasedSessionHandlerTest.php b/tests/Session/CacheBasedSessionHandlerTest.php new file mode 100644 index 000000000000..af6cf68fdc01 --- /dev/null +++ b/tests/Session/CacheBasedSessionHandlerTest.php @@ -0,0 +1,89 @@ +<?php +namespace Illuminate\Tests\Session; +use Illuminate\Contracts\Cache\Repository as CacheContract; +use Illuminate\Session\CacheBasedSessionHandler; +use Mockery; +class CacheBasedSessionHandlerTest extends TestCase +{ + protected $cacheMock; + protected $sessionHandler; + protected function setUp(): void + parent::setUp(); + $this->cacheMock = Mockery::mock(CacheContract::class); + $this->sessionHandler = new CacheBasedSessionHandler(cache: $this->cacheMock, minutes: 10); + protected function tearDown(): void + Mockery::close(); + parent::tearDown(); + $result = $this->sessionHandler->open('path', 'session_name'); + public function test_close() + $result = $this->sessionHandler->close(); + public function test_read_returns_data_from_cache() + $this->cacheMock->shouldReceive('get')->once()->with('session_id', '')->andReturn('session_data'); + $data = $this->sessionHandler->read(sessionId: 'session_id'); + $this->assertEquals('session_data', $data); + public function test_read_returns_empty_string_if_no_data() + $this->cacheMock->shouldReceive('get')->once()->with('some_id', '')->andReturn(''); + $data = $this->sessionHandler->read(sessionId: 'some_id'); + $this->assertEquals('', $data); + public function test_write_stores_data_in_cache() + $this->cacheMock->shouldReceive('put')->once()->with('session_id', 'session_data', 600) // 10 minutes in seconds + ->andReturn(true); + $result = $this->sessionHandler->write(sessionId: 'session_id', data: 'session_data'); + public function test_destroy_removes_data_from_cache() + $result = $this->sessionHandler->destroy(sessionId: 'session_id'); + public function test_gc_returns_zero() + $this->assertEquals(0, $result); + public function test_get_cache_returns_cache_instance() + $cacheInstance = $this->sessionHandler->getCache(); + $this->assertSame($this->cacheMock, $cacheInstance); +}
[ "+use PHPUnit\\Framework\\TestCase;", "+ public function test_open()", "+ $this->cacheMock->shouldReceive('forget')->once()->with('session_id')->andReturn(true);", "+ $result = $this->sessionHandler->gc(lifetime: 120);" ]
[ 13, 34, 74, 83 ]
{ "additions": 89, "author": "imanghafoori1", "deletions": 0, "html_url": "https://github.com/laravel/framework/pull/55487", "issue_id": 55487, "merged_at": "2025-04-21T14:17:26Z", "omission_probability": 0.1, "pr_number": 55487, "repo": "laravel/framework", "title": "[12.x] Add tests for `CacheBasedSessionHandler`", "total_changes": 89 }
24
diff --git a/src/Illuminate/Collections/Arr.php b/src/Illuminate/Collections/Arr.php index 72562305f251..e4ef759c8f61 100644 --- a/src/Illuminate/Collections/Arr.php +++ b/src/Illuminate/Collections/Arr.php @@ -112,13 +112,19 @@ public static function dot($array, $prepend = '') { $results = []; - foreach ($array as $key => $value) { - if (is_array($value) && ! empty($value)) { - $results = array_merge($results, static::dot($value, $prepend.$key.'.')); - } else { - $results[$prepend.$key] = $value; + $flatten = function ($data, $prefix) use (&$results, &$flatten): void { + foreach ($data as $key => $value) { + $newKey = $prefix.$key; + + if (is_array($value) && ! empty($value)) { + $flatten($value, $newKey.'.'); + } else { + $results[$newKey] = $value; + } } - } + }; + + $flatten($array, $prepend); return $results; }
diff --git a/src/Illuminate/Collections/Arr.php b/src/Illuminate/Collections/Arr.php index 72562305f251..e4ef759c8f61 100644 --- a/src/Illuminate/Collections/Arr.php +++ b/src/Illuminate/Collections/Arr.php @@ -112,13 +112,19 @@ public static function dot($array, $prepend = '') { $results = []; - foreach ($array as $key => $value) { - if (is_array($value) && ! empty($value)) { - $results = array_merge($results, static::dot($value, $prepend.$key.'.')); - $results[$prepend.$key] = $value; + $flatten = function ($data, $prefix) use (&$results, &$flatten): void { + foreach ($data as $key => $value) { + $newKey = $prefix.$key; + $flatten($value, $newKey.'.'); + } else { + $results[$newKey] = $value; + } } + }; + $flatten($array, $prepend); return $results; }
[ "- } else {", "+ if (is_array($value) && ! empty($value)) {", "- }" ]
[ 11, 17, 23 ]
{ "additions": 12, "author": "cyppe", "deletions": 6, "html_url": "https://github.com/laravel/framework/pull/55495", "issue_id": 55495, "merged_at": "2025-04-21T14:14:47Z", "omission_probability": 0.1, "pr_number": 55495, "repo": "laravel/framework", "title": "Improve performance of Arr::dot method - 300x in some cases", "total_changes": 18 }
25
diff --git a/src/Illuminate/View/Compilers/Concerns/CompilesUseStatements.php b/src/Illuminate/View/Compilers/Concerns/CompilesUseStatements.php index 8218c9fdf2c6..49a524a5fd9f 100644 --- a/src/Illuminate/View/Compilers/Concerns/CompilesUseStatements.php +++ b/src/Illuminate/View/Compilers/Concerns/CompilesUseStatements.php @@ -12,7 +12,16 @@ trait CompilesUseStatements */ protected function compileUse($expression) { - $segments = explode(',', preg_replace("/[\(\)]/", '', $expression)); + $expression = preg_replace('/[()]/', '', $expression); + + // Preserve grouped imports as-is... + if (str_contains($expression, '{')) { + $use = ltrim(trim($expression, " '\""), '\\'); + + return "<?php use \\{$use}; ?>"; + } + + $segments = explode(',', $expression); $use = ltrim(trim($segments[0], " '\""), '\\'); $as = isset($segments[1]) ? ' as '.trim($segments[1], " '\"") : ''; diff --git a/tests/View/Blade/BladeUseTest.php b/tests/View/Blade/BladeUseTest.php index ae99825de61e..980a266128a6 100644 --- a/tests/View/Blade/BladeUseTest.php +++ b/tests/View/Blade/BladeUseTest.php @@ -47,4 +47,26 @@ public function testUseStatementsWithBackslashAtBeginningAndAliasedAreCompiled() $string = "Foo @use(\SomeNamespace\SomeClass, Foo) bar"; $this->assertEquals($expected, $this->compiler->compileString($string)); } + + public function testUseStatementsWithBracesAreCompiledCorrectly() + { + $expected = "Foo <?php use \SomeNamespace\{Foo, Bar}; ?> bar"; + + $string = "Foo @use('SomeNamespace\{Foo, Bar}') bar"; + $this->assertEquals($expected, $this->compiler->compileString($string)); + + $string = "Foo @use(SomeNamespace\{Foo, Bar}) bar"; + $this->assertEquals($expected, $this->compiler->compileString($string)); + } + + public function testUseStatementWithBracesAndBackslashAreCompiledCorrectly() + { + $expected = "Foo <?php use \SomeNamespace\{Foo, Bar}; ?> bar"; + + $string = "Foo @use('\SomeNamespace\{Foo, Bar}') bar"; + $this->assertEquals($expected, $this->compiler->compileString($string)); + + $string = "Foo @use(\SomeNamespace\{Foo, Bar}) bar"; + $this->assertEquals($expected, $this->compiler->compileString($string)); + } }
diff --git a/src/Illuminate/View/Compilers/Concerns/CompilesUseStatements.php b/src/Illuminate/View/Compilers/Concerns/CompilesUseStatements.php index 8218c9fdf2c6..49a524a5fd9f 100644 --- a/src/Illuminate/View/Compilers/Concerns/CompilesUseStatements.php +++ b/src/Illuminate/View/Compilers/Concerns/CompilesUseStatements.php @@ -12,7 +12,16 @@ trait CompilesUseStatements */ protected function compileUse($expression) { + $expression = preg_replace('/[()]/', '', $expression); + // Preserve grouped imports as-is... + if (str_contains($expression, '{')) { + } + $segments = explode(',', $expression); $use = ltrim(trim($segments[0], " '\""), '\\'); $as = isset($segments[1]) ? ' as '.trim($segments[1], " '\"") : ''; diff --git a/tests/View/Blade/BladeUseTest.php b/tests/View/Blade/BladeUseTest.php index ae99825de61e..980a266128a6 100644 --- a/tests/View/Blade/BladeUseTest.php +++ b/tests/View/Blade/BladeUseTest.php @@ -47,4 +47,26 @@ public function testUseStatementsWithBackslashAtBeginningAndAliasedAreCompiled() $string = "Foo @use(\SomeNamespace\SomeClass, Foo) bar"; $this->assertEquals($expected, $this->compiler->compileString($string)); } + public function testUseStatementsWithBracesAreCompiledCorrectly() + $string = "Foo @use('SomeNamespace\{Foo, Bar}') bar"; + $string = "Foo @use(SomeNamespace\{Foo, Bar}) bar"; + public function testUseStatementWithBracesAndBackslashAreCompiledCorrectly() + $string = "Foo @use(\SomeNamespace\{Foo, Bar}) bar"; }
[ "- $segments = explode(',', preg_replace(\"/[\\(\\)]/\", '', $expression));", "+ $use = ltrim(trim($expression, \" '\\\"\"), '\\\\');", "+ return \"<?php use \\\\{$use}; ?>\";", "+ $string = \"Foo @use('\\SomeNamespace\\{Foo, Bar}') bar\";" ]
[ 8, 13, 15, 46 ]
{ "additions": 32, "author": "osbre", "deletions": 1, "html_url": "https://github.com/laravel/framework/pull/55461", "issue_id": 55461, "merged_at": "2025-04-18T20:17:46Z", "omission_probability": 0.1, "pr_number": 55461, "repo": "laravel/framework", "title": "[12.x] Fix group imports in Blade `@use` directive", "total_changes": 33 }
26
diff --git a/src/Illuminate/Database/Eloquent/Builder.php b/src/Illuminate/Database/Eloquent/Builder.php index 73163988aec..4e22b9ae9fa 100755 --- a/src/Illuminate/Database/Eloquent/Builder.php +++ b/src/Illuminate/Database/Eloquent/Builder.php @@ -854,13 +854,9 @@ public function get($columns = ['*']) $models = $builder->eagerLoadRelations($models); } - $collection = $builder->getModel()->newCollection($models); - - if (Model::isAutomaticallyEagerLoadingRelationships()) { - $collection->withRelationshipAutoloading(); - } - - return $this->applyAfterQueryCallbacks($collection); + return $this->applyAfterQueryCallbacks( + $builder->getModel()->newCollection($models) + ); } /** diff --git a/src/Illuminate/Database/Eloquent/HasCollection.php b/src/Illuminate/Database/Eloquent/HasCollection.php index a1b462784dd..d430f0099b8 100644 --- a/src/Illuminate/Database/Eloquent/HasCollection.php +++ b/src/Illuminate/Database/Eloquent/HasCollection.php @@ -27,7 +27,13 @@ public function newCollection(array $models = []) { static::$resolvedCollectionClasses[static::class] ??= ($this->resolveCollectionFromAttribute() ?? static::$collectionClass); - return new static::$resolvedCollectionClasses[static::class]($models); + $collection = new static::$resolvedCollectionClasses[static::class]($models); + + if (Model::isAutomaticallyEagerLoadingRelationships()) { + $collection->withRelationshipAutoloading(); + } + + return $collection; } /**
diff --git a/src/Illuminate/Database/Eloquent/Builder.php b/src/Illuminate/Database/Eloquent/Builder.php index 73163988aec..4e22b9ae9fa 100755 --- a/src/Illuminate/Database/Eloquent/Builder.php +++ b/src/Illuminate/Database/Eloquent/Builder.php @@ -854,13 +854,9 @@ public function get($columns = ['*']) $models = $builder->eagerLoadRelations($models); } - $collection = $builder->getModel()->newCollection($models); - if (Model::isAutomaticallyEagerLoadingRelationships()) { - $collection->withRelationshipAutoloading(); - } - return $this->applyAfterQueryCallbacks($collection); + return $this->applyAfterQueryCallbacks( + $builder->getModel()->newCollection($models) + ); diff --git a/src/Illuminate/Database/Eloquent/HasCollection.php b/src/Illuminate/Database/Eloquent/HasCollection.php index a1b462784dd..d430f0099b8 100644 --- a/src/Illuminate/Database/Eloquent/HasCollection.php +++ b/src/Illuminate/Database/Eloquent/HasCollection.php @@ -27,7 +27,13 @@ public function newCollection(array $models = []) { static::$resolvedCollectionClasses[static::class] ??= ($this->resolveCollectionFromAttribute() ?? static::$collectionClass); - return new static::$resolvedCollectionClasses[static::class]($models); + $collection = new static::$resolvedCollectionClasses[static::class]($models); + $collection->withRelationshipAutoloading(); + }
[ "+ if (Model::isAutomaticallyEagerLoadingRelationships()) {", "+ return $collection;" ]
[ 32, 36 ]
{ "additions": 10, "author": "litvinchuk", "deletions": 8, "html_url": "https://github.com/laravel/framework/pull/55443", "issue_id": 55443, "merged_at": "2025-04-18T12:55:05Z", "omission_probability": 0.1, "pr_number": 55443, "repo": "laravel/framework", "title": "[12.x] Fix for global autoload relationships not working in certain cases", "total_changes": 18 }
27
diff --git a/src/Illuminate/Cache/RateLimiter.php b/src/Illuminate/Cache/RateLimiter.php index c3598e364eb..67588ffbb1e 100644 --- a/src/Illuminate/Cache/RateLimiter.php +++ b/src/Illuminate/Cache/RateLimiter.php @@ -99,7 +99,7 @@ public function limiter($name) * @param string $key * @param int $maxAttempts * @param \Closure $callback - * @param int $decaySeconds + * @param \DateTimeInterface|\DateInterval|int $decaySeconds * @return mixed */ public function attempt($key, $maxAttempts, Closure $callback, $decaySeconds = 60) @@ -141,7 +141,7 @@ public function tooManyAttempts($key, $maxAttempts) * Increment (by 1) the counter for a given key for a given decay time. * * @param string $key - * @param int $decaySeconds + * @param \DateTimeInterface|\DateInterval|int $decaySeconds * @return int */ public function hit($key, $decaySeconds = 60) @@ -153,7 +153,7 @@ public function hit($key, $decaySeconds = 60) * Increment the counter for a given key for a given decay time by a given amount. * * @param string $key - * @param int $decaySeconds + * @param \DateTimeInterface|\DateInterval|int $decaySeconds * @param int $amount * @return int */ @@ -184,7 +184,7 @@ public function increment($key, $decaySeconds = 60, $amount = 1) * Decrement the counter for a given key for a given decay time by a given amount. * * @param string $key - * @param int $decaySeconds + * @param \DateTimeInterface|\DateInterval|int $decaySeconds * @param int $amount * @return int */ diff --git a/src/Illuminate/Support/Facades/RateLimiter.php b/src/Illuminate/Support/Facades/RateLimiter.php index 376c3ccc19d..7f8cf5c2166 100644 --- a/src/Illuminate/Support/Facades/RateLimiter.php +++ b/src/Illuminate/Support/Facades/RateLimiter.php @@ -5,11 +5,11 @@ /** * @method static \Illuminate\Cache\RateLimiter for(\BackedEnum|\UnitEnum|string $name, \Closure $callback) * @method static \Closure|null limiter(\BackedEnum|\UnitEnum|string $name) - * @method static mixed attempt(string $key, int $maxAttempts, \Closure $callback, int $decaySeconds = 60) + * @method static mixed attempt(string $key, int $maxAttempts, \Closure $callback, \DateTimeInterface|\DateInterval|int $decaySeconds = 60) * @method static bool tooManyAttempts(string $key, int $maxAttempts) - * @method static int hit(string $key, int $decaySeconds = 60) - * @method static int increment(string $key, int $decaySeconds = 60, int $amount = 1) - * @method static int decrement(string $key, int $decaySeconds = 60, int $amount = 1) + * @method static int hit(string $key, \DateTimeInterface|\DateInterval|int $decaySeconds = 60) + * @method static int increment(string $key, \DateTimeInterface|\DateInterval|int $decaySeconds = 60, int $amount = 1) + * @method static int decrement(string $key, \DateTimeInterface|\DateInterval|int $decaySeconds = 60, int $amount = 1) * @method static mixed attempts(string $key) * @method static mixed resetAttempts(string $key) * @method static int remaining(string $key, int $maxAttempts)
diff --git a/src/Illuminate/Cache/RateLimiter.php b/src/Illuminate/Cache/RateLimiter.php index c3598e364eb..67588ffbb1e 100644 --- a/src/Illuminate/Cache/RateLimiter.php +++ b/src/Illuminate/Cache/RateLimiter.php @@ -99,7 +99,7 @@ public function limiter($name) * @param int $maxAttempts * @param \Closure $callback * @return mixed public function attempt($key, $maxAttempts, Closure $callback, $decaySeconds = 60) @@ -141,7 +141,7 @@ public function tooManyAttempts($key, $maxAttempts) * Increment (by 1) the counter for a given key for a given decay time. public function hit($key, $decaySeconds = 60) @@ -153,7 +153,7 @@ public function hit($key, $decaySeconds = 60) * Increment the counter for a given key for a given decay time by a given amount. @@ -184,7 +184,7 @@ public function increment($key, $decaySeconds = 60, $amount = 1) * Decrement the counter for a given key for a given decay time by a given amount. diff --git a/src/Illuminate/Support/Facades/RateLimiter.php b/src/Illuminate/Support/Facades/RateLimiter.php index 376c3ccc19d..7f8cf5c2166 100644 --- a/src/Illuminate/Support/Facades/RateLimiter.php +++ b/src/Illuminate/Support/Facades/RateLimiter.php @@ -5,11 +5,11 @@ /** * @method static \Illuminate\Cache\RateLimiter for(\BackedEnum|\UnitEnum|string $name, \Closure $callback) * @method static \Closure|null limiter(\BackedEnum|\UnitEnum|string $name) - * @method static mixed attempt(string $key, int $maxAttempts, \Closure $callback, int $decaySeconds = 60) + * @method static mixed attempt(string $key, int $maxAttempts, \Closure $callback, \DateTimeInterface|\DateInterval|int $decaySeconds = 60) * @method static bool tooManyAttempts(string $key, int $maxAttempts) - * @method static int hit(string $key, int $decaySeconds = 60) - * @method static int increment(string $key, int $decaySeconds = 60, int $amount = 1) - * @method static int decrement(string $key, int $decaySeconds = 60, int $amount = 1) + * @method static int hit(string $key, \DateTimeInterface|\DateInterval|int $decaySeconds = 60) + * @method static int increment(string $key, \DateTimeInterface|\DateInterval|int $decaySeconds = 60, int $amount = 1) * @method static mixed attempts(string $key) * @method static mixed resetAttempts(string $key) * @method static int remaining(string $key, int $maxAttempts)
[ "+ * @method static int decrement(string $key, \\DateTimeInterface|\\DateInterval|int $decaySeconds = 60, int $amount = 1)" ]
[ 56 ]
{ "additions": 8, "author": "ClaudioEyzaguirre", "deletions": 8, "html_url": "https://github.com/laravel/framework/pull/55445", "issue_id": 55445, "merged_at": "2025-04-18T12:52:24Z", "omission_probability": 0.1, "pr_number": 55445, "repo": "laravel/framework", "title": "Add missing types to RateLimiter", "total_changes": 16 }
28
diff --git a/tests/Events/BroadcastedEventsTest.php b/tests/Events/BroadcastedEventsTest.php index c241938364ba..9b2a84a31ae7 100644 --- a/tests/Events/BroadcastedEventsTest.php +++ b/tests/Events/BroadcastedEventsTest.php @@ -62,6 +62,92 @@ public function testShouldBroadcastFail() $this->assertFalse($d->shouldBroadcast([$event])); } + + public function testBroadcastWithMultipleChannels() + { + $d = new Dispatcher($container = m::mock(Container::class)); + $broadcast = m::mock(BroadcastFactory::class); + $broadcast->shouldReceive('queue')->once(); + $container->shouldReceive('make')->once()->with(BroadcastFactory::class)->andReturn($broadcast); + + $event = new class implements ShouldBroadcast + { + public function broadcastOn() + { + return ['channel-1', 'channel-2']; + } + }; + + $d->dispatch($event); + } + + public function testBroadcastWithCustomConnectionName() + { + $d = new Dispatcher($container = m::mock(Container::class)); + $broadcast = m::mock(BroadcastFactory::class); + $broadcast->shouldReceive('queue')->once(); + $container->shouldReceive('make')->once()->with(BroadcastFactory::class)->andReturn($broadcast); + + $event = new class implements ShouldBroadcast + { + public $connection = 'custom-connection'; + + public function broadcastOn() + { + return ['test-channel']; + } + }; + + $d->dispatch($event); + } + + public function testBroadcastWithCustomEventName() + { + $d = new Dispatcher($container = m::mock(Container::class)); + $broadcast = m::mock(BroadcastFactory::class); + $broadcast->shouldReceive('queue')->once(); + $container->shouldReceive('make')->once()->with(BroadcastFactory::class)->andReturn($broadcast); + + $event = new class implements ShouldBroadcast + { + public function broadcastOn() + { + return ['test-channel']; + } + + public function broadcastAs() + { + return 'custom-event-name'; + } + }; + + $d->dispatch($event); + } + + public function testBroadcastWithCustomPayload() + { + $d = new Dispatcher($container = m::mock(Container::class)); + $broadcast = m::mock(BroadcastFactory::class); + $broadcast->shouldReceive('queue')->once(); + $container->shouldReceive('make')->once()->with(BroadcastFactory::class)->andReturn($broadcast); + + $event = new class implements ShouldBroadcast + { + public $customData = 'test-data'; + + public function broadcastOn() + { + return ['test-channel']; + } + + public function broadcastWith() + { + return ['custom' => $this->customData]; + } + }; + + $d->dispatch($event); + } } class BroadcastEvent implements ShouldBroadcast
diff --git a/tests/Events/BroadcastedEventsTest.php b/tests/Events/BroadcastedEventsTest.php index c241938364ba..9b2a84a31ae7 100644 --- a/tests/Events/BroadcastedEventsTest.php +++ b/tests/Events/BroadcastedEventsTest.php @@ -62,6 +62,92 @@ public function testShouldBroadcastFail() $this->assertFalse($d->shouldBroadcast([$event])); } + public function testBroadcastWithMultipleChannels() + return ['channel-1', 'channel-2']; + public $connection = 'custom-connection'; + public function testBroadcastWithCustomEventName() + public function broadcastAs() + public function testBroadcastWithCustomPayload() + public $customData = 'test-data'; + public function broadcastWith() } class BroadcastEvent implements ShouldBroadcast
[ "+ public function testBroadcastWithCustomConnectionName()", "+ return 'custom-event-name';", "+ return ['custom' => $this->customData];" ]
[ 27, 63, 88 ]
{ "additions": 86, "author": "roshandelpoor", "deletions": 0, "html_url": "https://github.com/laravel/framework/pull/55458", "issue_id": 55458, "merged_at": "2025-04-18T12:46:40Z", "omission_probability": 0.1, "pr_number": 55458, "repo": "laravel/framework", "title": "[12.x] Enhance Broadcast Events Test Coverage", "total_changes": 86 }
29
diff --git a/tests/View/Blade/BladeUseTest.php b/tests/View/Blade/BladeUseTest.php index 8e72c321540d..ae99825de61e 100644 --- a/tests/View/Blade/BladeUseTest.php +++ b/tests/View/Blade/BladeUseTest.php @@ -6,29 +6,45 @@ class BladeUseTest extends AbstractBladeTestCase { public function testUseStatementsAreCompiled() { - $string = "Foo @use('SomeNamespace\SomeClass', 'Foo') bar"; $expected = "Foo <?php use \SomeNamespace\SomeClass as Foo; ?> bar"; + + $string = "Foo @use('SomeNamespace\SomeClass', 'Foo') bar"; + $this->assertEquals($expected, $this->compiler->compileString($string)); + + $string = "Foo @use(SomeNamespace\SomeClass, Foo) bar"; $this->assertEquals($expected, $this->compiler->compileString($string)); } public function testUseStatementsWithoutAsAreCompiled() { - $string = "Foo @use('SomeNamespace\SomeClass') bar"; $expected = "Foo <?php use \SomeNamespace\SomeClass; ?> bar"; + + $string = "Foo @use('SomeNamespace\SomeClass') bar"; + $this->assertEquals($expected, $this->compiler->compileString($string)); + + $string = "Foo @use(SomeNamespace\SomeClass) bar"; $this->assertEquals($expected, $this->compiler->compileString($string)); } public function testUseStatementsWithBackslashAtBeginningAreCompiled() { - $string = "Foo @use('\SomeNamespace\SomeClass') bar"; $expected = "Foo <?php use \SomeNamespace\SomeClass; ?> bar"; + + $string = "Foo @use('\SomeNamespace\SomeClass') bar"; + $this->assertEquals($expected, $this->compiler->compileString($string)); + + $string = "Foo @use(\SomeNamespace\SomeClass) bar"; $this->assertEquals($expected, $this->compiler->compileString($string)); } public function testUseStatementsWithBackslashAtBeginningAndAliasedAreCompiled() { - $string = "Foo @use('\SomeNamespace\SomeClass', 'Foo') bar"; $expected = "Foo <?php use \SomeNamespace\SomeClass as Foo; ?> bar"; + + $string = "Foo @use('\SomeNamespace\SomeClass', 'Foo') bar"; + $this->assertEquals($expected, $this->compiler->compileString($string)); + + $string = "Foo @use(\SomeNamespace\SomeClass, Foo) bar"; $this->assertEquals($expected, $this->compiler->compileString($string)); } }
diff --git a/tests/View/Blade/BladeUseTest.php b/tests/View/Blade/BladeUseTest.php index 8e72c321540d..ae99825de61e 100644 --- a/tests/View/Blade/BladeUseTest.php +++ b/tests/View/Blade/BladeUseTest.php @@ -6,29 +6,45 @@ class BladeUseTest extends AbstractBladeTestCase { public function testUseStatementsAreCompiled() - $string = "Foo @use('SomeNamespace\SomeClass', 'Foo') bar"; + $string = "Foo @use('SomeNamespace\SomeClass', 'Foo') bar"; + $string = "Foo @use(SomeNamespace\SomeClass, Foo) bar"; public function testUseStatementsWithoutAsAreCompiled() - $string = "Foo @use('SomeNamespace\SomeClass') bar"; + $string = "Foo @use('SomeNamespace\SomeClass') bar"; + $string = "Foo @use(SomeNamespace\SomeClass) bar"; public function testUseStatementsWithBackslashAtBeginningAreCompiled() - $string = "Foo @use('\SomeNamespace\SomeClass') bar"; + $string = "Foo @use('\SomeNamespace\SomeClass') bar"; + $string = "Foo @use(\SomeNamespace\SomeClass) bar"; public function testUseStatementsWithBackslashAtBeginningAndAliasedAreCompiled() - $string = "Foo @use('\SomeNamespace\SomeClass', 'Foo') bar"; + $string = "Foo @use(\SomeNamespace\SomeClass, Foo) bar"; }
[ "+ $string = \"Foo @use('\\SomeNamespace\\SomeClass', 'Foo') bar\";" ]
[ 47 ]
{ "additions": 20, "author": "osbre", "deletions": 4, "html_url": "https://github.com/laravel/framework/pull/55462", "issue_id": 55462, "merged_at": "2025-04-18T12:45:24Z", "omission_probability": 0.1, "pr_number": 55462, "repo": "laravel/framework", "title": "[12.x] Test `@use` directive without quotes", "total_changes": 24 }
30
diff --git a/src/Illuminate/Database/Concerns/BuildsQueries.php b/src/Illuminate/Database/Concerns/BuildsQueries.php index 253fe516d438..f78e13b2d500 100644 --- a/src/Illuminate/Database/Concerns/BuildsQueries.php +++ b/src/Illuminate/Database/Concerns/BuildsQueries.php @@ -587,7 +587,7 @@ protected function cursorPaginator($items, $perPage, $cursor, $options) } /** - * Pass the query to a given callback. + * Pass the query to a given callback and then return it. * * @param callable($this): mixed $callback * @return $this @@ -598,4 +598,17 @@ public function tap($callback) return $this; } + + /** + * Pass the query to a given callback and return the result. + * + * @template TReturn + * + * @param (callable($this): TReturn) $callback + * @return (TReturn is null|void ? $this : TReturn) + */ + public function pipe($callback) + { + return $callback($this) ?? $this; + } } diff --git a/tests/Database/DatabaseEloquentBuilderTest.php b/tests/Database/DatabaseEloquentBuilderTest.php index a3ba7837cc2d..41e5fa529877 100755 --- a/tests/Database/DatabaseEloquentBuilderTest.php +++ b/tests/Database/DatabaseEloquentBuilderTest.php @@ -21,6 +21,7 @@ use Illuminate\Support\Carbon; use Illuminate\Support\Collection as BaseCollection; use Mockery as m; +use PDO; use PHPUnit\Framework\TestCase; use stdClass; @@ -2615,6 +2616,31 @@ public function getPassthru(): array } } + public function testPipeCallback() + { + $query = new Builder(new BaseBuilder( + $connection = new Connection(new PDO('sqlite::memory:')), + new Grammar($connection), + new Processor, + )); + + $result = $query->pipe(fn (Builder $query) => 5); + $this->assertSame(5, $result); + + $result = $query->pipe(fn (Builder $query) => null); + $this->assertSame($query, $result); + + $result = $query->pipe(function (Builder $query) { + // + }); + $this->assertSame($query, $result); + + $this->assertCount(0, $query->getQuery()->wheres); + $result = $query->pipe(fn (Builder $query) => $query->where('foo', 'bar')); + $this->assertSame($query, $result); + $this->assertCount(1, $query->getQuery()->wheres); + } + protected function mockConnectionForModel($model, $database) { $grammarClass = 'Illuminate\Database\Query\Grammars\\'.$database.'Grammar'; diff --git a/tests/Database/DatabaseQueryBuilderTest.php b/tests/Database/DatabaseQueryBuilderTest.php index 95142e0b698c..1fd624316acb 100755 --- a/tests/Database/DatabaseQueryBuilderTest.php +++ b/tests/Database/DatabaseQueryBuilderTest.php @@ -301,6 +301,27 @@ public function testTapCallback() $this->assertSame('select * from "users" where "id" = ? and "email" = ?', $builder->toSql()); } + public function testPipeCallback() + { + $query = $this->getBuilder(); + + $result = $query->pipe(fn (Builder $query) => 5); + $this->assertSame(5, $result); + + $result = $query->pipe(fn (Builder $query) => null); + $this->assertSame($query, $result); + + $result = $query->pipe(function (Builder $query) { + // + }); + $this->assertSame($query, $result); + + $this->assertCount(0, $query->wheres); + $result = $query->pipe(fn (Builder $query) => $query->where('foo', 'bar')); + $this->assertSame($query, $result); + $this->assertCount(1, $query->wheres); + } + public function testBasicWheres() { $builder = $this->getBuilder(); diff --git a/types/Database/Eloquent/Builder.php b/types/Database/Eloquent/Builder.php index fe11459c1875..24f03fc71f99 100644 --- a/types/Database/Eloquent/Builder.php +++ b/types/Database/Eloquent/Builder.php @@ -223,6 +223,12 @@ function test( assertType('Illuminate\Types\Builder\CommentBuilder', $comment->newQuery()->where('foo', 'bar')); assertType('Illuminate\Types\Builder\CommentBuilder', $comment->newQuery()->foo()); assertType('Illuminate\Types\Builder\Comment', $comment->newQuery()->create(['name' => 'John'])); + assertType('Illuminate\Database\Eloquent\Builder<Illuminate\Types\Builder\User>', $query->pipe(function () { + // + })); + assertType('Illuminate\Database\Eloquent\Builder<Illuminate\Types\Builder\User>', $query->pipe(fn () => null)); + assertType('Illuminate\Database\Eloquent\Builder<Illuminate\Types\Builder\User>', $query->pipe(fn ($query) => $query)); + assertType('5', $query->pipe(fn ($query) => 5)); } class User extends Model diff --git a/types/Database/Query/Builder.php b/types/Database/Query/Builder.php index c5917edf6b20..780630bdd39c 100644 --- a/types/Database/Query/Builder.php +++ b/types/Database/Query/Builder.php @@ -60,4 +60,10 @@ function test(Builder $query, EloquentBuilder $userQuery): void assertType('object', $users); assertType('int', $page); }); + assertType('Illuminate\Database\Query\Builder', $query->pipe(function () { + // + })); + assertType('Illuminate\Database\Query\Builder', $query->pipe(fn () => null)); + assertType('Illuminate\Database\Query\Builder', $query->pipe(fn ($query) => $query)); + assertType('5', $query->pipe(fn ($query) => 5)); }
diff --git a/src/Illuminate/Database/Concerns/BuildsQueries.php b/src/Illuminate/Database/Concerns/BuildsQueries.php index 253fe516d438..f78e13b2d500 100644 --- a/src/Illuminate/Database/Concerns/BuildsQueries.php +++ b/src/Illuminate/Database/Concerns/BuildsQueries.php @@ -587,7 +587,7 @@ protected function cursorPaginator($items, $perPage, $cursor, $options) /** + * Pass the query to a given callback and then return it. * * @param callable($this): mixed $callback * @return $this @@ -598,4 +598,17 @@ public function tap($callback) return $this; + /** + * Pass the query to a given callback and return the result. + * @template TReturn + * @param (callable($this): TReturn) $callback + * @return (TReturn is null|void ? $this : TReturn) + */ + public function pipe($callback) + return $callback($this) ?? $this; diff --git a/tests/Database/DatabaseEloquentBuilderTest.php b/tests/Database/DatabaseEloquentBuilderTest.php index a3ba7837cc2d..41e5fa529877 100755 --- a/tests/Database/DatabaseEloquentBuilderTest.php +++ b/tests/Database/DatabaseEloquentBuilderTest.php @@ -21,6 +21,7 @@ use Illuminate\Support\Carbon; use Illuminate\Support\Collection as BaseCollection; use Mockery as m; +use PDO; use PHPUnit\Framework\TestCase; use stdClass; @@ -2615,6 +2616,31 @@ public function getPassthru(): array } + $query = new Builder(new BaseBuilder( + $connection = new Connection(new PDO('sqlite::memory:')), + new Grammar($connection), + new Processor, + )); + $this->assertCount(1, $query->getQuery()->wheres); protected function mockConnectionForModel($model, $database) $grammarClass = 'Illuminate\Database\Query\Grammars\\'.$database.'Grammar'; diff --git a/tests/Database/DatabaseQueryBuilderTest.php b/tests/Database/DatabaseQueryBuilderTest.php index 95142e0b698c..1fd624316acb 100755 --- a/tests/Database/DatabaseQueryBuilderTest.php +++ b/tests/Database/DatabaseQueryBuilderTest.php @@ -301,6 +301,27 @@ public function testTapCallback() $this->assertSame('select * from "users" where "id" = ? and "email" = ?', $builder->toSql()); + $query = $this->getBuilder(); + $this->assertCount(0, $query->wheres); + $this->assertCount(1, $query->wheres); public function testBasicWheres() $builder = $this->getBuilder(); diff --git a/types/Database/Eloquent/Builder.php b/types/Database/Eloquent/Builder.php index fe11459c1875..24f03fc71f99 100644 --- a/types/Database/Eloquent/Builder.php +++ b/types/Database/Eloquent/Builder.php @@ -223,6 +223,12 @@ function test( assertType('Illuminate\Types\Builder\CommentBuilder', $comment->newQuery()->where('foo', 'bar')); assertType('Illuminate\Types\Builder\CommentBuilder', $comment->newQuery()->foo()); assertType('Illuminate\Types\Builder\Comment', $comment->newQuery()->create(['name' => 'John'])); + assertType('Illuminate\Database\Eloquent\Builder<Illuminate\Types\Builder\User>', $query->pipe(function () { + assertType('Illuminate\Database\Eloquent\Builder<Illuminate\Types\Builder\User>', $query->pipe(fn () => null)); + assertType('Illuminate\Database\Eloquent\Builder<Illuminate\Types\Builder\User>', $query->pipe(fn ($query) => $query)); class User extends Model diff --git a/types/Database/Query/Builder.php b/types/Database/Query/Builder.php index c5917edf6b20..780630bdd39c 100644 --- a/types/Database/Query/Builder.php +++ b/types/Database/Query/Builder.php @@ -60,4 +60,10 @@ function test(Builder $query, EloquentBuilder $userQuery): void assertType('object', $users); assertType('int', $page); }); + assertType('Illuminate\Database\Query\Builder', $query->pipe(function () { + assertType('Illuminate\Database\Query\Builder', $query->pipe(fn ($query) => $query));
[ "- * Pass the query to a given callback.", "+ $this->assertCount(0, $query->getQuery()->wheres);", "+ assertType('Illuminate\\Database\\Query\\Builder', $query->pipe(fn () => null));" ]
[ 8, 66, 135 ]
{ "additions": 73, "author": "timacdonald", "deletions": 1, "html_url": "https://github.com/laravel/framework/pull/55171", "issue_id": 55171, "merged_at": "2025-03-27T17:18:55Z", "omission_probability": 0.1, "pr_number": 55171, "repo": "laravel/framework", "title": "[12.x] Add `pipe` method query builders", "total_changes": 74 }
31
diff --git a/src/Illuminate/Database/Concerns/ManagesTransactions.php b/src/Illuminate/Database/Concerns/ManagesTransactions.php index 23bc60434e49..609095bee849 100644 --- a/src/Illuminate/Database/Concerns/ManagesTransactions.php +++ b/src/Illuminate/Database/Concerns/ManagesTransactions.php @@ -16,11 +16,12 @@ trait ManagesTransactions * * @param (\Closure(static): TReturn) $callback * @param int $attempts + * @param Closure|null $onFailure * @return TReturn * * @throws \Throwable */ - public function transaction(Closure $callback, $attempts = 1) + public function transaction(Closure $callback, $attempts = 1, ?Closure $onFailure = null) { for ($currentAttempt = 1; $currentAttempt <= $attempts; $currentAttempt++) { $this->beginTransaction(); @@ -37,7 +38,7 @@ public function transaction(Closure $callback, $attempts = 1) // exception back out, and let the developer handle an uncaught exception. catch (Throwable $e) { $this->handleTransactionException( - $e, $currentAttempt, $attempts + $e, $currentAttempt, $attempts, $onFailure ); continue; @@ -78,11 +79,12 @@ public function transaction(Closure $callback, $attempts = 1) * @param \Throwable $e * @param int $currentAttempt * @param int $maxAttempts + * @param Closure|null $onFailure * @return void * * @throws \Throwable */ - protected function handleTransactionException(Throwable $e, $currentAttempt, $maxAttempts) + protected function handleTransactionException(Throwable $e, $currentAttempt, $maxAttempts, ?Closure $onFailure) { // On a deadlock, MySQL rolls back the entire transaction so we can't just // retry the query. We have to throw this exception all the way out and @@ -108,6 +110,10 @@ protected function handleTransactionException(Throwable $e, $currentAttempt, $ma return; } + if ($onFailure !== null) { + $onFailure($e); + } + throw $e; } diff --git a/src/Illuminate/Database/ConnectionInterface.php b/src/Illuminate/Database/ConnectionInterface.php index 288adb4206e3..322a59576724 100755 --- a/src/Illuminate/Database/ConnectionInterface.php +++ b/src/Illuminate/Database/ConnectionInterface.php @@ -131,11 +131,12 @@ public function prepareBindings(array $bindings); * * @param \Closure $callback * @param int $attempts + * @param Closure|null $onFailure * @return mixed * * @throws \Throwable */ - public function transaction(Closure $callback, $attempts = 1); + public function transaction(Closure $callback, $attempts = 1, ?Closure $onFailure = null); /** * Start a new database transaction. diff --git a/src/Illuminate/Database/SqlServerConnection.php b/src/Illuminate/Database/SqlServerConnection.php index 1e6fe52bfe16..bddf82f02a70 100755 --- a/src/Illuminate/Database/SqlServerConnection.php +++ b/src/Illuminate/Database/SqlServerConnection.php @@ -27,15 +27,16 @@ public function getDriverTitle() * * @param \Closure $callback * @param int $attempts + * @param Closure|null $onFailure * @return mixed * * @throws \Throwable */ - public function transaction(Closure $callback, $attempts = 1) + public function transaction(Closure $callback, $attempts = 1, ?Closure $onFailure = null) { for ($a = 1; $a <= $attempts; $a++) { if ($this->getDriverName() === 'sqlsrv') { - return parent::transaction($callback, $attempts); + return parent::transaction($callback, $attempts, $onFailure); } $this->getPdo()->exec('BEGIN TRAN'); @@ -55,6 +56,10 @@ public function transaction(Closure $callback, $attempts = 1) catch (Throwable $e) { $this->getPdo()->exec('ROLLBACK TRAN'); + if ($a === $attempts && $onFailure !== null) { + $onFailure($e); + } + throw $e; } diff --git a/tests/Integration/Database/DatabaseTransactionsTest.php b/tests/Integration/Database/DatabaseTransactionsTest.php index 58894d01ae5e..35051f528b20 100644 --- a/tests/Integration/Database/DatabaseTransactionsTest.php +++ b/tests/Integration/Database/DatabaseTransactionsTest.php @@ -105,6 +105,42 @@ public function testTransactionsDoNotAffectDifferentConnections() $this->assertTrue($secondObject->ran); $this->assertFalse($thirdObject->ran); } + + public function testOnErrorCallbackIsCalled() + { + $executed = false; + try { + DB::transaction(function () { + throw new \Exception; + }, 1, function () use (&$executed) { + $executed = true; + }); + } catch (\Throwable) { + // Ignore the exception + } + + $this->assertTrue($executed); + } + + public function testOnErrorCallbackIsCalledWithDeadlockRetry() + { + $executed = false; + $attempts = 0; + + try { + DB::transaction(function () use (&$attempts) { + $attempts += 1; + throw new \Exception('has been chosen as the deadlock victim'); + }, 3, function () use (&$executed) { + $executed = true; + }); + } catch (\Throwable) { + // Ignore the exception + } + + $this->assertSame(3, $attempts); + $this->assertTrue($executed); + } } class TestObjectForTransactions
diff --git a/src/Illuminate/Database/Concerns/ManagesTransactions.php b/src/Illuminate/Database/Concerns/ManagesTransactions.php index 23bc60434e49..609095bee849 100644 --- a/src/Illuminate/Database/Concerns/ManagesTransactions.php +++ b/src/Illuminate/Database/Concerns/ManagesTransactions.php @@ -16,11 +16,12 @@ trait ManagesTransactions * @param (\Closure(static): TReturn) $callback * @return TReturn for ($currentAttempt = 1; $currentAttempt <= $attempts; $currentAttempt++) { $this->beginTransaction(); @@ -37,7 +38,7 @@ public function transaction(Closure $callback, $attempts = 1) // exception back out, and let the developer handle an uncaught exception. $this->handleTransactionException( - $e, $currentAttempt, $attempts + $e, $currentAttempt, $attempts, $onFailure ); continue; @@ -78,11 +79,12 @@ public function transaction(Closure $callback, $attempts = 1) * @param \Throwable $e * @param int $currentAttempt * @param int $maxAttempts + * @param Closure|null $onFailure * @return void + protected function handleTransactionException(Throwable $e, $currentAttempt, $maxAttempts, ?Closure $onFailure) // On a deadlock, MySQL rolls back the entire transaction so we can't just // retry the query. We have to throw this exception all the way out and @@ -108,6 +110,10 @@ protected function handleTransactionException(Throwable $e, $currentAttempt, $ma return; } + if ($onFailure !== null) { throw $e; diff --git a/src/Illuminate/Database/ConnectionInterface.php b/src/Illuminate/Database/ConnectionInterface.php index 288adb4206e3..322a59576724 100755 --- a/src/Illuminate/Database/ConnectionInterface.php +++ b/src/Illuminate/Database/ConnectionInterface.php @@ -131,11 +131,12 @@ public function prepareBindings(array $bindings); - public function transaction(Closure $callback, $attempts = 1); + public function transaction(Closure $callback, $attempts = 1, ?Closure $onFailure = null); /** * Start a new database transaction. diff --git a/src/Illuminate/Database/SqlServerConnection.php b/src/Illuminate/Database/SqlServerConnection.php index 1e6fe52bfe16..bddf82f02a70 100755 --- a/src/Illuminate/Database/SqlServerConnection.php +++ b/src/Illuminate/Database/SqlServerConnection.php @@ -27,15 +27,16 @@ public function getDriverTitle() for ($a = 1; $a <= $attempts; $a++) { if ($this->getDriverName() === 'sqlsrv') { - return parent::transaction($callback, $attempts); + return parent::transaction($callback, $attempts, $onFailure); $this->getPdo()->exec('BEGIN TRAN'); @@ -55,6 +56,10 @@ public function transaction(Closure $callback, $attempts = 1) $this->getPdo()->exec('ROLLBACK TRAN'); + if ($a === $attempts && $onFailure !== null) { + $onFailure($e); + } throw $e; diff --git a/tests/Integration/Database/DatabaseTransactionsTest.php b/tests/Integration/Database/DatabaseTransactionsTest.php index 58894d01ae5e..35051f528b20 100644 --- a/tests/Integration/Database/DatabaseTransactionsTest.php +++ b/tests/Integration/Database/DatabaseTransactionsTest.php @@ -105,6 +105,42 @@ public function testTransactionsDoNotAffectDifferentConnections() $this->assertTrue($secondObject->ran); $this->assertFalse($thirdObject->ran); + public function testOnErrorCallbackIsCalled() + DB::transaction(function () { + throw new \Exception; + }, 1, function () use (&$executed) { + public function testOnErrorCallbackIsCalledWithDeadlockRetry() + DB::transaction(function () use (&$attempts) { + $attempts += 1; + throw new \Exception('has been chosen as the deadlock victim'); + }, 3, function () use (&$executed) { + $this->assertSame(3, $attempts); } class TestObjectForTransactions
[ "- protected function handleTransactionException(Throwable $e, $currentAttempt, $maxAttempts)", "+ $onFailure($e);", "+ $attempts = 0;" ]
[ 36, 46, 132 ]
{ "additions": 54, "author": "dshafik", "deletions": 6, "html_url": "https://github.com/laravel/framework/pull/55338", "issue_id": 55338, "merged_at": "2025-04-09T14:14:56Z", "omission_probability": 0.1, "pr_number": 55338, "repo": "laravel/framework", "title": "feat: Add a callback to be called on transaction failure", "total_changes": 60 }
32
diff --git a/src/Illuminate/Console/View/Components/Task.php b/src/Illuminate/Console/View/Components/Task.php index a7dbf62df3c3..fb4ab8d3a517 100644 --- a/src/Illuminate/Console/View/Components/Task.php +++ b/src/Illuminate/Console/View/Components/Task.php @@ -2,7 +2,7 @@ namespace Illuminate\Console\View\Components; -use Illuminate\Database\Migrations\MigrationResult; +use Illuminate\Console\View\TaskResult; use Illuminate\Support\InteractsWithTime; use Symfony\Component\Console\Output\OutputInterface; use Throwable; @@ -35,10 +35,10 @@ public function render($description, $task = null, $verbosity = OutputInterface: $startTime = microtime(true); - $result = MigrationResult::Failure; + $result = TaskResult::Failure->value; try { - $result = ($task ?: fn () => MigrationResult::Success)(); + $result = ($task ?: fn () => TaskResult::Success->value)(); } catch (Throwable $e) { throw $e; } finally { @@ -55,8 +55,8 @@ public function render($description, $task = null, $verbosity = OutputInterface: $this->output->writeln( match ($result) { - MigrationResult::Failure => ' <fg=red;options=bold>FAIL</>', - MigrationResult::Skipped => ' <fg=yellow;options=bold>SKIPPED</>', + TaskResult::Failure->value => ' <fg=red;options=bold>FAIL</>', + TaskResult::Skipped->value => ' <fg=yellow;options=bold>SKIPPED</>', default => ' <fg=green;options=bold>DONE</>' }, $verbosity, diff --git a/src/Illuminate/Console/View/TaskResult.php b/src/Illuminate/Console/View/TaskResult.php new file mode 100644 index 000000000000..13d2afba018d --- /dev/null +++ b/src/Illuminate/Console/View/TaskResult.php @@ -0,0 +1,10 @@ +<?php + +namespace Illuminate\Console\View; + +enum TaskResult: int +{ + case Success = 1; + case Failure = 2; + case Skipped = 3; +} diff --git a/src/Illuminate/Database/Migrations/Migrator.php b/src/Illuminate/Database/Migrations/Migrator.php index 198ee5484791..d50c6d6b2d0d 100755 --- a/src/Illuminate/Database/Migrations/Migrator.php +++ b/src/Illuminate/Database/Migrations/Migrator.php @@ -245,7 +245,7 @@ protected function runUp($file, $batch, $pretend) : true; if (! $shouldRunMigration) { - $this->write(Task::class, $name, fn () => MigrationResult::Skipped); + $this->write(Task::class, $name, fn () => MigrationResult::Skipped->value); } else { $this->write(Task::class, $name, fn () => $this->runMigration($migration, 'up')); diff --git a/tests/Console/View/ComponentsTest.php b/tests/Console/View/ComponentsTest.php index e10ff74a17d1..31958ba6cb8f 100644 --- a/tests/Console/View/ComponentsTest.php +++ b/tests/Console/View/ComponentsTest.php @@ -109,17 +109,17 @@ public function testTask() { $output = new BufferedOutput(); - with(new Components\Task($output))->render('My task', fn () => MigrationResult::Success); + with(new Components\Task($output))->render('My task', fn () => MigrationResult::Success->value); $result = $output->fetch(); $this->assertStringContainsString('My task', $result); $this->assertStringContainsString('DONE', $result); - with(new Components\Task($output))->render('My task', fn () => MigrationResult::Failure); + with(new Components\Task($output))->render('My task', fn () => MigrationResult::Failure->value); $result = $output->fetch(); $this->assertStringContainsString('My task', $result); $this->assertStringContainsString('FAIL', $result); - with(new Components\Task($output))->render('My task', fn () => MigrationResult::Skipped); + with(new Components\Task($output))->render('My task', fn () => MigrationResult::Skipped->value); $result = $output->fetch(); $this->assertStringContainsString('My task', $result); $this->assertStringContainsString('SKIPPED', $result);
diff --git a/src/Illuminate/Console/View/Components/Task.php b/src/Illuminate/Console/View/Components/Task.php index a7dbf62df3c3..fb4ab8d3a517 100644 --- a/src/Illuminate/Console/View/Components/Task.php +++ b/src/Illuminate/Console/View/Components/Task.php @@ -2,7 +2,7 @@ namespace Illuminate\Console\View\Components; -use Illuminate\Database\Migrations\MigrationResult; use Illuminate\Support\InteractsWithTime; use Symfony\Component\Console\Output\OutputInterface; use Throwable; @@ -35,10 +35,10 @@ public function render($description, $task = null, $verbosity = OutputInterface: $startTime = microtime(true); - $result = MigrationResult::Failure; + $result = TaskResult::Failure->value; try { - $result = ($task ?: fn () => MigrationResult::Success)(); + $result = ($task ?: fn () => TaskResult::Success->value)(); } catch (Throwable $e) { throw $e; } finally { @@ -55,8 +55,8 @@ public function render($description, $task = null, $verbosity = OutputInterface: $this->output->writeln( match ($result) { - MigrationResult::Failure => ' <fg=red;options=bold>FAIL</>', - MigrationResult::Skipped => ' <fg=yellow;options=bold>SKIPPED</>', + TaskResult::Failure->value => ' <fg=red;options=bold>FAIL</>', + TaskResult::Skipped->value => ' <fg=yellow;options=bold>SKIPPED</>', default => ' <fg=green;options=bold>DONE</>' }, $verbosity, diff --git a/src/Illuminate/Console/View/TaskResult.php b/src/Illuminate/Console/View/TaskResult.php new file mode 100644 index 000000000000..13d2afba018d --- /dev/null +++ b/src/Illuminate/Console/View/TaskResult.php @@ -0,0 +1,10 @@ +namespace Illuminate\Console\View; +enum TaskResult: int +{ + case Success = 1; + case Failure = 2; + case Skipped = 3; +} diff --git a/src/Illuminate/Database/Migrations/Migrator.php b/src/Illuminate/Database/Migrations/Migrator.php index 198ee5484791..d50c6d6b2d0d 100755 --- a/src/Illuminate/Database/Migrations/Migrator.php +++ b/src/Illuminate/Database/Migrations/Migrator.php @@ -245,7 +245,7 @@ protected function runUp($file, $batch, $pretend) : true; if (! $shouldRunMigration) { - $this->write(Task::class, $name, fn () => MigrationResult::Skipped); + $this->write(Task::class, $name, fn () => MigrationResult::Skipped->value); } else { $this->write(Task::class, $name, fn () => $this->runMigration($migration, 'up')); diff --git a/tests/Console/View/ComponentsTest.php b/tests/Console/View/ComponentsTest.php index e10ff74a17d1..31958ba6cb8f 100644 --- a/tests/Console/View/ComponentsTest.php +++ b/tests/Console/View/ComponentsTest.php @@ -109,17 +109,17 @@ public function testTask() { $output = new BufferedOutput(); - with(new Components\Task($output))->render('My task', fn () => MigrationResult::Success); + with(new Components\Task($output))->render('My task', fn () => MigrationResult::Success->value); $this->assertStringContainsString('DONE', $result); - with(new Components\Task($output))->render('My task', fn () => MigrationResult::Failure); + with(new Components\Task($output))->render('My task', fn () => MigrationResult::Failure->value); $this->assertStringContainsString('FAIL', $result); $this->assertStringContainsString('SKIPPED', $result);
[ "+use Illuminate\\Console\\View\\TaskResult;", "+<?php", "- with(new Components\\Task($output))->render('My task', fn () => MigrationResult::Skipped);", "+ with(new Components\\Task($output))->render('My task', fn () => MigrationResult::Skipped->value);" ]
[ 9, 43, 86, 87 ]
{ "additions": 19, "author": "andrey-helldar", "deletions": 9, "html_url": "https://github.com/laravel/framework/pull/55430", "issue_id": 55430, "merged_at": "2025-04-16T14:44:02Z", "omission_probability": 0.1, "pr_number": 55430, "repo": "laravel/framework", "title": "[12.x] Fixed a bug in using `illuminate/console` in external apps", "total_changes": 28 }
33
diff --git a/.github/workflows/databases.yml b/.github/workflows/databases.yml index 15fcb4c1a463..961af6983a22 100644 --- a/.github/workflows/databases.yml +++ b/.github/workflows/databases.yml @@ -293,53 +293,53 @@ jobs: DB_USERNAME: SA DB_PASSWORD: Forge123 - mssql_2017: - runs-on: ubuntu-20.04 - timeout-minutes: 5 - - services: - sqlsrv: - image: mcr.microsoft.com/mssql/server:2017-latest - env: - ACCEPT_EULA: Y - SA_PASSWORD: Forge123 - ports: - - 1433:1433 - - strategy: - fail-fast: true - - name: SQL Server 2017 - - steps: - - name: Checkout code - uses: actions/checkout@v4 - - - name: Setup PHP - uses: shivammathur/setup-php@v2 - with: - php-version: 8.3 - extensions: dom, curl, libxml, mbstring, zip, pcntl, sqlsrv, pdo, pdo_sqlsrv, odbc, pdo_odbc, :php-psr - tools: composer:v2 - coverage: none - - - name: Set Framework version - run: composer config version "12.x-dev" - - - name: Install dependencies - uses: nick-fields/retry@v3 - with: - timeout_minutes: 5 - max_attempts: 5 - command: composer update --prefer-stable --prefer-dist --no-interaction --no-progress - - - name: Execute tests - run: vendor/bin/phpunit tests/Integration/Database - env: - DB_CONNECTION: sqlsrv - DB_DATABASE: master - DB_USERNAME: SA - DB_PASSWORD: Forge123 + # mssql_2017: + # runs-on: ubuntu-20.04 + # timeout-minutes: 5 + + # services: + # sqlsrv: + # image: mcr.microsoft.com/mssql/server:2017-latest + # env: + # ACCEPT_EULA: Y + # SA_PASSWORD: Forge123 + # ports: + # - 1433:1433 + + # strategy: + # fail-fast: true + + # name: SQL Server 2017 + + # steps: + # - name: Checkout code + # uses: actions/checkout@v4 + + # - name: Setup PHP + # uses: shivammathur/setup-php@v2 + # with: + # php-version: 8.3 + # extensions: dom, curl, libxml, mbstring, zip, pcntl, sqlsrv, pdo, pdo_sqlsrv, odbc, pdo_odbc, :php-psr + # tools: composer:v2 + # coverage: none + + # - name: Set Framework version + # run: composer config version "12.x-dev" + + # - name: Install dependencies + # uses: nick-fields/retry@v3 + # with: + # timeout_minutes: 5 + # max_attempts: 5 + # command: composer update --prefer-stable --prefer-dist --no-interaction --no-progress + + # - name: Execute tests + # run: vendor/bin/phpunit tests/Integration/Database + # env: + # DB_CONNECTION: sqlsrv + # DB_DATABASE: master + # DB_USERNAME: SA + # DB_PASSWORD: Forge123 sqlite: runs-on: ubuntu-24.04
diff --git a/.github/workflows/databases.yml b/.github/workflows/databases.yml index 15fcb4c1a463..961af6983a22 100644 --- a/.github/workflows/databases.yml +++ b/.github/workflows/databases.yml @@ -293,53 +293,53 @@ jobs: DB_USERNAME: SA DB_PASSWORD: Forge123 - mssql_2017: - runs-on: ubuntu-20.04 - timeout-minutes: 5 - sqlsrv: - image: mcr.microsoft.com/mssql/server:2017-latest - ACCEPT_EULA: Y - SA_PASSWORD: Forge123 - ports: - strategy: - fail-fast: true - - name: Checkout code - uses: actions/checkout@v4 - - name: Setup PHP - uses: shivammathur/setup-php@v2 - php-version: 8.3 - extensions: dom, curl, libxml, mbstring, zip, pcntl, sqlsrv, pdo, pdo_sqlsrv, odbc, pdo_odbc, :php-psr - tools: composer:v2 - coverage: none - - name: Set Framework version - run: composer config version "12.x-dev" - - name: Install dependencies - uses: nick-fields/retry@v3 - max_attempts: 5 - command: composer update --prefer-stable --prefer-dist --no-interaction --no-progress - - name: Execute tests - run: vendor/bin/phpunit tests/Integration/Database - DB_CONNECTION: sqlsrv - DB_USERNAME: SA - DB_PASSWORD: Forge123 + # mssql_2017: + # runs-on: ubuntu-20.04 + # timeout-minutes: 5 + # services: + # sqlsrv: + # image: mcr.microsoft.com/mssql/server:2017-latest + # SA_PASSWORD: Forge123 + # ports: + # - 1433:1433 + # strategy: + # fail-fast: true + # name: SQL Server 2017 + # steps: + # - name: Checkout code + # uses: actions/checkout@v4 + # - name: Setup PHP + # uses: shivammathur/setup-php@v2 + # php-version: 8.3 + # extensions: dom, curl, libxml, mbstring, zip, pcntl, sqlsrv, pdo, pdo_sqlsrv, odbc, pdo_odbc, :php-psr + # tools: composer:v2 + # coverage: none + # - name: Set Framework version + # run: composer config version "12.x-dev" + # - name: Install dependencies + # uses: nick-fields/retry@v3 + # timeout_minutes: 5 + # max_attempts: 5 + # command: composer update --prefer-stable --prefer-dist --no-interaction --no-progress + # - name: Execute tests + # run: vendor/bin/phpunit tests/Integration/Database + # DB_CONNECTION: sqlsrv + # DB_DATABASE: master + # DB_USERNAME: SA + # DB_PASSWORD: Forge123 sqlite: runs-on: ubuntu-24.04
[ "- services:", "- - 1433:1433", "- name: SQL Server 2017", "- steps:", "- timeout_minutes: 5", "- DB_DATABASE: master", "+ # ACCEPT_EULA: Y" ]
[ 12, 19, 24, 26, 44, 52, 63 ]
{ "additions": 47, "author": "crynobone", "deletions": 47, "html_url": "https://github.com/laravel/framework/pull/55425", "issue_id": 55425, "merged_at": "2025-04-16T14:45:29Z", "omission_probability": 0.1, "pr_number": 55425, "repo": "laravel/framework", "title": "Disable SQLServer 2017 CI as `ubuntu-20.24` has been removed", "total_changes": 94 }
34
diff --git a/.github/workflows/update-assets.yml b/.github/workflows/update-assets.yml new file mode 100644 index 000000000000..8ecd63efce0a --- /dev/null +++ b/.github/workflows/update-assets.yml @@ -0,0 +1,31 @@ +name: 'update assets' + +on: + push: + branches: + - '12.x' + paths: + - '/src/Illuminate/Foundation/resources/exceptions/renderer/package-lock.json' + workflow_dispatch: + +jobs: + update: + runs-on: ubuntu-latest + + steps: + - name: Checkout Code + uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: 18 + + - name: Update Exception Renderer Assets + run: | + npm ci --prefix "./src/Illuminate/Foundation/resources/exceptions/renderer" + npm run build --prefix "./src/Illuminate/Foundation/resources/exceptions/renderer" + + - name: Commit Compiled Files + uses: stefanzweifel/git-auto-commit-action@v5 + with: + commit_message: Update Assets diff --git a/src/Illuminate/Foundation/resources/exceptions/renderer/dist/styles.css b/src/Illuminate/Foundation/resources/exceptions/renderer/dist/styles.css index 0e5a2eeb8677..f0dc676d1bc4 100644 --- a/src/Illuminate/Foundation/resources/exceptions/renderer/dist/styles.css +++ b/src/Illuminate/Foundation/resources/exceptions/renderer/dist/styles.css @@ -1 +1 @@ -.tippy-box[data-animation=fade][data-state=hidden]{opacity:0}[data-tippy-root]{max-width:calc(100vw - 10px)}.tippy-box{position:relative;background-color:#333;color:#fff;border-radius:4px;font-size:14px;line-height:1.4;white-space:normal;outline:0;transition-property:transform,visibility,opacity}.tippy-box[data-placement^=top]>.tippy-arrow{bottom:0}.tippy-box[data-placement^=top]>.tippy-arrow:before{bottom:-7px;left:0;border-width:8px 8px 0;border-top-color:initial;transform-origin:center top}.tippy-box[data-placement^=bottom]>.tippy-arrow{top:0}.tippy-box[data-placement^=bottom]>.tippy-arrow:before{top:-7px;left:0;border-width:0 8px 8px;border-bottom-color:initial;transform-origin:center bottom}.tippy-box[data-placement^=left]>.tippy-arrow{right:0}.tippy-box[data-placement^=left]>.tippy-arrow:before{border-width:8px 0 8px 8px;border-left-color:initial;right:-7px;transform-origin:center left}.tippy-box[data-placement^=right]>.tippy-arrow{left:0}.tippy-box[data-placement^=right]>.tippy-arrow:before{left:-7px;border-width:8px 8px 8px 0;border-right-color:initial;transform-origin:center right}.tippy-box[data-inertia][data-state=visible]{transition-timing-function:cubic-bezier(.54,1.5,.38,1.11)}.tippy-arrow{width:16px;height:16px;color:#333}.tippy-arrow:before{content:"";position:absolute;border-color:transparent;border-style:solid}.tippy-content{position:relative;padding:5px 9px;z-index:1}.tippy-box[data-theme~=material]{background-color:#505355;font-weight:600}.tippy-box[data-theme~=material][data-placement^=top]>.tippy-arrow:before{border-top-color:#505355}.tippy-box[data-theme~=material][data-placement^=bottom]>.tippy-arrow:before{border-bottom-color:#505355}.tippy-box[data-theme~=material][data-placement^=left]>.tippy-arrow:before{border-left-color:#505355}.tippy-box[data-theme~=material][data-placement^=right]>.tippy-arrow:before{border-right-color:#505355}.tippy-box[data-theme~=material]>.tippy-backdrop{background-color:#505355}.tippy-box[data-theme~=material]>.tippy-svg-arrow{fill:#505355}.tippy-box[data-animation=scale][data-placement^=top]{transform-origin:bottom}.tippy-box[data-animation=scale][data-placement^=bottom]{transform-origin:top}.tippy-box[data-animation=scale][data-placement^=left]{transform-origin:right}.tippy-box[data-animation=scale][data-placement^=right]{transform-origin:left}.tippy-box[data-animation=scale][data-state=hidden]{transform:scale(.5);opacity:0}*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:Figtree,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]{display:none}*,:before,:after{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgb(59 130 246 / .5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgb(59 130 246 / .5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }.container{width:100%}@media (min-width: 640px){.container{max-width:640px}}@media (min-width: 768px){.container{max-width:768px}}@media (min-width: 1024px){.container{max-width:1024px}}@media (min-width: 1280px){.container{max-width:1280px}}@media (min-width: 1536px){.container{max-width:1536px}}.absolute{position:absolute}.relative{position:relative}.right-0{right:0}.z-10{z-index:10}.mx-5{margin-left:1.25rem;margin-right:1.25rem}.mx-auto{margin-left:auto;margin-right:auto}.my-3{margin-top:.75rem;margin-bottom:.75rem}.-mt-2{margin-top:-.5rem}.mb-12{margin-bottom:3rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.ml-1{margin-left:.25rem}.ml-3{margin-left:.75rem}.mt-1{margin-top:.25rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-6{margin-top:1.5rem}.block{display:block}.inline-block{display:inline-block}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.hidden{display:none}.h-4{height:1rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-\[32\.5rem\]{height:32.5rem}.h-\[35\.5rem\]{height:35.5rem}.max-h-32{max-height:8rem}.w-4{width:1rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-\[8rem\]{width:8rem}.w-full{width:100%}.min-w-0{min-width:0px}.max-w-full{max-width:100%}.flex-none{flex:none}.shrink-0{flex-shrink:0}.flex-grow{flex-grow:1}.origin-top-right{transform-origin:top right}.cursor-pointer{cursor:pointer}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.flex-col{flex-direction:column}.items-center{align-items:center}.items-baseline{align-items:baseline}.justify-between{justify-content:space-between}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-6{gap:1.5rem}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.overflow-x-auto{overflow-x:auto}.overflow-y-hidden{overflow-y:hidden}.overflow-x-scroll{overflow-x:scroll}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.break-words{overflow-wrap:break-word}.rounded{border-radius:.25rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.rounded-r-md{border-top-right-radius:.375rem;border-bottom-right-radius:.375rem}.border{border-width:1px}.border-l{border-left-width:1px}.border-l-2{border-left-width:2px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-transparent{border-color:transparent}.border-l-red-500{--tw-border-opacity:1;border-left-color:rgb(239 68 68 / var(--tw-border-opacity))}.bg-gray-100{--tw-bg-opacity:1;background-color:rgb(243 244 246 / var(--tw-bg-opacity))}.bg-gray-200{--tw-bg-opacity:1;background-color:rgb(229 231 235 / var(--tw-bg-opacity))}.bg-gray-200\/80{background-color:#e5e7ebcc}.bg-red-500\/20{background-color:#ef444433}.bg-white{--tw-bg-opacity:1;background-color:rgb(255 255 255 / var(--tw-bg-opacity))}.fill-red-500{fill:#ef4444}.p-1{padding:.25rem}.p-2{padding:.5rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.pb-12{padding-bottom:3rem}.pt-4{padding-top:1rem}.pt-6{padding-top:1.5rem}.text-left{text-align:left}.text-right{text-align:right}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.font-sans{font-family:Figtree,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji"}.text-2xl{font-size:1.5rem;line-height:2rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-semibold{font-weight:600}.leading-5{line-height:1.25rem}.text-blue-500{--tw-text-opacity:1;color:rgb(59 130 246 / var(--tw-text-opacity))}.text-gray-400{--tw-text-opacity:1;color:rgb(156 163 175 / var(--tw-text-opacity))}.text-gray-50{--tw-text-opacity:1;color:rgb(249 250 251 / var(--tw-text-opacity))}.text-gray-500{--tw-text-opacity:1;color:rgb(107 114 128 / var(--tw-text-opacity))}.text-gray-700{--tw-text-opacity:1;color:rgb(55 65 81 / var(--tw-text-opacity))}.text-gray-900{--tw-text-opacity:1;color:rgb(17 24 39 / var(--tw-text-opacity))}.text-red-500{--tw-text-opacity:1;color:rgb(239 68 68 / var(--tw-text-opacity))}.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.shadow-xl{--tw-shadow:0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored:0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.ring-1{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-gray-900\/5{--tw-ring-color:rgb(17 24 39 / .05)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}[x-cloak]{display:none}html{-moz-tab-size:4;-o-tab-size:4;tab-size:4}table.hljs-ln{color:inherit;font-size:inherit;border-spacing:2px}pre code.hljs{background:none;padding:.5em 0 0;width:100%}.hljs-ln-line{white-space-collapse:preserve;text-wrap:nowrap}.trace{-webkit-mask-image:linear-gradient(180deg,#000 calc(100% - 4rem),transparent)}.scrollbar-hidden{-ms-overflow-style:none;scrollbar-width:none;overflow-x:scroll}.scrollbar-hidden::-webkit-scrollbar{-webkit-appearance:none;width:0;height:0}.hljs-ln .hljs-ln-numbers{padding:5px;border-right-color:transparent;margin-right:5px}.hljs-ln-n{width:50px}.hljs-ln-numbers{-webkit-touch-callout:none;-webkit-user-select:none;-moz-user-select:none;user-select:none;text-align:center;border-right:1px solid #ccc;vertical-align:top;padding-right:5px}.hljs-ln-code{width:100%;padding-left:10px;padding-right:10px}.hljs-ln-code:hover{background-color:#ef444433}.default\:col-span-full:default{grid-column:1 / -1}.default\:row-span-1:default{grid-row:span 1 / span 1}.hover\:bg-gray-100:hover{--tw-bg-opacity:1;background-color:rgb(243 244 246 / var(--tw-bg-opacity))}.hover\:bg-gray-100\/75:hover{background-color:#f3f4f6bf}.hover\:text-gray-500:hover{--tw-text-opacity:1;color:rgb(107 114 128 / var(--tw-text-opacity))}.hover\:underline:hover{text-decoration-line:underline}.focus\:text-gray-500:focus{--tw-text-opacity:1;color:rgb(107 114 128 / var(--tw-text-opacity))}.dark\:block:is(.dark *){display:block}.dark\:hidden:is(.dark *){display:none}.dark\:border:is(.dark *){border-width:1px}.dark\:border-gray-700:is(.dark *){--tw-border-opacity:1;border-color:rgb(55 65 81 / var(--tw-border-opacity))}.dark\:border-gray-800:is(.dark *){--tw-border-opacity:1;border-color:rgb(31 41 55 / var(--tw-border-opacity))}.dark\:border-gray-900:is(.dark *){--tw-border-opacity:1;border-color:rgb(17 24 39 / var(--tw-border-opacity))}.dark\:border-l-red-500:is(.dark *){--tw-border-opacity:1;border-left-color:rgb(239 68 68 / var(--tw-border-opacity))}.dark\:bg-gray-800:is(.dark *){--tw-bg-opacity:1;background-color:rgb(31 41 55 / var(--tw-bg-opacity))}.dark\:bg-gray-900\/80:is(.dark *){background-color:#111827cc}.dark\:bg-gray-950\/95:is(.dark *){background-color:#030712f2}.dark\:bg-red-500\/20:is(.dark *){background-color:#ef444433}.dark\:text-gray-100:is(.dark *){--tw-text-opacity:1;color:rgb(243 244 246 / var(--tw-text-opacity))}.dark\:text-gray-300:is(.dark *){--tw-text-opacity:1;color:rgb(209 213 219 / var(--tw-text-opacity))}.dark\:text-gray-400:is(.dark *){--tw-text-opacity:1;color:rgb(156 163 175 / var(--tw-text-opacity))}.dark\:text-gray-600:is(.dark *){--tw-text-opacity:1;color:rgb(75 85 99 / var(--tw-text-opacity))}.dark\:text-gray-950:is(.dark *){--tw-text-opacity:1;color:rgb(3 7 18 / var(--tw-text-opacity))}.dark\:text-white:is(.dark *){--tw-text-opacity:1;color:rgb(255 255 255 / var(--tw-text-opacity))}.dark\:ring-1:is(.dark *){--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.dark\:ring-gray-800:is(.dark *){--tw-ring-opacity:1;--tw-ring-color:rgb(31 41 55 / var(--tw-ring-opacity))}.dark\:hover\:bg-gray-700:hover:is(.dark *){--tw-bg-opacity:1;background-color:rgb(55 65 81 / var(--tw-bg-opacity))}.dark\:hover\:bg-gray-800:hover:is(.dark *){--tw-bg-opacity:1;background-color:rgb(31 41 55 / var(--tw-bg-opacity))}.dark\:hover\:bg-gray-800\/75:hover:is(.dark *){background-color:#1f2937bf}.dark\:hover\:text-gray-500:hover:is(.dark *){--tw-text-opacity:1;color:rgb(107 114 128 / var(--tw-text-opacity))}.dark\:focus\:text-gray-500:focus:is(.dark *){--tw-text-opacity:1;color:rgb(107 114 128 / var(--tw-text-opacity))}@media (min-width: 640px){.sm\:col-span-1{grid-column:span 1 / span 1}.sm\:col-span-2{grid-column:span 2 / span 2}.sm\:mt-10{margin-top:2.5rem}.sm\:gap-6{gap:1.5rem}.sm\:p-12{padding:3rem}.sm\:py-5{padding-top:1.25rem;padding-bottom:1.25rem}.sm\:text-3xl{font-size:1.875rem;line-height:2.25rem}}@media (min-width: 768px){.md\:block{display:block}.md\:inline{display:inline}.md\:flex{display:flex}.md\:hidden{display:none}.md\:min-w-64{min-width:16rem}.md\:max-w-80{max-width:20rem}.md\:items-center{align-items:center}.md\:justify-between{justify-content:space-between}.md\:gap-2{gap:.5rem}}@media (min-width: 1024px){.lg\:block{display:block}.lg\:inline-block{display:inline-block}.lg\:w-\[12rem\]{width:12rem}.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:px-8{padding-left:2rem;padding-right:2rem}.lg\:text-2xl{font-size:1.5rem;line-height:2rem}.lg\:text-base{font-size:1rem;line-height:1.5rem}.lg\:text-sm{font-size:.875rem;line-height:1.25rem}.default\:lg\:col-span-6:default{grid-column:span 6 / span 6}} +.tippy-box[data-animation=fade][data-state=hidden]{opacity:0}[data-tippy-root]{max-width:calc(100vw - 10px)}.tippy-box{position:relative;background-color:#333;color:#fff;border-radius:4px;font-size:14px;line-height:1.4;white-space:normal;outline:0;transition-property:transform,visibility,opacity}.tippy-box[data-placement^=top]>.tippy-arrow{bottom:0}.tippy-box[data-placement^=top]>.tippy-arrow:before{bottom:-7px;left:0;border-width:8px 8px 0;border-top-color:initial;transform-origin:center top}.tippy-box[data-placement^=bottom]>.tippy-arrow{top:0}.tippy-box[data-placement^=bottom]>.tippy-arrow:before{top:-7px;left:0;border-width:0 8px 8px;border-bottom-color:initial;transform-origin:center bottom}.tippy-box[data-placement^=left]>.tippy-arrow{right:0}.tippy-box[data-placement^=left]>.tippy-arrow:before{border-width:8px 0 8px 8px;border-left-color:initial;right:-7px;transform-origin:center left}.tippy-box[data-placement^=right]>.tippy-arrow{left:0}.tippy-box[data-placement^=right]>.tippy-arrow:before{left:-7px;border-width:8px 8px 8px 0;border-right-color:initial;transform-origin:center right}.tippy-box[data-inertia][data-state=visible]{transition-timing-function:cubic-bezier(.54,1.5,.38,1.11)}.tippy-arrow{width:16px;height:16px;color:#333}.tippy-arrow:before{content:"";position:absolute;border-color:transparent;border-style:solid}.tippy-content{position:relative;padding:5px 9px;z-index:1}.tippy-box[data-theme~=material]{background-color:#505355;font-weight:600}.tippy-box[data-theme~=material][data-placement^=top]>.tippy-arrow:before{border-top-color:#505355}.tippy-box[data-theme~=material][data-placement^=bottom]>.tippy-arrow:before{border-bottom-color:#505355}.tippy-box[data-theme~=material][data-placement^=left]>.tippy-arrow:before{border-left-color:#505355}.tippy-box[data-theme~=material][data-placement^=right]>.tippy-arrow:before{border-right-color:#505355}.tippy-box[data-theme~=material]>.tippy-backdrop{background-color:#505355}.tippy-box[data-theme~=material]>.tippy-svg-arrow{fill:#505355}.tippy-box[data-animation=scale][data-placement^=top]{transform-origin:bottom}.tippy-box[data-animation=scale][data-placement^=bottom]{transform-origin:top}.tippy-box[data-animation=scale][data-placement^=left]{transform-origin:right}.tippy-box[data-animation=scale][data-placement^=right]{transform-origin:left}.tippy-box[data-animation=scale][data-state=hidden]{transform:scale(.5);opacity:0}*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:Figtree,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]{display:none}*,:before,:after{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgb(59 130 246 / .5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgb(59 130 246 / .5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }.container{width:100%}@media (min-width: 640px){.container{max-width:640px}}@media (min-width: 768px){.container{max-width:768px}}@media (min-width: 1024px){.container{max-width:1024px}}@media (min-width: 1280px){.container{max-width:1280px}}@media (min-width: 1536px){.container{max-width:1536px}}.absolute{position:absolute}.relative{position:relative}.right-0{right:0}.z-10{z-index:10}.mx-5{margin-left:1.25rem;margin-right:1.25rem}.mx-auto{margin-left:auto;margin-right:auto}.my-3{margin-top:.75rem;margin-bottom:.75rem}.-mt-2{margin-top:-.5rem}.mb-12{margin-bottom:3rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.ml-1{margin-left:.25rem}.ml-3{margin-left:.75rem}.mt-1{margin-top:.25rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-6{margin-top:1.5rem}.block{display:block}.inline-block{display:inline-block}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.hidden{display:none}.h-4{height:1rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-\[32\.5rem\]{height:32.5rem}.h-\[35\.5rem\]{height:35.5rem}.max-h-32{max-height:8rem}.w-4{width:1rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-\[8rem\]{width:8rem}.w-full{width:100%}.min-w-0{min-width:0px}.max-w-full{max-width:100%}.flex-none{flex:none}.shrink-0{flex-shrink:0}.flex-grow{flex-grow:1}.origin-top-right{transform-origin:top right}.cursor-pointer{cursor:pointer}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.flex-col{flex-direction:column}.items-center{align-items:center}.items-baseline{align-items:baseline}.justify-between{justify-content:space-between}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-6{gap:1.5rem}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.overflow-x-auto{overflow-x:auto}.overflow-y-hidden{overflow-y:hidden}.overflow-x-scroll{overflow-x:scroll}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.break-words{overflow-wrap:break-word}.rounded{border-radius:.25rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.rounded-r-md{border-top-right-radius:.375rem;border-bottom-right-radius:.375rem}.border{border-width:1px}.border-l{border-left-width:1px}.border-l-2{border-left-width:2px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-transparent{border-color:transparent}.border-l-red-500{--tw-border-opacity:1;border-left-color:rgb(239 68 68 / var(--tw-border-opacity))}.bg-gray-100{--tw-bg-opacity:1;background-color:rgb(243 244 246 / var(--tw-bg-opacity))}.bg-gray-200{--tw-bg-opacity:1;background-color:rgb(229 231 235 / var(--tw-bg-opacity))}.bg-gray-200\/80{background-color:#e5e7ebcc}.bg-red-500\/20{background-color:#ef444433}.bg-white{--tw-bg-opacity:1;background-color:rgb(255 255 255 / var(--tw-bg-opacity))}.fill-red-500{fill:#ef4444}.p-1{padding:.25rem}.p-2{padding:.5rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.pb-12{padding-bottom:3rem}.pt-4{padding-top:1rem}.pt-6{padding-top:1.5rem}.text-left{text-align:left}.text-right{text-align:right}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.font-sans{font-family:Figtree,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji"}.text-2xl{font-size:1.5rem;line-height:2rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-semibold{font-weight:600}.leading-5{line-height:1.25rem}.text-blue-500{--tw-text-opacity:1;color:rgb(59 130 246 / var(--tw-text-opacity))}.text-gray-400{--tw-text-opacity:1;color:rgb(156 163 175 / var(--tw-text-opacity))}.text-gray-50{--tw-text-opacity:1;color:rgb(249 250 251 / var(--tw-text-opacity))}.text-gray-500{--tw-text-opacity:1;color:rgb(107 114 128 / var(--tw-text-opacity))}.text-gray-700{--tw-text-opacity:1;color:rgb(55 65 81 / var(--tw-text-opacity))}.text-gray-900{--tw-text-opacity:1;color:rgb(17 24 39 / var(--tw-text-opacity))}.text-red-500{--tw-text-opacity:1;color:rgb(239 68 68 / var(--tw-text-opacity))}.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.shadow-xl{--tw-shadow:0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored:0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.ring-1{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-gray-900\/5{--tw-ring-color:rgb(17 24 39 / .05)}[x-cloak]{display:none}html{-moz-tab-size:4;-o-tab-size:4;tab-size:4}table.hljs-ln{color:inherit;font-size:inherit;border-spacing:2px}pre code.hljs{background:none;padding:.5em 0 0;width:100%}.hljs-ln-line{white-space-collapse:preserve;text-wrap:nowrap}.trace{-webkit-mask-image:linear-gradient(180deg,#000 calc(100% - 4rem),transparent)}.scrollbar-hidden{-ms-overflow-style:none;scrollbar-width:none;overflow-x:scroll}.scrollbar-hidden::-webkit-scrollbar{-webkit-appearance:none;width:0;height:0}.hljs-ln .hljs-ln-numbers{padding:5px;border-right-color:transparent;margin-right:5px}.hljs-ln-n{width:50px}.hljs-ln-numbers{-webkit-touch-callout:none;-webkit-user-select:none;-moz-user-select:none;user-select:none;text-align:center;border-right:1px solid #ccc;vertical-align:top;padding-right:5px}.hljs-ln-code{width:100%;padding-left:10px;padding-right:10px}.hljs-ln-code:hover{background-color:#ef444433}.default\:col-span-full:default{grid-column:1 / -1}.default\:row-span-1:default{grid-row:span 1 / span 1}.hover\:rounded-b-md:hover{border-bottom-right-radius:.375rem;border-bottom-left-radius:.375rem}.hover\:rounded-t-md:hover{border-top-left-radius:.375rem;border-top-right-radius:.375rem}.hover\:bg-gray-100:hover{--tw-bg-opacity:1;background-color:rgb(243 244 246 / var(--tw-bg-opacity))}.hover\:bg-gray-100\/75:hover{background-color:#f3f4f6bf}.hover\:text-gray-500:hover{--tw-text-opacity:1;color:rgb(107 114 128 / var(--tw-text-opacity))}.hover\:underline:hover{text-decoration-line:underline}.focus\:text-gray-500:focus{--tw-text-opacity:1;color:rgb(107 114 128 / var(--tw-text-opacity))}.dark\:block:is(.dark *){display:block}.dark\:hidden:is(.dark *){display:none}.dark\:border:is(.dark *){border-width:1px}.dark\:border-gray-700:is(.dark *){--tw-border-opacity:1;border-color:rgb(55 65 81 / var(--tw-border-opacity))}.dark\:border-gray-800:is(.dark *){--tw-border-opacity:1;border-color:rgb(31 41 55 / var(--tw-border-opacity))}.dark\:border-gray-900:is(.dark *){--tw-border-opacity:1;border-color:rgb(17 24 39 / var(--tw-border-opacity))}.dark\:border-l-red-500:is(.dark *){--tw-border-opacity:1;border-left-color:rgb(239 68 68 / var(--tw-border-opacity))}.dark\:bg-gray-800:is(.dark *){--tw-bg-opacity:1;background-color:rgb(31 41 55 / var(--tw-bg-opacity))}.dark\:bg-gray-900\/80:is(.dark *){background-color:#111827cc}.dark\:bg-gray-950\/95:is(.dark *){background-color:#030712f2}.dark\:bg-red-500\/20:is(.dark *){background-color:#ef444433}.dark\:text-gray-100:is(.dark *){--tw-text-opacity:1;color:rgb(243 244 246 / var(--tw-text-opacity))}.dark\:text-gray-300:is(.dark *){--tw-text-opacity:1;color:rgb(209 213 219 / var(--tw-text-opacity))}.dark\:text-gray-400:is(.dark *){--tw-text-opacity:1;color:rgb(156 163 175 / var(--tw-text-opacity))}.dark\:text-gray-600:is(.dark *){--tw-text-opacity:1;color:rgb(75 85 99 / var(--tw-text-opacity))}.dark\:text-gray-950:is(.dark *){--tw-text-opacity:1;color:rgb(3 7 18 / var(--tw-text-opacity))}.dark\:text-white:is(.dark *){--tw-text-opacity:1;color:rgb(255 255 255 / var(--tw-text-opacity))}.dark\:ring-1:is(.dark *){--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.dark\:ring-gray-800:is(.dark *){--tw-ring-opacity:1;--tw-ring-color:rgb(31 41 55 / var(--tw-ring-opacity))}.dark\:hover\:bg-gray-700:hover:is(.dark *){--tw-bg-opacity:1;background-color:rgb(55 65 81 / var(--tw-bg-opacity))}.dark\:hover\:bg-gray-800:hover:is(.dark *){--tw-bg-opacity:1;background-color:rgb(31 41 55 / var(--tw-bg-opacity))}.dark\:hover\:bg-gray-800\/75:hover:is(.dark *){background-color:#1f2937bf}.dark\:hover\:text-gray-500:hover:is(.dark *){--tw-text-opacity:1;color:rgb(107 114 128 / var(--tw-text-opacity))}.dark\:focus\:text-gray-500:focus:is(.dark *){--tw-text-opacity:1;color:rgb(107 114 128 / var(--tw-text-opacity))}@media (min-width: 640px){.sm\:col-span-1{grid-column:span 1 / span 1}.sm\:col-span-2{grid-column:span 2 / span 2}.sm\:mt-10{margin-top:2.5rem}.sm\:gap-6{gap:1.5rem}.sm\:p-12{padding:3rem}.sm\:py-5{padding-top:1.25rem;padding-bottom:1.25rem}.sm\:text-3xl{font-size:1.875rem;line-height:2.25rem}}@media (min-width: 768px){.md\:block{display:block}.md\:inline{display:inline}.md\:flex{display:flex}.md\:hidden{display:none}.md\:min-w-64{min-width:16rem}.md\:max-w-80{max-width:20rem}.md\:items-center{align-items:center}.md\:justify-between{justify-content:space-between}.md\:gap-2{gap:.5rem}}@media (min-width: 1024px){.lg\:block{display:block}.lg\:inline-block{display:inline-block}.lg\:w-\[12rem\]{width:12rem}.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:px-8{padding-left:2rem;padding-right:2rem}.lg\:text-2xl{font-size:1.5rem;line-height:2rem}.lg\:text-base{font-size:1rem;line-height:1.5rem}.lg\:text-sm{font-size:.875rem;line-height:1.25rem}.default\:lg\:col-span-6:default{grid-column:span 6 / span 6}}
diff --git a/.github/workflows/update-assets.yml b/.github/workflows/update-assets.yml new file mode 100644 index 000000000000..8ecd63efce0a --- /dev/null +++ b/.github/workflows/update-assets.yml @@ -0,0 +1,31 @@ +on: + push: + branches: + - '12.x' + paths: + - '/src/Illuminate/Foundation/resources/exceptions/renderer/package-lock.json' + workflow_dispatch: +jobs: + update: + steps: + - name: Checkout Code + - uses: actions/setup-node@v4 + node-version: 18 + - name: Update Exception Renderer Assets + run: | + npm ci --prefix "./src/Illuminate/Foundation/resources/exceptions/renderer" + npm run build --prefix "./src/Illuminate/Foundation/resources/exceptions/renderer" + - name: Commit Compiled Files + uses: stefanzweifel/git-auto-commit-action@v5 + commit_message: Update Assets diff --git a/src/Illuminate/Foundation/resources/exceptions/renderer/dist/styles.css b/src/Illuminate/Foundation/resources/exceptions/renderer/dist/styles.css index 0e5a2eeb8677..f0dc676d1bc4 100644 --- a/src/Illuminate/Foundation/resources/exceptions/renderer/dist/styles.css +++ b/src/Illuminate/Foundation/resources/exceptions/renderer/dist/styles.css @@ -1 +1 @@ -.tippy-box[data-animation=fade][data-state=hidden]{opacity:0}[data-tippy-root]{max-width:calc(100vw - 10px)}.tippy-box{position:relative;background-color:#333;color:#fff;border-radius:4px;font-size:14px;line-height:1.4;white-space:normal;outline:0;transition-property:transform,visibility,opacity}.tippy-box[data-placement^=top]>.tippy-arrow{bottom:0}.tippy-box[data-placement^=top]>.tippy-arrow:before{bottom:-7px;left:0;border-width:8px 8px 0;border-top-color:initial;transform-origin:center top}.tippy-box[data-placement^=bottom]>.tippy-arrow{top:0}.tippy-box[data-placement^=bottom]>.tippy-arrow:before{top:-7px;left:0;border-width:0 8px 8px;border-bottom-color:initial;transform-origin:center bottom}.tippy-box[data-placement^=left]>.tippy-arrow{right:0}.tippy-box[data-placement^=left]>.tippy-arrow:before{border-width:8px 0 8px 8px;border-left-color:initial;right:-7px;transform-origin:center left}.tippy-box[data-placement^=right]>.tippy-arrow{left:0}.tippy-box[data-placement^=right]>.tippy-arrow:before{left:-7px;border-width:8px 8px 8px 0;border-right-color:initial;transform-origin:center right}.tippy-box[data-inertia][data-state=visible]{transition-timing-function:cubic-bezier(.54,1.5,.38,1.11)}.tippy-arrow{width:16px;height:16px;color:#333}.tippy-arrow:before{content:"";position:absolute;border-color:transparent;border-style:solid}.tippy-content{position:relative;padding:5px 9px;z-index:1}.tippy-box[data-theme~=material]{background-color:#505355;font-weight:600}.tippy-box[data-theme~=material][data-placement^=top]>.tippy-arrow:before{border-top-color:#505355}.tippy-box[data-theme~=material][data-placement^=bottom]>.tippy-arrow:before{border-bottom-color:#505355}.tippy-box[data-theme~=material][data-placement^=left]>.tippy-arrow:before{border-left-color:#505355}.tippy-box[data-theme~=material][data-placement^=right]>.tippy-arrow:before{border-right-color:#505355}.tippy-box[data-theme~=material]>.tippy-backdrop{background-color:#505355}.tippy-box[data-theme~=material]>.tippy-svg-arrow{fill:#505355}.tippy-box[data-animation=scale][data-placement^=top]{transform-origin:bottom}.tippy-box[data-animation=scale][data-placement^=bottom]{transform-origin:top}.tippy-box[data-animation=scale][data-placement^=left]{transform-origin:right}.tippy-box[data-animation=scale][data-placement^=right]{transform-origin:left}.tippy-box[data-animation=scale][data-state=hidden]{transform:scale(.5);opacity:0}*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:Figtree,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]{display:none}*,:before,:after{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgb(59 130 246 / .5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgb(59 130 246 / .5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }.container{width:100%}@media (min-width: 640px){.container{max-width:640px}}@media (min-width: 768px){.container{max-width:768px}}@media (min-width: 1024px){.container{max-width:1024px}}@media (min-width: 1280px){.container{max-width:1280px}}@media (min-width: 1536px){.container{max-width:1536px}}.absolute{position:absolute}.relative{position:relative}.right-0{right:0}.z-10{z-index:10}.mx-5{margin-left:1.25rem;margin-right:1.25rem}.mx-auto{margin-left:auto;margin-right:auto}.my-3{margin-top:.75rem;margin-bottom:.75rem}.-mt-2{margin-top:-.5rem}.mb-12{margin-bottom:3rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.ml-1{margin-left:.25rem}.ml-3{margin-left:.75rem}.mt-1{margin-top:.25rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-6{margin-top:1.5rem}.block{display:block}.inline-block{display:inline-block}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.hidden{display:none}.h-4{height:1rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-\[32\.5rem\]{height:32.5rem}.h-\[35\.5rem\]{height:35.5rem}.max-h-32{max-height:8rem}.w-4{width:1rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-\[8rem\]{width:8rem}.w-full{width:100%}.min-w-0{min-width:0px}.max-w-full{max-width:100%}.flex-none{flex:none}.shrink-0{flex-shrink:0}.flex-grow{flex-grow:1}.origin-top-right{transform-origin:top right}.cursor-pointer{cursor:pointer}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.flex-col{flex-direction:column}.items-center{align-items:center}.items-baseline{align-items:baseline}.justify-between{justify-content:space-between}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-6{gap:1.5rem}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.overflow-x-auto{overflow-x:auto}.overflow-y-hidden{overflow-y:hidden}.overflow-x-scroll{overflow-x:scroll}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.break-words{overflow-wrap:break-word}.rounded{border-radius:.25rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.rounded-r-md{border-top-right-radius:.375rem;border-bottom-right-radius:.375rem}.border{border-width:1px}.border-l{border-left-width:1px}.border-l-2{border-left-width:2px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-transparent{border-color:transparent}.border-l-red-500{--tw-border-opacity:1;border-left-color:rgb(239 68 68 / var(--tw-border-opacity))}.bg-gray-100{--tw-bg-opacity:1;background-color:rgb(243 244 246 / var(--tw-bg-opacity))}.bg-gray-200{--tw-bg-opacity:1;background-color:rgb(229 231 235 / var(--tw-bg-opacity))}.bg-gray-200\/80{background-color:#e5e7ebcc}.bg-red-500\/20{background-color:#ef444433}.bg-white{--tw-bg-opacity:1;background-color:rgb(255 255 255 / var(--tw-bg-opacity))}.fill-red-500{fill:#ef4444}.p-1{padding:.25rem}.p-2{padding:.5rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.pb-12{padding-bottom:3rem}.pt-4{padding-top:1rem}.pt-6{padding-top:1.5rem}.text-left{text-align:left}.text-right{text-align:right}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.font-sans{font-family:Figtree,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji"}.text-2xl{font-size:1.5rem;line-height:2rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-semibold{font-weight:600}.leading-5{line-height:1.25rem}.text-blue-500{--tw-text-opacity:1;color:rgb(59 130 246 / var(--tw-text-opacity))}.text-gray-400{--tw-text-opacity:1;color:rgb(156 163 175 / var(--tw-text-opacity))}.text-gray-50{--tw-text-opacity:1;color:rgb(249 250 251 / var(--tw-text-opacity))}.text-gray-500{--tw-text-opacity:1;color:rgb(107 114 128 / var(--tw-text-opacity))}.text-gray-700{--tw-text-opacity:1;color:rgb(55 65 81 / var(--tw-text-opacity))}.text-gray-900{--tw-text-opacity:1;color:rgb(17 24 39 / var(--tw-text-opacity))}.text-red-500{--tw-text-opacity:1;color:rgb(239 68 68 / var(--tw-text-opacity))}.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.shadow-xl{--tw-shadow:0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored:0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.ring-1{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-gray-900\/5{--tw-ring-color:rgb(17 24 39 / .05)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}[x-cloak]{display:none}html{-moz-tab-size:4;-o-tab-size:4;tab-size:4}table.hljs-ln{color:inherit;font-size:inherit;border-spacing:2px}pre code.hljs{background:none;padding:.5em 0 0;width:100%}.hljs-ln-line{white-space-collapse:preserve;text-wrap:nowrap}.trace{-webkit-mask-image:linear-gradient(180deg,#000 calc(100% - 4rem),transparent)}.scrollbar-hidden{-ms-overflow-style:none;scrollbar-width:none;overflow-x:scroll}.scrollbar-hidden::-webkit-scrollbar{-webkit-appearance:none;width:0;height:0}.hljs-ln .hljs-ln-numbers{padding:5px;border-right-color:transparent;margin-right:5px}.hljs-ln-n{width:50px}.hljs-ln-numbers{-webkit-touch-callout:none;-webkit-user-select:none;-moz-user-select:none;user-select:none;text-align:center;border-right:1px solid #ccc;vertical-align:top;padding-right:5px}.hljs-ln-code{width:100%;padding-left:10px;padding-right:10px}.hljs-ln-code:hover{background-color:#ef444433}.default\:col-span-full:default{grid-column:1 / -1}.default\:row-span-1:default{grid-row:span 1 / span 1}.hover\:bg-gray-100:hover{--tw-bg-opacity:1;background-color:rgb(243 244 246 / var(--tw-bg-opacity))}.hover\:bg-gray-100\/75:hover{background-color:#f3f4f6bf}.hover\:text-gray-500:hover{--tw-text-opacity:1;color:rgb(107 114 128 / var(--tw-text-opacity))}.hover\:underline:hover{text-decoration-line:underline}.focus\:text-gray-500:focus{--tw-text-opacity:1;color:rgb(107 114 128 / var(--tw-text-opacity))}.dark\:block:is(.dark *){display:block}.dark\:hidden:is(.dark *){display:none}.dark\:border:is(.dark *){border-width:1px}.dark\:border-gray-700:is(.dark *){--tw-border-opacity:1;border-color:rgb(55 65 81 / var(--tw-border-opacity))}.dark\:border-gray-800:is(.dark *){--tw-border-opacity:1;border-color:rgb(31 41 55 / var(--tw-border-opacity))}.dark\:border-gray-900:is(.dark *){--tw-border-opacity:1;border-color:rgb(17 24 39 / var(--tw-border-opacity))}.dark\:border-l-red-500:is(.dark *){--tw-border-opacity:1;border-left-color:rgb(239 68 68 / var(--tw-border-opacity))}.dark\:bg-gray-800:is(.dark *){--tw-bg-opacity:1;background-color:rgb(31 41 55 / var(--tw-bg-opacity))}.dark\:bg-gray-900\/80:is(.dark *){background-color:#111827cc}.dark\:bg-gray-950\/95:is(.dark *){background-color:#030712f2}.dark\:bg-red-500\/20:is(.dark *){background-color:#ef444433}.dark\:text-gray-100:is(.dark *){--tw-text-opacity:1;color:rgb(243 244 246 / var(--tw-text-opacity))}.dark\:text-gray-300:is(.dark *){--tw-text-opacity:1;color:rgb(209 213 219 / var(--tw-text-opacity))}.dark\:text-gray-400:is(.dark *){--tw-text-opacity:1;color:rgb(156 163 175 / var(--tw-text-opacity))}.dark\:text-gray-600:is(.dark *){--tw-text-opacity:1;color:rgb(75 85 99 / var(--tw-text-opacity))}.dark\:text-gray-950:is(.dark *){--tw-text-opacity:1;color:rgb(3 7 18 / var(--tw-text-opacity))}.dark\:text-white:is(.dark *){--tw-text-opacity:1;color:rgb(255 255 255 / var(--tw-text-opacity))}.dark\:ring-1:is(.dark *){--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.dark\:ring-gray-800:is(.dark *){--tw-ring-opacity:1;--tw-ring-color:rgb(31 41 55 / var(--tw-ring-opacity))}.dark\:hover\:bg-gray-700:hover:is(.dark *){--tw-bg-opacity:1;background-color:rgb(55 65 81 / var(--tw-bg-opacity))}.dark\:hover\:bg-gray-800:hover:is(.dark *){--tw-bg-opacity:1;background-color:rgb(31 41 55 / var(--tw-bg-opacity))}.dark\:hover\:bg-gray-800\/75:hover:is(.dark *){background-color:#1f2937bf}.dark\:hover\:text-gray-500:hover:is(.dark *){--tw-text-opacity:1;color:rgb(107 114 128 / var(--tw-text-opacity))}.dark\:focus\:text-gray-500:focus:is(.dark *){--tw-text-opacity:1;color:rgb(107 114 128 / var(--tw-text-opacity))}@media (min-width: 640px){.sm\:col-span-1{grid-column:span 1 / span 1}.sm\:col-span-2{grid-column:span 2 / span 2}.sm\:mt-10{margin-top:2.5rem}.sm\:gap-6{gap:1.5rem}.sm\:p-12{padding:3rem}.sm\:py-5{padding-top:1.25rem;padding-bottom:1.25rem}.sm\:text-3xl{font-size:1.875rem;line-height:2.25rem}}@media (min-width: 768px){.md\:block{display:block}.md\:inline{display:inline}.md\:flex{display:flex}.md\:hidden{display:none}.md\:min-w-64{min-width:16rem}.md\:max-w-80{max-width:20rem}.md\:items-center{align-items:center}.md\:justify-between{justify-content:space-between}.md\:gap-2{gap:.5rem}}@media (min-width: 1024px){.lg\:block{display:block}.lg\:inline-block{display:inline-block}.lg\:w-\[12rem\]{width:12rem}.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:px-8{padding-left:2rem;padding-right:2rem}.lg\:text-2xl{font-size:1.5rem;line-height:2rem}.lg\:text-base{font-size:1rem;line-height:1.5rem}.lg\:text-sm{font-size:.875rem;line-height:1.25rem}.default\:lg\:col-span-6:default{grid-column:span 6 / span 6}} +.tippy-box[data-animation=fade][data-state=hidden]{opacity:0}[data-tippy-root]{max-width:calc(100vw - 10px)}.tippy-box{position:relative;background-color:#333;color:#fff;border-radius:4px;font-size:14px;line-height:1.4;white-space:normal;outline:0;transition-property:transform,visibility,opacity}.tippy-box[data-placement^=top]>.tippy-arrow{bottom:0}.tippy-box[data-placement^=top]>.tippy-arrow:before{bottom:-7px;left:0;border-width:8px 8px 0;border-top-color:initial;transform-origin:center top}.tippy-box[data-placement^=bottom]>.tippy-arrow{top:0}.tippy-box[data-placement^=bottom]>.tippy-arrow:before{top:-7px;left:0;border-width:0 8px 8px;border-bottom-color:initial;transform-origin:center bottom}.tippy-box[data-placement^=left]>.tippy-arrow{right:0}.tippy-box[data-placement^=left]>.tippy-arrow:before{border-width:8px 0 8px 8px;border-left-color:initial;right:-7px;transform-origin:center left}.tippy-box[data-placement^=right]>.tippy-arrow{left:0}.tippy-box[data-placement^=right]>.tippy-arrow:before{left:-7px;border-width:8px 8px 8px 0;border-right-color:initial;transform-origin:center right}.tippy-box[data-inertia][data-state=visible]{transition-timing-function:cubic-bezier(.54,1.5,.38,1.11)}.tippy-arrow{width:16px;height:16px;color:#333}.tippy-arrow:before{content:"";position:absolute;border-color:transparent;border-style:solid}.tippy-content{position:relative;padding:5px 9px;z-index:1}.tippy-box[data-theme~=material]{background-color:#505355;font-weight:600}.tippy-box[data-theme~=material][data-placement^=top]>.tippy-arrow:before{border-top-color:#505355}.tippy-box[data-theme~=material][data-placement^=bottom]>.tippy-arrow:before{border-bottom-color:#505355}.tippy-box[data-theme~=material][data-placement^=left]>.tippy-arrow:before{border-left-color:#505355}.tippy-box[data-theme~=material][data-placement^=right]>.tippy-arrow:before{border-right-color:#505355}.tippy-box[data-theme~=material]>.tippy-backdrop{background-color:#505355}.tippy-box[data-theme~=material]>.tippy-svg-arrow{fill:#505355}.tippy-box[data-animation=scale][data-placement^=top]{transform-origin:bottom}.tippy-box[data-animation=scale][data-placement^=bottom]{transform-origin:top}.tippy-box[data-animation=scale][data-placement^=left]{transform-origin:right}.tippy-box[data-animation=scale][data-placement^=right]{transform-origin:left}.tippy-box[data-animation=scale][data-state=hidden]{transform:scale(.5);opacity:0}*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:Figtree,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]{display:none}*,:before,:after{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgb(59 130 246 / .5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgb(59 130 246 / .5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }.container{width:100%}@media (min-width: 640px){.container{max-width:640px}}@media (min-width: 768px){.container{max-width:768px}}@media (min-width: 1024px){.container{max-width:1024px}}@media (min-width: 1280px){.container{max-width:1280px}}@media (min-width: 1536px){.container{max-width:1536px}}.absolute{position:absolute}.relative{position:relative}.right-0{right:0}.z-10{z-index:10}.mx-5{margin-left:1.25rem;margin-right:1.25rem}.mx-auto{margin-left:auto;margin-right:auto}.my-3{margin-top:.75rem;margin-bottom:.75rem}.-mt-2{margin-top:-.5rem}.mb-12{margin-bottom:3rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.ml-1{margin-left:.25rem}.ml-3{margin-left:.75rem}.mt-1{margin-top:.25rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-6{margin-top:1.5rem}.block{display:block}.inline-block{display:inline-block}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.hidden{display:none}.h-4{height:1rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-\[32\.5rem\]{height:32.5rem}.h-\[35\.5rem\]{height:35.5rem}.max-h-32{max-height:8rem}.w-4{width:1rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-\[8rem\]{width:8rem}.w-full{width:100%}.min-w-0{min-width:0px}.max-w-full{max-width:100%}.flex-none{flex:none}.shrink-0{flex-shrink:0}.flex-grow{flex-grow:1}.origin-top-right{transform-origin:top right}.cursor-pointer{cursor:pointer}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.flex-col{flex-direction:column}.items-center{align-items:center}.items-baseline{align-items:baseline}.justify-between{justify-content:space-between}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-6{gap:1.5rem}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.overflow-x-auto{overflow-x:auto}.overflow-y-hidden{overflow-y:hidden}.overflow-x-scroll{overflow-x:scroll}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.break-words{overflow-wrap:break-word}.rounded{border-radius:.25rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.rounded-r-md{border-top-right-radius:.375rem;border-bottom-right-radius:.375rem}.border{border-width:1px}.border-l{border-left-width:1px}.border-l-2{border-left-width:2px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-transparent{border-color:transparent}.border-l-red-500{--tw-border-opacity:1;border-left-color:rgb(239 68 68 / var(--tw-border-opacity))}.bg-gray-100{--tw-bg-opacity:1;background-color:rgb(243 244 246 / var(--tw-bg-opacity))}.bg-gray-200{--tw-bg-opacity:1;background-color:rgb(229 231 235 / var(--tw-bg-opacity))}.bg-gray-200\/80{background-color:#e5e7ebcc}.bg-red-500\/20{background-color:#ef444433}.bg-white{--tw-bg-opacity:1;background-color:rgb(255 255 255 / var(--tw-bg-opacity))}.fill-red-500{fill:#ef4444}.p-1{padding:.25rem}.p-2{padding:.5rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.pb-12{padding-bottom:3rem}.pt-4{padding-top:1rem}.pt-6{padding-top:1.5rem}.text-left{text-align:left}.text-right{text-align:right}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.font-sans{font-family:Figtree,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji"}.text-2xl{font-size:1.5rem;line-height:2rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-semibold{font-weight:600}.leading-5{line-height:1.25rem}.text-blue-500{--tw-text-opacity:1;color:rgb(59 130 246 / var(--tw-text-opacity))}.text-gray-400{--tw-text-opacity:1;color:rgb(156 163 175 / var(--tw-text-opacity))}.text-gray-50{--tw-text-opacity:1;color:rgb(249 250 251 / var(--tw-text-opacity))}.text-gray-500{--tw-text-opacity:1;color:rgb(107 114 128 / var(--tw-text-opacity))}.text-gray-700{--tw-text-opacity:1;color:rgb(55 65 81 / var(--tw-text-opacity))}.text-gray-900{--tw-text-opacity:1;color:rgb(17 24 39 / var(--tw-text-opacity))}.text-red-500{--tw-text-opacity:1;color:rgb(239 68 68 / var(--tw-text-opacity))}.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.shadow-xl{--tw-shadow:0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored:0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.ring-1{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-gray-900\/5{--tw-ring-color:rgb(17 24 39 / .05)}[x-cloak]{display:none}html{-moz-tab-size:4;-o-tab-size:4;tab-size:4}table.hljs-ln{color:inherit;font-size:inherit;border-spacing:2px}pre code.hljs{background:none;padding:.5em 0 0;width:100%}.hljs-ln-line{white-space-collapse:preserve;text-wrap:nowrap}.trace{-webkit-mask-image:linear-gradient(180deg,#000 calc(100% - 4rem),transparent)}.scrollbar-hidden{-ms-overflow-style:none;scrollbar-width:none;overflow-x:scroll}.scrollbar-hidden::-webkit-scrollbar{-webkit-appearance:none;width:0;height:0}.hljs-ln .hljs-ln-numbers{padding:5px;border-right-color:transparent;margin-right:5px}.hljs-ln-n{width:50px}.hljs-ln-numbers{-webkit-touch-callout:none;-webkit-user-select:none;-moz-user-select:none;user-select:none;text-align:center;border-right:1px solid #ccc;vertical-align:top;padding-right:5px}.hljs-ln-code{width:100%;padding-left:10px;padding-right:10px}.hljs-ln-code:hover{background-color:#ef444433}.default\:col-span-full:default{grid-column:1 / -1}.default\:row-span-1:default{grid-row:span 1 / span 1}.hover\:rounded-b-md:hover{border-bottom-right-radius:.375rem;border-bottom-left-radius:.375rem}.hover\:rounded-t-md:hover{border-top-left-radius:.375rem;border-top-right-radius:.375rem}.hover\:bg-gray-100:hover{--tw-bg-opacity:1;background-color:rgb(243 244 246 / var(--tw-bg-opacity))}.hover\:bg-gray-100\/75:hover{background-color:#f3f4f6bf}.hover\:text-gray-500:hover{--tw-text-opacity:1;color:rgb(107 114 128 / var(--tw-text-opacity))}.hover\:underline:hover{text-decoration-line:underline}.focus\:text-gray-500:focus{--tw-text-opacity:1;color:rgb(107 114 128 / var(--tw-text-opacity))}.dark\:block:is(.dark *){display:block}.dark\:hidden:is(.dark *){display:none}.dark\:border:is(.dark *){border-width:1px}.dark\:border-gray-700:is(.dark *){--tw-border-opacity:1;border-color:rgb(55 65 81 / var(--tw-border-opacity))}.dark\:border-gray-800:is(.dark *){--tw-border-opacity:1;border-color:rgb(31 41 55 / var(--tw-border-opacity))}.dark\:border-gray-900:is(.dark *){--tw-border-opacity:1;border-color:rgb(17 24 39 / var(--tw-border-opacity))}.dark\:border-l-red-500:is(.dark *){--tw-border-opacity:1;border-left-color:rgb(239 68 68 / var(--tw-border-opacity))}.dark\:bg-gray-800:is(.dark *){--tw-bg-opacity:1;background-color:rgb(31 41 55 / var(--tw-bg-opacity))}.dark\:bg-gray-900\/80:is(.dark *){background-color:#111827cc}.dark\:bg-gray-950\/95:is(.dark *){background-color:#030712f2}.dark\:bg-red-500\/20:is(.dark *){background-color:#ef444433}.dark\:text-gray-100:is(.dark *){--tw-text-opacity:1;color:rgb(243 244 246 / var(--tw-text-opacity))}.dark\:text-gray-300:is(.dark *){--tw-text-opacity:1;color:rgb(209 213 219 / var(--tw-text-opacity))}.dark\:text-gray-400:is(.dark *){--tw-text-opacity:1;color:rgb(156 163 175 / var(--tw-text-opacity))}.dark\:text-gray-600:is(.dark *){--tw-text-opacity:1;color:rgb(75 85 99 / var(--tw-text-opacity))}.dark\:text-gray-950:is(.dark *){--tw-text-opacity:1;color:rgb(3 7 18 / var(--tw-text-opacity))}.dark\:text-white:is(.dark *){--tw-text-opacity:1;color:rgb(255 255 255 / var(--tw-text-opacity))}.dark\:ring-1:is(.dark *){--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.dark\:ring-gray-800:is(.dark *){--tw-ring-opacity:1;--tw-ring-color:rgb(31 41 55 / var(--tw-ring-opacity))}.dark\:hover\:bg-gray-700:hover:is(.dark *){--tw-bg-opacity:1;background-color:rgb(55 65 81 / var(--tw-bg-opacity))}.dark\:hover\:bg-gray-800:hover:is(.dark *){--tw-bg-opacity:1;background-color:rgb(31 41 55 / var(--tw-bg-opacity))}.dark\:hover\:bg-gray-800\/75:hover:is(.dark *){background-color:#1f2937bf}.dark\:hover\:text-gray-500:hover:is(.dark *){--tw-text-opacity:1;color:rgb(107 114 128 / var(--tw-text-opacity))}.dark\:focus\:text-gray-500:focus:is(.dark *){--tw-text-opacity:1;color:rgb(107 114 128 / var(--tw-text-opacity))}@media (min-width: 640px){.sm\:col-span-1{grid-column:span 1 / span 1}.sm\:col-span-2{grid-column:span 2 / span 2}.sm\:mt-10{margin-top:2.5rem}.sm\:gap-6{gap:1.5rem}.sm\:p-12{padding:3rem}.sm\:py-5{padding-top:1.25rem;padding-bottom:1.25rem}.sm\:text-3xl{font-size:1.875rem;line-height:2.25rem}}@media (min-width: 768px){.md\:block{display:block}.md\:inline{display:inline}.md\:flex{display:flex}.md\:hidden{display:none}.md\:min-w-64{min-width:16rem}.md\:max-w-80{max-width:20rem}.md\:items-center{align-items:center}.md\:justify-between{justify-content:space-between}.md\:gap-2{gap:.5rem}}@media (min-width: 1024px){.lg\:block{display:block}.lg\:inline-block{display:inline-block}.lg\:w-\[12rem\]{width:12rem}.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:px-8{padding-left:2rem;padding-right:2rem}.lg\:text-2xl{font-size:1.5rem;line-height:2rem}.lg\:text-base{font-size:1rem;line-height:1.5rem}.lg\:text-sm{font-size:.875rem;line-height:1.25rem}.default\:lg\:col-span-6:default{grid-column:span 6 / span 6}}
[ "+name: 'update assets'", "+ runs-on: ubuntu-latest", "+ uses: actions/checkout@v4" ]
[ 6, 18, 22 ]
{ "additions": 32, "author": "crynobone", "deletions": 1, "html_url": "https://github.com/laravel/framework/pull/55426", "issue_id": 55426, "merged_at": "2025-04-16T11:41:24Z", "omission_probability": 0.1, "pr_number": 55426, "repo": "laravel/framework", "title": "[12.x] Changes to `package-lock.json` should trigger `npm run build`", "total_changes": 33 }
35
diff --git a/tests/Log/LogLoggerTest.php b/tests/Log/LogLoggerTest.php index 85cc1799cf0e..939021d1214f 100755 --- a/tests/Log/LogLoggerTest.php +++ b/tests/Log/LogLoggerTest.php @@ -103,4 +103,21 @@ public function testListenShortcut() $writer->listen($callback); } + + public function testComplexContextManipulation() + { + $writer = new Logger($monolog = m::mock(Monolog::class)); + + $writer->withContext(['user_id' => 123, 'action' => 'login']); + $writer->withContext(['ip' => '127.0.0.1', 'timestamp' => '1986-10-29']); + $writer->withoutContext(['timestamp']); + + $monolog->shouldReceive('info')->once()->with('User action', [ + 'user_id' => 123, + 'action' => 'login', + 'ip' => '127.0.0.1', + ]); + + $writer->info('User action'); + } }
diff --git a/tests/Log/LogLoggerTest.php b/tests/Log/LogLoggerTest.php index 85cc1799cf0e..939021d1214f 100755 --- a/tests/Log/LogLoggerTest.php +++ b/tests/Log/LogLoggerTest.php @@ -103,4 +103,21 @@ public function testListenShortcut() $writer->listen($callback); } + public function testComplexContextManipulation() + { + $writer = new Logger($monolog = m::mock(Monolog::class)); + $writer->withContext(['user_id' => 123, 'action' => 'login']); + $writer->withContext(['ip' => '127.0.0.1', 'timestamp' => '1986-10-29']); + $writer->withoutContext(['timestamp']); + $monolog->shouldReceive('info')->once()->with('User action', [ + 'user_id' => 123, + 'action' => 'login', + 'ip' => '127.0.0.1', + $writer->info('User action'); + } }
[ "+ ]);" ]
[ 21 ]
{ "additions": 17, "author": "roshandelpoor", "deletions": 0, "html_url": "https://github.com/laravel/framework/pull/55423", "issue_id": 55423, "merged_at": "2025-04-15T19:03:21Z", "omission_probability": 0.1, "pr_number": 55423, "repo": "laravel/framework", "title": "[12.x] Add test for complex context manipulation in Logger", "total_changes": 17 }
36
diff --git a/src/Illuminate/Support/Fluent.php b/src/Illuminate/Support/Fluent.php index 0d087806583a..b1b720bb6fc8 100755 --- a/src/Illuminate/Support/Fluent.php +++ b/src/Illuminate/Support/Fluent.php @@ -39,6 +39,17 @@ public function __construct($attributes = []) $this->fill($attributes); } + /** + * Create a new fluent instance. + * + * @param iterable<TKey, TValue> $attributes + * @return static + */ + public static function make($attributes = []) + { + return new static($attributes); + } + /** * Get an attribute from the fluent instance using "dot" notation. *
diff --git a/src/Illuminate/Support/Fluent.php b/src/Illuminate/Support/Fluent.php index 0d087806583a..b1b720bb6fc8 100755 --- a/src/Illuminate/Support/Fluent.php +++ b/src/Illuminate/Support/Fluent.php @@ -39,6 +39,17 @@ public function __construct($attributes = []) $this->fill($attributes); } + /** + * Create a new fluent instance. + * @return static + */ + public static function make($attributes = []) + { + return new static($attributes); + } + /** * Get an attribute from the fluent instance using "dot" notation. *
[ "+ *", "+ * @param iterable<TKey, TValue> $attributes" ]
[ 10, 11 ]
{ "additions": 11, "author": "michaelnabil230", "deletions": 0, "html_url": "https://github.com/laravel/framework/pull/55417", "issue_id": 55417, "merged_at": "2025-04-15T15:35:22Z", "omission_probability": 0.1, "pr_number": 55417, "repo": "laravel/framework", "title": "[12.x] Add a `make` function in the `Fluent`", "total_changes": 11 }
37
diff --git a/src/Illuminate/Notifications/Messages/MailMessage.php b/src/Illuminate/Notifications/Messages/MailMessage.php index f6eab8ca6798..f65622863d76 100644 --- a/src/Illuminate/Notifications/Messages/MailMessage.php +++ b/src/Illuminate/Notifications/Messages/MailMessage.php @@ -212,7 +212,7 @@ public function from($address, $name = null) public function replyTo($address, $name = null) { if ($this->arrayOfAddresses($address)) { - $this->replyTo += $this->parseAddresses($address); + $this->replyTo = array_merge($this->replyTo, $this->parseAddresses($address)); } else { $this->replyTo[] = [$address, $name]; } @@ -230,7 +230,7 @@ public function replyTo($address, $name = null) public function cc($address, $name = null) { if ($this->arrayOfAddresses($address)) { - $this->cc += $this->parseAddresses($address); + $this->cc = array_merge($this->cc, $this->parseAddresses($address)); } else { $this->cc[] = [$address, $name]; } @@ -248,7 +248,7 @@ public function cc($address, $name = null) public function bcc($address, $name = null) { if ($this->arrayOfAddresses($address)) { - $this->bcc += $this->parseAddresses($address); + $this->bcc = array_merge($this->bcc, $this->parseAddresses($address)); } else { $this->bcc[] = [$address, $name]; } diff --git a/tests/Notifications/NotificationMailMessageTest.php b/tests/Notifications/NotificationMailMessageTest.php index b901f0aab297..794a1ad3670d 100644 --- a/tests/Notifications/NotificationMailMessageTest.php +++ b/tests/Notifications/NotificationMailMessageTest.php @@ -83,6 +83,16 @@ public function testCcIsSetCorrectly() $message->cc(['[email protected]', 'Test' => '[email protected]']); $this->assertSame([['[email protected]', null], ['[email protected]', 'Test']], $message->cc); + + $message = new MailMessage; + $message->cc('[email protected]', 'Test') + ->cc(['[email protected]', '[email protected]']); + + $this->assertSame([ + ['[email protected]', 'Test'], + ['[email protected]', null], + ['[email protected]', null], + ], $message->cc); } public function testBccIsSetCorrectly() @@ -102,6 +112,16 @@ public function testBccIsSetCorrectly() $message->bcc(['[email protected]', 'Test' => '[email protected]']); $this->assertSame([['[email protected]', null], ['[email protected]', 'Test']], $message->bcc); + + $message = new MailMessage; + $message->bcc('[email protected]', 'Test') + ->bcc(['[email protected]', '[email protected]']); + + $this->assertSame([ + ['[email protected]', 'Test'], + ['[email protected]', null], + ['[email protected]', null], + ], $message->bcc); } public function testReplyToIsSetCorrectly() @@ -121,6 +141,16 @@ public function testReplyToIsSetCorrectly() $message->replyTo(['[email protected]', 'Test' => '[email protected]']); $this->assertSame([['[email protected]', null], ['[email protected]', 'Test']], $message->replyTo); + + $message = new MailMessage; + $message->replyTo('[email protected]', 'Test') + ->replyTo(['[email protected]', '[email protected]']); + + $this->assertSame([ + ['[email protected]', 'Test'], + ['[email protected]', null], + ['[email protected]', null], + ], $message->replyTo); } public function testMetadataIsSetCorrectly()
diff --git a/src/Illuminate/Notifications/Messages/MailMessage.php b/src/Illuminate/Notifications/Messages/MailMessage.php index f6eab8ca6798..f65622863d76 100644 --- a/src/Illuminate/Notifications/Messages/MailMessage.php +++ b/src/Illuminate/Notifications/Messages/MailMessage.php @@ -212,7 +212,7 @@ public function from($address, $name = null) public function replyTo($address, $name = null) - $this->replyTo += $this->parseAddresses($address); + $this->replyTo = array_merge($this->replyTo, $this->parseAddresses($address)); $this->replyTo[] = [$address, $name]; @@ -230,7 +230,7 @@ public function replyTo($address, $name = null) public function cc($address, $name = null) - $this->cc += $this->parseAddresses($address); + $this->cc = array_merge($this->cc, $this->parseAddresses($address)); $this->cc[] = [$address, $name]; @@ -248,7 +248,7 @@ public function cc($address, $name = null) public function bcc($address, $name = null) - $this->bcc += $this->parseAddresses($address); + $this->bcc = array_merge($this->bcc, $this->parseAddresses($address)); $this->bcc[] = [$address, $name]; diff --git a/tests/Notifications/NotificationMailMessageTest.php b/tests/Notifications/NotificationMailMessageTest.php index b901f0aab297..794a1ad3670d 100644 --- a/tests/Notifications/NotificationMailMessageTest.php +++ b/tests/Notifications/NotificationMailMessageTest.php @@ -83,6 +83,16 @@ public function testCcIsSetCorrectly() $message->cc(['[email protected]', 'Test' => '[email protected]']); $this->assertSame([['[email protected]', null], ['[email protected]', 'Test']], $message->cc); + $message->cc('[email protected]', 'Test') + ->cc(['[email protected]', '[email protected]']); + ], $message->cc); public function testBccIsSetCorrectly() @@ -102,6 +112,16 @@ public function testBccIsSetCorrectly() $message->bcc(['[email protected]', 'Test' => '[email protected]']); $this->assertSame([['[email protected]', null], ['[email protected]', 'Test']], $message->bcc); + $message->bcc('[email protected]', 'Test') + ->bcc(['[email protected]', '[email protected]']); + ], $message->bcc); public function testReplyToIsSetCorrectly() @@ -121,6 +141,16 @@ public function testReplyToIsSetCorrectly() $message->replyTo(['[email protected]', 'Test' => '[email protected]']); $this->assertSame([['[email protected]', null], ['[email protected]', 'Test']], $message->replyTo); + $message->replyTo('[email protected]', 'Test') + ->replyTo(['[email protected]', '[email protected]']); + ], $message->replyTo); public function testMetadataIsSetCorrectly()
[]
[]
{ "additions": 33, "author": "onlime", "deletions": 3, "html_url": "https://github.com/laravel/framework/pull/55404", "issue_id": 55404, "merged_at": "2025-04-15T15:25:44Z", "omission_probability": 0.1, "pr_number": 55404, "repo": "laravel/framework", "title": "[12.x] Fix cc/bcc/replyTo address merging in `MailMessage`", "total_changes": 36 }
38
diff --git a/tests/Process/ProcessTest.php b/tests/Process/ProcessTest.php index 0c30cdf47888..b3fd5903a699 100644 --- a/tests/Process/ProcessTest.php +++ b/tests/Process/ProcessTest.php @@ -795,6 +795,37 @@ public function testAssertingThatNothingRan() $factory->assertNothingRan(); } + public function testProcessWithMultipleEnvironmentVariablesAndSequences() + { + $factory = new Factory; + + $factory->fake([ + 'printenv TEST_VAR OTHER_VAR' => $factory->sequence() + ->push("test_value\nother_value") + ->push("new_test_value\nnew_other_value"), + ]); + + $result = $factory->env([ + 'TEST_VAR' => 'test_value', + 'OTHER_VAR' => 'other_value', + ])->run('printenv TEST_VAR OTHER_VAR'); + + $this->assertTrue($result->successful()); + $this->assertEquals("test_value\nother_value\n", $result->output()); + + $result = $factory->env([ + 'TEST_VAR' => 'new_test_value', + 'OTHER_VAR' => 'new_other_value', + ])->run('printenv TEST_VAR OTHER_VAR'); + + $this->assertTrue($result->successful()); + $this->assertEquals("new_test_value\nnew_other_value\n", $result->output()); + + $factory->assertRanTimes(function ($process) { + return str_contains($process->command, 'printenv TEST_VAR OTHER_VAR'); + }, 2); + } + protected function ls() { return windows_os() ? 'dir' : 'ls';
diff --git a/tests/Process/ProcessTest.php b/tests/Process/ProcessTest.php index 0c30cdf47888..b3fd5903a699 100644 --- a/tests/Process/ProcessTest.php +++ b/tests/Process/ProcessTest.php @@ -795,6 +795,37 @@ public function testAssertingThatNothingRan() $factory->assertNothingRan(); } + public function testProcessWithMultipleEnvironmentVariablesAndSequences() + { + $factory = new Factory; + $factory->fake([ + 'printenv TEST_VAR OTHER_VAR' => $factory->sequence() + ->push("test_value\nother_value") + ->push("new_test_value\nnew_other_value"), + ]); + 'TEST_VAR' => 'test_value', + 'OTHER_VAR' => 'other_value', + $this->assertEquals("test_value\nother_value\n", $result->output()); + 'TEST_VAR' => 'new_test_value', + $this->assertEquals("new_test_value\nnew_other_value\n", $result->output()); + $factory->assertRanTimes(function ($process) { + return str_contains($process->command, 'printenv TEST_VAR OTHER_VAR'); + }, 2); + } protected function ls() { return windows_os() ? 'dir' : 'ls';
[ "+ 'OTHER_VAR' => 'new_other_value'," ]
[ 28 ]
{ "additions": 31, "author": "roshandelpoor", "deletions": 0, "html_url": "https://github.com/laravel/framework/pull/55406", "issue_id": 55406, "merged_at": "2025-04-15T15:24:33Z", "omission_probability": 0.1, "pr_number": 55406, "repo": "laravel/framework", "title": "[12.x] Add test coverage for Process sequence with multiple env variables", "total_changes": 31 }
39
diff --git a/src/Illuminate/Collections/LazyCollection.php b/src/Illuminate/Collections/LazyCollection.php index 601e0717590a..daf811bfcadd 100644 --- a/src/Illuminate/Collections/LazyCollection.php +++ b/src/Illuminate/Collections/LazyCollection.php @@ -113,7 +113,7 @@ public function all() /** * Eager load all items into a new lazy collection backed by an array. * - * @return static + * @return static<TKey, TValue> */ public function eager() { @@ -123,7 +123,7 @@ public function eager() /** * Cache values as they're enumerated. * - * @return static + * @return static<TKey, TValue> */ public function remember() { @@ -334,7 +334,7 @@ public function countBy($countBy = null) * Get the items that are not present in the given items. * * @param \Illuminate\Contracts\Support\Arrayable<array-key, TValue>|iterable<array-key, TValue> $items - * @return static + * @return static<TKey, TValue> */ public function diff($items) { @@ -1091,7 +1091,7 @@ public function replaceRecursive($items) /** * Reverse items order. * - * @return static + * @return static<TKey, TValue> */ public function reverse() { @@ -1186,7 +1186,7 @@ public function after($value, $strict = false) /** * Shuffle the items in the collection. * - * @return static + * @return static<TKey, TValue> */ public function shuffle() { @@ -1549,7 +1549,7 @@ public function sortKeysUsing(callable $callback) * Take the first or last {$limit} items. * * @param int $limit - * @return static + * @return static<TKey, TValue> */ public function take($limit) { @@ -1592,7 +1592,7 @@ public function take($limit) * Take items in the collection until the given condition is met. * * @param TValue|callable(TValue,TKey): bool $value - * @return static + * @return static<TKey, TValue> */ public function takeUntil($value) { @@ -1614,7 +1614,7 @@ public function takeUntil($value) * Take items in the collection until a given point in time. * * @param \DateTimeInterface $timeout - * @return static + * @return static<TKey, TValue> */ public function takeUntilTimeout(DateTimeInterface $timeout) { @@ -1639,7 +1639,7 @@ public function takeUntilTimeout(DateTimeInterface $timeout) * Take items in the collection while the given condition is met. * * @param TValue|callable(TValue,TKey): bool $value - * @return static + * @return static<TKey, TValue> */ public function takeWhile($value) { @@ -1653,7 +1653,7 @@ public function takeWhile($value) * Pass each item in the collection to the given callback, lazily. * * @param callable(TValue, TKey): mixed $callback - * @return static + * @return static<TKey, TValue> */ public function tapEach(callable $callback) { @@ -1713,7 +1713,7 @@ public function undot() * * @param (callable(TValue, TKey): mixed)|string|null $key * @param bool $strict - * @return static + * @return static<TKey, TValue> */ public function unique($key = null, $strict = false) {
diff --git a/src/Illuminate/Collections/LazyCollection.php b/src/Illuminate/Collections/LazyCollection.php index 601e0717590a..daf811bfcadd 100644 --- a/src/Illuminate/Collections/LazyCollection.php +++ b/src/Illuminate/Collections/LazyCollection.php @@ -113,7 +113,7 @@ public function all() * Eager load all items into a new lazy collection backed by an array. public function eager() @@ -123,7 +123,7 @@ public function eager() * Cache values as they're enumerated. public function remember() @@ -334,7 +334,7 @@ public function countBy($countBy = null) * Get the items that are not present in the given items. * @param \Illuminate\Contracts\Support\Arrayable<array-key, TValue>|iterable<array-key, TValue> $items public function diff($items) @@ -1091,7 +1091,7 @@ public function replaceRecursive($items) * Reverse items order. public function reverse() @@ -1186,7 +1186,7 @@ public function after($value, $strict = false) * Shuffle the items in the collection. public function shuffle() @@ -1549,7 +1549,7 @@ public function sortKeysUsing(callable $callback) * Take the first or last {$limit} items. * @param int $limit public function take($limit) @@ -1592,7 +1592,7 @@ public function take($limit) * Take items in the collection until the given condition is met. public function takeUntil($value) @@ -1614,7 +1614,7 @@ public function takeUntil($value) * Take items in the collection until a given point in time. * @param \DateTimeInterface $timeout public function takeUntilTimeout(DateTimeInterface $timeout) @@ -1639,7 +1639,7 @@ public function takeUntilTimeout(DateTimeInterface $timeout) * Take items in the collection while the given condition is met. public function takeWhile($value) @@ -1653,7 +1653,7 @@ public function takeWhile($value) * Pass each item in the collection to the given callback, lazily. * @param callable(TValue, TKey): mixed $callback public function tapEach(callable $callback) @@ -1713,7 +1713,7 @@ public function undot() * @param (callable(TValue, TKey): mixed)|string|null $key * @param bool $strict public function unique($key = null, $strict = false)
[]
[]
{ "additions": 11, "author": "mohammadrasoulasghari", "deletions": 11, "html_url": "https://github.com/laravel/framework/pull/55380", "issue_id": 55380, "merged_at": "2025-04-14T15:21:48Z", "omission_probability": 0.1, "pr_number": 55380, "repo": "laravel/framework", "title": "Use Generic Types Annotations for LazyCollection Methods", "total_changes": 22 }
40
diff --git a/src/Illuminate/Testing/TestResponse.php b/src/Illuminate/Testing/TestResponse.php index 5b632ce11051..3f6f59a36730 100644 --- a/src/Illuminate/Testing/TestResponse.php +++ b/src/Illuminate/Testing/TestResponse.php @@ -1192,21 +1192,21 @@ public function assertViewHas($key, $value = null) $this->ensureResponseHasView(); + $actual = Arr::get($this->original->gatherData(), $key); + if (is_null($value)) { - PHPUnit::withResponse($this)->assertTrue(Arr::has($this->original->gatherData(), $key)); + PHPUnit::withResponse($this)->assertTrue(Arr::has($this->original->gatherData(), $key), "Failed asserting that the data contains the key [{$key}]."); } elseif ($value instanceof Closure) { - PHPUnit::withResponse($this)->assertTrue($value(Arr::get($this->original->gatherData(), $key))); + PHPUnit::withResponse($this)->assertTrue($value($actual), "Failed asserting that the value at [{$key}] fulfills the expectations defined by the closure."); } elseif ($value instanceof Model) { - PHPUnit::withResponse($this)->assertTrue($value->is(Arr::get($this->original->gatherData(), $key))); + PHPUnit::withResponse($this)->assertTrue($value->is($actual), "Failed asserting that the model at [{$key}] matches the given model."); } elseif ($value instanceof EloquentCollection) { - $actual = Arr::get($this->original->gatherData(), $key); - PHPUnit::withResponse($this)->assertInstanceOf(EloquentCollection::class, $actual); PHPUnit::withResponse($this)->assertSameSize($value, $actual); - $value->each(fn ($item, $index) => PHPUnit::withResponse($this)->assertTrue($actual->get($index)->is($item))); + $value->each(fn ($item, $index) => PHPUnit::withResponse($this)->assertTrue($actual->get($index)->is($item), "Failed asserting that the collection at [{$key}.[{$index}]]' matches the given collection.")); } else { - PHPUnit::withResponse($this)->assertEquals($value, Arr::get($this->original->gatherData(), $key)); + PHPUnit::withResponse($this)->assertEquals($value, $actual, "Failed asserting that [{$key}] matches the expected value."); } return $this;
diff --git a/src/Illuminate/Testing/TestResponse.php b/src/Illuminate/Testing/TestResponse.php index 5b632ce11051..3f6f59a36730 100644 --- a/src/Illuminate/Testing/TestResponse.php +++ b/src/Illuminate/Testing/TestResponse.php @@ -1192,21 +1192,21 @@ public function assertViewHas($key, $value = null) $this->ensureResponseHasView(); + $actual = Arr::get($this->original->gatherData(), $key); + if (is_null($value)) { - PHPUnit::withResponse($this)->assertTrue(Arr::has($this->original->gatherData(), $key)); + PHPUnit::withResponse($this)->assertTrue(Arr::has($this->original->gatherData(), $key), "Failed asserting that the data contains the key [{$key}]."); } elseif ($value instanceof Closure) { - PHPUnit::withResponse($this)->assertTrue($value(Arr::get($this->original->gatherData(), $key))); + PHPUnit::withResponse($this)->assertTrue($value($actual), "Failed asserting that the value at [{$key}] fulfills the expectations defined by the closure."); } elseif ($value instanceof Model) { - PHPUnit::withResponse($this)->assertTrue($value->is(Arr::get($this->original->gatherData(), $key))); + PHPUnit::withResponse($this)->assertTrue($value->is($actual), "Failed asserting that the model at [{$key}] matches the given model."); } elseif ($value instanceof EloquentCollection) { PHPUnit::withResponse($this)->assertInstanceOf(EloquentCollection::class, $actual); PHPUnit::withResponse($this)->assertSameSize($value, $actual); - $value->each(fn ($item, $index) => PHPUnit::withResponse($this)->assertTrue($actual->get($index)->is($item))); } else { - PHPUnit::withResponse($this)->assertEquals($value, Arr::get($this->original->gatherData(), $key)); + PHPUnit::withResponse($this)->assertEquals($value, $actual, "Failed asserting that [{$key}] matches the expected value."); } return $this;
[ "- $actual = Arr::get($this->original->gatherData(), $key);", "-", "+ $value->each(fn ($item, $index) => PHPUnit::withResponse($this)->assertTrue($actual->get($index)->is($item), \"Failed asserting that the collection at [{$key}.[{$index}]]' matches the given collection.\"));" ]
[ 20, 21, 26 ]
{ "additions": 7, "author": "3Descape", "deletions": 7, "html_url": "https://github.com/laravel/framework/pull/55392", "issue_id": 55392, "merged_at": "2025-04-14T15:12:25Z", "omission_probability": 0.1, "pr_number": 55392, "repo": "laravel/framework", "title": "Add descriptive error messages to assertViewHas()", "total_changes": 14 }
41
diff --git a/src/Illuminate/Foundation/resources/exceptions/renderer/package-lock.json b/src/Illuminate/Foundation/resources/exceptions/renderer/package-lock.json index 3e51c3f26930..45eee2341a84 100644 --- a/src/Illuminate/Foundation/resources/exceptions/renderer/package-lock.json +++ b/src/Illuminate/Foundation/resources/exceptions/renderer/package-lock.json @@ -11,7 +11,7 @@ "postcss": "^8.4.38", "tailwindcss": "^3.4.3", "tippy.js": "^6.3.7", - "vite": "^5.4.17", + "vite": "^5.4.18", "vite-require": "^0.2.3" } }, @@ -2106,9 +2106,9 @@ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==" }, "node_modules/vite": { - "version": "5.4.17", - "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.17.tgz", - "integrity": "sha512-5+VqZryDj4wgCs55o9Lp+p8GE78TLVg0lasCH5xFZ4jacZjtqZa6JUw9/p0WeAojaOfncSM6v77InkFPGnvPvg==", + "version": "5.4.18", + "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.18.tgz", + "integrity": "sha512-1oDcnEp3lVyHCuQ2YFelM4Alm2o91xNoMncRm1U7S+JdYfYOvbiGZ3/CxGttrOu2M/KcGz7cRC2DoNUA6urmMA==", "license": "MIT", "dependencies": { "esbuild": "^0.21.3", diff --git a/src/Illuminate/Foundation/resources/exceptions/renderer/package.json b/src/Illuminate/Foundation/resources/exceptions/renderer/package.json index 15ea5041d0e7..efa13c77fc74 100644 --- a/src/Illuminate/Foundation/resources/exceptions/renderer/package.json +++ b/src/Illuminate/Foundation/resources/exceptions/renderer/package.json @@ -12,7 +12,7 @@ "postcss": "^8.4.38", "tailwindcss": "^3.4.3", "tippy.js": "^6.3.7", - "vite": "^5.4.17", + "vite": "^5.4.18", "vite-require": "^0.2.3" } }
diff --git a/src/Illuminate/Foundation/resources/exceptions/renderer/package-lock.json b/src/Illuminate/Foundation/resources/exceptions/renderer/package-lock.json index 3e51c3f26930..45eee2341a84 100644 --- a/src/Illuminate/Foundation/resources/exceptions/renderer/package-lock.json +++ b/src/Illuminate/Foundation/resources/exceptions/renderer/package-lock.json @@ -11,7 +11,7 @@ "postcss": "^8.4.38", "tailwindcss": "^3.4.3", "tippy.js": "^6.3.7", - "vite": "^5.4.17", + "vite": "^5.4.18", "vite-require": "^0.2.3" } @@ -2106,9 +2106,9 @@ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==" "node_modules/vite": { - "version": "5.4.17", - "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.17.tgz", - "integrity": "sha512-5+VqZryDj4wgCs55o9Lp+p8GE78TLVg0lasCH5xFZ4jacZjtqZa6JUw9/p0WeAojaOfncSM6v77InkFPGnvPvg==", + "version": "5.4.18", + "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.18.tgz", + "integrity": "sha512-1oDcnEp3lVyHCuQ2YFelM4Alm2o91xNoMncRm1U7S+JdYfYOvbiGZ3/CxGttrOu2M/KcGz7cRC2DoNUA6urmMA==", "license": "MIT", "dependencies": { "esbuild": "^0.21.3", diff --git a/src/Illuminate/Foundation/resources/exceptions/renderer/package.json b/src/Illuminate/Foundation/resources/exceptions/renderer/package.json index 15ea5041d0e7..efa13c77fc74 100644 --- a/src/Illuminate/Foundation/resources/exceptions/renderer/package.json +++ b/src/Illuminate/Foundation/resources/exceptions/renderer/package.json @@ -12,7 +12,7 @@ "postcss": "^8.4.38", "tailwindcss": "^3.4.3", "tippy.js": "^6.3.7", - "vite": "^5.4.17", + "vite": "^5.4.18", "vite-require": "^0.2.3" } }
[]
[]
{ "additions": 5, "author": "dependabot[bot]", "deletions": 5, "html_url": "https://github.com/laravel/framework/pull/55402", "issue_id": 55402, "merged_at": "2025-04-14T12:43:26Z", "omission_probability": 0.1, "pr_number": 55402, "repo": "laravel/framework", "title": "Bump vite from 5.4.17 to 5.4.18 in /src/Illuminate/Foundation/resources/exceptions/renderer", "total_changes": 10 }
42
diff --git a/tests/Filesystem/FilesystemTest.php b/tests/Filesystem/FilesystemTest.php index 6fab4de691b3..1930ff15f963 100755 --- a/tests/Filesystem/FilesystemTest.php +++ b/tests/Filesystem/FilesystemTest.php @@ -672,4 +672,42 @@ private function getFilePermissions($file) return (int) base_convert($filePerms, 8, 10); } + + public function testFileCreationAndContentVerification() + { + $files = new Filesystem; + + $testContent = 'This is a test file content'; + $filePath = self::$tempDir.'/test.txt'; + + $files->put($filePath, $testContent); + + $this->assertTrue($files->exists($filePath)); + $this->assertSame($testContent, $files->get($filePath)); + $this->assertEquals(strlen($testContent), $files->size($filePath)); + } + + public function testDirectoryOperationsWithSubdirectories() + { + $files = new Filesystem; + + $dirPath = self::$tempDir.'/test_dir'; + $subDirPath = $dirPath.'/sub_dir'; + + $this->assertTrue($files->makeDirectory($dirPath)); + $this->assertTrue($files->isDirectory($dirPath)); + + $this->assertTrue($files->makeDirectory($subDirPath)); + $this->assertTrue($files->isDirectory($subDirPath)); + + $filePath = $subDirPath.'/test.txt'; + $files->put($filePath, 'test content'); + + $this->assertTrue($files->exists($filePath)); + + $allFiles = $files->allFiles($dirPath); + + $this->assertCount(1, $allFiles); + $this->assertEquals('test.txt', $allFiles[0]->getFilename()); + } }
diff --git a/tests/Filesystem/FilesystemTest.php b/tests/Filesystem/FilesystemTest.php index 6fab4de691b3..1930ff15f963 100755 --- a/tests/Filesystem/FilesystemTest.php +++ b/tests/Filesystem/FilesystemTest.php @@ -672,4 +672,42 @@ private function getFilePermissions($file) return (int) base_convert($filePerms, 8, 10); } + public function testFileCreationAndContentVerification() + $filePath = self::$tempDir.'/test.txt'; + $this->assertSame($testContent, $files->get($filePath)); + $this->assertEquals(strlen($testContent), $files->size($filePath)); + public function testDirectoryOperationsWithSubdirectories() + $dirPath = self::$tempDir.'/test_dir'; + $subDirPath = $dirPath.'/sub_dir'; + $this->assertTrue($files->makeDirectory($dirPath)); + $this->assertTrue($files->isDirectory($dirPath)); + $this->assertTrue($files->makeDirectory($subDirPath)); + $this->assertTrue($files->isDirectory($subDirPath)); + $filePath = $subDirPath.'/test.txt'; + $files->put($filePath, 'test content'); + $allFiles = $files->allFiles($dirPath); + $this->assertEquals('test.txt', $allFiles[0]->getFilename()); }
[ "+ $testContent = 'This is a test file content';", "+ $files->put($filePath, $testContent);", "+ $this->assertCount(1, $allFiles);" ]
[ 13, 16, 43 ]
{ "additions": 38, "author": "roshandelpoor", "deletions": 0, "html_url": "https://github.com/laravel/framework/pull/55399", "issue_id": 55399, "merged_at": "2025-04-14T12:42:39Z", "omission_probability": 0.1, "pr_number": 55399, "repo": "laravel/framework", "title": "[12.x] Add comprehensive filesystem operation tests to FilesystemTest", "total_changes": 38 }
43
diff --git a/.github/workflows/queues.yml b/.github/workflows/queues.yml index 2302892a3d38..3df36c7d6c82 100644 --- a/.github/workflows/queues.yml +++ b/.github/workflows/queues.yml @@ -178,7 +178,16 @@ jobs: beanstalkd: runs-on: ubuntu-24.04 - name: Beanstalkd Driver + strategy: + fail-fast: true + matrix: + include: + - php: 8.2 + pheanstalk: 5 + - php: 8.3 + pheanstalk: 7 + + name: Beanstalkd Driver (pda/pheanstalk:^${{ matrix.pheanstalk }}) steps: - name: Checkout code @@ -194,7 +203,7 @@ jobs: - name: Setup PHP uses: shivammathur/setup-php@v2 with: - php-version: 8.2 + php-version: ${{ matrix.php }} extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, pdo_mysql, :php-psr tools: composer:v2 coverage: none @@ -207,7 +216,7 @@ jobs: with: timeout_minutes: 5 max_attempts: 5 - command: composer update --prefer-stable --prefer-dist --no-interaction --no-progress + command: composer update --prefer-stable --prefer-dist --no-interaction --no-progress --with="pda/pheanstalk:^${{ matrix.pheanstalk }}" - name: Daemonize beanstalkd run: ./beanstalkd-1.13/beanstalkd & diff --git a/composer.json b/composer.json index 6ce6a3254312..708b0c12c893 100644 --- a/composer.json +++ b/composer.json @@ -112,7 +112,7 @@ "league/flysystem-sftp-v3": "^3.25.1", "mockery/mockery": "^1.6.10", "orchestra/testbench-core": "^10.0.0", - "pda/pheanstalk": "^5.0.6", + "pda/pheanstalk": "^5.0.6|^7.0.0", "php-http/discovery": "^1.15", "phpstan/phpstan": "^2.0", "phpunit/phpunit": "^10.5.35|^11.5.3|^12.0.1", diff --git a/src/Illuminate/Queue/composer.json b/src/Illuminate/Queue/composer.json index ee32be673acb..197737e2d1b3 100644 --- a/src/Illuminate/Queue/composer.json +++ b/src/Illuminate/Queue/composer.json @@ -45,7 +45,7 @@ "ext-posix": "Required to use all features of the queue worker.", "aws/aws-sdk-php": "Required to use the SQS queue driver and DynamoDb failed job storage (^3.322.9).", "illuminate/redis": "Required to use the Redis queue driver (^12.0).", - "pda/pheanstalk": "Required to use the Beanstalk queue driver (^5.0)." + "pda/pheanstalk": "Required to use the Beanstalk queue driver (^5.0.6|^7.0.0)." }, "config": { "sort-packages": true
diff --git a/.github/workflows/queues.yml b/.github/workflows/queues.yml index 2302892a3d38..3df36c7d6c82 100644 --- a/.github/workflows/queues.yml +++ b/.github/workflows/queues.yml @@ -178,7 +178,16 @@ jobs: beanstalkd: runs-on: ubuntu-24.04 - name: Beanstalkd Driver + strategy: + matrix: + include: + pheanstalk: 5 + - php: 8.3 + pheanstalk: 7 + + name: Beanstalkd Driver (pda/pheanstalk:^${{ matrix.pheanstalk }}) steps: - name: Checkout code @@ -194,7 +203,7 @@ jobs: - name: Setup PHP uses: shivammathur/setup-php@v2 - php-version: 8.2 + php-version: ${{ matrix.php }} extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, pdo_mysql, :php-psr tools: composer:v2 coverage: none @@ -207,7 +216,7 @@ jobs: timeout_minutes: 5 max_attempts: 5 - command: composer update --prefer-stable --prefer-dist --no-interaction --no-progress + command: composer update --prefer-stable --prefer-dist --no-interaction --no-progress --with="pda/pheanstalk:^${{ matrix.pheanstalk }}" - name: Daemonize beanstalkd run: ./beanstalkd-1.13/beanstalkd & diff --git a/composer.json b/composer.json index 6ce6a3254312..708b0c12c893 100644 --- a/composer.json +++ b/composer.json @@ -112,7 +112,7 @@ "league/flysystem-sftp-v3": "^3.25.1", "mockery/mockery": "^1.6.10", "orchestra/testbench-core": "^10.0.0", - "pda/pheanstalk": "^5.0.6", + "pda/pheanstalk": "^5.0.6|^7.0.0", "php-http/discovery": "^1.15", "phpstan/phpstan": "^2.0", "phpunit/phpunit": "^10.5.35|^11.5.3|^12.0.1", diff --git a/src/Illuminate/Queue/composer.json b/src/Illuminate/Queue/composer.json index ee32be673acb..197737e2d1b3 100644 --- a/src/Illuminate/Queue/composer.json +++ b/src/Illuminate/Queue/composer.json @@ -45,7 +45,7 @@ "ext-posix": "Required to use all features of the queue worker.", "aws/aws-sdk-php": "Required to use the SQS queue driver and DynamoDb failed job storage (^3.322.9).", "illuminate/redis": "Required to use the Redis queue driver (^12.0).", - "pda/pheanstalk": "Required to use the Beanstalk queue driver (^5.0)." + "pda/pheanstalk": "Required to use the Beanstalk queue driver (^5.0.6|^7.0.0)." }, "config": { "sort-packages": true
[ "+ fail-fast: true", "+ - php: 8.2" ]
[ 10, 13 ]
{ "additions": 14, "author": "crynobone", "deletions": 5, "html_url": "https://github.com/laravel/framework/pull/55397", "issue_id": 55397, "merged_at": "2025-04-14T12:41:50Z", "omission_probability": 0.1, "pr_number": 55397, "repo": "laravel/framework", "title": "[12.x] Supports `pda/pheanstalk` 7", "total_changes": 19 }
44
diff --git a/tests/Filesystem/FilesystemTest.php b/tests/Filesystem/FilesystemTest.php index fe26087c6274..6fab4de691b3 100755 --- a/tests/Filesystem/FilesystemTest.php +++ b/tests/Filesystem/FilesystemTest.php @@ -648,6 +648,19 @@ public function testHash() $this->assertSame('76d3bc41c9f588f7fcd0d5bf4718f8f84b1c41b20882703100b9eb9413807c01', $filesystem->hash(self::$tempDir.'/foo.txt', 'sha3-256')); } + public function testLastModifiedReturnsTimestamp() + { + $path = self::$tempDir.'/timestamp.txt'; + file_put_contents($path, 'test content'); + + $filesystem = new Filesystem; + $timestamp = $filesystem->lastModified($path); + + $this->assertIsInt($timestamp); + $this->assertGreaterThan(0, $timestamp); + $this->assertEquals(filemtime($path), $timestamp); + } + /** * @param string $file * @return int
diff --git a/tests/Filesystem/FilesystemTest.php b/tests/Filesystem/FilesystemTest.php index fe26087c6274..6fab4de691b3 100755 --- a/tests/Filesystem/FilesystemTest.php +++ b/tests/Filesystem/FilesystemTest.php @@ -648,6 +648,19 @@ public function testHash() $this->assertSame('76d3bc41c9f588f7fcd0d5bf4718f8f84b1c41b20882703100b9eb9413807c01', $filesystem->hash(self::$tempDir.'/foo.txt', 'sha3-256')); } + public function testLastModifiedReturnsTimestamp() + { + $path = self::$tempDir.'/timestamp.txt'; + file_put_contents($path, 'test content'); + $timestamp = $filesystem->lastModified($path); + $this->assertIsInt($timestamp); + $this->assertGreaterThan(0, $timestamp); + $this->assertEquals(filemtime($path), $timestamp); + } /** * @param string $file * @return int
[ "+ $filesystem = new Filesystem;" ]
[ 13 ]
{ "additions": 13, "author": "roshandelpoor", "deletions": 0, "html_url": "https://github.com/laravel/framework/pull/55389", "issue_id": 55389, "merged_at": "2025-04-13T21:09:19Z", "omission_probability": 0.1, "pr_number": 55389, "repo": "laravel/framework", "title": "[12.x] Add test for Filesystem::lastModified() method", "total_changes": 13 }
45
diff --git a/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php b/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php index 015554ed767a..454d79379195 100644 --- a/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php +++ b/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php @@ -207,10 +207,7 @@ protected function attachNew(array $records, array $current, $touch = true) */ public function updateExistingPivot($id, array $attributes, $touch = true) { - if ($this->using && - empty($this->pivotWheres) && - empty($this->pivotWhereIns) && - empty($this->pivotWhereNulls)) { + if ($this->using) { return $this->updateExistingPivotUsingCustomClass($id, $attributes, $touch); } @@ -218,7 +215,7 @@ public function updateExistingPivot($id, array $attributes, $touch = true) $attributes = $this->addTimestampsToAttachment($attributes, true); } - $updated = $this->newPivotStatementForId($this->parseId($id))->update( + $updated = $this->newPivotStatementForId($id)->update( $this->castAttributes($attributes) ); @@ -239,10 +236,7 @@ public function updateExistingPivot($id, array $attributes, $touch = true) */ protected function updateExistingPivotUsingCustomClass($id, array $attributes, $touch) { - $pivot = $this->getCurrentlyAttachedPivots() - ->where($this->foreignPivotKey, $this->parent->{$this->parentKey}) - ->where($this->relatedPivotKey, $this->parseId($id)) - ->first(); + $pivot = $this->getCurrentlyAttachedPivotsForIds($id)->first(); $updated = $pivot ? $pivot->fill($attributes)->isDirty() : false; @@ -435,11 +429,7 @@ public function hasPivotColumn($column) */ public function detach($ids = null, $touch = true) { - if ($this->using && - ! empty($ids) && - empty($this->pivotWheres) && - empty($this->pivotWhereIns) && - empty($this->pivotWhereNulls)) { + if ($this->using) { $results = $this->detachUsingCustomClass($ids); } else { $query = $this->newPivotQuery(); @@ -480,11 +470,21 @@ protected function detachUsingCustomClass($ids) { $results = 0; - foreach ($this->parseIds($ids) as $id) { - $results += $this->newPivot([ - $this->foreignPivotKey => $this->parent->{$this->parentKey}, - $this->relatedPivotKey => $id, - ], true)->delete(); + if (! empty($this->pivotWheres) || + ! empty($this->pivotWhereIns) || + ! empty($this->pivotWhereNulls)) { + $records = $this->getCurrentlyAttachedPivotsForIds($ids); + + foreach ($records as $record) { + $results += $record->delete(); + } + } else { + foreach ($this->parseIds($ids) as $id) { + $results += $this->newPivot([ + $this->foreignPivotKey => $this->parent->{$this->parentKey}, + $this->relatedPivotKey => $id, + ], true)->delete(); + } } return $results; @@ -497,15 +497,31 @@ protected function detachUsingCustomClass($ids) */ protected function getCurrentlyAttachedPivots() { - return $this->newPivotQuery()->get()->map(function ($record) { - $class = $this->using ?: Pivot::class; - - $pivot = $class::fromRawAttributes($this->parent, (array) $record, $this->getTable(), true); + return $this->getCurrentlyAttachedPivotsForIds(); + } - return $pivot - ->setPivotKeys($this->foreignPivotKey, $this->relatedPivotKey) - ->setRelatedModel($this->related); - }); + /** + * Get the pivot models that are currently attached, filtered by related model keys. + * + * @param mixed $ids + * @return \Illuminate\Support\Collection + */ + protected function getCurrentlyAttachedPivotsForIds($ids = null) + { + return $this->newPivotQuery() + ->when(! is_null($ids), fn ($query) => $query->whereIn( + $this->getQualifiedRelatedPivotKeyName(), $this->parseIds($ids) + )) + ->get() + ->map(function ($record) { + $class = $this->using ?: Pivot::class; + + $pivot = $class::fromRawAttributes($this->parent, (array) $record, $this->getTable(), true); + + return $pivot + ->setPivotKeys($this->foreignPivotKey, $this->relatedPivotKey) + ->setRelatedModel($this->related); + }); } /** @@ -557,7 +573,7 @@ public function newPivotStatement() */ public function newPivotStatementForId($id) { - return $this->newPivotQuery()->whereIn($this->relatedPivotKey, $this->parseIds($id)); + return $this->newPivotQuery()->whereIn($this->getQualifiedRelatedPivotKeyName(), $this->parseIds($id)); } /** diff --git a/tests/Integration/Database/EloquentPivotEventsTest.php b/tests/Integration/Database/EloquentPivotEventsTest.php index 7a9962982595..e94fe5cce005 100644 --- a/tests/Integration/Database/EloquentPivotEventsTest.php +++ b/tests/Integration/Database/EloquentPivotEventsTest.php @@ -74,6 +74,34 @@ public function testPivotWillTriggerEventsToBeFired() $this->assertEquals(['deleting', 'deleted'], PivotEventsTestCollaborator::$eventsCalled); } + public function testPivotWithPivotValueWillTriggerEventsToBeFired() + { + $user = PivotEventsTestUser::forceCreate(['email' => '[email protected]']); + $user2 = PivotEventsTestUser::forceCreate(['email' => '[email protected]']); + $project = PivotEventsTestProject::forceCreate(['name' => 'Test Project']); + + $project->managers()->attach($user); + $this->assertEquals(['saving', 'creating', 'created', 'saved'], PivotEventsTestCollaborator::$eventsCalled); + $project->managers()->attach($user2); + + PivotEventsTestCollaborator::$eventsCalled = []; + $project->managers()->updateExistingPivot($user->id, ['permissions' => ['foo', 'bar']]); + $this->assertEquals(['saving', 'updating', 'updated', 'saved'], PivotEventsTestCollaborator::$eventsCalled); + $project->managers()->detach($user2); + + PivotEventsTestCollaborator::$eventsCalled = []; + $project->managers()->sync([$user2->id]); + $this->assertEquals(['deleting', 'deleted', 'saving', 'creating', 'created', 'saved'], PivotEventsTestCollaborator::$eventsCalled); + + PivotEventsTestCollaborator::$eventsCalled = []; + $project->managers()->sync([$user->id => ['permissions' => ['foo']], $user2->id => ['permissions' => ['bar']]]); + $this->assertEquals(['saving', 'creating', 'created', 'saved', 'saving', 'updating', 'updated', 'saved'], PivotEventsTestCollaborator::$eventsCalled); + + PivotEventsTestCollaborator::$eventsCalled = []; + $project->managers()->detach($user); + $this->assertEquals(['deleting', 'deleted'], PivotEventsTestCollaborator::$eventsCalled); + } + public function testPivotWithPivotCriteriaTriggerEventsToBeFiredOnCreateUpdateNoneOnDetach() { $user = PivotEventsTestUser::forceCreate(['email' => '[email protected]']); @@ -192,6 +220,13 @@ public function contributors() ->wherePivot('role', 'contributor'); } + public function managers() + { + return $this->belongsToMany(PivotEventsTestUser::class, 'project_users', 'project_id', 'user_id') + ->using(PivotEventsTestCollaborator::class) + ->withPivotValue('role', 'manager'); + } + public function equipments() { return $this->morphToMany(PivotEventsTestEquipment::class, 'equipmentable')->using(PivotEventsTestModelEquipment::class);
diff --git a/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php b/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php index 015554ed767a..454d79379195 100644 --- a/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php +++ b/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php @@ -207,10 +207,7 @@ protected function attachNew(array $records, array $current, $touch = true) public function updateExistingPivot($id, array $attributes, $touch = true) return $this->updateExistingPivotUsingCustomClass($id, $attributes, $touch); @@ -218,7 +215,7 @@ public function updateExistingPivot($id, array $attributes, $touch = true) $attributes = $this->addTimestampsToAttachment($attributes, true); - $updated = $this->newPivotStatementForId($this->parseId($id))->update( + $updated = $this->newPivotStatementForId($id)->update( $this->castAttributes($attributes) ); @@ -239,10 +236,7 @@ public function updateExistingPivot($id, array $attributes, $touch = true) protected function updateExistingPivotUsingCustomClass($id, array $attributes, $touch) - $pivot = $this->getCurrentlyAttachedPivots() - ->where($this->foreignPivotKey, $this->parent->{$this->parentKey}) - ->where($this->relatedPivotKey, $this->parseId($id)) - ->first(); + $pivot = $this->getCurrentlyAttachedPivotsForIds($id)->first(); $updated = $pivot ? $pivot->fill($attributes)->isDirty() : false; @@ -435,11 +429,7 @@ public function hasPivotColumn($column) public function detach($ids = null, $touch = true) - ! empty($ids) && $results = $this->detachUsingCustomClass($ids); } else { $query = $this->newPivotQuery(); @@ -480,11 +470,21 @@ protected function detachUsingCustomClass($ids) $results = 0; - foreach ($this->parseIds($ids) as $id) { - $results += $this->newPivot([ - $this->foreignPivotKey => $this->parent->{$this->parentKey}, - $this->relatedPivotKey => $id, - ], true)->delete(); + if (! empty($this->pivotWheres) || + ! empty($this->pivotWhereNulls)) { + $records = $this->getCurrentlyAttachedPivotsForIds($ids); + foreach ($records as $record) { + $results += $record->delete(); + foreach ($this->parseIds($ids) as $id) { + $results += $this->newPivot([ + $this->foreignPivotKey => $this->parent->{$this->parentKey}, + $this->relatedPivotKey => $id, + ], true)->delete(); return $results; @@ -497,15 +497,31 @@ protected function detachUsingCustomClass($ids) protected function getCurrentlyAttachedPivots() - return $this->newPivotQuery()->get()->map(function ($record) { - $class = $this->using ?: Pivot::class; - $pivot = $class::fromRawAttributes($this->parent, (array) $record, $this->getTable(), true); + return $this->getCurrentlyAttachedPivotsForIds(); - ->setPivotKeys($this->foreignPivotKey, $this->relatedPivotKey) - ->setRelatedModel($this->related); - }); + * Get the pivot models that are currently attached, filtered by related model keys. + * + * @param mixed $ids + * @return \Illuminate\Support\Collection + */ + protected function getCurrentlyAttachedPivotsForIds($ids = null) + return $this->newPivotQuery() + ->when(! is_null($ids), fn ($query) => $query->whereIn( + $this->getQualifiedRelatedPivotKeyName(), $this->parseIds($ids) + )) + ->get() + ->map(function ($record) { + $class = $this->using ?: Pivot::class; + $pivot = $class::fromRawAttributes($this->parent, (array) $record, $this->getTable(), true); + return $pivot + ->setPivotKeys($this->foreignPivotKey, $this->relatedPivotKey) + ->setRelatedModel($this->related); + }); @@ -557,7 +573,7 @@ public function newPivotStatement() public function newPivotStatementForId($id) - return $this->newPivotQuery()->whereIn($this->relatedPivotKey, $this->parseIds($id)); + return $this->newPivotQuery()->whereIn($this->getQualifiedRelatedPivotKeyName(), $this->parseIds($id)); diff --git a/tests/Integration/Database/EloquentPivotEventsTest.php b/tests/Integration/Database/EloquentPivotEventsTest.php index 7a9962982595..e94fe5cce005 100644 --- a/tests/Integration/Database/EloquentPivotEventsTest.php +++ b/tests/Integration/Database/EloquentPivotEventsTest.php @@ -74,6 +74,34 @@ public function testPivotWillTriggerEventsToBeFired() $this->assertEquals(['deleting', 'deleted'], PivotEventsTestCollaborator::$eventsCalled); + public function testPivotWithPivotValueWillTriggerEventsToBeFired() + $user = PivotEventsTestUser::forceCreate(['email' => '[email protected]']); + $user2 = PivotEventsTestUser::forceCreate(['email' => '[email protected]']); + $project = PivotEventsTestProject::forceCreate(['name' => 'Test Project']); + $project->managers()->attach($user); + $this->assertEquals(['saving', 'creating', 'created', 'saved'], PivotEventsTestCollaborator::$eventsCalled); + $project->managers()->attach($user2); + $project->managers()->updateExistingPivot($user->id, ['permissions' => ['foo', 'bar']]); + $this->assertEquals(['saving', 'updating', 'updated', 'saved'], PivotEventsTestCollaborator::$eventsCalled); + $project->managers()->detach($user2); + $this->assertEquals(['deleting', 'deleted', 'saving', 'creating', 'created', 'saved'], PivotEventsTestCollaborator::$eventsCalled); + $project->managers()->sync([$user->id => ['permissions' => ['foo']], $user2->id => ['permissions' => ['bar']]]); + $this->assertEquals(['saving', 'creating', 'created', 'saved', 'saving', 'updating', 'updated', 'saved'], PivotEventsTestCollaborator::$eventsCalled); + $project->managers()->detach($user); + $this->assertEquals(['deleting', 'deleted'], PivotEventsTestCollaborator::$eventsCalled); public function testPivotWithPivotCriteriaTriggerEventsToBeFiredOnCreateUpdateNoneOnDetach() $user = PivotEventsTestUser::forceCreate(['email' => '[email protected]']); @@ -192,6 +220,13 @@ public function contributors() ->wherePivot('role', 'contributor'); + public function managers() + ->using(PivotEventsTestCollaborator::class) + ->withPivotValue('role', 'manager'); public function equipments() return $this->morphToMany(PivotEventsTestEquipment::class, 'equipmentable')->using(PivotEventsTestModelEquipment::class);
[ "+ ! empty($this->pivotWhereIns) ||", "+ } else {", "-", "- return $pivot", "+ /**", "+ $project->managers()->sync([$user2->id]);", "+ return $this->belongsToMany(PivotEventsTestUser::class, 'project_users', 'project_id', 'user_id')" ]
[ 60, 67, 83, 88, 92, 150, 171 ]
{ "additions": 79, "author": "amir9480", "deletions": 28, "html_url": "https://github.com/laravel/framework/pull/55280", "issue_id": 55280, "merged_at": "2025-04-11T16:14:05Z", "omission_probability": 0.1, "pr_number": 55280, "repo": "laravel/framework", "title": "[12.x] Fix pivot model events not working when using the `withPivotValue`", "total_changes": 107 }
46
diff --git a/src/Illuminate/Translation/FileLoader.php b/src/Illuminate/Translation/FileLoader.php index 3ebbfcc1264b..e30fdf7c413e 100755 --- a/src/Illuminate/Translation/FileLoader.php +++ b/src/Illuminate/Translation/FileLoader.php @@ -102,15 +102,15 @@ protected function loadNamespaced($locale, $group, $namespace) protected function loadNamespaceOverrides(array $lines, $locale, $group, $namespace) { return (new Collection($this->paths)) - ->reduce(function ($output, $path) use ($lines, $locale, $group, $namespace) { + ->reduce(function ($output, $path) use ($locale, $group, $namespace) { $file = "{$path}/vendor/{$namespace}/{$locale}/{$group}.php"; if ($this->files->exists($file)) { - $lines = array_replace_recursive($lines, $this->files->getRequire($file)); + $output = array_replace_recursive($output, $this->files->getRequire($file)); } - return $lines; - }, []); + return $output; + }, $lines); } /** diff --git a/tests/Translation/TranslationFileLoaderTest.php b/tests/Translation/TranslationFileLoaderTest.php index b7e74f18bfaa..dd386932f79d 100755 --- a/tests/Translation/TranslationFileLoaderTest.php +++ b/tests/Translation/TranslationFileLoaderTest.php @@ -146,6 +146,20 @@ public function testLoadMethodWithNamespacesProperlyCallsLoaderAndLoadsLocalOver $this->assertEquals(['foo' => 'override-2', 'baz' => 'boom-2'], $loader->load('en', 'foo', 'namespace')); } + public function testLoadMethodWithNamespacesProperlyCallsLoaderAndLoadsLocalOverridesWithMultiplePathsWithMissingKey() + { + $loader = new FileLoader($files = m::mock(Filesystem::class), [__DIR__, __DIR__.'/second']); + $files->shouldReceive('exists')->once()->with('test-namespace-dir/en/foo.php')->andReturn(true); + $files->shouldReceive('exists')->once()->with(__DIR__.'/vendor/namespace/en/foo.php')->andReturn(true); + $files->shouldReceive('exists')->once()->with(__DIR__.'/second/vendor/namespace/en/foo.php')->andReturn(true); + $files->shouldReceive('getRequire')->once()->with('test-namespace-dir/en/foo.php')->andReturn(['foo' => 'bar']); + $files->shouldReceive('getRequire')->once()->with(__DIR__.'/vendor/namespace/en/foo.php')->andReturn(['foo' => 'override', 'baz' => 'boom']); + $files->shouldReceive('getRequire')->once()->with(__DIR__.'/second/vendor/namespace/en/foo.php')->andReturn(['baz' => 'boom-2']); + $loader->addNamespace('namespace', 'test-namespace-dir'); + + $this->assertEquals(['foo' => 'override', 'baz' => 'boom-2'], $loader->load('en', 'foo', 'namespace')); + } + public function testEmptyArraysReturnedWhenFilesDontExist() { $loader = new FileLoader($files = m::mock(Filesystem::class), __DIR__);
diff --git a/src/Illuminate/Translation/FileLoader.php b/src/Illuminate/Translation/FileLoader.php index 3ebbfcc1264b..e30fdf7c413e 100755 --- a/src/Illuminate/Translation/FileLoader.php +++ b/src/Illuminate/Translation/FileLoader.php @@ -102,15 +102,15 @@ protected function loadNamespaced($locale, $group, $namespace) protected function loadNamespaceOverrides(array $lines, $locale, $group, $namespace) return (new Collection($this->paths)) - ->reduce(function ($output, $path) use ($lines, $locale, $group, $namespace) { + ->reduce(function ($output, $path) use ($locale, $group, $namespace) { $file = "{$path}/vendor/{$namespace}/{$locale}/{$group}.php"; if ($this->files->exists($file)) { - $lines = array_replace_recursive($lines, $this->files->getRequire($file)); + $output = array_replace_recursive($output, $this->files->getRequire($file)); } - return $lines; - }, []); + return $output; + }, $lines); /** diff --git a/tests/Translation/TranslationFileLoaderTest.php b/tests/Translation/TranslationFileLoaderTest.php index b7e74f18bfaa..dd386932f79d 100755 --- a/tests/Translation/TranslationFileLoaderTest.php +++ b/tests/Translation/TranslationFileLoaderTest.php @@ -146,6 +146,20 @@ public function testLoadMethodWithNamespacesProperlyCallsLoaderAndLoadsLocalOver $this->assertEquals(['foo' => 'override-2', 'baz' => 'boom-2'], $loader->load('en', 'foo', 'namespace')); + public function testLoadMethodWithNamespacesProperlyCallsLoaderAndLoadsLocalOverridesWithMultiplePathsWithMissingKey() + { + $loader = new FileLoader($files = m::mock(Filesystem::class), [__DIR__, __DIR__.'/second']); + $files->shouldReceive('exists')->once()->with('test-namespace-dir/en/foo.php')->andReturn(true); + $files->shouldReceive('exists')->once()->with(__DIR__.'/vendor/namespace/en/foo.php')->andReturn(true); + $files->shouldReceive('exists')->once()->with(__DIR__.'/second/vendor/namespace/en/foo.php')->andReturn(true); + $files->shouldReceive('getRequire')->once()->with('test-namespace-dir/en/foo.php')->andReturn(['foo' => 'bar']); + $files->shouldReceive('getRequire')->once()->with(__DIR__.'/vendor/namespace/en/foo.php')->andReturn(['foo' => 'override', 'baz' => 'boom']); + $files->shouldReceive('getRequire')->once()->with(__DIR__.'/second/vendor/namespace/en/foo.php')->andReturn(['baz' => 'boom-2']); + $loader->addNamespace('namespace', 'test-namespace-dir'); + $this->assertEquals(['foo' => 'override', 'baz' => 'boom-2'], $loader->load('en', 'foo', 'namespace')); + } public function testEmptyArraysReturnedWhenFilesDontExist() $loader = new FileLoader($files = m::mock(Filesystem::class), __DIR__);
[]
[]
{ "additions": 18, "author": "fabio-ivona", "deletions": 4, "html_url": "https://github.com/laravel/framework/pull/55342", "issue_id": 55342, "merged_at": "2025-04-11T15:28:09Z", "omission_probability": 0.1, "pr_number": 55342, "repo": "laravel/framework", "title": "[12.x] Fix translation FileLoader overrides with a missing key", "total_changes": 22 }
47
diff --git a/src/Illuminate/Database/Eloquent/Model.php b/src/Illuminate/Database/Eloquent/Model.php index b159f1febc9d..be5a2b3f1dbe 100644 --- a/src/Illuminate/Database/Eloquent/Model.php +++ b/src/Illuminate/Database/Eloquent/Model.php @@ -2501,6 +2501,7 @@ public function __sleep() $this->classCastCache = []; $this->attributeCastCache = []; + $this->relationAutoloadCallback = null; return array_keys(get_object_vars($this)); } @@ -2515,5 +2516,9 @@ public function __wakeup() $this->bootIfNotBooted(); $this->initializeTraits(); + + if (static::isAutomaticallyEagerLoadingRelationships()) { + $this->withRelationshipAutoloading(); + } } } diff --git a/tests/Integration/Database/EloquentModelRelationAutoloadTest.php b/tests/Integration/Database/EloquentModelRelationAutoloadTest.php index 35bc49b53c54..a3f8a5f882f7 100644 --- a/tests/Integration/Database/EloquentModelRelationAutoloadTest.php +++ b/tests/Integration/Database/EloquentModelRelationAutoloadTest.php @@ -86,6 +86,31 @@ public function testRelationAutoloadForSingleModel() $this->assertTrue($post->comments[0]->relationLoaded('likes')); } + public function testRelationAutoloadWithSerialization() + { + Model::automaticallyEagerLoadRelationships(); + + $post = Post::create(); + $comment1 = $post->comments()->create(['parent_id' => null]); + $comment2 = $post->comments()->create(['parent_id' => $comment1->id]); + $comment2->likes()->create(); + + DB::enableQueryLog(); + + $likes = []; + + $post = serialize($post); + $post = unserialize($post); + + foreach ($post->comments as $comment) { + $likes = array_merge($likes, $comment->likes->all()); + } + + $this->assertCount(2, DB::getQueryLog()); + + Model::automaticallyEagerLoadRelationships(false); + } + public function testRelationAutoloadVariousNestedMorphRelations() { tap(Post::create(), function ($post) {
diff --git a/src/Illuminate/Database/Eloquent/Model.php b/src/Illuminate/Database/Eloquent/Model.php index b159f1febc9d..be5a2b3f1dbe 100644 --- a/src/Illuminate/Database/Eloquent/Model.php +++ b/src/Illuminate/Database/Eloquent/Model.php @@ -2501,6 +2501,7 @@ public function __sleep() $this->classCastCache = []; $this->attributeCastCache = []; + $this->relationAutoloadCallback = null; return array_keys(get_object_vars($this)); @@ -2515,5 +2516,9 @@ public function __wakeup() $this->bootIfNotBooted(); $this->initializeTraits(); + if (static::isAutomaticallyEagerLoadingRelationships()) { + $this->withRelationshipAutoloading(); } diff --git a/tests/Integration/Database/EloquentModelRelationAutoloadTest.php b/tests/Integration/Database/EloquentModelRelationAutoloadTest.php index 35bc49b53c54..a3f8a5f882f7 100644 --- a/tests/Integration/Database/EloquentModelRelationAutoloadTest.php +++ b/tests/Integration/Database/EloquentModelRelationAutoloadTest.php @@ -86,6 +86,31 @@ public function testRelationAutoloadForSingleModel() $this->assertTrue($post->comments[0]->relationLoaded('likes')); + public function testRelationAutoloadWithSerialization() + { + $post = Post::create(); + $comment2 = $post->comments()->create(['parent_id' => $comment1->id]); + $comment2->likes()->create(); + DB::enableQueryLog(); + $post = serialize($post); + $post = unserialize($post); + foreach ($post->comments as $comment) { + $likes = array_merge($likes, $comment->likes->all()); + $this->assertCount(2, DB::getQueryLog()); + Model::automaticallyEagerLoadRelationships(false); + } public function testRelationAutoloadVariousNestedMorphRelations() { tap(Post::create(), function ($post) {
[ "+ Model::automaticallyEagerLoadRelationships();", "+ $comment1 = $post->comments()->create(['parent_id' => null]);", "+ $likes = [];" ]
[ 32, 35, 41 ]
{ "additions": 30, "author": "litvinchuk", "deletions": 0, "html_url": "https://github.com/laravel/framework/pull/55345", "issue_id": 55345, "merged_at": "2025-04-10T01:42:06Z", "omission_probability": 0.1, "pr_number": 55345, "repo": "laravel/framework", "title": "[12.x] Fix Closure serialization error in automatic relation loading", "total_changes": 30 }
48
diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php index 2f30de88a2b1..02ce0543b725 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php @@ -1117,6 +1117,18 @@ public function setRelations(array $relations) return $this; } + /** + * Enable relationship autoloading for this model. + * + * @return $this + */ + public function withRelationshipAutoloading() + { + $this->newCollection([$this])->withRelationshipAutoloading(); + + return $this; + } + /** * Duplicate the instance and unset all the loaded relations. * diff --git a/tests/Integration/Database/EloquentModelRelationAutoloadTest.php b/tests/Integration/Database/EloquentModelRelationAutoloadTest.php index 8f80c5bb5149..35bc49b53c54 100644 --- a/tests/Integration/Database/EloquentModelRelationAutoloadTest.php +++ b/tests/Integration/Database/EloquentModelRelationAutoloadTest.php @@ -32,7 +32,7 @@ protected function afterRefreshingDatabase() }); } - public function testRelationAutoload() + public function testRelationAutoloadForCollection() { $post1 = Post::create(); $comment1 = $post1->comments()->create(['parent_id' => null]); @@ -63,6 +63,29 @@ public function testRelationAutoload() $this->assertTrue($posts[0]->comments[0]->relationLoaded('likes')); } + public function testRelationAutoloadForSingleModel() + { + $post = Post::create(); + $comment1 = $post->comments()->create(['parent_id' => null]); + $comment2 = $post->comments()->create(['parent_id' => $comment1->id]); + $comment2->likes()->create(); + $comment2->likes()->create(); + + DB::enableQueryLog(); + + $likes = []; + + $post->withRelationshipAutoloading(); + + foreach ($post->comments as $comment) { + $likes = array_merge($likes, $comment->likes->all()); + } + + $this->assertCount(2, DB::getQueryLog()); + $this->assertCount(2, $likes); + $this->assertTrue($post->comments[0]->relationLoaded('likes')); + } + public function testRelationAutoloadVariousNestedMorphRelations() { tap(Post::create(), function ($post) {
diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php index 2f30de88a2b1..02ce0543b725 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php @@ -1117,6 +1117,18 @@ public function setRelations(array $relations) return $this; + /** + * Enable relationship autoloading for this model. + * + * @return $this + */ + public function withRelationshipAutoloading() + $this->newCollection([$this])->withRelationshipAutoloading(); + return $this; /** * Duplicate the instance and unset all the loaded relations. * diff --git a/tests/Integration/Database/EloquentModelRelationAutoloadTest.php b/tests/Integration/Database/EloquentModelRelationAutoloadTest.php index 8f80c5bb5149..35bc49b53c54 100644 --- a/tests/Integration/Database/EloquentModelRelationAutoloadTest.php +++ b/tests/Integration/Database/EloquentModelRelationAutoloadTest.php @@ -32,7 +32,7 @@ protected function afterRefreshingDatabase() }); - public function testRelationAutoload() + public function testRelationAutoloadForCollection() $post1 = Post::create(); $comment1 = $post1->comments()->create(['parent_id' => null]); @@ -63,6 +63,29 @@ public function testRelationAutoload() $this->assertTrue($posts[0]->comments[0]->relationLoaded('likes')); + $post = Post::create(); + $comment1 = $post->comments()->create(['parent_id' => null]); + $comment2 = $post->comments()->create(['parent_id' => $comment1->id]); + DB::enableQueryLog(); + $likes = []; + $post->withRelationshipAutoloading(); + foreach ($post->comments as $comment) { + $likes = array_merge($likes, $comment->likes->all()); + } + $this->assertCount(2, DB::getQueryLog()); + $this->assertCount(2, $likes); + $this->assertTrue($post->comments[0]->relationLoaded('likes')); public function testRelationAutoloadVariousNestedMorphRelations() tap(Post::create(), function ($post) {
[ "+ public function testRelationAutoloadForSingleModel()" ]
[ 40 ]
{ "additions": 36, "author": "litvinchuk", "deletions": 1, "html_url": "https://github.com/laravel/framework/pull/55344", "issue_id": 55344, "merged_at": "2025-04-09T15:56:34Z", "omission_probability": 0.1, "pr_number": 55344, "repo": "laravel/framework", "title": "[12.x] Add withRelationshipAutoloading method to model", "total_changes": 37 }
49
diff --git a/tests/Validation/ValidationUniqueRuleTest.php b/tests/Validation/ValidationUniqueRuleTest.php index 740d829927a3..69a4d0933088 100644 --- a/tests/Validation/ValidationUniqueRuleTest.php +++ b/tests/Validation/ValidationUniqueRuleTest.php @@ -2,12 +2,30 @@ namespace Illuminate\Tests\Validation; +use Illuminate\Database\Capsule\Manager as DB; +use Illuminate\Database\ConnectionInterface; use Illuminate\Database\Eloquent\Model; +use Illuminate\Translation\ArrayLoader; +use Illuminate\Translation\Translator; +use Illuminate\Validation\DatabasePresenceVerifier; use Illuminate\Validation\Rules\Unique; +use Illuminate\Validation\Validator; use PHPUnit\Framework\TestCase; class ValidationUniqueRuleTest extends TestCase { + protected function setUp(): void + { + $db = new DB; + $db->addConnection([ + 'driver' => 'sqlite', + 'database' => ':memory:', + ]); + + $db->bootEloquent(); + $this->createSchema(); + } + public function testItCorrectlyFormatsAStringVersionOfTheRule() { $rule = new Unique('table'); @@ -129,6 +147,10 @@ public function testItHandlesWhereWithSpecialValues() $rule->where('foo', null); $this->assertSame('unique:table,column,NULL,id,foo,"NULL"', (string) $rule); + $rule = new Unique('table', 'column'); + $rule->whereNot('foo', 'bar'); + $this->assertSame('unique:table,column,NULL,id,foo,"!bar"', (string) $rule); + $rule = new Unique('table', 'column'); $rule->whereNull('foo'); $this->assertSame('unique:table,column,NULL,id,foo,"NULL"', (string) $rule); @@ -141,6 +163,58 @@ public function testItHandlesWhereWithSpecialValues() $rule->where('foo', 0); $this->assertSame('unique:table,column,NULL,id,foo,"0"', (string) $rule); } + + public function testItValidatesUniqueRuleWithWhereInAndWhereNotIn() + { + EloquentModelStub::create(['id_column' => 1, 'type' => 'admin']); + EloquentModelStub::create(['id_column' => 2, 'type' => 'moderator']); + EloquentModelStub::create(['id_column' => 3, 'type' => 'editor']); + EloquentModelStub::create(['id_column' => 4, 'type' => 'user']); + + $rule = new Unique(table: 'table', column: 'id_column'); + $rule->whereIn(column: 'type', values: ['admin', 'moderator', 'editor']) + ->whereNotIn(column: 'type', values: ['editor']); + + $trans = $this->getIlluminateArrayTranslator(); + $v = new Validator($trans, [], ['id_column' => $rule]); + $v->setPresenceVerifier(new DatabasePresenceVerifier(Model::getConnectionResolver())); + + $v->setData(['id_column' => 1]); + $this->assertFalse($v->passes()); + + $v->setData(['id_column' => 2]); + $this->assertFalse($v->passes()); + + $v->setData(['id_column' => 3]); + $this->assertTrue($v->passes()); + + $v->setData(['id_column' => 4]); + $this->assertTrue($v->passes()); + + $v->setData(['id_column' => 5]); + $this->assertTrue($v->passes()); + } + + protected function createSchema(): void + { + $this->connection()->getSchemaBuilder()->create('table', function ($table) { + $table->unsignedInteger('id_column'); + $table->string('type'); + $table->timestamps(); + }); + } + + protected function connection(): ConnectionInterface + { + return Model::getConnectionResolver()->connection(); + } + + protected function getIlluminateArrayTranslator(): Translator + { + return new Translator( + new ArrayLoader, locale: 'en' + ); + } } class EloquentModelStub extends Model
diff --git a/tests/Validation/ValidationUniqueRuleTest.php b/tests/Validation/ValidationUniqueRuleTest.php index 740d829927a3..69a4d0933088 100644 --- a/tests/Validation/ValidationUniqueRuleTest.php +++ b/tests/Validation/ValidationUniqueRuleTest.php @@ -2,12 +2,30 @@ namespace Illuminate\Tests\Validation; +use Illuminate\Database\Capsule\Manager as DB; +use Illuminate\Database\ConnectionInterface; use Illuminate\Database\Eloquent\Model; +use Illuminate\Translation\Translator; +use Illuminate\Validation\DatabasePresenceVerifier; use Illuminate\Validation\Rules\Unique; +use Illuminate\Validation\Validator; use PHPUnit\Framework\TestCase; class ValidationUniqueRuleTest extends TestCase { + protected function setUp(): void + $db = new DB; + $db->addConnection([ + 'driver' => 'sqlite', + 'database' => ':memory:', + ]); + $db->bootEloquent(); + $this->createSchema(); public function testItCorrectlyFormatsAStringVersionOfTheRule() { $rule = new Unique('table'); @@ -129,6 +147,10 @@ public function testItHandlesWhereWithSpecialValues() $rule->where('foo', null); + $rule = new Unique('table', 'column'); + $rule->whereNot('foo', 'bar'); + $this->assertSame('unique:table,column,NULL,id,foo,"!bar"', (string) $rule); $rule = new Unique('table', 'column'); $rule->whereNull('foo'); @@ -141,6 +163,58 @@ public function testItHandlesWhereWithSpecialValues() $rule->where('foo', 0); $this->assertSame('unique:table,column,NULL,id,foo,"0"', (string) $rule); } + public function testItValidatesUniqueRuleWithWhereInAndWhereNotIn() + EloquentModelStub::create(['id_column' => 1, 'type' => 'admin']); + EloquentModelStub::create(['id_column' => 2, 'type' => 'moderator']); + EloquentModelStub::create(['id_column' => 3, 'type' => 'editor']); + EloquentModelStub::create(['id_column' => 4, 'type' => 'user']); + $rule = new Unique(table: 'table', column: 'id_column'); + $rule->whereIn(column: 'type', values: ['admin', 'moderator', 'editor']) + ->whereNotIn(column: 'type', values: ['editor']); + $trans = $this->getIlluminateArrayTranslator(); + $v->setPresenceVerifier(new DatabasePresenceVerifier(Model::getConnectionResolver())); + $v->setData(['id_column' => 2]); + $v->setData(['id_column' => 4]); + $v->setData(['id_column' => 5]); + protected function createSchema(): void + $this->connection()->getSchemaBuilder()->create('table', function ($table) { + $table->unsignedInteger('id_column'); + $table->string('type'); + }); + protected function connection(): ConnectionInterface + return Model::getConnectionResolver()->connection(); + protected function getIlluminateArrayTranslator(): Translator + return new Translator( + ); } class EloquentModelStub extends Model
[ "+use Illuminate\\Translation\\ArrayLoader;", "+ $v = new Validator($trans, [], ['id_column' => $rule]);", "+ $v->setData(['id_column' => 1]);", "+ $v->setData(['id_column' => 3]);", "+ $table->timestamps();", "+ new ArrayLoader, locale: 'en'" ]
[ 11, 63, 66, 72, 87, 99 ]
{ "additions": 74, "author": "mohammadrasoulasghari", "deletions": 0, "html_url": "https://github.com/laravel/framework/pull/55351", "issue_id": 55351, "merged_at": "2025-04-10T14:59:27Z", "omission_probability": 0.1, "pr_number": 55351, "repo": "laravel/framework", "title": "Add test for Unique validation rule with WhereIn constraints", "total_changes": 74 }
50
diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index 522577f9d8f87..a2ed0feb795a7 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -1302,7 +1302,7 @@ export namespace Core { const symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, /*useLocalSymbolForExportSpecifier*/ !isForRenameWithPrefixAndSuffixText(options)) || originalSymbol; // Compute the meaning from the location and the symbol it references - const searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : SemanticMeaning.All; + const searchMeaning = node && options.use !== FindReferencesUse.Rename ? getIntersectingMeaningFromDeclarations(node, symbol) : SemanticMeaning.All; const result: SymbolAndEntries[] = []; const state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : SpecialSearchKind.None, checker, cancellationToken, searchMeaning, options, result); diff --git a/tests/baselines/reference/findAllRefs_importType_exportEquals.baseline.jsonc b/tests/baselines/reference/findAllRefs_importType_exportEquals.baseline.jsonc index bd7279c9ebebc..0b2a8f523d40a 100644 --- a/tests/baselines/reference/findAllRefs_importType_exportEquals.baseline.jsonc +++ b/tests/baselines/reference/findAllRefs_importType_exportEquals.baseline.jsonc @@ -477,16 +477,16 @@ // === findRenameLocations === // === /a.ts === // <|type /*RENAME*/[|TRENAME|] = number;|> -// namespace T { +// <|namespace [|TRENAME|] { // export type U = string; -// } +// }|> // <|export = [|TRENAME|];|> // === findRenameLocations === // === /a.ts === -// type T = number; +// <|type [|TRENAME|] = number;|> // <|namespace /*RENAME*/[|TRENAME|] { // export type U = string; // }|> diff --git a/tests/baselines/reference/renameNamespace.baseline.jsonc b/tests/baselines/reference/renameNamespace.baseline.jsonc new file mode 100644 index 0000000000000..b85fa55d02dcc --- /dev/null +++ b/tests/baselines/reference/renameNamespace.baseline.jsonc @@ -0,0 +1,9 @@ +// === findRenameLocations === +// === /tests/cases/fourslash/renameNamespace.ts === +// <|namespace /*RENAME*/[|NSRENAME|] { +// export const enum E { +// A = 'a' +// } +// }|> +// +// const a: [|NSRENAME|].E = [|NSRENAME|].E.A; \ No newline at end of file diff --git a/tests/cases/fourslash/renameNamespace.ts b/tests/cases/fourslash/renameNamespace.ts new file mode 100644 index 0000000000000..4c6471fd7cee0 --- /dev/null +++ b/tests/cases/fourslash/renameNamespace.ts @@ -0,0 +1,11 @@ +/// <reference path='fourslash.ts'/> + +////namespace /**/NS { +//// export const enum E { +//// A = 'a' +//// } +////} +//// +////const a: NS.E = NS.E.A; + +verify.baselineRename("", { });
diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index 522577f9d8f87..a2ed0feb795a7 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -1302,7 +1302,7 @@ export namespace Core { const symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, /*useLocalSymbolForExportSpecifier*/ !isForRenameWithPrefixAndSuffixText(options)) || originalSymbol; // Compute the meaning from the location and the symbol it references + const searchMeaning = node && options.use !== FindReferencesUse.Rename ? getIntersectingMeaningFromDeclarations(node, symbol) : SemanticMeaning.All; const result: SymbolAndEntries[] = []; const state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : SpecialSearchKind.None, checker, cancellationToken, searchMeaning, options, result); diff --git a/tests/baselines/reference/findAllRefs_importType_exportEquals.baseline.jsonc b/tests/baselines/reference/findAllRefs_importType_exportEquals.baseline.jsonc index bd7279c9ebebc..0b2a8f523d40a 100644 --- a/tests/baselines/reference/findAllRefs_importType_exportEquals.baseline.jsonc +++ b/tests/baselines/reference/findAllRefs_importType_exportEquals.baseline.jsonc @@ -477,16 +477,16 @@ // <|type /*RENAME*/[|TRENAME|] = number;|> -// namespace T { +// <|namespace [|TRENAME|] { -// } // <|export = [|TRENAME|];|> -// type T = number; +// <|type [|TRENAME|] = number;|> // <|namespace /*RENAME*/[|TRENAME|] { // }|> diff --git a/tests/baselines/reference/renameNamespace.baseline.jsonc b/tests/baselines/reference/renameNamespace.baseline.jsonc index 0000000000000..b85fa55d02dcc +++ b/tests/baselines/reference/renameNamespace.baseline.jsonc @@ -0,0 +1,9 @@ +// === findRenameLocations === +// <|namespace /*RENAME*/[|NSRENAME|] { +// export const enum E { +// A = 'a' +// } +// \ No newline at end of file diff --git a/tests/cases/fourslash/renameNamespace.ts b/tests/cases/fourslash/renameNamespace.ts index 0000000000000..4c6471fd7cee0 +++ b/tests/cases/fourslash/renameNamespace.ts @@ -0,0 +1,11 @@ +/// <reference path='fourslash.ts'/> +////namespace /**/NS { +//// export const enum E { +//// A = 'a' +//// } +////} +//// +////const a: NS.E = NS.E.A; +verify.baselineRename("", { });
[ "- const searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : SemanticMeaning.All;", "+// === /tests/cases/fourslash/renameNamespace.ts ===", "+// const a: [|NSRENAME|].E = [|NSRENAME|].E.A;" ]
[ 8, 44, 51 ]
{ "additions": 24, "author": "a-tarasyuk", "deletions": 4, "html_url": "https://github.com/microsoft/TypeScript/pull/61263", "issue_id": 61263, "merged_at": "2025-04-24T21:35:05Z", "omission_probability": 0.1, "pr_number": 61263, "repo": "microsoft/TypeScript", "title": "fix(61258): Renaming namespace with const enum doesn't update enum references", "total_changes": 28 }
51
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index fcb93c45dc1dd..c10bec95be42d 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -23003,6 +23003,24 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } } + if (sourceFlags & TypeFlags.TemplateLiteral) { + if (arrayIsEqualTo((source as TemplateLiteralType).texts, (target as TemplateLiteralType).texts)) { + const sourceTypes = (source as TemplateLiteralType).types; + const targetTypes = (target as TemplateLiteralType).types; + result = Ternary.True; + for (let i = 0; i < sourceTypes.length; i++) { + if (!(result &= isRelatedTo(sourceTypes[i], targetTypes[i], RecursionFlags.Both, /*reportErrors*/ false))) { + break; + } + } + return result; + } + } + if (sourceFlags & TypeFlags.StringMapping) { + if ((source as StringMappingType).symbol === (target as StringMappingType).symbol) { + return isRelatedTo((source as StringMappingType).type, (target as StringMappingType).type, RecursionFlags.Both, /*reportErrors*/ false); + } + } if (!(sourceFlags & TypeFlags.Object)) { return Ternary.False; } diff --git a/tests/baselines/reference/assignmentToConditionalBrandedStringTemplateOrMapping.js b/tests/baselines/reference/assignmentToConditionalBrandedStringTemplateOrMapping.js new file mode 100644 index 0000000000000..4e6244df8e0e1 --- /dev/null +++ b/tests/baselines/reference/assignmentToConditionalBrandedStringTemplateOrMapping.js @@ -0,0 +1,21 @@ +//// [tests/cases/compiler/assignmentToConditionalBrandedStringTemplateOrMapping.ts] //// + +//// [assignmentToConditionalBrandedStringTemplateOrMapping.ts] +let a: (<T>() => T extends `${'a' & { a: 1 }}` ? 1 : 2) = null!; +let b: (<T>() => T extends `${'a' & { a: 1 }}` ? 1 : 2) = null!; + +a = b; + +let c: (<T>() => T extends Uppercase<'a' & { a: 1 }> ? 1 : 2) = null!; +let d: (<T>() => T extends Uppercase<'a' & { a: 1 }> ? 1 : 2) = null!; + +c = d; + + +//// [assignmentToConditionalBrandedStringTemplateOrMapping.js] +var a = null; +var b = null; +a = b; +var c = null; +var d = null; +c = d; diff --git a/tests/baselines/reference/assignmentToConditionalBrandedStringTemplateOrMapping.symbols b/tests/baselines/reference/assignmentToConditionalBrandedStringTemplateOrMapping.symbols new file mode 100644 index 0000000000000..250742a4b1986 --- /dev/null +++ b/tests/baselines/reference/assignmentToConditionalBrandedStringTemplateOrMapping.symbols @@ -0,0 +1,37 @@ +//// [tests/cases/compiler/assignmentToConditionalBrandedStringTemplateOrMapping.ts] //// + +=== assignmentToConditionalBrandedStringTemplateOrMapping.ts === +let a: (<T>() => T extends `${'a' & { a: 1 }}` ? 1 : 2) = null!; +>a : Symbol(a, Decl(assignmentToConditionalBrandedStringTemplateOrMapping.ts, 0, 3)) +>T : Symbol(T, Decl(assignmentToConditionalBrandedStringTemplateOrMapping.ts, 0, 9)) +>T : Symbol(T, Decl(assignmentToConditionalBrandedStringTemplateOrMapping.ts, 0, 9)) +>a : Symbol(a, Decl(assignmentToConditionalBrandedStringTemplateOrMapping.ts, 0, 37)) + +let b: (<T>() => T extends `${'a' & { a: 1 }}` ? 1 : 2) = null!; +>b : Symbol(b, Decl(assignmentToConditionalBrandedStringTemplateOrMapping.ts, 1, 3)) +>T : Symbol(T, Decl(assignmentToConditionalBrandedStringTemplateOrMapping.ts, 1, 9)) +>T : Symbol(T, Decl(assignmentToConditionalBrandedStringTemplateOrMapping.ts, 1, 9)) +>a : Symbol(a, Decl(assignmentToConditionalBrandedStringTemplateOrMapping.ts, 1, 37)) + +a = b; +>a : Symbol(a, Decl(assignmentToConditionalBrandedStringTemplateOrMapping.ts, 0, 3)) +>b : Symbol(b, Decl(assignmentToConditionalBrandedStringTemplateOrMapping.ts, 1, 3)) + +let c: (<T>() => T extends Uppercase<'a' & { a: 1 }> ? 1 : 2) = null!; +>c : Symbol(c, Decl(assignmentToConditionalBrandedStringTemplateOrMapping.ts, 5, 3)) +>T : Symbol(T, Decl(assignmentToConditionalBrandedStringTemplateOrMapping.ts, 5, 9)) +>T : Symbol(T, Decl(assignmentToConditionalBrandedStringTemplateOrMapping.ts, 5, 9)) +>Uppercase : Symbol(Uppercase, Decl(lib.es5.d.ts, --, --)) +>a : Symbol(a, Decl(assignmentToConditionalBrandedStringTemplateOrMapping.ts, 5, 44)) + +let d: (<T>() => T extends Uppercase<'a' & { a: 1 }> ? 1 : 2) = null!; +>d : Symbol(d, Decl(assignmentToConditionalBrandedStringTemplateOrMapping.ts, 6, 3)) +>T : Symbol(T, Decl(assignmentToConditionalBrandedStringTemplateOrMapping.ts, 6, 9)) +>T : Symbol(T, Decl(assignmentToConditionalBrandedStringTemplateOrMapping.ts, 6, 9)) +>Uppercase : Symbol(Uppercase, Decl(lib.es5.d.ts, --, --)) +>a : Symbol(a, Decl(assignmentToConditionalBrandedStringTemplateOrMapping.ts, 6, 44)) + +c = d; +>c : Symbol(c, Decl(assignmentToConditionalBrandedStringTemplateOrMapping.ts, 5, 3)) +>d : Symbol(d, Decl(assignmentToConditionalBrandedStringTemplateOrMapping.ts, 6, 3)) + diff --git a/tests/baselines/reference/assignmentToConditionalBrandedStringTemplateOrMapping.types b/tests/baselines/reference/assignmentToConditionalBrandedStringTemplateOrMapping.types new file mode 100644 index 0000000000000..61dc9b88001e7 --- /dev/null +++ b/tests/baselines/reference/assignmentToConditionalBrandedStringTemplateOrMapping.types @@ -0,0 +1,51 @@ +//// [tests/cases/compiler/assignmentToConditionalBrandedStringTemplateOrMapping.ts] //// + +=== assignmentToConditionalBrandedStringTemplateOrMapping.ts === +let a: (<T>() => T extends `${'a' & { a: 1 }}` ? 1 : 2) = null!; +>a : <T>() => T extends `${"a" & { a: 1; }}` ? 1 : 2 +> : ^ ^^^^^^^ +>a : 1 +> : ^ +>null! : null +> : ^^^^ + +let b: (<T>() => T extends `${'a' & { a: 1 }}` ? 1 : 2) = null!; +>b : <T>() => T extends `${"a" & { a: 1; }}` ? 1 : 2 +> : ^ ^^^^^^^ +>a : 1 +> : ^ +>null! : null +> : ^^^^ + +a = b; +>a = b : <T>() => T extends `${"a" & { a: 1; }}` ? 1 : 2 +> : ^ ^^^^^^^ +>a : <T>() => T extends `${"a" & { a: 1; }}` ? 1 : 2 +> : ^ ^^^^^^^ +>b : <T>() => T extends `${"a" & { a: 1; }}` ? 1 : 2 +> : ^ ^^^^^^^ + +let c: (<T>() => T extends Uppercase<'a' & { a: 1 }> ? 1 : 2) = null!; +>c : <T>() => T extends Uppercase<"a" & { a: 1; }> ? 1 : 2 +> : ^ ^^^^^^^ +>a : 1 +> : ^ +>null! : null +> : ^^^^ + +let d: (<T>() => T extends Uppercase<'a' & { a: 1 }> ? 1 : 2) = null!; +>d : <T>() => T extends Uppercase<"a" & { a: 1; }> ? 1 : 2 +> : ^ ^^^^^^^ +>a : 1 +> : ^ +>null! : null +> : ^^^^ + +c = d; +>c = d : <T>() => T extends Uppercase<"a" & { a: 1; }> ? 1 : 2 +> : ^ ^^^^^^^ +>c : <T>() => T extends Uppercase<"a" & { a: 1; }> ? 1 : 2 +> : ^ ^^^^^^^ +>d : <T>() => T extends Uppercase<"a" & { a: 1; }> ? 1 : 2 +> : ^ ^^^^^^^ + diff --git a/tests/cases/compiler/assignmentToConditionalBrandedStringTemplateOrMapping.ts b/tests/cases/compiler/assignmentToConditionalBrandedStringTemplateOrMapping.ts new file mode 100644 index 0000000000000..475e42e2f138b --- /dev/null +++ b/tests/cases/compiler/assignmentToConditionalBrandedStringTemplateOrMapping.ts @@ -0,0 +1,9 @@ +let a: (<T>() => T extends `${'a' & { a: 1 }}` ? 1 : 2) = null!; +let b: (<T>() => T extends `${'a' & { a: 1 }}` ? 1 : 2) = null!; + +a = b; + +let c: (<T>() => T extends Uppercase<'a' & { a: 1 }> ? 1 : 2) = null!; +let d: (<T>() => T extends Uppercase<'a' & { a: 1 }> ? 1 : 2) = null!; + +c = d;
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index fcb93c45dc1dd..c10bec95be42d 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -23003,6 +23003,24 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } } + if (sourceFlags & TypeFlags.TemplateLiteral) { + if (arrayIsEqualTo((source as TemplateLiteralType).texts, (target as TemplateLiteralType).texts)) { + const sourceTypes = (source as TemplateLiteralType).types; + const targetTypes = (target as TemplateLiteralType).types; + result = Ternary.True; + for (let i = 0; i < sourceTypes.length; i++) { + if (!(result &= isRelatedTo(sourceTypes[i], targetTypes[i], RecursionFlags.Both, /*reportErrors*/ false))) { + break; + } + } + return result; + if (sourceFlags & TypeFlags.StringMapping) { + if ((source as StringMappingType).symbol === (target as StringMappingType).symbol) { + return isRelatedTo((source as StringMappingType).type, (target as StringMappingType).type, RecursionFlags.Both, /*reportErrors*/ false); if (!(sourceFlags & TypeFlags.Object)) { return Ternary.False; diff --git a/tests/baselines/reference/assignmentToConditionalBrandedStringTemplateOrMapping.js b/tests/baselines/reference/assignmentToConditionalBrandedStringTemplateOrMapping.js index 0000000000000..4e6244df8e0e1 +++ b/tests/baselines/reference/assignmentToConditionalBrandedStringTemplateOrMapping.js @@ -0,0 +1,21 @@ +//// [assignmentToConditionalBrandedStringTemplateOrMapping.ts] +//// [assignmentToConditionalBrandedStringTemplateOrMapping.js] +var a = null; +var c = null; +var d = null; diff --git a/tests/baselines/reference/assignmentToConditionalBrandedStringTemplateOrMapping.symbols b/tests/baselines/reference/assignmentToConditionalBrandedStringTemplateOrMapping.symbols index 0000000000000..250742a4b1986 +++ b/tests/baselines/reference/assignmentToConditionalBrandedStringTemplateOrMapping.symbols @@ -0,0 +1,37 @@ +>a : Symbol(a, Decl(assignmentToConditionalBrandedStringTemplateOrMapping.ts, 0, 37)) +>a : Symbol(a, Decl(assignmentToConditionalBrandedStringTemplateOrMapping.ts, 1, 37)) +>a : Symbol(a, Decl(assignmentToConditionalBrandedStringTemplateOrMapping.ts, 5, 44)) +>a : Symbol(a, Decl(assignmentToConditionalBrandedStringTemplateOrMapping.ts, 6, 44)) diff --git a/tests/baselines/reference/assignmentToConditionalBrandedStringTemplateOrMapping.types b/tests/baselines/reference/assignmentToConditionalBrandedStringTemplateOrMapping.types index 0000000000000..61dc9b88001e7 +++ b/tests/baselines/reference/assignmentToConditionalBrandedStringTemplateOrMapping.types @@ -0,0 +1,51 @@ +>a = b : <T>() => T extends `${"a" & { a: 1; }}` ? 1 : 2 +> : ^ ^^^^^^^ +>c = d : <T>() => T extends Uppercase<"a" & { a: 1; }> ? 1 : 2 +> : ^ ^^^^^^^ diff --git a/tests/cases/compiler/assignmentToConditionalBrandedStringTemplateOrMapping.ts b/tests/cases/compiler/assignmentToConditionalBrandedStringTemplateOrMapping.ts index 0000000000000..475e42e2f138b +++ b/tests/cases/compiler/assignmentToConditionalBrandedStringTemplateOrMapping.ts @@ -0,0 +1,9 @@
[ "+var b = null;" ]
[ 51 ]
{ "additions": 136, "author": "HansBrende", "deletions": 0, "html_url": "https://github.com/microsoft/TypeScript/pull/61113", "issue_id": 61113, "merged_at": "2025-04-24T20:55:56Z", "omission_probability": 0.1, "pr_number": 61113, "repo": "microsoft/TypeScript", "title": "Fix #61098", "total_changes": 136 }
52
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 4856fb694e974..2cdcad6f13901 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -6127,7 +6127,6 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { }, isOptionalParameter, isUndefinedIdentifierExpression(node: Identifier) { - Debug.assert(isExpressionNode(node)); return getSymbolAtLocation(node) === undefinedSymbol; }, isEntityNameVisible(context, entityName, shouldComputeAliasToMakeVisible) { diff --git a/tests/baselines/reference/exportAssignmentExpressionIsExpressionNode.errors.txt b/tests/baselines/reference/exportAssignmentExpressionIsExpressionNode.errors.txt new file mode 100644 index 0000000000000..7a53980c7fc02 --- /dev/null +++ b/tests/baselines/reference/exportAssignmentExpressionIsExpressionNode.errors.txt @@ -0,0 +1,54 @@ +/index.ts(7,7): error TS2322: Type '{ default: { configs: { 'stage-0': PluginConfig; }; }; configs: { 'stage-0': PluginConfig; }; }' is not assignable to type 'Plugin'. + Types of property 'configs' are incompatible. + Type '{ 'stage-0': PluginConfig; }' is not assignable to type 'Record<string, { parser: string | null; }>'. + Property ''stage-0'' is incompatible with index signature. + Type 'PluginConfig' is not assignable to type '{ parser: string | null; }'. + Types of property 'parser' are incompatible. + Type 'string | null | undefined' is not assignable to type 'string | null'. + Type 'undefined' is not assignable to type 'string | null'. + + +==== /node_modules/eslint-plugin-import-x/package.json (0 errors) ==== + { + "name": "eslint-plugin-import-x", + "version": "1.0.0", + "main": "index.cjs" + } + +==== /node_modules/eslint-plugin-import-x/index.d.cts (0 errors) ==== + declare const eslintPluginImportX: typeof import("./lib/index.js"); + export = eslintPluginImportX; + +==== /node_modules/eslint-plugin-import-x/lib/index.d.ts (0 errors) ==== + interface PluginConfig { + parser?: string | null; + } + declare const configs: { + 'stage-0': PluginConfig; + }; + declare const _default: { + configs: { + 'stage-0': PluginConfig; + }; + }; + export default _default; + export { configs }; + +==== /index.ts (1 errors) ==== + import * as pluginImportX from 'eslint-plugin-import-x' + + interface Plugin { + configs?: Record<string, { parser: string | null }> + } + + const p: Plugin = pluginImportX; + ~ +!!! error TS2322: Type '{ default: { configs: { 'stage-0': PluginConfig; }; }; configs: { 'stage-0': PluginConfig; }; }' is not assignable to type 'Plugin'. +!!! error TS2322: Types of property 'configs' are incompatible. +!!! error TS2322: Type '{ 'stage-0': PluginConfig; }' is not assignable to type 'Record<string, { parser: string | null; }>'. +!!! error TS2322: Property ''stage-0'' is incompatible with index signature. +!!! error TS2322: Type 'PluginConfig' is not assignable to type '{ parser: string | null; }'. +!!! error TS2322: Types of property 'parser' are incompatible. +!!! error TS2322: Type 'string | null | undefined' is not assignable to type 'string | null'. +!!! error TS2322: Type 'undefined' is not assignable to type 'string | null'. + \ No newline at end of file diff --git a/tests/cases/compiler/exportAssignmentExpressionIsExpressionNode.ts b/tests/cases/compiler/exportAssignmentExpressionIsExpressionNode.ts new file mode 100644 index 0000000000000..76bd148f79d9f --- /dev/null +++ b/tests/cases/compiler/exportAssignmentExpressionIsExpressionNode.ts @@ -0,0 +1,39 @@ +// @strict: true +// @module: nodenext +// @noEmit: true +// @noTypesAndSymbols: true + +// @Filename: /node_modules/eslint-plugin-import-x/package.json +{ + "name": "eslint-plugin-import-x", + "version": "1.0.0", + "main": "index.cjs" +} + +// @Filename: /node_modules/eslint-plugin-import-x/index.d.cts +declare const eslintPluginImportX: typeof import("./lib/index.js"); +export = eslintPluginImportX; + +// @Filename: /node_modules/eslint-plugin-import-x/lib/index.d.ts +interface PluginConfig { + parser?: string | null; +} +declare const configs: { + 'stage-0': PluginConfig; +}; +declare const _default: { + configs: { + 'stage-0': PluginConfig; + }; +}; +export default _default; +export { configs }; + +// @Filename: /index.ts +import * as pluginImportX from 'eslint-plugin-import-x' + +interface Plugin { + configs?: Record<string, { parser: string | null }> +} + +const p: Plugin = pluginImportX;
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 4856fb694e974..2cdcad6f13901 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -6127,7 +6127,6 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { isOptionalParameter, isUndefinedIdentifierExpression(node: Identifier) { - Debug.assert(isExpressionNode(node)); return getSymbolAtLocation(node) === undefinedSymbol; isEntityNameVisible(context, entityName, shouldComputeAliasToMakeVisible) { diff --git a/tests/baselines/reference/exportAssignmentExpressionIsExpressionNode.errors.txt b/tests/baselines/reference/exportAssignmentExpressionIsExpressionNode.errors.txt index 0000000000000..7a53980c7fc02 +++ b/tests/baselines/reference/exportAssignmentExpressionIsExpressionNode.errors.txt @@ -0,0 +1,54 @@ +/index.ts(7,7): error TS2322: Type '{ default: { configs: { 'stage-0': PluginConfig; }; }; configs: { 'stage-0': PluginConfig; }; }' is not assignable to type 'Plugin'. + Types of property 'configs' are incompatible. + Type '{ 'stage-0': PluginConfig; }' is not assignable to type 'Record<string, { parser: string | null; }>'. + Property ''stage-0'' is incompatible with index signature. + Type 'PluginConfig' is not assignable to type '{ parser: string | null; }'. + Types of property 'parser' are incompatible. + Type 'string | null | undefined' is not assignable to type 'string | null'. + Type 'undefined' is not assignable to type 'string | null'. + { + "version": "1.0.0", + "main": "index.cjs" +==== /node_modules/eslint-plugin-import-x/index.d.cts (0 errors) ==== + declare const eslintPluginImportX: typeof import("./lib/index.js"); + export = eslintPluginImportX; +==== /node_modules/eslint-plugin-import-x/lib/index.d.ts (0 errors) ==== + interface PluginConfig { + parser?: string | null; + declare const configs: { + declare const _default: { + configs: { + 'stage-0': PluginConfig; + }; + export default _default; + export { configs }; +==== /index.ts (1 errors) ==== + import * as pluginImportX from 'eslint-plugin-import-x' + interface Plugin { + configs?: Record<string, { parser: string | null }> + const p: Plugin = pluginImportX; + ~ +!!! error TS2322: Types of property 'configs' are incompatible. +!!! error TS2322: Property ''stage-0'' is incompatible with index signature. +!!! error TS2322: Type 'PluginConfig' is not assignable to type '{ parser: string | null; }'. +!!! error TS2322: Types of property 'parser' are incompatible. +!!! error TS2322: Type 'string | null | undefined' is not assignable to type 'string | null'. +!!! error TS2322: Type 'undefined' is not assignable to type 'string | null'. \ No newline at end of file diff --git a/tests/cases/compiler/exportAssignmentExpressionIsExpressionNode.ts b/tests/cases/compiler/exportAssignmentExpressionIsExpressionNode.ts index 0000000000000..76bd148f79d9f +++ b/tests/cases/compiler/exportAssignmentExpressionIsExpressionNode.ts @@ -0,0 +1,39 @@ +// @strict: true +// @module: nodenext +// @noEmit: true +// @noTypesAndSymbols: true +// @Filename: /node_modules/eslint-plugin-import-x/package.json + "name": "eslint-plugin-import-x", + "version": "1.0.0", + "main": "index.cjs" +// @Filename: /node_modules/eslint-plugin-import-x/index.d.cts +declare const eslintPluginImportX: typeof import("./lib/index.js"); +export = eslintPluginImportX; +interface PluginConfig { + parser?: string | null; +declare const configs: { + 'stage-0': PluginConfig; +declare const _default: { + configs: { +export default _default; +export { configs }; +// @Filename: /index.ts +import * as pluginImportX from 'eslint-plugin-import-x' +interface Plugin { + configs?: Record<string, { parser: string | null }> +const p: Plugin = pluginImportX;
[ "+==== /node_modules/eslint-plugin-import-x/package.json (0 errors) ====", "+ \"name\": \"eslint-plugin-import-x\",", "+!!! error TS2322: Type '{ default: { configs: { 'stage-0': PluginConfig; }; }; configs: { 'stage-0': PluginConfig; }; }' is not assignable to type 'Plugin'.", "+!!! error TS2322: Type '{ 'stage-0': PluginConfig; }' is not assignable to type 'Record<string, { parser: string | null; }>'.", "+{", "+// @Filename: /node_modules/eslint-plugin-import-x/lib/index.d.ts" ]
[ 28, 30, 63, 65, 85, 95 ]
{ "additions": 93, "author": "andrewbranch", "deletions": 1, "html_url": "https://github.com/microsoft/TypeScript/pull/61582", "issue_id": 61582, "merged_at": "2025-04-16T16:43:33Z", "omission_probability": 0.1, "pr_number": 61582, "repo": "microsoft/TypeScript", "title": "Fix crash when serializing default export in error", "total_changes": 94 }
53
diff --git a/.github/workflows/accept-baselines-fix-lints.yaml b/.github/workflows/accept-baselines-fix-lints.yaml index 0b5fc8a49e306..f6b51d1d51c61 100644 --- a/.github/workflows/accept-baselines-fix-lints.yaml +++ b/.github/workflows/accept-baselines-fix-lints.yaml @@ -20,7 +20,7 @@ jobs: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: token: ${{ secrets.TS_BOT_GITHUB_TOKEN }} - - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 'lts/*' diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fbcf9e8f1cd48..9a72b16c66fc8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -51,7 +51,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - name: Use node version ${{ matrix.node-version }} - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: ${{ matrix.node-version }} check-latest: true @@ -81,7 +81,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 'lts/*' - run: npm ci @@ -95,7 +95,7 @@ jobs: name: coverage path: coverage - - uses: codecov/codecov-action@0565863a31f2c772f9f0395002a31e3f06189574 # v5.4.0 + - uses: codecov/codecov-action@ad3126e916f78f00edff4ed0317cf185271ccc2d # v5.4.2 with: use_oidc: ${{ !(github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork) }} disable_search: true @@ -106,7 +106,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 'lts/*' - run: npm ci @@ -119,7 +119,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 'lts/*' - run: npm ci @@ -132,7 +132,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 'lts/*' - run: npm ci @@ -152,7 +152,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 'lts/*' - run: npm ci @@ -168,7 +168,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 'lts/*' - run: npm ci @@ -182,7 +182,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 'lts/*' - run: | @@ -230,7 +230,7 @@ jobs: path: base ref: ${{ github.base_ref }} - - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 'lts/*' - run: | @@ -263,7 +263,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 'lts/*' - run: npm ci @@ -279,7 +279,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 'lts/*' - run: npm ci @@ -298,7 +298,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 'lts/*' - run: npm ci diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 966bb2d33bd26..026f0ebc48937 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -46,7 +46,7 @@ jobs: # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@1b549b9259bda1cb5ddde3b41741a82a2d15a841 # v3.28.13 + uses: github/codeql-action/init@45775bd8235c68ba998cffa5171334d58593da47 # v3.28.15 with: config-file: ./.github/codeql/codeql-configuration.yml # Override language selection by uncommenting this and choosing your languages @@ -56,7 +56,7 @@ jobs: # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below). - name: Autobuild - uses: github/codeql-action/autobuild@1b549b9259bda1cb5ddde3b41741a82a2d15a841 # v3.28.13 + uses: github/codeql-action/autobuild@45775bd8235c68ba998cffa5171334d58593da47 # v3.28.15 # ℹ️ Command-line programs to run using the OS shell. # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun @@ -70,4 +70,4 @@ jobs: # make release - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@1b549b9259bda1cb5ddde3b41741a82a2d15a841 # v3.28.13 + uses: github/codeql-action/analyze@45775bd8235c68ba998cffa5171334d58593da47 # v3.28.15 diff --git a/.github/workflows/insiders.yaml b/.github/workflows/insiders.yaml index 330ff6d42ee55..0069d5f476c0e 100644 --- a/.github/workflows/insiders.yaml +++ b/.github/workflows/insiders.yaml @@ -21,7 +21,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 'lts/*' - run: | @@ -43,7 +43,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 'lts/*' # Use NODE_AUTH_TOKEN environment variable to authenticate to this registry. diff --git a/.github/workflows/lkg.yml b/.github/workflows/lkg.yml index 734474388bd5d..427a78afbb313 100644 --- a/.github/workflows/lkg.yml +++ b/.github/workflows/lkg.yml @@ -31,7 +31,7 @@ jobs: with: ref: ${{ inputs.branch_name }} token: ${{ secrets.TS_BOT_GITHUB_TOKEN }} - - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 'lts/*' - run: | diff --git a/.github/workflows/new-release-branch.yaml b/.github/workflows/new-release-branch.yaml index 91a857b652ecb..6cc38b0289173 100644 --- a/.github/workflows/new-release-branch.yaml +++ b/.github/workflows/new-release-branch.yaml @@ -55,7 +55,7 @@ jobs: filter: blob:none # https://github.blog/2020-12-21-get-up-to-speed-with-partial-clone-and-shallow-clone/ fetch-depth: 0 # Default is 1; need to set to 0 to get the benefits of blob:none. token: ${{ secrets.TS_BOT_GITHUB_TOKEN }} - - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 'lts/*' - run: | diff --git a/.github/workflows/nightly.yaml b/.github/workflows/nightly.yaml index 21af15be711ed..2cba9873132bd 100644 --- a/.github/workflows/nightly.yaml +++ b/.github/workflows/nightly.yaml @@ -22,7 +22,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 'lts/*' - run: | @@ -43,7 +43,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 'lts/*' # Use NODE_AUTH_TOKEN environment variable to authenticate to this registry. diff --git a/.github/workflows/release-branch-artifact.yaml b/.github/workflows/release-branch-artifact.yaml index 693166d5f8949..4cdafd08f49d4 100644 --- a/.github/workflows/release-branch-artifact.yaml +++ b/.github/workflows/release-branch-artifact.yaml @@ -20,7 +20,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 'lts/*' - run: | diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml index 4aed0e4ac752d..6f55e8a5d49f2 100644 --- a/.github/workflows/scorecard.yml +++ b/.github/workflows/scorecard.yml @@ -55,6 +55,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: 'Upload to code-scanning' - uses: github/codeql-action/upload-sarif@1b549b9259bda1cb5ddde3b41741a82a2d15a841 # v3.28.13 + uses: github/codeql-action/upload-sarif@45775bd8235c68ba998cffa5171334d58593da47 # v3.28.15 with: sarif_file: results.sarif diff --git a/.github/workflows/set-version.yaml b/.github/workflows/set-version.yaml index 4aede772d5900..5c6834ce14674 100644 --- a/.github/workflows/set-version.yaml +++ b/.github/workflows/set-version.yaml @@ -53,7 +53,7 @@ jobs: with: ref: ${{ inputs.branch_name }} token: ${{ secrets.TS_BOT_GITHUB_TOKEN }} - - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 'lts/*' - run: | diff --git a/.github/workflows/sync-branch.yaml b/.github/workflows/sync-branch.yaml index 391f3e50edeae..770e2e8dff0b9 100644 --- a/.github/workflows/sync-branch.yaml +++ b/.github/workflows/sync-branch.yaml @@ -42,7 +42,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 'lts/*' - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 diff --git a/.github/workflows/twoslash-repros.yaml b/.github/workflows/twoslash-repros.yaml index 93cb170c8a673..74f6c5f5c058a 100644 --- a/.github/workflows/twoslash-repros.yaml +++ b/.github/workflows/twoslash-repros.yaml @@ -55,7 +55,7 @@ jobs: fetch-depth: 0 # Default is 1; need to set to 0 to get the benefits of blob:none. - if: ${{ !github.event.inputs.bisect }} uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 'lts/*' - uses: microsoft/TypeScript-Twoslash-Repro-Action@master diff --git a/.github/workflows/update-package-lock.yaml b/.github/workflows/update-package-lock.yaml index 7ed7da675044c..a7323313a3a15 100644 --- a/.github/workflows/update-package-lock.yaml +++ b/.github/workflows/update-package-lock.yaml @@ -25,7 +25,7 @@ jobs: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: token: ${{ secrets.TS_BOT_GITHUB_TOKEN }} - - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 'lts/*' - run: |
diff --git a/.github/workflows/accept-baselines-fix-lints.yaml b/.github/workflows/accept-baselines-fix-lints.yaml index 0b5fc8a49e306..f6b51d1d51c61 100644 --- a/.github/workflows/accept-baselines-fix-lints.yaml +++ b/.github/workflows/accept-baselines-fix-lints.yaml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fbcf9e8f1cd48..9a72b16c66fc8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -51,7 +51,7 @@ jobs: - name: Use node version ${{ matrix.node-version }} - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 node-version: ${{ matrix.node-version }} check-latest: true @@ -81,7 +81,7 @@ jobs: @@ -95,7 +95,7 @@ jobs: name: coverage path: coverage - - uses: codecov/codecov-action@0565863a31f2c772f9f0395002a31e3f06189574 # v5.4.0 + - uses: codecov/codecov-action@ad3126e916f78f00edff4ed0317cf185271ccc2d # v5.4.2 use_oidc: ${{ !(github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork) }} disable_search: true @@ -106,7 +106,7 @@ jobs: @@ -119,7 +119,7 @@ jobs: @@ -132,7 +132,7 @@ jobs: @@ -152,7 +152,7 @@ jobs: @@ -168,7 +168,7 @@ jobs: @@ -182,7 +182,7 @@ jobs: @@ -230,7 +230,7 @@ jobs: path: base ref: ${{ github.base_ref }} @@ -263,7 +263,7 @@ jobs: @@ -279,7 +279,7 @@ jobs: @@ -298,7 +298,7 @@ jobs: diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 966bb2d33bd26..026f0ebc48937 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -46,7 +46,7 @@ jobs: # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@1b549b9259bda1cb5ddde3b41741a82a2d15a841 # v3.28.13 + uses: github/codeql-action/init@45775bd8235c68ba998cffa5171334d58593da47 # v3.28.15 config-file: ./.github/codeql/codeql-configuration.yml # Override language selection by uncommenting this and choosing your languages @@ -56,7 +56,7 @@ jobs: # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below). - name: Autobuild - uses: github/codeql-action/autobuild@1b549b9259bda1cb5ddde3b41741a82a2d15a841 # v3.28.13 # ℹ️ Command-line programs to run using the OS shell. # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun @@ -70,4 +70,4 @@ jobs: # make release - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@1b549b9259bda1cb5ddde3b41741a82a2d15a841 # v3.28.13 + uses: github/codeql-action/analyze@45775bd8235c68ba998cffa5171334d58593da47 # v3.28.15 diff --git a/.github/workflows/insiders.yaml b/.github/workflows/insiders.yaml index 330ff6d42ee55..0069d5f476c0e 100644 --- a/.github/workflows/insiders.yaml +++ b/.github/workflows/insiders.yaml @@ -21,7 +21,7 @@ jobs: diff --git a/.github/workflows/lkg.yml b/.github/workflows/lkg.yml index 734474388bd5d..427a78afbb313 100644 --- a/.github/workflows/lkg.yml +++ b/.github/workflows/lkg.yml @@ -31,7 +31,7 @@ jobs: diff --git a/.github/workflows/new-release-branch.yaml b/.github/workflows/new-release-branch.yaml index 91a857b652ecb..6cc38b0289173 100644 --- a/.github/workflows/new-release-branch.yaml +++ b/.github/workflows/new-release-branch.yaml filter: blob:none # https://github.blog/2020-12-21-get-up-to-speed-with-partial-clone-and-shallow-clone/ diff --git a/.github/workflows/nightly.yaml b/.github/workflows/nightly.yaml index 21af15be711ed..2cba9873132bd 100644 --- a/.github/workflows/nightly.yaml +++ b/.github/workflows/nightly.yaml @@ -22,7 +22,7 @@ jobs: diff --git a/.github/workflows/release-branch-artifact.yaml b/.github/workflows/release-branch-artifact.yaml index 693166d5f8949..4cdafd08f49d4 100644 --- a/.github/workflows/release-branch-artifact.yaml +++ b/.github/workflows/release-branch-artifact.yaml diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml index 4aed0e4ac752d..6f55e8a5d49f2 100644 --- a/.github/workflows/scorecard.yml +++ b/.github/workflows/scorecard.yml @@ -55,6 +55,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: 'Upload to code-scanning' - uses: github/codeql-action/upload-sarif@1b549b9259bda1cb5ddde3b41741a82a2d15a841 # v3.28.13 + uses: github/codeql-action/upload-sarif@45775bd8235c68ba998cffa5171334d58593da47 # v3.28.15 sarif_file: results.sarif diff --git a/.github/workflows/set-version.yaml b/.github/workflows/set-version.yaml index 4aede772d5900..5c6834ce14674 100644 --- a/.github/workflows/set-version.yaml +++ b/.github/workflows/set-version.yaml @@ -53,7 +53,7 @@ jobs: diff --git a/.github/workflows/sync-branch.yaml b/.github/workflows/sync-branch.yaml index 391f3e50edeae..770e2e8dff0b9 100644 --- a/.github/workflows/sync-branch.yaml +++ b/.github/workflows/sync-branch.yaml @@ -42,7 +42,7 @@ jobs: runs-on: ubuntu-latest diff --git a/.github/workflows/twoslash-repros.yaml b/.github/workflows/twoslash-repros.yaml index 93cb170c8a673..74f6c5f5c058a 100644 --- a/.github/workflows/twoslash-repros.yaml +++ b/.github/workflows/twoslash-repros.yaml - if: ${{ !github.event.inputs.bisect }} uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - uses: microsoft/TypeScript-Twoslash-Repro-Action@master diff --git a/.github/workflows/update-package-lock.yaml b/.github/workflows/update-package-lock.yaml index 7ed7da675044c..a7323313a3a15 100644 --- a/.github/workflows/update-package-lock.yaml +++ b/.github/workflows/update-package-lock.yaml @@ -25,7 +25,7 @@ jobs:
[ "+ uses: github/codeql-action/autobuild@45775bd8235c68ba998cffa5171334d58593da47 # v3.28.15" ]
[ 152 ]
{ "additions": 29, "author": "dependabot[bot]", "deletions": 29, "html_url": "https://github.com/microsoft/TypeScript/pull/61601", "issue_id": 61601, "merged_at": "2025-04-21T17:15:39Z", "omission_probability": 0.1, "pr_number": 61601, "repo": "microsoft/TypeScript", "title": "Bump the github-actions group across 1 directory with 3 updates", "total_changes": 58 }
54
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 7f18bbc1a1dec..f5c2ba822e1da 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -15504,6 +15504,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { isInJSFile(declaration) && isValueSignatureDeclaration(declaration) && !hasJSDocParameterTags(declaration) && + !some(declaration.parameters, p => !!getJSDocType(p)) && !getJSDocType(declaration) && !getContextualSignatureForFunctionLikeDeclaration(declaration); if (isUntypedSignatureInJSFile) { diff --git a/tests/baselines/reference/jsdocTypeTagOnParameter1.symbols b/tests/baselines/reference/jsdocTypeTagOnParameter1.symbols new file mode 100644 index 0000000000000..3f6099b16adc2 --- /dev/null +++ b/tests/baselines/reference/jsdocTypeTagOnParameter1.symbols @@ -0,0 +1,31 @@ +//// [tests/cases/conformance/jsdoc/jsdocTypeTagOnParameter1.ts] //// + +=== /index.js === +function repeat( +>repeat : Symbol(repeat, Decl(index.js, 0, 0)) + + /** @type {string} */ message, +>message : Symbol(message, Decl(index.js, 0, 16)) + + /** @type {number} */ times, +>times : Symbol(times, Decl(index.js, 1, 31)) + +) { + return Array(times).fill(message).join(` `); +>Array(times).fill(message).join : Symbol(Array.join, Decl(lib.es5.d.ts, --, --)) +>Array(times).fill : Symbol(Array.fill, Decl(lib.es2015.core.d.ts, --, --)) +>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --) ... and 4 more) +>times : Symbol(times, Decl(index.js, 1, 31)) +>fill : Symbol(Array.fill, Decl(lib.es2015.core.d.ts, --, --)) +>message : Symbol(message, Decl(index.js, 0, 16)) +>join : Symbol(Array.join, Decl(lib.es5.d.ts, --, --)) +} + +/** @type {Parameters<typeof repeat>[0]} */ +const message = `hello`; +>message : Symbol(message, Decl(index.js, 8, 5)) + +/** @type {Parameters<typeof repeat>[1]} */ +const times = 3; +>times : Symbol(times, Decl(index.js, 11, 5)) + diff --git a/tests/baselines/reference/jsdocTypeTagOnParameter1.types b/tests/baselines/reference/jsdocTypeTagOnParameter1.types new file mode 100644 index 0000000000000..5b3b0ea8855af --- /dev/null +++ b/tests/baselines/reference/jsdocTypeTagOnParameter1.types @@ -0,0 +1,55 @@ +//// [tests/cases/conformance/jsdoc/jsdocTypeTagOnParameter1.ts] //// + +=== /index.js === +function repeat( +>repeat : (message: string, times: number) => string +> : ^ ^^ ^^ ^^ ^^^^^^^^^^^ + + /** @type {string} */ message, +>message : string +> : ^^^^^^ + + /** @type {number} */ times, +>times : number +> : ^^^^^^ + +) { + return Array(times).fill(message).join(` `); +>Array(times).fill(message).join(` `) : string +> : ^^^^^^ +>Array(times).fill(message).join : (separator?: string) => string +> : ^ ^^^ ^^^^^ +>Array(times).fill(message) : any[] +> : ^^^^^ +>Array(times).fill : (value: any, start?: number, end?: number) => any[] +> : ^ ^^^^^^^ ^^^ ^^ ^^^ ^^^^^^^^^^ +>Array(times) : any[] +> : ^^^^^ +>Array : ArrayConstructor +> : ^^^^^^^^^^^^^^^^ +>times : number +> : ^^^^^^ +>fill : (value: any, start?: number, end?: number) => any[] +> : ^ ^^^^^^^ ^^^ ^^ ^^^ ^^^^^^^^^^ +>message : string +> : ^^^^^^ +>join : (separator?: string) => string +> : ^ ^^^ ^^^^^ +>` ` : " " +> : ^^^ +} + +/** @type {Parameters<typeof repeat>[0]} */ +const message = `hello`; +>message : string +> : ^^^^^^ +>`hello` : "hello" +> : ^^^^^^^ + +/** @type {Parameters<typeof repeat>[1]} */ +const times = 3; +>times : number +> : ^^^^^^ +>3 : 3 +> : ^ + diff --git a/tests/cases/conformance/jsdoc/jsdocTypeTagOnParameter1.ts b/tests/cases/conformance/jsdoc/jsdocTypeTagOnParameter1.ts new file mode 100644 index 0000000000000..3dec04c0432a2 --- /dev/null +++ b/tests/cases/conformance/jsdoc/jsdocTypeTagOnParameter1.ts @@ -0,0 +1,21 @@ +// @strict: true +// @lib: esnext +// @allowJS: true +// @checkJs: true +// @noEmit: true + +// https://github.com/microsoft/TypeScript/issues/61172 + +// @filename: /index.js +function repeat( + /** @type {string} */ message, + /** @type {number} */ times, +) { + return Array(times).fill(message).join(` `); +} + +/** @type {Parameters<typeof repeat>[0]} */ +const message = `hello`; + +/** @type {Parameters<typeof repeat>[1]} */ +const times = 3;
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 7f18bbc1a1dec..f5c2ba822e1da 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -15504,6 +15504,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { isInJSFile(declaration) && isValueSignatureDeclaration(declaration) && !hasJSDocParameterTags(declaration) && + !some(declaration.parameters, p => !!getJSDocType(p)) && !getJSDocType(declaration) && !getContextualSignatureForFunctionLikeDeclaration(declaration); if (isUntypedSignatureInJSFile) { diff --git a/tests/baselines/reference/jsdocTypeTagOnParameter1.symbols b/tests/baselines/reference/jsdocTypeTagOnParameter1.symbols index 0000000000000..3f6099b16adc2 +++ b/tests/baselines/reference/jsdocTypeTagOnParameter1.symbols @@ -0,0 +1,31 @@ +>repeat : Symbol(repeat, Decl(index.js, 0, 0)) +>Array(times).fill(message).join : Symbol(Array.join, Decl(lib.es5.d.ts, --, --)) +>Array(times).fill : Symbol(Array.fill, Decl(lib.es2015.core.d.ts, --, --)) +>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --) ... and 4 more) +>fill : Symbol(Array.fill, Decl(lib.es2015.core.d.ts, --, --)) +>join : Symbol(Array.join, Decl(lib.es5.d.ts, --, --)) +>message : Symbol(message, Decl(index.js, 8, 5)) +>times : Symbol(times, Decl(index.js, 11, 5)) diff --git a/tests/baselines/reference/jsdocTypeTagOnParameter1.types b/tests/baselines/reference/jsdocTypeTagOnParameter1.types index 0000000000000..5b3b0ea8855af +++ b/tests/baselines/reference/jsdocTypeTagOnParameter1.types @@ -0,0 +1,55 @@ +>repeat : (message: string, times: number) => string +> : ^ ^^ ^^ ^^ ^^^^^^^^^^^ +>Array(times).fill(message).join(` `) : string +> : ^^^^^^ +>Array(times).fill(message).join : (separator?: string) => string +> : ^ ^^^ ^^^^^ +>Array(times).fill(message) : any[] +> : ^^^^^ +>Array(times).fill : (value: any, start?: number, end?: number) => any[] +> : ^ ^^^^^^^ ^^^ ^^ ^^^ ^^^^^^^^^^ +>Array(times) : any[] +> : ^^^^^ +>Array : ArrayConstructor +> : ^^^^^^^^^^^^^^^^ +>fill : (value: any, start?: number, end?: number) => any[] +>join : (separator?: string) => string +> : ^ ^^^ ^^^^^ +>` ` : " " +>`hello` : "hello" +> : ^^^^^^^ +>3 : 3 +> : ^ diff --git a/tests/cases/conformance/jsdoc/jsdocTypeTagOnParameter1.ts b/tests/cases/conformance/jsdoc/jsdocTypeTagOnParameter1.ts index 0000000000000..3dec04c0432a2 +++ b/tests/cases/conformance/jsdoc/jsdocTypeTagOnParameter1.ts @@ -0,0 +1,21 @@ +// @strict: true +// @lib: esnext +// @allowJS: true +// @noEmit: true +// https://github.com/microsoft/TypeScript/issues/61172 +// @filename: /index.js
[ "+> : ^ ^^^^^^^ ^^^ ^^ ^^^ ^^^^^^^^^^", "+> : ^^^", "+// @checkJs: true" ]
[ 87, 93, 119 ]
{ "additions": 108, "author": "Andarist", "deletions": 0, "html_url": "https://github.com/microsoft/TypeScript/pull/61177", "issue_id": 61177, "merged_at": "2025-04-14T22:35:21Z", "omission_probability": 0.1, "pr_number": 61177, "repo": "microsoft/TypeScript", "title": "Treat functions with `@type` tags on parameters as typed in JS files", "total_changes": 108 }
55
diff --git a/azure-pipelines.release-publish.yml b/azure-pipelines.release-publish.yml index c928166efb115..2f3aac21446cc 100644 --- a/azure-pipelines.release-publish.yml +++ b/azure-pipelines.release-publish.yml @@ -1,15 +1,25 @@ trigger: none pr: none +parameters: + - name: _REMINDER + default: Review & undraft the release at https://github.com/microsoft/TypeScript/releases once it appears! + - name: PUBLISH_TAG + default: dev + - name: RELEASE_TITLE_NAME + default: 0.0.0 Test + - name: TAG_NAME + default: v0.0.0-SetMe + variables: - name: _REMINDER - value: Review & undraft the release at https://github.com/microsoft/TypeScript/releases once it appears! + value: ${{ parameters._REMINDER }} - name: PUBLISH_TAG - value: dev + value: ${{ parameters.PUBLISH_TAG }} - name: RELEASE_TITLE_NAME - value: 0.0.0 Test + value: ${{ parameters.RELEASE_TITLE_NAME }} - name: TAG_NAME - value: v0.0.0-SetMe + value: ${{ parameters.TAG_NAME }} resources: pipelines: @@ -54,6 +64,7 @@ extends: artifactName: 'tgz' targetPath: '$(Pipeline.Workspace)/tgz' steps: + - checkout: none - task: CmdLine@2 displayName: Rename versioned drop to typescript.tgz inputs: @@ -68,6 +79,7 @@ extends: workingDir: $(Pipeline.Workspace)/tgz verbose: false customCommand: publish $(Pipeline.Workspace)/tgz/typescript.tgz --tag $(PUBLISH_TAG) + # This must match the service connection. customEndpoint: Typescript NPM publishEndpoint: Typescript NPM @@ -88,9 +100,11 @@ extends: artifactName: 'tgz' targetPath: '$(Pipeline.Workspace)/tgz' steps: + - checkout: none - task: GitHubRelease@1 displayName: GitHub release (create) inputs: + # This must match the service connection. gitHubConnection: typescript-bot connection repositoryName: microsoft/TypeScript tagSource: userSpecifiedTag @@ -101,7 +115,7 @@ extends: For release notes, check out the [release announcement](). For new features, check out the [What's new in TypeScript $(TAG_NAME)](). For the complete list of fixed issues, check out the - * [fixed issues query for Typescript $(TAG_NAME)](https://github.com/microsoft/TypeScript/issues?utf8=%E2%9C%93&q=is%3Aissue+milestone%3A%22TypeScript+3.3%22+is%3Aclosed+). + * [fixed issues query for TypeScript $(TAG_NAME)](https://github.com/microsoft/TypeScript/issues?utf8=%E2%9C%93&q=is%3Aissue+milestone%3A%22TypeScript+3.3%22+is%3Aclosed+). Downloads are available on: * [npm](https://www.npmjs.com/package/typescript) assets: $(Pipeline.Workspace)/tgz/**/typescript-*.tgz
diff --git a/azure-pipelines.release-publish.yml b/azure-pipelines.release-publish.yml index c928166efb115..2f3aac21446cc 100644 --- a/azure-pipelines.release-publish.yml +++ b/azure-pipelines.release-publish.yml @@ -1,15 +1,25 @@ trigger: none pr: none +parameters: + - name: _REMINDER + default: Review & undraft the release at https://github.com/microsoft/TypeScript/releases once it appears! + - name: PUBLISH_TAG + default: dev + - name: RELEASE_TITLE_NAME + default: 0.0.0 Test + default: v0.0.0-SetMe + variables: - name: _REMINDER - value: Review & undraft the release at https://github.com/microsoft/TypeScript/releases once it appears! + value: ${{ parameters._REMINDER }} - name: PUBLISH_TAG - value: dev + value: ${{ parameters.PUBLISH_TAG }} - name: RELEASE_TITLE_NAME - value: 0.0.0 Test + value: ${{ parameters.RELEASE_TITLE_NAME }} - name: TAG_NAME - value: v0.0.0-SetMe + value: ${{ parameters.TAG_NAME }} resources: pipelines: @@ -54,6 +64,7 @@ extends: - task: CmdLine@2 displayName: Rename versioned drop to typescript.tgz @@ -68,6 +79,7 @@ extends: workingDir: $(Pipeline.Workspace)/tgz verbose: false customCommand: publish $(Pipeline.Workspace)/tgz/typescript.tgz --tag $(PUBLISH_TAG) customEndpoint: Typescript NPM publishEndpoint: Typescript NPM @@ -88,9 +100,11 @@ extends: - task: GitHubRelease@1 displayName: GitHub release (create) gitHubConnection: typescript-bot connection repositoryName: microsoft/TypeScript tagSource: userSpecifiedTag @@ -101,7 +115,7 @@ extends: For release notes, check out the [release announcement](). For new features, check out the [What's new in TypeScript $(TAG_NAME)](). For the complete list of fixed issues, check out the - * [fixed issues query for Typescript $(TAG_NAME)](https://github.com/microsoft/TypeScript/issues?utf8=%E2%9C%93&q=is%3Aissue+milestone%3A%22TypeScript+3.3%22+is%3Aclosed+). + * [fixed issues query for TypeScript $(TAG_NAME)](https://github.com/microsoft/TypeScript/issues?utf8=%E2%9C%93&q=is%3Aissue+milestone%3A%22TypeScript+3.3%22+is%3Aclosed+). Downloads are available on: * [npm](https://www.npmjs.com/package/typescript) assets: $(Pipeline.Workspace)/tgz/**/typescript-*.tgz
[ "+ - name: TAG_NAME" ]
[ 15 ]
{ "additions": 19, "author": "jakebailey", "deletions": 5, "html_url": "https://github.com/microsoft/TypeScript/pull/61523", "issue_id": 61523, "merged_at": "2025-04-04T19:22:19Z", "omission_probability": 0.1, "pr_number": 61523, "repo": "microsoft/TypeScript", "title": "Convert release publishing inputs into parameters", "total_changes": 24 }
56
diff --git a/src/services/completions.ts b/src/services/completions.ts index 30e9ad40bf3f1..dd623aadeb156 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -2745,8 +2745,14 @@ export function getCompletionEntriesFromSymbols( } // Filter out variables from their own initializers // `const a = /* no 'a' here */` - if (tryCast(closestSymbolDeclaration, isVariableDeclaration) && symbol.valueDeclaration === closestSymbolDeclaration) { - return false; + if (closestSymbolDeclaration && tryCast(closestSymbolDeclaration, isVariableDeclaration)) { + if (symbol.valueDeclaration === closestSymbolDeclaration) { + return false; + } + // const { a } = /* no 'a' here */; + if (isBindingPattern(closestSymbolDeclaration.name) && closestSymbolDeclaration.name.elements.some(e => e === symbol.valueDeclaration)) { + return false; + } } // Filter out current and latter parameters from defaults diff --git a/tests/cases/fourslash/completionListWithoutVariableinitializer.ts b/tests/cases/fourslash/completionListWithoutVariableinitializer.ts index 5d2a95b743cca..cba6743f3f6c0 100644 --- a/tests/cases/fourslash/completionListWithoutVariableinitializer.ts +++ b/tests/cases/fourslash/completionListWithoutVariableinitializer.ts @@ -9,6 +9,10 @@ //// const fn = (p = /*7*/) => {} //// const { g, h = /*8*/ } = { ... } //// const [ g1, h1 = /*9*/ ] = [ ... ] +//// const { a1 } = a/*10*/; +//// const { a2 } = fn({a: a/*11*/}); +//// const [ a3 ] = a/*12*/; +//// const [ a4 ] = fn([a/*13*/]); verify.completions({ marker: ["1"], @@ -58,3 +62,26 @@ verify.completions({ marker: ["9"], includes: ["a", "b", "c", "d", "e", "fn"], }); + +verify.completions({ + marker: ["10"], + excludes: ["a1"], + isNewIdentifierLocation: true, +}); + +verify.completions({ + marker: ["11"], + excludes: ["a2"], +}); + +verify.completions({ + marker: ["12"], + excludes: ["a3"], + isNewIdentifierLocation: true, +}); + +verify.completions({ + marker: ["13"], + excludes: ["a4"], + isNewIdentifierLocation: true, +});
diff --git a/src/services/completions.ts b/src/services/completions.ts index 30e9ad40bf3f1..dd623aadeb156 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -2745,8 +2745,14 @@ export function getCompletionEntriesFromSymbols( // Filter out variables from their own initializers // `const a = /* no 'a' here */` - if (tryCast(closestSymbolDeclaration, isVariableDeclaration) && symbol.valueDeclaration === closestSymbolDeclaration) { - return false; + if (closestSymbolDeclaration && tryCast(closestSymbolDeclaration, isVariableDeclaration)) { + if (symbol.valueDeclaration === closestSymbolDeclaration) { + // const { a } = /* no 'a' here */; + if (isBindingPattern(closestSymbolDeclaration.name) && closestSymbolDeclaration.name.elements.some(e => e === symbol.valueDeclaration)) { // Filter out current and latter parameters from defaults diff --git a/tests/cases/fourslash/completionListWithoutVariableinitializer.ts b/tests/cases/fourslash/completionListWithoutVariableinitializer.ts index 5d2a95b743cca..cba6743f3f6c0 100644 --- a/tests/cases/fourslash/completionListWithoutVariableinitializer.ts +++ b/tests/cases/fourslash/completionListWithoutVariableinitializer.ts @@ -9,6 +9,10 @@ //// const fn = (p = /*7*/) => {} //// const { g, h = /*8*/ } = { ... } //// const [ g1, h1 = /*9*/ ] = [ ... ] +//// const { a2 } = fn({a: a/*11*/}); +//// const [ a3 ] = a/*12*/; +//// const [ a4 ] = fn([a/*13*/]); verify.completions({ marker: ["1"], @@ -58,3 +62,26 @@ verify.completions({ marker: ["9"], includes: ["a", "b", "c", "d", "e", "fn"], }); + marker: ["10"], + excludes: ["a1"], + marker: ["11"], + excludes: ["a2"], + marker: ["12"], + excludes: ["a3"], + marker: ["13"], + excludes: ["a4"],
[ "+//// const { a1 } = a/*10*/;" ]
[ 29 ]
{ "additions": 35, "author": "zardoy", "deletions": 2, "html_url": "https://github.com/microsoft/TypeScript/pull/52723", "issue_id": 52723, "merged_at": "2025-04-02T20:47:43Z", "omission_probability": 0.1, "pr_number": 52723, "repo": "microsoft/TypeScript", "title": "Exclude completions of binding pattern variable initializers", "total_changes": 37 }
57
diff --git a/src/services/symbolDisplay.ts b/src/services/symbolDisplay.ts index 0524d150972bc..8a0a9719a940f 100644 --- a/src/services/symbolDisplay.ts +++ b/src/services/symbolDisplay.ts @@ -1,4 +1,5 @@ import { + AccessorDeclaration, addRange, arrayFrom, BinaryExpression, @@ -16,7 +17,6 @@ import { first, firstDefined, forEach, - GetAccessorDeclaration, getCombinedLocalAndExportSymbolFlags, getDeclarationOfKind, getExternalModuleImportEqualsDeclarationExpression, @@ -83,7 +83,6 @@ import { ScriptElementKind, ScriptElementKindModifier, SemanticMeaning, - SetAccessorDeclaration, Signature, SignatureDeclaration, SignatureFlags, @@ -276,7 +275,14 @@ function getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker: Type if (symbolKind !== ScriptElementKind.unknown || symbolFlags & SymbolFlags.Class || symbolFlags & SymbolFlags.Alias) { // If symbol is accessor, they are allowed only if location is at declaration identifier of the accessor if (symbolKind === ScriptElementKind.memberGetAccessorElement || symbolKind === ScriptElementKind.memberSetAccessorElement) { - const declaration = find(symbol.declarations as ((GetAccessorDeclaration | SetAccessorDeclaration | PropertyDeclaration)[]), declaration => declaration.name === location); + const declaration = find( + symbol.declarations as (AccessorDeclaration | PropertyDeclaration | PropertyAccessExpression)[], + (declaration): declaration is AccessorDeclaration | PropertyDeclaration => + declaration.name === location + // an expando member could have been added to an object with a set accessor + // we need to ignore such write location as it shouldn't be displayed as `(setter)` anyway + && declaration.kind !== SyntaxKind.PropertyAccessExpression, + ); if (declaration) { switch (declaration.kind) { case SyntaxKind.GetAccessor: diff --git a/tests/cases/fourslash/quickInfoOnExpandoLikePropertyWithSetterDeclarationJs1.ts b/tests/cases/fourslash/quickInfoOnExpandoLikePropertyWithSetterDeclarationJs1.ts new file mode 100644 index 0000000000000..70fdf451007fd --- /dev/null +++ b/tests/cases/fourslash/quickInfoOnExpandoLikePropertyWithSetterDeclarationJs1.ts @@ -0,0 +1,16 @@ +/// <reference path="fourslash.ts" /> + +// @strict: true +// @checkJs: true +// @filename: index.js + +//// const x = {}; +//// +//// Object.defineProperty(x, "foo", { +//// /** @param {number} v */ +//// set(v) {}, +//// }); +//// +//// x.foo/**/ = 1; + +verify.quickInfoAt("", "(property) x.foo: number"); diff --git a/tests/cases/fourslash/quickInfoOnExpandoLikePropertyWithSetterDeclarationJs2.ts b/tests/cases/fourslash/quickInfoOnExpandoLikePropertyWithSetterDeclarationJs2.ts new file mode 100644 index 0000000000000..9bd9548be8aa1 --- /dev/null +++ b/tests/cases/fourslash/quickInfoOnExpandoLikePropertyWithSetterDeclarationJs2.ts @@ -0,0 +1,19 @@ +/// <reference path="fourslash.ts" /> + +// @strict: true +// @checkJs: true +// @filename: index.js + +//// const obj = {}; +//// let val = 10; +//// Object.defineProperty(obj, "a", { +//// configurable: true, +//// enumerable: true, +//// set(v) { +//// val = v; +//// }, +//// }); +//// +//// obj.a/**/ = 100; + +verify.quickInfoAt("", "(property) obj.a: any");
diff --git a/src/services/symbolDisplay.ts b/src/services/symbolDisplay.ts index 0524d150972bc..8a0a9719a940f 100644 --- a/src/services/symbolDisplay.ts +++ b/src/services/symbolDisplay.ts @@ -1,4 +1,5 @@ import { + AccessorDeclaration, addRange, arrayFrom, BinaryExpression, @@ -16,7 +17,6 @@ import { first, firstDefined, forEach, - GetAccessorDeclaration, getCombinedLocalAndExportSymbolFlags, getDeclarationOfKind, getExternalModuleImportEqualsDeclarationExpression, @@ -83,7 +83,6 @@ import { ScriptElementKind, ScriptElementKindModifier, SemanticMeaning, - SetAccessorDeclaration, Signature, SignatureDeclaration, SignatureFlags, @@ -276,7 +275,14 @@ function getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker: Type if (symbolKind !== ScriptElementKind.unknown || symbolFlags & SymbolFlags.Class || symbolFlags & SymbolFlags.Alias) { // If symbol is accessor, they are allowed only if location is at declaration identifier of the accessor if (symbolKind === ScriptElementKind.memberGetAccessorElement || symbolKind === ScriptElementKind.memberSetAccessorElement) { - const declaration = find(symbol.declarations as ((GetAccessorDeclaration | SetAccessorDeclaration | PropertyDeclaration)[]), declaration => declaration.name === location); + const declaration = find( + symbol.declarations as (AccessorDeclaration | PropertyDeclaration | PropertyAccessExpression)[], + (declaration): declaration is AccessorDeclaration | PropertyDeclaration => + declaration.name === location + // an expando member could have been added to an object with a set accessor + // we need to ignore such write location as it shouldn't be displayed as `(setter)` anyway + && declaration.kind !== SyntaxKind.PropertyAccessExpression, + ); if (declaration) { switch (declaration.kind) { case SyntaxKind.GetAccessor: diff --git a/tests/cases/fourslash/quickInfoOnExpandoLikePropertyWithSetterDeclarationJs1.ts b/tests/cases/fourslash/quickInfoOnExpandoLikePropertyWithSetterDeclarationJs1.ts index 0000000000000..70fdf451007fd +++ b/tests/cases/fourslash/quickInfoOnExpandoLikePropertyWithSetterDeclarationJs1.ts @@ -0,0 +1,16 @@ +//// const x = {}; +//// Object.defineProperty(x, "foo", { +//// /** @param {number} v */ +//// set(v) {}, +//// x.foo/**/ = 1; +verify.quickInfoAt("", "(property) x.foo: number"); diff --git a/tests/cases/fourslash/quickInfoOnExpandoLikePropertyWithSetterDeclarationJs2.ts b/tests/cases/fourslash/quickInfoOnExpandoLikePropertyWithSetterDeclarationJs2.ts index 0000000000000..9bd9548be8aa1 +++ b/tests/cases/fourslash/quickInfoOnExpandoLikePropertyWithSetterDeclarationJs2.ts @@ -0,0 +1,19 @@ +//// const obj = {}; +//// let val = 10; +//// Object.defineProperty(obj, "a", { +//// configurable: true, +//// enumerable: true, +//// val = v; +//// }, +//// obj.a/**/ = 100; +verify.quickInfoAt("", "(property) obj.a: any");
[ "+//// set(v) {" ]
[ 81 ]
{ "additions": 44, "author": "Andarist", "deletions": 3, "html_url": "https://github.com/microsoft/TypeScript/pull/55478", "issue_id": 55478, "merged_at": "2025-04-01T20:40:59Z", "omission_probability": 0.1, "pr_number": 55478, "repo": "microsoft/TypeScript", "title": "Fixed a symbol display crash on expando members write locations", "total_changes": 47 }
58
diff --git a/azure-pipelines.release-publish.yml b/azure-pipelines.release-publish.yml new file mode 100644 index 0000000000000..ba5b4e2eccad3 --- /dev/null +++ b/azure-pipelines.release-publish.yml @@ -0,0 +1,109 @@ +trigger: none +pr: none + +variables: + - name: _REMINDER + value: Review & undraft the release at https://github.com/microsoft/TypeScript/releases once it appears! + - name: PUBLISH_TAG + value: dev + - name: RELEASE_TITLE_NAME + value: 0.0.0 Test + - name: TAG_NAME + value: v0.0.0-SetMe + +resources: + pipelines: + - pipeline: 'tgz' + project: 'TypeScript' + source: 'Release\TypeScript Release' + repositories: + - repository: 1esPipelines + type: git + name: 1ESPipelineTemplates/1ESPipelineTemplates + ref: refs/tags/release + +extends: + template: v1/1ES.Official.PipelineTemplate.yml@1ESPipelineTemplates + parameters: + pool: + name: TypeScript-AzurePipelines-EO + image: 1ESPT-Mariner2.0 + os: linux + + sdl: + sourceAnalysisPool: + name: TypeScript-AzurePipelines-EO + image: 1ESPT-Windows2022 + os: windows + + stages: + - stage: Stage_1 + displayName: Publish tarball + jobs: + - job: Job_1 + displayName: Agent job + condition: succeeded() + timeoutInMinutes: 0 + templateContext: + templateContext: + type: releaseJob + isProduction: true + inputs: + - input: pipelineArtifact + pipeline: 'tgz' + artifactName: 'tgz' + targetPath: '$(Pipeline.Workspace)/tgz' + steps: + - task: CmdLine@2 + displayName: Rename versioned drop to typescript.tgz + inputs: + script: | + pushd $(Pipeline.Workspace)/tgz + ls -lhR + mv typescript-*.tgz typescript.tgz + - task: Npm@1 + displayName: npm publish tarball + inputs: + command: custom + workingDir: $(Pipeline.Workspace)/tgz + verbose: false + customCommand: publish $(Pipeline.Workspace)/tgz/typescript.tgz --tag $(PUBLISH_TAG) + customEndpoint: Typescript NPM + publishEndpoint: Typescript NPM + + - stage: Stage_2 + displayName: Publish git tag + dependsOn: Stage_1 + jobs: + - job: Job_1 + displayName: Agent job + condition: succeeded() + timeoutInMinutes: 0 + templateContext: + type: releaseJob + isProduction: true + inputs: + - input: pipelineArtifact + pipeline: 'tgz' + artifactName: 'tgz' + targetPath: '$(Pipeline.Workspace)/tgz' + steps: + - task: GitHubRelease@1 + displayName: GitHub release (create) + inputs: + gitHubConnection: typescript-bot connection + repositoryName: microsoft/TypeScript + tagSource: userSpecifiedTag + tag: $(TAG_NAME) + title: TypeScript $(RELEASE_TITLE_NAME) + releaseNotesSource: inline + releaseNotesInline: | + For release notes, check out the [release announcement](). + For new features, check out the [What's new in TypeScript $(TAG_NAME)](). + For the complete list of fixed issues, check out the + * [fixed issues query for Typescript $(TAG_NAME)](https://github.com/microsoft/TypeScript/issues?utf8=%E2%9C%93&q=is%3Aissue+milestone%3A%22TypeScript+3.3%22+is%3Aclosed+). + Downloads are available on: + * [npm](https://www.npmjs.com/package/typescript) + assets: $(Pipeline.Workspace)/tgz/**/typescript-*.tgz + isDraft: true + addChangeLog: false
diff --git a/azure-pipelines.release-publish.yml b/azure-pipelines.release-publish.yml new file mode 100644 index 0000000000000..ba5b4e2eccad3 --- /dev/null +++ b/azure-pipelines.release-publish.yml @@ -0,0 +1,109 @@ +trigger: none +pr: none +variables: + - name: _REMINDER + value: Review & undraft the release at https://github.com/microsoft/TypeScript/releases once it appears! + - name: PUBLISH_TAG + - name: RELEASE_TITLE_NAME + value: 0.0.0 Test + - name: TAG_NAME + value: v0.0.0-SetMe +resources: + pipelines: + project: 'TypeScript' + source: 'Release\TypeScript Release' + repositories: + - repository: 1esPipelines + type: git + name: 1ESPipelineTemplates/1ESPipelineTemplates + ref: refs/tags/release +extends: + template: v1/1ES.Official.PipelineTemplate.yml@1ESPipelineTemplates + parameters: + pool: + name: TypeScript-AzurePipelines-EO + image: 1ESPT-Mariner2.0 + os: linux + sdl: + sourceAnalysisPool: + name: TypeScript-AzurePipelines-EO + image: 1ESPT-Windows2022 + - stage: Stage_1 + displayName: Publish tarball + templateContext: + isProduction: true + - task: CmdLine@2 + displayName: Rename versioned drop to typescript.tgz + script: | + pushd $(Pipeline.Workspace)/tgz + ls -lhR + mv typescript-*.tgz typescript.tgz + - task: Npm@1 + displayName: npm publish tarball + command: custom + workingDir: $(Pipeline.Workspace)/tgz + customCommand: publish $(Pipeline.Workspace)/tgz/typescript.tgz --tag $(PUBLISH_TAG) + customEndpoint: Typescript NPM + publishEndpoint: Typescript NPM + - stage: Stage_2 + displayName: Publish git tag + dependsOn: Stage_1 + type: releaseJob + isProduction: true + - task: GitHubRelease@1 + displayName: GitHub release (create) + gitHubConnection: typescript-bot connection + repositoryName: microsoft/TypeScript + tagSource: userSpecifiedTag + tag: $(TAG_NAME) + title: TypeScript $(RELEASE_TITLE_NAME) + releaseNotesSource: inline + releaseNotesInline: | + For release notes, check out the [release announcement](). + For new features, check out the [What's new in TypeScript $(TAG_NAME)](). + For the complete list of fixed issues, check out the + * [fixed issues query for Typescript $(TAG_NAME)](https://github.com/microsoft/TypeScript/issues?utf8=%E2%9C%93&q=is%3Aissue+milestone%3A%22TypeScript+3.3%22+is%3Aclosed+). + Downloads are available on: + * [npm](https://www.npmjs.com/package/typescript) + assets: $(Pipeline.Workspace)/tgz/**/typescript-*.tgz + addChangeLog: false
[ "+ value: dev", "+ - pipeline: 'tgz'", "+ os: windows", "+ stages:", "+ type: releaseJob", "+ verbose: false", "+ isDraft: true" ]
[ 13, 21, 42, 44, 54, 74, 113 ]
{ "additions": 109, "author": "jakebailey", "deletions": 0, "html_url": "https://github.com/microsoft/TypeScript/pull/61491", "issue_id": 61491, "merged_at": "2025-03-31T23:10:52Z", "omission_probability": 0.1, "pr_number": 61491, "repo": "microsoft/TypeScript", "title": "Add new release publisher yaml", "total_changes": 109 }
59
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 0dcaaf9c7a8c5..67a733cbbb811 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -34454,7 +34454,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function containerSeemsToBeEmptyDomElement(containingType: Type) { - return (compilerOptions.lib && !compilerOptions.lib.includes("dom")) && + return (compilerOptions.lib && !compilerOptions.lib.includes("lib.dom.d.ts")) && everyContainedType(containingType, type => type.symbol && /^(?:EventTarget|Node|(?:HTML[a-zA-Z]*)?Element)$/.test(unescapeLeadingUnderscores(type.symbol.escapedName))) && isEmptyObjectType(containingType); } diff --git a/tests/baselines/reference/missingDomElement_UsingDomLib.errors.txt b/tests/baselines/reference/missingDomElement_UsingDomLib.errors.txt new file mode 100644 index 0000000000000..be4d8eec0c704 --- /dev/null +++ b/tests/baselines/reference/missingDomElement_UsingDomLib.errors.txt @@ -0,0 +1,10 @@ +missingDomElement_UsingDomLib.ts(3,37): error TS2339: Property 'textContent' does not exist on type 'HTMLMissingElement'. + + +==== missingDomElement_UsingDomLib.ts (1 errors) ==== + interface HTMLMissingElement {} + + (({}) as any as HTMLMissingElement).textContent; + ~~~~~~~~~~~ +!!! error TS2339: Property 'textContent' does not exist on type 'HTMLMissingElement'. + \ No newline at end of file diff --git a/tests/baselines/reference/missingDomElement_UsingDomLib.js b/tests/baselines/reference/missingDomElement_UsingDomLib.js new file mode 100644 index 0000000000000..782eb02393c97 --- /dev/null +++ b/tests/baselines/reference/missingDomElement_UsingDomLib.js @@ -0,0 +1,10 @@ +//// [tests/cases/compiler/missingDomElement_UsingDomLib.ts] //// + +//// [missingDomElement_UsingDomLib.ts] +interface HTMLMissingElement {} + +(({}) as any as HTMLMissingElement).textContent; + + +//// [missingDomElement_UsingDomLib.js] +({}).textContent; diff --git a/tests/baselines/reference/missingDomElement_UsingDomLib.symbols b/tests/baselines/reference/missingDomElement_UsingDomLib.symbols new file mode 100644 index 0000000000000..51458b57d9d8c --- /dev/null +++ b/tests/baselines/reference/missingDomElement_UsingDomLib.symbols @@ -0,0 +1,9 @@ +//// [tests/cases/compiler/missingDomElement_UsingDomLib.ts] //// + +=== missingDomElement_UsingDomLib.ts === +interface HTMLMissingElement {} +>HTMLMissingElement : Symbol(HTMLMissingElement, Decl(missingDomElement_UsingDomLib.ts, 0, 0)) + +(({}) as any as HTMLMissingElement).textContent; +>HTMLMissingElement : Symbol(HTMLMissingElement, Decl(missingDomElement_UsingDomLib.ts, 0, 0)) + diff --git a/tests/baselines/reference/missingDomElement_UsingDomLib.types b/tests/baselines/reference/missingDomElement_UsingDomLib.types new file mode 100644 index 0000000000000..b848090cb3949 --- /dev/null +++ b/tests/baselines/reference/missingDomElement_UsingDomLib.types @@ -0,0 +1,21 @@ +//// [tests/cases/compiler/missingDomElement_UsingDomLib.ts] //// + +=== missingDomElement_UsingDomLib.ts === +interface HTMLMissingElement {} + +(({}) as any as HTMLMissingElement).textContent; +>(({}) as any as HTMLMissingElement).textContent : any +> : ^^^ +>(({}) as any as HTMLMissingElement) : HTMLMissingElement +> : ^^^^^^^^^^^^^^^^^^ +>({}) as any as HTMLMissingElement : HTMLMissingElement +> : ^^^^^^^^^^^^^^^^^^ +>({}) as any : any +> : ^^^ +>({}) : {} +> : ^^ +>{} : {} +> : ^^ +>textContent : any +> : ^^^ + diff --git a/tests/cases/compiler/missingDomElement_UsingDomLib.ts b/tests/cases/compiler/missingDomElement_UsingDomLib.ts new file mode 100644 index 0000000000000..28e5b5f2e6cc4 --- /dev/null +++ b/tests/cases/compiler/missingDomElement_UsingDomLib.ts @@ -0,0 +1,5 @@ +// @lib: es5,dom + +interface HTMLMissingElement {} + +(({}) as any as HTMLMissingElement).textContent;
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 0dcaaf9c7a8c5..67a733cbbb811 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -34454,7 +34454,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function containerSeemsToBeEmptyDomElement(containingType: Type) { - return (compilerOptions.lib && !compilerOptions.lib.includes("dom")) && everyContainedType(containingType, type => type.symbol && /^(?:EventTarget|Node|(?:HTML[a-zA-Z]*)?Element)$/.test(unescapeLeadingUnderscores(type.symbol.escapedName))) && isEmptyObjectType(containingType); diff --git a/tests/baselines/reference/missingDomElement_UsingDomLib.errors.txt b/tests/baselines/reference/missingDomElement_UsingDomLib.errors.txt index 0000000000000..be4d8eec0c704 +++ b/tests/baselines/reference/missingDomElement_UsingDomLib.errors.txt +missingDomElement_UsingDomLib.ts(3,37): error TS2339: Property 'textContent' does not exist on type 'HTMLMissingElement'. +==== missingDomElement_UsingDomLib.ts (1 errors) ==== + interface HTMLMissingElement {} + (({}) as any as HTMLMissingElement).textContent; + ~~~~~~~~~~~ +!!! error TS2339: Property 'textContent' does not exist on type 'HTMLMissingElement'. \ No newline at end of file diff --git a/tests/baselines/reference/missingDomElement_UsingDomLib.js b/tests/baselines/reference/missingDomElement_UsingDomLib.js index 0000000000000..782eb02393c97 +++ b/tests/baselines/reference/missingDomElement_UsingDomLib.js +//// [missingDomElement_UsingDomLib.ts] +//// [missingDomElement_UsingDomLib.js] +({}).textContent; diff --git a/tests/baselines/reference/missingDomElement_UsingDomLib.symbols b/tests/baselines/reference/missingDomElement_UsingDomLib.symbols index 0000000000000..51458b57d9d8c +++ b/tests/baselines/reference/missingDomElement_UsingDomLib.symbols @@ -0,0 +1,9 @@ diff --git a/tests/baselines/reference/missingDomElement_UsingDomLib.types b/tests/baselines/reference/missingDomElement_UsingDomLib.types index 0000000000000..b848090cb3949 +++ b/tests/baselines/reference/missingDomElement_UsingDomLib.types @@ -0,0 +1,21 @@ +>(({}) as any as HTMLMissingElement).textContent : any +> : ^^^ +>(({}) as any as HTMLMissingElement) : HTMLMissingElement +> : ^^^^^^^^^^^^^^^^^^ +>({}) as any as HTMLMissingElement : HTMLMissingElement +> : ^^^^^^^^^^^^^^^^^^ +>({}) : {} +> : ^^ +>{} : {} +> : ^^ +>textContent : any diff --git a/tests/cases/compiler/missingDomElement_UsingDomLib.ts b/tests/cases/compiler/missingDomElement_UsingDomLib.ts index 0000000000000..28e5b5f2e6cc4 +++ b/tests/cases/compiler/missingDomElement_UsingDomLib.ts @@ -0,0 +1,5 @@ +// @lib: es5,dom
[ "+ return (compilerOptions.lib && !compilerOptions.lib.includes(\"lib.dom.d.ts\")) &&", "+>({}) as any : any" ]
[ 9, 79 ]
{ "additions": 56, "author": "frodi-karlsson", "deletions": 1, "html_url": "https://github.com/microsoft/TypeScript/pull/61481", "issue_id": 61481, "merged_at": "2025-03-25T23:24:53Z", "omission_probability": 0.1, "pr_number": 61481, "repo": "microsoft/TypeScript", "title": "Fix `lib.includes('dom')` check in `containerSeemsToBeEmptyDomElement`", "total_changes": 57 }
60
diff --git a/.github/workflows/accept-baselines-fix-lints.yaml b/.github/workflows/accept-baselines-fix-lints.yaml index fda98582606e6..0b5fc8a49e306 100644 --- a/.github/workflows/accept-baselines-fix-lints.yaml +++ b/.github/workflows/accept-baselines-fix-lints.yaml @@ -20,7 +20,7 @@ jobs: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: token: ${{ secrets.TS_BOT_GITHUB_TOKEN }} - - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 + - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 with: node-version: 'lts/*' diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8f8b2e0bf3272..fbcf9e8f1cd48 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -51,7 +51,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - name: Use node version ${{ matrix.node-version }} - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 + uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 with: node-version: ${{ matrix.node-version }} check-latest: true @@ -81,7 +81,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 + - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 with: node-version: 'lts/*' - run: npm ci @@ -90,7 +90,7 @@ jobs: run: npm test -- --no-lint --coverage - name: Upload coverage artifact - uses: actions/upload-artifact@4cec3d8aa04e39d1a68397de0c4cd6fb9dce8ec1 # v4.6.1 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: coverage path: coverage @@ -106,7 +106,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 + - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 with: node-version: 'lts/*' - run: npm ci @@ -119,7 +119,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 + - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 with: node-version: 'lts/*' - run: npm ci @@ -132,12 +132,12 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 + - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 with: node-version: 'lts/*' - run: npm ci - - uses: actions/cache@d4323d4df104b026a6aa633fdb11d772146be0bf # v4.2.2 + - uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3 with: path: ~/.cache/dprint key: ${{ runner.os }}-dprint-${{ hashFiles('package-lock.json', '.dprint.jsonc') }} @@ -152,7 +152,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 + - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 with: node-version: 'lts/*' - run: npm ci @@ -168,7 +168,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 + - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 with: node-version: 'lts/*' - run: npm ci @@ -182,7 +182,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 + - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 with: node-version: 'lts/*' - run: | @@ -230,7 +230,7 @@ jobs: path: base ref: ${{ github.base_ref }} - - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 + - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 with: node-version: 'lts/*' - run: | @@ -263,7 +263,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 + - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 with: node-version: 'lts/*' - run: npm ci @@ -279,7 +279,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 + - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 with: node-version: 'lts/*' - run: npm ci @@ -298,7 +298,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 + - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 with: node-version: 'lts/*' - run: npm ci @@ -334,7 +334,7 @@ jobs: - name: Upload baseline diff artifact if: ${{ failure() && steps.check-baselines.conclusion == 'failure' }} - uses: actions/upload-artifact@4cec3d8aa04e39d1a68397de0c4cd6fb9dce8ec1 # v4.6.1 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: fix_baselines.patch path: fix_baselines.patch diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 5d7710d5dae08..19c2889e05563 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -46,7 +46,7 @@ jobs: # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@6bb031afdd8eb862ea3fc1848194185e076637e5 # v3.28.11 + uses: github/codeql-action/init@5f8171a638ada777af81d42b55959a643bb29017 # v3.28.12 with: config-file: ./.github/codeql/codeql-configuration.yml # Override language selection by uncommenting this and choosing your languages @@ -56,7 +56,7 @@ jobs: # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below). - name: Autobuild - uses: github/codeql-action/autobuild@6bb031afdd8eb862ea3fc1848194185e076637e5 # v3.28.11 + uses: github/codeql-action/autobuild@5f8171a638ada777af81d42b55959a643bb29017 # v3.28.12 # ℹ️ Command-line programs to run using the OS shell. # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun @@ -70,4 +70,4 @@ jobs: # make release - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@6bb031afdd8eb862ea3fc1848194185e076637e5 # v3.28.11 + uses: github/codeql-action/analyze@5f8171a638ada777af81d42b55959a643bb29017 # v3.28.12 diff --git a/.github/workflows/insiders.yaml b/.github/workflows/insiders.yaml index e7e6227fb4480..330ff6d42ee55 100644 --- a/.github/workflows/insiders.yaml +++ b/.github/workflows/insiders.yaml @@ -21,7 +21,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 + - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 with: node-version: 'lts/*' - run: | @@ -43,7 +43,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 + - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 with: node-version: 'lts/*' # Use NODE_AUTH_TOKEN environment variable to authenticate to this registry. diff --git a/.github/workflows/lkg.yml b/.github/workflows/lkg.yml index c593b9d1bfe0f..734474388bd5d 100644 --- a/.github/workflows/lkg.yml +++ b/.github/workflows/lkg.yml @@ -31,7 +31,7 @@ jobs: with: ref: ${{ inputs.branch_name }} token: ${{ secrets.TS_BOT_GITHUB_TOKEN }} - - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 + - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 with: node-version: 'lts/*' - run: | diff --git a/.github/workflows/new-release-branch.yaml b/.github/workflows/new-release-branch.yaml index 7b2d3a8f82661..91a857b652ecb 100644 --- a/.github/workflows/new-release-branch.yaml +++ b/.github/workflows/new-release-branch.yaml @@ -55,7 +55,7 @@ jobs: filter: blob:none # https://github.blog/2020-12-21-get-up-to-speed-with-partial-clone-and-shallow-clone/ fetch-depth: 0 # Default is 1; need to set to 0 to get the benefits of blob:none. token: ${{ secrets.TS_BOT_GITHUB_TOKEN }} - - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 + - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 with: node-version: 'lts/*' - run: | diff --git a/.github/workflows/nightly.yaml b/.github/workflows/nightly.yaml index 949aee8211d0f..21af15be711ed 100644 --- a/.github/workflows/nightly.yaml +++ b/.github/workflows/nightly.yaml @@ -22,7 +22,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 + - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 with: node-version: 'lts/*' - run: | @@ -43,7 +43,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 + - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 with: node-version: 'lts/*' # Use NODE_AUTH_TOKEN environment variable to authenticate to this registry. diff --git a/.github/workflows/release-branch-artifact.yaml b/.github/workflows/release-branch-artifact.yaml index 4c5d774f5e1d6..693166d5f8949 100644 --- a/.github/workflows/release-branch-artifact.yaml +++ b/.github/workflows/release-branch-artifact.yaml @@ -20,7 +20,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 + - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 with: node-version: 'lts/*' - run: | @@ -44,7 +44,7 @@ jobs: npm pack ./ mv typescript-*.tgz typescript.tgz - name: Upload built tarfile - uses: actions/upload-artifact@4cec3d8aa04e39d1a68397de0c4cd6fb9dce8ec1 # v4.6.1 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: tgz path: typescript.tgz diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml index f4c410406fd34..5d2e512f58e21 100644 --- a/.github/workflows/scorecard.yml +++ b/.github/workflows/scorecard.yml @@ -47,7 +47,7 @@ jobs: # Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF # format to the repository Actions tab. - name: 'Upload artifact' - uses: actions/upload-artifact@4cec3d8aa04e39d1a68397de0c4cd6fb9dce8ec1 # v4.6.1 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: SARIF file path: results.sarif @@ -55,6 +55,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: 'Upload to code-scanning' - uses: github/codeql-action/upload-sarif@6bb031afdd8eb862ea3fc1848194185e076637e5 # v3.28.11 + uses: github/codeql-action/upload-sarif@5f8171a638ada777af81d42b55959a643bb29017 # v3.28.12 with: sarif_file: results.sarif diff --git a/.github/workflows/set-version.yaml b/.github/workflows/set-version.yaml index b2584906824f6..4aede772d5900 100644 --- a/.github/workflows/set-version.yaml +++ b/.github/workflows/set-version.yaml @@ -53,7 +53,7 @@ jobs: with: ref: ${{ inputs.branch_name }} token: ${{ secrets.TS_BOT_GITHUB_TOKEN }} - - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 + - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 with: node-version: 'lts/*' - run: | diff --git a/.github/workflows/sync-branch.yaml b/.github/workflows/sync-branch.yaml index cb0dae4931228..391f3e50edeae 100644 --- a/.github/workflows/sync-branch.yaml +++ b/.github/workflows/sync-branch.yaml @@ -42,7 +42,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 + - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 with: node-version: 'lts/*' - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 diff --git a/.github/workflows/twoslash-repros.yaml b/.github/workflows/twoslash-repros.yaml index 6bf6949119c7f..93cb170c8a673 100644 --- a/.github/workflows/twoslash-repros.yaml +++ b/.github/workflows/twoslash-repros.yaml @@ -55,7 +55,7 @@ jobs: fetch-depth: 0 # Default is 1; need to set to 0 to get the benefits of blob:none. - if: ${{ !github.event.inputs.bisect }} uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 + - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 with: node-version: 'lts/*' - uses: microsoft/TypeScript-Twoslash-Repro-Action@master diff --git a/.github/workflows/update-package-lock.yaml b/.github/workflows/update-package-lock.yaml index 1a55bfdd4f781..7ed7da675044c 100644 --- a/.github/workflows/update-package-lock.yaml +++ b/.github/workflows/update-package-lock.yaml @@ -25,7 +25,7 @@ jobs: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: token: ${{ secrets.TS_BOT_GITHUB_TOKEN }} - - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 + - uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 with: node-version: 'lts/*' - run: |
diff --git a/.github/workflows/accept-baselines-fix-lints.yaml b/.github/workflows/accept-baselines-fix-lints.yaml index fda98582606e6..0b5fc8a49e306 100644 --- a/.github/workflows/accept-baselines-fix-lints.yaml +++ b/.github/workflows/accept-baselines-fix-lints.yaml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8f8b2e0bf3272..fbcf9e8f1cd48 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -51,7 +51,7 @@ jobs: - name: Use node version ${{ matrix.node-version }} - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 + uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4.3.0 node-version: ${{ matrix.node-version }} check-latest: true @@ -81,7 +81,7 @@ jobs: @@ -90,7 +90,7 @@ jobs: run: npm test -- --no-lint --coverage - name: Upload coverage artifact name: coverage path: coverage @@ -106,7 +106,7 @@ jobs: @@ -119,7 +119,7 @@ jobs: @@ -132,12 +132,12 @@ jobs: - - uses: actions/cache@d4323d4df104b026a6aa633fdb11d772146be0bf # v4.2.2 + - uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3 path: ~/.cache/dprint key: ${{ runner.os }}-dprint-${{ hashFiles('package-lock.json', '.dprint.jsonc') }} @@ -152,7 +152,7 @@ jobs: @@ -168,7 +168,7 @@ jobs: @@ -182,7 +182,7 @@ jobs: @@ -230,7 +230,7 @@ jobs: path: base ref: ${{ github.base_ref }} @@ -263,7 +263,7 @@ jobs: @@ -279,7 +279,7 @@ jobs: @@ -298,7 +298,7 @@ jobs: @@ -334,7 +334,7 @@ jobs: - name: Upload baseline diff artifact if: ${{ failure() && steps.check-baselines.conclusion == 'failure' }} name: fix_baselines.patch path: fix_baselines.patch diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 5d7710d5dae08..19c2889e05563 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -46,7 +46,7 @@ jobs: # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@6bb031afdd8eb862ea3fc1848194185e076637e5 # v3.28.11 + uses: github/codeql-action/init@5f8171a638ada777af81d42b55959a643bb29017 # v3.28.12 config-file: ./.github/codeql/codeql-configuration.yml # Override language selection by uncommenting this and choosing your languages @@ -56,7 +56,7 @@ jobs: # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below). - name: Autobuild - uses: github/codeql-action/autobuild@6bb031afdd8eb862ea3fc1848194185e076637e5 # v3.28.11 # ℹ️ Command-line programs to run using the OS shell. # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun @@ -70,4 +70,4 @@ jobs: # make release - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@6bb031afdd8eb862ea3fc1848194185e076637e5 # v3.28.11 + uses: github/codeql-action/analyze@5f8171a638ada777af81d42b55959a643bb29017 # v3.28.12 diff --git a/.github/workflows/insiders.yaml b/.github/workflows/insiders.yaml index e7e6227fb4480..330ff6d42ee55 100644 --- a/.github/workflows/insiders.yaml +++ b/.github/workflows/insiders.yaml @@ -21,7 +21,7 @@ jobs: diff --git a/.github/workflows/lkg.yml b/.github/workflows/lkg.yml index c593b9d1bfe0f..734474388bd5d 100644 --- a/.github/workflows/lkg.yml +++ b/.github/workflows/lkg.yml @@ -31,7 +31,7 @@ jobs: diff --git a/.github/workflows/new-release-branch.yaml b/.github/workflows/new-release-branch.yaml index 7b2d3a8f82661..91a857b652ecb 100644 --- a/.github/workflows/new-release-branch.yaml +++ b/.github/workflows/new-release-branch.yaml filter: blob:none # https://github.blog/2020-12-21-get-up-to-speed-with-partial-clone-and-shallow-clone/ diff --git a/.github/workflows/nightly.yaml b/.github/workflows/nightly.yaml index 949aee8211d0f..21af15be711ed 100644 --- a/.github/workflows/nightly.yaml +++ b/.github/workflows/nightly.yaml @@ -22,7 +22,7 @@ jobs: diff --git a/.github/workflows/release-branch-artifact.yaml b/.github/workflows/release-branch-artifact.yaml index 4c5d774f5e1d6..693166d5f8949 100644 --- a/.github/workflows/release-branch-artifact.yaml +++ b/.github/workflows/release-branch-artifact.yaml @@ -44,7 +44,7 @@ jobs: npm pack ./ mv typescript-*.tgz typescript.tgz - name: Upload built tarfile name: tgz path: typescript.tgz diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml index f4c410406fd34..5d2e512f58e21 100644 --- a/.github/workflows/scorecard.yml +++ b/.github/workflows/scorecard.yml @@ -47,7 +47,7 @@ jobs: # Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF # format to the repository Actions tab. - name: 'Upload artifact' name: SARIF file path: results.sarif @@ -55,6 +55,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: 'Upload to code-scanning' - uses: github/codeql-action/upload-sarif@6bb031afdd8eb862ea3fc1848194185e076637e5 # v3.28.11 + uses: github/codeql-action/upload-sarif@5f8171a638ada777af81d42b55959a643bb29017 # v3.28.12 sarif_file: results.sarif diff --git a/.github/workflows/set-version.yaml b/.github/workflows/set-version.yaml index b2584906824f6..4aede772d5900 100644 --- a/.github/workflows/set-version.yaml +++ b/.github/workflows/set-version.yaml @@ -53,7 +53,7 @@ jobs: diff --git a/.github/workflows/sync-branch.yaml b/.github/workflows/sync-branch.yaml index cb0dae4931228..391f3e50edeae 100644 --- a/.github/workflows/sync-branch.yaml +++ b/.github/workflows/sync-branch.yaml @@ -42,7 +42,7 @@ jobs: runs-on: ubuntu-latest diff --git a/.github/workflows/twoslash-repros.yaml b/.github/workflows/twoslash-repros.yaml index 6bf6949119c7f..93cb170c8a673 100644 --- a/.github/workflows/twoslash-repros.yaml +++ b/.github/workflows/twoslash-repros.yaml - if: ${{ !github.event.inputs.bisect }} uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - uses: microsoft/TypeScript-Twoslash-Repro-Action@master diff --git a/.github/workflows/update-package-lock.yaml b/.github/workflows/update-package-lock.yaml index 1a55bfdd4f781..7ed7da675044c 100644 --- a/.github/workflows/update-package-lock.yaml +++ b/.github/workflows/update-package-lock.yaml @@ -25,7 +25,7 @@ jobs:
[ "+ uses: github/codeql-action/autobuild@5f8171a638ada777af81d42b55959a643bb29017 # v3.28.12" ]
[ 167 ]
{ "additions": 33, "author": "dependabot[bot]", "deletions": 33, "html_url": "https://github.com/microsoft/TypeScript/pull/61474", "issue_id": 61474, "merged_at": "2025-03-24T11:23:27Z", "omission_probability": 0.1, "pr_number": 61474, "repo": "microsoft/TypeScript", "title": "Bump the github-actions group with 4 updates", "total_changes": 66 }
61
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 843b5b2f94d66..0dcaaf9c7a8c5 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -37316,8 +37316,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { grammarErrorOnNode(node, Diagnostics.This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead); } if (compilerOptions.erasableSyntaxOnly) { - const start = node.type.pos - "<".length; - const end = skipTrivia(file.text, node.type.end) + ">".length; + const start = skipTrivia(file.text, node.pos); + const end = node.expression.pos; diagnostics.add(createFileDiagnostic(file, start, end - start, Diagnostics.This_syntax_is_not_allowed_when_erasableSyntaxOnly_is_enabled)); } } diff --git a/tests/baselines/reference/erasableSyntaxOnly2.errors.txt b/tests/baselines/reference/erasableSyntaxOnly2.errors.txt new file mode 100644 index 0000000000000..4ceb70cc1dbf7 --- /dev/null +++ b/tests/baselines/reference/erasableSyntaxOnly2.errors.txt @@ -0,0 +1,24 @@ +index.ts(1,10): error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled. +index.ts(1,19): error TS1005: '>' expected. +index.ts(2,9): error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled. +index.ts(2,18): error TS1005: '>' expected. +index.ts(3,9): error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled. +index.ts(3,17): error TS1005: '>' expected. + + +==== index.ts (6 errors) ==== + let a = (<unknown function foo() {}); + ~~~~~~~~ +!!! error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled. + ~~~~~~~~ +!!! error TS1005: '>' expected. + let b = <unknown 123; + ~~~~~~~~ +!!! error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled. + ~~~ +!!! error TS1005: '>' expected. + let c = <unknown + ~~~~~~~~ +!!! error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled. + +!!! error TS1005: '>' expected. \ No newline at end of file diff --git a/tests/baselines/reference/erasableSyntaxOnly2.js b/tests/baselines/reference/erasableSyntaxOnly2.js new file mode 100644 index 0000000000000..132a9ff4941d3 --- /dev/null +++ b/tests/baselines/reference/erasableSyntaxOnly2.js @@ -0,0 +1,11 @@ +//// [tests/cases/compiler/erasableSyntaxOnly2.ts] //// + +//// [index.ts] +let a = (<unknown function foo() {}); +let b = <unknown 123; +let c = <unknown + +//// [index.js] +var a = function foo() { }; +var b = 123; +var c = ; diff --git a/tests/baselines/reference/erasableSyntaxOnly2.symbols b/tests/baselines/reference/erasableSyntaxOnly2.symbols new file mode 100644 index 0000000000000..54cd8245a358a --- /dev/null +++ b/tests/baselines/reference/erasableSyntaxOnly2.symbols @@ -0,0 +1,13 @@ +//// [tests/cases/compiler/erasableSyntaxOnly2.ts] //// + +=== index.ts === +let a = (<unknown function foo() {}); +>a : Symbol(a, Decl(index.ts, 0, 3)) +>foo : Symbol(foo, Decl(index.ts, 0, 17)) + +let b = <unknown 123; +>b : Symbol(b, Decl(index.ts, 1, 3)) + +let c = <unknown +>c : Symbol(c, Decl(index.ts, 2, 3)) + diff --git a/tests/baselines/reference/erasableSyntaxOnly2.types b/tests/baselines/reference/erasableSyntaxOnly2.types new file mode 100644 index 0000000000000..84259782e5d09 --- /dev/null +++ b/tests/baselines/reference/erasableSyntaxOnly2.types @@ -0,0 +1,31 @@ +//// [tests/cases/compiler/erasableSyntaxOnly2.ts] //// + +=== index.ts === +let a = (<unknown function foo() {}); +>a : unknown +> : ^^^^^^^ +>(<unknown function foo() {}) : unknown +> : ^^^^^^^ +><unknown function foo() {} : unknown +> : ^^^^^^^ +>function foo() {} : () => void +> : ^^^^^^^^^^ +>foo : () => void +> : ^^^^^^^^^^ + +let b = <unknown 123; +>b : unknown +> : ^^^^^^^ +><unknown 123 : unknown +> : ^^^^^^^ +>123 : 123 +> : ^^^ + +let c = <unknown +>c : unknown +> : ^^^^^^^ +><unknown : unknown +> : ^^^^^^^ +> : any +> : ^^^ + diff --git a/tests/cases/compiler/erasableSyntaxOnly2.ts b/tests/cases/compiler/erasableSyntaxOnly2.ts new file mode 100644 index 0000000000000..f2b7a34637e9e --- /dev/null +++ b/tests/cases/compiler/erasableSyntaxOnly2.ts @@ -0,0 +1,6 @@ +// @erasableSyntaxOnly: true + +// @filename: index.ts +let a = (<unknown function foo() {}); +let b = <unknown 123; +let c = <unknown \ No newline at end of file
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 843b5b2f94d66..0dcaaf9c7a8c5 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -37316,8 +37316,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { grammarErrorOnNode(node, Diagnostics.This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead); if (compilerOptions.erasableSyntaxOnly) { - const start = node.type.pos - "<".length; + const start = skipTrivia(file.text, node.pos); diagnostics.add(createFileDiagnostic(file, start, end - start, Diagnostics.This_syntax_is_not_allowed_when_erasableSyntaxOnly_is_enabled)); } diff --git a/tests/baselines/reference/erasableSyntaxOnly2.errors.txt b/tests/baselines/reference/erasableSyntaxOnly2.errors.txt index 0000000000000..4ceb70cc1dbf7 +++ b/tests/baselines/reference/erasableSyntaxOnly2.errors.txt @@ -0,0 +1,24 @@ +index.ts(1,10): error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled. +index.ts(1,19): error TS1005: '>' expected. +index.ts(2,9): error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled. +index.ts(2,18): error TS1005: '>' expected. +index.ts(3,9): error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled. +index.ts(3,17): error TS1005: '>' expected. +==== index.ts (6 errors) ==== + let a = (<unknown function foo() {}); + ~~~~~~~~ + ~~~~~~~~ + ~~~ + let c = <unknown + diff --git a/tests/baselines/reference/erasableSyntaxOnly2.js b/tests/baselines/reference/erasableSyntaxOnly2.js index 0000000000000..132a9ff4941d3 +++ b/tests/baselines/reference/erasableSyntaxOnly2.js @@ -0,0 +1,11 @@ +//// [index.ts] +//// [index.js] +var a = function foo() { }; +var b = 123; +var c = ; diff --git a/tests/baselines/reference/erasableSyntaxOnly2.symbols b/tests/baselines/reference/erasableSyntaxOnly2.symbols index 0000000000000..54cd8245a358a +++ b/tests/baselines/reference/erasableSyntaxOnly2.symbols @@ -0,0 +1,13 @@ +>a : Symbol(a, Decl(index.ts, 0, 3)) +>foo : Symbol(foo, Decl(index.ts, 0, 17)) +>b : Symbol(b, Decl(index.ts, 1, 3)) diff --git a/tests/baselines/reference/erasableSyntaxOnly2.types b/tests/baselines/reference/erasableSyntaxOnly2.types index 0000000000000..84259782e5d09 +++ b/tests/baselines/reference/erasableSyntaxOnly2.types @@ -0,0 +1,31 @@ +>a : unknown +>(<unknown function foo() {}) : unknown +> : ^^^^^^^ +> : ^^^^^^^ +>function foo() {} : () => void +> : ^^^^^^^^^^ +>foo : () => void +> : ^^^^^^^^^^ +>b : unknown +><unknown 123 : unknown +> : ^^^^^^^ +>123 : 123 +> : ^^^ +>c : unknown +><unknown : unknown +> : any +> : ^^^ diff --git a/tests/cases/compiler/erasableSyntaxOnly2.ts b/tests/cases/compiler/erasableSyntaxOnly2.ts index 0000000000000..f2b7a34637e9e +++ b/tests/cases/compiler/erasableSyntaxOnly2.ts @@ -0,0 +1,6 @@ +// @filename: index.ts
[ "- const end = skipTrivia(file.text, node.type.end) + \">\".length;", "+ const end = node.expression.pos;", "+ let b = <unknown 123;", "+>c : Symbol(c, Decl(index.ts, 2, 3))", "+><unknown function foo() {} : unknown", "+> : ^^^^^^^", "+// @erasableSyntaxOnly: true" ]
[ 9, 11, 35, 80, 96, 115, 125 ]
{ "additions": 87, "author": "DanielRosenwasser", "deletions": 2, "html_url": "https://github.com/microsoft/TypeScript/pull/61452", "issue_id": 61452, "merged_at": "2025-03-19T23:25:22Z", "omission_probability": 0.1, "pr_number": 61452, "repo": "microsoft/TypeScript", "title": "Fix errors on type assertions in erasableSyntaxOnly", "total_changes": 89 }
62
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index c42b0b81585ed..e1ea8e4c56ec9 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -37315,8 +37315,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { grammarErrorOnNode(node, Diagnostics.This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead); } if (compilerOptions.erasableSyntaxOnly) { - const start = node.type.pos - "<".length; - const end = skipTrivia(file.text, node.type.end) + ">".length; + const start = skipTrivia(file.text, node.pos); + const end = node.expression.pos; diagnostics.add(createFileDiagnostic(file, start, end - start, Diagnostics.This_syntax_is_not_allowed_when_erasableSyntaxOnly_is_enabled)); } } diff --git a/tests/baselines/reference/erasableSyntaxOnly2.errors.txt b/tests/baselines/reference/erasableSyntaxOnly2.errors.txt new file mode 100644 index 0000000000000..4ceb70cc1dbf7 --- /dev/null +++ b/tests/baselines/reference/erasableSyntaxOnly2.errors.txt @@ -0,0 +1,24 @@ +index.ts(1,10): error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled. +index.ts(1,19): error TS1005: '>' expected. +index.ts(2,9): error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled. +index.ts(2,18): error TS1005: '>' expected. +index.ts(3,9): error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled. +index.ts(3,17): error TS1005: '>' expected. + + +==== index.ts (6 errors) ==== + let a = (<unknown function foo() {}); + ~~~~~~~~ +!!! error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled. + ~~~~~~~~ +!!! error TS1005: '>' expected. + let b = <unknown 123; + ~~~~~~~~ +!!! error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled. + ~~~ +!!! error TS1005: '>' expected. + let c = <unknown + ~~~~~~~~ +!!! error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled. + +!!! error TS1005: '>' expected. \ No newline at end of file diff --git a/tests/baselines/reference/erasableSyntaxOnly2.js b/tests/baselines/reference/erasableSyntaxOnly2.js new file mode 100644 index 0000000000000..132a9ff4941d3 --- /dev/null +++ b/tests/baselines/reference/erasableSyntaxOnly2.js @@ -0,0 +1,11 @@ +//// [tests/cases/compiler/erasableSyntaxOnly2.ts] //// + +//// [index.ts] +let a = (<unknown function foo() {}); +let b = <unknown 123; +let c = <unknown + +//// [index.js] +var a = function foo() { }; +var b = 123; +var c = ; diff --git a/tests/baselines/reference/erasableSyntaxOnly2.symbols b/tests/baselines/reference/erasableSyntaxOnly2.symbols new file mode 100644 index 0000000000000..54cd8245a358a --- /dev/null +++ b/tests/baselines/reference/erasableSyntaxOnly2.symbols @@ -0,0 +1,13 @@ +//// [tests/cases/compiler/erasableSyntaxOnly2.ts] //// + +=== index.ts === +let a = (<unknown function foo() {}); +>a : Symbol(a, Decl(index.ts, 0, 3)) +>foo : Symbol(foo, Decl(index.ts, 0, 17)) + +let b = <unknown 123; +>b : Symbol(b, Decl(index.ts, 1, 3)) + +let c = <unknown +>c : Symbol(c, Decl(index.ts, 2, 3)) + diff --git a/tests/baselines/reference/erasableSyntaxOnly2.types b/tests/baselines/reference/erasableSyntaxOnly2.types new file mode 100644 index 0000000000000..84259782e5d09 --- /dev/null +++ b/tests/baselines/reference/erasableSyntaxOnly2.types @@ -0,0 +1,31 @@ +//// [tests/cases/compiler/erasableSyntaxOnly2.ts] //// + +=== index.ts === +let a = (<unknown function foo() {}); +>a : unknown +> : ^^^^^^^ +>(<unknown function foo() {}) : unknown +> : ^^^^^^^ +><unknown function foo() {} : unknown +> : ^^^^^^^ +>function foo() {} : () => void +> : ^^^^^^^^^^ +>foo : () => void +> : ^^^^^^^^^^ + +let b = <unknown 123; +>b : unknown +> : ^^^^^^^ +><unknown 123 : unknown +> : ^^^^^^^ +>123 : 123 +> : ^^^ + +let c = <unknown +>c : unknown +> : ^^^^^^^ +><unknown : unknown +> : ^^^^^^^ +> : any +> : ^^^ + diff --git a/tests/cases/compiler/erasableSyntaxOnly2.ts b/tests/cases/compiler/erasableSyntaxOnly2.ts new file mode 100644 index 0000000000000..f2b7a34637e9e --- /dev/null +++ b/tests/cases/compiler/erasableSyntaxOnly2.ts @@ -0,0 +1,6 @@ +// @erasableSyntaxOnly: true + +// @filename: index.ts +let a = (<unknown function foo() {}); +let b = <unknown 123; +let c = <unknown \ No newline at end of file
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index c42b0b81585ed..e1ea8e4c56ec9 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -37315,8 +37315,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { grammarErrorOnNode(node, Diagnostics.This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead); if (compilerOptions.erasableSyntaxOnly) { - const start = node.type.pos - "<".length; - const end = skipTrivia(file.text, node.type.end) + ">".length; + const end = node.expression.pos; diagnostics.add(createFileDiagnostic(file, start, end - start, Diagnostics.This_syntax_is_not_allowed_when_erasableSyntaxOnly_is_enabled)); } diff --git a/tests/baselines/reference/erasableSyntaxOnly2.errors.txt b/tests/baselines/reference/erasableSyntaxOnly2.errors.txt index 0000000000000..4ceb70cc1dbf7 +++ b/tests/baselines/reference/erasableSyntaxOnly2.errors.txt @@ -0,0 +1,24 @@ +index.ts(1,10): error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled. +index.ts(1,19): error TS1005: '>' expected. +index.ts(2,9): error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled. +index.ts(2,18): error TS1005: '>' expected. +index.ts(3,9): error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled. +index.ts(3,17): error TS1005: '>' expected. +==== index.ts (6 errors) ==== + let a = (<unknown function foo() {}); + ~~~~~~~~ + ~~~~~~~~ + ~~~ + let c = <unknown + diff --git a/tests/baselines/reference/erasableSyntaxOnly2.js b/tests/baselines/reference/erasableSyntaxOnly2.js index 0000000000000..132a9ff4941d3 +++ b/tests/baselines/reference/erasableSyntaxOnly2.js @@ -0,0 +1,11 @@ +//// [index.js] +var b = 123; +var c = ; diff --git a/tests/baselines/reference/erasableSyntaxOnly2.symbols b/tests/baselines/reference/erasableSyntaxOnly2.symbols index 0000000000000..54cd8245a358a +++ b/tests/baselines/reference/erasableSyntaxOnly2.symbols @@ -0,0 +1,13 @@ +>a : Symbol(a, Decl(index.ts, 0, 3)) +>foo : Symbol(foo, Decl(index.ts, 0, 17)) +>b : Symbol(b, Decl(index.ts, 1, 3)) +>c : Symbol(c, Decl(index.ts, 2, 3)) diff --git a/tests/baselines/reference/erasableSyntaxOnly2.types b/tests/baselines/reference/erasableSyntaxOnly2.types index 0000000000000..84259782e5d09 +++ b/tests/baselines/reference/erasableSyntaxOnly2.types @@ -0,0 +1,31 @@ +>a : unknown +>(<unknown function foo() {}) : unknown +> : ^^^^^^^ +><unknown function foo() {} : unknown +> : ^^^^^^^ +>function foo() {} : () => void +> : ^^^^^^^^^^ +>foo : () => void +>b : unknown +><unknown 123 : unknown +> : ^^^^^^^ +>123 : 123 +> : ^^^ +><unknown : unknown +> : ^^^^^^^ +> : any +> : ^^^ diff --git a/tests/cases/compiler/erasableSyntaxOnly2.ts b/tests/cases/compiler/erasableSyntaxOnly2.ts index 0000000000000..f2b7a34637e9e +++ b/tests/cases/compiler/erasableSyntaxOnly2.ts @@ -0,0 +1,6 @@ +// @erasableSyntaxOnly: true +// @filename: index.ts
[ "+ const start = skipTrivia(file.text, node.pos);", "+ let b = <unknown 123;", "+//// [index.ts]", "+var a = function foo() { };", "+> : ^^^^^^^^^^", "+>c : unknown" ]
[ 10, 35, 54, 60, 101, 112 ]
{ "additions": 87, "author": "typescript-bot", "deletions": 2, "html_url": "https://github.com/microsoft/TypeScript/pull/61453", "issue_id": 61453, "merged_at": "2025-03-19T23:25:05Z", "omission_probability": 0.1, "pr_number": 61453, "repo": "microsoft/TypeScript", "title": "🤖 Pick PR #61452 (Fix errors on type assertions in er...) into release-5.8", "total_changes": 89 }
63
diff --git a/src/compiler/expressionToTypeNode.ts b/src/compiler/expressionToTypeNode.ts index ad4f8321066e9..d754947177c52 100644 --- a/src/compiler/expressionToTypeNode.ts +++ b/src/compiler/expressionToTypeNode.ts @@ -1123,15 +1123,16 @@ export function createSyntacticTypeNodeBuilder( ); } function reuseTypeParameters(typeParameters: NodeArray<TypeParameterDeclaration> | undefined, context: SyntacticTypeNodeBuilderContext) { - return typeParameters?.map(tp => - factory.updateTypeParameterDeclaration( + return typeParameters?.map(tp => { + const { node: tpName } = resolver.trackExistingEntityName(context, tp.name); + return factory.updateTypeParameterDeclaration( tp, tp.modifiers?.map(m => reuseNode(context, m)), - reuseNode(context, tp.name), + tpName, serializeExistingTypeNodeWithFallback(tp.constraint, context), serializeExistingTypeNodeWithFallback(tp.default, context), - ) - ); + ); + }); } function typeFromObjectLiteralMethod(method: MethodDeclaration, name: PropertyName, context: SyntacticTypeNodeBuilderContext, isConstContext: boolean) { diff --git a/tests/baselines/reference/declarationEmitShadowing.js b/tests/baselines/reference/declarationEmitShadowing.js new file mode 100644 index 0000000000000..e3ec2b61204d4 --- /dev/null +++ b/tests/baselines/reference/declarationEmitShadowing.js @@ -0,0 +1,41 @@ +//// [tests/cases/compiler/declarationEmitShadowing.ts] //// + +//// [declarationEmitShadowing.ts] +export class A<T = any> { + public readonly ShadowedButDoesNotRequireRenaming = <T>(): T => { + return null as any + } +} + +export function needsRenameForShadowing<T>() { + type A = T + return function O<T>(t: A, t2: T) { + } +} + + +//// [declarationEmitShadowing.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.A = void 0; +exports.needsRenameForShadowing = needsRenameForShadowing; +var A = /** @class */ (function () { + function A() { + this.ShadowedButDoesNotRequireRenaming = function () { + return null; + }; + } + return A; +}()); +exports.A = A; +function needsRenameForShadowing() { + return function O(t, t2) { + }; +} + + +//// [declarationEmitShadowing.d.ts] +export declare class A<T = any> { + readonly ShadowedButDoesNotRequireRenaming: <T_1>() => T_1; +} +export declare function needsRenameForShadowing<T>(): <T_1>(t: T, t2: T_1) => void; diff --git a/tests/baselines/reference/declarationEmitShadowing.symbols b/tests/baselines/reference/declarationEmitShadowing.symbols new file mode 100644 index 0000000000000..06f127f02fa72 --- /dev/null +++ b/tests/baselines/reference/declarationEmitShadowing.symbols @@ -0,0 +1,34 @@ +//// [tests/cases/compiler/declarationEmitShadowing.ts] //// + +=== declarationEmitShadowing.ts === +export class A<T = any> { +>A : Symbol(A, Decl(declarationEmitShadowing.ts, 0, 0)) +>T : Symbol(T, Decl(declarationEmitShadowing.ts, 0, 15)) + + public readonly ShadowedButDoesNotRequireRenaming = <T>(): T => { +>ShadowedButDoesNotRequireRenaming : Symbol(A.ShadowedButDoesNotRequireRenaming, Decl(declarationEmitShadowing.ts, 0, 25)) +>T : Symbol(T, Decl(declarationEmitShadowing.ts, 1, 55)) +>T : Symbol(T, Decl(declarationEmitShadowing.ts, 1, 55)) + + return null as any + } +} + +export function needsRenameForShadowing<T>() { +>needsRenameForShadowing : Symbol(needsRenameForShadowing, Decl(declarationEmitShadowing.ts, 4, 1)) +>T : Symbol(T, Decl(declarationEmitShadowing.ts, 6, 40)) + + type A = T +>A : Symbol(A, Decl(declarationEmitShadowing.ts, 6, 46)) +>T : Symbol(T, Decl(declarationEmitShadowing.ts, 6, 40)) + + return function O<T>(t: A, t2: T) { +>O : Symbol(O, Decl(declarationEmitShadowing.ts, 8, 8)) +>T : Symbol(T, Decl(declarationEmitShadowing.ts, 8, 20)) +>t : Symbol(t, Decl(declarationEmitShadowing.ts, 8, 23)) +>A : Symbol(A, Decl(declarationEmitShadowing.ts, 6, 46)) +>t2 : Symbol(t2, Decl(declarationEmitShadowing.ts, 8, 28)) +>T : Symbol(T, Decl(declarationEmitShadowing.ts, 8, 20)) + } +} + diff --git a/tests/baselines/reference/declarationEmitShadowing.types b/tests/baselines/reference/declarationEmitShadowing.types new file mode 100644 index 0000000000000..014d0569cfe30 --- /dev/null +++ b/tests/baselines/reference/declarationEmitShadowing.types @@ -0,0 +1,38 @@ +//// [tests/cases/compiler/declarationEmitShadowing.ts] //// + +=== declarationEmitShadowing.ts === +export class A<T = any> { +>A : A<T> +> : ^^^^ + + public readonly ShadowedButDoesNotRequireRenaming = <T>(): T => { +>ShadowedButDoesNotRequireRenaming : <T_1>() => T_1 +> : ^^^^^^^^^^^ +><T>(): T => { return null as any } : <T_1>() => T_1 +> : ^^^^^^^^^^^ + + return null as any +>null as any : any + } +} + +export function needsRenameForShadowing<T>() { +>needsRenameForShadowing : <T>() => <T_1>(t: T, t2: T_1) => void +> : ^ ^^^^^^^^ ^^ ^^^ ^^^^^^^^^ + + type A = T +>A : T +> : ^ + + return function O<T>(t: A, t2: T) { +>function O<T>(t: A, t2: T) { } : <T_1>(t: T, t2: T_1) => void +> : ^^^^^^ ^^^^^ ^^ ^^^^^^^^^ +>O : <T>(t: T_1, t2: T) => void +> : ^ ^^ ^^^^^^^ ^^ ^^^^^^^^^ +>t : T_1 +> : ^^^ +>t2 : T +> : ^ + } +} + diff --git a/tests/cases/compiler/declarationEmitShadowing.ts b/tests/cases/compiler/declarationEmitShadowing.ts new file mode 100644 index 0000000000000..53c00fbc455a9 --- /dev/null +++ b/tests/cases/compiler/declarationEmitShadowing.ts @@ -0,0 +1,13 @@ +// @declaration: true + +export class A<T = any> { + public readonly ShadowedButDoesNotRequireRenaming = <T>(): T => { + return null as any + } +} + +export function needsRenameForShadowing<T>() { + type A = T + return function O<T>(t: A, t2: T) { + } +}
diff --git a/src/compiler/expressionToTypeNode.ts b/src/compiler/expressionToTypeNode.ts index ad4f8321066e9..d754947177c52 100644 --- a/src/compiler/expressionToTypeNode.ts +++ b/src/compiler/expressionToTypeNode.ts @@ -1123,15 +1123,16 @@ export function createSyntacticTypeNodeBuilder( ); function reuseTypeParameters(typeParameters: NodeArray<TypeParameterDeclaration> | undefined, context: SyntacticTypeNodeBuilderContext) { - return typeParameters?.map(tp => - factory.updateTypeParameterDeclaration( + return typeParameters?.map(tp => { + const { node: tpName } = resolver.trackExistingEntityName(context, tp.name); + return factory.updateTypeParameterDeclaration( tp, tp.modifiers?.map(m => reuseNode(context, m)), - reuseNode(context, tp.name), + tpName, serializeExistingTypeNodeWithFallback(tp.constraint, context), serializeExistingTypeNodeWithFallback(tp.default, context), - ) - ); + }); function typeFromObjectLiteralMethod(method: MethodDeclaration, name: PropertyName, context: SyntacticTypeNodeBuilderContext, isConstContext: boolean) { diff --git a/tests/baselines/reference/declarationEmitShadowing.js b/tests/baselines/reference/declarationEmitShadowing.js index 0000000000000..e3ec2b61204d4 +++ b/tests/baselines/reference/declarationEmitShadowing.js @@ -0,0 +1,41 @@ +//// [declarationEmitShadowing.ts] +//// [declarationEmitShadowing.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.A = void 0; +var A = /** @class */ (function () { + function A() { + this.ShadowedButDoesNotRequireRenaming = function () { + return null; + }; + } + return A; +}()); +exports.A = A; +function needsRenameForShadowing() { + return function O(t, t2) { + readonly ShadowedButDoesNotRequireRenaming: <T_1>() => T_1; diff --git a/tests/baselines/reference/declarationEmitShadowing.symbols b/tests/baselines/reference/declarationEmitShadowing.symbols index 0000000000000..06f127f02fa72 +++ b/tests/baselines/reference/declarationEmitShadowing.symbols @@ -0,0 +1,34 @@ +>A : Symbol(A, Decl(declarationEmitShadowing.ts, 0, 0)) +>T : Symbol(T, Decl(declarationEmitShadowing.ts, 0, 15)) +>ShadowedButDoesNotRequireRenaming : Symbol(A.ShadowedButDoesNotRequireRenaming, Decl(declarationEmitShadowing.ts, 0, 25)) +>O : Symbol(O, Decl(declarationEmitShadowing.ts, 8, 8)) +>t : Symbol(t, Decl(declarationEmitShadowing.ts, 8, 23)) +>t2 : Symbol(t2, Decl(declarationEmitShadowing.ts, 8, 28)) diff --git a/tests/baselines/reference/declarationEmitShadowing.types b/tests/baselines/reference/declarationEmitShadowing.types index 0000000000000..014d0569cfe30 +++ b/tests/baselines/reference/declarationEmitShadowing.types @@ -0,0 +1,38 @@ +>A : A<T> +> : ^^^^ +>ShadowedButDoesNotRequireRenaming : <T_1>() => T_1 +><T>(): T => { return null as any } : <T_1>() => T_1 +>null as any : any +>needsRenameForShadowing : <T>() => <T_1>(t: T, t2: T_1) => void +> : ^ ^^^^^^^^ ^^ ^^^ ^^^^^^^^^ +>A : T +> : ^ +>function O<T>(t: A, t2: T) { } : <T_1>(t: T, t2: T_1) => void +> : ^^^^^^ ^^^^^ ^^ ^^^^^^^^^ +>O : <T>(t: T_1, t2: T) => void +> : ^ ^^ ^^^^^^^ ^^ ^^^^^^^^^ +>t : T_1 +> : ^^^ +>t2 : T +> : ^ diff --git a/tests/cases/compiler/declarationEmitShadowing.ts b/tests/cases/compiler/declarationEmitShadowing.ts index 0000000000000..53c00fbc455a9 +++ b/tests/cases/compiler/declarationEmitShadowing.ts @@ -0,0 +1,13 @@ +// @declaration: true
[ "+ );", "+exports.needsRenameForShadowing = needsRenameForShadowing;", "+ };", "+//// [declarationEmitShadowing.d.ts]", "+export declare class A<T = any> {", "+export declare function needsRenameForShadowing<T>(): <T_1>(t: T, t2: T_1) => void;", "+>needsRenameForShadowing : Symbol(needsRenameForShadowing, Decl(declarationEmitShadowing.ts, 4, 1))", "+> : ^^^^^^^^^^^ ", "+> : ^^^^^^^^^^^ " ]
[ 21, 52, 64, 68, 69, 72, 96, 128, 130 ]
{ "additions": 132, "author": "typescript-bot", "deletions": 5, "html_url": "https://github.com/microsoft/TypeScript/pull/61345", "issue_id": 61345, "merged_at": "2025-03-19T21:53:48Z", "omission_probability": 0.1, "pr_number": 61345, "repo": "microsoft/TypeScript", "title": "🤖 Pick PR #61342 (Rename type parameters when they ar...) into release-5.8", "total_changes": 137 }
64
diff --git a/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl index 857e007dbff90..e3eac2d03f42e 100644 --- a/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -11391,12 +11391,18 @@ <Item ItemId=";Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Project '{0}' can't be built because its dependency '{1}' has errors]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[无法生成项目“{0}”,因为其依赖项“{1}”有错误]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> <Item ItemId=";Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Project '{0}' can't be built because its dependency '{1}' was not built]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[无法生成项目 "{0}" ,因为未生成其依赖项 "{1}"]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> @@ -13350,12 +13356,18 @@ <Item ItemId=";Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Skipping build of project '{0}' because its dependency '{1}' has errors]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[正在跳过项目“{0}”的生成,因为其依赖项“{1}”有错误]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> <Item ItemId=";Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Skipping build of project '{0}' because its dependency '{1}' was not built]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[即将跳过项目 "{0}" 的生成,因为未生成其依赖项 "{1}"]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> diff --git a/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl index 7f3d86df295aa..520f91b11de06 100644 --- a/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -11391,12 +11391,18 @@ <Item ItemId=";Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Project '{0}' can't be built because its dependency '{1}' has errors]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[因為專案 '{0}' 的相依性 '{1}' 發生錯誤,所以無法建置該專案]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> <Item ItemId=";Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Project '{0}' can't be built because its dependency '{1}' was not built]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[因為未建置專案 '{0}' 的相依性 '{1}',所以無法建置該專案]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> @@ -13350,12 +13356,18 @@ <Item ItemId=";Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Skipping build of project '{0}' because its dependency '{1}' has errors]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[因為專案 '{0}' 的相依性 '{1}' 發生錯誤,所以跳過建置該專案]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> <Item ItemId=";Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Skipping build of project '{0}' because its dependency '{1}' was not built]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[因為未建置專案 '{0}' 的相依性 '{1}',所以正在跳過該專案的組建]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> diff --git a/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl index cd0fe7d510832..88df03446cb11 100644 --- a/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -11400,12 +11400,18 @@ <Item ItemId=";Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Project '{0}' can't be built because its dependency '{1}' has errors]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Projekt {0} nejde sestavit, protože jeho závislost {1} obsahuje chyby.]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> <Item ItemId=";Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Project '{0}' can't be built because its dependency '{1}' was not built]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Projekt {0} nejde sestavit, protože se nesestavila jeho závislost {1}.]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> @@ -13359,12 +13365,18 @@ <Item ItemId=";Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Skipping build of project '{0}' because its dependency '{1}' has errors]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Sestavení projektu {0} se přeskakuje, protože jeho závislost {1} obsahuje chyby.]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> <Item ItemId=";Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Skipping build of project '{0}' because its dependency '{1}' was not built]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Sestavení projektu {0} se přeskakuje, protože se nesestavila jeho závislost {1}.]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> diff --git a/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl index 8d0ec0976a102..47990786ca940 100644 --- a/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -11385,12 +11385,18 @@ <Item ItemId=";Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Project '{0}' can't be built because its dependency '{1}' has errors]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Projekt "{0}" kann nicht erstellt werden, weil die Abhängigkeit "{1}" Fehler enthält.]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> <Item ItemId=";Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Project '{0}' can't be built because its dependency '{1}' was not built]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Das Projekt "{0}" kann nicht erstellt werden, weil die zugehörige Abhängigkeit "{1}" nicht erstellt wurde.]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> @@ -13344,12 +13350,18 @@ <Item ItemId=";Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Skipping build of project '{0}' because its dependency '{1}' has errors]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Das Erstellen von Projekt "{0}" wird übersprungen, weil die Abhängigkeit "{1}" einen Fehler aufweist.]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> <Item ItemId=";Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Skipping build of project '{0}' because its dependency '{1}' was not built]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Das Kompilieren von Projekt "{0}" wird übersprungen, weil die Abhängigkeit "{1}" nicht erstellt wurde.]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> diff --git a/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl index a24cd15b61e6d..976779497e7b9 100644 --- a/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -11403,12 +11403,18 @@ <Item ItemId=";Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Project '{0}' can't be built because its dependency '{1}' has errors]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[El proyecto "{0}" no puede generarse porque su dependencia "{1}" tiene errores]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> <Item ItemId=";Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Project '{0}' can't be built because its dependency '{1}' was not built]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[El proyecto "{0}" no puede compilarse porque su dependencia "{1}" no se ha compilado.]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> @@ -13362,12 +13368,18 @@ <Item ItemId=";Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Skipping build of project '{0}' because its dependency '{1}' has errors]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Omitiendo la compilación del proyecto "{0}" porque su dependencia "{1}" tiene errores]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> <Item ItemId=";Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Skipping build of project '{0}' because its dependency '{1}' was not built]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Omitiendo la compilación del proyecto "{0}" porque su dependencia "{1}" no se ha compilado]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> diff --git a/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl index a514aa1a91893..c2bfb3cc811a2 100644 --- a/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -11403,12 +11403,18 @@ <Item ItemId=";Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Project '{0}' can't be built because its dependency '{1}' has errors]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Impossible de générer le projet '{0}' car sa dépendance '{1}' comporte des erreurs]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> <Item ItemId=";Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Project '{0}' can't be built because its dependency '{1}' was not built]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Impossible de générer le projet '{0}', car sa dépendance '{1}' n'a pas été générée]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> @@ -13362,12 +13368,18 @@ <Item ItemId=";Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Skipping build of project '{0}' because its dependency '{1}' has errors]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Ignorer la génération du projet '{0}' car sa dépendance '{1}' comporte des erreurs]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> <Item ItemId=";Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Skipping build of project '{0}' because its dependency '{1}' was not built]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Ignorer la build du projet '{0}', car sa dépendance '{1}' n'a pas été générée]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> diff --git a/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl index b77b61764b2bd..e2c1a25a4615c 100644 --- a/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -11391,12 +11391,18 @@ <Item ItemId=";Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Project '{0}' can't be built because its dependency '{1}' has errors]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Non è possibile compilare il progetto '{0}' perché la dipendenza '{1}' contiene errori]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> <Item ItemId=";Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Project '{0}' can't be built because its dependency '{1}' was not built]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Non è possibile compilare il progetto '{0}' perché la relativa dipendenza '{1}' non è stata compilata]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> @@ -13350,12 +13356,18 @@ <Item ItemId=";Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Skipping build of project '{0}' because its dependency '{1}' has errors]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[La compilazione del progetto '{0}' verrà ignorata perché la dipendenza '{1}' contiene errori]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> <Item ItemId=";Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Skipping build of project '{0}' because its dependency '{1}' was not built]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[La compilazione del progetto '{0}' verrà ignorata perché la dipendenza '{1}' non è stata compilata]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> diff --git a/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl index 929d85c8a4cbe..ba31bc33c943d 100644 --- a/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -11391,12 +11391,18 @@ <Item ItemId=";Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Project '{0}' can't be built because its dependency '{1}' has errors]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[プロジェクト '{0}' はその依存関係 '{1}' にエラーがあるためビルドできません]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> <Item ItemId=";Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Project '{0}' can't be built because its dependency '{1}' was not built]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[依存関係 '{1}' がビルドされていないため、プロジェクト '{0}' はビルドできません]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> @@ -13350,12 +13356,18 @@ <Item ItemId=";Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Skipping build of project '{0}' because its dependency '{1}' has errors]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[プロジェクト '{0}' のビルドは、その依存関係 '{1}' にエラーがあるため、スキップしています]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> <Item ItemId=";Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Skipping build of project '{0}' because its dependency '{1}' was not built]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[依存関係 '{1}' がビルドされていないため、プロジェクト '{0}' のビルドをスキップしています]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> diff --git a/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl index 3881baed4ea08..0df4432d102da 100644 --- a/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -11391,12 +11391,18 @@ <Item ItemId=";Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Project '{0}' can't be built because its dependency '{1}' has errors]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA['{0}' 프로젝트는 '{1}' 종속성에 오류가 있기 때문에 빌드할 수 없습니다.]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> <Item ItemId=";Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Project '{0}' can't be built because its dependency '{1}' was not built]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA['{1}' 종속성이 빌드되지 않았기 때문에 '{0}' 프로젝트를 빌드할 수 없습니다.]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> @@ -13350,12 +13356,18 @@ <Item ItemId=";Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Skipping build of project '{0}' because its dependency '{1}' has errors]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA['{0}' 프로젝트의 빌드는 '{1}' 종속성에 오류가 있기 때문에 건너뜁니다.]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> <Item ItemId=";Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Skipping build of project '{0}' because its dependency '{1}' was not built]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA['{1}' 종속성이 빌드되지 않았기 때문에 '{0}' 프로젝트의 빌드를 건너뛰는 중]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> diff --git a/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl index 1d63900fb1627..8cb1aff1e8da5 100644 --- a/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -11378,12 +11378,18 @@ <Item ItemId=";Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Project '{0}' can't be built because its dependency '{1}' has errors]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Nie można skompilować projektu „{0}”, ponieważ jego zależność „{1}” zawiera błędy]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> <Item ItemId=";Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Project '{0}' can't be built because its dependency '{1}' was not built]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Nie można skompilować projektu „{0}”, ponieważ jego zależność „{1}” nie została skompilowania]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> @@ -13337,12 +13343,18 @@ <Item ItemId=";Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Skipping build of project '{0}' because its dependency '{1}' has errors]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Pomijanie kompilacji projektu „{0}”, ponieważ jego zależność „{1}” zawiera błędy]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> <Item ItemId=";Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Skipping build of project '{0}' because its dependency '{1}' was not built]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Pomijanie kompilacji projektu „{0}”, ponieważ jego zależność „{1}” nie została skompilowana]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> diff --git a/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl index bcfe2e5092305..d83955c806a83 100644 --- a/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -11381,12 +11381,18 @@ <Item ItemId=";Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Project '{0}' can't be built because its dependency '{1}' has errors]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[O projeto '{0}' não pode ser compilado porque sua dependência '{1}' tem erros]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> <Item ItemId=";Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Project '{0}' can't be built because its dependency '{1}' was not built]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[O projeto '{0}' não pode ser criado porque sua dependência '{1}' não foi criada]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> @@ -13340,12 +13346,18 @@ <Item ItemId=";Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Skipping build of project '{0}' because its dependency '{1}' has errors]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Ignorando o build do projeto '{0}' porque a dependência '{1}' tem erros]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> <Item ItemId=";Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Skipping build of project '{0}' because its dependency '{1}' was not built]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Ignorando o build do projeto '{0}' porque a dependência '{1}' não foi criada]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> diff --git a/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl index cebc482da2c3a..8b813746aa106 100644 --- a/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -11390,12 +11390,18 @@ <Item ItemId=";Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Project '{0}' can't be built because its dependency '{1}' has errors]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Не удается собрать проект "{0}", так как его зависимость "{1}" содержит ошибки]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> <Item ItemId=";Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Project '{0}' can't be built because its dependency '{1}' was not built]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Не удается собрать проект "{0}", так как его зависимость "{1}" не была собрана]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> @@ -13349,12 +13355,18 @@ <Item ItemId=";Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Skipping build of project '{0}' because its dependency '{1}' has errors]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Сборка проекта "{0}" будет пропущена, так как его зависимость "{1}" содержит ошибки]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> <Item ItemId=";Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Skipping build of project '{0}' because its dependency '{1}' was not built]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Сборка проекта "{0}" будет пропущена, так как его зависимость "{1}" не была собрана]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> diff --git a/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl index 7d3513f3dd423..76cffc44e5a7a 100644 --- a/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -11384,12 +11384,18 @@ <Item ItemId=";Project_0_can_t_be_built_because_its_dependency_1_has_errors_6363" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Project '{0}' can't be built because its dependency '{1}' has errors]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA['{0}' projesinin '{1}' bağımlılığında hatalar olduğundan proje derlenemiyor]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> <Item ItemId=";Project_0_can_t_be_built_because_its_dependency_1_was_not_built_6383" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Project '{0}' can't be built because its dependency '{1}' was not built]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA['{0}' projesinin '{1}' bağımlılığı derlenmediğinden proje derlenemiyor]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> @@ -13343,12 +13349,18 @@ <Item ItemId=";Skipping_build_of_project_0_because_its_dependency_1_has_errors_6362" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Skipping build of project '{0}' because its dependency '{1}' has errors]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA['{0}' projesinin '{1}' bağımlılığında hatalar olduğundan projenin derlenmesi atlanıyor]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item> <Item ItemId=";Skipping_build_of_project_0_because_its_dependency_1_was_not_built_6382" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[Skipping build of project '{0}' because its dependency '{1}' was not built]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA['{0}' projesinin '{1}' bağımlılığı derlenmediğinden projenin derlenmesi atlanıyor]]></Val> + </Tgt> </Str> <Disp Icon="Str" /> </Item>
diff --git a/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl index 857e007dbff90..e3eac2d03f42e 100644 --- a/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl + <Val><![CDATA[无法生成项目“{0}”,因为其依赖项“{1}”有错误]]></Val> + <Val><![CDATA[无法生成项目 "{0}" ,因为未生成其依赖项 "{1}"]]></Val> + <Val><![CDATA[正在跳过项目“{0}”的生成,因为其依赖项“{1}”有错误]]></Val> + <Val><![CDATA[即将跳过项目 "{0}" 的生成,因为未生成其依赖项 "{1}"]]></Val> diff --git a/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl index 7f3d86df295aa..520f91b11de06 100644 --- a/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl + <Val><![CDATA[因為專案 '{0}' 的相依性 '{1}' 發生錯誤,所以無法建置該專案]]></Val> + <Val><![CDATA[因為未建置專案 '{0}' 的相依性 '{1}',所以無法建置該專案]]></Val> + <Val><![CDATA[因為專案 '{0}' 的相依性 '{1}' 發生錯誤,所以跳過建置該專案]]></Val> + <Val><![CDATA[因為未建置專案 '{0}' 的相依性 '{1}',所以正在跳過該專案的組建]]></Val> diff --git a/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl index cd0fe7d510832..88df03446cb11 100644 --- a/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -11400,12 +11400,18 @@ + <Val><![CDATA[Projekt {0} nejde sestavit, protože jeho závislost {1} obsahuje chyby.]]></Val> + <Val><![CDATA[Projekt {0} nejde sestavit, protože se nesestavila jeho závislost {1}.]]></Val> @@ -13359,12 +13365,18 @@ + <Val><![CDATA[Sestavení projektu {0} se přeskakuje, protože jeho závislost {1} obsahuje chyby.]]></Val> + <Val><![CDATA[Sestavení projektu {0} se přeskakuje, protože se nesestavila jeho závislost {1}.]]></Val> diff --git a/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl index 8d0ec0976a102..47990786ca940 100644 --- a/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -11385,12 +11385,18 @@ + <Val><![CDATA[Das Projekt "{0}" kann nicht erstellt werden, weil die zugehörige Abhängigkeit "{1}" nicht erstellt wurde.]]></Val> @@ -13344,12 +13350,18 @@ + <Val><![CDATA[Das Erstellen von Projekt "{0}" wird übersprungen, weil die Abhängigkeit "{1}" einen Fehler aufweist.]]></Val> + <Val><![CDATA[Das Kompilieren von Projekt "{0}" wird übersprungen, weil die Abhängigkeit "{1}" nicht erstellt wurde.]]></Val> diff --git a/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl index a24cd15b61e6d..976779497e7b9 100644 --- a/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl + <Val><![CDATA[El proyecto "{0}" no puede generarse porque su dependencia "{1}" tiene errores]]></Val> + <Val><![CDATA[El proyecto "{0}" no puede compilarse porque su dependencia "{1}" no se ha compilado.]]></Val> + <Val><![CDATA[Omitiendo la compilación del proyecto "{0}" porque su dependencia "{1}" tiene errores]]></Val> diff --git a/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl index a514aa1a91893..c2bfb3cc811a2 100644 --- a/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl + <Val><![CDATA[Impossible de générer le projet '{0}' car sa dépendance '{1}' comporte des erreurs]]></Val> + <Val><![CDATA[Impossible de générer le projet '{0}', car sa dépendance '{1}' n'a pas été générée]]></Val> + <Val><![CDATA[Ignorer la génération du projet '{0}' car sa dépendance '{1}' comporte des erreurs]]></Val> diff --git a/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl index b77b61764b2bd..e2c1a25a4615c 100644 --- a/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl + <Val><![CDATA[Non è possibile compilare il progetto '{0}' perché la dipendenza '{1}' contiene errori]]></Val> + <Val><![CDATA[La compilazione del progetto '{0}' verrà ignorata perché la dipendenza '{1}' contiene errori]]></Val> + <Val><![CDATA[La compilazione del progetto '{0}' verrà ignorata perché la dipendenza '{1}' non è stata compilata]]></Val> diff --git a/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl index 929d85c8a4cbe..ba31bc33c943d 100644 --- a/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl + <Val><![CDATA[プロジェクト '{0}' はその依存関係 '{1}' にエラーがあるためビルドできません]]></Val> + <Val><![CDATA[依存関係 '{1}' がビルドされていないため、プロジェクト '{0}' はビルドできません]]></Val> + <Val><![CDATA[プロジェクト '{0}' のビルドは、その依存関係 '{1}' にエラーがあるため、スキップしています]]></Val> + <Val><![CDATA[依存関係 '{1}' がビルドされていないため、プロジェクト '{0}' のビルドをスキップしています]]></Val> diff --git a/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl index 3881baed4ea08..0df4432d102da 100644 --- a/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl + <Val><![CDATA['{0}' 프로젝트는 '{1}' 종속성에 오류가 있기 때문에 빌드할 수 없습니다.]]></Val> + <Val><![CDATA['{1}' 종속성이 빌드되지 않았기 때문에 '{0}' 프로젝트를 빌드할 수 없습니다.]]></Val> + <Val><![CDATA['{0}' 프로젝트의 빌드는 '{1}' 종속성에 오류가 있기 때문에 건너뜁니다.]]></Val> + <Val><![CDATA['{1}' 종속성이 빌드되지 않았기 때문에 '{0}' 프로젝트의 빌드를 건너뛰는 중]]></Val> diff --git a/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl index 1d63900fb1627..8cb1aff1e8da5 100644 --- a/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -11378,12 +11378,18 @@ + <Val><![CDATA[Nie można skompilować projektu „{0}”, ponieważ jego zależność „{1}” zawiera błędy]]></Val> @@ -13337,12 +13343,18 @@ + <Val><![CDATA[Pomijanie kompilacji projektu „{0}”, ponieważ jego zależność „{1}” nie została skompilowana]]></Val> diff --git a/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl index bcfe2e5092305..d83955c806a83 100644 --- a/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -11381,12 +11381,18 @@ + <Val><![CDATA[O projeto '{0}' não pode ser compilado porque sua dependência '{1}' tem erros]]></Val> + <Val><![CDATA[O projeto '{0}' não pode ser criado porque sua dependência '{1}' não foi criada]]></Val> @@ -13340,12 +13346,18 @@ + <Val><![CDATA[Ignorando o build do projeto '{0}' porque a dependência '{1}' tem erros]]></Val> + <Val><![CDATA[Ignorando o build do projeto '{0}' porque a dependência '{1}' não foi criada]]></Val> diff --git a/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl index cebc482da2c3a..8b813746aa106 100644 --- a/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -11390,12 +11390,18 @@ + <Val><![CDATA[Не удается собрать проект "{0}", так как его зависимость "{1}" содержит ошибки]]></Val> + <Val><![CDATA[Не удается собрать проект "{0}", так как его зависимость "{1}" не была собрана]]></Val> @@ -13349,12 +13355,18 @@ + <Val><![CDATA[Сборка проекта "{0}" будет пропущена, так как его зависимость "{1}" содержит ошибки]]></Val> diff --git a/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl index 7d3513f3dd423..76cffc44e5a7a 100644 --- a/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -11384,12 +11384,18 @@ + <Val><![CDATA['{0}' projesinin '{1}' bağımlılığında hatalar olduğundan proje derlenemiyor]]></Val> + <Val><![CDATA['{0}' projesinin '{1}' bağımlılığı derlenmediğinden proje derlenemiyor]]></Val> @@ -13343,12 +13349,18 @@ + <Val><![CDATA['{0}' projesinin '{1}' bağımlılığında hatalar olduğundan projenin derlenmesi atlanıyor]]></Val> + <Val><![CDATA['{0}' projesinin '{1}' bağımlılığı derlenmediğinden projenin derlenmesi atlanıyor]]></Val>
[ "+ <Val><![CDATA[Projekt \"{0}\" kann nicht erstellt werden, weil die Abhängigkeit \"{1}\" Fehler enthält.]]></Val>", "+ <Val><![CDATA[Omitiendo la compilación del proyecto \"{0}\" porque su dependencia \"{1}\" no se ha compilado]]></Val>", "+ <Val><![CDATA[Ignorer la build du projet '{0}', car sa dépendance '{1}' n'a pas été générée]]></Val>", "+ <Val><![CDATA[Non è possibile compilare il progetto '{0}' perché la relativa dipendenza '{1}' non è stata compilata]]></Val>", "+ <Val><![CDATA[Nie można skompilować projektu „{0}”, ponieważ jego zależność „{1}” nie została skompilowania]]></Val>", "+ <Val><![CDATA[Pomijanie kompilacji projektu „{0}”, ponieważ jego zależność „{1}” zawiera błędy]]></Val>", "+ <Val><![CDATA[Сборка проекта \"{0}\" будет пропущена, так как его зависимость \"{1}\" не была собрана]]></Val>" ]
[ 135, 205, 247, 270, 396, 406, 499 ]
{ "additions": 156, "author": "csigs", "deletions": 0, "html_url": "https://github.com/microsoft/TypeScript/pull/61368", "issue_id": 61368, "merged_at": "2025-03-06T20:41:55Z", "omission_probability": 0.1, "pr_number": 61368, "repo": "microsoft/TypeScript", "title": "LEGO: Pull request from lego/hb_5378966c-b857-470a-8675-daebef4a6da1_20250306202248269 to main", "total_changes": 156 }
65
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index abd6fd4bf2e8d..8797dbbf80137 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -47974,7 +47974,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return; } - if (compilerOptions.erasableSyntaxOnly && !(node.flags & NodeFlags.Ambient)) { + if (compilerOptions.erasableSyntaxOnly && node.isExportEquals && !(node.flags & NodeFlags.Ambient)) { error(node, Diagnostics.This_syntax_is_not_allowed_when_erasableSyntaxOnly_is_enabled); } const container = node.parent.kind === SyntaxKind.SourceFile ? node.parent : node.parent.parent as ModuleDeclaration; diff --git a/tests/baselines/reference/erasableSyntaxOnly.errors.txt b/tests/baselines/reference/erasableSyntaxOnly.errors.txt index 39a724aa00c51..2005ef65de8e7 100644 --- a/tests/baselines/reference/erasableSyntaxOnly.errors.txt +++ b/tests/baselines/reference/erasableSyntaxOnly.errors.txt @@ -104,4 +104,9 @@ index.ts(28,12): error TS1294: This syntax is not allowed when 'erasableSyntaxOn ==== other.d.cts (0 errors) ==== declare function foo(): void; export = foo; + + +==== esm.mts (0 errors) ==== + const foo = 1234; + export default foo; \ No newline at end of file diff --git a/tests/baselines/reference/erasableSyntaxOnly.js b/tests/baselines/reference/erasableSyntaxOnly.js index 1d7393620df4d..9edf749d7b038 100644 --- a/tests/baselines/reference/erasableSyntaxOnly.js +++ b/tests/baselines/reference/erasableSyntaxOnly.js @@ -74,6 +74,11 @@ export = foo; //// [other.d.cts] declare function foo(): void; export = foo; + + +//// [esm.mts] +const foo = 1234; +export default foo; //// [index.js] @@ -119,3 +124,6 @@ var MyClassOk = /** @class */ (function () { "use strict"; var foo = require("./other.cjs"); module.exports = foo; +//// [esm.mjs] +var foo = 1234; +export default foo; diff --git a/tests/baselines/reference/erasableSyntaxOnly.symbols b/tests/baselines/reference/erasableSyntaxOnly.symbols index f0220004341b3..8e057dc990217 100644 --- a/tests/baselines/reference/erasableSyntaxOnly.symbols +++ b/tests/baselines/reference/erasableSyntaxOnly.symbols @@ -133,3 +133,11 @@ declare function foo(): void; export = foo; >foo : Symbol(foo, Decl(other.d.cts, 0, 0)) + +=== esm.mts === +const foo = 1234; +>foo : Symbol(foo, Decl(esm.mts, 0, 5)) + +export default foo; +>foo : Symbol(foo, Decl(esm.mts, 0, 5)) + diff --git a/tests/baselines/reference/erasableSyntaxOnly.types b/tests/baselines/reference/erasableSyntaxOnly.types index 599a8d2125ead..4d4ddaea49701 100644 --- a/tests/baselines/reference/erasableSyntaxOnly.types +++ b/tests/baselines/reference/erasableSyntaxOnly.types @@ -179,3 +179,15 @@ export = foo; >foo : () => void > : ^^^^^^ + +=== esm.mts === +const foo = 1234; +>foo : 1234 +> : ^^^^ +>1234 : 1234 +> : ^^^^ + +export default foo; +>foo : 1234 +> : ^^^^ + diff --git a/tests/baselines/reference/erasableSyntaxOnlyDeclaration.errors.txt b/tests/baselines/reference/erasableSyntaxOnlyDeclaration.errors.txt index 7bc78e382b7ed..fdb4d96f8498b 100644 --- a/tests/baselines/reference/erasableSyntaxOnlyDeclaration.errors.txt +++ b/tests/baselines/reference/erasableSyntaxOnlyDeclaration.errors.txt @@ -65,4 +65,9 @@ index.d.ts(1,1): error TS1046: Top-level declarations in .d.ts files must start ==== other.d.cts (0 errors) ==== declare function foo(): void; export = foo; + + +==== esm.d.mts (0 errors) ==== + declare const foo = 1234; + export default foo; \ No newline at end of file diff --git a/tests/baselines/reference/erasableSyntaxOnlyDeclaration.symbols b/tests/baselines/reference/erasableSyntaxOnlyDeclaration.symbols index 4f439b211c5c3..2763999d6468b 100644 --- a/tests/baselines/reference/erasableSyntaxOnlyDeclaration.symbols +++ b/tests/baselines/reference/erasableSyntaxOnlyDeclaration.symbols @@ -112,3 +112,11 @@ declare function foo(): void; export = foo; >foo : Symbol(foo, Decl(other.d.cts, 0, 0)) + +=== esm.d.mts === +declare const foo = 1234; +>foo : Symbol(foo, Decl(esm.d.mts, 0, 13)) + +export default foo; +>foo : Symbol(foo, Decl(esm.d.mts, 0, 13)) + diff --git a/tests/baselines/reference/erasableSyntaxOnlyDeclaration.types b/tests/baselines/reference/erasableSyntaxOnlyDeclaration.types index 031eb9bbb59cb..053aa1b60d2e4 100644 --- a/tests/baselines/reference/erasableSyntaxOnlyDeclaration.types +++ b/tests/baselines/reference/erasableSyntaxOnlyDeclaration.types @@ -154,3 +154,15 @@ export = foo; >foo : () => void > : ^^^^^^ + +=== esm.d.mts === +declare const foo = 1234; +>foo : 1234 +> : ^^^^ +>1234 : 1234 +> : ^^^^ + +export default foo; +>foo : 1234 +> : ^^^^ + diff --git a/tests/cases/compiler/erasableSyntaxOnly.ts b/tests/cases/compiler/erasableSyntaxOnly.ts index 6a76e80337e11..d2ff6d72ce8f3 100644 --- a/tests/cases/compiler/erasableSyntaxOnly.ts +++ b/tests/cases/compiler/erasableSyntaxOnly.ts @@ -74,3 +74,8 @@ export = foo; // @filename: other.d.cts declare function foo(): void; export = foo; + + +// @filename: esm.mts +const foo = 1234; +export default foo; diff --git a/tests/cases/compiler/erasableSyntaxOnlyDeclaration.ts b/tests/cases/compiler/erasableSyntaxOnlyDeclaration.ts index f87e2346f094b..3a986719a160c 100644 --- a/tests/cases/compiler/erasableSyntaxOnlyDeclaration.ts +++ b/tests/cases/compiler/erasableSyntaxOnlyDeclaration.ts @@ -66,3 +66,8 @@ export = foo; // @filename: other.d.cts declare function foo(): void; export = foo; + + +// @filename: esm.d.mts +declare const foo = 1234; +export default foo;
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index abd6fd4bf2e8d..8797dbbf80137 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -47974,7 +47974,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return; - if (compilerOptions.erasableSyntaxOnly && !(node.flags & NodeFlags.Ambient)) { + if (compilerOptions.erasableSyntaxOnly && node.isExportEquals && !(node.flags & NodeFlags.Ambient)) { error(node, Diagnostics.This_syntax_is_not_allowed_when_erasableSyntaxOnly_is_enabled); const container = node.parent.kind === SyntaxKind.SourceFile ? node.parent : node.parent.parent as ModuleDeclaration; diff --git a/tests/baselines/reference/erasableSyntaxOnly.errors.txt b/tests/baselines/reference/erasableSyntaxOnly.errors.txt index 39a724aa00c51..2005ef65de8e7 100644 --- a/tests/baselines/reference/erasableSyntaxOnly.errors.txt +++ b/tests/baselines/reference/erasableSyntaxOnly.errors.txt @@ -104,4 +104,9 @@ index.ts(28,12): error TS1294: This syntax is not allowed when 'erasableSyntaxOn + const foo = 1234; diff --git a/tests/baselines/reference/erasableSyntaxOnly.js b/tests/baselines/reference/erasableSyntaxOnly.js index 1d7393620df4d..9edf749d7b038 100644 --- a/tests/baselines/reference/erasableSyntaxOnly.js +++ b/tests/baselines/reference/erasableSyntaxOnly.js @@ -74,6 +74,11 @@ export = foo; //// [other.d.cts] +//// [esm.mts] //// [index.js] @@ -119,3 +124,6 @@ var MyClassOk = /** @class */ (function () { "use strict"; var foo = require("./other.cjs"); module.exports = foo; +var foo = 1234; diff --git a/tests/baselines/reference/erasableSyntaxOnly.symbols b/tests/baselines/reference/erasableSyntaxOnly.symbols index f0220004341b3..8e057dc990217 100644 --- a/tests/baselines/reference/erasableSyntaxOnly.symbols +++ b/tests/baselines/reference/erasableSyntaxOnly.symbols @@ -133,3 +133,11 @@ declare function foo(): void; diff --git a/tests/baselines/reference/erasableSyntaxOnly.types b/tests/baselines/reference/erasableSyntaxOnly.types index 599a8d2125ead..4d4ddaea49701 100644 --- a/tests/baselines/reference/erasableSyntaxOnly.types +++ b/tests/baselines/reference/erasableSyntaxOnly.types @@ -179,3 +179,15 @@ export = foo; diff --git a/tests/baselines/reference/erasableSyntaxOnlyDeclaration.errors.txt b/tests/baselines/reference/erasableSyntaxOnlyDeclaration.errors.txt index 7bc78e382b7ed..fdb4d96f8498b 100644 --- a/tests/baselines/reference/erasableSyntaxOnlyDeclaration.errors.txt +++ b/tests/baselines/reference/erasableSyntaxOnlyDeclaration.errors.txt @@ -65,4 +65,9 @@ index.d.ts(1,1): error TS1046: Top-level declarations in .d.ts files must start +==== esm.d.mts (0 errors) ==== + declare const foo = 1234; diff --git a/tests/baselines/reference/erasableSyntaxOnlyDeclaration.symbols b/tests/baselines/reference/erasableSyntaxOnlyDeclaration.symbols index 4f439b211c5c3..2763999d6468b 100644 --- a/tests/baselines/reference/erasableSyntaxOnlyDeclaration.symbols +++ b/tests/baselines/reference/erasableSyntaxOnlyDeclaration.symbols @@ -112,3 +112,11 @@ declare function foo(): void; diff --git a/tests/baselines/reference/erasableSyntaxOnlyDeclaration.types b/tests/baselines/reference/erasableSyntaxOnlyDeclaration.types index 031eb9bbb59cb..053aa1b60d2e4 100644 --- a/tests/baselines/reference/erasableSyntaxOnlyDeclaration.types +++ b/tests/baselines/reference/erasableSyntaxOnlyDeclaration.types @@ -154,3 +154,15 @@ export = foo; diff --git a/tests/cases/compiler/erasableSyntaxOnly.ts b/tests/cases/compiler/erasableSyntaxOnly.ts index 6a76e80337e11..d2ff6d72ce8f3 100644 --- a/tests/cases/compiler/erasableSyntaxOnly.ts +++ b/tests/cases/compiler/erasableSyntaxOnly.ts @@ -74,3 +74,8 @@ export = foo; +// @filename: esm.mts diff --git a/tests/cases/compiler/erasableSyntaxOnlyDeclaration.ts b/tests/cases/compiler/erasableSyntaxOnlyDeclaration.ts index f87e2346f094b..3a986719a160c 100644 --- a/tests/cases/compiler/erasableSyntaxOnlyDeclaration.ts +++ b/tests/cases/compiler/erasableSyntaxOnlyDeclaration.ts @@ -66,3 +66,8 @@ export = foo; +// @filename: esm.d.mts
[ "+==== esm.mts (0 errors) ====", "+//// [esm.mjs]" ]
[ 23, 48 ]
{ "additions": 69, "author": "jakebailey", "deletions": 1, "html_url": "https://github.com/microsoft/TypeScript/pull/61210", "issue_id": 61210, "merged_at": "2025-02-18T16:06:12Z", "omission_probability": 0.1, "pr_number": 61210, "repo": "microsoft/TypeScript", "title": "Fix mistakenly disallowed default export under erasableSyntaxOnly", "total_changes": 70 }
66
diff --git a/src/compiler/expressionToTypeNode.ts b/src/compiler/expressionToTypeNode.ts index 7ef64ad6375b5..73e176432d5ac 100644 --- a/src/compiler/expressionToTypeNode.ts +++ b/src/compiler/expressionToTypeNode.ts @@ -1122,15 +1122,16 @@ export function createSyntacticTypeNodeBuilder( ); } function reuseTypeParameters(typeParameters: NodeArray<TypeParameterDeclaration> | undefined, context: SyntacticTypeNodeBuilderContext) { - return typeParameters?.map(tp => - factory.updateTypeParameterDeclaration( + return typeParameters?.map(tp => { + const { node: tpName } = resolver.trackExistingEntityName(context, tp.name); + return factory.updateTypeParameterDeclaration( tp, tp.modifiers?.map(m => reuseNode(context, m)), - reuseNode(context, tp.name), + tpName, serializeExistingTypeNodeWithFallback(tp.constraint, context), serializeExistingTypeNodeWithFallback(tp.default, context), - ) - ); + ); + }); } function typeFromObjectLiteralMethod(method: MethodDeclaration, name: PropertyName, context: SyntacticTypeNodeBuilderContext, isConstContext: boolean) { diff --git a/tests/baselines/reference/declarationEmitShadowing.js b/tests/baselines/reference/declarationEmitShadowing.js new file mode 100644 index 0000000000000..e3ec2b61204d4 --- /dev/null +++ b/tests/baselines/reference/declarationEmitShadowing.js @@ -0,0 +1,41 @@ +//// [tests/cases/compiler/declarationEmitShadowing.ts] //// + +//// [declarationEmitShadowing.ts] +export class A<T = any> { + public readonly ShadowedButDoesNotRequireRenaming = <T>(): T => { + return null as any + } +} + +export function needsRenameForShadowing<T>() { + type A = T + return function O<T>(t: A, t2: T) { + } +} + + +//// [declarationEmitShadowing.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.A = void 0; +exports.needsRenameForShadowing = needsRenameForShadowing; +var A = /** @class */ (function () { + function A() { + this.ShadowedButDoesNotRequireRenaming = function () { + return null; + }; + } + return A; +}()); +exports.A = A; +function needsRenameForShadowing() { + return function O(t, t2) { + }; +} + + +//// [declarationEmitShadowing.d.ts] +export declare class A<T = any> { + readonly ShadowedButDoesNotRequireRenaming: <T_1>() => T_1; +} +export declare function needsRenameForShadowing<T>(): <T_1>(t: T, t2: T_1) => void; diff --git a/tests/baselines/reference/declarationEmitShadowing.symbols b/tests/baselines/reference/declarationEmitShadowing.symbols new file mode 100644 index 0000000000000..06f127f02fa72 --- /dev/null +++ b/tests/baselines/reference/declarationEmitShadowing.symbols @@ -0,0 +1,34 @@ +//// [tests/cases/compiler/declarationEmitShadowing.ts] //// + +=== declarationEmitShadowing.ts === +export class A<T = any> { +>A : Symbol(A, Decl(declarationEmitShadowing.ts, 0, 0)) +>T : Symbol(T, Decl(declarationEmitShadowing.ts, 0, 15)) + + public readonly ShadowedButDoesNotRequireRenaming = <T>(): T => { +>ShadowedButDoesNotRequireRenaming : Symbol(A.ShadowedButDoesNotRequireRenaming, Decl(declarationEmitShadowing.ts, 0, 25)) +>T : Symbol(T, Decl(declarationEmitShadowing.ts, 1, 55)) +>T : Symbol(T, Decl(declarationEmitShadowing.ts, 1, 55)) + + return null as any + } +} + +export function needsRenameForShadowing<T>() { +>needsRenameForShadowing : Symbol(needsRenameForShadowing, Decl(declarationEmitShadowing.ts, 4, 1)) +>T : Symbol(T, Decl(declarationEmitShadowing.ts, 6, 40)) + + type A = T +>A : Symbol(A, Decl(declarationEmitShadowing.ts, 6, 46)) +>T : Symbol(T, Decl(declarationEmitShadowing.ts, 6, 40)) + + return function O<T>(t: A, t2: T) { +>O : Symbol(O, Decl(declarationEmitShadowing.ts, 8, 8)) +>T : Symbol(T, Decl(declarationEmitShadowing.ts, 8, 20)) +>t : Symbol(t, Decl(declarationEmitShadowing.ts, 8, 23)) +>A : Symbol(A, Decl(declarationEmitShadowing.ts, 6, 46)) +>t2 : Symbol(t2, Decl(declarationEmitShadowing.ts, 8, 28)) +>T : Symbol(T, Decl(declarationEmitShadowing.ts, 8, 20)) + } +} + diff --git a/tests/baselines/reference/declarationEmitShadowing.types b/tests/baselines/reference/declarationEmitShadowing.types new file mode 100644 index 0000000000000..014d0569cfe30 --- /dev/null +++ b/tests/baselines/reference/declarationEmitShadowing.types @@ -0,0 +1,38 @@ +//// [tests/cases/compiler/declarationEmitShadowing.ts] //// + +=== declarationEmitShadowing.ts === +export class A<T = any> { +>A : A<T> +> : ^^^^ + + public readonly ShadowedButDoesNotRequireRenaming = <T>(): T => { +>ShadowedButDoesNotRequireRenaming : <T_1>() => T_1 +> : ^^^^^^^^^^^ +><T>(): T => { return null as any } : <T_1>() => T_1 +> : ^^^^^^^^^^^ + + return null as any +>null as any : any + } +} + +export function needsRenameForShadowing<T>() { +>needsRenameForShadowing : <T>() => <T_1>(t: T, t2: T_1) => void +> : ^ ^^^^^^^^ ^^ ^^^ ^^^^^^^^^ + + type A = T +>A : T +> : ^ + + return function O<T>(t: A, t2: T) { +>function O<T>(t: A, t2: T) { } : <T_1>(t: T, t2: T_1) => void +> : ^^^^^^ ^^^^^ ^^ ^^^^^^^^^ +>O : <T>(t: T_1, t2: T) => void +> : ^ ^^ ^^^^^^^ ^^ ^^^^^^^^^ +>t : T_1 +> : ^^^ +>t2 : T +> : ^ + } +} + diff --git a/tests/cases/compiler/declarationEmitShadowing.ts b/tests/cases/compiler/declarationEmitShadowing.ts new file mode 100644 index 0000000000000..53c00fbc455a9 --- /dev/null +++ b/tests/cases/compiler/declarationEmitShadowing.ts @@ -0,0 +1,13 @@ +// @declaration: true + +export class A<T = any> { + public readonly ShadowedButDoesNotRequireRenaming = <T>(): T => { + return null as any + } +} + +export function needsRenameForShadowing<T>() { + type A = T + return function O<T>(t: A, t2: T) { + } +}
diff --git a/src/compiler/expressionToTypeNode.ts b/src/compiler/expressionToTypeNode.ts index 7ef64ad6375b5..73e176432d5ac 100644 --- a/src/compiler/expressionToTypeNode.ts +++ b/src/compiler/expressionToTypeNode.ts @@ -1122,15 +1122,16 @@ export function createSyntacticTypeNodeBuilder( ); function reuseTypeParameters(typeParameters: NodeArray<TypeParameterDeclaration> | undefined, context: SyntacticTypeNodeBuilderContext) { - return typeParameters?.map(tp => - factory.updateTypeParameterDeclaration( + return typeParameters?.map(tp => { + const { node: tpName } = resolver.trackExistingEntityName(context, tp.name); + return factory.updateTypeParameterDeclaration( tp, tp.modifiers?.map(m => reuseNode(context, m)), - reuseNode(context, tp.name), + tpName, serializeExistingTypeNodeWithFallback(tp.constraint, context), serializeExistingTypeNodeWithFallback(tp.default, context), - ) + ); + }); function typeFromObjectLiteralMethod(method: MethodDeclaration, name: PropertyName, context: SyntacticTypeNodeBuilderContext, isConstContext: boolean) { diff --git a/tests/baselines/reference/declarationEmitShadowing.js b/tests/baselines/reference/declarationEmitShadowing.js index 0000000000000..e3ec2b61204d4 +++ b/tests/baselines/reference/declarationEmitShadowing.js @@ -0,0 +1,41 @@ +//// [declarationEmitShadowing.ts] +//// [declarationEmitShadowing.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.needsRenameForShadowing = needsRenameForShadowing; +var A = /** @class */ (function () { + this.ShadowedButDoesNotRequireRenaming = function () { + return null; + }; + } + return A; +}()); +exports.A = A; +function needsRenameForShadowing() { + return function O(t, t2) { + }; +//// [declarationEmitShadowing.d.ts] +export declare class A<T = any> { + readonly ShadowedButDoesNotRequireRenaming: <T_1>() => T_1; +export declare function needsRenameForShadowing<T>(): <T_1>(t: T, t2: T_1) => void; diff --git a/tests/baselines/reference/declarationEmitShadowing.symbols b/tests/baselines/reference/declarationEmitShadowing.symbols index 0000000000000..06f127f02fa72 +++ b/tests/baselines/reference/declarationEmitShadowing.symbols @@ -0,0 +1,34 @@ +>A : Symbol(A, Decl(declarationEmitShadowing.ts, 0, 0)) +>T : Symbol(T, Decl(declarationEmitShadowing.ts, 0, 15)) +>ShadowedButDoesNotRequireRenaming : Symbol(A.ShadowedButDoesNotRequireRenaming, Decl(declarationEmitShadowing.ts, 0, 25)) +>needsRenameForShadowing : Symbol(needsRenameForShadowing, Decl(declarationEmitShadowing.ts, 4, 1)) +>O : Symbol(O, Decl(declarationEmitShadowing.ts, 8, 8)) +>t2 : Symbol(t2, Decl(declarationEmitShadowing.ts, 8, 28)) diff --git a/tests/baselines/reference/declarationEmitShadowing.types b/tests/baselines/reference/declarationEmitShadowing.types index 0000000000000..014d0569cfe30 +++ b/tests/baselines/reference/declarationEmitShadowing.types @@ -0,0 +1,38 @@ +>A : A<T> +> : ^^^^^^^^^^^ +><T>(): T => { return null as any } : <T_1>() => T_1 +> : ^^^^^^^^^^^ +>null as any : any +>needsRenameForShadowing : <T>() => <T_1>(t: T, t2: T_1) => void +> : ^ ^^^^^^^^ ^^ ^^^ ^^^^^^^^^ +>A : T +> : ^ +> : ^ ^^ ^^^^^^^ ^^ ^^^^^^^^^ +>t : T_1 +> : ^^^ +>t2 : T diff --git a/tests/cases/compiler/declarationEmitShadowing.ts b/tests/cases/compiler/declarationEmitShadowing.ts index 0000000000000..53c00fbc455a9 +++ b/tests/cases/compiler/declarationEmitShadowing.ts @@ -0,0 +1,13 @@ +// @declaration: true
[ "- );", "+exports.A = void 0;", "+ function A() {", "+>t : Symbol(t, Decl(declarationEmitShadowing.ts, 8, 23))", "+> : ^^^^", "+>ShadowedButDoesNotRequireRenaming : <T_1>() => T_1", "+>function O<T>(t: A, t2: T) { } : <T_1>(t: T, t2: T_1) => void", "+> : ^^^^^^ ^^^^^ ^^ ^^^^^^^^^", "+>O : <T>(t: T_1, t2: T) => void", "+> : ^" ]
[ 20, 51, 54, 106, 124, 127, 146, 147, 148, 153 ]
{ "additions": 132, "author": "dragomirtitian", "deletions": 5, "html_url": "https://github.com/microsoft/TypeScript/pull/61342", "issue_id": 61342, "merged_at": "2025-03-04T19:34:33Z", "omission_probability": 0.1, "pr_number": 61342, "repo": "microsoft/TypeScript", "title": "Rename type parameters when they are shadowed.", "total_changes": 137 }
67
diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index 5ce9ca431b15f..3fa7da5d5c960 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -3118,7 +3118,7 @@ function loadModuleFromSpecificNodeModulesDirectory(extensions: Extensions, modu packageInfo, ); if ( - !pathAndExtension && packageInfo + !pathAndExtension && !rest && packageInfo // eslint-disable-next-line no-restricted-syntax && (packageInfo.contents.packageJsonContent.exports === undefined || packageInfo.contents.packageJsonContent.exports === null) && state.features & NodeResolutionFeatures.EsmMode diff --git a/tests/baselines/reference/nodeModulesNoDirectoryModule.errors.txt b/tests/baselines/reference/nodeModulesNoDirectoryModule.errors.txt new file mode 100644 index 0000000000000..b6f165f8b9014 --- /dev/null +++ b/tests/baselines/reference/nodeModulesNoDirectoryModule.errors.txt @@ -0,0 +1,26 @@ +/index.ts(2,8): error TS2307: Cannot find module 'i-have-a-dir-and-main/dist/dir' or its corresponding type declarations. + + +==== /node_modules/i-have-a-dir-and-main/package.json (0 errors) ==== + { + "name": "i-have-a-dir-and-main", + "version": "1.0.0", + "type": "module", + "main": "dist/index.js" + } + +==== /node_modules/i-have-a-dir-and-main/dist/index.d.ts (0 errors) ==== + export declare const a = 1; + +==== /node_modules/i-have-a-dir-and-main/dist/dir/index.d.ts (0 errors) ==== + export declare const b = 2; + +==== /package.json (0 errors) ==== + { "type": "module" } + +==== /index.ts (1 errors) ==== + import 'i-have-a-dir-and-main' // ok + import 'i-have-a-dir-and-main/dist/dir' // error + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2307: Cannot find module 'i-have-a-dir-and-main/dist/dir' or its corresponding type declarations. + \ No newline at end of file diff --git a/tests/cases/conformance/node/nodeModulesNoDirectoryModule.ts b/tests/cases/conformance/node/nodeModulesNoDirectoryModule.ts new file mode 100644 index 0000000000000..5b5d38a99466c --- /dev/null +++ b/tests/cases/conformance/node/nodeModulesNoDirectoryModule.ts @@ -0,0 +1,26 @@ +// @noUncheckedSideEffectImports: true +// @strict: true +// @module: node16 +// @noEmit: true +// @noTypesAndSymbols: true + +// @Filename: /node_modules/i-have-a-dir-and-main/package.json +{ + "name": "i-have-a-dir-and-main", + "version": "1.0.0", + "type": "module", + "main": "dist/index.js" +} + +// @Filename: /node_modules/i-have-a-dir-and-main/dist/index.d.ts +export declare const a = 1; + +// @Filename: /node_modules/i-have-a-dir-and-main/dist/dir/index.d.ts +export declare const b = 2; + +// @Filename: /package.json +{ "type": "module" } + +// @Filename: /index.ts +import 'i-have-a-dir-and-main' // ok +import 'i-have-a-dir-and-main/dist/dir' // error
diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index 5ce9ca431b15f..3fa7da5d5c960 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -3118,7 +3118,7 @@ function loadModuleFromSpecificNodeModulesDirectory(extensions: Extensions, modu packageInfo, ); if ( - !pathAndExtension && packageInfo + !pathAndExtension && !rest && packageInfo // eslint-disable-next-line no-restricted-syntax && (packageInfo.contents.packageJsonContent.exports === undefined || packageInfo.contents.packageJsonContent.exports === null) && state.features & NodeResolutionFeatures.EsmMode diff --git a/tests/baselines/reference/nodeModulesNoDirectoryModule.errors.txt b/tests/baselines/reference/nodeModulesNoDirectoryModule.errors.txt index 0000000000000..b6f165f8b9014 +++ b/tests/baselines/reference/nodeModulesNoDirectoryModule.errors.txt +/index.ts(2,8): error TS2307: Cannot find module 'i-have-a-dir-and-main/dist/dir' or its corresponding type declarations. +==== /node_modules/i-have-a-dir-and-main/package.json (0 errors) ==== + { + "name": "i-have-a-dir-and-main", + "version": "1.0.0", + "type": "module", + "main": "dist/index.js" + } + export declare const a = 1; +==== /node_modules/i-have-a-dir-and-main/dist/dir/index.d.ts (0 errors) ==== + export declare const b = 2; +==== /package.json (0 errors) ==== +==== /index.ts (1 errors) ==== + import 'i-have-a-dir-and-main' // ok + import 'i-have-a-dir-and-main/dist/dir' // error + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2307: Cannot find module 'i-have-a-dir-and-main/dist/dir' or its corresponding type declarations. \ No newline at end of file diff --git a/tests/cases/conformance/node/nodeModulesNoDirectoryModule.ts b/tests/cases/conformance/node/nodeModulesNoDirectoryModule.ts index 0000000000000..5b5d38a99466c +++ b/tests/cases/conformance/node/nodeModulesNoDirectoryModule.ts +// @strict: true +// @module: node16 +// @noEmit: true +// @noTypesAndSymbols: true +// @Filename: /node_modules/i-have-a-dir-and-main/package.json +{ + "name": "i-have-a-dir-and-main", + "version": "1.0.0", + "type": "module", + "main": "dist/index.js" +} +// @Filename: /node_modules/i-have-a-dir-and-main/dist/index.d.ts +export declare const a = 1; +// @Filename: /node_modules/i-have-a-dir-and-main/dist/dir/index.d.ts +export declare const b = 2; +// @Filename: /package.json +{ "type": "module" } +// @Filename: /index.ts +import 'i-have-a-dir-and-main' // ok
[ "+==== /node_modules/i-have-a-dir-and-main/dist/index.d.ts (0 errors) ====", "+ { \"type\": \"module\" }", "+// @noUncheckedSideEffectImports: true", "+import 'i-have-a-dir-and-main/dist/dir' // error" ]
[ 30, 37, 52, 77 ]
{ "additions": 53, "author": "andrewbranch", "deletions": 1, "html_url": "https://github.com/microsoft/TypeScript/pull/61082", "issue_id": 61082, "merged_at": "2025-01-30T18:17:14Z", "omission_probability": 0.1, "pr_number": 61082, "repo": "microsoft/TypeScript", "title": "Fix accidental ESM-mode directory module lookup in package non-root", "total_changes": 54 }
68
diff --git a/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl index 8630475bb08ea..7f3d86df295aa 100644 --- a/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -15270,6 +15270,15 @@ </Str> <Disp Icon="Str" /> </Item> + <Item ItemId=";This_expression_is_never_nullish_2881" ItemType="0" PsrId="306" Leaf="true"> + <Str Cat="Text"> + <Val><![CDATA[This expression is never nullish.]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[此運算式一律不會是 nullish。]]></Val> + </Tgt> + </Str> + <Disp Icon="Str" /> + </Item> <Item ItemId=";This_expression_is_not_callable_2349" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[This expression is not callable.]]></Val> diff --git a/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl index 9c856436898e4..cd0fe7d510832 100644 --- a/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -15279,6 +15279,15 @@ </Str> <Disp Icon="Str" /> </Item> + <Item ItemId=";This_expression_is_never_nullish_2881" ItemType="0" PsrId="306" Leaf="true"> + <Str Cat="Text"> + <Val><![CDATA[This expression is never nullish.]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Tento výraz nikdy nemá hodnotu null.]]></Val> + </Tgt> + </Str> + <Disp Icon="Str" /> + </Item> <Item ItemId=";This_expression_is_not_callable_2349" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[This expression is not callable.]]></Val> diff --git a/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl index e726c146c15eb..8d0ec0976a102 100644 --- a/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -15264,6 +15264,15 @@ </Str> <Disp Icon="Str" /> </Item> + <Item ItemId=";This_expression_is_never_nullish_2881" ItemType="0" PsrId="306" Leaf="true"> + <Str Cat="Text"> + <Val><![CDATA[This expression is never nullish.]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Dieser binäre Ausdruck ist nie „NULLISH“.]]></Val> + </Tgt> + </Str> + <Disp Icon="Str" /> + </Item> <Item ItemId=";This_expression_is_not_callable_2349" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[This expression is not callable.]]></Val> diff --git a/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl index b5a69e413a2dc..a514aa1a91893 100644 --- a/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -15282,6 +15282,15 @@ </Str> <Disp Icon="Str" /> </Item> + <Item ItemId=";This_expression_is_never_nullish_2881" ItemType="0" PsrId="306" Leaf="true"> + <Str Cat="Text"> + <Val><![CDATA[This expression is never nullish.]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Cette expression n’est jamais nulle.]]></Val> + </Tgt> + </Str> + <Disp Icon="Str" /> + </Item> <Item ItemId=";This_expression_is_not_callable_2349" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[This expression is not callable.]]></Val> diff --git a/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl index 7d6a048b62785..929d85c8a4cbe 100644 --- a/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -15270,6 +15270,15 @@ </Str> <Disp Icon="Str" /> </Item> + <Item ItemId=";This_expression_is_never_nullish_2881" ItemType="0" PsrId="306" Leaf="true"> + <Str Cat="Text"> + <Val><![CDATA[This expression is never nullish.]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[この式が NULL 値になることはありません。]]></Val> + </Tgt> + </Str> + <Disp Icon="Str" /> + </Item> <Item ItemId=";This_expression_is_not_callable_2349" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[This expression is not callable.]]></Val> diff --git a/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl index ead631be12465..3881baed4ea08 100644 --- a/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -15270,6 +15270,15 @@ </Str> <Disp Icon="Str" /> </Item> + <Item ItemId=";This_expression_is_never_nullish_2881" ItemType="0" PsrId="306" Leaf="true"> + <Str Cat="Text"> + <Val><![CDATA[This expression is never nullish.]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[이 표현식은 nullish가 되지 않습니다.]]></Val> + </Tgt> + </Str> + <Disp Icon="Str" /> + </Item> <Item ItemId=";This_expression_is_not_callable_2349" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[This expression is not callable.]]></Val> diff --git a/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl index bdff8b5d661cd..1d63900fb1627 100644 --- a/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -15257,6 +15257,15 @@ </Str> <Disp Icon="Str" /> </Item> + <Item ItemId=";This_expression_is_never_nullish_2881" ItemType="0" PsrId="306" Leaf="true"> + <Str Cat="Text"> + <Val><![CDATA[This expression is never nullish.]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[To wyrażenie nigdy nie ma wartości null.]]></Val> + </Tgt> + </Str> + <Disp Icon="Str" /> + </Item> <Item ItemId=";This_expression_is_not_callable_2349" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[This expression is not callable.]]></Val> diff --git a/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl index 7424a5b72a994..7d3513f3dd423 100644 --- a/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -15263,6 +15263,15 @@ </Str> <Disp Icon="Str" /> </Item> + <Item ItemId=";This_expression_is_never_nullish_2881" ItemType="0" PsrId="306" Leaf="true"> + <Str Cat="Text"> + <Val><![CDATA[This expression is never nullish.]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Bu ifade hiçbir zaman boş gibi değildir.]]></Val> + </Tgt> + </Str> + <Disp Icon="Str" /> + </Item> <Item ItemId=";This_expression_is_not_callable_2349" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[This expression is not callable.]]></Val>
diff --git a/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl index 8630475bb08ea..7f3d86df295aa 100644 --- a/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl + <Val><![CDATA[此運算式一律不會是 nullish。]]></Val> diff --git a/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl index 9c856436898e4..cd0fe7d510832 100644 --- a/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -15279,6 +15279,15 @@ + <Val><![CDATA[Tento výraz nikdy nemá hodnotu null.]]></Val> diff --git a/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl index e726c146c15eb..8d0ec0976a102 100644 --- a/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -15264,6 +15264,15 @@ + <Val><![CDATA[Dieser binäre Ausdruck ist nie „NULLISH“.]]></Val> diff --git a/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl index b5a69e413a2dc..a514aa1a91893 100644 --- a/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -15282,6 +15282,15 @@ diff --git a/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl index 7d6a048b62785..929d85c8a4cbe 100644 --- a/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl + <Val><![CDATA[この式が NULL 値になることはありません。]]></Val> diff --git a/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl index ead631be12465..3881baed4ea08 100644 --- a/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl diff --git a/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl index bdff8b5d661cd..1d63900fb1627 100644 --- a/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -15257,6 +15257,15 @@ + <Val><![CDATA[To wyrażenie nigdy nie ma wartości null.]]></Val> diff --git a/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl index 7424a5b72a994..7d3513f3dd423 100644 --- a/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -15263,6 +15263,15 @@ + <Val><![CDATA[Bu ifade hiçbir zaman boş gibi değildir.]]></Val>
[ "+ <Val><![CDATA[Cette expression n’est jamais nulle.]]></Val>", "+ <Val><![CDATA[이 표현식은 nullish가 되지 않습니다.]]></Val>" ]
[ 72, 112 ]
{ "additions": 72, "author": "csigs", "deletions": 0, "html_url": "https://github.com/microsoft/TypeScript/pull/61315", "issue_id": 61315, "merged_at": "2025-02-27T20:58:31Z", "omission_probability": 0.1, "pr_number": 61315, "repo": "microsoft/TypeScript", "title": "LEGO: Pull request from lego/hb_5378966c-b857-470a-8675-daebef4a6da1_20250227204102665 to main", "total_changes": 72 }
69
diff --git a/src/harness/vfsUtil.ts b/src/harness/vfsUtil.ts index 4799927a70a14..596575beece2c 100644 --- a/src/harness/vfsUtil.ts +++ b/src/harness/vfsUtil.ts @@ -637,7 +637,7 @@ export class FileSystem { * * NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module. */ - public readFileSync(path: string, encoding?: null): Buffer; // eslint-disable-line no-restricted-syntax + public readFileSync(path: string, encoding?: null): Buffer<ArrayBuffer>; // eslint-disable-line no-restricted-syntax /** * Read from a file. * @@ -649,7 +649,7 @@ export class FileSystem { * * NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module. */ - public readFileSync(path: string, encoding?: BufferEncoding | null): string | Buffer; // eslint-disable-line no-restricted-syntax + public readFileSync(path: string, encoding?: BufferEncoding | null): string | Buffer<ArrayBuffer>; // eslint-disable-line no-restricted-syntax public readFileSync(path: string, encoding: BufferEncoding | null = null) { // eslint-disable-line no-restricted-syntax const { node } = this._walk(this._resolve(path)); if (!node) throw createIOError("ENOENT"); diff --git a/src/lib/es2015.symbol.wellknown.d.ts b/src/lib/es2015.symbol.wellknown.d.ts index ed5d1ddbb388f..1ab84be969fca 100644 --- a/src/lib/es2015.symbol.wellknown.d.ts +++ b/src/lib/es2015.symbol.wellknown.d.ts @@ -251,7 +251,7 @@ interface String { } interface ArrayBuffer { - readonly [Symbol.toStringTag]: string; + readonly [Symbol.toStringTag]: "ArrayBuffer"; } interface DataView<TArrayBuffer extends ArrayBufferLike> { diff --git a/tests/baselines/reference/assignSharedArrayBufferToArrayBuffer.errors.txt b/tests/baselines/reference/assignSharedArrayBufferToArrayBuffer.errors.txt new file mode 100644 index 0000000000000..cc22119ec5064 --- /dev/null +++ b/tests/baselines/reference/assignSharedArrayBufferToArrayBuffer.errors.txt @@ -0,0 +1,11 @@ +assignSharedArrayBufferToArrayBuffer.ts(1,5): error TS2322: Type 'SharedArrayBuffer' is not assignable to type 'ArrayBuffer'. + Types of property '[Symbol.toStringTag]' are incompatible. + Type '"SharedArrayBuffer"' is not assignable to type '"ArrayBuffer"'. + + +==== assignSharedArrayBufferToArrayBuffer.ts (1 errors) ==== + var foo: ArrayBuffer = new SharedArrayBuffer(1024); // should error + ~~~ +!!! error TS2322: Type 'SharedArrayBuffer' is not assignable to type 'ArrayBuffer'. +!!! error TS2322: Types of property '[Symbol.toStringTag]' are incompatible. +!!! error TS2322: Type '"SharedArrayBuffer"' is not assignable to type '"ArrayBuffer"'. \ No newline at end of file diff --git a/tests/baselines/reference/assignSharedArrayBufferToArrayBuffer.js b/tests/baselines/reference/assignSharedArrayBufferToArrayBuffer.js new file mode 100644 index 0000000000000..f7642aae6275d --- /dev/null +++ b/tests/baselines/reference/assignSharedArrayBufferToArrayBuffer.js @@ -0,0 +1,7 @@ +//// [tests/cases/conformance/es2017/assignSharedArrayBufferToArrayBuffer.ts] //// + +//// [assignSharedArrayBufferToArrayBuffer.ts] +var foo: ArrayBuffer = new SharedArrayBuffer(1024); // should error + +//// [assignSharedArrayBufferToArrayBuffer.js] +var foo = new SharedArrayBuffer(1024); // should error diff --git a/tests/baselines/reference/assignSharedArrayBufferToArrayBuffer.symbols b/tests/baselines/reference/assignSharedArrayBufferToArrayBuffer.symbols new file mode 100644 index 0000000000000..43cfb5a1787b0 --- /dev/null +++ b/tests/baselines/reference/assignSharedArrayBufferToArrayBuffer.symbols @@ -0,0 +1,8 @@ +//// [tests/cases/conformance/es2017/assignSharedArrayBufferToArrayBuffer.ts] //// + +=== assignSharedArrayBufferToArrayBuffer.ts === +var foo: ArrayBuffer = new SharedArrayBuffer(1024); // should error +>foo : Symbol(foo, Decl(assignSharedArrayBufferToArrayBuffer.ts, 0, 3)) +>ArrayBuffer : Symbol(ArrayBuffer, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) +>SharedArrayBuffer : Symbol(SharedArrayBuffer, Decl(lib.es2017.sharedmemory.d.ts, --, --), Decl(lib.es2017.sharedmemory.d.ts, --, --)) + diff --git a/tests/baselines/reference/assignSharedArrayBufferToArrayBuffer.types b/tests/baselines/reference/assignSharedArrayBufferToArrayBuffer.types new file mode 100644 index 0000000000000..1f6b881dfb452 --- /dev/null +++ b/tests/baselines/reference/assignSharedArrayBufferToArrayBuffer.types @@ -0,0 +1,13 @@ +//// [tests/cases/conformance/es2017/assignSharedArrayBufferToArrayBuffer.ts] //// + +=== assignSharedArrayBufferToArrayBuffer.ts === +var foo: ArrayBuffer = new SharedArrayBuffer(1024); // should error +>foo : ArrayBuffer +> : ^^^^^^^^^^^ +>new SharedArrayBuffer(1024) : SharedArrayBuffer +> : ^^^^^^^^^^^^^^^^^ +>SharedArrayBuffer : SharedArrayBufferConstructor +> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +>1024 : 1024 +> : ^^^^ + diff --git a/tests/cases/conformance/es2017/assignSharedArrayBufferToArrayBuffer.ts b/tests/cases/conformance/es2017/assignSharedArrayBufferToArrayBuffer.ts new file mode 100644 index 0000000000000..f0a38d9ee04f4 --- /dev/null +++ b/tests/cases/conformance/es2017/assignSharedArrayBufferToArrayBuffer.ts @@ -0,0 +1,4 @@ +// @target: es5 +// @lib: es2015,es2017.sharedmemory + +var foo: ArrayBuffer = new SharedArrayBuffer(1024); // should error \ No newline at end of file
diff --git a/src/harness/vfsUtil.ts b/src/harness/vfsUtil.ts index 4799927a70a14..596575beece2c 100644 --- a/src/harness/vfsUtil.ts +++ b/src/harness/vfsUtil.ts @@ -637,7 +637,7 @@ export class FileSystem { - public readFileSync(path: string, encoding?: null): Buffer; // eslint-disable-line no-restricted-syntax + public readFileSync(path: string, encoding?: null): Buffer<ArrayBuffer>; // eslint-disable-line no-restricted-syntax /** * Read from a file. @@ -649,7 +649,7 @@ export class FileSystem { - public readFileSync(path: string, encoding?: BufferEncoding | null): string | Buffer; // eslint-disable-line no-restricted-syntax + public readFileSync(path: string, encoding?: BufferEncoding | null): string | Buffer<ArrayBuffer>; // eslint-disable-line no-restricted-syntax public readFileSync(path: string, encoding: BufferEncoding | null = null) { // eslint-disable-line no-restricted-syntax const { node } = this._walk(this._resolve(path)); if (!node) throw createIOError("ENOENT"); diff --git a/src/lib/es2015.symbol.wellknown.d.ts b/src/lib/es2015.symbol.wellknown.d.ts index ed5d1ddbb388f..1ab84be969fca 100644 --- a/src/lib/es2015.symbol.wellknown.d.ts +++ b/src/lib/es2015.symbol.wellknown.d.ts @@ -251,7 +251,7 @@ interface String { interface ArrayBuffer { - readonly [Symbol.toStringTag]: string; + readonly [Symbol.toStringTag]: "ArrayBuffer"; interface DataView<TArrayBuffer extends ArrayBufferLike> { diff --git a/tests/baselines/reference/assignSharedArrayBufferToArrayBuffer.errors.txt b/tests/baselines/reference/assignSharedArrayBufferToArrayBuffer.errors.txt index 0000000000000..cc22119ec5064 +++ b/tests/baselines/reference/assignSharedArrayBufferToArrayBuffer.errors.txt @@ -0,0 +1,11 @@ +assignSharedArrayBufferToArrayBuffer.ts(1,5): error TS2322: Type 'SharedArrayBuffer' is not assignable to type 'ArrayBuffer'. + Type '"SharedArrayBuffer"' is not assignable to type '"ArrayBuffer"'. +==== assignSharedArrayBufferToArrayBuffer.ts (1 errors) ==== + var foo: ArrayBuffer = new SharedArrayBuffer(1024); // should error + ~~~ +!!! error TS2322: Type 'SharedArrayBuffer' is not assignable to type 'ArrayBuffer'. +!!! error TS2322: Types of property '[Symbol.toStringTag]' are incompatible. +!!! error TS2322: Type '"SharedArrayBuffer"' is not assignable to type '"ArrayBuffer"'. diff --git a/tests/baselines/reference/assignSharedArrayBufferToArrayBuffer.js b/tests/baselines/reference/assignSharedArrayBufferToArrayBuffer.js index 0000000000000..f7642aae6275d +++ b/tests/baselines/reference/assignSharedArrayBufferToArrayBuffer.js @@ -0,0 +1,7 @@ +//// [assignSharedArrayBufferToArrayBuffer.ts] +//// [assignSharedArrayBufferToArrayBuffer.js] +var foo = new SharedArrayBuffer(1024); // should error diff --git a/tests/baselines/reference/assignSharedArrayBufferToArrayBuffer.symbols b/tests/baselines/reference/assignSharedArrayBufferToArrayBuffer.symbols index 0000000000000..43cfb5a1787b0 +++ b/tests/baselines/reference/assignSharedArrayBufferToArrayBuffer.symbols @@ -0,0 +1,8 @@ +>foo : Symbol(foo, Decl(assignSharedArrayBufferToArrayBuffer.ts, 0, 3)) +>ArrayBuffer : Symbol(ArrayBuffer, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) +>SharedArrayBuffer : Symbol(SharedArrayBuffer, Decl(lib.es2017.sharedmemory.d.ts, --, --), Decl(lib.es2017.sharedmemory.d.ts, --, --)) diff --git a/tests/baselines/reference/assignSharedArrayBufferToArrayBuffer.types b/tests/baselines/reference/assignSharedArrayBufferToArrayBuffer.types index 0000000000000..1f6b881dfb452 +++ b/tests/baselines/reference/assignSharedArrayBufferToArrayBuffer.types @@ -0,0 +1,13 @@ +>foo : ArrayBuffer +> : ^^^^^^^^^^^ +>new SharedArrayBuffer(1024) : SharedArrayBuffer +> : ^^^^^^^^^^^^^^^^^ +>SharedArrayBuffer : SharedArrayBufferConstructor +> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +>1024 : 1024 +> : ^^^^ diff --git a/tests/cases/conformance/es2017/assignSharedArrayBufferToArrayBuffer.ts b/tests/cases/conformance/es2017/assignSharedArrayBufferToArrayBuffer.ts index 0000000000000..f0a38d9ee04f4 +++ b/tests/cases/conformance/es2017/assignSharedArrayBufferToArrayBuffer.ts @@ -0,0 +1,4 @@ +// @target: es5 +// @lib: es2015,es2017.sharedmemory
[ "+ Types of property '[Symbol.toStringTag]' are incompatible." ]
[ 42 ]
{ "additions": 46, "author": "petamoriken", "deletions": 3, "html_url": "https://github.com/microsoft/TypeScript/pull/60150", "issue_id": 60150, "merged_at": "2025-02-24T19:17:35Z", "omission_probability": 0.1, "pr_number": 60150, "repo": "microsoft/TypeScript", "title": "Fix to use string literal type in ArrayBuffer's `Symbol.toStringTag`", "total_changes": 49 }
70
diff --git a/src/lib/es2017.sharedmemory.d.ts b/src/lib/es2017.sharedmemory.d.ts index 5e4e59018c622..f658c8155364f 100644 --- a/src/lib/es2017.sharedmemory.d.ts +++ b/src/lib/es2017.sharedmemory.d.ts @@ -11,13 +11,13 @@ interface SharedArrayBuffer { * Returns a section of an SharedArrayBuffer. */ slice(begin?: number, end?: number): SharedArrayBuffer; - readonly [Symbol.species]: SharedArrayBuffer; readonly [Symbol.toStringTag]: "SharedArrayBuffer"; } interface SharedArrayBufferConstructor { readonly prototype: SharedArrayBuffer; new (byteLength?: number): SharedArrayBuffer; + readonly [Symbol.species]: SharedArrayBufferConstructor; } declare var SharedArrayBuffer: SharedArrayBufferConstructor; diff --git a/tests/baselines/reference/useSharedArrayBuffer4.js b/tests/baselines/reference/useSharedArrayBuffer4.js index 0e43b146e2e68..4640e42858457 100644 --- a/tests/baselines/reference/useSharedArrayBuffer4.js +++ b/tests/baselines/reference/useSharedArrayBuffer4.js @@ -3,13 +3,13 @@ //// [useSharedArrayBuffer4.ts] var foge = new SharedArrayBuffer(1024); var bar = foge.slice(1, 10); -var species = foge[Symbol.species]; var stringTag = foge[Symbol.toStringTag]; -var len = foge.byteLength; +var len = foge.byteLength; +var species = SharedArrayBuffer[Symbol.species]; //// [useSharedArrayBuffer4.js] var foge = new SharedArrayBuffer(1024); var bar = foge.slice(1, 10); -var species = foge[Symbol.species]; var stringTag = foge[Symbol.toStringTag]; var len = foge.byteLength; +var species = SharedArrayBuffer[Symbol.species]; diff --git a/tests/baselines/reference/useSharedArrayBuffer4.symbols b/tests/baselines/reference/useSharedArrayBuffer4.symbols index 7c6e1dc5b0a19..56efeebfd3c29 100644 --- a/tests/baselines/reference/useSharedArrayBuffer4.symbols +++ b/tests/baselines/reference/useSharedArrayBuffer4.symbols @@ -11,23 +11,23 @@ var bar = foge.slice(1, 10); >foge : Symbol(foge, Decl(useSharedArrayBuffer4.ts, 0, 3)) >slice : Symbol(SharedArrayBuffer.slice, Decl(lib.es2017.sharedmemory.d.ts, --, --)) -var species = foge[Symbol.species]; ->species : Symbol(species, Decl(useSharedArrayBuffer4.ts, 2, 3)) ->foge : Symbol(foge, Decl(useSharedArrayBuffer4.ts, 0, 3)) ->Symbol.species : Symbol(SymbolConstructor.species, Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) ->Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) ->species : Symbol(SymbolConstructor.species, Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) - var stringTag = foge[Symbol.toStringTag]; ->stringTag : Symbol(stringTag, Decl(useSharedArrayBuffer4.ts, 3, 3)) +>stringTag : Symbol(stringTag, Decl(useSharedArrayBuffer4.ts, 2, 3)) >foge : Symbol(foge, Decl(useSharedArrayBuffer4.ts, 0, 3)) >Symbol.toStringTag : Symbol(SymbolConstructor.toStringTag, Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) >Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) >toStringTag : Symbol(SymbolConstructor.toStringTag, Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) var len = foge.byteLength; ->len : Symbol(len, Decl(useSharedArrayBuffer4.ts, 4, 3)) +>len : Symbol(len, Decl(useSharedArrayBuffer4.ts, 3, 3)) >foge.byteLength : Symbol(SharedArrayBuffer.byteLength, Decl(lib.es2017.sharedmemory.d.ts, --, --)) >foge : Symbol(foge, Decl(useSharedArrayBuffer4.ts, 0, 3)) >byteLength : Symbol(SharedArrayBuffer.byteLength, Decl(lib.es2017.sharedmemory.d.ts, --, --)) +var species = SharedArrayBuffer[Symbol.species]; +>species : Symbol(species, Decl(useSharedArrayBuffer4.ts, 4, 3)) +>SharedArrayBuffer : Symbol(SharedArrayBuffer, Decl(lib.es2017.sharedmemory.d.ts, --, --), Decl(lib.es2017.sharedmemory.d.ts, --, --)) +>Symbol.species : Symbol(SymbolConstructor.species, Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) +>species : Symbol(SymbolConstructor.species, Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) + diff --git a/tests/baselines/reference/useSharedArrayBuffer4.types b/tests/baselines/reference/useSharedArrayBuffer4.types index 5edff0d374ba1..495b761d8ad54 100644 --- a/tests/baselines/reference/useSharedArrayBuffer4.types +++ b/tests/baselines/reference/useSharedArrayBuffer4.types @@ -27,20 +27,6 @@ var bar = foge.slice(1, 10); >10 : 10 > : ^^ -var species = foge[Symbol.species]; ->species : SharedArrayBuffer -> : ^^^^^^^^^^^^^^^^^ ->foge[Symbol.species] : SharedArrayBuffer -> : ^^^^^^^^^^^^^^^^^ ->foge : SharedArrayBuffer -> : ^^^^^^^^^^^^^^^^^ ->Symbol.species : unique symbol -> : ^^^^^^^^^^^^^ ->Symbol : SymbolConstructor -> : ^^^^^^^^^^^^^^^^^ ->species : unique symbol -> : ^^^^^^^^^^^^^ - var stringTag = foge[Symbol.toStringTag]; >stringTag : "SharedArrayBuffer" > : ^^^^^^^^^^^^^^^^^^^ @@ -65,3 +51,17 @@ var len = foge.byteLength; >byteLength : number > : ^^^^^^ +var species = SharedArrayBuffer[Symbol.species]; +>species : SharedArrayBufferConstructor +> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +>SharedArrayBuffer[Symbol.species] : SharedArrayBufferConstructor +> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +>SharedArrayBuffer : SharedArrayBufferConstructor +> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +>Symbol.species : unique symbol +> : ^^^^^^^^^^^^^ +>Symbol : SymbolConstructor +> : ^^^^^^^^^^^^^^^^^ +>species : unique symbol +> : ^^^^^^^^^^^^^ + diff --git a/tests/baselines/reference/useSharedArrayBuffer5.js b/tests/baselines/reference/useSharedArrayBuffer5.js index 6a75e35f75e5c..7c96f2cb6b56c 100644 --- a/tests/baselines/reference/useSharedArrayBuffer5.js +++ b/tests/baselines/reference/useSharedArrayBuffer5.js @@ -2,10 +2,10 @@ //// [useSharedArrayBuffer5.ts] var foge = new SharedArrayBuffer(1024); -var species = foge[Symbol.species]; -var stringTag = foge[Symbol.toStringTag]; +var stringTag = foge[Symbol.toStringTag]; +var species = SharedArrayBuffer[Symbol.species]; //// [useSharedArrayBuffer5.js] var foge = new SharedArrayBuffer(1024); -var species = foge[Symbol.species]; var stringTag = foge[Symbol.toStringTag]; +var species = SharedArrayBuffer[Symbol.species]; diff --git a/tests/baselines/reference/useSharedArrayBuffer5.symbols b/tests/baselines/reference/useSharedArrayBuffer5.symbols index 0b67e6e8b2697..9c5fc6a70290b 100644 --- a/tests/baselines/reference/useSharedArrayBuffer5.symbols +++ b/tests/baselines/reference/useSharedArrayBuffer5.symbols @@ -5,17 +5,17 @@ var foge = new SharedArrayBuffer(1024); >foge : Symbol(foge, Decl(useSharedArrayBuffer5.ts, 0, 3)) >SharedArrayBuffer : Symbol(SharedArrayBuffer, Decl(lib.es2017.sharedmemory.d.ts, --, --), Decl(lib.es2017.sharedmemory.d.ts, --, --)) -var species = foge[Symbol.species]; ->species : Symbol(species, Decl(useSharedArrayBuffer5.ts, 1, 3)) ->foge : Symbol(foge, Decl(useSharedArrayBuffer5.ts, 0, 3)) ->Symbol.species : Symbol(SymbolConstructor.species, Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) ->Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) ->species : Symbol(SymbolConstructor.species, Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) - var stringTag = foge[Symbol.toStringTag]; ->stringTag : Symbol(stringTag, Decl(useSharedArrayBuffer5.ts, 2, 3)) +>stringTag : Symbol(stringTag, Decl(useSharedArrayBuffer5.ts, 1, 3)) >foge : Symbol(foge, Decl(useSharedArrayBuffer5.ts, 0, 3)) >Symbol.toStringTag : Symbol(SymbolConstructor.toStringTag, Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) >Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) >toStringTag : Symbol(SymbolConstructor.toStringTag, Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) +var species = SharedArrayBuffer[Symbol.species]; +>species : Symbol(species, Decl(useSharedArrayBuffer5.ts, 2, 3)) +>SharedArrayBuffer : Symbol(SharedArrayBuffer, Decl(lib.es2017.sharedmemory.d.ts, --, --), Decl(lib.es2017.sharedmemory.d.ts, --, --)) +>Symbol.species : Symbol(SymbolConstructor.species, Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) +>species : Symbol(SymbolConstructor.species, Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) + diff --git a/tests/baselines/reference/useSharedArrayBuffer5.types b/tests/baselines/reference/useSharedArrayBuffer5.types index d1dd605674381..9a5778b48c494 100644 --- a/tests/baselines/reference/useSharedArrayBuffer5.types +++ b/tests/baselines/reference/useSharedArrayBuffer5.types @@ -11,20 +11,6 @@ var foge = new SharedArrayBuffer(1024); >1024 : 1024 > : ^^^^ -var species = foge[Symbol.species]; ->species : SharedArrayBuffer -> : ^^^^^^^^^^^^^^^^^ ->foge[Symbol.species] : SharedArrayBuffer -> : ^^^^^^^^^^^^^^^^^ ->foge : SharedArrayBuffer -> : ^^^^^^^^^^^^^^^^^ ->Symbol.species : unique symbol -> : ^^^^^^^^^^^^^ ->Symbol : SymbolConstructor -> : ^^^^^^^^^^^^^^^^^ ->species : unique symbol -> : ^^^^^^^^^^^^^ - var stringTag = foge[Symbol.toStringTag]; >stringTag : "SharedArrayBuffer" > : ^^^^^^^^^^^^^^^^^^^ @@ -39,3 +25,17 @@ var stringTag = foge[Symbol.toStringTag]; >toStringTag : unique symbol > : ^^^^^^^^^^^^^ +var species = SharedArrayBuffer[Symbol.species]; +>species : SharedArrayBufferConstructor +> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +>SharedArrayBuffer[Symbol.species] : SharedArrayBufferConstructor +> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +>SharedArrayBuffer : SharedArrayBufferConstructor +> : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +>Symbol.species : unique symbol +> : ^^^^^^^^^^^^^ +>Symbol : SymbolConstructor +> : ^^^^^^^^^^^^^^^^^ +>species : unique symbol +> : ^^^^^^^^^^^^^ + diff --git a/tests/cases/conformance/es2017/useSharedArrayBuffer4.ts b/tests/cases/conformance/es2017/useSharedArrayBuffer4.ts index 4d47c739ff3fe..e030976474583 100644 --- a/tests/cases/conformance/es2017/useSharedArrayBuffer4.ts +++ b/tests/cases/conformance/es2017/useSharedArrayBuffer4.ts @@ -3,6 +3,6 @@ var foge = new SharedArrayBuffer(1024); var bar = foge.slice(1, 10); -var species = foge[Symbol.species]; var stringTag = foge[Symbol.toStringTag]; -var len = foge.byteLength; \ No newline at end of file +var len = foge.byteLength; +var species = SharedArrayBuffer[Symbol.species]; \ No newline at end of file diff --git a/tests/cases/conformance/es2017/useSharedArrayBuffer5.ts b/tests/cases/conformance/es2017/useSharedArrayBuffer5.ts index 3606c1c634600..e55d44a1d3cd9 100644 --- a/tests/cases/conformance/es2017/useSharedArrayBuffer5.ts +++ b/tests/cases/conformance/es2017/useSharedArrayBuffer5.ts @@ -2,5 +2,5 @@ // @lib: es6,es2017.sharedmemory var foge = new SharedArrayBuffer(1024); -var species = foge[Symbol.species]; -var stringTag = foge[Symbol.toStringTag]; \ No newline at end of file +var stringTag = foge[Symbol.toStringTag]; +var species = SharedArrayBuffer[Symbol.species]; \ No newline at end of file
diff --git a/src/lib/es2017.sharedmemory.d.ts b/src/lib/es2017.sharedmemory.d.ts index 5e4e59018c622..f658c8155364f 100644 --- a/src/lib/es2017.sharedmemory.d.ts +++ b/src/lib/es2017.sharedmemory.d.ts @@ -11,13 +11,13 @@ interface SharedArrayBuffer { * Returns a section of an SharedArrayBuffer. */ slice(begin?: number, end?: number): SharedArrayBuffer; - readonly [Symbol.species]: SharedArrayBuffer; readonly [Symbol.toStringTag]: "SharedArrayBuffer"; interface SharedArrayBufferConstructor { readonly prototype: SharedArrayBuffer; new (byteLength?: number): SharedArrayBuffer; + readonly [Symbol.species]: SharedArrayBufferConstructor; declare var SharedArrayBuffer: SharedArrayBufferConstructor; diff --git a/tests/baselines/reference/useSharedArrayBuffer4.js b/tests/baselines/reference/useSharedArrayBuffer4.js index 0e43b146e2e68..4640e42858457 100644 --- a/tests/baselines/reference/useSharedArrayBuffer4.js +++ b/tests/baselines/reference/useSharedArrayBuffer4.js @@ -3,13 +3,13 @@ //// [useSharedArrayBuffer4.ts] //// [useSharedArrayBuffer4.js] diff --git a/tests/baselines/reference/useSharedArrayBuffer4.symbols b/tests/baselines/reference/useSharedArrayBuffer4.symbols index 7c6e1dc5b0a19..56efeebfd3c29 100644 --- a/tests/baselines/reference/useSharedArrayBuffer4.symbols +++ b/tests/baselines/reference/useSharedArrayBuffer4.symbols @@ -11,23 +11,23 @@ var bar = foge.slice(1, 10); >slice : Symbol(SharedArrayBuffer.slice, Decl(lib.es2017.sharedmemory.d.ts, --, --)) ->species : Symbol(species, Decl(useSharedArrayBuffer4.ts, 2, 3)) ->foge : Symbol(foge, Decl(useSharedArrayBuffer4.ts, 0, 3)) ->stringTag : Symbol(stringTag, Decl(useSharedArrayBuffer4.ts, 3, 3)) +>stringTag : Symbol(stringTag, Decl(useSharedArrayBuffer4.ts, 2, 3)) ->len : Symbol(len, Decl(useSharedArrayBuffer4.ts, 4, 3)) +>len : Symbol(len, Decl(useSharedArrayBuffer4.ts, 3, 3)) >foge.byteLength : Symbol(SharedArrayBuffer.byteLength, Decl(lib.es2017.sharedmemory.d.ts, --, --)) >byteLength : Symbol(SharedArrayBuffer.byteLength, Decl(lib.es2017.sharedmemory.d.ts, --, --)) diff --git a/tests/baselines/reference/useSharedArrayBuffer4.types b/tests/baselines/reference/useSharedArrayBuffer4.types index 5edff0d374ba1..495b761d8ad54 100644 --- a/tests/baselines/reference/useSharedArrayBuffer4.types +++ b/tests/baselines/reference/useSharedArrayBuffer4.types @@ -27,20 +27,6 @@ var bar = foge.slice(1, 10); >10 : 10 > : ^^ @@ -65,3 +51,17 @@ var len = foge.byteLength; >byteLength : number > : ^^^^^^ diff --git a/tests/baselines/reference/useSharedArrayBuffer5.js b/tests/baselines/reference/useSharedArrayBuffer5.js index 6a75e35f75e5c..7c96f2cb6b56c 100644 --- a/tests/baselines/reference/useSharedArrayBuffer5.js +++ b/tests/baselines/reference/useSharedArrayBuffer5.js @@ -2,10 +2,10 @@ //// [useSharedArrayBuffer5.ts] //// [useSharedArrayBuffer5.js] diff --git a/tests/baselines/reference/useSharedArrayBuffer5.symbols b/tests/baselines/reference/useSharedArrayBuffer5.symbols index 0b67e6e8b2697..9c5fc6a70290b 100644 --- a/tests/baselines/reference/useSharedArrayBuffer5.symbols +++ b/tests/baselines/reference/useSharedArrayBuffer5.symbols @@ -5,17 +5,17 @@ var foge = new SharedArrayBuffer(1024); >SharedArrayBuffer : Symbol(SharedArrayBuffer, Decl(lib.es2017.sharedmemory.d.ts, --, --), Decl(lib.es2017.sharedmemory.d.ts, --, --)) ->species : Symbol(species, Decl(useSharedArrayBuffer5.ts, 1, 3)) ->foge : Symbol(foge, Decl(useSharedArrayBuffer5.ts, 0, 3)) ->stringTag : Symbol(stringTag, Decl(useSharedArrayBuffer5.ts, 2, 3)) +>species : Symbol(species, Decl(useSharedArrayBuffer5.ts, 2, 3)) diff --git a/tests/baselines/reference/useSharedArrayBuffer5.types b/tests/baselines/reference/useSharedArrayBuffer5.types index d1dd605674381..9a5778b48c494 100644 --- a/tests/baselines/reference/useSharedArrayBuffer5.types +++ b/tests/baselines/reference/useSharedArrayBuffer5.types @@ -11,20 +11,6 @@ var foge = new SharedArrayBuffer(1024); >1024 : 1024 > : ^^^^ @@ -39,3 +25,17 @@ var stringTag = foge[Symbol.toStringTag]; >toStringTag : unique symbol > : ^^^^^^^^^^^^^ diff --git a/tests/cases/conformance/es2017/useSharedArrayBuffer4.ts b/tests/cases/conformance/es2017/useSharedArrayBuffer4.ts index 4d47c739ff3fe..e030976474583 100644 --- a/tests/cases/conformance/es2017/useSharedArrayBuffer4.ts +++ b/tests/cases/conformance/es2017/useSharedArrayBuffer4.ts @@ -3,6 +3,6 @@ diff --git a/tests/cases/conformance/es2017/useSharedArrayBuffer5.ts b/tests/cases/conformance/es2017/useSharedArrayBuffer5.ts index 3606c1c634600..e55d44a1d3cd9 100644 --- a/tests/cases/conformance/es2017/useSharedArrayBuffer5.ts +++ b/tests/cases/conformance/es2017/useSharedArrayBuffer5.ts @@ -2,5 +2,5 @@ // @lib: es6,es2017.sharedmemory
[ "+>species : Symbol(species, Decl(useSharedArrayBuffer4.ts, 4, 3))", "+>stringTag : Symbol(stringTag, Decl(useSharedArrayBuffer5.ts, 1, 3))" ]
[ 71, 155 ]
{ "additions": 56, "author": "Renegade334", "deletions": 56, "html_url": "https://github.com/microsoft/TypeScript/pull/61271", "issue_id": 61271, "merged_at": "2025-02-26T21:47:50Z", "omission_probability": 0.1, "pr_number": 61271, "repo": "microsoft/TypeScript", "title": "lib.es2017: Move `SharedArrayBuffer[Symbol.species]` onto constructor interface", "total_changes": 112 }
71
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index abd6fd4bf2e8d..8797dbbf80137 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -47974,7 +47974,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return; } - if (compilerOptions.erasableSyntaxOnly && !(node.flags & NodeFlags.Ambient)) { + if (compilerOptions.erasableSyntaxOnly && node.isExportEquals && !(node.flags & NodeFlags.Ambient)) { error(node, Diagnostics.This_syntax_is_not_allowed_when_erasableSyntaxOnly_is_enabled); } const container = node.parent.kind === SyntaxKind.SourceFile ? node.parent : node.parent.parent as ModuleDeclaration; diff --git a/tests/baselines/reference/erasableSyntaxOnly.errors.txt b/tests/baselines/reference/erasableSyntaxOnly.errors.txt index 39a724aa00c51..2005ef65de8e7 100644 --- a/tests/baselines/reference/erasableSyntaxOnly.errors.txt +++ b/tests/baselines/reference/erasableSyntaxOnly.errors.txt @@ -104,4 +104,9 @@ index.ts(28,12): error TS1294: This syntax is not allowed when 'erasableSyntaxOn ==== other.d.cts (0 errors) ==== declare function foo(): void; export = foo; + + +==== esm.mts (0 errors) ==== + const foo = 1234; + export default foo; \ No newline at end of file diff --git a/tests/baselines/reference/erasableSyntaxOnly.js b/tests/baselines/reference/erasableSyntaxOnly.js index 1d7393620df4d..9edf749d7b038 100644 --- a/tests/baselines/reference/erasableSyntaxOnly.js +++ b/tests/baselines/reference/erasableSyntaxOnly.js @@ -74,6 +74,11 @@ export = foo; //// [other.d.cts] declare function foo(): void; export = foo; + + +//// [esm.mts] +const foo = 1234; +export default foo; //// [index.js] @@ -119,3 +124,6 @@ var MyClassOk = /** @class */ (function () { "use strict"; var foo = require("./other.cjs"); module.exports = foo; +//// [esm.mjs] +var foo = 1234; +export default foo; diff --git a/tests/baselines/reference/erasableSyntaxOnly.symbols b/tests/baselines/reference/erasableSyntaxOnly.symbols index f0220004341b3..8e057dc990217 100644 --- a/tests/baselines/reference/erasableSyntaxOnly.symbols +++ b/tests/baselines/reference/erasableSyntaxOnly.symbols @@ -133,3 +133,11 @@ declare function foo(): void; export = foo; >foo : Symbol(foo, Decl(other.d.cts, 0, 0)) + +=== esm.mts === +const foo = 1234; +>foo : Symbol(foo, Decl(esm.mts, 0, 5)) + +export default foo; +>foo : Symbol(foo, Decl(esm.mts, 0, 5)) + diff --git a/tests/baselines/reference/erasableSyntaxOnly.types b/tests/baselines/reference/erasableSyntaxOnly.types index 599a8d2125ead..4d4ddaea49701 100644 --- a/tests/baselines/reference/erasableSyntaxOnly.types +++ b/tests/baselines/reference/erasableSyntaxOnly.types @@ -179,3 +179,15 @@ export = foo; >foo : () => void > : ^^^^^^ + +=== esm.mts === +const foo = 1234; +>foo : 1234 +> : ^^^^ +>1234 : 1234 +> : ^^^^ + +export default foo; +>foo : 1234 +> : ^^^^ + diff --git a/tests/baselines/reference/erasableSyntaxOnlyDeclaration.errors.txt b/tests/baselines/reference/erasableSyntaxOnlyDeclaration.errors.txt index 7bc78e382b7ed..fdb4d96f8498b 100644 --- a/tests/baselines/reference/erasableSyntaxOnlyDeclaration.errors.txt +++ b/tests/baselines/reference/erasableSyntaxOnlyDeclaration.errors.txt @@ -65,4 +65,9 @@ index.d.ts(1,1): error TS1046: Top-level declarations in .d.ts files must start ==== other.d.cts (0 errors) ==== declare function foo(): void; export = foo; + + +==== esm.d.mts (0 errors) ==== + declare const foo = 1234; + export default foo; \ No newline at end of file diff --git a/tests/baselines/reference/erasableSyntaxOnlyDeclaration.symbols b/tests/baselines/reference/erasableSyntaxOnlyDeclaration.symbols index 4f439b211c5c3..2763999d6468b 100644 --- a/tests/baselines/reference/erasableSyntaxOnlyDeclaration.symbols +++ b/tests/baselines/reference/erasableSyntaxOnlyDeclaration.symbols @@ -112,3 +112,11 @@ declare function foo(): void; export = foo; >foo : Symbol(foo, Decl(other.d.cts, 0, 0)) + +=== esm.d.mts === +declare const foo = 1234; +>foo : Symbol(foo, Decl(esm.d.mts, 0, 13)) + +export default foo; +>foo : Symbol(foo, Decl(esm.d.mts, 0, 13)) + diff --git a/tests/baselines/reference/erasableSyntaxOnlyDeclaration.types b/tests/baselines/reference/erasableSyntaxOnlyDeclaration.types index 031eb9bbb59cb..053aa1b60d2e4 100644 --- a/tests/baselines/reference/erasableSyntaxOnlyDeclaration.types +++ b/tests/baselines/reference/erasableSyntaxOnlyDeclaration.types @@ -154,3 +154,15 @@ export = foo; >foo : () => void > : ^^^^^^ + +=== esm.d.mts === +declare const foo = 1234; +>foo : 1234 +> : ^^^^ +>1234 : 1234 +> : ^^^^ + +export default foo; +>foo : 1234 +> : ^^^^ + diff --git a/tests/cases/compiler/erasableSyntaxOnly.ts b/tests/cases/compiler/erasableSyntaxOnly.ts index 6a76e80337e11..d2ff6d72ce8f3 100644 --- a/tests/cases/compiler/erasableSyntaxOnly.ts +++ b/tests/cases/compiler/erasableSyntaxOnly.ts @@ -74,3 +74,8 @@ export = foo; // @filename: other.d.cts declare function foo(): void; export = foo; + + +// @filename: esm.mts +const foo = 1234; +export default foo; diff --git a/tests/cases/compiler/erasableSyntaxOnlyDeclaration.ts b/tests/cases/compiler/erasableSyntaxOnlyDeclaration.ts index f87e2346f094b..3a986719a160c 100644 --- a/tests/cases/compiler/erasableSyntaxOnlyDeclaration.ts +++ b/tests/cases/compiler/erasableSyntaxOnlyDeclaration.ts @@ -66,3 +66,8 @@ export = foo; // @filename: other.d.cts declare function foo(): void; export = foo; + + +// @filename: esm.d.mts +declare const foo = 1234; +export default foo;
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index abd6fd4bf2e8d..8797dbbf80137 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -47974,7 +47974,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return; + if (compilerOptions.erasableSyntaxOnly && node.isExportEquals && !(node.flags & NodeFlags.Ambient)) { error(node, Diagnostics.This_syntax_is_not_allowed_when_erasableSyntaxOnly_is_enabled); const container = node.parent.kind === SyntaxKind.SourceFile ? node.parent : node.parent.parent as ModuleDeclaration; diff --git a/tests/baselines/reference/erasableSyntaxOnly.errors.txt b/tests/baselines/reference/erasableSyntaxOnly.errors.txt index 39a724aa00c51..2005ef65de8e7 100644 --- a/tests/baselines/reference/erasableSyntaxOnly.errors.txt +++ b/tests/baselines/reference/erasableSyntaxOnly.errors.txt @@ -104,4 +104,9 @@ index.ts(28,12): error TS1294: This syntax is not allowed when 'erasableSyntaxOn +==== esm.mts (0 errors) ==== + const foo = 1234; diff --git a/tests/baselines/reference/erasableSyntaxOnly.js b/tests/baselines/reference/erasableSyntaxOnly.js index 1d7393620df4d..9edf749d7b038 100644 --- a/tests/baselines/reference/erasableSyntaxOnly.js +++ b/tests/baselines/reference/erasableSyntaxOnly.js @@ -74,6 +74,11 @@ export = foo; //// [other.d.cts] +//// [esm.mts] //// [index.js] @@ -119,3 +124,6 @@ var MyClassOk = /** @class */ (function () { "use strict"; var foo = require("./other.cjs"); module.exports = foo; +//// [esm.mjs] +var foo = 1234; diff --git a/tests/baselines/reference/erasableSyntaxOnly.symbols b/tests/baselines/reference/erasableSyntaxOnly.symbols index f0220004341b3..8e057dc990217 100644 --- a/tests/baselines/reference/erasableSyntaxOnly.symbols +++ b/tests/baselines/reference/erasableSyntaxOnly.symbols @@ -133,3 +133,11 @@ declare function foo(): void; diff --git a/tests/baselines/reference/erasableSyntaxOnly.types b/tests/baselines/reference/erasableSyntaxOnly.types index 599a8d2125ead..4d4ddaea49701 100644 --- a/tests/baselines/reference/erasableSyntaxOnly.types +++ b/tests/baselines/reference/erasableSyntaxOnly.types @@ -179,3 +179,15 @@ export = foo; diff --git a/tests/baselines/reference/erasableSyntaxOnlyDeclaration.errors.txt b/tests/baselines/reference/erasableSyntaxOnlyDeclaration.errors.txt index 7bc78e382b7ed..fdb4d96f8498b 100644 --- a/tests/baselines/reference/erasableSyntaxOnlyDeclaration.errors.txt +++ b/tests/baselines/reference/erasableSyntaxOnlyDeclaration.errors.txt @@ -65,4 +65,9 @@ index.d.ts(1,1): error TS1046: Top-level declarations in .d.ts files must start + declare const foo = 1234; diff --git a/tests/baselines/reference/erasableSyntaxOnlyDeclaration.symbols b/tests/baselines/reference/erasableSyntaxOnlyDeclaration.symbols index 4f439b211c5c3..2763999d6468b 100644 --- a/tests/baselines/reference/erasableSyntaxOnlyDeclaration.symbols +++ b/tests/baselines/reference/erasableSyntaxOnlyDeclaration.symbols @@ -112,3 +112,11 @@ declare function foo(): void; diff --git a/tests/baselines/reference/erasableSyntaxOnlyDeclaration.types b/tests/baselines/reference/erasableSyntaxOnlyDeclaration.types index 031eb9bbb59cb..053aa1b60d2e4 100644 --- a/tests/baselines/reference/erasableSyntaxOnlyDeclaration.types +++ b/tests/baselines/reference/erasableSyntaxOnlyDeclaration.types @@ -154,3 +154,15 @@ export = foo; diff --git a/tests/cases/compiler/erasableSyntaxOnly.ts b/tests/cases/compiler/erasableSyntaxOnly.ts index 6a76e80337e11..d2ff6d72ce8f3 100644 --- a/tests/cases/compiler/erasableSyntaxOnly.ts +++ b/tests/cases/compiler/erasableSyntaxOnly.ts @@ -74,3 +74,8 @@ export = foo; +// @filename: esm.mts diff --git a/tests/cases/compiler/erasableSyntaxOnlyDeclaration.ts b/tests/cases/compiler/erasableSyntaxOnlyDeclaration.ts index f87e2346f094b..3a986719a160c 100644 --- a/tests/cases/compiler/erasableSyntaxOnlyDeclaration.ts +++ b/tests/cases/compiler/erasableSyntaxOnlyDeclaration.ts @@ -66,3 +66,8 @@ export = foo; +// @filename: esm.d.mts
[ "- if (compilerOptions.erasableSyntaxOnly && !(node.flags & NodeFlags.Ambient)) {", "+==== esm.d.mts (0 errors) ====" ]
[ 8, 97 ]
{ "additions": 69, "author": "typescript-bot", "deletions": 1, "html_url": "https://github.com/microsoft/TypeScript/pull/61237", "issue_id": 61237, "merged_at": "2025-02-26T06:46:12Z", "omission_probability": 0.1, "pr_number": 61237, "repo": "microsoft/TypeScript", "title": "🤖 Pick PR #61210 (Fix mistakenly disallowed default e...) into release-5.8", "total_changes": 70 }
72
diff --git a/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl index 720fea33b86ba..857e007dbff90 100644 --- a/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -15270,6 +15270,15 @@ </Str> <Disp Icon="Str" /> </Item> + <Item ItemId=";This_expression_is_never_nullish_2881" ItemType="0" PsrId="306" Leaf="true"> + <Str Cat="Text"> + <Val><![CDATA[This expression is never nullish.]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[此表达式从不为 null。]]></Val> + </Tgt> + </Str> + <Disp Icon="Str" /> + </Item> <Item ItemId=";This_expression_is_not_callable_2349" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[This expression is not callable.]]></Val> diff --git a/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl index e26e96401f42b..a24cd15b61e6d 100644 --- a/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -15282,6 +15282,15 @@ </Str> <Disp Icon="Str" /> </Item> + <Item ItemId=";This_expression_is_never_nullish_2881" ItemType="0" PsrId="306" Leaf="true"> + <Str Cat="Text"> + <Val><![CDATA[This expression is never nullish.]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Esta expresión nunca es nula.]]></Val> + </Tgt> + </Str> + <Disp Icon="Str" /> + </Item> <Item ItemId=";This_expression_is_not_callable_2349" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[This expression is not callable.]]></Val> diff --git a/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl index e2a3a5137dcb9..b77b61764b2bd 100644 --- a/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -15270,6 +15270,15 @@ </Str> <Disp Icon="Str" /> </Item> + <Item ItemId=";This_expression_is_never_nullish_2881" ItemType="0" PsrId="306" Leaf="true"> + <Str Cat="Text"> + <Val><![CDATA[This expression is never nullish.]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Questa espressione non è mai null.]]></Val> + </Tgt> + </Str> + <Disp Icon="Str" /> + </Item> <Item ItemId=";This_expression_is_not_callable_2349" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[This expression is not callable.]]></Val> diff --git a/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl index 3aba11775753f..bcfe2e5092305 100644 --- a/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -15260,6 +15260,15 @@ </Str> <Disp Icon="Str" /> </Item> + <Item ItemId=";This_expression_is_never_nullish_2881" ItemType="0" PsrId="306" Leaf="true"> + <Str Cat="Text"> + <Val><![CDATA[This expression is never nullish.]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Esta expressão nunca é nula.]]></Val> + </Tgt> + </Str> + <Disp Icon="Str" /> + </Item> <Item ItemId=";This_expression_is_not_callable_2349" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[This expression is not callable.]]></Val> diff --git a/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl index ed3d8618a042d..cebc482da2c3a 100644 --- a/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -15269,6 +15269,15 @@ </Str> <Disp Icon="Str" /> </Item> + <Item ItemId=";This_expression_is_never_nullish_2881" ItemType="0" PsrId="306" Leaf="true"> + <Str Cat="Text"> + <Val><![CDATA[This expression is never nullish.]]></Val> + <Tgt Cat="Text" Stat="Loc" Orig="New"> + <Val><![CDATA[Это выражение никогда не принимает значение null.]]></Val> + </Tgt> + </Str> + <Disp Icon="Str" /> + </Item> <Item ItemId=";This_expression_is_not_callable_2349" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> <Val><![CDATA[This expression is not callable.]]></Val>
diff --git a/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl index 720fea33b86ba..857e007dbff90 100644 --- a/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl + <Val><![CDATA[此表达式从不为 null。]]></Val> diff --git a/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl index e26e96401f42b..a24cd15b61e6d 100644 --- a/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -15282,6 +15282,15 @@ + <Val><![CDATA[Esta expresión nunca es nula.]]></Val> diff --git a/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl index e2a3a5137dcb9..b77b61764b2bd 100644 --- a/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl + <Val><![CDATA[Questa espressione non è mai null.]]></Val> diff --git a/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl index 3aba11775753f..bcfe2e5092305 100644 --- a/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -15260,6 +15260,15 @@ + <Val><![CDATA[Esta expressão nunca é nula.]]></Val> diff --git a/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl index ed3d8618a042d..cebc482da2c3a 100644 --- a/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -15269,6 +15269,15 @@ + <Val><![CDATA[Это выражение никогда не принимает значение null.]]></Val>
[]
[]
{ "additions": 45, "author": "csigs", "deletions": 0, "html_url": "https://github.com/microsoft/TypeScript/pull/61269", "issue_id": 61269, "merged_at": "2025-02-25T22:39:49Z", "omission_probability": 0.1, "pr_number": 61269, "repo": "microsoft/TypeScript", "title": "LEGO: Pull request from lego/hb_5378966c-b857-470a-8675-daebef4a6da1_20250225202237529 to main", "total_changes": 45 }
73
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index d9d1950d6b675..8b015d6dd0af8 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -11821,7 +11821,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } // always widen a 'unique symbol' type if the type was created for a different declaration. - if (type.flags & TypeFlags.UniqueESSymbol && (isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfDeclaration(declaration)) { + if (type.flags & TypeFlags.UniqueESSymbol && (isBindingElement(declaration) || !tryGetTypeFromEffectiveTypeNode(declaration)) && type.symbol !== getSymbolOfDeclaration(declaration)) { type = esSymbolType; } diff --git a/tests/baselines/reference/uniqueSymbolJs2.errors.txt b/tests/baselines/reference/uniqueSymbolJs2.errors.txt new file mode 100644 index 0000000000000..cb2d4dc7d6fc0 --- /dev/null +++ b/tests/baselines/reference/uniqueSymbolJs2.errors.txt @@ -0,0 +1,15 @@ +/index.js(9,1): error TS2367: This comparison appears to be unintentional because the types 'typeof x' and 'typeof y' have no overlap. + + +==== /index.js (1 errors) ==== + /** @type {unique symbol} */ + const x = Symbol() + /** @type {unique symbol} */ + const y = Symbol() + + /** @type {typeof x} */ + let z = x + + z == y // error + ~~~~~~ +!!! error TS2367: This comparison appears to be unintentional because the types 'typeof x' and 'typeof y' have no overlap. \ No newline at end of file diff --git a/tests/baselines/reference/uniqueSymbolJs2.js b/tests/baselines/reference/uniqueSymbolJs2.js new file mode 100644 index 0000000000000..9aff6a702a259 --- /dev/null +++ b/tests/baselines/reference/uniqueSymbolJs2.js @@ -0,0 +1,31 @@ +//// [tests/cases/compiler/uniqueSymbolJs2.ts] //// + +//// [index.js] +/** @type {unique symbol} */ +const x = Symbol() +/** @type {unique symbol} */ +const y = Symbol() + +/** @type {typeof x} */ +let z = x + +z == y // error + +//// [index.js] +"use strict"; +/** @type {unique symbol} */ +var x = Symbol(); +/** @type {unique symbol} */ +var y = Symbol(); +/** @type {typeof x} */ +var z = x; +z == y; // error + + +//// [index.d.ts] +/** @type {unique symbol} */ +declare const x: unique symbol; +/** @type {unique symbol} */ +declare const y: unique symbol; +/** @type {typeof x} */ +declare let z: typeof x; diff --git a/tests/baselines/reference/uniqueSymbolJs2.symbols b/tests/baselines/reference/uniqueSymbolJs2.symbols new file mode 100644 index 0000000000000..cea37701f5b37 --- /dev/null +++ b/tests/baselines/reference/uniqueSymbolJs2.symbols @@ -0,0 +1,22 @@ +//// [tests/cases/compiler/uniqueSymbolJs2.ts] //// + +=== /index.js === +/** @type {unique symbol} */ +const x = Symbol() +>x : Symbol(x, Decl(index.js, 1, 5)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) + +/** @type {unique symbol} */ +const y = Symbol() +>y : Symbol(y, Decl(index.js, 3, 5)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) + +/** @type {typeof x} */ +let z = x +>z : Symbol(z, Decl(index.js, 6, 3)) +>x : Symbol(x, Decl(index.js, 1, 5)) + +z == y // error +>z : Symbol(z, Decl(index.js, 6, 3)) +>y : Symbol(y, Decl(index.js, 3, 5)) + diff --git a/tests/baselines/reference/uniqueSymbolJs2.types b/tests/baselines/reference/uniqueSymbolJs2.types new file mode 100644 index 0000000000000..8cb3c434c25f2 --- /dev/null +++ b/tests/baselines/reference/uniqueSymbolJs2.types @@ -0,0 +1,36 @@ +//// [tests/cases/compiler/uniqueSymbolJs2.ts] //// + +=== /index.js === +/** @type {unique symbol} */ +const x = Symbol() +>x : unique symbol +> : ^^^^^^^^^^^^^ +>Symbol() : unique symbol +> : ^^^^^^^^^^^^^ +>Symbol : SymbolConstructor +> : ^^^^^^^^^^^^^^^^^ + +/** @type {unique symbol} */ +const y = Symbol() +>y : unique symbol +> : ^^^^^^^^^^^^^ +>Symbol() : unique symbol +> : ^^^^^^^^^^^^^ +>Symbol : SymbolConstructor +> : ^^^^^^^^^^^^^^^^^ + +/** @type {typeof x} */ +let z = x +>z : unique symbol +> : ^^^^^^^^^^^^^ +>x : unique symbol +> : ^^^^^^^^^^^^^ + +z == y // error +>z == y : boolean +> : ^^^^^^^ +>z : unique symbol +> : ^^^^^^^^^^^^^ +>y : unique symbol +> : ^^^^^^^^^^^^^ + diff --git a/tests/cases/compiler/uniqueSymbolJs2.ts b/tests/cases/compiler/uniqueSymbolJs2.ts new file mode 100644 index 0000000000000..916b47762db55 --- /dev/null +++ b/tests/cases/compiler/uniqueSymbolJs2.ts @@ -0,0 +1,19 @@ +// @strict: true +// @lib: esnext +// @allowJS: true +// @checkJs: true +// @declaration: true +// @outDir: dist + +// https://github.com/microsoft/TypeScript/issues/61170 + +// @filename: /index.js +/** @type {unique symbol} */ +const x = Symbol() +/** @type {unique symbol} */ +const y = Symbol() + +/** @type {typeof x} */ +let z = x + +z == y // error \ No newline at end of file
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index d9d1950d6b675..8b015d6dd0af8 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -11821,7 +11821,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // always widen a 'unique symbol' type if the type was created for a different declaration. - if (type.flags & TypeFlags.UniqueESSymbol && (isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfDeclaration(declaration)) { + if (type.flags & TypeFlags.UniqueESSymbol && (isBindingElement(declaration) || !tryGetTypeFromEffectiveTypeNode(declaration)) && type.symbol !== getSymbolOfDeclaration(declaration)) { type = esSymbolType; diff --git a/tests/baselines/reference/uniqueSymbolJs2.errors.txt b/tests/baselines/reference/uniqueSymbolJs2.errors.txt index 0000000000000..cb2d4dc7d6fc0 +++ b/tests/baselines/reference/uniqueSymbolJs2.errors.txt @@ -0,0 +1,15 @@ +/index.js(9,1): error TS2367: This comparison appears to be unintentional because the types 'typeof x' and 'typeof y' have no overlap. +==== /index.js (1 errors) ==== + const x = Symbol() + const y = Symbol() + /** @type {typeof x} */ + let z = x + z == y // error + ~~~~~~ +!!! error TS2367: This comparison appears to be unintentional because the types 'typeof x' and 'typeof y' have no overlap. diff --git a/tests/baselines/reference/uniqueSymbolJs2.js b/tests/baselines/reference/uniqueSymbolJs2.js index 0000000000000..9aff6a702a259 +++ b/tests/baselines/reference/uniqueSymbolJs2.js @@ -0,0 +1,31 @@ +"use strict"; +var x = Symbol(); +var y = Symbol(); +z == y; // error +//// [index.d.ts] +declare const x: unique symbol; +declare const y: unique symbol; +declare let z: typeof x; diff --git a/tests/baselines/reference/uniqueSymbolJs2.symbols b/tests/baselines/reference/uniqueSymbolJs2.symbols index 0000000000000..cea37701f5b37 +++ b/tests/baselines/reference/uniqueSymbolJs2.symbols @@ -0,0 +1,22 @@ diff --git a/tests/baselines/reference/uniqueSymbolJs2.types b/tests/baselines/reference/uniqueSymbolJs2.types index 0000000000000..8cb3c434c25f2 +++ b/tests/baselines/reference/uniqueSymbolJs2.types @@ -0,0 +1,36 @@ +>z == y : boolean +> : ^^^^^^^ diff --git a/tests/cases/compiler/uniqueSymbolJs2.ts b/tests/cases/compiler/uniqueSymbolJs2.ts index 0000000000000..916b47762db55 +++ b/tests/cases/compiler/uniqueSymbolJs2.ts @@ -0,0 +1,19 @@ +// @strict: true +// @lib: esnext +// @allowJS: true +// @checkJs: true +// @declaration: true +// @outDir: dist +// https://github.com/microsoft/TypeScript/issues/61170 +// @filename: /index.js
[ "+var z = x;" ]
[ 61 ]
{ "additions": 124, "author": "Andarist", "deletions": 1, "html_url": "https://github.com/microsoft/TypeScript/pull/61180", "issue_id": 61180, "merged_at": "2025-02-24T19:53:10Z", "omission_probability": 0.1, "pr_number": 61180, "repo": "microsoft/TypeScript", "title": "Don't widen unique symbols annotated by effective type nodes in JS files", "total_changes": 125 }
74
diff --git a/src/services/formatting/smartIndenter.ts b/src/services/formatting/smartIndenter.ts index c6ed975a1a516..7f41a2701b8c3 100644 --- a/src/services/formatting/smartIndenter.ts +++ b/src/services/formatting/smartIndenter.ts @@ -729,6 +729,11 @@ export namespace SmartIndenter { return false; } break; + case SyntaxKind.TryStatement: + if (childKind === SyntaxKind.Block) { + return false; + } + break; } // No explicit rule for given nodes so the result will follow the default value argument return indentByDefault; diff --git a/tests/cases/fourslash/formatTryFinally.ts b/tests/cases/fourslash/formatTryFinally.ts new file mode 100644 index 0000000000000..d81cd45e79366 --- /dev/null +++ b/tests/cases/fourslash/formatTryFinally.ts @@ -0,0 +1,15 @@ +/// <reference path="fourslash.ts"/> + +////if (true) try { +//// // ... +////} finally { +//// // ... +////} + +format.document(); +verify.currentFileContentIs( +`if (true) try { + // ... +} finally { + // ... +}`);
diff --git a/src/services/formatting/smartIndenter.ts b/src/services/formatting/smartIndenter.ts index c6ed975a1a516..7f41a2701b8c3 100644 --- a/src/services/formatting/smartIndenter.ts +++ b/src/services/formatting/smartIndenter.ts @@ -729,6 +729,11 @@ export namespace SmartIndenter { return false; } break; + case SyntaxKind.TryStatement: + if (childKind === SyntaxKind.Block) { + return false; + } + break; } // No explicit rule for given nodes so the result will follow the default value argument return indentByDefault; diff --git a/tests/cases/fourslash/formatTryFinally.ts b/tests/cases/fourslash/formatTryFinally.ts new file mode 100644 index 0000000000000..d81cd45e79366 --- /dev/null +++ b/tests/cases/fourslash/formatTryFinally.ts @@ -0,0 +1,15 @@ +/// <reference path="fourslash.ts"/> +////if (true) try { +////} finally { +////} +format.document(); +verify.currentFileContentIs( +`if (true) try { +} finally { +}`);
[]
[]
{ "additions": 20, "author": "a-tarasyuk", "deletions": 0, "html_url": "https://github.com/microsoft/TypeScript/pull/60898", "issue_id": 60898, "merged_at": "2025-02-24T19:51:29Z", "omission_probability": 0.1, "pr_number": 60898, "repo": "microsoft/TypeScript", "title": "fix(60887): Incorrect Formatting on if (a) try {} finally {} ", "total_changes": 20 }
75
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 7f18bbc1a1dec..9d92c2bcbaf40 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -28732,7 +28732,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // parameter declared in the same parameter list is a candidate. if (isIdentifier(expr)) { const symbol = getResolvedSymbol(expr); - const declaration = symbol.valueDeclaration; + const declaration = getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; if (declaration && (isBindingElement(declaration) || isParameter(declaration)) && reference === declaration.parent && !declaration.initializer && !declaration.dotDotDotToken) { return declaration; } diff --git a/tests/baselines/reference/dependentDestructuredVariablesWithExport.symbols b/tests/baselines/reference/dependentDestructuredVariablesWithExport.symbols new file mode 100644 index 0000000000000..c65d71e28d6b4 --- /dev/null +++ b/tests/baselines/reference/dependentDestructuredVariablesWithExport.symbols @@ -0,0 +1,49 @@ +//// [tests/cases/conformance/controlFlow/dependentDestructuredVariablesWithExport.ts] //// + +=== dependentDestructuredVariablesWithExport.ts === +// https://github.com/microsoft/TypeScript/issues/59652 + +declare function mutuallyEnabledPair(): { +>mutuallyEnabledPair : Symbol(mutuallyEnabledPair, Decl(dependentDestructuredVariablesWithExport.ts, 0, 0)) + + discriminator: true, +>discriminator : Symbol(discriminator, Decl(dependentDestructuredVariablesWithExport.ts, 2, 41)) + + value: string, +>value : Symbol(value, Decl(dependentDestructuredVariablesWithExport.ts, 3, 24)) + + } | { + discriminator: false, +>discriminator : Symbol(discriminator, Decl(dependentDestructuredVariablesWithExport.ts, 5, 7)) + + value: null | undefined, +>value : Symbol(value, Decl(dependentDestructuredVariablesWithExport.ts, 6, 25)) + } + +const { discriminator: discriminator1, value: value1 } = mutuallyEnabledPair() +>discriminator : Symbol(discriminator, Decl(dependentDestructuredVariablesWithExport.ts, 2, 41), Decl(dependentDestructuredVariablesWithExport.ts, 5, 7)) +>discriminator1 : Symbol(discriminator1, Decl(dependentDestructuredVariablesWithExport.ts, 10, 7)) +>value : Symbol(value, Decl(dependentDestructuredVariablesWithExport.ts, 3, 24), Decl(dependentDestructuredVariablesWithExport.ts, 6, 25)) +>value1 : Symbol(value1, Decl(dependentDestructuredVariablesWithExport.ts, 10, 38)) +>mutuallyEnabledPair : Symbol(mutuallyEnabledPair, Decl(dependentDestructuredVariablesWithExport.ts, 0, 0)) + +if (discriminator1) { +>discriminator1 : Symbol(discriminator1, Decl(dependentDestructuredVariablesWithExport.ts, 10, 7)) + + value1; +>value1 : Symbol(value1, Decl(dependentDestructuredVariablesWithExport.ts, 10, 38)) +} + +export const { discriminator: discriminator2, value: value2 } = mutuallyEnabledPair() +>discriminator : Symbol(discriminator, Decl(dependentDestructuredVariablesWithExport.ts, 2, 41), Decl(dependentDestructuredVariablesWithExport.ts, 5, 7)) +>discriminator2 : Symbol(discriminator2, Decl(dependentDestructuredVariablesWithExport.ts, 16, 14)) +>value : Symbol(value, Decl(dependentDestructuredVariablesWithExport.ts, 3, 24), Decl(dependentDestructuredVariablesWithExport.ts, 6, 25)) +>value2 : Symbol(value2, Decl(dependentDestructuredVariablesWithExport.ts, 16, 45)) +>mutuallyEnabledPair : Symbol(mutuallyEnabledPair, Decl(dependentDestructuredVariablesWithExport.ts, 0, 0)) + +if (discriminator2) { +>discriminator2 : Symbol(discriminator2, Decl(dependentDestructuredVariablesWithExport.ts, 16, 14)) + + value2; +>value2 : Symbol(value2, Decl(dependentDestructuredVariablesWithExport.ts, 16, 45)) +} diff --git a/tests/baselines/reference/dependentDestructuredVariablesWithExport.types b/tests/baselines/reference/dependentDestructuredVariablesWithExport.types new file mode 100644 index 0000000000000..09386ce819b5e --- /dev/null +++ b/tests/baselines/reference/dependentDestructuredVariablesWithExport.types @@ -0,0 +1,76 @@ +//// [tests/cases/conformance/controlFlow/dependentDestructuredVariablesWithExport.ts] //// + +=== dependentDestructuredVariablesWithExport.ts === +// https://github.com/microsoft/TypeScript/issues/59652 + +declare function mutuallyEnabledPair(): { +>mutuallyEnabledPair : () => { discriminator: true; value: string; } | { discriminator: false; value: null | undefined; } +> : ^^^^^^ + + discriminator: true, +>discriminator : true +> : ^^^^ +>true : true +> : ^^^^ + + value: string, +>value : string +> : ^^^^^^ + + } | { + discriminator: false, +>discriminator : false +> : ^^^^^ +>false : false +> : ^^^^^ + + value: null | undefined, +>value : null | undefined +> : ^^^^^^^^^^^^^^^^ + } + +const { discriminator: discriminator1, value: value1 } = mutuallyEnabledPair() +>discriminator : any +> : ^^^ +>discriminator1 : boolean +> : ^^^^^^^ +>value : any +> : ^^^ +>value1 : string | null | undefined +> : ^^^^^^^^^^^^^^^^^^^^^^^^^ +>mutuallyEnabledPair() : { discriminator: true; value: string; } | { discriminator: false; value: null | undefined; } +> : ^^^^^^^^^^^^^^^^^ ^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^ ^^^ +>mutuallyEnabledPair : () => { discriminator: true; value: string; } | { discriminator: false; value: null | undefined; } +> : ^^^^^^ + +if (discriminator1) { +>discriminator1 : boolean +> : ^^^^^^^ + + value1; +>value1 : string +> : ^^^^^^ +} + +export const { discriminator: discriminator2, value: value2 } = mutuallyEnabledPair() +>discriminator : any +> : ^^^ +>discriminator2 : boolean +> : ^^^^^^^ +>value : any +> : ^^^ +>value2 : string | null | undefined +> : ^^^^^^^^^^^^^^^^^^^^^^^^^ +>mutuallyEnabledPair() : { discriminator: true; value: string; } | { discriminator: false; value: null | undefined; } +> : ^^^^^^^^^^^^^^^^^ ^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^ ^^^ +>mutuallyEnabledPair : () => { discriminator: true; value: string; } | { discriminator: false; value: null | undefined; } +> : ^^^^^^ + +if (discriminator2) { +>discriminator2 : boolean +> : ^^^^^^^ + + value2; +>value2 : string +> : ^^^^^^ +} diff --git a/tests/cases/conformance/controlFlow/dependentDestructuredVariablesWithExport.ts b/tests/cases/conformance/controlFlow/dependentDestructuredVariablesWithExport.ts new file mode 100644 index 0000000000000..69a7aab62d5a7 --- /dev/null +++ b/tests/cases/conformance/controlFlow/dependentDestructuredVariablesWithExport.ts @@ -0,0 +1,24 @@ +// @strict: true +// @noEmit: true + +// https://github.com/microsoft/TypeScript/issues/59652 + +declare function mutuallyEnabledPair(): { + discriminator: true, + value: string, + } | { + discriminator: false, + value: null | undefined, + } + +const { discriminator: discriminator1, value: value1 } = mutuallyEnabledPair() + +if (discriminator1) { + value1; +} + +export const { discriminator: discriminator2, value: value2 } = mutuallyEnabledPair() + +if (discriminator2) { + value2; +} \ No newline at end of file
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 7f18bbc1a1dec..9d92c2bcbaf40 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -28732,7 +28732,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // parameter declared in the same parameter list is a candidate. if (isIdentifier(expr)) { const symbol = getResolvedSymbol(expr); - const declaration = symbol.valueDeclaration; + const declaration = getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; if (declaration && (isBindingElement(declaration) || isParameter(declaration)) && reference === declaration.parent && !declaration.initializer && !declaration.dotDotDotToken) { return declaration; } diff --git a/tests/baselines/reference/dependentDestructuredVariablesWithExport.symbols b/tests/baselines/reference/dependentDestructuredVariablesWithExport.symbols index 0000000000000..c65d71e28d6b4 +++ b/tests/baselines/reference/dependentDestructuredVariablesWithExport.symbols @@ -0,0 +1,49 @@ +>discriminator : Symbol(discriminator, Decl(dependentDestructuredVariablesWithExport.ts, 2, 41)) +>value : Symbol(value, Decl(dependentDestructuredVariablesWithExport.ts, 3, 24)) +>discriminator : Symbol(discriminator, Decl(dependentDestructuredVariablesWithExport.ts, 5, 7)) +>value : Symbol(value, Decl(dependentDestructuredVariablesWithExport.ts, 6, 25)) diff --git a/tests/baselines/reference/dependentDestructuredVariablesWithExport.types b/tests/baselines/reference/dependentDestructuredVariablesWithExport.types index 0000000000000..09386ce819b5e +++ b/tests/baselines/reference/dependentDestructuredVariablesWithExport.types @@ -0,0 +1,76 @@ +>discriminator : true +> : ^^^^ +> : ^^^^ +>value : string +> : ^^^^^^ +>discriminator : false +> : ^^^^^ +>false : false +> : ^^^^^ +>value : null | undefined +> : ^^^^^^^^^^^^^^^^ +>value1 : string | null | undefined +>value1 : string +>value2 : string | null | undefined +>value2 : string diff --git a/tests/cases/conformance/controlFlow/dependentDestructuredVariablesWithExport.ts b/tests/cases/conformance/controlFlow/dependentDestructuredVariablesWithExport.ts index 0000000000000..69a7aab62d5a7 +++ b/tests/cases/conformance/controlFlow/dependentDestructuredVariablesWithExport.ts @@ -0,0 +1,24 @@ +// @strict: true +// @noEmit: true \ No newline at end of file
[ "+>true : true" ]
[ 86 ]
{ "additions": 150, "author": "MichalMarsalek", "deletions": 1, "html_url": "https://github.com/microsoft/TypeScript/pull/59673", "issue_id": 59673, "merged_at": "2025-02-24T18:29:01Z", "omission_probability": 0.1, "pr_number": 59673, "repo": "microsoft/TypeScript", "title": "make exported destructured discriminated union narrowing work", "total_changes": 151 }
76
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6b3d9c346a2ab..11dcdc0cda385 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -90,7 +90,7 @@ jobs: run: npm test -- --no-lint --coverage - name: Upload coverage artifact - uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4.6.0 + uses: actions/upload-artifact@4cec3d8aa04e39d1a68397de0c4cd6fb9dce8ec1 # v4.6.1 with: name: coverage path: coverage @@ -137,7 +137,7 @@ jobs: node-version: 'lts/*' - run: npm ci - - uses: actions/cache@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 + - uses: actions/cache@0c907a75c2c80ebcb7f088228285e798b750cf8f # v4.2.1 with: path: ~/.cache/dprint key: ${{ runner.os }}-dprint-${{ hashFiles('package-lock.json', '.dprint.jsonc') }} @@ -334,7 +334,7 @@ jobs: - name: Upload baseline diff artifact if: ${{ failure() && steps.check-baselines.conclusion == 'failure' }} - uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4.6.0 + uses: actions/upload-artifact@4cec3d8aa04e39d1a68397de0c4cd6fb9dce8ec1 # v4.6.1 with: name: fix_baselines.patch path: fix_baselines.patch diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index d0d0ebc1a442b..ee92c5bc14eb2 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -46,7 +46,7 @@ jobs: # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@9e8d0789d4a0fa9ceb6b1738f7e269594bdd67f0 # v3.28.9 + uses: github/codeql-action/init@b56ba49b26e50535fa1e7f7db0f4f7b4bf65d80d # v3.28.10 with: config-file: ./.github/codeql/codeql-configuration.yml # Override language selection by uncommenting this and choosing your languages @@ -56,7 +56,7 @@ jobs: # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below). - name: Autobuild - uses: github/codeql-action/autobuild@9e8d0789d4a0fa9ceb6b1738f7e269594bdd67f0 # v3.28.9 + uses: github/codeql-action/autobuild@b56ba49b26e50535fa1e7f7db0f4f7b4bf65d80d # v3.28.10 # ℹ️ Command-line programs to run using the OS shell. # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun @@ -70,4 +70,4 @@ jobs: # make release - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@9e8d0789d4a0fa9ceb6b1738f7e269594bdd67f0 # v3.28.9 + uses: github/codeql-action/analyze@b56ba49b26e50535fa1e7f7db0f4f7b4bf65d80d # v3.28.10 diff --git a/.github/workflows/release-branch-artifact.yaml b/.github/workflows/release-branch-artifact.yaml index a3cfb107ea0b5..4c5d774f5e1d6 100644 --- a/.github/workflows/release-branch-artifact.yaml +++ b/.github/workflows/release-branch-artifact.yaml @@ -44,7 +44,7 @@ jobs: npm pack ./ mv typescript-*.tgz typescript.tgz - name: Upload built tarfile - uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4.6.0 + uses: actions/upload-artifact@4cec3d8aa04e39d1a68397de0c4cd6fb9dce8ec1 # v4.6.1 with: name: tgz path: typescript.tgz diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml index cca13091e26c9..18372ab8c0bf2 100644 --- a/.github/workflows/scorecard.yml +++ b/.github/workflows/scorecard.yml @@ -34,7 +34,7 @@ jobs: persist-credentials: false - name: 'Run analysis' - uses: ossf/scorecard-action@62b2cac7ed8198b15735ed49ab1e5cf35480ba46 # v2.4.0 + uses: ossf/scorecard-action@f49aabe0b5af0936a0987cfb85d86b75731b0186 # v2.4.1 with: results_file: results.sarif results_format: sarif @@ -47,7 +47,7 @@ jobs: # Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF # format to the repository Actions tab. - name: 'Upload artifact' - uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4.6.0 + uses: actions/upload-artifact@4cec3d8aa04e39d1a68397de0c4cd6fb9dce8ec1 # v4.6.1 with: name: SARIF file path: results.sarif @@ -55,6 +55,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: 'Upload to code-scanning' - uses: github/codeql-action/upload-sarif@9e8d0789d4a0fa9ceb6b1738f7e269594bdd67f0 # v3.28.9 + uses: github/codeql-action/upload-sarif@b56ba49b26e50535fa1e7f7db0f4f7b4bf65d80d # v3.28.10 with: sarif_file: results.sarif
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6b3d9c346a2ab..11dcdc0cda385 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -90,7 +90,7 @@ jobs: run: npm test -- --no-lint --coverage - name: Upload coverage artifact name: coverage path: coverage @@ -137,7 +137,7 @@ jobs: node-version: 'lts/*' - run: npm ci - - uses: actions/cache@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 + - uses: actions/cache@0c907a75c2c80ebcb7f088228285e798b750cf8f # v4.2.1 path: ~/.cache/dprint key: ${{ runner.os }}-dprint-${{ hashFiles('package-lock.json', '.dprint.jsonc') }} @@ -334,7 +334,7 @@ jobs: - name: Upload baseline diff artifact if: ${{ failure() && steps.check-baselines.conclusion == 'failure' }} name: fix_baselines.patch path: fix_baselines.patch diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index d0d0ebc1a442b..ee92c5bc14eb2 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -46,7 +46,7 @@ jobs: # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@9e8d0789d4a0fa9ceb6b1738f7e269594bdd67f0 # v3.28.9 + uses: github/codeql-action/init@b56ba49b26e50535fa1e7f7db0f4f7b4bf65d80d # v3.28.10 config-file: ./.github/codeql/codeql-configuration.yml # Override language selection by uncommenting this and choosing your languages @@ -56,7 +56,7 @@ jobs: # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below). - name: Autobuild - uses: github/codeql-action/autobuild@9e8d0789d4a0fa9ceb6b1738f7e269594bdd67f0 # v3.28.9 + uses: github/codeql-action/autobuild@b56ba49b26e50535fa1e7f7db0f4f7b4bf65d80d # v3.28.10 # ℹ️ Command-line programs to run using the OS shell. # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun @@ -70,4 +70,4 @@ jobs: # make release - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@9e8d0789d4a0fa9ceb6b1738f7e269594bdd67f0 # v3.28.9 + uses: github/codeql-action/analyze@b56ba49b26e50535fa1e7f7db0f4f7b4bf65d80d # v3.28.10 diff --git a/.github/workflows/release-branch-artifact.yaml b/.github/workflows/release-branch-artifact.yaml index a3cfb107ea0b5..4c5d774f5e1d6 100644 --- a/.github/workflows/release-branch-artifact.yaml +++ b/.github/workflows/release-branch-artifact.yaml @@ -44,7 +44,7 @@ jobs: npm pack ./ mv typescript-*.tgz typescript.tgz - name: Upload built tarfile name: tgz path: typescript.tgz diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml index cca13091e26c9..18372ab8c0bf2 100644 --- a/.github/workflows/scorecard.yml +++ b/.github/workflows/scorecard.yml @@ -34,7 +34,7 @@ jobs: persist-credentials: false - name: 'Run analysis' - uses: ossf/scorecard-action@62b2cac7ed8198b15735ed49ab1e5cf35480ba46 # v2.4.0 + uses: ossf/scorecard-action@f49aabe0b5af0936a0987cfb85d86b75731b0186 # v2.4.1 results_file: results.sarif results_format: sarif @@ -47,7 +47,7 @@ jobs: # Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF # format to the repository Actions tab. - name: 'Upload artifact' name: SARIF file path: results.sarif @@ -55,6 +55,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: 'Upload to code-scanning' - uses: github/codeql-action/upload-sarif@9e8d0789d4a0fa9ceb6b1738f7e269594bdd67f0 # v3.28.9 + uses: github/codeql-action/upload-sarif@b56ba49b26e50535fa1e7f7db0f4f7b4bf65d80d # v3.28.10 sarif_file: results.sarif
[]
[]
{ "additions": 10, "author": "dependabot[bot]", "deletions": 10, "html_url": "https://github.com/microsoft/TypeScript/pull/61257", "issue_id": 61257, "merged_at": "2025-02-24T17:05:10Z", "omission_probability": 0.1, "pr_number": 61257, "repo": "microsoft/TypeScript", "title": "Bump the github-actions group with 4 updates", "total_changes": 20 }
77
diff --git a/src/services/stringCompletions.ts b/src/services/stringCompletions.ts index b5cf950c337ae..04c6638136ebf 100644 --- a/src/services/stringCompletions.ts +++ b/src/services/stringCompletions.ts @@ -12,6 +12,7 @@ import { addToSeen, altDirectorySeparator, arrayFrom, + BinaryExpression, CallLikeExpression, CancellationToken, CaseClause, @@ -484,7 +485,17 @@ function getStringLiteralCompletionEntries(sourceFile: SourceFile, node: StringL const existing = new Set(namedImportsOrExports.elements.map(n => moduleExportNameTextEscaped(n.propertyName || n.name))); const uniques = exports.filter(e => e.escapedName !== InternalSymbolName.Default && !existing.has(e.escapedName)); return { kind: StringLiteralCompletionKind.Properties, symbols: uniques, hasIndexSignature: false }; - + case SyntaxKind.BinaryExpression: + if ((parent as BinaryExpression).operatorToken.kind === SyntaxKind.InKeyword) { + const type = typeChecker.getTypeAtLocation((parent as BinaryExpression).right); + const properties = type.isUnion() ? typeChecker.getAllPossiblePropertiesOfTypes(type.types) : type.getApparentProperties(); + return { + kind: StringLiteralCompletionKind.Properties, + symbols: properties.filter(prop => !prop.valueDeclaration || !isPrivateIdentifierClassElementDeclaration(prop.valueDeclaration)), + hasIndexSignature: false, + }; + } + return fromContextualType(ContextFlags.None); default: return fromContextualType() || fromContextualType(ContextFlags.None); } diff --git a/tests/cases/fourslash/completionInChecks1.ts b/tests/cases/fourslash/completionInChecks1.ts new file mode 100644 index 0000000000000..b2385d967f62b --- /dev/null +++ b/tests/cases/fourslash/completionInChecks1.ts @@ -0,0 +1,42 @@ +/// <reference path='fourslash.ts' /> + +// @target: esnext + +//// declare const obj: { +//// a?: string; +//// b: number; +//// }; +//// +//// if ("/*1*/" in obj) {} +//// if (((("/*2*/"))) in obj) {} +//// if ("/*3*/" in (((obj)))) {} +//// if (((("/*4*/"))) in (((obj)))) {} +//// +//// type MyUnion = { missing: true } | { result: string }; +//// declare const u: MyUnion; +//// if ("/*5*/" in u) {} +//// +//// class Cls1 { foo = ''; #bar = 0; } +//// declare const c1: Cls1; +//// if ("/*6*/" in c1) {} +//// +//// class Cls2 { foo = ''; private bar = 0; } +//// declare const c2: Cls2; +//// if ("/*7*/" in c2) {} + +verify.completions({ + marker: ["1", "2", "3", "4"], + exact: ["a", "b"], +}); +verify.completions({ + marker: "5", + exact: ["missing", "result"], +}); +verify.completions({ + marker: "6", + exact: ["foo"], +}); +verify.completions({ + marker: "7", + exact: ["bar", "foo"], +});
diff --git a/src/services/stringCompletions.ts b/src/services/stringCompletions.ts index b5cf950c337ae..04c6638136ebf 100644 --- a/src/services/stringCompletions.ts +++ b/src/services/stringCompletions.ts @@ -12,6 +12,7 @@ import { addToSeen, altDirectorySeparator, arrayFrom, + BinaryExpression, CallLikeExpression, CancellationToken, CaseClause, @@ -484,7 +485,17 @@ function getStringLiteralCompletionEntries(sourceFile: SourceFile, node: StringL const existing = new Set(namedImportsOrExports.elements.map(n => moduleExportNameTextEscaped(n.propertyName || n.name))); const uniques = exports.filter(e => e.escapedName !== InternalSymbolName.Default && !existing.has(e.escapedName)); return { kind: StringLiteralCompletionKind.Properties, symbols: uniques, hasIndexSignature: false }; - + if ((parent as BinaryExpression).operatorToken.kind === SyntaxKind.InKeyword) { + const type = typeChecker.getTypeAtLocation((parent as BinaryExpression).right); + const properties = type.isUnion() ? typeChecker.getAllPossiblePropertiesOfTypes(type.types) : type.getApparentProperties(); + return { + kind: StringLiteralCompletionKind.Properties, + symbols: properties.filter(prop => !prop.valueDeclaration || !isPrivateIdentifierClassElementDeclaration(prop.valueDeclaration)), + hasIndexSignature: false, + }; + } + return fromContextualType(ContextFlags.None); default: return fromContextualType() || fromContextualType(ContextFlags.None); } diff --git a/tests/cases/fourslash/completionInChecks1.ts b/tests/cases/fourslash/completionInChecks1.ts new file mode 100644 index 0000000000000..b2385d967f62b --- /dev/null +++ b/tests/cases/fourslash/completionInChecks1.ts @@ -0,0 +1,42 @@ +/// <reference path='fourslash.ts' /> +// @target: esnext +//// a?: string; +//// b: number; +//// }; +//// if ("/*3*/" in (((obj)))) {} +//// if (((("/*4*/"))) in (((obj)))) {} +//// type MyUnion = { missing: true } | { result: string }; +//// declare const u: MyUnion; +//// if ("/*5*/" in u) {} +//// declare const c1: Cls1; +//// if ("/*6*/" in c1) {} +//// class Cls2 { foo = ''; private bar = 0; } +//// declare const c2: Cls2; +//// if ("/*7*/" in c2) {} + marker: ["1", "2", "3", "4"], + exact: ["a", "b"], + marker: "5", + exact: ["missing", "result"], + marker: "6", + exact: ["foo"], + exact: ["bar", "foo"],
[ "+ case SyntaxKind.BinaryExpression:", "+//// declare const obj: {", "+//// if (\"/*1*/\" in obj) {}", "+//// if ((((\"/*2*/\"))) in obj) {}", "+//// class Cls1 { foo = ''; #bar = 0; }", "+ marker: \"7\"," ]
[ 17, 41, 46, 47, 55, 76 ]
{ "additions": 54, "author": "Andarist", "deletions": 1, "html_url": "https://github.com/microsoft/TypeScript/pull/60272", "issue_id": 60272, "merged_at": "2025-02-20T22:01:52Z", "omission_probability": 0.1, "pr_number": 60272, "repo": "microsoft/TypeScript", "title": "Provide string completions for `in` keyword checks", "total_changes": 55 }
78
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index abd6fd4bf2e8d..9b0adae70bbd4 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -47165,7 +47165,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { checkCollisionsForDeclarationName(node, node.name); checkExportsOnMergedDeclarations(node); - node.members.forEach(checkEnumMember); + node.members.forEach(checkSourceElement); if (compilerOptions.erasableSyntaxOnly && !(node.flags & NodeFlags.Ambient)) { error(node, Diagnostics.This_syntax_is_not_allowed_when_erasableSyntaxOnly_is_enabled); @@ -48366,6 +48366,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return checkTypeAliasDeclaration(node as TypeAliasDeclaration); case SyntaxKind.EnumDeclaration: return checkEnumDeclaration(node as EnumDeclaration); + case SyntaxKind.EnumMember: + return checkEnumMember(node as EnumMember); case SyntaxKind.ModuleDeclaration: return checkModuleDeclaration(node as ModuleDeclaration); case SyntaxKind.ImportDeclaration: diff --git a/tests/baselines/reference/jsdocLinkTag9.symbols b/tests/baselines/reference/jsdocLinkTag9.symbols new file mode 100644 index 0000000000000..cefcebbbe11f7 --- /dev/null +++ b/tests/baselines/reference/jsdocLinkTag9.symbols @@ -0,0 +1,20 @@ +//// [tests/cases/conformance/jsdoc/jsdocLinkTag9.ts] //// + +=== /a.ts === +export interface A {} +>A : Symbol(A, Decl(a.ts, 0, 0)) + +=== /b.ts === +import type { A } from "./a"; +>A : Symbol(A, Decl(b.ts, 0, 13)) + +export enum Enum { +>Enum : Symbol(Enum, Decl(b.ts, 0, 29)) + + /** + * {@link A} + */ + EnumValue, +>EnumValue : Symbol(Enum.EnumValue, Decl(b.ts, 2, 18)) +} + diff --git a/tests/baselines/reference/jsdocLinkTag9.types b/tests/baselines/reference/jsdocLinkTag9.types new file mode 100644 index 0000000000000..0671a3ee934db --- /dev/null +++ b/tests/baselines/reference/jsdocLinkTag9.types @@ -0,0 +1,23 @@ +//// [tests/cases/conformance/jsdoc/jsdocLinkTag9.ts] //// + +=== /a.ts === + +export interface A {} + +=== /b.ts === +import type { A } from "./a"; +>A : A +> : ^ + +export enum Enum { +>Enum : Enum +> : ^^^^ + + /** + * {@link A} + */ + EnumValue, +>EnumValue : Enum.EnumValue +> : ^^^^^^^^^^^^^^ +} + diff --git a/tests/cases/conformance/jsdoc/jsdocLinkTag9.ts b/tests/cases/conformance/jsdoc/jsdocLinkTag9.ts new file mode 100644 index 0000000000000..1cc1783245421 --- /dev/null +++ b/tests/cases/conformance/jsdoc/jsdocLinkTag9.ts @@ -0,0 +1,16 @@ +// @strict: true +// @noUnusedLocals: true +// @noEmit: true + +// @filename: /a.ts +export interface A {} + +// @filename: /b.ts +import type { A } from "./a"; + +export enum Enum { + /** + * {@link A} + */ + EnumValue, +}
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index abd6fd4bf2e8d..9b0adae70bbd4 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -47165,7 +47165,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { checkCollisionsForDeclarationName(node, node.name); checkExportsOnMergedDeclarations(node); - node.members.forEach(checkEnumMember); + node.members.forEach(checkSourceElement); if (compilerOptions.erasableSyntaxOnly && !(node.flags & NodeFlags.Ambient)) { error(node, Diagnostics.This_syntax_is_not_allowed_when_erasableSyntaxOnly_is_enabled); @@ -48366,6 +48366,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return checkTypeAliasDeclaration(node as TypeAliasDeclaration); case SyntaxKind.EnumDeclaration: return checkEnumDeclaration(node as EnumDeclaration); + case SyntaxKind.EnumMember: + return checkEnumMember(node as EnumMember); case SyntaxKind.ModuleDeclaration: return checkModuleDeclaration(node as ModuleDeclaration); case SyntaxKind.ImportDeclaration: diff --git a/tests/baselines/reference/jsdocLinkTag9.symbols b/tests/baselines/reference/jsdocLinkTag9.symbols index 0000000000000..cefcebbbe11f7 +++ b/tests/baselines/reference/jsdocLinkTag9.symbols @@ -0,0 +1,20 @@ +>A : Symbol(A, Decl(a.ts, 0, 0)) +>A : Symbol(A, Decl(b.ts, 0, 13)) +>Enum : Symbol(Enum, Decl(b.ts, 0, 29)) +>EnumValue : Symbol(Enum.EnumValue, Decl(b.ts, 2, 18)) diff --git a/tests/baselines/reference/jsdocLinkTag9.types b/tests/baselines/reference/jsdocLinkTag9.types index 0000000000000..0671a3ee934db +++ b/tests/baselines/reference/jsdocLinkTag9.types @@ -0,0 +1,23 @@ +> : ^ +>Enum : Enum +> : ^^^^ +>EnumValue : Enum.EnumValue +> : ^^^^^^^^^^^^^^ diff --git a/tests/cases/conformance/jsdoc/jsdocLinkTag9.ts b/tests/cases/conformance/jsdoc/jsdocLinkTag9.ts index 0000000000000..1cc1783245421 +++ b/tests/cases/conformance/jsdoc/jsdocLinkTag9.ts @@ -0,0 +1,16 @@ +// @strict: true +// @noUnusedLocals: true +// @noEmit: true +// @filename: /a.ts +// @filename: /b.ts
[ "+>A : A" ]
[ 62 ]
{ "additions": 62, "author": "Andarist", "deletions": 1, "html_url": "https://github.com/microsoft/TypeScript/pull/61184", "issue_id": 61184, "merged_at": "2025-02-20T18:48:34Z", "omission_probability": 0.1, "pr_number": 61184, "repo": "microsoft/TypeScript", "title": "Fixed JSDoc checking on enum members", "total_changes": 63 }
79
diff --git a/src/services/codefixes/helpers.ts b/src/services/codefixes/helpers.ts index 107f954def412..ebb58bae13c09 100644 --- a/src/services/codefixes/helpers.ts +++ b/src/services/codefixes/helpers.ts @@ -621,6 +621,9 @@ function endOfRequiredTypeParameters(checker: TypeChecker, type: GenericType): n const fullTypeArguments = type.typeArguments; const target = type.target; for (let cutoff = 0; cutoff < fullTypeArguments.length; cutoff++) { + if (target.localTypeParameters?.[cutoff].constraint === undefined) { + continue; + } const typeArguments = fullTypeArguments.slice(0, cutoff); const filledIn = checker.fillMissingTypeArguments(typeArguments, target.typeParameters, cutoff, /*isJavaScriptImplicitAny*/ false); if (filledIn.every((fill, i) => fill === fullTypeArguments[i])) { diff --git a/tests/cases/fourslash/codeFixMissingTypeAnnotationOnExports57-generics-doesnt-drop-trailing-unknown.ts b/tests/cases/fourslash/codeFixMissingTypeAnnotationOnExports57-generics-doesnt-drop-trailing-unknown.ts new file mode 100644 index 0000000000000..5b3e75aa13df3 --- /dev/null +++ b/tests/cases/fourslash/codeFixMissingTypeAnnotationOnExports57-generics-doesnt-drop-trailing-unknown.ts @@ -0,0 +1,19 @@ +/// <reference path='fourslash.ts'/> + +// @isolatedDeclarations: true +// @declaration: true +// @lib: es2015 +//// +////let x: unknown; +////export const s = new Set([x]); +//// + +verify.codeFix({ + description: "Add annotation of type 'Set<unknown>'", + index: 0, + newFileContent: +` +let x: unknown; +export const s: Set<unknown> = new Set([x]); +`, +}); diff --git a/tests/cases/fourslash/codeFixMissingTypeAnnotationOnExports58-genercs-doesnt-drop-trailing-unknown-2.ts b/tests/cases/fourslash/codeFixMissingTypeAnnotationOnExports58-genercs-doesnt-drop-trailing-unknown-2.ts new file mode 100644 index 0000000000000..df71c96aad80f --- /dev/null +++ b/tests/cases/fourslash/codeFixMissingTypeAnnotationOnExports58-genercs-doesnt-drop-trailing-unknown-2.ts @@ -0,0 +1,17 @@ +/// <reference path='fourslash.ts'/> + +// @isolatedDeclarations: true +// @declaration: true +// @lib: es2015 +//// +////export const s = new Set<unknown>(); +//// + +verify.codeFix({ + description: "Add annotation of type 'Set<unknown>'", + index: 0, + newFileContent: +` +export const s: Set<unknown> = new Set<unknown>(); +`, +}); diff --git a/tests/cases/fourslash/codeFixMissingTypeAnnotationOnExports59-drops-unneeded-after-unknown.ts b/tests/cases/fourslash/codeFixMissingTypeAnnotationOnExports59-drops-unneeded-after-unknown.ts new file mode 100644 index 0000000000000..0df342ea44cd2 --- /dev/null +++ b/tests/cases/fourslash/codeFixMissingTypeAnnotationOnExports59-drops-unneeded-after-unknown.ts @@ -0,0 +1,18 @@ +/// <reference path='fourslash.ts'/> + +// @isolatedDeclarations: true +// @declaration: true +//// +////export interface Foo<S = string, T = unknown, U = number> {} +////export function g(x: Foo<number, unknown, number>) { return x; } +//// + +verify.codeFix({ + description: "Add return type 'Foo<number>'", + index: 0, + newFileContent: +` +export interface Foo<S = string, T = unknown, U = number> {} +export function g(x: Foo<number, unknown, number>): Foo<number> { return x; } +`, +}); \ No newline at end of file diff --git a/tests/cases/fourslash/codeFixMissingTypeAnnotationOnExports60-drops-unneeded-non-trailing-unknown.ts b/tests/cases/fourslash/codeFixMissingTypeAnnotationOnExports60-drops-unneeded-non-trailing-unknown.ts new file mode 100644 index 0000000000000..a44acbea25d4b --- /dev/null +++ b/tests/cases/fourslash/codeFixMissingTypeAnnotationOnExports60-drops-unneeded-non-trailing-unknown.ts @@ -0,0 +1,18 @@ +/// <reference path='fourslash.ts'/> + +// @isolatedDeclarations: true +// @declaration: true +//// +////export interface Foo<S = string, T = unknown> {} +////export function f(x: Foo<string, unknown>) { return x; } +//// + +verify.codeFix({ + description: "Add return type 'Foo'", + index: 0, + newFileContent: +` +export interface Foo<S = string, T = unknown> {} +export function f(x: Foo<string, unknown>): Foo { return x; } +`, +}); \ No newline at end of file
diff --git a/src/services/codefixes/helpers.ts b/src/services/codefixes/helpers.ts index 107f954def412..ebb58bae13c09 100644 --- a/src/services/codefixes/helpers.ts +++ b/src/services/codefixes/helpers.ts @@ -621,6 +621,9 @@ function endOfRequiredTypeParameters(checker: TypeChecker, type: GenericType): n const fullTypeArguments = type.typeArguments; const target = type.target; for (let cutoff = 0; cutoff < fullTypeArguments.length; cutoff++) { + if (target.localTypeParameters?.[cutoff].constraint === undefined) { + continue; + } const typeArguments = fullTypeArguments.slice(0, cutoff); const filledIn = checker.fillMissingTypeArguments(typeArguments, target.typeParameters, cutoff, /*isJavaScriptImplicitAny*/ false); if (filledIn.every((fill, i) => fill === fullTypeArguments[i])) { diff --git a/tests/cases/fourslash/codeFixMissingTypeAnnotationOnExports57-generics-doesnt-drop-trailing-unknown.ts b/tests/cases/fourslash/codeFixMissingTypeAnnotationOnExports57-generics-doesnt-drop-trailing-unknown.ts index 0000000000000..5b3e75aa13df3 +++ b/tests/cases/fourslash/codeFixMissingTypeAnnotationOnExports57-generics-doesnt-drop-trailing-unknown.ts @@ -0,0 +1,19 @@ +////let x: unknown; +////export const s = new Set([x]); +let x: unknown; +export const s: Set<unknown> = new Set([x]); diff --git a/tests/cases/fourslash/codeFixMissingTypeAnnotationOnExports58-genercs-doesnt-drop-trailing-unknown-2.ts b/tests/cases/fourslash/codeFixMissingTypeAnnotationOnExports58-genercs-doesnt-drop-trailing-unknown-2.ts index 0000000000000..df71c96aad80f +++ b/tests/cases/fourslash/codeFixMissingTypeAnnotationOnExports58-genercs-doesnt-drop-trailing-unknown-2.ts @@ -0,0 +1,17 @@ +////export const s = new Set<unknown>(); +export const s: Set<unknown> = new Set<unknown>(); diff --git a/tests/cases/fourslash/codeFixMissingTypeAnnotationOnExports59-drops-unneeded-after-unknown.ts b/tests/cases/fourslash/codeFixMissingTypeAnnotationOnExports59-drops-unneeded-after-unknown.ts index 0000000000000..0df342ea44cd2 +++ b/tests/cases/fourslash/codeFixMissingTypeAnnotationOnExports59-drops-unneeded-after-unknown.ts +////export interface Foo<S = string, T = unknown, U = number> {} +////export function g(x: Foo<number, unknown, number>) { return x; } + description: "Add return type 'Foo<number>'", +export interface Foo<S = string, T = unknown, U = number> {} diff --git a/tests/cases/fourslash/codeFixMissingTypeAnnotationOnExports60-drops-unneeded-non-trailing-unknown.ts b/tests/cases/fourslash/codeFixMissingTypeAnnotationOnExports60-drops-unneeded-non-trailing-unknown.ts index 0000000000000..a44acbea25d4b +++ b/tests/cases/fourslash/codeFixMissingTypeAnnotationOnExports60-drops-unneeded-non-trailing-unknown.ts +////export interface Foo<S = string, T = unknown> {} +////export function f(x: Foo<string, unknown>) { return x; } +export interface Foo<S = string, T = unknown> {} +export function f(x: Foo<string, unknown>): Foo { return x; }
[ "+export function g(x: Foo<number, unknown, number>): Foo<number> { return x; }", "+ description: \"Add return type 'Foo'\"," ]
[ 83, 103 ]
{ "additions": 75, "author": "blickly", "deletions": 0, "html_url": "https://github.com/microsoft/TypeScript/pull/61227", "issue_id": 61227, "merged_at": "2025-02-20T01:28:50Z", "omission_probability": 0.1, "pr_number": 61227, "repo": "microsoft/TypeScript", "title": "Fix quick fix for isolatedDeclarations to keep trailing unknown in generics", "total_changes": 75 }
80
diff --git a/package-lock.json b/package-lock.json index 40e69852eb561..5a0b173b47c3a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "typescript", - "version": "5.8.0", + "version": "5.9.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "typescript", - "version": "5.8.0", + "version": "5.9.0", "license": "Apache-2.0", "bin": { "tsc": "bin/tsc", diff --git a/package.json b/package.json index d89e98d368c0b..0c1578eb8f038 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "typescript", "author": "Microsoft Corp.", "homepage": "https://www.typescriptlang.org/", - "version": "5.8.0", + "version": "5.9.0", "license": "Apache-2.0", "description": "TypeScript is a language for application scale JavaScript development", "keywords": [ diff --git a/src/compiler/corePublic.ts b/src/compiler/corePublic.ts index 532d2bb55c3e7..dc4843810a8a4 100644 --- a/src/compiler/corePublic.ts +++ b/src/compiler/corePublic.ts @@ -1,6 +1,6 @@ // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configurePrerelease` too. -export const versionMajorMinor = "5.8"; +export const versionMajorMinor = "5.9"; // The following is baselined as a literal template type without intervention /** The version of the TypeScript compiler release */ export const version: string = `${versionMajorMinor}.0-dev`; diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index e7d26171cf4cd..7de0463c6150e 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -3642,7 +3642,7 @@ declare namespace ts { readDirectory(rootDir: string, extensions: readonly string[], excludes: readonly string[] | undefined, includes: readonly string[] | undefined, depth?: number): string[]; } } - const versionMajorMinor = "5.8"; + const versionMajorMinor = "5.9"; /** The version of the TypeScript compiler release */ const version: string; /**
diff --git a/package-lock.json b/package-lock.json index 40e69852eb561..5a0b173b47c3a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "typescript", - "version": "5.8.0", + "version": "5.9.0", "license": "Apache-2.0", "bin": { "tsc": "bin/tsc", diff --git a/package.json b/package.json index d89e98d368c0b..0c1578eb8f038 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "author": "Microsoft Corp.", "homepage": "https://www.typescriptlang.org/", "license": "Apache-2.0", "description": "TypeScript is a language for application scale JavaScript development", "keywords": [ diff --git a/src/compiler/corePublic.ts b/src/compiler/corePublic.ts index 532d2bb55c3e7..dc4843810a8a4 100644 --- a/src/compiler/corePublic.ts +++ b/src/compiler/corePublic.ts @@ -1,6 +1,6 @@ // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configurePrerelease` too. -export const versionMajorMinor = "5.8"; +export const versionMajorMinor = "5.9"; // The following is baselined as a literal template type without intervention /** The version of the TypeScript compiler release */ export const version: string = `${versionMajorMinor}.0-dev`; diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index e7d26171cf4cd..7de0463c6150e 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -3642,7 +3642,7 @@ declare namespace ts { readDirectory(rootDir: string, extensions: readonly string[], excludes: readonly string[] | undefined, includes: readonly string[] | undefined, depth?: number): string[]; } } - const versionMajorMinor = "5.8"; + const versionMajorMinor = "5.9"; /** The version of the TypeScript compiler release */ const version: string; /**
[]
[]
{ "additions": 5, "author": "DanielRosenwasser", "deletions": 5, "html_url": "https://github.com/microsoft/TypeScript/pull/61218", "issue_id": 61218, "merged_at": "2025-02-18T19:16:22Z", "omission_probability": 0.1, "pr_number": 61218, "repo": "microsoft/TypeScript", "title": "Bump version to 5.9", "total_changes": 10 }
81
diff --git a/src/compiler/path.ts b/src/compiler/path.ts index b05216adc47b5..a06359d51e549 100644 --- a/src/compiler/path.ts +++ b/src/compiler/path.ts @@ -624,28 +624,128 @@ export function getNormalizedPathComponents(path: string, currentDirectory: stri } /** @internal */ -export function getNormalizedAbsolutePath(fileName: string, currentDirectory: string | undefined): string { - return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); +export function getNormalizedAbsolutePath(path: string, currentDirectory: string | undefined): string { + let rootLength = getRootLength(path); + if (rootLength === 0 && currentDirectory) { + path = combinePaths(currentDirectory, path); + rootLength = getRootLength(path); + } + else { + // combinePaths normalizes slashes, so not necessary in the other branch + path = normalizeSlashes(path); + } + + const simpleNormalized = simpleNormalizePath(path); + if (simpleNormalized !== undefined) { + return simpleNormalized.length > rootLength ? removeTrailingDirectorySeparator(simpleNormalized) : simpleNormalized; + } + + const length = path.length; + const root = path.substring(0, rootLength); + // `normalized` is only initialized once `path` is determined to be non-normalized + let normalized; + let index = rootLength; + let segmentStart = index; + let normalizedUpTo = index; + let seenNonDotDotSegment = rootLength !== 0; + while (index < length) { + // At beginning of segment + segmentStart = index; + let ch = path.charCodeAt(index); + while (ch === CharacterCodes.slash && index + 1 < length) { + index++; + ch = path.charCodeAt(index); + } + if (index > segmentStart) { + // Seen superfluous separator + normalized ??= path.substring(0, segmentStart - 1); + segmentStart = index; + } + // Past any superfluous separators + let segmentEnd = path.indexOf(directorySeparator, index + 1); + if (segmentEnd === -1) { + segmentEnd = length; + } + const segmentLength = segmentEnd - segmentStart; + if (segmentLength === 1 && path.charCodeAt(index) === CharacterCodes.dot) { + // "." segment (skip) + normalized ??= path.substring(0, normalizedUpTo); + } + else if (segmentLength === 2 && path.charCodeAt(index) === CharacterCodes.dot && path.charCodeAt(index + 1) === CharacterCodes.dot) { + // ".." segment + if (!seenNonDotDotSegment) { + if (normalized !== undefined) { + normalized += normalized.length === rootLength ? ".." : "/.."; + } + else { + normalizedUpTo = index + 2; + } + } + else if (normalized === undefined) { + if (normalizedUpTo - 2 >= 0) { + normalized = path.substring(0, Math.max(rootLength, path.lastIndexOf(directorySeparator, normalizedUpTo - 2))); + } + else { + normalized = path.substring(0, normalizedUpTo); + } + } + else { + const lastSlash = normalized.lastIndexOf(directorySeparator); + if (lastSlash !== -1) { + normalized = normalized.substring(0, Math.max(rootLength, lastSlash)); + } + else { + normalized = root; + } + if (normalized.length === rootLength) { + seenNonDotDotSegment = rootLength !== 0; + } + } + } + else if (normalized !== undefined) { + if (normalized.length !== rootLength) { + normalized += directorySeparator; + } + seenNonDotDotSegment = true; + normalized += path.substring(segmentStart, segmentEnd); + } + else { + seenNonDotDotSegment = true; + normalizedUpTo = segmentEnd; + } + index = segmentEnd + 1; + } + return normalized ?? (length > rootLength ? removeTrailingDirectorySeparator(path) : path); } /** @internal */ export function normalizePath(path: string): string { path = normalizeSlashes(path); + let normalized = simpleNormalizePath(path); + if (normalized !== undefined) { + return normalized; + } + normalized = getNormalizedAbsolutePath(path, ""); + return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized; +} + +function simpleNormalizePath(path: string): string | undefined { // Most paths don't require normalization if (!relativePathSegmentRegExp.test(path)) { return path; } // Some paths only require cleanup of `/./` or leading `./` - const simplified = path.replace(/\/\.\//g, "/").replace(/^\.\//, ""); + let simplified = path.replace(/\/\.\//g, "/"); + if (simplified.startsWith("./")) { + simplified = simplified.slice(2); + } if (simplified !== path) { path = simplified; if (!relativePathSegmentRegExp.test(path)) { return path; } } - // Other paths require full normalization - const normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path))); - return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized; + return undefined; } function getPathWithoutRoot(pathComponents: readonly string[]) { diff --git a/src/testRunner/unittests/paths.ts b/src/testRunner/unittests/paths.ts index e76bdc7cd26de..743e791baa181 100644 --- a/src/testRunner/unittests/paths.ts +++ b/src/testRunner/unittests/paths.ts @@ -317,9 +317,24 @@ describe("unittests:: core paths", () => { assert.strictEqual(ts.getNormalizedAbsolutePath("", ""), ""); assert.strictEqual(ts.getNormalizedAbsolutePath(".", ""), ""); assert.strictEqual(ts.getNormalizedAbsolutePath("./", ""), ""); + assert.strictEqual(ts.getNormalizedAbsolutePath("./a", ""), "a"); // Strangely, these do not normalize to the empty string. assert.strictEqual(ts.getNormalizedAbsolutePath("..", ""), ".."); assert.strictEqual(ts.getNormalizedAbsolutePath("../", ""), ".."); + assert.strictEqual(ts.getNormalizedAbsolutePath("../..", ""), "../.."); + assert.strictEqual(ts.getNormalizedAbsolutePath("../../", ""), "../.."); + assert.strictEqual(ts.getNormalizedAbsolutePath("./..", ""), ".."); + assert.strictEqual(ts.getNormalizedAbsolutePath("../../a/..", ""), "../.."); + + // More .. segments + assert.strictEqual(ts.getNormalizedAbsolutePath("src/ts/foo/../../../bar/bar.ts", ""), "bar/bar.ts"); + assert.strictEqual(ts.getNormalizedAbsolutePath("src/ts/foo/../../..", ""), ""); + // not a real URL root! + assert.strictEqual(ts.getNormalizedAbsolutePath("file:/Users/matb/projects/san/../../../../../../typings/@epic/Core.d.ts", ""), "../typings/@epic/Core.d.ts"); + // the root is `file://Users/` + assert.strictEqual(ts.getNormalizedAbsolutePath("file://Users/matb/projects/san/../../../../../../typings/@epic/Core.d.ts", ""), "file://Users/typings/@epic/Core.d.ts"); + // this is real + assert.strictEqual(ts.getNormalizedAbsolutePath("file:///Users/matb/projects/san/../../../../../../typings/@epic/Core.d.ts", ""), "file:///typings/@epic/Core.d.ts"); // Interaction between relative paths and currentDirectory. assert.strictEqual(ts.getNormalizedAbsolutePath("", "/home"), "/home");
diff --git a/src/compiler/path.ts b/src/compiler/path.ts index b05216adc47b5..a06359d51e549 100644 --- a/src/compiler/path.ts +++ b/src/compiler/path.ts @@ -624,28 +624,128 @@ export function getNormalizedPathComponents(path: string, currentDirectory: stri -export function getNormalizedAbsolutePath(fileName: string, currentDirectory: string | undefined): string { - return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); +export function getNormalizedAbsolutePath(path: string, currentDirectory: string | undefined): string { + let rootLength = getRootLength(path); + if (rootLength === 0 && currentDirectory) { + path = combinePaths(currentDirectory, path); + rootLength = getRootLength(path); + else { + // combinePaths normalizes slashes, so not necessary in the other branch + path = normalizeSlashes(path); + const simpleNormalized = simpleNormalizePath(path); + if (simpleNormalized !== undefined) { + return simpleNormalized.length > rootLength ? removeTrailingDirectorySeparator(simpleNormalized) : simpleNormalized; + const length = path.length; + const root = path.substring(0, rootLength); + // `normalized` is only initialized once `path` is determined to be non-normalized + let normalized; + let index = rootLength; + let segmentStart = index; + let normalizedUpTo = index; + let seenNonDotDotSegment = rootLength !== 0; + while (index < length) { + // At beginning of segment + segmentStart = index; + let ch = path.charCodeAt(index); + while (ch === CharacterCodes.slash && index + 1 < length) { + index++; + ch = path.charCodeAt(index); + if (index > segmentStart) { + // Seen superfluous separator + normalized ??= path.substring(0, segmentStart - 1); + segmentStart = index; + // Past any superfluous separators + let segmentEnd = path.indexOf(directorySeparator, index + 1); + if (segmentEnd === -1) { + segmentEnd = length; + const segmentLength = segmentEnd - segmentStart; + if (segmentLength === 1 && path.charCodeAt(index) === CharacterCodes.dot) { + // "." segment (skip) + normalized ??= path.substring(0, normalizedUpTo); + else if (segmentLength === 2 && path.charCodeAt(index) === CharacterCodes.dot && path.charCodeAt(index + 1) === CharacterCodes.dot) { + // ".." segment + if (!seenNonDotDotSegment) { + if (normalized !== undefined) { + normalized += normalized.length === rootLength ? ".." : "/.."; + normalizedUpTo = index + 2; + else if (normalized === undefined) { + if (normalizedUpTo - 2 >= 0) { + normalized = path.substring(0, Math.max(rootLength, path.lastIndexOf(directorySeparator, normalizedUpTo - 2))); + normalized = path.substring(0, normalizedUpTo); + else { + const lastSlash = normalized.lastIndexOf(directorySeparator); + if (lastSlash !== -1) { + normalized = normalized.substring(0, Math.max(rootLength, lastSlash)); + normalized = root; + if (normalized.length === rootLength) { + else if (normalized !== undefined) { + if (normalized.length !== rootLength) { + normalized += directorySeparator; + normalized += path.substring(segmentStart, segmentEnd); + else { + normalizedUpTo = segmentEnd; + index = segmentEnd + 1; + return normalized ?? (length > rootLength ? removeTrailingDirectorySeparator(path) : path); export function normalizePath(path: string): string { path = normalizeSlashes(path); + let normalized = simpleNormalizePath(path); + if (normalized !== undefined) { + return normalized; + normalized = getNormalizedAbsolutePath(path, ""); + return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized; +} +function simpleNormalizePath(path: string): string | undefined { // Most paths don't require normalization if (!relativePathSegmentRegExp.test(path)) { return path; // Some paths only require cleanup of `/./` or leading `./` - const simplified = path.replace(/\/\.\//g, "/").replace(/^\.\//, ""); + let simplified = path.replace(/\/\.\//g, "/"); + if (simplified.startsWith("./")) { + simplified = simplified.slice(2); if (simplified !== path) { path = simplified; if (!relativePathSegmentRegExp.test(path)) { return path; } - // Other paths require full normalization - const normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path))); - return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized; + return undefined; function getPathWithoutRoot(pathComponents: readonly string[]) { diff --git a/src/testRunner/unittests/paths.ts b/src/testRunner/unittests/paths.ts index e76bdc7cd26de..743e791baa181 100644 --- a/src/testRunner/unittests/paths.ts +++ b/src/testRunner/unittests/paths.ts @@ -317,9 +317,24 @@ describe("unittests:: core paths", () => { assert.strictEqual(ts.getNormalizedAbsolutePath("", ""), ""); assert.strictEqual(ts.getNormalizedAbsolutePath(".", ""), ""); assert.strictEqual(ts.getNormalizedAbsolutePath("./", ""), ""); + assert.strictEqual(ts.getNormalizedAbsolutePath("./a", ""), "a"); // Strangely, these do not normalize to the empty string. assert.strictEqual(ts.getNormalizedAbsolutePath("..", ""), ".."); assert.strictEqual(ts.getNormalizedAbsolutePath("../", ""), ".."); + assert.strictEqual(ts.getNormalizedAbsolutePath("../..", ""), "../.."); + assert.strictEqual(ts.getNormalizedAbsolutePath("../../", ""), "../.."); + assert.strictEqual(ts.getNormalizedAbsolutePath("./..", ""), ".."); + assert.strictEqual(ts.getNormalizedAbsolutePath("../../a/..", ""), "../.."); + // More .. segments + assert.strictEqual(ts.getNormalizedAbsolutePath("src/ts/foo/../../../bar/bar.ts", ""), "bar/bar.ts"); + assert.strictEqual(ts.getNormalizedAbsolutePath("src/ts/foo/../../..", ""), ""); + // not a real URL root! + assert.strictEqual(ts.getNormalizedAbsolutePath("file:/Users/matb/projects/san/../../../../../../typings/@epic/Core.d.ts", ""), "../typings/@epic/Core.d.ts"); + // the root is `file://Users/` + assert.strictEqual(ts.getNormalizedAbsolutePath("file://Users/matb/projects/san/../../../../../../typings/@epic/Core.d.ts", ""), "file://Users/typings/@epic/Core.d.ts"); + // this is real + assert.strictEqual(ts.getNormalizedAbsolutePath("file:///Users/matb/projects/san/../../../../../../typings/@epic/Core.d.ts", ""), "file:///typings/@epic/Core.d.ts"); // Interaction between relative paths and currentDirectory. assert.strictEqual(ts.getNormalizedAbsolutePath("", "/home"), "/home");
[ "+ seenNonDotDotSegment = rootLength !== 0;" ]
[ 84 ]
{ "additions": 121, "author": "andrewbranch", "deletions": 6, "html_url": "https://github.com/microsoft/TypeScript/pull/60812", "issue_id": 60812, "merged_at": "2025-01-09T19:36:08Z", "omission_probability": 0.1, "pr_number": 60812, "repo": "microsoft/TypeScript", "title": "Write path normalization without array allocations", "total_changes": 127 }
82
diff --git a/src/compiler/transformers/module/esnextAnd2015.ts b/src/compiler/transformers/module/esnextAnd2015.ts index 2f2d23c468089..40662f302269c 100644 --- a/src/compiler/transformers/module/esnextAnd2015.ts +++ b/src/compiler/transformers/module/esnextAnd2015.ts @@ -158,7 +158,7 @@ export function transformECMAScriptModule(context: TransformationContext): (x: S if (node === importsAndRequiresToRewriteOrShim?.[0]) { return visitImportOrRequireCall(importsAndRequiresToRewriteOrShim.shift()!); } - break; + // fallthrough default: if (importsAndRequiresToRewriteOrShim?.length && rangeContainsRange(node, importsAndRequiresToRewriteOrShim[0])) { return visitEachChild(node, visitor, context); diff --git a/tests/baselines/reference/emit(jsx=preserve).errors.txt b/tests/baselines/reference/emit(jsx=preserve).errors.txt index cda66163154d1..894ae70f4392d 100644 --- a/tests/baselines/reference/emit(jsx=preserve).errors.txt +++ b/tests/baselines/reference/emit(jsx=preserve).errors.txt @@ -6,6 +6,8 @@ main.ts(6,22): error TS2307: Cannot find module './foo.ts' or its corresponding main.ts(8,15): error TS2307: Cannot find module './foo.ts' or its corresponding type declarations. main.ts(10,8): error TS2307: Cannot find module './foo.ts' or its corresponding type declarations. main.ts(11,8): error TS2307: Cannot find module './foo.ts' or its corresponding type declarations. +main.ts(13,18): error TS2307: Cannot find module './foo.ts' or its corresponding type declarations. +main.ts(14,8): error TS2307: Cannot find module './foo.ts' or its corresponding type declarations. no.ts(1,16): error TS2307: Cannot find module './foo.ts/foo.js' or its corresponding type declarations. no.ts(2,16): error TS2307: Cannot find module 'foo.ts' or its corresponding type declarations. no.ts(3,16): error TS2307: Cannot find module 'pkg/foo.ts' or its corresponding type declarations. @@ -21,7 +23,7 @@ no.ts(11,8): error TS2307: Cannot find module 'node:path' or its corresponding t ==== globals.d.ts (0 errors) ==== declare function require(module: string): any; -==== main.ts (8 errors) ==== +==== main.ts (10 errors) ==== // Rewrite import {} from "./foo.ts"; ~~~~~~~~~~ @@ -45,6 +47,13 @@ no.ts(11,8): error TS2307: Cannot find module 'node:path' or its corresponding t //Shim import("./foo.ts"); ~~~~~~~~~~ +!!! error TS2307: Cannot find module './foo.ts' or its corresponding type declarations. + import("./foo.ts").then(() => {}); + ~~~~~~~~~~ +!!! error TS2307: Cannot find module './foo.ts' or its corresponding type declarations. + function acceptAny(arg: any) {} + acceptAny(import("./foo.ts")); + ~~~~~~~~~~ !!! error TS2307: Cannot find module './foo.ts' or its corresponding type declarations. import("./foo.ts", { with: { attr: "value" } }); ~~~~~~~~~~ diff --git a/tests/baselines/reference/emit(jsx=preserve).js b/tests/baselines/reference/emit(jsx=preserve).js index 101590ab644b9..46da467f6ac0b 100644 --- a/tests/baselines/reference/emit(jsx=preserve).js +++ b/tests/baselines/reference/emit(jsx=preserve).js @@ -14,6 +14,9 @@ import "./foo.ts"; export * from "./foo.ts"; //Shim import("./foo.ts"); +import("./foo.ts").then(() => {}); +function acceptAny(arg: any) {} +acceptAny(import("./foo.ts")); import("./foo.ts", { with: { attr: "value" } }); import("" + "./foo.ts"); //// [js.js] @@ -71,6 +74,9 @@ import "./foo.js"; export * from "./foo.js"; //Shim import("./foo.js"); +import("./foo.js").then(() => { }); +function acceptAny(arg) { } +acceptAny(import("./foo.js")); import("./foo.js", { with: { attr: "value" } }); import(__rewriteRelativeImportExtension("" + "./foo.ts", true)); //// [js.js] diff --git a/tests/baselines/reference/emit(jsx=react).errors.txt b/tests/baselines/reference/emit(jsx=react).errors.txt index cda66163154d1..894ae70f4392d 100644 --- a/tests/baselines/reference/emit(jsx=react).errors.txt +++ b/tests/baselines/reference/emit(jsx=react).errors.txt @@ -6,6 +6,8 @@ main.ts(6,22): error TS2307: Cannot find module './foo.ts' or its corresponding main.ts(8,15): error TS2307: Cannot find module './foo.ts' or its corresponding type declarations. main.ts(10,8): error TS2307: Cannot find module './foo.ts' or its corresponding type declarations. main.ts(11,8): error TS2307: Cannot find module './foo.ts' or its corresponding type declarations. +main.ts(13,18): error TS2307: Cannot find module './foo.ts' or its corresponding type declarations. +main.ts(14,8): error TS2307: Cannot find module './foo.ts' or its corresponding type declarations. no.ts(1,16): error TS2307: Cannot find module './foo.ts/foo.js' or its corresponding type declarations. no.ts(2,16): error TS2307: Cannot find module 'foo.ts' or its corresponding type declarations. no.ts(3,16): error TS2307: Cannot find module 'pkg/foo.ts' or its corresponding type declarations. @@ -21,7 +23,7 @@ no.ts(11,8): error TS2307: Cannot find module 'node:path' or its corresponding t ==== globals.d.ts (0 errors) ==== declare function require(module: string): any; -==== main.ts (8 errors) ==== +==== main.ts (10 errors) ==== // Rewrite import {} from "./foo.ts"; ~~~~~~~~~~ @@ -45,6 +47,13 @@ no.ts(11,8): error TS2307: Cannot find module 'node:path' or its corresponding t //Shim import("./foo.ts"); ~~~~~~~~~~ +!!! error TS2307: Cannot find module './foo.ts' or its corresponding type declarations. + import("./foo.ts").then(() => {}); + ~~~~~~~~~~ +!!! error TS2307: Cannot find module './foo.ts' or its corresponding type declarations. + function acceptAny(arg: any) {} + acceptAny(import("./foo.ts")); + ~~~~~~~~~~ !!! error TS2307: Cannot find module './foo.ts' or its corresponding type declarations. import("./foo.ts", { with: { attr: "value" } }); ~~~~~~~~~~ diff --git a/tests/baselines/reference/emit(jsx=react).js b/tests/baselines/reference/emit(jsx=react).js index e25e6fd2f058d..a3074c3e2fb8e 100644 --- a/tests/baselines/reference/emit(jsx=react).js +++ b/tests/baselines/reference/emit(jsx=react).js @@ -14,6 +14,9 @@ import "./foo.ts"; export * from "./foo.ts"; //Shim import("./foo.ts"); +import("./foo.ts").then(() => {}); +function acceptAny(arg: any) {} +acceptAny(import("./foo.ts")); import("./foo.ts", { with: { attr: "value" } }); import("" + "./foo.ts"); //// [js.js] @@ -71,6 +74,9 @@ import "./foo.js"; export * from "./foo.js"; //Shim import("./foo.js"); +import("./foo.js").then(() => { }); +function acceptAny(arg) { } +acceptAny(import("./foo.js")); import("./foo.js", { with: { attr: "value" } }); import(__rewriteRelativeImportExtension("" + "./foo.ts")); //// [js.js] diff --git a/tests/cases/conformance/externalModules/rewriteRelativeImportExtensions/emit.ts b/tests/cases/conformance/externalModules/rewriteRelativeImportExtensions/emit.ts index 57af4ea118719..4636edf650d36 100644 --- a/tests/cases/conformance/externalModules/rewriteRelativeImportExtensions/emit.ts +++ b/tests/cases/conformance/externalModules/rewriteRelativeImportExtensions/emit.ts @@ -21,6 +21,9 @@ import "./foo.ts"; export * from "./foo.ts"; //Shim import("./foo.ts"); +import("./foo.ts").then(() => {}); +function acceptAny(arg: any) {} +acceptAny(import("./foo.ts")); import("./foo.ts", { with: { attr: "value" } }); import("" + "./foo.ts"); // @Filename: js.js
diff --git a/src/compiler/transformers/module/esnextAnd2015.ts b/src/compiler/transformers/module/esnextAnd2015.ts index 2f2d23c468089..40662f302269c 100644 --- a/src/compiler/transformers/module/esnextAnd2015.ts +++ b/src/compiler/transformers/module/esnextAnd2015.ts @@ -158,7 +158,7 @@ export function transformECMAScriptModule(context: TransformationContext): (x: S if (node === importsAndRequiresToRewriteOrShim?.[0]) { return visitImportOrRequireCall(importsAndRequiresToRewriteOrShim.shift()!); } - break; + // fallthrough default: if (importsAndRequiresToRewriteOrShim?.length && rangeContainsRange(node, importsAndRequiresToRewriteOrShim[0])) { return visitEachChild(node, visitor, context); diff --git a/tests/baselines/reference/emit(jsx=preserve).errors.txt b/tests/baselines/reference/emit(jsx=preserve).errors.txt --- a/tests/baselines/reference/emit(jsx=preserve).errors.txt +++ b/tests/baselines/reference/emit(jsx=preserve).errors.txt diff --git a/tests/baselines/reference/emit(jsx=preserve).js b/tests/baselines/reference/emit(jsx=preserve).js index 101590ab644b9..46da467f6ac0b 100644 --- a/tests/baselines/reference/emit(jsx=preserve).js +++ b/tests/baselines/reference/emit(jsx=preserve).js import(__rewriteRelativeImportExtension("" + "./foo.ts", true)); diff --git a/tests/baselines/reference/emit(jsx=react).errors.txt b/tests/baselines/reference/emit(jsx=react).errors.txt --- a/tests/baselines/reference/emit(jsx=react).errors.txt +++ b/tests/baselines/reference/emit(jsx=react).errors.txt diff --git a/tests/baselines/reference/emit(jsx=react).js b/tests/baselines/reference/emit(jsx=react).js index e25e6fd2f058d..a3074c3e2fb8e 100644 --- a/tests/baselines/reference/emit(jsx=react).js +++ b/tests/baselines/reference/emit(jsx=react).js import(__rewriteRelativeImportExtension("" + "./foo.ts")); diff --git a/tests/cases/conformance/externalModules/rewriteRelativeImportExtensions/emit.ts b/tests/cases/conformance/externalModules/rewriteRelativeImportExtensions/emit.ts index 57af4ea118719..4636edf650d36 100644 --- a/tests/cases/conformance/externalModules/rewriteRelativeImportExtensions/emit.ts +++ b/tests/cases/conformance/externalModules/rewriteRelativeImportExtensions/emit.ts @@ -21,6 +21,9 @@ import "./foo.ts"; // @Filename: js.js
[]
[]
{ "additions": 36, "author": "Andarist", "deletions": 3, "html_url": "https://github.com/microsoft/TypeScript/pull/61154", "issue_id": 61154, "merged_at": "2025-02-10T23:02:37Z", "omission_probability": 0.1, "pr_number": 61154, "repo": "microsoft/TypeScript", "title": "Fixed `rewriteRelativeImportExtensions` for `import()` within call expressions", "total_changes": 39 }
83
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 7a4370b2b52fc..29229cf34fbd3 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -49216,11 +49216,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } else if (isEntityName(name) && isTypeReferenceIdentifier(name)) { const meaning = name.parent.kind === SyntaxKind.TypeReference ? SymbolFlags.Type : SymbolFlags.Namespace; - const symbol = resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + const symbol = resolveEntityName(name, meaning, /*ignoreErrors*/ true, /*dontResolveAlias*/ true); return symbol && symbol !== unknownSymbol ? symbol : getUnresolvedSymbolForEntityName(name); } if (name.parent.kind === SyntaxKind.TypePredicate) { - return resolveEntityName(name as Identifier, /*meaning*/ SymbolFlags.FunctionScopedVariable); + return resolveEntityName(name as Identifier, /*meaning*/ SymbolFlags.FunctionScopedVariable, /*ignoreErrors*/ true); } return undefined; } @@ -49451,7 +49451,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getShorthandAssignmentValueSymbol(location: Node | undefined): Symbol | undefined { if (location && location.kind === SyntaxKind.ShorthandPropertyAssignment) { - return resolveEntityName((location as ShorthandPropertyAssignment).name, SymbolFlags.Value | SymbolFlags.Alias); + return resolveEntityName((location as ShorthandPropertyAssignment).name, SymbolFlags.Value | SymbolFlags.Alias, /*ignoreErrors*/ true); } return undefined; } @@ -49463,10 +49463,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : name.kind === SyntaxKind.StringLiteral ? undefined : // Skip for invalid syntax like this: export { "x" } - resolveEntityName(name, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias); + resolveEntityName(name, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias, /*ignoreErrors*/ true); } else { - return resolveEntityName(node, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias); + return resolveEntityName(node, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias, /*ignoreErrors*/ true); } }
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 7a4370b2b52fc..29229cf34fbd3 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -49216,11 +49216,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { else if (isEntityName(name) && isTypeReferenceIdentifier(name)) { const meaning = name.parent.kind === SyntaxKind.TypeReference ? SymbolFlags.Type : SymbolFlags.Namespace; - const symbol = resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true); + const symbol = resolveEntityName(name, meaning, /*ignoreErrors*/ true, /*dontResolveAlias*/ true); return symbol && symbol !== unknownSymbol ? symbol : getUnresolvedSymbolForEntityName(name); if (name.parent.kind === SyntaxKind.TypePredicate) { - return resolveEntityName(name as Identifier, /*meaning*/ SymbolFlags.FunctionScopedVariable); + return resolveEntityName(name as Identifier, /*meaning*/ SymbolFlags.FunctionScopedVariable, /*ignoreErrors*/ true); @@ -49451,7 +49451,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { function getShorthandAssignmentValueSymbol(location: Node | undefined): Symbol | undefined { if (location && location.kind === SyntaxKind.ShorthandPropertyAssignment) { - return resolveEntityName((location as ShorthandPropertyAssignment).name, SymbolFlags.Value | SymbolFlags.Alias); + return resolveEntityName((location as ShorthandPropertyAssignment).name, SymbolFlags.Value | SymbolFlags.Alias, /*ignoreErrors*/ true); @@ -49463,10 +49463,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : name.kind === SyntaxKind.StringLiteral ? undefined : // Skip for invalid syntax like this: export { "x" } - resolveEntityName(name, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias); + resolveEntityName(name, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias, /*ignoreErrors*/ true); else { - return resolveEntityName(node, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias); + return resolveEntityName(node, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias, /*ignoreErrors*/ true);
[]
[]
{ "additions": 5, "author": "jakebailey", "deletions": 5, "html_url": "https://github.com/microsoft/TypeScript/pull/61144", "issue_id": 61144, "merged_at": "2025-02-10T17:26:52Z", "omission_probability": 0.1, "pr_number": 61144, "repo": "microsoft/TypeScript", "title": "Pass ignoreErrors=true to more resolveEntityName callers", "total_changes": 10 }
84
diff --git a/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl index aea89613258c3..720fea33b86ba 100644 --- a/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -8265,11 +8265,11 @@ </Str> <Disp Icon="Str" /> </Item> - <Item ItemId=";Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_asserts_2880" ItemType="0" PsrId="306" Leaf="true"> + <Item ItemId=";Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_assert_2880" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> - <Val><![CDATA[Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'.]]></Val> + <Val><![CDATA[Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'.]]></Val> <Tgt Cat="Text" Stat="Loc" Orig="New"> - <Val><![CDATA[导入断言已被导入属性替换。使用 “with” 而不是 “asserts”。]]></Val> + <Val><![CDATA[导入断言已被导入属性替换。使用 “with” 而不是 “assert”。]]></Val> </Tgt> </Str> <Disp Icon="Str" /> diff --git a/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl index 36940ed013ab5..8630475bb08ea 100644 --- a/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -8265,11 +8265,11 @@ </Str> <Disp Icon="Str" /> </Item> - <Item ItemId=";Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_asserts_2880" ItemType="0" PsrId="306" Leaf="true"> + <Item ItemId=";Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_assert_2880" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> - <Val><![CDATA[Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'.]]></Val> + <Val><![CDATA[Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'.]]></Val> <Tgt Cat="Text" Stat="Loc" Orig="New"> - <Val><![CDATA[匯入宣告已由匯入屬性取代。使用 『with』 而非 'asserts'。]]></Val> + <Val><![CDATA[匯入宣告已由匯入屬性取代。使用 『with』 而非 'assert'。]]></Val> </Tgt> </Str> <Disp Icon="Str" /> diff --git a/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl index 668cb9e96fd07..9c856436898e4 100644 --- a/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -8274,11 +8274,11 @@ </Str> <Disp Icon="Str" /> </Item> - <Item ItemId=";Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_asserts_2880" ItemType="0" PsrId="306" Leaf="true"> + <Item ItemId=";Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_assert_2880" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> - <Val><![CDATA[Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'.]]></Val> + <Val><![CDATA[Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'.]]></Val> <Tgt Cat="Text" Stat="Loc" Orig="New"> - <Val><![CDATA[Kontrolní výrazy importu byly nahrazeny atributy importu. Místo asserts použijte with.]]></Val> + <Val><![CDATA[Kontrolní výrazy importu byly nahrazeny atributy importu. Místo assert použijte with.]]></Val> </Tgt> </Str> <Disp Icon="Str" /> diff --git a/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl index 17937acbc647d..e726c146c15eb 100644 --- a/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -8262,11 +8262,11 @@ </Str> <Disp Icon="Str" /> </Item> - <Item ItemId=";Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_asserts_2880" ItemType="0" PsrId="306" Leaf="true"> + <Item ItemId=";Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_assert_2880" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> - <Val><![CDATA[Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'.]]></Val> + <Val><![CDATA[Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'.]]></Val> <Tgt Cat="Text" Stat="Loc" Orig="New"> - <Val><![CDATA[Importassertionen wurden durch Importattribute ersetzt. Verwenden Sie "with" anstelle von "asserts".]]></Val> + <Val><![CDATA[Importassertionen wurden durch Importattribute ersetzt. Verwenden Sie "with" anstelle von "assert".]]></Val> </Tgt> </Str> <Disp Icon="Str" /> diff --git a/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl index d665b1834734a..e26e96401f42b 100644 --- a/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -8277,11 +8277,11 @@ </Str> <Disp Icon="Str" /> </Item> - <Item ItemId=";Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_asserts_2880" ItemType="0" PsrId="306" Leaf="true"> + <Item ItemId=";Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_assert_2880" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> - <Val><![CDATA[Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'.]]></Val> + <Val><![CDATA[Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'.]]></Val> <Tgt Cat="Text" Stat="Loc" Orig="New"> - <Val><![CDATA[Las aserciones de importación se han reemplazado por atributos de importación. Use 'with' en lugar de 'asserts'.]]></Val> + <Val><![CDATA[Las aserciones de importación se han reemplazado por atributos de importación. Use 'with' en lugar de 'assert'.]]></Val> </Tgt> </Str> <Disp Icon="Str" /> diff --git a/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl index 9e19de20e65fb..b5a69e413a2dc 100644 --- a/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -8277,11 +8277,11 @@ </Str> <Disp Icon="Str" /> </Item> - <Item ItemId=";Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_asserts_2880" ItemType="0" PsrId="306" Leaf="true"> + <Item ItemId=";Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_assert_2880" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> - <Val><![CDATA[Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'.]]></Val> + <Val><![CDATA[Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'.]]></Val> <Tgt Cat="Text" Stat="Loc" Orig="New"> - <Val><![CDATA[Les assertions d’importation ont été remplacées par des attributs d’importation. Utilisez 'with' à la place de 'asserts'.]]></Val> + <Val><![CDATA[Les assertions d’importation ont été remplacées par des attributs d’importation. Utilisez 'with' à la place de 'assert'.]]></Val> </Tgt> </Str> <Disp Icon="Str" /> diff --git a/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl index 1b475c1f4c493..e2a3a5137dcb9 100644 --- a/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -8265,11 +8265,11 @@ </Str> <Disp Icon="Str" /> </Item> - <Item ItemId=";Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_asserts_2880" ItemType="0" PsrId="306" Leaf="true"> + <Item ItemId=";Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_assert_2880" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> - <Val><![CDATA[Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'.]]></Val> + <Val><![CDATA[Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'.]]></Val> <Tgt Cat="Text" Stat="Loc" Orig="New"> - <Val><![CDATA[Le asserzioni di importazione sono state sostituite dagli attributi di importazione. Usare 'with' invece di 'asserts'.]]></Val> + <Val><![CDATA[Le asserzioni di importazione sono state sostituite dagli attributi di importazione. Usare 'with' invece di 'assert'.]]></Val> </Tgt> </Str> <Disp Icon="Str" /> diff --git a/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl index e9f181074855c..7d6a048b62785 100644 --- a/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -8265,11 +8265,11 @@ </Str> <Disp Icon="Str" /> </Item> - <Item ItemId=";Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_asserts_2880" ItemType="0" PsrId="306" Leaf="true"> + <Item ItemId=";Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_assert_2880" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> - <Val><![CDATA[Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'.]]></Val> + <Val><![CDATA[Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'.]]></Val> <Tgt Cat="Text" Stat="Loc" Orig="New"> - <Val><![CDATA[インポート アサーションはインポート属性に置き換えられました。'asserts' ではなく 'with' を使用してください。]]></Val> + <Val><![CDATA[インポート アサーションはインポート属性に置き換えられました。'assert' ではなく 'with' を使用してください。]]></Val> </Tgt> </Str> <Disp Icon="Str" /> diff --git a/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl index d9a2d6448a1a5..ead631be12465 100644 --- a/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -8265,11 +8265,11 @@ </Str> <Disp Icon="Str" /> </Item> - <Item ItemId=";Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_asserts_2880" ItemType="0" PsrId="306" Leaf="true"> + <Item ItemId=";Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_assert_2880" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> - <Val><![CDATA[Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'.]]></Val> + <Val><![CDATA[Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'.]]></Val> <Tgt Cat="Text" Stat="Loc" Orig="New"> - <Val><![CDATA[가져오기 어설션이 가져오기 특성으로 바뀌었습니다. 'asserts' 대신 'with'를 사용합니다.]]></Val> + <Val><![CDATA[가져오기 어설션이 가져오기 특성으로 바뀌었습니다. 'assert' 대신 'with'를 사용합니다.]]></Val> </Tgt> </Str> <Disp Icon="Str" /> diff --git a/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl index bd985b397518e..bdff8b5d661cd 100644 --- a/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -8255,11 +8255,11 @@ </Str> <Disp Icon="Str" /> </Item> - <Item ItemId=";Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_asserts_2880" ItemType="0" PsrId="306" Leaf="true"> + <Item ItemId=";Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_assert_2880" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> - <Val><![CDATA[Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'.]]></Val> + <Val><![CDATA[Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'.]]></Val> <Tgt Cat="Text" Stat="Loc" Orig="New"> - <Val><![CDATA[Asercje importu zostały zastąpione atrybutami importu. Użyj instrukcji "with" zamiast "asserts".]]></Val> + <Val><![CDATA[Asercje importu zostały zastąpione atrybutami importu. Użyj instrukcji "with" zamiast "assert".]]></Val> </Tgt> </Str> <Disp Icon="Str" /> diff --git a/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl index 8bbbd27edd1f4..3aba11775753f 100644 --- a/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -8258,11 +8258,11 @@ </Str> <Disp Icon="Str" /> </Item> - <Item ItemId=";Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_asserts_2880" ItemType="0" PsrId="306" Leaf="true"> + <Item ItemId=";Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_assert_2880" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> - <Val><![CDATA[Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'.]]></Val> + <Val><![CDATA[Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'.]]></Val> <Tgt Cat="Text" Stat="Loc" Orig="New"> - <Val><![CDATA[As asserções de importação foram substituídas por atributos de importação. Use 'with' em vez de 'asserts'.]]></Val> + <Val><![CDATA[As asserções de importação foram substituídas por atributos de importação. Use 'with' em vez de 'assert'.]]></Val> </Tgt> </Str> <Disp Icon="Str" /> diff --git a/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl index 7eaa7209efa5c..ed3d8618a042d 100644 --- a/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -8264,11 +8264,11 @@ </Str> <Disp Icon="Str" /> </Item> - <Item ItemId=";Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_asserts_2880" ItemType="0" PsrId="306" Leaf="true"> + <Item ItemId=";Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_assert_2880" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> - <Val><![CDATA[Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'.]]></Val> + <Val><![CDATA[Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'.]]></Val> <Tgt Cat="Text" Stat="Loc" Orig="New"> - <Val><![CDATA[Утверждения импорта заменены атрибутами импорта. Используйте "with" вместо "asserts".]]></Val> + <Val><![CDATA[Утверждения импорта заменены атрибутами импорта. Используйте "with" вместо "assert".]]></Val> </Tgt> </Str> <Disp Icon="Str" /> diff --git a/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl index e2db85240f5a7..7424a5b72a994 100644 --- a/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -8258,11 +8258,11 @@ </Str> <Disp Icon="Str" /> </Item> - <Item ItemId=";Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_asserts_2880" ItemType="0" PsrId="306" Leaf="true"> + <Item ItemId=";Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_assert_2880" ItemType="0" PsrId="306" Leaf="true"> <Str Cat="Text"> - <Val><![CDATA[Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'.]]></Val> + <Val><![CDATA[Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'.]]></Val> <Tgt Cat="Text" Stat="Loc" Orig="New"> - <Val><![CDATA[İçeri aktarma onaylamaları içeri aktarma öznitelikleriyle değiştirildi. 'asserts' yerine 'with' kullanın.]]></Val> + <Val><![CDATA[İçeri aktarma onaylamaları içeri aktarma öznitelikleriyle değiştirildi. 'assert' yerine 'with' kullanın.]]></Val> </Tgt> </Str> <Disp Icon="Str" />
diff --git a/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl index aea89613258c3..720fea33b86ba 100644 --- a/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl - <Val><![CDATA[导入断言已被导入属性替换。使用 “with” 而不是 “asserts”。]]></Val> + <Val><![CDATA[导入断言已被导入属性替换。使用 “with” 而不是 “assert”。]]></Val> diff --git a/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl index 36940ed013ab5..8630475bb08ea 100644 --- a/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl - <Val><![CDATA[匯入宣告已由匯入屬性取代。使用 『with』 而非 'asserts'。]]></Val> diff --git a/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl index 668cb9e96fd07..9c856436898e4 100644 --- a/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -8274,11 +8274,11 @@ - <Val><![CDATA[Kontrolní výrazy importu byly nahrazeny atributy importu. Místo asserts použijte with.]]></Val> diff --git a/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl index 17937acbc647d..e726c146c15eb 100644 --- a/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -8262,11 +8262,11 @@ - <Val><![CDATA[Importassertionen wurden durch Importattribute ersetzt. Verwenden Sie "with" anstelle von "asserts".]]></Val> + <Val><![CDATA[Importassertionen wurden durch Importattribute ersetzt. Verwenden Sie "with" anstelle von "assert".]]></Val> diff --git a/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl index d665b1834734a..e26e96401f42b 100644 --- a/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl - <Val><![CDATA[Las aserciones de importación se han reemplazado por atributos de importación. Use 'with' en lugar de 'asserts'.]]></Val> + <Val><![CDATA[Las aserciones de importación se han reemplazado por atributos de importación. Use 'with' en lugar de 'assert'.]]></Val> diff --git a/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl index 9e19de20e65fb..b5a69e413a2dc 100644 --- a/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl - <Val><![CDATA[Les assertions d’importation ont été remplacées par des attributs d’importation. Utilisez 'with' à la place de 'asserts'.]]></Val> + <Val><![CDATA[Les assertions d’importation ont été remplacées par des attributs d’importation. Utilisez 'with' à la place de 'assert'.]]></Val> diff --git a/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl index 1b475c1f4c493..e2a3a5137dcb9 100644 --- a/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/ita/diagnosticMessages/diagnosticMessages.generated.json.lcl - <Val><![CDATA[Le asserzioni di importazione sono state sostituite dagli attributi di importazione. Usare 'with' invece di 'asserts'.]]></Val> + <Val><![CDATA[Le asserzioni di importazione sono state sostituite dagli attributi di importazione. Usare 'with' invece di 'assert'.]]></Val> diff --git a/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl index e9f181074855c..7d6a048b62785 100644 --- a/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl - <Val><![CDATA[インポート アサーションはインポート属性に置き換えられました。'asserts' ではなく 'with' を使用してください。]]></Val> + <Val><![CDATA[インポート アサーションはインポート属性に置き換えられました。'assert' ではなく 'with' を使用してください。]]></Val> diff --git a/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl index d9a2d6448a1a5..ead631be12465 100644 --- a/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl - <Val><![CDATA[가져오기 어설션이 가져오기 특성으로 바뀌었습니다. 'asserts' 대신 'with'를 사용합니다.]]></Val> + <Val><![CDATA[가져오기 어설션이 가져오기 특성으로 바뀌었습니다. 'assert' 대신 'with'를 사용합니다.]]></Val> diff --git a/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl index bd985b397518e..bdff8b5d661cd 100644 --- a/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -8255,11 +8255,11 @@ - <Val><![CDATA[Asercje importu zostały zastąpione atrybutami importu. Użyj instrukcji "with" zamiast "asserts".]]></Val> + <Val><![CDATA[Asercje importu zostały zastąpione atrybutami importu. Użyj instrukcji "with" zamiast "assert".]]></Val> diff --git a/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl index 8bbbd27edd1f4..3aba11775753f 100644 --- a/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl + <Val><![CDATA[As asserções de importação foram substituídas por atributos de importação. Use 'with' em vez de 'assert'.]]></Val> diff --git a/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl index 7eaa7209efa5c..ed3d8618a042d 100644 --- a/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -8264,11 +8264,11 @@ - <Val><![CDATA[Утверждения импорта заменены атрибутами импорта. Используйте "with" вместо "asserts".]]></Val> + <Val><![CDATA[Утверждения импорта заменены атрибутами импорта. Используйте "with" вместо "assert".]]></Val> diff --git a/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl index e2db85240f5a7..7424a5b72a994 100644 --- a/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl - <Val><![CDATA[İçeri aktarma onaylamaları içeri aktarma öznitelikleriyle değiştirildi. 'asserts' yerine 'with' kullanın.]]></Val> + <Val><![CDATA[İçeri aktarma onaylamaları içeri aktarma öznitelikleriyle değiştirildi. 'assert' yerine 'with' kullanın.]]></Val>
[ "+ <Val><![CDATA[匯入宣告已由匯入屬性取代。使用 『with』 而非 'assert'。]]></Val>", "+ <Val><![CDATA[Kontrolní výrazy importu byly nahrazeny atributy importu. Místo assert použijte with.]]></Val>", "- <Val><![CDATA[As asserções de importação foram substituídas por atributos de importação. Use 'with' em vez de 'asserts'.]]></Val>" ]
[ 34, 53, 204 ]
{ "additions": 39, "author": "csigs", "deletions": 39, "html_url": "https://github.com/microsoft/TypeScript/pull/61114", "issue_id": 61114, "merged_at": "2025-02-04T20:46:49Z", "omission_probability": 0.1, "pr_number": 61114, "repo": "microsoft/TypeScript", "title": "LEGO: Pull request from lego/hb_5378966c-b857-470a-8675-daebef4a6da1_20250204202444390 to main", "total_changes": 78 }
85
diff --git a/.github/workflows/accept-baselines-fix-lints.yaml b/.github/workflows/accept-baselines-fix-lints.yaml index 333348156fbf1..fda98582606e6 100644 --- a/.github/workflows/accept-baselines-fix-lints.yaml +++ b/.github/workflows/accept-baselines-fix-lints.yaml @@ -20,7 +20,7 @@ jobs: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: token: ${{ secrets.TS_BOT_GITHUB_TOKEN }} - - uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 with: node-version: 'lts/*' diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 45874e1fa4c76..6b3d9c346a2ab 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -51,7 +51,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - name: Use node version ${{ matrix.node-version }} - uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 with: node-version: ${{ matrix.node-version }} check-latest: true @@ -81,7 +81,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 with: node-version: 'lts/*' - run: npm ci @@ -106,7 +106,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 with: node-version: 'lts/*' - run: npm ci @@ -119,7 +119,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 with: node-version: 'lts/*' - run: npm ci @@ -132,7 +132,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 with: node-version: 'lts/*' - run: npm ci @@ -152,7 +152,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 with: node-version: 'lts/*' - run: npm ci @@ -168,7 +168,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 with: node-version: 'lts/*' - run: npm ci @@ -182,7 +182,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 with: node-version: 'lts/*' - run: | @@ -230,7 +230,7 @@ jobs: path: base ref: ${{ github.base_ref }} - - uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 with: node-version: 'lts/*' - run: | @@ -263,7 +263,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 with: node-version: 'lts/*' - run: npm ci @@ -279,7 +279,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 with: node-version: 'lts/*' - run: npm ci @@ -298,7 +298,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 with: node-version: 'lts/*' - run: npm ci diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index dee604efcb1c8..7a4c1ba86633d 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -46,7 +46,7 @@ jobs: # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@f6091c0113d1dcf9b98e269ee48e8a7e51b7bdd4 # v3.28.5 + uses: github/codeql-action/init@dd746615b3b9d728a6a37ca2045b68ca76d4841a # v3.28.8 with: config-file: ./.github/codeql/codeql-configuration.yml # Override language selection by uncommenting this and choosing your languages @@ -56,7 +56,7 @@ jobs: # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below). - name: Autobuild - uses: github/codeql-action/autobuild@f6091c0113d1dcf9b98e269ee48e8a7e51b7bdd4 # v3.28.5 + uses: github/codeql-action/autobuild@dd746615b3b9d728a6a37ca2045b68ca76d4841a # v3.28.8 # ℹ️ Command-line programs to run using the OS shell. # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun @@ -70,4 +70,4 @@ jobs: # make release - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@f6091c0113d1dcf9b98e269ee48e8a7e51b7bdd4 # v3.28.5 + uses: github/codeql-action/analyze@dd746615b3b9d728a6a37ca2045b68ca76d4841a # v3.28.8 diff --git a/.github/workflows/insiders.yaml b/.github/workflows/insiders.yaml index dc23cc43673b8..e7e6227fb4480 100644 --- a/.github/workflows/insiders.yaml +++ b/.github/workflows/insiders.yaml @@ -21,7 +21,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 with: node-version: 'lts/*' - run: | @@ -43,7 +43,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 with: node-version: 'lts/*' # Use NODE_AUTH_TOKEN environment variable to authenticate to this registry. diff --git a/.github/workflows/lkg.yml b/.github/workflows/lkg.yml index 26fe358473e22..c593b9d1bfe0f 100644 --- a/.github/workflows/lkg.yml +++ b/.github/workflows/lkg.yml @@ -31,7 +31,7 @@ jobs: with: ref: ${{ inputs.branch_name }} token: ${{ secrets.TS_BOT_GITHUB_TOKEN }} - - uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 with: node-version: 'lts/*' - run: | diff --git a/.github/workflows/new-release-branch.yaml b/.github/workflows/new-release-branch.yaml index 17bffe12ee4c1..7b2d3a8f82661 100644 --- a/.github/workflows/new-release-branch.yaml +++ b/.github/workflows/new-release-branch.yaml @@ -55,7 +55,7 @@ jobs: filter: blob:none # https://github.blog/2020-12-21-get-up-to-speed-with-partial-clone-and-shallow-clone/ fetch-depth: 0 # Default is 1; need to set to 0 to get the benefits of blob:none. token: ${{ secrets.TS_BOT_GITHUB_TOKEN }} - - uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 with: node-version: 'lts/*' - run: | diff --git a/.github/workflows/nightly.yaml b/.github/workflows/nightly.yaml index 375a8255ae67b..949aee8211d0f 100644 --- a/.github/workflows/nightly.yaml +++ b/.github/workflows/nightly.yaml @@ -22,7 +22,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 with: node-version: 'lts/*' - run: | @@ -43,7 +43,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 with: node-version: 'lts/*' # Use NODE_AUTH_TOKEN environment variable to authenticate to this registry. diff --git a/.github/workflows/release-branch-artifact.yaml b/.github/workflows/release-branch-artifact.yaml index 21488653e0855..a3cfb107ea0b5 100644 --- a/.github/workflows/release-branch-artifact.yaml +++ b/.github/workflows/release-branch-artifact.yaml @@ -20,7 +20,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 with: node-version: 'lts/*' - run: | diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml index b96a9ab144281..389790241e477 100644 --- a/.github/workflows/scorecard.yml +++ b/.github/workflows/scorecard.yml @@ -55,6 +55,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: 'Upload to code-scanning' - uses: github/codeql-action/upload-sarif@f6091c0113d1dcf9b98e269ee48e8a7e51b7bdd4 # v3.28.5 + uses: github/codeql-action/upload-sarif@dd746615b3b9d728a6a37ca2045b68ca76d4841a # v3.28.8 with: sarif_file: results.sarif diff --git a/.github/workflows/set-version.yaml b/.github/workflows/set-version.yaml index 145a717383d47..b2584906824f6 100644 --- a/.github/workflows/set-version.yaml +++ b/.github/workflows/set-version.yaml @@ -53,7 +53,7 @@ jobs: with: ref: ${{ inputs.branch_name }} token: ${{ secrets.TS_BOT_GITHUB_TOKEN }} - - uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 with: node-version: 'lts/*' - run: | diff --git a/.github/workflows/sync-branch.yaml b/.github/workflows/sync-branch.yaml index e5baa9b763142..cb0dae4931228 100644 --- a/.github/workflows/sync-branch.yaml +++ b/.github/workflows/sync-branch.yaml @@ -42,7 +42,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 with: node-version: 'lts/*' - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 diff --git a/.github/workflows/twoslash-repros.yaml b/.github/workflows/twoslash-repros.yaml index 2a50aadcf14b5..6bf6949119c7f 100644 --- a/.github/workflows/twoslash-repros.yaml +++ b/.github/workflows/twoslash-repros.yaml @@ -55,7 +55,7 @@ jobs: fetch-depth: 0 # Default is 1; need to set to 0 to get the benefits of blob:none. - if: ${{ !github.event.inputs.bisect }} uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 with: node-version: 'lts/*' - uses: microsoft/TypeScript-Twoslash-Repro-Action@master diff --git a/.github/workflows/update-package-lock.yaml b/.github/workflows/update-package-lock.yaml index abf340d4f3360..1a55bfdd4f781 100644 --- a/.github/workflows/update-package-lock.yaml +++ b/.github/workflows/update-package-lock.yaml @@ -25,7 +25,7 @@ jobs: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: token: ${{ secrets.TS_BOT_GITHUB_TOKEN }} - - uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + - uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 with: node-version: 'lts/*' - run: |
diff --git a/.github/workflows/accept-baselines-fix-lints.yaml b/.github/workflows/accept-baselines-fix-lints.yaml index 333348156fbf1..fda98582606e6 100644 --- a/.github/workflows/accept-baselines-fix-lints.yaml +++ b/.github/workflows/accept-baselines-fix-lints.yaml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 45874e1fa4c76..6b3d9c346a2ab 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -51,7 +51,7 @@ jobs: - name: Use node version ${{ matrix.node-version }} - uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0 + uses: actions/setup-node@1d0ff469b7ec7b3cb9d8673fde0c81c44821de2a # v4.2.0 node-version: ${{ matrix.node-version }} check-latest: true @@ -81,7 +81,7 @@ jobs: @@ -106,7 +106,7 @@ jobs: @@ -119,7 +119,7 @@ jobs: @@ -132,7 +132,7 @@ jobs: @@ -152,7 +152,7 @@ jobs: @@ -168,7 +168,7 @@ jobs: @@ -182,7 +182,7 @@ jobs: @@ -230,7 +230,7 @@ jobs: path: base ref: ${{ github.base_ref }} @@ -263,7 +263,7 @@ jobs: @@ -279,7 +279,7 @@ jobs: @@ -298,7 +298,7 @@ jobs: diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index dee604efcb1c8..7a4c1ba86633d 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -46,7 +46,7 @@ jobs: # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@f6091c0113d1dcf9b98e269ee48e8a7e51b7bdd4 # v3.28.5 + uses: github/codeql-action/init@dd746615b3b9d728a6a37ca2045b68ca76d4841a # v3.28.8 config-file: ./.github/codeql/codeql-configuration.yml # Override language selection by uncommenting this and choosing your languages @@ -56,7 +56,7 @@ jobs: # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below). - name: Autobuild + uses: github/codeql-action/autobuild@dd746615b3b9d728a6a37ca2045b68ca76d4841a # v3.28.8 # ℹ️ Command-line programs to run using the OS shell. # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun @@ -70,4 +70,4 @@ jobs: # make release - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@f6091c0113d1dcf9b98e269ee48e8a7e51b7bdd4 # v3.28.5 + uses: github/codeql-action/analyze@dd746615b3b9d728a6a37ca2045b68ca76d4841a # v3.28.8 diff --git a/.github/workflows/insiders.yaml b/.github/workflows/insiders.yaml index dc23cc43673b8..e7e6227fb4480 100644 --- a/.github/workflows/insiders.yaml +++ b/.github/workflows/insiders.yaml @@ -21,7 +21,7 @@ jobs: diff --git a/.github/workflows/lkg.yml b/.github/workflows/lkg.yml index 26fe358473e22..c593b9d1bfe0f 100644 --- a/.github/workflows/lkg.yml +++ b/.github/workflows/lkg.yml @@ -31,7 +31,7 @@ jobs: diff --git a/.github/workflows/new-release-branch.yaml b/.github/workflows/new-release-branch.yaml index 17bffe12ee4c1..7b2d3a8f82661 100644 --- a/.github/workflows/new-release-branch.yaml +++ b/.github/workflows/new-release-branch.yaml filter: blob:none # https://github.blog/2020-12-21-get-up-to-speed-with-partial-clone-and-shallow-clone/ diff --git a/.github/workflows/nightly.yaml b/.github/workflows/nightly.yaml index 375a8255ae67b..949aee8211d0f 100644 --- a/.github/workflows/nightly.yaml +++ b/.github/workflows/nightly.yaml @@ -22,7 +22,7 @@ jobs: diff --git a/.github/workflows/release-branch-artifact.yaml b/.github/workflows/release-branch-artifact.yaml index 21488653e0855..a3cfb107ea0b5 100644 --- a/.github/workflows/release-branch-artifact.yaml +++ b/.github/workflows/release-branch-artifact.yaml diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml index b96a9ab144281..389790241e477 100644 --- a/.github/workflows/scorecard.yml +++ b/.github/workflows/scorecard.yml @@ -55,6 +55,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: 'Upload to code-scanning' - uses: github/codeql-action/upload-sarif@f6091c0113d1dcf9b98e269ee48e8a7e51b7bdd4 # v3.28.5 + uses: github/codeql-action/upload-sarif@dd746615b3b9d728a6a37ca2045b68ca76d4841a # v3.28.8 sarif_file: results.sarif diff --git a/.github/workflows/set-version.yaml b/.github/workflows/set-version.yaml index 145a717383d47..b2584906824f6 100644 --- a/.github/workflows/set-version.yaml +++ b/.github/workflows/set-version.yaml @@ -53,7 +53,7 @@ jobs: diff --git a/.github/workflows/sync-branch.yaml b/.github/workflows/sync-branch.yaml index e5baa9b763142..cb0dae4931228 100644 --- a/.github/workflows/sync-branch.yaml +++ b/.github/workflows/sync-branch.yaml @@ -42,7 +42,7 @@ jobs: runs-on: ubuntu-latest diff --git a/.github/workflows/twoslash-repros.yaml b/.github/workflows/twoslash-repros.yaml index 2a50aadcf14b5..6bf6949119c7f 100644 --- a/.github/workflows/twoslash-repros.yaml +++ b/.github/workflows/twoslash-repros.yaml - if: ${{ !github.event.inputs.bisect }} uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - uses: microsoft/TypeScript-Twoslash-Repro-Action@master diff --git a/.github/workflows/update-package-lock.yaml b/.github/workflows/update-package-lock.yaml index abf340d4f3360..1a55bfdd4f781 100644 --- a/.github/workflows/update-package-lock.yaml +++ b/.github/workflows/update-package-lock.yaml @@ -25,7 +25,7 @@ jobs:
[ "- uses: github/codeql-action/autobuild@f6091c0113d1dcf9b98e269ee48e8a7e51b7bdd4 # v3.28.5" ]
[ 142 ]
{ "additions": 28, "author": "dependabot[bot]", "deletions": 28, "html_url": "https://github.com/microsoft/TypeScript/pull/61102", "issue_id": 61102, "merged_at": "2025-02-03T16:36:45Z", "omission_probability": 0.1, "pr_number": 61102, "repo": "microsoft/TypeScript", "title": "Bump the github-actions group with 2 updates", "total_changes": 56 }
86
diff --git a/eslint.config.mjs b/eslint.config.mjs index 195ca4293e4be..9fd6276e584fc 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -155,6 +155,7 @@ export default tseslint.config( "local/no-keywords": "error", "local/jsdoc-format": "error", "local/js-extensions": "error", + "local/no-array-mutating-method-expressions": "error", }, }, { diff --git a/package-lock.json b/package-lock.json index eb0db3e839ac6..baeb2565e5f66 100644 --- a/package-lock.json +++ b/package-lock.json @@ -27,6 +27,7 @@ "@types/source-map-support": "^0.5.10", "@types/which": "^3.0.4", "@typescript-eslint/rule-tester": "^8.1.0", + "@typescript-eslint/type-utils": "^8.1.0", "@typescript-eslint/utils": "^8.1.0", "azure-devops-node-api": "^14.0.2", "c8": "^10.1.2", diff --git a/package.json b/package.json index 05e08606a75ed..2528f6b59b353 100644 --- a/package.json +++ b/package.json @@ -53,6 +53,7 @@ "@types/source-map-support": "^0.5.10", "@types/which": "^3.0.4", "@typescript-eslint/rule-tester": "^8.1.0", + "@typescript-eslint/type-utils": "^8.1.0", "@typescript-eslint/utils": "^8.1.0", "azure-devops-node-api": "^14.0.2", "c8": "^10.1.2", diff --git a/scripts/eslint/rules/no-array-mutating-method-expressions.cjs b/scripts/eslint/rules/no-array-mutating-method-expressions.cjs new file mode 100644 index 0000000000000..b085933953b19 --- /dev/null +++ b/scripts/eslint/rules/no-array-mutating-method-expressions.cjs @@ -0,0 +1,126 @@ +const { ESLintUtils } = require("@typescript-eslint/utils"); +const { createRule } = require("./utils.cjs"); +const { getConstrainedTypeAtLocation, isTypeArrayTypeOrUnionOfArrayTypes } = require("@typescript-eslint/type-utils"); + +/** + * @import { TSESTree } from "@typescript-eslint/utils" + */ +void 0; + +module.exports = createRule({ + name: "no-array-mutating-method-expressions", + meta: { + docs: { + description: ``, + }, + messages: { + noSideEffectUse: `This call to {{method}} appears to be unintentional as it appears in an expression position. Sort the array in a separate statement or explicitly copy the array with slice.`, + noSideEffectUseToMethod: `This call to {{method}} appears to be unintentional as it appears in an expression position. Sort the array in a separate statement or explicitly copy and slice the array with slice/{{toMethod}}.`, + }, + schema: [], + type: "problem", + }, + defaultOptions: [], + + create(context) { + const services = ESLintUtils.getParserServices(context, /*allowWithoutFullTypeInformation*/ true); + if (!services.program) { + return {}; + } + + const checker = services.program.getTypeChecker(); + + /** + * This is a heuristic to ignore cases where the mutating method appears to be + * operating on a "fresh" array. + * + * @type {(callee: TSESTree.MemberExpression) => boolean} + */ + const isFreshArray = callee => { + const object = callee.object; + + if (object.type === "ArrayExpression") { + return true; + } + + if (object.type !== "CallExpression") { + return false; + } + + if (object.callee.type === "Identifier") { + // TypeScript codebase specific helpers. + // TODO(jakebailey): handle ts. + switch (object.callee.name) { + case "arrayFrom": + case "getOwnKeys": + return true; + } + return false; + } + + if (object.callee.type === "MemberExpression" && object.callee.property.type === "Identifier") { + switch (object.callee.property.name) { + case "concat": + case "filter": + case "map": + case "slice": + return true; + } + + if (object.callee.object.type === "Identifier") { + if (object.callee.object.name === "Array") { + switch (object.callee.property.name) { + case "from": + case "of": + return true; + } + return false; + } + + if (object.callee.object.name === "Object") { + switch (object.callee.property.name) { + case "values": + case "keys": + case "entries": + return true; + } + return false; + } + } + } + + return false; + }; + + /** @type {(callee: TSESTree.MemberExpression & { parent: TSESTree.CallExpression; }, method: string, toMethod: string | undefined) => void} */ + const check = (callee, method, toMethod) => { + if (callee.parent.parent.type === "ExpressionStatement") return; + if (isFreshArray(callee)) return; + + const calleeObjType = getConstrainedTypeAtLocation(services, callee.object); + if (!isTypeArrayTypeOrUnionOfArrayTypes(calleeObjType, checker)) return; + + if (toMethod) { + context.report({ node: callee.property, messageId: "noSideEffectUseToMethod", data: { method, toMethod } }); + } + else { + context.report({ node: callee.property, messageId: "noSideEffectUse", data: { method } }); + } + }; + + // Methods with new copying variants. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#copying_methods_and_mutating_methods + const mutatingMethods = { + reverse: undefined, + sort: "toSorted", // This exists as `ts.toSorted`, so recommend that. + splice: undefined, + }; + + return Object.fromEntries( + Object.entries(mutatingMethods).map(([method, toMethod]) => [ + `CallExpression > MemberExpression[property.name='${method}'][computed=false]`, + node => check(node, method, toMethod), + ]), + ); + }, +}); diff --git a/src/harness/fourslashImpl.ts b/src/harness/fourslashImpl.ts index 04beb984ae538..33e0f84a7443c 100644 --- a/src/harness/fourslashImpl.ts +++ b/src/harness/fourslashImpl.ts @@ -963,7 +963,7 @@ export class TestState { const fileName = this.activeFile.fileName; const hints = this.languageService.provideInlayHints(fileName, span, preferences); - const annotations = ts.map(hints.sort(sortHints), hint => { + const annotations = ts.map(hints.slice().sort(sortHints), hint => { if (hint.displayParts) { hint.displayParts = ts.map(hint.displayParts, part => { if (part.file && /lib.*\.d\.ts$/.test(part.file)) { @@ -3257,8 +3257,8 @@ export class TestState { allSpanInsets.push({ text: "|]", pos: span.textSpan.start + span.textSpan.length }); }); - const reverseSpans = allSpanInsets.sort((l, r) => r.pos - l.pos); - ts.forEach(reverseSpans, span => { + allSpanInsets.sort((l, r) => r.pos - l.pos); + ts.forEach(allSpanInsets, span => { annotated = annotated.slice(0, span.pos) + span.text + annotated.slice(span.pos); }); Harness.IO.log(`\nMockup:\n${annotated}`); @@ -3783,7 +3783,7 @@ export class TestState { return { baselineContent: baselineContent + activeFile.content + `\n\n--No linked edits found--`, offset }; } - let inlineLinkedEditBaselines: { start: number; end: number; index: number; }[] = []; + const inlineLinkedEditBaselines: { start: number; end: number; index: number; }[] = []; let linkedEditInfoBaseline = ""; for (const edit of linkedEditsByRange) { const [linkedEdit, positions] = edit; @@ -3802,7 +3802,7 @@ export class TestState { offset++; } - inlineLinkedEditBaselines = inlineLinkedEditBaselines.sort((a, b) => a.start - b.start); + inlineLinkedEditBaselines.sort((a, b) => a.start - b.start); const fileText = activeFile.content; baselineContent += fileText.slice(0, inlineLinkedEditBaselines[0].start); for (let i = 0; i < inlineLinkedEditBaselines.length; i++) { @@ -4058,7 +4058,7 @@ export class TestState { public verifyRefactorKindsAvailable(kind: string, expected: string[], preferences = ts.emptyOptions) { const refactors = this.getApplicableRefactorsAtSelection("invoked", kind, preferences); const availableKinds = ts.flatMap(refactors, refactor => refactor.actions).map(action => action.kind); - assert.deepEqual(availableKinds.sort(), expected.sort(), `Expected kinds to be equal`); + assert.deepEqual(availableKinds.slice().sort(), expected.slice().sort(), `Expected kinds to be equal`); } public verifyRefactorsAvailable(names: readonly string[]): void { @@ -4938,7 +4938,7 @@ function parseFileContent(content: string, fileName: string, markerMap: Map<stri const openRanges: RangeLocationInformation[] = []; /// A list of ranges we've collected so far */ - let localRanges: Range[] = []; + const localRanges: Range[] = []; /// The latest position of the start of an unflushed plain text area let lastNormalCharPosition = 0; @@ -5105,7 +5105,7 @@ function parseFileContent(content: string, fileName: string, markerMap: Map<stri } // put ranges in the correct order - localRanges = localRanges.sort((a, b) => a.pos < b.pos ? -1 : a.pos === b.pos && a.end > b.end ? -1 : 1); + localRanges.sort((a, b) => a.pos < b.pos ? -1 : a.pos === b.pos && a.end > b.end ? -1 : 1); localRanges.forEach(r => ranges.push(r)); return { diff --git a/src/harness/projectServiceStateLogger.ts b/src/harness/projectServiceStateLogger.ts index 599769b8e734b..42f64fde7f321 100644 --- a/src/harness/projectServiceStateLogger.ts +++ b/src/harness/projectServiceStateLogger.ts @@ -9,6 +9,7 @@ import { isString, noop, SourceMapper, + toSorted, } from "./_namespaces/ts.js"; import { AutoImportProviderProject, @@ -93,7 +94,7 @@ export function patchServiceForStateBaseline(service: ProjectService) { function sendLogsToLogger(title: string, logs: StateItemLog[] | undefined) { if (!logs) return; logger.log(title); - logs.sort((a, b) => compareStringsCaseSensitive(a[0], b[0])) + toSorted(logs, (a, b) => compareStringsCaseSensitive(a[0], b[0])) .forEach(([title, propertyLogs]) => { logger.log(title); propertyLogs.forEach(p => isString(p) ? logger.log(p) : p.forEach(s => logger.log(s))); diff --git a/src/services/mapCode.ts b/src/services/mapCode.ts index b87ea5e75301f..11d9fb5acf2f9 100644 --- a/src/services/mapCode.ts +++ b/src/services/mapCode.ts @@ -113,11 +113,12 @@ function parse(sourceFile: SourceFile, content: string): NodeArray<Node> { } } // Heuristic: fewer errors = more likely to be the right kind. - const { body } = parsedNodes.sort( + parsedNodes.sort( (a, b) => a.sourceFile.parseDiagnostics.length - b.sourceFile.parseDiagnostics.length, - )[0]; + ); + const { body } = parsedNodes[0]; return body; } diff --git a/src/services/navigateTo.ts b/src/services/navigateTo.ts index cb75e1478113f..e2858e48fedba 100644 --- a/src/services/navigateTo.ts +++ b/src/services/navigateTo.ts @@ -164,7 +164,8 @@ function getContainers(declaration: Declaration): readonly string[] { container = getContainerNode(container); } - return containers.reverse(); + containers.reverse(); + return containers; } function compareNavigateToItems(i1: RawNavigateToItem, i2: RawNavigateToItem) { diff --git a/src/services/outliningElementsCollector.ts b/src/services/outliningElementsCollector.ts index 0254620c1e6d8..7248133ec8ca7 100644 --- a/src/services/outliningElementsCollector.ts +++ b/src/services/outliningElementsCollector.ts @@ -60,7 +60,8 @@ export function collectElements(sourceFile: SourceFile, cancellationToken: Cance const res: OutliningSpan[] = []; addNodeOutliningSpans(sourceFile, cancellationToken, res); addRegionOutliningSpans(sourceFile, res); - return res.sort((span1, span2) => span1.textSpan.start - span2.textSpan.start); + res.sort((span1, span2) => span1.textSpan.start - span2.textSpan.start); + return res; } function addNodeOutliningSpans(sourceFile: SourceFile, cancellationToken: CancellationToken, out: OutliningSpan[]): void { diff --git a/src/services/refactors/extractSymbol.ts b/src/services/refactors/extractSymbol.ts index 4093074b9575a..423922f691323 100644 --- a/src/services/refactors/extractSymbol.ts +++ b/src/services/refactors/extractSymbol.ts @@ -1081,11 +1081,11 @@ function extractFunctionInScope( }); const typeParametersAndDeclarations = arrayFrom(typeParameterUsages.values(), type => ({ type, declaration: getFirstDeclarationBeforePosition(type, context.startPosition) })); - const sortedTypeParametersAndDeclarations = typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder); + typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder); - const typeParameters: readonly TypeParameterDeclaration[] | undefined = sortedTypeParametersAndDeclarations.length === 0 + const typeParameters: readonly TypeParameterDeclaration[] | undefined = typeParametersAndDeclarations.length === 0 ? undefined - : mapDefined(sortedTypeParametersAndDeclarations, ({ declaration }) => declaration as TypeParameterDeclaration); + : mapDefined(typeParametersAndDeclarations, ({ declaration }) => declaration as TypeParameterDeclaration); // Strictly speaking, we should check whether each name actually binds to the appropriate type // parameter. In cases of shadowing, they may not. diff --git a/src/services/suggestionDiagnostics.ts b/src/services/suggestionDiagnostics.ts index a5daf3e6666f2..3c4cf5c39b976 100644 --- a/src/services/suggestionDiagnostics.ts +++ b/src/services/suggestionDiagnostics.ts @@ -97,7 +97,8 @@ export function computeSuggestionDiagnostics(sourceFile: SourceFile, program: Pr addRange(diags, sourceFile.bindSuggestionDiagnostics); addRange(diags, program.getSuggestionDiagnostics(sourceFile, cancellationToken)); - return diags.sort((d1, d2) => d1.start - d2.start); + diags.sort((d1, d2) => d1.start - d2.start); + return diags; function check(node: Node) { if (isJsFile) { diff --git a/src/testRunner/unittests/services/extract/ranges.ts b/src/testRunner/unittests/services/extract/ranges.ts index 9fd9bee8bebbe..c54760476ddb4 100644 --- a/src/testRunner/unittests/services/extract/ranges.ts +++ b/src/testRunner/unittests/services/extract/ranges.ts @@ -1,7 +1,7 @@ import * as ts from "../../../_namespaces/ts.js"; import { extractTest } from "./helpers.js"; -function testExtractRangeFailed(caption: string, s: string, expectedErrors: string[]) { +function testExtractRangeFailed(caption: string, s: string, expectedErrors: readonly string[]) { return it(caption, () => { const t = extractTest(s); const file = ts.createSourceFile("a.ts", t.source, ts.ScriptTarget.Latest, /*setParentNodes*/ true); @@ -12,7 +12,7 @@ function testExtractRangeFailed(caption: string, s: string, expectedErrors: stri const result = ts.refactor.extractSymbol.getRangeToExtract(file, ts.createTextSpanFromRange(selectionRange), /*invoked*/ false); assert(result.targetRange === undefined, "failure expected"); const sortedErrors = result.errors.map(e => e.messageText as string).sort(); - assert.deepEqual(sortedErrors, expectedErrors.sort(), "unexpected errors"); + assert.deepEqual(sortedErrors, expectedErrors.slice().sort(), "unexpected errors"); }); }
diff --git a/eslint.config.mjs b/eslint.config.mjs index 195ca4293e4be..9fd6276e584fc 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -155,6 +155,7 @@ export default tseslint.config( "local/no-keywords": "error", "local/jsdoc-format": "error", "local/js-extensions": "error", + "local/no-array-mutating-method-expressions": "error", }, }, { diff --git a/package-lock.json b/package-lock.json index eb0db3e839ac6..baeb2565e5f66 100644 --- a/package-lock.json +++ b/package-lock.json @@ -27,6 +27,7 @@ "@types/source-map-support": "^0.5.10", "@types/which": "^3.0.4", "@typescript-eslint/rule-tester": "^8.1.0", + "@typescript-eslint/type-utils": "^8.1.0", "@typescript-eslint/utils": "^8.1.0", "azure-devops-node-api": "^14.0.2", "c8": "^10.1.2", diff --git a/package.json b/package.json index 05e08606a75ed..2528f6b59b353 100644 --- a/package.json +++ b/package.json @@ -53,6 +53,7 @@ "@types/source-map-support": "^0.5.10", "@types/which": "^3.0.4", "@typescript-eslint/rule-tester": "^8.1.0", + "@typescript-eslint/type-utils": "^8.1.0", "@typescript-eslint/utils": "^8.1.0", "azure-devops-node-api": "^14.0.2", "c8": "^10.1.2", diff --git a/scripts/eslint/rules/no-array-mutating-method-expressions.cjs b/scripts/eslint/rules/no-array-mutating-method-expressions.cjs new file mode 100644 index 0000000000000..b085933953b19 --- /dev/null +++ b/scripts/eslint/rules/no-array-mutating-method-expressions.cjs @@ -0,0 +1,126 @@ +const { ESLintUtils } = require("@typescript-eslint/utils"); +const { createRule } = require("./utils.cjs"); +const { getConstrainedTypeAtLocation, isTypeArrayTypeOrUnionOfArrayTypes } = require("@typescript-eslint/type-utils"); +/** + * @import { TSESTree } from "@typescript-eslint/utils" + */ +void 0; +module.exports = createRule({ + name: "no-array-mutating-method-expressions", + meta: { + docs: { + description: ``, + messages: { + noSideEffectUse: `This call to {{method}} appears to be unintentional as it appears in an expression position. Sort the array in a separate statement or explicitly copy the array with slice.`, + noSideEffectUseToMethod: `This call to {{method}} appears to be unintentional as it appears in an expression position. Sort the array in a separate statement or explicitly copy and slice the array with slice/{{toMethod}}.`, + schema: [], + type: "problem", + defaultOptions: [], + create(context) { + const services = ESLintUtils.getParserServices(context, /*allowWithoutFullTypeInformation*/ true); + if (!services.program) { + return {}; + } + const checker = services.program.getTypeChecker(); + /** + * operating on a "fresh" array. + * + * @type {(callee: TSESTree.MemberExpression) => boolean} + */ + const isFreshArray = callee => { + const object = callee.object; + if (object.type === "ArrayExpression") { + if (object.type !== "CallExpression") { + if (object.callee.type === "Identifier") { + // TypeScript codebase specific helpers. + // TODO(jakebailey): handle ts. + switch (object.callee.name) { + case "arrayFrom": + case "getOwnKeys": + if (object.callee.type === "MemberExpression" && object.callee.property.type === "Identifier") { + switch (object.callee.property.name) { + case "concat": + case "filter": + case "map": + case "slice": + if (object.callee.object.type === "Identifier") { + if (object.callee.object.name === "Array") { + case "from": + case "of": + if (object.callee.object.name === "Object") { + case "values": + case "keys": + case "entries": + return false; + /** @type {(callee: TSESTree.MemberExpression & { parent: TSESTree.CallExpression; }, method: string, toMethod: string | undefined) => void} */ + const check = (callee, method, toMethod) => { + if (isFreshArray(callee)) return; + if (!isTypeArrayTypeOrUnionOfArrayTypes(calleeObjType, checker)) return; + if (toMethod) { + context.report({ node: callee.property, messageId: "noSideEffectUseToMethod", data: { method, toMethod } }); + else { + // Methods with new copying variants. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#copying_methods_and_mutating_methods + const mutatingMethods = { + reverse: undefined, + sort: "toSorted", // This exists as `ts.toSorted`, so recommend that. + splice: undefined, + return Object.fromEntries( + Object.entries(mutatingMethods).map(([method, toMethod]) => [ + `CallExpression > MemberExpression[property.name='${method}'][computed=false]`, + ); +}); diff --git a/src/harness/fourslashImpl.ts b/src/harness/fourslashImpl.ts index 04beb984ae538..33e0f84a7443c 100644 --- a/src/harness/fourslashImpl.ts +++ b/src/harness/fourslashImpl.ts @@ -963,7 +963,7 @@ export class TestState { const fileName = this.activeFile.fileName; const hints = this.languageService.provideInlayHints(fileName, span, preferences); - const annotations = ts.map(hints.sort(sortHints), hint => { + const annotations = ts.map(hints.slice().sort(sortHints), hint => { if (hint.displayParts) { hint.displayParts = ts.map(hint.displayParts, part => { if (part.file && /lib.*\.d\.ts$/.test(part.file)) { @@ -3257,8 +3257,8 @@ export class TestState { allSpanInsets.push({ text: "|]", pos: span.textSpan.start + span.textSpan.length }); - const reverseSpans = allSpanInsets.sort((l, r) => r.pos - l.pos); - ts.forEach(reverseSpans, span => { + ts.forEach(allSpanInsets, span => { annotated = annotated.slice(0, span.pos) + span.text + annotated.slice(span.pos); Harness.IO.log(`\nMockup:\n${annotated}`); @@ -3783,7 +3783,7 @@ export class TestState { return { baselineContent: baselineContent + activeFile.content + `\n\n--No linked edits found--`, offset }; - let inlineLinkedEditBaselines: { start: number; end: number; index: number; }[] = []; + const inlineLinkedEditBaselines: { start: number; end: number; index: number; }[] = []; let linkedEditInfoBaseline = ""; for (const edit of linkedEditsByRange) { const [linkedEdit, positions] = edit; @@ -3802,7 +3802,7 @@ export class TestState { offset++; - inlineLinkedEditBaselines = inlineLinkedEditBaselines.sort((a, b) => a.start - b.start); + inlineLinkedEditBaselines.sort((a, b) => a.start - b.start); const fileText = activeFile.content; baselineContent += fileText.slice(0, inlineLinkedEditBaselines[0].start); for (let i = 0; i < inlineLinkedEditBaselines.length; i++) { @@ -4058,7 +4058,7 @@ export class TestState { public verifyRefactorKindsAvailable(kind: string, expected: string[], preferences = ts.emptyOptions) { const refactors = this.getApplicableRefactorsAtSelection("invoked", kind, preferences); const availableKinds = ts.flatMap(refactors, refactor => refactor.actions).map(action => action.kind); - assert.deepEqual(availableKinds.sort(), expected.sort(), `Expected kinds to be equal`); + assert.deepEqual(availableKinds.slice().sort(), expected.slice().sort(), `Expected kinds to be equal`); public verifyRefactorsAvailable(names: readonly string[]): void { @@ -4938,7 +4938,7 @@ function parseFileContent(content: string, fileName: string, markerMap: Map<stri const openRanges: RangeLocationInformation[] = []; /// A list of ranges we've collected so far */ - let localRanges: Range[] = []; + const localRanges: Range[] = []; /// The latest position of the start of an unflushed plain text area let lastNormalCharPosition = 0; @@ -5105,7 +5105,7 @@ function parseFileContent(content: string, fileName: string, markerMap: Map<stri // put ranges in the correct order + localRanges.sort((a, b) => a.pos < b.pos ? -1 : a.pos === b.pos && a.end > b.end ? -1 : 1); localRanges.forEach(r => ranges.push(r)); return { diff --git a/src/harness/projectServiceStateLogger.ts b/src/harness/projectServiceStateLogger.ts index 599769b8e734b..42f64fde7f321 100644 --- a/src/harness/projectServiceStateLogger.ts +++ b/src/harness/projectServiceStateLogger.ts @@ -9,6 +9,7 @@ import { isString, noop, SourceMapper, } from "./_namespaces/ts.js"; import { AutoImportProviderProject, @@ -93,7 +94,7 @@ export function patchServiceForStateBaseline(service: ProjectService) { function sendLogsToLogger(title: string, logs: StateItemLog[] | undefined) { if (!logs) return; logger.log(title); .forEach(([title, propertyLogs]) => { logger.log(title); propertyLogs.forEach(p => isString(p) ? logger.log(p) : p.forEach(s => logger.log(s))); diff --git a/src/services/mapCode.ts b/src/services/mapCode.ts index b87ea5e75301f..11d9fb5acf2f9 100644 --- a/src/services/mapCode.ts +++ b/src/services/mapCode.ts @@ -113,11 +113,12 @@ function parse(sourceFile: SourceFile, content: string): NodeArray<Node> { } // Heuristic: fewer errors = more likely to be the right kind. - const { body } = parsedNodes.sort( (a, b) => a.sourceFile.parseDiagnostics.length - b.sourceFile.parseDiagnostics.length, - )[0]; + ); + const { body } = parsedNodes[0]; return body; diff --git a/src/services/navigateTo.ts b/src/services/navigateTo.ts index cb75e1478113f..e2858e48fedba 100644 --- a/src/services/navigateTo.ts +++ b/src/services/navigateTo.ts @@ -164,7 +164,8 @@ function getContainers(declaration: Declaration): readonly string[] { container = getContainerNode(container); - return containers.reverse(); + containers.reverse(); + return containers; function compareNavigateToItems(i1: RawNavigateToItem, i2: RawNavigateToItem) { diff --git a/src/services/outliningElementsCollector.ts b/src/services/outliningElementsCollector.ts index 0254620c1e6d8..7248133ec8ca7 100644 --- a/src/services/outliningElementsCollector.ts +++ b/src/services/outliningElementsCollector.ts @@ -60,7 +60,8 @@ export function collectElements(sourceFile: SourceFile, cancellationToken: Cance const res: OutliningSpan[] = []; addNodeOutliningSpans(sourceFile, cancellationToken, res); addRegionOutliningSpans(sourceFile, res); - return res.sort((span1, span2) => span1.textSpan.start - span2.textSpan.start); + res.sort((span1, span2) => span1.textSpan.start - span2.textSpan.start); + return res; function addNodeOutliningSpans(sourceFile: SourceFile, cancellationToken: CancellationToken, out: OutliningSpan[]): void { diff --git a/src/services/refactors/extractSymbol.ts b/src/services/refactors/extractSymbol.ts index 4093074b9575a..423922f691323 100644 --- a/src/services/refactors/extractSymbol.ts +++ b/src/services/refactors/extractSymbol.ts @@ -1081,11 +1081,11 @@ function extractFunctionInScope( const typeParametersAndDeclarations = arrayFrom(typeParameterUsages.values(), type => ({ type, declaration: getFirstDeclarationBeforePosition(type, context.startPosition) })); - const sortedTypeParametersAndDeclarations = typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder); + typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder); - const typeParameters: readonly TypeParameterDeclaration[] | undefined = sortedTypeParametersAndDeclarations.length === 0 + const typeParameters: readonly TypeParameterDeclaration[] | undefined = typeParametersAndDeclarations.length === 0 ? undefined - : mapDefined(sortedTypeParametersAndDeclarations, ({ declaration }) => declaration as TypeParameterDeclaration); + : mapDefined(typeParametersAndDeclarations, ({ declaration }) => declaration as TypeParameterDeclaration); // Strictly speaking, we should check whether each name actually binds to the appropriate type // parameter. In cases of shadowing, they may not. diff --git a/src/services/suggestionDiagnostics.ts b/src/services/suggestionDiagnostics.ts index a5daf3e6666f2..3c4cf5c39b976 100644 --- a/src/services/suggestionDiagnostics.ts +++ b/src/services/suggestionDiagnostics.ts @@ -97,7 +97,8 @@ export function computeSuggestionDiagnostics(sourceFile: SourceFile, program: Pr addRange(diags, sourceFile.bindSuggestionDiagnostics); addRange(diags, program.getSuggestionDiagnostics(sourceFile, cancellationToken)); + diags.sort((d1, d2) => d1.start - d2.start); + return diags; function check(node: Node) { if (isJsFile) { diff --git a/src/testRunner/unittests/services/extract/ranges.ts b/src/testRunner/unittests/services/extract/ranges.ts index 9fd9bee8bebbe..c54760476ddb4 100644 --- a/src/testRunner/unittests/services/extract/ranges.ts +++ b/src/testRunner/unittests/services/extract/ranges.ts @@ -1,7 +1,7 @@ import * as ts from "../../../_namespaces/ts.js"; import { extractTest } from "./helpers.js"; -function testExtractRangeFailed(caption: string, s: string, expectedErrors: string[]) { +function testExtractRangeFailed(caption: string, s: string, expectedErrors: readonly string[]) { return it(caption, () => { const t = extractTest(s); const file = ts.createSourceFile("a.ts", t.source, ts.ScriptTarget.Latest, /*setParentNodes*/ true); @@ -12,7 +12,7 @@ function testExtractRangeFailed(caption: string, s: string, expectedErrors: stri const result = ts.refactor.extractSymbol.getRangeToExtract(file, ts.createTextSpanFromRange(selectionRange), /*invoked*/ false); assert(result.targetRange === undefined, "failure expected"); const sortedErrors = result.errors.map(e => e.messageText as string).sort(); - assert.deepEqual(sortedErrors, expectedErrors.sort(), "unexpected errors"); + assert.deepEqual(sortedErrors, expectedErrors.slice().sort(), "unexpected errors");
[ "+ * This is a heuristic to ignore cases where the mutating method appears to be", "+ return true;", "+ if (callee.parent.parent.type === \"ExpressionStatement\") return;", "+ const calleeObjType = getConstrainedTypeAtLocation(services, callee.object);", "+ context.report({ node: callee.property, messageId: \"noSideEffectUse\", data: { method } });", "+ node => check(node, method, toMethod),", "+ ]),", "+ allSpanInsets.sort((l, r) => r.pos - l.pos);", "- localRanges = localRanges.sort((a, b) => a.pos < b.pos ? -1 : a.pos === b.pos && a.end > b.end ? -1 : 1);", "+ toSorted,", "- logs.sort((a, b) => compareStringsCaseSensitive(a[0], b[0]))", "+ toSorted(logs, (a, b) => compareStringsCaseSensitive(a[0], b[0]))", "+ parsedNodes.sort(", "- return diags.sort((d1, d2) => d1.start - d2.start);" ]
[ 75, 84, 138, 141, 148, 163, 164, 187, 232, 245, 253, 254, 267, 332 ]
{ "additions": 153, "author": "jakebailey", "deletions": 19, "html_url": "https://github.com/microsoft/TypeScript/pull/59526", "issue_id": 59526, "merged_at": "2024-08-14T16:28:57Z", "omission_probability": 0.1, "pr_number": 59526, "repo": "microsoft/TypeScript", "title": "Add custom eslint rule 'no-array-mutating-method-expressions'", "total_changes": 172 }
87
diff --git a/src/services/refactors/moveToFile.ts b/src/services/refactors/moveToFile.ts index 6245fe4903dcc..18fd421d6d0ee 100644 --- a/src/services/refactors/moveToFile.ts +++ b/src/services/refactors/moveToFile.ts @@ -886,7 +886,7 @@ export function getUsageInfo(oldFile: SourceFile, toMove: readonly Statement[], const unusedImportsFromOldFile = new Set<Symbol>(); for (const statement of toMove) { forEachReference(statement, checker, enclosingRange, (symbol, isValidTypeOnlyUseSite) => { - if (!symbol.declarations) { + if (!some(symbol.declarations)) { return; } if (existingTargetLocals.has(skipAlias(symbol, checker))) { diff --git a/tests/cases/fourslash/moveToFile_undefined.ts b/tests/cases/fourslash/moveToFile_undefined.ts new file mode 100644 index 0000000000000..42ce03ec5abfe --- /dev/null +++ b/tests/cases/fourslash/moveToFile_undefined.ts @@ -0,0 +1,15 @@ +/// <reference path="fourslash.ts" /> + +// @module: esnext +// @moduleResolution: bundler + +// @Filename: /orig.ts +//// [|export const variable = undefined;|] + +verify.moveToFile({ + newFileContents: { + "/orig.ts": "", + "/new.ts": "export const variable = undefined;\n" + }, + interactiveRefactorArguments: { targetFile: "/new.ts" }, +});
diff --git a/src/services/refactors/moveToFile.ts b/src/services/refactors/moveToFile.ts index 6245fe4903dcc..18fd421d6d0ee 100644 --- a/src/services/refactors/moveToFile.ts +++ b/src/services/refactors/moveToFile.ts @@ -886,7 +886,7 @@ export function getUsageInfo(oldFile: SourceFile, toMove: readonly Statement[], const unusedImportsFromOldFile = new Set<Symbol>(); for (const statement of toMove) { forEachReference(statement, checker, enclosingRange, (symbol, isValidTypeOnlyUseSite) => { + if (!some(symbol.declarations)) { return; } if (existingTargetLocals.has(skipAlias(symbol, checker))) { diff --git a/tests/cases/fourslash/moveToFile_undefined.ts b/tests/cases/fourslash/moveToFile_undefined.ts new file mode 100644 index 0000000000000..42ce03ec5abfe --- /dev/null +++ b/tests/cases/fourslash/moveToFile_undefined.ts @@ -0,0 +1,15 @@ +// @module: esnext +// @moduleResolution: bundler +// @Filename: /orig.ts +//// [|export const variable = undefined;|] +verify.moveToFile({ + newFileContents: { + "/orig.ts": "", + "/new.ts": "export const variable = undefined;\n" + }, + interactiveRefactorArguments: { targetFile: "/new.ts" }, +});
[ "- if (!symbol.declarations) {", "+/// <reference path=\"fourslash.ts\" />" ]
[ 8, 19 ]
{ "additions": 16, "author": "andrewbranch", "deletions": 1, "html_url": "https://github.com/microsoft/TypeScript/pull/61084", "issue_id": 61084, "merged_at": "2025-01-30T21:49:26Z", "omission_probability": 0.1, "pr_number": 61084, "repo": "microsoft/TypeScript", "title": "[moveToFile] Fix symbols with empty `declarations` being treated as importable", "total_changes": 17 }
88
diff --git a/src/lib/dom.generated.d.ts b/src/lib/dom.generated.d.ts index a063538168562..edcb4aac24ff0 100644 --- a/src/lib/dom.generated.d.ts +++ b/src/lib/dom.generated.d.ts @@ -4854,11 +4854,23 @@ interface CSSStyleDeclaration { paddingTop: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/page) */ page: string; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/page-break-after) */ + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/page-break-after) + */ pageBreakAfter: string; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/page-break-before) */ + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/page-break-before) + */ pageBreakBefore: string; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/page-break-inside) */ + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/page-break-inside) + */ pageBreakInside: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/paint-order) */ paintOrder: string; @@ -5967,11 +5979,9 @@ interface CanvasRect { * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D) */ -interface CanvasRenderingContext2D extends CanvasCompositing, CanvasDrawImage, CanvasDrawPath, CanvasFillStrokeStyles, CanvasFilters, CanvasImageData, CanvasImageSmoothing, CanvasPath, CanvasPathDrawingStyles, CanvasRect, CanvasShadowStyles, CanvasState, CanvasText, CanvasTextDrawingStyles, CanvasTransform, CanvasUserInterface { +interface CanvasRenderingContext2D extends CanvasCompositing, CanvasDrawImage, CanvasDrawPath, CanvasFillStrokeStyles, CanvasFilters, CanvasImageData, CanvasImageSmoothing, CanvasPath, CanvasPathDrawingStyles, CanvasRect, CanvasSettings, CanvasShadowStyles, CanvasState, CanvasText, CanvasTextDrawingStyles, CanvasTransform, CanvasUserInterface { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/canvas) */ readonly canvas: HTMLCanvasElement; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/getContextAttributes) */ - getContextAttributes(): CanvasRenderingContext2DSettings; } declare var CanvasRenderingContext2D: { @@ -5979,6 +5989,11 @@ declare var CanvasRenderingContext2D: { new(): CanvasRenderingContext2D; }; +interface CanvasSettings { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/getContextAttributes) */ + getContextAttributes(): CanvasRenderingContext2DSettings; +} + interface CanvasShadowStyles { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/shadowBlur) */ shadowBlur: number; @@ -6684,7 +6699,9 @@ interface DOMMatrixReadOnly { readonly e: number; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly f: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/is2D) */ readonly is2D: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/isIdentity) */ readonly isIdentity: boolean; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m11: number; @@ -11439,7 +11456,7 @@ interface HTMLImageElement extends HTMLElement { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLImageElement/decoding) */ decoding: "async" | "sync" | "auto"; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLImageElement/fetchPriority) */ - fetchPriority: string; + fetchPriority: "high" | "low" | "auto"; /** * Sets or retrieves the height of the object. * @@ -11958,7 +11975,7 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLLinkElement/disabled) */ disabled: boolean; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLLinkElement/fetchPriority) */ - fetchPriority: string; + fetchPriority: "high" | "low" | "auto"; /** * Sets or retrieves a destination URL or an anchor point. * @@ -12430,7 +12447,11 @@ interface HTMLModElement extends HTMLElement { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLModElement/cite) */ cite: string; - /** Sets or retrieves the date and time of a modification to the object. */ + /** + * Sets or retrieves the date and time of a modification to the object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLModElement/dateTime) + */ dateTime: string; addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -13004,7 +13025,7 @@ interface HTMLScriptElement extends HTMLElement { */ event: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLScriptElement/fetchPriority) */ - fetchPriority: string; + fetchPriority: "high" | "low" | "auto"; /** * Sets or retrieves the object that is bound to the event script. * @deprecated @@ -15115,7 +15136,7 @@ interface ImageDecoder { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ImageDecoder/complete) */ readonly complete: boolean; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ImageDecoder/completed) */ - readonly completed: Promise<undefined>; + readonly completed: Promise<void>; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ImageDecoder/tracks) */ readonly tracks: ImageTrackList; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ImageDecoder/type) */ @@ -15157,7 +15178,7 @@ interface ImageTrackList { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ImageTrackList/length) */ readonly length: number; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ImageTrackList/ready) */ - readonly ready: Promise<undefined>; + readonly ready: Promise<void>; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ImageTrackList/selectedIndex) */ readonly selectedIndex: number; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ImageTrackList/selectedTrack) */ @@ -19612,7 +19633,7 @@ declare var ReadableStreamDefaultReader: { interface ReadableStreamGenericReader { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/closed) */ - readonly closed: Promise<undefined>; + readonly closed: Promise<void>; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/cancel) */ cancel(reason?: any): Promise<void>; } @@ -20186,8 +20207,11 @@ interface SVGAnimationElement extends SVGElement, SVGTests { endElement(): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGAnimationElement/endElementAt) */ endElementAt(offset: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGAnimationElement/getCurrentTime) */ getCurrentTime(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGAnimationElement/getSimpleDuration) */ getSimpleDuration(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGAnimationElement/getStartTime) */ getStartTime(): number; addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGAnimationElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -20868,8 +20892,11 @@ declare var SVGFEOffsetElement: { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGFEPointLightElement) */ interface SVGFEPointLightElement extends SVGElement { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGFEPointLightElement/x) */ readonly x: SVGAnimatedNumber; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGFEPointLightElement/y) */ readonly y: SVGAnimatedNumber; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGFEPointLightElement/z) */ readonly z: SVGAnimatedNumber; addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -20920,8 +20947,11 @@ interface SVGFESpotLightElement extends SVGElement { readonly pointsAtY: SVGAnimatedNumber; readonly pointsAtZ: SVGAnimatedNumber; readonly specularExponent: SVGAnimatedNumber; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGFESpotLightElement/x) */ readonly x: SVGAnimatedNumber; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGFESpotLightElement/y) */ readonly y: SVGAnimatedNumber; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGFESpotLightElement/z) */ readonly z: SVGAnimatedNumber; addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -24149,12 +24179,12 @@ declare var VideoPlaybackQuality: { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ViewTransition) */ interface ViewTransition { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ViewTransition/finished) */ - readonly finished: Promise<undefined>; + readonly finished: Promise<void>; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ViewTransition/ready) */ - readonly ready: Promise<undefined>; + readonly ready: Promise<void>; types: ViewTransitionTypeSet; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ViewTransition/updateCallbackDone) */ - readonly updateCallbackDone: Promise<undefined>; + readonly updateCallbackDone: Promise<void>; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ViewTransition/skipTransition) */ skipTransition(): void; } @@ -26745,7 +26775,7 @@ interface WebTransport { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebTransport/incomingUnidirectionalStreams) */ readonly incomingUnidirectionalStreams: ReadableStream; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebTransport/ready) */ - readonly ready: Promise<undefined>; + readonly ready: Promise<void>; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebTransport/close) */ close(closeInfo?: WebTransportCloseInfo): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebTransport/createBidirectionalStream) */ @@ -27259,8 +27289,6 @@ interface WindowSessionStorage { } interface WorkerEventMap extends AbstractWorkerEventMap, MessageEventTargetEventMap { - "message": MessageEvent; - "messageerror": MessageEvent; } /** @@ -27361,11 +27389,11 @@ declare var WritableStreamDefaultController: { */ interface WritableStreamDefaultWriter<W = any> { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */ - readonly closed: Promise<undefined>; + readonly closed: Promise<void>; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */ readonly desiredSize: number | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */ - readonly ready: Promise<undefined>; + readonly ready: Promise<void>; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */ abort(reason?: any): Promise<void>; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */ diff --git a/src/lib/webworker.generated.d.ts b/src/lib/webworker.generated.d.ts index c1a359205cec6..a462c72346f1a 100644 --- a/src/lib/webworker.generated.d.ts +++ b/src/lib/webworker.generated.d.ts @@ -274,7 +274,7 @@ interface ExtendableMessageEventInit extends ExtendableEventInit { interface FetchEventInit extends ExtendableEventInit { clientId?: string; - handled?: Promise<undefined>; + handled?: Promise<void>; preloadResponse?: Promise<any>; replacesClientId?: string; request: Request; @@ -2258,7 +2258,9 @@ interface DOMMatrixReadOnly { readonly e: number; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly f: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/is2D) */ readonly is2D: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/isIdentity) */ readonly isIdentity: boolean; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m11: number; @@ -2955,7 +2957,7 @@ interface FetchEvent extends ExtendableEvent { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/clientId) */ readonly clientId: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/handled) */ - readonly handled: Promise<undefined>; + readonly handled: Promise<void>; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/preloadResponse) */ readonly preloadResponse: Promise<any>; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */ @@ -4125,7 +4127,7 @@ interface ImageDecoder { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ImageDecoder/complete) */ readonly complete: boolean; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ImageDecoder/completed) */ - readonly completed: Promise<undefined>; + readonly completed: Promise<void>; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ImageDecoder/tracks) */ readonly tracks: ImageTrackList; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ImageDecoder/type) */ @@ -4167,7 +4169,7 @@ interface ImageTrackList { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ImageTrackList/length) */ readonly length: number; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ImageTrackList/ready) */ - readonly ready: Promise<undefined>; + readonly ready: Promise<void>; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ImageTrackList/selectedIndex) */ readonly selectedIndex: number; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ImageTrackList/selectedTrack) */ @@ -5351,7 +5353,7 @@ declare var ReadableStreamDefaultReader: { interface ReadableStreamGenericReader { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/closed) */ - readonly closed: Promise<undefined>; + readonly closed: Promise<void>; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/cancel) */ cancel(reason?: any): Promise<void>; } @@ -8779,7 +8781,7 @@ interface WebTransport { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebTransport/incomingUnidirectionalStreams) */ readonly incomingUnidirectionalStreams: ReadableStream; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebTransport/ready) */ - readonly ready: Promise<undefined>; + readonly ready: Promise<void>; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebTransport/close) */ close(closeInfo?: WebTransportCloseInfo): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebTransport/createBidirectionalStream) */ @@ -8920,8 +8922,6 @@ interface WindowOrWorkerGlobalScope { } interface WorkerEventMap extends AbstractWorkerEventMap, MessageEventTargetEventMap { - "message": MessageEvent; - "messageerror": MessageEvent; } /** @@ -9116,11 +9116,11 @@ declare var WritableStreamDefaultController: { */ interface WritableStreamDefaultWriter<W = any> { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */ - readonly closed: Promise<undefined>; + readonly closed: Promise<void>; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */ readonly desiredSize: number | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */ - readonly ready: Promise<undefined>; + readonly ready: Promise<void>; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */ abort(reason?: any): Promise<void>; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */
diff --git a/src/lib/dom.generated.d.ts b/src/lib/dom.generated.d.ts index a063538168562..edcb4aac24ff0 100644 --- a/src/lib/dom.generated.d.ts +++ b/src/lib/dom.generated.d.ts @@ -4854,11 +4854,23 @@ interface CSSStyleDeclaration { paddingTop: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/page) */ page: string; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/page-break-after) */ + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/page-break-after) pageBreakAfter: string; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/page-break-before) */ + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/page-break-before) pageBreakBefore: string; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/page-break-inside) */ + * [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/page-break-inside) pageBreakInside: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/paint-order) */ paintOrder: string; @@ -5967,11 +5979,9 @@ interface CanvasRect { * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D) -interface CanvasRenderingContext2D extends CanvasCompositing, CanvasDrawImage, CanvasDrawPath, CanvasFillStrokeStyles, CanvasFilters, CanvasImageData, CanvasImageSmoothing, CanvasPath, CanvasPathDrawingStyles, CanvasRect, CanvasShadowStyles, CanvasState, CanvasText, CanvasTextDrawingStyles, CanvasTransform, CanvasUserInterface { +interface CanvasRenderingContext2D extends CanvasCompositing, CanvasDrawImage, CanvasDrawPath, CanvasFillStrokeStyles, CanvasFilters, CanvasImageData, CanvasImageSmoothing, CanvasPath, CanvasPathDrawingStyles, CanvasRect, CanvasSettings, CanvasShadowStyles, CanvasState, CanvasText, CanvasTextDrawingStyles, CanvasTransform, CanvasUserInterface { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/canvas) */ readonly canvas: HTMLCanvasElement; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/getContextAttributes) */ - getContextAttributes(): CanvasRenderingContext2DSettings; declare var CanvasRenderingContext2D: { @@ -5979,6 +5989,11 @@ declare var CanvasRenderingContext2D: { new(): CanvasRenderingContext2D; }; +interface CanvasSettings { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/getContextAttributes) */ +} + interface CanvasShadowStyles { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/shadowBlur) */ shadowBlur: number; @@ -6684,7 +6699,9 @@ interface DOMMatrixReadOnly { @@ -11439,7 +11456,7 @@ interface HTMLImageElement extends HTMLElement { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLImageElement/decoding) */ decoding: "async" | "sync" | "auto"; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLImageElement/fetchPriority) */ * Sets or retrieves the height of the object. @@ -11958,7 +11975,7 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLLinkElement/disabled) */ disabled: boolean; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLLinkElement/fetchPriority) */ * Sets or retrieves a destination URL or an anchor point. @@ -12430,7 +12447,11 @@ interface HTMLModElement extends HTMLElement { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLModElement/cite) cite: string; - /** Sets or retrieves the date and time of a modification to the object. */ + * Sets or retrieves the date and time of a modification to the object. + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLModElement/dateTime) dateTime: string; addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLModElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -13004,7 +13025,7 @@ interface HTMLScriptElement extends HTMLElement { event: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLScriptElement/fetchPriority) */ * Sets or retrieves the object that is bound to the event script. * @deprecated @@ -15115,7 +15136,7 @@ interface ImageDecoder { @@ -15157,7 +15178,7 @@ interface ImageTrackList { @@ -19612,7 +19633,7 @@ declare var ReadableStreamDefaultReader: { @@ -20186,8 +20207,11 @@ interface SVGAnimationElement extends SVGElement, SVGTests { endElement(): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGAnimationElement/endElementAt) */ endElementAt(offset: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGAnimationElement/getCurrentTime) */ getCurrentTime(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGAnimationElement/getSimpleDuration) */ getSimpleDuration(): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGAnimationElement/getStartTime) */ getStartTime(): number; addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGAnimationElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -20868,8 +20892,11 @@ declare var SVGFEOffsetElement: { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGFEPointLightElement) interface SVGFEPointLightElement extends SVGElement { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGFEPointLightElement/x) */ + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGFEPointLightElement/y) */ addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGFEPointLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -20920,8 +20947,11 @@ interface SVGFESpotLightElement extends SVGElement { readonly pointsAtY: SVGAnimatedNumber; readonly pointsAtZ: SVGAnimatedNumber; readonly specularExponent: SVGAnimatedNumber; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGFESpotLightElement/x) */ + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGFESpotLightElement/y) */ addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGFESpotLightElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -24149,12 +24179,12 @@ declare var VideoPlaybackQuality: { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ViewTransition) */ interface ViewTransition { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ViewTransition/finished) */ + readonly finished: Promise<void>; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ViewTransition/ready) */ types: ViewTransitionTypeSet; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ViewTransition/updateCallbackDone) */ - readonly updateCallbackDone: Promise<undefined>; + readonly updateCallbackDone: Promise<void>; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ViewTransition/skipTransition) */ skipTransition(): void; @@ -26745,7 +26775,7 @@ interface WebTransport { @@ -27259,8 +27289,6 @@ interface WindowSessionStorage { @@ -27361,11 +27389,11 @@ declare var WritableStreamDefaultController: { diff --git a/src/lib/webworker.generated.d.ts b/src/lib/webworker.generated.d.ts index c1a359205cec6..a462c72346f1a 100644 --- a/src/lib/webworker.generated.d.ts +++ b/src/lib/webworker.generated.d.ts @@ -274,7 +274,7 @@ interface ExtendableMessageEventInit extends ExtendableEventInit { interface FetchEventInit extends ExtendableEventInit { clientId?: string; - handled?: Promise<undefined>; + handled?: Promise<void>; preloadResponse?: Promise<any>; replacesClientId?: string; request: Request; @@ -2258,7 +2258,9 @@ interface DOMMatrixReadOnly { @@ -2955,7 +2957,7 @@ interface FetchEvent extends ExtendableEvent { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/clientId) */ readonly clientId: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/handled) */ - readonly handled: Promise<undefined>; + readonly handled: Promise<void>; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/preloadResponse) */ readonly preloadResponse: Promise<any>; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */ @@ -4125,7 +4127,7 @@ interface ImageDecoder { @@ -4167,7 +4169,7 @@ interface ImageTrackList { @@ -5351,7 +5353,7 @@ declare var ReadableStreamDefaultReader: { @@ -8779,7 +8781,7 @@ interface WebTransport { @@ -8920,8 +8922,6 @@ interface WindowOrWorkerGlobalScope { @@ -9116,11 +9116,11 @@ declare var WritableStreamDefaultController: {
[ "+ getContextAttributes(): CanvasRenderingContext2DSettings;", "+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGFEPointLightElement/z) */", "+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGFESpotLightElement/z) */", "- readonly finished: Promise<undefined>;" ]
[ 50, 153, 165, 173 ]
{ "additions": 59, "author": "sandersn", "deletions": 31, "html_url": "https://github.com/microsoft/TypeScript/pull/61073", "issue_id": 61073, "merged_at": "2025-01-30T19:39:52Z", "omission_probability": 0.1, "pr_number": 61073, "repo": "microsoft/TypeScript", "title": "DOM update 2025/01/29", "total_changes": 90 }
89
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ded639b7a09cf..fcb93c45dc1dd 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -48156,7 +48156,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } if (moduleKind === ModuleKind.NodeNext && !isImportAttributes) { - return grammarErrorOnFirstToken(node, Diagnostics.Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_asserts); + return grammarErrorOnFirstToken(node, Diagnostics.Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_assert); } if (declaration.moduleSpecifier && getEmitSyntaxForModuleSpecifierExpression(declaration.moduleSpecifier) === ModuleKind.CommonJS) { diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index b6dc93964940d..0d7e0bb39a8d4 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -3983,7 +3983,7 @@ "category": "Error", "code": 2879 }, - "Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'.": { + "Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'.": { "category": "Error", "code": 2880 }, diff --git a/tests/baselines/reference/importAssertionNonstring.errors.txt b/tests/baselines/reference/importAssertionNonstring.errors.txt index 20df276c17cc0..a220b1f213eaa 100644 --- a/tests/baselines/reference/importAssertionNonstring.errors.txt +++ b/tests/baselines/reference/importAssertionNonstring.errors.txt @@ -1,33 +1,33 @@ -mod.mts(1,37): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +mod.mts(1,37): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. mod.mts(1,37): error TS2322: Type '{ field: 0; }' is not assignable to type 'ImportAttributes'. Property 'field' is incompatible with index signature. Type 'number' is not assignable to type 'string'. mod.mts(1,52): error TS2837: Import assertion values must be string literal expressions. -mod.mts(3,37): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +mod.mts(3,37): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. mod.mts(3,52): error TS2837: Import assertion values must be string literal expressions. -mod.mts(5,37): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +mod.mts(5,37): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. mod.mts(5,37): error TS2322: Type '{ field: RegExp; }' is not assignable to type 'ImportAttributes'. Property 'field' is incompatible with index signature. Type 'RegExp' is not assignable to type 'string'. mod.mts(5,52): error TS2837: Import assertion values must be string literal expressions. -mod.mts(7,37): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +mod.mts(7,37): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. mod.mts(7,37): error TS2322: Type '{ field: string[]; }' is not assignable to type 'ImportAttributes'. Property 'field' is incompatible with index signature. Type 'string[]' is not assignable to type 'string'. mod.mts(7,52): error TS2837: Import assertion values must be string literal expressions. -mod.mts(9,37): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +mod.mts(9,37): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. mod.mts(9,37): error TS2322: Type '{ field: { a: number; }; }' is not assignable to type 'ImportAttributes'. Property 'field' is incompatible with index signature. Type '{ a: number; }' is not assignable to type 'string'. mod.mts(9,52): error TS2837: Import assertion values must be string literal expressions. -mod.mts(11,37): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +mod.mts(11,37): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. mod.mts(11,66): error TS2837: Import assertion values must be string literal expressions. ==== mod.mts (16 errors) ==== import * as thing1 from "./mod.mjs" assert {field: 0}; ~~~~~~ -!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. ~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ field: 0; }' is not assignable to type 'ImportAttributes'. !!! error TS2322: Property 'field' is incompatible with index signature. @@ -37,13 +37,13 @@ mod.mts(11,66): error TS2837: Import assertion values must be string literal exp import * as thing2 from "./mod.mjs" assert {field: `a`}; ~~~~~~ -!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. ~~~ !!! error TS2837: Import assertion values must be string literal expressions. import * as thing3 from "./mod.mjs" assert {field: /a/g}; ~~~~~~ -!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. ~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ field: RegExp; }' is not assignable to type 'ImportAttributes'. !!! error TS2322: Property 'field' is incompatible with index signature. @@ -53,7 +53,7 @@ mod.mts(11,66): error TS2837: Import assertion values must be string literal exp import * as thing4 from "./mod.mjs" assert {field: ["a"]}; ~~~~~~ -!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. ~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ field: string[]; }' is not assignable to type 'ImportAttributes'. !!! error TS2322: Property 'field' is incompatible with index signature. @@ -63,7 +63,7 @@ mod.mts(11,66): error TS2837: Import assertion values must be string literal exp import * as thing5 from "./mod.mjs" assert {field: { a: 0 }}; ~~~~~~ -!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. ~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ field: { a: number; }; }' is not assignable to type 'ImportAttributes'. !!! error TS2322: Property 'field' is incompatible with index signature. @@ -73,6 +73,6 @@ mod.mts(11,66): error TS2837: Import assertion values must be string literal exp import * as thing6 from "./mod.mjs" assert {type: "json", field: 0..toString()} ~~~~~~ -!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. ~~~~~~~~~~~~~ !!! error TS2837: Import assertion values must be string literal expressions. \ No newline at end of file diff --git a/tests/baselines/reference/nodeModulesImportAssertions(module=nodenext).errors.txt b/tests/baselines/reference/nodeModulesImportAssertions(module=nodenext).errors.txt index 667a16dc4a59b..1b09957ba0b0d 100644 --- a/tests/baselines/reference/nodeModulesImportAssertions(module=nodenext).errors.txt +++ b/tests/baselines/reference/nodeModulesImportAssertions(module=nodenext).errors.txt @@ -1,15 +1,15 @@ -index.ts(1,35): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. -otherc.cts(1,35): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +index.ts(1,35): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. +otherc.cts(1,35): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. ==== index.ts (1 errors) ==== import json from "./package.json" assert { type: "json" }; ~~~~~~ -!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. ==== otherc.cts (1 errors) ==== import json from "./package.json" assert { type: "json" }; // should error, cjs mode imports don't support assertions ~~~~~~ -!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. const json2 = import("./package.json", { assert: { type: "json" } }); // should be fine ==== package.json (0 errors) ==== { diff --git a/tests/baselines/reference/nodeModulesImportModeDeclarationEmit1(module=nodenext).errors.txt b/tests/baselines/reference/nodeModulesImportModeDeclarationEmit1(module=nodenext).errors.txt index 85d78cd955097..d2c0a64f66744 100644 --- a/tests/baselines/reference/nodeModulesImportModeDeclarationEmit1(module=nodenext).errors.txt +++ b/tests/baselines/reference/nodeModulesImportModeDeclarationEmit1(module=nodenext).errors.txt @@ -1,6 +1,6 @@ -/index.ts(6,50): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +/index.ts(6,50): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. /index.ts(7,14): error TS2305: Module '"pkg"' has no exported member 'ImportInterface'. -/index.ts(7,49): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +/index.ts(7,49): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. ==== /index.ts (3 errors) ==== @@ -11,12 +11,12 @@ import {type RequireInterface as Req} from "pkg" assert { "resolution-mode": "require" }; ~~~~~~ -!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. import {type ImportInterface as Imp} from "pkg" assert { "resolution-mode": "import" }; ~~~~~~~~~~~~~~~ !!! error TS2305: Module '"pkg"' has no exported member 'ImportInterface'. ~~~~~~ -!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. export interface Loc extends Req, Imp {} export type { RequireInterface } from "pkg" assert { "resolution-mode": "require" }; diff --git a/tests/baselines/reference/nodeModulesImportModeDeclarationEmit2(module=nodenext).errors.txt b/tests/baselines/reference/nodeModulesImportModeDeclarationEmit2(module=nodenext).errors.txt index c9a427dbbfe63..77b7ff5cd3914 100644 --- a/tests/baselines/reference/nodeModulesImportModeDeclarationEmit2(module=nodenext).errors.txt +++ b/tests/baselines/reference/nodeModulesImportModeDeclarationEmit2(module=nodenext).errors.txt @@ -1,6 +1,6 @@ /index.ts(6,14): error TS2305: Module '"pkg"' has no exported member 'RequireInterface'. -/index.ts(6,50): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. -/index.ts(7,49): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +/index.ts(6,50): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. +/index.ts(7,49): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. ==== /index.ts (3 errors) ==== @@ -13,10 +13,10 @@ ~~~~~~~~~~~~~~~~ !!! error TS2305: Module '"pkg"' has no exported member 'RequireInterface'. ~~~~~~ -!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. import {type ImportInterface as Imp} from "pkg" assert { "resolution-mode": "import" }; ~~~~~~ -!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. export interface Loc extends Req, Imp {} export type { RequireInterface } from "pkg" assert { "resolution-mode": "require" }; diff --git a/tests/baselines/reference/nodeModulesImportModeDeclarationEmitErrors1(module=nodenext).errors.txt b/tests/baselines/reference/nodeModulesImportModeDeclarationEmitErrors1(module=nodenext).errors.txt index dbb1ccdb5af49..11d577b0ea7d6 100644 --- a/tests/baselines/reference/nodeModulesImportModeDeclarationEmitErrors1(module=nodenext).errors.txt +++ b/tests/baselines/reference/nodeModulesImportModeDeclarationEmitErrors1(module=nodenext).errors.txt @@ -1,15 +1,15 @@ -/index.ts(2,45): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +/index.ts(2,45): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. /index.ts(2,73): error TS1453: `resolution-mode` should be either `require` or `import`. /index.ts(4,10): error TS2305: Module '"pkg"' has no exported member 'ImportInterface'. -/index.ts(4,39): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. -/index.ts(6,76): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +/index.ts(4,39): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. +/index.ts(6,76): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. ==== /index.ts (5 errors) ==== // incorrect mode import type { RequireInterface } from "pkg" assert { "resolution-mode": "foobar" }; ~~~~~~ -!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. ~~~~~~~~ !!! error TS1453: `resolution-mode` should be either `require` or `import`. // not type-only @@ -17,11 +17,11 @@ ~~~~~~~~~~~~~~~ !!! error TS2305: Module '"pkg"' has no exported member 'ImportInterface'. ~~~~~~ -!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. // not exclusively type-only import {type RequireInterface as Req, RequireInterface as Req2} from "pkg" assert { "resolution-mode": "require" }; ~~~~~~ -!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +!!! error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. export interface LocalInterface extends RequireInterface, ImportInterface {}
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ded639b7a09cf..fcb93c45dc1dd 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -48156,7 +48156,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (moduleKind === ModuleKind.NodeNext && !isImportAttributes) { - return grammarErrorOnFirstToken(node, Diagnostics.Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_asserts); + return grammarErrorOnFirstToken(node, Diagnostics.Import_assertions_have_been_replaced_by_import_attributes_Use_with_instead_of_assert); if (declaration.moduleSpecifier && getEmitSyntaxForModuleSpecifierExpression(declaration.moduleSpecifier) === ModuleKind.CommonJS) { diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index b6dc93964940d..0d7e0bb39a8d4 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -3983,7 +3983,7 @@ "code": 2879 - "Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'.": { + "Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'.": { "code": 2880 diff --git a/tests/baselines/reference/importAssertionNonstring.errors.txt b/tests/baselines/reference/importAssertionNonstring.errors.txt index 20df276c17cc0..a220b1f213eaa 100644 --- a/tests/baselines/reference/importAssertionNonstring.errors.txt +++ b/tests/baselines/reference/importAssertionNonstring.errors.txt @@ -1,33 +1,33 @@ -mod.mts(1,37): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +mod.mts(1,37): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. mod.mts(1,37): error TS2322: Type '{ field: 0; }' is not assignable to type 'ImportAttributes'. Type 'number' is not assignable to type 'string'. mod.mts(1,52): error TS2837: Import assertion values must be string literal expressions. -mod.mts(3,37): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +mod.mts(3,37): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. mod.mts(3,52): error TS2837: Import assertion values must be string literal expressions. +mod.mts(5,37): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. mod.mts(5,37): error TS2322: Type '{ field: RegExp; }' is not assignable to type 'ImportAttributes'. Type 'RegExp' is not assignable to type 'string'. mod.mts(5,52): error TS2837: Import assertion values must be string literal expressions. -mod.mts(7,37): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +mod.mts(7,37): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. mod.mts(7,37): error TS2322: Type '{ field: string[]; }' is not assignable to type 'ImportAttributes'. Type 'string[]' is not assignable to type 'string'. mod.mts(7,52): error TS2837: Import assertion values must be string literal expressions. -mod.mts(9,37): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +mod.mts(9,37): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. mod.mts(9,37): error TS2322: Type '{ field: { a: number; }; }' is not assignable to type 'ImportAttributes'. Type '{ a: number; }' is not assignable to type 'string'. mod.mts(9,52): error TS2837: Import assertion values must be string literal expressions. -mod.mts(11,37): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +mod.mts(11,37): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. mod.mts(11,66): error TS2837: Import assertion values must be string literal expressions. ==== mod.mts (16 errors) ==== import * as thing1 from "./mod.mjs" assert {field: 0}; ~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ field: 0; }' is not assignable to type 'ImportAttributes'. @@ -37,13 +37,13 @@ mod.mts(11,66): error TS2837: Import assertion values must be string literal exp import * as thing2 from "./mod.mjs" assert {field: `a`}; ~~~ import * as thing3 from "./mod.mjs" assert {field: /a/g}; ~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ field: RegExp; }' is not assignable to type 'ImportAttributes'. @@ -53,7 +53,7 @@ mod.mts(11,66): error TS2837: Import assertion values must be string literal exp import * as thing4 from "./mod.mjs" assert {field: ["a"]}; ~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ field: string[]; }' is not assignable to type 'ImportAttributes'. @@ -63,7 +63,7 @@ mod.mts(11,66): error TS2837: Import assertion values must be string literal exp import * as thing5 from "./mod.mjs" assert {field: { a: 0 }}; ~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ field: { a: number; }; }' is not assignable to type 'ImportAttributes'. @@ -73,6 +73,6 @@ mod.mts(11,66): error TS2837: Import assertion values must be string literal exp import * as thing6 from "./mod.mjs" assert {type: "json", field: 0..toString()} ~~~~~~~~~~~~~ \ No newline at end of file diff --git a/tests/baselines/reference/nodeModulesImportAssertions(module=nodenext).errors.txt b/tests/baselines/reference/nodeModulesImportAssertions(module=nodenext).errors.txt index 667a16dc4a59b..1b09957ba0b0d 100644 --- a/tests/baselines/reference/nodeModulesImportAssertions(module=nodenext).errors.txt +++ b/tests/baselines/reference/nodeModulesImportAssertions(module=nodenext).errors.txt -index.ts(1,35): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. -otherc.cts(1,35): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +index.ts(1,35): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. ==== index.ts (1 errors) ==== import json from "./package.json" assert { type: "json" }; ==== otherc.cts (1 errors) ==== import json from "./package.json" assert { type: "json" }; // should error, cjs mode imports don't support assertions const json2 = import("./package.json", { assert: { type: "json" } }); // should be fine ==== package.json (0 errors) ==== { diff --git a/tests/baselines/reference/nodeModulesImportModeDeclarationEmit1(module=nodenext).errors.txt b/tests/baselines/reference/nodeModulesImportModeDeclarationEmit1(module=nodenext).errors.txt index 85d78cd955097..d2c0a64f66744 100644 --- a/tests/baselines/reference/nodeModulesImportModeDeclarationEmit1(module=nodenext).errors.txt +++ b/tests/baselines/reference/nodeModulesImportModeDeclarationEmit1(module=nodenext).errors.txt /index.ts(7,14): error TS2305: Module '"pkg"' has no exported member 'ImportInterface'. @@ -11,12 +11,12 @@ import {type RequireInterface as Req} from "pkg" assert { "resolution-mode": "require" }; ~~~~~~~~~~~~~~~ diff --git a/tests/baselines/reference/nodeModulesImportModeDeclarationEmit2(module=nodenext).errors.txt b/tests/baselines/reference/nodeModulesImportModeDeclarationEmit2(module=nodenext).errors.txt index c9a427dbbfe63..77b7ff5cd3914 100644 --- a/tests/baselines/reference/nodeModulesImportModeDeclarationEmit2(module=nodenext).errors.txt +++ b/tests/baselines/reference/nodeModulesImportModeDeclarationEmit2(module=nodenext).errors.txt /index.ts(6,14): error TS2305: Module '"pkg"' has no exported member 'RequireInterface'. @@ -13,10 +13,10 @@ ~~~~~~~~~~~~~~~~ !!! error TS2305: Module '"pkg"' has no exported member 'RequireInterface'. diff --git a/tests/baselines/reference/nodeModulesImportModeDeclarationEmitErrors1(module=nodenext).errors.txt b/tests/baselines/reference/nodeModulesImportModeDeclarationEmitErrors1(module=nodenext).errors.txt index dbb1ccdb5af49..11d577b0ea7d6 100644 --- a/tests/baselines/reference/nodeModulesImportModeDeclarationEmitErrors1(module=nodenext).errors.txt +++ b/tests/baselines/reference/nodeModulesImportModeDeclarationEmitErrors1(module=nodenext).errors.txt +/index.ts(2,45): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. /index.ts(2,73): error TS1453: `resolution-mode` should be either `require` or `import`. /index.ts(4,10): error TS2305: Module '"pkg"' has no exported member 'ImportInterface'. -/index.ts(4,39): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. -/index.ts(6,76): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'. +/index.ts(4,39): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. +/index.ts(6,76): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'. ==== /index.ts (5 errors) ==== // incorrect mode import type { RequireInterface } from "pkg" assert { "resolution-mode": "foobar" }; ~~~~~~ ~~~~~~~~ !!! error TS1453: `resolution-mode` should be either `require` or `import`. // not type-only @@ -17,11 +17,11 @@ ~~~~~~~~~~~~~~~ ~~~~~~ // not exclusively type-only import {type RequireInterface as Req, RequireInterface as Req2} from "pkg" assert { "resolution-mode": "require" }; ~~~~~~ export interface LocalInterface extends RequireInterface, ImportInterface {}
[ "-mod.mts(5,37): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'.", "+otherc.cts(1,35): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'assert'.", "-/index.ts(2,45): error TS2880: Import assertions have been replaced by import attributes. Use 'with' instead of 'asserts'." ]
[ 40, 122, 197 ]
{ "additions": 32, "author": "DanielRosenwasser", "deletions": 32, "html_url": "https://github.com/microsoft/TypeScript/pull/61066", "issue_id": 61066, "merged_at": "2025-01-28T22:42:35Z", "omission_probability": 0.1, "pr_number": 61066, "repo": "microsoft/TypeScript", "title": "Fix error message incorrectly referencing 'asserts' instead of 'assert'.", "total_changes": 64 }
90
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e771cc8234f96..45874e1fa4c76 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -95,7 +95,7 @@ jobs: name: coverage path: coverage - - uses: codecov/codecov-action@1e68e06f1dbfde0e4cefc87efeba9e4643565303 # v5.1.2 + - uses: codecov/codecov-action@13ce06bfc6bbe3ecf90edbbf1bc32fe5978ca1d3 # v5.3.1 with: use_oidc: ${{ !(github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork) }} disable_search: true diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index e0aef479f0815..dee604efcb1c8 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -46,7 +46,7 @@ jobs: # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@b6a472f63d85b9c78a3ac5e89422239fc15e9b3c # v3.28.1 + uses: github/codeql-action/init@f6091c0113d1dcf9b98e269ee48e8a7e51b7bdd4 # v3.28.5 with: config-file: ./.github/codeql/codeql-configuration.yml # Override language selection by uncommenting this and choosing your languages @@ -56,7 +56,7 @@ jobs: # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below). - name: Autobuild - uses: github/codeql-action/autobuild@b6a472f63d85b9c78a3ac5e89422239fc15e9b3c # v3.28.1 + uses: github/codeql-action/autobuild@f6091c0113d1dcf9b98e269ee48e8a7e51b7bdd4 # v3.28.5 # ℹ️ Command-line programs to run using the OS shell. # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun @@ -70,4 +70,4 @@ jobs: # make release - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@b6a472f63d85b9c78a3ac5e89422239fc15e9b3c # v3.28.1 + uses: github/codeql-action/analyze@f6091c0113d1dcf9b98e269ee48e8a7e51b7bdd4 # v3.28.5 diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml index 253495c24edc1..b96a9ab144281 100644 --- a/.github/workflows/scorecard.yml +++ b/.github/workflows/scorecard.yml @@ -55,6 +55,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: 'Upload to code-scanning' - uses: github/codeql-action/upload-sarif@b6a472f63d85b9c78a3ac5e89422239fc15e9b3c # v3.28.1 + uses: github/codeql-action/upload-sarif@f6091c0113d1dcf9b98e269ee48e8a7e51b7bdd4 # v3.28.5 with: sarif_file: results.sarif
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e771cc8234f96..45874e1fa4c76 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -95,7 +95,7 @@ jobs: name: coverage path: coverage - - uses: codecov/codecov-action@1e68e06f1dbfde0e4cefc87efeba9e4643565303 # v5.1.2 + - uses: codecov/codecov-action@13ce06bfc6bbe3ecf90edbbf1bc32fe5978ca1d3 # v5.3.1 use_oidc: ${{ !(github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork) }} disable_search: true diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index e0aef479f0815..dee604efcb1c8 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -46,7 +46,7 @@ jobs: # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL + uses: github/codeql-action/init@f6091c0113d1dcf9b98e269ee48e8a7e51b7bdd4 # v3.28.5 config-file: ./.github/codeql/codeql-configuration.yml # Override language selection by uncommenting this and choosing your languages @@ -56,7 +56,7 @@ jobs: # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below). - name: Autobuild - uses: github/codeql-action/autobuild@b6a472f63d85b9c78a3ac5e89422239fc15e9b3c # v3.28.1 + uses: github/codeql-action/autobuild@f6091c0113d1dcf9b98e269ee48e8a7e51b7bdd4 # v3.28.5 # ℹ️ Command-line programs to run using the OS shell. # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun @@ -70,4 +70,4 @@ jobs: # make release - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@b6a472f63d85b9c78a3ac5e89422239fc15e9b3c # v3.28.1 + uses: github/codeql-action/analyze@f6091c0113d1dcf9b98e269ee48e8a7e51b7bdd4 # v3.28.5 diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml index 253495c24edc1..b96a9ab144281 100644 --- a/.github/workflows/scorecard.yml +++ b/.github/workflows/scorecard.yml @@ -55,6 +55,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: 'Upload to code-scanning' - uses: github/codeql-action/upload-sarif@b6a472f63d85b9c78a3ac5e89422239fc15e9b3c # v3.28.1 + uses: github/codeql-action/upload-sarif@f6091c0113d1dcf9b98e269ee48e8a7e51b7bdd4 # v3.28.5 sarif_file: results.sarif
[ "- uses: github/codeql-action/init@b6a472f63d85b9c78a3ac5e89422239fc15e9b3c # v3.28.1" ]
[ 21 ]
{ "additions": 5, "author": "dependabot[bot]", "deletions": 5, "html_url": "https://github.com/microsoft/TypeScript/pull/61055", "issue_id": 61055, "merged_at": "2025-01-27T15:54:45Z", "omission_probability": 0.1, "pr_number": 61055, "repo": "microsoft/TypeScript", "title": "Bump the github-actions group with 2 updates", "total_changes": 10 }
91
diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 96fad44852c62..03b307ff393cd 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -1511,10 +1511,14 @@ export function createProgram(createProgramOptions: CreateProgramOptions): Progr * @returns A 'Program' object. */ export function createProgram(rootNames: readonly string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: readonly Diagnostic[]): Program; -export function createProgram(rootNamesOrOptions: readonly string[] | CreateProgramOptions, _options?: CompilerOptions, _host?: CompilerHost, _oldProgram?: Program, _configFileParsingDiagnostics?: readonly Diagnostic[]): Program { - const createProgramOptions = isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options!, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217 - const { rootNames, options, configFileParsingDiagnostics, projectReferences, typeScriptVersion } = createProgramOptions; - let { oldProgram } = createProgramOptions; +export function createProgram(_rootNamesOrOptions: readonly string[] | CreateProgramOptions, _options?: CompilerOptions, _host?: CompilerHost, _oldProgram?: Program, _configFileParsingDiagnostics?: readonly Diagnostic[]): Program { + let _createProgramOptions = isArray(_rootNamesOrOptions) ? createCreateProgramOptions(_rootNamesOrOptions, _options!, _host, _oldProgram, _configFileParsingDiagnostics) : _rootNamesOrOptions; // TODO: GH#18217 + const { rootNames, options, configFileParsingDiagnostics, projectReferences, typeScriptVersion, host: createProgramOptionsHost } = _createProgramOptions; + let { oldProgram } = _createProgramOptions; + // Stop referencing these objects to ensure GC collects them. + _createProgramOptions = undefined!; + _rootNamesOrOptions = undefined!; + for (const option of commandLineOptionOfCustomType) { if (hasProperty(options, option.name)) { if (typeof options[option.name] === "string") { @@ -1569,7 +1573,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg tracing?.push(tracing.Phase.Program, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true); performance.mark("beforeProgram"); - const host = createProgramOptions.host || createCompilerHost(options); + const host = createProgramOptionsHost || createCompilerHost(options); const configParsingHost = parseConfigHostFromCompilerHostLike(host); let skipDefaultLib = options.noLib;
diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 96fad44852c62..03b307ff393cd 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -1511,10 +1511,14 @@ export function createProgram(createProgramOptions: CreateProgramOptions): Progr * @returns A 'Program' object. */ export function createProgram(rootNames: readonly string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: readonly Diagnostic[]): Program; - const createProgramOptions = isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options!, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217 - const { rootNames, options, configFileParsingDiagnostics, projectReferences, typeScriptVersion } = createProgramOptions; - let { oldProgram } = createProgramOptions; +export function createProgram(_rootNamesOrOptions: readonly string[] | CreateProgramOptions, _options?: CompilerOptions, _host?: CompilerHost, _oldProgram?: Program, _configFileParsingDiagnostics?: readonly Diagnostic[]): Program { + let _createProgramOptions = isArray(_rootNamesOrOptions) ? createCreateProgramOptions(_rootNamesOrOptions, _options!, _host, _oldProgram, _configFileParsingDiagnostics) : _rootNamesOrOptions; // TODO: GH#18217 + const { rootNames, options, configFileParsingDiagnostics, projectReferences, typeScriptVersion, host: createProgramOptionsHost } = _createProgramOptions; + let { oldProgram } = _createProgramOptions; + // Stop referencing these objects to ensure GC collects them. + _createProgramOptions = undefined!; + _rootNamesOrOptions = undefined!; + for (const option of commandLineOptionOfCustomType) { if (hasProperty(options, option.name)) { if (typeof options[option.name] === "string") { @@ -1569,7 +1573,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg tracing?.push(tracing.Phase.Program, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true); performance.mark("beforeProgram"); - const host = createProgramOptions.host || createCompilerHost(options); + const host = createProgramOptionsHost || createCompilerHost(options); const configParsingHost = parseConfigHostFromCompilerHostLike(host); let skipDefaultLib = options.noLib;
[ "-export function createProgram(rootNamesOrOptions: readonly string[] | CreateProgramOptions, _options?: CompilerOptions, _host?: CompilerHost, _oldProgram?: Program, _configFileParsingDiagnostics?: readonly Diagnostic[]): Program {" ]
[ 8 ]
{ "additions": 9, "author": "jakebailey", "deletions": 5, "html_url": "https://github.com/microsoft/TypeScript/pull/61034", "issue_id": 61034, "merged_at": "2025-01-23T23:05:21Z", "omission_probability": 0.1, "pr_number": 61034, "repo": "microsoft/TypeScript", "title": "Ensure createProgram stops referencing rootNamesOrOptions to ensure oldProgram is GC'd", "total_changes": 14 }
92
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 04facba3196e7..87eb3126eed50 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -27181,7 +27181,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return target.kind === SyntaxKind.SuperKeyword; case SyntaxKind.NonNullExpression: case SyntaxKind.ParenthesizedExpression: - return isMatchingReference((source as NonNullExpression | ParenthesizedExpression).expression, target); + case SyntaxKind.SatisfiesExpression: + return isMatchingReference((source as NonNullExpression | ParenthesizedExpression | SatisfiesExpression).expression, target); case SyntaxKind.PropertyAccessExpression: case SyntaxKind.ElementAccessExpression: const sourcePropertyName = getAccessedPropertyName(source as AccessExpression); @@ -29532,7 +29533,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return narrowTypeByCallExpression(type, expr as CallExpression, assumeTrue); case SyntaxKind.ParenthesizedExpression: case SyntaxKind.NonNullExpression: - return narrowType(type, (expr as ParenthesizedExpression | NonNullExpression).expression, assumeTrue); + case SyntaxKind.SatisfiesExpression: + return narrowType(type, (expr as ParenthesizedExpression | NonNullExpression | SatisfiesExpression).expression, assumeTrue); case SyntaxKind.BinaryExpression: return narrowTypeByBinaryExpression(type, expr as BinaryExpression, assumeTrue); case SyntaxKind.PrefixUnaryExpression: diff --git a/tests/baselines/reference/inferTypePredicates.errors.txt b/tests/baselines/reference/inferTypePredicates.errors.txt index 6a955c7cb0671..9701d6aeed82f 100644 --- a/tests/baselines/reference/inferTypePredicates.errors.txt +++ b/tests/baselines/reference/inferTypePredicates.errors.txt @@ -333,4 +333,14 @@ inferTypePredicates.ts(205,7): error TS2741: Property 'z' is missing in type 'C1 if (foobarPred(foobar)) { foobar.foo; } + + // https://github.com/microsoft/TypeScript/issues/60778 + const arrTest: Array<number> = [1, 2, null, 3].filter( + (x) => (x != null) satisfies boolean, + ); + + function isEmptyString(x: unknown) { + const rv = x === ""; + return rv satisfies boolean; + } \ No newline at end of file diff --git a/tests/baselines/reference/inferTypePredicates.js b/tests/baselines/reference/inferTypePredicates.js index 315652eec06d0..725c3eb6b0b34 100644 --- a/tests/baselines/reference/inferTypePredicates.js +++ b/tests/baselines/reference/inferTypePredicates.js @@ -279,6 +279,16 @@ const foobarPred = (fb: typeof foobar) => fb.type === "foo"; if (foobarPred(foobar)) { foobar.foo; } + +// https://github.com/microsoft/TypeScript/issues/60778 +const arrTest: Array<number> = [1, 2, null, 3].filter( + (x) => (x != null) satisfies boolean, +); + +function isEmptyString(x: unknown) { + const rv = x === ""; + return rv satisfies boolean; +} //// [inferTypePredicates.js] @@ -538,6 +548,12 @@ var foobarPred = function (fb) { return fb.type === "foo"; }; if (foobarPred(foobar)) { foobar.foo; } +// https://github.com/microsoft/TypeScript/issues/60778 +var arrTest = [1, 2, null, 3].filter(function (x) { return (x != null); }); +function isEmptyString(x) { + var rv = x === ""; + return rv; +} //// [inferTypePredicates.d.ts] @@ -630,3 +646,5 @@ declare const foobarPred: (fb: typeof foobar) => fb is { type: "foo"; foo: number; }; +declare const arrTest: Array<number>; +declare function isEmptyString(x: unknown): x is ""; diff --git a/tests/baselines/reference/inferTypePredicates.symbols b/tests/baselines/reference/inferTypePredicates.symbols index 8fd879787c205..aec451e86fd4b 100644 --- a/tests/baselines/reference/inferTypePredicates.symbols +++ b/tests/baselines/reference/inferTypePredicates.symbols @@ -777,3 +777,28 @@ if (foobarPred(foobar)) { >foo : Symbol(foo, Decl(inferTypePredicates.ts, 271, 18)) } +// https://github.com/microsoft/TypeScript/issues/60778 +const arrTest: Array<number> = [1, 2, null, 3].filter( +>arrTest : Symbol(arrTest, Decl(inferTypePredicates.ts, 280, 5)) +>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>[1, 2, null, 3].filter : Symbol(Array.filter, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>filter : Symbol(Array.filter, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + + (x) => (x != null) satisfies boolean, +>x : Symbol(x, Decl(inferTypePredicates.ts, 281, 3)) +>x : Symbol(x, Decl(inferTypePredicates.ts, 281, 3)) + +); + +function isEmptyString(x: unknown) { +>isEmptyString : Symbol(isEmptyString, Decl(inferTypePredicates.ts, 282, 2)) +>x : Symbol(x, Decl(inferTypePredicates.ts, 284, 23)) + + const rv = x === ""; +>rv : Symbol(rv, Decl(inferTypePredicates.ts, 285, 7)) +>x : Symbol(x, Decl(inferTypePredicates.ts, 284, 23)) + + return rv satisfies boolean; +>rv : Symbol(rv, Decl(inferTypePredicates.ts, 285, 7)) +} + diff --git a/tests/baselines/reference/inferTypePredicates.types b/tests/baselines/reference/inferTypePredicates.types index e604e593a0e2f..326617e83ba05 100644 --- a/tests/baselines/reference/inferTypePredicates.types +++ b/tests/baselines/reference/inferTypePredicates.types @@ -1649,3 +1649,61 @@ if (foobarPred(foobar)) { > : ^^^^^^ } +// https://github.com/microsoft/TypeScript/issues/60778 +const arrTest: Array<number> = [1, 2, null, 3].filter( +>arrTest : number[] +> : ^^^^^^^^ +>[1, 2, null, 3].filter( (x) => (x != null) satisfies boolean,) : number[] +> : ^^^^^^^^ +>[1, 2, null, 3].filter : { <S extends number | null>(predicate: (value: number | null, index: number, array: (number | null)[]) => value is S, thisArg?: any): S[]; (predicate: (value: number | null, index: number, array: (number | null)[]) => unknown, thisArg?: any): (number | null)[]; } +> : ^^^ ^^^^^^^^^^^^^^^^^^^^^^^^ ^^^ ^^^^^^^^^^^^^^^^^ ^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^ ^^^^^^^^^ ^^^ ^^^^^^^^^^^^^^^^^ ^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^ ^^ ^^^ ^^^^^^^^^^^^^^^^^^^^^^^ +>[1, 2, null, 3] : (number | null)[] +> : ^^^^^^^^^^^^^^^^^ +>1 : 1 +> : ^ +>2 : 2 +> : ^ +>3 : 3 +> : ^ +>filter : { <S extends number | null>(predicate: (value: number | null, index: number, array: (number | null)[]) => value is S, thisArg?: any): S[]; (predicate: (value: number | null, index: number, array: (number | null)[]) => unknown, thisArg?: any): (number | null)[]; } +> : ^^^ ^^^^^^^^^^^^^^^^^^^^^^^^ ^^^ ^^^^^^^^^^^^^^^^^ ^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^ ^^^^^^^^^ ^^^ ^^^^^^^^^^^^^^^^^ ^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^ ^^ ^^^ ^^^^^^^^^^^^^^^^^^^^^^^ + + (x) => (x != null) satisfies boolean, +>(x) => (x != null) satisfies boolean : (x: number | null) => x is number +> : ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +>x : number | null +> : ^^^^^^^^^^^^^ +>(x != null) satisfies boolean : boolean +> : ^^^^^^^ +>(x != null) : boolean +> : ^^^^^^^ +>x != null : boolean +> : ^^^^^^^ +>x : number | null +> : ^^^^^^^^^^^^^ + +); + +function isEmptyString(x: unknown) { +>isEmptyString : (x: unknown) => x is "" +> : ^ ^^ ^^^^^^^^^^^^ +>x : unknown +> : ^^^^^^^ + + const rv = x === ""; +>rv : boolean +> : ^^^^^^^ +>x === "" : boolean +> : ^^^^^^^ +>x : unknown +> : ^^^^^^^ +>"" : "" +> : ^^ + + return rv satisfies boolean; +>rv satisfies boolean : boolean +> : ^^^^^^^ +>rv : boolean +> : ^^^^^^^ +} + diff --git a/tests/cases/compiler/inferTypePredicates.ts b/tests/cases/compiler/inferTypePredicates.ts index 9b996ee8c8414..bb8e6132f4279 100644 --- a/tests/cases/compiler/inferTypePredicates.ts +++ b/tests/cases/compiler/inferTypePredicates.ts @@ -279,3 +279,13 @@ const foobarPred = (fb: typeof foobar) => fb.type === "foo"; if (foobarPred(foobar)) { foobar.foo; } + +// https://github.com/microsoft/TypeScript/issues/60778 +const arrTest: Array<number> = [1, 2, null, 3].filter( + (x) => (x != null) satisfies boolean, +); + +function isEmptyString(x: unknown) { + const rv = x === ""; + return rv satisfies boolean; +}
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 04facba3196e7..87eb3126eed50 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -27181,7 +27181,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return target.kind === SyntaxKind.SuperKeyword; case SyntaxKind.NonNullExpression: case SyntaxKind.ParenthesizedExpression: - return isMatchingReference((source as NonNullExpression | ParenthesizedExpression).expression, target); + case SyntaxKind.SatisfiesExpression: + return isMatchingReference((source as NonNullExpression | ParenthesizedExpression | SatisfiesExpression).expression, target); case SyntaxKind.PropertyAccessExpression: case SyntaxKind.ElementAccessExpression: const sourcePropertyName = getAccessedPropertyName(source as AccessExpression); @@ -29532,7 +29533,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { return narrowTypeByCallExpression(type, expr as CallExpression, assumeTrue); case SyntaxKind.ParenthesizedExpression: case SyntaxKind.NonNullExpression: - return narrowType(type, (expr as ParenthesizedExpression | NonNullExpression).expression, assumeTrue); + case SyntaxKind.SatisfiesExpression: + return narrowType(type, (expr as ParenthesizedExpression | NonNullExpression | SatisfiesExpression).expression, assumeTrue); case SyntaxKind.BinaryExpression: return narrowTypeByBinaryExpression(type, expr as BinaryExpression, assumeTrue); case SyntaxKind.PrefixUnaryExpression: diff --git a/tests/baselines/reference/inferTypePredicates.errors.txt b/tests/baselines/reference/inferTypePredicates.errors.txt index 6a955c7cb0671..9701d6aeed82f 100644 --- a/tests/baselines/reference/inferTypePredicates.errors.txt +++ b/tests/baselines/reference/inferTypePredicates.errors.txt @@ -333,4 +333,14 @@ inferTypePredicates.ts(205,7): error TS2741: Property 'z' is missing in type 'C1 if (foobarPred(foobar)) { foobar.foo; } + // https://github.com/microsoft/TypeScript/issues/60778 + const arrTest: Array<number> = [1, 2, null, 3].filter( + (x) => (x != null) satisfies boolean, + ); + function isEmptyString(x: unknown) { + return rv satisfies boolean; + } \ No newline at end of file diff --git a/tests/baselines/reference/inferTypePredicates.js b/tests/baselines/reference/inferTypePredicates.js index 315652eec06d0..725c3eb6b0b34 100644 --- a/tests/baselines/reference/inferTypePredicates.js +++ b/tests/baselines/reference/inferTypePredicates.js @@ -279,6 +279,16 @@ const foobarPred = (fb: typeof foobar) => fb.type === "foo"; //// [inferTypePredicates.js] @@ -538,6 +548,12 @@ var foobarPred = function (fb) { return fb.type === "foo"; }; foobar.foo; +var arrTest = [1, 2, null, 3].filter(function (x) { return (x != null); }); +function isEmptyString(x) { + var rv = x === ""; + return rv; //// [inferTypePredicates.d.ts] @@ -630,3 +646,5 @@ declare const foobarPred: (fb: typeof foobar) => fb is { type: "foo"; foo: number; }; +declare const arrTest: Array<number>; +declare function isEmptyString(x: unknown): x is ""; diff --git a/tests/baselines/reference/inferTypePredicates.symbols b/tests/baselines/reference/inferTypePredicates.symbols index 8fd879787c205..aec451e86fd4b 100644 --- a/tests/baselines/reference/inferTypePredicates.symbols +++ b/tests/baselines/reference/inferTypePredicates.symbols @@ -777,3 +777,28 @@ if (foobarPred(foobar)) { >foo : Symbol(foo, Decl(inferTypePredicates.ts, 271, 18)) +>arrTest : Symbol(arrTest, Decl(inferTypePredicates.ts, 280, 5)) +>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>[1, 2, null, 3].filter : Symbol(Array.filter, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>filter : Symbol(Array.filter, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>isEmptyString : Symbol(isEmptyString, Decl(inferTypePredicates.ts, 282, 2)) diff --git a/tests/baselines/reference/inferTypePredicates.types b/tests/baselines/reference/inferTypePredicates.types index e604e593a0e2f..326617e83ba05 100644 --- a/tests/baselines/reference/inferTypePredicates.types +++ b/tests/baselines/reference/inferTypePredicates.types @@ -1649,3 +1649,61 @@ if (foobarPred(foobar)) { > : ^^^^^^ +>arrTest : number[] +> : ^^^^^^^^ +>[1, 2, null, 3].filter( (x) => (x != null) satisfies boolean,) : number[] +> : ^^^^^^^^ +>[1, 2, null, 3].filter : { <S extends number | null>(predicate: (value: number | null, index: number, array: (number | null)[]) => value is S, thisArg?: any): S[]; (predicate: (value: number | null, index: number, array: (number | null)[]) => unknown, thisArg?: any): (number | null)[]; } +> : ^^^ ^^^^^^^^^^^^^^^^^^^^^^^^ ^^^ ^^^^^^^^^^^^^^^^^ ^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^ ^^^^^^^^^ ^^^ ^^^^^^^^^^^^^^^^^ ^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^ ^^ ^^^ ^^^^^^^^^^^^^^^^^^^^^^^ +> : ^^^^^^^^^^^^^^^^^ +>1 : 1 +>2 : 2 +>3 : 3 +>filter : { <S extends number | null>(predicate: (value: number | null, index: number, array: (number | null)[]) => value is S, thisArg?: any): S[]; (predicate: (value: number | null, index: number, array: (number | null)[]) => unknown, thisArg?: any): (number | null)[]; } +> : ^^^ ^^^^^^^^^^^^^^^^^^^^^^^^ ^^^ ^^^^^^^^^^^^^^^^^ ^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^ ^^^^^^^^^ ^^^ ^^^^^^^^^^^^^^^^^ ^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^ ^^ ^^^ ^^^^^^^^^^^^^^^^^^^^^^^ +> : ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +>(x != null) satisfies boolean : boolean +> : ^^^^^^^ +>(x != null) : boolean +> : ^^^^^^^ +>x != null : boolean +> : ^^^^^^^ +>isEmptyString : (x: unknown) => x is "" +> : ^ ^^ ^^^^^^^^^^^^ +>x === "" : boolean +> : ^^^^^^^ +>"" : "" +> : ^^ +>rv satisfies boolean : boolean +> : ^^^^^^^ diff --git a/tests/cases/compiler/inferTypePredicates.ts b/tests/cases/compiler/inferTypePredicates.ts index 9b996ee8c8414..bb8e6132f4279 100644 --- a/tests/cases/compiler/inferTypePredicates.ts +++ b/tests/cases/compiler/inferTypePredicates.ts @@ -279,3 +279,13 @@ const foobarPred = (fb: typeof foobar) => fb.type === "foo";
[ "+ const rv = x === \"\";", "+>[1, 2, null, 3] : (number | null)[]", "+>(x) => (x != null) satisfies boolean : (x: number | null) => x is number" ]
[ 39, 133, 145 ]
{ "additions": 125, "author": "Andarist", "deletions": 2, "html_url": "https://github.com/microsoft/TypeScript/pull/60782", "issue_id": 60782, "merged_at": "2025-01-22T21:44:58Z", "omission_probability": 0.1, "pr_number": 60782, "repo": "microsoft/TypeScript", "title": "Narrow types by satisfies expressions", "total_changes": 127 }
93
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 80b61edd3657a..abb22eb40a9c8 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -16683,6 +16683,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case "Number": checkNoTypeArguments(node); return numberType; + case "BigInt": + checkNoTypeArguments(node); + return bigintType; case "Boolean": checkNoTypeArguments(node); return booleanType; diff --git a/tests/baselines/reference/checkJsdocTypeTag8.symbols b/tests/baselines/reference/checkJsdocTypeTag8.symbols new file mode 100644 index 0000000000000..edc4f7401d4ca --- /dev/null +++ b/tests/baselines/reference/checkJsdocTypeTag8.symbols @@ -0,0 +1,16 @@ +//// [tests/cases/conformance/jsdoc/checkJsdocTypeTag8.ts] //// + +=== index.js === +// https://github.com/microsoft/TypeScript/issues/57953 + +/** + * @param {Number|BigInt} n + */ +function isLessThanFive(n) { +>isLessThanFive : Symbol(isLessThanFive, Decl(index.js, 0, 0)) +>n : Symbol(n, Decl(index.js, 5, 24)) + + return n < 5; +>n : Symbol(n, Decl(index.js, 5, 24)) +} + diff --git a/tests/baselines/reference/checkJsdocTypeTag8.types b/tests/baselines/reference/checkJsdocTypeTag8.types new file mode 100644 index 0000000000000..7c5dd272dfda8 --- /dev/null +++ b/tests/baselines/reference/checkJsdocTypeTag8.types @@ -0,0 +1,23 @@ +//// [tests/cases/conformance/jsdoc/checkJsdocTypeTag8.ts] //// + +=== index.js === +// https://github.com/microsoft/TypeScript/issues/57953 + +/** + * @param {Number|BigInt} n + */ +function isLessThanFive(n) { +>isLessThanFive : (n: number | bigint) => boolean +> : ^ ^^^^^^^^ ^^^^^^^^^^^^^^^^^^ +>n : number | bigint +> : ^^^^^^^^^^^^^^^ + + return n < 5; +>n < 5 : boolean +> : ^^^^^^^ +>n : number | bigint +> : ^^^^^^^^^^^^^^^ +>5 : 5 +> : ^ +} + diff --git a/tests/baselines/reference/jsdocTypeTag.js b/tests/baselines/reference/jsdocTypeTag.js index 394fb5a53da01..77d7aacba2b63 100644 --- a/tests/baselines/reference/jsdocTypeTag.js +++ b/tests/baselines/reference/jsdocTypeTag.js @@ -13,6 +13,12 @@ var N; /** @type {number} */ var n; +/** @type {BigInt} */ +var BI; + +/** @type {bigint} */ +var bi; + /** @type {Boolean} */ var B; @@ -74,6 +80,8 @@ var N: number; var n: number var B: boolean; var b: boolean; +var BI: bigint; +var bi: bigint; var V :void; var v: void; var U: undefined; @@ -101,6 +109,10 @@ var s; var N; /** @type {number} */ var n; +/** @type {BigInt} */ +var BI; +/** @type {bigint} */ +var bi; /** @type {Boolean} */ var B; /** @type {boolean} */ @@ -144,6 +156,8 @@ var N; var n; var B; var b; +var BI; +var bi; var V; var v; var U; diff --git a/tests/baselines/reference/jsdocTypeTag.symbols b/tests/baselines/reference/jsdocTypeTag.symbols index dda8d0bc9010b..8cffdb59036b5 100644 --- a/tests/baselines/reference/jsdocTypeTag.symbols +++ b/tests/baselines/reference/jsdocTypeTag.symbols @@ -17,77 +17,85 @@ var N; var n; >n : Symbol(n, Decl(a.js, 10, 3), Decl(b.ts, 3, 3)) +/** @type {BigInt} */ +var BI; +>BI : Symbol(BI, Decl(a.js, 13, 3), Decl(b.ts, 6, 3)) + +/** @type {bigint} */ +var bi; +>bi : Symbol(bi, Decl(a.js, 16, 3), Decl(b.ts, 7, 3)) + /** @type {Boolean} */ var B; ->B : Symbol(B, Decl(a.js, 13, 3), Decl(b.ts, 4, 3)) +>B : Symbol(B, Decl(a.js, 19, 3), Decl(b.ts, 4, 3)) /** @type {boolean} */ var b; ->b : Symbol(b, Decl(a.js, 16, 3), Decl(b.ts, 5, 3)) +>b : Symbol(b, Decl(a.js, 22, 3), Decl(b.ts, 5, 3)) /** @type {Void} */ var V; ->V : Symbol(V, Decl(a.js, 19, 3), Decl(b.ts, 6, 3)) +>V : Symbol(V, Decl(a.js, 25, 3), Decl(b.ts, 8, 3)) /** @type {void} */ var v; ->v : Symbol(v, Decl(a.js, 22, 3), Decl(b.ts, 7, 3)) +>v : Symbol(v, Decl(a.js, 28, 3), Decl(b.ts, 9, 3)) /** @type {Undefined} */ var U; ->U : Symbol(U, Decl(a.js, 25, 3), Decl(b.ts, 8, 3)) +>U : Symbol(U, Decl(a.js, 31, 3), Decl(b.ts, 10, 3)) /** @type {undefined} */ var u; ->u : Symbol(u, Decl(a.js, 28, 3), Decl(b.ts, 9, 3)) +>u : Symbol(u, Decl(a.js, 34, 3), Decl(b.ts, 11, 3)) /** @type {Null} */ var Nl; ->Nl : Symbol(Nl, Decl(a.js, 31, 3), Decl(b.ts, 10, 3)) +>Nl : Symbol(Nl, Decl(a.js, 37, 3), Decl(b.ts, 12, 3)) /** @type {null} */ var nl; ->nl : Symbol(nl, Decl(a.js, 34, 3), Decl(b.ts, 11, 3)) +>nl : Symbol(nl, Decl(a.js, 40, 3), Decl(b.ts, 13, 3)) /** @type {Array} */ var A; ->A : Symbol(A, Decl(a.js, 37, 3), Decl(b.ts, 12, 3)) +>A : Symbol(A, Decl(a.js, 43, 3), Decl(b.ts, 14, 3)) /** @type {array} */ var a; ->a : Symbol(a, Decl(a.js, 40, 3), Decl(b.ts, 13, 3)) +>a : Symbol(a, Decl(a.js, 46, 3), Decl(b.ts, 15, 3)) /** @type {Promise} */ var P; ->P : Symbol(P, Decl(a.js, 43, 3), Decl(b.ts, 14, 3)) +>P : Symbol(P, Decl(a.js, 49, 3), Decl(b.ts, 16, 3)) /** @type {promise} */ var p; ->p : Symbol(p, Decl(a.js, 46, 3), Decl(b.ts, 15, 3)) +>p : Symbol(p, Decl(a.js, 52, 3), Decl(b.ts, 17, 3)) /** @type {?number} */ var nullable; ->nullable : Symbol(nullable, Decl(a.js, 49, 3), Decl(b.ts, 16, 3)) +>nullable : Symbol(nullable, Decl(a.js, 55, 3), Decl(b.ts, 18, 3)) /** @type {Object} */ var Obj; ->Obj : Symbol(Obj, Decl(a.js, 52, 3), Decl(b.ts, 17, 3)) +>Obj : Symbol(Obj, Decl(a.js, 58, 3), Decl(b.ts, 19, 3)) /** @type {object} */ var obj; ->obj : Symbol(obj, Decl(a.js, 55, 3), Decl(b.ts, 18, 3)) +>obj : Symbol(obj, Decl(a.js, 61, 3), Decl(b.ts, 20, 3)) /** @type {Function} */ var Func; ->Func : Symbol(Func, Decl(a.js, 58, 3), Decl(b.ts, 19, 3)) +>Func : Symbol(Func, Decl(a.js, 64, 3), Decl(b.ts, 21, 3)) /** @type {(s: string) => number} */ var f; ->f : Symbol(f, Decl(a.js, 61, 3), Decl(b.ts, 20, 3)) +>f : Symbol(f, Decl(a.js, 67, 3), Decl(b.ts, 22, 3)) /** @type {new (s: string) => { s: string }} */ var ctor; ->ctor : Symbol(ctor, Decl(a.js, 64, 3), Decl(b.ts, 21, 3)) +>ctor : Symbol(ctor, Decl(a.js, 70, 3), Decl(b.ts, 23, 3)) === b.ts === var S: string; @@ -103,62 +111,68 @@ var n: number >n : Symbol(n, Decl(a.js, 10, 3), Decl(b.ts, 3, 3)) var B: boolean; ->B : Symbol(B, Decl(a.js, 13, 3), Decl(b.ts, 4, 3)) +>B : Symbol(B, Decl(a.js, 19, 3), Decl(b.ts, 4, 3)) var b: boolean; ->b : Symbol(b, Decl(a.js, 16, 3), Decl(b.ts, 5, 3)) +>b : Symbol(b, Decl(a.js, 22, 3), Decl(b.ts, 5, 3)) + +var BI: bigint; +>BI : Symbol(BI, Decl(a.js, 13, 3), Decl(b.ts, 6, 3)) + +var bi: bigint; +>bi : Symbol(bi, Decl(a.js, 16, 3), Decl(b.ts, 7, 3)) var V :void; ->V : Symbol(V, Decl(a.js, 19, 3), Decl(b.ts, 6, 3)) +>V : Symbol(V, Decl(a.js, 25, 3), Decl(b.ts, 8, 3)) var v: void; ->v : Symbol(v, Decl(a.js, 22, 3), Decl(b.ts, 7, 3)) +>v : Symbol(v, Decl(a.js, 28, 3), Decl(b.ts, 9, 3)) var U: undefined; ->U : Symbol(U, Decl(a.js, 25, 3), Decl(b.ts, 8, 3)) +>U : Symbol(U, Decl(a.js, 31, 3), Decl(b.ts, 10, 3)) var u: undefined; ->u : Symbol(u, Decl(a.js, 28, 3), Decl(b.ts, 9, 3)) +>u : Symbol(u, Decl(a.js, 34, 3), Decl(b.ts, 11, 3)) var Nl: null; ->Nl : Symbol(Nl, Decl(a.js, 31, 3), Decl(b.ts, 10, 3)) +>Nl : Symbol(Nl, Decl(a.js, 37, 3), Decl(b.ts, 12, 3)) var nl: null; ->nl : Symbol(nl, Decl(a.js, 34, 3), Decl(b.ts, 11, 3)) +>nl : Symbol(nl, Decl(a.js, 40, 3), Decl(b.ts, 13, 3)) var A: any[]; ->A : Symbol(A, Decl(a.js, 37, 3), Decl(b.ts, 12, 3)) +>A : Symbol(A, Decl(a.js, 43, 3), Decl(b.ts, 14, 3)) var a: any[]; ->a : Symbol(a, Decl(a.js, 40, 3), Decl(b.ts, 13, 3)) +>a : Symbol(a, Decl(a.js, 46, 3), Decl(b.ts, 15, 3)) var P: Promise<any>; ->P : Symbol(P, Decl(a.js, 43, 3), Decl(b.ts, 14, 3)) ->Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --)) +>P : Symbol(P, Decl(a.js, 49, 3), Decl(b.ts, 16, 3)) +>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2018.promise.d.ts, --, --)) var p: Promise<any>; ->p : Symbol(p, Decl(a.js, 46, 3), Decl(b.ts, 15, 3)) ->Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --)) +>p : Symbol(p, Decl(a.js, 52, 3), Decl(b.ts, 17, 3)) +>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2018.promise.d.ts, --, --)) var nullable: number | null; ->nullable : Symbol(nullable, Decl(a.js, 49, 3), Decl(b.ts, 16, 3)) +>nullable : Symbol(nullable, Decl(a.js, 55, 3), Decl(b.ts, 18, 3)) var Obj: any; ->Obj : Symbol(Obj, Decl(a.js, 52, 3), Decl(b.ts, 17, 3)) +>Obj : Symbol(Obj, Decl(a.js, 58, 3), Decl(b.ts, 19, 3)) var obj: any; ->obj : Symbol(obj, Decl(a.js, 55, 3), Decl(b.ts, 18, 3)) +>obj : Symbol(obj, Decl(a.js, 61, 3), Decl(b.ts, 20, 3)) var Func: Function; ->Func : Symbol(Func, Decl(a.js, 58, 3), Decl(b.ts, 19, 3)) ->Function : Symbol(Function, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>Func : Symbol(Func, Decl(a.js, 64, 3), Decl(b.ts, 21, 3)) +>Function : Symbol(Function, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.decorators.d.ts, --, --)) var f: (s: string) => number; ->f : Symbol(f, Decl(a.js, 61, 3), Decl(b.ts, 20, 3)) ->s : Symbol(s, Decl(b.ts, 20, 8)) +>f : Symbol(f, Decl(a.js, 67, 3), Decl(b.ts, 22, 3)) +>s : Symbol(s, Decl(b.ts, 22, 8)) var ctor: new (s: string) => { s: string }; ->ctor : Symbol(ctor, Decl(a.js, 64, 3), Decl(b.ts, 21, 3)) ->s : Symbol(s, Decl(b.ts, 21, 15)) ->s : Symbol(s, Decl(b.ts, 21, 30)) +>ctor : Symbol(ctor, Decl(a.js, 70, 3), Decl(b.ts, 23, 3)) +>s : Symbol(s, Decl(b.ts, 23, 15)) +>s : Symbol(s, Decl(b.ts, 23, 30)) diff --git a/tests/baselines/reference/jsdocTypeTag.types b/tests/baselines/reference/jsdocTypeTag.types index 10a42dee45c51..6a44a3d13447e 100644 --- a/tests/baselines/reference/jsdocTypeTag.types +++ b/tests/baselines/reference/jsdocTypeTag.types @@ -21,6 +21,16 @@ var n; >n : number > : ^^^^^^ +/** @type {BigInt} */ +var BI; +>BI : bigint +> : ^^^^^^ + +/** @type {bigint} */ +var bi; +>bi : bigint +> : ^^^^^^ + /** @type {Boolean} */ var B; >B : boolean @@ -134,6 +144,14 @@ var b: boolean; >b : boolean > : ^^^^^^^ +var BI: bigint; +>BI : bigint +> : ^^^^^^ + +var bi: bigint; +>bi : bigint +> : ^^^^^^ + var V :void; >V : void > : ^^^^ diff --git a/tests/cases/conformance/jsdoc/checkJsdocTypeTag8.ts b/tests/cases/conformance/jsdoc/checkJsdocTypeTag8.ts new file mode 100644 index 0000000000000..1a0dd4298b8c9 --- /dev/null +++ b/tests/cases/conformance/jsdoc/checkJsdocTypeTag8.ts @@ -0,0 +1,15 @@ +// @strict: true +// @allowJs: true +// @checkJs: true +// @noEmit: true + +// @filename: index.js + +// https://github.com/microsoft/TypeScript/issues/57953 + +/** + * @param {Number|BigInt} n + */ +function isLessThanFive(n) { + return n < 5; +} diff --git a/tests/cases/conformance/jsdoc/jsdocTypeTag.ts b/tests/cases/conformance/jsdoc/jsdocTypeTag.ts index b5fdd397fa765..2bf326acd740d 100644 --- a/tests/cases/conformance/jsdoc/jsdocTypeTag.ts +++ b/tests/cases/conformance/jsdoc/jsdocTypeTag.ts @@ -1,4 +1,5 @@ // @allowJS: true +// @target: esnext // @suppressOutputPathCheck: true // @strictNullChecks: true @@ -15,6 +16,12 @@ var N; /** @type {number} */ var n; +/** @type {BigInt} */ +var BI; + +/** @type {bigint} */ +var bi; + /** @type {Boolean} */ var B; @@ -76,6 +83,8 @@ var N: number; var n: number var B: boolean; var b: boolean; +var BI: bigint; +var bi: bigint; var V :void; var v: void; var U: undefined;
diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 80b61edd3657a..abb22eb40a9c8 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -16683,6 +16683,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { case "Number": return numberType; + case "BigInt": + checkNoTypeArguments(node); + return bigintType; case "Boolean": return booleanType; diff --git a/tests/baselines/reference/checkJsdocTypeTag8.symbols b/tests/baselines/reference/checkJsdocTypeTag8.symbols index 0000000000000..edc4f7401d4ca +++ b/tests/baselines/reference/checkJsdocTypeTag8.symbols @@ -0,0 +1,16 @@ +>isLessThanFive : Symbol(isLessThanFive, Decl(index.js, 0, 0)) diff --git a/tests/baselines/reference/checkJsdocTypeTag8.types b/tests/baselines/reference/checkJsdocTypeTag8.types index 0000000000000..7c5dd272dfda8 +++ b/tests/baselines/reference/checkJsdocTypeTag8.types @@ -0,0 +1,23 @@ +>isLessThanFive : (n: number | bigint) => boolean +> : ^ ^^^^^^^^ ^^^^^^^^^^^^^^^^^^ +>n < 5 : boolean +> : ^^^^^^^ +>5 : 5 +> : ^ diff --git a/tests/baselines/reference/jsdocTypeTag.js b/tests/baselines/reference/jsdocTypeTag.js index 394fb5a53da01..77d7aacba2b63 100644 --- a/tests/baselines/reference/jsdocTypeTag.js +++ b/tests/baselines/reference/jsdocTypeTag.js @@ -13,6 +13,12 @@ var N; @@ -74,6 +80,8 @@ var N: number; @@ -101,6 +109,10 @@ var s; var N; @@ -144,6 +156,8 @@ var N; diff --git a/tests/baselines/reference/jsdocTypeTag.symbols b/tests/baselines/reference/jsdocTypeTag.symbols index dda8d0bc9010b..8cffdb59036b5 100644 --- a/tests/baselines/reference/jsdocTypeTag.symbols +++ b/tests/baselines/reference/jsdocTypeTag.symbols @@ -17,77 +17,85 @@ var N; /** @type {Void} */ /** @type {void} */ /** @type {Undefined} */ /** @type {undefined} */ var u; /** @type {Null} */ var Nl; /** @type {null} */ var nl; /** @type {Array} */ var A; /** @type {array} */ var a; /** @type {Promise} */ var P; /** @type {promise} */ var p; /** @type {?number} */ var nullable; /** @type {Object} */ var Obj; /** @type {object} */ var obj; /** @type {Function} */ var Func; /** @type {(s: string) => number} */ var f; /** @type {new (s: string) => { s: string }} */ var ctor; === b.ts === var S: string; @@ -103,62 +111,68 @@ var n: number var u: undefined; var Nl: null; var nl: null; var A: any[]; var a: any[]; var P: Promise<any>; var p: Promise<any>; var nullable: number | null; var Obj: any; var obj: any; var Func: Function; ->Function : Symbol(Function, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>Function : Symbol(Function, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.decorators.d.ts, --, --)) var f: (s: string) => number; ->s : Symbol(s, Decl(b.ts, 20, 8)) var ctor: new (s: string) => { s: string }; ->s : Symbol(s, Decl(b.ts, 21, 15)) +>s : Symbol(s, Decl(b.ts, 23, 15)) +>s : Symbol(s, Decl(b.ts, 23, 30)) diff --git a/tests/baselines/reference/jsdocTypeTag.types b/tests/baselines/reference/jsdocTypeTag.types index 10a42dee45c51..6a44a3d13447e 100644 --- a/tests/baselines/reference/jsdocTypeTag.types +++ b/tests/baselines/reference/jsdocTypeTag.types @@ -21,6 +21,16 @@ var n; >n : number > : ^^^^^^ >B : boolean @@ -134,6 +144,14 @@ var b: boolean; >b : boolean > : ^^^^^^^ >V : void > : ^^^^ diff --git a/tests/cases/conformance/jsdoc/checkJsdocTypeTag8.ts b/tests/cases/conformance/jsdoc/checkJsdocTypeTag8.ts index 0000000000000..1a0dd4298b8c9 +++ b/tests/cases/conformance/jsdoc/checkJsdocTypeTag8.ts @@ -0,0 +1,15 @@ +// @strict: true +// @allowJs: true +// @checkJs: true +// @noEmit: true +// @filename: index.js diff --git a/tests/cases/conformance/jsdoc/jsdocTypeTag.ts b/tests/cases/conformance/jsdoc/jsdocTypeTag.ts index b5fdd397fa765..2bf326acd740d 100644 --- a/tests/cases/conformance/jsdoc/jsdocTypeTag.ts +++ b/tests/cases/conformance/jsdoc/jsdocTypeTag.ts @@ -1,4 +1,5 @@ // @allowJS: true +// @target: esnext // @suppressOutputPathCheck: true // @strictNullChecks: true @@ -15,6 +16,12 @@ var N; @@ -76,6 +83,8 @@ var N: number;
[ "+>s : Symbol(s, Decl(b.ts, 22, 8))", "->s : Symbol(s, Decl(b.ts, 21, 30))" ]
[ 302, 307 ]
{ "additions": 154, "author": "Andarist", "deletions": 42, "html_url": "https://github.com/microsoft/TypeScript/pull/60863", "issue_id": 60863, "merged_at": "2025-01-22T16:33:01Z", "omission_probability": 0.1, "pr_number": 60863, "repo": "microsoft/TypeScript", "title": "Treat `BigInt` type references in JSDoc as intended `bigint`s", "total_changes": 196 }
94
diff --git a/src/compiler/transformers/declarations/diagnostics.ts b/src/compiler/transformers/declarations/diagnostics.ts index 84e952da136df..873f23cbf7987 100644 --- a/src/compiler/transformers/declarations/diagnostics.ts +++ b/src/compiler/transformers/declarations/diagnostics.ts @@ -767,7 +767,7 @@ export function createGetIsolatedDeclarationErrors(resolver: EmitResolver): (nod if (isSetAccessor(node.parent)) { return createAccessorTypeError(node.parent); } - const addUndefined = resolver.requiresAddingImplicitUndefined(node, /*enclosingDeclaration*/ undefined); + const addUndefined = resolver.requiresAddingImplicitUndefined(node, node.parent); if (!addUndefined && node.initializer) { return createExpressionError(node.initializer); } diff --git a/tests/baselines/reference/transpile/declarationFunctionDeclarations.d.ts b/tests/baselines/reference/transpile/declarationFunctionDeclarations.d.ts index 7814e7759fa75..af1cb8016aab5 100644 --- a/tests/baselines/reference/transpile/declarationFunctionDeclarations.d.ts +++ b/tests/baselines/reference/transpile/declarationFunctionDeclarations.d.ts @@ -45,6 +45,14 @@ export class InClassMethodOk1 { o(array: number[] = [], rParam: string): void { export class InClassMethodOk2 { o(array: T | undefined = [], rParam: string): void { } }; export class InClassMethodBad { o(array: T = [], rParam: string): void { } }; +// https://github.com/microsoft/TypeScript/issues/60976 +class Bar {} +export class ClsWithRequiredInitializedParameter { + constructor( + private arr: Bar = new Bar(), + private bool: boolean, + ) {} +} //// [fnDecl.d.ts] //// type T = number[]; export declare function fnDeclBasic1(p: number[] | string[] | [T] | undefined, rParam: string): void; @@ -121,6 +129,13 @@ export declare class InClassMethodOk2 { export declare class InClassMethodBad { o(array: T | undefined, rParam: string): void; } +declare class Bar { +} +export declare class ClsWithRequiredInitializedParameter { + private arr; + private bool; + constructor(arr: Bar | undefined, bool: boolean); +} export {}; @@ -134,9 +149,10 @@ fnDecl.ts(32,45): error TS9025: Declaration emit for this parameter requires imp fnDecl.ts(37,47): error TS9025: Declaration emit for this parameter requires implicitly adding undefined to its type. This is not supported with --isolatedDeclarations. fnDecl.ts(41,37): error TS9025: Declaration emit for this parameter requires implicitly adding undefined to its type. This is not supported with --isolatedDeclarations. fnDecl.ts(45,35): error TS9025: Declaration emit for this parameter requires implicitly adding undefined to its type. This is not supported with --isolatedDeclarations. +fnDecl.ts(51,5): error TS9025: Declaration emit for this parameter requires implicitly adding undefined to its type. This is not supported with --isolatedDeclarations. -==== fnDecl.ts (9 errors) ==== +==== fnDecl.ts (10 errors) ==== type T = number[] export function fnDeclBasic1(p: number[] | string[] | [T] = [], rParam: string): void { }; export function fnDeclBasic2(p: (n: T) => T = () => null!, rParam: string): void { }; @@ -210,4 +226,14 @@ fnDecl.ts(45,35): error TS9025: Declaration emit for this parameter requires imp !!! error TS9025: Declaration emit for this parameter requires implicitly adding undefined to its type. This is not supported with --isolatedDeclarations. !!! related TS9028 fnDecl.ts:45:35: Add a type annotation to the parameter array. - + // https://github.com/microsoft/TypeScript/issues/60976 + class Bar {} + export class ClsWithRequiredInitializedParameter { + constructor( + private arr: Bar = new Bar(), + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS9025: Declaration emit for this parameter requires implicitly adding undefined to its type. This is not supported with --isolatedDeclarations. +!!! related TS9028 fnDecl.ts:51:5: Add a type annotation to the parameter arr. + private bool: boolean, + ) {} + } diff --git a/tests/baselines/reference/transpile/declarationFunctionDeclarations.js b/tests/baselines/reference/transpile/declarationFunctionDeclarations.js index 72ba57ff249ed..0e32cdf3471f0 100644 --- a/tests/baselines/reference/transpile/declarationFunctionDeclarations.js +++ b/tests/baselines/reference/transpile/declarationFunctionDeclarations.js @@ -45,6 +45,14 @@ export class InClassMethodOk1 { o(array: number[] = [], rParam: string): void { export class InClassMethodOk2 { o(array: T | undefined = [], rParam: string): void { } }; export class InClassMethodBad { o(array: T = [], rParam: string): void { } }; +// https://github.com/microsoft/TypeScript/issues/60976 +class Bar {} +export class ClsWithRequiredInitializedParameter { + constructor( + private arr: Bar = new Bar(), + private bool: boolean, + ) {} +} //// [fnDecl.js] //// export function fnDeclBasic1(p = [], rParam) { } ; @@ -118,3 +126,14 @@ export class InClassMethodBad { o(array = [], rParam) { } } ; +// https://github.com/microsoft/TypeScript/issues/60976 +class Bar { +} +export class ClsWithRequiredInitializedParameter { + arr; + bool; + constructor(arr = new Bar(), bool) { + this.arr = arr; + this.bool = bool; + } +} diff --git a/tests/cases/transpile/declarationFunctionDeclarations.ts b/tests/cases/transpile/declarationFunctionDeclarations.ts index 5aa0c50d4f8d9..7d9d8c82e2711 100644 --- a/tests/cases/transpile/declarationFunctionDeclarations.ts +++ b/tests/cases/transpile/declarationFunctionDeclarations.ts @@ -49,3 +49,11 @@ export class InClassMethodOk1 { o(array: number[] = [], rParam: string): void { export class InClassMethodOk2 { o(array: T | undefined = [], rParam: string): void { } }; export class InClassMethodBad { o(array: T = [], rParam: string): void { } }; +// https://github.com/microsoft/TypeScript/issues/60976 +class Bar {} +export class ClsWithRequiredInitializedParameter { + constructor( + private arr: Bar = new Bar(), + private bool: boolean, + ) {} +} \ No newline at end of file
diff --git a/src/compiler/transformers/declarations/diagnostics.ts b/src/compiler/transformers/declarations/diagnostics.ts index 84e952da136df..873f23cbf7987 100644 --- a/src/compiler/transformers/declarations/diagnostics.ts +++ b/src/compiler/transformers/declarations/diagnostics.ts @@ -767,7 +767,7 @@ export function createGetIsolatedDeclarationErrors(resolver: EmitResolver): (nod if (isSetAccessor(node.parent)) { return createAccessorTypeError(node.parent); - const addUndefined = resolver.requiresAddingImplicitUndefined(node, /*enclosingDeclaration*/ undefined); + const addUndefined = resolver.requiresAddingImplicitUndefined(node, node.parent); if (!addUndefined && node.initializer) { return createExpressionError(node.initializer); diff --git a/tests/baselines/reference/transpile/declarationFunctionDeclarations.d.ts b/tests/baselines/reference/transpile/declarationFunctionDeclarations.d.ts index 7814e7759fa75..af1cb8016aab5 100644 --- a/tests/baselines/reference/transpile/declarationFunctionDeclarations.d.ts +++ b/tests/baselines/reference/transpile/declarationFunctionDeclarations.d.ts //// [fnDecl.d.ts] //// type T = number[]; export declare function fnDeclBasic1(p: number[] | string[] | [T] | undefined, rParam: string): void; @@ -121,6 +129,13 @@ export declare class InClassMethodOk2 { export declare class InClassMethodBad { o(array: T | undefined, rParam: string): void; +declare class Bar { +export declare class ClsWithRequiredInitializedParameter { + private arr; + private bool; + constructor(arr: Bar | undefined, bool: boolean); export {}; @@ -134,9 +149,10 @@ fnDecl.ts(32,45): error TS9025: Declaration emit for this parameter requires imp fnDecl.ts(37,47): error TS9025: Declaration emit for this parameter requires implicitly adding undefined to its type. This is not supported with --isolatedDeclarations. fnDecl.ts(41,37): error TS9025: Declaration emit for this parameter requires implicitly adding undefined to its type. This is not supported with --isolatedDeclarations. fnDecl.ts(45,35): error TS9025: Declaration emit for this parameter requires implicitly adding undefined to its type. This is not supported with --isolatedDeclarations. -==== fnDecl.ts (9 errors) ==== +==== fnDecl.ts (10 errors) ==== type T = number[] export function fnDeclBasic1(p: number[] | string[] | [T] = [], rParam: string): void { }; export function fnDeclBasic2(p: (n: T) => T = () => null!, rParam: string): void { }; @@ -210,4 +226,14 @@ fnDecl.ts(45,35): error TS9025: Declaration emit for this parameter requires imp !!! error TS9025: Declaration emit for this parameter requires implicitly adding undefined to its type. This is not supported with --isolatedDeclarations. !!! related TS9028 fnDecl.ts:45:35: Add a type annotation to the parameter array. - + // https://github.com/microsoft/TypeScript/issues/60976 + class Bar {} + export class ClsWithRequiredInitializedParameter { + constructor( +!!! error TS9025: Declaration emit for this parameter requires implicitly adding undefined to its type. This is not supported with --isolatedDeclarations. +!!! related TS9028 fnDecl.ts:51:5: Add a type annotation to the parameter arr. + ) {} diff --git a/tests/baselines/reference/transpile/declarationFunctionDeclarations.js b/tests/baselines/reference/transpile/declarationFunctionDeclarations.js index 72ba57ff249ed..0e32cdf3471f0 100644 --- a/tests/baselines/reference/transpile/declarationFunctionDeclarations.js +++ b/tests/baselines/reference/transpile/declarationFunctionDeclarations.js //// [fnDecl.js] //// export function fnDeclBasic1(p = [], rParam) { } @@ -118,3 +126,14 @@ export class InClassMethodBad { o(array = [], rParam) { } +class Bar { + arr; + bool; + constructor(arr = new Bar(), bool) { + this.arr = arr; + this.bool = bool; diff --git a/tests/cases/transpile/declarationFunctionDeclarations.ts b/tests/cases/transpile/declarationFunctionDeclarations.ts index 5aa0c50d4f8d9..7d9d8c82e2711 100644 --- a/tests/cases/transpile/declarationFunctionDeclarations.ts +++ b/tests/cases/transpile/declarationFunctionDeclarations.ts @@ -49,3 +49,11 @@ export class InClassMethodOk1 { o(array: number[] = [], rParam: string): void { \ No newline at end of file
[ "+fnDecl.ts(51,5): error TS9025: Declaration emit for this parameter requires implicitly adding undefined to its type. This is not supported with --isolatedDeclarations.", "+ private arr: Bar = new Bar(),", "+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~", "+ private bool: boolean," ]
[ 50, 67, 68, 71 ]
{ "additions": 56, "author": "Andarist", "deletions": 3, "html_url": "https://github.com/microsoft/TypeScript/pull/60980", "issue_id": 60980, "merged_at": "2025-01-18T06:08:12Z", "omission_probability": 0.1, "pr_number": 60980, "repo": "microsoft/TypeScript", "title": "Fixed wrong error being reported on required initialized parameters with `isolatedDeclarations`", "total_changes": 59 }
95
diff --git a/src/services/codefixes/fixUnusedIdentifier.ts b/src/services/codefixes/fixUnusedIdentifier.ts index 1974e8067a45f..9d6c3be78c1cb 100644 --- a/src/services/codefixes/fixUnusedIdentifier.ts +++ b/src/services/codefixes/fixUnusedIdentifier.ts @@ -200,6 +200,9 @@ registerCodeFix({ else if (canDeleteEntireVariableStatement(sourceFile, token)) { deleteEntireVariableStatement(changes, sourceFile, token.parent as VariableDeclarationList); } + else if (isIdentifier(token) && isFunctionDeclaration(token.parent)) { + deleteFunctionLikeDeclaration(changes, sourceFile, token.parent as FunctionLikeDeclaration); + } else { tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, program, cancellationToken, /*isFixAll*/ true); } diff --git a/tests/cases/fourslash/codeFixUnusedIdentifier_all_selfReferencingFunction.ts b/tests/cases/fourslash/codeFixUnusedIdentifier_all_selfReferencingFunction.ts new file mode 100644 index 0000000000000..8017973ee96da --- /dev/null +++ b/tests/cases/fourslash/codeFixUnusedIdentifier_all_selfReferencingFunction.ts @@ -0,0 +1,18 @@ +/// <reference path='fourslash.ts' /> + +//// function fibonacci(n: number): number { +//// if (n <= 1) { +//// return n; +//// } +//// return fibonacci(n - 1) + fibonacci(n - 2); +//// } +//// +//// function other() {} +//// +//// export {}; + +verify.codeFixAll({ + fixId: "unusedIdentifier_delete", + fixAllDescription: ts.Diagnostics.Delete_all_unused_declarations.message, + newFileContent: "\n\nexport {};", +});
diff --git a/src/services/codefixes/fixUnusedIdentifier.ts b/src/services/codefixes/fixUnusedIdentifier.ts index 1974e8067a45f..9d6c3be78c1cb 100644 --- a/src/services/codefixes/fixUnusedIdentifier.ts +++ b/src/services/codefixes/fixUnusedIdentifier.ts @@ -200,6 +200,9 @@ registerCodeFix({ else if (canDeleteEntireVariableStatement(sourceFile, token)) { deleteEntireVariableStatement(changes, sourceFile, token.parent as VariableDeclarationList); + else if (isIdentifier(token) && isFunctionDeclaration(token.parent)) { + deleteFunctionLikeDeclaration(changes, sourceFile, token.parent as FunctionLikeDeclaration); + } else { tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, program, cancellationToken, /*isFixAll*/ true); diff --git a/tests/cases/fourslash/codeFixUnusedIdentifier_all_selfReferencingFunction.ts b/tests/cases/fourslash/codeFixUnusedIdentifier_all_selfReferencingFunction.ts new file mode 100644 index 0000000000000..8017973ee96da --- /dev/null +++ b/tests/cases/fourslash/codeFixUnusedIdentifier_all_selfReferencingFunction.ts @@ -0,0 +1,18 @@ +/// <reference path='fourslash.ts' /> +//// function fibonacci(n: number): number { +//// if (n <= 1) { +//// } +//// return fibonacci(n - 1) + fibonacci(n - 2); +//// +//// function other() {} +//// +//// export {}; +verify.codeFixAll({ + fixId: "unusedIdentifier_delete", + fixAllDescription: ts.Diagnostics.Delete_all_unused_declarations.message, + newFileContent: "\n\nexport {};", +});
[ "+//// return n;", "+//// }" ]
[ 24, 27 ]
{ "additions": 21, "author": "Andarist", "deletions": 0, "html_url": "https://github.com/microsoft/TypeScript/pull/60888", "issue_id": 60888, "merged_at": "2025-01-18T06:11:42Z", "omission_probability": 0.1, "pr_number": 60888, "repo": "microsoft/TypeScript", "title": "Fixed \"Delete all unused declarations\" to delete self-referential functions", "total_changes": 21 }
96
diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 60db22498601f..512fcc05832f4 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -10467,6 +10467,7 @@ export function isValidBigIntString(s: string, roundTripOnly: boolean): boolean /** @internal */ export function isValidTypeOnlyAliasUseSite(useSite: Node): boolean { return !!(useSite.flags & NodeFlags.Ambient) + || isInJSDoc(useSite) || isPartOfTypeQuery(useSite) || isIdentifierInNonEmittingHeritageClause(useSite) || isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(useSite) diff --git a/tests/baselines/reference/importTag23.errors.txt b/tests/baselines/reference/importTag23.errors.txt new file mode 100644 index 0000000000000..03bedf5694d7e --- /dev/null +++ b/tests/baselines/reference/importTag23.errors.txt @@ -0,0 +1,21 @@ +/b.js(6,14): error TS2420: Class 'C' incorrectly implements interface 'I'. + Property 'foo' is missing in type 'C' but required in type 'I'. + + +==== /a.ts (0 errors) ==== + export interface I { + foo(): void; + } + +==== /b.js (1 errors) ==== + /** + * @import * as NS from './a' + */ + + /** @implements {NS.I} */ + export class C {} + ~ +!!! error TS2420: Class 'C' incorrectly implements interface 'I'. +!!! error TS2420: Property 'foo' is missing in type 'C' but required in type 'I'. +!!! related TS2728 /a.ts:2:5: 'foo' is declared here. + \ No newline at end of file diff --git a/tests/baselines/reference/importTag23.symbols b/tests/baselines/reference/importTag23.symbols new file mode 100644 index 0000000000000..0ef50ac35705a --- /dev/null +++ b/tests/baselines/reference/importTag23.symbols @@ -0,0 +1,19 @@ +//// [tests/cases/conformance/jsdoc/importTag23.ts] //// + +=== /a.ts === +export interface I { +>I : Symbol(I, Decl(a.ts, 0, 0)) + + foo(): void; +>foo : Symbol(I.foo, Decl(a.ts, 0, 20)) +} + +=== /b.js === +/** + * @import * as NS from './a' + */ + +/** @implements {NS.I} */ +export class C {} +>C : Symbol(C, Decl(b.js, 0, 0)) + diff --git a/tests/baselines/reference/importTag23.types b/tests/baselines/reference/importTag23.types new file mode 100644 index 0000000000000..e2752f504851d --- /dev/null +++ b/tests/baselines/reference/importTag23.types @@ -0,0 +1,19 @@ +//// [tests/cases/conformance/jsdoc/importTag23.ts] //// + +=== /a.ts === +export interface I { + foo(): void; +>foo : () => void +> : ^^^^^^ +} + +=== /b.js === +/** + * @import * as NS from './a' + */ + +/** @implements {NS.I} */ +export class C {} +>C : C +> : ^ + diff --git a/tests/cases/conformance/jsdoc/importTag23.ts b/tests/cases/conformance/jsdoc/importTag23.ts new file mode 100644 index 0000000000000..ad2f361fe36c6 --- /dev/null +++ b/tests/cases/conformance/jsdoc/importTag23.ts @@ -0,0 +1,16 @@ +// @checkJs: true +// @allowJs: true +// @noEmit: true + +// @filename: /a.ts +export interface I { + foo(): void; +} + +// @filename: /b.js +/** + * @import * as NS from './a' + */ + +/** @implements {NS.I} */ +export class C {}
diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 60db22498601f..512fcc05832f4 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -10467,6 +10467,7 @@ export function isValidBigIntString(s: string, roundTripOnly: boolean): boolean /** @internal */ export function isValidTypeOnlyAliasUseSite(useSite: Node): boolean { return !!(useSite.flags & NodeFlags.Ambient) + || isInJSDoc(useSite) || isPartOfTypeQuery(useSite) || isIdentifierInNonEmittingHeritageClause(useSite) || isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(useSite) diff --git a/tests/baselines/reference/importTag23.errors.txt b/tests/baselines/reference/importTag23.errors.txt index 0000000000000..03bedf5694d7e +++ b/tests/baselines/reference/importTag23.errors.txt @@ -0,0 +1,21 @@ +/b.js(6,14): error TS2420: Class 'C' incorrectly implements interface 'I'. + Property 'foo' is missing in type 'C' but required in type 'I'. +==== /a.ts (0 errors) ==== + export interface I { + foo(): void; + } + /** + * @import * as NS from './a' + */ + /** @implements {NS.I} */ + export class C {} + ~ +!!! error TS2420: Class 'C' incorrectly implements interface 'I'. +!!! error TS2420: Property 'foo' is missing in type 'C' but required in type 'I'. +!!! related TS2728 /a.ts:2:5: 'foo' is declared here. \ No newline at end of file diff --git a/tests/baselines/reference/importTag23.symbols b/tests/baselines/reference/importTag23.symbols index 0000000000000..0ef50ac35705a +++ b/tests/baselines/reference/importTag23.symbols +>I : Symbol(I, Decl(a.ts, 0, 0)) diff --git a/tests/baselines/reference/importTag23.types b/tests/baselines/reference/importTag23.types index 0000000000000..e2752f504851d +++ b/tests/baselines/reference/importTag23.types +>foo : () => void +> : ^^^^^^ +>C : C +> : ^ diff --git a/tests/cases/conformance/jsdoc/importTag23.ts b/tests/cases/conformance/jsdoc/importTag23.ts index 0000000000000..ad2f361fe36c6 +++ b/tests/cases/conformance/jsdoc/importTag23.ts @@ -0,0 +1,16 @@ +// @checkJs: true +// @allowJs: true +// @noEmit: true +// @filename: /a.ts +// @filename: /b.js
[ "+==== /b.js (1 errors) ====", "+>foo : Symbol(I.foo, Decl(a.ts, 0, 20))", "+>C : Symbol(C, Decl(b.js, 0, 0))" ]
[ 27, 53, 63 ]
{ "additions": 76, "author": "a-tarasyuk", "deletions": 0, "html_url": "https://github.com/microsoft/TypeScript/pull/60566", "issue_id": 60566, "merged_at": "2025-01-17T22:54:28Z", "omission_probability": 0.1, "pr_number": 60566, "repo": "microsoft/TypeScript", "title": "fix(60563):@import * as namespace cannot be used with @implements", "total_changes": 76 }
97
diff --git a/src/services/inlayHints.ts b/src/services/inlayHints.ts index f5a29b332b595..d79def836396d 100644 --- a/src/services/inlayHints.ts +++ b/src/services/inlayHints.ts @@ -103,6 +103,7 @@ import { NodeArray, NodeBuilderFlags, ParameterDeclaration, + parameterIsThisKeyword, PrefixUnaryExpression, PropertyDeclaration, QuotePreference, @@ -437,24 +438,26 @@ export function provideInlayHints(context: InlayHintsContext): InlayHint[] { return; } - for (let i = 0; i < node.parameters.length && i < signature.parameters.length; ++i) { - const param = node.parameters[i]; - if (!isHintableDeclaration(param)) { - continue; + let pos = 0; + for (const param of node.parameters) { + if (isHintableDeclaration(param)) { + addParameterTypeHint(param, parameterIsThisKeyword(param) ? signature.thisParameter : signature.parameters[pos]); } - - const effectiveTypeAnnotation = getEffectiveTypeAnnotationNode(param); - if (effectiveTypeAnnotation) { + if (parameterIsThisKeyword(param)) { continue; } + pos++; + } + } - const typeHints = getParameterDeclarationTypeHints(signature.parameters[i]); - if (!typeHints) { - continue; - } + function addParameterTypeHint(node: ParameterDeclaration, symbol: Symbol | undefined) { + const effectiveTypeAnnotation = getEffectiveTypeAnnotationNode(node); + if (effectiveTypeAnnotation || symbol === undefined) return; - addTypeHints(typeHints, param.questionToken ? param.questionToken.end : param.name.end); - } + const typeHints = getParameterDeclarationTypeHints(symbol); + if (typeHints === undefined) return; + + addTypeHints(typeHints, node.questionToken ? node.questionToken.end : node.name.end); } function getParameterDeclarationTypeHints(symbol: Symbol) { diff --git a/tests/baselines/reference/inlayHintsThisParameter.baseline b/tests/baselines/reference/inlayHintsThisParameter.baseline new file mode 100644 index 0000000000000..d41eb76410e93 --- /dev/null +++ b/tests/baselines/reference/inlayHintsThisParameter.baseline @@ -0,0 +1,45 @@ +// === Inlay Hints === +fn(function (this, a, b) { }); + ^ +{ + "text": ": any", + "position": 126, + "kind": "Type", + "whitespaceBefore": true +} + +fn(function (this, a, b) { }); + ^ +{ + "text": ": number", + "position": 129, + "kind": "Type", + "whitespaceBefore": true +} + +fn(function (this, a, b) { }); + ^ +{ + "text": ": string", + "position": 132, + "kind": "Type", + "whitespaceBefore": true +} + +fn(function (this: I, a, b) { }); + ^ +{ + "text": ": number", + "position": 163, + "kind": "Type", + "whitespaceBefore": true +} + +fn(function (this: I, a, b) { }); + ^ +{ + "text": ": string", + "position": 166, + "kind": "Type", + "whitespaceBefore": true +} \ No newline at end of file diff --git a/tests/cases/fourslash/inlayHintsThisParameter.ts b/tests/cases/fourslash/inlayHintsThisParameter.ts new file mode 100644 index 0000000000000..dd4e181b1936b --- /dev/null +++ b/tests/cases/fourslash/inlayHintsThisParameter.ts @@ -0,0 +1,17 @@ +/// <reference path="fourslash.ts" /> + +////interface I { +//// a: number; +////} +//// +////declare function fn( +//// callback: (a: number, b: string) => void +////): void; +//// +//// +////fn(function (this, a, b) { }); +////fn(function (this: I, a, b) { }); + +verify.baselineInlayHints(undefined, { + includeInlayFunctionParameterTypeHints: true, +});
diff --git a/src/services/inlayHints.ts b/src/services/inlayHints.ts index f5a29b332b595..d79def836396d 100644 --- a/src/services/inlayHints.ts +++ b/src/services/inlayHints.ts @@ -103,6 +103,7 @@ import { NodeArray, NodeBuilderFlags, ParameterDeclaration, + parameterIsThisKeyword, PrefixUnaryExpression, PropertyDeclaration, QuotePreference, @@ -437,24 +438,26 @@ export function provideInlayHints(context: InlayHintsContext): InlayHint[] { return; } - for (let i = 0; i < node.parameters.length && i < signature.parameters.length; ++i) { - const param = node.parameters[i]; - if (!isHintableDeclaration(param)) { + let pos = 0; + for (const param of node.parameters) { + if (isHintableDeclaration(param)) { + addParameterTypeHint(param, parameterIsThisKeyword(param) ? signature.thisParameter : signature.parameters[pos]); - - const effectiveTypeAnnotation = getEffectiveTypeAnnotationNode(param); - if (effectiveTypeAnnotation) { continue; + pos++; + } - const typeHints = getParameterDeclarationTypeHints(signature.parameters[i]); - if (!typeHints) { - } + function addParameterTypeHint(node: ParameterDeclaration, symbol: Symbol | undefined) { + const effectiveTypeAnnotation = getEffectiveTypeAnnotationNode(node); - addTypeHints(typeHints, param.questionToken ? param.questionToken.end : param.name.end); - } + const typeHints = getParameterDeclarationTypeHints(symbol); + if (typeHints === undefined) return; + addTypeHints(typeHints, node.questionToken ? node.questionToken.end : node.name.end); } function getParameterDeclarationTypeHints(symbol: Symbol) { diff --git a/tests/baselines/reference/inlayHintsThisParameter.baseline b/tests/baselines/reference/inlayHintsThisParameter.baseline index 0000000000000..d41eb76410e93 +++ b/tests/baselines/reference/inlayHintsThisParameter.baseline @@ -0,0 +1,45 @@ +// === Inlay Hints === + ^ + "text": ": any", + "position": 126, + ^ + "position": 129, + "position": 132, + "position": 163, + ^ + "position": 166, \ No newline at end of file diff --git a/tests/cases/fourslash/inlayHintsThisParameter.ts b/tests/cases/fourslash/inlayHintsThisParameter.ts index 0000000000000..dd4e181b1936b +++ b/tests/cases/fourslash/inlayHintsThisParameter.ts @@ -0,0 +1,17 @@ +/// <reference path="fourslash.ts" /> +////interface I { +//// a: number; +////} +////declare function fn( +//// callback: (a: number, b: string) => void +////): void; +////fn(function (this, a, b) { }); +verify.baselineInlayHints(undefined, {
[ "+ if (parameterIsThisKeyword(param)) {", "+ }", "+ if (effectiveTypeAnnotation || symbol === undefined) return;", "+////fn(function (this: I, a, b) { });", "+ includeInlayFunctionParameterTypeHints: true,", "+});" ]
[ 28, 32, 41, 122, 125, 126 ]
{ "additions": 78, "author": "a-tarasyuk", "deletions": 13, "html_url": "https://github.com/microsoft/TypeScript/pull/60378", "issue_id": 60378, "merged_at": "2025-01-17T21:30:35Z", "omission_probability": 0.1, "pr_number": 60378, "repo": "microsoft/TypeScript", "title": "fix(60375): Parameter inlay hint is incorrect when function has a this type", "total_changes": 91 }
98
diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 59ad1f030220f..8c69cccba1282 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -9536,6 +9536,7 @@ namespace Parser { const node = factory.createExpressionWithTypeArguments(expression, typeArguments) as ExpressionWithTypeArguments & { expression: Identifier | PropertyAccessEntityNameExpression; }; const res = finishNode(node, pos); if (usedBrace) { + skipWhitespace(); parseExpected(SyntaxKind.CloseBraceToken); } return res; diff --git a/tests/baselines/reference/extendsTag3.js b/tests/baselines/reference/extendsTag3.js index 999982f3289b1..68180aa6214fb 100644 --- a/tests/baselines/reference/extendsTag3.js +++ b/tests/baselines/reference/extendsTag3.js @@ -17,6 +17,16 @@ class B extends A { super(); } } + +/** + * @extends { A } + * @constructor + */ +class C extends A { + constructor() { + super(); + } +} //// [foo.js] @@ -35,3 +45,12 @@ class B extends A { super(); } } +/** + * @extends { A } + * @constructor + */ +class C extends A { + constructor() { + super(); + } +} diff --git a/tests/baselines/reference/extendsTag3.symbols b/tests/baselines/reference/extendsTag3.symbols index 4fa623c2649ce..265cd1313f900 100644 --- a/tests/baselines/reference/extendsTag3.symbols +++ b/tests/baselines/reference/extendsTag3.symbols @@ -24,3 +24,17 @@ class B extends A { } } +/** + * @extends { A } + * @constructor + */ +class C extends A { +>C : Symbol(C, Decl(foo.js, 15, 1)) +>A : Symbol(A, Decl(foo.js, 0, 0)) + + constructor() { + super(); +>super : Symbol(A, Decl(foo.js, 0, 0)) + } +} + diff --git a/tests/baselines/reference/extendsTag3.types b/tests/baselines/reference/extendsTag3.types index c9f7a76260cdd..04a08d0f32ce2 100644 --- a/tests/baselines/reference/extendsTag3.types +++ b/tests/baselines/reference/extendsTag3.types @@ -30,3 +30,22 @@ class B extends A { } } +/** + * @extends { A } + * @constructor + */ +class C extends A { +>C : C +> : ^ +>A : A +> : ^ + + constructor() { + super(); +>super() : void +> : ^^^^ +>super : typeof A +> : ^^^^^^^^ + } +} + diff --git a/tests/baselines/reference/extendsTag6.symbols b/tests/baselines/reference/extendsTag6.symbols new file mode 100644 index 0000000000000..c0e9f051ce49f --- /dev/null +++ b/tests/baselines/reference/extendsTag6.symbols @@ -0,0 +1,26 @@ +//// [tests/cases/conformance/jsdoc/extendsTag6.ts] //// + +=== foo.js === +/** + * @constructor + */ +class A { +>A : Symbol(A, Decl(foo.js, 0, 0)) + + constructor() {} +} + +/** + * @extends { A } + * @constructor + */ +class B extends A { +>B : Symbol(B, Decl(foo.js, 5, 1)) +>A : Symbol(A, Decl(foo.js, 0, 0)) + + constructor() { + super(); +>super : Symbol(A, Decl(foo.js, 0, 0)) + } +} + diff --git a/tests/baselines/reference/extendsTag6.types b/tests/baselines/reference/extendsTag6.types new file mode 100644 index 0000000000000..886b33328eae3 --- /dev/null +++ b/tests/baselines/reference/extendsTag6.types @@ -0,0 +1,32 @@ +//// [tests/cases/conformance/jsdoc/extendsTag6.ts] //// + +=== foo.js === +/** + * @constructor + */ +class A { +>A : A +> : ^ + + constructor() {} +} + +/** + * @extends { A } + * @constructor + */ +class B extends A { +>B : B +> : ^ +>A : A +> : ^ + + constructor() { + super(); +>super() : void +> : ^^^^ +>super : typeof A +> : ^^^^^^^^ + } +} + diff --git a/tests/baselines/reference/jsdocImplementsTag.symbols b/tests/baselines/reference/jsdocImplementsTag.symbols new file mode 100644 index 0000000000000..e582dae1d074a --- /dev/null +++ b/tests/baselines/reference/jsdocImplementsTag.symbols @@ -0,0 +1,17 @@ +//// [tests/cases/conformance/jsdoc/jsdocImplementsTag.ts] //// + +=== /a.js === +/** + * @typedef { { foo: string } } A + */ + +/** + * @implements { A } + */ +class B { +>B : Symbol(B, Decl(a.js, 0, 0)) + + foo = '' +>foo : Symbol(B.foo, Decl(a.js, 7, 9)) +} + diff --git a/tests/baselines/reference/jsdocImplementsTag.types b/tests/baselines/reference/jsdocImplementsTag.types new file mode 100644 index 0000000000000..496e4b1fcbfe7 --- /dev/null +++ b/tests/baselines/reference/jsdocImplementsTag.types @@ -0,0 +1,21 @@ +//// [tests/cases/conformance/jsdoc/jsdocImplementsTag.ts] //// + +=== /a.js === +/** + * @typedef { { foo: string } } A + */ + +/** + * @implements { A } + */ +class B { +>B : B +> : ^ + + foo = '' +>foo : string +> : ^^^^^^ +>'' : "" +> : ^^ +} + diff --git a/tests/cases/conformance/jsdoc/extendsTag3.ts b/tests/cases/conformance/jsdoc/extendsTag3.ts index 81ac1e68843d3..28ca684ac71d8 100644 --- a/tests/cases/conformance/jsdoc/extendsTag3.ts +++ b/tests/cases/conformance/jsdoc/extendsTag3.ts @@ -20,3 +20,13 @@ class B extends A { super(); } } + +/** + * @extends { A } + * @constructor + */ +class C extends A { + constructor() { + super(); + } +} diff --git a/tests/cases/conformance/jsdoc/extendsTag6.ts b/tests/cases/conformance/jsdoc/extendsTag6.ts new file mode 100644 index 0000000000000..e7eee6ec8cdf9 --- /dev/null +++ b/tests/cases/conformance/jsdoc/extendsTag6.ts @@ -0,0 +1,22 @@ +// @allowJs: true +// @checkJs: true +// @target: esnext +// @noEmit: true +// @Filename: foo.js + +/** + * @constructor + */ +class A { + constructor() {} +} + +/** + * @extends { A } + * @constructor + */ +class B extends A { + constructor() { + super(); + } +} diff --git a/tests/cases/conformance/jsdoc/jsdocImplementsTag.ts b/tests/cases/conformance/jsdoc/jsdocImplementsTag.ts new file mode 100644 index 0000000000000..355ac8ca43af3 --- /dev/null +++ b/tests/cases/conformance/jsdoc/jsdocImplementsTag.ts @@ -0,0 +1,15 @@ +// @allowJs: true +// @checkJs: true +// @noEmit: true + +// @Filename: /a.js +/** + * @typedef { { foo: string } } A + */ + +/** + * @implements { A } + */ +class B { + foo = '' +}
diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 59ad1f030220f..8c69cccba1282 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -9536,6 +9536,7 @@ namespace Parser { const node = factory.createExpressionWithTypeArguments(expression, typeArguments) as ExpressionWithTypeArguments & { expression: Identifier | PropertyAccessEntityNameExpression; }; const res = finishNode(node, pos); if (usedBrace) { + skipWhitespace(); parseExpected(SyntaxKind.CloseBraceToken); } return res; diff --git a/tests/baselines/reference/extendsTag3.js b/tests/baselines/reference/extendsTag3.js index 999982f3289b1..68180aa6214fb 100644 --- a/tests/baselines/reference/extendsTag3.js +++ b/tests/baselines/reference/extendsTag3.js @@ -17,6 +17,16 @@ class B extends A { //// [foo.js] @@ -35,3 +45,12 @@ class B extends A { diff --git a/tests/baselines/reference/extendsTag3.symbols b/tests/baselines/reference/extendsTag3.symbols index 4fa623c2649ce..265cd1313f900 100644 --- a/tests/baselines/reference/extendsTag3.symbols +++ b/tests/baselines/reference/extendsTag3.symbols @@ -24,3 +24,17 @@ class B extends A { +>C : Symbol(C, Decl(foo.js, 15, 1)) diff --git a/tests/baselines/reference/extendsTag3.types b/tests/baselines/reference/extendsTag3.types index c9f7a76260cdd..04a08d0f32ce2 100644 --- a/tests/baselines/reference/extendsTag3.types +++ b/tests/baselines/reference/extendsTag3.types @@ -30,3 +30,22 @@ class B extends A { +>C : C diff --git a/tests/baselines/reference/extendsTag6.symbols b/tests/baselines/reference/extendsTag6.symbols index 0000000000000..c0e9f051ce49f +++ b/tests/baselines/reference/extendsTag6.symbols @@ -0,0 +1,26 @@ +>B : Symbol(B, Decl(foo.js, 5, 1)) diff --git a/tests/baselines/reference/extendsTag6.types b/tests/baselines/reference/extendsTag6.types index 0000000000000..886b33328eae3 +++ b/tests/baselines/reference/extendsTag6.types @@ -0,0 +1,32 @@ diff --git a/tests/baselines/reference/jsdocImplementsTag.symbols b/tests/baselines/reference/jsdocImplementsTag.symbols index 0000000000000..e582dae1d074a +++ b/tests/baselines/reference/jsdocImplementsTag.symbols @@ -0,0 +1,17 @@ +>B : Symbol(B, Decl(a.js, 0, 0)) +>foo : Symbol(B.foo, Decl(a.js, 7, 9)) diff --git a/tests/baselines/reference/jsdocImplementsTag.types b/tests/baselines/reference/jsdocImplementsTag.types index 0000000000000..496e4b1fcbfe7 +++ b/tests/baselines/reference/jsdocImplementsTag.types @@ -0,0 +1,21 @@ +>foo : string +> : ^^^^^^ +>'' : "" +> : ^^ diff --git a/tests/cases/conformance/jsdoc/extendsTag3.ts b/tests/cases/conformance/jsdoc/extendsTag3.ts index 81ac1e68843d3..28ca684ac71d8 100644 --- a/tests/cases/conformance/jsdoc/extendsTag3.ts +++ b/tests/cases/conformance/jsdoc/extendsTag3.ts @@ -20,3 +20,13 @@ class B extends A { diff --git a/tests/cases/conformance/jsdoc/extendsTag6.ts b/tests/cases/conformance/jsdoc/extendsTag6.ts index 0000000000000..e7eee6ec8cdf9 +++ b/tests/cases/conformance/jsdoc/extendsTag6.ts @@ -0,0 +1,22 @@ +// @target: esnext +// @Filename: foo.js diff --git a/tests/cases/conformance/jsdoc/jsdocImplementsTag.ts b/tests/cases/conformance/jsdoc/jsdocImplementsTag.ts index 0000000000000..355ac8ca43af3 +++ b/tests/cases/conformance/jsdoc/jsdocImplementsTag.ts @@ -0,0 +1,15 @@ +// @Filename: /a.js
[]
[]
{ "additions": 196, "author": "a-tarasyuk", "deletions": 0, "html_url": "https://github.com/microsoft/TypeScript/pull/60640", "issue_id": 60640, "merged_at": "2025-01-17T20:12:13Z", "omission_probability": 0.1, "pr_number": 60640, "repo": "microsoft/TypeScript", "title": "fix(60592): JSDoc implements space sensetive", "total_changes": 196 }
99
diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index 710a01b1c2dea..ea1f164f84f7f 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -179,6 +179,7 @@ import { isReferencedFile, isReferenceFileLocation, isRightSideOfPropertyAccess, + isSatisfiesExpression, isShorthandPropertyAssignment, isSourceFile, isStatement, @@ -2282,7 +2283,7 @@ export namespace Core { addIfImplementation(body); } } - else if (isAssertionExpression(typeHavingNode)) { + else if (isAssertionExpression(typeHavingNode) || isSatisfiesExpression(typeHavingNode)) { addIfImplementation(typeHavingNode.expression); } } diff --git a/tests/baselines/reference/goToImplementation_satisfies.baseline.jsonc b/tests/baselines/reference/goToImplementation_satisfies.baseline.jsonc new file mode 100644 index 0000000000000..7001dc9668590 --- /dev/null +++ b/tests/baselines/reference/goToImplementation_satisfies.baseline.jsonc @@ -0,0 +1,30 @@ +// === goToImplementation === +// === /a.ts === +// interface /*GOTO IMPL*/I { +// foo: string; +// } +// +// function f() { +// const foo = [|{ foo: '' }|] satisfies I; +// } + + // === Details === + [ + { + "kind": "interface", + "displayParts": [ + { + "text": "(", + "kind": "punctuation" + }, + { + "text": "object literal", + "kind": "text" + }, + { + "text": ")", + "kind": "punctuation" + } + ] + } + ] \ No newline at end of file diff --git a/tests/cases/fourslash/goToImplementation_satisfies.ts b/tests/cases/fourslash/goToImplementation_satisfies.ts new file mode 100644 index 0000000000000..1befdcfa40146 --- /dev/null +++ b/tests/cases/fourslash/goToImplementation_satisfies.ts @@ -0,0 +1,12 @@ +/// <reference path='fourslash.ts'/> + +// @filename: /a.ts +////interface /*def*/I { +//// foo: string; +////} +//// +////function f() { +//// const foo = { foo: '' } satisfies [|I|]; +////} + +verify.baselineGoToImplementation('def');
diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index 710a01b1c2dea..ea1f164f84f7f 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -179,6 +179,7 @@ import { isReferencedFile, isReferenceFileLocation, isRightSideOfPropertyAccess, + isSatisfiesExpression, isShorthandPropertyAssignment, isSourceFile, isStatement, @@ -2282,7 +2283,7 @@ export namespace Core { addIfImplementation(body); } - else if (isAssertionExpression(typeHavingNode)) { + else if (isAssertionExpression(typeHavingNode) || isSatisfiesExpression(typeHavingNode)) { addIfImplementation(typeHavingNode.expression); } diff --git a/tests/baselines/reference/goToImplementation_satisfies.baseline.jsonc b/tests/baselines/reference/goToImplementation_satisfies.baseline.jsonc index 0000000000000..7001dc9668590 +++ b/tests/baselines/reference/goToImplementation_satisfies.baseline.jsonc @@ -0,0 +1,30 @@ +// === goToImplementation === +// === /a.ts === +// interface /*GOTO IMPL*/I { +// foo: string; +// +// function f() { +// const foo = [|{ foo: '' }|] satisfies I; + // === Details === + "kind": "interface", + "displayParts": [ + "text": "(", + "text": "object literal", + "text": ")", + } + ] + } + ] \ No newline at end of file diff --git a/tests/cases/fourslash/goToImplementation_satisfies.ts b/tests/cases/fourslash/goToImplementation_satisfies.ts index 0000000000000..1befdcfa40146 +++ b/tests/cases/fourslash/goToImplementation_satisfies.ts @@ -0,0 +1,12 @@ +/// <reference path='fourslash.ts'/> +// @filename: /a.ts +//// foo: string; +//// +////function f() { +//// const foo = { foo: '' } satisfies [|I|]; +verify.baselineGoToImplementation('def');
[ "+ [", "+ {", "+ \"kind\": \"text\"", "+////interface /*def*/I {" ]
[ 38, 39, 48, 67 ]
{ "additions": 44, "author": "a-tarasyuk", "deletions": 1, "html_url": "https://github.com/microsoft/TypeScript/pull/60801", "issue_id": 60801, "merged_at": "2025-01-17T20:05:26Z", "omission_probability": 0.1, "pr_number": 60801, "repo": "microsoft/TypeScript", "title": "fix(60551): satisfies is shown on go-to-implementation", "total_changes": 45 }