-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathelementDestinationUrl.js
More file actions
56 lines (49 loc) · 1.61 KB
/
elementDestinationUrl.js
File metadata and controls
56 lines (49 loc) · 1.61 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
/** Matches one Mustache placeholder {{ variable }}. Variable: [^\s}]+ (no spaces, no '}'). Rejects {{}}, {{ }}, {{a b}}. */
const MUSTACHE_PLACEHOLDER = /\{\{\s*[^\s}]+\s*\}\}/;
/** Matches URL scheme at start (e.g. http:, https:). */
const HAS_SCHEME = /^[a-zA-Z][a-zA-Z0-9+.-]*:/;
/**
* True when the string has only valid Mustache placeholders and the literal parts form a valid URL.
* Rejects empty mustache ({{}}, {{ }}), stray { or }, and invalid URL characters.
*
* @param {string} str - Non-empty trimmed string.
* @returns {boolean}
*/
export function hasValidMustacheOnly(str) {
if (!str.includes('{{')) return false;
const g = new RegExp(MUSTACHE_PLACEHOLDER.source, 'g');
const urlSkeleton = str.replace(g, 'a');
if (urlSkeleton.includes('{') || urlSkeleton.includes('}')) return false;
const urlToTest = HAS_SCHEME.test(urlSkeleton) ? urlSkeleton : `http://${urlSkeleton}`;
try {
new URL(urlToTest);
return true;
} catch {
return false;
}
}
/**
* Validates the Element Destination / Conditional Redirect URL field.
* (1) Non-empty string. (2) If it contains {{: only valid Mustache placeholders and URL-valid literals. (3) Else: valid URL.
*
* @param {string} value - URL or Mustache template to validate.
* @returns {boolean}
*/
export function isValidElementDestinationURL(value) {
if (typeof value !== 'string') {
return false;
}
const trimmed = value.trim();
if (trimmed.length === 0) {
return false;
}
if (trimmed.includes('{{')) {
return hasValidMustacheOnly(trimmed);
}
try {
new URL(trimmed);
return true;
} catch {
return false;
}
}