@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.
Files changed (159) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +74 -2
  3. package/dist/action/action.d.ts +133 -0
  4. package/dist/action/action.js +224 -0
  5. package/dist/action/bulk.d.ts +24 -0
  6. package/dist/action/bulk.js +24 -0
  7. package/dist/cli/cli.d.ts +2 -0
  8. package/dist/cli/cli.js +51 -0
  9. package/dist/cli/routes.d.ts +17 -0
  10. package/dist/cli/routes.js +36 -0
  11. package/dist/core/assume.d.ts +1 -0
  12. package/dist/core/assume.js +8 -0
  13. package/dist/core/constants.d.ts +359 -0
  14. package/dist/core/constants.js +187 -0
  15. package/dist/core/contracts.d.ts +107 -0
  16. package/dist/core/contracts.js +3 -0
  17. package/dist/core/data-labels.d.ts +210 -0
  18. package/dist/core/data-labels.js +385 -0
  19. package/dist/core/errors.d.ts +52 -0
  20. package/dist/core/errors.js +209 -0
  21. package/dist/core/guards.d.ts +9 -0
  22. package/dist/core/guards.js +14 -0
  23. package/dist/core/refusal.d.ts +30 -0
  24. package/dist/core/refusal.js +53 -0
  25. package/dist/dialogs/dialogs.d.ts +75 -0
  26. package/dist/dialogs/dialogs.js +66 -0
  27. package/dist/draft/draft.d.ts +36 -0
  28. package/dist/draft/draft.js +87 -0
  29. package/dist/errors/adapters.d.ts +21 -0
  30. package/dist/errors/adapters.js +81 -0
  31. package/dist/errors/define-errors.d.ts +88 -0
  32. package/dist/errors/define-errors.js +168 -0
  33. package/dist/errors/idempotency.d.ts +2 -0
  34. package/dist/errors/idempotency.js +13 -0
  35. package/dist/export/csv.d.ts +25 -0
  36. package/dist/export/csv.js +59 -0
  37. package/dist/i18n/adapters.d.ts +53 -0
  38. package/dist/i18n/adapters.js +56 -0
  39. package/dist/i18n/format.d.ts +10 -0
  40. package/dist/i18n/format.js +273 -0
  41. package/dist/i18n/labels.d.ts +10 -0
  42. package/dist/i18n/labels.js +227 -0
  43. package/dist/i18n/locale.d.ts +73 -0
  44. package/dist/i18n/locale.js +74 -0
  45. package/dist/i18n/messages.d.ts +93 -0
  46. package/dist/i18n/messages.js +16 -0
  47. package/dist/import/csv-parse.d.ts +11 -0
  48. package/dist/import/csv-parse.js +70 -0
  49. package/dist/import/import.d.ts +104 -0
  50. package/dist/import/import.js +266 -0
  51. package/dist/index.d.ts +46 -0
  52. package/dist/index.js +45 -0
  53. package/dist/navigation/nav.d.ts +128 -0
  54. package/dist/navigation/nav.js +301 -0
  55. package/dist/navigation/router.d.ts +81 -0
  56. package/dist/navigation/router.js +249 -0
  57. package/dist/navigation/shortcuts.d.ts +37 -0
  58. package/dist/navigation/shortcuts.js +93 -0
  59. package/dist/next/index.d.ts +3 -0
  60. package/dist/next/index.js +3 -0
  61. package/dist/next/screen-hydration.d.ts +12 -0
  62. package/dist/next/screen-hydration.js +26 -0
  63. package/dist/next/screen.d.ts +25 -0
  64. package/dist/next/screen.js +44 -0
  65. package/dist/next/server/handler.d.ts +39 -0
  66. package/dist/next/server/handler.js +190 -0
  67. package/dist/next/server/index.d.ts +6 -0
  68. package/dist/next/server/index.js +6 -0
  69. package/dist/next/server/page.d.ts +63 -0
  70. package/dist/next/server/page.js +110 -0
  71. package/dist/next/server/prefetch.d.ts +29 -0
  72. package/dist/next/server/prefetch.js +97 -0
  73. package/dist/next/server/session.d.ts +25 -0
  74. package/dist/next/server/session.js +23 -0
  75. package/dist/next/use-next-router.d.ts +21 -0
  76. package/dist/next/use-next-router.js +104 -0
  77. package/dist/permissions/permissions.d.ts +134 -0
  78. package/dist/permissions/permissions.js +121 -0
  79. package/dist/react/data-layer.d.ts +68 -0
  80. package/dist/react/data-layer.js +76 -0
  81. package/dist/react/hooks/use-action-dialog.d.ts +25 -0
  82. package/dist/react/hooks/use-action-dialog.js +31 -0
  83. package/dist/react/hooks/use-action.d.ts +37 -0
  84. package/dist/react/hooks/use-action.js +125 -0
  85. package/dist/react/hooks/use-better-auth.d.ts +12 -0
  86. package/dist/react/hooks/use-better-auth.js +11 -0
  87. package/dist/react/hooks/use-bulk-action.d.ts +20 -0
  88. package/dist/react/hooks/use-bulk-action.js +24 -0
  89. package/dist/react/hooks/use-dialogs.d.ts +14 -0
  90. package/dist/react/hooks/use-dialogs.js +20 -0
  91. package/dist/react/hooks/use-draft.d.ts +5 -0
  92. package/dist/react/hooks/use-draft.js +17 -0
  93. package/dist/react/hooks/use-nav.d.ts +17 -0
  94. package/dist/react/hooks/use-nav.js +35 -0
  95. package/dist/react/hooks/use-new-rows.d.ts +22 -0
  96. package/dist/react/hooks/use-new-rows.js +24 -0
  97. package/dist/react/hooks/use-permissions.d.ts +13 -0
  98. package/dist/react/hooks/use-permissions.js +19 -0
  99. package/dist/react/hooks/use-reauthenticate.d.ts +6 -0
  100. package/dist/react/hooks/use-reauthenticate.js +11 -0
  101. package/dist/react/hooks/use-resource.d.ts +92 -0
  102. package/dist/react/hooks/use-resource.js +255 -0
  103. package/dist/react/hooks/use-view.d.ts +6 -0
  104. package/dist/react/hooks/use-view.js +24 -0
  105. package/dist/react/index.d.ts +15 -0
  106. package/dist/react/index.js +15 -0
  107. package/dist/react/keys.d.ts +60 -0
  108. package/dist/react/keys.js +71 -0
  109. package/dist/react/new-rows.d.ts +22 -0
  110. package/dist/react/new-rows.js +72 -0
  111. package/dist/refresh/new-rows.d.ts +13 -0
  112. package/dist/refresh/new-rows.js +18 -0
  113. package/dist/resource/form-schema.d.ts +11 -0
  114. package/dist/resource/form-schema.js +51 -0
  115. package/dist/resource/relations.d.ts +99 -0
  116. package/dist/resource/relations.js +194 -0
  117. package/dist/resource/resource-relations.d.ts +47 -0
  118. package/dist/resource/resource-relations.js +154 -0
  119. package/dist/resource/resource-schema.d.ts +9 -0
  120. package/dist/resource/resource-schema.js +73 -0
  121. package/dist/resource/resource-texts.d.ts +18 -0
  122. package/dist/resource/resource-texts.js +13 -0
  123. package/dist/resource/resource-types.d.ts +420 -0
  124. package/dist/resource/resource-types.js +1 -0
  125. package/dist/resource/resource-words.d.ts +25 -0
  126. package/dist/resource/resource-words.js +221 -0
  127. package/dist/resource/resource.d.ts +15 -0
  128. package/dist/resource/resource.js +280 -0
  129. package/dist/resource/schema.d.ts +57 -0
  130. package/dist/resource/schema.js +115 -0
  131. package/dist/services/from-page-source.d.ts +15 -0
  132. package/dist/services/from-page-source.js +27 -0
  133. package/dist/services/memory-query.d.ts +8 -0
  134. package/dist/services/memory-query.js +165 -0
  135. package/dist/services/memory-service.d.ts +33 -0
  136. package/dist/services/memory-service.js +291 -0
  137. package/dist/services/read-only-service.d.ts +18 -0
  138. package/dist/services/read-only-service.js +25 -0
  139. package/dist/services/rest-service.d.ts +65 -0
  140. package/dist/services/rest-service.js +222 -0
  141. package/dist/services/rng.d.ts +9 -0
  142. package/dist/services/rng.js +22 -0
  143. package/dist/services/spring-service.d.ts +58 -0
  144. package/dist/services/spring-service.js +132 -0
  145. package/dist/session/better-auth.d.ts +83 -0
  146. package/dist/session/better-auth.js +86 -0
  147. package/dist/session/session.d.ts +45 -0
  148. package/dist/session/session.js +36 -0
  149. package/dist/view/preferences.d.ts +35 -0
  150. package/dist/view/preferences.js +93 -0
  151. package/dist/view/view-types.d.ts +124 -0
  152. package/dist/view/view-types.js +1 -0
  153. package/dist/view/view-url.d.ts +7 -0
  154. package/dist/view/view-url.js +54 -0
  155. package/dist/view/view.d.ts +4 -0
  156. package/dist/view/view.js +392 -0
  157. package/locales/en.json +193 -0
  158. package/locales/es.json +193 -0
  159. package/package.json +88 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Pablo Otero
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,75 @@
1
- # Temporary Holding Version
1
+ # @eskais/app-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A declarative application layer over [Eskais UI](https://ui.eskais.com/). Describe your data and what can be done with it (resources, actions, views, navigation and permissions) and the Eskais UI resource and nav blocks give you the screens. The full guide is [ui.eskais.com/docs/app-sdk](https://ui.eskais.com/docs/app-sdk/).
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @eskais/app-sdk @tanstack/react-query zod
9
+ npx shadcn@latest add @eskais/resource-page @eskais/nav-shell @eskais/nav-breadcrumb
10
+ ```
11
+
12
+ The blocks pin the version of this package they were built with, and `shadcn add` installs it.
13
+
14
+ ## Entries
15
+
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
+
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
+
26
+ On Next.js, one optional catch-all serves every resource of the manifest, rendered on the server with its data:
27
+
28
+ ```tsx
29
+ // app/(admin)/[[...path]]/page.tsx
30
+ import { navPage } from "@eskais/app-sdk/next/server"
31
+
32
+ const page = navPage(nav, { render: () => <AdminScreen />, session: getSession, services: backend })
33
+
34
+ export default page.Page
35
+ export const generateMetadata = page.generateMetadata
36
+ ```
37
+
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
+
40
+ ```tsx
41
+ import en from "@eskais/app-sdk/locales/en.json"
42
+ import { defineLocale, defineResource, hashRouter, memoryService } from "@eskais/app-sdk"
43
+ import { DataLayer } from "@eskais/app-sdk/react"
44
+ import { z } from "zod"
45
+
46
+ import { ResourcePage } from "@/components/ui/resource-page"
47
+ import { createDataClient } from "@/components/ui/server-data"
48
+
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
+ })
56
+
57
+ const customers = defineResource<z.infer<typeof customer>>()({
58
+ key: "customers",
59
+ schema: customer,
60
+ service: memoryService(customer, { seed: 7, count: 40 }),
61
+ title: (c) => c.name,
62
+ })
63
+
64
+ export function App() {
65
+ return (
66
+ <DataLayer client={createDataClient()} router={hashRouter()} locale={locale}>
67
+ <ResourcePage resource={customers} />
68
+ </DataLayer>
69
+ )
70
+ }
71
+ ```
72
+
73
+ ## License
74
+
75
+ MIT
@@ -0,0 +1,133 @@
1
+ import { ActionScope, ActionTargetKind, Concurrency, Feedback, Idempotency } from "../core/constants.js";
2
+ import type { CallContext } from "../core/contracts.js";
3
+ import { type ServiceError } from "../core/errors.js";
4
+ import type { Errors } from "../errors/define-errors.js";
5
+ import { type BulkResult } from "./bulk.js";
6
+ import { type Allowed, type Refusal } from "../core/refusal.js";
7
+ import type { AnyResource, ToneName } from "../resource/resource.js";
8
+ import { type StandardSchema } from "../resource/schema.js";
9
+ import type { RegisteredOperation } from "../permissions/permissions.js";
10
+ import type { Session } from "../session/session.js";
11
+ import { type Locale, type MessageRef, type Text, type TextRefusal } from "../i18n/locale.js";
12
+ export type ActionTarget<T> = {
13
+ kind: typeof ActionTargetKind.none;
14
+ } | {
15
+ kind: typeof ActionTargetKind.row;
16
+ row: T;
17
+ } | {
18
+ kind: typeof ActionTargetKind.rows;
19
+ rows: readonly T[];
20
+ } | {
21
+ kind: typeof ActionTargetKind.query;
22
+ filter: unknown;
23
+ search?: string | undefined;
24
+ except: readonly unknown[];
25
+ };
26
+ export type ActionConfirm = {
27
+ title?: string;
28
+ description?: string;
29
+ tone?: ToneName;
30
+ confirmLabel?: string;
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;
40
+ export type ActionOptions<T, I, R> = {
41
+ id: string;
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;
47
+ icon?: unknown;
48
+ description?: Text;
49
+ resource?: AnyResource;
50
+ /** `ActionScope.row` by default when there's a `resource`, `ActionScope.global` otherwise. */
51
+ scope?: ActionScope | readonly ActionScope[];
52
+ input?: StandardSchema<unknown, I>;
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;
61
+ run: (target: ActionTarget<T>, input: I, context: CallContext) => Promise<R>;
62
+ optimistic?: (row: T, input: I) => T;
63
+ undo?: (target: ActionTarget<T>, result: R, context: CallContext) => Promise<void>;
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]>;
71
+ shortcut?: string;
72
+ /** What a second run does while one is going: `block` refuses it, `switch` aborts the first, `queue` waits. */
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;
90
+ };
91
+ export type AnyAction = Action<any, any, any>;
92
+ export type ActionRunOptions = {
93
+ session?: Session | undefined;
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;
99
+ };
100
+ export type Action<T = unknown, I = void, R = unknown> = {
101
+ readonly id: string;
102
+ readonly options: ActionOptions<T, I, R>;
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;
113
+ readonly scopes: readonly ActionScope[];
114
+ readonly destructive: boolean;
115
+ readonly confirm: ActionConfirm | undefined;
116
+ check(target: ActionTarget<T>, session?: Session, notAllowed?: string): Allowed;
117
+ parseInput(input: unknown): Promise<I>;
118
+ execute(target: ActionTarget<T>, input: I, options?: ActionRunOptions): Promise<R>;
119
+ running(): boolean;
120
+ countOf(target: ActionTarget<T>): number | undefined;
121
+ rowsOf(target: ActionTarget<T>): readonly T[];
122
+ };
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>>;
129
+ export declare function isAction(value: unknown): value is AnyAction;
130
+ export declare function actionsOf(resource: {
131
+ actions(): readonly unknown[];
132
+ }): AnyAction[];
133
+ export declare function messageOf<Value extends unknown[]>(option: ActionMessage<Value> | undefined, ...values: Value): string | undefined;
@@ -0,0 +1,224 @@
1
+ import { assumeType } from "../core/assume.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";
6
+ import { isFunction, isRecord, isString } from "../core/guards.js";
7
+ import { firstRefusal, toAllowed } from "../core/refusal.js";
8
+ import { isValidationFailure, issuePath, validate } from "../resource/schema.js";
9
+ import { isMessageRef, lookup, refusalIn, resolveText, } from "../i18n/locale.js";
10
+ function scopesOf(scope, hasResource) {
11
+ if (scope === undefined)
12
+ return [hasResource ? ActionScope.row : ActionScope.global];
13
+ return isString(scope) ? [scope] : scope;
14
+ }
15
+ function linked(signal, own) {
16
+ if (!signal)
17
+ return own.signal;
18
+ return AbortSignal.any([signal, own.signal]);
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
+ }
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) {
97
+ const scopes = scopesOf(options.scope, options.resource !== undefined);
98
+ const declared = options.confirm === true ? {} : options.confirm === false ? undefined : options.confirm;
99
+ const resourceKey = options.resource?.key;
100
+ const concurrency = options.concurrency ?? Concurrency.block;
101
+ let inFlight;
102
+ let tail = Promise.resolve();
103
+ const rowsOf = (target) => targetRows(target);
104
+ async function parseInput(input) {
105
+ if (!options.input) {
106
+ // Workaround: an action without an input schema takes no input; `I` is `void` for it.
107
+ return assumeType(input);
108
+ }
109
+ const result = await validate(options.input, input);
110
+ if (!isValidationFailure(result))
111
+ return result.value;
112
+ const fields = result.issues.map((issue) => ({ path: issuePath(issue), message: issue.message }));
113
+ const message = fields.map((field) => (field.path ? `${field.path}: ${field.message}` : field.message)).join("; ");
114
+ throw new ServiceFailure(serviceError(ServiceErrorKind.validation, message, { fields }));
115
+ }
116
+ function start(target, input, run) {
117
+ const controller = new AbortController();
118
+ const signal = linked(run.signal, controller);
119
+ const done = runner(target, input, run, signal);
120
+ const entry = { controller, done };
121
+ inFlight = entry;
122
+ const clear = () => {
123
+ if (inFlight === entry)
124
+ inFlight = undefined;
125
+ };
126
+ done.then(clear, clear);
127
+ return done;
128
+ }
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 = {
171
+ id: options.id,
172
+ options,
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;
187
+ },
188
+ refreshes,
189
+ scopes,
190
+ destructive: declared?.tone === "destructive",
191
+ parseInput,
192
+ execute(target, input, run = {}) {
193
+ if (inFlight && concurrency === Concurrency.block)
194
+ return Promise.reject(new ServiceFailure(serviceError(ServiceErrorKind.conflict, `${options.id} is already running.`)));
195
+ if (inFlight && concurrency === Concurrency.switch)
196
+ inFlight.controller.abort();
197
+ if (concurrency === Concurrency.queue) {
198
+ const next = tail.then(() => start(target, input, run), () => start(target, input, run));
199
+ tail = next.catch(() => undefined);
200
+ return next;
201
+ }
202
+ return start(target, input, run);
203
+ },
204
+ running: () => inFlight !== undefined,
205
+ countOf(target) {
206
+ if (target.kind === ActionTargetKind.none)
207
+ return 0;
208
+ if (target.kind === ActionTargetKind.query)
209
+ return undefined;
210
+ return rowsOf(target).length;
211
+ },
212
+ rowsOf,
213
+ };
214
+ return action;
215
+ }
216
+ export function isAction(value) {
217
+ return isRecord(value) && isString(value.id) && isFunction(value.execute) && Array.isArray(value.scopes);
218
+ }
219
+ export function actionsOf(resource) {
220
+ return resource.actions().filter(isAction);
221
+ }
222
+ export function messageOf(option, ...values) {
223
+ return textOf(option, undefined, {}, ...values);
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
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export declare function main(argv: readonly string[], cwd: string, log: (line: string) => void): number;
@@ -0,0 +1,51 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { parseArgs } from "node:util";
5
+ import { parseResource, routeFiles } from "./routes.js";
6
+ const usage = `app-sdk routes --from <module> --resource <name[:base[:create[:edit]]]>… [--dir src/routes] [--routes-module <module>] [--force]
7
+
8
+ Writes TanStack Router file routes for each resource: <base>/index.tsx, <base>/<create>.tsx,
9
+ <base>/$id/index.tsx and <base>/$id/<edit>.tsx, one line each with resourceRoute. Existing files stay
10
+ unless --force.`;
11
+ export function main(argv, cwd, log) {
12
+ const [command, ...rest] = argv;
13
+ if (command !== "routes") {
14
+ log(usage);
15
+ return command === undefined || command === "--help" ? 0 : 2;
16
+ }
17
+ const { values } = parseArgs({
18
+ args: [...rest],
19
+ options: {
20
+ from: { type: "string" },
21
+ resource: { type: "string", multiple: true },
22
+ dir: { type: "string", default: "src/routes" },
23
+ "routes-module": { type: "string" },
24
+ force: { type: "boolean", default: false },
25
+ },
26
+ });
27
+ const resources = values.resource ?? [];
28
+ if (values.from === undefined || resources.length === 0) {
29
+ log(usage);
30
+ return 2;
31
+ }
32
+ const files = routeFiles({
33
+ from: values.from,
34
+ resources: resources.map(parseResource),
35
+ ...(values["routes-module"] === undefined ? {} : { routesModule: values["routes-module"] }),
36
+ });
37
+ const root = resolve(cwd, values.dir);
38
+ for (const route of files) {
39
+ const target = join(root, route.path);
40
+ if (existsSync(target) && !values.force) {
41
+ log(`kept ${target}`);
42
+ continue;
43
+ }
44
+ mkdirSync(dirname(target), { recursive: true });
45
+ writeFileSync(target, route.content);
46
+ log(`wrote ${target}`);
47
+ }
48
+ return 0;
49
+ }
50
+ if (import.meta.main === true)
51
+ process.exitCode = main(process.argv.slice(2), process.cwd(), (line) => process.stdout.write(`${line}\n`));
@@ -0,0 +1,17 @@
1
+ export type RouteResource = {
2
+ name: string;
3
+ base: string;
4
+ create: string;
5
+ edit: string;
6
+ };
7
+ export type RoutesOptions = {
8
+ resources: readonly RouteResource[];
9
+ from: string;
10
+ routesModule?: string;
11
+ };
12
+ export type RouteFile = {
13
+ path: string;
14
+ content: string;
15
+ };
16
+ export declare function routeFiles(options: RoutesOptions): RouteFile[];
17
+ export declare function parseResource(spec: string): RouteResource;
@@ -0,0 +1,36 @@
1
+ const quote = (text) => JSON.stringify(text);
2
+ function file(path, route, screen, resource, options) {
3
+ const routesModule = options.routesModule ?? "@/components/ui/resource-routes";
4
+ const content = [
5
+ `import { createFileRoute } from "@tanstack/react-router"`,
6
+ "",
7
+ `import { resourceRoute } from ${quote(routesModule)}`,
8
+ `import { ${resource.name} } from ${quote(options.from)}`,
9
+ "",
10
+ `export const Route = createFileRoute(${quote(route)})(resourceRoute.${screen}(${resource.name}))`,
11
+ "",
12
+ ].join("\n");
13
+ return { path, content };
14
+ }
15
+ export function routeFiles(options) {
16
+ return options.resources.flatMap((resource) => {
17
+ const base = resource.base.replace(/^\/+|\/+$/gu, "");
18
+ return [
19
+ file(`${base}/index.tsx`, `/${base}/`, "list", resource, options),
20
+ file(`${base}/${resource.create}.tsx`, `/${base}/${resource.create}`, "create", resource, options),
21
+ file(`${base}/$id/index.tsx`, `/${base}/$id/`, "detail", resource, options),
22
+ file(`${base}/$id/${resource.edit}.tsx`, `/${base}/$id/${resource.edit}`, "edit", resource, options),
23
+ ];
24
+ });
25
+ }
26
+ const identifier = /^[A-Za-z_$][\w$]*$/u;
27
+ const segment = /^[\w-]+(?:\/[\w-]+)*$/u;
28
+ export function parseResource(spec) {
29
+ const [name = "", base = name, create = "new", edit = "edit"] = spec.split(":");
30
+ if (!identifier.test(name))
31
+ throw new RangeError(`"${name}" isn't an export name.`);
32
+ for (const part of [base, create, edit])
33
+ if (!segment.test(part))
34
+ throw new RangeError(`"${part}" isn't a route segment.`);
35
+ return { name, base, create, edit };
36
+ }
@@ -0,0 +1 @@
1
+ export declare function assumeType<T>(value: unknown): T;
@@ -0,0 +1,8 @@
1
+ function holds(_value) {
2
+ return true;
3
+ }
4
+ export function assumeType(value) {
5
+ if (holds(value))
6
+ return value;
7
+ throw new TypeError("Unreachable.");
8
+ }