@eskais/app-sdk 0.1.0 → 0.2.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/README.md +17 -11
- package/dist/action/action.d.ts +69 -10
- package/dist/action/action.js +147 -29
- package/dist/action/bulk.d.ts +24 -0
- package/dist/action/bulk.js +24 -0
- package/dist/core/constants.d.ts +57 -0
- package/dist/core/constants.js +31 -0
- package/dist/core/contracts.d.ts +7 -0
- package/dist/core/data-labels.d.ts +14 -0
- package/dist/core/data-labels.js +40 -0
- package/dist/core/errors.d.ts +11 -5
- package/dist/core/errors.js +52 -9
- package/dist/dialogs/dialogs.d.ts +75 -0
- package/dist/dialogs/dialogs.js +66 -0
- package/dist/errors/adapters.d.ts +21 -0
- package/dist/errors/adapters.js +81 -0
- package/dist/errors/define-errors.d.ts +88 -0
- package/dist/errors/define-errors.js +168 -0
- package/dist/errors/idempotency.d.ts +2 -0
- package/dist/errors/idempotency.js +13 -0
- package/dist/i18n/adapters.d.ts +53 -0
- package/dist/i18n/adapters.js +56 -0
- package/dist/i18n/format.d.ts +10 -0
- package/dist/i18n/format.js +273 -0
- package/dist/i18n/labels.d.ts +10 -0
- package/dist/i18n/labels.js +227 -0
- package/dist/i18n/locale.d.ts +73 -0
- package/dist/i18n/locale.js +74 -0
- package/dist/i18n/messages.d.ts +93 -0
- package/dist/i18n/messages.js +16 -0
- package/dist/import/import.d.ts +4 -2
- package/dist/import/import.js +7 -4
- package/dist/index.d.ts +18 -3
- package/dist/index.js +17 -2
- package/dist/navigation/nav.d.ts +14 -5
- package/dist/navigation/nav.js +37 -14
- package/dist/next/server/index.d.ts +2 -1
- package/dist/next/server/index.js +2 -1
- package/dist/next/server/page.d.ts +8 -2
- package/dist/next/server/page.js +14 -7
- package/dist/next/server/session.d.ts +13 -0
- package/dist/next/server/session.js +13 -0
- package/dist/permissions/permissions.d.ts +134 -0
- package/dist/permissions/permissions.js +121 -0
- package/dist/react/data-layer.d.ts +42 -5
- package/dist/react/data-layer.js +49 -4
- package/dist/react/hooks/use-action-dialog.d.ts +25 -0
- package/dist/react/hooks/use-action-dialog.js +31 -0
- package/dist/react/hooks/use-action.d.ts +30 -5
- package/dist/react/hooks/use-action.js +85 -27
- package/dist/react/hooks/use-bulk-action.d.ts +20 -0
- package/dist/react/hooks/use-bulk-action.js +24 -0
- package/dist/react/hooks/use-dialogs.d.ts +14 -0
- package/dist/react/hooks/use-dialogs.js +20 -0
- package/dist/react/hooks/use-nav.js +3 -2
- package/dist/react/hooks/use-new-rows.d.ts +22 -0
- package/dist/react/hooks/use-new-rows.js +24 -0
- package/dist/react/hooks/use-permissions.d.ts +13 -0
- package/dist/react/hooks/use-permissions.js +19 -0
- package/dist/react/hooks/use-reauthenticate.d.ts +6 -0
- package/dist/react/hooks/use-reauthenticate.js +11 -0
- package/dist/react/hooks/use-resource.d.ts +28 -5
- package/dist/react/hooks/use-resource.js +63 -26
- package/dist/react/index.d.ts +11 -4
- package/dist/react/index.js +11 -4
- package/dist/react/keys.d.ts +9 -0
- package/dist/react/keys.js +4 -0
- package/dist/react/new-rows.d.ts +22 -0
- package/dist/react/new-rows.js +72 -0
- package/dist/refresh/new-rows.d.ts +13 -0
- package/dist/refresh/new-rows.js +18 -0
- package/dist/resource/resource-relations.d.ts +6 -3
- package/dist/resource/resource-relations.js +26 -13
- package/dist/resource/resource-schema.d.ts +1 -1
- package/dist/resource/resource-schema.js +1 -1
- package/dist/resource/resource-texts.d.ts +18 -0
- package/dist/resource/resource-texts.js +13 -0
- package/dist/resource/resource-types.d.ts +169 -30
- package/dist/resource/resource-words.d.ts +25 -0
- package/dist/resource/resource-words.js +221 -0
- package/dist/resource/resource.d.ts +6 -2
- package/dist/resource/resource.js +99 -173
- package/dist/services/read-only-service.d.ts +18 -0
- package/dist/services/read-only-service.js +25 -0
- package/dist/services/rest-service.d.ts +4 -1
- package/dist/services/rest-service.js +2 -0
- package/dist/view/view-types.d.ts +4 -2
- package/locales/en.json +193 -0
- package/locales/es.json +193 -0
- package/package.json +5 -2
package/dist/navigation/nav.d.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { type Allowed, type Refusal } from "../core/refusal.js";
|
|
|
4
4
|
import type { AnyResource, ToneName } from "../resource/resource.js";
|
|
5
5
|
import { type RouterAdapter } from "./router.js";
|
|
6
6
|
import type { Session } from "../session/session.js";
|
|
7
|
+
import { type Locale, type Text } from "../i18n/locale.js";
|
|
7
8
|
export type NavCount = {
|
|
8
9
|
readonly resource: AnyResource;
|
|
9
10
|
readonly filter: Record<string, unknown>;
|
|
@@ -18,7 +19,8 @@ export type NavBadge = NavCount | {
|
|
|
18
19
|
} | string | number;
|
|
19
20
|
export type NavItem = {
|
|
20
21
|
id: string;
|
|
21
|
-
label
|
|
22
|
+
/** Shown with `resolveText(item.label, locale)`; `navItem` gives the resource's name in the locale. */
|
|
23
|
+
label: Text;
|
|
22
24
|
to: string;
|
|
23
25
|
icon?: unknown;
|
|
24
26
|
/** `NavMatch.prefix` by default: `/customers/7` keeps Customers current. */
|
|
@@ -42,13 +44,13 @@ export type NavItem = {
|
|
|
42
44
|
*/
|
|
43
45
|
export type NavGroup = {
|
|
44
46
|
group: string;
|
|
45
|
-
label?:
|
|
47
|
+
label?: Text;
|
|
46
48
|
collapsible?: boolean;
|
|
47
49
|
items: readonly NavItem[];
|
|
48
50
|
};
|
|
49
51
|
export type TrailEntry = {
|
|
50
52
|
id: string;
|
|
51
|
-
label:
|
|
53
|
+
label: Text;
|
|
52
54
|
to: string;
|
|
53
55
|
item?: NavItem;
|
|
54
56
|
record?: {
|
|
@@ -67,7 +69,7 @@ export type NavOptions<Route = unknown> = {
|
|
|
67
69
|
items: readonly (NavGroup | NavItem)[];
|
|
68
70
|
session?: Session;
|
|
69
71
|
preferences?: PreferencesStore;
|
|
70
|
-
title?: (trail: readonly TrailEntry[]) => string;
|
|
72
|
+
title?: (trail: readonly TrailEntry[], locale: Locale | undefined) => string;
|
|
71
73
|
/** Builds `nav.routes()`: `tanstackRoutes({ parent: () => rootRoute })` from the `resource-routes` item. */
|
|
72
74
|
routes?: NavRouteBuilder<Route>;
|
|
73
75
|
/** How many recent pages to keep. Default 5. */
|
|
@@ -88,13 +90,18 @@ export type Nav<Route = unknown> = {
|
|
|
88
90
|
visibleItems(): readonly NavItem[];
|
|
89
91
|
find(id: string): NavItem | undefined;
|
|
90
92
|
check(item: NavItem): Allowed;
|
|
93
|
+
/**
|
|
94
|
+
* Whether the session may open a path: a resource's screen asks for its use (`list`, `create`, `get`, `update`),
|
|
95
|
+
* any other page for its item's `can`. The nav's session by default; a route guard passes the `DataLayer`'s.
|
|
96
|
+
*/
|
|
97
|
+
checkPath(pathname?: string, session?: Session, notAllowed?: string): Allowed;
|
|
91
98
|
checkNavigate(id: string): Allowed;
|
|
92
99
|
navigate(id: string, options?: {
|
|
93
100
|
replace?: boolean;
|
|
94
101
|
}): void;
|
|
95
102
|
current(pathname?: string): NavItem | undefined;
|
|
96
103
|
trail(pathname?: string): readonly TrailEntry[];
|
|
97
|
-
documentTitle(pathname?: string): string | undefined;
|
|
104
|
+
documentTitle(pathname?: string, locale?: Locale): string | undefined;
|
|
98
105
|
resources(): readonly AnyResource[];
|
|
99
106
|
routes(): Route[];
|
|
100
107
|
getSnapshot(): NavSnapshot;
|
|
@@ -110,6 +117,8 @@ export type Nav<Route = unknown> = {
|
|
|
110
117
|
/** The same manifest over another router, with its own favorites and recents. */
|
|
111
118
|
withRouter(router: RouterAdapter): Nav<Route>;
|
|
112
119
|
};
|
|
120
|
+
/** The use a resource's screen needs: its list `list`, `new` `create`, a record `get` and its edit `update`. */
|
|
121
|
+
export declare function screenUse(screen: ResourceScreen): ResourceAction;
|
|
113
122
|
export declare function navItem(resource: AnyResource, overrides?: Partial<NavItem>): NavItem;
|
|
114
123
|
export declare function count(resource: AnyResource, filter?: Record<string, unknown>, options?: {
|
|
115
124
|
tone?: ToneName;
|
package/dist/navigation/nav.js
CHANGED
|
@@ -2,10 +2,21 @@ import { NavMatch, ResourceAction, ResourceScreen } from "../core/constants.js";
|
|
|
2
2
|
import { isFunction, isRecord, isString } from "../core/guards.js";
|
|
3
3
|
import { firstRefusal, refuse, toAllowed } from "../core/refusal.js";
|
|
4
4
|
import { memoryRouter } from "./router.js";
|
|
5
|
+
import { resolveText } from "../i18n/locale.js";
|
|
6
|
+
const screenUses = {
|
|
7
|
+
[ResourceScreen.list]: ResourceAction.list,
|
|
8
|
+
[ResourceScreen.create]: ResourceAction.create,
|
|
9
|
+
[ResourceScreen.detail]: ResourceAction.get,
|
|
10
|
+
[ResourceScreen.edit]: ResourceAction.update,
|
|
11
|
+
};
|
|
12
|
+
/** The use a resource's screen needs: its list `list`, `new` `create`, a record `get` and its edit `update`. */
|
|
13
|
+
export function screenUse(screen) {
|
|
14
|
+
return screenUses[screen];
|
|
15
|
+
}
|
|
5
16
|
export function navItem(resource, overrides = {}) {
|
|
6
17
|
return {
|
|
7
18
|
id: resource.key,
|
|
8
|
-
label: resource.label(2),
|
|
19
|
+
label: (_t, locale) => resource.in(locale).label(2),
|
|
9
20
|
to: resource.paths.list(),
|
|
10
21
|
icon: resource.icon,
|
|
11
22
|
can: ResourceAction.list,
|
|
@@ -43,6 +54,16 @@ function matches(item, pathname) {
|
|
|
43
54
|
return path === target || (target === "/" ? false : path.startsWith(`${target}/`));
|
|
44
55
|
}
|
|
45
56
|
const unique = (ids) => [...new Set(ids)];
|
|
57
|
+
function checkWith(item, asking, notAllowed = "") {
|
|
58
|
+
const can = item.can;
|
|
59
|
+
if (can === undefined)
|
|
60
|
+
return true;
|
|
61
|
+
if (isFunction(can))
|
|
62
|
+
return toAllowed(can(), notAllowed);
|
|
63
|
+
if (item.resource && can === ResourceAction.list)
|
|
64
|
+
return item.resource.check(ResourceAction.list, undefined, asking, notAllowed);
|
|
65
|
+
return toAllowed(asking?.can(can), notAllowed);
|
|
66
|
+
}
|
|
46
67
|
const readIds = (value) => (Array.isArray(value) ? value.filter(isString) : []);
|
|
47
68
|
export function defineNav(options) {
|
|
48
69
|
const { session, preferences } = options;
|
|
@@ -75,16 +96,7 @@ export function defineNav(options) {
|
|
|
75
96
|
flush();
|
|
76
97
|
return result;
|
|
77
98
|
};
|
|
78
|
-
|
|
79
|
-
const can = item.can;
|
|
80
|
-
if (can === undefined)
|
|
81
|
-
return true;
|
|
82
|
-
if (isFunction(can))
|
|
83
|
-
return toAllowed(can(), "");
|
|
84
|
-
if (item.resource && can === ResourceAction.list)
|
|
85
|
-
return item.resource.check(ResourceAction.list, undefined, session);
|
|
86
|
-
return toAllowed(session?.can(can), "");
|
|
87
|
-
}
|
|
99
|
+
const check = (item) => checkWith(item, session);
|
|
88
100
|
const visible = (items) => items
|
|
89
101
|
.filter((item) => check(item) === true)
|
|
90
102
|
.map((item) => (item.children ? { ...item, children: visible(item.children) } : item));
|
|
@@ -196,6 +208,16 @@ export function defineNav(options) {
|
|
|
196
208
|
visibleItems: () => flatten(visible(groups().flatMap((group) => group.items))),
|
|
197
209
|
find,
|
|
198
210
|
check,
|
|
211
|
+
checkPath(given, asking = session, notAllowed = "") {
|
|
212
|
+
const path = pathname(given);
|
|
213
|
+
for (const item of allItems()) {
|
|
214
|
+
const match = item.resource?.match(path);
|
|
215
|
+
if (item.resource && match)
|
|
216
|
+
return item.resource.check(screenUse(match.screen), undefined, asking, notAllowed);
|
|
217
|
+
}
|
|
218
|
+
const item = current(path);
|
|
219
|
+
return item ? checkWith(item, asking, notAllowed) : true;
|
|
220
|
+
},
|
|
199
221
|
checkNavigate,
|
|
200
222
|
navigate(id, navigateOptions) {
|
|
201
223
|
const item = find(id);
|
|
@@ -205,12 +227,13 @@ export function defineNav(options) {
|
|
|
205
227
|
},
|
|
206
228
|
current,
|
|
207
229
|
trail,
|
|
208
|
-
documentTitle(given) {
|
|
230
|
+
documentTitle(given, locale) {
|
|
209
231
|
const entries = trail(given);
|
|
210
232
|
if (options.title)
|
|
211
|
-
return options.title(entries);
|
|
233
|
+
return options.title(entries, locale);
|
|
212
234
|
const last = entries.at(-1)?.label;
|
|
213
|
-
|
|
235
|
+
const text = last === undefined ? undefined : resolveText(last, locale);
|
|
236
|
+
return text === undefined || text === "" ? undefined : text;
|
|
214
237
|
},
|
|
215
238
|
resources() {
|
|
216
239
|
const found = allItems().flatMap((item) => (item.resource ? [item.resource] : []));
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export { navPage, resourcePage, type NextMetadata, type NextPage, type NextPageOptions, type NextPageProps, type SearchParams, } from "./page.js";
|
|
2
2
|
export { prefetchScreen, type AnyService, type PrefetchOptions, type PrefetchResult } from "./prefetch.js";
|
|
3
|
-
export { nextSession, type NextRequestScope } from "./session.js";
|
|
3
|
+
export { nextPermissionSession, nextSession, type NextPermissionSession, type NextRequestScope } from "./session.js";
|
|
4
|
+
export { sessionPayload, type SessionPayload } from "../../permissions/permissions.js";
|
|
4
5
|
export { problemResponse, queryOfSearch, resourceHandler, type NextRouteContext, type ResourceHandler, type ResourceHandlerOptions, type RouteHandler, } from "./handler.js";
|
|
5
6
|
export { navScreen, pathOfParams, resourceScreen, type NextScreen, type RouteParams } from "../screen.js";
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export { navPage, resourcePage, } from "./page.js";
|
|
2
2
|
export { prefetchScreen } from "./prefetch.js";
|
|
3
|
-
export { nextSession } from "./session.js";
|
|
3
|
+
export { nextPermissionSession, nextSession } from "./session.js";
|
|
4
|
+
export { sessionPayload } from "../../permissions/permissions.js";
|
|
4
5
|
export { problemResponse, queryOfSearch, resourceHandler, } from "./handler.js";
|
|
5
6
|
export { navScreen, pathOfParams, resourceScreen } from "../screen.js";
|
|
@@ -2,7 +2,8 @@ import { QueryClient } from "@tanstack/react-query";
|
|
|
2
2
|
import { type ReactNode } from "react";
|
|
3
3
|
import { ResourceScreen } from "../../core/constants.js";
|
|
4
4
|
import { type DataLabels } from "../../core/data-labels.js";
|
|
5
|
-
import type {
|
|
5
|
+
import type { Locale } from "../../i18n/locale.js";
|
|
6
|
+
import { type Nav } from "../../navigation/nav.js";
|
|
6
7
|
import type { AnyResource } from "../../resource/resource.js";
|
|
7
8
|
import type { Session } from "../../session/session.js";
|
|
8
9
|
import type { ViewOptions } from "../../view/view.js";
|
|
@@ -28,7 +29,12 @@ export type NextPageOptions = {
|
|
|
28
29
|
view?: (resource: AnyResource) => ViewOptions<unknown> | undefined;
|
|
29
30
|
/** Where the app is mounted (`/admin`), as given to `useNextRouter`. */
|
|
30
31
|
base?: string;
|
|
31
|
-
/**
|
|
32
|
+
/**
|
|
33
|
+
* The request's language, for the titles: a `Locale`, or a function that reads it per request, such as
|
|
34
|
+
* `async () => fromNextIntl(await getTranslations("eskais"), { locale: await getLocale() })`.
|
|
35
|
+
*/
|
|
36
|
+
locale?: Locale | (() => Locale | Promise<Locale>);
|
|
37
|
+
/** @deprecated Use `locale`. The words of the default titles without one: `dataLabelsEn` by default. */
|
|
32
38
|
labels?: DataLabels;
|
|
33
39
|
/** A screen's title, instead of the resource's label, "New …", the record's title or "Edit …". */
|
|
34
40
|
title?: (screen: NextScreen, row: unknown) => string | undefined;
|
package/dist/next/server/page.js
CHANGED
|
@@ -3,8 +3,10 @@ import { dehydrate, QueryClient } from "@tanstack/react-query";
|
|
|
3
3
|
import { notFound, redirect } from "next/navigation";
|
|
4
4
|
import { cache } from "react";
|
|
5
5
|
import { ResourceScreen } from "../../core/constants.js";
|
|
6
|
-
import { isString } from "../../core/guards.js";
|
|
6
|
+
import { isFunction, isString } from "../../core/guards.js";
|
|
7
7
|
import { dataLabelsEn } from "../../core/data-labels.js";
|
|
8
|
+
import { dataLabelsOf } from "../../i18n/labels.js";
|
|
9
|
+
import { screenUse } from "../../navigation/nav.js";
|
|
8
10
|
import { isSegments, navScreen, pathOfParams, resourceScreen } from "../screen.js";
|
|
9
11
|
import { ScreenHydration } from "../screen-hydration.js";
|
|
10
12
|
import { prefetchScreen } from "./prefetch.js";
|
|
@@ -22,21 +24,21 @@ function searchOf(params) {
|
|
|
22
24
|
const text = query.toString();
|
|
23
25
|
return text === "" ? "" : `?${text}`;
|
|
24
26
|
}
|
|
25
|
-
function defaultTitle(screen, row, labels) {
|
|
26
|
-
const
|
|
27
|
+
function defaultTitle(screen, row, labels, locale) {
|
|
28
|
+
const resource = screen.resource.in(locale);
|
|
27
29
|
const one = resource.label(1);
|
|
28
30
|
const named = row === undefined ? one : resource.title(row);
|
|
29
31
|
if (screen.screen === ResourceScreen.list)
|
|
30
32
|
return resource.label(2);
|
|
31
33
|
if (screen.screen === ResourceScreen.create)
|
|
32
|
-
return labels.create(one);
|
|
34
|
+
return resource.createLabel ?? labels.create(one);
|
|
33
35
|
if (screen.screen === ResourceScreen.edit)
|
|
34
36
|
return `${labels.edit} ${named}`;
|
|
35
37
|
return named;
|
|
36
38
|
}
|
|
37
39
|
function screenPage(resolve, options) {
|
|
38
40
|
const clientOf = options.client ?? requestClient;
|
|
39
|
-
const
|
|
41
|
+
const localeOf = () => (isFunction(options.locale) ? options.locale() : options.locale);
|
|
40
42
|
const base = (options.base ?? "").replace(/\/+$/u, "");
|
|
41
43
|
async function load(props) {
|
|
42
44
|
const screen = resolve(await props.params);
|
|
@@ -46,6 +48,9 @@ function screenPage(resolve, options) {
|
|
|
46
48
|
notFound();
|
|
47
49
|
const session = await options.session?.();
|
|
48
50
|
const client = clientOf();
|
|
51
|
+
// Security: a screen the session may not open renders without its data; the browser's route guard says why.
|
|
52
|
+
if (screen.resource.check(screenUse(screen.screen), undefined, session) !== true)
|
|
53
|
+
return { screen, client, row: undefined };
|
|
49
54
|
const result = await prefetchScreen(client, screen, {
|
|
50
55
|
session,
|
|
51
56
|
services: options.services,
|
|
@@ -62,8 +67,10 @@ function screenPage(resolve, options) {
|
|
|
62
67
|
return _jsx(ScreenHydration, { state: dehydrate(client), children: options.render(screen) });
|
|
63
68
|
},
|
|
64
69
|
async generateMetadata(props) {
|
|
65
|
-
const { screen, row } = await load(props);
|
|
66
|
-
|
|
70
|
+
const [{ screen, row }, locale] = await Promise.all([load(props), localeOf()]);
|
|
71
|
+
const gender = locale ? screen.resource.in(locale).gender : undefined;
|
|
72
|
+
const labels = locale && !options.labels ? dataLabelsOf(locale, gender) : (options.labels ?? dataLabelsEn);
|
|
73
|
+
return { title: options.title?.(screen, row) ?? defaultTitle(screen, row, labels, locale) };
|
|
67
74
|
},
|
|
68
75
|
};
|
|
69
76
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { cookies, headers } from "next/headers";
|
|
2
|
+
import { type Operations, type Permissions, type PermissionSession, type PermissionSessionOptions, type SessionPayload } from "../../permissions/permissions.js";
|
|
2
3
|
import type { Session } from "../../session/session.js";
|
|
3
4
|
export type NextRequestScope = {
|
|
4
5
|
cookies: Awaited<ReturnType<typeof cookies>>;
|
|
@@ -10,3 +11,15 @@ export type NextRequestScope = {
|
|
|
10
11
|
* auth library and returns `undefined` for nobody.
|
|
11
12
|
*/
|
|
12
13
|
export declare function nextSession<User>(read: (request: NextRequestScope) => Session<User> | undefined | Promise<Session<User> | undefined>): () => Promise<Session<User> | undefined>;
|
|
14
|
+
export type NextPermissionSession<User, Claims> = {
|
|
15
|
+
/** The request's session, once per request, for `navPage`, route handlers and server components. */
|
|
16
|
+
getSession: () => Promise<PermissionSession<User, Claims> | undefined>;
|
|
17
|
+
/** What a server component passes the browser's provider, for `usePermissionSession`: the user and the claims. */
|
|
18
|
+
payload: () => Promise<SessionPayload<User, Claims> | null>;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* A request's session over `definePermissions`: `read` loads the user and the claims (a role, the grants a backend
|
|
22
|
+
* sent) from the cookies or the token, the rules answer on the server, and `payload` hands the same claims to the
|
|
23
|
+
* browser, where `usePermissionSession` rebuilds the session so hidden buttons and routes agree with the server.
|
|
24
|
+
*/
|
|
25
|
+
export declare function nextPermissionSession<Ops extends Operations, Claims, User>(permissions: Permissions<Ops, Claims>, read: (request: NextRequestScope) => PermissionSessionOptions<User, Claims> | undefined | Promise<PermissionSessionOptions<User, Claims> | undefined>): NextPermissionSession<User, Claims>;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { cookies, headers } from "next/headers";
|
|
2
2
|
import { cache } from "react";
|
|
3
|
+
import { sessionPayload, } from "../../permissions/permissions.js";
|
|
3
4
|
/**
|
|
4
5
|
* The session of the request being rendered, from its cookies and headers, read once per request: pages,
|
|
5
6
|
* `generateMetadata`, layouts and route handlers all get the same one. `read` verifies the cookie or token with your
|
|
@@ -8,3 +9,15 @@ import { cache } from "react";
|
|
|
8
9
|
export function nextSession(read) {
|
|
9
10
|
return cache(async () => read({ cookies: await cookies(), headers: await headers() }));
|
|
10
11
|
}
|
|
12
|
+
/**
|
|
13
|
+
* A request's session over `definePermissions`: `read` loads the user and the claims (a role, the grants a backend
|
|
14
|
+
* sent) from the cookies or the token, the rules answer on the server, and `payload` hands the same claims to the
|
|
15
|
+
* browser, where `usePermissionSession` rebuilds the session so hidden buttons and routes agree with the server.
|
|
16
|
+
*/
|
|
17
|
+
export function nextPermissionSession(permissions, read) {
|
|
18
|
+
const getSession = cache(async () => {
|
|
19
|
+
const given = await read({ cookies: await cookies(), headers: await headers() });
|
|
20
|
+
return given === undefined ? undefined : permissions.session(given);
|
|
21
|
+
});
|
|
22
|
+
return { getSession, payload: async () => sessionPayload(await getSession()) };
|
|
23
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { ResourceAction } from "../core/constants.js";
|
|
2
|
+
import { type Allowed, type Refusal } from "../core/refusal.js";
|
|
3
|
+
import { type Locale, type TextRefusal } from "../i18n/locale.js";
|
|
4
|
+
import type { PermissionSubject, Session } from "../session/session.js";
|
|
5
|
+
/**
|
|
6
|
+
* Augment it once per app to type every `requires` (actions, columns, fields) with your operations:
|
|
7
|
+
* `declare module "@eskais/app-sdk" { interface Register { permissions: typeof permissions } }`.
|
|
8
|
+
*/
|
|
9
|
+
export interface Register {
|
|
10
|
+
}
|
|
11
|
+
/** The operations of a `Register`-like type: its permissions' vocabulary, or any string before one is registered. */
|
|
12
|
+
export type OperationOf<Registered> = Registered extends {
|
|
13
|
+
permissions: {
|
|
14
|
+
readonly operations: infer Ops;
|
|
15
|
+
};
|
|
16
|
+
} ? Ops[keyof Ops] & string : string;
|
|
17
|
+
/** The operations `requires` accepts: the registered permissions' vocabulary, or any string. */
|
|
18
|
+
export type RegisteredOperation = OperationOf<Register>;
|
|
19
|
+
/** An app's vocabulary of operations, as an `as const` object: `{ read: "read", write: "write" }`. */
|
|
20
|
+
export type Operations = Readonly<Record<string, string>>;
|
|
21
|
+
type OperationIn<Ops extends Operations> = Ops[keyof Ops] & string;
|
|
22
|
+
/** The key of a server's grants that holds what applies to every resource. */
|
|
23
|
+
export declare const GrantScope: {
|
|
24
|
+
readonly everyResource: "*";
|
|
25
|
+
};
|
|
26
|
+
export type GrantScope = (typeof GrantScope)[keyof typeof GrantScope];
|
|
27
|
+
export type PermissionContext<Claims, Operation extends string> = {
|
|
28
|
+
readonly claims: Claims;
|
|
29
|
+
readonly roles: readonly string[];
|
|
30
|
+
readonly operation: Operation;
|
|
31
|
+
/** The resource asked about; `undefined` for a page or a global action. */
|
|
32
|
+
readonly resource: string | undefined;
|
|
33
|
+
/** What was asked: a built-in use (`update`), an action's operation or a nav item's `can`. */
|
|
34
|
+
readonly use: string;
|
|
35
|
+
};
|
|
36
|
+
/** A rule's answer: a refusal's reason may be a message (`msg("orders.ownOnly")`), worded in the session's locale. */
|
|
37
|
+
export type PermissionAnswer = boolean | Refusal | TextRefusal;
|
|
38
|
+
type RowRule<Claims, Operation extends string, Row> = {
|
|
39
|
+
rule(context: PermissionContext<Claims, Operation>, row: Row | undefined): PermissionAnswer;
|
|
40
|
+
}["rule"];
|
|
41
|
+
/**
|
|
42
|
+
* `true` or `false`, or a function of the context and the row. Without a row it answers for the resource as a whole
|
|
43
|
+
* (the New button, a column, a route); with one, for that record (its menu, its edit form, an action on it).
|
|
44
|
+
*/
|
|
45
|
+
export type PermissionRule<Claims, Operation extends string, Row = unknown> = boolean | RowRule<Claims, Operation, Row>;
|
|
46
|
+
export type OperationRules<Claims, Operation extends string> = {
|
|
47
|
+
readonly [Key in Operation]?: PermissionRule<Claims, Operation, any>;
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* `roles` grant operations everywhere, by role. `resources` narrow them for one resource: an operation a resource's
|
|
51
|
+
* rule names needs both a role that grants it and the rule.
|
|
52
|
+
*/
|
|
53
|
+
export type PermissionRules<Claims, Operation extends string> = {
|
|
54
|
+
readonly roles?: Readonly<Record<string, OperationRules<Claims, Operation>>>;
|
|
55
|
+
readonly resources?: Readonly<Record<string, OperationRules<Claims, Operation>>>;
|
|
56
|
+
};
|
|
57
|
+
/** Which operation each use needs: the built-in ones (`create`, `list`…) and any action id or nav `can`. */
|
|
58
|
+
export type PermissionUses<Operation extends string> = Readonly<Partial<Record<ResourceAction | (string & {}), Operation>>>;
|
|
59
|
+
/** Operations a server granted, by resource key, `GrantScope.everyResource` for all of them: `{ orders: ["approve"] }`. */
|
|
60
|
+
export type Grants<Operation extends string> = Readonly<Record<string, readonly Operation[]>>;
|
|
61
|
+
export type PermissionsOptions<Ops extends Operations, Claims> = {
|
|
62
|
+
operations: Ops;
|
|
63
|
+
uses: PermissionUses<OperationIn<Ops>>;
|
|
64
|
+
/** The roles in the claims, for `rules.roles`. */
|
|
65
|
+
roles?: (claims: Claims) => string | readonly string[] | undefined;
|
|
66
|
+
/** Operations the server granted in the claims, besides what the roles grant. */
|
|
67
|
+
grants?: (claims: Claims) => Grants<OperationIn<Ops>> | undefined;
|
|
68
|
+
rules?: PermissionRules<Claims, OperationIn<Ops>>;
|
|
69
|
+
};
|
|
70
|
+
/** What a check is about: a resource (its key or the resource) and, for a record, the row. */
|
|
71
|
+
export type PermissionTarget = {
|
|
72
|
+
resource?: string | {
|
|
73
|
+
readonly key: string;
|
|
74
|
+
} | undefined;
|
|
75
|
+
row?: unknown;
|
|
76
|
+
};
|
|
77
|
+
/** The permissions of one set of claims. `can` is a `Session`'s; `check` asks for an operation by name. */
|
|
78
|
+
export type GrantedPermissions<Claims, Operation extends string> = {
|
|
79
|
+
readonly claims: Claims;
|
|
80
|
+
check(operation: Operation, target?: PermissionTarget, notAllowed?: string): Allowed;
|
|
81
|
+
can(use: string, subject?: PermissionSubject): boolean | Refusal;
|
|
82
|
+
};
|
|
83
|
+
/** What the browser needs to rebuild a session the server made: JSON, so a server component can pass it down. */
|
|
84
|
+
export type SessionPayload<User, Claims> = {
|
|
85
|
+
user: User | null;
|
|
86
|
+
claims: Claims;
|
|
87
|
+
organization?: string | undefined;
|
|
88
|
+
};
|
|
89
|
+
export type PermissionSessionOptions<User, Claims> = SessionPayload<User, Claims> & {
|
|
90
|
+
token?: () => Promise<string | undefined>;
|
|
91
|
+
subscribe?: (listener: () => void) => () => void;
|
|
92
|
+
/** Words the rules' message refusals. */
|
|
93
|
+
locale?: Locale | undefined;
|
|
94
|
+
};
|
|
95
|
+
export type PermissionSession<User, Claims> = Session<User> & {
|
|
96
|
+
readonly claims: Claims;
|
|
97
|
+
};
|
|
98
|
+
export type Permissions<Ops extends Operations, Claims> = {
|
|
99
|
+
readonly operations: Ops;
|
|
100
|
+
readonly options: PermissionsOptions<Ops, Claims>;
|
|
101
|
+
/** The operation a use needs, or `undefined` when nothing maps it. */
|
|
102
|
+
operationOf(use: string): OperationIn<Ops> | undefined;
|
|
103
|
+
check(operation: OperationIn<Ops>, target: PermissionTarget & {
|
|
104
|
+
claims: Claims;
|
|
105
|
+
locale?: Locale | undefined;
|
|
106
|
+
notAllowed?: string;
|
|
107
|
+
}): Allowed;
|
|
108
|
+
for(claims: Claims, locale?: Locale): GrantedPermissions<Claims, OperationIn<Ops>>;
|
|
109
|
+
/** A `Session` whose `can` answers from these permissions: on the server with the request's claims, or hydrated. */
|
|
110
|
+
session<User>(options: PermissionSessionOptions<User, Claims>): PermissionSession<User, Claims>;
|
|
111
|
+
};
|
|
112
|
+
/**
|
|
113
|
+
* A role check for a rule: `approve: hasRole("manager")`. Any of the roles passes.
|
|
114
|
+
*/
|
|
115
|
+
export declare function hasRole(...roles: readonly string[]): (context: {
|
|
116
|
+
readonly roles: readonly string[];
|
|
117
|
+
}) => boolean;
|
|
118
|
+
/**
|
|
119
|
+
* An app's permissions over its own vocabulary of operations. `uses` says which operation each built-in use needs,
|
|
120
|
+
* `rules` grant operations by role and narrow them by resource, per row when a rule is a function. Its `session`
|
|
121
|
+
* answers every `can` the blocks, routes and agents ask.
|
|
122
|
+
*/
|
|
123
|
+
export declare function definePermissions<const Ops extends Operations, Claims = unknown>(options: PermissionsOptions<Ops, Claims>): Permissions<Ops, Claims>;
|
|
124
|
+
/** Whether `session` allows `operation` on the resource (and row): a column, a field or a button that `requires` it. */
|
|
125
|
+
export declare function allows(session: Session | undefined, operation: string | undefined, target?: PermissionTarget, notAllowed?: string): Allowed;
|
|
126
|
+
/** The items whose `requires` the session allows on the resource: columns, fields, sections. */
|
|
127
|
+
export declare function permitted<Item extends {
|
|
128
|
+
readonly requires?: string | undefined;
|
|
129
|
+
}>(items: readonly Item[], session: Session | undefined, resource: string | {
|
|
130
|
+
readonly key: string;
|
|
131
|
+
}): Item[];
|
|
132
|
+
/** The JSON a server component passes the browser for `permissions.session(payload)`. */
|
|
133
|
+
export declare function sessionPayload<User, Claims>(session: PermissionSession<User, Claims> | undefined): SessionPayload<User, Claims> | null;
|
|
134
|
+
export {};
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { ResourceAction } from "../core/constants.js";
|
|
2
|
+
import { isBoolean, isString } from "../core/guards.js";
|
|
3
|
+
import { isRefusal, toAllowed } from "../core/refusal.js";
|
|
4
|
+
import { refusalIn } from "../i18n/locale.js";
|
|
5
|
+
/** The key of a server's grants that holds what applies to every resource. */
|
|
6
|
+
export const GrantScope = { everyResource: "*" };
|
|
7
|
+
const fallbackUse = {
|
|
8
|
+
[ResourceAction.get]: ResourceAction.list,
|
|
9
|
+
[ResourceAction.restore]: ResourceAction.remove,
|
|
10
|
+
[ResourceAction.import]: ResourceAction.create,
|
|
11
|
+
};
|
|
12
|
+
function keyOf(resource) {
|
|
13
|
+
if (resource === undefined)
|
|
14
|
+
return undefined;
|
|
15
|
+
return isString(resource) ? resource : resource.key;
|
|
16
|
+
}
|
|
17
|
+
function rolesOf(given) {
|
|
18
|
+
if (given === undefined)
|
|
19
|
+
return [];
|
|
20
|
+
return isString(given) ? [given] : given;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* A role check for a rule: `approve: hasRole("manager")`. Any of the roles passes.
|
|
24
|
+
*/
|
|
25
|
+
export function hasRole(...roles) {
|
|
26
|
+
return (context) => context.roles.some((role) => roles.includes(role));
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* An app's permissions over its own vocabulary of operations. `uses` says which operation each built-in use needs,
|
|
30
|
+
* `rules` grant operations by role and narrow them by resource, per row when a rule is a function. Its `session`
|
|
31
|
+
* answers every `can` the blocks, routes and agents ask.
|
|
32
|
+
*/
|
|
33
|
+
export function definePermissions(options) {
|
|
34
|
+
const declared = new Set(Object.values(options.operations));
|
|
35
|
+
const isOperation = (value) => declared.has(value);
|
|
36
|
+
const roleRules = options.rules?.roles;
|
|
37
|
+
const resourceRules = options.rules?.resources;
|
|
38
|
+
const byRole = roleRules !== undefined || options.grants !== undefined;
|
|
39
|
+
function operationOf(use) {
|
|
40
|
+
const mapped = options.uses[use];
|
|
41
|
+
if (mapped !== undefined)
|
|
42
|
+
return mapped;
|
|
43
|
+
if (isOperation(use))
|
|
44
|
+
return use;
|
|
45
|
+
const fallback = fallbackUse[use];
|
|
46
|
+
return fallback === undefined ? undefined : options.uses[fallback];
|
|
47
|
+
}
|
|
48
|
+
function decide(claims, use, operation, resource, row, locale) {
|
|
49
|
+
const roles = rolesOf(options.roles?.(claims));
|
|
50
|
+
const context = { claims, roles, operation, resource, use };
|
|
51
|
+
const answer = (rule) => {
|
|
52
|
+
if (rule === undefined || isBoolean(rule))
|
|
53
|
+
return rule;
|
|
54
|
+
return refusalIn(rule(context, row), locale);
|
|
55
|
+
};
|
|
56
|
+
if (byRole) {
|
|
57
|
+
const sent = options.grants?.(claims);
|
|
58
|
+
const fromServer = sent !== undefined &&
|
|
59
|
+
[resource ?? GrantScope.everyResource, GrantScope.everyResource].some((scope) => sent[scope]?.includes(operation) === true);
|
|
60
|
+
if (!fromServer) {
|
|
61
|
+
const answers = roles.map((role) => answer(roleRules?.[role]?.[operation]));
|
|
62
|
+
if (!answers.includes(true))
|
|
63
|
+
return answers.find(isRefusal) ?? false;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
const own = resource === undefined ? undefined : answer(resourceRules?.[resource]?.[operation]);
|
|
67
|
+
return own === undefined ? true : own;
|
|
68
|
+
}
|
|
69
|
+
function granted(claims, locale) {
|
|
70
|
+
return {
|
|
71
|
+
claims,
|
|
72
|
+
check: (operation, target = {}, notAllowed = "") => toAllowed(decide(claims, operation, operation, keyOf(target.resource), target.row, locale), notAllowed),
|
|
73
|
+
can(use, subject) {
|
|
74
|
+
const operation = operationOf(use);
|
|
75
|
+
if (operation === undefined)
|
|
76
|
+
return false;
|
|
77
|
+
return decide(claims, use, operation, subject?.resource, subject?.row, locale);
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
return {
|
|
82
|
+
operations: options.operations,
|
|
83
|
+
options,
|
|
84
|
+
operationOf,
|
|
85
|
+
check: (operation, target) => granted(target.claims, target.locale).check(operation, target, target.notAllowed ?? ""),
|
|
86
|
+
for: granted,
|
|
87
|
+
session(given) {
|
|
88
|
+
const answers = granted(given.claims, given.locale);
|
|
89
|
+
return {
|
|
90
|
+
user: given.user,
|
|
91
|
+
claims: given.claims,
|
|
92
|
+
organization: given.organization,
|
|
93
|
+
can: answers.can,
|
|
94
|
+
...(given.token ? { token: given.token } : {}),
|
|
95
|
+
...(given.subscribe ? { subscribe: given.subscribe } : {}),
|
|
96
|
+
};
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
/** Whether `session` allows `operation` on the resource (and row): a column, a field or a button that `requires` it. */
|
|
101
|
+
export function allows(session, operation, target = {}, notAllowed = "") {
|
|
102
|
+
if (operation === undefined || session === undefined)
|
|
103
|
+
return true;
|
|
104
|
+
const resource = keyOf(target.resource);
|
|
105
|
+
const subject = resource === undefined ? undefined : { resource, ...(target.row === undefined ? {} : { row: target.row }) };
|
|
106
|
+
return toAllowed(session.can(operation, subject), notAllowed);
|
|
107
|
+
}
|
|
108
|
+
/** The items whose `requires` the session allows on the resource: columns, fields, sections. */
|
|
109
|
+
export function permitted(items, session, resource) {
|
|
110
|
+
return items.filter((item) => allows(session, item.requires, { resource }) === true);
|
|
111
|
+
}
|
|
112
|
+
/** The JSON a server component passes the browser for `permissions.session(payload)`. */
|
|
113
|
+
export function sessionPayload(session) {
|
|
114
|
+
if (session === undefined)
|
|
115
|
+
return null;
|
|
116
|
+
return {
|
|
117
|
+
user: session.user,
|
|
118
|
+
claims: session.claims,
|
|
119
|
+
...(session.organization === undefined ? {} : { organization: session.organization }),
|
|
120
|
+
};
|
|
121
|
+
}
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { QueryClient } from "@tanstack/react-query";
|
|
2
2
|
import { type ReactNode } from "react";
|
|
3
3
|
import type { DataLabels } from "../core/data-labels.js";
|
|
4
|
+
import { type DialogQueue } from "../dialogs/dialogs.js";
|
|
5
|
+
import { type Errors } from "../errors/define-errors.js";
|
|
6
|
+
import type { Locale } from "../i18n/locale.js";
|
|
4
7
|
import type { PreferencesStore } from "../view/preferences.js";
|
|
5
8
|
import type { RouterAdapter } from "../navigation/router.js";
|
|
6
9
|
import type { Session } from "../session/session.js";
|
|
@@ -9,7 +12,14 @@ export type DataLayerValue = {
|
|
|
9
12
|
router: RouterAdapter | undefined;
|
|
10
13
|
labels: DataLabels;
|
|
11
14
|
preferences: PreferencesStore | undefined;
|
|
15
|
+
/** The BCP 47 code numbers and dates format with. */
|
|
12
16
|
locale: string | undefined;
|
|
17
|
+
/** The messages resources and blocks read, when `DataLayer` got a `Locale`. */
|
|
18
|
+
i18n: Locale | undefined;
|
|
19
|
+
/** The error policy every resource call and action goes through. */
|
|
20
|
+
errors: Errors;
|
|
21
|
+
/** The queue `useDialogs` adds to and `NavDialogs` draws. */
|
|
22
|
+
dialogs: DialogQueue;
|
|
13
23
|
};
|
|
14
24
|
export type DataLayerProps = {
|
|
15
25
|
/**
|
|
@@ -19,13 +29,40 @@ export type DataLayerProps = {
|
|
|
19
29
|
client?: QueryClient;
|
|
20
30
|
session?: Session;
|
|
21
31
|
router?: RouterAdapter;
|
|
22
|
-
/**
|
|
23
|
-
|
|
32
|
+
/**
|
|
33
|
+
* The language: a `Locale` from `defineLocale`, `fromNextIntl`, `fromI18next` or `fromIntl`, which words the blocks
|
|
34
|
+
* and the resources' labels. A BCP 47 code alone only formats numbers and dates, with `labels` for the words.
|
|
35
|
+
*/
|
|
36
|
+
locale?: Locale | string;
|
|
37
|
+
/** @deprecated Give `locale` a `Locale` instead: `dataLabelsEn`, `dataLabelsEs` or your own still work here. */
|
|
38
|
+
labels?: DataLabels;
|
|
24
39
|
preferences?: PreferencesStore;
|
|
25
|
-
|
|
40
|
+
/**
|
|
41
|
+
* The app's `defineErrors` policy: how errors classify, read and show, when calls retry and how an expired session
|
|
42
|
+
* signs in again. `defineErrors()`'s defaults without it.
|
|
43
|
+
*/
|
|
44
|
+
errors?: Errors;
|
|
26
45
|
children: ReactNode;
|
|
27
46
|
};
|
|
28
|
-
export declare function DataLayer({ client, session, router, labels, preferences, locale, children }: DataLayerProps): import("react").JSX.Element;
|
|
47
|
+
export declare function DataLayer({ client, session, router, labels, preferences, locale, errors, children }: DataLayerProps): import("react").JSX.Element;
|
|
29
48
|
export declare function useDataLayer(): DataLayerValue;
|
|
30
49
|
export declare function useSession(): Session | undefined;
|
|
31
|
-
|
|
50
|
+
type Localizable<Value> = {
|
|
51
|
+
in(locale: Locale | undefined): Value;
|
|
52
|
+
};
|
|
53
|
+
/**
|
|
54
|
+
* The generic texts. Given the resource they're about, messages with a `{gender, select, …}` agree with it
|
|
55
|
+
* ("Nueva línea", "Nuevo pedido").
|
|
56
|
+
*/
|
|
57
|
+
export declare function useLabels(resource?: Localizable<{
|
|
58
|
+
gender: string | undefined;
|
|
59
|
+
}>): DataLabels;
|
|
60
|
+
/** A resource or an action with its texts in the `DataLayer`'s locale: `useLocalized(customers).label(2)`. */
|
|
61
|
+
export declare function useLocalized<Value extends Localizable<Value>>(value: Value): Value;
|
|
62
|
+
/** The `DataLayer` for a block about one resource: the resource in its locale, and the texts in its gender. */
|
|
63
|
+
export declare function useResourceLayer<Value extends Localizable<Value> & {
|
|
64
|
+
gender: string | undefined;
|
|
65
|
+
}>(resource: Value): DataLayerValue & {
|
|
66
|
+
resource: Value;
|
|
67
|
+
};
|
|
68
|
+
export {};
|