-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathvalidation.ts
More file actions
247 lines (234 loc) · 6.96 KB
/
validation.ts
File metadata and controls
247 lines (234 loc) · 6.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
/**
* Input validation utilities
*/
import { z } from 'zod';
import type { ActionInputs, RepoInfo } from '../types/inputs.js';
import { logger } from './logger.js';
import { ERROR, INPUT_FIELD_MAP } from '../config/constants.js';
const createJsonStringArraySchema = (invalidTypeMessage: string, emptyEntryMessage: string) =>
z.preprocess(
value => {
if (value === undefined || value === null) {
return undefined;
}
if (typeof value === 'string') {
const trimmed = value.trim();
if (trimmed.length === 0) {
return undefined;
}
try {
return JSON.parse(trimmed);
} catch {
return value;
}
}
return value;
},
z
.array(
z
.string()
.transform(val => val.trim())
.refine(val => val.length > 0, { message: emptyEntryMessage }),
{ invalid_type_error: invalidTypeMessage }
)
.optional()
);
/**
* Zod schema for action inputs validation
*/
const ActionInputsSchema = z
.object({
augmentSessionAuth: z.string().optional(),
augmentApiToken: z.string().optional(),
augmentApiUrl: z.string().optional(),
githubToken: z.string().optional(),
instruction: z.string().optional(),
instructionFile: z.string().optional(),
model: z.string().optional(),
templateDirectory: z.string().optional(),
templateName: z.string().default('prompt.njk'),
customContext: z.string().optional(),
pullNumber: z.number().int().positive('Pull number must be a positive integer').optional(),
repoName: z
.string()
.regex(/^[^\/]+\/[^\/]+$/, ERROR.INPUT.REPO_FORMAT)
.optional(),
rules: createJsonStringArraySchema(
'rules must be a JSON array of strings',
'Rule file paths cannot be empty'
),
mcpConfigs: createJsonStringArraySchema(
'mcp_configs must be a JSON array of strings',
'MCP config file paths cannot be empty'
),
})
.refine(
data => {
const hasInstruction = data.instruction || data.instructionFile;
const hasTemplate = data.templateDirectory;
return hasInstruction || hasTemplate;
},
{
message: ERROR.INPUT.MISSING_INSTRUCTION_OR_TEMPLATE,
path: ['instruction', 'instructionFile', 'templateDirectory'],
}
)
.refine(
data => {
const hasInstruction = data.instruction || data.instructionFile;
const hasTemplate = data.templateDirectory;
return !(hasInstruction && hasTemplate);
},
{
message: ERROR.INPUT.CONFLICTING_INSTRUCTION_TEMPLATE,
path: ['instruction', 'instructionFile', 'templateDirectory'],
}
)
.refine(data => !(data.instruction && data.instructionFile), {
message: ERROR.INPUT.CONFLICTING_INSTRUCTION_INPUTS,
path: ['instruction', 'instructionFile'],
})
.refine(
data => {
const hasPullNumber = data.pullNumber !== undefined;
const hasRepoName = data.repoName !== undefined;
return hasPullNumber === hasRepoName;
},
{
message: ERROR.INPUT.MISMATCHED_PR_FIELDS,
path: ['pullNumber', 'repoName'],
}
)
.refine(
data => {
if (!data.customContext) return true;
try {
JSON.parse(data.customContext);
return true;
} catch {
return false;
}
},
{
message: ERROR.INPUT.INVALID_CONTEXT_JSON,
path: ['customContext'],
}
)
.refine(
data => {
const hasSessionAuth = data.augmentSessionAuth;
const hasTokenAuth = data.augmentApiToken && data.augmentApiUrl;
return hasSessionAuth || hasTokenAuth;
},
{
message:
'Either augment_session_auth or both augment_api_token and augment_api_url must be provided',
path: ['augmentSessionAuth', 'augmentApiToken', 'augmentApiUrl'],
}
)
.refine(
data => {
const hasSessionAuth = data.augmentSessionAuth;
const hasTokenAuth = data.augmentApiToken || data.augmentApiUrl;
return !(hasSessionAuth && hasTokenAuth);
},
{
message:
'Cannot use both augment_session_auth and augment_api_token/augment_api_url simultaneously',
path: ['augmentSessionAuth', 'augmentApiToken', 'augmentApiUrl'],
}
)
.refine(
data => {
if (!data.augmentSessionAuth) return true;
try {
JSON.parse(data.augmentSessionAuth);
return true;
} catch {
return false;
}
},
{
message: 'augment_session_auth must be valid JSON',
path: ['augmentSessionAuth'],
}
)
.refine(
data => {
if (!data.augmentApiUrl) return true;
try {
new URL(data.augmentApiUrl);
return true;
} catch {
return false;
}
},
{
message: 'Augment API URL must be a valid URL',
path: ['augmentApiUrl'],
}
);
/**
* Validation utilities
*/
export class ValidationUtils {
/**
* Validate action inputs from environment variables
*/
static validateInputs(): ActionInputs {
try {
logger.debug('Reading action inputs from environment variables');
// Build inputs object from field map
const inputs = Object.fromEntries(
Object.entries(INPUT_FIELD_MAP)
.map(([key, fieldDef]) => {
const value = process.env[fieldDef.envVar];
// Skip optional fields if no value set
if (!fieldDef.required && !value) {
return null;
}
// Apply transformation if defined
const transformedValue =
fieldDef.transform && value ? fieldDef.transform(value) : value;
return [key, transformedValue];
})
.filter((entry): entry is [string, any] => entry !== null)
);
logger.debug('Validating action inputs');
const validated = ActionInputsSchema.parse(inputs) as ActionInputs;
logger.debug('Action inputs validated successfully');
return validated;
} catch (error) {
if (error instanceof z.ZodError) {
const errorMessages = error.errors.map(err => `${err.path.join('.')}: ${err.message}`);
const message = `${ERROR.INPUT.INVALID}: ${errorMessages.join(', ')}`;
logger.error(message, error);
throw new Error(message);
}
logger.error('Unexpected validation error', error);
throw error;
}
}
/**
* Parse repository name into owner and repo
*/
static parseRepoName(repoName: string): RepoInfo {
logger.debug('Parsing repository name', { repoName });
const parts = repoName.split('/');
if (parts.length !== 2) {
const message = `${ERROR.INPUT.REPO_FORMAT}: ${repoName}`;
logger.error(message);
throw new Error(message);
}
const [owner, repo] = parts;
if (!owner || !repo) {
const message = `${ERROR.INPUT.REPO_FORMAT}: ${repoName}. Owner and repo cannot be empty`;
logger.error(message);
throw new Error(message);
}
const result = { owner, repo };
logger.debug('Repository name parsed successfully', result);
return result;
}
}