Skip to content

Commit 525fedc

Browse files
authoredNov 8, 2024··
fix(internet): ensure domainWord always returns a valid value in all locales (#3253)
1 parent 69173a3 commit 525fedc

File tree

2 files changed

+38
-4
lines changed

2 files changed

+38
-4
lines changed
 

‎src/modules/internet/index.ts

+26-3
Original file line numberDiff line numberDiff line change
@@ -595,9 +595,32 @@ export class InternetModule extends ModuleBase {
595595
* @since 2.0.1
596596
*/
597597
domainWord(): string {
598-
return this.faker.helpers
599-
.slugify(`${this.faker.word.adjective()}-${this.faker.word.noun()}`)
600-
.toLowerCase();
598+
// Generate an ASCII "word" in the form `noun-adjective`
599+
// For locales with non-ASCII characters, we fall back to lorem words, or a random string
600+
const isValidSlug = (slug: string): boolean => {
601+
return /^[a-z][a-z-]*[a-z]$/i.exec(slug) !== null;
602+
};
603+
604+
const makeValidSlug = (word: string): string => {
605+
const slug1 = this.faker.helpers.slugify(word);
606+
if (isValidSlug(slug1)) {
607+
return slug1;
608+
}
609+
610+
const slug2 = this.faker.helpers.slugify(this.faker.lorem.word());
611+
if (isValidSlug(slug2)) {
612+
return slug2;
613+
}
614+
615+
return this.faker.string.alpha({
616+
casing: 'lower',
617+
length: this.faker.number.int({ min: 4, max: 8 }),
618+
});
619+
};
620+
621+
const word1 = makeValidSlug(this.faker.word.adjective());
622+
const word2 = makeValidSlug(this.faker.word.noun());
623+
return `${word1}-${word2}`.toLowerCase();
601624
}
602625

603626
/**

‎test/modules/internet.spec.ts

+12-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import validator from 'validator';
22
import { describe, expect, it } from 'vitest';
3-
import { allFakers, faker } from '../../src';
3+
import { allFakers, faker, fakerKO } from '../../src';
44
import { FakerError } from '../../src/errors/faker-error';
55
import { IPv4Network } from '../../src/modules/internet';
66
import { seededTests } from '../support/seeded-runs';
@@ -667,6 +667,17 @@ describe('internet', () => {
667667
validator.isFQDN(value, { require_tld: false })
668668
);
669669
});
670+
671+
it('should return a lower-case domain in non-ASCII locales', () => {
672+
const domainWord = fakerKO.internet.domainWord();
673+
674+
expect(domainWord).toBeTruthy();
675+
expect(domainWord).toBeTypeOf('string');
676+
expect(domainWord).toSatisfy(validator.isSlug);
677+
expect(domainWord).toSatisfy((value: string) =>
678+
validator.isFQDN(value, { require_tld: false })
679+
);
680+
});
670681
});
671682

672683
describe('ip()', () => {

0 commit comments

Comments
 (0)
Please sign in to comment.