@jskit-ai/users-core 0.2.4 → 0.2.6

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 (53) hide show
  1. package/locales/en.json +1 -7
  2. package/package.json +42 -19
  3. package/patterns/user-administration-server/PATTERN.md +16 -1
  4. package/patterns/user-administration-server/example/packages/users/package.json +3 -2
  5. package/patterns/user-administration-server/example/packages/users/src/server/types.js +5 -0
  6. package/patterns/user-administration-server/example/packages/users-workspace/package.json +4 -3
  7. package/patterns/user-administration-server/example/packages/users-workspace/src/server/UsersWorkspaceFeature.js +2 -9
  8. package/patterns/user-administration-server/example/packages/users-workspace/src/server/types.js +5 -0
  9. package/src/server/UsersFeature.js +26 -78
  10. package/src/server/UsersIdentityProvider.js +11 -22
  11. package/src/server/accountNotifications/accountNotificationsActions.js +28 -41
  12. package/src/server/accountNotifications/{bootAccountNotificationsRoutes.js → accountNotificationsRoutes.js} +1 -4
  13. package/src/server/accountNotifications/accountNotificationsService.js +9 -10
  14. package/src/server/accountPreferences/accountPreferencesActions.js +28 -41
  15. package/src/server/accountPreferences/{bootAccountPreferencesRoutes.js → accountPreferencesRoutes.js} +1 -4
  16. package/src/server/accountPreferences/accountPreferencesService.js +10 -10
  17. package/src/server/accountProfile/accountProfileActions.js +87 -127
  18. package/src/server/accountProfile/{bootAccountProfileRoutes.js → accountProfileRoutes.js} +12 -18
  19. package/src/server/accountProfile/accountProfileService.js +19 -35
  20. package/src/server/accountProfile/avatarService.js +15 -39
  21. package/src/server/accountProfile/avatarStorageService.js +2 -1
  22. package/src/server/accountSecurity/accountSecurityActions.js +100 -148
  23. package/src/server/accountSecurity/{bootAccountSecurityRoutes.js → accountSecurityRoutes.js} +9 -8
  24. package/src/server/accountSecurity/accountSecurityService.js +15 -44
  25. package/src/server/common/formatters/accountAvatarFormatter.js +4 -4
  26. package/src/server/common/formatters/accountSecurityStatusFormatter.js +2 -3
  27. package/src/server/common/formatters/accountSettingsResponseFormatter.js +11 -2
  28. package/src/server/common/repositories/userProfilesRepository.js +31 -55
  29. package/src/server/common/repositories/userSettingsRepository.js +16 -21
  30. package/src/server/common/services/accountContextService.js +9 -7
  31. package/src/server/common/services/authProfileSyncService.js +15 -42
  32. package/src/server/common/support/accountSettingsJsonApiTransport.js +10 -3
  33. package/src/server/common/support/realtimeServiceEvents.js +3 -2
  34. package/src/server/common/support/resolveActionUser.js +9 -2
  35. package/src/server/types.js +29 -0
  36. package/src/server/usersBootstrapContributor.js +60 -84
  37. package/src/server/usersExtensions.js +1 -0
  38. package/src/server/usersIdentity.js +28 -0
  39. package/src/server/usersRuntime.js +61 -0
  40. package/src/shared/operationMessages.js +6 -15
  41. package/src/shared/resources/userProfileResource.js +3 -31
  42. package/src/shared/resources/userProfileValues.js +32 -0
  43. package/src/shared/resources/userSettingsResource.js +2 -4
  44. package/test/accountProfileService.test.js +1 -0
  45. package/test/accountSecurityService.test.js +2 -4
  46. package/test/exportsContract.test.js +2 -0
  47. package/test/featureRuntime.test.js +11 -8
  48. package/test/i18nCodes.test.js +3 -10
  49. package/test/usersBootstrapContributor.test.js +0 -1
  50. package/test/usersPackageScaffoldContract.test.js +3 -5
  51. package/test/usersRouteRequestInputValidator.test.js +4 -4
  52. package/src/server/common/repositories/repositoryUtils.js +0 -44
  53. package/src/server/common/support/deepFreeze.js +0 -1
@@ -9,162 +9,114 @@ const oauthLinkStartInputValidator = composeSchemaDefinitions([
9
9
  userSettingsResource.operations.oauthLinkStart.params,
10
10
  userSettingsResource.operations.oauthLinkStart.query
11
11
  ], {
12
- mode: "patch",
12
+ mode: "create",
13
13
  context: "accountSecurityActions.oauthLinkStartInputValidator"
14
14
  });
15
15
 
16
- const accountSecurityActionSpecifications = Object.freeze([
17
- {
18
- id: "settings.security.password.change",
19
- version: 1,
20
- kind: "command",
21
- channels: ["api", "automation", "internal"],
22
- surfaces: ["*"],
23
- permission: {
24
- require: "authenticated"
25
- },
26
- input: userSettingsResource.operations.passwordChange.body,
27
- output: null,
28
- extensions: {
29
- assistant: {
30
- exclude: "Use the authenticated account security form; passwords must not enter assistant arguments."
31
- }
32
- },
33
- idempotency: "none",
34
- async run(accountSecurityService, input, context) {
35
- return accountSecurityService.changePassword(
36
- resolveRequest(context),
37
- resolveActionUser(context, input),
38
- input,
39
- {
40
- context
16
+ /** @param {{ accountSecurityService: import("../types.js").AccountSecurityService }} dependencies */
17
+ function createAccountSecurityActions({ accountSecurityService }) {
18
+ return Object.freeze([
19
+ Object.freeze({
20
+ id: "settings.security.password.change",
21
+ version: 1,
22
+ kind: "command",
23
+ channels: ["api", "automation", "internal"],
24
+ surfaces: ["*"],
25
+ permission: {
26
+ require: "authenticated"
27
+ },
28
+ input: userSettingsResource.operations.passwordChange.body,
29
+ output: null,
30
+ extensions: {
31
+ assistant: {
32
+ exclude: "Use the authenticated account security form; passwords must not enter assistant arguments."
41
33
  }
42
- );
43
- }
44
- },
45
- {
46
- id: "settings.security.password_method.toggle",
47
- version: 1,
48
- kind: "command",
49
- channels: ["api", "automation", "internal"],
50
- surfaces: ["*"],
51
- permission: {
52
- require: "authenticated"
53
- },
54
- input: userSettingsResource.operations.passwordMethodToggle.body,
55
- output: null,
56
- extensions: {
57
- assistant: {
58
- description: "Enable or disable password sign-in for the signed-in user, subject to the account authentication policy.",
59
- output: userSettingsResource.operations.passwordMethodToggle.output,
60
- transformResult: (result) => ({ securityStatus: result.value.securityStatus, settings: result.value.settings })
61
- }
62
- },
63
- idempotency: "none",
64
- async run(accountSecurityService, input, context) {
65
- return accountSecurityService.setPasswordMethodEnabled(
66
- resolveRequest(context),
67
- resolveActionUser(context, input),
68
- input,
69
- {
70
- context
34
+ },
35
+ execute: (input, context) => accountSecurityService.changePassword(resolveRequest(context), input)
36
+ }),
37
+ Object.freeze({
38
+ id: "settings.security.password_method.toggle",
39
+ version: 1,
40
+ kind: "command",
41
+ channels: ["api", "automation", "internal"],
42
+ surfaces: ["*"],
43
+ permission: {
44
+ require: "authenticated"
45
+ },
46
+ input: { schema: userSettingsResource.operations.passwordMethodToggle.body.schema },
47
+ output: null,
48
+ extensions: {
49
+ assistant: {
50
+ description: "Enable or disable password sign-in for the signed-in user, subject to the account authentication policy.",
51
+ output: userSettingsResource.operations.passwordMethodToggle.output,
52
+ transformResult: (result) => ({ securityStatus: result.value.securityStatus, settings: result.value.settings })
71
53
  }
72
- );
73
- }
74
- },
75
- {
76
- id: "settings.security.oauth.link.start",
77
- version: 1,
78
- kind: "query",
79
- channels: ["api", "automation", "internal"],
80
- surfaces: ["*"],
81
- permission: {
82
- require: "authenticated"
83
- },
84
- input: oauthLinkStartInputValidator,
85
- output: null,
86
- extensions: {
87
- assistant: {
88
- exclude: "Use the authenticated account security screen; OAuth authorization URLs contain transient credentials."
89
- }
90
- },
91
- idempotency: "none",
92
- async run(accountSecurityService, input, context) {
93
- return accountSecurityService.startOAuthProviderLink(
54
+ },
55
+ execute: (input, context) => accountSecurityService.setPasswordMethodEnabled(
94
56
  resolveRequest(context),
95
57
  resolveActionUser(context, input),
96
- input,
97
- {
98
- context
58
+ input
59
+ )
60
+ }),
61
+ Object.freeze({
62
+ id: "settings.security.oauth.link.start",
63
+ version: 1,
64
+ kind: "query",
65
+ channels: ["api", "automation", "internal"],
66
+ surfaces: ["*"],
67
+ permission: {
68
+ require: "authenticated"
69
+ },
70
+ input: oauthLinkStartInputValidator,
71
+ output: null,
72
+ extensions: {
73
+ assistant: {
74
+ exclude: "Use the authenticated account security screen; OAuth authorization URLs contain transient credentials."
99
75
  }
100
- );
101
- }
102
- },
103
- {
104
- id: "settings.security.oauth.unlink",
105
- version: 1,
106
- kind: "command",
107
- channels: ["api", "automation", "internal"],
108
- surfaces: ["*"],
109
- permission: {
110
- require: "authenticated"
111
- },
112
- input: userSettingsResource.operations.oauthUnlink.params,
113
- output: null,
114
- extensions: {
115
- assistant: {
116
- description: "Unlink an OAuth sign-in method from the signed-in account, subject to the account authentication policy.",
117
- output: userSettingsResource.operations.oauthUnlink.output,
118
- transformResult: (result) => ({ securityStatus: result.value.securityStatus })
119
- }
120
- },
121
- idempotency: "none",
122
- async run(accountSecurityService, input, context) {
123
- return accountSecurityService.unlinkOAuthProvider(
124
- resolveRequest(context),
125
- resolveActionUser(context, input),
126
- input,
127
- {
128
- context
76
+ },
77
+ execute: (input, context) => accountSecurityService.startOAuthProviderLink(resolveRequest(context), input)
78
+ }),
79
+ Object.freeze({
80
+ id: "settings.security.oauth.unlink",
81
+ version: 1,
82
+ kind: "command",
83
+ channels: ["api", "automation", "internal"],
84
+ surfaces: ["*"],
85
+ permission: {
86
+ require: "authenticated"
87
+ },
88
+ input: { schema: userSettingsResource.operations.oauthUnlink.params.schema },
89
+ output: null,
90
+ extensions: {
91
+ assistant: {
92
+ description: "Unlink an OAuth sign-in method from the signed-in account, subject to the account authentication policy.",
93
+ output: userSettingsResource.operations.oauthUnlink.output,
94
+ transformResult: (result) => ({ securityStatus: result.value.securityStatus })
129
95
  }
130
- );
131
- }
132
- },
133
- {
134
- id: "settings.security.sessions.logout_others",
135
- version: 1,
136
- kind: "command",
137
- channels: ["api", "automation", "internal"],
138
- surfaces: ["*"],
139
- permission: {
140
- require: "authenticated"
141
- },
142
- input: userSettingsResource.operations.logoutOtherSessions.body,
143
- output: null,
144
- extensions: {
145
- assistant: {
146
- description: "Sign the current user out of other devices.",
147
- output: userSettingsResource.operations.logoutOtherSessions.output,
148
- transformResult: () => ({ ok: true })
149
- }
150
- },
151
- idempotency: "none",
152
- async run(accountSecurityService, input, context) {
153
- return accountSecurityService.logoutOtherSessions(resolveRequest(context), resolveActionUser(context, input), {
154
- context
155
- });
156
- }
157
- }
158
- ]);
159
-
160
- function buildAccountSecurityActions({ accountSecurityService } = {}) {
161
- if (!accountSecurityService) throw new TypeError("buildAccountSecurityActions requires accountSecurityService.");
162
- return accountSecurityActionSpecifications.map(({ run, ...definition }) => Object.freeze({
163
- ...definition,
164
- execute(input, context) {
165
- return run(accountSecurityService, input, context);
166
- }
167
- }));
96
+ },
97
+ execute: (input, context) => accountSecurityService.unlinkOAuthProvider(resolveRequest(context), input)
98
+ }),
99
+ Object.freeze({
100
+ id: "settings.security.sessions.logout_others",
101
+ version: 1,
102
+ kind: "command",
103
+ channels: ["api", "automation", "internal"],
104
+ surfaces: ["*"],
105
+ permission: {
106
+ require: "authenticated"
107
+ },
108
+ input: userSettingsResource.operations.logoutOtherSessions.body,
109
+ output: null,
110
+ extensions: {
111
+ assistant: {
112
+ description: "Sign the current user out of other devices.",
113
+ output: userSettingsResource.operations.logoutOtherSessions.output,
114
+ transformResult: () => ({ ok: true })
115
+ }
116
+ },
117
+ execute: (input, context) => accountSecurityService.logoutOtherSessions(resolveRequest(context))
118
+ })
119
+ ]);
168
120
  }
169
121
 
170
- export { accountSecurityActionSpecifications, buildAccountSecurityActions };
122
+ export { createAccountSecurityActions };
@@ -26,11 +26,11 @@ const passwordChangeMetaOutputValidator = deepFreeze({
26
26
  mode: "replace"
27
27
  });
28
28
 
29
- function registerAccountSecurityRoutes(router, { authService } = {}) {
30
- if (!router || typeof router.register !== "function") {
31
- throw new TypeError("registerAccountSecurityRoutes requires router.register().");
32
- }
33
-
29
+ /**
30
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeRouter} router
31
+ * @param {{ authService: import("@jskit-ai/auth-core/server/types").AuthService }} dependencies
32
+ */
33
+ function registerAccountSecurityRoutes(router, { authService }) {
34
34
  router.register(
35
35
  "POST",
36
36
  "/api/settings/security/change-password",
@@ -58,11 +58,11 @@ function registerAccountSecurityRoutes(router, { authService } = {}) {
58
58
  input: request.input.body
59
59
  });
60
60
 
61
- if (result?.session && typeof authService.writeSessionCookies === "function") {
61
+ if (result.session) {
62
62
  authService.writeSessionCookies(reply, result.session);
63
63
  }
64
64
 
65
- reply.code(200).send(result?.response || result);
65
+ reply.code(200).send(result.response);
66
66
  }
67
67
  );
68
68
 
@@ -133,7 +133,8 @@ function registerAccountSecurityRoutes(router, { authService } = {}) {
133
133
  });
134
134
 
135
135
  // As at sign-in, a provider that binds the attempt to this browser sets its cookie.
136
- if (typeof authService?.writeOAuthStartCookies === "function") {
136
+ // readable-check: allow method-probe - optional operation: writeOAuthStartCookies is an optional auth.service operation
137
+ if (typeof authService.writeOAuthStartCookies === "function") {
137
138
  authService.writeOAuthStartCookies(reply, result);
138
139
  }
139
140
  reply.redirect(result.url);
@@ -10,22 +10,16 @@ import {
10
10
  } from "../common/formatters/accountSettingsResponseFormatter.js";
11
11
  import { accountSecurityStatusFormatter } from "../common/formatters/accountSecurityStatusFormatter.js";
12
12
 
13
- function createService({
14
- userSettingsRepository,
15
- userProfilesRepository,
16
- authService
17
- } = {}) {
18
- if (!userSettingsRepository || !userProfilesRepository) {
19
- throw new Error("accountSecurityService requires repositories.");
20
- }
21
-
22
- async function changePassword(request, user, payload = {}, options = {}) {
23
- if (!authService || typeof authService.changePassword !== "function") {
24
- throw new AppError(501, "Password change is not available.", {
25
- code: "users.security.passwordChangeUnavailable"
26
- });
27
- }
28
-
13
+ /**
14
+ * A signed-in user's password, sign-in methods and sessions, through the
15
+ * installed auth provider.
16
+ * @param {object} dependencies
17
+ * @param {import("../types.js").UserSettingsRepository} dependencies.userSettingsRepository
18
+ * @param {import("../types.js").UserProfilesRepository} dependencies.userProfilesRepository
19
+ * @param {import("@jskit-ai/auth-core/server/types").AuthService} dependencies.authService The installed provider's `auth.service`.
20
+ */
21
+ function createService({ userSettingsRepository, userProfilesRepository, authService }) {
22
+ async function changePassword(request, payload) {
29
23
  if (payload.confirmPassword !== payload.newPassword) {
30
24
  throw createValidationError({
31
25
  confirmPassword: {
@@ -51,13 +45,7 @@ function createService({
51
45
  };
52
46
  }
53
47
 
54
- async function setPasswordMethodEnabled(request, user, payload = {}, options = {}) {
55
- if (!authService || typeof authService.setPasswordSignInEnabled !== "function") {
56
- throw new AppError(501, "Password method toggle is not available.", {
57
- code: "users.security.passwordMethodToggleUnavailable"
58
- });
59
- }
60
-
48
+ async function setPasswordMethodEnabled(request, user, payload) {
61
49
  const profile = await resolveUserProfile(userProfilesRepository, user);
62
50
  if (!profile) {
63
51
  throw new AppError(404, "User profile was not found.", { code: "users.profile.notFound" });
@@ -80,26 +68,14 @@ function createService({
80
68
  });
81
69
  }
82
70
 
83
- async function startOAuthProviderLink(request, user, payload = {}, options = {}) {
84
- if (!authService || typeof authService.startProviderLink !== "function") {
85
- throw new AppError(501, "OAuth linking is not available.", {
86
- code: "users.security.oauthLinkUnavailable"
87
- });
88
- }
89
-
71
+ async function startOAuthProviderLink(request, payload) {
90
72
  return authService.startProviderLink(request, {
91
73
  provider: payload.provider,
92
74
  returnTo: payload.returnTo
93
75
  });
94
76
  }
95
77
 
96
- async function unlinkOAuthProvider(request, user, payload = {}, options = {}) {
97
- if (!authService || typeof authService.unlinkProvider !== "function") {
98
- throw new AppError(501, "OAuth unlink is not available.", {
99
- code: "users.security.oauthUnlinkUnavailable"
100
- });
101
- }
102
-
78
+ async function unlinkOAuthProvider(request, payload) {
103
79
  const result = await authService.unlinkProvider(request, {
104
80
  provider: payload.provider
105
81
  });
@@ -108,13 +84,7 @@ function createService({
108
84
  });
109
85
  }
110
86
 
111
- async function logoutOtherSessions(request, _user, options = {}) {
112
- if (!authService || typeof authService.signOutOtherSessions !== "function") {
113
- throw new AppError(501, "Logout other sessions is not available.", {
114
- code: "users.security.logoutOtherSessionsUnavailable"
115
- });
116
- }
117
-
87
+ async function logoutOtherSessions(request) {
118
88
  await authService.signOutOtherSessions(request);
119
89
 
120
90
  return null;
@@ -122,6 +92,7 @@ function createService({
122
92
 
123
93
  return Object.freeze({
124
94
  changePassword,
95
+ // readable-check: allow setter-seam - not a slot: setPasswordMethodEnabled is a service operation
125
96
  setPasswordMethodEnabled,
126
97
  startOAuthProviderLink,
127
98
  unlinkOAuthProvider,
@@ -4,13 +4,13 @@ import { DEFAULT_USER_SETTINGS } from "../../../shared/settings.js";
4
4
 
5
5
  const ACCOUNT_AVATAR_FILE_PATH = "/api/settings/profile/avatar";
6
6
 
7
- function createGravatarUrl(email, size = 64) {
7
+ function buildGravatarUrl(email, size) {
8
8
  const normalizedEmail = normalizeLowerText(email);
9
9
  const hash = createHash("sha256").update(normalizedEmail).digest("hex");
10
10
  return `https://www.gravatar.com/avatar/${hash}?d=mp&s=${Number(size) || 64}`;
11
11
  }
12
12
 
13
- function createUploadedAvatarUrl(profile = {}) {
13
+ function buildUploadedAvatarUrl(profile) {
14
14
  const storageKey = String(profile?.avatarStorageKey || "").trim();
15
15
  if (!storageKey) {
16
16
  return null;
@@ -26,8 +26,8 @@ function createUploadedAvatarUrl(profile = {}) {
26
26
 
27
27
  function accountAvatarFormatter(profile, settings) {
28
28
  const size = Number(settings?.avatarSize || DEFAULT_USER_SETTINGS.avatarSize);
29
- const uploadedUrl = createUploadedAvatarUrl(profile);
30
- const gravatarUrl = createGravatarUrl(profile?.email, size);
29
+ const uploadedUrl = buildUploadedAvatarUrl(profile);
30
+ const gravatarUrl = buildGravatarUrl(profile?.email, size);
31
31
 
32
32
  return {
33
33
  uploadedUrl,
@@ -1,5 +1,4 @@
1
- import { normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
2
- import { isRecord } from "@jskit-ai/kernel/shared/support/normalize";
1
+ import { isRecord, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
3
2
 
4
3
  function normalizeMfa(source) {
5
4
  const mfaSource = isRecord(source?.mfa) ? source.mfa : {};
@@ -49,7 +48,7 @@ function normalizeAuthMethods(sourceMethods) {
49
48
  };
50
49
  }
51
50
 
52
- function accountSecurityStatusFormatter(securityStatus = {}) {
51
+ function accountSecurityStatusFormatter(securityStatus) {
53
52
  const source = isRecord(securityStatus) ? securityStatus : {};
54
53
  const policy = isRecord(source.policy) ? source.policy : {};
55
54
  const { methods: authMethods, enabledMethodsCount } = normalizeAuthMethods(source.authMethods);
@@ -6,8 +6,10 @@ import {
6
6
  import { accountAvatarFormatter } from "./accountAvatarFormatter.js";
7
7
  import { accountSecurityStatusFormatter } from "./accountSecurityStatusFormatter.js";
8
8
 
9
+ /** @param {import("@jskit-ai/auth-core/server/types").AuthService} authService */
9
10
  function resolveAuthProfileSettings(authService) {
10
- if (!authService || typeof authService.getSettingsProfileAuthInfo !== "function") {
11
+ // readable-check: allow method-probe - optional operation: getSettingsProfileAuthInfo is an optional auth.service operation
12
+ if (typeof authService.getSettingsProfileAuthInfo !== "function") {
11
13
  return {
12
14
  emailManagedBy: "auth",
13
15
  emailChangeFlow: "auth"
@@ -32,6 +34,13 @@ function formatUserSettingsSection(fieldKeys, settings = {}) {
32
34
  return formatted;
33
35
  }
34
36
 
37
+ /**
38
+ * @param {object} input
39
+ * @param {object | null} input.profile
40
+ * @param {object | null} input.settings
41
+ * @param {object | null} input.securityStatus
42
+ * @param {import("@jskit-ai/auth-core/server/types").AuthService} input.authService The installed provider's `auth.service`.
43
+ */
35
44
  function accountSettingsResponseFormatter({ profile, settings, securityStatus, authService }) {
36
45
  const authProfileSettings = resolveAuthProfileSettings(authService);
37
46
 
@@ -49,4 +58,4 @@ function accountSettingsResponseFormatter({ profile, settings, securityStatus, a
49
58
  };
50
59
  }
51
60
 
52
- export { accountSettingsResponseFormatter };
61
+ export { accountSettingsResponseFormatter, formatUserSettingsSection };
@@ -1,45 +1,19 @@
1
1
  import {
2
2
  findDuplicateEntryError,
3
- isDuplicateEntryError,
3
+ isLostDuplicateInsertRace,
4
+ joinOrOpenTransaction,
4
5
  normalizeDbRecordId,
5
- normalizeLowerText,
6
- normalizeRecordId,
7
- normalizeText,
8
- toIsoString,
9
- retryDeadlocks
10
- } from "./repositoryUtils.js";
6
+ resolveTransaction,
7
+ retryDeadlocks,
8
+ toIsoString
9
+ } from "@jskit-ai/database-runtime/shared";
10
+ import { normalizeLowerText, normalizeRecordId, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
11
11
  import {
12
12
  createJsonRestContext,
13
13
  extractJsonRestCollectionRows
14
14
  } from "@jskit-ai/json-rest-api-core/server/jsonRestApiHost";
15
15
  import { normalizeIdentity } from "../support/identity.js";
16
-
17
- const USERNAME_MAX_LENGTH = 120;
18
-
19
- function normalizeUsername(value) {
20
- const normalized = normalizeLowerText(value)
21
- .replace(/[^a-z0-9]+/g, "-")
22
- .replace(/^-+|-+$/g, "")
23
- .slice(0, USERNAME_MAX_LENGTH);
24
-
25
- return normalized || "";
26
- }
27
-
28
- function normalizeNullableString(value) {
29
- if (value === null || value === undefined) {
30
- return null;
31
- }
32
-
33
- return normalizeText(value);
34
- }
35
-
36
- function normalizeNullableVersion(value) {
37
- if (value === null || value === undefined || value === "") {
38
- return null;
39
- }
40
-
41
- return String(value);
42
- }
16
+ import { USERNAME_MAX_LENGTH, normalizeNullableString, normalizeNullableVersion, normalizeUsername } from "../../../shared/resources/userProfileValues.js";
43
17
 
44
18
  function normalizeProfileRecord(payload = null) {
45
19
  if (!payload || typeof payload !== "object") {
@@ -132,13 +106,18 @@ function duplicateTargetsUsername(error) {
132
106
  return message.includes("username");
133
107
  }
134
108
 
135
- function createDuplicateEmailConflictError(cause) {
109
+ function buildDuplicateEmailConflictError(cause) {
136
110
  const error = new Error("Email is already linked to a different profile.", { cause });
137
111
  error.transactionOutcome = cause.transactionOutcome;
138
112
  error.code = "USER_PROFILE_EMAIL_CONFLICT";
139
113
  return error;
140
114
  }
141
115
 
116
+ /**
117
+ * @param {import("@jskit-ai/json-rest-api-core/server/types").RuntimeJsonRestApi} api
118
+ * @param {string} baseUsername
119
+ * @param {{ excludeUserId?: unknown, transaction?: object | null }} [options]
120
+ */
142
121
  async function resolveUniqueUsername(api, baseUsername, { excludeUserId = null, transaction = null } = {}) {
143
122
  const normalizedExcludeUserId = normalizeDbRecordId(excludeUserId, { fallback: null });
144
123
 
@@ -165,11 +144,8 @@ async function resolveUniqueUsername(api, baseUsername, { excludeUserId = null,
165
144
  throw new Error("Unable to generate unique username.");
166
145
  }
167
146
 
168
- function createRepository({ api } = {}) {
169
- if (!api?.resources?.userProfiles) {
170
- throw new TypeError("internal.repository.user-profiles requires json-rest-api userProfiles resource.");
171
- }
172
-
147
+ /** @param {{ api: import("@jskit-ai/json-rest-api-core/server/types").RuntimeJsonRestApi }} dependencies */
148
+ function createRepository({ api }) {
173
149
  const withTransaction = (work) => retryDeadlocks(() => api.transaction(work));
174
150
 
175
151
  async function queryFirst(filters = {}, options = {}) {
@@ -179,10 +155,10 @@ function createRepository({ api } = {}) {
179
155
  queryParams: {
180
156
  filters
181
157
  },
182
- transaction: options?.trx || null,
158
+ transaction: resolveTransaction(options),
183
159
  format: "plain"
184
160
  },
185
- createJsonRestContext(options?.context || null)
161
+ createJsonRestContext(options.context)
186
162
  )
187
163
  );
188
164
 
@@ -239,9 +215,9 @@ function createRepository({ api } = {}) {
239
215
  },
240
216
  format: "plain",
241
217
  returning: "full",
242
- transaction: options?.trx || null
218
+ transaction: resolveTransaction(options)
243
219
  },
244
- createJsonRestContext(options?.context || null)
220
+ createJsonRestContext(options.context)
245
221
  );
246
222
 
247
223
  return normalizeProfileRecord(updated);
@@ -264,9 +240,9 @@ function createRepository({ api } = {}) {
264
240
  },
265
241
  format: "plain",
266
242
  returning: "full",
267
- transaction: options?.trx || null
243
+ transaction: resolveTransaction(options)
268
244
  },
269
- createJsonRestContext(options?.context || null)
245
+ createJsonRestContext(options.context)
270
246
  );
271
247
 
272
248
  return normalizeProfileRecord(updated);
@@ -289,9 +265,9 @@ function createRepository({ api } = {}) {
289
265
  },
290
266
  format: "plain",
291
267
  returning: "full",
292
- transaction: options?.trx || null
268
+ transaction: resolveTransaction(options)
293
269
  },
294
- createJsonRestContext(options?.context || null)
270
+ createJsonRestContext(options.context)
295
271
  );
296
272
 
297
273
  return normalizeProfileRecord(updated);
@@ -317,7 +293,7 @@ function createRepository({ api } = {}) {
317
293
  const executeUpsert = async (trx) => {
318
294
  const existing = await findByIdentity(identity, {
319
295
  trx,
320
- context: options?.context || null
296
+ context: options.context
321
297
  });
322
298
 
323
299
  if (existing) {
@@ -343,7 +319,7 @@ function createRepository({ api } = {}) {
343
319
  returning: "full",
344
320
  transaction: trx
345
321
  },
346
- createJsonRestContext(options?.context || null)
322
+ createJsonRestContext(options.context)
347
323
  );
348
324
 
349
325
  return normalizeProfileRecord(updated);
@@ -369,26 +345,26 @@ function createRepository({ api } = {}) {
369
345
  returning: "full",
370
346
  transaction: trx
371
347
  },
372
- createJsonRestContext(options?.context || null)
348
+ createJsonRestContext(options.context)
373
349
  );
374
350
 
375
351
  return normalizeProfileRecord(created);
376
352
  };
377
353
 
378
354
  try {
379
- return await (options?.trx ? executeUpsert(options.trx) : withTransaction(executeUpsert));
355
+ return await joinOrOpenTransaction(options, withTransaction, executeUpsert);
380
356
  } catch (error) {
381
357
  if (["pending", "rolledBack"].includes(error?.transactionOutcome) && duplicateTargetsEmail(error)) {
382
- throw createDuplicateEmailConflictError(error);
358
+ throw buildDuplicateEmailConflictError(error);
383
359
  }
384
360
  // A failed participant cannot recover inside the caller's transaction.
385
- if (options?.trx || error?.transactionOutcome !== "rolledBack" || !isDuplicateEntryError(error)) {
361
+ if (!isLostDuplicateInsertRace(error, options)) {
386
362
  throw error;
387
363
  }
388
364
  if (duplicateTargetsUsername(error)) {
389
365
  throw error;
390
366
  }
391
- const existing = await findByIdentity(identity, { context: options?.context || null });
367
+ const existing = await findByIdentity(identity, { context: options.context });
392
368
  if (existing) {
393
369
  return existing;
394
370
  }