index.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. const typeChecker = (type) => {
  2. const typeString = "[object " + type + "]";
  3. return function (value) {
  4. return getClassName(value) === typeString;
  5. };
  6. };
  7. const getClassName = (value) => Object.prototype.toString.call(value);
  8. const comparable = (value) => {
  9. if (value instanceof Date) {
  10. return value.getTime();
  11. }
  12. else if (isArray(value)) {
  13. return value.map(comparable);
  14. }
  15. else if (value && typeof value.toJSON === "function") {
  16. return value.toJSON();
  17. }
  18. return value;
  19. };
  20. const coercePotentiallyNull = (value) => value == null ? null : value;
  21. const isArray = typeChecker("Array");
  22. const isObject = typeChecker("Object");
  23. const isFunction = typeChecker("Function");
  24. const isProperty = (item, key) => {
  25. return item.hasOwnProperty(key) && !isFunction(item[key]);
  26. };
  27. const isVanillaObject = (value) => {
  28. return (value &&
  29. (value.constructor === Object ||
  30. value.constructor === Array ||
  31. value.constructor.toString() === "function Object() { [native code] }" ||
  32. value.constructor.toString() === "function Array() { [native code] }") &&
  33. !value.toJSON);
  34. };
  35. const equals = (a, b) => {
  36. if (a == null && a == b) {
  37. return true;
  38. }
  39. if (a === b) {
  40. return true;
  41. }
  42. if (Object.prototype.toString.call(a) !== Object.prototype.toString.call(b)) {
  43. return false;
  44. }
  45. if (isArray(a)) {
  46. if (a.length !== b.length) {
  47. return false;
  48. }
  49. for (let i = 0, { length } = a; i < length; i++) {
  50. if (!equals(a[i], b[i]))
  51. return false;
  52. }
  53. return true;
  54. }
  55. else if (isObject(a)) {
  56. if (Object.keys(a).length !== Object.keys(b).length) {
  57. return false;
  58. }
  59. for (const key in a) {
  60. if (!equals(a[key], b[key]))
  61. return false;
  62. }
  63. return true;
  64. }
  65. return false;
  66. };
  67. /**
  68. * Walks through each value given the context - used for nested operations. E.g:
  69. * { "person.address": { $eq: "blarg" }}
  70. */
  71. const walkKeyPathValues = (item, keyPath, next, depth, key, owner) => {
  72. const currentKey = keyPath[depth];
  73. // if array, then try matching. Might fall through for cases like:
  74. // { $eq: [1, 2, 3] }, [ 1, 2, 3 ].
  75. if (isArray(item) &&
  76. isNaN(Number(currentKey)) &&
  77. !isProperty(item, currentKey)) {
  78. for (let i = 0, { length } = item; i < length; i++) {
  79. // if FALSE is returned, then terminate walker. For operations, this simply
  80. // means that the search critera was met.
  81. if (!walkKeyPathValues(item[i], keyPath, next, depth, i, item)) {
  82. return false;
  83. }
  84. }
  85. }
  86. if (depth === keyPath.length || item == null) {
  87. return next(item, key, owner, depth === 0, depth === keyPath.length);
  88. }
  89. return walkKeyPathValues(item[currentKey], keyPath, next, depth + 1, currentKey, item);
  90. };
  91. class BaseOperation {
  92. constructor(params, owneryQuery, options, name) {
  93. this.params = params;
  94. this.owneryQuery = owneryQuery;
  95. this.options = options;
  96. this.name = name;
  97. this.init();
  98. }
  99. init() { }
  100. reset() {
  101. this.done = false;
  102. this.keep = false;
  103. }
  104. }
  105. class GroupOperation extends BaseOperation {
  106. constructor(params, owneryQuery, options, children) {
  107. super(params, owneryQuery, options);
  108. this.children = children;
  109. }
  110. /**
  111. */
  112. reset() {
  113. this.keep = false;
  114. this.done = false;
  115. for (let i = 0, { length } = this.children; i < length; i++) {
  116. this.children[i].reset();
  117. }
  118. }
  119. /**
  120. */
  121. childrenNext(item, key, owner, root, leaf) {
  122. let done = true;
  123. let keep = true;
  124. for (let i = 0, { length } = this.children; i < length; i++) {
  125. const childOperation = this.children[i];
  126. if (!childOperation.done) {
  127. childOperation.next(item, key, owner, root, leaf);
  128. }
  129. if (!childOperation.keep) {
  130. keep = false;
  131. }
  132. if (childOperation.done) {
  133. if (!childOperation.keep) {
  134. break;
  135. }
  136. }
  137. else {
  138. done = false;
  139. }
  140. }
  141. this.done = done;
  142. this.keep = keep;
  143. }
  144. }
  145. class NamedGroupOperation extends GroupOperation {
  146. constructor(params, owneryQuery, options, children, name) {
  147. super(params, owneryQuery, options, children);
  148. this.name = name;
  149. }
  150. }
  151. class QueryOperation extends GroupOperation {
  152. constructor() {
  153. super(...arguments);
  154. this.propop = true;
  155. }
  156. /**
  157. */
  158. next(item, key, parent, root) {
  159. this.childrenNext(item, key, parent, root);
  160. }
  161. }
  162. class NestedOperation extends GroupOperation {
  163. constructor(keyPath, params, owneryQuery, options, children) {
  164. super(params, owneryQuery, options, children);
  165. this.keyPath = keyPath;
  166. this.propop = true;
  167. /**
  168. */
  169. this._nextNestedValue = (value, key, owner, root, leaf) => {
  170. this.childrenNext(value, key, owner, root, leaf);
  171. return !this.done;
  172. };
  173. }
  174. /**
  175. */
  176. next(item, key, parent) {
  177. walkKeyPathValues(item, this.keyPath, this._nextNestedValue, 0, key, parent);
  178. }
  179. }
  180. const createTester = (a, compare) => {
  181. if (a instanceof Function) {
  182. return a;
  183. }
  184. if (a instanceof RegExp) {
  185. return (b) => {
  186. const result = typeof b === "string" && a.test(b);
  187. a.lastIndex = 0;
  188. return result;
  189. };
  190. }
  191. const comparableA = comparable(a);
  192. return (b) => compare(comparableA, comparable(b));
  193. };
  194. class EqualsOperation extends BaseOperation {
  195. constructor() {
  196. super(...arguments);
  197. this.propop = true;
  198. }
  199. init() {
  200. this._test = createTester(this.params, this.options.compare);
  201. }
  202. next(item, key, parent) {
  203. if (!Array.isArray(parent) || parent.hasOwnProperty(key)) {
  204. if (this._test(item, key, parent)) {
  205. this.done = true;
  206. this.keep = true;
  207. }
  208. }
  209. }
  210. }
  211. const createEqualsOperation = (params, owneryQuery, options) => new EqualsOperation(params, owneryQuery, options);
  212. const numericalOperationCreator = (createNumericalOperation) => (params, owneryQuery, options, name) => {
  213. return createNumericalOperation(params, owneryQuery, options, name);
  214. };
  215. const numericalOperation = (createTester) => numericalOperationCreator((params, owneryQuery, options, name) => {
  216. const typeofParams = typeof comparable(params);
  217. const test = createTester(params);
  218. return new EqualsOperation((b) => {
  219. const actualValue = coercePotentiallyNull(b);
  220. return (typeof comparable(actualValue) === typeofParams && test(actualValue));
  221. }, owneryQuery, options, name);
  222. });
  223. const createNamedOperation = (name, params, parentQuery, options) => {
  224. const operationCreator = options.operations[name];
  225. if (!operationCreator) {
  226. throwUnsupportedOperation(name);
  227. }
  228. return operationCreator(params, parentQuery, options, name);
  229. };
  230. const throwUnsupportedOperation = (name) => {
  231. throw new Error(`Unsupported operation: ${name}`);
  232. };
  233. const containsOperation = (query, options) => {
  234. for (const key in query) {
  235. if (options.operations.hasOwnProperty(key) || key.charAt(0) === "$")
  236. return true;
  237. }
  238. return false;
  239. };
  240. const createNestedOperation = (keyPath, nestedQuery, parentKey, owneryQuery, options) => {
  241. if (containsOperation(nestedQuery, options)) {
  242. const [selfOperations, nestedOperations] = createQueryOperations(nestedQuery, parentKey, options);
  243. if (nestedOperations.length) {
  244. throw new Error(`Property queries must contain only operations, or exact objects.`);
  245. }
  246. return new NestedOperation(keyPath, nestedQuery, owneryQuery, options, selfOperations);
  247. }
  248. return new NestedOperation(keyPath, nestedQuery, owneryQuery, options, [
  249. new EqualsOperation(nestedQuery, owneryQuery, options),
  250. ]);
  251. };
  252. const createQueryOperation = (query, owneryQuery = null, { compare, operations } = {}) => {
  253. const options = {
  254. compare: compare || equals,
  255. operations: Object.assign({}, operations || {}),
  256. };
  257. const [selfOperations, nestedOperations] = createQueryOperations(query, null, options);
  258. const ops = [];
  259. if (selfOperations.length) {
  260. ops.push(new NestedOperation([], query, owneryQuery, options, selfOperations));
  261. }
  262. ops.push(...nestedOperations);
  263. if (ops.length === 1) {
  264. return ops[0];
  265. }
  266. return new QueryOperation(query, owneryQuery, options, ops);
  267. };
  268. const createQueryOperations = (query, parentKey, options) => {
  269. const selfOperations = [];
  270. const nestedOperations = [];
  271. if (!isVanillaObject(query)) {
  272. selfOperations.push(new EqualsOperation(query, query, options));
  273. return [selfOperations, nestedOperations];
  274. }
  275. for (const key in query) {
  276. if (options.operations.hasOwnProperty(key)) {
  277. const op = createNamedOperation(key, query[key], query, options);
  278. if (op) {
  279. if (!op.propop && parentKey && !options.operations[parentKey]) {
  280. throw new Error(`Malformed query. ${key} cannot be matched against property.`);
  281. }
  282. }
  283. // probably just a flag for another operation (like $options)
  284. if (op != null) {
  285. selfOperations.push(op);
  286. }
  287. }
  288. else if (key.charAt(0) === "$") {
  289. throwUnsupportedOperation(key);
  290. }
  291. else {
  292. nestedOperations.push(createNestedOperation(key.split("."), query[key], key, query, options));
  293. }
  294. }
  295. return [selfOperations, nestedOperations];
  296. };
  297. const createOperationTester = (operation) => (item, key, owner) => {
  298. operation.reset();
  299. operation.next(item, key, owner);
  300. return operation.keep;
  301. };
  302. const createQueryTester = (query, options = {}) => {
  303. return createOperationTester(createQueryOperation(query, null, options));
  304. };
  305. class $Ne extends BaseOperation {
  306. constructor() {
  307. super(...arguments);
  308. this.propop = true;
  309. }
  310. init() {
  311. this._test = createTester(this.params, this.options.compare);
  312. }
  313. reset() {
  314. super.reset();
  315. this.keep = true;
  316. }
  317. next(item) {
  318. if (this._test(item)) {
  319. this.done = true;
  320. this.keep = false;
  321. }
  322. }
  323. }
  324. // https://docs.mongodb.com/manual/reference/operator/query/elemMatch/
  325. class $ElemMatch extends BaseOperation {
  326. constructor() {
  327. super(...arguments);
  328. this.propop = true;
  329. }
  330. init() {
  331. if (!this.params || typeof this.params !== "object") {
  332. throw new Error(`Malformed query. $elemMatch must by an object.`);
  333. }
  334. this._queryOperation = createQueryOperation(this.params, this.owneryQuery, this.options);
  335. }
  336. reset() {
  337. super.reset();
  338. this._queryOperation.reset();
  339. }
  340. next(item) {
  341. if (isArray(item)) {
  342. for (let i = 0, { length } = item; i < length; i++) {
  343. // reset query operation since item being tested needs to pass _all_ query
  344. // operations for it to be a success
  345. this._queryOperation.reset();
  346. const child = item[i];
  347. this._queryOperation.next(child, i, item, false);
  348. this.keep = this.keep || this._queryOperation.keep;
  349. }
  350. this.done = true;
  351. }
  352. else {
  353. this.done = false;
  354. this.keep = false;
  355. }
  356. }
  357. }
  358. class $Not extends BaseOperation {
  359. constructor() {
  360. super(...arguments);
  361. this.propop = true;
  362. }
  363. init() {
  364. this._queryOperation = createQueryOperation(this.params, this.owneryQuery, this.options);
  365. }
  366. reset() {
  367. super.reset();
  368. this._queryOperation.reset();
  369. }
  370. next(item, key, owner, root) {
  371. this._queryOperation.next(item, key, owner, root);
  372. this.done = this._queryOperation.done;
  373. this.keep = !this._queryOperation.keep;
  374. }
  375. }
  376. class $Size extends BaseOperation {
  377. constructor() {
  378. super(...arguments);
  379. this.propop = true;
  380. }
  381. init() { }
  382. next(item) {
  383. if (isArray(item) && item.length === this.params) {
  384. this.done = true;
  385. this.keep = true;
  386. }
  387. // if (parent && parent.length === this.params) {
  388. // this.done = true;
  389. // this.keep = true;
  390. // }
  391. }
  392. }
  393. const assertGroupNotEmpty = (values) => {
  394. if (values.length === 0) {
  395. throw new Error(`$and/$or/$nor must be a nonempty array`);
  396. }
  397. };
  398. class $Or extends BaseOperation {
  399. constructor() {
  400. super(...arguments);
  401. this.propop = false;
  402. }
  403. init() {
  404. assertGroupNotEmpty(this.params);
  405. this._ops = this.params.map((op) => createQueryOperation(op, null, this.options));
  406. }
  407. reset() {
  408. this.done = false;
  409. this.keep = false;
  410. for (let i = 0, { length } = this._ops; i < length; i++) {
  411. this._ops[i].reset();
  412. }
  413. }
  414. next(item, key, owner) {
  415. let done = false;
  416. let success = false;
  417. for (let i = 0, { length } = this._ops; i < length; i++) {
  418. const op = this._ops[i];
  419. op.next(item, key, owner);
  420. if (op.keep) {
  421. done = true;
  422. success = op.keep;
  423. break;
  424. }
  425. }
  426. this.keep = success;
  427. this.done = done;
  428. }
  429. }
  430. class $Nor extends $Or {
  431. constructor() {
  432. super(...arguments);
  433. this.propop = false;
  434. }
  435. next(item, key, owner) {
  436. super.next(item, key, owner);
  437. this.keep = !this.keep;
  438. }
  439. }
  440. class $In extends BaseOperation {
  441. constructor() {
  442. super(...arguments);
  443. this.propop = true;
  444. }
  445. init() {
  446. const params = Array.isArray(this.params) ? this.params : [this.params];
  447. this._testers = params.map((value) => {
  448. if (containsOperation(value, this.options)) {
  449. throw new Error(`cannot nest $ under ${this.name.toLowerCase()}`);
  450. }
  451. return createTester(value, this.options.compare);
  452. });
  453. }
  454. next(item, key, owner) {
  455. let done = false;
  456. let success = false;
  457. for (let i = 0, { length } = this._testers; i < length; i++) {
  458. const test = this._testers[i];
  459. if (test(item)) {
  460. done = true;
  461. success = true;
  462. break;
  463. }
  464. }
  465. this.keep = success;
  466. this.done = done;
  467. }
  468. }
  469. class $Nin extends BaseOperation {
  470. constructor(params, ownerQuery, options, name) {
  471. super(params, ownerQuery, options, name);
  472. this.propop = true;
  473. this._in = new $In(params, ownerQuery, options, name);
  474. }
  475. next(item, key, owner, root) {
  476. this._in.next(item, key, owner);
  477. if (isArray(owner) && !root) {
  478. if (this._in.keep) {
  479. this.keep = false;
  480. this.done = true;
  481. }
  482. else if (key == owner.length - 1) {
  483. this.keep = true;
  484. this.done = true;
  485. }
  486. }
  487. else {
  488. this.keep = !this._in.keep;
  489. this.done = true;
  490. }
  491. }
  492. reset() {
  493. super.reset();
  494. this._in.reset();
  495. }
  496. }
  497. class $Exists extends BaseOperation {
  498. constructor() {
  499. super(...arguments);
  500. this.propop = true;
  501. }
  502. next(item, key, owner, root, leaf) {
  503. if (!leaf) {
  504. this.done = true;
  505. this.keep = !this.params;
  506. }
  507. else if (owner.hasOwnProperty(key) === this.params) {
  508. this.done = true;
  509. this.keep = true;
  510. }
  511. }
  512. }
  513. class $And extends NamedGroupOperation {
  514. constructor(params, owneryQuery, options, name) {
  515. super(params, owneryQuery, options, params.map((query) => createQueryOperation(query, owneryQuery, options)), name);
  516. this.propop = false;
  517. assertGroupNotEmpty(params);
  518. }
  519. next(item, key, owner, root) {
  520. this.childrenNext(item, key, owner, root);
  521. }
  522. }
  523. class $All extends NamedGroupOperation {
  524. constructor(params, owneryQuery, options, name) {
  525. super(params, owneryQuery, options, params.map((query) => createQueryOperation(query, owneryQuery, options)), name);
  526. this.propop = true;
  527. }
  528. next(item, key, owner, root) {
  529. this.childrenNext(item, key, owner, root);
  530. }
  531. }
  532. const $eq = (params, owneryQuery, options) => new EqualsOperation(params, owneryQuery, options);
  533. const $ne = (params, owneryQuery, options, name) => new $Ne(params, owneryQuery, options, name);
  534. const $or = (params, owneryQuery, options, name) => new $Or(params, owneryQuery, options, name);
  535. const $nor = (params, owneryQuery, options, name) => new $Nor(params, owneryQuery, options, name);
  536. const $elemMatch = (params, owneryQuery, options, name) => new $ElemMatch(params, owneryQuery, options, name);
  537. const $nin = (params, owneryQuery, options, name) => new $Nin(params, owneryQuery, options, name);
  538. const $in = (params, owneryQuery, options, name) => {
  539. return new $In(params, owneryQuery, options, name);
  540. };
  541. const $lt = numericalOperation((params) => (b) => {
  542. return b != null && b < params;
  543. });
  544. const $lte = numericalOperation((params) => (b) => {
  545. return b === params || b <= params;
  546. });
  547. const $gt = numericalOperation((params) => (b) => {
  548. return b != null && b > params;
  549. });
  550. const $gte = numericalOperation((params) => (b) => {
  551. return b === params || b >= params;
  552. });
  553. const $mod = ([mod, equalsValue], owneryQuery, options) => new EqualsOperation((b) => comparable(b) % mod === equalsValue, owneryQuery, options);
  554. const $exists = (params, owneryQuery, options, name) => new $Exists(params, owneryQuery, options, name);
  555. const $regex = (pattern, owneryQuery, options) => new EqualsOperation(new RegExp(pattern, owneryQuery.$options), owneryQuery, options);
  556. const $not = (params, owneryQuery, options, name) => new $Not(params, owneryQuery, options, name);
  557. const typeAliases = {
  558. number: (v) => typeof v === "number",
  559. string: (v) => typeof v === "string",
  560. bool: (v) => typeof v === "boolean",
  561. array: (v) => Array.isArray(v),
  562. null: (v) => v === null,
  563. timestamp: (v) => v instanceof Date,
  564. };
  565. const $type = (clazz, owneryQuery, options) => new EqualsOperation((b) => {
  566. if (typeof clazz === "string") {
  567. if (!typeAliases[clazz]) {
  568. throw new Error(`Type alias does not exist`);
  569. }
  570. return typeAliases[clazz](b);
  571. }
  572. return b != null ? b instanceof clazz || b.constructor === clazz : false;
  573. }, owneryQuery, options);
  574. const $and = (params, ownerQuery, options, name) => new $And(params, ownerQuery, options, name);
  575. const $all = (params, ownerQuery, options, name) => new $All(params, ownerQuery, options, name);
  576. const $size = (params, ownerQuery, options) => new $Size(params, ownerQuery, options, "$size");
  577. const $options = () => null;
  578. const $where = (params, ownerQuery, options) => {
  579. let test;
  580. if (isFunction(params)) {
  581. test = params;
  582. }
  583. else if (!process.env.CSP_ENABLED) {
  584. test = new Function("obj", "return " + params);
  585. }
  586. else {
  587. throw new Error(`In CSP mode, sift does not support strings in "$where" condition`);
  588. }
  589. return new EqualsOperation((b) => test.bind(b)(b), ownerQuery, options);
  590. };
  591. var defaultOperations = /*#__PURE__*/Object.freeze({
  592. __proto__: null,
  593. $Size: $Size,
  594. $all: $all,
  595. $and: $and,
  596. $elemMatch: $elemMatch,
  597. $eq: $eq,
  598. $exists: $exists,
  599. $gt: $gt,
  600. $gte: $gte,
  601. $in: $in,
  602. $lt: $lt,
  603. $lte: $lte,
  604. $mod: $mod,
  605. $ne: $ne,
  606. $nin: $nin,
  607. $nor: $nor,
  608. $not: $not,
  609. $options: $options,
  610. $or: $or,
  611. $regex: $regex,
  612. $size: $size,
  613. $type: $type,
  614. $where: $where
  615. });
  616. const createDefaultQueryOperation = (query, ownerQuery, { compare, operations } = {}) => {
  617. return createQueryOperation(query, ownerQuery, {
  618. compare,
  619. operations: Object.assign({}, defaultOperations, operations || {}),
  620. });
  621. };
  622. const createDefaultQueryTester = (query, options = {}) => {
  623. const op = createDefaultQueryOperation(query, null, options);
  624. return createOperationTester(op);
  625. };
  626. export { $Size, $all, $and, $elemMatch, $eq, $exists, $gt, $gte, $in, $lt, $lte, $mod, $ne, $nin, $nor, $not, $options, $or, $regex, $size, $type, $where, EqualsOperation, createDefaultQueryOperation, createEqualsOperation, createOperationTester, createQueryOperation, createQueryTester, createDefaultQueryTester as default };
  627. //# sourceMappingURL=index.js.map