-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtesters.ts
More file actions
194 lines (163 loc) · 7 KB
/
testers.ts
File metadata and controls
194 lines (163 loc) · 7 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
import type { RendererContext, TesterFunction } from './types'
/**
* Helper to create a tester that returns a rank if predicate is true
*/
export function rankWith(rank: number, predicate: boolean): number {
return predicate ? rank : -1
}
/**
* Combine multiple testers with AND logic
*/
export function and(...testers: TesterFunction[]): TesterFunction {
return (value, context) => {
const ranks = testers.map((t) => t(value, context))
if (ranks.some((r) => r === -1)) return -1
return Math.max(...ranks)
}
}
/**
* Combine multiple testers with OR logic (returns highest passing rank)
*/
export function or(...testers: TesterFunction[]): TesterFunction {
return (value, context) => {
const ranks = testers.map((t) => t(value, context))
const passing = ranks.filter((r) => r !== -1)
return passing.length > 0 ? Math.max(...passing) : -1
}
}
// ============================================
// Primitive Type Testers
// ============================================
export const isNull: TesterFunction = (value) => rankWith(1, value === null)
export const isUndefined: TesterFunction = (value) => rankWith(1, value === undefined)
export const isBoolean: TesterFunction = (value) => rankWith(1, typeof value === 'boolean')
export const isNumber: TesterFunction = (value) =>
rankWith(1, typeof value === 'number' && !isNaN(value))
export const isString: TesterFunction = (value) => rankWith(1, typeof value === 'string')
export const isArray: TesterFunction = (value) => rankWith(1, Array.isArray(value))
export const isObject: TesterFunction = (value) =>
rankWith(1, typeof value === 'object' && value !== null && !Array.isArray(value))
// ============================================
// Smart String Testers
// ============================================
const URL_REGEX = /^https?:\/\/[^\s]+$/i
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
const ISO_DATE_REGEX = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d{3})?(Z|[+-]\d{2}:\d{2})?)?$/
const BASE64_REGEX = /^[A-Za-z0-9+/]+=*$/
const HEX_COLOR_REGEX = /^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$/
const RGB_COLOR_REGEX = /^rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*(,\s*[\d.]+\s*)?\)$/i
const HTML_TAG_REGEX = /<\s*(html|head|body|div|span|p|a|img|table|form|input|button|script|style|link|meta|header|footer|nav|section|article|aside|main|h[1-6]|ul|ol|li|br|hr)\b[^>]*>/i
export const isUrl: TesterFunction = (value) =>
rankWith(10, typeof value === 'string' && URL_REGEX.test(value))
export const isEmail: TesterFunction = (value) =>
rankWith(10, typeof value === 'string' && EMAIL_REGEX.test(value))
export const isIsoDate: TesterFunction = (value) =>
rankWith(10, typeof value === 'string' && ISO_DATE_REGEX.test(value))
export const isBase64: TesterFunction = (value) =>
rankWith(
5,
typeof value === 'string' && value.length > 100 && value.length % 4 === 0 && BASE64_REGEX.test(value)
)
export const isColor: TesterFunction = (value) =>
rankWith(
10,
typeof value === 'string' && (HEX_COLOR_REGEX.test(value) || RGB_COLOR_REGEX.test(value))
)
export const isLongString: TesterFunction = (value) =>
rankWith(2, typeof value === 'string' && value.length > 500)
export const isJsonString: TesterFunction = (value) => {
if (typeof value !== 'string' || value.length < 2) return -1
const trimmed = value.trim()
if ((trimmed.startsWith('{') && trimmed.endsWith('}')) ||
(trimmed.startsWith('[') && trimmed.endsWith(']'))) {
try {
JSON.parse(trimmed)
return 8
} catch {
return -1
}
}
return -1
}
export const isHtmlString: TesterFunction = (value) => {
if (typeof value !== 'string' || value.length < 10) return -1
const trimmed = value.trim()
// Check for common HTML patterns
if (HTML_TAG_REGEX.test(trimmed)) {
// Give higher priority if it looks like a full HTML document
if (trimmed.toLowerCase().includes('<!doctype html') || trimmed.toLowerCase().includes('<html')) {
return 9
}
return 8
}
return -1
}
// ============================================
// Smart Array Testers
// ============================================
export const isEmptyArray: TesterFunction = (value) =>
rankWith(5, Array.isArray(value) && value.length === 0)
export const isHomogeneousObjectArray: TesterFunction = (value) => {
if (!Array.isArray(value) || value.length === 0) return -1
if (!value.every((item) => typeof item === 'object' && item !== null && !Array.isArray(item))) {
return -1
}
// Check if all objects have similar keys
const firstKeys = Object.keys(value[0]).sort().join(',')
const allSameKeys = value.every((item) => Object.keys(item).sort().join(',') === firstKeys)
return rankWith(10, allSameKeys)
}
// ============================================
// Smart Object Testers
// ============================================
export const isEmptyObject: TesterFunction = (value) =>
rankWith(5, isObject(value, {} as RendererContext) > 0 && Object.keys(value as object).length === 0)
/**
* Detects HTTP response shape: { status, headers, body }
*/
export const isHttpResponse: TesterFunction = (value) => {
if (typeof value !== 'object' || value === null || Array.isArray(value)) return -1
const obj = value as Record<string, unknown>
const hasStatus = 'status' in obj && typeof obj.status === 'number'
const hasHeaders = 'headers' in obj && typeof obj.headers === 'object'
const hasBody = 'body' in obj
return rankWith(100, hasStatus && hasHeaders && hasBody)
}
/**
* Detects file object shape: { url, mimeType } or { content, filename }
*/
export const isFileObject: TesterFunction = (value) => {
if (typeof value !== 'object' || value === null || Array.isArray(value)) return -1
const obj = value as Record<string, unknown>
const hasUrlAndMime = 'url' in obj && 'mimeType' in obj
const hasContentAndFilename = 'content' in obj && 'filename' in obj
return rankWith(100, hasUrlAndMime || hasContentAndFilename)
}
/**
* Detects error object shape: { message } or { error }
*/
export const isErrorObject: TesterFunction = (value) => {
if (typeof value !== 'object' || value === null || Array.isArray(value)) return -1
const obj = value as Record<string, unknown>
const hasMessage = 'message' in obj && typeof obj.message === 'string'
const hasStack = 'stack' in obj && typeof obj.stack === 'string'
const hasError = 'error' in obj
return rankWith(50, (hasMessage && hasStack) || (hasMessage && hasError))
}
/**
* Detects Date object
*/
export const isDateObject: TesterFunction = (value) => rankWith(10, value instanceof Date)
/**
* Check if object has specific keys (for custom shape detection)
*/
export function hasShape(requiredKeys: string[], optionalKeys: string[] = []): TesterFunction {
return (value) => {
if (typeof value !== 'object' || value === null || Array.isArray(value)) return -1
const obj = value as Record<string, unknown>
const hasRequired = requiredKeys.every((key) => key in obj)
if (!hasRequired) return -1
const matchedOptional = optionalKeys.filter((key) => key in obj).length
return 50 + matchedOptional * 5
}
}