@jskit-ai/workspaces-core 0.2.15 → 0.2.16

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 (61) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/locales/en.json +0 -5
  3. package/package.json +26 -16
  4. package/patterns/workspace-server/PATTERN.md +9 -9
  5. package/src/server/WorkspacesFeature.js +28 -16
  6. package/src/server/WorkspacesIntegrationsProvider.js +5 -6
  7. package/src/server/common/repositories/workspaceInvitesRepository.js +69 -123
  8. package/src/server/common/repositories/workspaceMembershipsRepository.js +106 -146
  9. package/src/server/common/repositories/workspacesRepository.js +105 -113
  10. package/src/server/common/services/workspaceDirectoryService.js +39 -19
  11. package/src/server/common/support/realtimeServiceEvents.js +19 -17
  12. package/src/server/support/resolveWorkspace.js +1 -1
  13. package/src/server/support/workspaceCrud.js +1 -1
  14. package/src/server/types.js +14 -3
  15. package/src/server/workspaceDirectory/workspaceDirectoryActions.js +7 -7
  16. package/src/server/workspaceDirectory/workspaceDirectoryRoutes.js +6 -6
  17. package/src/server/workspaceMembers/workspaceMembersActions.js +31 -30
  18. package/src/server/workspaceMembers/workspaceMembersRoutes.js +10 -10
  19. package/src/server/workspaceMembers/workspaceMembersService.js +35 -24
  20. package/src/server/workspacePendingInvitations/workspacePendingInvitationsActions.js +4 -4
  21. package/src/server/workspacePendingInvitations/workspacePendingInvitationsRoutes.js +7 -7
  22. package/src/server/workspacePendingInvitations/workspacePendingInvitationsService.js +8 -11
  23. package/src/server/workspaceSettings/workspaceSettingsActions.js +4 -4
  24. package/src/server/workspaceSettings/workspaceSettingsRepository.js +19 -50
  25. package/src/server/workspaceSettings/workspaceSettingsRoutes.js +4 -4
  26. package/src/server/workspacesRuntime.js +40 -47
  27. package/src/shared/resources/workspaceAssistantOutputs.js +1 -1
  28. package/src/shared/resources/workspaceInvitesResource.js +12 -73
  29. package/src/shared/resources/workspaceMembersResource.js +3 -3
  30. package/src/shared/resources/workspaceMembershipsResource.js +10 -48
  31. package/src/shared/resources/workspacePendingInvitationsResource.js +3 -3
  32. package/src/shared/resources/workspaceResource.js +20 -17
  33. package/src/shared/resources/workspaceSettingsResource.js +16 -24
  34. package/src/test/WorkspaceRecordsFeature.js +27 -0
  35. package/test/exportsContract.test.js +2 -0
  36. package/test/featureRuntime.test.js +34 -41
  37. package/test/repositories.integration.test.js +264 -41
  38. package/test/repositoryContracts.test.js +52 -40
  39. package/test/resourcesCanonical.test.js +41 -38
  40. package/test/roleLabels.test.js +10 -10
  41. package/test/support/invitationTransactions.js +49 -47
  42. package/test/support/mysqlWorkspaces.js +129 -0
  43. package/test/usersRouteResources.test.js +17 -17
  44. package/test/workspaceDirectoryService.mysql.test.js +255 -0
  45. package/test/workspaceInvitesRepository.mysql.test.js +355 -0
  46. package/test/workspaceMembersResource.test.js +2 -2
  47. package/test/workspaceMembersService.mysql.test.js +223 -0
  48. package/test/workspaceMembersService.test.js +10 -10
  49. package/test/workspacePendingInvitationsResource.test.js +6 -6
  50. package/test/workspacePendingInvitationsService.mysql.test.js +292 -0
  51. package/test/workspacePendingInvitationsService.test.js +2 -2
  52. package/test/workspaceRecords.test.js +142 -0
  53. package/test/workspaceRecordsFeature.test.js +42 -0
  54. package/test/workspaceService.test.js +2 -2
  55. package/test/workspaceSettingsActions.test.js +26 -21
  56. package/test/workspaceSettingsRepository.test.js +66 -86
  57. package/test/workspaceSettingsResource.test.js +5 -5
  58. package/test/workspaceInternalCrudResources.test.js +0 -98
  59. package/test/workspaceInvitesRepository.test.js +0 -318
  60. package/test/workspaceMembershipsRepository.test.js +0 -329
  61. package/test/workspacesRepository.test.js +0 -410
package/CHANGELOG.md CHANGED
@@ -2,6 +2,18 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - An anonymous visitor on a workspace surface that does not require membership (`requireMembership: false`, such as a public payment link under `/api/w/<slug>/...`) resolves to the workspace with no membership and no permissions, as a signed-in non-member does, where every such request answered 401 `workspaces.auth.required`. A surface that requires membership still answers 401 to an anonymous visitor, before it reads the workspace.
6
+ - The workspace settings colours and `invitesEnabled`, and the role and status of a membership and of an invite, are no longer `required`, which `defineTableResource` now refuses beside `defaultTo`: a create that leaves one out gets its default where it failed REQUIRED. The settings contract keeps its own body and output schemas, so requests are unchanged.
7
+ - `@jskit-ai/database-runtime` and `@jskit-ai/resource-runtime` are peer dependencies, required and at the same versions, where they were dependencies: its workspaces, memberships, invites and settings are table resources, and the app holds one copy of the table runtime that every package shares, as it does the kernel. npm installs a required peer as it installed the dependency, so an app installs the same packages and versions; a release whose versions disagree now fails the install with ERESOLVE instead of nesting a second copy.
8
+ - `workspaces.listByIds(ids, options)` reads the workspaces with these ids in one statement however many, sorted by id; an id naming none is left out and a deleted workspace kept, as `findById` keeps it. A caller that read one workspace per id with `findById` reads them at once.
9
+ - `workspaces.joinSource({ alias, filters }, options)` and `workspaces.memberships.joinSource({ alias, filters }, options)` answer `{ query, column }`: the scoped workspaces or memberships under `alias`, matching the resource's search filters (such as `{ deletedAt: null }`, or `{ workspace, status: "active" }`), and each field's column under that alias. Another feature's report joins them as subqueries in its own statement, instead of joining `workspaces` or `workspace_memberships` by name, which reads them past their owner.
10
+ - `@jskit-ai/workspaces-core/test/WorkspaceRecordsFeature` exports `WorkspaceRecordsFeature`, for an application's tests. It owns the workspaces tables as `workspaces.core` does and provides only its records, `workspaces` and `workspaces.memberships`, without the routes, settings and invitations, so a test can start it beside the feature it tests with `startTestFeatures`. `WorkspacesFeature` and it name the four tables once, as `WORKSPACES_TABLES`.
11
+ - The workspaces, memberships, invites and settings table resources no longer declare their own `id` search entry (nor `search: true` on the settings' `id` field): their handles' `id` filter takes one id or a list.
12
+ - Security: a new workspace that loses its slug to a concurrent create answers the workspace already there only when that one has the same owner and the same personal flag (a personal workspace made twice at a first sign-in). It never answers another owner's workspace, which it used to; the directory then picks the next free slug and creates the caller's own, up to three times, and a duplicate inside the caller's transaction fails it as before.
13
+ - The invitation bootstrap audience says `publicTablesOnly: true`: it reads the invite and the recipient's profile, both public tables, so an app needs no `RealtimeAudienceScopeFeature` for it, now that realtime refuses to boot without one for any other `audienceUsers` audience.
14
+ - `workspaces.memberships` gains `listByWorkspaceId(workspaceId, options)`: every member of a workspace whatever their membership's status, such as one just removed (`revoked`), each summary with its status, as `listActiveByWorkspaceId` lists the active ones, in the same single read with the users included.
15
+ - **Breaking (data-access redesign).** `WorkspacesFeature` owns the `workspaces`, `workspace_memberships`, `workspace_invites` and `workspace_settings` tables through `defineFeature({ owns })` and its repositories read and write them through their resource handles, instead of registering them on `runtime.json-rest-api`; it requires `runtime.resources`. `installWorkspaceResources` is removed. `workspaces`, `workspaces.memberships` and `workspaces.core` keep their methods and answers. Each repository's `withTransaction(options, work)` runs `work(txOptions)` in the caller's transaction or in one it opens. The `workspaces` capability and the invites repository answer `inTransaction(options)`, whether a call runs inside a transaction, so the invitation protocol's guards (prepareInvite needs the caller's transaction; createInvite, sendInvite and invitation acceptance and refusal open their own) keep their messages without reading the transaction. Behaviour differences: `updateById` of a missing workspace answers `null` outside a transaction instead of failing with json-rest-api's 404; an invitation's locking read takes the matching invites' ids and then locks them by id (see the resource handle's `lockWhere`); and the memberships reads that only need ids no longer include each workspace and user.
16
+ - **Breaking (data-access redesign).** Each workspaces table is one table resource, registered under its name: `workspaceResource` (`workspaces`), `workspaceSettingsResource` (`workspaceSettings`), `workspaceMembershipsResource` (`workspaceMemberships`) and `workspaceInvitesResource` (`workspaceInvites`). Workspaces and their settings have CRUD contracts, `workspaceCrud` (namespace `workspace`) and `workspaceSettingsCrud`, with view, list, create, replace and patch. Memberships and invites have no HTTP surface, so their unserved CRUD operations are gone, with the five feedback keys only they used (`fixInvalidValues`, `recordSaved`, `recordSaveFailed`, `recordDeleted`, `recordDeleteFailed`). The member and pending-invitation operations are API contracts: `workspaceMembersContract` and `workspacePendingInvitationsContract`.
5
17
  - A workspace request's auth policy and its action context share one workspace context resolution: `resolveWorkspaceContextForUserBySlug` called with the same `request` (the auth policy resolver now passes it, as the action context contributor already did), user, slug and membership requirement reads the workspace, membership and workspace settings once instead of once per check, so a workspace action with a permission no longer repeats those reads before its handler. Calls without a request, or in a transaction, resolve on their own as before.
6
18
  - `workspaceMembershipsRepository.listActiveWorkspaceIdsByUserIds(userIds, options)` answers many users' active workspace ids as a `Map` in one query per 1,000 users, reading the memberships' `workspace_id` instead of including each workspace. The memberships resource gains the `users` filter (`user_id in [...]`) it uses. The realtime audience contributor (`workspaces.memberships`) answers realtime's bulk `resolveActorsScopes(actorIds)` with it, so a workspace event costs one memberships query, not one per online user.
7
19
  - A new workspace's slug (`base`, then `base-2` to `base-1000`) is chosen with one read of every taken candidate through `workspacesRepository.listSlugsIn(slugs, options)` and the workspace resource's new `slugs` filter (`in`), instead of one `findBySlug` per taken candidate, so a common name costs the same statements after 10 namesakes as after 200. The chosen slug and the error when all 1,000 are taken are unchanged.
@@ -9,6 +21,19 @@
9
21
  - The workspace, settings, member and invitation field messages are sent in the coded form `{ code, message, params }`, so their field errors translate. The English is unchanged.
10
22
  - The resources' save, delete and validation feedback names catalog keys under `jskit.workspaces.feedback.*` instead of plain English; JSKIT's forms render them with `text()`, so the English shown is unchanged.
11
23
  - The invitation email writes its expiry date with `Intl` in the recipient's locale and saved time zone (UTC without one), for example "November 2, 2026 at 12:00 AM UTC", instead of the raw ISO timestamp. An app's own `workspaces.invite-email-template` also receives the recipient's `timeZone` next to `locale`.
24
+ - **Breaking (data-access redesign).** The workspaces and their memberships are their owners' capabilities, provided by `WorkspacesFeature`: `workspaces` (`findById`, `findBySlug`, `listSlugsIn`, `findPersonalByOwnerUserId`, `listForUserId`, `insert`, `updateById`, `lock`) and `workspaces.memberships` (`findByWorkspaceIdAndUserId`, `ensureOwnerMembership`, `upsertMembership`, `addMember`, `activeMemberIds`, `listActiveByWorkspaceId`, `findActiveByWorkspaceIdAndUserId`, `listActiveWorkspaceIdsByUserId(s)`). `workspaces.core`'s `repositories` keep `workspaceInvites` and `workspaceSettings`. The types are `Workspaces` and `WorkspacesMemberships`. The feature requires `users.profiles` and `users.settings` instead of `users.core`.
25
+ - `findBySlug` no longer finds a deleted workspace; its slug stays taken. A workspace request to a deleted workspace's slug now answers 404 `workspaces.workspace.notFound` instead of resolving that workspace.
26
+ - New `lock(workspaceId, options)` on `workspaces` takes the workspace's row lock until the caller's transaction ends; it needs the caller's transaction (the `txOptions` of `withTransaction`) and answers `{ id }`, or `null` when there is no such workspace. The invitations' lock (`lockWorkspaceForInvitations`) is built on it and keeps its 404 `workspaces.invite.workspaceMissing`.
27
+ - New `addMember({ workspaceId, userId, roleSid }, options)` on `workspaces.memberships` makes the user an active member with the role (`member` when none is given), adding the membership or reactivating it, and `activeMemberIds(workspaceId, options)` answers the active members' user ids at the same cost however many members there are (one page per 1,000 memberships), without including their profiles.
28
+ - The bootstrap change of a created or revoked invitation reaches its recipient through realtime's `audienceUsers`: the members service's new `inviteRecipientUserIds(inviteId, options)` reads the invitation (the invites repository's new `findById`, in any status) and the profile with its email through `users.profiles`, instead of a hand-written join of the two tables.
29
+ - `createWorkspacesRuntime` takes the four tables' handles as `resources`, with `userProfiles`, `userSettings`, `workspaces` and `workspaceMemberships`, instead of `users`; the new `createWorkspaceRecords(resources)`, exported beside it, builds the last two from the handles.
30
+
31
+ ### Upgrading
32
+
33
+ - Replace `workspaces.repositories.workspaces` with the `workspaces` capability and `workspaces.repositories.workspaceMemberships` with `workspaces.memberships`. Application composition that locked a workspace with `workspaces.repositories.workspaceInvites.lockWorkspaceForInvitations(workspaceId, { trx })` uses `lock(workspaceId, txOptions)` of `workspaces` inside `withTransaction(options, async (txOptions) => …)`, which answers `null` instead of throwing when the workspace is missing.
34
+ - Code that found a deleted workspace by slug reads it by id.
35
+ - Tests that call `createWorkspacesRuntime({ ..., users })` own the four tables, `runtime.own("workspaces.core", [workspaceResource, workspaceMembershipsResource, workspaceInvitesResource, workspaceSettingsResource])` on a `createTestResourceRuntime` of `@jskit-ai/resource-runtime/test`, and pass the handles as `resources`, with `userProfiles`, `userSettings` and the `workspaces` and `memberships` of `createWorkspaceRecords(resources)`. Tests that called `installWorkspaceResources(api)` own the tables the same way.
36
+ - `repository.withTransaction(async (trx) => …)` with `{ trx }` passed inside becomes `repository.withTransaction(options, async (txOptions) => …)` with `txOptions` passed inside.
12
37
 
13
38
  ### New codes (21)
14
39
 
package/locales/en.json CHANGED
@@ -52,11 +52,6 @@
52
52
  },
53
53
  "feedback": {
54
54
  "validationFailed": "Validation failed.",
55
- "fixInvalidValues": "Fix invalid values and try again.",
56
- "recordSaved": "Record saved.",
57
- "recordSaveFailed": "Unable to save record.",
58
- "recordDeleted": "Record deleted.",
59
- "recordDeleteFailed": "Unable to delete record.",
60
55
  "workspaceInvalid": "Fix invalid workspace values and try again.",
61
56
  "workspaceUpdated": "Workspace updated.",
62
57
  "workspaceUpdateFailed": "Unable to update workspace.",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/workspaces-core",
3
- "version": "0.2.15",
3
+ "version": "0.2.16",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -19,14 +19,13 @@
19
19
  "./shared/support/workspacePathModel": "./src/shared/support/workspacePathModel.js",
20
20
  "./shared/resources/workspaceResource": "./src/shared/resources/workspaceResource.js",
21
21
  "./shared/resources/workspaceSettingsResource": "./src/shared/resources/workspaceSettingsResource.js",
22
+ "./test/WorkspaceRecordsFeature": "./src/test/WorkspaceRecordsFeature.js",
22
23
  "./locales/en.json": "./locales/en.json"
23
24
  },
24
25
  "dependencies": {
25
- "@jskit-ai/database-runtime": "0.1.262",
26
- "@jskit-ai/json-rest-api-core": "0.2.14",
27
- "@jskit-ai/resource-core": "0.1.204",
28
- "@jskit-ai/resource-crud-core": "0.1.204",
29
- "@jskit-ai/users-core": "0.2.15",
26
+ "@jskit-ai/resource-core": "0.1.205",
27
+ "@jskit-ai/resource-crud-core": "0.1.205",
28
+ "@jskit-ai/users-core": "0.2.16",
30
29
  "json-rest-schema": "^1.0.17"
31
30
  },
32
31
  "description": "Workspace tenancy runtime plus HTTP routes, role catalog, and workspace config scaffolding.",
@@ -34,7 +33,9 @@
34
33
  "kind": "runtime",
35
34
  "capabilities": {
36
35
  "provides": [
37
- "workspaces.core"
36
+ "workspaces.core",
37
+ "workspaces",
38
+ "workspaces.memberships"
38
39
  ],
39
40
  "requires": [
40
41
  "auth.extensions",
@@ -45,9 +46,10 @@
45
46
  "runtime.database",
46
47
  "runtime.env",
47
48
  "runtime.http",
48
- "runtime.json-rest-api",
49
- "users.core",
50
- "users.extensions"
49
+ "runtime.resources",
50
+ "users.extensions",
51
+ "users.profiles",
52
+ "users.settings"
51
53
  ]
52
54
  },
53
55
  "runtime": {
@@ -90,7 +92,7 @@
90
92
  "surfaces": [
91
93
  {
92
94
  "subpath": "./server/WorkspacesFeature",
93
- "summary": "Exports WorkspacesFeature, which provides workspaces.core (directory, members, pending invitations and settings services, their actions and routes), and the optional tokens' defaults."
95
+ "summary": "Exports WorkspacesFeature, which provides workspaces.core (directory, members, pending invitations and settings services, their actions and routes), workspaces (the workspaces' records, with findBySlug and lock) and workspaces.memberships (the memberships' records, with addMember and activeMemberIds), and the optional tokens' defaults."
94
96
  },
95
97
  {
96
98
  "subpath": "./server/WorkspacesIntegrationsProvider",
@@ -114,11 +116,17 @@
114
116
  },
115
117
  {
116
118
  "subpath": "./server/types",
117
- "summary": "Type of the workspaces.core capability, for features that require it."
119
+ "summary": "Types of the workspaces.core, workspaces and workspaces.memberships capabilities, for features that require them."
120
+ },
121
+ {
122
+ "subpath": "./test/WorkspaceRecordsFeature",
123
+ "summary": "For an application's tests: WorkspaceRecordsFeature owns the workspaces tables and provides only workspaces and workspaces.memberships, the records workspaces.core provides, without its routes, settings or invitations."
118
124
  }
119
125
  ],
120
126
  "capabilities": [
121
- "workspaces.core"
127
+ "workspaces.core",
128
+ "workspaces",
129
+ "workspaces.memberships"
122
130
  ]
123
131
  },
124
132
  "server": {
@@ -198,8 +206,10 @@
198
206
  }
199
207
  },
200
208
  "peerDependencies": {
201
- "@jskit-ai/auth-core": "0.2.13",
202
- "@jskit-ai/http-runtime": "0.2.13",
203
- "@jskit-ai/kernel": "0.2.13"
209
+ "@jskit-ai/auth-core": "0.2.14",
210
+ "@jskit-ai/database-runtime": "0.1.263",
211
+ "@jskit-ai/http-runtime": "0.2.14",
212
+ "@jskit-ai/kernel": "0.2.14",
213
+ "@jskit-ai/resource-runtime": "0.2.12"
204
214
  }
205
215
  }
@@ -66,20 +66,20 @@ catalogue entries. Updating labels requires no database migration.
66
66
  Provide one function as the optional `workspaces.invite-acceptance-participant`
67
67
  capability, from a small application feature that requires only what its writes
68
68
  need (it cannot require `workspaces.core`, which receives it). The built-in
69
- `workspace.invite.redeem` action invokes `fn({ invite, user }, { trx, context })`
69
+ `workspace.invite.redeem` action invokes `fn({ invite, user }, txOptions)`
70
70
  after validating the recipient, state and expiry and activating membership in the
71
- uncommitted transaction. Forward `trx` to every application owner and propagate
72
- failures. JSKIT marks accepted and commits after the function succeeds. Keep
71
+ uncommitted transaction. Pass `txOptions` to every application owner's calls and
72
+ propagate failures. JSKIT marks accepted and commits after the function succeeds. Keep
73
73
  external effects out of it. Without the capability, acceptance activates the
74
74
  membership only. Allow ordinary invitations; reject stale, revoked, conflicting
75
75
  or unexpectedly missing application associations.
76
76
 
77
- Use `members.prepareInvite(workspace, actor,
78
- payload, { trx, context })` in `repositories.workspaceInvites.withTransaction`
79
- or the same JSON REST API's managed `transaction`. It returns
77
+ Call `members.prepareInvite(workspace, actor, payload, txOptions)` inside
78
+ `repositories.workspaceInvites.withTransaction(options, async (txOptions) => …)`
79
+ or another resource handle's `withTransaction`. It returns
80
80
  `{ createdInviteId, inviteTokenPreview }` without delivery. Lock the workspace
81
- with `repositories.workspaceInvites.lockWorkspaceForInvitations(workspace.id,
82
- { trx })` before application draft/receipt rows, and save the exact invitation
81
+ with `lock(workspace.id, txOptions)` of the `workspaces` capability before
82
+ application draft/receipt rows, and save the exact invitation
83
83
  association and retry receipt before commit. Failure restores the previous
84
84
  pending invitation. Keep access drafts separate: preparation creates a real token.
85
85
 
@@ -92,7 +92,7 @@ failure. A provider may accept a message before failing; the application owns
92
92
  receipts and retries. Keep tokens/URLs out of logs and use controlled mailers in tests.
93
93
 
94
94
  `createInvite`, acceptance and refusal own their managed transactions and
95
- reject a borrowed `options.trx`. Use preparation followed by delivery after commit for
95
+ refuse a call made inside one (`withTransaction({ ...options, outermost: true }, work)`). Use preparation followed by delivery after commit for
96
96
  transactional creation; put related acceptance writes in the participant. Revocation may join
97
97
  a managed transaction. Raw Knex/savepoint transactions cannot own resource
98
98
  writes. Invitation mutations lock workspace then invitation rows, revalidate
@@ -12,19 +12,20 @@ import { renderDefaultWorkspaceInviteEmail } from "./workspaceMembers/defaultWor
12
12
  import { noInviteAcceptanceParticipant } from "./workspacePendingInvitations/noInviteAcceptanceParticipant.js";
13
13
  import { buildWorkspaceName } from "./common/services/workspaceDirectoryService.js";
14
14
  import { createWorkspaceSettingsActions } from "./workspaceSettings/workspaceSettingsActions.js";
15
- import { createWorkspacesRuntime, installWorkspaceResources } from "./workspacesRuntime.js";
15
+ import { WORKSPACES_TABLES, createWorkspaceRecords, createWorkspacesRuntime } from "./workspacesRuntime.js";
16
16
 
17
17
  const WorkspacesFeature = defineFeature({
18
18
  id: "workspaces.core",
19
19
  domain: "workspace",
20
+ owns: WORKSPACES_TABLES,
20
21
  requires: {
21
22
  appRoot: "runtime.app-root",
22
23
  bootstrap: "runtime.bootstrap",
23
24
  config: "runtime.config",
24
25
  env: "runtime.env",
25
26
  http: "runtime.http",
26
- jsonRestApi: "runtime.json-rest-api",
27
- users: "users.core"
27
+ userProfiles: "users.profiles",
28
+ userSettings: "users.settings"
28
29
  },
29
30
  optional: {
30
31
  inviteAcceptanceParticipant: "workspaces.invite-acceptance-participant",
@@ -33,7 +34,9 @@ const WorkspacesFeature = defineFeature({
33
34
  personalWorkspaceName: "workspaces.personal-workspace-name"
34
35
  },
35
36
  provides: {
36
- workspaces: "workspaces.core"
37
+ workspaces: "workspaces.core",
38
+ workspaceRecords: "workspaces",
39
+ workspaceMemberships: "workspaces.memberships"
37
40
  },
38
41
  /**
39
42
  * @param {object} capabilities
@@ -45,9 +48,10 @@ const WorkspacesFeature = defineFeature({
45
48
  * @param {import("./types.js").WorkspaceInviteAcceptanceParticipant | null} capabilities.inviteAcceptanceParticipant
46
49
  * @param {import("./types.js").WorkspaceInviteEmailTemplate | null} capabilities.inviteEmailTemplate
47
50
  * @param {import("./types.js").WorkspaceInviteMailer | null} capabilities.inviteMailer
48
- * @param {import("@jskit-ai/json-rest-api-core/server/types").RuntimeJsonRestApi} capabilities.jsonRestApi
49
51
  * @param {import("./types.js").PersonalWorkspaceName | null} capabilities.personalWorkspaceName
50
- * @param {import("@jskit-ai/users-core/server/types").UsersCore} capabilities.users
52
+ * @param {import("./types.js").WorkspacesResources} capabilities.resources
53
+ * @param {import("@jskit-ai/users-core/server/types").UsersProfiles} capabilities.userProfiles
54
+ * @param {import("@jskit-ai/users-core/server/types").UsersSettings} capabilities.userSettings
51
55
  */
52
56
  async setup({
53
57
  appRoot,
@@ -58,11 +62,12 @@ const WorkspacesFeature = defineFeature({
58
62
  inviteAcceptanceParticipant,
59
63
  inviteEmailTemplate,
60
64
  inviteMailer,
61
- jsonRestApi,
62
65
  personalWorkspaceName,
63
- users
66
+ resources,
67
+ userProfiles,
68
+ userSettings
64
69
  }) {
65
- await installWorkspaceResources(jsonRestApi);
70
+ const records = createWorkspaceRecords(resources);
66
71
  const workspaces = createWorkspacesRuntime({
67
72
  appRoot,
68
73
  config,
@@ -70,9 +75,12 @@ const WorkspacesFeature = defineFeature({
70
75
  inviteAcceptanceParticipant: inviteAcceptanceParticipant ?? noInviteAcceptanceParticipant,
71
76
  inviteEmailTemplate: inviteEmailTemplate ?? renderDefaultWorkspaceInviteEmail,
72
77
  inviteMailer: inviteMailer ?? unconfiguredWorkspaceInviteMailer,
73
- jsonRestApi,
74
78
  personalWorkspaceName: personalWorkspaceName ?? buildWorkspaceName,
75
- users
79
+ resources,
80
+ userProfiles,
81
+ userSettings,
82
+ workspaces: records.workspaces,
83
+ workspaceMemberships: records.memberships
76
84
  });
77
85
 
78
86
  bootstrap.register({
@@ -80,7 +88,7 @@ const WorkspacesFeature = defineFeature({
80
88
  order: 200,
81
89
  contribute: createWorkspaceBootstrapContributor({
82
90
  tenancyProfile: workspaces.tenancyProfile,
83
- userProfilesRepository: users.repositories.userProfiles,
91
+ userProfilesRepository: userProfiles,
84
92
  workspaceInvitationsEnabled: workspaces.invitationsEnabled,
85
93
  workspacePendingInvitationsService: workspaces.services.pendingInvitations,
86
94
  workspaceService: workspaces.services.directory
@@ -102,7 +110,11 @@ const WorkspacesFeature = defineFeature({
102
110
  }
103
111
  }
104
112
 
105
- return { workspaces };
113
+ return {
114
+ workspaces,
115
+ workspaceRecords: records.workspaces,
116
+ workspaceMemberships: records.memberships
117
+ };
106
118
  },
107
119
  actions({ workspaces }) {
108
120
  if (!workspaces.enabled) return Object.freeze([]);
@@ -119,13 +131,13 @@ const WorkspacesFeature = defineFeature({
119
131
  }
120
132
  });
121
133
 
122
- // Applications' tests build the runtime and install its resources directly, from
123
- // this package's public feature path, with the optional tokens' defaults.
134
+ // Applications' tests build the runtime directly, from this package's public
135
+ // feature path, on handles of the four table resources, with the optional tokens' defaults.
124
136
  export {
125
137
  WorkspacesFeature,
126
138
  buildWorkspaceName,
139
+ createWorkspaceRecords,
127
140
  createWorkspacesRuntime,
128
- installWorkspaceResources,
129
141
  noInviteAcceptanceParticipant,
130
142
  renderDefaultWorkspaceInviteEmail,
131
143
  unconfiguredWorkspaceInviteMailer
@@ -10,7 +10,7 @@ import {
10
10
  /**
11
11
  * Every active membership puts the actor in the workspace audience and in its
12
12
  * own workspace-user audience. All the actors' memberships are one bulk read.
13
- * @param {import("./types.js").WorkspaceMembershipsRepository} workspaceMemberships
13
+ * @param {import("./types.js").WorkspacesMemberships} workspaceMemberships
14
14
  * @param {string[]} actorIds
15
15
  */
16
16
  async function resolveWorkspaceRealtimeScopes(workspaceMemberships, actorIds) {
@@ -33,6 +33,7 @@ const WorkspacesIntegrationsProvider = defineProvider({
33
33
  config: "runtime.config",
34
34
  http: "runtime.http",
35
35
  usersExtensions: "users.extensions",
36
+ workspaceMemberships: "workspaces.memberships",
36
37
  workspaces: "workspaces.core"
37
38
  },
38
39
  optional: {
@@ -46,9 +47,10 @@ const WorkspacesIntegrationsProvider = defineProvider({
46
47
  * @param {import("@jskit-ai/kernel/server/types").RuntimeHttp} capabilities.http
47
48
  * @param {import("@jskit-ai/realtime/server/types").RuntimeRealtime | null} capabilities.realtime The installed realtime runtime, when there is one.
48
49
  * @param {import("@jskit-ai/users-core/server/types").UsersExtensions} capabilities.usersExtensions
50
+ * @param {import("./types.js").WorkspacesMemberships} capabilities.workspaceMemberships
49
51
  * @param {import("./types.js").WorkspacesCore} capabilities.workspaces
50
52
  */
51
- setup({ actions, authExtensions, config, http, realtime, usersExtensions, workspaces }) {
53
+ setup({ actions, authExtensions, config, http, realtime, usersExtensions, workspaceMemberships, workspaces }) {
52
54
  const workspaceService = workspaces.services.directory;
53
55
  const membershipOptionalSurfaceIds = resolveWorkspaceMembershipOptionalSurfaceIdsFromAppConfig(config);
54
56
  const workspaceSurfaceIds = resolveWorkspaceSurfaceIdsFromAppConfig(config);
@@ -92,10 +94,7 @@ const WorkspacesIntegrationsProvider = defineProvider({
92
94
  if (realtime) {
93
95
  realtime.registerAudienceContributor({
94
96
  id: "workspaces.memberships",
95
- resolveActorsScopes: (actorIds) => resolveWorkspaceRealtimeScopes(
96
- workspaces.repositories.workspaceMemberships,
97
- actorIds
98
- )
97
+ resolveActorsScopes: (actorIds) => resolveWorkspaceRealtimeScopes(workspaceMemberships, actorIds)
99
98
  });
100
99
  }
101
100
 
@@ -1,17 +1,9 @@
1
- import {
2
- isLostDuplicateInsertRace,
3
- joinOrOpenTransaction,
4
- normalizeDbRecordId,
5
- resolveTransaction,
6
- retryDeadlocks,
7
- toIsoString
8
- } from "@jskit-ai/database-runtime/shared";
1
+ import { isLostDuplicateInsertRace, normalizeDbRecordId, toIsoString } from "@jskit-ai/database-runtime/shared";
9
2
  import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
10
3
  import { normalizeLowerText, normalizeRecordId, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
11
- import {
12
- createJsonRestContext,
13
- queryAllJsonRestCollectionRows
14
- } from "@jskit-ai/json-rest-api-core/server/jsonRestApiHost";
4
+
5
+ // The filters a locking read takes: the invite, its workspace, email, status and token.
6
+ const LOCKING_FILTERS = Object.freeze(["id", "workspace", "email", "status", "tokenHash"]);
15
7
 
16
8
  function normalizeInviteRecord(payload) {
17
9
  if (!payload) {
@@ -77,77 +69,53 @@ function normalizeInviteWithWorkspace(payload = {}) {
77
69
  };
78
70
  }
79
71
 
80
- /** @param {{ api: import("@jskit-ai/json-rest-api-core/server/types").RuntimeJsonRestApi }} dependencies */
81
- function createRepository({ api }) {
82
- const withTransaction = (work) => retryDeadlocks(() => api.transaction(work));
83
-
84
- async function queryInvites(filters = {}, options = {}, { includeWorkspace = false } = {}) {
72
+ /**
73
+ * The workspace invites' records, `repositories.workspaceInvites` of
74
+ * `workspaces.core`. Every method takes the caller's options last and joins
75
+ * their transaction; `lock: true` reads lock the invites, and their workspace
76
+ * first, in it.
77
+ * @param {object} dependencies
78
+ * @param {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} dependencies.workspaceInvites
79
+ * The workspace_invites table's handle.
80
+ * @param {import("../../types.js").Workspaces} dependencies.workspaces The workspaces, whose lock an invite's work takes first.
81
+ */
82
+ function createRepository({ workspaceInvites, workspaces }) {
83
+ async function queryInvites(filters, options, { includeWorkspace = false } = {}) {
85
84
  if (options.lock === true) {
86
- // readable-check: allow method-probe - platform object: a Knex transaction, which a locking read needs and options may omit
87
- if (typeof options.trx !== "function" || includeWorkspace) {
88
- throw new TypeError("Locking invites requires a transaction and no relationship includes.");
85
+ // The handle's lock refuses a call outside a transaction.
86
+ if (includeWorkspace) {
87
+ throw new TypeError("Locking invites takes no relationship includes.");
89
88
  }
90
- // Locking reads must see changes committed while waiting for the lock.
91
- const fields = {
92
- id: "id",
93
- workspace: "workspace_id",
94
- email: "email",
95
- status: "status",
96
- tokenHash: "token_hash"
97
- };
98
- const where = Object.fromEntries(Object.entries(filters).map(([key, value]) => {
99
- if (!fields[key]) {
100
- throw new TypeError("Unsupported locking invitation filter.");
101
- }
102
- return [fields[key], value];
103
- }));
104
- // Read PostgreSQL's UTC timestamps as text to avoid the driver's local-time conversion.
105
- // readable-check: allow method-probe - platform object: a Knex transaction, whose client config names its dialect
106
- const dateColumn = (name) => options.trx.client?.config?.client === "pg"
107
- ? options.trx.raw("CAST(?? AS TEXT)", [name])
108
- : name;
109
- return options.trx("workspace_invites").where(where).select({
110
- id: "id",
111
- workspaceId: "workspace_id",
112
- email: "email",
113
- roleSid: "role_sid",
114
- status: "status",
115
- tokenHash: "token_hash",
116
- invitedByUserId: "invited_by_user_id",
117
- expiresAt: dateColumn("expires_at"),
118
- acceptedAt: dateColumn("accepted_at"),
119
- revokedAt: dateColumn("revoked_at"),
120
- createdAt: dateColumn("created_at"),
121
- updatedAt: dateColumn("updated_at")
122
- }).forUpdate();
89
+ if (Object.keys(filters).some((key) => !LOCKING_FILTERS.includes(key))) {
90
+ throw new TypeError("Unsupported locking invitation filter.");
91
+ }
92
+ // The locking read answers the rows as committed when the lock is granted. A row whose status changed while the
93
+ // lock waited (another request accepted or revoked it) is left out, whether or not the database re-checked it.
94
+ const rows = await workspaceInvites.lockWhere(filters, options);
95
+ return filters.status === undefined ? rows : rows.filter((row) => row.status === filters.status);
123
96
  }
124
- return queryAllJsonRestCollectionRows(
125
- api.resources.workspaceInvites,
126
- {
127
- queryParams: {
128
- filters,
129
- ...(includeWorkspace ? { include: ["workspace"] } : {})
130
- },
131
- transaction: resolveTransaction(options),
132
- format: "plain"
133
- },
134
- options.context
135
- );
97
+ return workspaceInvites.queryAll({ filters, ...(includeWorkspace ? { include: ["workspace"] } : {}) }, options);
98
+ }
99
+
100
+ async function patchInvite(id, changes, options) {
101
+ await workspaceInvites.patch(id, changes, { ...options, returning: "none" });
136
102
  }
137
103
 
138
104
  async function lockWorkspaceForInvitations(workspaceId, options = {}) {
139
- // readable-check: allow method-probe - platform object: a Knex transaction, which the workspace lock needs and options may omit
140
- if (typeof options.trx !== "function" || options.trx.isCompleted()) {
141
- throw new TypeError("Invitation locking requires an active transaction.");
105
+ if (!await workspaces.lock(workspaceId, { ...options, missing: "skip" })) {
106
+ throw new AppError(404, "Invitation workspace no longer exists.", { code: "workspaces.invite.workspaceMissing" });
142
107
  }
143
- const id = normalizeRecordId(workspaceId, { fallback: null });
108
+ }
109
+
110
+ // An invite in any status, or null.
111
+ async function findById(inviteId, options = {}) {
112
+ const id = normalizeRecordId(inviteId, { fallback: null });
144
113
  if (!id) {
145
- throw new TypeError("Invitation locking requires workspaceId.");
146
- }
147
- const row = await options.trx("workspaces").where({ id }).forUpdate().first("id");
148
- if (!row) {
149
- throw new AppError(404, "Invitation workspace no longer exists.", { code: "workspaces.invite.workspaceMissing" });
114
+ return null;
150
115
  }
116
+
117
+ const rows = await queryInvites({ id }, options);
118
+ return normalizeInviteRecord(rows[0] || null);
151
119
  }
152
120
 
153
121
  async function findPendingByTokenHash(tokenHash, options = {}) {
@@ -244,26 +212,21 @@ function createRepository({ api }) {
244
212
 
245
213
  try {
246
214
  const createdAt = new Date().toISOString();
247
- const created = await api.resources.workspaceInvites.post(
215
+ const created = await workspaceInvites.create(
248
216
  {
249
- data: {
250
- email: createPayload.email,
251
- roleSid: createPayload.roleSid,
252
- status: createPayload.status,
253
- tokenHash: createPayload.tokenHash,
254
- expiresAt: createPayload.expiresAt == null ? null : toIsoString(createPayload.expiresAt),
255
- acceptedAt: null,
256
- revokedAt: null,
257
- createdAt,
258
- updatedAt: createdAt,
259
- workspace: createPayload.workspaceId,
260
- invitedByUser: createPayload.invitedByUserId ?? null
261
- },
262
- format: "plain",
263
- returning: "full",
264
- transaction: resolveTransaction(options)
217
+ email: createPayload.email,
218
+ roleSid: createPayload.roleSid,
219
+ status: createPayload.status,
220
+ tokenHash: createPayload.tokenHash,
221
+ expiresAt: createPayload.expiresAt == null ? null : toIsoString(createPayload.expiresAt),
222
+ acceptedAt: null,
223
+ revokedAt: null,
224
+ createdAt,
225
+ updatedAt: createdAt,
226
+ workspaceId: createPayload.workspaceId,
227
+ invitedByUserId: createPayload.invitedByUserId ?? null
265
228
  },
266
- createJsonRestContext(options.context)
229
+ options
267
230
  );
268
231
 
269
232
  return normalizeInviteRecord(created);
@@ -292,9 +255,8 @@ function createRepository({ api }) {
292
255
  return;
293
256
  }
294
257
 
295
- await joinOrOpenTransaction(options, withTransaction, async (trx) => {
296
- const transactionOptions = { ...options, trx };
297
- await lockWorkspaceForInvitations(normalizedWorkspaceId, transactionOptions);
258
+ await workspaceInvites.withTransaction(options, async (txOptions) => {
259
+ await lockWorkspaceForInvitations(normalizedWorkspaceId, txOptions);
298
260
  const patch = normalizeInvitePatchPayload({ status: "expired" });
299
261
  const rows = await queryInvites(
300
262
  {
@@ -302,26 +264,14 @@ function createRepository({ api }) {
302
264
  email: normalizeLowerText(email),
303
265
  status: "pending"
304
266
  },
305
- { ...transactionOptions, lock: true }
267
+ { ...txOptions, lock: true }
306
268
  );
307
269
 
308
270
  for (const row of rows) {
309
271
  if (!row?.id) {
310
272
  continue;
311
273
  }
312
- await api.resources.workspaceInvites.patch(
313
- {
314
- id: row.id,
315
- data: {
316
- status: patch.status,
317
- updatedAt: new Date().toISOString()
318
- },
319
- format: "plain",
320
- returning: "full",
321
- transaction: trx
322
- },
323
- createJsonRestContext(options.context)
324
- );
274
+ await patchInvite(row.id, { status: patch.status, updatedAt: new Date().toISOString() }, txOptions);
325
275
  }
326
276
  });
327
277
  }
@@ -341,27 +291,22 @@ function createRepository({ api }) {
341
291
  }
342
292
  workspaceId = normalizeInviteRecord(candidate[0]).workspaceId;
343
293
  }
344
- await joinOrOpenTransaction(options, withTransaction, async (trx) => {
345
- const invite = await findPendingByIdForWorkspace(id, workspaceId, { ...options, trx, workspaceId, lock: true });
294
+ await workspaceInvites.withTransaction(options, async (txOptions) => {
295
+ const invite = await findPendingByIdForWorkspace(id, workspaceId, { ...txOptions, workspaceId, lock: true });
346
296
  if (!invite) {
347
297
  throw new AppError(404, "Invitation not found or already handled.", {
348
298
  code: "workspaces.invite.invitationNotFoundOrHandled"
349
299
  });
350
300
  }
351
301
  const updatedAt = new Date().toISOString();
352
- await api.resources.workspaceInvites.patch(
302
+ await patchInvite(
303
+ id,
353
304
  {
354
- id,
355
- data: {
356
- status,
357
- [status === "accepted" ? "acceptedAt" : "revokedAt"]: updatedAt,
358
- updatedAt
359
- },
360
- format: "plain",
361
- returning: "full",
362
- transaction: trx
305
+ status,
306
+ [status === "accepted" ? "acceptedAt" : "revokedAt"]: updatedAt,
307
+ updatedAt
363
308
  },
364
- createJsonRestContext(options.context)
309
+ txOptions
365
310
  );
366
311
  });
367
312
  }
@@ -400,8 +345,9 @@ function createRepository({ api }) {
400
345
  }
401
346
 
402
347
  return Object.freeze({
403
- withTransaction,
348
+ withTransaction: workspaceInvites.withTransaction,
404
349
  lockWorkspaceForInvitations,
350
+ findById,
405
351
  findPendingByTokenHash,
406
352
  findByTokenHashWithWorkspace,
407
353
  listPendingByEmail,