@collective-intelligence/external-apps-server-sdk 0.1.38 → 0.1.40
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 +303 -21
- package/dist/admin.d.ts +1 -0
- package/dist/auth/better-auth.d.ts +6 -0
- package/dist/auth/better-auth.js +1 -1
- package/dist/auth/federated.d.ts +6 -0
- package/dist/auth/federated.js +1 -1
- package/dist/chunks/index-15774myk.js +2 -0
- package/dist/chunks/index-8yk07eg5.js +2 -0
- package/dist/chunks/{index-zrrnrqkm.js → index-mp74xvyn.js} +3 -3
- package/dist/chunks/index-pzge02c9.js +2 -0
- package/dist/effect/next.d.ts +7 -0
- package/dist/effect/next.js +1 -0
- package/dist/effect/node-postgres.d.ts +34 -0
- package/dist/effect/node-postgres.js +1 -0
- package/dist/effect.d.ts +105 -25
- package/dist/effect.js +1 -1
- package/dist/index.d.ts +112 -16
- package/dist/index.js +1 -1
- package/dist/next.d.ts +102 -5
- package/dist/next.js +1 -1
- package/dist/persistence/drizzle-effect.d.ts +12 -11
- package/dist/persistence/drizzle-effect.js +1 -0
- package/dist/resources.d.ts +18 -1
- package/dist/resources.js +1 -1
- package/dist/runtime/effect.d.ts +1 -0
- package/dist/runtime/nestjs.js +1 -1
- package/dist/runtime/next.d.ts +59 -5
- package/dist/runtime/web.d.ts +60 -5
- package/dist/runtime/web.js +1 -1
- package/package.json +20 -6
package/README.md
CHANGED
|
@@ -31,13 +31,19 @@ one `effect` version in the application. The SDK depends on
|
|
|
31
31
|
bundle their JavaScript, so the application has one copy of their error
|
|
32
32
|
classes.
|
|
33
33
|
`/effect` is the Effect export and `/next` is the Next.js export; see
|
|
34
|
-
[Effect authoring](#effect-authoring)
|
|
35
|
-
[Next.js, Web and Express hosting](#nextjs-web-and-express-hosting)
|
|
34
|
+
[Effect authoring](#effect-authoring),
|
|
35
|
+
[Next.js, Web and Express hosting](#nextjs-web-and-express-hosting) and
|
|
36
|
+
[Next.js Cache Primitives](#nextjs-cache-primitives). `/next` loads `next`
|
|
37
|
+
(`next/cache`); `/effect` loads no `next`. `/effect/next` holds the Next.js
|
|
38
|
+
layer of `/effect` ([Write invalidation](#write-invalidation)) and loads
|
|
39
|
+
`next` too. `/effect` loads no `pg` and no `drizzle-orm`.
|
|
40
|
+
`/effect/node-postgres` holds `layerNodePostgres`
|
|
41
|
+
([Shared CRUD resources](#shared-crud-resources)) and imports both.
|
|
36
42
|
|
|
37
43
|
### Subpath migration
|
|
38
44
|
|
|
39
45
|
Three subpaths are deprecated re-exports for one minor release. Each exports
|
|
40
|
-
the same values as its
|
|
46
|
+
the same values as its replacements, so classes and service tags have one
|
|
41
47
|
identity. Each name that a subpath takes from its replacement is marked
|
|
42
48
|
`@deprecated`, and the `ci-solution/effect-subpath` lint rule reports the
|
|
43
49
|
subpaths. The replacements do not export the types of the sibling SDKs that
|
|
@@ -45,11 +51,14 @@ the deprecated subpaths kept from 0.1.x: import them from
|
|
|
45
51
|
`@collective-intelligence/extensions-sdk` or
|
|
46
52
|
`@collective-intelligence/external-apps-client-sdk/resources`.
|
|
47
53
|
|
|
48
|
-
| Deprecated subpath | Import instead
|
|
49
|
-
| ----------------------------- |
|
|
50
|
-
| `/runtime/effect` | `/effect`
|
|
51
|
-
| `/persistence/drizzle/effect` | `/effect`
|
|
52
|
-
| `/runtime/next` | `/next`
|
|
54
|
+
| Deprecated subpath | Import instead |
|
|
55
|
+
| ----------------------------- | ----------------------------------------------------------- |
|
|
56
|
+
| `/runtime/effect` | `/effect` |
|
|
57
|
+
| `/persistence/drizzle/effect` | `/effect`; `layerNodePostgres` from `/effect/node-postgres` |
|
|
58
|
+
| `/runtime/next` | `/next` |
|
|
59
|
+
|
|
60
|
+
`/persistence/drizzle/effect` imports `pg` and `drizzle-orm`, as
|
|
61
|
+
`/effect/node-postgres` does.
|
|
53
62
|
|
|
54
63
|
### Errors
|
|
55
64
|
|
|
@@ -646,7 +655,8 @@ const slot = await ci.resources.createUpload({
|
|
|
646
655
|
filename: "logo.png",
|
|
647
656
|
mimeType: "image/png",
|
|
648
657
|
organizationId,
|
|
649
|
-
schemaId: "apito.vetrina.schemas.member-company"
|
|
658
|
+
schemaId: "apito.vetrina.schemas.member-company",
|
|
659
|
+
size: logo.byteLength
|
|
650
660
|
})
|
|
651
661
|
if (slot.ok) {
|
|
652
662
|
const { headers, method, uploadId, url } = slot.value.result
|
|
@@ -681,6 +691,53 @@ if (slot.ok) {
|
|
|
681
691
|
values; a portable resource form has no File field, so
|
|
682
692
|
`projectResourceSchema` refuses them.
|
|
683
693
|
|
|
694
|
+
## Record writes
|
|
695
|
+
|
|
696
|
+
`resources.records` creates, updates and deletes the records of an entity
|
|
697
|
+
schema through CI's resources API.
|
|
698
|
+
|
|
699
|
+
```ts
|
|
700
|
+
const created = await ci.resources.records.create({
|
|
701
|
+
organizationId,
|
|
702
|
+
schemaId: "acme.crm.lead",
|
|
703
|
+
value: { name: "Rossi Srl", status: "open" }
|
|
704
|
+
})
|
|
705
|
+
if (created.ok) {
|
|
706
|
+
const { id, revision } = created.value.result
|
|
707
|
+
await ci.resources.records.update({
|
|
708
|
+
id,
|
|
709
|
+
organizationId,
|
|
710
|
+
revision,
|
|
711
|
+
schemaId: "acme.crm.lead",
|
|
712
|
+
value: { status: "won" }
|
|
713
|
+
})
|
|
714
|
+
}
|
|
715
|
+
```
|
|
716
|
+
|
|
717
|
+
- `schemaId` is the schema id or FQN. `create` writes `value`, and CI names
|
|
718
|
+
the id. `update` merges the top-level keys of `value` into the record at
|
|
719
|
+
`revision`. `delete` soft-deletes the record at `revision`. Each write
|
|
720
|
+
resolves `{ ok: true, value: { correlationId, result } }`, where `result`
|
|
721
|
+
is the record `{ id, revision, value }`; a deleted record also has
|
|
722
|
+
`deletedAt`. The next write of the record names the new `revision`.
|
|
723
|
+
- The credentials are those of `createUpload`: the member's delegated token
|
|
724
|
+
writes as that member; the service credential writes as the Organization
|
|
725
|
+
default service principal, only on schemas its own package declares.
|
|
726
|
+
- A refusal resolves `{ ok: false, error }` with CI's `correlationId` and a
|
|
727
|
+
`code`. `conflict` means that the record changed after `revision`, or,
|
|
728
|
+
with `details.fields`, that another record holds the value of a unique
|
|
729
|
+
field. Only `retryable` failures are retried, and each attempt sends the
|
|
730
|
+
same `idempotencyKey`. The key is generated when omitted; pass one key for
|
|
731
|
+
one intent, so that a repeated save is one CI write.
|
|
732
|
+
- `timeoutMs` bounds each attempt's request and response body; it defaults
|
|
733
|
+
to 10 seconds. A timeout is the retryable `unavailable` refusal. A cancel
|
|
734
|
+
through `signal` rejects with its reason and is not retried.
|
|
735
|
+
- After CI confirms a write, the SDK invalidates the cache tags of the record
|
|
736
|
+
([Write invalidation](#write-invalidation)).
|
|
737
|
+
- `knowledge.createEntity`, `updateEntity`, `upsertEntity` and `deleteEntity`
|
|
738
|
+
do not reach CI: they reject with `TypeError` and point to
|
|
739
|
+
`/application/v1/resources`. Use `resources.records`.
|
|
740
|
+
|
|
684
741
|
## Records a user acts for
|
|
685
742
|
|
|
686
743
|
A schema declares its accounts field to name the users that act for each of its
|
|
@@ -933,6 +990,9 @@ that reads Effect `Config`:
|
|
|
933
990
|
request)` keeps the CI error envelope as a value; `execute` fails with
|
|
934
991
|
`CiError`. A transport failure fails with `CiTransportError`.
|
|
935
992
|
`sendMessage` and `createUpload` keep the refusal of CI as a value.
|
|
993
|
+
`records.create`, `records.update` and `records.delete`
|
|
994
|
+
([Record writes](#record-writes)) fail with `CiError`; `recordsResult`
|
|
995
|
+
has the same writes and keeps the refusal of CI as a value.
|
|
936
996
|
- Without a `sleep` option, the retry backoff of `ServerClient` is
|
|
937
997
|
`Effect.sleep` on the Clock: `TestClock` drives it, and an interruption
|
|
938
998
|
stops it. With `sleep`, the client waits on that function.
|
|
@@ -1148,6 +1208,137 @@ abort the forwarded request signal. The host owns server and database shutdown.
|
|
|
1148
1208
|
Next, Express and Web against one PostgreSQL resource. `bun run test:pack`
|
|
1149
1209
|
compiles and runs that consumer from the installed package.
|
|
1150
1210
|
|
|
1211
|
+
## Next.js Cache Primitives
|
|
1212
|
+
|
|
1213
|
+
`/next` gives cache tags and a cache lifetime to the CI reads that the app
|
|
1214
|
+
caches with Next.js Cache Components (Next.js 16, `cacheComponents: true`).
|
|
1215
|
+
The SDK ships no cached read, no `"use cache"` directive and no cache store:
|
|
1216
|
+
the app writes the directive in its own function, and the store of Next
|
|
1217
|
+
(built in, or the one that the app configures) holds the entries.
|
|
1218
|
+
|
|
1219
|
+
```ts
|
|
1220
|
+
"use cache"
|
|
1221
|
+
// app/leads/data.ts: every function in this file is cached.
|
|
1222
|
+
import { cacheCiRead } from "@collective-intelligence/external-apps-server-sdk/next"
|
|
1223
|
+
import { ci } from "../server/ci" // createServerClient({ authentication: { mode: "service", credentials }, tenantUrl })
|
|
1224
|
+
|
|
1225
|
+
export const getLead = async (organizationId: string, entityId: string) => {
|
|
1226
|
+
cacheCiRead(ci, { id: entityId, schema: "acme.crm.lead" })
|
|
1227
|
+
return await ci.knowledge.getEntity({ entityId, organizationId })
|
|
1228
|
+
}
|
|
1229
|
+
```
|
|
1230
|
+
|
|
1231
|
+
`cacheCiRead(client, { schema, id?, filter?, life? })` calls `cacheTag` and
|
|
1232
|
+
`cacheLife` of `next/cache`, so call it only inside a `"use cache"` scope:
|
|
1233
|
+
|
|
1234
|
+
- `cacheTag` gets `ciTag.all`, `ciTag.schema(schema)` and, for a get,
|
|
1235
|
+
`ciTag.entity(schema, id)`, or, for a list filtered by `filter`,
|
|
1236
|
+
`ciTag.topic({ schema, filter })`. `schema` is the FQN of the schema.
|
|
1237
|
+
- `cacheLife` gets `life`, by default
|
|
1238
|
+
`{ stale: 60, revalidate: 60, expire: 86400 }` (seconds). A `life` replaces
|
|
1239
|
+
the default as a whole: a field that it does not set keeps the value that
|
|
1240
|
+
Next gives the scope.
|
|
1241
|
+
- `client` must be a service-mode server client. Its reads use the app's own
|
|
1242
|
+
credential and give the same answer to every user. Only a config whose
|
|
1243
|
+
`authentication` type is `{ credentials, mode: "service" }` gives that
|
|
1244
|
+
client type, `ServerClient<"service">`. These clients do not type-check:
|
|
1245
|
+
- a client of a user session (`getAccessToken`, for example with a token
|
|
1246
|
+
from `exchangeMemberSession`);
|
|
1247
|
+
- a client whose mode the type does not know: a client typed
|
|
1248
|
+
`ServerClient`, a client whose `authentication` can have either mode, or
|
|
1249
|
+
the client of `runAsApplication`.
|
|
1250
|
+
|
|
1251
|
+
Keep user-scoped reads in TanStack Query on the client; they never go into
|
|
1252
|
+
the shared cache.
|
|
1253
|
+
|
|
1254
|
+
`ciTag` is the one tag vocabulary of the SDK. Each tag is
|
|
1255
|
+
`ci:<kind>:<base64url(sha256(key))>` with kind `s` (schema), `e` (entity) or
|
|
1256
|
+
`t` (topic), 48 characters, or `ci:all`. A tag holds no id and no filter
|
|
1257
|
+
value in clear text, so it stays within the 256-character limit of Next. The
|
|
1258
|
+
hash has no key: a person who knows the possible values of a key can find the
|
|
1259
|
+
key of a tag by trial, so a tag is not a secret. `ciTag.topic({ schema })`
|
|
1260
|
+
without a filter is the Schema Tag. Tags are `CiTag` strings, a branded type.
|
|
1261
|
+
|
|
1262
|
+
With more than one instance and the built-in in-memory store, an
|
|
1263
|
+
invalidation reaches only the instance that receives it; other instances serve
|
|
1264
|
+
old data until the lifetime ends. Configure a shared cache store when that gap
|
|
1265
|
+
matters. The [Revalidate Route](#realtime-revalidation) revalidates these tags
|
|
1266
|
+
when a realtime change arrives in a tab.
|
|
1267
|
+
|
|
1268
|
+
### Write invalidation
|
|
1269
|
+
|
|
1270
|
+
After CI confirms a write of `resources.records`, the SDK invalidates the
|
|
1271
|
+
Entity Tag (`ciTag.entity(fqn, id)`) and the Schema Tag (`ciTag.schema(fqn)`)
|
|
1272
|
+
of its record, so the next read recomputes each cached entry that carries
|
|
1273
|
+
them. A create, update, delete or restore through the CI entity proxy, which
|
|
1274
|
+
the browser entity hooks use, does the same: `ciResources` of the BFF,
|
|
1275
|
+
`createCiResourceMounts`, `defineCiEntityResource` and `CiEntities`. A read,
|
|
1276
|
+
and a write that CI refuses or that fails, invalidates nothing. The app does
|
|
1277
|
+
not call `revalidateTag` for SDK writes.
|
|
1278
|
+
|
|
1279
|
+
```ts
|
|
1280
|
+
// server/ci.ts
|
|
1281
|
+
import { createServerClient } from "@collective-intelligence/external-apps-server-sdk"
|
|
1282
|
+
import { nextInvalidate } from "@collective-intelligence/external-apps-server-sdk/next"
|
|
1283
|
+
|
|
1284
|
+
export const ci = createServerClient({
|
|
1285
|
+
authentication: { credentials, mode: "service" },
|
|
1286
|
+
invalidate: nextInvalidate,
|
|
1287
|
+
tenantUrl
|
|
1288
|
+
})
|
|
1289
|
+
```
|
|
1290
|
+
|
|
1291
|
+
`runAsApplication` takes the same `invalidate`, and so do `ciResources` of
|
|
1292
|
+
the BFF, `createCiResourceMounts` and `defineCiEntityResource`:
|
|
1293
|
+
|
|
1294
|
+
```ts
|
|
1295
|
+
createExternalApplicationBffNextHandlers({
|
|
1296
|
+
auth,
|
|
1297
|
+
ciResources: {
|
|
1298
|
+
bindings,
|
|
1299
|
+
invalidate: nextInvalidate,
|
|
1300
|
+
organizationId,
|
|
1301
|
+
tenantUrl
|
|
1302
|
+
},
|
|
1303
|
+
publicOrigin: env.APP_ORIGIN
|
|
1304
|
+
})
|
|
1305
|
+
```
|
|
1306
|
+
|
|
1307
|
+
```ts
|
|
1308
|
+
// An Effect server that runs in Next.js
|
|
1309
|
+
import { layerServerClientConfig } from "@collective-intelligence/external-apps-server-sdk/effect"
|
|
1310
|
+
import { CacheInvalidation } from "@collective-intelligence/external-apps-server-sdk/effect/next"
|
|
1311
|
+
|
|
1312
|
+
const runtime = ManagedRuntime.make(
|
|
1313
|
+
Layer.mergeAll(layerServerClientConfig(config), CacheInvalidation.layerNext)
|
|
1314
|
+
)
|
|
1315
|
+
```
|
|
1316
|
+
|
|
1317
|
+
- `nextInvalidate` (`/next`) and `CacheInvalidation.layerNext`
|
|
1318
|
+
(`/effect/next`) call `revalidateTag(tag, { expire: 0 })` of `next/cache`.
|
|
1319
|
+
Next allows that in a Route Handler and a Server Function; write there,
|
|
1320
|
+
not while a page renders.
|
|
1321
|
+
- `/effect` exports `CacheInvalidation`, a `Context.Reference` whose default
|
|
1322
|
+
does nothing. The server client and `CiEntities` read it from the fiber of
|
|
1323
|
+
each write, so provide `layerNext` to the program or merge it into the
|
|
1324
|
+
runtime, next to their layers. `Layer.provide` of `layerNext` to
|
|
1325
|
+
`layerServerClient` or `layerCiEntities` does not reach the writes. An app
|
|
1326
|
+
can provide its own `CacheInvalidation`, for example in a test.
|
|
1327
|
+
- Without `invalidate` or a `CacheInvalidation`, a write behaves as before.
|
|
1328
|
+
- The tags need the FQN of the schema. A write named by FQN has it, and a
|
|
1329
|
+
write of the CI entity proxy has the `schemaFqn` of its binding. For a
|
|
1330
|
+
write named by schema id, and only when an invalidation is set, the SDK
|
|
1331
|
+
reads the schema snapshot (`knowledge.getEntitySchemaSnapshot`) once per
|
|
1332
|
+
process for each schema id, in either letter case, and every client of
|
|
1333
|
+
the process uses the FQN. When the snapshot gives no FQN, the write
|
|
1334
|
+
invalidates nothing and logs a warning; the write itself does not fail.
|
|
1335
|
+
- CI has the write before the invalidation starts, so a failure of the
|
|
1336
|
+
invalidation does not fail the write. When `invalidate` throws or
|
|
1337
|
+
rejects, or `revalidateTag` throws, as it does outside a Next.js request
|
|
1338
|
+
or while a page renders, the write logs a warning with the tags and
|
|
1339
|
+
resolves the record that CI confirmed. The cached entries keep their old
|
|
1340
|
+
value until their lifetime ends.
|
|
1341
|
+
|
|
1151
1342
|
## Shared CRUD resources
|
|
1152
1343
|
|
|
1153
1344
|
Expose a remote resource once with `defineGateway({ knowledge: [{ resource,
|
|
@@ -1208,15 +1399,33 @@ while authentication policy and configuration remain app-owned. The same
|
|
|
1208
1399
|
entrypoint also exports the individual store factories for hosts that need
|
|
1209
1400
|
custom composition.
|
|
1210
1401
|
|
|
1211
|
-
|
|
1212
|
-
`
|
|
1402
|
+
`@collective-intelligence/external-apps-server-sdk/effect` exports the service
|
|
1403
|
+
`DrizzlePostgres`, `DrizzlePostgresInitializationError` and
|
|
1404
|
+
`layerFromDatabase`. It imports no optional peer, so an app without `pg` and
|
|
1405
|
+
`drizzle-orm` loads it and builds with it.
|
|
1406
|
+
|
|
1407
|
+
`layerNodePostgres` is at
|
|
1408
|
+
`@collective-intelligence/external-apps-server-sdk/effect/node-postgres`:
|
|
1409
|
+
|
|
1410
|
+
```ts
|
|
1411
|
+
import { DrizzlePostgres } from "@collective-intelligence/external-apps-server-sdk/effect"
|
|
1412
|
+
import { layerNodePostgres } from "@collective-intelligence/external-apps-server-sdk/effect/node-postgres"
|
|
1413
|
+
```
|
|
1414
|
+
|
|
1213
1415
|
The Node PostgreSQL layer owns the pool lifetime and accepts an explicit
|
|
1214
|
-
`migrate` hook. It
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
`
|
|
1219
|
-
`
|
|
1416
|
+
`migrate` hook. It never discovers a migration directory or runs hidden DDL.
|
|
1417
|
+
`/effect/node-postgres` imports `pg` and `drizzle-orm/node-postgres`
|
|
1418
|
+
statically. The bundler and the output tracing of an app see both, so a
|
|
1419
|
+
Next.js app with `output: "standalone"` gets them in its output without a
|
|
1420
|
+
`serverExternalPackages` entry. Install both: without one, the import of
|
|
1421
|
+
`/effect/node-postgres` fails, in Node.js with `Cannot find package` and in a
|
|
1422
|
+
bundler with `Module not found`. A bad pool config or a failed migration fails
|
|
1423
|
+
the layer with `DrizzlePostgresInitializationError`.
|
|
1424
|
+
`DrizzlePostgres` and `DrizzlePostgresInitializationError` have one identity
|
|
1425
|
+
in `/effect`, `/effect/node-postgres` and `/persistence/drizzle/effect`. The
|
|
1426
|
+
declarations of `/effect` and `/effect/node-postgres` refer to `drizzle-orm`
|
|
1427
|
+
and `pg` types: an application that type checks with `skipLibCheck: false`
|
|
1428
|
+
installs `drizzle-orm` and `@types/pg`.
|
|
1220
1429
|
|
|
1221
1430
|
The generic machine resource API retains its explicit hard-delete behavior.
|
|
1222
1431
|
Updates and hard deletes compare and replace the revision atomically. Stale
|
|
@@ -1600,6 +1809,9 @@ const resource = defineCiEntityResource({
|
|
|
1600
1809
|
```
|
|
1601
1810
|
|
|
1602
1811
|
The tenant HTTPS origin, organization, and schema FQN are server configuration.
|
|
1812
|
+
With `invalidate: nextInvalidate` (`/next`), each create, update, delete or
|
|
1813
|
+
restore that CI confirms invalidates the cache tags of its record
|
|
1814
|
+
([Write invalidation](#write-invalidation)).
|
|
1603
1815
|
Pass the original context returned by `auth.getEntityContext` to the handler;
|
|
1604
1816
|
copying or serializing it intentionally loses its private forwarding capability.
|
|
1605
1817
|
The verified grant stays server-side. CI rechecks current application/user policy
|
|
@@ -1613,7 +1825,7 @@ explicit resubmission.
|
|
|
1613
1825
|
#### File uploads through the BFF
|
|
1614
1826
|
|
|
1615
1827
|
When the definition declares `capabilities.upload: true`, the handler also
|
|
1616
|
-
accepts `POST {basePath}/uploads` with `{ field, filename, mimeType }`. It calls
|
|
1828
|
+
accepts `POST {basePath}/uploads` with `{ field, filename, mimeType, size }`. It calls
|
|
1617
1829
|
`authorize` with the operation `upload`, then forwards the request with the
|
|
1618
1830
|
verified grant to `/application/v1/resources/{schemaFqn}/uploads`. CI answers
|
|
1619
1831
|
the File upload `{ uploadId, url, method: "PUT", headers }`; the browser PUTs
|
|
@@ -1656,6 +1868,74 @@ per-user connection cap, 503 `unavailable`. Use
|
|
|
1656
1868
|
`createRealtimeTicketHandler` from `/runtime/web` or `/next` to mount
|
|
1657
1869
|
the route yourself. The client SDK README documents the browser client.
|
|
1658
1870
|
|
|
1871
|
+
### Realtime revalidation
|
|
1872
|
+
|
|
1873
|
+
With `secrets`, each ticket answer also holds `grantToken`: the Topic Grant
|
|
1874
|
+
of the ticket. It holds the Realtime Topics that CI accepted, the session of
|
|
1875
|
+
the request and an expiry 10 minutes after mint, sealed with the secret, so
|
|
1876
|
+
the browser cannot read or change it. `revalidate` mounts the Revalidate
|
|
1877
|
+
Route `POST {basePath}/realtime/revalidate` next to the ticket route. It
|
|
1878
|
+
revalidates the [Next.js cache tags](#nextjs-cache-primitives) of the
|
|
1879
|
+
realtime changes that a tab posts:
|
|
1880
|
+
|
|
1881
|
+
```ts
|
|
1882
|
+
import {
|
|
1883
|
+
createExternalApplicationBffNextHandlers,
|
|
1884
|
+
createRealtimeRevalidateHandler
|
|
1885
|
+
} from "@collective-intelligence/external-apps-server-sdk/next"
|
|
1886
|
+
|
|
1887
|
+
createExternalApplicationBffNextHandlers({
|
|
1888
|
+
auth,
|
|
1889
|
+
publicOrigin: env.APP_ORIGIN,
|
|
1890
|
+
realtime: {
|
|
1891
|
+
organizationId: env.CI_ORGANIZATION_ID,
|
|
1892
|
+
tenantUrl: env.CI_TENANT_URL,
|
|
1893
|
+
// The session secrets, the current one first.
|
|
1894
|
+
secrets: [env.SESSION_SECRET],
|
|
1895
|
+
revalidate: createRealtimeRevalidateHandler
|
|
1896
|
+
}
|
|
1897
|
+
})
|
|
1898
|
+
```
|
|
1899
|
+
|
|
1900
|
+
Give the realtime client of the browser
|
|
1901
|
+
`revalidateUrl: "/api/realtime/revalidate"` (client SDK README).
|
|
1902
|
+
|
|
1903
|
+
- The route reads `{ token, changes: { topic, id }[], reset? }` as JSON from
|
|
1904
|
+
the application's own origin. It refuses a token that it did not seal, that
|
|
1905
|
+
expired or that another session got (403 `invalid_grant`), and a request
|
|
1906
|
+
without a session (401). It ignores a change whose topic is not in the
|
|
1907
|
+
token. It refuses a body of more than 100 changes or 1 MiB (400
|
|
1908
|
+
`invalid_request`); the client SDK splits a larger delivery into bodies of
|
|
1909
|
+
100 changes.
|
|
1910
|
+
- For each accepted change it revalidates the Topic Tag
|
|
1911
|
+
(`ciTag.topic(topic)`, the Schema Tag for a topic without a filter) and the
|
|
1912
|
+
Entity Tag. `reset: true`, which the client posts after a `reset` or
|
|
1913
|
+
`access-changed` event, revalidates the tag of each topic in the token. The
|
|
1914
|
+
route never revalidates `ci:all`.
|
|
1915
|
+
- It calls `revalidateTag(tag, { expire: 0 })`, so the next read computes the
|
|
1916
|
+
entry again. On one instance, the first post for a tag revalidates it at
|
|
1917
|
+
once and opens a window of 1 second. When more posts for that tag arrive in
|
|
1918
|
+
the window, the route revalidates the tag once more at the window end,
|
|
1919
|
+
through `after` of `next/server`. It never compares event ids. Each other
|
|
1920
|
+
instance revalidates on the posts that it receives.
|
|
1921
|
+
- Each tab keeps its own token in memory, and each ticket renews it. No grant
|
|
1922
|
+
state is shared between tabs, so two tabs that get tickets at the same time
|
|
1923
|
+
both keep their grants. A stream can stay open longer than its token: the
|
|
1924
|
+
client SDK asks the ticket route for a new ticket 8 minutes after each
|
|
1925
|
+
token while the stream stays open, and keeps only the new token. Each
|
|
1926
|
+
renewal thus mints one CI ticket that no stream uses.
|
|
1927
|
+
- `secrets` needs `auth.getSession`; the BFF gives both routes its `auth`. To
|
|
1928
|
+
mount the route yourself, call `createRealtimeRevalidateHandler` from `/next`
|
|
1929
|
+
with the `auth` and the `secrets` of the ticket route.
|
|
1930
|
+
- The token binds to the `sessionId` of the `ApplicationUserSession` that
|
|
1931
|
+
`getSession` returns, so another session of the same user cannot use it.
|
|
1932
|
+
`createFederatedAuth` gives the `sid` claim of the CI Access token, which
|
|
1933
|
+
stays the same after a renewal; `createBetterAuth` gives the id of the
|
|
1934
|
+
Better Auth session. `sessionId` is optional: when a custom
|
|
1935
|
+
`ApplicationUserAuth` gives none, the token binds to the user identity,
|
|
1936
|
+
and each session of that user can use it. Give a session id that stays
|
|
1937
|
+
the same for each request of one session.
|
|
1938
|
+
|
|
1659
1939
|
## Optional local user authentication
|
|
1660
1940
|
|
|
1661
1941
|
Import `createBetterAuth` only from
|
|
@@ -1665,8 +1945,9 @@ database and own its migrations and model names. Enable password login
|
|
|
1665
1945
|
explicitly with `emailAndPassword: { enabled: true }` when required.
|
|
1666
1946
|
|
|
1667
1947
|
The adapter verifies sessions against SQL on every lookup; cookie session caches
|
|
1668
|
-
and secondary storage are disabled. `getSession` returns a session
|
|
1669
|
-
|
|
1948
|
+
and secondary storage are disabled. `getSession` returns a session, with the
|
|
1949
|
+
Better Auth session id as `sessionId`, or `null`, and reports database outages
|
|
1950
|
+
through a typed unavailable error. Local user
|
|
1670
1951
|
identity grants no CI organization or gateway machine authority. The CRM demo
|
|
1671
1952
|
uses federated authentication.
|
|
1672
1953
|
|
|
@@ -1708,7 +1989,8 @@ the only source of published JavaScript and declarations. Confidential CI
|
|
|
1708
1989
|
clients live under `src/clients`; application login belongs to
|
|
1709
1990
|
`src/application-auth`; gateway machine authorization, definitions, and HTTP
|
|
1710
1991
|
routing stay under `src/gateway`; portable resource behavior stays under
|
|
1711
|
-
`src/resources`;
|
|
1992
|
+
`src/resources`; write invalidation stays under `src/cache`; and proxy
|
|
1993
|
+
policy stays under `src/proxy`.
|
|
1712
1994
|
|
|
1713
1995
|
Framework runtimes, provider mappings, persistence adapters, and private
|
|
1714
1996
|
generated-client bridges are isolated under `src/adapters`. Optional peer
|
package/dist/admin.d.ts
CHANGED
|
@@ -377,6 +377,7 @@ declare const KnowledgeFileVisibility: {
|
|
|
377
377
|
export type KnowledgeFileVisibility = typeof KnowledgeFileVisibility[keyof typeof KnowledgeFileVisibility];
|
|
378
378
|
export type KnowledgeFileFieldEntry = {
|
|
379
379
|
accepts: Array<string>;
|
|
380
|
+
maxBytes?: number;
|
|
380
381
|
multiple: boolean;
|
|
381
382
|
};
|
|
382
383
|
export type PackageOperationAccepted = {
|
|
@@ -19,6 +19,12 @@ export type ApplicationUserIdentity = Readonly<{
|
|
|
19
19
|
export type ApplicationUserSession = Readonly<{
|
|
20
20
|
identity: ApplicationUserIdentity;
|
|
21
21
|
expiresAt: Date;
|
|
22
|
+
/**
|
|
23
|
+
* The id of the login session, the same for each request of that session.
|
|
24
|
+
* The federated and better-auth adapters give it; the Topic Grant binds to
|
|
25
|
+
* it, or to `identity` without it (Q109).
|
|
26
|
+
*/
|
|
27
|
+
sessionId?: string;
|
|
22
28
|
}>;
|
|
23
29
|
/** Constructed only after user/app/organization authorization at server ingress.
|
|
24
30
|
* Canonical identities survive proxy hops and scope mutation receipts; credentials
|
package/dist/auth/better-auth.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{betterAuth}from"better-auth";var unavailableBrand=Symbol.for("@collective-intelligence/external-apps-server-sdk/ApplicationUserAuthUnavailableError");class ApplicationUserAuthUnavailableError extends Error{[unavailableBrand]=true;code="user_auth_unavailable";static[Symbol.hasInstance](value){return value instanceof Error&&unavailableBrand in value&&value[unavailableBrand]===true&&"code"in value&&value.code==="user_auth_unavailable"}constructor(cause){super("Application user authentication is unavailable",{cause});this.name="ApplicationUserAuthUnavailableError"}}var createBetterAuth=(options)=>{if(options.database===undefined||options.database===null){throw new TypeError("Application-owned SQL persistence is required")}const auth=betterAuth({...options,plugins:[],secondaryStorage:undefined,session:{...options.session,cookieCache:{enabled:false},preserveSessionInDatabase:false,storeSessionInDatabase:true}});return{getEntityContext:async()=>null,getSession:async(request)=>{const result=await auth.api.getSession({headers:request.headers,query:{disableCookieCache:true}}).catch((error)=>{throw new ApplicationUserAuthUnavailableError(error)});if(result===null){return null}return{expiresAt:result.session.expiresAt,identity:{email:result.user.email,id:result.user.id,kind:"local_user",name:result.user.name}}},handler:auth.handler,mode:"local"}};var ApplicationUserAuthUnavailableError2=ApplicationUserAuthUnavailableError;var createBetterAuth2=createBetterAuth;export{ApplicationUserAuthUnavailableError2 as ApplicationUserAuthUnavailableError,createBetterAuth2 as createBetterAuth};
|
|
1
|
+
import{betterAuth}from"better-auth";var unavailableBrand=Symbol.for("@collective-intelligence/external-apps-server-sdk/ApplicationUserAuthUnavailableError");class ApplicationUserAuthUnavailableError extends Error{[unavailableBrand]=true;code="user_auth_unavailable";static[Symbol.hasInstance](value){return value instanceof Error&&unavailableBrand in value&&value[unavailableBrand]===true&&"code"in value&&value.code==="user_auth_unavailable"}constructor(cause){super("Application user authentication is unavailable",{cause});this.name="ApplicationUserAuthUnavailableError"}}var createBetterAuth=(options)=>{if(options.database===undefined||options.database===null){throw new TypeError("Application-owned SQL persistence is required")}const auth=betterAuth({...options,plugins:[],secondaryStorage:undefined,session:{...options.session,cookieCache:{enabled:false},preserveSessionInDatabase:false,storeSessionInDatabase:true}});return{getEntityContext:async()=>null,getSession:async(request)=>{const result=await auth.api.getSession({headers:request.headers,query:{disableCookieCache:true}}).catch((error)=>{throw new ApplicationUserAuthUnavailableError(error)});if(result===null){return null}return{expiresAt:result.session.expiresAt,identity:{email:result.user.email,id:result.user.id,kind:"local_user",name:result.user.name},sessionId:result.session.id}},handler:auth.handler,mode:"local"}};var ApplicationUserAuthUnavailableError2=ApplicationUserAuthUnavailableError;var createBetterAuth2=createBetterAuth;export{ApplicationUserAuthUnavailableError2 as ApplicationUserAuthUnavailableError,createBetterAuth2 as createBetterAuth};
|
package/dist/auth/federated.d.ts
CHANGED
|
@@ -17,6 +17,12 @@ export type ApplicationUserIdentity = Readonly<{
|
|
|
17
17
|
export type ApplicationUserSession = Readonly<{
|
|
18
18
|
identity: ApplicationUserIdentity;
|
|
19
19
|
expiresAt: Date;
|
|
20
|
+
/**
|
|
21
|
+
* The id of the login session, the same for each request of that session.
|
|
22
|
+
* The federated and better-auth adapters give it; the Topic Grant binds to
|
|
23
|
+
* it, or to `identity` without it (Q109).
|
|
24
|
+
*/
|
|
25
|
+
sessionId?: string;
|
|
20
26
|
}>;
|
|
21
27
|
/** Constructed only after user/app/organization authorization at server ingress.
|
|
22
28
|
* Canonical identities survive proxy hops and scope mutation receipts; credentials
|