UNPKG

typedash

Version:

modern, type-safe collection of utility functions

61 lines (58 loc) 2.08 kB
const require_assert = require('./assert-d3rr9bN5.cjs'); const require_createTypeGuard = require('./createTypeGuard-CC3eS9IQ.cjs'); //#region src/functions/_internal/isMaliciousObjectPath.ts /** * Determines whether the given property name is malicious or not (e.g. `__proto__` or `constructor`). * @param propertyName The property name to check for maliciousness. * @returns true if the property name is malicious, false otherwise. * @example * ```ts * isMaliciousObjectProperty('constructor'); // returns true * isMaliciousObjectProperty('nonMaliciousPath'); // returns false * isMaliciousObjectProperty('__proto__'); // returns true * ``` */ const isMaliciousObjectProperty = require_createTypeGuard.createTypeGuard(Object.getOwnPropertyNames(Object.getPrototypeOf({}))); //#endregion //#region src/functions/set/set.ts /** * Sets a value at the specified (possibly nested) path in an object. * @template TObject The type of the object. * @template Path The type of the path. * @param object The object to set the value in. * @param path The path to set the value at. * @param value The value to set. * @example * ```ts * const object: { * foo?: { * bar?: { * anArray: string[]; * }; * } * }; * * set(object, 'foo.bar.anArray[0]', 'value'); * object.foo.bar.anArray[0]; // 'value' */ function set(object, path, value) { const segments = path.match(pathSegmentsRegex); require_assert.assert(segments !== null, "Invalid path"); require_assert.assert(segments.every((segment) => isMaliciousObjectProperty(segment) === false), "Potentially malicious path"); let currentObject = object; for (let index = 0; index < segments.length - 1; index++) { const segment = segments[index]; if (segment in currentObject === false) currentObject[segment] = Object.create(null); currentObject = currentObject[segment]; } currentObject[segments.at(-1)] = value; } const pathSegmentsRegex = /[\w-]+/g; //#endregion Object.defineProperty(exports, 'set', { enumerable: true, get: function () { return set; } }); //# sourceMappingURL=set-D4MA3o6n.cjs.map