@webitel/api-services 26.12.22 → 26.12.23

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 (27) hide show
  1. package/package.json +1 -1
  2. package/src/api/clients/emailProfiles/emailProfiles.ts +6 -19
  3. package/src/api/clients/importTemplates/importTemplates.ts +36 -21
  4. package/src/api/clients/storagePolicies/storagePolicies.ts +24 -36
  5. package/src/api/clients/triggers/triggerJobs.ts +22 -12
  6. package/src/api/clients/triggers/triggers.ts +12 -37
  7. package/src/scripts/convertDuration/__tests__/convertDurationWithMilliseconds.spec.ts +19 -0
  8. package/src/scripts/convertDuration/convertDurationWithMilliseconds.ts +18 -0
  9. package/src/scripts/index.ts +2 -0
  10. package/src/validations/emailProfile/__tests__/emailProfile.validations.spec.ts +105 -0
  11. package/src/validations/emailProfile/emailProfile.validations.ts +113 -0
  12. package/src/validations/importTemplate/__tests__/importTemplate.validations.spec.ts +77 -0
  13. package/src/validations/importTemplate/importTemplate.validations.ts +56 -0
  14. package/src/validations/index.ts +4 -0
  15. package/src/validations/storagePolicy/__tests__/storagePolicy.validations.spec.ts +52 -0
  16. package/src/validations/storagePolicy/storagePolicy.validations.ts +36 -0
  17. package/src/validations/trigger/__tests__/trigger.validations.spec.ts +92 -0
  18. package/src/validations/trigger/trigger.validations.ts +82 -0
  19. package/types/.tsbuildinfo +1 -1
  20. package/types/api/clients/importTemplates/importTemplates.d.ts +2 -2
  21. package/types/scripts/convertDuration/convertDurationWithMilliseconds.d.ts +6 -0
  22. package/types/scripts/index.d.ts +2 -1
  23. package/types/validations/emailProfile/emailProfile.validations.d.ts +36 -0
  24. package/types/validations/importTemplate/importTemplate.validations.d.ts +62 -0
  25. package/types/validations/index.d.ts +4 -0
  26. package/types/validations/storagePolicy/storagePolicy.validations.d.ts +26 -0
  27. package/types/validations/trigger/trigger.validations.d.ts +38 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webitel/api-services",
3
- "version": "26.12.22",
3
+ "version": "26.12.23",
4
4
  "private": false,
5
5
  "repository": {
6
6
  "type": "git",
@@ -1,3 +1,5 @@
1
+ import { getShallowFieldsToSendFromZodSchema } from '@webitel/api-services/gen/utils';
2
+ import { emailProfileSchema } from '@webitel/api-services/validations';
1
3
  import { EngineEmailAuthType } from '../../../gen/_models';
2
4
  import { getEmailProfileService } from '../../../gen-wire';
3
5
  import { getDefaultGetListResponse, getDefaultGetParams } from '../../defaults';
@@ -21,25 +23,10 @@ import type {
21
23
  UpdateItemParams,
22
24
  } from '../_shared/types';
23
25
 
24
- const fieldsToSend = [
25
- 'name',
26
- 'description',
27
- 'domainId',
28
- 'enabled',
29
- 'imapHost',
30
- 'smtpHost',
31
- 'fetchInterval',
32
- 'imapPort',
33
- 'login',
34
- 'mailbox',
35
- 'password',
36
- 'schema',
37
- 'smtpPort',
38
- 'authType',
39
- 'listen',
40
- 'logged',
41
- 'params',
42
- ];
26
+ /** [Claude] the card schema's fields; `id` goes in the url, not the body */
27
+ const fieldsToSend = getShallowFieldsToSendFromZodSchema(
28
+ emailProfileSchema,
29
+ ).filter((field) => field !== 'id');
43
30
 
44
31
  const getEmailProfilesList = async (params: ApiParams) => {
45
32
  const defaultObject = {
@@ -1,4 +1,9 @@
1
- import { getImportTemplateService } from '../../../gen-wire';
1
+ import { getShallowFieldsToSendFromZodSchema } from '@webitel/api-services/gen/utils';
2
+ import { importTemplateSchema } from '@webitel/api-services/validations';
3
+ import {
4
+ getImportTemplateService,
5
+ SearchImportTemplateQueryParams,
6
+ } from '../../../gen-wire';
2
7
  import { getDefaultGetListResponse, getDefaultGetParams } from '../../defaults';
3
8
  import {
4
9
  applyTransform,
@@ -6,6 +11,7 @@ import {
6
11
  merge,
7
12
  notify,
8
13
  sanitize,
14
+ sanitizeToWire,
9
15
  snakeToCamel,
10
16
  starToSearch,
11
17
  } from '../../transformers';
@@ -29,30 +35,27 @@ const doNotConvertKeys = [
29
35
  'mappings',
30
36
  ];
31
37
 
32
- const fieldsToSend = [
33
- 'description',
34
- 'name',
35
- 'parameters',
36
- 'source',
37
- 'sourceType',
38
- ];
38
+ /** [Claude] the card schema's fields */
39
+ const fieldsToSend = getShallowFieldsToSendFromZodSchema(importTemplateSchema);
39
40
 
40
- const getImportTemplatesList = async (params: ApiParams) => {
41
- const { page, size, search, sort, fields, id } = applyTransform(params, [
41
+ const searchImportTemplates = async (params: ApiParams) => {
42
+ const requestParams = applyTransform(params, [
42
43
  merge(getDefaultGetParams()),
43
44
  starToSearch('search'),
45
+ (params: ApiParams) => ({
46
+ ...params,
47
+ // [Claude] the generated param is `q`; `search` is what the datalist store sends
48
+ q: params.q ?? params.search,
49
+ }),
50
+ sanitizeToWire(
51
+ getShallowFieldsToSendFromZodSchema(SearchImportTemplateQueryParams),
52
+ ),
53
+ camelToSnake(),
44
54
  ]);
45
55
 
46
56
  try {
47
- const response = await getImportTemplateService().searchImportTemplate({
48
- page,
49
- size,
50
- // the generated param is `q`; `search` is what the datalist store sends
51
- q: search,
52
- sort,
53
- fields,
54
- id,
55
- });
57
+ const response =
58
+ await getImportTemplateService().searchImportTemplate(requestParams);
56
59
  const { items, next } = applyTransform(response.data, [
57
60
  snakeToCamel(doNotConvertKeys),
58
61
  merge(getDefaultGetListResponse()),
@@ -148,6 +151,18 @@ const updateImportTemplate = async ({
148
151
  }
149
152
  };
150
153
 
154
+ /** [Claude] a template row is uploaded from, which needs its `parameters` even when no column shows them; without a field list every field comes anyway */
155
+ const getImportTemplatesList = (params: ApiParams) =>
156
+ searchImportTemplates({
157
+ ...params,
158
+ fields: params.fields && [
159
+ ...new Set([
160
+ ...params.fields,
161
+ 'parameters',
162
+ ]),
163
+ ],
164
+ });
165
+
151
166
  const deleteImportTemplate = async ({ id }: DeleteItemParams) => {
152
167
  try {
153
168
  const response = await getImportTemplateService().deleteImportTemplate(
@@ -162,9 +177,9 @@ const deleteImportTemplate = async ({ id }: DeleteItemParams) => {
162
177
  };
163
178
 
164
179
  const getImportTemplatesLookup = (
165
- params: Parameters<typeof getImportTemplatesList>[0],
180
+ params: Parameters<typeof searchImportTemplates>[0],
166
181
  ) =>
167
- getImportTemplatesList({
182
+ searchImportTemplates({
168
183
  ...params,
169
184
  fields: params.fields || [
170
185
  'id',
@@ -1,5 +1,9 @@
1
- import deepCopy from 'deep-copy';
2
- import { getFilePoliciesService } from '../../../gen-wire';
1
+ import { getShallowFieldsToSendFromZodSchema } from '@webitel/api-services/gen/utils';
2
+ import { storagePolicySchema } from '@webitel/api-services/validations';
3
+ import {
4
+ getFilePoliciesService,
5
+ SearchFilePoliciesQueryParams,
6
+ } from '../../../gen-wire';
3
7
  import { getDefaultGetListResponse, getDefaultGetParams } from '../../defaults';
4
8
  import {
5
9
  applyTransform,
@@ -8,6 +12,7 @@ import {
8
12
  mergeEach,
9
13
  notify,
10
14
  sanitize,
15
+ sanitizeToWire,
11
16
  snakeToCamel,
12
17
  starToSearch,
13
18
  } from '../../transformers';
@@ -21,18 +26,8 @@ import type {
21
26
  UpdateItemParams,
22
27
  } from '../_shared/types';
23
28
 
24
- const fieldsToSend = [
25
- 'name',
26
- 'description',
27
- 'channels',
28
- 'mimeTypes',
29
- 'retentionDays',
30
- 'speedDownload',
31
- 'speedUpload',
32
- 'maxUploadSize',
33
- 'enabled',
34
- 'encrypt',
35
- ];
29
+ /** [Claude] the card schema's fields */
30
+ const fieldsToSend = getShallowFieldsToSendFromZodSchema(storagePolicySchema);
36
31
 
37
32
  /**
38
33
  * The list endpoint returns nothing useful without an explicit field list, so
@@ -53,6 +48,7 @@ const listFields = [
53
48
  'encrypt',
54
49
  ];
55
50
 
51
+ /** [Claude] the api leaves out zero values, a missing `enabled` or `encrypt` is `false` */
56
52
  const defaultObject = {
57
53
  name: '',
58
54
  description: '',
@@ -64,34 +60,28 @@ const defaultObject = {
64
60
  maxUploadSize: 0,
65
61
  position: 0,
66
62
  enabled: false,
67
- };
68
-
69
- const preRequestHandler = (item: ApiParams) => {
70
- const copy = deepCopy(item);
71
- return {
72
- ...copy,
73
- channels: item.channels.map(
74
- (channel: ApiParams) => channel.value || channel,
75
- ),
76
- };
63
+ encrypt: false,
77
64
  };
78
65
 
79
66
  const getStoragePoliciesList = async (params: ApiParams) => {
80
- const { page, size, search, sort, id } = applyTransform(params, [
67
+ const requestParams = applyTransform(params, [
81
68
  merge(getDefaultGetParams()),
82
69
  starToSearch('search'),
70
+ (params: ApiParams) => ({
71
+ ...params,
72
+ // [Claude] the generated param is `q`; `search` is what the datalist store sends
73
+ q: params.q ?? params.search,
74
+ fields: listFields,
75
+ }),
76
+ sanitizeToWire(
77
+ getShallowFieldsToSendFromZodSchema(SearchFilePoliciesQueryParams),
78
+ ),
79
+ camelToSnake(),
83
80
  ]);
84
81
 
85
82
  try {
86
- const response = await getFilePoliciesService().searchFilePolicies({
87
- page,
88
- size,
89
- // the generated param is `q`; `search` is what the datalist store sends
90
- q: search,
91
- sort,
92
- fields: listFields,
93
- id,
94
- });
83
+ const response =
84
+ await getFilePoliciesService().searchFilePolicies(requestParams);
95
85
  const { items, next } = applyTransform(response.data, [
96
86
  snakeToCamel(),
97
87
  merge(getDefaultGetListResponse()),
@@ -125,7 +115,6 @@ const getStoragePolicy = async ({ itemId: id }: GetItemParams) => {
125
115
 
126
116
  const addStoragePolicy = async ({ itemInstance }: AddItemParams) => {
127
117
  const item = applyTransform(itemInstance, [
128
- preRequestHandler,
129
118
  sanitize(fieldsToSend),
130
119
  // `channels` values mirror the StorageUploadFileChannel enum and stay camelCase
131
120
  camelToSnake([
@@ -149,7 +138,6 @@ const updateStoragePolicy = async ({
149
138
  itemId: id,
150
139
  }: UpdateItemParams) => {
151
140
  const item = applyTransform(itemInstance, [
152
- preRequestHandler,
153
141
  sanitize(fieldsToSend),
154
142
  // `channels` values mirror the StorageUploadFileChannel enum and stay camelCase
155
143
  camelToSnake([
@@ -1,4 +1,5 @@
1
1
  import { getTriggerService } from '../../../gen-wire';
2
+ import { normalizeDatetimeRange } from '../../../scripts';
2
3
  import { getDefaultGetListResponse, getDefaultGetParams } from '../../defaults';
3
4
  import {
4
5
  applyTransform,
@@ -9,21 +10,29 @@ import {
9
10
  } from '../../transformers';
10
11
  import type { ApiParams } from '../_shared/types';
11
12
 
13
+ /**
14
+ * [Claude] The params are the trigger logs datalist's filters: `startedAt` is
15
+ * a date range filter (a relative value or `{ from, to }`), `duration` a
16
+ * from-to range and `triggerJobState` the picked run states. The ranges are
17
+ * protobuf nested messages, so they only bind as dotted keys.
18
+ */
12
19
  const getTriggerJobsList = async (params: ApiParams) => {
13
20
  const {
14
21
  parentId,
15
22
  page,
16
23
  size,
17
- q,
24
+ search,
18
25
  sort,
19
26
  fields,
20
- startedAtFrom,
21
- startedAtTo,
22
- durationFrom,
23
- durationTo,
24
- result,
27
+ startedAt,
28
+ duration,
29
+ triggerJobState,
25
30
  } = applyTransform(params, [
26
31
  merge(getDefaultGetParams()),
32
+ ({ startedAt, ...rest }) => ({
33
+ ...rest,
34
+ startedAt: normalizeDatetimeRange(startedAt),
35
+ }),
27
36
  starToSearch('search'),
28
37
  ]);
29
38
 
@@ -33,14 +42,15 @@ const getTriggerJobsList = async (params: ApiParams) => {
33
42
  {
34
43
  page,
35
44
  size,
36
- q,
45
+ // [Claude] the generated param is `q`; `search` is what the datalist store sends
46
+ q: search,
37
47
  sort,
38
48
  fields,
39
- 'started_at.from': startedAtFrom,
40
- 'started_at.to': startedAtTo,
41
- 'duration.from': durationFrom,
42
- 'duration.to': durationTo,
43
- state: result,
49
+ 'started_at.from': startedAt?.from,
50
+ 'started_at.to': startedAt?.to,
51
+ 'duration.from': duration?.from,
52
+ 'duration.to': duration?.to,
53
+ state: triggerJobState,
44
54
  },
45
55
  );
46
56
  const { items, next } = applyTransform(response.data, [
@@ -1,3 +1,5 @@
1
+ import { getShallowFieldsToSendFromZodSchema } from '@webitel/api-services/gen/utils';
2
+ import { triggerSchema } from '@webitel/api-services/validations';
1
3
  import deepCopy from 'deep-copy';
2
4
  import { getTriggerService } from '../../../gen-wire';
3
5
  import { getDefaultGetListResponse, getDefaultGetParams } from '../../defaults';
@@ -28,29 +30,13 @@ const doNotConvertKeys = [
28
30
  'variables',
29
31
  ];
30
32
 
31
- const fieldsToSend = [
32
- 'description',
33
- 'enabled',
34
- 'id',
35
- 'name',
36
- 'schema',
37
- 'timeout',
38
- 'timezone',
39
- 'type',
40
- 'variables',
41
- 'expression',
42
- 'event',
43
- 'object',
44
- ];
33
+ /** [Claude] the card schema's fields */
34
+ const fieldsToSend = getShallowFieldsToSendFromZodSchema(triggerSchema);
45
35
 
46
- /**
47
- * The form binds `variables` as a `{ key, value }[]`, the API takes a map.
48
- * `type`, `event` and `object` are bound as lookup objects; only the value
49
- * goes over the wire.
50
- */
36
+ /** The form binds `variables` as a `{ key, value }[]`, the API takes a map. */
51
37
  const preRequestHandler = (item: ApiParams) => {
52
38
  const copy = deepCopy(item);
53
- copy.variables = copy.variables.reduce(
39
+ copy.variables = (copy.variables ?? []).reduce(
54
40
  (variables: ApiParams, variable: ApiParams) => {
55
41
  if (!variable.key) return variables;
56
42
  variables[variable.key] = variable.value;
@@ -58,12 +44,7 @@ const preRequestHandler = (item: ApiParams) => {
58
44
  },
59
45
  {},
60
46
  );
61
- return {
62
- ...copy,
63
- type: copy?.type?.value ?? copy?.type,
64
- event: copy?.event?.value ?? copy?.event,
65
- object: copy?.object?.value ?? copy?.object,
66
- };
47
+ return copy;
67
48
  };
68
49
 
69
50
  const getTriggersList = async (params: ApiParams) => {
@@ -117,11 +98,6 @@ const getTriggersList = async (params: ApiParams) => {
117
98
  }
118
99
  };
119
100
 
120
- /**
121
- * Returns `type`, `event` and `object` as raw enum values. Mapping them onto
122
- * localized lookup entries is the caller's job — the labels are app-side i18n
123
- * keys.
124
- */
125
101
  const getTrigger = async ({ itemId: id }: GetItemParams) => {
126
102
  const defaultObject = {
127
103
  timeout: 0,
@@ -130,12 +106,11 @@ const getTrigger = async ({ itemId: id }: GetItemParams) => {
130
106
 
131
107
  const responseHandler = (response: ApiParams) => {
132
108
  const copy = deepCopy(response);
133
- if (response.variables) {
134
- copy.variables = Object.keys(copy.variables).map((key) => ({
135
- key,
136
- value: copy.variables[key],
137
- }));
138
- }
109
+ // [Claude] a trigger without variables gets the default `{}`, which the form needs as `[]` too
110
+ copy.variables = Object.keys(copy.variables ?? {}).map((key) => ({
111
+ key,
112
+ value: copy.variables[key],
113
+ }));
139
114
  return copy;
140
115
  };
141
116
 
@@ -0,0 +1,19 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import convertDurationWithMilliseconds from '../convertDurationWithMilliseconds';
4
+
5
+ describe('convertDurationWithMilliseconds', () => {
6
+ it('formats hours, minutes, seconds and milliseconds', () => {
7
+ expect(convertDurationWithMilliseconds(3_723_456)).toBe('01:02:03.456');
8
+ });
9
+
10
+ it('pads milliseconds to three digits', () => {
11
+ expect(convertDurationWithMilliseconds(1_005)).toBe('00:00:01.005');
12
+ });
13
+
14
+ it('shows zero for a missing or invalid duration', () => {
15
+ expect(convertDurationWithMilliseconds()).toBe('00:00:00.000');
16
+ expect(convertDurationWithMilliseconds(Number.NaN)).toBe('00:00:00.000');
17
+ expect(convertDurationWithMilliseconds(-10)).toBe('00:00:00.000');
18
+ });
19
+ });
@@ -0,0 +1,18 @@
1
+ import convertDuration from './convertDuration';
2
+
3
+ /**
4
+ * [Claude] A duration given in milliseconds, as `HH:MM:SS.mmm`. A missing or
5
+ * invalid one (e.g. a run that has not stopped yet) shows as zero.
6
+ */
7
+ const convertDurationWithMilliseconds = (duration?: number) => {
8
+ const milliseconds = Number.isFinite(duration)
9
+ ? Math.max(0, Math.floor(duration as number))
10
+ : 0;
11
+
12
+ const time = convertDuration(Math.floor(milliseconds / 1000));
13
+ const rest = `${milliseconds % 1000}`.padStart(3, '0');
14
+
15
+ return `${time}.${rest}`;
16
+ };
17
+
18
+ export default convertDurationWithMilliseconds;
@@ -1,4 +1,5 @@
1
1
  import convertDuration from './convertDuration/convertDuration';
2
+ import convertDurationWithMilliseconds from './convertDuration/convertDurationWithMilliseconds';
2
3
  import { minToSec, secToMin } from './convertTimeUnits/convertTimeUnits';
3
4
  import downloadFile from './downloadFile/downloadFile';
4
5
  import { FileFormat } from './downloadFile/types/fileFormat.types';
@@ -16,6 +17,7 @@ export type {
16
17
  } from './normalizeDatetime/normalizeDatetime';
17
18
  export {
18
19
  convertDuration,
20
+ convertDurationWithMilliseconds,
19
21
  downloadFile,
20
22
  FileFormat,
21
23
  isRelativeDatetimeValue,
@@ -0,0 +1,105 @@
1
+ import { EngineEmailAuthType } from '@webitel/api-services/gen/models';
2
+ import { getDefaultsFromZodSchema } from '@webitel/api-services/gen/utils';
3
+ import { describe, expect, it } from 'vitest';
4
+
5
+ import { emailProfileSchema } from '../emailProfile.validations';
6
+
7
+ const issuePaths = (result: ReturnType<typeof emailProfileSchema.safeParse>) =>
8
+ result.error?.issues.map(({ path }) => path.join('.')) ?? [];
9
+
10
+ const filled = {
11
+ name: 'support',
12
+ mailbox: 'support@example.com',
13
+ imapHost: 'imap.example.com',
14
+ smtpHost: 'smtp.example.com',
15
+ login: 'support@example.com',
16
+ password: 'secret',
17
+ schema: {
18
+ id: '1',
19
+ name: 'flow',
20
+ },
21
+ };
22
+
23
+ describe('emailProfileSchema', () => {
24
+ it('seeds a new profile with plain auth and the usual ports', () => {
25
+ expect(getDefaultsFromZodSchema(emailProfileSchema, {})).toMatchObject({
26
+ enabled: true,
27
+ imapPort: 993,
28
+ smtpPort: 587,
29
+ fetchInterval: 60,
30
+ listen: false,
31
+ authType: EngineEmailAuthType.Plain,
32
+ params: {
33
+ oauth2: {
34
+ clientId: '',
35
+ clientSecret: '',
36
+ redirectUrl: '',
37
+ },
38
+ },
39
+ });
40
+ });
41
+
42
+ it('requires the connection settings, the flow and a password for a new profile', () => {
43
+ const paths = issuePaths(
44
+ emailProfileSchema.safeParse(
45
+ getDefaultsFromZodSchema(emailProfileSchema, {}),
46
+ ),
47
+ );
48
+
49
+ expect(paths).toEqual(
50
+ expect.arrayContaining([
51
+ 'name',
52
+ 'mailbox',
53
+ 'imapHost',
54
+ 'smtpHost',
55
+ 'login',
56
+ 'schema.id',
57
+ 'password',
58
+ ]),
59
+ );
60
+ });
61
+
62
+ it('does not require the password of a saved profile', () => {
63
+ const result = emailProfileSchema.safeParse({
64
+ ...getDefaultsFromZodSchema(emailProfileSchema, {}),
65
+ ...filled,
66
+ id: '1',
67
+ password: '',
68
+ });
69
+
70
+ expect(result.success).toBe(true);
71
+ });
72
+
73
+ it('requires the client settings instead of a password for oauth2', () => {
74
+ const paths = issuePaths(
75
+ emailProfileSchema.safeParse({
76
+ ...getDefaultsFromZodSchema(emailProfileSchema, {}),
77
+ ...filled,
78
+ password: '',
79
+ authType: EngineEmailAuthType.OAuth2,
80
+ }),
81
+ );
82
+
83
+ expect(paths).toEqual([
84
+ 'params.oauth2.clientId',
85
+ 'params.oauth2.clientSecret',
86
+ 'params.oauth2.redirectUrl',
87
+ ]);
88
+ });
89
+
90
+ it('rejects a port out of range and an emptied one', () => {
91
+ const paths = issuePaths(
92
+ emailProfileSchema.safeParse({
93
+ ...getDefaultsFromZodSchema(emailProfileSchema, {}),
94
+ ...filled,
95
+ imapPort: 70000,
96
+ smtpPort: null,
97
+ }),
98
+ );
99
+
100
+ expect(paths).toEqual([
101
+ 'imapPort',
102
+ 'smtpPort',
103
+ ]);
104
+ });
105
+ });
@@ -0,0 +1,113 @@
1
+ import {
2
+ EngineEmailAuthType,
3
+ type EngineEmailProfile,
4
+ } from '@webitel/api-services/gen/models';
5
+ import { get } from 'lodash-es';
6
+ import { z } from 'zod';
7
+
8
+ import { clearableNumberSchema } from '../_shared/clearableNumber.validations';
9
+ import { i18nIssue } from '../_shared/i18nIssue';
10
+ import { isFilled } from '../_shared/isFilled';
11
+ import { filledLookupSchema } from '../_shared/lookup.validations';
12
+ import type { ZodShape } from '../types';
13
+
14
+ /** [Claude] the highest tcp port, the limit of the imap and smtp port fields */
15
+ export const EMAIL_PROFILE_MAX_PORT = 65535;
16
+
17
+ const oauth2Fields = [
18
+ 'clientId',
19
+ 'clientSecret',
20
+ 'redirectUrl',
21
+ ] as const;
22
+
23
+ const oauth2Schema = z
24
+ .object({
25
+ clientId: z.string().optional().default(''),
26
+ clientSecret: z.string().optional().default(''),
27
+ redirectUrl: z.string().optional().default(''),
28
+ })
29
+ .passthrough();
30
+
31
+ /**
32
+ * [Claude] Email profile card schema.
33
+ *
34
+ * Plain auth signs in with a password, oauth2 with the app's client settings.
35
+ * The password is required only when creating: an empty one on update means
36
+ * "keep the current one".
37
+ */
38
+ export const emailProfileSchema = z
39
+ .object<ZodShape<EngineEmailProfile>>({
40
+ id: z.string().optional(),
41
+ name: z.string().min(1).default(''),
42
+ description: z.string().optional().default(''),
43
+ enabled: z.boolean().default(true),
44
+ mailbox: z.string().min(1).default(''),
45
+ imapHost: z.string().min(1).default(''),
46
+ imapPort: clearableNumberSchema.default(993),
47
+ smtpHost: z.string().min(1).default(''),
48
+ smtpPort: clearableNumberSchema.default(587),
49
+ // [Claude] `.prefault`, not `.default`: zod 4's `.default({})` would skip the required check
50
+ schema: filledLookupSchema.prefault({}),
51
+ fetchInterval: clearableNumberSchema.default(60),
52
+ listen: z.boolean().default(false),
53
+ logged: z.boolean().default(false),
54
+ authType: z.string().min(1).default(EngineEmailAuthType.Plain),
55
+ login: z.string().min(1).default(''),
56
+ password: z.string().optional().default(''),
57
+ params: z
58
+ .object({
59
+ oauth2: oauth2Schema.prefault({}),
60
+ })
61
+ .passthrough()
62
+ .prefault({}),
63
+ })
64
+ .passthrough()
65
+ .superRefine((profile, ctx) => {
66
+ const requireField = (path: string) => {
67
+ if (isFilled(get(profile, path))) return;
68
+ ctx.addIssue({
69
+ code: 'custom',
70
+ path: path.split('.'),
71
+ ...i18nIssue('required'),
72
+ });
73
+ };
74
+
75
+ requireField('fetchInterval');
76
+
77
+ for (const path of [
78
+ 'imapPort',
79
+ 'smtpPort',
80
+ ]) {
81
+ requireField(path);
82
+ const port = get(profile, path);
83
+ if (
84
+ typeof port === 'number' &&
85
+ (port < 0 || port > EMAIL_PROFILE_MAX_PORT)
86
+ ) {
87
+ ctx.addIssue({
88
+ code: port < 0 ? 'too_small' : 'too_big',
89
+ origin: 'number',
90
+ ...(port < 0
91
+ ? {
92
+ minimum: 0,
93
+ }
94
+ : {
95
+ maximum: EMAIL_PROFILE_MAX_PORT,
96
+ }),
97
+ inclusive: true,
98
+ input: port,
99
+ path: [
100
+ path,
101
+ ],
102
+ } as Parameters<typeof ctx.addIssue>[0]);
103
+ }
104
+ }
105
+
106
+ if (profile.authType === EngineEmailAuthType.OAuth2) {
107
+ for (const field of oauth2Fields) {
108
+ requireField(`params.oauth2.${field}`);
109
+ }
110
+ } else if (!profile.id) {
111
+ requireField('password');
112
+ }
113
+ });