Repository navigation
Expand file tree
/
Copy pathWireCoreServiceProvider.php
More file actions
1027 lines (904 loc) · 51.1 KB
/
Copy pathWireCoreServiceProvider.php
File metadata and controls
1027 lines (904 loc) · 51.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
namespace NyonCode\WireCore;
use Illuminate\Notifications\ChannelManager;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\View;
use Livewire\ComponentHookRegistry;
use Livewire\Livewire;
use NyonCode\LaravelPackageToolkit\Commands\InstallCommand;
use NyonCode\LaravelPackageToolkit\Packager;
use NyonCode\LaravelPackageToolkit\PackageServiceProvider;
use NyonCode\LaravelPackageToolkit\Support\PackageAssets;
use NyonCode\LaravelPackageToolkit\Support\PublishedAssets;
use NyonCode\WireCore\Actions\Console\MakeActionCommand;
use NyonCode\WireCore\Actions\Support\ActionCallbackInvoker;
use NyonCode\WireCore\Actions\Support\ComponentActionRunner;
use NyonCode\WireCore\Actions\Support\ModalIslandHook;
use NyonCode\WireCore\Actions\View\BulkButtonComponent;
use NyonCode\WireCore\Actions\View\ButtonComponent;
use NyonCode\WireCore\Actions\View\GroupComponent;
use NyonCode\WireCore\Actions\View\HaltHostComponent;
use NyonCode\WireCore\Actions\View\ModalHostComponent;
use NyonCode\WireCore\Audit\AuditEventSubscriber;
use NyonCode\WireCore\Audit\Console\PruneAuditEntriesCommand;
use NyonCode\WireCore\Core\Actions\ActionPipeline;
use NyonCode\WireCore\Core\Actions\ActionRegistry;
use NyonCode\WireCore\Core\Metadata\MetadataRegistry;
use NyonCode\WireCore\Core\Modules\Module;
use NyonCode\WireCore\Core\Plugin\Contracts\Plugin;
use NyonCode\WireCore\Core\Plugin\PluginManager;
use NyonCode\WireCore\Core\Resources\Contracts\DescribesResource;
use NyonCode\WireCore\Core\Resources\Navigation\NavigationGroups;
use NyonCode\WireCore\Core\Resources\ResourceRecordUrls;
use NyonCode\WireCore\Core\Resources\ResourceRegistry;
use NyonCode\WireCore\Core\Resources\View\Breadcrumbs;
use NyonCode\WireCore\Core\Resources\Workspace;
use NyonCode\WireCore\Core\Tenancy\Console\CreateTenantDatabaseCommand;
use NyonCode\WireCore\Core\Tenancy\Console\MigrateTenantsCommand;
use NyonCode\WireCore\Core\Tenancy\Contracts\IsolatesTenants;
use NyonCode\WireCore\Core\Tenancy\Contracts\TenantResolver;
use NyonCode\WireCore\Core\Tenancy\CurrentTenant;
use NyonCode\WireCore\Core\Tenancy\CurrentTenantResolver;
use NyonCode\WireCore\Core\Tenancy\Isolation\ColumnIsolation;
use NyonCode\WireCore\Core\Tenancy\Isolation\DatabaseIsolation;
use NyonCode\WireCore\Core\Tenancy\Queue\CarriesTenantThroughQueue;
use NyonCode\WireCore\Core\Tenancy\Tenancy;
use NyonCode\WireCore\Core\Validation\ValidationPipeline;
use NyonCode\WireCore\Exceptions\IconSetRegistrationException;
use NyonCode\WireCore\Exceptions\PluginRegistrationException;
use NyonCode\WireCore\Exceptions\TenancyException;
use NyonCode\WireCore\Foundation\Assets\Bundle;
use NyonCode\WireCore\Foundation\Components\Component;
use NyonCode\WireCore\Foundation\Contracts\ClassifiesComponentActions;
use NyonCode\WireCore\Foundation\Contracts\ResolvesRecordUrls;
use NyonCode\WireCore\Foundation\Contracts\RunsComponentActions;
use NyonCode\WireCore\Foundation\Icons\IconManager;
use NyonCode\WireCore\Foundation\Icons\IconSet;
use NyonCode\WireCore\Foundation\Icons\IconSprite;
use NyonCode\WireCore\Foundation\Icons\IconSpriteHook;
use NyonCode\WireCore\Foundation\Mentions\MentionRegistry;
use NyonCode\WireCore\Foundation\Mentions\MentionRenderer;
use NyonCode\WireCore\Foundation\Registration\Catalog;
use NyonCode\WireCore\Foundation\Registration\ClassDiscovery;
use NyonCode\WireCore\Foundation\Routing\ClientNavigation;
use NyonCode\WireCore\Foundation\Routing\Contracts\AuthorizesUrls;
use NyonCode\WireCore\Foundation\Routing\Contracts\ResolvesPageUrls;
use NyonCode\WireCore\Foundation\Routing\RenderedPage;
use NyonCode\WireCore\Foundation\Routing\UnguardedUrls;
use NyonCode\WireCore\Foundation\Routing\UnroutedPageUrls;
use NyonCode\WireCore\Foundation\Routing\WireRoutes;
use NyonCode\WireCore\Foundation\Setup\EnvFile;
use NyonCode\WireCore\Foundation\Support\IslandViewScope;
use NyonCode\WireCore\Foundation\Support\PartialRenderHook;
use NyonCode\WireCore\Foundation\Support\RecordVersion;
use NyonCode\WireCore\Foundation\View\CellSync;
use NyonCode\WireCore\Foundation\View\CopyButton;
use NyonCode\WireCore\Foundation\View\ElementHook;
use NyonCode\WireCore\Foundation\View\ExtraAttributes;
use NyonCode\WireCore\Foundation\View\FloatingAssets;
use NyonCode\WireCore\Foundation\View\PageChrome;
use NyonCode\WireCore\Foundation\View\Primitives;
use NyonCode\WireCore\GlobalSearch\GlobalSearchPalette;
use NyonCode\WireCore\Infolists\Console\MakeEntryCommand;
use NyonCode\WireCore\Modals\View\ConfirmationComponent;
use NyonCode\WireCore\Modals\View\ModalComponent;
use NyonCode\WireCore\Modals\View\SlideOverComponent;
use NyonCode\WireCore\Notifications\AuthenticatedNotifiable;
use NyonCode\WireCore\Notifications\Channels\WireChannel;
use NyonCode\WireCore\Notifications\Console\PruneNotificationsCommand;
use NyonCode\WireCore\Notifications\Contracts\NotificationDriver;
use NyonCode\WireCore\Notifications\Contracts\ResolvesNotifiable;
use NyonCode\WireCore\Notifications\Drivers\BroadcastDriver;
use NyonCode\WireCore\Notifications\Drivers\DatabaseDriver;
use NyonCode\WireCore\Notifications\Drivers\FlasherDriver;
use NyonCode\WireCore\Notifications\Drivers\LivewireEventDriver;
use NyonCode\WireCore\Notifications\Drivers\NullDriver;
use NyonCode\WireCore\Notifications\Drivers\SessionDriver;
use NyonCode\WireCore\Notifications\Drivers\StackDriver;
use NyonCode\WireCore\Notifications\NotificationBell;
use NyonCode\WireCore\Notifications\NotificationManager;
use NyonCode\WireCore\Notifications\Support\ConfiguredDrivers;
use NyonCode\WireCore\Notifications\Support\NotificationChannel;
use NyonCode\WireCore\Tours\TourAcknowledgement;
use NyonCode\WireCore\Tours\TourHost;
use NyonCode\WireCore\Tours\TourReplay;
use NyonCode\WireCore\Tours\Tours;
use NyonCode\WireCore\Widgets\Console\MakeDashboardCommand;
use NyonCode\WireCore\Widgets\Console\MakeWidgetCommand;
use NyonCode\WireCore\Widgets\Dashboard;
use NyonCode\WireCore\Widgets\DashboardRegistry;
class WireCoreServiceProvider extends PackageServiceProvider
{
/** Absolute path to the pre-bundled, self-registering browser assets. */
public const ASSETS_PATH = __DIR__.'/../dist';
/**
* @throws \Exception
*/
public function configure(Packager $packager): void
{
$packager
->name('WireCore')
->hasShortName('wire-core')
->registeredPackage(function ($packager) {
$this->registerFoundation();
$this->registerCore();
$this->registerNotifications();
$this->registerPlugins();
$this->registerResources();
$this->registerTenancy();
$this->registerRouting();
})
->bootedPackage(function ($packager) {
$this->bootFoundation();
$this->bootActions();
$this->bootNotifications();
$this->bootModals();
$this->bootPlugins();
$this->bootResources();
$this->bootTours();
// Queued work runs in the tenant it was dispatched in (ADR 0040 §9).
$this->app->make(CarriesTenantThroughQueue::class)->register($this->app->make('events'));
Bundle::serve('wire-core', self::ASSETS_PATH);
})
->hasConfig()
->hasCommand(PruneAuditEntriesCommand::class)
->hasCommand(CreateTenantDatabaseCommand::class)
->hasCommand(MigrateTenantsCommand::class)
->hasCommand(PruneNotificationsCommand::class)
->hasCommand(MakeDashboardCommand::class)
->hasCommand(MakeWidgetCommand::class)
->hasCommand(MakeEntryCommand::class)
->hasCommand(MakeActionCommand::class)
// The generators' templates, publishable so an application can
// change what they produce — Laravel's own `stub:publish`
// convention, which the commands honour by preferring
// `base_path('stubs/…')` over these. A generator that writes a view
// has two: the class and the Blade view it names.
->hasStubs([
'../stubs/dashboard.stub',
'../stubs/widget.stub',
'../stubs/widget-view.stub',
'../stubs/entry.stub',
'../stubs/entry-view.stub',
'../stubs/action.stub',
'../stubs/bulk-action.stub',
])
// A provider the consumer owns, the way Cashier and Fortify ship
// one: where an application registers its dashboards and declares
// its navigation groups. Shipped as a .stub so the package's own
// test suite, PHPStan and coverage never load a template that
// references App\ classes.
->hasProviders(['../stubs/WireDashboardServiceProvider.stub'])
// Wire the audit pipeline: HasAuditable models fire AuditableEvents and
// this subscriber persists them through AuditLogger. Declared rather than
// subscribed by hand — the toolkit subscribes it in the same boot pass —
// and unconditional, because the logger itself gates on
// `wire-core.audit.enabled` and the subscription is idempotent for apps
// that also register it themselves.
->hasSubscriber(AuditEventSubscriber::class)
->hasViews()
->hasMigrations()
->hasTranslations('resources/lang')
// `wire-core-dropdown.js` carries every shared Alpine controller
// (wireDropdown, wireContextMenu, wireTabs, wireWizard, wireEditableCell)
// — the interaction layer, which is exactly what must never arrive late.
// `wireFillHandle` used to ride along and no longer does: it is a table
// gesture, so it ships in `wire-table-fill.js` and a forms-only app stops
// paying 9 KB for it (ADR 0025 § step 10).
->hasAssets('dist', entries: [
Bundle::make('wire-core-dropdown.js'),
// The delegated clipboard controller. In core because two packages ask
// for the same affordance — a table's copyable cell and an infolist's
// copyable entry — and core is the lowest layer that can own it.
Bundle::make('wire-core-copy.js'),
// Was `loadedOnRequest()` under the old registry, on the grounds that
// charts are the heavy optional class. They are not: this is 671 bytes
// of Alpine registrar around `window.Chart`, which is the consuming
// app's own dependency and is not shipped here. Delivering a registrar
// late is the one thing ADR 0024 forbids, so it ships with the rest.
Bundle::make('wire-core-chart.js'),
// The notification bell's live bridge (`wireNotificationLive`).
// 1.2 kB of Alpine around `window.Echo`, which is the consuming
// app's own dependency and is not shipped here — the same shape
// as the chart registrar above, and declared for the same
// reason: ADR 0024 forbids delivering an interaction registrar
// late, and the bell can arrive on a `wire:navigate` visit.
Bundle::make('wire-core-notifications.js'),
// `wire-core-passkey.js` is deliberately NOT declared here, for
// the same reason as the sortable list below: it compiles
// Laravel's own passkey client in (12 kB), and every declared
// entry is rendered into the <head> of every page by
// `@wireStackScripts`. Two surfaces draw a passkey control — the
// auth module's sign-in button and the users module's profile
// card — and both include `wire-core::partials.passkey-assets`,
// which puts the tag on those pages and nowhere else.
// `wire-core-sortable-list.js` is deliberately NOT declared here.
// `@wireStackScripts` renders every declared entry, so declaring it
// would put 38 kB of compiled SortableJS into the <head> of every
// page of every wire-core application — which is exactly the cost
// giving it its own bundle was meant to avoid. It ships through
// `Bundle::serve()`'s route instead, emitted per surface by
// `wire-core::partials.sortable-list-assets`, which only a
// reorderable list includes. The toolkit has no "declared but not
// aggregated" flag (`loadedOnRequest()` went away with the old
// registry), so the route is the whole mechanism.
])
->hasAssetFallback(Bundle::servedByRoute('wire-core'))
->hasAbout()
->hasInstallCommand(function (InstallCommand $command) {
// Assets are deliberately not published here. Publishing is what
// switches this package's bundles from route delivery to static
// files, and that is a decision about the whole stack — one
// `vendor:publish --tag=laravel-assets` covers every installed
// package, where the installer would flip only this one.
$command
->publishConfig()
->publishMigrations()
->publishViews()
->publishTranslations();
});
}
/**
* Extra rows for this package's `php artisan about` section (the toolkit
* already prepends "Version"). Values are closures so config resolves at
* boot, not at declaration time.
*
* @return array<string, string|\Closure>
*/
public function aboutData(): array
{
return [
'Notifications' => fn (): string => (string) config('wire-core.notifications.default', 'session'),
'Icons' => fn (): string => (string) config('wire-core.icons.default_set', 'default'),
'Audit' => fn (): string => config('wire-core.audit.enabled', true) ? 'enabled' : 'disabled',
];
}
// ─── Foundation ─────────────────────────────────────────────
protected function registerFoundation(): void
{
// The application's `.env`, for the setup steps that flip a switch in
// it. Bound because the path is a constructor string the container
// cannot invent, and bound here rather than left to each step so an
// application under test can point it somewhere disposable.
$this->app->bind(EnvFile::class, static fn (): EnvFile => EnvFile::forApplication());
// Row-granular rendering: a write can render the regions it touched
// instead of the view. Inert until something calls renderPartial().
//
// In the REGISTER phase deliberately. ComponentHookRegistry::boot() walks
// its static list once and wires an `on('mount')` listener per hook; one
// registered after that sits in the list unwired until the NEXT app boot.
// Under Testbench that means the first test of a process silently has no
// hook and later ones do — which is exactly how it presented.
ComponentHookRegistry::register(PartialRenderHook::class);
// A modal mounted by a call that targeted another island (a row action
// without a modal of its own opening one) still answers with the modal.
// Registered here for the same reason as the hook above.
ComponentHookRegistry::register(ModalIslandHook::class);
// Per request: a sprite scope opened by a render that then threw must not
// keep the next request's PDFs and mails sprited.
$this->app->scoped(IconSprite::class, static fn (): IconSprite => new IconSprite(
(bool) config('wire-core.icons.sprite', false),
));
$this->app->singleton(IconManager::class, function ($app) {
$manager = new IconManager;
// Register icon sets declared in config. The set whose key matches
// `icons.default_set` becomes the unprefixed base (Heroicons by
// default); every other set's key is its required prefix, so its icons
// are addressed as `prefix:name` (e.g. `lucide:home`).
$defaultKey = config('wire-core.icons.default_set', 'default');
/** @var array<int|string, mixed> $sets */
$sets = config('wire-core.icons.sets', []);
// Heroicons is the base without being listed, so only another base
// has to be found in the list — and one that is not there would leave
// Heroicons in its place without a word.
if ($defaultKey !== 'default' && ! array_key_exists($defaultKey, $sets)) {
throw IconSetRegistrationException::defaultSetNotListed((string) $defaultKey, array_keys($sets));
}
foreach ($sets as $prefix => $class) {
// Refused rather than skipped. A typo here used to cost every
// icon addressed through this prefix — each one rendering the
// missing-icon placeholder, with nothing connecting the two.
if (! is_string($class) || ! is_a($class, IconSet::class, true)) {
throw IconSetRegistrationException::notAnIconSet($class, IconSet::class);
}
if ($prefix === $defaultKey) {
$manager->setDefaultIconSet($app->make($class));
continue;
}
// The shipped Heroicons entry, when another set took the base: it
// has no prefix of its own to move to ('default' is reserved), and
// registering it anyway refused the whole config at boot.
if ($prefix === 'default') {
continue;
}
if (! is_string($prefix) || $prefix === '') {
throw IconSetRegistrationException::prefixNotAString($class);
}
$manager->registerIconSet($app->make($class), $prefix);
}
// Load SVG files from any configured directories. This is the
// easiest way to add custom icons — no class required. A string key
// is used as a name prefix (e.g. 'brand' => '/path' → 'brand-logo'),
// which also avoids collisions when two folders share a file name.
/** @var array<int|string, mixed> $paths */
$paths = config('wire-core.icons.paths', []);
foreach ($paths as $prefix => $path) {
// As above: a mistyped directory silently registered nothing.
if (! is_string($path) || ! is_dir($path)) {
throw IconSetRegistrationException::iconDirectoryUnreadable($path);
}
$manager->registerIconsFromDirectory($path, is_string($prefix) ? $prefix : '');
}
return $manager;
});
// Canonical owner of record-invariant primitive markup (spinner, success
// check). Singleton so its per-request string memo spans the whole request.
$this->app->singleton(Primitives::class);
// Canonical owner of the copy-to-clipboard affordance — markup here, the
// delegated listener in the `copy` bundle, the feedback pill in
// `partials.copy-assets`. Singleton so its per-shape compile is per request.
$this->app->singleton(CopyButton::class);
// Canonical owner of an editable cell's server→client sync node. Singleton
// for the same reason: the partial is rendered once into a skeleton and
// every editable cell on the page splices its two values into it.
$this->app->singleton(CellSync::class);
// Stateless, and asked for once per editable cell — so leaving it
// unregistered meant a reflective build per cell, which measured at
// ~14µs each: 40ms of pure container on a 500-row table with three
// editable columns, for an object with no constructor and no state.
$this->app->singleton(RecordVersion::class);
// Thin facade over the toolkit's renderer for the floating-dropdown bundle
// URL, kept because a dozen partials already resolve it by that name.
$this->app->singleton(FloatingAssets::class);
// Where a package puts a view the shell has to render once per page.
// Singleton because that is the whole contract: two instances would mean
// two copies of a modal in one document, both listening for one event.
$this->app->singleton(PageChrome::class);
// The registered walkthroughs. Singleton for the reason PageChrome is
// one: providers write to it at boot, and a second instance would be a
// registry holding half the tours — with which half depending on who
// resolved it first.
$this->app->singleton(Tours::class);
// Whether a link is followed with `wire:navigate`. Scoped rather than a
// singleton because it compares a url against the request's own origin,
// and an Octane worker serves more than one.
$this->app->scoped(ClientNavigation::class);
}
protected function bootFoundation(): void
{
// An island renders without the shared `$__livewire` a full render has, and
// every modal here is an Htmlable that only shared data reaches. See the class.
IslandViewScope::register();
// A component's and an island's render each become a sprite scope when
// `wire-core.icons.sprite` is on; inert otherwise (the listener returns
// no finisher).
IconSpriteHook::register();
// Register <x-wire::icon />, <x-wire::badge />, etc. `<x-wire::icon>` stays
// the consumer-facing Blade API. The framework's OWN partials never render
// icons through it (a full Blade component = one view render per call);
// they call the `icon()` helper — `{!! icon('check', 'w-5 h-5') !!}` — which
// returns the memoised IconManager <svg> string (zero view renders) and can
// forward Alpine/data-* attributes via its $attributes argument.
Blade::componentNamespace('NyonCode\\WireCore\\Foundation\\View', 'wire');
// Registered by hand because it lives in `Core/` rather than in
// `Foundation/View`: it names NavigationItem, which is L1, and the layer
// test refuses that import from L0. The tag is the same either way.
Blade::component('wire::breadcrumbs', Breadcrumbs::class);
// `@wireStackScripts` — the one tag an app puts in its layout <head> to get
// every wireStack Alpine controller into the initial document (which is what
// survives Livewire's cached Back/Forward navigation).
//
// Now an alias for the toolkit's `@packageAssets`, which since 2.4.2 renders
// every package that declared entries when given no argument. Kept rather than
// removed because it is in consuming apps' layouts, and a minor release is no
// place to break a `<head>`. Note the widened meaning: the aggregate is every
// *toolkit* package, not only the four wireStack ones — which is what a layout
// wants anyway, and the argument the aggregate was added for.
//
// A thin passthrough, the same as before: the whole expression goes to the
// renderer, so an app may still narrow it to one package.
// `@wireRenderHook('panels.page.header.end', ['page' => $page])` — whatever
// an application registered for that position. Nothing registered is an
// empty string and one array lookup, so an unused position is free.
Blade::directive('wireRenderHook', static fn (string $expression): string => sprintf(
'<?php echo app(%s::class)->runRenderHook(%s); ?>',
'\\'.PluginManager::class,
$expression,
));
// `@wireEl('admin-sidebar')` — the stable name an application styles this
// element by, as `data-wire="…"`. An attribute rather than a class
// because 143 elements build their class list with `@class([…])`, and a
// second `class` attribute is silently dropped by the browser.
Blade::directive('wireEl', static fn (string $expression): string => sprintf(
'<?php echo %s::render(%s); ?>',
'\\'.ElementHook::class,
$expression,
));
// `@wireExtraAttributes($component)` — the component's `extraAttributes()`
// on its root tag. A directive rather than a partial because the field
// wrapper renders once per field of every form, and an `@include` there
// costs a view render per field (FormRenderCountTest measures it).
// `<a href="{{ $url }}" @wireNavigate($url)>` — `wire:navigate` when
// `wire-core.navigate` is on and the url is this application's, nothing
// otherwise. A second argument is the link's own preference.
Blade::directive('wireNavigate', static fn (string $expression): string => sprintf(
'<?php echo app(%s::class)->attribute(%s); ?>',
'\\'.ClientNavigation::class,
$expression,
));
Blade::directive('wireExtraAttributes', static fn (string $expression): string => sprintf(
'<?php echo %s::for(%s)->toHtml(); ?>',
'\\'.ExtraAttributes::class,
$expression,
));
Blade::directive('wireStackScripts', static fn (string $expression): string => sprintf(
'<?php echo app(%s::class)->tags(%s); ?>',
'\\'.PackageAssets::class,
$expression,
));
// Octane: three memos that are per-request everywhere else become
// per-worker-lifetime here, so flush them as each request ends.
//
// The view-render memo is a class static that would otherwise accumulate
// (unbounded growth; potential cross-tenant bleed). The asset URLs are the
// subtler one: each carries the `?id=<mtime>` of its mirrored copy, so a
// worker still alive across a deploy would keep emitting last release's query
// string — and `data-navigate-track`, which exists to catch exactly that,
// would never fire. Since the toolkit owns the tag there is one memo to
// flush, not two.
//
// RecordVersion's baselines are the third, and the one where a leak would
// be a correctness bug rather than a stale URL: a baseline is "the stamp
// this REQUEST first saw", and holding one into the next request would
// forgive an optimistic-lock version that has genuinely gone stale since.
//
// Referenced by string, not ::class import: laravel/octane is an optional
// dependency the package does not require, so the symbol may not exist.
$octaneRequestTerminated = 'Laravel\\Octane\\Events\\RequestTerminated';
if (class_exists($octaneRequestTerminated)) {
Event::listen($octaneRequestTerminated, function (): void {
Component::flushViewRenderCache();
$this->app->make(PublishedAssets::class)->flush();
$this->app->make(RecordVersion::class)->flush();
});
}
}
// ─── Core Infrastructure ──────────────────────────────────
protected function registerCore(): void
{
$this->app->singleton(ValidationPipeline::class);
$this->app->singleton(ActionRegistry::class);
$this->app->singleton(MetadataRegistry::class);
$this->app->singleton(ActionCallbackInvoker::class);
// The way across a module boundary the layers forbid importing over: a
// widget carries actions, `Widgets` may not see `Actions`, so the widget
// host asks the container for the capability and this is what answers.
// Bound to the contract rather than to the class, so a consumer names
// `Foundation\Contracts\RunsComponentActions` and nothing else.
$this->app->singleton(RunsComponentActions::class, ComponentActionRunner::class);
// The same object under its other contract, and `singleton` on both would
// build it twice — one instance answering "may this run" and a different
// one running it. Aliased so the two questions and the answer are the
// same object, which is what a caller asking all three assumes.
$this->app->alias(RunsComponentActions::class, ClassifiesComponentActions::class);
// ActionPipeline is transient — each execution gets a fresh instance
$this->app->bind(ActionPipeline::class);
}
// ─── Actions ────────────────────────────────────────────────
protected function bootActions(): void
{
// Register <x-wire-actions::button />, <x-wire-actions::group />, etc.
Blade::componentNamespace('NyonCode\\WireCore\\Actions\\View', 'wire-actions');
// Map short aliases for cleaner component names
Blade::component('wire-actions::button', ButtonComponent::class);
Blade::component('wire-actions::group', GroupComponent::class);
Blade::component('wire-actions::bulk-button', BulkButtonComponent::class);
Blade::component('wire-actions::modal-host', ModalHostComponent::class);
Blade::component('wire-actions::halt-host', HaltHostComponent::class);
}
// ─── Notifications ──────────────────────────────────────────
protected function registerNotifications(): void
{
// Who a notification is for. Bound rather than left to each driver's
// `new AuthenticatedNotifiable` default so that an application with its
// own answer — a tenant, an impersonated user — replaces it once and
// every reader agrees: the drivers on the write side, NotificationCenter
// and the bell on the read side, and the channel they broadcast on.
$this->app->bindIf(ResolvesNotifiable::class, AuthenticatedNotifiable::class);
$this->app->singleton(NotificationDriver::class, function ($app) {
// A list is the ordinary case, not an edge one: showing the toast
// *and* keeping it in the bell is what an application usually wants,
// and neither driver needs to know about the other.
//
// A string is split on commas, so the list can also come from the
// environment — `WIRE_NOTIFICATIONS_DRIVER=session,database`. An
// env var carries a string and nothing else, so without this the
// only way to ask for two drivers was to edit the published config,
// and `wire:install` had no way to turn storage on for the
// notifications module. One name has no comma and is unaffected.
$drivers = array_map($this->makeNotificationDriver(...), ConfiguredDrivers::names());
return count($drivers) === 1 ? $drivers[0] : new StackDriver(...$drivers);
});
$this->app->singleton(NotificationManager::class);
}
protected function makeNotificationDriver(string $name): NotificationDriver
{
return match ($name) {
'livewire' => new LivewireEventDriver,
'flasher' => new FlasherDriver,
// The two recipient-aware drivers take the bound resolver rather
// than their own default, so the row is written against — and the
// channel named after — whoever the application says the recipient
// is. The bell resolves the same binding, and a broadcast to a
// channel nobody is subscribed to is a failure nothing reports.
'database' => new DatabaseDriver($this->app->make(ResolvesNotifiable::class)),
'broadcast' => new BroadcastDriver($this->app->make(ResolvesNotifiable::class)),
'null' => new NullDriver,
default => new SessionDriver,
};
}
protected function bootNotifications(): void
{
// Register <x-wire-notifications::toast-container /> etc.
Blade::componentNamespace('NyonCode\\WireCore\\Notifications\\View', 'wire-notifications');
// The bell is a Livewire component, not a Blade one: everything it does
// is a round trip. Registered under a stable name so a layout can mount
// it without knowing the class.
Livewire::component('wire-notification-bell', NotificationBell::class);
Livewire::component('wire-global-search', GlobalSearchPalette::class);
$this->authorizeNotificationChannel();
$this->registerLaravelNotificationChannel();
}
/**
* Let `$user->notify(...)` deliver here, via `via() => ['wire']`.
*
* Guarded on the class, not required in composer.json: `illuminate/notifications`
* ships with the framework and every application has it, but this package
* requires `illuminate/support` and `illuminate/database` and nothing else —
* and a bridge to an ecosystem is not a reason to make that ecosystem
* mandatory. Registered through `resolving()` so an application that never
* sends a Laravel notification never builds the manager.
*/
protected function registerLaravelNotificationChannel(): void
{
if (! class_exists(ChannelManager::class)) {
return; // @codeCoverageIgnore — the suite runs on the full framework.
}
$this->app->resolving(ChannelManager::class, function (ChannelManager $manager): void {
$manager->extend(
WireChannel::NAME,
fn ($app): WireChannel => new WireChannel($app->make(NotificationDriver::class)),
);
});
}
/**
* Authorize the recipient's own notification channel, for an app that
* configured the `broadcast` driver and said nothing further.
*
* Gated on that driver being in use, and the gate is not a nicety:
* `Broadcast::channel()` resolves the default broadcaster, so registering
* this unconditionally would construct a connection in every wire-core
* application — including the ones that broadcast nothing and may have no
* credentials for the driver their config names.
*/
protected function authorizeNotificationChannel(): void
{
if (! ConfiguredDrivers::includes('broadcast')) {
return;
}
if (! (bool) config('wire-core.notifications.broadcast.authorize', true)) {
return;
}
NotificationChannel::authorize();
}
// ─── Modals ─────────────────────────────────────────────────
protected function bootModals(): void
{
// Register <x-wire-modals::modal />, <x-wire-modals::confirmation />, etc.
Blade::componentNamespace('NyonCode\\WireCore\\Modals\\View', 'wire-modals');
// Map short aliases for cleaner component names
Blade::component('wire-modals::modal', ModalComponent::class);
Blade::component('wire-modals::confirmation', ConfirmationComponent::class);
Blade::component('wire-modals::slide-over', SlideOverComponent::class);
// Universal alias: <x-wire::modal />
Blade::component('wire::modal', ModalComponent::class);
}
// ─── Plugins ────────────────────────────────────────────────
/**
* One registry per application.
*
* A singleton because the menu, the model router and boost introspection
* must see the same set, and a resource added in code has to survive the
* request that added it.
*/
/**
* Bind the tenancy seam.
*
* The resolver defaults to whatever tenant was entered ({@see CurrentTenant})
* rather than to the authenticated user: the framework does not know which
* column holds an application's tenant, and guessing would be a guess about
* who may see what. Nothing entered is still "no tenant" — with tenancy on,
* an empty page until something enters one, which is the safe direction to
* fail in. An application binding its own resolver keeps it.
*
* The holder is scoped, so a request under Octane and a queued job each
* start with none (ADR 0040 §1).
*/
protected function registerTenancy(): void
{
$this->app->bindIf(TenantResolver::class, CurrentTenantResolver::class);
$this->app->singleton(Tenancy::class);
$this->app->scoped(CurrentTenant::class);
$this->app->singleton(CarriesTenantThroughQueue::class);
$this->app->bindIf(IsolatesTenants::class, function ($app): IsolatesTenants {
$isolation = config('wire-core.tenancy.isolation', 'column');
if ($isolation === 'column' || $isolation === null) {
return new ColumnIsolation;
}
if ($isolation === 'database') {
return $app->make(DatabaseIsolation::class);
}
if (is_string($isolation) && is_a($isolation, IsolatesTenants::class, true)) {
return $app->make($isolation);
}
throw TenancyException::unknownIsolation(is_string($isolation) ? $isolation : get_debug_type($isolation));
});
}
protected function registerResources(): void
{
$this->app->singleton(ResourceRegistry::class);
$this->app->singleton(DashboardRegistry::class);
// The menu's headings. A singleton for the reason the resource registry
// is one: an application declares them once at boot and every request
// asks the same object, so a fresh instance per resolve would answer
// with an empty menu on the request that renders it.
$this->app->singleton(NavigationGroups::class);
// Assembled here rather than autowired, because what an application is
// made of is this provider's decision and not the catalogue's: it takes
// a list of sources and never learns what kind of thing any of them
// holds. An application adding a source of its own binds its own list —
// one binding, read by the menu, the router and the search palette
// alike, which is the whole of ADR 0026.
$this->app->bind(Catalog::class, fn ($app): Catalog => new Catalog([
$app->make(ResourceRegistry::class),
$app->make(DashboardRegistry::class),
]));
// Null by default, rebound by whoever owns routing. A menu and a search
// palette both need a URL and both are core, while the URL convention is
// `wire-panels` — so core declares the question and answers it with
// "nothing is routed" until a package that routes says otherwise.
$this->app->bindIf(ResolvesPageUrls::class, UnroutedPageUrls::class);
// The page a Livewire round trip is working on, so Zone can answer
// on the second render too; the routing package fills it.
$this->app->scoped(RenderedPage::class);
// Its other half: whether somebody may open a URL. Yes until the same
// package says which routes carry `can:` middleware.
$this->app->bindIf(AuthorizesUrls::class, UnguardedUrls::class);
$this->app->bind(Workspace::class, fn ($app): Workspace => new Workspace(
$app->make(Catalog::class),
$app->make(NavigationGroups::class),
$app->make(ResolvesPageUrls::class),
));
// Mentions are stored as identities and read back on every render, so
// both halves are one binding: the registry an application declares its
// non-Mentionable models in at boot, and the renderer every display
// surface resolves through. Singleton — the registry is filled once.
$this->app->singleton(MentionRegistry::class);
// Foundation asks "where can this record be read"; `Core/` answers it from
// the resource registry. bindIf, so an application that routes its own
// public pages can answer differently without touching the asker.
$this->app->bindIf(ResolvesRecordUrls::class, fn ($app): ResourceRecordUrls => new ResourceRecordUrls(
$app->make(ResourceRegistry::class),
$app->make(ResolvesPageUrls::class),
));
$this->app->bind(MentionRenderer::class, fn ($app): MentionRenderer => new MentionRenderer(
$app->make(MentionRegistry::class),
$app->make(ResolvesRecordUrls::class),
));
}
/**
* Put the configured resources in the registry.
*
* Booted rather than registered: a resource class is application code that
* may reference models and policies, so it is read once the application's
* own providers have run.
*/
/**
* Put the walkthrough's chrome on every page, and give it its data.
*
* **Unconditional, deliberately.** Provider order in a Laravel application
* is composer's discovery order, so an application that registers its tours
* in its own provider may boot after this one — and a `if ($tours->all())`
* here would answer "none" for exactly that application and leave the chrome
* off every page for ever. The same reasoning `wire-module-users` records
* for its user-menu entry. Whether there is a tour to run is asked at
* render, where the answer is knowable.
*
* A composer rather than a view that resolves its own dependencies: a view
* reaching into the container is a view doing PHP's job (Rendering Rule 1),
* and `PageChrome` renders by name with no data of its own to pass.
*
* The cost to an application with no tours is one `@include`, one empty
* `foreach` over the registry, and the `@if` that ends the view. Nothing
* touches the preference store until a tour actually claims a screen.
*/
protected function bootTours(): void
{
View::composer('wire-core::tours.host', function ($view): void {
$host = $this->app->make(TourHost::class);
$view->with(['tourHost' => $host, 'tour' => $host->current()]);
});
View::composer('wire-core::tours.replay-entry', function ($view): void {
$view->with('replayableTour', $this->app->make(TourHost::class)->replayable());
});
// The one round trip a tour makes, and the way back into one that is
// finished. Addressable by name so a Blade file mounts them without
// importing a class, the same as the bell and the palette above.
Livewire::component('wire-tour-acknowledgement', TourAcknowledgement::class);
Livewire::component('wire-tour-replay', TourReplay::class);
$chrome = $this->app->make(PageChrome::class);
$chrome->add('wire-core::tours.host');
// In the person's own menu rather than the page's chrome, because a
// walkthrough is theirs: they are the one who finished it, and they are
// the one who wants it again. The sort leaves room above for the profile
// link and below for the way out, neither of which this package can see.
$chrome->add('wire-core::tours.replay-entry', PageChrome::USER_MENU, sort: 20);
}
/**
* The classes of one kind under the directories `config('wire-core.discover')`
* names for it — namespace => directory — or none when it names nothing.
*
* @param class-string $kind
* @return array<int, class-string>
*/
private function discovered(string $key, string $kind): array
{
$directories = config("wire-core.discover.{$key}", []);
if (! is_array($directories) || $directories === []) {
return [];
}
$discovery = $this->app->make(ClassDiscovery::class);
$found = [];
foreach ($directories as $namespace => $directory) {
if (is_string($namespace) && is_string($directory)) {
array_push($found, ...$discovery->in($directory, $namespace, $kind));
}
}
return $found;
}
/**
* `Route::wire('key', …options)` — every package's routes, placed by the
* application's own route file inside whatever group it builds (ADR 0041).
* Named arguments arrive as the group's options: `zone:`, `only:`,
* `routes:` for changes to single routes.
*/
protected function registerRouting(): void
{
$this->app->singleton(WireRoutes::class);
// Only named arguments are options; a positional one names nothing.
Route::macro(WireRoutes::MACRO, fn (string $key, mixed ...$options): array => app(WireRoutes::class)->wire(
$key,
array_filter($options, is_string(...), ARRAY_FILTER_USE_KEY),
));
}
protected function bootResources(): void
{
$this->app->make(ResourceRegistry::class)->registerMany(config('wire-core.resources', []));
$this->app->make(DashboardRegistry::class)->registerMany(config('wire-core.dashboards', []));
// After the lists, so a class both listed and discovered registers once
// (registering one class twice is a no-op) and the listed order wins.
$this->app->make(ResourceRegistry::class)->registerMany($this->discovered('resources', DescribesResource::class));
$this->app->make(DashboardRegistry::class)->registerMany($this->discovered('dashboards', Dashboard::class));
$this->bootModules();
// The framework's one route file, last: the first moment every
// package's resources and route groups are registered, so the groups
// config describes can read a complete catalogue. In boot(), never in a
// booted() callback — Laravel installs a cached route collection from
// one of those, and a route registered after it vanishes or doubles
// depending on callback order. `loadRoutesFrom()` skips it when the
// routes are cached.
$this->loadRoutesFrom(__DIR__.'/../routes/web.php');
}
/**
* Spread every registered domain module's declarations into the registries
* that own them.
*
* Here rather than inside the module for a reason the layer test enforces: a
* dashboard is `Widgets/` (L2) and a module that reached for
* `DashboardRegistry` itself would be an L2→L2 import. A provider is outside
* the layer map and already holds both registries, so this is the one place
* that can see all three at once.
*
* Modules come from the plugin manager because a module *is* a plugin —
* registered from `config('wire-core.plugins')`, dependency-checked by the
* same rule, booted by the same lifecycle. There is no second registry, and
* nothing for one to hold.
*
* Ordering follows registration, so a module listed after the one it depends
* on sees that module's groups already declared. A group registered twice
* replaces, which is how an application adjusts a heading a module shipped.
*/
protected function bootModules(): void
{
$resources = $this->app->make(ResourceRegistry::class);
$dashboards = $this->app->make(DashboardRegistry::class);
$groups = $this->app->make(NavigationGroups::class);
// Group keys a module has already declared in this pass.
$declared = [];
foreach ($this->app->make(PluginManager::class)->all() as $plugin) {
if (! $plugin instanceof Module) {
continue;
}
$resources->registerMany($plugin->resources());
$dashboards->registerMany($plugin->dashboards());
$group = $plugin->navigation();
if ($group === null) {
continue;
}
// Two modules naming one heading — audit, notifications and settings
// all ship `system` — declare one group, not a race to replace each
// other: which one booted last used to decide its position. The first
// declaration's heading and icon stand, and the group sits where the
// earliest of them asked. An application registering the key itself
// still replaces, as the registry promises.
$existing = isset($declared[$group->getKey()]) ? $groups->find($group->getKey()) : null;
if ($existing !== null) {
$existing->sort(min($existing->getSort(), $group->getSort()));
continue;
}
$groups->register($group);
$declared[$group->getKey()] = true;
}
}
protected function registerPlugins(): void
{
$this->app->singleton(PluginManager::class);
// Register plugins from config
$this->app->afterResolving(PluginManager::class, function (PluginManager $manager) {
$plugins = config('wire-core.plugins', []);
// Named rather than fatal. Without this the foreach below dies inside
// a package provider on a mistake that lives in the application's own
// config file, and the stack trace points anywhere but at the line
// that has to change.
if (! is_array($plugins)) {
throw PluginRegistrationException::invalidPluginList($plugins);
}
foreach ($plugins as $pluginClass) {
// A blank entry is a trailing comma in a published config file,
// not a declaration, and skipping it is the same tolerance
// ResourceRegistry::registerMany() extends to the same mistake.
if (! is_string($pluginClass) || $pluginClass === '') {
continue;
}
// Anything else that is named and cannot be a plugin is refused.
// It used to be skipped, and that is the silence this replaces: a
// typo in a class name meant the plugin — a whole domain module,
// for the axis that registers this way — simply did not exist, with
// no menu entry and no error to say why.
if (! is_subclass_of($pluginClass, Plugin::class)) {
throw PluginRegistrationException::notAPlugin($pluginClass, Plugin::class);
}