@eskais/app-sdk 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -11
- package/dist/action/action.d.ts +69 -10
- package/dist/action/action.js +147 -29
- package/dist/action/bulk.d.ts +24 -0
- package/dist/action/bulk.js +24 -0
- package/dist/core/constants.d.ts +57 -0
- package/dist/core/constants.js +31 -0
- package/dist/core/contracts.d.ts +7 -0
- package/dist/core/data-labels.d.ts +14 -0
- package/dist/core/data-labels.js +40 -0
- package/dist/core/errors.d.ts +11 -5
- package/dist/core/errors.js +52 -9
- package/dist/dialogs/dialogs.d.ts +75 -0
- package/dist/dialogs/dialogs.js +66 -0
- package/dist/errors/adapters.d.ts +21 -0
- package/dist/errors/adapters.js +81 -0
- package/dist/errors/define-errors.d.ts +88 -0
- package/dist/errors/define-errors.js +168 -0
- package/dist/errors/idempotency.d.ts +2 -0
- package/dist/errors/idempotency.js +13 -0
- package/dist/i18n/adapters.d.ts +53 -0
- package/dist/i18n/adapters.js +56 -0
- package/dist/i18n/format.d.ts +10 -0
- package/dist/i18n/format.js +273 -0
- package/dist/i18n/labels.d.ts +10 -0
- package/dist/i18n/labels.js +227 -0
- package/dist/i18n/locale.d.ts +73 -0
- package/dist/i18n/locale.js +74 -0
- package/dist/i18n/messages.d.ts +93 -0
- package/dist/i18n/messages.js +16 -0
- package/dist/import/import.d.ts +4 -2
- package/dist/import/import.js +7 -4
- package/dist/index.d.ts +18 -3
- package/dist/index.js +17 -2
- package/dist/navigation/nav.d.ts +14 -5
- package/dist/navigation/nav.js +37 -14
- package/dist/next/server/index.d.ts +2 -1
- package/dist/next/server/index.js +2 -1
- package/dist/next/server/page.d.ts +8 -2
- package/dist/next/server/page.js +14 -7
- package/dist/next/server/session.d.ts +13 -0
- package/dist/next/server/session.js +13 -0
- package/dist/permissions/permissions.d.ts +134 -0
- package/dist/permissions/permissions.js +121 -0
- package/dist/react/data-layer.d.ts +42 -5
- package/dist/react/data-layer.js +49 -4
- package/dist/react/hooks/use-action-dialog.d.ts +25 -0
- package/dist/react/hooks/use-action-dialog.js +31 -0
- package/dist/react/hooks/use-action.d.ts +30 -5
- package/dist/react/hooks/use-action.js +85 -27
- package/dist/react/hooks/use-bulk-action.d.ts +20 -0
- package/dist/react/hooks/use-bulk-action.js +24 -0
- package/dist/react/hooks/use-dialogs.d.ts +14 -0
- package/dist/react/hooks/use-dialogs.js +20 -0
- package/dist/react/hooks/use-nav.js +3 -2
- package/dist/react/hooks/use-new-rows.d.ts +22 -0
- package/dist/react/hooks/use-new-rows.js +24 -0
- package/dist/react/hooks/use-permissions.d.ts +13 -0
- package/dist/react/hooks/use-permissions.js +19 -0
- package/dist/react/hooks/use-reauthenticate.d.ts +6 -0
- package/dist/react/hooks/use-reauthenticate.js +11 -0
- package/dist/react/hooks/use-resource.d.ts +28 -5
- package/dist/react/hooks/use-resource.js +63 -26
- package/dist/react/index.d.ts +11 -4
- package/dist/react/index.js +11 -4
- package/dist/react/keys.d.ts +9 -0
- package/dist/react/keys.js +4 -0
- package/dist/react/new-rows.d.ts +22 -0
- package/dist/react/new-rows.js +72 -0
- package/dist/refresh/new-rows.d.ts +13 -0
- package/dist/refresh/new-rows.js +18 -0
- package/dist/resource/resource-relations.d.ts +6 -3
- package/dist/resource/resource-relations.js +26 -13
- package/dist/resource/resource-schema.d.ts +1 -1
- package/dist/resource/resource-schema.js +1 -1
- package/dist/resource/resource-texts.d.ts +18 -0
- package/dist/resource/resource-texts.js +13 -0
- package/dist/resource/resource-types.d.ts +169 -30
- package/dist/resource/resource-words.d.ts +25 -0
- package/dist/resource/resource-words.js +221 -0
- package/dist/resource/resource.d.ts +6 -2
- package/dist/resource/resource.js +99 -173
- package/dist/services/read-only-service.d.ts +18 -0
- package/dist/services/read-only-service.js +25 -0
- package/dist/services/rest-service.d.ts +4 -1
- package/dist/services/rest-service.js +2 -0
- package/dist/view/view-types.d.ts +4 -2
- package/locales/en.json +193 -0
- package/locales/es.json +193 -0
- package/package.json +5 -2
package/README.md
CHANGED
|
@@ -13,13 +13,13 @@ The blocks pin the version of this package they were built with, and `shadcn add
|
|
|
13
13
|
|
|
14
14
|
## Entries
|
|
15
15
|
|
|
16
|
-
| Entry | What it has
|
|
17
|
-
| ----------------------------- |
|
|
18
|
-
| `@eskais/app-sdk` | No React and no dependencies: `defineResource`, `defineAction`, `defineView`, `defineNav`, `defineDraft`, `defineImport`, relations (`belongsTo`, `hasMany`, `manyToMany`, `embeds`, `resolveRelations`), the `ResourceService` contract with `memoryService`, `restService`, `springService` and `fromPageSource`, sessions (`createSession`, `fromCasl`, `betterAuthSession`), routers, shortcuts, errors and labels |
|
|
19
|
-
| `@eskais/app-sdk/react` | `DataLayer` and the hooks (`useResourceList`, `useResource`, `useResourceMutations`, `useAction`, `useView`, `useNav`, `useDraft`, `useBetterAuthSession`…) on TanStack Query
|
|
20
|
-
| `@eskais/app-sdk/next` | The Next.js App Router in the browser: `useNextRouter`, `ScreenHydration` and the path helpers (`navScreen`, `pathOfParams`)
|
|
21
|
-
| `@eskais/app-sdk/next/server` | Server components and route handlers: `navPage` and `resourcePage` (a catch-all page with its query prefetched and hydrated, `generateMetadata` and `notFound()`), `nextSession` and `resourceHandler`
|
|
22
|
-
| `app-sdk` (bin) | `app-sdk routes`: TanStack Router file routes for each resource
|
|
16
|
+
| Entry | What it has |
|
|
17
|
+
| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
18
|
+
| `@eskais/app-sdk` | No React and no dependencies: `defineResource`, `defineAction`, `defineBulkAction`, `defineErrors` (error reasons, feedback, retries, re-authentication and idempotency keys), `definePermissions`, `defineView`, `defineNav`, `defineDraft`, `defineImport`, relations (`belongsTo`, `hasMany`, `manyToMany`, `embeds`, `resolveRelations`), the `ResourceService` contract with `memoryService`, `restService`, `springService` and `fromPageSource`, sessions (`createSession`, `fromCasl`, `betterAuthSession`), routers, shortcuts, errors and labels |
|
|
19
|
+
| `@eskais/app-sdk/react` | `DataLayer` and the hooks (`useResourceList`, `useResource`, `useResourceMutations`, `useAction`, `useActionDialog`, `useBulkAction`, `useReauthenticate`, `useView`, `useNav`, `useDraft`, `usePermission`, `usePermissionSession`, `useDialogs`, `useBetterAuthSession`…) on TanStack Query |
|
|
20
|
+
| `@eskais/app-sdk/next` | The Next.js App Router in the browser: `useNextRouter`, `ScreenHydration` and the path helpers (`navScreen`, `pathOfParams`) |
|
|
21
|
+
| `@eskais/app-sdk/next/server` | Server components and route handlers: `navPage` and `resourcePage` (a catch-all page with its query prefetched and hydrated, `generateMetadata` and `notFound()`), `nextSession`, `nextPermissionSession` and `resourceHandler` |
|
|
22
|
+
| `app-sdk` (bin) | `app-sdk routes`: TanStack Router file routes for each resource |
|
|
23
23
|
|
|
24
24
|
React 19, `@tanstack/react-query` 5, Zod 4, `@tanstack/react-router` 1 and Next.js 15 or 16 are optional peers: the core needs none of them.
|
|
25
25
|
|
|
@@ -38,18 +38,24 @@ export const generateMetadata = page.generateMetadata
|
|
|
38
38
|
The guide's [Next.js section](https://ui.eskais.com/docs/guides/app-sdk/#nextjs) has the layout, the session and the route handlers.
|
|
39
39
|
|
|
40
40
|
```tsx
|
|
41
|
-
import
|
|
41
|
+
import en from "@eskais/app-sdk/locales/en.json"
|
|
42
|
+
import { defineLocale, defineResource, hashRouter, memoryService } from "@eskais/app-sdk"
|
|
42
43
|
import { DataLayer } from "@eskais/app-sdk/react"
|
|
43
44
|
import { z } from "zod"
|
|
44
45
|
|
|
45
46
|
import { ResourcePage } from "@/components/ui/resource-page"
|
|
46
47
|
import { createDataClient } from "@/components/ui/server-data"
|
|
47
48
|
|
|
48
|
-
const customer = z.object({ id: z.number(), name: z.string()
|
|
49
|
+
const customer = z.object({ id: z.number(), name: z.string() })
|
|
50
|
+
|
|
51
|
+
// The shipped catalog, with your resources by their key: { resources: { customers: { one, other, fields } } }
|
|
52
|
+
const locale = defineLocale("en", {
|
|
53
|
+
base: en,
|
|
54
|
+
messages: { resources: { customers: { one: "Customer", other: "Customers", fields: { name: "Name" } } } },
|
|
55
|
+
})
|
|
49
56
|
|
|
50
57
|
const customers = defineResource<z.infer<typeof customer>>()({
|
|
51
58
|
key: "customers",
|
|
52
|
-
label: { one: "Customer", other: "Customers" },
|
|
53
59
|
schema: customer,
|
|
54
60
|
service: memoryService(customer, { seed: 7, count: 40 }),
|
|
55
61
|
title: (c) => c.name,
|
|
@@ -57,7 +63,7 @@ const customers = defineResource<z.infer<typeof customer>>()({
|
|
|
57
63
|
|
|
58
64
|
export function App() {
|
|
59
65
|
return (
|
|
60
|
-
<DataLayer client={createDataClient()} router={hashRouter()}
|
|
66
|
+
<DataLayer client={createDataClient()} router={hashRouter()} locale={locale}>
|
|
61
67
|
<ResourcePage resource={customers} />
|
|
62
68
|
</DataLayer>
|
|
63
69
|
)
|
package/dist/action/action.d.ts
CHANGED
|
@@ -1,10 +1,14 @@
|
|
|
1
|
-
import { ActionScope, ActionTargetKind, Concurrency } from "../core/constants.js";
|
|
1
|
+
import { ActionScope, ActionTargetKind, Concurrency, Feedback, Idempotency } from "../core/constants.js";
|
|
2
2
|
import type { CallContext } from "../core/contracts.js";
|
|
3
3
|
import { type ServiceError } from "../core/errors.js";
|
|
4
|
+
import type { Errors } from "../errors/define-errors.js";
|
|
5
|
+
import { type BulkResult } from "./bulk.js";
|
|
4
6
|
import { type Allowed, type Refusal } from "../core/refusal.js";
|
|
5
7
|
import type { AnyResource, ToneName } from "../resource/resource.js";
|
|
6
8
|
import { type StandardSchema } from "../resource/schema.js";
|
|
9
|
+
import type { RegisteredOperation } from "../permissions/permissions.js";
|
|
7
10
|
import type { Session } from "../session/session.js";
|
|
11
|
+
import { type Locale, type MessageRef, type Text, type TextRefusal } from "../i18n/locale.js";
|
|
8
12
|
export type ActionTarget<T> = {
|
|
9
13
|
kind: typeof ActionTargetKind.none;
|
|
10
14
|
} | {
|
|
@@ -25,37 +29,87 @@ export type ActionConfirm = {
|
|
|
25
29
|
tone?: ToneName;
|
|
26
30
|
confirmLabel?: string;
|
|
27
31
|
};
|
|
32
|
+
export type ActionConfirmDef = {
|
|
33
|
+
title?: Text;
|
|
34
|
+
description?: Text;
|
|
35
|
+
tone?: ToneName;
|
|
36
|
+
confirmLabel?: Text;
|
|
37
|
+
};
|
|
38
|
+
/** A toast's text: a string, a message (`msg("orders.cancelled")`, given `{ count }`), or a function of the result. */
|
|
39
|
+
export type ActionMessage<Value extends unknown[]> = string | MessageRef | ((...values: Value) => string) | false;
|
|
28
40
|
export type ActionOptions<T, I, R> = {
|
|
29
41
|
id: string;
|
|
30
|
-
|
|
42
|
+
/**
|
|
43
|
+
* By default `resources.<resource>.actions.<id>` in the locale, the id after `<resource>.`:
|
|
44
|
+
* `orders.cancel` reads `resources.orders.actions.cancel`.
|
|
45
|
+
*/
|
|
46
|
+
label?: Text;
|
|
31
47
|
icon?: unknown;
|
|
32
|
-
description?:
|
|
48
|
+
description?: Text;
|
|
33
49
|
resource?: AnyResource;
|
|
34
50
|
/** `ActionScope.row` by default when there's a `resource`, `ActionScope.global` otherwise. */
|
|
35
51
|
scope?: ActionScope | readonly ActionScope[];
|
|
36
52
|
input?: StandardSchema<unknown, I>;
|
|
37
|
-
confirm?: boolean |
|
|
38
|
-
|
|
53
|
+
confirm?: boolean | ActionConfirmDef;
|
|
54
|
+
/** Its reason may be a message, worded in the `DataLayer`'s locale. */
|
|
55
|
+
can?: (row?: T) => boolean | Refusal | TextRefusal;
|
|
56
|
+
/**
|
|
57
|
+
* The operation it needs from `definePermissions` (`Op.approve`): the session is asked for it instead of the
|
|
58
|
+
* action's id. Typed by the registered permissions' operations.
|
|
59
|
+
*/
|
|
60
|
+
requires?: RegisteredOperation;
|
|
39
61
|
run: (target: ActionTarget<T>, input: I, context: CallContext) => Promise<R>;
|
|
40
62
|
optimistic?: (row: T, input: I) => T;
|
|
41
63
|
undo?: (target: ActionTarget<T>, result: R, context: CallContext) => Promise<void>;
|
|
42
|
-
/**
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
64
|
+
/**
|
|
65
|
+
* Resources whose queries refresh after it runs (or is undone), besides its own: a function when they're defined
|
|
66
|
+
* after it.
|
|
67
|
+
*/
|
|
68
|
+
invalidates?: readonly AnyResource[] | (() => readonly AnyResource[]);
|
|
69
|
+
success?: ActionMessage<[result: R, count: number]>;
|
|
70
|
+
failure?: ActionMessage<[error: ServiceError]>;
|
|
46
71
|
shortcut?: string;
|
|
47
72
|
/** What a second run does while one is going: `block` refuses it, `switch` aborts the first, `queue` waits. */
|
|
48
73
|
concurrency?: Concurrency;
|
|
74
|
+
/**
|
|
75
|
+
* Whether it may run again after a failure: never by default; `Idempotency.idempotent` retries it, and
|
|
76
|
+
* `Idempotency.key` sends one `idempotencyKey` in its `CallContext`, the same on every retry of a submit.
|
|
77
|
+
*/
|
|
78
|
+
idempotency?: Idempotency;
|
|
79
|
+
/** Where its outcome shows, over the `defineErrors` defaults: `{ success: Feedback.silent }`. */
|
|
80
|
+
feedback?: {
|
|
81
|
+
success?: Feedback;
|
|
82
|
+
error?: Feedback;
|
|
83
|
+
};
|
|
84
|
+
};
|
|
85
|
+
/** A bulk action: `each` changes one row, and the action reports per row what changed and what didn't. */
|
|
86
|
+
export type BulkActionOptions<T, I> = Omit<ActionOptions<T, I, BulkResult<T>>, "run"> & {
|
|
87
|
+
each: (row: T, input: I, context: CallContext) => Promise<unknown>;
|
|
88
|
+
/** How many rows run at once; 4 by default. */
|
|
89
|
+
parallel?: number;
|
|
49
90
|
};
|
|
50
91
|
export type AnyAction = Action<any, any, any>;
|
|
51
92
|
export type ActionRunOptions = {
|
|
52
93
|
session?: Session | undefined;
|
|
53
94
|
signal?: AbortSignal | undefined;
|
|
95
|
+
/** The app's policy, which retries, re-authenticates and classifies; the `DataLayer` passes its own. */
|
|
96
|
+
errors?: Errors | undefined;
|
|
97
|
+
/** The submit's idempotency key, kept by a dialog or a bulk retry; a new one per run otherwise. */
|
|
98
|
+
idempotencyKey?: string | undefined;
|
|
54
99
|
};
|
|
55
100
|
export type Action<T = unknown, I = void, R = unknown> = {
|
|
56
101
|
readonly id: string;
|
|
57
102
|
readonly options: ActionOptions<T, I, R>;
|
|
58
103
|
readonly label: string;
|
|
104
|
+
readonly description: string | undefined;
|
|
105
|
+
/** The locale its texts are in. */
|
|
106
|
+
readonly locale: Locale | undefined;
|
|
107
|
+
/** The same action with its texts in `locale`. Cached. */
|
|
108
|
+
in(locale: Locale | undefined): Action<T, I, R>;
|
|
109
|
+
/** Its resource and `invalidates`: what refreshes after it runs. */
|
|
110
|
+
refreshes(): readonly AnyResource[];
|
|
111
|
+
successText(result: R, count: number): string | undefined;
|
|
112
|
+
failureText(error: ServiceError): string | undefined;
|
|
59
113
|
readonly scopes: readonly ActionScope[];
|
|
60
114
|
readonly destructive: boolean;
|
|
61
115
|
readonly confirm: ActionConfirm | undefined;
|
|
@@ -67,8 +121,13 @@ export type Action<T = unknown, I = void, R = unknown> = {
|
|
|
67
121
|
rowsOf(target: ActionTarget<T>): readonly T[];
|
|
68
122
|
};
|
|
69
123
|
export declare function defineAction<T = unknown, I = void, R = unknown>(options: ActionOptions<T, I, R>): Action<T, I, R>;
|
|
124
|
+
/**
|
|
125
|
+
* An action over many rows that reports each one: it resolves with the rows it changed and the ones it didn't, with
|
|
126
|
+
* their reasons, instead of failing whole. Run it again on `failedTarget(result)` with `result.idempotencyKey`.
|
|
127
|
+
*/
|
|
128
|
+
export declare function defineBulkAction<T = unknown, I = void>(options: BulkActionOptions<T, I>): Action<T, I, BulkResult<T>>;
|
|
70
129
|
export declare function isAction(value: unknown): value is AnyAction;
|
|
71
130
|
export declare function actionsOf(resource: {
|
|
72
131
|
actions(): readonly unknown[];
|
|
73
132
|
}): AnyAction[];
|
|
74
|
-
export declare function messageOf<Value extends unknown[]>(option:
|
|
133
|
+
export declare function messageOf<Value extends unknown[]>(option: ActionMessage<Value> | undefined, ...values: Value): string | undefined;
|
package/dist/action/action.js
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import { assumeType } from "../core/assume.js";
|
|
2
|
-
import { ActionScope, ActionTargetKind, Concurrency, ServiceErrorKind } from "../core/constants.js";
|
|
3
|
-
import { ServiceFailure, serviceError } from "../core/errors.js";
|
|
2
|
+
import { ActionScope, ActionTargetKind, Concurrency, Feedback, Idempotency, Operation, ServiceErrorKind, } from "../core/constants.js";
|
|
3
|
+
import { reasonOf, ServiceFailure, serviceError, toServiceError } from "../core/errors.js";
|
|
4
|
+
import { idempotencyKey } from "../errors/idempotency.js";
|
|
5
|
+
import { mapLimited } from "./bulk.js";
|
|
4
6
|
import { isFunction, isRecord, isString } from "../core/guards.js";
|
|
5
7
|
import { firstRefusal, toAllowed } from "../core/refusal.js";
|
|
6
8
|
import { isValidationFailure, issuePath, validate } from "../resource/schema.js";
|
|
9
|
+
import { isMessageRef, lookup, refusalIn, resolveText, } from "../i18n/locale.js";
|
|
7
10
|
function scopesOf(scope, hasResource) {
|
|
8
11
|
if (scope === undefined)
|
|
9
12
|
return [hasResource ? ActionScope.row : ActionScope.global];
|
|
@@ -14,19 +17,90 @@ function linked(signal, own) {
|
|
|
14
17
|
return own.signal;
|
|
15
18
|
return AbortSignal.any([signal, own.signal]);
|
|
16
19
|
}
|
|
20
|
+
function shortId(id, resource) {
|
|
21
|
+
return resource !== undefined && id.startsWith(`${resource}.`) ? id.slice(resource.length + 1) : id;
|
|
22
|
+
}
|
|
23
|
+
function textOf(message, locale, values, ...args) {
|
|
24
|
+
if (message === undefined || message === false)
|
|
25
|
+
return undefined;
|
|
26
|
+
if (isMessageRef(message))
|
|
27
|
+
return locale ? locale.t(message.key, { ...values, ...message.values }) : message.key;
|
|
28
|
+
if (isString(message))
|
|
29
|
+
return message;
|
|
30
|
+
return message(...args);
|
|
31
|
+
}
|
|
32
|
+
function classified(error, errors) {
|
|
33
|
+
if (errors)
|
|
34
|
+
return errors.classify(error);
|
|
35
|
+
const normalized = toServiceError(error);
|
|
36
|
+
return { ...normalized, reason: reasonOf(normalized) };
|
|
37
|
+
}
|
|
38
|
+
function targetRows(target) {
|
|
39
|
+
if (target.kind === ActionTargetKind.row)
|
|
40
|
+
return [target.row];
|
|
41
|
+
if (target.kind === ActionTargetKind.rows)
|
|
42
|
+
return target.rows;
|
|
43
|
+
return [];
|
|
44
|
+
}
|
|
45
|
+
function invoke(call, run, signal, idempotency, key) {
|
|
46
|
+
if (run.errors)
|
|
47
|
+
return run.errors.run(call, {
|
|
48
|
+
operation: Operation.mutation,
|
|
49
|
+
signal,
|
|
50
|
+
session: run.session,
|
|
51
|
+
idempotency,
|
|
52
|
+
idempotencyKey: key,
|
|
53
|
+
});
|
|
54
|
+
return call({ signal, session: run.session, ...(key === undefined ? {} : { idempotencyKey: key }) });
|
|
55
|
+
}
|
|
56
|
+
const submitKey = (run, idempotency) => run.idempotencyKey ?? (idempotency === Idempotency.key ? idempotencyKey() : undefined);
|
|
57
|
+
function runOnce(options) {
|
|
58
|
+
return (target, input, run, signal) => invoke((context) => options.run(target, input, context), run, signal, options.idempotency, submitKey(run, options.idempotency));
|
|
59
|
+
}
|
|
60
|
+
function runEach(options) {
|
|
61
|
+
const { resource, idempotency } = options;
|
|
62
|
+
const rowKey = (row, index) => (resource ? resource.idKey(resource.idOf(row)) : String(index));
|
|
63
|
+
return async (target, input, run, signal) => {
|
|
64
|
+
if (target.kind === ActionTargetKind.query)
|
|
65
|
+
throw new ServiceFailure(serviceError(ServiceErrorKind.validation, `${options.id} runs on listed rows only.`));
|
|
66
|
+
const key = submitKey(run, idempotency);
|
|
67
|
+
const outcomes = await mapLimited(targetRows(target), options.parallel ?? 4, async (row, index) => {
|
|
68
|
+
try {
|
|
69
|
+
const rowKeyed = key === undefined ? undefined : `${key}:${rowKey(row, index)}`;
|
|
70
|
+
await invoke((context) => options.each(row, input, context), run, signal, idempotency, rowKeyed);
|
|
71
|
+
return { row };
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
if (signal.aborted)
|
|
75
|
+
throw error;
|
|
76
|
+
return { row, error: classified(error, run.errors) };
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
const failed = outcomes.filter((outcome) => outcome.error !== undefined);
|
|
80
|
+
const succeeded = outcomes.filter((outcome) => outcome.error === undefined).map((outcome) => outcome.row);
|
|
81
|
+
return { succeeded, failed, ...(key === undefined ? {} : { idempotencyKey: key }) };
|
|
82
|
+
};
|
|
83
|
+
}
|
|
17
84
|
export function defineAction(options) {
|
|
85
|
+
return createAction(options, runOnce(options));
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* An action over many rows that reports each one: it resolves with the rows it changed and the ones it didn't, with
|
|
89
|
+
* their reasons, instead of failing whole. Run it again on `failedTarget(result)` with `result.idempotencyKey`.
|
|
90
|
+
*/
|
|
91
|
+
export function defineBulkAction(options) {
|
|
92
|
+
const { each: _each, parallel: _parallel, ...rest } = options;
|
|
93
|
+
const unused = () => Promise.reject(new TypeError(`${options.id} runs row by row.`));
|
|
94
|
+
return createAction({ scope: [ActionScope.row, ActionScope.bulk], ...rest, run: unused }, runEach(options));
|
|
95
|
+
}
|
|
96
|
+
function createAction(options, runner) {
|
|
18
97
|
const scopes = scopesOf(options.scope, options.resource !== undefined);
|
|
19
|
-
const
|
|
98
|
+
const declared = options.confirm === true ? {} : options.confirm === false ? undefined : options.confirm;
|
|
99
|
+
const resourceKey = options.resource?.key;
|
|
20
100
|
const concurrency = options.concurrency ?? Concurrency.block;
|
|
21
101
|
let inFlight;
|
|
22
102
|
let tail = Promise.resolve();
|
|
23
|
-
const rowsOf = (target) =>
|
|
24
|
-
if (target.kind === ActionTargetKind.row)
|
|
25
|
-
return [target.row];
|
|
26
|
-
if (target.kind === ActionTargetKind.rows)
|
|
27
|
-
return target.rows;
|
|
28
|
-
return [];
|
|
29
|
-
};
|
|
103
|
+
const rowsOf = (target) => targetRows(target);
|
|
30
104
|
async function parseInput(input) {
|
|
31
105
|
if (!options.input) {
|
|
32
106
|
// Workaround: an action without an input schema takes no input; `I` is `void` for it.
|
|
@@ -41,7 +115,8 @@ export function defineAction(options) {
|
|
|
41
115
|
}
|
|
42
116
|
function start(target, input, run) {
|
|
43
117
|
const controller = new AbortController();
|
|
44
|
-
const
|
|
118
|
+
const signal = linked(run.signal, controller);
|
|
119
|
+
const done = runner(target, input, run, signal);
|
|
45
120
|
const entry = { controller, done };
|
|
46
121
|
inFlight = entry;
|
|
47
122
|
const clear = () => {
|
|
@@ -51,24 +126,68 @@ export function defineAction(options) {
|
|
|
51
126
|
done.then(clear, clear);
|
|
52
127
|
return done;
|
|
53
128
|
}
|
|
54
|
-
|
|
129
|
+
const refreshes = () => {
|
|
130
|
+
const extra = isFunction(options.invalidates) ? options.invalidates() : (options.invalidates ?? []);
|
|
131
|
+
return [...new Set([...(options.resource ? [options.resource] : []), ...extra])];
|
|
132
|
+
};
|
|
133
|
+
const localized = new WeakMap();
|
|
134
|
+
const sources = new WeakMap();
|
|
135
|
+
function texts(locale) {
|
|
136
|
+
const text = (value) => resolveText(value, locale);
|
|
137
|
+
const confirm = declared
|
|
138
|
+
? {
|
|
139
|
+
...(declared.title === undefined ? {} : { title: resolveText(declared.title, locale) }),
|
|
140
|
+
...(declared.description === undefined ? {} : { description: resolveText(declared.description, locale) }),
|
|
141
|
+
...(declared.tone === undefined ? {} : { tone: declared.tone }),
|
|
142
|
+
...(declared.confirmLabel === undefined ? {} : { confirmLabel: resolveText(declared.confirmLabel, locale) }),
|
|
143
|
+
}
|
|
144
|
+
: undefined;
|
|
145
|
+
return {
|
|
146
|
+
label: text(options.label) ??
|
|
147
|
+
(resourceKey === undefined
|
|
148
|
+
? undefined
|
|
149
|
+
: lookup(locale, `resources.${resourceKey}.actions.${shortId(options.id, resourceKey)}`)) ??
|
|
150
|
+
options.id,
|
|
151
|
+
description: text(options.description),
|
|
152
|
+
confirm,
|
|
153
|
+
locale,
|
|
154
|
+
successText: (result, count) => textOf(options.success, locale, { count }, result, count),
|
|
155
|
+
check(target, session, notAllowed = "") {
|
|
156
|
+
const rows = rowsOf(target);
|
|
157
|
+
const own = rows.length === 0
|
|
158
|
+
? [toAllowed(refusalIn(options.can?.(), locale), notAllowed)]
|
|
159
|
+
: rows.map((row) => toAllowed(refusalIn(options.can?.(row), locale), notAllowed));
|
|
160
|
+
const resource = options.resource?.key;
|
|
161
|
+
const asked = options.requires ?? options.id;
|
|
162
|
+
const fromSession = rows.length === 0
|
|
163
|
+
? [toAllowed(session?.can(asked, resource === undefined ? undefined : { resource }), notAllowed)]
|
|
164
|
+
: rows.map((row) => toAllowed(session?.can(asked, resource === undefined ? undefined : { resource, row }), notAllowed));
|
|
165
|
+
return firstRefusal(...own, ...fromSession);
|
|
166
|
+
},
|
|
167
|
+
failureText: (error) => textOf(options.failure, locale, { message: error.message }, error),
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
const action = {
|
|
55
171
|
id: options.id,
|
|
56
172
|
options,
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
const
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
const
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
return
|
|
173
|
+
...texts(undefined),
|
|
174
|
+
in(locale) {
|
|
175
|
+
const from = sources.get(this) ?? this;
|
|
176
|
+
if (!locale)
|
|
177
|
+
return from;
|
|
178
|
+
const byLocale = localized.get(from) ?? new WeakMap();
|
|
179
|
+
localized.set(from, byLocale);
|
|
180
|
+
const known = byLocale.get(locale);
|
|
181
|
+
if (known)
|
|
182
|
+
return known;
|
|
183
|
+
const made = { ...from, ...texts(locale) };
|
|
184
|
+
sources.set(made, from);
|
|
185
|
+
byLocale.set(locale, made);
|
|
186
|
+
return made;
|
|
71
187
|
},
|
|
188
|
+
refreshes,
|
|
189
|
+
scopes,
|
|
190
|
+
destructive: declared?.tone === "destructive",
|
|
72
191
|
parseInput,
|
|
73
192
|
execute(target, input, run = {}) {
|
|
74
193
|
if (inFlight && concurrency === Concurrency.block)
|
|
@@ -92,6 +211,7 @@ export function defineAction(options) {
|
|
|
92
211
|
},
|
|
93
212
|
rowsOf,
|
|
94
213
|
};
|
|
214
|
+
return action;
|
|
95
215
|
}
|
|
96
216
|
export function isAction(value) {
|
|
97
217
|
return isRecord(value) && isString(value.id) && isFunction(value.execute) && Array.isArray(value.scopes);
|
|
@@ -100,7 +220,5 @@ export function actionsOf(resource) {
|
|
|
100
220
|
return resource.actions().filter(isAction);
|
|
101
221
|
}
|
|
102
222
|
export function messageOf(option, ...values) {
|
|
103
|
-
|
|
104
|
-
return undefined;
|
|
105
|
-
return isFunction(option) ? option(...values) : option;
|
|
223
|
+
return textOf(option, undefined, {}, ...values);
|
|
106
224
|
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { ServiceError } from "../core/errors.js";
|
|
2
|
+
import type { ErrorReason } from "../core/constants.js";
|
|
3
|
+
import type { ActionTarget } from "./action.js";
|
|
4
|
+
/** One row a bulk action couldn't change, and why. */
|
|
5
|
+
export type BulkFailure<T> = {
|
|
6
|
+
row: T;
|
|
7
|
+
error: ServiceError & {
|
|
8
|
+
reason: ErrorReason;
|
|
9
|
+
};
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* What a bulk action did, row by row: the rows it changed and the ones it didn't with their reasons. Pass
|
|
13
|
+
* `idempotencyKey` back when retrying the failed rows, so each row keeps its key.
|
|
14
|
+
*/
|
|
15
|
+
export type BulkResult<T> = {
|
|
16
|
+
succeeded: readonly T[];
|
|
17
|
+
failed: readonly BulkFailure<T>[];
|
|
18
|
+
idempotencyKey?: string | undefined;
|
|
19
|
+
};
|
|
20
|
+
export declare function isBulkResult(value: unknown): value is BulkResult<unknown>;
|
|
21
|
+
/** The failed rows as the target to run the action on again: `action.execute(failedTarget(result), input, …)`. */
|
|
22
|
+
export declare function failedTarget<T>(result: BulkResult<T>): ActionTarget<T>;
|
|
23
|
+
/** Runs `work` over `items`, at most `limit` at once, keeping their order. */
|
|
24
|
+
export declare function mapLimited<Item, Value>(items: readonly Item[], limit: number, work: (item: Item, index: number) => Promise<Value>): Promise<Value[]>;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { ActionTargetKind } from "../core/constants.js";
|
|
2
|
+
import { isRecord } from "../core/guards.js";
|
|
3
|
+
export function isBulkResult(value) {
|
|
4
|
+
return isRecord(value) && Array.isArray(value.succeeded) && Array.isArray(value.failed);
|
|
5
|
+
}
|
|
6
|
+
/** The failed rows as the target to run the action on again: `action.execute(failedTarget(result), input, …)`. */
|
|
7
|
+
export function failedTarget(result) {
|
|
8
|
+
return { kind: ActionTargetKind.rows, rows: result.failed.map((entry) => entry.row) };
|
|
9
|
+
}
|
|
10
|
+
/** Runs `work` over `items`, at most `limit` at once, keeping their order. */
|
|
11
|
+
export async function mapLimited(items, limit, work) {
|
|
12
|
+
const results = [];
|
|
13
|
+
let next = 0;
|
|
14
|
+
const worker = async () => {
|
|
15
|
+
if (next >= items.length)
|
|
16
|
+
return;
|
|
17
|
+
const index = next;
|
|
18
|
+
next += 1;
|
|
19
|
+
results[index] = await work(items[index], index);
|
|
20
|
+
return worker();
|
|
21
|
+
};
|
|
22
|
+
await Promise.all(Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, () => worker()));
|
|
23
|
+
return results;
|
|
24
|
+
}
|
package/dist/core/constants.d.ts
CHANGED
|
@@ -300,3 +300,60 @@ export declare const RefusalKind: {
|
|
|
300
300
|
readonly unavailable: "unavailable";
|
|
301
301
|
};
|
|
302
302
|
export type RefusalKind = (typeof RefusalKind)[keyof typeof RefusalKind];
|
|
303
|
+
/**
|
|
304
|
+
* Why a call failed, by a stable code and never by its message: what `defineErrors` words, retries and re-authenticates
|
|
305
|
+
* by.
|
|
306
|
+
*/
|
|
307
|
+
export declare const ErrorReason: {
|
|
308
|
+
readonly network: "network";
|
|
309
|
+
readonly timeout: "timeout";
|
|
310
|
+
readonly unauthorized: "unauthorized";
|
|
311
|
+
readonly sessionExpired: "session-expired";
|
|
312
|
+
readonly forbidden: "forbidden";
|
|
313
|
+
readonly notFound: "not-found";
|
|
314
|
+
readonly conflict: "conflict";
|
|
315
|
+
readonly validation: "validation";
|
|
316
|
+
readonly rateLimited: "rate-limited";
|
|
317
|
+
readonly server: "server";
|
|
318
|
+
readonly unknown: "unknown";
|
|
319
|
+
readonly aborted: "aborted";
|
|
320
|
+
};
|
|
321
|
+
export type ErrorReason = (typeof ErrorReason)[keyof typeof ErrorReason];
|
|
322
|
+
/** Where a person learns how a call went: a toast, next to what they used, a dialog, or nowhere. */
|
|
323
|
+
export declare const Feedback: {
|
|
324
|
+
readonly toast: "toast";
|
|
325
|
+
readonly inline: "inline";
|
|
326
|
+
readonly dialog: "dialog";
|
|
327
|
+
readonly silent: "silent";
|
|
328
|
+
};
|
|
329
|
+
export type Feedback = (typeof Feedback)[keyof typeof Feedback];
|
|
330
|
+
/** A read retries on its own; a write only when repeating it can't do it twice. */
|
|
331
|
+
export declare const Operation: {
|
|
332
|
+
readonly query: "query";
|
|
333
|
+
readonly mutation: "mutation";
|
|
334
|
+
};
|
|
335
|
+
export type Operation = (typeof Operation)[keyof typeof Operation];
|
|
336
|
+
/**
|
|
337
|
+
* Whether a write may run again after a failure: `none` never retries, `idempotent` repeats safely (a PUT, a "set
|
|
338
|
+
* status"), `key` sends one idempotency key for the submit, the same on every retry, so the server runs it once.
|
|
339
|
+
*/
|
|
340
|
+
export declare const Idempotency: {
|
|
341
|
+
readonly none: "none";
|
|
342
|
+
readonly idempotent: "idempotent";
|
|
343
|
+
readonly key: "key";
|
|
344
|
+
};
|
|
345
|
+
export type Idempotency = (typeof Idempotency)[keyof typeof Idempotency];
|
|
346
|
+
/** Where an action's last run is: not run yet, running, done or failed. */
|
|
347
|
+
export declare const ActionStatus: {
|
|
348
|
+
readonly idle: "idle";
|
|
349
|
+
readonly pending: "pending";
|
|
350
|
+
readonly success: "success";
|
|
351
|
+
readonly error: "error";
|
|
352
|
+
};
|
|
353
|
+
export type ActionStatus = (typeof ActionStatus)[keyof typeof ActionStatus];
|
|
354
|
+
/** What a background reload does with rows the list didn't show: hold them behind a "N new rows" banner, or show them. */
|
|
355
|
+
export declare const NewRows: {
|
|
356
|
+
readonly hold: "hold";
|
|
357
|
+
readonly show: "show";
|
|
358
|
+
};
|
|
359
|
+
export type NewRows = (typeof NewRows)[keyof typeof NewRows];
|
package/dist/core/constants.js
CHANGED
|
@@ -154,3 +154,34 @@ export const JsonFormat = {
|
|
|
154
154
|
duration: "duration",
|
|
155
155
|
};
|
|
156
156
|
export const RefusalKind = { refused: "refused", unavailable: "unavailable" };
|
|
157
|
+
/**
|
|
158
|
+
* Why a call failed, by a stable code and never by its message: what `defineErrors` words, retries and re-authenticates
|
|
159
|
+
* by.
|
|
160
|
+
*/
|
|
161
|
+
export const ErrorReason = {
|
|
162
|
+
network: "network",
|
|
163
|
+
timeout: "timeout",
|
|
164
|
+
unauthorized: "unauthorized",
|
|
165
|
+
sessionExpired: "session-expired",
|
|
166
|
+
forbidden: "forbidden",
|
|
167
|
+
notFound: "not-found",
|
|
168
|
+
conflict: "conflict",
|
|
169
|
+
validation: "validation",
|
|
170
|
+
rateLimited: "rate-limited",
|
|
171
|
+
server: "server",
|
|
172
|
+
unknown: "unknown",
|
|
173
|
+
aborted: "aborted",
|
|
174
|
+
};
|
|
175
|
+
/** Where a person learns how a call went: a toast, next to what they used, a dialog, or nowhere. */
|
|
176
|
+
export const Feedback = { toast: "toast", inline: "inline", dialog: "dialog", silent: "silent" };
|
|
177
|
+
/** A read retries on its own; a write only when repeating it can't do it twice. */
|
|
178
|
+
export const Operation = { query: "query", mutation: "mutation" };
|
|
179
|
+
/**
|
|
180
|
+
* Whether a write may run again after a failure: `none` never retries, `idempotent` repeats safely (a PUT, a "set
|
|
181
|
+
* status"), `key` sends one idempotency key for the submit, the same on every retry, so the server runs it once.
|
|
182
|
+
*/
|
|
183
|
+
export const Idempotency = { none: "none", idempotent: "idempotent", key: "key" };
|
|
184
|
+
/** Where an action's last run is: not run yet, running, done or failed. */
|
|
185
|
+
export const ActionStatus = { idle: "idle", pending: "pending", success: "success", error: "error" };
|
|
186
|
+
/** What a background reload does with rows the list didn't show: hold them behind a "N new rows" banner, or show them. */
|
|
187
|
+
export const NewRows = { hold: "hold", show: "show" };
|
package/dist/core/contracts.d.ts
CHANGED
|
@@ -3,6 +3,11 @@ import type { Session } from "../session/session.js";
|
|
|
3
3
|
export type CallContext = {
|
|
4
4
|
signal: AbortSignal;
|
|
5
5
|
session?: Session | undefined;
|
|
6
|
+
/**
|
|
7
|
+
* One key for a write's submit, the same on every retry of it, when it's declared `Idempotency.key`: send it as the
|
|
8
|
+
* `Idempotency-Key` header (`restService` does) so the server runs it once.
|
|
9
|
+
*/
|
|
10
|
+
idempotencyKey?: string | undefined;
|
|
6
11
|
};
|
|
7
12
|
export type SortSpec = {
|
|
8
13
|
field: string;
|
|
@@ -55,6 +60,8 @@ export type Target<Id, F> = {
|
|
|
55
60
|
except: readonly Id[];
|
|
56
61
|
};
|
|
57
62
|
export type ResourceCapabilities = SourceCapabilities & {
|
|
63
|
+
/** It can't write: `create`, `update`, `remove`, `restore` and `import` are refused. `readOnlyService` sets it. */
|
|
64
|
+
readOnly?: boolean;
|
|
58
65
|
restore?: boolean;
|
|
59
66
|
versioned?: boolean;
|
|
60
67
|
bulkByQuery?: boolean;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { ErrorReason } from "./constants.js";
|
|
1
2
|
export type ImportCounts = {
|
|
2
3
|
created: number;
|
|
3
4
|
updated: number;
|
|
@@ -92,6 +93,13 @@ export type DataLabels = {
|
|
|
92
93
|
notFound: (one: string) => string;
|
|
93
94
|
forbidden: (one: string) => string;
|
|
94
95
|
notAllowed: string;
|
|
96
|
+
/** A route guard's page, when the session may not open the path. */
|
|
97
|
+
forbiddenPage: string;
|
|
98
|
+
/** The banner that shows rows a background reload held back. */
|
|
99
|
+
newRows: (count: number, locale?: string) => string;
|
|
100
|
+
/** `useDialogs`: confirm's yes, and alert's button. */
|
|
101
|
+
confirm: string;
|
|
102
|
+
ok: string;
|
|
95
103
|
range: (range: RowRange, locale?: string) => string;
|
|
96
104
|
loading: string;
|
|
97
105
|
search: (other: string) => string;
|
|
@@ -191,6 +199,12 @@ export type DataLabels = {
|
|
|
191
199
|
addRow: string;
|
|
192
200
|
removeRow: (row: number) => string;
|
|
193
201
|
invalidDuration: string;
|
|
202
|
+
/** What a person reads about a failed call, by its reason; `defineErrors` can word one otherwise. */
|
|
203
|
+
errors: Readonly<Record<ErrorReason, string>>;
|
|
204
|
+
/** A bulk action's outcome: "3 done, 2 failed". */
|
|
205
|
+
bulkResult: (succeeded: number, failed: number, locale?: string) => string;
|
|
206
|
+
/** The button that runs a bulk action again on the rows that failed. */
|
|
207
|
+
retryFailed: (count: number, locale?: string) => string;
|
|
194
208
|
};
|
|
195
209
|
export declare const dataLabelsEn: DataLabels;
|
|
196
210
|
export declare const dataLabelsEs: DataLabels;
|