-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidators.ts
More file actions
1622 lines (1437 loc) · 42.4 KB
/
Copy pathvalidators.ts
File metadata and controls
1622 lines (1437 loc) · 42.4 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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Zod-based validators for Claude Code hooks
*
* CRITICAL: Always use .safeParse() at system boundaries
* Never bypass runtime validation - this prevents silent data corruption
*
* Following established patterns:
* - Two-step type assertion: unknown → validate → assert
* - Custom error types for better debugging
* - Never use 'any' types
*/
import type { z } from 'zod';
import {
hookInputSchemas,
toolInputSchemas,
mcpToolInputSchema,
hooksConfigSchema,
hookHandlerSchema,
matcherGroupSchema,
rawHistoryLineSchema,
rawTranscriptPayloadMetadataSchema,
type HookInputSchema,
type ToolInputSchema,
type PreToolUseInputSchema,
type PostToolUseInputSchema,
type PermissionRequestInputSchema,
type PermissionDeniedInputSchema,
type PostToolUseFailureInputSchema,
type PostToolBatchInputSchema,
type UserPromptSubmitInputSchema,
type UserPromptExpansionInputSchema,
type SessionStartInputSchema,
type SessionEndInputSchema,
type NotificationInputSchema,
type StopInputSchema,
type StopFailureInputSchema,
type SubagentStartInputSchema,
type SubagentStopInputSchema,
type TeammateIdleInputSchema,
type TaskCreatedInputSchema,
type TaskCompletedInputSchema,
type InstructionsLoadedInputSchema,
type ConfigChangeInputSchema,
type CwdChangedInputSchema,
type FileChangedInputSchema,
type WorktreeCreateInputSchema,
type WorktreeRemoveInputSchema,
type PreCompactInputSchema,
type PostCompactInputSchema,
type ElicitationInputSchema,
type ElicitationResultInputSchema,
type HooksConfigSchema,
type HookHandlerSchema,
type MatcherGroupSchema,
type RawHistoryLineSchema,
type RawTranscriptPayloadMetadataSchema,
type TranscriptParseDiagnosticsSchema,
type TranscriptParseIssueSchema,
} from './schemas.js';
type ToolBearingHookInput =
| PreToolUseInputSchema
| PostToolUseInputSchema
| PermissionRequestInputSchema
| PermissionDeniedInputSchema
| PostToolUseFailureInputSchema;
const MCP_TOOL_NAME_PATTERN = /^mcp__[^_]+__[^_]+/;
// =============================================================================
// Custom Error Types
// =============================================================================
/**
* Custom error class for hook validation failures
* Provides structured error information for debugging
*/
export class HookValidationError extends Error {
public readonly code: string;
public readonly context: Record<string, unknown>;
public readonly zodError?: z.ZodError;
constructor(
message: string,
code: string,
context: Record<string, unknown> = {},
zodError?: z.ZodError
) {
super(message);
this.name = 'HookValidationError';
this.code = code;
this.context = context;
if (zodError) {
this.zodError = zodError;
}
// Maintain proper stack trace in V8
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, HookValidationError);
}
}
/**
* Create a detailed error message including Zod validation details
*/
public getDetailedMessage(): string {
let message = `${this.message} (Code: ${this.code})`;
if (this.zodError) {
const issues = this.zodError.issues
.map(issue => ` - ${issue.path.join('.')}: ${issue.message}`)
.join('\n');
message += `\nValidation Issues:\n${issues}`;
}
if (Object.keys(this.context).length > 0) {
message += `\nContext: ${JSON.stringify(this.context, null, 2)}`;
}
return message;
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object';
}
// =============================================================================
// Hook Input Validation
// =============================================================================
/**
* Validate hook input using the two-step type assertion pattern
*
* @param input - Unknown input data from Claude Code
* @returns Validated and typed hook input
* @throws HookValidationError if validation fails
*/
export function validateHookInput(input: unknown): HookInputSchema {
// Step 1: Basic structure validation
if (!isRecord(input)) {
throw new HookValidationError(
'Hook input must be a non-null object',
'INVALID_INPUT_TYPE',
{ inputType: typeof input }
);
}
// Step 2: Extract hook event name
const hookEventName = input['hook_event_name'];
if (
hookEventName === null ||
hookEventName === undefined ||
typeof hookEventName !== 'string'
) {
throw new HookValidationError(
'Missing or invalid hook_event_name',
'MISSING_HOOK_EVENT_NAME',
{ hookEventName, inputKeys: Object.keys(input) }
);
}
// Step 3: Get appropriate schema
const schema = (
hookInputSchemas as Record<
string,
(typeof hookInputSchemas)[keyof typeof hookInputSchemas] | undefined
>
)[hookEventName];
if (schema === undefined) {
throw new HookValidationError(
`Unsupported hook event: ${hookEventName}`,
'UNSUPPORTED_HOOK_EVENT',
{ hookEventName, supportedEvents: Object.keys(hookInputSchemas) }
);
}
// Step 4: Validate using Zod schema
const result = schema.safeParse(input);
if (!result.success) {
throw new HookValidationError(
`Hook input validation failed for ${hookEventName}`,
'HOOK_VALIDATION_FAILED',
{ hookEventName, input },
result.error
);
}
return result.data;
}
/**
* Validate tool input from PreToolUse or PostToolUse hooks
*
* @param hookInput - Validated hook input (PreToolUse or PostToolUse)
* @returns Validated and typed tool input
* @throws HookValidationError if validation fails
*/
export function validateToolInput(
hookInput: ToolBearingHookInput
): ToolInputSchema {
const toolName = hookInput.tool_name;
// Get appropriate schema for the tool
const schema = (
toolInputSchemas as Record<
string,
(typeof toolInputSchemas)[keyof typeof toolInputSchemas] | undefined
>
)[toolName];
if (schema === undefined) {
if (MCP_TOOL_NAME_PATTERN.test(toolName)) {
const result = mcpToolInputSchema.safeParse(hookInput.tool_input);
if (!result.success) {
throw new HookValidationError(
`MCP tool input validation failed for ${toolName}`,
'MCP_TOOL_VALIDATION_FAILED',
{ toolName, toolInput: hookInput.tool_input },
result.error
);
}
return result.data;
}
throw new HookValidationError(
`Unsupported tool: ${toolName}`,
'UNSUPPORTED_TOOL',
{ toolName, supportedTools: Object.keys(toolInputSchemas) }
);
}
// Validate tool input using Zod schema
const result = schema.safeParse(hookInput.tool_input);
if (!result.success) {
throw new HookValidationError(
`Tool input validation failed for ${toolName}`,
'TOOL_VALIDATION_FAILED',
{ toolName, toolInput: hookInput.tool_input },
result.error
);
}
return result.data;
}
// =============================================================================
// Specific Tool Validators (Convenience Functions)
// =============================================================================
/**
* Validate and extract Bash tool input with proper typing
*/
export function validateBashToolInput(
hookInput: ToolBearingHookInput
): z.infer<typeof toolInputSchemas.Bash> {
if (hookInput.tool_name !== 'Bash') {
throw new HookValidationError(
`Expected Bash tool, got ${hookInput.tool_name}`,
'WRONG_TOOL_TYPE',
{ expected: 'Bash', actual: hookInput.tool_name }
);
}
const result = toolInputSchemas.Bash.safeParse(hookInput.tool_input);
if (!result.success) {
throw new HookValidationError(
'Bash tool input validation failed',
'BASH_VALIDATION_FAILED',
{ toolInput: hookInput.tool_input },
result.error
);
}
return result.data;
}
/**
* Validate and extract Write tool input with proper typing
*/
export function validateWriteToolInput(
hookInput: ToolBearingHookInput
): z.infer<typeof toolInputSchemas.Write> {
if (hookInput.tool_name !== 'Write') {
throw new HookValidationError(
`Expected Write tool, got ${hookInput.tool_name}`,
'WRONG_TOOL_TYPE',
{ expected: 'Write', actual: hookInput.tool_name }
);
}
const result = toolInputSchemas.Write.safeParse(hookInput.tool_input);
if (!result.success) {
throw new HookValidationError(
'Write tool input validation failed',
'WRITE_VALIDATION_FAILED',
{ toolInput: hookInput.tool_input },
result.error
);
}
return result.data;
}
/**
* Validate and extract Edit tool input with proper typing
*/
export function validateEditToolInput(
hookInput: ToolBearingHookInput
): z.infer<typeof toolInputSchemas.Edit> {
if (hookInput.tool_name !== 'Edit') {
throw new HookValidationError(
`Expected Edit tool, got ${hookInput.tool_name}`,
'WRONG_TOOL_TYPE',
{ expected: 'Edit', actual: hookInput.tool_name }
);
}
const result = toolInputSchemas.Edit.safeParse(hookInput.tool_input);
if (!result.success) {
throw new HookValidationError(
'Edit tool input validation failed',
'EDIT_VALIDATION_FAILED',
{ toolInput: hookInput.tool_input },
result.error
);
}
return result.data;
}
/**
* Validate and extract Read tool input with proper typing
*/
export function validateReadToolInput(
hookInput: ToolBearingHookInput
): z.infer<typeof toolInputSchemas.Read> {
if (hookInput.tool_name !== 'Read') {
throw new HookValidationError(
`Expected Read tool, got ${hookInput.tool_name}`,
'WRONG_TOOL_TYPE',
{ expected: 'Read', actual: hookInput.tool_name }
);
}
const result = toolInputSchemas.Read.safeParse(hookInput.tool_input);
if (!result.success) {
throw new HookValidationError(
'Read tool input validation failed',
'READ_VALIDATION_FAILED',
{ toolInput: hookInput.tool_input },
result.error
);
}
return result.data;
}
/**
* Validate and extract WebFetch tool input with proper typing
*/
export function validateWebFetchToolInput(
hookInput: ToolBearingHookInput
): z.infer<typeof toolInputSchemas.WebFetch> {
if (hookInput.tool_name !== 'WebFetch') {
throw new HookValidationError(
`Expected WebFetch tool, got ${hookInput.tool_name}`,
'WRONG_TOOL_TYPE',
{ expected: 'WebFetch', actual: hookInput.tool_name }
);
}
const result = toolInputSchemas.WebFetch.safeParse(hookInput.tool_input);
if (!result.success) {
throw new HookValidationError(
'WebFetch tool input validation failed',
'WEBFETCH_VALIDATION_FAILED',
{ toolInput: hookInput.tool_input },
result.error
);
}
return result.data;
}
/**
* Validate and extract WebSearch tool input with proper typing
*/
export function validateWebSearchToolInput(
hookInput: ToolBearingHookInput
): z.infer<typeof toolInputSchemas.WebSearch> {
if (hookInput.tool_name !== 'WebSearch') {
throw new HookValidationError(
`Expected WebSearch tool, got ${hookInput.tool_name}`,
'WRONG_TOOL_TYPE',
{ expected: 'WebSearch', actual: hookInput.tool_name }
);
}
const result = toolInputSchemas.WebSearch.safeParse(hookInput.tool_input);
if (!result.success) {
throw new HookValidationError(
'WebSearch tool input validation failed',
'WEBSEARCH_VALIDATION_FAILED',
{ toolInput: hookInput.tool_input },
result.error
);
}
return result.data;
}
/**
* Validate and extract Glob tool input with proper typing
*/
export function validateGlobToolInput(
hookInput: ToolBearingHookInput
): z.infer<typeof toolInputSchemas.Glob> {
if (hookInput.tool_name !== 'Glob') {
throw new HookValidationError(
`Expected Glob tool, got ${hookInput.tool_name}`,
'WRONG_TOOL_TYPE',
{ expected: 'Glob', actual: hookInput.tool_name }
);
}
const result = toolInputSchemas.Glob.safeParse(hookInput.tool_input);
if (!result.success) {
throw new HookValidationError(
'Glob tool input validation failed',
'GLOB_VALIDATION_FAILED',
{ toolInput: hookInput.tool_input },
result.error
);
}
return result.data;
}
/**
* Validate and extract Grep tool input with proper typing
*/
export function validateGrepToolInput(
hookInput: ToolBearingHookInput
): z.infer<typeof toolInputSchemas.Grep> {
if (hookInput.tool_name !== 'Grep') {
throw new HookValidationError(
`Expected Grep tool, got ${hookInput.tool_name}`,
'WRONG_TOOL_TYPE',
{ expected: 'Grep', actual: hookInput.tool_name }
);
}
const result = toolInputSchemas.Grep.safeParse(hookInput.tool_input);
if (!result.success) {
throw new HookValidationError(
'Grep tool input validation failed',
'GREP_VALIDATION_FAILED',
{ toolInput: hookInput.tool_input },
result.error
);
}
return result.data;
}
/**
* Validate and extract MultiEdit tool input with proper typing
*/
export function validateMultiEditToolInput(
hookInput: ToolBearingHookInput
): z.infer<typeof toolInputSchemas.MultiEdit> {
if (hookInput.tool_name !== 'MultiEdit') {
throw new HookValidationError(
`Expected MultiEdit tool, got ${hookInput.tool_name}`,
'WRONG_TOOL_TYPE',
{ expected: 'MultiEdit', actual: hookInput.tool_name }
);
}
const result = toolInputSchemas.MultiEdit.safeParse(hookInput.tool_input);
if (!result.success) {
throw new HookValidationError(
'MultiEdit tool input validation failed',
'MULTIEDIT_VALIDATION_FAILED',
{ toolInput: hookInput.tool_input },
result.error
);
}
return result.data;
}
/**
* Validate and extract Task tool input with proper typing
*/
export function validateTaskToolInput(
hookInput: ToolBearingHookInput
): z.infer<typeof toolInputSchemas.Task> {
if (hookInput.tool_name !== 'Task') {
throw new HookValidationError(
`Expected Task tool, got ${hookInput.tool_name}`,
'WRONG_TOOL_TYPE',
{ expected: 'Task', actual: hookInput.tool_name }
);
}
const result = toolInputSchemas.Task.safeParse(hookInput.tool_input);
if (!result.success) {
throw new HookValidationError(
'Task tool input validation failed',
'TASK_VALIDATION_FAILED',
{ toolInput: hookInput.tool_input },
result.error
);
}
return result.data;
}
/**
* Validate and extract Agent tool input with proper typing
*/
export function validateAgentToolInput(
hookInput: ToolBearingHookInput
): z.infer<typeof toolInputSchemas.Agent> {
if (hookInput.tool_name !== 'Agent') {
throw new HookValidationError(
`Expected Agent tool, got ${hookInput.tool_name}`,
'WRONG_TOOL_TYPE',
{ expected: 'Agent', actual: hookInput.tool_name }
);
}
const result = toolInputSchemas.Agent.safeParse(hookInput.tool_input);
if (!result.success) {
throw new HookValidationError(
'Agent tool input validation failed',
'AGENT_VALIDATION_FAILED',
{ toolInput: hookInput.tool_input },
result.error
);
}
return result.data;
}
/**
* Validate and extract AskUserQuestion tool input with proper typing
*/
export function validateAskUserQuestionToolInput(
hookInput: ToolBearingHookInput
): z.infer<typeof toolInputSchemas.AskUserQuestion> {
if (hookInput.tool_name !== 'AskUserQuestion') {
throw new HookValidationError(
`Expected AskUserQuestion tool, got ${hookInput.tool_name}`,
'WRONG_TOOL_TYPE',
{ expected: 'AskUserQuestion', actual: hookInput.tool_name }
);
}
const result = toolInputSchemas.AskUserQuestion.safeParse(
hookInput.tool_input
);
if (!result.success) {
throw new HookValidationError(
'AskUserQuestion tool input validation failed',
'ASK_USER_QUESTION_VALIDATION_FAILED',
{ toolInput: hookInput.tool_input },
result.error
);
}
return result.data;
}
/**
* Validate and extract ExitPlanMode tool input with proper typing
*/
export function validateExitPlanModeToolInput(
hookInput: ToolBearingHookInput
): z.infer<typeof toolInputSchemas.ExitPlanMode> {
if (hookInput.tool_name !== 'ExitPlanMode') {
throw new HookValidationError(
`Expected ExitPlanMode tool, got ${hookInput.tool_name}`,
'WRONG_TOOL_TYPE',
{ expected: 'ExitPlanMode', actual: hookInput.tool_name }
);
}
const result = toolInputSchemas.ExitPlanMode.safeParse(hookInput.tool_input);
if (!result.success) {
throw new HookValidationError(
'ExitPlanMode tool input validation failed',
'EXIT_PLAN_MODE_VALIDATION_FAILED',
{ toolInput: hookInput.tool_input },
result.error
);
}
return result.data;
}
/**
* Validate and extract TodoWrite tool input with proper typing
*/
export function validateTodoWriteToolInput(
hookInput: ToolBearingHookInput
): z.infer<typeof toolInputSchemas.TodoWrite> {
if (hookInput.tool_name !== 'TodoWrite') {
throw new HookValidationError(
`Expected TodoWrite tool, got ${hookInput.tool_name}`,
'WRONG_TOOL_TYPE',
{ expected: 'TodoWrite', actual: hookInput.tool_name }
);
}
const result = toolInputSchemas.TodoWrite.safeParse(hookInput.tool_input);
if (!result.success) {
throw new HookValidationError(
'TodoWrite tool input validation failed',
'TODOWRITE_VALIDATION_FAILED',
{ toolInput: hookInput.tool_input },
result.error
);
}
return result.data;
}
/**
* Validate and extract generic MCP tool input with proper typing
*/
export function validateMCPToolInput(
hookInput: ToolBearingHookInput
): z.infer<typeof mcpToolInputSchema> {
if (!MCP_TOOL_NAME_PATTERN.test(hookInput.tool_name)) {
throw new HookValidationError(
`Expected MCP tool name, got ${hookInput.tool_name}`,
'WRONG_TOOL_TYPE',
{ expected: 'mcp__<server>__<tool>', actual: hookInput.tool_name }
);
}
const result = mcpToolInputSchema.safeParse(hookInput.tool_input);
if (!result.success) {
throw new HookValidationError(
'MCP tool input validation failed',
'MCP_TOOL_VALIDATION_FAILED',
{ toolName: hookInput.tool_name, toolInput: hookInput.tool_input },
result.error
);
}
return result.data;
}
// =============================================================================
// Transcript Validators
// =============================================================================
export type SafeTranscriptValidationResult<T> =
| { success: true; data: T }
| { success: false; diagnostics: TranscriptParseDiagnosticsSchema };
function buildTranscriptParseDiagnostics(
summary: string,
error: z.ZodError
): TranscriptParseDiagnosticsSchema {
const issues = flattenTranscriptIssues(error.issues);
return {
summary,
issueCount: issues.length,
issues,
};
}
function flattenTranscriptIssues(
issues: readonly z.ZodIssue[],
parentPath: readonly (string | number)[] = []
): TranscriptParseIssueSchema[] {
const flattened: TranscriptParseIssueSchema[] = [];
for (const issue of issues) {
const combinedPath = [
...parentPath,
...issue.path.map(segment =>
typeof segment === 'number' ? segment : String(segment)
),
];
if (
issue.code === 'invalid_union' &&
'errors' in issue &&
Array.isArray(issue.errors)
) {
if (issue.errors.length === 0) {
// No nested branch errors to recurse into (e.g. a discriminated-union
// drop where the discriminator value matched no member). Fold any
// `discriminator`/`note` the issue carries into the message so the
// diagnostic explains *why* an unknown line type was dropped instead
// of emitting a bare 'Invalid input'.
flattened.push({
code: issue.code,
path: combinedPath,
message: augmentUnionMessage(issue),
});
continue;
}
for (const unionBranchIssues of issue.errors) {
flattened.push(
...flattenTranscriptIssues(unionBranchIssues, combinedPath)
);
}
continue;
}
flattened.push({
code: issue.code,
path: combinedPath,
message: issue.message,
});
}
return flattened;
}
/**
* Read an optional non-empty string property off a Zod issue without using
* `any`. Both `discriminator` and `note` are optional/non-standard on union
* issues, so they are accessed defensively (they may be absent).
*/
function readIssueString(
issue: z.ZodIssue,
key: 'discriminator' | 'note'
): string | undefined {
if (!(key in issue)) return undefined;
const view = issue as unknown;
if (!isRecord(view)) return undefined;
const value = view[key];
return typeof value === 'string' && value.length > 0 ? value : undefined;
}
/**
* Build a self-explanatory message for an `invalid_union` issue that carries no
* nested branch errors, folding in any `discriminator` and/or `note` so the
* diagnostic names the offending value instead of a bare 'Invalid input'.
*/
function augmentUnionMessage(issue: z.ZodIssue): string {
const discriminator = readIssueString(issue, 'discriminator');
const note = readIssueString(issue, 'note');
const annotations: string[] = [];
if (discriminator !== undefined) {
annotations.push(`discriminator: ${discriminator}`);
}
if (note !== undefined) {
annotations.push(note);
}
if (annotations.length === 0) return issue.message;
return `${issue.message} (${annotations.join('; ')})`;
}
export function safeValidateRawTranscriptPayloadMetadata(
input: unknown
): SafeTranscriptValidationResult<RawTranscriptPayloadMetadataSchema> {
const result = rawTranscriptPayloadMetadataSchema.safeParse(input);
if (result.success) {
return { success: true, data: result.data };
}
return {
success: false,
diagnostics: buildTranscriptParseDiagnostics(
'Raw transcript payload metadata validation failed',
result.error
),
};
}
export function validateRawTranscriptPayloadMetadata(
input: unknown
): RawTranscriptPayloadMetadataSchema {
const result = safeValidateRawTranscriptPayloadMetadata(input);
if (!result.success) {
throw new HookValidationError(
'Raw transcript payload metadata validation failed',
'RAW_TRANSCRIPT_PAYLOAD_METADATA_VALIDATION_FAILED',
{ diagnostics: result.diagnostics }
);
}
return result.data;
}
export function safeValidateRawHistoryLine(
input: unknown
): SafeTranscriptValidationResult<RawHistoryLineSchema> {
const result = rawHistoryLineSchema.safeParse(input);
if (result.success) {
return { success: true, data: result.data };
}
return {
success: false,
diagnostics: buildTranscriptParseDiagnostics(
'Raw history line validation failed',
result.error
),
};
}
export function validateRawHistoryLine(input: unknown): RawHistoryLineSchema {
const result = safeValidateRawHistoryLine(input);
if (!result.success) {
throw new HookValidationError(
'Raw history line validation failed',
'RAW_HISTORY_LINE_VALIDATION_FAILED',
{ diagnostics: result.diagnostics }
);
}
return result.data;
}
// =============================================================================
// Utility Functions
// =============================================================================
/**
* Safe validation that returns success/error result instead of throwing
* Useful for hooks that want to handle validation errors gracefully
*/
export function safeValidateHookInput(input: unknown): {
success: boolean;
data?: HookInputSchema;
error?: HookValidationError;
} {
try {
const data = validateHookInput(input);
return { success: true, data };
} catch (error) {
if (error instanceof HookValidationError) {
return { success: false, error };
}
// Convert unexpected errors to HookValidationError
return {
success: false,
error: new HookValidationError(
'Unexpected validation error',
'UNEXPECTED_ERROR',
{ originalError: String(error) }
),
};
}
}
/**
* Validate that input is specifically a PreToolUse hook
* Type guard function for narrowing types
*/
export function isPreToolUseInput(
input: HookInputSchema
): input is PreToolUseInputSchema {
return input.hook_event_name === 'PreToolUse';
}
/**
* Validate that input is specifically a PostToolUse hook
* Type guard function for narrowing types
*/
export function isPostToolUseInput(
input: HookInputSchema
): input is PostToolUseInputSchema {
return input.hook_event_name === 'PostToolUse';
}
/**
* Type guard for PermissionDenied hook input
*/
export function isPermissionDeniedInput(
input: HookInputSchema
): input is PermissionDeniedInputSchema {
return input.hook_event_name === 'PermissionDenied';
}
/**
* Type guard for PostToolBatch hook input
*/
export function isPostToolBatchInput(
input: HookInputSchema
): input is PostToolBatchInputSchema {
return input.hook_event_name === 'PostToolBatch';
}
/**
* Type guard for UserPromptSubmit hook input
*/
export function isUserPromptSubmitInput(
input: HookInputSchema
): input is UserPromptSubmitInputSchema {
return input.hook_event_name === 'UserPromptSubmit';
}
/**
* Type guard for UserPromptExpansion hook input
*/
export function isUserPromptExpansionInput(
input: HookInputSchema
): input is UserPromptExpansionInputSchema {
return input.hook_event_name === 'UserPromptExpansion';
}
/**
* Type guard for SessionStart hook input
*/
export function isSessionStartInput(
input: HookInputSchema
): input is SessionStartInputSchema {
return input.hook_event_name === 'SessionStart';
}
/**
* Type guard for SessionEnd hook input
*/
export function isSessionEndInput(
input: HookInputSchema
): input is SessionEndInputSchema {
return input.hook_event_name === 'SessionEnd';
}
/**
* Type guard for Notification hook input
*/
export function isNotificationInput(
input: HookInputSchema
): input is NotificationInputSchema {
return input.hook_event_name === 'Notification';
}
/**
* Type guard for Stop hook input
*/
export function isStopInput(input: HookInputSchema): input is StopInputSchema {
return input.hook_event_name === 'Stop';
}
/**
* Type guard for StopFailure hook input
*/
export function isStopFailureInput(
input: HookInputSchema
): input is StopFailureInputSchema {
return input.hook_event_name === 'StopFailure';
}
/**
* Type guard for SubagentStop hook input
*/
export function isSubagentStopInput(
input: HookInputSchema
): input is SubagentStopInputSchema {
return input.hook_event_name === 'SubagentStop';
}
/**
* Type guard for PreCompact hook input
*/
export function isPreCompactInput(
input: HookInputSchema
): input is PreCompactInputSchema {
return input.hook_event_name === 'PreCompact';
}
/**
* Type guard for PostCompact hook input
*/
export function isPostCompactInput(
input: HookInputSchema
): input is PostCompactInputSchema {
return input.hook_event_name === 'PostCompact';
}
/**
* Type guard for PermissionRequest hook input
*/
export function isPermissionRequestInput(
input: HookInputSchema
): input is PermissionRequestInputSchema {
return input.hook_event_name === 'PermissionRequest';
}
/**
* Type guard for PostToolUseFailure hook input
*/
export function isPostToolUseFailureInput(