@mpfrontend/access-react 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +57 -2
- package/dist/browser-refusal.d.ts +1 -0
- package/dist/browser-refusal.js +4 -0
- package/dist/browser-refusal.js.map +1 -0
- package/dist/index.d.ts +81 -0
- package/dist/index.js +127 -0
- package/dist/index.js.map +1 -0
- package/dist/server.d.ts +34 -0
- package/dist/server.js +40 -0
- package/dist/server.js.map +1 -0
- package/dist/testing.d.ts +5 -0
- package/dist/testing.js +24 -0
- package/dist/testing.js.map +1 -0
- package/package.json +43 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,58 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @mpfrontend/access-react
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Local development package. Runtime: client, with a server-only entry. Public API is exported from
|
|
4
|
+
`src/index.tsx`, `src/server.ts` and `src/testing.ts` and compiled into dist. Nx owns build, typecheck, lint and
|
|
5
|
+
test targets. Consumer applications install packed artifacts. See ../../docs/IMPLEMENTATION-STATUS.md for
|
|
6
|
+
observed evidence and remaining work.
|
|
7
|
+
|
|
8
|
+
React bindings for an access snapshot of `@mpfrontend/access-core`. The consumer's server decides what each
|
|
9
|
+
person may see and do: it resolves its own rules into an explicit snapshot (context reference, revision, expiry,
|
|
10
|
+
capabilities and fields) and sends it through the BFF. The UI shows menus, pages, actions and fields from that
|
|
11
|
+
snapshot only; whatever it does not grant stays closed. A hidden control is not authorization: the BFF, the
|
|
12
|
+
gateway and every service still check each request. No export takes a role name or reads a token claim, and
|
|
13
|
+
nothing here calls the identity provider or a policy service.
|
|
14
|
+
|
|
15
|
+
## Server entry: `@mpfrontend/access-react/server`
|
|
16
|
+
|
|
17
|
+
`createAccessLoader({load, contextRef, keys, timeoutMs})` returns a function of one request object (for example
|
|
18
|
+
`await headers()` in a server component). It calls the consumer's `load` (its own endpoint, reached through the
|
|
19
|
+
BFF) with an abort signal bounded by `timeoutMs`, validates the answer at run time (shape, context reference and
|
|
20
|
+
revision, expiry, the request's `contextRef`, the known `keys`) and memoizes the result for that request object.
|
|
21
|
+
A malformed, expired or mismatched snapshot, a failed load and a slow one grant nothing.
|
|
22
|
+
`clientSnapshot(result, keys)` keeps only the keys a provider's components need (`pageKeys` and `navigationKeys`
|
|
23
|
+
of the page manifest), never identity or token data, and is `null` when nothing is granted.
|
|
24
|
+
|
|
25
|
+
The entry is never part of a browser bundle: its `browser` export condition resolves to a module that throws
|
|
26
|
+
`ACCESS_SERVER_ENTRY_IN_BROWSER`.
|
|
27
|
+
|
|
28
|
+
## Client entry: `@mpfrontend/access-react`
|
|
29
|
+
|
|
30
|
+
- `AccessProvider` holds one snapshot for its subtree and is read during server rendering, so the first paint
|
|
31
|
+
shows no forbidden entry. It validates the snapshot it receives (`keys` and `contextRef` when given). A new
|
|
32
|
+
snapshot replaces the old one whole. At `expiresAt` it closes every entry, on an idle screen too, with a timer.
|
|
33
|
+
When the window regains focus it calls `reload(signal)`, and the answer replaces the snapshot; an answer that
|
|
34
|
+
arrives after the snapshot was replaced is dropped. Work captured with `useAccessCapture()` is aborted and cannot
|
|
35
|
+
publish once the context or revision changes (`AuthorityFence`).
|
|
36
|
+
- `useCapability(key)` returns whether the capability is granted. `useFieldState(key, {disabled, busy})` returns
|
|
37
|
+
`hidden`, `disabled` or `enabled`; a control that is already disabled or busy stays disabled. `useAccess()` returns
|
|
38
|
+
the reader for loops and forms (`ResourceForm` and `ResourceTable` of `@mpfrontend/ui` take it as `access`).
|
|
39
|
+
`useAccessScope()` returns the context reference and revision in use; `useAccessStatus()` returns `granted`,
|
|
40
|
+
`missing`, `invalid` or `expired`.
|
|
41
|
+
- `AccessGuard` renders its children only when its capability is granted and otherwise nothing. A `fallback`, or
|
|
42
|
+
`whenDenied="disabled"` with a render function, only when that guard asks for it.
|
|
43
|
+
- `AccessLink` renders no anchor, href, prefetch or focus target when denied; `as` takes the router's link
|
|
44
|
+
component, for example `next/link`.
|
|
45
|
+
- `useNavigation(manifest)` builds navigation from the page manifest and the snapshot.
|
|
46
|
+
|
|
47
|
+
A missing provider, a missing, malformed or expired snapshot and an unknown key close every kind of entry: menu,
|
|
48
|
+
page, element and field. The browser decides no rule; a rule such as "open unless denied" is resolved by the
|
|
49
|
+
consumer's server into the snapshot.
|
|
50
|
+
|
|
51
|
+
## Page manifest
|
|
52
|
+
|
|
53
|
+
`definePageManifest` (from `@mpfrontend/access-core`) lists every route once: the capability its page needs, the
|
|
54
|
+
capability of its menu entry, its elements (an element's own stable id is its capability key unless it names
|
|
55
|
+
another) and the field keys its components read, plus navigation groups. A test of the consumer runs
|
|
56
|
+
`assertPageManifest(manifest, {routes: await appRoutes('src/app'), ids})`, with `appRoutes` from
|
|
57
|
+
`@mpfrontend/access-react/testing`; it fails on a duplicate id, an id the app uses that the manifest does not
|
|
58
|
+
register, and a route with no manifest entry.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// A browser bundle resolves the server entry to this module, so the loader never reaches a browser.
|
|
2
|
+
throw new Error('ACCESS_SERVER_ENTRY_IN_BROWSER: import @mpfrontend/access-react/server only from server code');
|
|
3
|
+
export {};
|
|
4
|
+
//# sourceMappingURL=browser-refusal.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"browser-refusal.js","sourceRoot":"","sources":["../src/browser-refusal.ts"],"names":[],"mappings":"AAAA,oGAAoG;AACpG,MAAM,IAAI,KAAK,CAAC,8FAA8F,CAAC,CAAC;AAChH,OAAO,EAAE,CAAC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { type ComponentPropsWithoutRef, type ElementType, type ReactNode } from 'react';
|
|
2
|
+
import { type AccessKeys, type AccessReader, type ControlState, type FieldPresentation, type NavigationEntry, type PageManifest } from '@mpfrontend/access-core';
|
|
3
|
+
/** granted: a valid snapshot is in use. Every other status closes every entry. */
|
|
4
|
+
export type AccessStatus = 'granted' | 'missing' | 'invalid' | 'expired';
|
|
5
|
+
/** The context reference and revision of the snapshot in use: the scope of data read under it. */
|
|
6
|
+
export type AccessScope = Readonly<{
|
|
7
|
+
contextRef: string;
|
|
8
|
+
revision: string;
|
|
9
|
+
}>;
|
|
10
|
+
export type AccessCapture = Readonly<{
|
|
11
|
+
signal: AbortSignal;
|
|
12
|
+
assertCurrent: () => void;
|
|
13
|
+
}>;
|
|
14
|
+
export type AccessProviderProps = Readonly<{
|
|
15
|
+
/** The part of the snapshot this subtree needs, as the server sent it; it is validated before use. */
|
|
16
|
+
snapshot: unknown;
|
|
17
|
+
/** Asks the consumer's loader again, through its own route or the BFF. Called when the window regains focus. */
|
|
18
|
+
reload?: (signal: AbortSignal) => Promise<unknown>;
|
|
19
|
+
/** The keys this subtree knows; a snapshot that names another key is refused. */
|
|
20
|
+
keys?: AccessKeys;
|
|
21
|
+
/** The context this subtree is in; a snapshot of another context is refused. */
|
|
22
|
+
contextRef?: string;
|
|
23
|
+
now?: () => number;
|
|
24
|
+
children?: ReactNode;
|
|
25
|
+
}>;
|
|
26
|
+
/**
|
|
27
|
+
* Holds one access snapshot for its subtree, readable during server rendering. A new snapshot replaces the old one
|
|
28
|
+
* whole; at its expiry every entry closes, on an idle screen too; the loader is asked again when the window regains
|
|
29
|
+
* focus. Work captured under one context and revision is aborted and cannot publish once they change. The snapshot
|
|
30
|
+
* presents the server's decision; it never authorizes a request.
|
|
31
|
+
*/
|
|
32
|
+
export declare function AccessProvider({ snapshot, reload, keys, contextRef, now, children }: AccessProviderProps): import("react").FunctionComponentElement<import("react").ProviderProps<Readonly<{
|
|
33
|
+
reader: AccessReader;
|
|
34
|
+
status: AccessStatus;
|
|
35
|
+
scope: AccessScope | undefined;
|
|
36
|
+
capture: () => AccessCapture;
|
|
37
|
+
now: () => number;
|
|
38
|
+
}>>>;
|
|
39
|
+
/** The snapshot reader of the nearest provider; without a provider every entry is closed. */
|
|
40
|
+
export declare function useAccess(): AccessReader;
|
|
41
|
+
export declare function useAccessStatus(): AccessStatus;
|
|
42
|
+
/** The context reference and revision in use, or undefined when no valid snapshot is held. */
|
|
43
|
+
export declare function useAccessScope(): AccessScope | undefined;
|
|
44
|
+
/**
|
|
45
|
+
* Captures the current context and revision for asynchronous work: abort with the signal and call assertCurrent
|
|
46
|
+
* before publishing a result. It throws AUTHORITY_CHANGED when no valid snapshot is held.
|
|
47
|
+
*/
|
|
48
|
+
export declare function useAccessCapture(): () => AccessCapture;
|
|
49
|
+
export declare function useCapability(capability: string): boolean;
|
|
50
|
+
/** hidden, disabled or enabled; a control that is already disabled or busy stays disabled. */
|
|
51
|
+
export declare function useFieldState(key: string, state?: ControlState): FieldPresentation;
|
|
52
|
+
/** The navigation that the manifest and the snapshot allow. */
|
|
53
|
+
export declare function useNavigation(manifest: PageManifest): readonly NavigationEntry[];
|
|
54
|
+
export type AccessGuardProps = Readonly<{
|
|
55
|
+
capability: string;
|
|
56
|
+
children?: ReactNode;
|
|
57
|
+
fallback?: ReactNode;
|
|
58
|
+
whenDenied?: never;
|
|
59
|
+
}> | Readonly<{
|
|
60
|
+
capability: string;
|
|
61
|
+
whenDenied: 'disabled';
|
|
62
|
+
children: (state: Readonly<{
|
|
63
|
+
disabled: boolean;
|
|
64
|
+
}>) => ReactNode;
|
|
65
|
+
fallback?: never;
|
|
66
|
+
}>;
|
|
67
|
+
/**
|
|
68
|
+
* Renders its children only when the capability is granted, and otherwise nothing. A fallback, or children rendered
|
|
69
|
+
* in a disabled state, only when this guard asks for it.
|
|
70
|
+
*/
|
|
71
|
+
export declare function AccessGuard(props: AccessGuardProps): ReactNode;
|
|
72
|
+
export type AccessLinkProps<C extends ElementType> = Readonly<{
|
|
73
|
+
capability: string;
|
|
74
|
+
as?: C;
|
|
75
|
+
fallback?: ReactNode;
|
|
76
|
+
}> & Omit<ComponentPropsWithoutRef<C>, 'capability' | 'as' | 'fallback'>;
|
|
77
|
+
/**
|
|
78
|
+
* A link that exists only when its capability is granted. When denied it renders no anchor, no href, no prefetch
|
|
79
|
+
* and no focus target: nothing, or the fallback this link asks for. `as` renders the router's own link component.
|
|
80
|
+
*/
|
|
81
|
+
export declare function AccessLink<C extends ElementType = 'a'>({ capability, as, fallback, ...props }: AccessLinkProps<C>): ReactNode;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { createContext, createElement, useContext, useEffect, useMemo, useRef, useState } from 'react';
|
|
3
|
+
import { AuthorityFence, accessReader, buildNavigation, parsePageAccess } from '@mpfrontend/access-core';
|
|
4
|
+
const refusedCapture = () => { throw new DOMException('AUTHORITY_CHANGED', 'AbortError'); };
|
|
5
|
+
const CLOSED = Object.freeze({ reader: accessReader(undefined), status: 'missing', scope: undefined, capture: refusedCapture, now: Date.now });
|
|
6
|
+
const AccessContext = createContext(CLOSED);
|
|
7
|
+
// setTimeout holds at most 2^31-1 milliseconds; a longer lifetime re-arms the timer.
|
|
8
|
+
const MAX_DELAY = 2147483647;
|
|
9
|
+
/**
|
|
10
|
+
* Holds one access snapshot for its subtree, readable during server rendering. A new snapshot replaces the old one
|
|
11
|
+
* whole; at its expiry every entry closes, on an idle screen too; the loader is asked again when the window regains
|
|
12
|
+
* focus. Work captured under one context and revision is aborted and cannot publish once they change. The snapshot
|
|
13
|
+
* presents the server's decision; it never authorizes a request.
|
|
14
|
+
*/
|
|
15
|
+
export function AccessProvider({ snapshot, reload, keys, contextRef, now = Date.now, children }) {
|
|
16
|
+
const evaluate = (value) => {
|
|
17
|
+
if (value === undefined || value === null)
|
|
18
|
+
return { status: 'missing', snapshot: undefined };
|
|
19
|
+
const result = parsePageAccess(value, { now: now(), ...(keys ? { keys } : {}), ...(contextRef !== undefined ? { contextRef } : {}) });
|
|
20
|
+
return result.ok ? { status: 'granted', snapshot: result.access } : { status: result.reason === 'EXPIRED' ? 'expired' : 'invalid', snapshot: undefined };
|
|
21
|
+
};
|
|
22
|
+
const [held, setHeld] = useState(() => ({ source: snapshot, current: evaluate(snapshot) }));
|
|
23
|
+
let state = held;
|
|
24
|
+
if (held.source !== snapshot) {
|
|
25
|
+
// A new snapshot from the server replaces the held one whole during this render.
|
|
26
|
+
state = { source: snapshot, current: evaluate(snapshot) };
|
|
27
|
+
setHeld(state);
|
|
28
|
+
}
|
|
29
|
+
const { current } = state;
|
|
30
|
+
const fence = useRef(null);
|
|
31
|
+
if (!fence.current)
|
|
32
|
+
fence.current = new AuthorityFence();
|
|
33
|
+
const identity = current.snapshot ? current.snapshot.contextRef + '\n' + current.snapshot.revision : null;
|
|
34
|
+
// Idempotent for an unchanged identity; a change aborts the work captured under the previous one before any
|
|
35
|
+
// child reads the new scope.
|
|
36
|
+
fence.current.update(identity);
|
|
37
|
+
const latest = useRef(state);
|
|
38
|
+
useEffect(() => { latest.current = state; });
|
|
39
|
+
const expiresAt = current.snapshot?.expiresAt;
|
|
40
|
+
useEffect(() => {
|
|
41
|
+
if (expiresAt === undefined)
|
|
42
|
+
return;
|
|
43
|
+
let timer;
|
|
44
|
+
const check = () => {
|
|
45
|
+
const left = expiresAt - now();
|
|
46
|
+
if (left > 0) {
|
|
47
|
+
timer = setTimeout(check, Math.min(left, MAX_DELAY));
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
setHeld(previous => previous.current.snapshot?.expiresAt === expiresAt && previous.current.status === 'granted'
|
|
51
|
+
? { source: previous.source, current: { status: 'expired', snapshot: undefined } } : previous);
|
|
52
|
+
};
|
|
53
|
+
check();
|
|
54
|
+
return () => clearTimeout(timer);
|
|
55
|
+
}, [expiresAt, now]);
|
|
56
|
+
const reloadRef = useRef(reload);
|
|
57
|
+
useEffect(() => { reloadRef.current = reload; });
|
|
58
|
+
const canReload = reload !== undefined;
|
|
59
|
+
const evaluateRef = useRef(evaluate);
|
|
60
|
+
useEffect(() => { evaluateRef.current = evaluate; });
|
|
61
|
+
useEffect(() => {
|
|
62
|
+
if (!canReload)
|
|
63
|
+
return;
|
|
64
|
+
let controller;
|
|
65
|
+
const run = () => {
|
|
66
|
+
controller?.abort();
|
|
67
|
+
const own = controller = new AbortController(), startedWith = latest.current;
|
|
68
|
+
Promise.resolve().then(() => reloadRef.current?.(own.signal)).then(value => {
|
|
69
|
+
if (own.signal.aborted)
|
|
70
|
+
return;
|
|
71
|
+
// A snapshot that replaced this one while the request was pending wins; the late answer is dropped.
|
|
72
|
+
setHeld(previous => previous === startedWith ? { source: previous.source, current: evaluateRef.current(value) } : previous);
|
|
73
|
+
}, () => undefined);
|
|
74
|
+
};
|
|
75
|
+
const visible = () => { if (document.visibilityState === 'visible')
|
|
76
|
+
run(); };
|
|
77
|
+
window.addEventListener('focus', run);
|
|
78
|
+
document.addEventListener('visibilitychange', visible);
|
|
79
|
+
return () => { controller?.abort(); window.removeEventListener('focus', run); document.removeEventListener('visibilitychange', visible); };
|
|
80
|
+
}, [canReload]);
|
|
81
|
+
const value = useMemo(() => {
|
|
82
|
+
const scope = current.snapshot ? Object.freeze({ contextRef: current.snapshot.contextRef, revision: current.snapshot.revision }) : undefined;
|
|
83
|
+
const owner = fence.current;
|
|
84
|
+
return Object.freeze({ reader: accessReader(current.snapshot, now), status: current.status, scope,
|
|
85
|
+
capture: identity === null ? refusedCapture : () => owner.capture(identity), now });
|
|
86
|
+
}, [current, identity, now]);
|
|
87
|
+
return createElement(AccessContext.Provider, { value }, children);
|
|
88
|
+
}
|
|
89
|
+
/** The snapshot reader of the nearest provider; without a provider every entry is closed. */
|
|
90
|
+
export function useAccess() { return useContext(AccessContext).reader; }
|
|
91
|
+
export function useAccessStatus() { return useContext(AccessContext).status; }
|
|
92
|
+
/** The context reference and revision in use, or undefined when no valid snapshot is held. */
|
|
93
|
+
export function useAccessScope() { return useContext(AccessContext).scope; }
|
|
94
|
+
/**
|
|
95
|
+
* Captures the current context and revision for asynchronous work: abort with the signal and call assertCurrent
|
|
96
|
+
* before publishing a result. It throws AUTHORITY_CHANGED when no valid snapshot is held.
|
|
97
|
+
*/
|
|
98
|
+
export function useAccessCapture() { return useContext(AccessContext).capture; }
|
|
99
|
+
export function useCapability(capability) { return useAccess().can(capability); }
|
|
100
|
+
/** hidden, disabled or enabled; a control that is already disabled or busy stays disabled. */
|
|
101
|
+
export function useFieldState(key, state = {}) { return useAccess().fieldState(key, state); }
|
|
102
|
+
/** The navigation that the manifest and the snapshot allow. */
|
|
103
|
+
export function useNavigation(manifest) {
|
|
104
|
+
const { reader, now } = useContext(AccessContext);
|
|
105
|
+
return buildNavigation(manifest, reader.snapshot, now());
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Renders its children only when the capability is granted, and otherwise nothing. A fallback, or children rendered
|
|
109
|
+
* in a disabled state, only when this guard asks for it.
|
|
110
|
+
*/
|
|
111
|
+
export function AccessGuard(props) {
|
|
112
|
+
const granted = useCapability(props.capability);
|
|
113
|
+
if (props.whenDenied === 'disabled')
|
|
114
|
+
return props.children({ disabled: !granted });
|
|
115
|
+
return granted ? props.children : (props.fallback ?? null);
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* A link that exists only when its capability is granted. When denied it renders no anchor, no href, no prefetch
|
|
119
|
+
* and no focus target: nothing, or the fallback this link asks for. `as` renders the router's own link component.
|
|
120
|
+
*/
|
|
121
|
+
export function AccessLink({ capability, as, fallback, ...props }) {
|
|
122
|
+
const granted = useCapability(capability);
|
|
123
|
+
if (!granted)
|
|
124
|
+
return fallback ?? null;
|
|
125
|
+
return createElement(as ?? 'a', props);
|
|
126
|
+
}
|
|
127
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;AACb,OAAO,EAAC,aAAa,EAAC,aAAa,EAAC,UAAU,EAAC,SAAS,EAAC,OAAO,EAAC,MAAM,EAAC,QAAQ,EAChB,MAAM,OAAO,CAAC;AAC9E,OAAO,EAAC,cAAc,EAAC,YAAY,EAAC,eAAe,EAAC,eAAe,EACiE,MAAM,yBAAyB,CAAC;AAUpK,MAAM,cAAc,GAAC,GAAgB,EAAE,GAAC,MAAM,IAAI,YAAY,CAAC,mBAAmB,EAAC,YAAY,CAAC,CAAC,CAAA,CAAC,CAAC;AACnG,MAAM,MAAM,GAAO,MAAM,CAAC,MAAM,CAAC,EAAC,MAAM,EAAC,YAAY,CAAC,SAAS,CAAC,EAAC,MAAM,EAAC,SAAS,EAAC,KAAK,EAAC,SAAS,EAAC,OAAO,EAAC,cAAc,EAAC,GAAG,EAAC,IAAI,CAAC,GAAG,EAAC,CAAC,CAAC;AACxI,MAAM,aAAa,GAAC,aAAa,CAAQ,MAAM,CAAC,CAAC;AACjD,qFAAqF;AACrF,MAAM,SAAS,GAAC,UAAU,CAAC;AAe3B;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAAC,EAAC,QAAQ,EAAC,MAAM,EAAC,IAAI,EAAC,UAAU,EAAC,GAAG,GAAC,IAAI,CAAC,GAAG,EAAC,QAAQ,EAAqB;IACxG,MAAM,QAAQ,GAAC,CAAC,KAAa,EAAS,EAAE;QACtC,IAAG,KAAK,KAAG,SAAS,IAAE,KAAK,KAAG,IAAI;YAAC,OAAO,EAAC,MAAM,EAAC,SAAS,EAAC,QAAQ,EAAC,SAAS,EAAC,CAAC;QAChF,MAAM,MAAM,GAAC,eAAe,CAAC,KAA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AAC,QAAQ,CAAA,CAAC,CAAA,CAAC,KAAK,CAAC,QAAQ,IAAE,IAAI,CAAC,CAAC;AACvD,CAAC;AAID;;;GAGG;AACH,MAAM,UAAU,UAAU,CAA4B,EAAC,UAAU,EAAC,EAAE,EAAC,QAAQ,EAAC,GAAG,KAAK,EAAoB;IACxG,MAAM,OAAO,GAAC,aAAa,CAAC,UAAU,CAAC,CAAC;IACxC,IAAG,CAAC,OAAO;QAAC,OAAO,QAAQ,IAAE,IAAI,CAAC;IAClC,OAAO,aAAa,CAAC,EAAE,IAAE,GAAG,EAAC,KAAK,CAAC,CAAC;AACtC,CAAC"}
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type AccessKeys, type AccessRefusal, type PageAccess } from '@mpfrontend/access-core';
|
|
2
|
+
/** The snapshot this request may use, or why it may use none. Only `ok` grants anything. */
|
|
3
|
+
export type AccessResult = Readonly<{
|
|
4
|
+
ok: true;
|
|
5
|
+
access: PageAccess;
|
|
6
|
+
}> | Readonly<{
|
|
7
|
+
ok: false;
|
|
8
|
+
reason: AccessRefusal | 'UNAVAILABLE';
|
|
9
|
+
}>;
|
|
10
|
+
export type AccessLoaderOptions<Request extends object> = Readonly<{
|
|
11
|
+
/**
|
|
12
|
+
* Reads the snapshot from the consumer's own endpoint through the BFF, forwarding the request's session. The
|
|
13
|
+
* consumer's server has already resolved its rules into explicit grants; this package decides none.
|
|
14
|
+
*/
|
|
15
|
+
load: (request: Request, signal: AbortSignal) => Promise<unknown>;
|
|
16
|
+
/** The context reference this request is in; a snapshot of another context, or of none, is refused. */
|
|
17
|
+
contextRef: (request: Request) => string | undefined | Promise<string | undefined>;
|
|
18
|
+
/** Every key the app knows (manifestKeys of its page manifest); a snapshot that names another key is refused. */
|
|
19
|
+
keys: AccessKeys;
|
|
20
|
+
/** The time bound of one load, in milliseconds. */
|
|
21
|
+
timeoutMs: number;
|
|
22
|
+
now?: () => number;
|
|
23
|
+
}>;
|
|
24
|
+
/**
|
|
25
|
+
* A server-only loader. It loads, validates (shape, revision, expiry, context reference, known keys) and memoizes the
|
|
26
|
+
* snapshot once per request object: pass the same object for one request, for example the headers of a server
|
|
27
|
+
* component's request. A failed or slow load, and a malformed, expired or mismatched snapshot, grant nothing.
|
|
28
|
+
*/
|
|
29
|
+
export declare function createAccessLoader<Request extends object>(options: AccessLoaderOptions<Request>): (request: Request) => Promise<AccessResult>;
|
|
30
|
+
/**
|
|
31
|
+
* The part of the result that a provider receives: only the listed keys, never identity or token data. null when the
|
|
32
|
+
* result grants nothing, which the provider treats as a missing snapshot.
|
|
33
|
+
*/
|
|
34
|
+
export declare function clientSnapshot(result: AccessResult, keys: AccessKeys): PageAccess | null;
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { parsePageAccess, pickPageAccess } from '@mpfrontend/access-core';
|
|
2
|
+
/**
|
|
3
|
+
* A server-only loader. It loads, validates (shape, revision, expiry, context reference, known keys) and memoizes the
|
|
4
|
+
* snapshot once per request object: pass the same object for one request, for example the headers of a server
|
|
5
|
+
* component's request. A failed or slow load, and a malformed, expired or mismatched snapshot, grant nothing.
|
|
6
|
+
*/
|
|
7
|
+
export function createAccessLoader(options) {
|
|
8
|
+
if (!Number.isInteger(options.timeoutMs) || options.timeoutMs <= 0)
|
|
9
|
+
throw new Error('ACCESS_LOAD_TIMEOUT_REQUIRED');
|
|
10
|
+
const memo = new WeakMap();
|
|
11
|
+
const read = async (request) => {
|
|
12
|
+
const signal = AbortSignal.timeout(options.timeoutMs);
|
|
13
|
+
try {
|
|
14
|
+
const timedOut = new Promise((_, reject) => signal.addEventListener('abort', () => reject(signal.reason), { once: true }));
|
|
15
|
+
const [value, contextRef] = await Promise.race([Promise.all([options.load(request, signal), options.contextRef(request)]), timedOut]);
|
|
16
|
+
if (contextRef === undefined)
|
|
17
|
+
return { ok: false, reason: 'CONTEXT_MISMATCH' };
|
|
18
|
+
return parsePageAccess(value, { now: (options.now ?? Date.now)(), contextRef, keys: options.keys });
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return { ok: false, reason: 'UNAVAILABLE' };
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
return request => {
|
|
25
|
+
let pending = memo.get(request);
|
|
26
|
+
if (!pending) {
|
|
27
|
+
pending = read(request);
|
|
28
|
+
memo.set(request, pending);
|
|
29
|
+
}
|
|
30
|
+
return pending;
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* The part of the result that a provider receives: only the listed keys, never identity or token data. null when the
|
|
35
|
+
* result grants nothing, which the provider treats as a missing snapshot.
|
|
36
|
+
*/
|
|
37
|
+
export function clientSnapshot(result, keys) {
|
|
38
|
+
return result.ok ? pickPageAccess(result.access, keys) : null;
|
|
39
|
+
}
|
|
40
|
+
//# sourceMappingURL=server.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,eAAe,EAAC,cAAc,EAAoD,MAAM,yBAAyB,CAAC;AAmB1H;;;;GAIG;AACH,MAAM,UAAU,kBAAkB,CAAyB,OAAoC;IAC7F,IAAG,CAAC,MAAM,CAAC,SAAS,CAAC,OAAO,CAAC,SAAS,CAAC,IAAE,OAAO,CAAC,SAAS,IAAE,CAAC;QAAC,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;IAC9G,MAAM,IAAI,GAAC,IAAI,OAAO,EAAiC,CAAC;IACxD,MAAM,IAAI,GAAC,KAAK,EAAC,OAAe,EAAuB,EAAE;QACvD,MAAM,MAAM,GAAC,WAAW,CAAC,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;QACpD,IAAG,CAAC;YACF,MAAM,QAAQ,GAAC,IAAI,OAAO,CAAQ,CAAC,CAAC,EAAC,MAAM,EAAC,EAAE,CAAA,MAAM,CAAC,gBAAgB,CAAC,OAAO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,IAAI,CAAC,CAAA,CAAC,CAAA,IAAI,CAAC;AAC3D,CAAC"}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The page routes of a Next.js app folder, for a test of the page manifest: `/orders`, `/orders/[position]`.
|
|
3
|
+
* Route groups `(name)` add no segment; private folders `_name`, parallel slots `@name` and their pages are skipped.
|
|
4
|
+
*/
|
|
5
|
+
export declare function appRoutes(appDirectory: string): Promise<string[]>;
|
package/dist/testing.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { readdir } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
const PAGE = /^page\.(?:tsx|ts|jsx|js|mdx)$/;
|
|
4
|
+
/**
|
|
5
|
+
* The page routes of a Next.js app folder, for a test of the page manifest: `/orders`, `/orders/[position]`.
|
|
6
|
+
* Route groups `(name)` add no segment; private folders `_name`, parallel slots `@name` and their pages are skipped.
|
|
7
|
+
*/
|
|
8
|
+
export async function appRoutes(appDirectory) {
|
|
9
|
+
const routes = [];
|
|
10
|
+
const visit = async (directory, segments) => {
|
|
11
|
+
for (const entry of (await readdir(directory, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
12
|
+
if (entry.isDirectory()) {
|
|
13
|
+
if (entry.name.startsWith('_') || entry.name.startsWith('@'))
|
|
14
|
+
continue;
|
|
15
|
+
await visit(join(directory, entry.name), /^\(.*\)$/.test(entry.name) ? segments : [...segments, entry.name]);
|
|
16
|
+
}
|
|
17
|
+
else if (PAGE.test(entry.name))
|
|
18
|
+
routes.push('/' + segments.join('/'));
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
await visit(appDirectory, []);
|
|
22
|
+
return [...new Set(routes)].sort();
|
|
23
|
+
}
|
|
24
|
+
//# sourceMappingURL=testing.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"testing.js","sourceRoot":"","sources":["../src/testing.ts"],"names":[],"mappings":"A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AAG,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;AACrC,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,46 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mpfrontend/access-react",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/panahister/mpfrontend.git",
|
|
8
|
+
"directory": "packages/access-react"
|
|
9
|
+
},
|
|
10
|
+
"type": "module",
|
|
11
|
+
"main": "./dist/index.js",
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
16
|
+
"import": "./dist/index.js"
|
|
17
|
+
},
|
|
18
|
+
"./server": {
|
|
19
|
+
"types": "./dist/server.d.ts",
|
|
20
|
+
"browser": "./dist/browser-refusal.js",
|
|
21
|
+
"import": "./dist/server.js"
|
|
22
|
+
},
|
|
23
|
+
"./testing": {
|
|
24
|
+
"types": "./dist/testing.d.ts",
|
|
25
|
+
"import": "./dist/testing.js"
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
"files": [
|
|
29
|
+
"dist",
|
|
30
|
+
"README.md"
|
|
31
|
+
],
|
|
32
|
+
"publishConfig": {
|
|
33
|
+
"access": "public",
|
|
34
|
+
"provenance": true
|
|
35
|
+
},
|
|
36
|
+
"dependencies": {
|
|
37
|
+
"@mpfrontend/access-core": "0.1.0"
|
|
38
|
+
},
|
|
39
|
+
"devDependencies": {
|
|
40
|
+
"@happy-dom/global-registrator": "20.14.5",
|
|
41
|
+
"happy-dom": "20.14.5"
|
|
42
|
+
},
|
|
43
|
+
"peerDependencies": {
|
|
44
|
+
"react": "^19.3.0"
|
|
45
|
+
}
|
|
6
46
|
}
|