@jskit-ai/users-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 (46) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/package.json +24 -17
  3. package/patterns/user-administration-server/PATTERN.md +59 -10
  4. package/patterns/user-administration-server/example/packages/users/package.json +5 -4
  5. package/patterns/user-administration-server/example/packages/users/src/server/UsersFeature.js +7 -5
  6. package/patterns/user-administration-server/example/packages/users/src/shared/index.js +1 -1
  7. package/patterns/user-administration-server/example/packages/users/src/shared/userCrud.js +21 -0
  8. package/patterns/user-administration-server/example/packages/users-workspace/package.json +11 -5
  9. package/patterns/user-administration-server/example/packages/users-workspace/src/server/UsersWorkspaceFeature.js +14 -5
  10. package/patterns/user-administration-server/example/packages/users-workspace/src/server/workspaceMembersOnly.js +52 -0
  11. package/patterns/user-administration-server/example/packages/users-workspace/src/shared/index.js +1 -1
  12. package/patterns/user-administration-server/example/packages/users-workspace/src/shared/userCrud.js +21 -0
  13. package/src/server/UsersFeature.js +10 -6
  14. package/src/server/UsersIdentityProvider.js +13 -29
  15. package/src/server/accountNotifications/accountNotificationsActions.js +3 -3
  16. package/src/server/accountNotifications/accountNotificationsRoutes.js +3 -3
  17. package/src/server/accountPreferences/accountPreferencesActions.js +3 -3
  18. package/src/server/accountPreferences/accountPreferencesRoutes.js +3 -3
  19. package/src/server/accountProfile/accountProfileActions.js +9 -9
  20. package/src/server/accountProfile/accountProfileRoutes.js +5 -5
  21. package/src/server/accountSecurity/accountSecurityActions.js +10 -10
  22. package/src/server/accountSecurity/accountSecurityRoutes.js +9 -9
  23. package/src/server/common/repositories/userProfilesRepository.js +246 -145
  24. package/src/server/common/repositories/userSettingsRepository.js +20 -49
  25. package/src/server/common/services/authProfileSyncService.js +3 -5
  26. package/src/server/types.js +9 -1
  27. package/src/server/usersIdentity.js +11 -11
  28. package/src/server/usersRuntime.js +13 -11
  29. package/src/shared/resources/userProfileResource.js +43 -13
  30. package/src/shared/resources/userSettingsResource.js +34 -29
  31. package/test/accountSecurityService.test.js +2 -2
  32. package/test/authProfileSyncService.test.js +13 -9
  33. package/test/exportsContract.test.js +2 -0
  34. package/test/featureRuntime.test.js +63 -20
  35. package/test/i18nCodes.test.js +6 -10
  36. package/test/repositories.mysql.test.js +384 -0
  37. package/test/resourcesCanonical.test.js +58 -22
  38. package/test/support/mysqlUsers.js +74 -0
  39. package/test/userSettingsInternalResource.test.js +3 -3
  40. package/test/userSettingsResource.test.js +3 -3
  41. package/test/usersPackageScaffoldContract.test.js +70 -12
  42. package/test/usersRouteRequestInputValidator.test.js +2 -2
  43. package/test/usersRouteResources.test.js +73 -29
  44. package/patterns/user-administration-server/example/packages/users/src/shared/userResource.js +0 -69
  45. package/patterns/user-administration-server/example/packages/users-workspace/src/shared/userResource.js +0 -56
  46. package/test/repositoryContracts.test.js +0 -596
@@ -3,24 +3,24 @@ import { createRepository as createUserSettingsRepository } from "./common/repos
3
3
  import { createService as createAuthProfileSyncService } from "./common/services/authProfileSyncService.js";
4
4
 
5
5
  /**
6
- * The users' profile and settings records, and the projector that keeps a
7
- * profile in step with the identity that signs in.
6
+ * The users' profile and settings records (`users.profiles`, `users.settings`),
7
+ * and the projector that keeps a profile in step with the identity that signs
8
+ * in (`auth.profile.projector`).
8
9
  * @param {object} dependencies
9
- * @param {import("@jskit-ai/json-rest-api-core/server/types").RuntimeJsonRestApi} dependencies.jsonRestApi
10
+ * @param {import("./types.js").UsersResources} dependencies.resources The handles of the users and user_settings tables.
10
11
  * @param {import("./types.js").UsersExtensions} dependencies.extensions
11
12
  */
12
- function createUsersIdentity({ jsonRestApi, extensions }) {
13
- const repositories = Object.freeze({
14
- userProfiles: createUserProfilesRepository({ api: jsonRestApi }),
15
- userSettings: createUserSettingsRepository({ api: jsonRestApi })
16
- });
13
+ function createUsersIdentity({ resources, extensions }) {
14
+ const settings = createUserSettingsRepository({ userSettings: resources.userSettings });
15
+ const profiles = createUserProfilesRepository({ userProfiles: resources.userProfiles, userSettings: settings });
17
16
  const profileProjector = createAuthProfileSyncService({
18
- userProfilesRepository: repositories.userProfiles,
19
- userSettingsRepository: repositories.userSettings,
17
+ userProfilesRepository: profiles,
18
+ userSettingsRepository: settings,
20
19
  resolveLifecycleContributors: extensions.profileSyncLifecycleContributors
21
20
  });
22
21
  return Object.freeze({
23
- repositories,
22
+ profiles,
23
+ settings,
24
24
  profileProjector
25
25
  });
26
26
  }
@@ -7,16 +7,22 @@ import { createService as createAvatarStorageService } from "./accountProfile/av
7
7
  import { createService as createAccountSecurityService } from "./accountSecurity/accountSecurityService.js";
8
8
 
9
9
  /**
10
- * The `users.core` capability: the users' repositories and the account
11
- * services built on them.
10
+ * The `users.core` capability: the account services built on the users'
11
+ * records. The records themselves are `users.profiles` and `users.settings`.
12
12
  * @param {object} dependencies
13
13
  * @param {import("@jskit-ai/auth-core/server/types").AuthService} dependencies.authService
14
- * @param {import("./types.js").UsersIdentity} dependencies.identity
14
+ * @param {import("@jskit-ai/auth-core/server/types").AuthProfileProjector} dependencies.profileProjector
15
+ * @param {import("./types.js").UsersProfiles} dependencies.profiles
16
+ * @param {import("./types.js").UsersSettings} dependencies.settings
15
17
  * @param {import("@jskit-ai/storage-runtime/server/types").RuntimeStorage} dependencies.storage
16
18
  */
17
- function createUsersRuntime({ authService, identity, storage }) {
18
- const userProfilesRepository = identity.repositories.userProfiles;
19
- const userSettingsRepository = identity.repositories.userSettings;
19
+ function createUsersRuntime({
20
+ authService,
21
+ profileProjector,
22
+ profiles: userProfilesRepository,
23
+ settings: userSettingsRepository,
24
+ storage
25
+ }) {
20
26
  const avatarStorageService = createAvatarStorageService({ storage });
21
27
  const avatarService = createAvatarService({ userProfilesRepository, avatarStorageService });
22
28
  const accountProfileService = createAccountProfileService({
@@ -42,17 +48,13 @@ function createUsersRuntime({ authService, identity, storage }) {
42
48
  });
43
49
 
44
50
  return Object.freeze({
45
- repositories: Object.freeze({
46
- userProfiles: userProfilesRepository,
47
- userSettings: userSettingsRepository
48
- }),
49
51
  services: Object.freeze({
50
52
  accountNotifications: accountNotificationsService,
51
53
  accountPreferences: accountPreferencesService,
52
54
  accountProfile: accountProfileService,
53
55
  accountSecurity: accountSecurityService,
54
56
  avatar: avatarService,
55
- profileProjector: identity.profileProjector
57
+ profileProjector
56
58
  }),
57
59
  shared: USERS_SHARED_API
58
60
  });
@@ -1,7 +1,9 @@
1
1
  import { createSchema } from "json-rest-schema";
2
2
  import { deepFreeze } from "@jskit-ai/kernel/shared/support/deepFreeze";
3
3
  import { normalizeLowerText, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
4
- import { defineCrudResource } from "@jskit-ai/resource-crud-core/shared/crudResource";
4
+ import { defineApiContract } from "@jskit-ai/resource-core/shared/apiContract";
5
+ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
6
+ import { defineCrudContract } from "@jskit-ai/resource-crud-core/shared/crudContract";
5
7
  import { OPERATION_MESSAGES } from "../operationMessages.js";
6
8
  import { userProfileOutputSchema } from "./accountSettingsSchemas.js";
7
9
  import { userSettingsOutputSchema } from "./userSettingsResource.js";
@@ -61,12 +63,23 @@ const avatarUploadBodySchema = createSchema({
61
63
  }
62
64
  });
63
65
 
64
- const userProfileResource = defineCrudResource({
65
- namespace: "userProfile",
66
+ // The users table.
67
+ const userProfileTableResource = defineTableResource({
68
+ name: "userProfiles",
66
69
  tableName: "users",
70
+ ownership: "public",
67
71
  searchSchema: {
68
- id: { type: "id", actualField: "id" },
69
- usernames: { type: "array", actualField: "username", filterOperator: "in", items: { type: "string" } }
72
+ usernames: { type: "array", actualField: "username", filterOperator: "in", items: { type: "string" } },
73
+ emails: { type: "array", actualField: "email", filterOperator: "in", items: { type: "string" } },
74
+ createdSince: { type: "dateTime", actualField: "createdAt", filterOperator: ">=" },
75
+ // A list's free-text search: every word in the display name, email or username.
76
+ q: {
77
+ type: "string",
78
+ oneOf: ["displayName", "email", "username"],
79
+ filterOperator: "like",
80
+ splitBy: " ",
81
+ matchAll: true
82
+ }
70
83
  },
71
84
  schema: {
72
85
  authProvider: {
@@ -130,7 +143,6 @@ const userProfileResource = defineCrudResource({
130
143
  },
131
144
  createdAt: {
132
145
  type: "dateTime",
133
- default: "now()",
134
146
  storage: {
135
147
  column: "created_at",
136
148
  writeSerializer: "datetime-utc"
@@ -138,20 +150,38 @@ const userProfileResource = defineCrudResource({
138
150
  },
139
151
  updatedAt: {
140
152
  type: "dateTime",
141
- default: "now()",
142
153
  storage: {
143
154
  column: "updated_at",
144
155
  writeSerializer: "datetime-utc"
145
156
  }
146
157
  }
147
158
  },
159
+ // A users list reads by name, then email; the id breaks ties.
160
+ defaultSort: ["displayName", "email"]
161
+ });
162
+
163
+ // The account profile's CRUD surface on the users table: view, list, create,
164
+ // replace and patch, each with the account profile's output and display name
165
+ // body. No JSKIT route serves it; an application that offers these operations
166
+ // serves this contract.
167
+ const userProfileCrud = defineCrudContract(userProfileTableResource, {
168
+ namespace: "userProfile",
169
+ messages: OPERATION_MESSAGES,
170
+ operations: ["view", "list", "create", "replace", "patch"],
171
+ output: userProfileOutputSchema,
172
+ body: userProfileBodySchema
173
+ });
174
+
175
+ // The signed-in user's profile over HTTP.
176
+ const userProfileContract = defineApiContract({
177
+ namespace: "userProfile",
148
178
  messages: OPERATION_MESSAGES,
149
- crudOperations: ["view", "list", "create", "replace", "patch"],
150
- crud: {
151
- output: userProfileOutputSchema,
152
- body: userProfileBodySchema
153
- },
154
179
  operations: {
180
+ patch: {
181
+ method: "PATCH",
182
+ body: userProfileBodySchema,
183
+ output: userProfileOutputSchema
184
+ },
155
185
  avatarUpload: {
156
186
  method: "POST",
157
187
  body: avatarUploadBodySchema,
@@ -165,4 +195,4 @@ const userProfileResource = defineCrudResource({
165
195
  }
166
196
  });
167
197
 
168
- export { userProfileResource };
198
+ export { userProfileContract, userProfileCrud, userProfileTableResource };
@@ -2,9 +2,11 @@ import { createSchema } from "json-rest-schema";
2
2
  import { deepFreeze } from "@jskit-ai/kernel/shared/support/deepFreeze";
3
3
  import { normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
4
4
  import {
5
- createSchemaDefinition
6
- } from "@jskit-ai/resource-core/shared/resource";
7
- import { defineCrudResource } from "@jskit-ai/resource-crud-core/shared/crudResource";
5
+ createSchemaDefinition,
6
+ defineApiContract
7
+ } from "@jskit-ai/resource-core/shared/apiContract";
8
+ import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
9
+ import { defineCrudContract } from "@jskit-ai/resource-crud-core/shared/crudContract";
8
10
  import { OPERATION_MESSAGES } from "../operationMessages.js";
9
11
  import { DEFAULT_USER_SETTINGS, normalizeLocaleCode } from "../settings.js";
10
12
  import {
@@ -64,6 +66,7 @@ function normalizePositiveInteger(value) {
64
66
  return Number(value);
65
67
  }
66
68
 
69
+ // Every preference and notification setting at once: the CRUD contract's body.
67
70
  const userSettingsBodySchema = createSchema({
68
71
  theme: { type: "string", required: true, minLength: 1, maxLength: 32 },
69
72
  locale: { type: "string", required: true, minLength: 1, maxLength: 24 },
@@ -277,38 +280,33 @@ const logoutOtherSessionsOutputSchema = createSchema({
277
280
  ok: { type: "boolean", required: true }
278
281
  });
279
282
 
280
- const userSettingsResource = defineCrudResource({
281
- namespace: "userSettings",
283
+ // The user_settings table, one row per user.
284
+ const userSettingsTableResource = defineTableResource({
285
+ name: "userSettings",
282
286
  tableName: "user_settings",
287
+ ownership: "public",
283
288
  idProperty: "user_id",
284
- searchSchema: {
285
- id: { type: "id", actualField: "id" }
286
- },
287
289
  schema: {
288
290
  id: {
289
291
  type: "id",
290
292
  primary: true,
291
293
  required: true,
292
- search: true,
293
294
  storage: { column: "user_id" }
294
295
  },
295
296
  theme: {
296
297
  type: "string",
297
- required: true,
298
298
  max: 32,
299
299
  defaultTo: DEFAULT_USER_SETTINGS.theme,
300
300
  setter: (value) => normalizeText(value)
301
301
  },
302
302
  locale: {
303
303
  type: "string",
304
- required: true,
305
304
  max: 24,
306
305
  defaultTo: DEFAULT_USER_SETTINGS.locale,
307
306
  setter: (value) => normalizeLocaleCode(value)
308
307
  },
309
308
  timeZone: {
310
309
  type: "string",
311
- required: true,
312
310
  max: 64,
313
311
  defaultTo: DEFAULT_USER_SETTINGS.timeZone,
314
312
  storage: { column: "time_zone" },
@@ -316,7 +314,6 @@ const userSettingsResource = defineCrudResource({
316
314
  },
317
315
  dateFormat: {
318
316
  type: "string",
319
- required: true,
320
317
  max: 32,
321
318
  defaultTo: DEFAULT_USER_SETTINGS.dateFormat,
322
319
  storage: { column: "date_format" },
@@ -324,7 +321,6 @@ const userSettingsResource = defineCrudResource({
324
321
  },
325
322
  numberFormat: {
326
323
  type: "string",
327
- required: true,
328
324
  max: 32,
329
325
  defaultTo: DEFAULT_USER_SETTINGS.numberFormat,
330
326
  storage: { column: "number_format" },
@@ -332,7 +328,6 @@ const userSettingsResource = defineCrudResource({
332
328
  },
333
329
  currencyCode: {
334
330
  type: "string",
335
- required: true,
336
331
  minLength: 3,
337
332
  maxLength: 3,
338
333
  defaultTo: DEFAULT_USER_SETTINGS.currencyCode,
@@ -341,7 +336,6 @@ const userSettingsResource = defineCrudResource({
341
336
  },
342
337
  avatarSize: {
343
338
  type: "number",
344
- required: true,
345
339
  min: 1,
346
340
  defaultTo: DEFAULT_USER_SETTINGS.avatarSize,
347
341
  storage: { column: "avatar_size" },
@@ -349,37 +343,31 @@ const userSettingsResource = defineCrudResource({
349
343
  },
350
344
  passwordSignInEnabled: {
351
345
  type: "boolean",
352
- required: true,
353
346
  defaultTo: DEFAULT_USER_SETTINGS.passwordSignInEnabled,
354
347
  storage: { column: "password_sign_in_enabled" }
355
348
  },
356
349
  passwordSetupRequired: {
357
350
  type: "boolean",
358
- required: true,
359
351
  defaultTo: DEFAULT_USER_SETTINGS.passwordSetupRequired,
360
352
  storage: { column: "password_setup_required" }
361
353
  },
362
354
  productUpdates: {
363
355
  type: "boolean",
364
- required: true,
365
356
  defaultTo: DEFAULT_USER_SETTINGS.productUpdates,
366
357
  storage: { column: "notify_product_updates" }
367
358
  },
368
359
  accountActivity: {
369
360
  type: "boolean",
370
- required: true,
371
361
  defaultTo: DEFAULT_USER_SETTINGS.accountActivity,
372
362
  storage: { column: "notify_account_activity" }
373
363
  },
374
364
  securityAlerts: {
375
365
  type: "boolean",
376
- required: true,
377
366
  defaultTo: DEFAULT_USER_SETTINGS.securityAlerts,
378
367
  storage: { column: "notify_security_alerts" }
379
368
  },
380
369
  createdAt: {
381
370
  type: "dateTime",
382
- default: "now()",
383
371
  storage: {
384
372
  column: "created_at",
385
373
  writeSerializer: "datetime-utc"
@@ -387,20 +375,35 @@ const userSettingsResource = defineCrudResource({
387
375
  },
388
376
  updatedAt: {
389
377
  type: "dateTime",
390
- default: "now()",
391
378
  storage: {
392
379
  column: "updated_at",
393
380
  writeSerializer: "datetime-utc"
394
381
  }
395
382
  }
396
383
  },
384
+ });
385
+
386
+ // The account settings' CRUD surface on the user_settings table: view, list,
387
+ // create, replace and patch, each with the account settings output and every
388
+ // setting as its body. No JSKIT route serves it; an application that offers
389
+ // these operations serves this contract.
390
+ const userSettingsCrud = defineCrudContract(userSettingsTableResource, {
391
+ namespace: "userSettings",
392
+ messages: OPERATION_MESSAGES,
393
+ operations: ["view", "list", "create", "replace", "patch"],
394
+ output: userSettingsOutputValidator,
395
+ body: userSettingsBodySchema
396
+ });
397
+
398
+ // The signed-in user's settings over HTTP.
399
+ const userSettingsContract = defineApiContract({
400
+ namespace: "userSettings",
397
401
  messages: OPERATION_MESSAGES,
398
- crudOperations: ["view", "list", "create", "replace", "patch"],
399
- crud: {
400
- output: userSettingsOutputValidator,
401
- body: userSettingsBodySchema
402
- },
403
402
  operations: {
403
+ view: {
404
+ method: "GET",
405
+ output: userSettingsOutputValidator
406
+ },
404
407
  preferencesUpdate: {
405
408
  method: "PATCH",
406
409
  body: userSettingsPreferencesSchema,
@@ -446,6 +449,8 @@ export {
446
449
  USER_SETTINGS_NOTIFICATION_KEYS,
447
450
  USER_SETTINGS_PREFERENCE_KEYS,
448
451
  userSettingsOutputSchema,
452
+ userSettingsContract,
453
+ userSettingsCrud,
449
454
  userSettingsOutputValidator,
450
- userSettingsResource
455
+ userSettingsTableResource
451
456
  };
@@ -3,7 +3,7 @@ import assert from "node:assert/strict";
3
3
  import { buildSecurityStatusFromAuthMethodsStatus } from "@jskit-ai/auth-core/shared/authSecurityStatus";
4
4
  import { validateOperationSection } from "@jskit-ai/http-runtime/shared/validators/operationValidation";
5
5
  import { createService } from "../src/server/accountSecurity/accountSecurityService.js";
6
- import { userSettingsResource } from "../src/shared/resources/userSettingsResource.js";
6
+ import { userSettingsContract } from "../src/shared/resources/userSettingsResource.js";
7
7
 
8
8
  test("account security service returns no content result for other sessions", async () => {
9
9
  const calls = [];
@@ -41,7 +41,7 @@ test("unlinking returns the security status in the settings output contract", as
41
41
  ]
42
42
  });
43
43
  const outputOf = (value) => validateOperationSection({
44
- operation: userSettingsResource.operations.oauthUnlink,
44
+ operation: userSettingsContract.operations.oauthUnlink,
45
45
  section: "output",
46
46
  value
47
47
  });
@@ -22,9 +22,9 @@ test("authProfileSyncService.syncIdentityProfile uses shared transaction for pro
22
22
  displayName: payload.displayName
23
23
  };
24
24
  },
25
- async withTransaction(work) {
25
+ async withTransaction(options, work) {
26
26
  calls.push({ step: "withTransaction", trx: transaction });
27
- return work(transaction);
27
+ return work({ ...options, trx: transaction });
28
28
  }
29
29
  },
30
30
  userSettingsRepository: {
@@ -82,8 +82,8 @@ test("authProfileSyncService.syncIdentityProfile skips write path when profile i
82
82
  upsertCalls += 1;
83
83
  return null;
84
84
  },
85
- async withTransaction(work) {
86
- return work({ trxId: "tx-2" });
85
+ async withTransaction(options, work) {
86
+ return work({ ...options, trx: { trxId: "tx-2" } });
87
87
  }
88
88
  },
89
89
  userSettingsRepository: {
@@ -126,8 +126,8 @@ test("authProfileSyncService.findByIdentity normalizes provider identity input",
126
126
  async upsert() {
127
127
  return null;
128
128
  },
129
- async withTransaction(work) {
130
- return work({ trxId: "tx-3" });
129
+ async withTransaction(options, work) {
130
+ return work({ ...options, trx: { trxId: "tx-3" } });
131
131
  }
132
132
  },
133
133
  userSettingsRepository: {
@@ -160,7 +160,11 @@ test("auth profile sync joins the supplied managed transaction and propagates co
160
160
  userProfilesRepository: {
161
161
  async findByIdentity(_identity, options) { calls.push(options.trx); return null; },
162
162
  async upsert(_data, options) { calls.push(options.trx); return profile; },
163
- async withTransaction() { throw new Error("Must join the caller's owner"); }
163
+ // The repository joins the caller's transaction instead of opening one.
164
+ async withTransaction(options, work) {
165
+ if (!options.trx) throw new Error("Must join the caller's owner");
166
+ return work(options);
167
+ }
164
168
  },
165
169
  userSettingsRepository: {
166
170
  async ensureForUserId(_id, options) { calls.push(options.trx); }
@@ -191,9 +195,9 @@ test("an ordinary request's profile check (onlyWhenChanged) reads a matching pro
191
195
  row = { id: row?.id || "8", ...payload };
192
196
  return row;
193
197
  },
194
- async withTransaction(work) {
198
+ async withTransaction(options, work) {
195
199
  calls.push("transaction");
196
- return work({ trxId: "tx" });
200
+ return work({ ...options, trx: { trxId: "tx" } });
197
201
  }
198
202
  },
199
203
  userSettingsRepository: {
@@ -14,6 +14,8 @@ test("users-core exports are explicit and aligned with production/template usage
14
14
  packageDir: PACKAGE_DIR,
15
15
  packageId: "@jskit-ai/users-core",
16
16
  requiredExports: [
17
+ // An application's tests start it with UsersIdentityProvider for users.profiles.
18
+ "./server/UsersExtensionsProvider",
17
19
  "./server/UsersFeature",
18
20
  "./server/UsersIdentityProvider",
19
21
  "./server/usersExtensions",
@@ -1,5 +1,7 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
+ import knexLib from "knex";
4
+ import { createTestResourceRuntime } from "@jskit-ai/resource-runtime/test";
3
5
  import { ActionProvider } from "@jskit-ai/kernel/server/actions";
4
6
  import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
5
7
  import { createCapabilityRuntime, defineProvider } from "@jskit-ai/kernel/shared/capabilities";
@@ -7,26 +9,18 @@ import { createBootstrapRuntime, EventProvider } from "@jskit-ai/kernel/server/r
7
9
  import { UsersExtensionsProvider } from "../src/server/UsersExtensionsProvider.js";
8
10
  import { UsersFeature } from "../src/server/UsersFeature.js";
9
11
  import { UsersIdentityProvider } from "../src/server/UsersIdentityProvider.js";
12
+ import { userProfileTableResource } from "../src/shared/resources/userProfileResource.js";
13
+ import { userSettingsTableResource } from "../src/shared/resources/userSettingsResource.js";
10
14
 
11
- function createJsonRestApiFixture() {
12
- const resources = {};
13
- return {
14
- resources,
15
- async addResource(scopeName) {
16
- resources[scopeName] = Object.freeze({
17
- query: async () => ({ data: [] }),
18
- post: async () => null,
19
- patch: async () => null
20
- });
21
- }
22
- };
23
- }
24
-
25
- test("UsersFeature assembles account behavior through explicit capabilities", async () => {
15
+ test("UsersFeature assembles account behavior through explicit capabilities", async (t) => {
26
16
  const routes = [];
27
17
  const bootstrap = createBootstrapRuntime();
28
- const jsonRestApi = createJsonRestApiFixture();
18
+ const knex = knexLib({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true });
19
+ t.after(() => knex.destroy());
20
+ const resourceRuntime = await createTestResourceRuntime({ knex });
29
21
  let users = null;
22
+ let profiles = null;
23
+ let settings = null;
30
24
  let actionCatalogue = null;
31
25
  let profileProjector = null;
32
26
  const probe = defineProvider({
@@ -34,11 +28,15 @@ test("UsersFeature assembles account behavior through explicit capabilities", as
34
28
  requires: {
35
29
  actions: "runtime.actions",
36
30
  projector: "auth.profile.projector",
31
+ profilesCapability: "users.profiles",
32
+ settingsCapability: "users.settings",
37
33
  usersCapability: "users.core"
38
34
  },
39
- setup({ actions, projector, usersCapability }) {
35
+ setup({ actions, projector, profilesCapability, settingsCapability, usersCapability }) {
40
36
  actionCatalogue = actions;
41
37
  profileProjector = projector;
38
+ profiles = profilesCapability;
39
+ settings = settingsCapability;
42
40
  users = usersCapability;
43
41
  return {};
44
42
  }
@@ -55,7 +53,7 @@ test("UsersFeature assembles account behavior through explicit capabilities", as
55
53
  }
56
54
  }
57
55
  },
58
- "runtime.json-rest-api": jsonRestApi,
56
+ "runtime.resources": resourceRuntime,
59
57
  "runtime.storage": {
60
58
  async getItemRaw() { return null; },
61
59
  async setItemRaw() {},
@@ -68,8 +66,21 @@ test("UsersFeature assembles account behavior through explicit capabilities", as
68
66
 
69
67
  await runtime.start();
70
68
 
71
- assert.deepEqual(Object.keys(jsonRestApi.resources).sort(), ["userProfiles", "userSettings"]);
72
- assert.equal(typeof users.repositories.userProfiles.findByIdentity, "function");
69
+ assert.deepEqual(resourceRuntime.ownedTables(), [
70
+ { name: "userProfiles", tableName: "users", featureId: "users.identity" },
71
+ { name: "userSettings", tableName: "user_settings", featureId: "users.identity" }
72
+ ]);
73
+ assert.equal(typeof profiles.findByIdentity, "function");
74
+ assert.equal(typeof profiles.createWithSettings, "function");
75
+ assert.equal(typeof profiles.countUsers, "function");
76
+ assert.deepEqual(
77
+ ["query", "get", "pageLimits"].map((method) => typeof profiles[method]),
78
+ ["function", "function", "function"],
79
+ "users.profiles serves a CRUD feature's reads"
80
+ );
81
+ assert.equal(Object.hasOwn(profiles, "create"), false, "and no handle writes");
82
+ assert.equal(typeof settings.ensureForUserId, "function");
83
+ assert.equal(Object.hasOwn(users, "repositories"), false);
73
84
  assert.equal(typeof users.services.accountProfile.updateProfile, "function");
74
85
  assert.equal(routes.includes("GET /api/settings"), true);
75
86
  assert.equal(routes.includes("POST /api/settings/security/change-password"), true);
@@ -78,3 +89,35 @@ test("UsersFeature assembles account behavior through explicit capabilities", as
78
89
  assert.equal(typeof profileProjector.syncIdentityProfile, "function");
79
90
  assert.equal(typeof profileProjector.findByIdentity, "function");
80
91
  });
92
+
93
+ test("every search entry of the users tables filters, and id takes one id or a list", async (t) => {
94
+ const knex = knexLib({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true });
95
+ t.after(() => knex.destroy());
96
+ const resourceRuntime = await createTestResourceRuntime({ knex, createTables: true });
97
+ const { userProfiles, userSettings } = await resourceRuntime.own("test.users", [userProfileTableResource, userSettingsTableResource]);
98
+ const options = { context: {} };
99
+ const people = [["ada", "Ada Lovelace"], ["grace", "Grace Hopper"], ["alan", "Alan Turing"]];
100
+ const ids = [];
101
+ for (const [username, displayName] of people) {
102
+ const { id } = await userProfiles.create({
103
+ authProvider: "local",
104
+ authProviderUserSid: username,
105
+ email: `${username}@example.com`,
106
+ username,
107
+ displayName
108
+ }, options);
109
+ ids.push(id);
110
+ }
111
+ const usernames = async (filters) => (await userProfiles.queryAll({ filters }, options)).map(({ username }) => username).sort();
112
+
113
+ assert.deepEqual(await usernames({ id: ids[1] }), ["grace"]);
114
+ assert.deepEqual(await usernames({ id: [ids[0], ids[2]] }), ["ada", "alan"]);
115
+ assert.deepEqual(await usernames({ id: [] }), []);
116
+ assert.deepEqual(await usernames({ usernames: ["ada", "grace"] }), ["ada", "grace"]);
117
+ assert.deepEqual(await usernames({ emails: ["alan@example.com"] }), ["alan"]);
118
+ assert.deepEqual(await usernames({ createdSince: "2000-01-01T00:00:00.000Z" }), ["ada", "alan", "grace"]);
119
+ assert.deepEqual(await usernames({ q: "lovelace" }), ["ada"]);
120
+ assert.deepEqual(await usernames({ authProvider: "local", authProviderUserSid: "grace" }), ["grace"]);
121
+ // The settings table is keyed by its user's id, and its id filter takes a list as well.
122
+ assert.deepEqual(await userSettings.queryAll({ filters: { id: [ids[0], ids[1]] } }, options), []);
123
+ });
@@ -6,7 +6,7 @@ import en from "../locales/en.json" with { type: "json" };
6
6
  import { createService as createAccountProfileService } from "../src/server/accountProfile/accountProfileService.js";
7
7
  import { createService as createAccountSecurityService } from "../src/server/accountSecurity/accountSecurityService.js";
8
8
  import { createRepository as createUserSettingsRepository } from "../src/server/common/repositories/userSettingsRepository.js";
9
- import { userSettingsResource } from "../src/shared/resources/userSettingsResource.js";
9
+ import { userSettingsContract, userSettingsTableResource } from "../src/shared/resources/userSettingsResource.js";
10
10
  import { normalizeLocaleCode } from "../src/shared/settings.js";
11
11
 
12
12
  // A code's catalog English, rendered with its params, is exactly the English sent.
@@ -71,7 +71,7 @@ test("saved locales are canonical BCP 47 tags", () => {
71
71
 
72
72
  test("preference input keeps the locale's case and storage canonicalizes it", async () => {
73
73
  const parsed = validateOperationSection({
74
- operation: userSettingsResource.operations.preferencesUpdate,
74
+ operation: userSettingsContract.operations.preferencesUpdate,
75
75
  section: "body",
76
76
  value: {
77
77
  theme: "system",
@@ -85,18 +85,14 @@ test("preference input keeps the locale's case and storage canonicalizes it", as
85
85
  });
86
86
  assert.equal(parsed.ok, true);
87
87
  assert.equal(parsed.value.locale, "en-US");
88
- assert.equal(userSettingsResource.schema.locale.setter("it-it"), "it-IT");
88
+ assert.equal(userSettingsTableResource.schema.locale.setter("it-it"), "it-IT");
89
89
  });
90
90
 
91
91
  test("user settings reads canonicalize locales saved lowercased", async () => {
92
92
  const repository = createUserSettingsRepository({
93
- api: {
94
- resources: {
95
- userSettings: {
96
- async query() {
97
- return { data: [{ id: "7", locale: "en-us", theme: "dark" }] };
98
- }
99
- }
93
+ userSettings: {
94
+ async query() {
95
+ return { records: [{ id: "7", locale: "en-us", theme: "dark" }], page: { size: 1, hasMore: false, next: null } };
100
96
  }
101
97
  }
102
98
  });