%PDF- %PDF-
| Direktori : /home2/rezakur1/api.rezakurnia.com/zh-router/node_modules/sql-escaper/lib/ |
| Current File : //home2/rezakur1/api.rezakurnia.com/zh-router/node_modules/sql-escaper/lib/index.mjs |
import { Buffer } from "buffer";
const EXPAND_SYMBOL = /* @__PURE__ */ Symbol.for("sql-escaper.expand");
const MAY_OPEN_QUOTE_OR_COMMENT = new Uint8Array(128);
const SET_CLAUSE_TERMINATORS_BY_FIRST = {};
const SET_CLAUSE_TERMINATORS = [
"where",
"order",
"group",
"having",
"limit",
"union",
"returning",
"into",
"for",
"lock",
"offset",
"window",
"procedure",
"on"
];
const regex = {
backtick: /`/g,
backslash: /\\/g,
dot: /\./g,
timezone: /([+\-\s])(\d\d):?(\d\d)?/,
escapeChars: /[\0\b\t\n\r\x1a"'\\]/g
};
const sqlModeFlag = {
ansiQuotes: 1,
noBackslashEscapes: 2
};
const sqlModeByFlags = [
void 0,
Object.freeze({ ansiQuotes: true, noBackslashEscapes: false }),
Object.freeze({ ansiQuotes: false, noBackslashEscapes: true }),
Object.freeze({ ansiQuotes: true, noBackslashEscapes: true })
];
const charCode = {
singleQuote: 39,
doubleQuote: 34,
backtick: 96,
backslash: 92,
hash: 35,
dash: 45,
slash: 47,
asterisk: 42,
exclamation: 33,
plus: 43,
questionMark: 63,
comma: 44,
openParen: 40,
closeParen: 41,
semicolon: 59,
newline: 10,
space: 32,
tab: 9,
carriageReturn: 13
};
const NOT_SEARCHED = -2;
const hasOwnProperty = Object.prototype.hasOwnProperty;
MAY_OPEN_QUOTE_OR_COMMENT[charCode.singleQuote] = 1;
MAY_OPEN_QUOTE_OR_COMMENT[charCode.doubleQuote] = 1;
MAY_OPEN_QUOTE_OR_COMMENT[charCode.backtick] = 1;
MAY_OPEN_QUOTE_OR_COMMENT[charCode.hash] = 1;
MAY_OPEN_QUOTE_OR_COMMENT[charCode.dash] = 1;
MAY_OPEN_QUOTE_OR_COMMENT[charCode.slash] = 1;
for (const word of SET_CLAUSE_TERMINATORS) {
const first = word.charCodeAt(0);
const bucket = SET_CLAUSE_TERMINATORS_BY_FIRST[first];
if (bucket) bucket.push(word);
else SET_CLAUSE_TERMINATORS_BY_FIRST[first] = [word];
}
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Set) && !(value instanceof Map);
const isWordChar = (code) => code >= 65 && code <= 90 || code >= 97 && code <= 122 || code >= 48 && code <= 57 || code === 95;
const isWhitespace = (code) => code === charCode.space || code === charCode.tab || code === charCode.newline || code === charCode.carriageReturn;
const toLower = (code) => code | 32;
const matchesWord = (sql, position, word, length) => {
const wordLength = word.length;
for (let offset = 0; offset < wordLength; offset++)
if (toLower(sql.charCodeAt(position + offset)) !== word.charCodeAt(offset))
return false;
return (position === 0 || !isWordChar(sql.charCodeAt(position - 1))) && (position + wordLength >= length || !isWordChar(sql.charCodeAt(position + wordLength)));
};
const skipLineComment = (sql, start) => {
const lineBreak = sql.indexOf("\n", start);
return lineBreak === -1 ? sql.length : lineBreak + 1;
};
const skipQuotedWithoutEscapes = (sql, position, quote) => {
const length = sql.length;
for (let cursor = position + 1; cursor < length; cursor++) {
if (sql.charCodeAt(cursor) !== quote) continue;
if (sql.charCodeAt(cursor + 1) !== quote) return cursor + 1;
cursor++;
}
return length;
};
const followsOddBackslashRun = (sql, position) => {
let runStart = position;
while (sql.charCodeAt(runStart - 1) === charCode.backslash) runStart--;
return (position - runStart & 1) === 1;
};
const rejectAmbiguousQuote = (position) => {
throw new TypeError(
`argument sql has a quote after an odd number of backslashes at position ${position}, which the SQL modes read differently: pass the string that holds it as a value instead`
);
};
const skipUnambiguousString = (sql, position, quote) => {
const length = sql.length;
for (let cursor = position + 1; cursor < length; cursor++) {
if (sql.charCodeAt(cursor) !== quote) continue;
if (followsOddBackslashRun(sql, cursor)) rejectAmbiguousQuote(cursor);
if (sql.charCodeAt(cursor + 1) !== quote) return cursor + 1;
cursor++;
}
return length;
};
const skipSqlContext = (sql, position, modeFlags) => {
const currentChar = sql.charCodeAt(position);
if (currentChar === charCode.singleQuote || currentChar === charCode.doubleQuote) {
if ((modeFlags & sqlModeFlag.ansiQuotes) !== 0 && currentChar === charCode.doubleQuote)
return skipQuotedWithoutEscapes(sql, position, currentChar);
if ((modeFlags & sqlModeFlag.noBackslashEscapes) !== 0)
return skipUnambiguousString(sql, position, currentChar);
const length = sql.length;
for (let cursor = position + 1; cursor < length; cursor++) {
const code = sql.charCodeAt(cursor);
if (code === charCode.backslash) cursor++;
else if (code === currentChar) return cursor + 1;
}
return length;
}
if (currentChar === charCode.backtick)
return skipQuotedWithoutEscapes(sql, position, currentChar);
if (currentChar === charCode.hash) return skipLineComment(sql, position + 1);
const nextChar = sql.charCodeAt(position + 1);
if (currentChar === charCode.dash && nextChar === charCode.dash) {
const afterDash = sql.charCodeAt(position + 2);
if (Number.isNaN(afterDash) || afterDash <= charCode.space)
return skipLineComment(sql, position + 2);
return -1;
}
if (currentChar === charCode.slash && nextChar === charCode.asterisk) {
const markerChar = sql.charCodeAt(position + 2);
if (markerChar === charCode.exclamation || markerChar === charCode.plus)
return -1;
const commentEnd = sql.indexOf("*/", position + 2);
return commentEnd === -1 ? sql.length : commentEnd + 2;
}
return -1;
};
const findNextPlaceholder = (sql, start, modeFlags) => {
const sqlLength = sql.length;
for (let position = start; position < sqlLength; position++) {
const code = sql.charCodeAt(position);
if (code === charCode.questionMark) return position;
if (code < 128 && MAY_OPEN_QUOTE_OR_COMMENT[code]) {
const contextEnd = skipSqlContext(sql, position, modeFlags);
if (contextEnd !== -1) position = contextEnd - 1;
}
}
return -1;
};
const rejectAmbiguousStringsAfter = (sql, placeholderPosition, modeFlags) => {
let position = placeholderPosition;
while (position !== -1)
position = findNextPlaceholder(sql, position + 1, modeFlags);
};
const isInSetAssignmentList = (sql, setEnd, placeholderPosition, modeFlags) => {
const length = sql.length;
let depth = 0;
let sawContent = false;
let lastWasComma = false;
for (let position = setEnd; position < placeholderPosition; ) {
const code = sql.charCodeAt(position);
if (code < 128 && MAY_OPEN_QUOTE_OR_COMMENT[code]) {
const contextEnd = skipSqlContext(sql, position, modeFlags);
if (contextEnd !== -1) {
position = contextEnd;
sawContent = true;
lastWasComma = false;
continue;
}
}
if (isWhitespace(code)) {
position++;
continue;
}
if (code === charCode.openParen) {
depth++;
sawContent = true;
lastWasComma = false;
position++;
continue;
}
if (code === charCode.closeParen) {
if (--depth < 0) return false;
sawContent = true;
lastWasComma = false;
position++;
continue;
}
if (isWordChar(code)) {
if (depth === 0 && !(code >= 48 && code <= 57)) {
const bucket = SET_CLAUSE_TERMINATORS_BY_FIRST[toLower(code)];
if (bucket) {
for (const terminator of bucket)
if (matchesWord(sql, position, terminator, length)) return false;
}
}
do {
position++;
} while (position < placeholderPosition && isWordChar(sql.charCodeAt(position)));
sawContent = true;
lastWasComma = false;
continue;
}
if (depth === 0) {
if (code === charCode.semicolon) return false;
if (code === charCode.comma) {
lastWasComma = true;
sawContent = true;
position++;
continue;
}
}
sawContent = true;
lastWasComma = false;
position++;
}
return depth === 0 && (!sawContent || lastWasComma);
};
const findSetKeyword = (sql, startFrom, modeFlags) => {
const length = sql.length;
for (let position = startFrom; position < length; position++) {
const code = sql.charCodeAt(position);
if (code < 128 && MAY_OPEN_QUOTE_OR_COMMENT[code]) {
const contextEnd = skipSqlContext(sql, position, modeFlags);
if (contextEnd !== -1) {
position = contextEnd - 1;
continue;
}
}
const lower = toLower(code);
if (lower === 115 && matchesWord(sql, position, "set", length))
return position + 3;
if (lower === 107 && matchesWord(sql, position, "key", length)) {
let cursor = position + 3;
while (cursor < length && isWhitespace(sql.charCodeAt(cursor))) cursor++;
if (matchesWord(sql, cursor, "update", length)) return cursor + 6;
}
}
return -1;
};
const createSetAssignmentTest = (sql, modeFlags) => {
let setIndex = NOT_SEARCHED;
let nextSetIndex = -1;
return (chunkIndex, placeholderPosition) => {
let previous = placeholderPosition - 1;
while (previous >= chunkIndex && isWhitespace(sql.charCodeAt(previous)))
previous--;
const previousChar = previous >= chunkIndex ? toLower(sql.charCodeAt(previous)) : 0;
const followsLetterOrComma = previousChar >= 97 && previousChar <= 122 || previousChar === charCode.comma;
if (!followsLetterOrComma) return false;
if (setIndex === NOT_SEARCHED) {
setIndex = findSetKeyword(sql, 0, modeFlags);
nextSetIndex = setIndex === -1 ? -1 : findSetKeyword(sql, setIndex, modeFlags);
}
while (nextSetIndex !== -1 && nextSetIndex <= placeholderPosition) {
setIndex = nextSetIndex;
nextSetIndex = findSetKeyword(sql, nextSetIndex, modeFlags);
}
return setIndex !== -1 && setIndex <= placeholderPosition && isInSetAssignmentList(sql, setIndex, placeholderPosition, modeFlags);
};
};
const isDate = (value) => Object.prototype.toString.call(value) === "[object Date]";
const isTemporal = (value) => Object.prototype.toString.call(value).startsWith("[object Temporal.");
const hasSqlString = (value) => typeof value === "object" && value !== null && "toSqlString" in value && typeof value.toSqlString === "function";
const isOwn = (value, key) => hasOwnProperty.call(value, key);
const isExpandable = (value) => !(Array.isArray(value) || value instanceof Uint8Array || value instanceof Date || hasSqlString(value) || isDate(value)) && (isRecord(value) || value instanceof Map);
const isMarkable = (value) => typeof value === "object" && value !== null && isExpandable(value) && !hasOwnProperty.call(value, EXPAND_SYMBOL);
const isMark = (value) => isOwn(value, EXPAND_SYMBOL) && value[EXPAND_SYMBOL] === true && isOwn(value, "value") && isMarkable(value.value);
const isColumnList = (columns) => {
if (!Array.isArray(columns)) return false;
const length = columns.length;
for (let index = 0; index < length; index++)
if (typeof columns[index] !== "string") return false;
return true;
};
const pickColumns = (value, columns) => {
const picked = /* @__PURE__ */ new Map();
if (value instanceof Map) {
for (const column of columns)
if (value.has(column)) picked.set(column, value.get(column));
return picked;
}
for (const column of columns)
if (hasOwnProperty.call(value, column)) picked.set(column, value[column]);
return picked;
};
const escapeString = (value) => {
const escapeChars = regex.escapeChars;
escapeChars.lastIndex = 0;
const first = escapeChars.exec(value);
if (first === null) return `'${value}'`;
const length = value.length;
let result = "'" + value.slice(0, first.index);
let chunkStart = first.index;
for (let index = first.index; index < length; index++) {
let escaped;
switch (value.charCodeAt(index)) {
case 0:
escaped = "\\0";
break;
case 8:
escaped = "\\b";
break;
case 9:
escaped = "\\t";
break;
case 10:
escaped = "\\n";
break;
case 13:
escaped = "\\r";
break;
case 26:
escaped = "\\Z";
break;
case 34:
escaped = '\\"';
break;
case 39:
escaped = "\\'";
break;
case 92:
escaped = "\\\\";
break;
default:
continue;
}
result += value.slice(chunkStart, index) + escaped;
chunkStart = index + 1;
}
return result + value.slice(chunkStart) + "'";
};
const quoteByDoubling = (value) => {
let quotePosition = value.indexOf("'");
if (quotePosition === -1) return `'${value}'`;
let result = "'";
let chunkStart = 0;
while (quotePosition !== -1) {
result += value.slice(chunkStart, quotePosition + 1) + "'";
chunkStart = quotePosition + 1;
quotePosition = value.indexOf("'", chunkStart);
}
return result + value.slice(chunkStart) + "'";
};
const quoteString = (value) => {
const literal = quoteByDoubling(value);
if (!value.includes("\\")) return literal;
return `REPLACE(${literal.replace(regex.backslash, "\\%")}, '\\%', LEFT('\\%', 1))`;
};
const readNoBackslashEscapes = (sqlMode) => {
if (!hasOwnProperty.call(sqlMode, "noBackslashEscapes")) return false;
const noBackslashEscapes = sqlMode.noBackslashEscapes;
if (noBackslashEscapes === void 0) return false;
if (typeof noBackslashEscapes !== "boolean")
throw new TypeError(
`sqlMode.noBackslashEscapes must be a boolean, received ${noBackslashEscapes === null ? "null" : typeof noBackslashEscapes}`
);
return noBackslashEscapes;
};
const toModeFlags = (sqlMode) => {
if (sqlMode === void 0 || sqlMode === null) return 0;
return (sqlMode.ansiQuotes === true ? sqlModeFlag.ansiQuotes : 0) | (readNoBackslashEscapes(sqlMode) ? sqlModeFlag.noBackslashEscapes : 0);
};
const escapeText = (value, modeFlags) => (modeFlags & sqlModeFlag.noBackslashEscapes) === 0 ? escapeString(value) : quoteString(value);
const pad2 = (value) => value < 10 ? "0" + value : "" + value;
const pad3 = (value) => value < 10 ? "00" + value : value < 100 ? "0" + value : "" + value;
const pad4 = (value) => value < 10 ? "000" + value : value < 100 ? "00" + value : value < 1e3 ? "0" + value : "" + value;
const convertTimezone = (timezone) => {
if (timezone === "Z") return 0;
const timezoneMatch = timezone.match(regex.timezone);
if (timezoneMatch)
return (timezoneMatch[1] === "-" ? -1 : 1) * (Number.parseInt(timezoneMatch[2], 10) + (timezoneMatch[3] ? Number.parseInt(timezoneMatch[3], 10) : 0) / 60) * 60;
return false;
};
const writeDate = (date, timezone, modeFlags) => {
if (Number.isNaN(date.getTime())) return "NULL";
let year;
let month;
let day;
let hour;
let minute;
let second;
let millisecond;
if (timezone === "local") {
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
hour = date.getHours();
minute = date.getMinutes();
second = date.getSeconds();
millisecond = date.getMilliseconds();
} else {
const timezoneOffsetMinutes = convertTimezone(timezone);
let time = date.getTime();
if (timezoneOffsetMinutes !== false && timezoneOffsetMinutes !== 0)
time += timezoneOffsetMinutes * 6e4;
const adjustedDate = new Date(time);
year = adjustedDate.getUTCFullYear();
month = adjustedDate.getUTCMonth() + 1;
day = adjustedDate.getUTCDate();
hour = adjustedDate.getUTCHours();
minute = adjustedDate.getUTCMinutes();
second = adjustedDate.getUTCSeconds();
millisecond = adjustedDate.getUTCMilliseconds();
}
return escapeText(
pad4(year) + "-" + pad2(month) + "-" + pad2(day) + " " + pad2(hour) + ":" + pad2(minute) + ":" + pad2(second) + "." + pad3(millisecond),
modeFlags
);
};
const dateToString = (date, timezone, sqlMode) => writeDate(date, timezone, toModeFlags(sqlMode));
const writeTemporal = (value, timezone, modeFlags) => {
if (typeof value.epochMilliseconds === "number")
return writeDate(
new Date(value.epochMilliseconds),
timezone || "local",
modeFlags
);
if (value[Symbol.toStringTag] === "Temporal.PlainDateTime")
return escapeText(value.toString().replace("T", " "), modeFlags);
return escapeText(value.toString(), modeFlags);
};
const temporalToString = (value, timezone, sqlMode) => writeTemporal(value, timezone, toModeFlags(sqlMode));
const escapeId = (value, forbidQualified) => {
if (Array.isArray(value)) {
const length = value.length;
let sql = "";
for (let index = 0; index < length; index++) {
if (index > 0) sql += ", ";
sql += escapeId(value[index], forbidQualified);
}
return sql;
}
const identifier = String(value);
if (identifier.indexOf("`") === -1) {
if (forbidQualified || identifier.indexOf(".") === -1 || identifier.indexOf("->") !== -1)
return `\`${identifier}\``;
return `\`${identifier.replace(regex.dot, "`.`")}\``;
}
const quoted = identifier.replace(regex.backtick, "``");
if (forbidQualified || identifier.indexOf("->") !== -1)
return `\`${quoted}\``;
return `\`${quoted.replace(regex.dot, "`.`")}\``;
};
const writeAssignments = (object, timezone, modeFlags) => {
let sql = "";
if (object instanceof Map) {
for (const [key, value] of object) {
if (typeof value === "function") continue;
if (sql.length > 0) sql += ", ";
sql += escapeId(String(key));
sql += " = ";
sql += escapeValue(value, true, timezone, false, modeFlags);
}
return sql;
}
for (const key in object) {
if (!hasOwnProperty.call(object, key)) continue;
const value = object[key];
if (typeof value === "function") continue;
if (sql.length > 0) sql += ", ";
sql += escapeId(key);
sql += " = ";
sql += escapeValue(value, true, timezone, false, modeFlags);
}
return sql;
};
const objectToValues = (object, timezone, sqlMode) => writeAssignments(object, timezone, toModeFlags(sqlMode));
const bufferToString = (buffer) => `X${escapeString(buffer.toString("hex"))}`;
const writeList = (array, timezone, modeFlags) => {
const length = array.length;
let sql = "";
for (let index = 0; index < length; index++) {
if (index > 0) sql += ", ";
const value = array[index];
if (Array.isArray(value))
sql += `(${writeList(value, timezone, modeFlags)})`;
else if (value instanceof Set)
sql += `(${writeList(Array.from(value), timezone, modeFlags)})`;
else sql += escapeValue(value, true, timezone, false, modeFlags);
}
return sql;
};
const arrayToList = (array, timezone, sqlMode) => writeList(array, timezone, toModeFlags(sqlMode));
const escapeValue = (value, stringifyObjects, timezone, topLevel, modeFlags) => {
if (value === void 0 || value === null) return "NULL";
switch (typeof value) {
case "boolean":
return value ? "true" : "false";
case "number":
case "bigint":
return value + "";
case "object": {
if (isDate(value))
return writeDate(value, timezone || "local", modeFlags);
if (isTemporal(value)) return writeTemporal(value, timezone, modeFlags);
if (Array.isArray(value)) return writeList(value, timezone, modeFlags);
if (value instanceof Set)
return writeList(Array.from(value), timezone, modeFlags);
if (Buffer.isBuffer(value)) return bufferToString(value);
if (value instanceof Uint8Array)
return bufferToString(Buffer.from(value));
if (hasSqlString(value))
return String(value.toSqlString(sqlModeByFlags[modeFlags]));
if (topLevel && isMark(value))
return writeAssignments(value.value, timezone, modeFlags);
if (!(stringifyObjects === void 0 || stringifyObjects === null))
return escapeText(String(value), modeFlags);
if (isRecord(value) || value instanceof Map)
return writeAssignments(value, timezone, modeFlags);
return escapeText(String(value), modeFlags);
}
case "string":
return escapeText(value, modeFlags);
default:
return escapeText(String(value), modeFlags);
}
};
const escape = (value, stringifyObjects, timezone, sqlMode) => escapeValue(value, stringifyObjects, timezone, true, toModeFlags(sqlMode));
const format = (sql, values, stringifyObjects, timezone, sqlMode) => {
if (values === void 0 || values === null) return sql;
const modeFlags = toModeFlags(sqlMode);
const valuesArray = Array.isArray(values) ? values : [values];
const length = valuesArray.length;
let isSetAssignment;
let result = "";
let chunkIndex = 0;
let valuesIndex = 0;
let placeholderPosition = findNextPlaceholder(sql, 0, modeFlags);
while (valuesIndex < length && placeholderPosition !== -1) {
let placeholderEnd = placeholderPosition + 1;
while (sql.charCodeAt(placeholderEnd) === charCode.questionMark)
placeholderEnd++;
const placeholderLength = placeholderEnd - placeholderPosition;
if (placeholderLength > 2) {
placeholderPosition = findNextPlaceholder(sql, placeholderEnd, modeFlags);
continue;
}
const currentValue = valuesArray[valuesIndex];
let escapedValue;
if (placeholderLength === 2) escapedValue = escapeId(currentValue);
else if (typeof currentValue === "number" || typeof currentValue === "bigint")
escapedValue = `${currentValue}`;
else if (typeof currentValue !== "object" || currentValue === null || stringifyObjects)
escapedValue = escapeValue(
currentValue,
stringifyObjects,
timezone,
true,
modeFlags
);
else if (!isExpandable(currentValue))
escapedValue = escapeValue(
currentValue,
true,
timezone,
false,
modeFlags
);
else if (isMark(currentValue))
escapedValue = writeAssignments(currentValue.value, timezone, modeFlags);
else {
if (isSetAssignment === void 0)
isSetAssignment = createSetAssignmentTest(sql, modeFlags);
escapedValue = isSetAssignment(chunkIndex, placeholderPosition) ? writeAssignments(currentValue, timezone, modeFlags) : escapeValue(currentValue, true, timezone, false, modeFlags);
}
result += sql.slice(chunkIndex, placeholderPosition);
result += escapedValue;
chunkIndex = placeholderEnd;
valuesIndex++;
placeholderPosition = findNextPlaceholder(sql, placeholderEnd, modeFlags);
}
if ((modeFlags & sqlModeFlag.noBackslashEscapes) !== 0)
rejectAmbiguousStringsAfter(sql, placeholderPosition, modeFlags);
if (chunkIndex === 0) return sql;
if (chunkIndex < sql.length) return result + sql.slice(chunkIndex);
return result;
};
const raw = (sql) => {
if (typeof sql !== "string")
throw new TypeError("argument sql must be a string");
return {
toSqlString: () => sql
};
};
const expand = (value, columns) => {
if (!isMarkable(value))
throw new TypeError("argument value must be an object or a Map");
if (columns === void 0) return { [EXPAND_SYMBOL]: true, value };
if (!isColumnList(columns))
throw new TypeError("argument columns must be an array of strings");
return { [EXPAND_SYMBOL]: true, value: pickColumns(value, columns) };
};
export {
EXPAND_SYMBOL,
arrayToList,
bufferToString,
dateToString,
escape,
escapeId,
expand,
format,
objectToValues,
raw,
temporalToString
};