"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: Object.getOwnPropertyDescriptor(all, name).get
    });
}
_export(exports, {
    get FAKE_UUID_PATTERN () {
        return FAKE_UUID_PATTERN;
    },
    get fakeUUID () {
        return fakeUUID;
    },
    get generateId () {
        return generateId;
    },
    get generateIdFromPattern () {
        return generateIdFromPattern;
    },
    get isGeneratedDisplayId () {
        return isGeneratedDisplayId;
    },
    get isGeneratedIdFromPattern () {
        return isGeneratedIdFromPattern;
    }
});
const _constants = require("@tamanu/constants");
const _uuid = require("uuid");
const generators = {
    A: ()=>String.fromCharCode(65 + Math.floor(Math.random() * 26)),
    '0': ()=>Math.floor(Math.random() * 10).toFixed(0)
};
// Max pattern length to avoid ReDoS with PATTERN_TOKEN_REGEX on long input
const MAX_PATTERN_LENGTH = 255;
/*
 * This regex is used to match each token in the pattern.
 * It will match groups of characters wrapped in [] or single A or 0.
 */ const PATTERN_TOKEN_REGEX = /(\[.+?\])(?=\[|[A0]|$)|[A0]/g;
const tokenAsRegex = (token)=>{
    if (token.startsWith('[') && token.endsWith(']')) {
        // Escape special characters in the token to use in a regex
        return token.slice(1, -1).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    }
    if (token === 'A') {
        return '[A-Z]';
    }
    if (token === '0') {
        return '[0-9]';
    }
    throw new Error(`Invalid token: ${token}`);
};
const generateIdFromPattern = (pattern)=>{
    if (pattern.length > MAX_PATTERN_LENGTH) {
        throw new Error(`Pattern length exceeds maximum of ${MAX_PATTERN_LENGTH}`);
    }
    return pattern.replace(PATTERN_TOKEN_REGEX, (token)=>{
        if (token.startsWith('[') && token.endsWith(']')) {
            return token.slice(1, -1);
        }
        return generators[token]?.() ?? '';
    });
};
const generateId = ()=>generateIdFromPattern(_constants.DEFAULT_PATIENT_DISPLAY_ID_PATTERN);
const isGeneratedIdFromPattern = (displayId, pattern)=>{
    if (pattern.length > MAX_PATTERN_LENGTH) return false;
    const patternTokens = pattern.match(PATTERN_TOKEN_REGEX);
    if (!patternTokens) return false;
    const expression = patternTokens.reduce((acc, token)=>acc + tokenAsRegex(token), '');
    const patternRegex = new RegExp(`^${expression}$`);
    return patternRegex.test(displayId);
};
const isGeneratedDisplayId = (displayId)=>isGeneratedIdFromPattern(displayId, _constants.DEFAULT_PATIENT_DISPLAY_ID_PATTERN);
const fakeUUID = ()=>{
    return (0, _uuid.v4)().replace(/(.{8}-.{4})-.{4}-(.+)/, '$1-0000-$2');
};
const FAKE_UUID_PATTERN = '________-____-0000-____-____________';

//# sourceMappingURL=generateId.js.map