@eskais/app-sdk 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +68 -2
- package/dist/action/action.d.ts +74 -0
- package/dist/action/action.js +106 -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 +302 -0
- package/dist/core/constants.js +156 -0
- package/dist/core/contracts.d.ts +100 -0
- package/dist/core/contracts.js +3 -0
- package/dist/core/data-labels.d.ts +196 -0
- package/dist/core/data-labels.js +345 -0
- package/dist/core/errors.d.ts +46 -0
- package/dist/core/errors.js +166 -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/draft/draft.d.ts +36 -0
- package/dist/draft/draft.js +87 -0
- package/dist/export/csv.d.ts +25 -0
- package/dist/export/csv.js +59 -0
- package/dist/import/csv-parse.d.ts +11 -0
- package/dist/import/csv-parse.js +70 -0
- package/dist/import/import.d.ts +102 -0
- package/dist/import/import.js +263 -0
- package/dist/index.d.ts +31 -0
- package/dist/index.js +30 -0
- package/dist/navigation/nav.d.ts +119 -0
- package/dist/navigation/nav.js +278 -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 +5 -0
- package/dist/next/server/index.js +5 -0
- package/dist/next/server/page.d.ts +57 -0
- package/dist/next/server/page.js +103 -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 +12 -0
- package/dist/next/server/session.js +10 -0
- package/dist/next/use-next-router.d.ts +21 -0
- package/dist/next/use-next-router.js +104 -0
- package/dist/react/data-layer.d.ts +31 -0
- package/dist/react/data-layer.js +31 -0
- package/dist/react/hooks/use-action.d.ts +12 -0
- package/dist/react/hooks/use-action.js +67 -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-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 +34 -0
- package/dist/react/hooks/use-resource.d.ts +69 -0
- package/dist/react/hooks/use-resource.js +218 -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 +8 -0
- package/dist/react/index.js +8 -0
- package/dist/react/keys.d.ts +51 -0
- package/dist/react/keys.js +67 -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 +44 -0
- package/dist/resource/resource-relations.js +141 -0
- package/dist/resource/resource-schema.d.ts +9 -0
- package/dist/resource/resource-schema.js +73 -0
- package/dist/resource/resource-types.d.ts +281 -0
- package/dist/resource/resource-types.js +1 -0
- package/dist/resource/resource.d.ts +11 -0
- package/dist/resource/resource.js +354 -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/rest-service.d.ts +62 -0
- package/dist/services/rest-service.js +220 -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 +122 -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/package.json +85 -4
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
import { JsonFormat, JsonType, PagePositionKind, ServiceErrorKind, TargetKind, TotalKind } from "../core/constants.js";
|
|
2
|
+
import { ServiceFailure, serviceError } from "../core/errors.js";
|
|
3
|
+
import { isNumber, isRecord } from "../core/guards.js";
|
|
4
|
+
import { applyQuery, matchesFilter, matchesSearch, valueAt } from "./memory-query.js";
|
|
5
|
+
import { assumeType } from "../core/assume.js";
|
|
6
|
+
import { createRng } from "./rng.js";
|
|
7
|
+
import { isStandardSchema, isValidationFailure, issuePath, validate, zodIntrospect, } from "../resource/schema.js";
|
|
8
|
+
const firstNames = [
|
|
9
|
+
"Ana",
|
|
10
|
+
"Luis",
|
|
11
|
+
"Marta",
|
|
12
|
+
"Jorge",
|
|
13
|
+
"Lucía",
|
|
14
|
+
"Pablo",
|
|
15
|
+
"Elena",
|
|
16
|
+
"Diego",
|
|
17
|
+
"Sara",
|
|
18
|
+
"Hugo",
|
|
19
|
+
"Irene",
|
|
20
|
+
"Raúl",
|
|
21
|
+
];
|
|
22
|
+
const lastNames = ["García", "Martín", "López", "Sánchez", "Pérez", "Gómez", "Ruiz", "Díaz", "Moreno", "Álvarez"];
|
|
23
|
+
const companyWords = ["Acme", "Nova", "Atlas", "Cobalto", "Delta", "Faro", "Lince", "Olivo", "Prisma", "Vela", "Zenit"];
|
|
24
|
+
const companySuffixes = ["S.L.", "S.A.", "Group", "Labs", "& Co."];
|
|
25
|
+
const words = ["alpha", "bravo", "cedar", "dune", "ember", "fjord", "grove", "harbor", "iris", "jade", "kelp", "lumen"];
|
|
26
|
+
const fixedNow = new Date("2026-06-01T09:00:00.000Z");
|
|
27
|
+
function ascii(text) {
|
|
28
|
+
return text
|
|
29
|
+
.normalize("NFD")
|
|
30
|
+
.replace(/[̀-ͯ]/gu, "")
|
|
31
|
+
.replace(/[^a-z0-9]/giu, "")
|
|
32
|
+
.toLowerCase();
|
|
33
|
+
}
|
|
34
|
+
function generateString(property, rng, index, now) {
|
|
35
|
+
const key = property.key.toLowerCase();
|
|
36
|
+
if (property.enum)
|
|
37
|
+
return rng.pick(property.enum);
|
|
38
|
+
if (property.format === JsonFormat.email)
|
|
39
|
+
return `${ascii(rng.pick(firstNames))}.${ascii(rng.pick(lastNames))}${String(index + 1)}@example.com`;
|
|
40
|
+
if (property.format === JsonFormat.dateTime) {
|
|
41
|
+
const back = rng.int(0, 730 * 24 * 60) * 60_000;
|
|
42
|
+
return new Date(now.getTime() - back).toISOString();
|
|
43
|
+
}
|
|
44
|
+
if (property.format === JsonFormat.date)
|
|
45
|
+
return new Date(now.getTime() - rng.int(0, 730) * 86_400_000).toISOString().slice(0, 10);
|
|
46
|
+
if (property.format === JsonFormat.time)
|
|
47
|
+
return `${String(rng.int(8, 19)).padStart(2, "0")}:${String(rng.int(0, 3) * 15).padStart(2, "0")}`;
|
|
48
|
+
if (property.format === JsonFormat.uuid)
|
|
49
|
+
return `00000000-0000-4000-8000-${String(index + 1).padStart(12, "0")}`;
|
|
50
|
+
if (property.format === JsonFormat.uri || property.format === JsonFormat.url)
|
|
51
|
+
return `https://example.com/${String(index + 1)}`;
|
|
52
|
+
if (property.minLength !== undefined && property.minLength === property.maxLength)
|
|
53
|
+
return Array.from({ length: property.minLength }, () => String.fromCodePoint(65 + rng.int(0, 25))).join("");
|
|
54
|
+
if (/(?:number|^code|ref)$/u.test(key))
|
|
55
|
+
return `${key.slice(0, 2).toUpperCase()}-${String(10_000 + index + 1)}`;
|
|
56
|
+
let text;
|
|
57
|
+
if (key === "name" || key.endsWith("name"))
|
|
58
|
+
text = rng.bool(0.5)
|
|
59
|
+
? `${rng.pick(firstNames)} ${rng.pick(lastNames)}`
|
|
60
|
+
: `${rng.pick(companyWords)} ${rng.pick(companyWords)} ${rng.pick(companySuffixes)}`;
|
|
61
|
+
else if (/^(?:title|label)$/u.test(key))
|
|
62
|
+
text = `${rng.pick(companyWords)} ${rng.pick(words)}`;
|
|
63
|
+
else
|
|
64
|
+
text = Array.from({ length: rng.int(2, 6) }, () => rng.pick(words)).join(" ");
|
|
65
|
+
const max = property.maxLength ?? 200;
|
|
66
|
+
const fitted = text.slice(0, max);
|
|
67
|
+
return fitted.length >= (property.minLength ?? 0) ? fitted : fitted.padEnd(property.minLength ?? 0, "x");
|
|
68
|
+
}
|
|
69
|
+
function generateNumber(property, rng) {
|
|
70
|
+
const key = property.key.toLowerCase();
|
|
71
|
+
const min = property.minimum ?? 0;
|
|
72
|
+
const money = ["total", "price", "amount", "balance", "cost"].some((word) => key.includes(word));
|
|
73
|
+
const max = property.maximum ?? (money ? 5000 : 1000);
|
|
74
|
+
if (property.type === JsonType.integer || !money)
|
|
75
|
+
return rng.int(Math.ceil(min), Math.floor(max));
|
|
76
|
+
return Math.round((min + rng.next() * (max - min)) * 100) / 100;
|
|
77
|
+
}
|
|
78
|
+
function generateValue(property, rng, index, now) {
|
|
79
|
+
const { type, items, properties } = property;
|
|
80
|
+
if (type === JsonType.string)
|
|
81
|
+
return generateString(property, rng, index, now);
|
|
82
|
+
if (type === JsonType.number || type === JsonType.integer)
|
|
83
|
+
return generateNumber(property, rng);
|
|
84
|
+
if (type === JsonType.boolean)
|
|
85
|
+
return rng.bool();
|
|
86
|
+
if (type === JsonType.array)
|
|
87
|
+
return items ? Array.from({ length: rng.int(0, 3) }, (_, at) => generateValue(items, rng, index + at, now)) : [];
|
|
88
|
+
if (type === JsonType.object)
|
|
89
|
+
return properties ? generateObject(properties, rng, index, now, {}) : {};
|
|
90
|
+
return property.enum ? rng.pick(property.enum) : undefined;
|
|
91
|
+
}
|
|
92
|
+
function generateObject(properties, rng, index, now, generators) {
|
|
93
|
+
const row = {};
|
|
94
|
+
for (const property of properties) {
|
|
95
|
+
const own = generators?.[property.key];
|
|
96
|
+
if (own)
|
|
97
|
+
row[property.key] = own(rng, index);
|
|
98
|
+
else if (property.key === "id")
|
|
99
|
+
row.id = property.type === JsonType.string ? String(index + 1) : index + 1;
|
|
100
|
+
else if (property.required)
|
|
101
|
+
row[property.key] = generateValue(property, rng, index, now);
|
|
102
|
+
}
|
|
103
|
+
return row;
|
|
104
|
+
}
|
|
105
|
+
function wait(ms, signal) {
|
|
106
|
+
if (ms <= 0)
|
|
107
|
+
return signal.aborted ? Promise.reject(abortReason(signal)) : Promise.resolve();
|
|
108
|
+
return new Promise((resolve, reject) => {
|
|
109
|
+
const timer = setTimeout(() => {
|
|
110
|
+
signal.removeEventListener("abort", onAbort);
|
|
111
|
+
resolve();
|
|
112
|
+
}, ms);
|
|
113
|
+
const onAbort = () => {
|
|
114
|
+
clearTimeout(timer);
|
|
115
|
+
reject(abortReason(signal));
|
|
116
|
+
};
|
|
117
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
function abortReason(signal) {
|
|
121
|
+
return signal.reason instanceof Error ? signal.reason : new DOMException("The operation was aborted.", "AbortError");
|
|
122
|
+
}
|
|
123
|
+
function idKey(id) {
|
|
124
|
+
return String(id);
|
|
125
|
+
}
|
|
126
|
+
function schemaOf(resource) {
|
|
127
|
+
return isStandardSchema(resource) ? resource : resource.schema;
|
|
128
|
+
}
|
|
129
|
+
const deletedKey = "deleted";
|
|
130
|
+
export function memoryService(resource, options = {}) {
|
|
131
|
+
const schema = schemaOf(resource);
|
|
132
|
+
const now = options.now ?? fixedNow;
|
|
133
|
+
const properties = (options.introspect ?? zodIntrospect)(schema) ?? [];
|
|
134
|
+
const make = () => {
|
|
135
|
+
if (options.rows)
|
|
136
|
+
return options.rows.map((row) => structuredClone(row));
|
|
137
|
+
const rng = createRng(options.seed ?? 1);
|
|
138
|
+
const generators = options.generate;
|
|
139
|
+
const rows = [];
|
|
140
|
+
for (let index = 0; index < (options.count ?? 50); index++) {
|
|
141
|
+
// Workaround: a row generated from the schema's own JSON Schema is a T by construction; validating it would be async.
|
|
142
|
+
rows.push(assumeType(generateObject(properties, rng, index, now, generators)));
|
|
143
|
+
}
|
|
144
|
+
return rows;
|
|
145
|
+
};
|
|
146
|
+
let rows = make();
|
|
147
|
+
let deleted = new Set();
|
|
148
|
+
let versions = new Map();
|
|
149
|
+
// Spec: an id is taken before the row is validated, so creates that overlap never share one.
|
|
150
|
+
let issued = 0;
|
|
151
|
+
const jitter = createRng((options.seed ?? 1) + 1);
|
|
152
|
+
// Workaround: `Id` is the type of the rows' `id`, which TypeScript can't read back from a generic `T`.
|
|
153
|
+
const idOf = (row) => assumeType(valueAt(row, "id"));
|
|
154
|
+
const expand = (row) => (options.expand ? options.expand(structuredClone(row)) : structuredClone(row));
|
|
155
|
+
async function call(context) {
|
|
156
|
+
const latency = options.latency ?? 0;
|
|
157
|
+
const ms = isNumber(latency) ? latency : jitter.int(latency[0], latency[1]);
|
|
158
|
+
await wait(ms, context.signal);
|
|
159
|
+
if (options.failRate !== undefined && Math.random() < options.failRate)
|
|
160
|
+
throw new ServiceFailure(serviceError(ServiceErrorKind.server, "The in-memory service failed on purpose.", { status: 503 }));
|
|
161
|
+
}
|
|
162
|
+
const live = () => rows.filter((row) => !deleted.has(idKey(idOf(row))));
|
|
163
|
+
const find = (id) => rows.find((row) => idKey(idOf(row)) === idKey(id));
|
|
164
|
+
const notFound = (id) => new ServiceFailure(serviceError(ServiceErrorKind.notFound, `There is no record ${idKey(id)}.`, { status: 404 }));
|
|
165
|
+
async function checked(value) {
|
|
166
|
+
const result = await validate(schema, value);
|
|
167
|
+
if (!isValidationFailure(result))
|
|
168
|
+
return result.value;
|
|
169
|
+
const fields = result.issues.map((issue) => ({ path: issuePath(issue), message: issue.message }));
|
|
170
|
+
throw new ServiceFailure(serviceError(ServiceErrorKind.validation, fields[0]?.message ?? "The record isn't valid.", {
|
|
171
|
+
status: 422,
|
|
172
|
+
fields,
|
|
173
|
+
}));
|
|
174
|
+
}
|
|
175
|
+
function stamp(row, created) {
|
|
176
|
+
const at = new Date().toISOString();
|
|
177
|
+
for (const property of properties) {
|
|
178
|
+
if (property.format !== JsonFormat.dateTime)
|
|
179
|
+
continue;
|
|
180
|
+
if (property.key === "updatedAt" || (created && property.key === "createdAt"))
|
|
181
|
+
row[property.key] = at;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
function targetRows(target) {
|
|
185
|
+
if (target.kind === TargetKind.ids) {
|
|
186
|
+
const wanted = new Set(target.ids.map(idKey));
|
|
187
|
+
return rows.filter((row) => wanted.has(idKey(idOf(row))));
|
|
188
|
+
}
|
|
189
|
+
const except = new Set(target.except.map(idKey));
|
|
190
|
+
return live().filter((row) => matchesFilter(row, target.filter) && matchesSearch(row, target.search) && !except.has(idKey(idOf(row))));
|
|
191
|
+
}
|
|
192
|
+
const service = {
|
|
193
|
+
capabilities: {
|
|
194
|
+
position: PagePositionKind.page,
|
|
195
|
+
total: TotalKind.exact,
|
|
196
|
+
bulkByQuery: true,
|
|
197
|
+
...(options.versioned === true ? { versioned: true } : {}),
|
|
198
|
+
...(options.softDelete === true ? { restore: true } : {}),
|
|
199
|
+
},
|
|
200
|
+
rows: () => live().map((row) => structuredClone(row)),
|
|
201
|
+
reset() {
|
|
202
|
+
rows = make();
|
|
203
|
+
deleted = new Set();
|
|
204
|
+
issued = 0;
|
|
205
|
+
versions = new Map();
|
|
206
|
+
},
|
|
207
|
+
async list(query, context) {
|
|
208
|
+
await call(context);
|
|
209
|
+
const showDeleted = isRecord(query.filter) && query.filter[deletedKey] === true;
|
|
210
|
+
const pool = showDeleted ? rows.filter((row) => deleted.has(idKey(idOf(row)))) : live();
|
|
211
|
+
const { [deletedKey]: _deleted, ...filter } = query.filter;
|
|
212
|
+
const page = applyQuery(pool.map(expand), { ...query, filter });
|
|
213
|
+
return page;
|
|
214
|
+
},
|
|
215
|
+
async count(filter, context) {
|
|
216
|
+
await call(context);
|
|
217
|
+
return live().filter((row) => matchesFilter(expand(row), filter)).length;
|
|
218
|
+
},
|
|
219
|
+
async get(id, context) {
|
|
220
|
+
await call(context);
|
|
221
|
+
const row = find(id);
|
|
222
|
+
if (row === undefined || deleted.has(idKey(id)))
|
|
223
|
+
throw notFound(id);
|
|
224
|
+
return expand(row);
|
|
225
|
+
},
|
|
226
|
+
async getMany(ids, context) {
|
|
227
|
+
await call(context);
|
|
228
|
+
const wanted = new Set(ids.map(idKey));
|
|
229
|
+
return live()
|
|
230
|
+
.filter((row) => wanted.has(idKey(idOf(row))))
|
|
231
|
+
.map(expand);
|
|
232
|
+
},
|
|
233
|
+
async create(input, context) {
|
|
234
|
+
await call(context);
|
|
235
|
+
const numeric = rows.every((row) => isNumber(idOf(row)));
|
|
236
|
+
const next = Math.max(issued, rows.reduce((max, row) => Math.max(max, Number(idOf(row)) || 0), 0)) + 1;
|
|
237
|
+
issued = next;
|
|
238
|
+
const draft = { ...(isRecord(input) ? input : {}) };
|
|
239
|
+
if (draft.id === undefined)
|
|
240
|
+
draft.id = numeric ? next : String(next);
|
|
241
|
+
stamp(draft, true);
|
|
242
|
+
const row = await checked(draft);
|
|
243
|
+
rows = [...rows, row];
|
|
244
|
+
versions.set(idKey(idOf(row)), 1);
|
|
245
|
+
return expand(row);
|
|
246
|
+
},
|
|
247
|
+
async update(id, patch, context) {
|
|
248
|
+
await call(context);
|
|
249
|
+
const current = find(id);
|
|
250
|
+
if (current === undefined || deleted.has(idKey(id)))
|
|
251
|
+
throw notFound(id);
|
|
252
|
+
const version = versions.get(idKey(id)) ?? 1;
|
|
253
|
+
if (options.versioned === true && context.version !== undefined && context.version !== version)
|
|
254
|
+
throw new ServiceFailure(serviceError(ServiceErrorKind.conflict, "The record changed since it was read.", {
|
|
255
|
+
status: 409,
|
|
256
|
+
current: expand(current),
|
|
257
|
+
}));
|
|
258
|
+
const draft = {
|
|
259
|
+
...(isRecord(current) ? current : {}),
|
|
260
|
+
...(isRecord(patch) ? patch : {}),
|
|
261
|
+
};
|
|
262
|
+
draft.id = idOf(current);
|
|
263
|
+
stamp(draft, false);
|
|
264
|
+
const row = await checked(draft);
|
|
265
|
+
rows = rows.map((entry) => (idKey(idOf(entry)) === idKey(id) ? row : entry));
|
|
266
|
+
versions.set(idKey(id), version + 1);
|
|
267
|
+
return expand(row);
|
|
268
|
+
},
|
|
269
|
+
async remove(target, context) {
|
|
270
|
+
await call(context);
|
|
271
|
+
const gone = new Set(targetRows(target).map((row) => idKey(idOf(row))));
|
|
272
|
+
if (options.softDelete === true)
|
|
273
|
+
for (const id of gone)
|
|
274
|
+
deleted.add(id);
|
|
275
|
+
else
|
|
276
|
+
rows = rows.filter((row) => !gone.has(idKey(idOf(row))));
|
|
277
|
+
},
|
|
278
|
+
async restore(target, context) {
|
|
279
|
+
await call(context);
|
|
280
|
+
const back = target.kind === TargetKind.ids
|
|
281
|
+
? target.ids.map(idKey)
|
|
282
|
+
: rows
|
|
283
|
+
.filter((row) => deleted.has(idKey(idOf(row))) && matchesFilter(row, target.filter))
|
|
284
|
+
.map((row) => idKey(idOf(row)));
|
|
285
|
+
for (const id of back)
|
|
286
|
+
deleted.delete(id);
|
|
287
|
+
},
|
|
288
|
+
versionOf: (row) => options.versioned === true ? (versions.get(idKey(idOf(row))) ?? 1) : undefined,
|
|
289
|
+
};
|
|
290
|
+
return service;
|
|
291
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { PagePositionKind, TotalKind, VersionRead, VersionSend, type SortDirection } from "../core/constants.js";
|
|
2
|
+
import { type CallContext, type Page, type ResourceService } from "../core/contracts.js";
|
|
3
|
+
import { type ServiceError } from "../core/errors.js";
|
|
4
|
+
export declare const HttpMethod: {
|
|
5
|
+
readonly get: "GET";
|
|
6
|
+
readonly post: "POST";
|
|
7
|
+
readonly put: "PUT";
|
|
8
|
+
readonly patch: "PATCH";
|
|
9
|
+
readonly delete: "DELETE";
|
|
10
|
+
};
|
|
11
|
+
export type HttpMethod = (typeof HttpMethod)[keyof typeof HttpMethod];
|
|
12
|
+
export type RestServiceOptions<T, F> = {
|
|
13
|
+
fetch?: typeof fetch;
|
|
14
|
+
/** Headers for every call; `session.token()` becomes `Authorization: Bearer …` unless you set it. */
|
|
15
|
+
headers?: (context: CallContext) => Record<string, string> | Promise<Record<string, string>>;
|
|
16
|
+
position?: PagePositionKind;
|
|
17
|
+
/** The first page's number: 1 (default) or 0. */
|
|
18
|
+
pageBase?: 0 | 1;
|
|
19
|
+
/** Query parameter names; `include` carries the relations to embed (`?include=customer,tags`). */
|
|
20
|
+
params?: {
|
|
21
|
+
page?: string;
|
|
22
|
+
size?: string;
|
|
23
|
+
sort?: string;
|
|
24
|
+
search?: string;
|
|
25
|
+
cursor?: string;
|
|
26
|
+
before?: string;
|
|
27
|
+
include?: string;
|
|
28
|
+
};
|
|
29
|
+
/** Writes `Query.include` as parameters; `?include=a,b` by default, `false` sends nothing. */
|
|
30
|
+
includeParams?: false | ((include: readonly string[]) => Record<string, string>);
|
|
31
|
+
filterParams?: (filter: F) => Record<string, unknown>;
|
|
32
|
+
sortStyle?: (field: string, direction: SortDirection) => string;
|
|
33
|
+
read?: (raw: unknown, response: Response) => Page<T>;
|
|
34
|
+
/** `PATCH` (default) or `PUT` for updates. */
|
|
35
|
+
updateMethod?: typeof HttpMethod.patch | typeof HttpMethod.put;
|
|
36
|
+
version?: {
|
|
37
|
+
read: VersionRead;
|
|
38
|
+
send: VersionSend;
|
|
39
|
+
field?: string;
|
|
40
|
+
};
|
|
41
|
+
total?: TotalKind;
|
|
42
|
+
maxPageSize?: number;
|
|
43
|
+
/** Sends bulk removes and restores as `DELETE /x?…` with the filter, not one call per id. */
|
|
44
|
+
bulkByQuery?: boolean;
|
|
45
|
+
/**
|
|
46
|
+
* Reads many records in one request, `GET /x?ids=1&ids=2` (`param` renames it), so relations and comboboxes never
|
|
47
|
+
* read one id at a time; `size` is the most ids per request. `resourceHandler` serves it.
|
|
48
|
+
*/
|
|
49
|
+
batch?: boolean | {
|
|
50
|
+
param?: string;
|
|
51
|
+
size?: number;
|
|
52
|
+
};
|
|
53
|
+
/** Has `POST /x/restore` with `{ ids }`. */
|
|
54
|
+
restore?: boolean;
|
|
55
|
+
/** Adjusts every error before it's thrown, like a backend's own field paths. */
|
|
56
|
+
mapError?: (error: ServiceError) => ServiceError;
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* A REST backend: `GET /x?page=&size=&sort=`, `GET /x/:id`, `POST /x`, `PATCH /x/:id` and `DELETE /x/:id`. Errors
|
|
60
|
+
* (RFC 9457 `ProblemDetail`, Spring validation, JSON:API) become `ServiceError`s with their fields.
|
|
61
|
+
*/
|
|
62
|
+
export declare function restService<T, Id = string, F = Record<string, unknown>>(base: string, options?: RestServiceOptions<T, F>): ResourceService<T, Id, F>;
|
|
@@ -0,0 +1,220 @@
|
|
|
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
|
+
const fail = (error) => new ServiceFailure(options.mapError ? options.mapError(error) : error);
|
|
79
|
+
let response;
|
|
80
|
+
try {
|
|
81
|
+
response = await send(path, {
|
|
82
|
+
method,
|
|
83
|
+
headers,
|
|
84
|
+
signal: context.signal,
|
|
85
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
throw fail(toServiceError(error));
|
|
90
|
+
}
|
|
91
|
+
if (!response.ok)
|
|
92
|
+
throw fail((await problemDetailError(response)).error);
|
|
93
|
+
return response;
|
|
94
|
+
}
|
|
95
|
+
async function readRow(response) {
|
|
96
|
+
const row = await json(response);
|
|
97
|
+
const etag = response.headers.get("etag");
|
|
98
|
+
if (etag !== null && isRecord(row))
|
|
99
|
+
etags.set(row, etag);
|
|
100
|
+
// Workaround: the server answers with the row as JSON; nothing here can check it against `T`.
|
|
101
|
+
return assumeType(row);
|
|
102
|
+
}
|
|
103
|
+
function listParams(query) {
|
|
104
|
+
const params = new URLSearchParams();
|
|
105
|
+
const filter = options.filterParams
|
|
106
|
+
? options.filterParams(query.filter)
|
|
107
|
+
: isRecord(query.filter)
|
|
108
|
+
? query.filter
|
|
109
|
+
: {};
|
|
110
|
+
for (const [name, value] of Object.entries(filter))
|
|
111
|
+
appendValue(params, name, value);
|
|
112
|
+
if (query.search !== undefined && query.search !== "")
|
|
113
|
+
params.set(names.search, query.search);
|
|
114
|
+
for (const spec of query.sort)
|
|
115
|
+
params.append(names.sort, options.sortStyle ? options.sortStyle(spec.field, spec.direction) : `${spec.field},${spec.direction}`);
|
|
116
|
+
if (query.include && query.include.length > 0 && options.includeParams !== false) {
|
|
117
|
+
const written = options.includeParams
|
|
118
|
+
? options.includeParams(query.include)
|
|
119
|
+
: { [names.include]: query.include.join(",") };
|
|
120
|
+
for (const [name, value] of Object.entries(written))
|
|
121
|
+
params.set(name, value);
|
|
122
|
+
}
|
|
123
|
+
params.set(names.size, String(query.size));
|
|
124
|
+
if (isPagePosition(query.position))
|
|
125
|
+
params.set(names.page, String(query.position.page - 1 + pageBase));
|
|
126
|
+
else if (query.position.cursor !== null)
|
|
127
|
+
params.set(query.position.direction === CursorDirection.backward ? names.before : names.cursor, query.position.cursor);
|
|
128
|
+
return params;
|
|
129
|
+
}
|
|
130
|
+
function targetParams(target) {
|
|
131
|
+
if (target.kind === TargetKind.ids)
|
|
132
|
+
return undefined;
|
|
133
|
+
const params = new URLSearchParams();
|
|
134
|
+
const filter = options.filterParams
|
|
135
|
+
? options.filterParams(target.filter)
|
|
136
|
+
: isRecord(target.filter)
|
|
137
|
+
? target.filter
|
|
138
|
+
: {};
|
|
139
|
+
for (const [name, value] of Object.entries(filter))
|
|
140
|
+
appendValue(params, name, value);
|
|
141
|
+
if (target.search !== undefined)
|
|
142
|
+
params.set(names.search, target.search);
|
|
143
|
+
for (const id of target.except)
|
|
144
|
+
params.append("except", String(id));
|
|
145
|
+
return params;
|
|
146
|
+
}
|
|
147
|
+
const versionOf = (row) => {
|
|
148
|
+
if (!options.version)
|
|
149
|
+
return undefined;
|
|
150
|
+
if (options.version.read === VersionRead.etag)
|
|
151
|
+
return isRecord(row) ? etags.get(row) : undefined;
|
|
152
|
+
const value = valueAt(row, options.version.field ?? "version");
|
|
153
|
+
return isString(value) || isNumber(value) ? value : undefined;
|
|
154
|
+
};
|
|
155
|
+
const service = {
|
|
156
|
+
capabilities: {
|
|
157
|
+
position: options.position ?? PagePositionKind.page,
|
|
158
|
+
total: options.total ?? TotalKind.exact,
|
|
159
|
+
...(options.maxPageSize === undefined ? {} : { maxPageSize: options.maxPageSize }),
|
|
160
|
+
...(options.version ? { versioned: true } : {}),
|
|
161
|
+
...(options.bulkByQuery === true ? { bulkByQuery: true } : {}),
|
|
162
|
+
...(options.restore === true ? { restore: true } : {}),
|
|
163
|
+
...(isRecord(options.batch) && options.batch.size !== undefined ? { batchSize: options.batch.size } : {}),
|
|
164
|
+
},
|
|
165
|
+
async list(query, context) {
|
|
166
|
+
const response = await call(HttpMethod.get, url("", listParams(query)), context);
|
|
167
|
+
const raw = await json(response);
|
|
168
|
+
return options.read ? options.read(raw, response) : defaultRead(raw);
|
|
169
|
+
},
|
|
170
|
+
async get(id, context) {
|
|
171
|
+
return readRow(await call(HttpMethod.get, url(itemPath(id)), context));
|
|
172
|
+
},
|
|
173
|
+
...(options.batch === undefined || options.batch === false
|
|
174
|
+
? {}
|
|
175
|
+
: {
|
|
176
|
+
async getMany(ids, context) {
|
|
177
|
+
const params = new URLSearchParams();
|
|
178
|
+
const name = isRecord(options.batch) ? (options.batch.param ?? "ids") : "ids";
|
|
179
|
+
for (const id of ids)
|
|
180
|
+
params.append(name, String(id));
|
|
181
|
+
const raw = await json(await call(HttpMethod.get, url("", params), context));
|
|
182
|
+
const page = options.read ? undefined : defaultRead(raw);
|
|
183
|
+
// Workaround: the server answers with the rows as JSON; nothing here can check them against `T`.
|
|
184
|
+
return page ? page.items : assumeType(Array.isArray(raw) ? raw : []);
|
|
185
|
+
},
|
|
186
|
+
}),
|
|
187
|
+
async create(input, context) {
|
|
188
|
+
return readRow(await call(HttpMethod.post, url(), context, input));
|
|
189
|
+
},
|
|
190
|
+
async update(id, patch, context) {
|
|
191
|
+
const version = context.version;
|
|
192
|
+
const headers = {};
|
|
193
|
+
let body = patch;
|
|
194
|
+
if (options.version && version !== undefined) {
|
|
195
|
+
if (options.version.send === VersionSend.ifMatch)
|
|
196
|
+
headers["if-match"] = String(version);
|
|
197
|
+
else
|
|
198
|
+
body = { ...(isRecord(patch) ? patch : {}), [options.version.field ?? "version"]: version };
|
|
199
|
+
}
|
|
200
|
+
return readRow(await call(options.updateMethod ?? HttpMethod.patch, url(itemPath(id)), context, body, headers));
|
|
201
|
+
},
|
|
202
|
+
async remove(target, context) {
|
|
203
|
+
if (target.kind === TargetKind.ids) {
|
|
204
|
+
await Promise.all(target.ids.map((id) => call(HttpMethod.delete, url(itemPath(id)), context)));
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
if (options.bulkByQuery !== true)
|
|
208
|
+
throw new ServiceFailure(serviceError(ServiceErrorKind.validation, "This service removes by id only."));
|
|
209
|
+
await call(HttpMethod.delete, url("", targetParams(target)), context);
|
|
210
|
+
},
|
|
211
|
+
async restore(target, context) {
|
|
212
|
+
if (target.kind === TargetKind.ids)
|
|
213
|
+
await call(HttpMethod.post, url("/restore"), context, { ids: target.ids });
|
|
214
|
+
else
|
|
215
|
+
await call(HttpMethod.post, url("/restore", targetParams(target)), context);
|
|
216
|
+
},
|
|
217
|
+
versionOf,
|
|
218
|
+
};
|
|
219
|
+
return service;
|
|
220
|
+
}
|
|
@@ -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>;
|