@seliseblocks/client 0.1.6 → 0.3.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 CHANGED
@@ -1,222 +1,270 @@
1
- # Blocks Client
2
-
3
- Framework-neutral TypeScript SDK for SELISE Blocks frontend and app-runtime code.
4
-
5
- `@seliseblocks/client` gives consumer apps a small, typed wrapper around the Blocks APIs they normally call at runtime: Auth/IAM, Data, Localization, and shared HTTP configuration. Detailed `what / why / how` descriptions are kept on the SDK functions themselves so editors and generated typings show the guidance where developers use the API.
6
-
7
- Admin/control-plane work belongs in `@seliseblocks/cli-os`: project setup, schema/rules deploy, release deploy, and AI/admin terminal workflows.
8
-
9
- For AI agents and automation, see [AI_USAGE_GUIDE.md](AI_USAGE_GUIDE.md).
10
-
11
- ## Install
12
-
13
- ```bash
14
- npm install @seliseblocks/client@latest
15
- ```
16
-
17
- Requires Node.js 20+ or a browser/runtime with `fetch`.
18
-
19
- ## Create A Client
20
-
21
- ```ts
22
- import { createBlocksClient } from "@seliseblocks/client";
23
-
24
- const blocks = createBlocksClient({
25
- apiUrl: "https://api.seliseblocks.com",
26
- xBlocksKey: "<blocks-key>",
27
- accessToken: () => currentUserSession?.accessToken,
28
- oidc: {
29
- url: "https://iam.seliseblocks.com",
30
- clientId: "<public-browser-client-id>",
31
- redirectUri: configuredRedirectUri ?? `${window.location.origin}/login/callback`
32
- }
33
- });
34
- ```
35
-
36
- `xBlocksKey` is always sent as the `x-blocks-key` header. Do not send `ProjectKey` or `projectKey` in request query/body payloads.
37
-
38
- The SDK does not store tokens. Your app owns login state, refresh scheduling, storage, and logout cleanup.
39
-
40
- Use a configured OIDC redirect URI when your app has one. The current-origin `/login/callback` URL is only a browser fallback.
41
-
42
- ## Auth
43
-
44
- Auth has two login flows.
45
-
46
- OIDC/hosted IAM login uses `auth.idp`. The SDK relies on Blocks IAM `IdpController`, sends the configured public `clientId`, and does not manually build `oidc/authorize` URLs. Refresh OIDC sessions with `auth.oidc.refreshToken()`, which calls `/iam/v4/oidc/token` and sends `client_id`.
47
-
48
- ```ts
49
- await blocks.auth.idp.redirectToProvider();
50
-
51
- const result = await blocks.auth.idp.callback(window.location.href);
52
-
53
- const refreshed = await blocks.auth.oidc.refreshToken({
54
- refreshToken: result.refresh_token,
55
- clientId: "<public-browser-client-id>"
56
- });
57
- ```
58
-
59
- Embedded/app-owned login UI uses AuthController methods directly on `auth`: `auth.login()`, `auth.socialInitiate(clientId, redirectUri)` (two positional strings, not an object), `auth.socialCallback(request)`, and `auth.refresh()`.
60
-
61
- ```ts
62
- const login = await blocks.auth.login({
63
- username: "user@example.com",
64
- password: "password"
65
- });
66
-
67
- const refreshed = await blocks.auth.refresh({
68
- refreshToken: login.refresh_token
69
- });
70
- ```
71
-
72
- Other auth APIs, such as user info, organization switch, logout, signup, recovery, activation, auth config, user codes, client credentials, and identity providers, can be used by either flow when the app has the required token/permission.
73
-
74
- `auth.oidc.clientCredentials()` is for trusted non-browser runtimes only because it requires a client secret.
75
-
76
- `auth.accessToken()` resolves the caller-owned bearer token configured on `createBlocksClient` (string or callback). `auth.isAuthenticated()` checks the current session against IAM through `GET /iam/v4/auth/me` and returns a boolean based on the raw response status - use it instead of `userInfo()` when you need a true/false signal, since IAM's hosted IdP flow may set the session as a cookie with no local `accessToken` to inspect.
77
-
78
- ```ts
79
- const config = await blocks.mfa.config();
80
- await blocks.mfa.totp.setup();
81
- await blocks.mfa.totp.verifySetup({ code: "123456" });
82
- await blocks.mfa.setMethod({ mfaType: 1 });
83
- const backupCodes = await blocks.mfa.backupCodes.generate();
84
- ```
85
-
86
- ## Mail And Notifications
87
-
88
- ```ts
89
- await blocks.mail.send({
90
- to: ["user@example.com"],
91
- purpose: "welcome",
92
- language: "en",
93
- subjectDataContext: { firstName: "Ada" }
94
- });
95
-
96
- await blocks.mail.sendToAny({
97
- to: ["qa@example.com"],
98
- purpose: "welcome",
99
- language: "en",
100
- isTestMail: true
101
- });
102
-
103
- await blocks.notifier.notify({
104
- userIds: ["user-id"],
105
- denormalizedPayload: JSON.stringify({ orderId: "123" }),
106
- saveDenormalizedPayloadAsAnObject: true
107
- });
108
-
109
- const inbox = await blocks.notifier.getNotifications({ isUnreadOnly: true, page: 1, pageSize: 20 });
110
- await blocks.notifier.markNotificationAsRead({ id: inbox.notifications[0].id });
111
- await blocks.notifier.markAllNotificationAsRead();
112
- ```
113
-
114
- `mail.send`/`mail.sendToAny` call `/logic/v4/Mail/Send`/`SendToAny`. `notifier.*` calls `/logic/v4/Notifier/*`
115
- for sending/reading notifications; tenant notification *channel configuration* (`/os/v4/Notification/*`)
116
- is an admin concern handled by `@seliseblocks/cli-os`'s `notification *` commands, not this SDK.
117
-
118
- ## Common Runtime Calls
119
-
120
- ```ts
121
- const me = await blocks.iam.me();
122
- const orgs = await blocks.iam.organizations.my();
123
- const features = await blocks.iam.resources.features();
124
- ```
125
-
126
- `iam.organizations.my()` returns the IAM envelope with `organizations`, not `data`.
127
-
128
- ```ts
129
- const schemas = await blocks.data.schemas.list();
130
- const schemaInfo = await blocks.data.schemas.infoByName("Student");
131
- const schemaRules = await blocks.data.validations.bySchemaId("schema-id");
132
-
133
- const students = blocks.data.collection("Students");
134
- const rows = await students.list({ pageNo: 1, pageSize: 20 });
135
- await students.create({ firstName: "Test" });
136
-
137
- const graph = await blocks.data.graphql({
138
- query: "{ students { items { itemId firstName } } }"
139
- });
140
- ```
141
-
142
- ```ts
143
- const upload = await blocks.data.files.presignedUploadUrl({
144
- name: "avatar.png",
145
- configurationName: "default",
146
- parentDirectoryId: "root",
147
- accessModifier: "Private"
148
- });
149
-
150
- await blocks.data.files.uploadToUrl({
151
- url: upload.uploadUrl,
152
- body: file,
153
- contentType: file.type
154
- });
155
-
156
- const items = await blocks.data.objects.list({
157
- parentDirectoryId: "root",
158
- limit: 20
159
- });
160
-
161
- const directory = await blocks.data.directories.create({
162
- name: "Contracts",
163
- parentDirectoryId: "root",
164
- allowedFileExtensions: ["pdf", "docx"]
165
- });
166
- ```
167
-
168
- ```ts
169
- await blocks.localization.load("en-US", ["common", "dashboard"]);
170
- const label = blocks.localization.t("dashboard.title", "Dashboard");
171
-
172
- const tenantLanguages = await blocks.localization.languagesForCurrentTenant();
173
- const selectedKeys = await blocks.localization.keysByNames({
174
- keyNames: ["dashboard.title"]
175
- });
176
- ```
177
-
178
- ## API Surface
179
-
180
- - `blocks.auth`: AuthController login, social login, refresh, org switch, logout, signup, recovery, activation, auth config, user codes, client credentials, identity providers.
181
- - `blocks.auth.idp`: hosted IdP initiate, browser redirect, callback, UI config.
182
- - `blocks.auth.oidc`: refresh-token and client-credentials token endpoint helpers.
183
- - `blocks.iam`: current user, users, roles, permissions, resources, organizations, signup settings (`blocks.iam.signupSettings`).
184
- - `blocks.data`: schema reads, validation reads, GraphQL gateway execution, file/directory/object-tree storage helpers, and runtime collection CRUD.
185
- - `blocks.localization`: tenant language/module discovery, UILM dictionary loading, selected key lookup, simple `t()` lookup.
186
- - `blocks.mfa`: tenant MFA policy read/save, TOTP enrollment, OTP generate/resend/verify, method switch, disable, and backup codes.
187
- - `blocks.mail`: `send`/`sendToAny` transactional email through the tenant's configured mail provider.
188
- - `blocks.notifier`: `notify`, `getNotifications`, `getUnreadNotificationsBySubscriptionFilter`, `markNotificationAsRead`, `markAllNotificationAsRead`.
189
-
190
- Professional class names are exported for advanced typing and adapters: `BlocksAuthenticationClient`, `BlocksIAMClient`, `BlocksDataClient`, `BlocksLocalizationClient`, `BlocksMfaClient`, `BlocksMailClient`, and `BlocksNotifierClient`. `BlocksApiError` is exported for typed error handling - every non-2xx response from `http.request`/`http.external` throws it, exposing `status`, `statusText`, and the parsed `body`:
191
-
192
- ```ts
193
- try {
194
- await blocks.iam.me();
195
- } catch (error) {
196
- if (error instanceof BlocksApiError) {
197
- console.error(error.status, error.body);
198
- }
199
- }
200
- ```
201
-
202
- ## Boundaries
203
-
204
- This package must not contain:
205
-
206
- - CLI client secrets
207
- - impersonation APIs
208
- - project create/list/use
209
- - schema/rules deploy
210
- - release deploy
211
- - token/session/PKCE storage
212
- - Node filesystem or OS credential storage
213
- - framework UI components
214
- - Localization authoring/admin endpoints
215
- - Data schema/rules mutation endpoints
216
-
217
- ## Package Checks
218
-
219
- ```bash
220
- npm test
221
- npm pack --dry-run
222
- ```
1
+ # Blocks Client
2
+
3
+ Framework-neutral TypeScript SDK for SELISE Blocks frontend and app-runtime code.
4
+
5
+ [`@seliseblocks/client`](https://www.npmjs.com/package/@seliseblocks/client) gives consumer apps a small, typed wrapper around the Blocks APIs they normally call at runtime: Auth/IAM, Data, Localization, and shared HTTP configuration. Detailed `what / why / how` descriptions are kept on the SDK functions themselves so editors and generated typings show the guidance where developers use the API.
6
+
7
+ Admin/control-plane work belongs in `@seliseblocks/cli-os`: project setup, schema/rules deploy, release deploy, and AI/admin terminal workflows.
8
+
9
+ For AI agents and automation, see [AGENT_GUIDE.md](AGENT_GUIDE.md).
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ npm install @seliseblocks/client@latest
15
+ ```
16
+
17
+ Requires Node.js 20+ or a browser/runtime with `fetch`.
18
+
19
+ ## Create A Client
20
+
21
+ ```ts
22
+ import { createBlocksClient } from "@seliseblocks/client";
23
+
24
+ const blocks = createBlocksClient({
25
+ apiUrl: "https://api.seliseblocks.com",
26
+ xBlocksKey: "<blocks-key>",
27
+ accessToken: () => currentUserSession?.accessToken,
28
+ oidc: {
29
+ url: "https://iam.seliseblocks.com",
30
+ clientId: "<public-browser-client-id>",
31
+ redirectUri: configuredRedirectUri ?? `${window.location.origin}/login/callback`
32
+ }
33
+ });
34
+ ```
35
+
36
+ `xBlocksKey` is always sent as the `x-blocks-key` header. Do not send `ProjectKey` or `projectKey` in request query/body payloads.
37
+
38
+ The SDK does not store tokens. Your app owns login state, refresh scheduling, storage, and logout cleanup.
39
+
40
+ `blocks.config` reads back the resolved settings (`apiUrl`, `xBlocksKey`,
41
+ `appDomain`, `oidc`). It deliberately excludes your `accessToken` resolver and
42
+ `onUnauthorized` hook, so the client never doubles as a place to read a live
43
+ session out of; use `await blocks.auth.accessToken()` when you need the token.
44
+
45
+ `http.request()` only ever talks to the configured `apiUrl` — it attaches your
46
+ bearer token, `x-blocks-key`, and cookies, so an absolute URL on another origin
47
+ is refused rather than handed a live session. Use `http.external(url)` for
48
+ third-party URLs such as a pre-signed storage upload; it sends no Blocks
49
+ credentials.
50
+
51
+ Use a configured OIDC redirect URI when your app has one. The current-origin `/login/callback` URL is only a browser fallback.
52
+
53
+ ## Auth
54
+
55
+ Auth has two login flows.
56
+
57
+ OIDC/hosted IAM login uses `auth.idp`. The SDK relies on Blocks IAM `IdpController`, sends the configured public `clientId`, and does not manually build `oidc/authorize` URLs. Refresh OIDC sessions with `auth.oidc.refreshToken()`, which calls `/iam/v4/oidc/token` and sends `client_id`.
58
+
59
+ ```ts
60
+ await blocks.auth.idp.redirectToProvider();
61
+
62
+ const result = await blocks.auth.idp.callback(window.location.href);
63
+
64
+ const refreshed = await blocks.auth.oidc.refreshToken({
65
+ refreshToken: result.refresh_token,
66
+ clientId: "<public-browser-client-id>"
67
+ });
68
+ ```
69
+
70
+ Embedded/app-owned login UI uses AuthController methods directly on `auth`: `auth.login()`, `auth.socialInitiate(clientId, redirectUri)` (two positional strings, not an object), `auth.socialCallback(request)`, and `auth.refresh()`.
71
+
72
+ ```ts
73
+ const login = await blocks.auth.login({
74
+ username: "user@example.com",
75
+ password: "password"
76
+ });
77
+
78
+ const refreshed = await blocks.auth.refresh({
79
+ refreshToken: login.refresh_token
80
+ });
81
+ ```
82
+
83
+ Other auth APIs, such as user info, organization switch, logout, signup, recovery, activation, auth config, user codes, client credentials, and identity providers, can be used by either flow when the app has the required token/permission.
84
+
85
+ `auth.oidc.clientCredentials()` is for trusted non-browser runtimes only because it requires a client secret.
86
+
87
+ `auth.accessToken()` resolves the caller-owned bearer token configured on `createBlocksClient` (string or callback). `auth.isAuthenticated()` checks the current session against IAM through `GET /iam/v4/auth/me` and returns a boolean based on the raw response status - use it instead of `userInfo()` when you need a true/false signal, since IAM's hosted IdP flow may set the session as a cookie with no local `accessToken` to inspect.
88
+
89
+ ## MFA
90
+
91
+ `blocks.mfa` covers the signed-in user's own multi-factor setup — TOTP
92
+ enrollment, OTP challenges, switching the active method, and backup codes —
93
+ plus `mfa.saveConfig()` for tenant-wide MFA policy, which needs an admin
94
+ token.
95
+
96
+ ```ts
97
+ const config = await blocks.mfa.config();
98
+ await blocks.mfa.totp.setup();
99
+ await blocks.mfa.totp.verifySetup({ code: "123456" });
100
+ await blocks.mfa.setMethod({ mfaType: 1 });
101
+ const backupCodes = await blocks.mfa.backupCodes.generate();
102
+ ```
103
+
104
+ ## Mail And Notifications
105
+
106
+ ```ts
107
+ await blocks.mail.send({
108
+ to: ["user@example.com"],
109
+ purpose: "welcome",
110
+ language: "en",
111
+ subjectDataContext: { firstName: "Ada" }
112
+ });
113
+
114
+ await blocks.mail.sendToAny({
115
+ to: ["qa@example.com"],
116
+ purpose: "welcome",
117
+ language: "en",
118
+ isTestMail: true
119
+ });
120
+
121
+ await blocks.notifier.notify({
122
+ configurationName: "in-app", // the `name` of a notification configuration in this project
123
+ userIds: ["user-id"],
124
+ denormalizedPayload: JSON.stringify({ orderId: "123" }),
125
+ saveDenormalizedPayloadAsAnObject: true
126
+ });
127
+
128
+ const inbox = await blocks.notifier.getNotifications({ isUnreadOnly: true, page: 1, pageSize: 20 });
129
+ await blocks.notifier.markNotificationAsRead({ id: inbox.notifications[0].id });
130
+ await blocks.notifier.markAllNotificationAsRead();
131
+ ```
132
+
133
+ `mail.send`/`mail.sendToAny` call `/logic/v4/Mail/Send`/`SendToAny`. `notifier.*` calls `/logic/v4/Notifier/*`
134
+ for sending/reading notifications; tenant notification *channel configuration* (`/os/v4/Notification/*`)
135
+ is an admin concern handled by `@seliseblocks/cli-os`'s `notification *` commands, not this SDK.
136
+
137
+ ## Functions And Proxies
138
+
139
+ ```ts
140
+ // A deployed Blocks function -- sync or async, you get the value:
141
+ const quote = await blocks.logic.functions.call<{ total: number }>("<functionId>", {
142
+ path: "quotes",
143
+ body: { items: [{ sku: "A1", qty: 2 }] }
144
+ });
145
+
146
+ // Or the transport-level result:
147
+ const outcome = await blocks.logic.functions.invoke("<functionId>", { respondAsync: true });
148
+ if (outcome.kind === "accepted") {
149
+ const run = await blocks.logic.functions.waitForResult(outcome, { timeoutMs: 30_000 });
150
+ }
151
+
152
+ // A third-party API through a Blocks proxy (upstream URL and keys stay server-side):
153
+ const charge = await blocks.logic.proxy.request("stripe", { path: "charges/ch_123" });
154
+ ```
155
+
156
+ A failed or timed-out run throws `BlocksFunctionRunError`; platform refusals throw `BlocksApiError`
157
+ (`body.code` is `FUNCTION_INVOKE_*` or `PROXY_GATEWAY_*`). `invokeRaw()` returns the unread `Response`
158
+ for streaming handlers. Creating, saving and deploying functions and configuring proxies is CLI work
159
+ (`blocks logic function|proxy *`).
160
+
161
+ Writing a function? Its handler types ship type-only under a subpath:
162
+
163
+ ```js
164
+ /** @type {import("@seliseblocks/client/functions").FunctionHandler} */
165
+ export default async function handler(input, ctx) {
166
+ ctx.log.info("called", { path: input.path });
167
+ return { ok: true, region: ctx.env.REGION };
168
+ }
169
+ ```
170
+
171
+ ## Common Runtime Calls
172
+
173
+ ```ts
174
+ const me = await blocks.iam.me();
175
+ const orgs = await blocks.iam.organizations.my();
176
+ const features = await blocks.iam.resources.features();
177
+ ```
178
+
179
+ `iam.organizations.my()` returns the IAM envelope with `organizations`, not `data`.
180
+
181
+ ```ts
182
+ const schemas = await blocks.data.schemas.list();
183
+ const schemaInfo = await blocks.data.schemas.infoByName("Student");
184
+ const schemaRules = await blocks.data.validations.bySchemaId("schema-id");
185
+
186
+ const students = blocks.data.collection("Students");
187
+ const rows = await students.list({ pageNo: 1, pageSize: 20 });
188
+ await students.create({ firstName: "Test" });
189
+
190
+ const graph = await blocks.data.graphql({
191
+ query: "{ students { items { itemId firstName } } }"
192
+ });
193
+ ```
194
+
195
+ ```ts
196
+ const upload = await blocks.data.files.presignedUploadUrl({
197
+ name: "avatar.png",
198
+ configurationName: "default",
199
+ parentDirectoryId: "root",
200
+ accessModifier: "Private"
201
+ });
202
+
203
+ await blocks.data.files.uploadToUrl({
204
+ url: upload.uploadUrl,
205
+ body: file,
206
+ contentType: file.type
207
+ });
208
+
209
+ const items = await blocks.data.objects.list({
210
+ parentDirectoryId: "root",
211
+ limit: 20
212
+ });
213
+
214
+ const directory = await blocks.data.directories.create({
215
+ name: "Contracts",
216
+ parentDirectoryId: "root",
217
+ allowedFileExtensions: ["pdf", "docx"]
218
+ });
219
+ ```
220
+
221
+ ```ts
222
+ await blocks.localization.load("en-US", ["common", "dashboard"]);
223
+ const label = blocks.localization.t("dashboard.title", "Dashboard");
224
+
225
+ const tenantLanguages = await blocks.localization.languagesForCurrentTenant();
226
+ const selectedKeys = await blocks.localization.keysByNames({
227
+ keyNames: ["dashboard.title"]
228
+ });
229
+ ```
230
+
231
+ ## API Surface
232
+
233
+ See [`AGENT_GUIDE.md`](AGENT_GUIDE.md)'s Service Map for the full method-level
234
+ list under `blocks.auth`, `blocks.iam`, `blocks.data`, `blocks.localization`,
235
+ `blocks.logic`, `blocks.mfa`, `blocks.mail`, and `blocks.notifier`.
236
+
237
+ Professional class names are exported for advanced typing and adapters: `BlocksAuthenticationClient`, `BlocksIAMClient`, `BlocksDataClient`, `BlocksLocalizationClient`, `BlocksLogicClient` (with `BlocksFunctionsClient` / `BlocksProxyClient` and `BlocksFunctionRunError`), `BlocksMfaClient`, `BlocksMailClient`, and `BlocksNotifierClient`. `BlocksApiError` is exported for typed error handling - every non-2xx response from `http.request`/`http.external` throws it, exposing `status`, `statusText`, and the parsed `body`. That holds even when the body is not really JSON: a proxy or WAF answering with an HTML error page under a JSON content type surfaces as a `BlocksApiError` carrying the status and the raw text, not as a `SyntaxError`.
238
+
239
+ ```ts
240
+ try {
241
+ await blocks.iam.me();
242
+ } catch (error) {
243
+ if (error instanceof BlocksApiError) {
244
+ console.error(error.status, error.body);
245
+ }
246
+ }
247
+ ```
248
+
249
+ ## Boundaries
250
+
251
+ This package must not contain:
252
+
253
+ - CLI client secrets
254
+ - impersonation APIs
255
+ - project create/list/use
256
+ - schema/rules deploy
257
+ - release deploy
258
+ - token/session/PKCE storage
259
+ - Node filesystem or OS credential storage
260
+ - framework UI components
261
+ - Localization authoring/admin endpoints
262
+ - Data schema/rules mutation endpoints
263
+ - Function create/save/deploy or proxy configuration endpoints
264
+
265
+ ## Package Checks
266
+
267
+ ```bash
268
+ npm test
269
+ npm pack --dry-run
270
+ ```
@@ -1,10 +1,10 @@
1
- import type { RequiredConfig } from "../client.js";
1
+ import type { BlocksResolvedConfig } from "../client.js";
2
2
  import type { BlocksAuthJsonOptions, BlocksAuthLoginRequest, BlocksAuthPassThroughResponse, BlocksAuthResponse, BlocksClientCredentialsRequest, BlocksIdpCallbackRequest, BlocksIdpInitiateRequest, BlocksIdpInitiateResponse, BlocksLoginOption, BlocksLogoutRequest, BlocksOidcRefreshRequest, BlocksOidcUserInfo, BlocksRefreshRequest, BlocksSocialLoginRequest, BlocksSwitchOrganizationRequest } from "./types.js";
3
- export type { BlocksAuthLoginRequest, BlocksAuthPassThroughResponse, BlocksAuthResponse, BlocksClientCredentialsRequest, BlocksIdpCallbackRequest, BlocksIdpInitiateRequest, BlocksIdpInitiateResponse, BlocksLoginOption, BlocksLogoutRequest, BlocksOidcRefreshRequest, BlocksOidcUserInfo, BlocksRefreshRequest, BlocksSocialLoginRequest, BlocksSwitchOrganizationRequest } from "./types.js";
3
+ export type { BlocksAuthJsonOptions, BlocksAuthLoginRequest, BlocksAuthPassThroughResponse, BlocksAuthResponse, BlocksClientCredentialsRequest, BlocksIdpCallbackRequest, BlocksIdpInitiateRequest, BlocksIdpInitiateResponse, BlocksLoginOption, BlocksLogoutRequest, BlocksOidcRefreshRequest, BlocksOidcUserInfo, BlocksRefreshRequest, BlocksSocialLoginRequest, BlocksSwitchOrganizationRequest } from "./types.js";
4
4
  export declare class BlocksAuthenticationClient {
5
5
  private readonly clientConfig;
6
6
  private readonly fetchImpl;
7
- constructor(clientConfig: RequiredConfig, fetchImpl?: typeof fetch);
7
+ constructor(clientConfig: BlocksResolvedConfig, fetchImpl?: typeof fetch);
8
8
  /**
9
9
  * What: discovers tenant login options through `GET /iam/v4/auth/login-options`.
10
10
  * Why: login screens need to know which login methods the tenant supports before rendering controls.
@@ -38,7 +38,8 @@ export declare class BlocksAuthenticationClient {
38
38
  /**
39
39
  * What: switches the active organization through `POST /iam/v4/auth/switch-org`.
40
40
  * Why: multi-organization users need a new IAM response for the selected organization context.
41
- * How: pass `organizationId` plus the refresh/session fields IAM expects; then replace app-owned session state with the response if needed.
41
+ * How: pass `organizationId` (sent as IAM's `organization_id`). IAM reads the refresh token from the session
42
+ * cookie, so call it from a browser session; then replace app-owned session state with the response if needed.
42
43
  */
43
44
  switchOrganization(request: BlocksSwitchOrganizationRequest): Promise<BlocksAuthResponse>;
44
45
  /**
@@ -62,10 +62,15 @@ export class BlocksAuthenticationClient {
62
62
  /**
63
63
  * What: switches the active organization through `POST /iam/v4/auth/switch-org`.
64
64
  * Why: multi-organization users need a new IAM response for the selected organization context.
65
- * How: pass `organizationId` plus the refresh/session fields IAM expects; then replace app-owned session state with the response if needed.
65
+ * How: pass `organizationId` (sent as IAM's `organization_id`). IAM reads the refresh token from the session
66
+ * cookie, so call it from a browser session; then replace app-owned session state with the response if needed.
66
67
  */
67
68
  switchOrganization(request) {
68
- return this.json("/iam/v4/auth/switch-org", { body: request });
69
+ // refreshToken is dropped: IAM never reads it from this body, so sending it only spreads a secret.
70
+ const { organizationId, refreshToken: _unused, ...rest } = request;
71
+ return this.json("/iam/v4/auth/switch-org", {
72
+ body: { ...rest, organization_id: rest.organization_id ?? organizationId }
73
+ });
69
74
  }
70
75
  /**
71
76
  * What: reads OIDC-style current-user info through `GET /iam/v4/auth/me`.
@@ -55,7 +55,12 @@ export type BlocksLogoutRequest = Record<string, unknown> & {
55
55
  refreshToken?: string;
56
56
  };
57
57
  export type BlocksSwitchOrganizationRequest = Record<string, unknown> & {
58
+ /** Sent as IAM's `organization_id`. */
58
59
  organizationId?: string;
60
+ /**
61
+ * @deprecated Not sent. IAM's switch-org reads the refresh token only from the
62
+ * session cookie (or its `rt_<domain>` header), never from the body.
63
+ */
59
64
  refreshToken?: string;
60
65
  };
61
66
  export type BlocksOidcRefreshRequest = {
package/dist/client.d.ts CHANGED
@@ -3,6 +3,7 @@ import { BlocksDataClient } from "./data/data-client.js";
3
3
  import { BlocksHttpClient } from "./http/http-client.js";
4
4
  import { BlocksIAMClient } from "./iam/iam-client.js";
5
5
  import { BlocksLocalizationClient } from "./localization/localization-client.js";
6
+ import { BlocksLogicClient } from "./logic/logic-client.js";
6
7
  import { BlocksMailClient } from "./mail/mail-client.js";
7
8
  import { BlocksMfaClient } from "./mfa/mfa-client.js";
8
9
  import { BlocksNotifierClient } from "./notifier/notifier-client.js";
@@ -58,18 +59,33 @@ export type BlocksClientConfig = {
58
59
  */
59
60
  xBlocksKey: string;
60
61
  };
62
+ /**
63
+ * The resolved configuration a client exposes on `blocks.config`: the settings
64
+ * an app may want to read back (which tenant, which API, which OIDC client),
65
+ * with the caller-owned `accessToken` resolver and `onUnauthorized` hook left
66
+ * out. Those two are callables that reach live credentials, and this package's
67
+ * boundary is that it never becomes a place to read a session from -- use
68
+ * `blocks.auth.accessToken()` when you need the token itself.
69
+ */
70
+ export type BlocksPublicConfig = Omit<BlocksResolvedConfig, "accessToken" | "onUnauthorized">;
61
71
  export type BlocksClient = {
62
72
  auth: BlocksAuthenticationClient;
63
- config: Readonly<RequiredConfig>;
73
+ config: Readonly<BlocksPublicConfig>;
64
74
  data: BlocksDataClient;
65
75
  http: BlocksHttpClient;
66
76
  iam: BlocksIAMClient;
67
77
  localization: BlocksLocalizationClient;
78
+ logic: BlocksLogicClient;
68
79
  mail: BlocksMailClient;
69
80
  mfa: BlocksMfaClient;
70
81
  notifier: BlocksNotifierClient;
71
82
  };
72
- export type RequiredConfig = {
83
+ /**
84
+ * `BlocksClientConfig` after defaults are applied -- the shape the internal
85
+ * service clients are constructed with. Consumers normally want
86
+ * `BlocksPublicConfig` (what `blocks.config` actually exposes) instead.
87
+ */
88
+ export type BlocksResolvedConfig = {
73
89
  accessToken?: string | (() => Promise<string | undefined> | string | undefined);
74
90
  apiUrl: string;
75
91
  appDomain?: string;
@@ -80,9 +96,11 @@ export type RequiredConfig = {
80
96
  };
81
97
  xBlocksKey: string;
82
98
  };
99
+ /** @deprecated Renamed to `BlocksResolvedConfig` for consistency with the other exported names. */
100
+ export type RequiredConfig = BlocksResolvedConfig;
83
101
  /**
84
102
  * What: creates a framework-neutral Blocks SDK instance for one tenant/app runtime.
85
- * Why: frontend code needs a single configured entry point for IAM, Auth, Data, and Localization APIs.
103
+ * Why: frontend code needs a single configured entry point for IAM, Auth, Data, Localization and Logic (functions, proxies) APIs.
86
104
  * How: pass `apiUrl` and `xBlocksKey`; optionally pass an `accessToken` callback and OIDC config. The SDK never adds `ProjectKey` and never stores tokens.
87
105
  */
88
106
  export declare function createBlocksClient(config: BlocksClientConfig): BlocksClient;
package/dist/client.js CHANGED
@@ -3,25 +3,28 @@ import { BlocksDataClient } from "./data/data-client.js";
3
3
  import { BlocksHttpClient } from "./http/http-client.js";
4
4
  import { BlocksIAMClient } from "./iam/iam-client.js";
5
5
  import { BlocksLocalizationClient } from "./localization/localization-client.js";
6
+ import { BlocksLogicClient } from "./logic/logic-client.js";
6
7
  import { BlocksMailClient } from "./mail/mail-client.js";
7
8
  import { BlocksMfaClient } from "./mfa/mfa-client.js";
8
9
  import { BlocksNotifierClient } from "./notifier/notifier-client.js";
9
10
  /**
10
11
  * What: creates a framework-neutral Blocks SDK instance for one tenant/app runtime.
11
- * Why: frontend code needs a single configured entry point for IAM, Auth, Data, and Localization APIs.
12
+ * Why: frontend code needs a single configured entry point for IAM, Auth, Data, Localization and Logic (functions, proxies) APIs.
12
13
  * How: pass `apiUrl` and `xBlocksKey`; optionally pass an `accessToken` callback and OIDC config. The SDK never adds `ProjectKey` and never stores tokens.
13
14
  */
14
15
  export function createBlocksClient(config) {
15
16
  const normalized = normalizeConfig(config);
16
17
  const auth = new BlocksAuthenticationClient(normalized, config.fetch);
17
18
  const http = new BlocksHttpClient(normalized, auth, config.fetch);
19
+ const { accessToken: _accessToken, onUnauthorized: _onUnauthorized, ...publicConfig } = normalized;
18
20
  return {
19
21
  auth,
20
- config: normalized,
22
+ config: publicConfig,
21
23
  data: new BlocksDataClient(http),
22
24
  http,
23
25
  iam: new BlocksIAMClient(http),
24
26
  localization: new BlocksLocalizationClient(http),
27
+ logic: new BlocksLogicClient(http, normalized.apiUrl),
25
28
  mail: new BlocksMailClient(http),
26
29
  mfa: new BlocksMfaClient(http),
27
30
  notifier: new BlocksNotifierClient(http)