@opencloudcms/client 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 +337 -2
- package/dist/cjs/actions/runner.js +434 -0
- package/dist/cjs/core/account.js +22 -0
- package/dist/cjs/core/actions.js +56 -0
- package/dist/cjs/core/auth.js +73 -0
- package/dist/cjs/core/client.js +160 -0
- package/dist/cjs/core/content.js +89 -0
- package/dist/cjs/core/default-client.js +27 -0
- package/dist/cjs/core/errors.js +53 -0
- package/dist/cjs/core/typed.js +22 -0
- package/dist/cjs/core/types.js +2 -0
- package/dist/cjs/core/utils.js +64 -0
- package/dist/cjs/index.js +37 -0
- package/dist/cjs/next/loopback.js +12 -0
- package/dist/cjs/next/server.js +99 -0
- package/dist/cjs/next/stubs.js +10 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/react/provider.js +162 -0
- package/dist/cjs/react/stubs.js +13 -0
- package/dist/cjs/server.js +38 -0
- package/dist/esm/actions/runner.d.ts +92 -0
- package/dist/esm/actions/runner.js +428 -0
- package/dist/esm/core/account.d.ts +20 -0
- package/dist/esm/core/account.js +19 -0
- package/dist/esm/core/actions.d.ts +81 -0
- package/dist/esm/core/actions.js +51 -0
- package/dist/esm/core/auth.d.ts +61 -0
- package/dist/esm/core/auth.js +69 -0
- package/dist/esm/core/client.d.ts +2 -0
- package/dist/esm/core/client.js +157 -0
- package/dist/esm/core/content.d.ts +5 -0
- package/dist/esm/core/content.js +85 -0
- package/dist/esm/core/default-client.d.ts +9 -0
- package/dist/esm/core/default-client.js +23 -0
- package/dist/esm/core/errors.d.ts +13 -0
- package/dist/esm/core/errors.js +47 -0
- package/dist/esm/core/typed.d.ts +31 -0
- package/dist/esm/core/typed.js +19 -0
- package/dist/esm/core/types.d.ts +90 -0
- package/dist/esm/core/types.js +1 -0
- package/dist/esm/core/utils.d.ts +27 -0
- package/dist/esm/core/utils.js +56 -0
- package/dist/esm/index.d.ts +20 -0
- package/dist/esm/index.js +12 -0
- package/dist/esm/next/loopback.d.ts +6 -0
- package/dist/esm/next/loopback.js +9 -0
- package/dist/esm/next/server.d.ts +19 -0
- package/dist/esm/next/server.js +60 -0
- package/dist/esm/next/stubs.d.ts +5 -0
- package/dist/esm/next/stubs.js +7 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/react/provider.d.ts +38 -0
- package/dist/esm/react/provider.js +153 -0
- package/dist/esm/react/stubs.d.ts +6 -0
- package/dist/esm/react/stubs.js +10 -0
- package/dist/esm/server.d.ts +21 -0
- package/dist/esm/server.js +13 -0
- package/package.json +61 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ánh Nguyễn
|
|
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,338 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @opencloudcms/client
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Storefront SDK for OpenCloudCMS: the API client, customer sign-in and account calls, React hooks, Next.js server
|
|
4
|
+
helpers, a typed content client (generated) and small utilities. **One import path**, `@opencloudcms/client`, with
|
|
5
|
+
conditional builds:
|
|
6
|
+
|
|
7
|
+
| Condition | File | Used by |
|
|
8
|
+
| -------------- | ---------------------- | ----------------------------------------------------------- |
|
|
9
|
+
| `react-server` | `dist/esm/server.js` | Next server components and route handlers (no hooks/context) |
|
|
10
|
+
| `import` | `dist/esm/index.js` | browser / client components (`'use client'`), ESM |
|
|
11
|
+
| `require` | `dist/cjs/index.js` | CommonJS (the NestJS server, which loads `src/blocks`) |
|
|
12
|
+
|
|
13
|
+
Built with `tsc` twice (ESM and CJS); per-file `'use client'` directives are kept (no single-file bundle). The SDK
|
|
14
|
+
depends on no Nest, Kysely or `@opencloudcms/core`; `react` and `next` are optional peer dependencies. The admin SPA
|
|
15
|
+
does not use it.
|
|
16
|
+
|
|
17
|
+
## Server or client: what to use where
|
|
18
|
+
|
|
19
|
+
| Where | Customer | Content | Calls |
|
|
20
|
+
| --------------------------------------------- | ------------------------------------------ | --------------------------------------------- | ---------------------------------------------- |
|
|
21
|
+
| Server component / route handler (`react-server`) | `getCustomer()`, `requireCustomer()` | `cms.product.list()` (bound to `publicClient()`), `publicClient().content` | `serverClient().request()` (forwards the cookie) |
|
|
22
|
+
| Client component (`'use client'`) | `useCustomer()`, `useSignIn()`, `useSignOut()` | `cms.product.list()` (same-origin client) | `useClient().request()` / `.auth` / `.account` |
|
|
23
|
+
| Anywhere else (scripts, React Native, another domain) | `createClient({ baseUrl, auth: 'bearer', getAccessToken }).auth.me()` | `cms.with(client)` / `client.content` | `client.request()` |
|
|
24
|
+
|
|
25
|
+
Hooks called in a server component throw a clear error **when called** (never at import time). In the browser build
|
|
26
|
+
`serverClient` / `publicClient` / `getCustomer` / `requireCustomer` are stubs that throw when called, so `next/headers`
|
|
27
|
+
never enters the browser bundle.
|
|
28
|
+
|
|
29
|
+
## Setup in a Next app
|
|
30
|
+
|
|
31
|
+
```tsx
|
|
32
|
+
// app/providers.tsx
|
|
33
|
+
'use client';
|
|
34
|
+
import type { ReactNode } from 'react';
|
|
35
|
+
import { OpenCloudCmsProvider } from '@opencloudcms/client';
|
|
36
|
+
|
|
37
|
+
export default function Providers({ children }: { children: ReactNode }) {
|
|
38
|
+
return <OpenCloudCmsProvider signInPath="/account/login">{children}</OpenCloudCmsProvider>;
|
|
39
|
+
}
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
```tsx
|
|
43
|
+
// app/(site)/layout.tsx (server component)
|
|
44
|
+
<body><Providers>{children}</Providers></body>
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
`opencloudcms init` writes both. `<OpenCloudCmsProvider client? signInPath? initialCustomer? actions?>`:
|
|
48
|
+
|
|
49
|
+
- `client` — defaults to a same-origin cookie client (`createClient()`).
|
|
50
|
+
- `signInPath` — where signed-out customers are sent by page actions (default `/account/login`; that page redirects
|
|
51
|
+
to the BFF sign-in when opened without an interaction `uid`, see `examples/my-store/app/(site)/account/login`).
|
|
52
|
+
- `initialCustomer` — a server-fetched customer (`await getCustomer()`), or `null`: then no client-side `me()` call.
|
|
53
|
+
- `actions` — the browser halves of page actions (`defineActionClient`), see [Page actions](#page-actions).
|
|
54
|
+
- `ui` — a `UiAdapter`: your own toast, confirm, overlay and navigation for the action runner (read on every run).
|
|
55
|
+
|
|
56
|
+
## Core client
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
import { createClient, errorMessage, isApiError } from '@opencloudcms/client';
|
|
60
|
+
|
|
61
|
+
const client = createClient({
|
|
62
|
+
baseUrl: '', // default: same origin as the page
|
|
63
|
+
auth: 'cookie', // default; or 'bearer' (below)
|
|
64
|
+
locale: 'vi-VN', // `locale` query on content calls and Accept-Language
|
|
65
|
+
fetch, // injectable (tests, React Native)
|
|
66
|
+
headers: {}, // extra headers on every request
|
|
67
|
+
messages: { out_of_stock: { 'en-US': 'Sold out', 'vi-VN': 'Hết hàng' } },
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
try {
|
|
71
|
+
const order = await client.request<{ code: string }>('POST', '/api/store/orders', { body: { items } });
|
|
72
|
+
} catch (e) {
|
|
73
|
+
if (isApiError(e) && e.status === 401) client.auth.signIn();
|
|
74
|
+
else alert(errorMessage(e, 'vi-VN', client.options.messages));
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
- `client.request<T>(method, path, { body?, query?, headers?, signal?, cache?, next? })` — JSON in and out; the way
|
|
79
|
+
to call a project's own routes (e.g. `/api/store/**`). Cookie mode sends `credentials: 'same-origin'`
|
|
80
|
+
when `baseUrl` is empty or the page origin, and `credentials: 'omit'` when `baseUrl` is another origin (the SDK
|
|
81
|
+
never sends cookies cross-origin); cross-origin storefronts use bearer mode (`auth: 'bearer'` + `getAccessToken`).
|
|
82
|
+
- Non-2xx responses throw `ApiError { status, code, message, issues?, details? }` from
|
|
83
|
+
`{ error: { code, message, issues } }` (`http_<status>` for other bodies, `network_error` with status 0 when the
|
|
84
|
+
request cannot be sent). `isApiError(e)` also recognises errors from another copy of the SDK.
|
|
85
|
+
- `errorMessage(err | code, locale?, messages?)` — en-US / vi-VN texts for `invalid_identifier`,
|
|
86
|
+
`identifier_kind_disabled`, `method_disabled`, `invalid_code`, `invalid_credentials`, `account_disabled`,
|
|
87
|
+
`rate_limited`, `weak_password`, `validation_failed`, `unauthenticated`, `login_expired`, `invalid_state`,
|
|
88
|
+
`unknown_action`, `action_failed`, `network_error`; `messages` overrides or adds codes; anything else gets a
|
|
89
|
+
generic text. A locale starting with `vi` uses vi-VN, everything else en-US. A client's own `messages` option is
|
|
90
|
+
kept on `client.options.messages` for this third argument.
|
|
91
|
+
- `ErrorMessages` (type) — texts by code, then by locale:
|
|
92
|
+
`Partial<Record<string, Partial<Record<'en-US' | 'vi-VN', string>>>>`, e.g.
|
|
93
|
+
`{ out_of_stock: { 'en-US': 'Sold out', 'vi-VN': 'Hết hàng' } }`. A code with only an en-US text uses it for every
|
|
94
|
+
locale (a built-in vi-VN text of the same code still wins in vi-VN).
|
|
95
|
+
|
|
96
|
+
### Bearer mode
|
|
97
|
+
|
|
98
|
+
For a mobile app or a storefront on another domain that signs customers in itself (OAuth2 PKCE with the
|
|
99
|
+
`opencloudcms-storefront-mobile` / `opencloudcms-storefront-web` clients):
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
const client = createClient({
|
|
103
|
+
baseUrl: 'https://shop.example.com',
|
|
104
|
+
auth: 'bearer',
|
|
105
|
+
getAccessToken: async () => (await storage.get('access_token')) ?? null, // null → no Authorization header
|
|
106
|
+
});
|
|
107
|
+
const me = await client.auth.me();
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
The SDK only adds `Authorization: Bearer <token>`, and only to `baseUrl`'s origin; it never stores, refreshes or
|
|
111
|
+
exposes tokens. `auth.signIn()` throws `ApiError('unsupported_in_bearer_mode')` (the app runs its own OAuth flow).
|
|
112
|
+
Cookie mode never exposes a token either: the `oc_customer` cookie is httpOnly.
|
|
113
|
+
|
|
114
|
+
## Content
|
|
115
|
+
|
|
116
|
+
```ts
|
|
117
|
+
await client.content.list('product', { filter: { active: true, brand: { in: [a, b] } }, sort: 'createdAt:desc', limit: 12 });
|
|
118
|
+
await client.content.get('product', documentId); // null on 404
|
|
119
|
+
await client.content.bySlug('product', 'linen-shirt'); // null when none
|
|
120
|
+
await client.content.byIds('product', ids); // chunks of 100, order kept, missing ids left out
|
|
121
|
+
await client.assets.byIds(assetIds); // [{ id, url, alt?, width?, height? }]
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
`opencloudcms generate` writes the typed version, `src/generated/client.ts` (public content types only):
|
|
125
|
+
|
|
126
|
+
```ts
|
|
127
|
+
import { cms } from '@/generated/client';
|
|
128
|
+
const p = await cms.product.bySlug('linen-shirt'); // Product | null
|
|
129
|
+
await cms.with(serverClient()).product.list({ filter: { brand: id } });
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
`cms` is `createContentApi<{ product: Product; … }>()`. Call `createContentApi<M>(client?)` yourself for a typed
|
|
133
|
+
API over your own map of content types (`M` maps each API id to its entry type), bound to `client` or, without one,
|
|
134
|
+
to the default client; `.with(client)` returns the same API bound to another client. Each type has `list(o?)`
|
|
135
|
+
(filters typed by the entry's field names), `get(documentId, o?)`, `bySlug(slug, o?)` and `byIds(ids, o?)`, with
|
|
136
|
+
the same behaviour as `client.content`.
|
|
137
|
+
|
|
138
|
+
```ts
|
|
139
|
+
import { createContentApi } from '@opencloudcms/client';
|
|
140
|
+
import type { Product } from './generated/types';
|
|
141
|
+
const shop = createContentApi<{ product: Product }>(myClient);
|
|
142
|
+
const { data } = await shop.product.list({ filter: { featured: true }, limit: 4 }); // Product[]
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
`cms` uses the default client chosen per call: on the server (no `window`) the loopback `publicClient()`, in the
|
|
146
|
+
browser a same-origin cookie client. `setDefaultClientFactory(fn)` overrides it (tests).
|
|
147
|
+
|
|
148
|
+
## Customer sign-in (`client.auth`)
|
|
149
|
+
|
|
150
|
+
| Call | What it does |
|
|
151
|
+
| ------------------------------------------------- | ------------------------------------------------------------------------------ |
|
|
152
|
+
| `me()` | `Customer` (`{ id, name, identifiers: [{ id, kind, value, verified }] }`), `null` when signed out |
|
|
153
|
+
| `methods()` | the sign-in methods the admin turned on: `{ email, phone }`, each `{ otp, password }` or `null` |
|
|
154
|
+
| `signIn(returnTo?)` | navigates to `/api/customer/auth/login?returnTo=…` (default: the current path + query; always `utils.safeReturnTo`) |
|
|
155
|
+
| `signOut({ navigate? })` | `POST /api/customer/auth/logout`, then follows its `redirectTo` unless `navigate: false` |
|
|
156
|
+
| `otp.request(uid, identifier)` | `{ resendAfterSec }`, or `{ redirectTo }` when the interaction already ended |
|
|
157
|
+
| `otp.verify(uid, identifier, code, name?)` | `{ redirectTo }` |
|
|
158
|
+
| `password.signIn(uid, identifier, password)` | `{ redirectTo }` |
|
|
159
|
+
| `passwordReset.request(identifier)` / `.confirm(identifier, code, newPassword)` | password reset by code |
|
|
160
|
+
| `followRedirect({ redirectTo })` | navigates there when it is a path or on this origin, otherwise to `/` |
|
|
161
|
+
|
|
162
|
+
The interaction calls (`uid` from the sign-in page's `?uid=`) are what a login page needs; see
|
|
163
|
+
`examples/my-store/app/(site)/account/login/login-forms.tsx`.
|
|
164
|
+
|
|
165
|
+
## Account (`client.account`)
|
|
166
|
+
|
|
167
|
+
`update({ name })`, `password.set(newPassword)` (no password yet), `password.change(currentPassword, newPassword)`,
|
|
168
|
+
`identifiers.add(identifier)` (sends a code), `identifiers.verify(identifier, code)` (→ the updated `Customer`),
|
|
169
|
+
`identifiers.remove(id)`.
|
|
170
|
+
|
|
171
|
+
## React (client components)
|
|
172
|
+
|
|
173
|
+
```tsx
|
|
174
|
+
'use client';
|
|
175
|
+
import { useClient, useCustomer, useSignIn, useSignOut } from '@opencloudcms/client';
|
|
176
|
+
|
|
177
|
+
export function AccountMenu() {
|
|
178
|
+
const { customer, loading, refresh } = useCustomer(); // one me() per provider mount, shared
|
|
179
|
+
const signIn = useSignIn(); // (returnTo?) => void; default returnTo: this page
|
|
180
|
+
const signOut = useSignOut(); // () => Promise<void>: logout, refresh, follow redirectTo
|
|
181
|
+
if (loading) return <span className="h-9 w-24" />;
|
|
182
|
+
return customer ? <button onClick={signOut}>{customer.name}</button> : <button onClick={() => signIn()}>Sign in</button>;
|
|
183
|
+
}
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
`useClient()` gives the provider's client (`.request`, `.auth`, `.account`, `.content`). Call `refresh()` after
|
|
187
|
+
changing the customer (name, identifiers).
|
|
188
|
+
|
|
189
|
+
## Page actions
|
|
190
|
+
|
|
191
|
+
Page actions are defined on the server with `defineAction` (`@opencloudcms/core`, see its README) and attached to
|
|
192
|
+
buttons and forms in the page builder. This package holds the browser half: the **runner** that every trigger (a
|
|
193
|
+
builder button or Form, `useAction` in your code) goes through, and the optional per-action client hooks.
|
|
194
|
+
|
|
195
|
+
Lifecycle of one run: `trigger` → collect the request `{ id, name, params, input?, page? }` (`id`: a fresh UUID) →
|
|
196
|
+
auth gate (an action with `requireCustomer` in the manifest and no session: navigate to
|
|
197
|
+
`<signInPath>?returnTo=<this page>`, or open the page's `sign-in` overlay when it has one) → `beforeRun` → `pending`
|
|
198
|
+
(trigger and the form's submit buttons disabled, `aria-busy`; a second click or submit is ignored) → `POST
|
|
199
|
+
/api/actions/:name` → `onSuccess` / `onError` (or the default) → `settled`. A `401` from the server (the session
|
|
200
|
+
expired since the page loaded) goes to sign-in the same way, without a toast or hook, preferring the server's
|
|
201
|
+
`signIn` path (its configured `loginPath`, exposed as `error.details.signIn`) over `signInPath`. Built-ins: `sign-in`
|
|
202
|
+
(navigate to sign-in, back here), `sign-out` (end the session, refresh `useCustomer`, then `/`) and `navigate-back`.
|
|
203
|
+
|
|
204
|
+
### Client hooks: `defineActionClient`
|
|
205
|
+
|
|
206
|
+
```ts
|
|
207
|
+
// src/actions/place-order.client.ts (browser-only: keep it out of tsconfig.server.json)
|
|
208
|
+
import { defineActionClient } from '@opencloudcms/client';
|
|
209
|
+
|
|
210
|
+
export default defineActionClient<{ code: string }>('place-order', {
|
|
211
|
+
beforeRun: async (req, ui) => ((await ui.confirm('Xác nhận đặt hàng?')) ? req : false), // false cancels
|
|
212
|
+
onSuccess: (res, ui) => ui.navigate(`/account/orders/${encodeURIComponent(res.code)}`), // replaces the default
|
|
213
|
+
onError: (err, ui) => (err.code === 'out_of_stock' ? ui.toast('Hết hàng', 'error') : ui.defaultBehaviour()),
|
|
214
|
+
});
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
```tsx
|
|
218
|
+
// src/actions/client.ts
|
|
219
|
+
'use client';
|
|
220
|
+
import placeOrder from './place-order.client';
|
|
221
|
+
export const clientActions = [placeOrder];
|
|
222
|
+
|
|
223
|
+
// app/providers.tsx
|
|
224
|
+
<OpenCloudCmsProvider signInPath="/account/login" actions={clientActions}>{children}</OpenCloudCmsProvider>
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
- `beforeRun(req, ui)` — return a changed request, `false` to cancel (nothing is sent), or nothing to keep it.
|
|
228
|
+
A throw ends the run (logged).
|
|
229
|
+
- `onSuccess(result, ui)` / `onError(err: ApiError, ui)` — replace the default; call `ui.defaultBehaviour()` to keep
|
|
230
|
+
it. Throws are logged, never propagated.
|
|
231
|
+
- Without a hook the **default**: on success a form resets (unless `resetOnSuccess` is off) and shows "Sent
|
|
232
|
+
successfully." / "Đã gửi thành công."; a button does nothing. On error the issues with `path: ['input', <name>]`
|
|
233
|
+
are shown next to the controls of that name and an error toast shows `errorMessage(err)` (pass `messages` to
|
|
234
|
+
`createClient` for your own codes, e.g. `{ out_of_stock: { 'en-US': 'Sold out', 'vi-VN': 'Hết hàng' } }`).
|
|
235
|
+
- Only one definition per name counts (the last). Client halves never hold secrets or server code: the action's
|
|
236
|
+
server half is never imported in the browser.
|
|
237
|
+
|
|
238
|
+
`ui` (`ActionUi`): `navigate(path)` (same-site only, anything else goes to `/`), `toast(message, tone?)`,
|
|
239
|
+
`confirm(message)` → `Promise<boolean>`, `openOverlay(name)`, `closeOverlay(name?)`, `resetForm()` (the triggering
|
|
240
|
+
form, field errors cleared), `refresh()`, `setFieldErrors(issues)`, `defaultBehaviour()`.
|
|
241
|
+
|
|
242
|
+
### `useAction` in your own components
|
|
243
|
+
|
|
244
|
+
```tsx
|
|
245
|
+
'use client';
|
|
246
|
+
import { useAction } from '@opencloudcms/client';
|
|
247
|
+
|
|
248
|
+
export function ReorderButton({ productId }: { productId: string }) {
|
|
249
|
+
const { run, pending, error } = useAction('place-order');
|
|
250
|
+
return (
|
|
251
|
+
<button disabled={pending} onClick={() => run({ params: { productId } })}>
|
|
252
|
+
{error ? 'Try again' : 'Order again'}
|
|
253
|
+
</button>
|
|
254
|
+
);
|
|
255
|
+
}
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
Same lifecycle, client hooks and events as page triggers. `run({ params?, input?, page?, id? })` resolves to `{ ok,
|
|
259
|
+
result?, error? }` and never throws (`ok: false` without `error`: cancelled or ignored); a second `run()` while one
|
|
260
|
+
is pending returns the same promise (one request). Pass the same `id` to retry one logical call. Without React:
|
|
261
|
+
`client.actions.run(name, { params, input, id })` (throws `ApiError`) and `client.actions.manifest()` (cached 60 s).
|
|
262
|
+
|
|
263
|
+
### Theming: the `ui` adapter
|
|
264
|
+
|
|
265
|
+
The defaults are deliberately plain: `window.confirm`, and a DOM toast (`.ocms-toasts > .ocms-toast[data-tone="success
|
|
266
|
+
| error | info"]`, `role="status"` / `"alert"`, 5 s) whose built-in CSS uses `:where()` so any rule of yours wins. To
|
|
267
|
+
use your design system, pass a `UiAdapter` (every member optional):
|
|
268
|
+
|
|
269
|
+
```tsx
|
|
270
|
+
<OpenCloudCmsProvider
|
|
271
|
+
actions={clientActions}
|
|
272
|
+
ui={{
|
|
273
|
+
toast: (message, tone) => myToast({ title: message, variant: tone === 'error' ? 'destructive' : 'default' }),
|
|
274
|
+
confirm: (message) => myConfirmDialog({ message }), // boolean | Promise<boolean>
|
|
275
|
+
navigate: (path) => router.push(path), // already a safe same-site target
|
|
276
|
+
refresh: () => router.refresh(),
|
|
277
|
+
}}
|
|
278
|
+
>
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
`openOverlay` / `closeOverlay` default to no-ops here; `@opencloudcms/core/blocks` registers its overlay store with
|
|
282
|
+
the runner, so builder overlays work without them. Field errors go into an element `[data-ocms-error-for="<name>"]`
|
|
283
|
+
inside the form when there is one (style or place it yourself), else a generated `span.ocms-field-error` after the
|
|
284
|
+
control; the controls get `aria-invalid="true"` and `aria-describedby`.
|
|
285
|
+
|
|
286
|
+
### Events
|
|
287
|
+
|
|
288
|
+
Every phase dispatches a bubbling `CustomEvent` `opencloudcms:action` (`ACTION_EVENT`) on the trigger (on `document`
|
|
289
|
+
for `useAction` runs), `detail: { name, phase, ok?, code? }`, phases `trigger | pending | success | error |
|
|
290
|
+
settled` (`settled` carries `ok` and the error code, or `cancelled` / `preview_disabled` when nothing was sent). For
|
|
291
|
+
analytics without touching action code:
|
|
292
|
+
|
|
293
|
+
```ts
|
|
294
|
+
document.addEventListener('opencloudcms:action', (e) => {
|
|
295
|
+
const { name, phase, ok, code } = (e as CustomEvent<ActionEventDetail>).detail;
|
|
296
|
+
if (phase === 'settled') analytics.track('action', { name, ok, code });
|
|
297
|
+
});
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
### Draft preview and the low-level runner
|
|
301
|
+
|
|
302
|
+
In a draft preview (`core/blocks` puts the runner in preview with `runner.setPreview`), only actions whose manifest
|
|
303
|
+
entry sets `previewSafe` (and the built-ins `sign-in`, `navigate-back`) run; others show "Actions are disabled in
|
|
304
|
+
preview". `useActionRunner()` gives the provider's `ActionRunner`; outside React, `new ActionRunner({ client, actions,
|
|
305
|
+
signInPath, ui, getCustomer, onAuthChange }).run(triggerElement | null, { name, params, input, page, form? })` runs the
|
|
306
|
+
same lifecycle.
|
|
307
|
+
|
|
308
|
+
## Next server helpers (server components, route handlers)
|
|
309
|
+
|
|
310
|
+
- `getCustomer()` → `Customer | null` for the current request (forwards its cookie; never cached).
|
|
311
|
+
- `requireCustomer({ returnTo? })` → `Customer`, or `redirect()` to `/api/customer/auth/login?returnTo=…`
|
|
312
|
+
(`returnTo` defaults to the `x-pathname` header, then `next-url`, then `/`).
|
|
313
|
+
- `serverClient(opts?)` — loopback client (`http://127.0.0.1:${PORT ?? 4000}`) that forwards the request's `cookie`
|
|
314
|
+
header (only to the loopback origin); requests default to `cache: 'no-store'`. Makes the page dynamic.
|
|
315
|
+
- `publicClient(opts?)` — loopback client without cookies, so pages stay static/cacheable (`next: { revalidate, tags }`
|
|
316
|
+
pass through).
|
|
317
|
+
- `loopbackUrl()` — the loopback base URL, read per call.
|
|
318
|
+
|
|
319
|
+
```tsx
|
|
320
|
+
// app/(site)/orders/page.tsx
|
|
321
|
+
import { requireCustomer, serverClient } from '@opencloudcms/client';
|
|
322
|
+
|
|
323
|
+
export default async function Orders() {
|
|
324
|
+
await requireCustomer({ returnTo: '/orders' });
|
|
325
|
+
const { data } = await serverClient().request<{ data: Order[] }>('GET', '/api/store/orders');
|
|
326
|
+
return <OrderList orders={data} />;
|
|
327
|
+
}
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
## Utilities (`utils`)
|
|
331
|
+
|
|
332
|
+
Only through the `utils` object:
|
|
333
|
+
|
|
334
|
+
- `utils.formatMoney({ amount, currency }, locale)`, `utils.formatDate(value, locale, 'date' | 'datetime')`.
|
|
335
|
+
- `utils.normalizeIdentifier(raw, region)` → `{ kind: 'email' | 'phone', value }` or `null` (same rules as the
|
|
336
|
+
server: email lower-cased, phone to E.164; for form validation, the server stays authoritative).
|
|
337
|
+
- `utils.safeReturnTo(path)` — a local path (starts with `/`, no `//`, no `\`, no control characters), else `/`.
|
|
338
|
+
- `utils.buildQuery(params)` — a query string as the content API reads it (`filter[field]=v`, arrays joined by `,`).
|