UNPKG

@datastax/astra-db-ts

Version:
71 lines (70 loc) 2.49 kB
"use strict"; // Copyright Datastax, Inc // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", { value: true }); exports.escapeFieldNames = escapeFieldNames; exports.unescapeFieldPath = unescapeFieldPath; function escapeFieldNames(segments, ...args) { if (arguments.length === 0) { return ''; } if (_isTemplateStringsArray(segments)) { return segments.map((str, i) => str + _escapeSegment(args[i] ?? '')).join(''); } const arr = (typeof segments === 'string' || typeof segments === 'number') ? (args.unshift(segments), args) : (!Array.isArray(segments)) ? [...segments] : segments; return arr.map(_escapeSegment).join('.'); } function _escapeSegment(segment) { if (typeof segment === 'number') { return segment.toString(); } return segment.replace(/([.&])/g, '&$1'); } function _isTemplateStringsArray(strs) { return Array.isArray(strs) && 'raw' in strs; } function unescapeFieldPath(path) { const ret = []; let segment = ''; if (!path) { return []; } if (!path.includes('&') && !path.includes('.')) { return [path]; } if (path.startsWith('.')) { throw new Error(`Invalid field path '${path}'; '.' may not appear at the beginning of the path`); } for (let i = 0, n = path.length; i <= n; i++) { if (path[i] === '.' && i === n - 1) { throw new Error(`Invalid field path '${path}'; '.' may not appear at the end of the path`); } else if (path[i] === '.' || i === n) { if (!segment) { throw new Error(`Invalid field path '${path}'; empty segment found at position ${i}`); } ret.push(segment.slice()); // force rope flattening to reduce memory usage slightly segment = ''; } else if (path[i] === '&') { if (i + 1 === n) { throw new Error(`Invalid escape sequence in field path '${path}'; '&' may not appear at the end of the path`); } const c = path[++i]; if (c === '&' || c === '.') { segment += c; } else { throw new Error(`Invalid escape sequence in field path '${path}' at position ${i - 1}; '&' may not appear alone (must be used as either '&&' or '&.')`); } } else { segment += path[i]; } } return ret; }