@seliseblocks/client 0.2.0 → 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/AGENT_GUIDE.md CHANGED
@@ -1,165 +1,176 @@
1
- # Blocks Client Guide for AI Agents
2
-
3
- Use this file only for `@seliseblocks/client` app-code work. For full method details, read the source docstrings.
4
-
5
- Source refs:
6
-
7
- - Client setup: `src/client.ts`
8
- - Auth: `src/auth/auth-client.ts`
9
- - IAM: `src/iam/iam-client.ts`
10
- - Data: `src/data/data-client.ts`
11
- - Localization: `src/localization/localization-client.ts`
12
- - MFA: `src/mfa/mfa-client.ts`
13
- - HTTP/errors: `src/http/http-client.ts`, `src/http/errors.ts`
14
-
15
- ## Non-Negotiable Rules
16
-
17
- - Configure `xBlocksKey`; SDK sends it as `x-blocks-key`.
18
- - Do not send `ProjectKey` or `projectKey`.
19
- - Do not add `/api` after `/v4`.
20
- - Valid route shapes: `/iam/v4/...`, `/data/v4/...`, `/localization/v4/...`.
21
- - SDK does not store tokens. App owns access token, refresh token, storage, and logout cleanup.
22
- - Frontend code must not contain client secrets.
23
- - Do not add impersonation, release deploy, schema/rules mutation, or localization authoring/admin APIs.
24
-
25
- ## Create Client
26
-
27
- ```ts
28
- import { createBlocksClient } from "@seliseblocks/client";
29
-
30
- export const blocks = createBlocksClient({
31
- apiUrl: "https://api.seliseblocks.com",
32
- xBlocksKey: env.BLOCKS_KEY,
33
- accessToken: () => session.accessToken,
34
- oidc: {
35
- url: "https://iam.seliseblocks.com",
36
- clientId: env.OIDC_CLIENT_ID,
37
- redirectUri: env.OIDC_REDIRECT_URI ?? `${window.location.origin}/login/callback`
38
- }
39
- });
40
- ```
41
-
42
- Use `accessToken` only for the current token resolver. Do not add SDK token storage.
43
- Use a configured `redirectUri` when available; the current-origin `/login/callback` URL is only a browser fallback.
44
-
45
- ## Auth Decision
46
-
47
- There are two auth flows.
48
-
49
- OIDC/hosted IAM flow:
50
-
51
- - Login: `blocks.auth.idp.initiate()`, `blocks.auth.idp.redirectToProvider()`, `blocks.auth.idp.callback(...)`
52
- - Refresh: `blocks.auth.oidc.refreshToken({ refreshToken })`
53
- - Refresh route: `POST /iam/v4/oidc/token`
54
- - Must send `client_id`; SDK uses `request.clientId` or configured `oidc.clientId`.
55
- - Do not manually build `oidc/authorize`.
56
-
57
- Embedded/app-owned flow:
58
-
59
- - Login: `blocks.auth.login(...)`
60
- - Social: `blocks.auth.socialInitiate(clientId, redirectUri)` (two positional strings), `blocks.auth.socialCallback(request)` (object)
61
- - Refresh: `blocks.auth.refresh({ refreshToken })`
62
- - Routes: `/iam/v4/auth/login`, `/iam/v4/auth/social/*`, `/iam/v4/auth/refresh`
63
-
64
- Shared auth methods for both flows:
65
-
66
- - `userInfo()`
67
- - `switchOrganization(...)`
68
- - `logout(...)`, `logoutAll(...)`
69
- - `signup(...)`, `recover(...)`, `resetPassword(...)`
70
- - `changePassword(...)`
71
- - `activate(...)`, `resendActivation(...)`, `validateActivation(...)`
72
- - `identityProviders.*`, `config.*`, `userCodes.*`, `clientCredentials.*` when app has permission
73
- - `accessToken()` - resolves the caller-owned bearer token configured on `createBlocksClient`.
74
- - `isAuthenticated()` - checks the session against IAM via `GET /iam/v4/auth/me`, returns a boolean from the raw response status. Prefer this over `userInfo()` for a true/false check, since a hosted-IdP session may live in a cookie with no local `accessToken` to inspect.
75
-
76
- ## Service Map
77
-
78
- IAM:
79
-
80
- - `blocks.iam.me()`
81
- - `blocks.iam.users.*`
82
- - `blocks.iam.roles.*`
83
- - `blocks.iam.permissions.*`
84
- - `blocks.iam.resources.*`
85
- - `blocks.iam.organizations.*`
86
- - `blocks.iam.signupSettings.get()` / `.save(...)`
87
-
88
- MFA:
89
-
90
- - `blocks.mfa.config()` / `.saveConfig(...)` - tenant MFA policy
91
- - `blocks.mfa.totp.setup()` / `.verifySetup({ code })` - TOTP enrollment
92
- - `blocks.mfa.generate(...)` / `.resend(...)` / `.verify(...)` - OTP challenge flow
93
- - `blocks.mfa.setMethod({ mfaType })`, `.disable()`
94
- - `blocks.mfa.backupCodes.list()` / `.generate()` / `.use({ code, userId })`
95
-
96
- Data:
97
-
98
- - `blocks.data.schemas.*` for schema reads only
99
- - `blocks.data.validations.*` for validation reads
100
- - `blocks.data.collection("Name").list/get/create/update/delete`
101
- - `blocks.data.graphql(...)`
102
- - `blocks.data.files.*` for file/storage helpers
103
- - `blocks.data.directories.*` for directory create/get/update/delete/move
104
- - `blocks.data.objects.*` for browse/search/trash/shared/restore/share/access/inheritance
105
- - `blocks.data.utilities.*` for runtime utility helpers
106
-
107
- Localization:
108
-
109
- - `blocks.localization.languages()`
110
- - `blocks.localization.modules()`
111
- - `blocks.localization.languagesForCurrentTenant()`
112
- - `blocks.localization.modulesForCurrentTenant()`
113
- - `blocks.localization.translations(moduleName, language)`
114
- - `blocks.localization.load(language, modules)`
115
- - `blocks.localization.cloudTranslations(moduleName, language)`
116
- - `blocks.localization.loadCloud(language, modules)`
117
- - `blocks.localization.keysByNames(...)`
118
- - `blocks.localization.t(key, fallback, options)`
119
-
120
- HTTP fallback:
121
-
122
- - Use `blocks.http.request("/service/v4/...")` only when no typed method exists.
123
- - Use `blocks.http.external(url, ...)` only for external URLs such as pre-signed uploads.
124
-
125
- Errors:
126
-
127
- - Every non-2xx response from `http.request`/`http.external` throws `BlocksApiError` (`status`, `statusText`, `body`). Catch it with `instanceof BlocksApiError` rather than assuming a generic `Error` shape.
128
-
129
- ## Minimal Examples
130
-
131
- ```ts
132
- const me = await blocks.iam.me();
133
- const schemas = await blocks.data.schemas.list({ pageNo: 1, pageSize: 20 });
134
- const rows = await blocks.data.collection("Students").list({ pageNo: 1, pageSize: 20 });
135
- await blocks.localization.load("en-US", ["common"]);
136
- const label = blocks.localization.t("save", "Save");
137
- ```
138
-
139
- OIDC refresh with explicit client id:
140
-
141
- ```ts
142
- await blocks.auth.oidc.refreshToken({
143
- clientId: env.OIDC_CLIENT_ID,
144
- refreshToken: session.refreshToken
145
- });
146
- ```
147
-
148
- Embedded refresh:
149
-
150
- ```ts
151
- await blocks.auth.refresh({
152
- refreshToken: session.refreshToken
153
- });
154
- ```
155
-
156
- ## Check Before Finishing
157
-
158
- ```bash
159
- npm test
160
- npm run lint
161
- npm pack --dry-run
162
- rg -n "v4[/\\]api|iam[/\\]v4[/\\]api|data[/\\]v4[/\\]api|localization[/\\]v4[/\\]api" src README.md AGENT_GUIDE.md test
163
- ```
164
-
165
- Only negative route-guard tests should match.
1
+ # Blocks Client Guide for AI Agents
2
+
3
+ Use this file only for `@seliseblocks/client` app-code work. For full method details, read the source docstrings.
4
+
5
+ Source refs:
6
+
7
+ - Client setup: `src/client.ts`
8
+ - Auth: `src/auth/auth-client.ts`
9
+ - IAM: `src/iam/iam-client.ts`
10
+ - Data: `src/data/data-client.ts`
11
+ - Localization: `src/localization/localization-client.ts`
12
+ - MFA: `src/mfa/mfa-client.ts`
13
+ - HTTP/errors: `src/http/http-client.ts`, `src/http/errors.ts`
14
+
15
+ ## Non-Negotiable Rules
16
+
17
+ - Configure `xBlocksKey`; SDK sends it as `x-blocks-key`.
18
+ - Do not send `ProjectKey` or `projectKey`.
19
+ - Do not add `/api` after `/v4`.
20
+ - Valid route shapes: `/iam/v4/...`, `/data/v4/...`, `/localization/v4/...`.
21
+ - SDK does not store tokens. App owns access token, refresh token, storage, and logout cleanup.
22
+ - Frontend code must not contain client secrets.
23
+ - Do not add impersonation, release deploy, schema/rules mutation, or localization authoring/admin APIs.
24
+
25
+ ## Create Client
26
+
27
+ ```ts
28
+ import { createBlocksClient } from "@seliseblocks/client";
29
+
30
+ export const blocks = createBlocksClient({
31
+ apiUrl: "https://api.seliseblocks.com",
32
+ xBlocksKey: env.BLOCKS_KEY,
33
+ accessToken: () => session.accessToken,
34
+ oidc: {
35
+ url: "https://iam.seliseblocks.com",
36
+ clientId: env.OIDC_CLIENT_ID,
37
+ redirectUri: env.OIDC_REDIRECT_URI ?? `${window.location.origin}/login/callback`
38
+ }
39
+ });
40
+ ```
41
+
42
+ Use `accessToken` only for the current token resolver. Do not add SDK token storage.
43
+ Use a configured `redirectUri` when available; the current-origin `/login/callback` URL is only a browser fallback.
44
+
45
+ ## Auth Decision
46
+
47
+ There are two auth flows.
48
+
49
+ OIDC/hosted IAM flow:
50
+
51
+ - Login: `blocks.auth.idp.initiate()`, `blocks.auth.idp.redirectToProvider()`, `blocks.auth.idp.callback(...)`
52
+ - Refresh: `blocks.auth.oidc.refreshToken({ refreshToken })`
53
+ - Refresh route: `POST /iam/v4/oidc/token`
54
+ - Must send `client_id`; SDK uses `request.clientId` or configured `oidc.clientId`.
55
+ - Do not manually build `oidc/authorize`.
56
+
57
+ Embedded/app-owned flow:
58
+
59
+ - Login: `blocks.auth.login(...)`
60
+ - Social: `blocks.auth.socialInitiate(clientId, redirectUri)` (two positional strings), `blocks.auth.socialCallback(request)` (object)
61
+ - Refresh: `blocks.auth.refresh({ refreshToken })`
62
+ - Routes: `/iam/v4/auth/login`, `/iam/v4/auth/social/*`, `/iam/v4/auth/refresh`
63
+
64
+ Shared auth methods for both flows:
65
+
66
+ - `userInfo()`
67
+ - `switchOrganization(...)`
68
+ - `logout(...)`, `logoutAll(...)`
69
+ - `signup(...)`, `recover(...)`, `resetPassword(...)`
70
+ - `changePassword(...)`
71
+ - `activate(...)`, `resendActivation(...)`, `validateActivation(...)`
72
+ - `identityProviders.*`, `config.*`, `userCodes.*`, `clientCredentials.*` when app has permission
73
+ - `accessToken()` - resolves the caller-owned bearer token configured on `createBlocksClient`.
74
+ - `isAuthenticated()` - checks the session against IAM via `GET /iam/v4/auth/me`, returns a boolean from the raw response status. Prefer this over `userInfo()` for a true/false check, since a hosted-IdP session may live in a cookie with no local `accessToken` to inspect.
75
+
76
+ ## Service Map
77
+
78
+ IAM:
79
+
80
+ - `blocks.iam.me()`
81
+ - `blocks.iam.users.*`
82
+ - `blocks.iam.roles.*`
83
+ - `blocks.iam.permissions.*`
84
+ - `blocks.iam.resources.*`
85
+ - `blocks.iam.organizations.*`
86
+ - `blocks.iam.signupSettings.get()` / `.save(...)`
87
+
88
+ MFA:
89
+
90
+ - `blocks.mfa.config()` / `.saveConfig(...)` - tenant MFA policy
91
+ - `blocks.mfa.totp.setup()` / `.verifySetup({ code })` - TOTP enrollment
92
+ - `blocks.mfa.generate(...)` / `.resend(...)` / `.verify(...)` - OTP challenge flow
93
+ - `blocks.mfa.setMethod({ mfaType })`, `.disable()`
94
+ - `blocks.mfa.backupCodes.list()` / `.generate()` / `.use({ code, userId })`
95
+
96
+ Data:
97
+
98
+ - `blocks.data.schemas.*` for schema reads only
99
+ - `blocks.data.validations.*` for validation reads
100
+ - `blocks.data.collection("Name").list/get/create/update/delete`
101
+ - `blocks.data.graphql(...)`
102
+ - `blocks.data.files.*` for file/storage helpers
103
+ - `blocks.data.directories.*` for directory create/get/update/delete/move
104
+ - `blocks.data.objects.*` for browse/search/trash/shared/restore/share/access/inheritance
105
+ - `blocks.data.utilities.*` for runtime utility helpers
106
+
107
+ Localization:
108
+
109
+ - `blocks.localization.languages()`
110
+ - `blocks.localization.modules()`
111
+ - `blocks.localization.languagesForCurrentTenant()`
112
+ - `blocks.localization.modulesForCurrentTenant()`
113
+ - `blocks.localization.translations(moduleName, language)`
114
+ - `blocks.localization.load(language, modules)`
115
+ - `blocks.localization.cloudTranslations(moduleName, language)`
116
+ - `blocks.localization.loadCloud(language, modules)`
117
+ - `blocks.localization.keysByNames(...)`
118
+ - `blocks.localization.t(key, fallback, options)`
119
+
120
+ Logic (runtime only -- authoring/deploying functions and configuring proxies is `blocks logic function|proxy *`):
121
+
122
+ - `blocks.logic.functions.call(id, options)` - the deployed function's value; polls async runs, unwraps `{ statusCode, body }`
123
+ - `blocks.logic.functions.invoke(id, options)` - `{ kind: "answered", status, headers, body }` or `{ kind: "accepted", runId, pollToken }`
124
+ - `blocks.logic.functions.waitForResult(accepted, { intervalMs, timeoutMs })` / `.getResult(runId, pollToken)` / `.getRun(runId)`
125
+ - `blocks.logic.functions.invokeRaw(id, options)` - unread `Response` for streaming handlers
126
+ - `blocks.logic.functions.url(id, path?)`, `blocks.logic.proxy.url(slug, path?)`
127
+ - `blocks.logic.proxy.request(slug, { method, path, query, body })` / `.requestRaw(...)`
128
+ - Failed runs throw `BlocksFunctionRunError` (`runId`, `status`, `errorCode`, `errorMessage`); refusals throw `BlocksApiError` with `body.code` `FUNCTION_INVOKE_*` / `PROXY_GATEWAY_*`.
129
+ - Function authoring types: `import("@seliseblocks/client/functions")` - `FunctionHandler`, `FunctionInput`, `FunctionContext`, `FunctionHttpResponse` (type-only).
130
+
131
+ HTTP fallback:
132
+
133
+ - Use `blocks.http.request("/service/v4/...")` only when no typed method exists.
134
+ - Use `blocks.http.external(url, ...)` only for external URLs such as pre-signed uploads.
135
+
136
+ Errors:
137
+
138
+ - Every non-2xx response from `http.request`/`http.external` throws `BlocksApiError` (`status`, `statusText`, `body`). Catch it with `instanceof BlocksApiError` rather than assuming a generic `Error` shape.
139
+
140
+ ## Minimal Examples
141
+
142
+ ```ts
143
+ const me = await blocks.iam.me();
144
+ const schemas = await blocks.data.schemas.list({ pageNo: 1, pageSize: 20 });
145
+ const rows = await blocks.data.collection("Students").list({ pageNo: 1, pageSize: 20 });
146
+ await blocks.localization.load("en-US", ["common"]);
147
+ const label = blocks.localization.t("save", "Save");
148
+ ```
149
+
150
+ OIDC refresh with explicit client id:
151
+
152
+ ```ts
153
+ await blocks.auth.oidc.refreshToken({
154
+ clientId: env.OIDC_CLIENT_ID,
155
+ refreshToken: session.refreshToken
156
+ });
157
+ ```
158
+
159
+ Embedded refresh:
160
+
161
+ ```ts
162
+ await blocks.auth.refresh({
163
+ refreshToken: session.refreshToken
164
+ });
165
+ ```
166
+
167
+ ## Check Before Finishing
168
+
169
+ ```bash
170
+ npm test
171
+ npm run lint
172
+ npm pack --dry-run
173
+ rg -n "v4[/\\]api|iam[/\\]v4[/\\]api|data[/\\]v4[/\\]api|localization[/\\]v4[/\\]api" src README.md AGENT_GUIDE.md test
174
+ ```
175
+
176
+ Only negative route-guard tests should match.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,91 @@ This project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
  Versions before 0.2.0 were released without a changelog; their history is in the
7
7
  repository's git log.
8
8
 
9
+ ## 0.3.0
10
+
11
+ ### Added
12
+
13
+ - `blocks.logic` -- the blocks-logic runtime surface:
14
+ - `logic.functions.call(id, options)` invokes a deployed function and returns
15
+ its value whether it is deployed sync (the answer's body) or async (polls the
16
+ run, parses its result). A returned `{ statusCode, headers, body }` is
17
+ unwrapped to `body` so both modes read alike. A run that fails or times out
18
+ throws the new `BlocksFunctionRunError`.
19
+ - `logic.functions.invoke()` returns the transport result --
20
+ `{ kind: "answered", status, headers, body, runId? }` or
21
+ `{ kind: "accepted", runId, runStatus, pollToken }` -- with `respondAsync` /
22
+ `waitSeconds` mapped to the `Prefer` header; `waitForResult()`,
23
+ `getResult(runId, pollToken)` and `getRun(runId)` collect a queued run;
24
+ `invokeRaw()` returns the unread `Response` for streaming handlers;
25
+ `url()` gives the public address.
26
+ - `logic.proxy.request(slug, options)` / `requestRaw()` / `url()` call a
27
+ configured proxy's gateway route.
28
+ - `@seliseblocks/client/functions` -- type-only declarations of the function
29
+ sandbox contract (`FunctionHandler`, `FunctionInput`, `FunctionContext`,
30
+ `FunctionHttpResponse`, …) for editor checking of a function's `index.js`.
31
+ Nothing from it is needed at runtime inside a function.
32
+ - `http.send(path, options)` -- the same authenticated request as
33
+ `http.request`, returning the unread `Response` (status and headers intact,
34
+ never throws on a non-2xx). `request` is now built on it, unchanged.
35
+ - Request `query` values may be arrays (a repeated key), and requests take an
36
+ `AbortSignal` (`signal`).
37
+
38
+ ### Fixed
39
+
40
+ - `auth.switchOrganization({ organizationId })` now sends IAM's
41
+ `organization_id`.
42
+ - Why: IAM binds `SwitchOrganizationRequest.OrganizationId` only as
43
+ `organization_id` (`[JsonPropertyName]`). The SDK sent the camelCase name,
44
+ so every call that followed the documented type failed with 400
45
+ `organization_id is required`.
46
+ - Compatible: the type is unchanged. A caller already sending
47
+ `organization_id` keeps working, and that value still wins when both are
48
+ given, matching what IAM bound before. Other extra fields pass through as
49
+ before.
50
+ - `refreshToken` on this request is deprecated and no longer sent. IAM's
51
+ switch-org reads the refresh token only from the session cookie (or its
52
+ `rt_<domain>` header), never from the body. It had no effect, and sending
53
+ it only put a secret in a request body. Switch organization from a browser
54
+ session that holds the IAM cookie.
55
+ - `BlocksApiError.message` now includes the reason from validation responses.
56
+ - Why: the message was built only from `message`, `detail`,
57
+ `error_description` and `error`. ASP.NET validation responses
58
+ (`{ title, errors }`) and Blocks mutation responses (`{ errors: { Field:
59
+ "text" } }`) carry the reason in `errors`, so the message was only the
60
+ status line (`Blocks API 400 Bad Request`) and the reason sat unseen in
61
+ `.body`.
62
+ - What: when none of those four fields is present, the message adds the
63
+ `errors` entries (`Field: text`, first five fields), or else `title`.
64
+ - Compatible: `status`, `statusText` and `body` are unchanged, and a body
65
+ that already had `message` / `detail` / `error_description` / `error`
66
+ gives exactly the same message as before.
67
+
68
+ ### Fixed (blocks-site reports)
69
+
70
+ - `notifier.notify` fills `connectionId`, `responseKey` and `responseValue` with
71
+ `server` / `notification` / `notification` when omitted. The service binds all
72
+ three as required strings, so the documented minimal call failed with 400
73
+ (95737817). `organizationIds` is added to the request type. A send needs a
74
+ user whose role has `blocks-logic::notifier::send`; blocks-logic answers 401
75
+ otherwise.
76
+ - `iam.users.emailAvailable` and `iam.users.exists` use IAM's POST forms; the
77
+ deprecated GETs put the address in the URL (3b86fd8d). `emailAvailable` now
78
+ sends the signed-in user's token: IAM protects it with
79
+ `blocks-iam::iam::email-available`, so it no longer works before sign-in.
80
+
81
+ ### Breaking (type-level)
82
+
83
+ - `iam.users.activate` takes `BlocksActivateUserRequest` (`{ userId, reason }`,
84
+ both required) instead of `Record<string, unknown>`. IAM requires `reason`, so a
85
+ call without it always failed with 400; the type now says so (bacbaebd).
86
+ - `BlocksNotifyRequest.configurationName` and `.denormalizedPayload` are required.
87
+ Every send without them was already refused by the service (95737817).
88
+
89
+ ### Changed
90
+
91
+ - `iam.organizations.list` accepts an array for `Filter.Ids`; its JSDoc documents
92
+ that IAM pages from 0 and refuses `Filter.*` without a non-empty `Filter.Search`.
93
+
9
94
  ## 0.2.0
10
95
 
11
96
  ### Breaking