summaryrefslogtreecommitdiff
path: root/packages/integrations/cloudflare/src/utils/deduplicatePatterns.ts
blob: b408083ba40289188f5d4e0e1ec961e5e23a0d43 (plain) (blame)
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
/**
 * Remove duplicates and redundant patterns from an `include` or `exclude` list.
 * Otherwise Cloudflare will throw an error on deployment. Plus, it saves more entries.
 * E.g. `['/foo/*', '/foo/*', '/foo/bar'] => ['/foo/*']`
 * @param patterns a list of `include` or `exclude` patterns
 * @returns a deduplicated list of patterns
 */
export function deduplicatePatterns(patterns: string[]) {
	const openPatterns: RegExp[] = [];

	// A value in the set may only occur once; it is unique in the set's collection.
	// ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
	const uniquePatterns = [...new Set(patterns)];
	for (const pattern of uniquePatterns) {
		if (pattern.endsWith('*')) {
			openPatterns.push(new RegExp(`^${pattern.replace(/(\*\/)*\*$/g, '(?=.{2,}).+[^*\n]$')}`));
		}
	}

	return uniquePatterns
		.sort((a, b) => a.length - b.length)
		.filter((pattern) => {
			if (openPatterns.some((p) => p.test(pattern))) return false;

			return true;
		});
}