|
| 1 | +'use strict' |
| 2 | + |
| 3 | +module.exports = compile |
| 4 | + |
| 5 | +const identifierRegex = /^[@a-zA-Z_$][\w$]*$/ |
| 6 | + |
| 7 | +// The following identifiers have purposefully not been included in this list: |
| 8 | +// - The reserved words `this` and `super` as they can have valid use cases as `ref` values |
| 9 | +// - The literals `undefined` and `Infinity` as they can be useful as `ref` values, especially to check if a |
| 10 | +// variable is `undefined`. |
| 11 | +// - The following future reserved words in older standards, as they can now be used safely: |
| 12 | +// `abstract`, `boolean`, `byte`, `char`, `double`, `final`, `float`, `goto`, `int`, `long`, `native`, `short`, |
| 13 | +// `synchronized`, `throws`, `transient`, `volatile`. |
| 14 | +const reservedWords = new Set([ |
| 15 | + // Reserved words |
| 16 | + 'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do', 'else', 'export', |
| 17 | + 'extends', 'false', 'finally', 'for', 'function', 'if', 'import', 'in', 'instanceof', 'new', 'null', 'return', |
| 18 | + 'switch', 'throw', 'true', 'try', 'typeof', 'var', 'void', 'while', 'with', |
| 19 | + |
| 20 | + // Reserved in strict mode |
| 21 | + 'let', 'static', 'yield', |
| 22 | + |
| 23 | + // Reserved in module code or async function bodies: |
| 24 | + 'await', |
| 25 | + |
| 26 | + // Future reserved words |
| 27 | + 'enum', |
| 28 | + |
| 29 | + // Future reserved words in strict mode |
| 30 | + 'implements', 'interface', 'package', 'private', 'protected', 'public', |
| 31 | + |
| 32 | + // Litterals |
| 33 | + 'NaN' |
| 34 | +]) |
| 35 | + |
| 36 | +// TODO: Consider storing some of these functions on `process` so they can be reused across probes |
| 37 | +function compile (node) { |
| 38 | + if (node === null || typeof node === 'number' || typeof node === 'boolean' || typeof node === 'string') { |
| 39 | + return JSON.stringify(node) |
| 40 | + } |
| 41 | + |
| 42 | + const [type, value] = Object.entries(node)[0] |
| 43 | + |
| 44 | + if (type === 'not') { |
| 45 | + return `!(${compile(value)})` |
| 46 | + } else if (type === 'len' || type === 'count') { |
| 47 | + return getSize(compile(value)) |
| 48 | + } else if (type === 'isEmpty') { |
| 49 | + return `${getSize(compile(value))} === 0` |
| 50 | + } else if (type === 'isDefined') { |
| 51 | + return `(() => { |
| 52 | + try { |
| 53 | + ${value} |
| 54 | + return true |
| 55 | + } catch { |
| 56 | + return false |
| 57 | + } |
| 58 | + })()` |
| 59 | + } else if (type === 'instanceof') { |
| 60 | + return `Function.prototype[Symbol.hasInstance].call(${value[1]}, ${compile(value[0])})` |
| 61 | + } else if (type === 'ref') { |
| 62 | + if (value === '@it') { |
| 63 | + return '$dd_it' |
| 64 | + } else if (value === '@key') { |
| 65 | + return '$dd_key' |
| 66 | + } else if (value === '@value') { |
| 67 | + return '$dd_value' |
| 68 | + } else { |
| 69 | + return assertIdentifier(value) |
| 70 | + } |
| 71 | + } else if (Array.isArray(value)) { |
| 72 | + const args = value.map(compile) |
| 73 | + switch (type) { |
| 74 | + case 'eq': return `(${args[0]}) === (${args[1]})` |
| 75 | + case 'ne': return `(${args[0]}) !== (${args[1]})` |
| 76 | + case 'gt': return `${guardAgainstCoercionSideEffects(args[0])} > ${guardAgainstCoercionSideEffects(args[1])}` |
| 77 | + case 'ge': return `${guardAgainstCoercionSideEffects(args[0])} >= ${guardAgainstCoercionSideEffects(args[1])}` |
| 78 | + case 'lt': return `${guardAgainstCoercionSideEffects(args[0])} < ${guardAgainstCoercionSideEffects(args[1])}` |
| 79 | + case 'le': return `${guardAgainstCoercionSideEffects(args[0])} <= ${guardAgainstCoercionSideEffects(args[1])}` |
| 80 | + case 'any': return iterateOn('some', ...args) |
| 81 | + case 'all': return iterateOn('every', ...args) |
| 82 | + case 'and': return `(${args.join(') && (')})` |
| 83 | + case 'or': return `(${args.join(') || (')})` |
| 84 | + case 'startsWith': return `String.prototype.startsWith.call(${assertString(args[0])}, ${assertString(args[1])})` |
| 85 | + case 'endsWith': return `String.prototype.endsWith.call(${assertString(args[0])}, ${assertString(args[1])})` |
| 86 | + case 'contains': return `((obj, elm) => { |
| 87 | + if (${isString('obj')}) { |
| 88 | + return String.prototype.includes.call(obj, elm) |
| 89 | + } else if (Array.isArray(obj)) { |
| 90 | + return Array.prototype.includes.call(obj, elm) |
| 91 | + } else if (${isTypedArray('obj')}) { |
| 92 | + return Object.getPrototypeOf(Int8Array.prototype).includes.call(obj, elm) |
| 93 | + } else if (${isInstanceOfCoreType('Set', 'obj')}) { |
| 94 | + return Set.prototype.has.call(obj, elm) |
| 95 | + } else if (${isInstanceOfCoreType('WeakSet', 'obj')}) { |
| 96 | + return WeakSet.prototype.has.call(obj, elm) |
| 97 | + } else if (${isInstanceOfCoreType('Map', 'obj')}) { |
| 98 | + return Map.prototype.has.call(obj, elm) |
| 99 | + } else if (${isInstanceOfCoreType('WeakMap', 'obj')}) { |
| 100 | + return WeakMap.prototype.has.call(obj, elm) |
| 101 | + } else { |
| 102 | + throw new TypeError('Variable does not support contains') |
| 103 | + } |
| 104 | + })(${args[0]}, ${args[1]})` |
| 105 | + case 'matches': return `((str, regex) => { |
| 106 | + if (${isString('str')}) { |
| 107 | + const regexIsString = ${isString('regex')} |
| 108 | + if (regexIsString || Object.getPrototypeOf(regex) === RegExp.prototype) { |
| 109 | + return RegExp.prototype.test.call(regexIsString ? new RegExp(regex) : regex, str) |
| 110 | + } else { |
| 111 | + throw new TypeError('Regular expression must be either a string or an instance of RegExp') |
| 112 | + } |
| 113 | + } else { |
| 114 | + throw new TypeError('Variable is not a string') |
| 115 | + } |
| 116 | + })(${args[0]}, ${args[1]})` |
| 117 | + case 'filter': return `(($dd_var) => { |
| 118 | + return ${isIterableCollection('$dd_var')} |
| 119 | + ? Array.from($dd_var).filter(($dd_it) => ${args[1]}) |
| 120 | + : Object.entries($dd_var).reduce((acc, [$dd_key, $dd_value]) => { |
| 121 | + if (${args[1]}) acc[$dd_key] = $dd_value |
| 122 | + return acc |
| 123 | + }, {}) |
| 124 | + })(${args[0]})` |
| 125 | + case 'substring': return `((str) => { |
| 126 | + if (${isString('str')}) { |
| 127 | + return String.prototype.substring.call(str, ${args[1]}, ${args[2]}) |
| 128 | + } else { |
| 129 | + throw new TypeError('Variable is not a string') |
| 130 | + } |
| 131 | + })(${args[0]})` |
| 132 | + case 'getmember': return accessProperty(args[0], args[1], false) |
| 133 | + case 'index': return accessProperty(args[0], args[1], true) |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + throw new TypeError(`Unknown AST node type: ${type}`) |
| 138 | +} |
| 139 | + |
| 140 | +function iterateOn (fnName, variable, callbackCode) { |
| 141 | + return `(($dd_val) => { |
| 142 | + return ${isIterableCollection('$dd_val')} |
| 143 | + ? Array.from($dd_val).${fnName}(($dd_it) => ${callbackCode}) |
| 144 | + : Object.entries($dd_val).${fnName}(([$dd_key, $dd_value]) => ${callbackCode}) |
| 145 | + })(${variable})` |
| 146 | +} |
| 147 | + |
| 148 | +function isString (variable) { |
| 149 | + return `(typeof ${variable} === 'string' || ${variable} instanceof String)` |
| 150 | +} |
| 151 | + |
| 152 | +function isIterableCollection (variable) { |
| 153 | + return `(${isArrayOrTypedArray(variable)} || ${isInstanceOfCoreType('Set', variable)} || ` + |
| 154 | + `${isInstanceOfCoreType('WeakSet', variable)})` |
| 155 | +} |
| 156 | + |
| 157 | +function isArrayOrTypedArray (variable) { |
| 158 | + return `(Array.isArray(${variable}) || ${isTypedArray(variable)})` |
| 159 | +} |
| 160 | + |
| 161 | +function isTypedArray (variable) { |
| 162 | + return isInstanceOfCoreType('TypedArray', variable, `${variable} instanceof Object.getPrototypeOf(Int8Array)`) |
| 163 | +} |
| 164 | + |
| 165 | +function isInstanceOfCoreType (type, variable, fallback = `${variable} instanceof ${type}`) { |
| 166 | + return `(process[Symbol.for('datadog:node:util:types')]?.is${type}?.(${variable}) ?? ${fallback})` |
| 167 | +} |
| 168 | + |
| 169 | +function getSize (variable) { |
| 170 | + return `((val) => { |
| 171 | + if (${isString('val')} || ${isArrayOrTypedArray('val')}) { |
| 172 | + return ${guardAgainstPropertyAccessSideEffects('val', '"length"')} |
| 173 | + } else if (${isInstanceOfCoreType('Set', 'val')} || ${isInstanceOfCoreType('Map', 'val')}) { |
| 174 | + return ${guardAgainstPropertyAccessSideEffects('val', '"size"')} |
| 175 | + } else { |
| 176 | + throw new TypeError('Cannot get length or size of string/collection') |
| 177 | + } |
| 178 | + })(${variable})` |
| 179 | +} |
| 180 | + |
| 181 | +function accessProperty (variable, keyOrIndex, allowMapAccess) { |
| 182 | + return `((val, key) => { |
| 183 | + if (${isInstanceOfCoreType('Map', 'val')}) { |
| 184 | + ${allowMapAccess |
| 185 | + ? 'return Map.prototype.get.call(val, key)' |
| 186 | + : 'throw new Error(\'Accessing a Map is not allowed\')'} |
| 187 | + } else if (${isInstanceOfCoreType('WeakMap', 'val')}) { |
| 188 | + ${allowMapAccess |
| 189 | + ? 'return WeakMap.prototype.get.call(val, key)' |
| 190 | + : 'throw new Error(\'Accessing a WeakMap is not allowed\')'} |
| 191 | + } else if (${isInstanceOfCoreType('Set', 'val')} || ${isInstanceOfCoreType('WeakSet', 'val')}) { |
| 192 | + throw new Error('Accessing a Set or WeakSet is not allowed') |
| 193 | + } else { |
| 194 | + return ${guardAgainstPropertyAccessSideEffects('val', 'key')} |
| 195 | + } |
| 196 | + })(${variable}, ${keyOrIndex})` |
| 197 | +} |
| 198 | + |
| 199 | +function guardAgainstPropertyAccessSideEffects (variable, propertyName) { |
| 200 | + return `((val, key) => { |
| 201 | + if ( |
| 202 | + ${isInstanceOfCoreType('Proxy', 'val', 'true')} || |
| 203 | + Object.getOwnPropertyDescriptor(val, key)?.get !== undefined |
| 204 | + ) { |
| 205 | + throw new Error('Possibility of side effect') |
| 206 | + } else { |
| 207 | + return val[key] |
| 208 | + } |
| 209 | + })(${variable}, ${propertyName})` |
| 210 | +} |
| 211 | + |
| 212 | +function guardAgainstCoercionSideEffects (variable) { |
| 213 | + return `((val) => { |
| 214 | + if ( |
| 215 | + typeof val === 'object' && val !== null && ( |
| 216 | + ${isInstanceOfCoreType('Proxy', 'val', 'true')} || |
| 217 | + val[Symbol.toPrimitive] !== undefined || |
| 218 | + val.valueOf !== Object.prototype.valueOf || |
| 219 | + val.toString !== Object.prototype.toString |
| 220 | + ) |
| 221 | + ) { |
| 222 | + throw new Error('Possibility of side effect due to coercion methods') |
| 223 | + } else { |
| 224 | + return val |
| 225 | + } |
| 226 | + })(${variable})` |
| 227 | +} |
| 228 | + |
| 229 | +function assertString (variable) { |
| 230 | + return `((val) => { |
| 231 | + if (typeof val === 'string' || val instanceof String) { |
| 232 | + return val |
| 233 | + } else { |
| 234 | + throw new TypeError('Variable is not a string') |
| 235 | + } |
| 236 | + })(${variable})` |
| 237 | +} |
| 238 | + |
| 239 | +function assertIdentifier (value) { |
| 240 | + if (!identifierRegex.test(value) || reservedWords.has(value)) { |
| 241 | + throw new SyntaxError(`Illegal identifier: ${value}`) |
| 242 | + } |
| 243 | + return value |
| 244 | +} |
0 commit comments