@collective-intelligence/external-apps-server-sdk 0.1.39 → 0.1.41

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
@@ -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) and
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 replacement, so classes and service tags have one
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
 
@@ -682,6 +691,53 @@ if (slot.ok) {
682
691
  values; a portable resource form has no File field, so
683
692
  `projectResourceSchema` refuses them.
684
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
+
685
741
  ## Records a user acts for
686
742
 
687
743
  A schema declares its accounts field to name the users that act for each of its
@@ -934,6 +990,9 @@ that reads Effect `Config`:
934
990
  request)` keeps the CI error envelope as a value; `execute` fails with
935
991
  `CiError`. A transport failure fails with `CiTransportError`.
936
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.
937
996
  - Without a `sleep` option, the retry backoff of `ServerClient` is
938
997
  `Effect.sleep` on the Clock: `TestClock` drives it, and an interruption
939
998
  stops it. With `sleep`, the client waits on that function.
@@ -1149,6 +1208,137 @@ abort the forwarded request signal. The host owns server and database shutdown.
1149
1208
  Next, Express and Web against one PostgreSQL resource. `bun run test:pack`
1150
1209
  compiles and runs that consumer from the installed package.
1151
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
+
1152
1342
  ## Shared CRUD resources
1153
1343
 
1154
1344
  Expose a remote resource once with `defineGateway({ knowledge: [{ resource,
@@ -1163,7 +1353,10 @@ identifies CI's destination organization; it never adds a source-row predicate.
1163
1353
  and gateway authorization policies. Its validated `executeCrud` service is also
1164
1354
  used by `createResourceHttpHandler({ resource, basePath, authorize })`; the host
1165
1355
  must authorize browser requests explicitly. A browser session is not a machine
1166
- caller identity. Both transports enforce declared capabilities, schemas,
1356
+ caller identity. For an entity batch (`POST records/batch`), the handler calls
1357
+ `authorize` with `"batch"` and then once for each distinct op kind in the
1358
+ batch (`create`, `update`, `delete`, `restore`); one refusal refuses the whole
1359
+ batch before any write. Both transports enforce declared capabilities, schemas,
1167
1360
  revision preconditions and idempotency keys.
1168
1361
 
1169
1362
  The application routes are `POST /search`, `POST /records`, and
@@ -1209,15 +1402,33 @@ while authentication policy and configuration remain app-owned. The same
1209
1402
  entrypoint also exports the individual store factories for hosts that need
1210
1403
  custom composition.
1211
1404
 
1212
- Effect applications may import `DrizzlePostgres`, `layerFromDatabase`, and
1213
- `layerNodePostgres` from `@collective-intelligence/external-apps-server-sdk/effect`.
1405
+ `@collective-intelligence/external-apps-server-sdk/effect` exports the service
1406
+ `DrizzlePostgres`, `DrizzlePostgresInitializationError` and
1407
+ `layerFromDatabase`. It imports no optional peer, so an app without `pg` and
1408
+ `drizzle-orm` loads it and builds with it.
1409
+
1410
+ `layerNodePostgres` is at
1411
+ `@collective-intelligence/external-apps-server-sdk/effect/node-postgres`:
1412
+
1413
+ ```ts
1414
+ import { DrizzlePostgres } from "@collective-intelligence/external-apps-server-sdk/effect"
1415
+ import { layerNodePostgres } from "@collective-intelligence/external-apps-server-sdk/effect/node-postgres"
1416
+ ```
1417
+
1214
1418
  The Node PostgreSQL layer owns the pool lifetime and accepts an explicit
1215
- `migrate` hook. It loads the optional `pg` and `drizzle-orm` peers when it
1216
- builds, so `/effect` loads without them. It never discovers a migration directory or runs hidden DDL.
1217
- A missing peer, a bad pool config or a failed migration fails the layer with
1218
- `DrizzlePostgresInitializationError`. The `/effect` declarations refer to
1219
- `drizzle-orm` and `pg` types: an application that type checks with
1220
- `skipLibCheck: false` installs `drizzle-orm` and `@types/pg`.
1419
+ `migrate` hook. It never discovers a migration directory or runs hidden DDL.
1420
+ `/effect/node-postgres` imports `pg` and `drizzle-orm/node-postgres`
1421
+ statically. The bundler and the output tracing of an app see both, so a
1422
+ Next.js app with `output: "standalone"` gets them in its output without a
1423
+ `serverExternalPackages` entry. Install both: without one, the import of
1424
+ `/effect/node-postgres` fails, in Node.js with `Cannot find package` and in a
1425
+ bundler with `Module not found`. A bad pool config or a failed migration fails
1426
+ the layer with `DrizzlePostgresInitializationError`.
1427
+ `DrizzlePostgres` and `DrizzlePostgresInitializationError` have one identity
1428
+ in `/effect`, `/effect/node-postgres` and `/persistence/drizzle/effect`. The
1429
+ declarations of `/effect` and `/effect/node-postgres` refer to `drizzle-orm`
1430
+ and `pg` types: an application that type checks with `skipLibCheck: false`
1431
+ installs `drizzle-orm` and `@types/pg`.
1221
1432
 
1222
1433
  The generic machine resource API retains its explicit hard-delete behavior.
1223
1434
  Updates and hard deletes compare and replace the revision atomically. Stale
@@ -1601,6 +1812,9 @@ const resource = defineCiEntityResource({
1601
1812
  ```
1602
1813
 
1603
1814
  The tenant HTTPS origin, organization, and schema FQN are server configuration.
1815
+ With `invalidate: nextInvalidate` (`/next`), each create, update, delete or
1816
+ restore that CI confirms invalidates the cache tags of its record
1817
+ ([Write invalidation](#write-invalidation)).
1604
1818
  Pass the original context returned by `auth.getEntityContext` to the handler;
1605
1819
  copying or serializing it intentionally loses its private forwarding capability.
1606
1820
  The verified grant stays server-side. CI rechecks current application/user policy
@@ -1657,6 +1871,74 @@ per-user connection cap, 503 `unavailable`. Use
1657
1871
  `createRealtimeTicketHandler` from `/runtime/web` or `/next` to mount
1658
1872
  the route yourself. The client SDK README documents the browser client.
1659
1873
 
1874
+ ### Realtime revalidation
1875
+
1876
+ With `secrets`, each ticket answer also holds `grantToken`: the Topic Grant
1877
+ of the ticket. It holds the Realtime Topics that CI accepted, the session of
1878
+ the request and an expiry 10 minutes after mint, sealed with the secret, so
1879
+ the browser cannot read or change it. `revalidate` mounts the Revalidate
1880
+ Route `POST {basePath}/realtime/revalidate` next to the ticket route. It
1881
+ revalidates the [Next.js cache tags](#nextjs-cache-primitives) of the
1882
+ realtime changes that a tab posts:
1883
+
1884
+ ```ts
1885
+ import {
1886
+ createExternalApplicationBffNextHandlers,
1887
+ createRealtimeRevalidateHandler
1888
+ } from "@collective-intelligence/external-apps-server-sdk/next"
1889
+
1890
+ createExternalApplicationBffNextHandlers({
1891
+ auth,
1892
+ publicOrigin: env.APP_ORIGIN,
1893
+ realtime: {
1894
+ organizationId: env.CI_ORGANIZATION_ID,
1895
+ tenantUrl: env.CI_TENANT_URL,
1896
+ // The session secrets, the current one first.
1897
+ secrets: [env.SESSION_SECRET],
1898
+ revalidate: createRealtimeRevalidateHandler
1899
+ }
1900
+ })
1901
+ ```
1902
+
1903
+ Give the realtime client of the browser
1904
+ `revalidateUrl: "/api/realtime/revalidate"` (client SDK README).
1905
+
1906
+ - The route reads `{ token, changes: { topic, id }[], reset? }` as JSON from
1907
+ the application's own origin. It refuses a token that it did not seal, that
1908
+ expired or that another session got (403 `invalid_grant`), and a request
1909
+ without a session (401). It ignores a change whose topic is not in the
1910
+ token. It refuses a body of more than 100 changes or 1 MiB (400
1911
+ `invalid_request`); the client SDK splits a larger delivery into bodies of
1912
+ 100 changes.
1913
+ - For each accepted change it revalidates the Topic Tag
1914
+ (`ciTag.topic(topic)`, the Schema Tag for a topic without a filter) and the
1915
+ Entity Tag. `reset: true`, which the client posts after a `reset` or
1916
+ `access-changed` event, revalidates the tag of each topic in the token. The
1917
+ route never revalidates `ci:all`.
1918
+ - It calls `revalidateTag(tag, { expire: 0 })`, so the next read computes the
1919
+ entry again. On one instance, the first post for a tag revalidates it at
1920
+ once and opens a window of 1 second. When more posts for that tag arrive in
1921
+ the window, the route revalidates the tag once more at the window end,
1922
+ through `after` of `next/server`. It never compares event ids. Each other
1923
+ instance revalidates on the posts that it receives.
1924
+ - Each tab keeps its own token in memory, and each ticket renews it. No grant
1925
+ state is shared between tabs, so two tabs that get tickets at the same time
1926
+ both keep their grants. A stream can stay open longer than its token: the
1927
+ client SDK asks the ticket route for a new ticket 8 minutes after each
1928
+ token while the stream stays open, and keeps only the new token. Each
1929
+ renewal thus mints one CI ticket that no stream uses.
1930
+ - `secrets` needs `auth.getSession`; the BFF gives both routes its `auth`. To
1931
+ mount the route yourself, call `createRealtimeRevalidateHandler` from `/next`
1932
+ with the `auth` and the `secrets` of the ticket route.
1933
+ - The token binds to the `sessionId` of the `ApplicationUserSession` that
1934
+ `getSession` returns, so another session of the same user cannot use it.
1935
+ `createFederatedAuth` gives the `sid` claim of the CI Access token, which
1936
+ stays the same after a renewal; `createBetterAuth` gives the id of the
1937
+ Better Auth session. `sessionId` is optional: when a custom
1938
+ `ApplicationUserAuth` gives none, the token binds to the user identity,
1939
+ and each session of that user can use it. Give a session id that stays
1940
+ the same for each request of one session.
1941
+
1660
1942
  ## Optional local user authentication
1661
1943
 
1662
1944
  Import `createBetterAuth` only from
@@ -1666,8 +1948,9 @@ database and own its migrations and model names. Enable password login
1666
1948
  explicitly with `emailAndPassword: { enabled: true }` when required.
1667
1949
 
1668
1950
  The adapter verifies sessions against SQL on every lookup; cookie session caches
1669
- and secondary storage are disabled. `getSession` returns a session or `null`,
1670
- and reports database outages through a typed unavailable error. Local user
1951
+ and secondary storage are disabled. `getSession` returns a session, with the
1952
+ Better Auth session id as `sessionId`, or `null`, and reports database outages
1953
+ through a typed unavailable error. Local user
1671
1954
  identity grants no CI organization or gateway machine authority. The CRM demo
1672
1955
  uses federated authentication.
1673
1956
 
@@ -1709,7 +1992,8 @@ the only source of published JavaScript and declarations. Confidential CI
1709
1992
  clients live under `src/clients`; application login belongs to
1710
1993
  `src/application-auth`; gateway machine authorization, definitions, and HTTP
1711
1994
  routing stay under `src/gateway`; portable resource behavior stays under
1712
- `src/resources`; and proxy policy stays under `src/proxy`.
1995
+ `src/resources`; write invalidation stays under `src/cache`; and proxy
1996
+ policy stays under `src/proxy`.
1713
1997
 
1714
1998
  Framework runtimes, provider mappings, persistence adapters, and private
1715
1999
  generated-client bridges are isolated under `src/adapters`. Optional peer
@@ -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
@@ -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};
@@ -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