@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,190 @@
|
|
|
1
|
+
import { FilterKind, ResourceAction, ServiceErrorKind, SortDirection, TargetKind } from "../../core/constants.js";
|
|
2
|
+
import { ServiceFailure, isServiceError, serviceError, toServiceError } from "../../core/errors.js";
|
|
3
|
+
import { isOneOf, isString, valuesOf } from "../../core/guards.js";
|
|
4
|
+
import { searchKey } from "../../resource/resource.js";
|
|
5
|
+
const statusOf = {
|
|
6
|
+
[ServiceErrorKind.validation]: 422,
|
|
7
|
+
[ServiceErrorKind.conflict]: 409,
|
|
8
|
+
[ServiceErrorKind.forbidden]: 403,
|
|
9
|
+
[ServiceErrorKind.notFound]: 404,
|
|
10
|
+
[ServiceErrorKind.network]: 502,
|
|
11
|
+
[ServiceErrorKind.server]: 500,
|
|
12
|
+
[ServiceErrorKind.aborted]: 499,
|
|
13
|
+
};
|
|
14
|
+
const reserved = new Set(["page", "size", "sort", searchKey, "except", "ids", "include"]);
|
|
15
|
+
const sortDirections = valuesOf(SortDirection);
|
|
16
|
+
function fail(kind, message) {
|
|
17
|
+
throw new ServiceFailure(serviceError(kind, message));
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* A `ServiceError` as an RFC 9457 problem: the status of its kind, the message as `detail`, field errors as
|
|
21
|
+
* `errors[{ field, message, code }]` and a conflict's `current` row. `restService` reads it back into the same error.
|
|
22
|
+
*/
|
|
23
|
+
export function problemResponse(error) {
|
|
24
|
+
const status = error.status ?? statusOf[error.kind];
|
|
25
|
+
const body = {
|
|
26
|
+
type: "about:blank",
|
|
27
|
+
title: error.kind,
|
|
28
|
+
status,
|
|
29
|
+
detail: error.message,
|
|
30
|
+
...(error.fields
|
|
31
|
+
? { errors: error.fields.map((field) => ({ field: field.path, message: field.message, code: field.code })) }
|
|
32
|
+
: {}),
|
|
33
|
+
...(error.kind === ServiceErrorKind.conflict && error.current !== undefined ? { current: error.current } : {}),
|
|
34
|
+
};
|
|
35
|
+
return Response.json(body, { status, headers: { "content-type": "application/problem+json" } });
|
|
36
|
+
}
|
|
37
|
+
function safeError(error) {
|
|
38
|
+
if (error instanceof ServiceFailure || isServiceError(error))
|
|
39
|
+
return toServiceError(error);
|
|
40
|
+
const normalized = toServiceError(error);
|
|
41
|
+
if (normalized.kind === ServiceErrorKind.aborted)
|
|
42
|
+
return normalized;
|
|
43
|
+
// Security: an unexpected exception's message can name tables, paths or queries; the client gets a generic one.
|
|
44
|
+
return serviceError(ServiceErrorKind.server, "Something went wrong.");
|
|
45
|
+
}
|
|
46
|
+
function parseJson(raw) {
|
|
47
|
+
try {
|
|
48
|
+
return JSON.parse(raw);
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function sortOf(values) {
|
|
55
|
+
return values.flatMap((value) => {
|
|
56
|
+
const at = value.lastIndexOf(",");
|
|
57
|
+
const direction = value.slice(at + 1);
|
|
58
|
+
return at > 0 && isOneOf(sortDirections, direction) ? [{ field: value.slice(0, at), direction }] : [];
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
function wholeNumber(raw, fallback) {
|
|
62
|
+
const value = Number(raw ?? "");
|
|
63
|
+
return Number.isInteger(value) && value > 0 ? value : fallback;
|
|
64
|
+
}
|
|
65
|
+
/** The `Query` a `restService` list request carries: filters by their declared kind, `q`, `sort`, `size`, `page`. */
|
|
66
|
+
export function queryOfSearch(resource, params, maxPageSize = 100) {
|
|
67
|
+
const kinds = new Map(resource.filters().map((filter) => [filter.key, filter.kind]));
|
|
68
|
+
const filter = {};
|
|
69
|
+
for (const name of new Set(params.keys())) {
|
|
70
|
+
if (reserved.has(name))
|
|
71
|
+
continue;
|
|
72
|
+
const values = params.getAll(name);
|
|
73
|
+
const first = values[0] ?? "";
|
|
74
|
+
const kind = kinds.get(name);
|
|
75
|
+
if (kind === FilterKind.multiSelect)
|
|
76
|
+
filter[name] = values;
|
|
77
|
+
else if (kind === FilterKind.boolean)
|
|
78
|
+
filter[name] = first === "true";
|
|
79
|
+
else if (kind === FilterKind.dateRange || kind === FilterKind.numberRange)
|
|
80
|
+
filter[name] = parseJson(first);
|
|
81
|
+
else
|
|
82
|
+
filter[name] = values.length > 1 ? values : first;
|
|
83
|
+
}
|
|
84
|
+
const search = params.get(searchKey);
|
|
85
|
+
const include = (params.get("include") ?? "").split(",").filter((name) => name !== "");
|
|
86
|
+
return {
|
|
87
|
+
...(include.length > 0 ? { include } : {}),
|
|
88
|
+
filter: resource.filterOf(filter),
|
|
89
|
+
search: search === null || search === "" ? undefined : search,
|
|
90
|
+
sort: sortOf(params.getAll("sort")),
|
|
91
|
+
size: Math.min(wholeNumber(params.get("size"), 25), maxPageSize),
|
|
92
|
+
position: { page: wholeNumber(params.get("page"), 1) },
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
async function bodyOf(request) {
|
|
96
|
+
const raw = await request.text();
|
|
97
|
+
const body = raw === "" ? undefined : parseJson(raw);
|
|
98
|
+
if (body === undefined)
|
|
99
|
+
fail(ServiceErrorKind.validation, "The request body isn't JSON.");
|
|
100
|
+
return body;
|
|
101
|
+
}
|
|
102
|
+
const ctx = (request, session) => ({ signal: request.signal, session });
|
|
103
|
+
function idParam(params) {
|
|
104
|
+
const raw = Object.values(params).find((value) => value !== undefined);
|
|
105
|
+
const segments = raw === undefined ? [] : isString(raw) ? [raw] : raw;
|
|
106
|
+
if (segments.length > 1)
|
|
107
|
+
return null;
|
|
108
|
+
return segments[0];
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Route handlers (`app/api/customers/[[...id]]/route.ts`) that serve a service the way `restService` calls it: `GET`,
|
|
112
|
+
* `POST`, `PATCH`/`PUT` (`If-Match` is the version), `DELETE`. Each asks the resource's `can` with the request's
|
|
113
|
+
* session first; every error goes back as a problem `restService` reads into the same `ServiceError`.
|
|
114
|
+
*/
|
|
115
|
+
export function resourceHandler(resource, options = {}) {
|
|
116
|
+
const service = options.service ?? resource.service;
|
|
117
|
+
const maxPageSize = options.maxPageSize ?? service.capabilities.maxPageSize ?? 100;
|
|
118
|
+
function demand(action, row, session) {
|
|
119
|
+
const allowed = resource.check(action, row, session, "not allowed");
|
|
120
|
+
if (allowed !== true)
|
|
121
|
+
fail(ServiceErrorKind.forbidden, allowed.reason === "" ? "Not allowed." : allowed.reason);
|
|
122
|
+
}
|
|
123
|
+
function handle(run) {
|
|
124
|
+
return async (request, context) => {
|
|
125
|
+
try {
|
|
126
|
+
const id = idParam(await context.params);
|
|
127
|
+
if (id === null)
|
|
128
|
+
fail(ServiceErrorKind.notFound, "No such path.");
|
|
129
|
+
return await run(request, id, await options.session?.());
|
|
130
|
+
}
|
|
131
|
+
catch (error) {
|
|
132
|
+
return problemResponse(safeError(error));
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
async function existing(id, request, session) {
|
|
137
|
+
return service.get(resource.parseId(id), ctx(request, session));
|
|
138
|
+
}
|
|
139
|
+
const update = handle(async (request, id, session) => {
|
|
140
|
+
if (id === undefined)
|
|
141
|
+
fail(ServiceErrorKind.notFound, "Updates need an id.");
|
|
142
|
+
demand(ResourceAction.update, await existing(id, request, session), session);
|
|
143
|
+
const version = request.headers.get("if-match");
|
|
144
|
+
const row = await service.update(resource.parseId(id), await bodyOf(request), {
|
|
145
|
+
...ctx(request, session),
|
|
146
|
+
...(version === null ? {} : { version }),
|
|
147
|
+
});
|
|
148
|
+
return Response.json(row);
|
|
149
|
+
});
|
|
150
|
+
return {
|
|
151
|
+
GET: handle(async (request, id, session) => {
|
|
152
|
+
if (id === undefined) {
|
|
153
|
+
demand(ResourceAction.list, undefined, session);
|
|
154
|
+
const params = new URL(request.url).searchParams;
|
|
155
|
+
const ids = params.getAll("ids");
|
|
156
|
+
if (ids.length > 0) {
|
|
157
|
+
const parsed = ids.slice(0, maxPageSize).map((raw) => resource.parseId(raw));
|
|
158
|
+
const getMany = service.getMany;
|
|
159
|
+
const rows = getMany
|
|
160
|
+
? await getMany.call(service, parsed, ctx(request, session))
|
|
161
|
+
: await Promise.all(parsed.map((one) => service.get(one, ctx(request, session))));
|
|
162
|
+
for (const row of rows)
|
|
163
|
+
demand(ResourceAction.get, row, session);
|
|
164
|
+
return Response.json(rows);
|
|
165
|
+
}
|
|
166
|
+
const query = queryOfSearch(resource, params, maxPageSize);
|
|
167
|
+
return Response.json(await service.list(query, ctx(request, session)));
|
|
168
|
+
}
|
|
169
|
+
const row = await existing(id, request, session);
|
|
170
|
+
demand(ResourceAction.get, row, session);
|
|
171
|
+
return Response.json(row);
|
|
172
|
+
}),
|
|
173
|
+
POST: handle(async (request, id, session) => {
|
|
174
|
+
if (id !== undefined)
|
|
175
|
+
fail(ServiceErrorKind.notFound, "Create posts to the collection.");
|
|
176
|
+
demand(ResourceAction.create, undefined, session);
|
|
177
|
+
const row = await service.create(await bodyOf(request), ctx(request, session));
|
|
178
|
+
return Response.json(row, { status: 201 });
|
|
179
|
+
}),
|
|
180
|
+
PATCH: update,
|
|
181
|
+
PUT: update,
|
|
182
|
+
DELETE: handle(async (request, id, session) => {
|
|
183
|
+
if (id === undefined)
|
|
184
|
+
fail(ServiceErrorKind.validation, "This route removes by id only.");
|
|
185
|
+
demand(ResourceAction.remove, await existing(id, request, session), session);
|
|
186
|
+
await service.remove({ kind: TargetKind.ids, ids: [resource.parseId(id)] }, ctx(request, session));
|
|
187
|
+
return new Response(null, { status: 204 });
|
|
188
|
+
}),
|
|
189
|
+
};
|
|
190
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { navPage, resourcePage, type NextMetadata, type NextPage, type NextPageOptions, type NextPageProps, type SearchParams, } from "./page.js";
|
|
2
|
+
export { prefetchScreen, type AnyService, type PrefetchOptions, type PrefetchResult } from "./prefetch.js";
|
|
3
|
+
export { nextPermissionSession, nextSession, type NextPermissionSession, type NextRequestScope } from "./session.js";
|
|
4
|
+
export { sessionPayload, type SessionPayload } from "../../permissions/permissions.js";
|
|
5
|
+
export { problemResponse, queryOfSearch, resourceHandler, type NextRouteContext, type ResourceHandler, type ResourceHandlerOptions, type RouteHandler, } from "./handler.js";
|
|
6
|
+
export { navScreen, pathOfParams, resourceScreen, type NextScreen, type RouteParams } from "../screen.js";
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { navPage, resourcePage, } from "./page.js";
|
|
2
|
+
export { prefetchScreen } from "./prefetch.js";
|
|
3
|
+
export { nextPermissionSession, nextSession } from "./session.js";
|
|
4
|
+
export { sessionPayload } from "../../permissions/permissions.js";
|
|
5
|
+
export { problemResponse, queryOfSearch, resourceHandler, } from "./handler.js";
|
|
6
|
+
export { navScreen, pathOfParams, resourceScreen } from "../screen.js";
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { QueryClient } from "@tanstack/react-query";
|
|
2
|
+
import { type ReactNode } from "react";
|
|
3
|
+
import { ResourceScreen } from "../../core/constants.js";
|
|
4
|
+
import { type DataLabels } from "../../core/data-labels.js";
|
|
5
|
+
import type { Locale } from "../../i18n/locale.js";
|
|
6
|
+
import { type Nav } from "../../navigation/nav.js";
|
|
7
|
+
import type { AnyResource } from "../../resource/resource.js";
|
|
8
|
+
import type { Session } from "../../session/session.js";
|
|
9
|
+
import type { ViewOptions } from "../../view/view.js";
|
|
10
|
+
import { type NextScreen, type RouteParams } from "../screen.js";
|
|
11
|
+
import { type AnyService } from "./prefetch.js";
|
|
12
|
+
export type SearchParams = Record<string, string | readonly string[] | undefined>;
|
|
13
|
+
/** The props Next.js passes a page; `params` holds the catch-all's segments. */
|
|
14
|
+
export type NextPageProps = {
|
|
15
|
+
params: Promise<RouteParams>;
|
|
16
|
+
searchParams: Promise<SearchParams>;
|
|
17
|
+
};
|
|
18
|
+
export type NextMetadata = {
|
|
19
|
+
title?: string;
|
|
20
|
+
};
|
|
21
|
+
export type NextPageOptions = {
|
|
22
|
+
/** The client component that draws the screen (`NavPage` or `ResourcePage` inside a `"use client"` file). */
|
|
23
|
+
render: (screen: NextScreen) => ReactNode;
|
|
24
|
+
/** The request's session, as `nextSession(…)` gives it; services get it in their `CallContext`. */
|
|
25
|
+
session?: () => Session | undefined | Promise<Session | undefined>;
|
|
26
|
+
/** Services that answer on the server, by resource key, when the resources' own call the backend over HTTP. */
|
|
27
|
+
services?: Readonly<Record<string, AnyService>>;
|
|
28
|
+
/** The view options the client screen gives each resource (scopes, base filter, page size). */
|
|
29
|
+
view?: (resource: AnyResource) => ViewOptions<unknown> | undefined;
|
|
30
|
+
/** Where the app is mounted (`/admin`), as given to `useNextRouter`. */
|
|
31
|
+
base?: string;
|
|
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. */
|
|
38
|
+
labels?: DataLabels;
|
|
39
|
+
/** A screen's title, instead of the resource's label, "New …", the record's title or "Edit …". */
|
|
40
|
+
title?: (screen: NextScreen, row: unknown) => string | undefined;
|
|
41
|
+
/** The request's query client; by default a new one per request (React's `cache`). */
|
|
42
|
+
client?: () => QueryClient;
|
|
43
|
+
};
|
|
44
|
+
export type NextPage = {
|
|
45
|
+
/** The page component: `export default page.Page`. */
|
|
46
|
+
Page: (props: NextPageProps) => Promise<ReactNode>;
|
|
47
|
+
/** `export const generateMetadata = page.generateMetadata`: the screen's title, from the same fetch as the page. */
|
|
48
|
+
generateMetadata: (props: NextPageProps) => Promise<NextMetadata>;
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* One optional catch-all page (`app/(admin)/[[...path]]/page.tsx`) for every resource of the manifest: it fetches the
|
|
52
|
+
* path's screen (list, `new`, a record, its `edit`) with the request's session and renders `render(screen)` already
|
|
53
|
+
* hydrated. An unknown path or record is `notFound()`; the bare root redirects to the manifest's first page.
|
|
54
|
+
*/
|
|
55
|
+
export declare function navPage<Route>(nav: Nav<Route>, options: NextPageOptions): NextPage;
|
|
56
|
+
/**
|
|
57
|
+
* A Next.js page for one resource. In an optional catch-all of its own (`app/customers/[[...slug]]/page.tsx`) it
|
|
58
|
+
* reads the screen from the segments; in a folder per screen (`app/customers/[id]/edit/page.tsx`) give `screen`, and
|
|
59
|
+
* the record's id comes from the `id` param.
|
|
60
|
+
*/
|
|
61
|
+
export declare function resourcePage(resource: AnyResource, options: NextPageOptions & {
|
|
62
|
+
screen?: ResourceScreen;
|
|
63
|
+
}): NextPage;
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { dehydrate, QueryClient } from "@tanstack/react-query";
|
|
3
|
+
import { notFound, redirect } from "next/navigation";
|
|
4
|
+
import { cache } from "react";
|
|
5
|
+
import { ResourceScreen } from "../../core/constants.js";
|
|
6
|
+
import { isFunction, isString } from "../../core/guards.js";
|
|
7
|
+
import { dataLabelsEn } from "../../core/data-labels.js";
|
|
8
|
+
import { dataLabelsOf } from "../../i18n/labels.js";
|
|
9
|
+
import { screenUse } from "../../navigation/nav.js";
|
|
10
|
+
import { isSegments, navScreen, pathOfParams, resourceScreen } from "../screen.js";
|
|
11
|
+
import { ScreenHydration } from "../screen-hydration.js";
|
|
12
|
+
import { prefetchScreen } from "./prefetch.js";
|
|
13
|
+
const requestClient = cache(() => new QueryClient({
|
|
14
|
+
defaultOptions: { queries: { staleTime: 60_000, retry: false } },
|
|
15
|
+
}));
|
|
16
|
+
function searchOf(params) {
|
|
17
|
+
const query = new URLSearchParams();
|
|
18
|
+
for (const [name, value] of Object.entries(params)) {
|
|
19
|
+
if (value === undefined)
|
|
20
|
+
continue;
|
|
21
|
+
for (const entry of isSegments(value) ? value : [value])
|
|
22
|
+
query.append(name, entry);
|
|
23
|
+
}
|
|
24
|
+
const text = query.toString();
|
|
25
|
+
return text === "" ? "" : `?${text}`;
|
|
26
|
+
}
|
|
27
|
+
function defaultTitle(screen, row, labels, locale) {
|
|
28
|
+
const resource = screen.resource.in(locale);
|
|
29
|
+
const one = resource.label(1);
|
|
30
|
+
const named = row === undefined ? one : resource.title(row);
|
|
31
|
+
if (screen.screen === ResourceScreen.list)
|
|
32
|
+
return resource.label(2);
|
|
33
|
+
if (screen.screen === ResourceScreen.create)
|
|
34
|
+
return resource.createLabel ?? labels.create(one);
|
|
35
|
+
if (screen.screen === ResourceScreen.edit)
|
|
36
|
+
return `${labels.edit} ${named}`;
|
|
37
|
+
return named;
|
|
38
|
+
}
|
|
39
|
+
function screenPage(resolve, options) {
|
|
40
|
+
const clientOf = options.client ?? requestClient;
|
|
41
|
+
const localeOf = () => (isFunction(options.locale) ? options.locale() : options.locale);
|
|
42
|
+
const base = (options.base ?? "").replace(/\/+$/u, "");
|
|
43
|
+
async function load(props) {
|
|
44
|
+
const screen = resolve(await props.params);
|
|
45
|
+
if (screen && "home" in screen && screen.home !== undefined)
|
|
46
|
+
redirect(`${base}${screen.home}`);
|
|
47
|
+
if (!screen || "home" in screen)
|
|
48
|
+
notFound();
|
|
49
|
+
const session = await options.session?.();
|
|
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 };
|
|
54
|
+
const result = await prefetchScreen(client, screen, {
|
|
55
|
+
session,
|
|
56
|
+
services: options.services,
|
|
57
|
+
search: searchOf(await props.searchParams),
|
|
58
|
+
view: options.view?.(screen.resource),
|
|
59
|
+
});
|
|
60
|
+
if (result.notFound)
|
|
61
|
+
notFound();
|
|
62
|
+
return { screen, client, row: result.row };
|
|
63
|
+
}
|
|
64
|
+
return {
|
|
65
|
+
async Page(props) {
|
|
66
|
+
const { screen, client } = await load(props);
|
|
67
|
+
return _jsx(ScreenHydration, { state: dehydrate(client), children: options.render(screen) });
|
|
68
|
+
},
|
|
69
|
+
async generateMetadata(props) {
|
|
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) };
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* One optional catch-all page (`app/(admin)/[[...path]]/page.tsx`) for every resource of the manifest: it fetches the
|
|
79
|
+
* path's screen (list, `new`, a record, its `edit`) with the request's session and renders `render(screen)` already
|
|
80
|
+
* hydrated. An unknown path or record is `notFound()`; the bare root redirects to the manifest's first page.
|
|
81
|
+
*/
|
|
82
|
+
export function navPage(nav, options) {
|
|
83
|
+
return screenPage((params) => {
|
|
84
|
+
const pathname = pathOfParams(params);
|
|
85
|
+
return pathname === "/" ? { home: nav.visibleItems()[0]?.to } : navScreen(nav, pathname);
|
|
86
|
+
}, options);
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* A Next.js page for one resource. In an optional catch-all of its own (`app/customers/[[...slug]]/page.tsx`) it
|
|
90
|
+
* reads the screen from the segments; in a folder per screen (`app/customers/[id]/edit/page.tsx`) give `screen`, and
|
|
91
|
+
* the record's id comes from the `id` param.
|
|
92
|
+
*/
|
|
93
|
+
export function resourcePage(resource, options) {
|
|
94
|
+
const fixed = options.screen;
|
|
95
|
+
return screenPage((params) => {
|
|
96
|
+
if (fixed === undefined)
|
|
97
|
+
return resourceScreen(resource, pathOfParams(params, resource.paths.list()));
|
|
98
|
+
const raw = params.id;
|
|
99
|
+
const id = isSegments(raw) ? raw[0] : raw;
|
|
100
|
+
if (fixed === ResourceScreen.list)
|
|
101
|
+
return resourceScreen(resource, resource.paths.list());
|
|
102
|
+
if (fixed === ResourceScreen.create)
|
|
103
|
+
return resourceScreen(resource, resource.paths.create());
|
|
104
|
+
if (!isString(id))
|
|
105
|
+
return undefined;
|
|
106
|
+
const parsed = resource.parseId(id);
|
|
107
|
+
const path = fixed === ResourceScreen.edit ? resource.paths.edit(parsed) : resource.paths.detail(parsed);
|
|
108
|
+
return resourceScreen(resource, path);
|
|
109
|
+
}, options);
|
|
110
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { QueryClient } from "@tanstack/react-query";
|
|
2
|
+
import type { ResourceService } from "../../core/contracts.js";
|
|
3
|
+
import type { Session } from "../../session/session.js";
|
|
4
|
+
import { type ViewOptions } from "../../view/view.js";
|
|
5
|
+
import type { NextScreen } from "../screen.js";
|
|
6
|
+
export type AnyService = ResourceService<any, any, any, any, any>;
|
|
7
|
+
export type PrefetchOptions = {
|
|
8
|
+
session?: Session | undefined;
|
|
9
|
+
/** The service that answers on the server, when the resource's own calls the backend over HTTP. */
|
|
10
|
+
service?: AnyService | undefined;
|
|
11
|
+
/** Services that answer on the server for the related resources too, by key; their own otherwise. */
|
|
12
|
+
services?: Readonly<Record<string, AnyService>> | undefined;
|
|
13
|
+
/** The page's query string: `?status=blocked&page=2`. */
|
|
14
|
+
search?: string;
|
|
15
|
+
/** The view options the client screen uses (scopes, base filter, page size), so both ask for the same page. */
|
|
16
|
+
view?: ViewOptions<unknown> | undefined;
|
|
17
|
+
};
|
|
18
|
+
export type PrefetchResult = {
|
|
19
|
+
/** The record of a detail or edit screen. */
|
|
20
|
+
row?: unknown;
|
|
21
|
+
/** True when the record doesn't exist: the service answered `ServiceErrorKind.notFound`. */
|
|
22
|
+
notFound: boolean;
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Fetches a screen's first queries into `client` under the keys the blocks read: a list's first page with its
|
|
26
|
+
* relations, or a record with its relations and its `hasMany` tab's first page. A failed list stays out for the
|
|
27
|
+
* client to show; a missing record is `notFound`; a screen the session may not see fetches nothing.
|
|
28
|
+
*/
|
|
29
|
+
export declare function prefetchScreen(client: QueryClient, screen: NextScreen, options?: PrefetchOptions): Promise<PrefetchResult>;
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { RelationKind, ResourceAction, ResourceScreen, ServiceErrorKind } from "../../core/constants.js";
|
|
2
|
+
import { toServiceError } from "../../core/errors.js";
|
|
3
|
+
import { defineView } from "../../view/view.js";
|
|
4
|
+
import { resourceDetailKey, resourceDetailWithKey, resourceTableQuery, shownPaths } from "../../react/keys.js";
|
|
5
|
+
import { includeOf, resolveRelations } from "../../resource/relations.js";
|
|
6
|
+
function allowed(resource, action, session) {
|
|
7
|
+
return resource.check(action, undefined, session) === true;
|
|
8
|
+
}
|
|
9
|
+
function relationsOn(client, options, signal) {
|
|
10
|
+
const { session } = options;
|
|
11
|
+
return {
|
|
12
|
+
signal,
|
|
13
|
+
session,
|
|
14
|
+
known: (target, id) => client.getQueryData(resourceDetailKey(target, id)),
|
|
15
|
+
seed: (target, record) => client.setQueryData(resourceDetailKey(target, target.idKey(target.idOf(record))), record),
|
|
16
|
+
canRead: (target) => allowed(target, ResourceAction.get, session),
|
|
17
|
+
serviceOf: (target) => options.services?.[target.key] ?? target.service,
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
async function prefetchTable(client, resource, service, options) {
|
|
21
|
+
const { session } = options;
|
|
22
|
+
const view = defineView(resource, { ...options.view, search: options.search });
|
|
23
|
+
const paths = shownPaths(resource, options.except);
|
|
24
|
+
const table = resourceTableQuery(resource, view, options.fixed ?? {}, paths);
|
|
25
|
+
const count = service.count;
|
|
26
|
+
await Promise.all([
|
|
27
|
+
client.prefetchQuery({
|
|
28
|
+
queryKey: table.page,
|
|
29
|
+
queryFn: async ({ signal }) => {
|
|
30
|
+
const page = await service.list(table.query, { signal, session });
|
|
31
|
+
const items = await resolveRelations(resource, page.items, paths, relationsOn(client, options, signal));
|
|
32
|
+
return { ...page, items };
|
|
33
|
+
},
|
|
34
|
+
}),
|
|
35
|
+
table.total && count
|
|
36
|
+
? client.prefetchQuery({
|
|
37
|
+
queryKey: table.total,
|
|
38
|
+
queryFn: ({ signal }) => count.call(service, table.query.filter, { signal, session }),
|
|
39
|
+
})
|
|
40
|
+
: undefined,
|
|
41
|
+
]);
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Fetches a screen's first queries into `client` under the keys the blocks read: a list's first page with its
|
|
45
|
+
* relations, or a record with its relations and its `hasMany` tab's first page. A failed list stays out for the
|
|
46
|
+
* client to show; a missing record is `notFound`; a screen the session may not see fetches nothing.
|
|
47
|
+
*/
|
|
48
|
+
export async function prefetchScreen(client, screen, options = {}) {
|
|
49
|
+
const { resource, id } = screen;
|
|
50
|
+
const service = options.service ?? options.services?.[resource.key] ?? resource.service;
|
|
51
|
+
const { session } = options;
|
|
52
|
+
if (screen.screen === ResourceScreen.create)
|
|
53
|
+
return { notFound: false };
|
|
54
|
+
if (screen.screen === ResourceScreen.list) {
|
|
55
|
+
if (!allowed(resource, ResourceAction.list, session))
|
|
56
|
+
return { notFound: false };
|
|
57
|
+
await prefetchTable(client, resource, service, { ...options, search: options.search ?? "" });
|
|
58
|
+
return { notFound: false };
|
|
59
|
+
}
|
|
60
|
+
if (!allowed(resource, ResourceAction.get, session))
|
|
61
|
+
return { notFound: false };
|
|
62
|
+
try {
|
|
63
|
+
const row = await client.fetchQuery({
|
|
64
|
+
queryKey: resourceDetailKey(resource, resource.idKey(id)),
|
|
65
|
+
queryFn: ({ signal }) => service.get(id, { signal, session }),
|
|
66
|
+
staleTime: resource.staleTime,
|
|
67
|
+
});
|
|
68
|
+
const paths = shownPaths(resource);
|
|
69
|
+
const include = includeOf(resource.relations, paths);
|
|
70
|
+
if (include.length > 0 && screen.screen === ResourceScreen.detail)
|
|
71
|
+
await client.prefetchQuery({
|
|
72
|
+
queryKey: resourceDetailWithKey(resource, resource.idKey(id), include),
|
|
73
|
+
queryFn: async ({ signal }) => {
|
|
74
|
+
const [resolved] = await resolveRelations(resource, [row], paths, relationsOn(client, options, signal));
|
|
75
|
+
return resolved;
|
|
76
|
+
},
|
|
77
|
+
});
|
|
78
|
+
const tab = screen.tab === undefined ? undefined : resource.relations[screen.tab];
|
|
79
|
+
if (tab?.kind === RelationKind.hasMany) {
|
|
80
|
+
const target = tab.target();
|
|
81
|
+
if (allowed(target, ResourceAction.list, session))
|
|
82
|
+
await prefetchTable(client, target, options.services?.[target.key] ?? target.service, {
|
|
83
|
+
...options,
|
|
84
|
+
search: "",
|
|
85
|
+
view: undefined,
|
|
86
|
+
fixed: { [tab.foreignKey]: id },
|
|
87
|
+
except: tab.foreignKey,
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
return { row, notFound: false };
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
if (toServiceError(error).kind === ServiceErrorKind.notFound)
|
|
94
|
+
return { notFound: true };
|
|
95
|
+
return { notFound: false };
|
|
96
|
+
}
|
|
97
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { cookies, headers } from "next/headers";
|
|
2
|
+
import { type Operations, type Permissions, type PermissionSession, type PermissionSessionOptions, type SessionPayload } from "../../permissions/permissions.js";
|
|
3
|
+
import type { Session } from "../../session/session.js";
|
|
4
|
+
export type NextRequestScope = {
|
|
5
|
+
cookies: Awaited<ReturnType<typeof cookies>>;
|
|
6
|
+
headers: Awaited<ReturnType<typeof headers>>;
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* The session of the request being rendered, from its cookies and headers, read once per request: pages,
|
|
10
|
+
* `generateMetadata`, layouts and route handlers all get the same one. `read` verifies the cookie or token with your
|
|
11
|
+
* auth library and returns `undefined` for nobody.
|
|
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>;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { cookies, headers } from "next/headers";
|
|
2
|
+
import { cache } from "react";
|
|
3
|
+
import { sessionPayload, } from "../../permissions/permissions.js";
|
|
4
|
+
/**
|
|
5
|
+
* The session of the request being rendered, from its cookies and headers, read once per request: pages,
|
|
6
|
+
* `generateMetadata`, layouts and route handlers all get the same one. `read` verifies the cookie or token with your
|
|
7
|
+
* auth library and returns `undefined` for nobody.
|
|
8
|
+
*/
|
|
9
|
+
export function nextSession(read) {
|
|
10
|
+
return cache(async () => read({ cookies: await cookies(), headers: await headers() }));
|
|
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,21 @@
|
|
|
1
|
+
import { type RouterAdapter } from "../navigation/router.js";
|
|
2
|
+
/** The part of Next's `useRouter()` the adapter uses. */
|
|
3
|
+
export type NextAppRouter = {
|
|
4
|
+
push(href: string, options?: {
|
|
5
|
+
scroll?: boolean;
|
|
6
|
+
}): void;
|
|
7
|
+
replace(href: string, options?: {
|
|
8
|
+
scroll?: boolean;
|
|
9
|
+
}): void;
|
|
10
|
+
};
|
|
11
|
+
export type NextRouterOptions = {
|
|
12
|
+
/** Where the app is mounted, as `app/admin/[[...path]]` is at `/admin`. The resources' paths go below it. */
|
|
13
|
+
base?: string;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* The Next.js App Router as a `RouterAdapter`: the location from `usePathname` and `useSearchParams` (the server and
|
|
17
|
+
* the first client render agree), a new path through `useRouter().push`, a new query alone through the History API.
|
|
18
|
+
* Render it in a dynamic layout (one that reads cookies, headers or `connection()`), not under `<Suspense>`: a stream
|
|
19
|
+
* that starts before the page's `notFound()` answers 200.
|
|
20
|
+
*/
|
|
21
|
+
export declare function useNextRouter(options?: NextRouterOptions): RouterAdapter;
|