typia
Version:
Superfast runtime validators with only one line
48 lines (47 loc) • 1.63 kB
JavaScript
import { _randomInteger } from "./_randomInteger.mjs";
import { _randomString } from "./_randomString.mjs";
//#region src/internal/_randomFormatHostname.ts
const _randomFormatHostname = (props) => {
if (props?.minLength === void 0 && props?.maxLength === void 0) return `${random(10)}.${random(3)}`;
return _randomHostnameLabels(pickLength(props));
};
const MAX_TOTAL = 253;
const MAX_LABEL = 63;
const pickLength = (props) => {
let low = props.minLength === void 0 ? 1 : props.minLength;
if (low < 1) low = 1;
const high = props.maxLength === void 0 ? Math.min(MAX_TOTAL, low + 14) : Math.min(MAX_TOTAL, props.maxLength);
if (high < low) throw new Error("unable to generate a random hostname satisfying both the format and the length constraints.");
return _randomInteger({
type: "integer",
minimum: low,
maximum: high
});
};
/**
* Builds dot-joined hostname labels totaling exactly `length` characters, each
* label within 63 chars. Shared with the idn-hostname generator, which reserves
* a fixed `.<tld>` suffix and realizes the rest as these leading labels.
*/
const _randomHostnameLabels = (length) => {
const parts = [];
let remaining = length;
while (remaining > 64) {
parts.push(random(MAX_LABEL));
remaining -= 64;
}
if (remaining <= MAX_LABEL) parts.push(random(remaining));
else {
parts.push(random(MAX_LABEL - 1));
parts.push(random(1));
}
return parts.join(".");
};
const random = (length) => _randomString({
type: "string",
minLength: length,
maxLength: length
});
//#endregion
export { _randomFormatHostname, _randomHostnameLabels };
//# sourceMappingURL=_randomFormatHostname.mjs.map