@blueraiz/integrati-client 0.5.0 → 0.5.2

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 (2) hide show
  1. package/README.md +204 -204
  2. package/package.json +6 -1
package/README.md CHANGED
@@ -1,204 +1,204 @@
1
- # @blueraiz/integrati-client
2
-
3
- Client for apps connected to Integrati. Node 20.3+, ES modules, no runtime dependencies.
4
-
5
- **Install from a checkout of this repository.** npm cannot install from a subfolder of a git
6
- repository, so pack it once (packing builds `dist/`), then install the tarball:
7
-
8
- ```bash
9
- cd integrati/sdk/typescript && npm install && npm pack # → blueraiz-integrati-client-0.4.0.tgz
10
- cd my-app && npm install ../integrati/sdk/typescript/blueraiz-integrati-client-0.4.0.tgz
11
- ```
12
-
13
- pnpm can also install straight from git: `pnpm add "git+https://<git host>/blueraiz/integrati.git#path:/sdk/typescript"`.
14
-
15
- ## Set up
16
-
17
- ```ts
18
- import { IntegratiClient, cloudEvent } from "@blueraiz/integrati-client";
19
-
20
- export const integrati = new IntegratiClient({
21
- baseUrl: "https://integrati.example.com",
22
- authority: "https://auth.example.com/noauth/oidc", // or tokenEndpoint
23
- clientId: process.env.INTEGRATI_CLIENT_ID!,
24
- clientSecret: process.env.INTEGRATI_CLIENT_SECRET!,
25
- resource: "https://integrati.example.com"
26
- // clientAuthentication: "basic" (default "post", as noauth expects)
27
- });
28
- ```
29
-
30
- Tokens are cached and renewed a minute before they expire, and a 401 renews them once
31
- automatically. Create one client and reuse it.
32
-
33
- ## Events
34
-
35
- ```ts
36
- const result = await integrati.publish(cloudEvent("blueraiz.ecom.order.created.v1", { orderId: 1842 }, { subject: "order/1842", tenantid: "acme" }));
37
- // result.status: "accepted", or "duplicate" when this id was sent before (retries are safe)
38
- ```
39
-
40
- A refusal throws `IntegratiError`. Its `errors` holds per-field problems such as `data/qty`.
41
- `isTransient` tells you whether retrying later can help.
42
-
43
- ## Receiving
44
-
45
- **Webhook** (Next.js route handler; pass the raw body):
46
-
47
- ```ts
48
- import { verifyWebhook, VerificationError } from "@blueraiz/integrati-client";
49
-
50
- export async function POST(request: Request) {
51
- const body = await request.text();
52
- try {
53
- const event = verifyWebhook<{ orderId: number }>(process.env.INTEGRATI_WEBHOOK_SECRET!, request.headers, body);
54
- // deduplicate on event.id, queue the work
55
- return new Response(null, { status: 204 });
56
- } catch (error) {
57
- if (error instanceof VerificationError) return new Response(null, { status: 401 });
58
- throw error;
59
- }
60
- }
61
- ```
62
-
63
- **Inbox** (pull subscription). Handled messages are acknowledged; a message whose handler throws
64
- is given back and retried:
65
-
66
- ```ts
67
- const stop = new AbortController();
68
- await integrati.processInbox(subscriptionId, async event => { /* idempotent handling */ }, { signal: stop.signal, visibilitySeconds: 120 });
69
- ```
70
-
71
- Or stream, acknowledging yourself:
72
-
73
- ```ts
74
- for await (const message of integrati.stream(subscriptionId, { max: 10, signal })) {
75
- // handle message.event
76
- await integrati.ack(subscriptionId, [message.receipt]);
77
- }
78
- ```
79
-
80
- `receive`, `ack` and `nack` are there for full control.
81
-
82
- ## Commands
83
-
84
- ```ts
85
- // Caller: send and wait up to 30 s for the reply (null if none came in time).
86
- const reply = await integrati.call<{ key: string }>("license", cloudEvent("blueraiz.license.key.issue.v1", { customer: "C-7" }), 30, { ttlSeconds: 3600 });
87
-
88
- // Target: commands arrive on its direct subscription; answer once.
89
- await integrati.reply(command, cloudEvent("blueraiz.license.key.issued.v1", { key }));
90
- ```
91
-
92
- `sendCommand` and `getCommand(commandId, { waitSeconds })` split `call` in two.
93
-
94
- ## Backfill
95
-
96
- Stored events sent to one of your subscriptions again (an admin must allow backfill for it):
97
-
98
- ```ts
99
- import { isBackfill } from "@blueraiz/integrati-client";
100
-
101
- const from = new Date(Date.now() - 90 * 86_400_000);
102
- const { events } = await integrati.previewBackfill(subscriptionId, { from });
103
- const job = await integrati.startBackfill(subscriptionId, { from });
104
- const progress = await integrati.getBackfill(job.id); // status, sent of total
105
-
106
- // In your handler: backfilled events carry the job id.
107
- if (isBackfill(event)) { /* e.g. skip notifications; deduplicate on event.id as always */ }
108
- ```
109
-
110
- ## Describe the app from its code (manifest)
111
-
112
- The app tells Integrati what it publishes, consumes, calls and exposes. `start()` sends the
113
- manifest and fetches the app's secrets, so webhooks and gateway calls are verified without secrets
114
- in its settings. An admin connects the entries in the portal's **Connections** page; describing
115
- grants nothing.
116
-
117
- ```ts
118
- import { IntegratiApp, IntegratiClient, defineEvent } from "@blueraiz/integrati-client";
119
-
120
- const MemberAdded = defineEvent<{ organizationId: string; userId: string }>("blueraiz.noauth.member.added.v1", {
121
- description: "A member joined an organization.",
122
- schema: { type: "object", properties: { organizationId: { type: "string" }, userId: { type: "string" } }, required: ["organizationId", "userId"] }
123
- });
124
-
125
- const integrati = new IntegratiApp({
126
- client: new IntegratiClient({ baseUrl: process.env.INTEGRATI_URL!, authority: "…", clientId: "…", clientSecret: "…", resource: "…" }),
127
- key: "noauth", name: "NoAuth",
128
- publicUrl: "https://auth.example.com", // webhooks are delivered here
129
- apiBaseUrl: "http://noauth:3000" // the gateway forwards calls here
130
- })
131
- .publishes(MemberAdded)
132
- .exposes("GET", "/api/admin/organizations/*", "Read an organization")
133
- .calls("crm", "Tenant settings", "GET /api/tenants/*");
134
-
135
- // A webhook (Express or node:http). Mount it before express.json(), or behind express.raw().
136
- app.post("/integrati/events", integrati.consumes("blueraiz.crm.#", "/integrati/events", async event => { /* … */ }));
137
-
138
- // In your API: who called through the gateway (null without the header; throws if it is forged).
139
- const caller = integrati.callerOf(req.method, req.originalUrl, req.headers);
140
-
141
- await integrati.start(); // send the manifest, then refresh every 5 minutes
142
- await integrati.publish(MemberAdded, { organizationId: "o1", userId: "u1" }, { tenantid: "acme" });
143
- ```
144
-
145
- Without `IntegratiApp`, `new ManifestBuilder(key, name)…build()` makes the manifest, and
146
- `client.pushManifest()` and `client.manifestStatus()` send it and read the status.
147
-
148
- ## Calls to your API through the gateway
149
-
150
- ```ts
151
- import { verifyGatewayAssertion } from "@blueraiz/integrati-client";
152
-
153
- const caller = verifyGatewayAssertion(req.headers["x-integrati-assertion"], process.env.INTEGRATI_ASSERTION_SECRET!, "crm",
154
- { method: req.method, path: req.path }); // path relative to the base URL registered with Integrati
155
- // caller.appKey is the calling app; throws VerificationError otherwise.
156
- ```
157
-
158
- ## Outbox
159
-
160
- `OutboxRelay` sends messages saved in your database. It works with any storage through a small
161
- `OutboxStore` interface. With Prisma:
162
-
163
- ```prisma
164
- model IntegratiOutbox {
165
- id BigInt @id @default(autoincrement())
166
- kind String // "event" | "command"
167
- target String?
168
- ttlSeconds Int? @map("ttl_seconds")
169
- payload Json
170
- attempts Int @default(0)
171
- nextAttemptAt DateTime? @map("next_attempt_at")
172
- lastError String? @map("last_error")
173
- failedAt DateTime? @map("failed_at")
174
- @@map("integrati_outbox")
175
- }
176
- ```
177
-
178
- ```ts
179
- // Same transaction as the change:
180
- await prisma.$transaction([
181
- prisma.order.create({ data: order }),
182
- prisma.integratiOutbox.create({ data: { kind: "event", payload: cloudEvent("blueraiz.ecom.order.created.v1", { orderId: order.id }) } })
183
- ]);
184
-
185
- // The relay, e.g. started with the app:
186
- const store: OutboxStore = {
187
- pending: limit => prisma.integratiOutbox.findMany({ where: { failedAt: null }, orderBy: { id: "asc" }, take: limit })
188
- .then(rows => rows.map(r => ({ ...r, payload: r.payload as CloudEvent, kind: r.kind as "event" | "command" }))),
189
- remove: async id => { await prisma.integratiOutbox.delete({ where: { id: BigInt(id) } }); },
190
- retryLater: async (id, attempts, nextAttemptAt, lastError) => { await prisma.integratiOutbox.update({ where: { id: BigInt(id) }, data: { attempts, nextAttemptAt, lastError } }); },
191
- fail: async (id, attempts, lastError) => { await prisma.integratiOutbox.update({ where: { id: BigInt(id) }, data: { attempts, lastError, failedAt: new Date() } }); }
192
- };
193
- void new OutboxRelay(integrati, store).run(shutdownSignal);
194
- ```
195
-
196
- The relay sends in order and removes each message once Integrati has it:
197
- - A message Integrati can't take now is retried with a growing delay, and nothing behind it is sent
198
- first.
199
- - A message Integrati refuses is marked failed.
200
- - Several instances may relay at once: Integrati ignores an id it already has.
201
-
202
- ## Develop
203
-
204
- `npm test` runs the tests from source; it needs Node 22.6+. `npm run build` writes `dist/`.
1
+ # @blueraiz/integrati-client
2
+
3
+ Client for apps connected to Integrati. Node 20.3+, ES modules, no runtime dependencies.
4
+
5
+ **Install from a checkout of this repository.** npm cannot install from a subfolder of a git
6
+ repository, so pack it once (packing builds `dist/`), then install the tarball:
7
+
8
+ ```bash
9
+ cd integrati/sdk/typescript && npm install && npm pack # → blueraiz-integrati-client-0.4.0.tgz
10
+ cd my-app && npm install ../integrati/sdk/typescript/blueraiz-integrati-client-0.4.0.tgz
11
+ ```
12
+
13
+ pnpm can also install straight from git: `pnpm add "git+https://<git host>/blueraiz/integrati.git#path:/sdk/typescript"`.
14
+
15
+ ## Set up
16
+
17
+ ```ts
18
+ import { IntegratiClient, cloudEvent } from "@blueraiz/integrati-client";
19
+
20
+ export const integrati = new IntegratiClient({
21
+ baseUrl: "https://integrati.example.com",
22
+ authority: "https://auth.example.com/noauth/oidc", // or tokenEndpoint
23
+ clientId: process.env.INTEGRATI_CLIENT_ID!,
24
+ clientSecret: process.env.INTEGRATI_CLIENT_SECRET!,
25
+ resource: "https://integrati.example.com"
26
+ // clientAuthentication: "basic" (default "post", as noauth expects)
27
+ });
28
+ ```
29
+
30
+ Tokens are cached and renewed a minute before they expire, and a 401 renews them once
31
+ automatically. Create one client and reuse it.
32
+
33
+ ## Events
34
+
35
+ ```ts
36
+ const result = await integrati.publish(cloudEvent("blueraiz.ecom.order.created.v1", { orderId: 1842 }, { subject: "order/1842", tenantid: "acme" }));
37
+ // result.status: "accepted", or "duplicate" when this id was sent before (retries are safe)
38
+ ```
39
+
40
+ A refusal throws `IntegratiError`. Its `errors` holds per-field problems such as `data/qty`.
41
+ `isTransient` tells you whether retrying later can help.
42
+
43
+ ## Receiving
44
+
45
+ **Webhook** (Next.js route handler; pass the raw body):
46
+
47
+ ```ts
48
+ import { verifyWebhook, VerificationError } from "@blueraiz/integrati-client";
49
+
50
+ export async function POST(request: Request) {
51
+ const body = await request.text();
52
+ try {
53
+ const event = verifyWebhook<{ orderId: number }>(process.env.INTEGRATI_WEBHOOK_SECRET!, request.headers, body);
54
+ // deduplicate on event.id, queue the work
55
+ return new Response(null, { status: 204 });
56
+ } catch (error) {
57
+ if (error instanceof VerificationError) return new Response(null, { status: 401 });
58
+ throw error;
59
+ }
60
+ }
61
+ ```
62
+
63
+ **Inbox** (pull subscription). Handled messages are acknowledged; a message whose handler throws
64
+ is given back and retried:
65
+
66
+ ```ts
67
+ const stop = new AbortController();
68
+ await integrati.processInbox(subscriptionId, async event => { /* idempotent handling */ }, { signal: stop.signal, visibilitySeconds: 120 });
69
+ ```
70
+
71
+ Or stream, acknowledging yourself:
72
+
73
+ ```ts
74
+ for await (const message of integrati.stream(subscriptionId, { max: 10, signal })) {
75
+ // handle message.event
76
+ await integrati.ack(subscriptionId, [message.receipt]);
77
+ }
78
+ ```
79
+
80
+ `receive`, `ack` and `nack` are there for full control.
81
+
82
+ ## Commands
83
+
84
+ ```ts
85
+ // Caller: send and wait up to 30 s for the reply (null if none came in time).
86
+ const reply = await integrati.call<{ key: string }>("license", cloudEvent("blueraiz.license.key.issue.v1", { customer: "C-7" }), 30, { ttlSeconds: 3600 });
87
+
88
+ // Target: commands arrive on its direct subscription; answer once.
89
+ await integrati.reply(command, cloudEvent("blueraiz.license.key.issued.v1", { key }));
90
+ ```
91
+
92
+ `sendCommand` and `getCommand(commandId, { waitSeconds })` split `call` in two.
93
+
94
+ ## Backfill
95
+
96
+ Stored events sent to one of your subscriptions again (an admin must allow backfill for it):
97
+
98
+ ```ts
99
+ import { isBackfill } from "@blueraiz/integrati-client";
100
+
101
+ const from = new Date(Date.now() - 90 * 86_400_000);
102
+ const { events } = await integrati.previewBackfill(subscriptionId, { from });
103
+ const job = await integrati.startBackfill(subscriptionId, { from });
104
+ const progress = await integrati.getBackfill(job.id); // status, sent of total
105
+
106
+ // In your handler: backfilled events carry the job id.
107
+ if (isBackfill(event)) { /* e.g. skip notifications; deduplicate on event.id as always */ }
108
+ ```
109
+
110
+ ## Describe the app from its code (manifest)
111
+
112
+ The app tells Integrati what it publishes, consumes, calls and exposes. `start()` sends the
113
+ manifest and fetches the app's secrets, so webhooks and gateway calls are verified without secrets
114
+ in its settings. An admin connects the entries in the portal's **Connections** page; describing
115
+ grants nothing.
116
+
117
+ ```ts
118
+ import { IntegratiApp, IntegratiClient, defineEvent } from "@blueraiz/integrati-client";
119
+
120
+ const MemberAdded = defineEvent<{ organizationId: string; userId: string }>("blueraiz.noauth.member.added.v1", {
121
+ description: "A member joined an organization.",
122
+ schema: { type: "object", properties: { organizationId: { type: "string" }, userId: { type: "string" } }, required: ["organizationId", "userId"] }
123
+ });
124
+
125
+ const integrati = new IntegratiApp({
126
+ client: new IntegratiClient({ baseUrl: process.env.INTEGRATI_URL!, authority: "…", clientId: "…", clientSecret: "…", resource: "…" }),
127
+ key: "noauth", name: "NoAuth",
128
+ publicUrl: "https://auth.example.com", // webhooks are delivered here
129
+ apiBaseUrl: "http://noauth:3000" // the gateway forwards calls here
130
+ })
131
+ .publishes(MemberAdded)
132
+ .exposes("GET", "/api/admin/organizations/*", "Read an organization")
133
+ .calls("crm", "Tenant settings", "GET /api/tenants/*");
134
+
135
+ // A webhook (Express or node:http). Mount it before express.json(), or behind express.raw().
136
+ app.post("/integrati/events", integrati.consumes("blueraiz.crm.#", "/integrati/events", async event => { /* … */ }));
137
+
138
+ // In your API: who called through the gateway (null without the header; throws if it is forged).
139
+ const caller = integrati.callerOf(req.method, req.originalUrl, req.headers);
140
+
141
+ await integrati.start(); // send the manifest, then refresh every 5 minutes
142
+ await integrati.publish(MemberAdded, { organizationId: "o1", userId: "u1" }, { tenantid: "acme" });
143
+ ```
144
+
145
+ Without `IntegratiApp`, `new ManifestBuilder(key, name)…build()` makes the manifest, and
146
+ `client.pushManifest()` and `client.manifestStatus()` send it and read the status.
147
+
148
+ ## Calls to your API through the gateway
149
+
150
+ ```ts
151
+ import { verifyGatewayAssertion } from "@blueraiz/integrati-client";
152
+
153
+ const caller = verifyGatewayAssertion(req.headers["x-integrati-assertion"], process.env.INTEGRATI_ASSERTION_SECRET!, "crm",
154
+ { method: req.method, path: req.path }); // path relative to the base URL registered with Integrati
155
+ // caller.appKey is the calling app; throws VerificationError otherwise.
156
+ ```
157
+
158
+ ## Outbox
159
+
160
+ `OutboxRelay` sends messages saved in your database. It works with any storage through a small
161
+ `OutboxStore` interface. With Prisma:
162
+
163
+ ```prisma
164
+ model IntegratiOutbox {
165
+ id BigInt @id @default(autoincrement())
166
+ kind String // "event" | "command"
167
+ target String?
168
+ ttlSeconds Int? @map("ttl_seconds")
169
+ payload Json
170
+ attempts Int @default(0)
171
+ nextAttemptAt DateTime? @map("next_attempt_at")
172
+ lastError String? @map("last_error")
173
+ failedAt DateTime? @map("failed_at")
174
+ @@map("integrati_outbox")
175
+ }
176
+ ```
177
+
178
+ ```ts
179
+ // Same transaction as the change:
180
+ await prisma.$transaction([
181
+ prisma.order.create({ data: order }),
182
+ prisma.integratiOutbox.create({ data: { kind: "event", payload: cloudEvent("blueraiz.ecom.order.created.v1", { orderId: order.id }) } })
183
+ ]);
184
+
185
+ // The relay, e.g. started with the app:
186
+ const store: OutboxStore = {
187
+ pending: limit => prisma.integratiOutbox.findMany({ where: { failedAt: null }, orderBy: { id: "asc" }, take: limit })
188
+ .then(rows => rows.map(r => ({ ...r, payload: r.payload as CloudEvent, kind: r.kind as "event" | "command" }))),
189
+ remove: async id => { await prisma.integratiOutbox.delete({ where: { id: BigInt(id) } }); },
190
+ retryLater: async (id, attempts, nextAttemptAt, lastError) => { await prisma.integratiOutbox.update({ where: { id: BigInt(id) }, data: { attempts, nextAttemptAt, lastError } }); },
191
+ fail: async (id, attempts, lastError) => { await prisma.integratiOutbox.update({ where: { id: BigInt(id) }, data: { attempts, lastError, failedAt: new Date() } }); }
192
+ };
193
+ void new OutboxRelay(integrati, store).run(shutdownSignal);
194
+ ```
195
+
196
+ The relay sends in order and removes each message once Integrati has it:
197
+ - A message Integrati can't take now is retried with a growing delay, and nothing behind it is sent
198
+ first.
199
+ - A message Integrati refuses is marked failed.
200
+ - Several instances may relay at once: Integrati ignores an id it already has.
201
+
202
+ ## Develop
203
+
204
+ `npm test` runs the tests from source; it needs Node 22.6+. `npm run build` writes `dist/`.
package/package.json CHANGED
@@ -1,8 +1,13 @@
1
1
  {
2
2
  "name": "@blueraiz/integrati-client",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "description": "Client for the Integrati hub: publish events, send and answer commands, read inboxes, verify webhooks and gateway assertions.",
5
5
  "license": "UNLICENSED",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/zees-tech/integrati.git",
9
+ "directory": "sdk/typescript"
10
+ },
6
11
  "type": "module",
7
12
  "main": "./dist/cjs/index.js",
8
13
  "types": "./dist/index.d.ts",