@eskais/app-sdk 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +74 -2
- package/dist/action/action.d.ts +133 -0
- package/dist/action/action.js +224 -0
- package/dist/action/bulk.d.ts +24 -0
- package/dist/action/bulk.js +24 -0
- package/dist/cli/cli.d.ts +2 -0
- package/dist/cli/cli.js +51 -0
- package/dist/cli/routes.d.ts +17 -0
- package/dist/cli/routes.js +36 -0
- package/dist/core/assume.d.ts +1 -0
- package/dist/core/assume.js +8 -0
- package/dist/core/constants.d.ts +359 -0
- package/dist/core/constants.js +187 -0
- package/dist/core/contracts.d.ts +107 -0
- package/dist/core/contracts.js +3 -0
- package/dist/core/data-labels.d.ts +210 -0
- package/dist/core/data-labels.js +385 -0
- package/dist/core/errors.d.ts +52 -0
- package/dist/core/errors.js +209 -0
- package/dist/core/guards.d.ts +9 -0
- package/dist/core/guards.js +14 -0
- package/dist/core/refusal.d.ts +30 -0
- package/dist/core/refusal.js +53 -0
- package/dist/dialogs/dialogs.d.ts +75 -0
- package/dist/dialogs/dialogs.js +66 -0
- package/dist/draft/draft.d.ts +36 -0
- package/dist/draft/draft.js +87 -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/export/csv.d.ts +25 -0
- package/dist/export/csv.js +59 -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/csv-parse.d.ts +11 -0
- package/dist/import/csv-parse.js +70 -0
- package/dist/import/import.d.ts +104 -0
- package/dist/import/import.js +266 -0
- package/dist/index.d.ts +46 -0
- package/dist/index.js +45 -0
- package/dist/navigation/nav.d.ts +128 -0
- package/dist/navigation/nav.js +301 -0
- package/dist/navigation/router.d.ts +81 -0
- package/dist/navigation/router.js +249 -0
- package/dist/navigation/shortcuts.d.ts +37 -0
- package/dist/navigation/shortcuts.js +93 -0
- package/dist/next/index.d.ts +3 -0
- package/dist/next/index.js +3 -0
- package/dist/next/screen-hydration.d.ts +12 -0
- package/dist/next/screen-hydration.js +26 -0
- package/dist/next/screen.d.ts +25 -0
- package/dist/next/screen.js +44 -0
- package/dist/next/server/handler.d.ts +39 -0
- package/dist/next/server/handler.js +190 -0
- package/dist/next/server/index.d.ts +6 -0
- package/dist/next/server/index.js +6 -0
- package/dist/next/server/page.d.ts +63 -0
- package/dist/next/server/page.js +110 -0
- package/dist/next/server/prefetch.d.ts +29 -0
- package/dist/next/server/prefetch.js +97 -0
- package/dist/next/server/session.d.ts +25 -0
- package/dist/next/server/session.js +23 -0
- package/dist/next/use-next-router.d.ts +21 -0
- package/dist/next/use-next-router.js +104 -0
- package/dist/permissions/permissions.d.ts +134 -0
- package/dist/permissions/permissions.js +121 -0
- package/dist/react/data-layer.d.ts +68 -0
- package/dist/react/data-layer.js +76 -0
- 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 +37 -0
- package/dist/react/hooks/use-action.js +125 -0
- package/dist/react/hooks/use-better-auth.d.ts +12 -0
- package/dist/react/hooks/use-better-auth.js +11 -0
- 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-draft.d.ts +5 -0
- package/dist/react/hooks/use-draft.js +17 -0
- package/dist/react/hooks/use-nav.d.ts +17 -0
- package/dist/react/hooks/use-nav.js +35 -0
- 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 +92 -0
- package/dist/react/hooks/use-resource.js +255 -0
- package/dist/react/hooks/use-view.d.ts +6 -0
- package/dist/react/hooks/use-view.js +24 -0
- package/dist/react/index.d.ts +15 -0
- package/dist/react/index.js +15 -0
- package/dist/react/keys.d.ts +60 -0
- package/dist/react/keys.js +71 -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/form-schema.d.ts +11 -0
- package/dist/resource/form-schema.js +51 -0
- package/dist/resource/relations.d.ts +99 -0
- package/dist/resource/relations.js +194 -0
- package/dist/resource/resource-relations.d.ts +47 -0
- package/dist/resource/resource-relations.js +154 -0
- package/dist/resource/resource-schema.d.ts +9 -0
- package/dist/resource/resource-schema.js +73 -0
- package/dist/resource/resource-texts.d.ts +18 -0
- package/dist/resource/resource-texts.js +13 -0
- package/dist/resource/resource-types.d.ts +420 -0
- package/dist/resource/resource-types.js +1 -0
- package/dist/resource/resource-words.d.ts +25 -0
- package/dist/resource/resource-words.js +221 -0
- package/dist/resource/resource.d.ts +15 -0
- package/dist/resource/resource.js +280 -0
- package/dist/resource/schema.d.ts +57 -0
- package/dist/resource/schema.js +115 -0
- package/dist/services/from-page-source.d.ts +15 -0
- package/dist/services/from-page-source.js +27 -0
- package/dist/services/memory-query.d.ts +8 -0
- package/dist/services/memory-query.js +165 -0
- package/dist/services/memory-service.d.ts +33 -0
- package/dist/services/memory-service.js +291 -0
- 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 +65 -0
- package/dist/services/rest-service.js +222 -0
- package/dist/services/rng.d.ts +9 -0
- package/dist/services/rng.js +22 -0
- package/dist/services/spring-service.d.ts +58 -0
- package/dist/services/spring-service.js +132 -0
- package/dist/session/better-auth.d.ts +83 -0
- package/dist/session/better-auth.js +86 -0
- package/dist/session/session.d.ts +45 -0
- package/dist/session/session.js +36 -0
- package/dist/view/preferences.d.ts +35 -0
- package/dist/view/preferences.js +93 -0
- package/dist/view/view-types.d.ts +124 -0
- package/dist/view/view-types.js +1 -0
- package/dist/view/view-url.d.ts +7 -0
- package/dist/view/view-url.js +54 -0
- package/dist/view/view.d.ts +4 -0
- package/dist/view/view.js +392 -0
- package/locales/en.json +193 -0
- package/locales/es.json +193 -0
- package/package.json +88 -4
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
import { assumeType } from "../core/assume.js";
|
|
2
|
+
import { CursorDirection, PagePositionKind, ServiceErrorKind, TargetKind, TotalKind, VersionRead, VersionSend, } from "../core/constants.js";
|
|
3
|
+
import { isPagePosition, } from "../core/contracts.js";
|
|
4
|
+
import { problemDetailError, ServiceFailure, serviceError, toServiceError } from "../core/errors.js";
|
|
5
|
+
import { isBoolean, isNumber, isRecord, isString } from "../core/guards.js";
|
|
6
|
+
import { valueAt } from "./memory-query.js";
|
|
7
|
+
export const HttpMethod = { get: "GET", post: "POST", put: "PUT", patch: "PATCH", delete: "DELETE" };
|
|
8
|
+
function defaultRead(raw) {
|
|
9
|
+
// Workaround: a REST body is JSON the server promises to be rows of `T`; nothing here can check it.
|
|
10
|
+
if (Array.isArray(raw))
|
|
11
|
+
return { items: assumeType(raw) };
|
|
12
|
+
if (!isRecord(raw))
|
|
13
|
+
return { items: [] };
|
|
14
|
+
const items = Array.isArray(raw.items)
|
|
15
|
+
? raw.items
|
|
16
|
+
: Array.isArray(raw.data)
|
|
17
|
+
? raw.data
|
|
18
|
+
: Array.isArray(raw.content)
|
|
19
|
+
? raw.content
|
|
20
|
+
: [];
|
|
21
|
+
return {
|
|
22
|
+
// Workaround: as above, the rows of a JSON body can't be checked against `T` here.
|
|
23
|
+
items: assumeType(items),
|
|
24
|
+
...(isNumber(raw.total) ? { total: raw.total } : isNumber(raw.totalElements) ? { total: raw.totalElements } : {}),
|
|
25
|
+
...(isBoolean(raw.hasMore) ? { hasMore: raw.hasMore } : {}),
|
|
26
|
+
...(isString(raw.nextCursor) || raw.nextCursor === null ? { nextCursor: raw.nextCursor } : {}),
|
|
27
|
+
...(isString(raw.prevCursor) || raw.prevCursor === null ? { prevCursor: raw.prevCursor } : {}),
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
async function json(response) {
|
|
31
|
+
const raw = await response.text();
|
|
32
|
+
return raw === "" ? undefined : JSON.parse(raw);
|
|
33
|
+
}
|
|
34
|
+
function appendValue(params, name, value) {
|
|
35
|
+
if (value === undefined || value === null || value === "")
|
|
36
|
+
return;
|
|
37
|
+
if (Array.isArray(value)) {
|
|
38
|
+
for (const entry of value)
|
|
39
|
+
appendValue(params, name, entry);
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
params.append(name, isRecord(value) ? JSON.stringify(value) : String(value));
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* A REST backend: `GET /x?page=&size=&sort=`, `GET /x/:id`, `POST /x`, `PATCH /x/:id` and `DELETE /x/:id`. Errors
|
|
46
|
+
* (RFC 9457 `ProblemDetail`, Spring validation, JSON:API) become `ServiceError`s with their fields.
|
|
47
|
+
*/
|
|
48
|
+
export function restService(base, options = {}) {
|
|
49
|
+
const send = options.fetch ?? ((input, init) => fetch(input, init));
|
|
50
|
+
const names = {
|
|
51
|
+
page: "page",
|
|
52
|
+
size: "size",
|
|
53
|
+
sort: "sort",
|
|
54
|
+
search: "q",
|
|
55
|
+
cursor: "cursor",
|
|
56
|
+
before: "before",
|
|
57
|
+
include: "include",
|
|
58
|
+
...options.params,
|
|
59
|
+
};
|
|
60
|
+
const pageBase = options.pageBase ?? 1;
|
|
61
|
+
const etags = new WeakMap();
|
|
62
|
+
const url = (path = "", params) => {
|
|
63
|
+
const query = params?.toString() ?? "";
|
|
64
|
+
return `${base.replace(/\/$/u, "")}${path}${query === "" ? "" : `?${query}`}`;
|
|
65
|
+
};
|
|
66
|
+
const itemPath = (id) => `/${encodeURIComponent(String(id))}`;
|
|
67
|
+
async function call(method, path, context, body, extra = {}) {
|
|
68
|
+
const headers = {
|
|
69
|
+
accept: "application/json",
|
|
70
|
+
...(await options.headers?.(context)),
|
|
71
|
+
...extra,
|
|
72
|
+
};
|
|
73
|
+
const token = await context.session?.token?.();
|
|
74
|
+
if (token !== undefined && headers.authorization === undefined)
|
|
75
|
+
headers.authorization = `Bearer ${token}`;
|
|
76
|
+
if (body !== undefined)
|
|
77
|
+
headers["content-type"] = "application/json";
|
|
78
|
+
if (context.idempotencyKey !== undefined && method !== HttpMethod.get)
|
|
79
|
+
headers["idempotency-key"] = context.idempotencyKey;
|
|
80
|
+
const fail = (error) => new ServiceFailure(options.mapError ? options.mapError(error) : error);
|
|
81
|
+
let response;
|
|
82
|
+
try {
|
|
83
|
+
response = await send(path, {
|
|
84
|
+
method,
|
|
85
|
+
headers,
|
|
86
|
+
signal: context.signal,
|
|
87
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
throw fail(toServiceError(error));
|
|
92
|
+
}
|
|
93
|
+
if (!response.ok)
|
|
94
|
+
throw fail((await problemDetailError(response)).error);
|
|
95
|
+
return response;
|
|
96
|
+
}
|
|
97
|
+
async function readRow(response) {
|
|
98
|
+
const row = await json(response);
|
|
99
|
+
const etag = response.headers.get("etag");
|
|
100
|
+
if (etag !== null && isRecord(row))
|
|
101
|
+
etags.set(row, etag);
|
|
102
|
+
// Workaround: the server answers with the row as JSON; nothing here can check it against `T`.
|
|
103
|
+
return assumeType(row);
|
|
104
|
+
}
|
|
105
|
+
function listParams(query) {
|
|
106
|
+
const params = new URLSearchParams();
|
|
107
|
+
const filter = options.filterParams
|
|
108
|
+
? options.filterParams(query.filter)
|
|
109
|
+
: isRecord(query.filter)
|
|
110
|
+
? query.filter
|
|
111
|
+
: {};
|
|
112
|
+
for (const [name, value] of Object.entries(filter))
|
|
113
|
+
appendValue(params, name, value);
|
|
114
|
+
if (query.search !== undefined && query.search !== "")
|
|
115
|
+
params.set(names.search, query.search);
|
|
116
|
+
for (const spec of query.sort)
|
|
117
|
+
params.append(names.sort, options.sortStyle ? options.sortStyle(spec.field, spec.direction) : `${spec.field},${spec.direction}`);
|
|
118
|
+
if (query.include && query.include.length > 0 && options.includeParams !== false) {
|
|
119
|
+
const written = options.includeParams
|
|
120
|
+
? options.includeParams(query.include)
|
|
121
|
+
: { [names.include]: query.include.join(",") };
|
|
122
|
+
for (const [name, value] of Object.entries(written))
|
|
123
|
+
params.set(name, value);
|
|
124
|
+
}
|
|
125
|
+
params.set(names.size, String(query.size));
|
|
126
|
+
if (isPagePosition(query.position))
|
|
127
|
+
params.set(names.page, String(query.position.page - 1 + pageBase));
|
|
128
|
+
else if (query.position.cursor !== null)
|
|
129
|
+
params.set(query.position.direction === CursorDirection.backward ? names.before : names.cursor, query.position.cursor);
|
|
130
|
+
return params;
|
|
131
|
+
}
|
|
132
|
+
function targetParams(target) {
|
|
133
|
+
if (target.kind === TargetKind.ids)
|
|
134
|
+
return undefined;
|
|
135
|
+
const params = new URLSearchParams();
|
|
136
|
+
const filter = options.filterParams
|
|
137
|
+
? options.filterParams(target.filter)
|
|
138
|
+
: isRecord(target.filter)
|
|
139
|
+
? target.filter
|
|
140
|
+
: {};
|
|
141
|
+
for (const [name, value] of Object.entries(filter))
|
|
142
|
+
appendValue(params, name, value);
|
|
143
|
+
if (target.search !== undefined)
|
|
144
|
+
params.set(names.search, target.search);
|
|
145
|
+
for (const id of target.except)
|
|
146
|
+
params.append("except", String(id));
|
|
147
|
+
return params;
|
|
148
|
+
}
|
|
149
|
+
const versionOf = (row) => {
|
|
150
|
+
if (!options.version)
|
|
151
|
+
return undefined;
|
|
152
|
+
if (options.version.read === VersionRead.etag)
|
|
153
|
+
return isRecord(row) ? etags.get(row) : undefined;
|
|
154
|
+
const value = valueAt(row, options.version.field ?? "version");
|
|
155
|
+
return isString(value) || isNumber(value) ? value : undefined;
|
|
156
|
+
};
|
|
157
|
+
const service = {
|
|
158
|
+
capabilities: {
|
|
159
|
+
position: options.position ?? PagePositionKind.page,
|
|
160
|
+
total: options.total ?? TotalKind.exact,
|
|
161
|
+
...(options.maxPageSize === undefined ? {} : { maxPageSize: options.maxPageSize }),
|
|
162
|
+
...(options.version ? { versioned: true } : {}),
|
|
163
|
+
...(options.bulkByQuery === true ? { bulkByQuery: true } : {}),
|
|
164
|
+
...(options.restore === true ? { restore: true } : {}),
|
|
165
|
+
...(isRecord(options.batch) && options.batch.size !== undefined ? { batchSize: options.batch.size } : {}),
|
|
166
|
+
},
|
|
167
|
+
async list(query, context) {
|
|
168
|
+
const response = await call(HttpMethod.get, url("", listParams(query)), context);
|
|
169
|
+
const raw = await json(response);
|
|
170
|
+
return options.read ? options.read(raw, response) : defaultRead(raw);
|
|
171
|
+
},
|
|
172
|
+
async get(id, context) {
|
|
173
|
+
return readRow(await call(HttpMethod.get, url(itemPath(id)), context));
|
|
174
|
+
},
|
|
175
|
+
...(options.batch === undefined || options.batch === false
|
|
176
|
+
? {}
|
|
177
|
+
: {
|
|
178
|
+
async getMany(ids, context) {
|
|
179
|
+
const params = new URLSearchParams();
|
|
180
|
+
const name = isRecord(options.batch) ? (options.batch.param ?? "ids") : "ids";
|
|
181
|
+
for (const id of ids)
|
|
182
|
+
params.append(name, String(id));
|
|
183
|
+
const raw = await json(await call(HttpMethod.get, url("", params), context));
|
|
184
|
+
const page = options.read ? undefined : defaultRead(raw);
|
|
185
|
+
// Workaround: the server answers with the rows as JSON; nothing here can check them against `T`.
|
|
186
|
+
return page ? page.items : assumeType(Array.isArray(raw) ? raw : []);
|
|
187
|
+
},
|
|
188
|
+
}),
|
|
189
|
+
async create(input, context) {
|
|
190
|
+
return readRow(await call(HttpMethod.post, url(), context, input));
|
|
191
|
+
},
|
|
192
|
+
async update(id, patch, context) {
|
|
193
|
+
const version = context.version;
|
|
194
|
+
const headers = {};
|
|
195
|
+
let body = patch;
|
|
196
|
+
if (options.version && version !== undefined) {
|
|
197
|
+
if (options.version.send === VersionSend.ifMatch)
|
|
198
|
+
headers["if-match"] = String(version);
|
|
199
|
+
else
|
|
200
|
+
body = { ...(isRecord(patch) ? patch : {}), [options.version.field ?? "version"]: version };
|
|
201
|
+
}
|
|
202
|
+
return readRow(await call(options.updateMethod ?? HttpMethod.patch, url(itemPath(id)), context, body, headers));
|
|
203
|
+
},
|
|
204
|
+
async remove(target, context) {
|
|
205
|
+
if (target.kind === TargetKind.ids) {
|
|
206
|
+
await Promise.all(target.ids.map((id) => call(HttpMethod.delete, url(itemPath(id)), context)));
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
if (options.bulkByQuery !== true)
|
|
210
|
+
throw new ServiceFailure(serviceError(ServiceErrorKind.validation, "This service removes by id only."));
|
|
211
|
+
await call(HttpMethod.delete, url("", targetParams(target)), context);
|
|
212
|
+
},
|
|
213
|
+
async restore(target, context) {
|
|
214
|
+
if (target.kind === TargetKind.ids)
|
|
215
|
+
await call(HttpMethod.post, url("/restore"), context, { ids: target.ids });
|
|
216
|
+
else
|
|
217
|
+
await call(HttpMethod.post, url("/restore", targetParams(target)), context);
|
|
218
|
+
},
|
|
219
|
+
versionOf,
|
|
220
|
+
};
|
|
221
|
+
return service;
|
|
222
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export type Rng = {
|
|
2
|
+
/** A number in [0, 1). */
|
|
3
|
+
next(): number;
|
|
4
|
+
/** An integer in [min, max], both included. */
|
|
5
|
+
int(min: number, max: number): number;
|
|
6
|
+
pick<T>(values: readonly T[]): T;
|
|
7
|
+
bool(probability?: number): boolean;
|
|
8
|
+
};
|
|
9
|
+
export declare function createRng(seed?: number): Rng;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Perf: mulberry32, a 32-bit generator that is fast, small and good enough for fixtures; never for secrets.
|
|
2
|
+
export function createRng(seed = 1) {
|
|
3
|
+
let state = seed >>> 0;
|
|
4
|
+
const next = () => {
|
|
5
|
+
state = (state + 0x6d2b79f5) >>> 0;
|
|
6
|
+
let t = state;
|
|
7
|
+
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
8
|
+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
9
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
|
|
10
|
+
};
|
|
11
|
+
const int = (min, max) => min + Math.floor(next() * (max - min + 1));
|
|
12
|
+
return {
|
|
13
|
+
next,
|
|
14
|
+
int,
|
|
15
|
+
pick(values) {
|
|
16
|
+
if (values.length === 0)
|
|
17
|
+
throw new RangeError("Can't pick from an empty list.");
|
|
18
|
+
return values[int(0, values.length - 1)];
|
|
19
|
+
},
|
|
20
|
+
bool: (probability = 0.5) => next() < probability,
|
|
21
|
+
};
|
|
22
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { ResourceService } from "../core/contracts.js";
|
|
2
|
+
import { type RestServiceOptions } from "./rest-service.js";
|
|
3
|
+
/** Spring Data's `Page<T>` as JSON, or the `PagedModel` that `pageSerializationMode = VIA_DTO` writes (`page: {…}`). */
|
|
4
|
+
export type SpringPage<T> = {
|
|
5
|
+
content: T[];
|
|
6
|
+
totalElements?: number;
|
|
7
|
+
totalPages?: number;
|
|
8
|
+
number?: number;
|
|
9
|
+
size?: number;
|
|
10
|
+
first?: boolean;
|
|
11
|
+
last?: boolean;
|
|
12
|
+
/** A `Slice<T>`'s only clue to what follows. */
|
|
13
|
+
hasNext?: boolean;
|
|
14
|
+
page?: {
|
|
15
|
+
size?: number;
|
|
16
|
+
number?: number;
|
|
17
|
+
totalElements?: number;
|
|
18
|
+
totalPages?: number;
|
|
19
|
+
};
|
|
20
|
+
};
|
|
21
|
+
export type SpringServiceOptions<T, F> = Omit<RestServiceOptions<T, F>, "pageBase" | "position" | "read" | "sortStyle" | "total"> & {
|
|
22
|
+
/** A `Slice<T>` backend: no count query, so no total, only whether another slice follows. */
|
|
23
|
+
slice?: boolean;
|
|
24
|
+
/** Where the page sits in the body, when it isn't the body itself (`(raw) => raw.data`). */
|
|
25
|
+
select?: (raw: unknown) => unknown;
|
|
26
|
+
/**
|
|
27
|
+
* Sends the filter as one spring-filter expression in `?filter=` (`status : 'active' and total > 10`) instead of a
|
|
28
|
+
* parameter per field. `true` writes it with `springFilter`; a function writes your own.
|
|
29
|
+
*/
|
|
30
|
+
springFilter?: boolean | ((filter: F) => string | undefined);
|
|
31
|
+
/**
|
|
32
|
+
* A field error's path as the form knows it. By default a constraint violation's method and argument
|
|
33
|
+
* (`create.arg0.email`) are dropped, leaving `email`.
|
|
34
|
+
*/
|
|
35
|
+
fieldPath?: (path: string) => string;
|
|
36
|
+
/**
|
|
37
|
+
* How the relations to embed (`Query.include`) reach Spring: by default `?projection=customer,tags`, which a
|
|
38
|
+
* controller maps to an entity graph or a Spring Data REST projection; a function writes your own parameters,
|
|
39
|
+
* `false` sends nothing.
|
|
40
|
+
*/
|
|
41
|
+
projection?: false | ((include: readonly string[]) => Record<string, string>);
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* A filter as a spring-filter expression: a value is `field : 'x'`, a list `field in ['a', 'b']`, a range
|
|
45
|
+
* (`{ from, to }`, `{ min, max }`) `field >: a and field <: b`, and a nested record `country.code : 'ES'`.
|
|
46
|
+
*/
|
|
47
|
+
export declare function springFilter(filter: unknown): string | undefined;
|
|
48
|
+
/**
|
|
49
|
+
* A filter as query parameters Spring's data binder reads: a list repeats its parameter (`status=a&status=b`, a
|
|
50
|
+
* `List<String>`), a nested record goes by dotted path (`createdAt.from=…`, a nested object), a date as ISO text.
|
|
51
|
+
*/
|
|
52
|
+
export declare function springParams(filter: unknown, prefix?: string): Record<string, unknown>;
|
|
53
|
+
/**
|
|
54
|
+
* A Spring Boot backend: Spring Data's `Pageable` (`?page=0&size=25&sort=name,asc&sort=id,desc`), its `Page<T>` or
|
|
55
|
+
* `PagedModel` (or `Slice<T>` with `slice`), the filter as parameters the data binder reads or as spring-filter,
|
|
56
|
+
* and errors from `ProblemDetail` (RFC 9457) and Bean Validation as `ServiceError`s with their field errors.
|
|
57
|
+
*/
|
|
58
|
+
export declare function springService<T, Id = string, F = Record<string, unknown>>(base: string, options?: SpringServiceOptions<T, F>): ResourceService<T, Id, F>;
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { assumeType } from "../core/assume.js";
|
|
2
|
+
import { PagePositionKind, TotalKind } from "../core/constants.js";
|
|
3
|
+
import { isBoolean, isNumber, isRecord, isString } from "../core/guards.js";
|
|
4
|
+
import { restService } from "./rest-service.js";
|
|
5
|
+
const quote = (value) => `'${value.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`;
|
|
6
|
+
function literal(value) {
|
|
7
|
+
if (isString(value))
|
|
8
|
+
return quote(value);
|
|
9
|
+
if (isNumber(value) || isBoolean(value))
|
|
10
|
+
return String(value);
|
|
11
|
+
if (value instanceof Date)
|
|
12
|
+
return quote(value.toISOString());
|
|
13
|
+
return undefined;
|
|
14
|
+
}
|
|
15
|
+
function clauses(path, value) {
|
|
16
|
+
if (value === undefined || value === null || value === "")
|
|
17
|
+
return [];
|
|
18
|
+
if (Array.isArray(value)) {
|
|
19
|
+
const entries = value;
|
|
20
|
+
const items = entries.flatMap((entry) => {
|
|
21
|
+
const text = literal(entry);
|
|
22
|
+
return text === undefined ? [] : [text];
|
|
23
|
+
});
|
|
24
|
+
return items.length === 0 ? [] : [`${path} in [${items.join(", ")}]`];
|
|
25
|
+
}
|
|
26
|
+
if (isRecord(value)) {
|
|
27
|
+
const lower = value.from ?? value.min ?? value.gte;
|
|
28
|
+
const upper = value.to ?? value.max ?? value.lte;
|
|
29
|
+
if (lower !== undefined || upper !== undefined) {
|
|
30
|
+
const low = literal(lower);
|
|
31
|
+
const high = literal(upper);
|
|
32
|
+
return [
|
|
33
|
+
...(low === undefined ? [] : [`${path} >: ${low}`]),
|
|
34
|
+
...(high === undefined ? [] : [`${path} <: ${high}`]),
|
|
35
|
+
];
|
|
36
|
+
}
|
|
37
|
+
return Object.entries(value).flatMap(([key, entry]) => clauses(`${path}.${key}`, entry));
|
|
38
|
+
}
|
|
39
|
+
const text = literal(value);
|
|
40
|
+
return text === undefined ? [] : [`${path} : ${text}`];
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* A filter as a spring-filter expression: a value is `field : 'x'`, a list `field in ['a', 'b']`, a range
|
|
44
|
+
* (`{ from, to }`, `{ min, max }`) `field >: a and field <: b`, and a nested record `country.code : 'ES'`.
|
|
45
|
+
*/
|
|
46
|
+
export function springFilter(filter) {
|
|
47
|
+
if (!isRecord(filter))
|
|
48
|
+
return undefined;
|
|
49
|
+
const parts = Object.entries(filter).flatMap(([key, value]) => clauses(key, value));
|
|
50
|
+
return parts.length === 0 ? undefined : parts.join(" and ");
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* A filter as query parameters Spring's data binder reads: a list repeats its parameter (`status=a&status=b`, a
|
|
54
|
+
* `List<String>`), a nested record goes by dotted path (`createdAt.from=…`, a nested object), a date as ISO text.
|
|
55
|
+
*/
|
|
56
|
+
export function springParams(filter, prefix = "") {
|
|
57
|
+
if (!isRecord(filter))
|
|
58
|
+
return {};
|
|
59
|
+
const params = {};
|
|
60
|
+
for (const [key, value] of Object.entries(filter)) {
|
|
61
|
+
const name = `${prefix}${key}`;
|
|
62
|
+
if (value instanceof Date)
|
|
63
|
+
params[name] = value.toISOString();
|
|
64
|
+
else if (isRecord(value))
|
|
65
|
+
Object.assign(params, springParams(value, `${name}.`));
|
|
66
|
+
else
|
|
67
|
+
params[name] = value;
|
|
68
|
+
}
|
|
69
|
+
return params;
|
|
70
|
+
}
|
|
71
|
+
const violationPrefix = /^[A-Za-z_$][\w$]*\.arg\d+\./u;
|
|
72
|
+
function readSpringPage(raw, slice) {
|
|
73
|
+
if (Array.isArray(raw)) {
|
|
74
|
+
// Workaround: a body that is a bare list is the server's rows, typed by the service's `T`.
|
|
75
|
+
return { items: assumeType(raw) };
|
|
76
|
+
}
|
|
77
|
+
if (!isRecord(raw) || !Array.isArray(raw.content))
|
|
78
|
+
return { items: [] };
|
|
79
|
+
const meta = isRecord(raw.page) ? raw.page : raw;
|
|
80
|
+
const number = isNumber(meta.number) ? meta.number : undefined;
|
|
81
|
+
const totalPages = isNumber(meta.totalPages) ? meta.totalPages : undefined;
|
|
82
|
+
const totalElements = isNumber(meta.totalElements) ? meta.totalElements : undefined;
|
|
83
|
+
const hasMore = isBoolean(raw.hasNext)
|
|
84
|
+
? raw.hasNext
|
|
85
|
+
: isBoolean(raw.last)
|
|
86
|
+
? !raw.last
|
|
87
|
+
: number !== undefined && totalPages !== undefined
|
|
88
|
+
? number + 1 < totalPages
|
|
89
|
+
: undefined;
|
|
90
|
+
const hasPrevious = isBoolean(raw.first) ? !raw.first : number === undefined ? undefined : number > 0;
|
|
91
|
+
return {
|
|
92
|
+
// Workaround: `content` is checked to be a list above; its rows are the server's, typed by the service's `T`.
|
|
93
|
+
items: assumeType(raw.content),
|
|
94
|
+
...(slice || totalElements === undefined ? {} : { total: totalElements }),
|
|
95
|
+
...(hasMore === undefined ? {} : { hasMore }),
|
|
96
|
+
...(hasPrevious === undefined ? {} : { hasPrevious }),
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* A Spring Boot backend: Spring Data's `Pageable` (`?page=0&size=25&sort=name,asc&sort=id,desc`), its `Page<T>` or
|
|
101
|
+
* `PagedModel` (or `Slice<T>` with `slice`), the filter as parameters the data binder reads or as spring-filter,
|
|
102
|
+
* and errors from `ProblemDetail` (RFC 9457) and Bean Validation as `ServiceError`s with their field errors.
|
|
103
|
+
*/
|
|
104
|
+
export function springService(base, options = {}) {
|
|
105
|
+
const { slice = false, select, springFilter: expression, fieldPath, projection, ...rest } = options;
|
|
106
|
+
const pathOf = fieldPath ?? ((path) => path.replace(violationPrefix, ""));
|
|
107
|
+
const mapError = (error) => {
|
|
108
|
+
const mapped = error.fields
|
|
109
|
+
? { ...error, fields: error.fields.map((field) => ({ ...field, path: pathOf(field.path) })) }
|
|
110
|
+
: error;
|
|
111
|
+
return rest.mapError ? rest.mapError(mapped) : mapped;
|
|
112
|
+
};
|
|
113
|
+
const writeExpression = expression === true ? (filter) => springFilter(filter) : expression === false ? undefined : expression;
|
|
114
|
+
return restService(base, {
|
|
115
|
+
...rest,
|
|
116
|
+
pageBase: 0,
|
|
117
|
+
position: PagePositionKind.page,
|
|
118
|
+
total: slice ? TotalKind.none : TotalKind.exact,
|
|
119
|
+
filterParams: rest.filterParams ??
|
|
120
|
+
(writeExpression
|
|
121
|
+
? (filter) => {
|
|
122
|
+
const text = writeExpression(filter);
|
|
123
|
+
return text === undefined ? {} : { filter: text };
|
|
124
|
+
}
|
|
125
|
+
: springParams),
|
|
126
|
+
read: (raw) => readSpringPage(select ? select(raw) : raw, slice),
|
|
127
|
+
includeParams: projection === false
|
|
128
|
+
? false
|
|
129
|
+
: (projection ?? ((include) => ({ projection: include.join(",") }))),
|
|
130
|
+
mapError,
|
|
131
|
+
});
|
|
132
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import type { PermissionSubject, Session } from "./session.js";
|
|
2
|
+
/** What Better Auth's `useSession()` gives as `data`, and `auth.api.getSession({ headers })` returns. */
|
|
3
|
+
export type BetterAuthSessionData<User = BetterAuthUser> = {
|
|
4
|
+
user: User;
|
|
5
|
+
session: {
|
|
6
|
+
activeOrganizationId?: string | null;
|
|
7
|
+
token?: string;
|
|
8
|
+
[key: string]: unknown;
|
|
9
|
+
};
|
|
10
|
+
} | null;
|
|
11
|
+
export type BetterAuthUser = {
|
|
12
|
+
id: string;
|
|
13
|
+
role?: string | null;
|
|
14
|
+
[key: string]: unknown;
|
|
15
|
+
};
|
|
16
|
+
/** Better Auth's statements: `{ project: ["create", "update"] }`. */
|
|
17
|
+
export type BetterAuthPermissions = Record<string, string[]>;
|
|
18
|
+
/** A role made with Better Auth's access control (`ac.newRole({ … })`). */
|
|
19
|
+
export type BetterAuthRoleLike = {
|
|
20
|
+
authorize(request: BetterAuthPermissions): {
|
|
21
|
+
success: boolean;
|
|
22
|
+
error?: string | undefined;
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
/** `authClient.useSession` in Better Auth's vanilla client: a store of `{ data }`. */
|
|
26
|
+
export type BetterAuthStoreLike<User = BetterAuthUser> = {
|
|
27
|
+
get(): {
|
|
28
|
+
data: BetterAuthSessionData<User> | undefined;
|
|
29
|
+
isPending?: boolean;
|
|
30
|
+
};
|
|
31
|
+
listen?(listener: () => void): () => void;
|
|
32
|
+
subscribe?(listener: () => void): () => void;
|
|
33
|
+
};
|
|
34
|
+
/** `auth` on the server: `auth.api.getSession({ headers })`. */
|
|
35
|
+
export type BetterAuthServerLike<User = BetterAuthUser> = {
|
|
36
|
+
api: {
|
|
37
|
+
getSession(input: {
|
|
38
|
+
headers: Headers;
|
|
39
|
+
}): Promise<BetterAuthSessionData<User> | undefined>;
|
|
40
|
+
};
|
|
41
|
+
};
|
|
42
|
+
export type BetterAuthSessionOptions<User = BetterAuthUser> = {
|
|
43
|
+
/**
|
|
44
|
+
* The person's roles: the admin plugin's `user.role` by default (`"admin,support"` gives two). With the
|
|
45
|
+
* organization plugin, pass the active member's role, which the session doesn't carry.
|
|
46
|
+
*/
|
|
47
|
+
role?: string | readonly string[] | ((data: NonNullable<BetterAuthSessionData<User>>) => string | readonly string[] | undefined);
|
|
48
|
+
/** The access control roles by name (`{ admin, member }` from `ac.newRole`); a role may grant what's asked. */
|
|
49
|
+
roles?: Record<string, BetterAuthRoleLike>;
|
|
50
|
+
/**
|
|
51
|
+
* Checks a role instead of `roles`: `authClient.organization.checkRolePermission` or
|
|
52
|
+
* `authClient.admin.checkRolePermission`, called with `{ role, permissions }`.
|
|
53
|
+
*/
|
|
54
|
+
checkRolePermission?: (input: {
|
|
55
|
+
role: string;
|
|
56
|
+
permissions: BetterAuthPermissions;
|
|
57
|
+
}) => boolean;
|
|
58
|
+
/**
|
|
59
|
+
* What an action asks for. By default `customers.block` asks `{ customers: ["block"] }`, and a resource action
|
|
60
|
+
* (`create` on customers) `{ customers: ["create"] }`; an action with no resource is allowed.
|
|
61
|
+
*/
|
|
62
|
+
permissions?: (action: string, subject?: PermissionSubject) => BetterAuthPermissions | undefined;
|
|
63
|
+
/** The refusal's reason when nobody is signed in; a plain `false` (the dictionary's "not allowed") without it. */
|
|
64
|
+
signedOut?: string;
|
|
65
|
+
/** The refusal's reason when no role grants it, unless the access control gave one. */
|
|
66
|
+
denied?: string;
|
|
67
|
+
token?: () => Promise<string | undefined>;
|
|
68
|
+
};
|
|
69
|
+
/** `customers.block` asks `{ customers: ["block"] }`; `create` on customers asks `{ customers: ["create"] }`. */
|
|
70
|
+
export declare function betterAuthPermissions(action: string, subject?: PermissionSubject): BetterAuthPermissions | undefined;
|
|
71
|
+
/**
|
|
72
|
+
* A session from Better Auth's session data: the `data` of `authClient.useSession()` in a component, or what
|
|
73
|
+
* `auth.api.getSession({ headers })` returns on the server. `can` asks the person's roles (`user.role` by default)
|
|
74
|
+
* through your access control (`roles`) or `checkRolePermission`; the organization is the active one.
|
|
75
|
+
*/
|
|
76
|
+
export declare function betterAuthSession<User = BetterAuthUser>(data: BetterAuthSessionData<User> | undefined, options?: BetterAuthSessionOptions<User>): Session<User>;
|
|
77
|
+
/**
|
|
78
|
+
* A live session over the vanilla client's store (`authClient.useSession` from `better-auth/client`): `user`,
|
|
79
|
+
* `organization` and `can` read the latest data, and `subscribe` follows sign-in, sign-out and organization changes.
|
|
80
|
+
*/
|
|
81
|
+
export declare function betterAuthStoreSession<User = BetterAuthUser>(store: BetterAuthStoreLike<User>, options?: BetterAuthSessionOptions<User>): Session<User>;
|
|
82
|
+
/** The request's session on the server: `auth.api.getSession({ headers })`, as a `Session`. */
|
|
83
|
+
export declare function betterAuthServerSession<User = BetterAuthUser>(auth: BetterAuthServerLike<User>, headers: Headers, options?: BetterAuthSessionOptions<User>): Promise<Session<User>>;
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { isFunction, isRecord, isString } from "../core/guards.js";
|
|
2
|
+
const roleSplit = /\s*,\s*/u;
|
|
3
|
+
/** `customers.block` asks `{ customers: ["block"] }`; `create` on customers asks `{ customers: ["create"] }`. */
|
|
4
|
+
export function betterAuthPermissions(action, subject) {
|
|
5
|
+
const dot = action.lastIndexOf(".");
|
|
6
|
+
const resource = dot > 0 ? action.slice(0, dot) : subject?.resource;
|
|
7
|
+
const verb = dot > 0 ? action.slice(dot + 1) : action;
|
|
8
|
+
return resource === undefined || verb === "" ? undefined : { [resource]: [verb] };
|
|
9
|
+
}
|
|
10
|
+
function rolesOf(data, option) {
|
|
11
|
+
const given = isFunction(option) ? option(data) : option;
|
|
12
|
+
const raw = given ?? (isRecord(data.user) && isString(data.user.role) ? data.user.role : undefined);
|
|
13
|
+
const list = raw === undefined ? [] : isString(raw) ? raw.split(roleSplit) : raw;
|
|
14
|
+
return list.filter((role) => role !== "");
|
|
15
|
+
}
|
|
16
|
+
function checkerOf(data, options) {
|
|
17
|
+
return (action, subject) => {
|
|
18
|
+
if (data === undefined || data === null)
|
|
19
|
+
return options.signedOut === undefined ? false : { allowed: false, reason: options.signedOut };
|
|
20
|
+
if (!options.roles && !options.checkRolePermission)
|
|
21
|
+
return true;
|
|
22
|
+
const asked = (options.permissions ?? betterAuthPermissions)(action, subject);
|
|
23
|
+
if (asked === undefined)
|
|
24
|
+
return true;
|
|
25
|
+
let reason;
|
|
26
|
+
for (const role of rolesOf(data, options.role)) {
|
|
27
|
+
if (options.checkRolePermission?.({ role, permissions: asked }) === true)
|
|
28
|
+
return true;
|
|
29
|
+
const answer = options.roles?.[role]?.authorize(asked);
|
|
30
|
+
if (answer?.success === true)
|
|
31
|
+
return true;
|
|
32
|
+
reason ??= answer?.error;
|
|
33
|
+
}
|
|
34
|
+
const why = options.denied ?? reason;
|
|
35
|
+
return why === undefined ? false : { allowed: false, reason: why };
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
function organizationOf(data) {
|
|
39
|
+
const id = data?.session.activeOrganizationId;
|
|
40
|
+
return isString(id) ? id : undefined;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* A session from Better Auth's session data: the `data` of `authClient.useSession()` in a component, or what
|
|
44
|
+
* `auth.api.getSession({ headers })` returns on the server. `can` asks the person's roles (`user.role` by default)
|
|
45
|
+
* through your access control (`roles`) or `checkRolePermission`; the organization is the active one.
|
|
46
|
+
*/
|
|
47
|
+
export function betterAuthSession(data, options = {}) {
|
|
48
|
+
return {
|
|
49
|
+
user: data?.user ?? null,
|
|
50
|
+
organization: organizationOf(data),
|
|
51
|
+
can: checkerOf(data, options),
|
|
52
|
+
...(options.token ? { token: options.token } : {}),
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* A live session over the vanilla client's store (`authClient.useSession` from `better-auth/client`): `user`,
|
|
57
|
+
* `organization` and `can` read the latest data, and `subscribe` follows sign-in, sign-out and organization changes.
|
|
58
|
+
*/
|
|
59
|
+
export function betterAuthStoreSession(store, options = {}) {
|
|
60
|
+
const data = () => store.get().data;
|
|
61
|
+
return {
|
|
62
|
+
get user() {
|
|
63
|
+
return data()?.user ?? null;
|
|
64
|
+
},
|
|
65
|
+
get organization() {
|
|
66
|
+
return organizationOf(data());
|
|
67
|
+
},
|
|
68
|
+
can: (action, subject) => checkerOf(data(), options)(action, subject),
|
|
69
|
+
subscribe(listener) {
|
|
70
|
+
if (store.listen)
|
|
71
|
+
return store.listen(listener);
|
|
72
|
+
let first = true;
|
|
73
|
+
return (store.subscribe?.(() => {
|
|
74
|
+
if (first)
|
|
75
|
+
first = false;
|
|
76
|
+
else
|
|
77
|
+
listener();
|
|
78
|
+
}) ?? (() => { }));
|
|
79
|
+
},
|
|
80
|
+
...(options.token ? { token: options.token } : {}),
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
/** The request's session on the server: `auth.api.getSession({ headers })`, as a `Session`. */
|
|
84
|
+
export async function betterAuthServerSession(auth, headers, options = {}) {
|
|
85
|
+
return betterAuthSession(await auth.api.getSession({ headers }), options);
|
|
86
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { ResourceAction } from "../core/constants.js";
|
|
2
|
+
import type { Refusal } from "../core/refusal.js";
|
|
3
|
+
export type PermissionSubject = {
|
|
4
|
+
resource: string;
|
|
5
|
+
row?: unknown;
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* Who is asking and what they may do. It only reads: signing in or out and refreshing tokens stay in the auth
|
|
9
|
+
* library. `can` is the one place permissions live; tables, forms, actions, navigation and agents ask it.
|
|
10
|
+
*/
|
|
11
|
+
export interface Session<User = unknown> {
|
|
12
|
+
user: User | null;
|
|
13
|
+
organization?: string | undefined;
|
|
14
|
+
token?(): Promise<string | undefined>;
|
|
15
|
+
can(action: ResourceAction | string, subject?: PermissionSubject): boolean | Refusal;
|
|
16
|
+
subscribe?(listener: () => void): () => void;
|
|
17
|
+
}
|
|
18
|
+
export type SessionOptions<User> = {
|
|
19
|
+
user: User | null;
|
|
20
|
+
organization?: string;
|
|
21
|
+
token?: () => Promise<string | undefined>;
|
|
22
|
+
/** Allows everything when left out. */
|
|
23
|
+
can?: (action: ResourceAction | string, subject?: PermissionSubject) => boolean | Refusal;
|
|
24
|
+
subscribe?: (listener: () => void) => () => void;
|
|
25
|
+
};
|
|
26
|
+
export declare function createSession<User>(options: SessionOptions<User>): Session<User>;
|
|
27
|
+
export type CaslAbilityLike = {
|
|
28
|
+
can(action: string, subject: unknown, field?: string): boolean;
|
|
29
|
+
relevantRuleFor?(action: string, subject: unknown): {
|
|
30
|
+
reason?: string | undefined;
|
|
31
|
+
} | null | undefined;
|
|
32
|
+
on?(event: string, listener: () => void): () => void;
|
|
33
|
+
};
|
|
34
|
+
export type CaslSessionOptions<User> = {
|
|
35
|
+
user: User | null;
|
|
36
|
+
organization?: string;
|
|
37
|
+
token?: () => Promise<string | undefined>;
|
|
38
|
+
/** Wraps a row as CASL's `subject(type, row)`; by default the row gets a `__caslSubjectType__`. */
|
|
39
|
+
subject?: (resource: string, row: unknown) => unknown;
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* A session over a CASL ability: `can(action, { resource, row })` asks `ability.can(action, subject(resource, row))`.
|
|
43
|
+
* A rule's `because(...)` reason becomes the refusal's reason.
|
|
44
|
+
*/
|
|
45
|
+
export declare function fromCasl<User>(ability: CaslAbilityLike, options: CaslSessionOptions<User>): Session<User>;
|