From 04a7faa52a1193c82888ae0ec89ef51554ab9bdf Mon Sep 17 00:00:00 2001 From: adrien2p Date: Thu, 19 Sep 2024 11:48:19 +0200 Subject: [PATCH 01/10] feat(index): Provide a similar API to Query --- .../modules/__tests__/index/search.spec.ts | 106 ++++++--- integration-tests/modules/package.json | 2 +- packages/core/types/src/index/service.ts | 22 +- packages/modules/index/coverage/clover.xml | 18 ++ .../index/coverage/coverage-final.json | 2 + .../index/coverage/lcov-report/base.css | 224 ++++++++++++++++++ .../coverage/lcov-report/block-navigation.js | 87 +++++++ .../index/coverage/lcov-report/favicon.png | Bin 0 -> 445 bytes .../lcov-report/flatten-where-clauses.ts.html | 199 ++++++++++++++++ .../index/coverage/lcov-report/index.html | 116 +++++++++ .../index/coverage/lcov-report/prettify.css | 1 + .../index/coverage/lcov-report/prettify.js | 2 + .../lcov-report/sort-arrow-sprite.png | Bin 0 -> 138 bytes .../index/coverage/lcov-report/sorter.js | 196 +++++++++++++++ packages/modules/index/coverage/lcov.info | 26 ++ .../__tests__/query-builder.spec.ts | 96 +++----- .../src/services/index-module-service.ts | 11 +- .../index/src/services/postgres-provider.ts | 106 ++++++--- packages/modules/index/src/types/index.ts | 7 +- .../__tests__/flatten-object-keys.spec.ts | 29 +++ .../normalize-fields-selcetion.spec.ts | 22 ++ .../index/src/utils/flatten-object-keys.ts | 59 +++++ .../src/utils/normalize-fields-selection.ts | 7 + .../modules/index/src/utils/query-builder.ts | 25 +- 24 files changed, 1213 insertions(+), 150 deletions(-) create mode 100644 packages/modules/index/coverage/clover.xml create mode 100644 packages/modules/index/coverage/coverage-final.json create mode 100644 packages/modules/index/coverage/lcov-report/base.css create mode 100644 packages/modules/index/coverage/lcov-report/block-navigation.js create mode 100644 packages/modules/index/coverage/lcov-report/favicon.png create mode 100644 packages/modules/index/coverage/lcov-report/flatten-where-clauses.ts.html create mode 100644 packages/modules/index/coverage/lcov-report/index.html create mode 100644 packages/modules/index/coverage/lcov-report/prettify.css create mode 100644 packages/modules/index/coverage/lcov-report/prettify.js create mode 100644 packages/modules/index/coverage/lcov-report/sort-arrow-sprite.png create mode 100644 packages/modules/index/coverage/lcov-report/sorter.js create mode 100644 packages/modules/index/coverage/lcov.info create mode 100644 packages/modules/index/src/utils/__tests__/flatten-object-keys.spec.ts create mode 100644 packages/modules/index/src/utils/__tests__/normalize-fields-selcetion.spec.ts create mode 100644 packages/modules/index/src/utils/flatten-object-keys.ts create mode 100644 packages/modules/index/src/utils/normalize-fields-selection.ts diff --git a/integration-tests/modules/__tests__/index/search.spec.ts b/integration-tests/modules/__tests__/index/search.spec.ts index 44917c906c366..72aa0e2066c37 100644 --- a/integration-tests/modules/__tests__/index/search.spec.ts +++ b/integration-tests/modules/__tests__/index/search.spec.ts @@ -58,23 +58,33 @@ medusaIntegrationTestRunner({ // Timeout to allow indexing to finish await setTimeout(2000) - const [results, count] = await indexEngine.queryAndCount( - { - select: { + const [results, count] = await indexEngine.queryAndCount({ + fields: [ + "product.*", + "product.variants.*", + "product.variants.prices.*", + ], + filters: { + product: { + variants: { + prices: { + amount: { $gt: 50 }, + }, + }, + }, + }, + pagination: { + orderBy: { product: { variants: { - prices: true, + prices: { + amount: "DESC", + }, }, }, }, - where: { - "product.variants.prices.amount": { $gt: 50 }, - }, }, - { - orderBy: [{ "product.variants.prices.amount": "DESC" }], - } - ) + }) expect(count).toBe(1) @@ -118,24 +128,34 @@ medusaIntegrationTestRunner({ // Timeout to allow indexing to finish await setTimeout(2000) - const [results, count] = await indexEngine.queryAndCount( - { - select: { - product: { - variants: { - prices: true, + const [results, count] = await indexEngine.queryAndCount({ + fields: [ + "product.*", + "product.variants.*", + "product.variants.prices.*", + ], + filters: { + product: { + variants: { + prices: { + amount: { $gt: 50 }, + currency_code: { $eq: "AUD" }, }, }, }, - where: { - "product.variants.prices.amount": { $gt: 50 }, - "product.variants.prices.currency_code": { $eq: "AUD" }, + pagination: { + orderBy: { + product: { + variants: { + prices: { + amount: "DESC", + }, + }, + }, + }, }, }, - { - orderBy: [{ "product.variants.prices.amount": "DESC" }], - } - ) + }) expect(count).toBe(1) @@ -179,29 +199,39 @@ medusaIntegrationTestRunner({ await setTimeout(5000) - const queryArgs = [ - { - select: { + const queryArgs = { + fields: [ + "product.*", + "product.variants.*", + "product.variants.prices.*", + ], + filters: { + product: { + variants: { + prices: { + amount: { $gt: 50 }, + currency_code: { $eq: "AUD" }, + }, + }, + }, + }, + pagination: { + orderBy: { product: { variants: { - prices: true, + prices: { + amount: "DESC", + }, }, }, }, - where: { - "product.variants.prices.amount": { $gt: 50 }, - "product.variants.prices.currency_code": { $eq: "AUD" }, - }, }, - { - orderBy: [{ "product.variants.prices.amount": "DESC" }], - }, - ] + } - await indexEngine.queryAndCount(...queryArgs) + await indexEngine.queryAndCount(queryArgs) const [results, count, perf] = await indexEngine.queryAndCount( - ...queryArgs + queryArgs ) console.log(perf) diff --git a/integration-tests/modules/package.json b/integration-tests/modules/package.json index d3af78cd227cb..52f626f3060b6 100644 --- a/integration-tests/modules/package.json +++ b/integration-tests/modules/package.json @@ -5,7 +5,7 @@ "license": "MIT", "private": true, "scripts": { - "test:integration": "NODE_OPTIONS=--experimental-vm-modules jest --no-cache --maxWorkers=50% --bail --detectOpenHandles --forceExit --logHeapUsage", + "test:integration": "NODE_OPTIONS=--experimental-vm-modules jest --no-cache --maxWorkers=50% --bail --detectOpenHandles --forceExit --logHeapUsage -- __tests__/index/*.spec.ts", "test:integration:chunk": "NODE_OPTIONS=--experimental-vm-modules jest --silent --no-cache --bail --maxWorkers=50% --forceExit --testPathPattern=$(echo $CHUNKS | jq -r \".[${CHUNK}] | .[]\")", "build": "tsc --allowJs --outDir ./dist" }, diff --git a/packages/core/types/src/index/service.ts b/packages/core/types/src/index/service.ts index 0d96d37daf228..d66d47f5293b4 100644 --- a/packages/core/types/src/index/service.ts +++ b/packages/core/types/src/index/service.ts @@ -1,6 +1,24 @@ import { IModuleService } from "../modules-sdk" +type OrderBy = { + [key: string]: OrderBy | "ASC" | "DESC" | 1 | -1 | true | false +} + +export type IndexQueryConfig = { + fields: string[] + filters?: Record + joinFilters?: Record + pagination?: { + skip?: number + take?: number + orderBy?: OrderBy + } + keepFilteredEntities?: boolean +} + export interface IIndexService extends IModuleService { - query(...args): Promise - queryAndCount(...args): Promise + query(config: IndexQueryConfig): Promise + queryAndCount( + config: IndexQueryConfig + ): Promise<[any[], number, PerformanceMeasure]> } diff --git a/packages/modules/index/coverage/clover.xml b/packages/modules/index/coverage/clover.xml new file mode 100644 index 0000000000000..652b0d15c745c --- /dev/null +++ b/packages/modules/index/coverage/clover.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + diff --git a/packages/modules/index/coverage/coverage-final.json b/packages/modules/index/coverage/coverage-final.json new file mode 100644 index 0000000000000..05df22285b9fd --- /dev/null +++ b/packages/modules/index/coverage/coverage-final.json @@ -0,0 +1,2 @@ +{"/Users/adriendeperetti/Documents/02-personnel/01-projects/medusa/packages/modules/index/src/utils/flatten-where-clauses.ts": {"path":"/Users/adriendeperetti/Documents/02-personnel/01-projects/medusa/packages/modules/index/src/utils/flatten-where-clauses.ts","statementMap":{"0":{"start":{"line":22,"column":16},"end":{"line":22,"column":36}},"1":{"start":{"line":23,"column":38},"end":{"line":23,"column":null}},"2":{"start":{"line":26,"column":4},"end":{"line":33,"column":null}},"3":{"start":{"line":27,"column":6},"end":{"line":32,"column":null}},"4":{"start":{"line":28,"column":24},"end":{"line":28,"column":null}},"5":{"start":{"line":29,"column":8},"end":{"line":29,"column":null}},"6":{"start":{"line":31,"column":8},"end":{"line":31,"column":null}},"7":{"start":{"line":36,"column":2},"end":{"line":36,"column":null}},"8":{"start":{"line":37,"column":2},"end":{"line":37,"column":null}}},"fnMap":{"0":{"name":"flattenWhereClauses","decl":{"start":{"line":22,"column":16},"end":{"line":22,"column":36}},"loc":{"start":{"line":22,"column":62},"end":{"line":38,"column":null}}},"1":{"name":"flatten","decl":{"start":{"line":25,"column":11},"end":{"line":25,"column":19}},"loc":{"start":{"line":25,"column":58},"end":{"line":34,"column":null}}}},"branchMap":{"0":{"loc":{"start":{"line":27,"column":6},"end":{"line":32,"column":null}},"type":"if","locations":[{"start":{"line":27,"column":6},"end":{"line":32,"column":null}},{"start":{"line":30,"column":13},"end":{"line":32,"column":null}}]},"1":{"loc":{"start":{"line":28,"column":24},"end":{"line":28,"column":null}},"type":"cond-expr","locations":[{"start":{"line":28,"column":31},"end":{"line":28,"column":47}},{"start":{"line":28,"column":50},"end":{"line":28,"column":null}}]}},"s":{"0":1,"1":1,"2":2,"3":5,"4":1,"5":1,"6":4,"7":1,"8":1},"f":{"0":1,"1":2},"b":{"0":[1,4],"1":[0,1]}} +} diff --git a/packages/modules/index/coverage/lcov-report/base.css b/packages/modules/index/coverage/lcov-report/base.css new file mode 100644 index 0000000000000..f418035b469af --- /dev/null +++ b/packages/modules/index/coverage/lcov-report/base.css @@ -0,0 +1,224 @@ +body, html { + margin:0; padding: 0; + height: 100%; +} +body { + font-family: Helvetica Neue, Helvetica, Arial; + font-size: 14px; + color:#333; +} +.small { font-size: 12px; } +*, *:after, *:before { + -webkit-box-sizing:border-box; + -moz-box-sizing:border-box; + box-sizing:border-box; + } +h1 { font-size: 20px; margin: 0;} +h2 { font-size: 14px; } +pre { + font: 12px/1.4 Consolas, "Liberation Mono", Menlo, Courier, monospace; + margin: 0; + padding: 0; + -moz-tab-size: 2; + -o-tab-size: 2; + tab-size: 2; +} +a { color:#0074D9; text-decoration:none; } +a:hover { text-decoration:underline; } +.strong { font-weight: bold; } +.space-top1 { padding: 10px 0 0 0; } +.pad2y { padding: 20px 0; } +.pad1y { padding: 10px 0; } +.pad2x { padding: 0 20px; } +.pad2 { padding: 20px; } +.pad1 { padding: 10px; } +.space-left2 { padding-left:55px; } +.space-right2 { padding-right:20px; } +.center { text-align:center; } +.clearfix { display:block; } +.clearfix:after { + content:''; + display:block; + height:0; + clear:both; + visibility:hidden; + } +.fl { float: left; } +@media only screen and (max-width:640px) { + .col3 { width:100%; max-width:100%; } + .hide-mobile { display:none!important; } +} + +.quiet { + color: #7f7f7f; + color: rgba(0,0,0,0.5); +} +.quiet a { opacity: 0.7; } + +.fraction { + font-family: Consolas, 'Liberation Mono', Menlo, Courier, monospace; + font-size: 10px; + color: #555; + background: #E8E8E8; + padding: 4px 5px; + border-radius: 3px; + vertical-align: middle; +} + +div.path a:link, div.path a:visited { color: #333; } +table.coverage { + border-collapse: collapse; + margin: 10px 0 0 0; + padding: 0; +} + +table.coverage td { + margin: 0; + padding: 0; + vertical-align: top; +} +table.coverage td.line-count { + text-align: right; + padding: 0 5px 0 20px; +} +table.coverage td.line-coverage { + text-align: right; + padding-right: 10px; + min-width:20px; +} + +table.coverage td span.cline-any { + display: inline-block; + padding: 0 5px; + width: 100%; +} +.missing-if-branch { + display: inline-block; + margin-right: 5px; + border-radius: 3px; + position: relative; + padding: 0 4px; + background: #333; + color: yellow; +} + +.skip-if-branch { + display: none; + margin-right: 10px; + position: relative; + padding: 0 4px; + background: #ccc; + color: white; +} +.missing-if-branch .typ, .skip-if-branch .typ { + color: inherit !important; +} +.coverage-summary { + border-collapse: collapse; + width: 100%; +} +.coverage-summary tr { border-bottom: 1px solid #bbb; } +.keyline-all { border: 1px solid #ddd; } +.coverage-summary td, .coverage-summary th { padding: 10px; } +.coverage-summary tbody { border: 1px solid #bbb; } +.coverage-summary td { border-right: 1px solid #bbb; } +.coverage-summary td:last-child { border-right: none; } +.coverage-summary th { + text-align: left; + font-weight: normal; + white-space: nowrap; +} +.coverage-summary th.file { border-right: none !important; } +.coverage-summary th.pct { } +.coverage-summary th.pic, +.coverage-summary th.abs, +.coverage-summary td.pct, +.coverage-summary td.abs { text-align: right; } +.coverage-summary td.file { white-space: nowrap; } +.coverage-summary td.pic { min-width: 120px !important; } +.coverage-summary tfoot td { } + +.coverage-summary .sorter { + height: 10px; + width: 7px; + display: inline-block; + margin-left: 0.5em; + background: url(sort-arrow-sprite.png) no-repeat scroll 0 0 transparent; +} +.coverage-summary .sorted .sorter { + background-position: 0 -20px; +} +.coverage-summary .sorted-desc .sorter { + background-position: 0 -10px; +} +.status-line { height: 10px; } +/* yellow */ +.cbranch-no { background: yellow !important; color: #111; } +/* dark red */ +.red.solid, .status-line.low, .low .cover-fill { background:#C21F39 } +.low .chart { border:1px solid #C21F39 } +.highlighted, +.highlighted .cstat-no, .highlighted .fstat-no, .highlighted .cbranch-no{ + background: #C21F39 !important; +} +/* medium red */ +.cstat-no, .fstat-no, .cbranch-no, .cbranch-no { background:#F6C6CE } +/* light red */ +.low, .cline-no { background:#FCE1E5 } +/* light green */ +.high, .cline-yes { background:rgb(230,245,208) } +/* medium green */ +.cstat-yes { background:rgb(161,215,106) } +/* dark green */ +.status-line.high, .high .cover-fill { background:rgb(77,146,33) } +.high .chart { border:1px solid rgb(77,146,33) } +/* dark yellow (gold) */ +.status-line.medium, .medium .cover-fill { background: #f9cd0b; } +.medium .chart { border:1px solid #f9cd0b; } +/* light yellow */ +.medium { background: #fff4c2; } + +.cstat-skip { background: #ddd; color: #111; } +.fstat-skip { background: #ddd; color: #111 !important; } +.cbranch-skip { background: #ddd !important; color: #111; } + +span.cline-neutral { background: #eaeaea; } + +.coverage-summary td.empty { + opacity: .5; + padding-top: 4px; + padding-bottom: 4px; + line-height: 1; + color: #888; +} + +.cover-fill, .cover-empty { + display:inline-block; + height: 12px; +} +.chart { + line-height: 0; +} +.cover-empty { + background: white; +} +.cover-full { + border-right: none !important; +} +pre.prettyprint { + border: none !important; + padding: 0 !important; + margin: 0 !important; +} +.com { color: #999 !important; } +.ignore-none { color: #999; font-weight: normal; } + +.wrapper { + min-height: 100%; + height: auto !important; + height: 100%; + margin: 0 auto -48px; +} +.footer, .push { + height: 48px; +} diff --git a/packages/modules/index/coverage/lcov-report/block-navigation.js b/packages/modules/index/coverage/lcov-report/block-navigation.js new file mode 100644 index 0000000000000..cc121302316c8 --- /dev/null +++ b/packages/modules/index/coverage/lcov-report/block-navigation.js @@ -0,0 +1,87 @@ +/* eslint-disable */ +var jumpToCode = (function init() { + // Classes of code we would like to highlight in the file view + var missingCoverageClasses = ['.cbranch-no', '.cstat-no', '.fstat-no']; + + // Elements to highlight in the file listing view + var fileListingElements = ['td.pct.low']; + + // We don't want to select elements that are direct descendants of another match + var notSelector = ':not(' + missingCoverageClasses.join('):not(') + ') > '; // becomes `:not(a):not(b) > ` + + // Selecter that finds elements on the page to which we can jump + var selector = + fileListingElements.join(', ') + + ', ' + + notSelector + + missingCoverageClasses.join(', ' + notSelector); // becomes `:not(a):not(b) > a, :not(a):not(b) > b` + + // The NodeList of matching elements + var missingCoverageElements = document.querySelectorAll(selector); + + var currentIndex; + + function toggleClass(index) { + missingCoverageElements + .item(currentIndex) + .classList.remove('highlighted'); + missingCoverageElements.item(index).classList.add('highlighted'); + } + + function makeCurrent(index) { + toggleClass(index); + currentIndex = index; + missingCoverageElements.item(index).scrollIntoView({ + behavior: 'smooth', + block: 'center', + inline: 'center' + }); + } + + function goToPrevious() { + var nextIndex = 0; + if (typeof currentIndex !== 'number' || currentIndex === 0) { + nextIndex = missingCoverageElements.length - 1; + } else if (missingCoverageElements.length > 1) { + nextIndex = currentIndex - 1; + } + + makeCurrent(nextIndex); + } + + function goToNext() { + var nextIndex = 0; + + if ( + typeof currentIndex === 'number' && + currentIndex < missingCoverageElements.length - 1 + ) { + nextIndex = currentIndex + 1; + } + + makeCurrent(nextIndex); + } + + return function jump(event) { + if ( + document.getElementById('fileSearch') === document.activeElement && + document.activeElement != null + ) { + // if we're currently focused on the search input, we don't want to navigate + return; + } + + switch (event.which) { + case 78: // n + case 74: // j + goToNext(); + break; + case 66: // b + case 75: // k + case 80: // p + goToPrevious(); + break; + } + }; +})(); +window.addEventListener('keydown', jumpToCode); diff --git a/packages/modules/index/coverage/lcov-report/favicon.png b/packages/modules/index/coverage/lcov-report/favicon.png new file mode 100644 index 0000000000000000000000000000000000000000..c1525b811a167671e9de1fa78aab9f5c0b61cef7 GIT binary patch literal 445 zcmV;u0Yd(XP))rP{nL}Ln%S7`m{0DjX9TLF* zFCb$4Oi7vyLOydb!7n&^ItCzb-%BoB`=x@N2jll2Nj`kauio%aw_@fe&*}LqlFT43 z8doAAe))z_%=P%v^@JHp3Hjhj^6*Kr_h|g_Gr?ZAa&y>wxHE99Gk>A)2MplWz2xdG zy8VD2J|Uf#EAw*bo5O*PO_}X2Tob{%bUoO2G~T`@%S6qPyc}VkhV}UifBuRk>%5v( z)x7B{I~z*k<7dv#5tC+m{km(D087J4O%+<<;K|qwefb6@GSX45wCK}Sn*> + + + + Code coverage report for flatten-object-keys.ts + + + + + + + + + +
+
+

All files flatten-object-keys.ts

+
+ +
+ 100% + Statements + 9/9 +
+ + +
+ 75% + Branches + 3/4 +
+ + +
+ 100% + Functions + 2/2 +
+ + +
+ 100% + Lines + 9/9 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+ +
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +1x +1x +  +  +2x +5x +1x +1x +  +4x +  +  +  +  +1x +1x +  + 
/**
+ * Flatten where clauses
+ * @example
+ * input: {
+ *   a: 1,
+ *   b: {
+ *     c: 2,
+ *     d: 3,
+ *   },
+ *   e: 4,
+ * }
+ *
+ * output: {
+ *   a: 1,
+ *   b.c: 2,
+ *   b.d: 3,
+ *   e: 4,
+ * }
+ *
+ * @param where
+ */
+export function flattenObjectKeys(where: Record<string, any>) {
+  const result: Record<string, any> = {}
+ 
+  function flatten(obj: Record<string, any>, path?: string) {
+    for (const key in obj) {
+      if (typeof obj[key] === "object") {
+        const newPath = path ? `${path}.${key}` : key
+        flatten(obj[key], newPath)
+      } else {
+        result[`${path}.${key}`] = obj[key]
+      }
+    }
+  }
+ 
+  flatten(where)
+  return result
+}
+ 
+ +
+
+ + + + + + + + \ No newline at end of file diff --git a/packages/modules/index/coverage/lcov-report/index.html b/packages/modules/index/coverage/lcov-report/index.html new file mode 100644 index 0000000000000..02fa54c732fd3 --- /dev/null +++ b/packages/modules/index/coverage/lcov-report/index.html @@ -0,0 +1,116 @@ + + + + + + Code coverage report for All files + + + + + + + + + +
+
+

All files

+
+ +
+ 100% + Statements + 9/9 +
+ + +
+ 75% + Branches + 3/4 +
+ + +
+ 100% + Functions + 2/2 +
+ + +
+ 100% + Lines + 9/9 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+ +
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FileStatementsBranchesFunctionsLines
flatten-object-keys.ts +
+
100%9/975%3/4100%2/2100%9/9
+
+
+
+ + + + + + + + \ No newline at end of file diff --git a/packages/modules/index/coverage/lcov-report/prettify.css b/packages/modules/index/coverage/lcov-report/prettify.css new file mode 100644 index 0000000000000..b317a7cda31a4 --- /dev/null +++ b/packages/modules/index/coverage/lcov-report/prettify.css @@ -0,0 +1 @@ +.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} diff --git a/packages/modules/index/coverage/lcov-report/prettify.js b/packages/modules/index/coverage/lcov-report/prettify.js new file mode 100644 index 0000000000000..b3225238f26e3 --- /dev/null +++ b/packages/modules/index/coverage/lcov-report/prettify.js @@ -0,0 +1,2 @@ +/* eslint-disable */ +window.PR_SHOULD_USE_CONTINUATION=true;(function(){var h=["break,continue,do,else,for,if,return,while"];var u=[h,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"];var p=[u,"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"];var l=[p,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"];var x=[p,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"];var R=[x,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"];var r="all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes";var w=[p,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"];var s="caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END";var I=[h,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"];var f=[h,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"];var H=[h,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"];var A=[l,R,w,s+I,f,H];var e=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/;var C="str";var z="kwd";var j="com";var O="typ";var G="lit";var L="pun";var F="pln";var m="tag";var E="dec";var J="src";var P="atn";var n="atv";var N="nocode";var M="(?:^^\\.?|[+-]|\\!|\\!=|\\!==|\\#|\\%|\\%=|&|&&|&&=|&=|\\(|\\*|\\*=|\\+=|\\,|\\-=|\\->|\\/|\\/=|:|::|\\;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|\\?|\\@|\\[|\\^|\\^=|\\^\\^|\\^\\^=|\\{|\\||\\|=|\\|\\||\\|\\|=|\\~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*";function k(Z){var ad=0;var S=false;var ac=false;for(var V=0,U=Z.length;V122)){if(!(al<65||ag>90)){af.push([Math.max(65,ag)|32,Math.min(al,90)|32])}if(!(al<97||ag>122)){af.push([Math.max(97,ag)&~32,Math.min(al,122)&~32])}}}}af.sort(function(av,au){return(av[0]-au[0])||(au[1]-av[1])});var ai=[];var ap=[NaN,NaN];for(var ar=0;arat[0]){if(at[1]+1>at[0]){an.push("-")}an.push(T(at[1]))}}an.push("]");return an.join("")}function W(al){var aj=al.source.match(new RegExp("(?:\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]|\\\\u[A-Fa-f0-9]{4}|\\\\x[A-Fa-f0-9]{2}|\\\\[0-9]+|\\\\[^ux0-9]|\\(\\?[:!=]|[\\(\\)\\^]|[^\\x5B\\x5C\\(\\)\\^]+)","g"));var ah=aj.length;var an=[];for(var ak=0,am=0;ak=2&&ai==="["){aj[ak]=X(ag)}else{if(ai!=="\\"){aj[ak]=ag.replace(/[a-zA-Z]/g,function(ao){var ap=ao.charCodeAt(0);return"["+String.fromCharCode(ap&~32,ap|32)+"]"})}}}}return aj.join("")}var aa=[];for(var V=0,U=Z.length;V=0;){S[ac.charAt(ae)]=Y}}var af=Y[1];var aa=""+af;if(!ag.hasOwnProperty(aa)){ah.push(af);ag[aa]=null}}ah.push(/[\0-\uffff]/);V=k(ah)})();var X=T.length;var W=function(ah){var Z=ah.sourceCode,Y=ah.basePos;var ad=[Y,F];var af=0;var an=Z.match(V)||[];var aj={};for(var ae=0,aq=an.length;ae=5&&"lang-"===ap.substring(0,5);if(am&&!(ai&&typeof ai[1]==="string")){am=false;ap=J}if(!am){aj[ag]=ap}}var ab=af;af+=ag.length;if(!am){ad.push(Y+ab,ap)}else{var al=ai[1];var ak=ag.indexOf(al);var ac=ak+al.length;if(ai[2]){ac=ag.length-ai[2].length;ak=ac-al.length}var ar=ap.substring(5);B(Y+ab,ag.substring(0,ak),W,ad);B(Y+ab+ak,al,q(ar,al),ad);B(Y+ab+ac,ag.substring(ac),W,ad)}}ah.decorations=ad};return W}function i(T){var W=[],S=[];if(T.tripleQuotedStrings){W.push([C,/^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,null,"'\""])}else{if(T.multiLineStrings){W.push([C,/^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,null,"'\"`"])}else{W.push([C,/^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,null,"\"'"])}}if(T.verbatimStrings){S.push([C,/^@\"(?:[^\"]|\"\")*(?:\"|$)/,null])}var Y=T.hashComments;if(Y){if(T.cStyleComments){if(Y>1){W.push([j,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,null,"#"])}else{W.push([j,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/,null,"#"])}S.push([C,/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,null])}else{W.push([j,/^#[^\r\n]*/,null,"#"])}}if(T.cStyleComments){S.push([j,/^\/\/[^\r\n]*/,null]);S.push([j,/^\/\*[\s\S]*?(?:\*\/|$)/,null])}if(T.regexLiterals){var X=("/(?=[^/*])(?:[^/\\x5B\\x5C]|\\x5C[\\s\\S]|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+/");S.push(["lang-regex",new RegExp("^"+M+"("+X+")")])}var V=T.types;if(V){S.push([O,V])}var U=(""+T.keywords).replace(/^ | $/g,"");if(U.length){S.push([z,new RegExp("^(?:"+U.replace(/[\s,]+/g,"|")+")\\b"),null])}W.push([F,/^\s+/,null," \r\n\t\xA0"]);S.push([G,/^@[a-z_$][a-z_$@0-9]*/i,null],[O,/^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\w+_t\b)/,null],[F,/^[a-z_$][a-z_$@0-9]*/i,null],[G,new RegExp("^(?:0x[a-f0-9]+|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)(?:e[+\\-]?\\d+)?)[a-z]*","i"),null,"0123456789"],[F,/^\\[\s\S]?/,null],[L,/^.[^\s\w\.$@\'\"\`\/\#\\]*/,null]);return g(W,S)}var K=i({keywords:A,hashComments:true,cStyleComments:true,multiLineStrings:true,regexLiterals:true});function Q(V,ag){var U=/(?:^|\s)nocode(?:\s|$)/;var ab=/\r\n?|\n/;var ac=V.ownerDocument;var S;if(V.currentStyle){S=V.currentStyle.whiteSpace}else{if(window.getComputedStyle){S=ac.defaultView.getComputedStyle(V,null).getPropertyValue("white-space")}}var Z=S&&"pre"===S.substring(0,3);var af=ac.createElement("LI");while(V.firstChild){af.appendChild(V.firstChild)}var W=[af];function ae(al){switch(al.nodeType){case 1:if(U.test(al.className)){break}if("BR"===al.nodeName){ad(al);if(al.parentNode){al.parentNode.removeChild(al)}}else{for(var an=al.firstChild;an;an=an.nextSibling){ae(an)}}break;case 3:case 4:if(Z){var am=al.nodeValue;var aj=am.match(ab);if(aj){var ai=am.substring(0,aj.index);al.nodeValue=ai;var ah=am.substring(aj.index+aj[0].length);if(ah){var ak=al.parentNode;ak.insertBefore(ac.createTextNode(ah),al.nextSibling)}ad(al);if(!ai){al.parentNode.removeChild(al)}}}break}}function ad(ak){while(!ak.nextSibling){ak=ak.parentNode;if(!ak){return}}function ai(al,ar){var aq=ar?al.cloneNode(false):al;var ao=al.parentNode;if(ao){var ap=ai(ao,1);var an=al.nextSibling;ap.appendChild(aq);for(var am=an;am;am=an){an=am.nextSibling;ap.appendChild(am)}}return aq}var ah=ai(ak.nextSibling,0);for(var aj;(aj=ah.parentNode)&&aj.nodeType===1;){ah=aj}W.push(ah)}for(var Y=0;Y=S){ah+=2}if(V>=ap){Z+=2}}}var t={};function c(U,V){for(var S=V.length;--S>=0;){var T=V[S];if(!t.hasOwnProperty(T)){t[T]=U}else{if(window.console){console.warn("cannot override language handler %s",T)}}}}function q(T,S){if(!(T&&t.hasOwnProperty(T))){T=/^\s*]*(?:>|$)/],[j,/^<\!--[\s\S]*?(?:-\->|$)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],[L,/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]),["default-markup","htm","html","mxml","xhtml","xml","xsl"]);c(g([[F,/^[\s]+/,null," \t\r\n"],[n,/^(?:\"[^\"]*\"?|\'[^\']*\'?)/,null,"\"'"]],[[m,/^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],[P,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/],[L,/^[=<>\/]+/],["lang-js",/^on\w+\s*=\s*\"([^\"]+)\"/i],["lang-js",/^on\w+\s*=\s*\'([^\']+)\'/i],["lang-js",/^on\w+\s*=\s*([^\"\'>\s]+)/i],["lang-css",/^style\s*=\s*\"([^\"]+)\"/i],["lang-css",/^style\s*=\s*\'([^\']+)\'/i],["lang-css",/^style\s*=\s*([^\"\'>\s]+)/i]]),["in.tag"]);c(g([],[[n,/^[\s\S]+/]]),["uq.val"]);c(i({keywords:l,hashComments:true,cStyleComments:true,types:e}),["c","cc","cpp","cxx","cyc","m"]);c(i({keywords:"null,true,false"}),["json"]);c(i({keywords:R,hashComments:true,cStyleComments:true,verbatimStrings:true,types:e}),["cs"]);c(i({keywords:x,cStyleComments:true}),["java"]);c(i({keywords:H,hashComments:true,multiLineStrings:true}),["bsh","csh","sh"]);c(i({keywords:I,hashComments:true,multiLineStrings:true,tripleQuotedStrings:true}),["cv","py"]);c(i({keywords:s,hashComments:true,multiLineStrings:true,regexLiterals:true}),["perl","pl","pm"]);c(i({keywords:f,hashComments:true,multiLineStrings:true,regexLiterals:true}),["rb"]);c(i({keywords:w,cStyleComments:true,regexLiterals:true}),["js"]);c(i({keywords:r,hashComments:3,cStyleComments:true,multilineStrings:true,tripleQuotedStrings:true,regexLiterals:true}),["coffee"]);c(g([],[[C,/^[\s\S]+/]]),["regex"]);function d(V){var U=V.langExtension;try{var S=a(V.sourceNode);var T=S.sourceCode;V.sourceCode=T;V.spans=S.spans;V.basePos=0;q(U,T)(V);D(V)}catch(W){if("console" in window){console.log(W&&W.stack?W.stack:W)}}}function y(W,V,U){var S=document.createElement("PRE");S.innerHTML=W;if(U){Q(S,U)}var T={langExtension:V,numberLines:U,sourceNode:S};d(T);return S.innerHTML}function b(ad){function Y(af){return document.getElementsByTagName(af)}var ac=[Y("pre"),Y("code"),Y("xmp")];var T=[];for(var aa=0;aa=0){var ah=ai.match(ab);var am;if(!ah&&(am=o(aj))&&"CODE"===am.tagName){ah=am.className.match(ab)}if(ah){ah=ah[1]}var al=false;for(var ak=aj.parentNode;ak;ak=ak.parentNode){if((ak.tagName==="pre"||ak.tagName==="code"||ak.tagName==="xmp")&&ak.className&&ak.className.indexOf("prettyprint")>=0){al=true;break}}if(!al){var af=aj.className.match(/\blinenums\b(?::(\d+))?/);af=af?af[1]&&af[1].length?+af[1]:true:false;if(af){Q(aj,af)}S={langExtension:ah,sourceNode:aj,numberLines:af};d(S)}}}if(X]*(?:>|$)/],[PR.PR_COMMENT,/^<\!--[\s\S]*?(?:-\->|$)/],[PR.PR_PUNCTUATION,/^(?:<[%?]|[%?]>)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],["lang-",/^]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-handlebars",/^]*type\s*=\s*['"]?text\/x-handlebars-template['"]?\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-js",/^]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i],[PR.PR_DECLARATION,/^{{[#^>/]?\s*[\w.][^}]*}}/],[PR.PR_DECLARATION,/^{{&?\s*[\w.][^}]*}}/],[PR.PR_DECLARATION,/^{{{>?\s*[\w.][^}]*}}}/],[PR.PR_COMMENT,/^{{![^}]*}}/]]),["handlebars","hbs"]);PR.registerLangHandler(PR.createSimpleLexer([[PR.PR_PLAIN,/^[ \t\r\n\f]+/,null," \t\r\n\f"]],[[PR.PR_STRING,/^\"(?:[^\n\r\f\\\"]|\\(?:\r\n?|\n|\f)|\\[\s\S])*\"/,null],[PR.PR_STRING,/^\'(?:[^\n\r\f\\\']|\\(?:\r\n?|\n|\f)|\\[\s\S])*\'/,null],["lang-css-str",/^url\(([^\)\"\']*)\)/i],[PR.PR_KEYWORD,/^(?:url|rgb|\!important|@import|@page|@media|@charset|inherit)(?=[^\-\w]|$)/i,null],["lang-css-kw",/^(-?(?:[_a-z]|(?:\\[0-9a-f]+ ?))(?:[_a-z0-9\-]|\\(?:\\[0-9a-f]+ ?))*)\s*:/i],[PR.PR_COMMENT,/^\/\*[^*]*\*+(?:[^\/*][^*]*\*+)*\//],[PR.PR_COMMENT,/^(?:)/],[PR.PR_LITERAL,/^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i],[PR.PR_LITERAL,/^#(?:[0-9a-f]{3}){1,2}/i],[PR.PR_PLAIN,/^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i],[PR.PR_PUNCTUATION,/^[^\s\w\'\"]+/]]),["css"]);PR.registerLangHandler(PR.createSimpleLexer([],[[PR.PR_KEYWORD,/^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i]]),["css-kw"]);PR.registerLangHandler(PR.createSimpleLexer([],[[PR.PR_STRING,/^[^\)\"\']+/]]),["css-str"]); diff --git a/packages/modules/index/coverage/lcov-report/sort-arrow-sprite.png b/packages/modules/index/coverage/lcov-report/sort-arrow-sprite.png new file mode 100644 index 0000000000000000000000000000000000000000..6ed68316eb3f65dec9063332d2f69bf3093bbfab GIT binary patch literal 138 zcmeAS@N?(olHy`uVBq!ia0vp^>_9Bd!3HEZxJ@+%Qh}Z>jv*C{$p!i!8j}?a+@3A= zIAGwzjijN=FBi!|L1t?LM;Q;gkwn>2cAy-KV{dn nf0J1DIvEHQu*n~6U}x}qyky7vi4|9XhBJ7&`njxgN@xNA8m%nc literal 0 HcmV?d00001 diff --git a/packages/modules/index/coverage/lcov-report/sorter.js b/packages/modules/index/coverage/lcov-report/sorter.js new file mode 100644 index 0000000000000..2bb296a8ca8e4 --- /dev/null +++ b/packages/modules/index/coverage/lcov-report/sorter.js @@ -0,0 +1,196 @@ +/* eslint-disable */ +var addSorting = (function() { + 'use strict'; + var cols, + currentSort = { + index: 0, + desc: false + }; + + // returns the summary table element + function getTable() { + return document.querySelector('.coverage-summary'); + } + // returns the thead element of the summary table + function getTableHeader() { + return getTable().querySelector('thead tr'); + } + // returns the tbody element of the summary table + function getTableBody() { + return getTable().querySelector('tbody'); + } + // returns the th element for nth column + function getNthColumn(n) { + return getTableHeader().querySelectorAll('th')[n]; + } + + function onFilterInput() { + const searchValue = document.getElementById('fileSearch').value; + const rows = document.getElementsByTagName('tbody')[0].children; + for (let i = 0; i < rows.length; i++) { + const row = rows[i]; + if ( + row.textContent + .toLowerCase() + .includes(searchValue.toLowerCase()) + ) { + row.style.display = ''; + } else { + row.style.display = 'none'; + } + } + } + + // loads the search box + function addSearchBox() { + var template = document.getElementById('filterTemplate'); + var templateClone = template.content.cloneNode(true); + templateClone.getElementById('fileSearch').oninput = onFilterInput; + template.parentElement.appendChild(templateClone); + } + + // loads all columns + function loadColumns() { + var colNodes = getTableHeader().querySelectorAll('th'), + colNode, + cols = [], + col, + i; + + for (i = 0; i < colNodes.length; i += 1) { + colNode = colNodes[i]; + col = { + key: colNode.getAttribute('data-col'), + sortable: !colNode.getAttribute('data-nosort'), + type: colNode.getAttribute('data-type') || 'string' + }; + cols.push(col); + if (col.sortable) { + col.defaultDescSort = col.type === 'number'; + colNode.innerHTML = + colNode.innerHTML + ''; + } + } + return cols; + } + // attaches a data attribute to every tr element with an object + // of data values keyed by column name + function loadRowData(tableRow) { + var tableCols = tableRow.querySelectorAll('td'), + colNode, + col, + data = {}, + i, + val; + for (i = 0; i < tableCols.length; i += 1) { + colNode = tableCols[i]; + col = cols[i]; + val = colNode.getAttribute('data-value'); + if (col.type === 'number') { + val = Number(val); + } + data[col.key] = val; + } + return data; + } + // loads all row data + function loadData() { + var rows = getTableBody().querySelectorAll('tr'), + i; + + for (i = 0; i < rows.length; i += 1) { + rows[i].data = loadRowData(rows[i]); + } + } + // sorts the table using the data for the ith column + function sortByIndex(index, desc) { + var key = cols[index].key, + sorter = function(a, b) { + a = a.data[key]; + b = b.data[key]; + return a < b ? -1 : a > b ? 1 : 0; + }, + finalSorter = sorter, + tableBody = document.querySelector('.coverage-summary tbody'), + rowNodes = tableBody.querySelectorAll('tr'), + rows = [], + i; + + if (desc) { + finalSorter = function(a, b) { + return -1 * sorter(a, b); + }; + } + + for (i = 0; i < rowNodes.length; i += 1) { + rows.push(rowNodes[i]); + tableBody.removeChild(rowNodes[i]); + } + + rows.sort(finalSorter); + + for (i = 0; i < rows.length; i += 1) { + tableBody.appendChild(rows[i]); + } + } + // removes sort indicators for current column being sorted + function removeSortIndicators() { + var col = getNthColumn(currentSort.index), + cls = col.className; + + cls = cls.replace(/ sorted$/, '').replace(/ sorted-desc$/, ''); + col.className = cls; + } + // adds sort indicators for current column being sorted + function addSortIndicators() { + getNthColumn(currentSort.index).className += currentSort.desc + ? ' sorted-desc' + : ' sorted'; + } + // adds event listeners for all sorter widgets + function enableUI() { + var i, + el, + ithSorter = function ithSorter(i) { + var col = cols[i]; + + return function() { + var desc = col.defaultDescSort; + + if (currentSort.index === i) { + desc = !currentSort.desc; + } + sortByIndex(i, desc); + removeSortIndicators(); + currentSort.index = i; + currentSort.desc = desc; + addSortIndicators(); + }; + }; + for (i = 0; i < cols.length; i += 1) { + if (cols[i].sortable) { + // add the click event handler on the th so users + // dont have to click on those tiny arrows + el = getNthColumn(i).querySelector('.sorter').parentElement; + if (el.addEventListener) { + el.addEventListener('click', ithSorter(i)); + } else { + el.attachEvent('onclick', ithSorter(i)); + } + } + } + } + // adds sorting functionality to the UI + return function() { + if (!getTable()) { + return; + } + cols = loadColumns(); + loadData(); + addSearchBox(); + addSortIndicators(); + enableUI(); + }; +})(); + +window.addEventListener('load', addSorting); diff --git a/packages/modules/index/coverage/lcov.info b/packages/modules/index/coverage/lcov.info new file mode 100644 index 0000000000000..eab832ccd7710 --- /dev/null +++ b/packages/modules/index/coverage/lcov.info @@ -0,0 +1,26 @@ +TN: +SF:src/utils/flatten-object-keys.ts +FN:22,flattenObjectKeys +FN:25,flatten +FNF:2 +FNH:2 +FNDA:1,flattenObjectKeys +FNDA:2,flatten +DA:22,1 +DA:23,1 +DA:26,2 +DA:27,5 +DA:28,1 +DA:29,1 +DA:31,4 +DA:36,1 +DA:37,1 +LF:9 +LH:9 +BRDA:27,0,0,1 +BRDA:27,0,1,4 +BRDA:28,1,0,0 +BRDA:28,1,1,1 +BRF:4 +BRH:3 +end_of_record diff --git a/packages/modules/index/integration-tests/__tests__/query-builder.spec.ts b/packages/modules/index/integration-tests/__tests__/query-builder.spec.ts index e6c5fd164c637..f328207e51f9f 100644 --- a/packages/modules/index/integration-tests/__tests__/query-builder.spec.ts +++ b/packages/modules/index/integration-tests/__tests__/query-builder.spec.ts @@ -1,8 +1,8 @@ import { - MedusaAppLoader, configLoader, container, logger, + MedusaAppLoader, } from "@medusajs/framework" import { MedusaAppOutput, MedusaModule } from "@medusajs/modules-sdk" import { IndexTypes } from "@medusajs/types" @@ -287,20 +287,18 @@ describe("IndexModuleService query", function () { afterEach(afterEach_) it("should query all products ordered by sku DESC", async () => { - const [result, count] = await module.queryAndCount( - { - select: { + const [result, count] = await module.queryAndCount({ + fields: ["product.*", "product.variants.*", "product.variants.prices.*"], + pagination: { + orderBy: { product: { variants: { - prices: true, + sku: "DESC", }, }, }, }, - { - orderBy: [{ "product.variants.sku": "DESC" }], - } - ) + }) expect(count).toEqual(2) expect(result).toEqual([ @@ -346,16 +344,14 @@ describe("IndexModuleService query", function () { it("should query products filtering by variant sku", async () => { const result = await module.query({ - select: { + fields: ["product.*", "product.variants.*", "product.variants.prices.*"], + filters: { product: { variants: { - prices: true, + sku: { $like: "aaa%" }, }, }, }, - where: { - "product.variants.sku": { $like: "aaa%" }, - }, }) expect(result).toEqual([ @@ -378,23 +374,20 @@ describe("IndexModuleService query", function () { }) it("should query products filtering by price and returning the complete entity", async () => { - const [result] = await module.queryAndCount( - { - select: { - product: { - variants: { - prices: true, + const [result] = await module.queryAndCount({ + fields: ["product.*", "product.variants.*", "product.variants.prices.*"], + filters: { + product: { + variants: { + prices: { + amount: { $gt: 50 }, }, }, }, - where: { - "product.variants.prices.amount": { $gt: "50" }, - }, }, - { - keepFilteredEntities: true, - } - ) + keepFilteredEntities: true, + }) + expect(result).toEqual([ { id: "prod_1", @@ -426,13 +419,7 @@ describe("IndexModuleService query", function () { it("should query all products", async () => { const [result, count] = await module.queryAndCount({ - select: { - product: { - variants: { - prices: true, - }, - }, - }, + fields: ["product.*", "product.variants.*", "product.variants.prices.*"], }) expect(count).toEqual(2) @@ -477,21 +464,13 @@ describe("IndexModuleService query", function () { }) it("should paginate products", async () => { - const result = await module.query( - { - select: { - product: { - variants: { - prices: true, - }, - }, - }, - }, - { + const result = await module.query({ + fields: ["product.*", "product.variants.*", "product.variants.prices.*"], + pagination: { take: 1, skip: 1, - } - ) + }, + }) expect(result).toEqual([ { @@ -510,16 +489,14 @@ describe("IndexModuleService query", function () { it("should handle null values on where clause", async () => { const result = await module.query({ - select: { + fields: ["product.*", "product.variants.*", "product.variants.prices.*"], + filters: { product: { variants: { - prices: true, + sku: null, }, }, }, - where: { - "product.variants.sku": null, - }, }) expect(result).toEqual([ @@ -539,13 +516,18 @@ describe("IndexModuleService query", function () { it("should query products filtering by deep nested levels", async () => { const [result] = await module.queryAndCount({ - select: { - product: true, - }, - where: { - "product.deep.obj.b": 15, + fields: ["product.*"], + filters: { + product: { + deep: { + obj: { + b: 15, + }, + }, + }, }, }) + expect(result).toEqual([ { id: "prod_2", diff --git a/packages/modules/index/src/services/index-module-service.ts b/packages/modules/index/src/services/index-module-service.ts index e88b8558b9836..5654dc2d83ec7 100644 --- a/packages/modules/index/src/services/index-module-service.ts +++ b/packages/modules/index/src/services/index-module-service.ts @@ -98,15 +98,12 @@ export default class IndexModuleService implements IndexTypes.IIndexService { } } - async query(...args) { - return await this.storageProvider_.query.apply(this.storageProvider_, args) + async query(config: IndexTypes.IndexQueryConfig) { + return await this.storageProvider_.query(config) } - async queryAndCount(...args) { - return await this.storageProvider_.queryAndCount.apply( - this.storageProvider_, - args - ) + async queryAndCount(config: IndexTypes.IndexQueryConfig) { + return await this.storageProvider_.queryAndCount(config) } protected registerListeners() { diff --git a/packages/modules/index/src/services/postgres-provider.ts b/packages/modules/index/src/services/postgres-provider.ts index d93e0e11ba602..2edc76d1dae63 100644 --- a/packages/modules/index/src/services/postgres-provider.ts +++ b/packages/modules/index/src/services/postgres-provider.ts @@ -1,6 +1,7 @@ import { Context, Event, + IndexTypes, RemoteQueryFunction, Subscriber, } from "@medusajs/types" @@ -18,12 +19,12 @@ import { IndexData, IndexRelation } from "@models" import { EntityNameModuleConfigMap, IndexModuleOptions, - QueryFormat, - QueryOptions, SchemaObjectEntityRepresentation, SchemaObjectRepresentation, } from "@types" import { createPartitions, QueryBuilder } from "../utils" +import { flattenObjectKeys } from "../utils/flatten-object-keys" +import { normalizeFieldsSelection } from "../utils/normalize-fields-selection" type InjectedDependencies = { manager: EntityManager @@ -196,18 +197,27 @@ export class PostgresProvider { @InjectManager("baseRepository_") async query( - selection: QueryFormat, - options?: QueryOptions, + config: IndexTypes.IndexQueryConfig, @MedusaContext() sharedContext: Context = {} ) { await this.#isReady_ + const { + keepFilteredEntities, + fields = [], + filters = {}, + joinFilters = {}, + } = config + const { take, skip, orderBy: inputOrderBy = {} } = config.pagination ?? {} + + const select = normalizeFieldsSelection(fields) + const where = flattenObjectKeys(filters) + const joinWhere = flattenObjectKeys(joinFilters) + const orderBy = flattenObjectKeys(inputOrderBy) + const { manager } = sharedContext as { manager: SqlEntityManager } let hasPagination = false - if ( - typeof options?.take === "number" || - typeof options?.skip === "number" - ) { + if (typeof take === "number" || typeof skip === "number") { hasPagination = true } @@ -216,27 +226,38 @@ export class PostgresProvider { schema: this.schemaObjectRepresentation_, entityMap: this.schemaEntitiesMap_, knex: connection.getKnex(), - selector: selection, - options, + selector: { + select, + where, + joinWhere, + }, + options: { + skip, + take, + keepFilteredEntities, + orderBy, + }, }) - const sql = qb.buildQuery(hasPagination, !!options?.keepFilteredEntities) + const sql = qb.buildQuery(hasPagination, !!keepFilteredEntities) let resultset = await manager.execute(sql) - if (options?.keepFilteredEntities) { - const mainEntity = Object.keys(selection.select)[0] + if (keepFilteredEntities) { + const mainEntity = Object.keys(select)[0] const ids = resultset.map((r) => r[`${mainEntity}.id`]) if (ids.length) { const selection_ = { - select: selection.select, - joinWhere: selection.joinWhere, - where: { - [`${mainEntity}.id`]: ids, + fields, + joinFilters: joinFilters, + filters: { + [mainEntity]: { + id: ids, + }, }, } - return await this.query(selection_, undefined, sharedContext) + return await this.query(selection_, sharedContext) } } @@ -245,23 +266,44 @@ export class PostgresProvider { @InjectManager("baseRepository_") async queryAndCount( - selection: QueryFormat, - options?: QueryOptions, + config: IndexTypes.IndexQueryConfig, @MedusaContext() sharedContext: Context = {} ): Promise<[Record[], number, PerformanceEntry]> { await this.#isReady_ + const { + keepFilteredEntities, + fields = [], + filters = {}, + joinFilters = {}, + } = config + const { take, skip, orderBy: inputOrderBy = {} } = config.pagination ?? {} + + const select = normalizeFieldsSelection(fields) + const where = flattenObjectKeys(filters) + const joinWhere = flattenObjectKeys(joinFilters) + const orderBy = flattenObjectKeys(inputOrderBy) + const { manager } = sharedContext as { manager: SqlEntityManager } const connection = manager.getConnection() const qb = new QueryBuilder({ schema: this.schemaObjectRepresentation_, entityMap: this.schemaEntitiesMap_, knex: connection.getKnex(), - selector: selection, - options, + selector: { + select, + where, + joinWhere, + }, + options: { + skip, + take, + keepFilteredEntities, + orderBy, + }, }) - const sql = qb.buildQuery(true, !!options?.keepFilteredEntities) + const sql = qb.buildQuery(true, !!keepFilteredEntities) performance.mark("index-query-start") let resultset = await connection.execute(sql) performance.mark("index-query-end") @@ -273,21 +315,23 @@ export class PostgresProvider { const count = +(resultset[0]?.count ?? 0) - if (options?.keepFilteredEntities) { - const mainEntity = Object.keys(selection.select)[0] + if (keepFilteredEntities) { + const mainEntity = Object.keys(select)[0] const ids = resultset.map((r) => r[`${mainEntity}.id`]) if (ids.length) { - const selection_ = { - select: selection.select, - joinWhere: selection.joinWhere, - where: { - [`${mainEntity}.id`]: ids, + const selection_: Parameters[0] = { + fields, + joinFilters: joinFilters, + filters: { + [mainEntity]: { + id: ids, + }, }, } performance.mark("index-query-start") - resultset = await this.query(selection_, undefined, sharedContext) + resultset = await this.query(selection_, sharedContext) performance.mark("index-query-end") const performanceMesurements = performance.measure( diff --git a/packages/modules/index/src/types/index.ts b/packages/modules/index/src/types/index.ts index 2b5f38cc8ce63..3b6edf949badb 100644 --- a/packages/modules/index/src/types/index.ts +++ b/packages/modules/index/src/types/index.ts @@ -1,4 +1,5 @@ import { + IndexTypes, ModuleJoinerConfig, ModulesSdkTypes, Subscriber, @@ -119,9 +120,11 @@ export interface StorageProvider { onApplicationStart?(): Promise - query(...args): unknown + query(config: IndexTypes.IndexQueryConfig): Promise - queryAndCount(...args): unknown + queryAndCount( + config: IndexTypes.IndexQueryConfig + ): Promise<[any[], number, PerformanceMeasure]> consumeEvent( schemaEntityObjectRepresentation: SchemaObjectEntityRepresentation diff --git a/packages/modules/index/src/utils/__tests__/flatten-object-keys.spec.ts b/packages/modules/index/src/utils/__tests__/flatten-object-keys.spec.ts new file mode 100644 index 0000000000000..1596e4ef21ad7 --- /dev/null +++ b/packages/modules/index/src/utils/__tests__/flatten-object-keys.spec.ts @@ -0,0 +1,29 @@ +import { flattenObjectKeys } from "../flatten-object-keys" + +describe("flattenWhereClauses", () => { + it("should flatten where clauses", () => { + const where = { + a: 1, + b: { + c: 2, + d: 3, + z: { + $ilike: "%test%", + }, + y: null, + }, + e: 4, + } + + const result = flattenObjectKeys(where) + + expect(result).toEqual({ + a: 1, + "b.c": 2, + "b.d": 3, + "b.z": { $ilike: "%test%" }, + "b.y": null, + e: 4, + }) + }) +}) diff --git a/packages/modules/index/src/utils/__tests__/normalize-fields-selcetion.spec.ts b/packages/modules/index/src/utils/__tests__/normalize-fields-selcetion.spec.ts new file mode 100644 index 0000000000000..730465230a82c --- /dev/null +++ b/packages/modules/index/src/utils/__tests__/normalize-fields-selcetion.spec.ts @@ -0,0 +1,22 @@ +import { normalizeFieldsSelection } from "../normalize-fields-selection" + +describe("normalizeFieldsSelection", () => { + it("should normalize fields selection", () => { + const fields = [ + "product.id", + "product.title", + "product.variants.*", + "product.variants.prices.*", + ] + const result = normalizeFieldsSelection(fields) + expect(result).toEqual({ + product: { + id: true, + title: true, + variants: { + prices: true, + }, + }, + }) + }) +}) diff --git a/packages/modules/index/src/utils/flatten-object-keys.ts b/packages/modules/index/src/utils/flatten-object-keys.ts new file mode 100644 index 0000000000000..c0c0e8f0ad076 --- /dev/null +++ b/packages/modules/index/src/utils/flatten-object-keys.ts @@ -0,0 +1,59 @@ +import { OPERATOR_MAP } from "./query-builder" + +/** + * Flatten object keys + * @example + * input: { + * a: 1, + * b: { + * c: 2, + * d: 3, + * }, + * e: 4, + * } + * + * output: { + * a: 1, + * b.c: 2, + * b.d: 3, + * e: 4, + * } + * + * @param where + */ +export function flattenObjectKeys(where: Record) { + const result: Record = {} + + function flatten(obj: Record, path?: string) { + for (const key in obj) { + const isOperatorMap = !!OPERATOR_MAP[key] + + if (!isOperatorMap) { + const newPath = path ? `${path}.${key}` : key + + if (obj[key] === null) { + result[newPath] = null + continue + } + + if (Array.isArray(obj[key])) { + result[newPath] = obj[key] + continue + } + + if (typeof obj[key] === "object" && !isOperatorMap) { + flatten(obj[key], newPath) + continue + } + + result[newPath] = obj[key] + continue + } + + result[path ?? key] = obj + } + } + + flatten(where) + return result +} diff --git a/packages/modules/index/src/utils/normalize-fields-selection.ts b/packages/modules/index/src/utils/normalize-fields-selection.ts new file mode 100644 index 0000000000000..0036b4dcd472e --- /dev/null +++ b/packages/modules/index/src/utils/normalize-fields-selection.ts @@ -0,0 +1,7 @@ +import { objectFromStringPath } from "@medusajs/utils" + +export function normalizeFieldsSelection(fields: string[]) { + const normalizedFields = fields.map((field) => field.replace(/\.\*/g, "")) + const fieldsObject = objectFromStringPath(normalizedFields) + return fieldsObject +} diff --git a/packages/modules/index/src/utils/query-builder.ts b/packages/modules/index/src/utils/query-builder.ts index ad52bcedb5e90..cba83b8f6ecac 100644 --- a/packages/modules/index/src/utils/query-builder.ts +++ b/packages/modules/index/src/utils/query-builder.ts @@ -10,6 +10,19 @@ import { Select, } from "../types" +export const OPERATOR_MAP = { + $eq: "=", + $lt: "<", + $gt: ">", + $lte: "<=", + $gte: ">=", + $ne: "!=", + $in: "IN", + $is: "IS", + $like: "LIKE", + $ilike: "ILIKE", +} + export class QueryBuilder { private readonly structure: Select private readonly entityMap: Record @@ -119,18 +132,6 @@ export class QueryBuilder { obj: object, builder: Knex.QueryBuilder ) { - const OPERATOR_MAP = { - $eq: "=", - $lt: "<", - $gt: ">", - $lte: "<=", - $gte: ">=", - $ne: "!=", - $in: "IN", - $is: "IS", - $like: "LIKE", - $ilike: "ILIKE", - } const keys = Object.keys(obj) const getPathAndField = (key: string) => { From c787575c5c30cbeae7b141b549ad54bebf337d36 Mon Sep 17 00:00:00 2001 From: adrien2p Date: Thu, 19 Sep 2024 12:12:00 +0200 Subject: [PATCH 02/10] rm coverage --- packages/modules/index/coverage/clover.xml | 18 -- .../index/coverage/coverage-final.json | 2 - .../index/coverage/lcov-report/base.css | 224 ------------------ .../coverage/lcov-report/block-navigation.js | 87 ------- .../index/coverage/lcov-report/favicon.png | Bin 445 -> 0 bytes .../lcov-report/flatten-where-clauses.ts.html | 199 ---------------- .../index/coverage/lcov-report/index.html | 116 --------- .../index/coverage/lcov-report/prettify.css | 1 - .../index/coverage/lcov-report/prettify.js | 2 - .../lcov-report/sort-arrow-sprite.png | Bin 138 -> 0 bytes .../index/coverage/lcov-report/sorter.js | 196 --------------- packages/modules/index/coverage/lcov.info | 26 -- 12 files changed, 871 deletions(-) delete mode 100644 packages/modules/index/coverage/clover.xml delete mode 100644 packages/modules/index/coverage/coverage-final.json delete mode 100644 packages/modules/index/coverage/lcov-report/base.css delete mode 100644 packages/modules/index/coverage/lcov-report/block-navigation.js delete mode 100644 packages/modules/index/coverage/lcov-report/favicon.png delete mode 100644 packages/modules/index/coverage/lcov-report/flatten-where-clauses.ts.html delete mode 100644 packages/modules/index/coverage/lcov-report/index.html delete mode 100644 packages/modules/index/coverage/lcov-report/prettify.css delete mode 100644 packages/modules/index/coverage/lcov-report/prettify.js delete mode 100644 packages/modules/index/coverage/lcov-report/sort-arrow-sprite.png delete mode 100644 packages/modules/index/coverage/lcov-report/sorter.js delete mode 100644 packages/modules/index/coverage/lcov.info diff --git a/packages/modules/index/coverage/clover.xml b/packages/modules/index/coverage/clover.xml deleted file mode 100644 index 652b0d15c745c..0000000000000 --- a/packages/modules/index/coverage/clover.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/packages/modules/index/coverage/coverage-final.json b/packages/modules/index/coverage/coverage-final.json deleted file mode 100644 index 05df22285b9fd..0000000000000 --- a/packages/modules/index/coverage/coverage-final.json +++ /dev/null @@ -1,2 +0,0 @@ -{"/Users/adriendeperetti/Documents/02-personnel/01-projects/medusa/packages/modules/index/src/utils/flatten-where-clauses.ts": {"path":"/Users/adriendeperetti/Documents/02-personnel/01-projects/medusa/packages/modules/index/src/utils/flatten-where-clauses.ts","statementMap":{"0":{"start":{"line":22,"column":16},"end":{"line":22,"column":36}},"1":{"start":{"line":23,"column":38},"end":{"line":23,"column":null}},"2":{"start":{"line":26,"column":4},"end":{"line":33,"column":null}},"3":{"start":{"line":27,"column":6},"end":{"line":32,"column":null}},"4":{"start":{"line":28,"column":24},"end":{"line":28,"column":null}},"5":{"start":{"line":29,"column":8},"end":{"line":29,"column":null}},"6":{"start":{"line":31,"column":8},"end":{"line":31,"column":null}},"7":{"start":{"line":36,"column":2},"end":{"line":36,"column":null}},"8":{"start":{"line":37,"column":2},"end":{"line":37,"column":null}}},"fnMap":{"0":{"name":"flattenWhereClauses","decl":{"start":{"line":22,"column":16},"end":{"line":22,"column":36}},"loc":{"start":{"line":22,"column":62},"end":{"line":38,"column":null}}},"1":{"name":"flatten","decl":{"start":{"line":25,"column":11},"end":{"line":25,"column":19}},"loc":{"start":{"line":25,"column":58},"end":{"line":34,"column":null}}}},"branchMap":{"0":{"loc":{"start":{"line":27,"column":6},"end":{"line":32,"column":null}},"type":"if","locations":[{"start":{"line":27,"column":6},"end":{"line":32,"column":null}},{"start":{"line":30,"column":13},"end":{"line":32,"column":null}}]},"1":{"loc":{"start":{"line":28,"column":24},"end":{"line":28,"column":null}},"type":"cond-expr","locations":[{"start":{"line":28,"column":31},"end":{"line":28,"column":47}},{"start":{"line":28,"column":50},"end":{"line":28,"column":null}}]}},"s":{"0":1,"1":1,"2":2,"3":5,"4":1,"5":1,"6":4,"7":1,"8":1},"f":{"0":1,"1":2},"b":{"0":[1,4],"1":[0,1]}} -} diff --git a/packages/modules/index/coverage/lcov-report/base.css b/packages/modules/index/coverage/lcov-report/base.css deleted file mode 100644 index f418035b469af..0000000000000 --- a/packages/modules/index/coverage/lcov-report/base.css +++ /dev/null @@ -1,224 +0,0 @@ -body, html { - margin:0; padding: 0; - height: 100%; -} -body { - font-family: Helvetica Neue, Helvetica, Arial; - font-size: 14px; - color:#333; -} -.small { font-size: 12px; } -*, *:after, *:before { - -webkit-box-sizing:border-box; - -moz-box-sizing:border-box; - box-sizing:border-box; - } -h1 { font-size: 20px; margin: 0;} -h2 { font-size: 14px; } -pre { - font: 12px/1.4 Consolas, "Liberation Mono", Menlo, Courier, monospace; - margin: 0; - padding: 0; - -moz-tab-size: 2; - -o-tab-size: 2; - tab-size: 2; -} -a { color:#0074D9; text-decoration:none; } -a:hover { text-decoration:underline; } -.strong { font-weight: bold; } -.space-top1 { padding: 10px 0 0 0; } -.pad2y { padding: 20px 0; } -.pad1y { padding: 10px 0; } -.pad2x { padding: 0 20px; } -.pad2 { padding: 20px; } -.pad1 { padding: 10px; } -.space-left2 { padding-left:55px; } -.space-right2 { padding-right:20px; } -.center { text-align:center; } -.clearfix { display:block; } -.clearfix:after { - content:''; - display:block; - height:0; - clear:both; - visibility:hidden; - } -.fl { float: left; } -@media only screen and (max-width:640px) { - .col3 { width:100%; max-width:100%; } - .hide-mobile { display:none!important; } -} - -.quiet { - color: #7f7f7f; - color: rgba(0,0,0,0.5); -} -.quiet a { opacity: 0.7; } - -.fraction { - font-family: Consolas, 'Liberation Mono', Menlo, Courier, monospace; - font-size: 10px; - color: #555; - background: #E8E8E8; - padding: 4px 5px; - border-radius: 3px; - vertical-align: middle; -} - -div.path a:link, div.path a:visited { color: #333; } -table.coverage { - border-collapse: collapse; - margin: 10px 0 0 0; - padding: 0; -} - -table.coverage td { - margin: 0; - padding: 0; - vertical-align: top; -} -table.coverage td.line-count { - text-align: right; - padding: 0 5px 0 20px; -} -table.coverage td.line-coverage { - text-align: right; - padding-right: 10px; - min-width:20px; -} - -table.coverage td span.cline-any { - display: inline-block; - padding: 0 5px; - width: 100%; -} -.missing-if-branch { - display: inline-block; - margin-right: 5px; - border-radius: 3px; - position: relative; - padding: 0 4px; - background: #333; - color: yellow; -} - -.skip-if-branch { - display: none; - margin-right: 10px; - position: relative; - padding: 0 4px; - background: #ccc; - color: white; -} -.missing-if-branch .typ, .skip-if-branch .typ { - color: inherit !important; -} -.coverage-summary { - border-collapse: collapse; - width: 100%; -} -.coverage-summary tr { border-bottom: 1px solid #bbb; } -.keyline-all { border: 1px solid #ddd; } -.coverage-summary td, .coverage-summary th { padding: 10px; } -.coverage-summary tbody { border: 1px solid #bbb; } -.coverage-summary td { border-right: 1px solid #bbb; } -.coverage-summary td:last-child { border-right: none; } -.coverage-summary th { - text-align: left; - font-weight: normal; - white-space: nowrap; -} -.coverage-summary th.file { border-right: none !important; } -.coverage-summary th.pct { } -.coverage-summary th.pic, -.coverage-summary th.abs, -.coverage-summary td.pct, -.coverage-summary td.abs { text-align: right; } -.coverage-summary td.file { white-space: nowrap; } -.coverage-summary td.pic { min-width: 120px !important; } -.coverage-summary tfoot td { } - -.coverage-summary .sorter { - height: 10px; - width: 7px; - display: inline-block; - margin-left: 0.5em; - background: url(sort-arrow-sprite.png) no-repeat scroll 0 0 transparent; -} -.coverage-summary .sorted .sorter { - background-position: 0 -20px; -} -.coverage-summary .sorted-desc .sorter { - background-position: 0 -10px; -} -.status-line { height: 10px; } -/* yellow */ -.cbranch-no { background: yellow !important; color: #111; } -/* dark red */ -.red.solid, .status-line.low, .low .cover-fill { background:#C21F39 } -.low .chart { border:1px solid #C21F39 } -.highlighted, -.highlighted .cstat-no, .highlighted .fstat-no, .highlighted .cbranch-no{ - background: #C21F39 !important; -} -/* medium red */ -.cstat-no, .fstat-no, .cbranch-no, .cbranch-no { background:#F6C6CE } -/* light red */ -.low, .cline-no { background:#FCE1E5 } -/* light green */ -.high, .cline-yes { background:rgb(230,245,208) } -/* medium green */ -.cstat-yes { background:rgb(161,215,106) } -/* dark green */ -.status-line.high, .high .cover-fill { background:rgb(77,146,33) } -.high .chart { border:1px solid rgb(77,146,33) } -/* dark yellow (gold) */ -.status-line.medium, .medium .cover-fill { background: #f9cd0b; } -.medium .chart { border:1px solid #f9cd0b; } -/* light yellow */ -.medium { background: #fff4c2; } - -.cstat-skip { background: #ddd; color: #111; } -.fstat-skip { background: #ddd; color: #111 !important; } -.cbranch-skip { background: #ddd !important; color: #111; } - -span.cline-neutral { background: #eaeaea; } - -.coverage-summary td.empty { - opacity: .5; - padding-top: 4px; - padding-bottom: 4px; - line-height: 1; - color: #888; -} - -.cover-fill, .cover-empty { - display:inline-block; - height: 12px; -} -.chart { - line-height: 0; -} -.cover-empty { - background: white; -} -.cover-full { - border-right: none !important; -} -pre.prettyprint { - border: none !important; - padding: 0 !important; - margin: 0 !important; -} -.com { color: #999 !important; } -.ignore-none { color: #999; font-weight: normal; } - -.wrapper { - min-height: 100%; - height: auto !important; - height: 100%; - margin: 0 auto -48px; -} -.footer, .push { - height: 48px; -} diff --git a/packages/modules/index/coverage/lcov-report/block-navigation.js b/packages/modules/index/coverage/lcov-report/block-navigation.js deleted file mode 100644 index cc121302316c8..0000000000000 --- a/packages/modules/index/coverage/lcov-report/block-navigation.js +++ /dev/null @@ -1,87 +0,0 @@ -/* eslint-disable */ -var jumpToCode = (function init() { - // Classes of code we would like to highlight in the file view - var missingCoverageClasses = ['.cbranch-no', '.cstat-no', '.fstat-no']; - - // Elements to highlight in the file listing view - var fileListingElements = ['td.pct.low']; - - // We don't want to select elements that are direct descendants of another match - var notSelector = ':not(' + missingCoverageClasses.join('):not(') + ') > '; // becomes `:not(a):not(b) > ` - - // Selecter that finds elements on the page to which we can jump - var selector = - fileListingElements.join(', ') + - ', ' + - notSelector + - missingCoverageClasses.join(', ' + notSelector); // becomes `:not(a):not(b) > a, :not(a):not(b) > b` - - // The NodeList of matching elements - var missingCoverageElements = document.querySelectorAll(selector); - - var currentIndex; - - function toggleClass(index) { - missingCoverageElements - .item(currentIndex) - .classList.remove('highlighted'); - missingCoverageElements.item(index).classList.add('highlighted'); - } - - function makeCurrent(index) { - toggleClass(index); - currentIndex = index; - missingCoverageElements.item(index).scrollIntoView({ - behavior: 'smooth', - block: 'center', - inline: 'center' - }); - } - - function goToPrevious() { - var nextIndex = 0; - if (typeof currentIndex !== 'number' || currentIndex === 0) { - nextIndex = missingCoverageElements.length - 1; - } else if (missingCoverageElements.length > 1) { - nextIndex = currentIndex - 1; - } - - makeCurrent(nextIndex); - } - - function goToNext() { - var nextIndex = 0; - - if ( - typeof currentIndex === 'number' && - currentIndex < missingCoverageElements.length - 1 - ) { - nextIndex = currentIndex + 1; - } - - makeCurrent(nextIndex); - } - - return function jump(event) { - if ( - document.getElementById('fileSearch') === document.activeElement && - document.activeElement != null - ) { - // if we're currently focused on the search input, we don't want to navigate - return; - } - - switch (event.which) { - case 78: // n - case 74: // j - goToNext(); - break; - case 66: // b - case 75: // k - case 80: // p - goToPrevious(); - break; - } - }; -})(); -window.addEventListener('keydown', jumpToCode); diff --git a/packages/modules/index/coverage/lcov-report/favicon.png b/packages/modules/index/coverage/lcov-report/favicon.png deleted file mode 100644 index c1525b811a167671e9de1fa78aab9f5c0b61cef7..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 445 zcmV;u0Yd(XP))rP{nL}Ln%S7`m{0DjX9TLF* zFCb$4Oi7vyLOydb!7n&^ItCzb-%BoB`=x@N2jll2Nj`kauio%aw_@fe&*}LqlFT43 z8doAAe))z_%=P%v^@JHp3Hjhj^6*Kr_h|g_Gr?ZAa&y>wxHE99Gk>A)2MplWz2xdG zy8VD2J|Uf#EAw*bo5O*PO_}X2Tob{%bUoO2G~T`@%S6qPyc}VkhV}UifBuRk>%5v( z)x7B{I~z*k<7dv#5tC+m{km(D087J4O%+<<;K|qwefb6@GSX45wCK}Sn*> - - - - Code coverage report for flatten-object-keys.ts - - - - - - - - - -
-
-

All files flatten-object-keys.ts

-
- -
- 100% - Statements - 9/9 -
- - -
- 75% - Branches - 3/4 -
- - -
- 100% - Functions - 2/2 -
- - -
- 100% - Lines - 9/9 -
- - -
-

- Press n or j to go to the next uncovered block, b, p or k for the previous block. -

- -
-
-

-
1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 -25 -26 -27 -28 -29 -30 -31 -32 -33 -34 -35 -36 -37 -38 -39  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -1x -1x -  -  -2x -5x -1x -1x -  -4x -  -  -  -  -1x -1x -  - 
/**
- * Flatten where clauses
- * @example
- * input: {
- *   a: 1,
- *   b: {
- *     c: 2,
- *     d: 3,
- *   },
- *   e: 4,
- * }
- *
- * output: {
- *   a: 1,
- *   b.c: 2,
- *   b.d: 3,
- *   e: 4,
- * }
- *
- * @param where
- */
-export function flattenObjectKeys(where: Record<string, any>) {
-  const result: Record<string, any> = {}
- 
-  function flatten(obj: Record<string, any>, path?: string) {
-    for (const key in obj) {
-      if (typeof obj[key] === "object") {
-        const newPath = path ? `${path}.${key}` : key
-        flatten(obj[key], newPath)
-      } else {
-        result[`${path}.${key}`] = obj[key]
-      }
-    }
-  }
- 
-  flatten(where)
-  return result
-}
- 
- -
-
- - - - - - - - \ No newline at end of file diff --git a/packages/modules/index/coverage/lcov-report/index.html b/packages/modules/index/coverage/lcov-report/index.html deleted file mode 100644 index 02fa54c732fd3..0000000000000 --- a/packages/modules/index/coverage/lcov-report/index.html +++ /dev/null @@ -1,116 +0,0 @@ - - - - - - Code coverage report for All files - - - - - - - - - -
-
-

All files

-
- -
- 100% - Statements - 9/9 -
- - -
- 75% - Branches - 3/4 -
- - -
- 100% - Functions - 2/2 -
- - -
- 100% - Lines - 9/9 -
- - -
-

- Press n or j to go to the next uncovered block, b, p or k for the previous block. -

- -
-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FileStatementsBranchesFunctionsLines
flatten-object-keys.ts -
-
100%9/975%3/4100%2/2100%9/9
-
-
-
- - - - - - - - \ No newline at end of file diff --git a/packages/modules/index/coverage/lcov-report/prettify.css b/packages/modules/index/coverage/lcov-report/prettify.css deleted file mode 100644 index b317a7cda31a4..0000000000000 --- a/packages/modules/index/coverage/lcov-report/prettify.css +++ /dev/null @@ -1 +0,0 @@ -.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} diff --git a/packages/modules/index/coverage/lcov-report/prettify.js b/packages/modules/index/coverage/lcov-report/prettify.js deleted file mode 100644 index b3225238f26e3..0000000000000 --- a/packages/modules/index/coverage/lcov-report/prettify.js +++ /dev/null @@ -1,2 +0,0 @@ -/* eslint-disable */ -window.PR_SHOULD_USE_CONTINUATION=true;(function(){var h=["break,continue,do,else,for,if,return,while"];var u=[h,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"];var p=[u,"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"];var l=[p,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"];var x=[p,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"];var R=[x,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"];var r="all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes";var w=[p,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"];var s="caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END";var I=[h,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"];var f=[h,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"];var H=[h,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"];var A=[l,R,w,s+I,f,H];var e=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/;var C="str";var z="kwd";var j="com";var O="typ";var G="lit";var L="pun";var F="pln";var m="tag";var E="dec";var J="src";var P="atn";var n="atv";var N="nocode";var M="(?:^^\\.?|[+-]|\\!|\\!=|\\!==|\\#|\\%|\\%=|&|&&|&&=|&=|\\(|\\*|\\*=|\\+=|\\,|\\-=|\\->|\\/|\\/=|:|::|\\;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|\\?|\\@|\\[|\\^|\\^=|\\^\\^|\\^\\^=|\\{|\\||\\|=|\\|\\||\\|\\|=|\\~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*";function k(Z){var ad=0;var S=false;var ac=false;for(var V=0,U=Z.length;V122)){if(!(al<65||ag>90)){af.push([Math.max(65,ag)|32,Math.min(al,90)|32])}if(!(al<97||ag>122)){af.push([Math.max(97,ag)&~32,Math.min(al,122)&~32])}}}}af.sort(function(av,au){return(av[0]-au[0])||(au[1]-av[1])});var ai=[];var ap=[NaN,NaN];for(var ar=0;arat[0]){if(at[1]+1>at[0]){an.push("-")}an.push(T(at[1]))}}an.push("]");return an.join("")}function W(al){var aj=al.source.match(new RegExp("(?:\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]|\\\\u[A-Fa-f0-9]{4}|\\\\x[A-Fa-f0-9]{2}|\\\\[0-9]+|\\\\[^ux0-9]|\\(\\?[:!=]|[\\(\\)\\^]|[^\\x5B\\x5C\\(\\)\\^]+)","g"));var ah=aj.length;var an=[];for(var ak=0,am=0;ak=2&&ai==="["){aj[ak]=X(ag)}else{if(ai!=="\\"){aj[ak]=ag.replace(/[a-zA-Z]/g,function(ao){var ap=ao.charCodeAt(0);return"["+String.fromCharCode(ap&~32,ap|32)+"]"})}}}}return aj.join("")}var aa=[];for(var V=0,U=Z.length;V=0;){S[ac.charAt(ae)]=Y}}var af=Y[1];var aa=""+af;if(!ag.hasOwnProperty(aa)){ah.push(af);ag[aa]=null}}ah.push(/[\0-\uffff]/);V=k(ah)})();var X=T.length;var W=function(ah){var Z=ah.sourceCode,Y=ah.basePos;var ad=[Y,F];var af=0;var an=Z.match(V)||[];var aj={};for(var ae=0,aq=an.length;ae=5&&"lang-"===ap.substring(0,5);if(am&&!(ai&&typeof ai[1]==="string")){am=false;ap=J}if(!am){aj[ag]=ap}}var ab=af;af+=ag.length;if(!am){ad.push(Y+ab,ap)}else{var al=ai[1];var ak=ag.indexOf(al);var ac=ak+al.length;if(ai[2]){ac=ag.length-ai[2].length;ak=ac-al.length}var ar=ap.substring(5);B(Y+ab,ag.substring(0,ak),W,ad);B(Y+ab+ak,al,q(ar,al),ad);B(Y+ab+ac,ag.substring(ac),W,ad)}}ah.decorations=ad};return W}function i(T){var W=[],S=[];if(T.tripleQuotedStrings){W.push([C,/^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,null,"'\""])}else{if(T.multiLineStrings){W.push([C,/^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,null,"'\"`"])}else{W.push([C,/^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,null,"\"'"])}}if(T.verbatimStrings){S.push([C,/^@\"(?:[^\"]|\"\")*(?:\"|$)/,null])}var Y=T.hashComments;if(Y){if(T.cStyleComments){if(Y>1){W.push([j,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,null,"#"])}else{W.push([j,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/,null,"#"])}S.push([C,/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,null])}else{W.push([j,/^#[^\r\n]*/,null,"#"])}}if(T.cStyleComments){S.push([j,/^\/\/[^\r\n]*/,null]);S.push([j,/^\/\*[\s\S]*?(?:\*\/|$)/,null])}if(T.regexLiterals){var X=("/(?=[^/*])(?:[^/\\x5B\\x5C]|\\x5C[\\s\\S]|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+/");S.push(["lang-regex",new RegExp("^"+M+"("+X+")")])}var V=T.types;if(V){S.push([O,V])}var U=(""+T.keywords).replace(/^ | $/g,"");if(U.length){S.push([z,new RegExp("^(?:"+U.replace(/[\s,]+/g,"|")+")\\b"),null])}W.push([F,/^\s+/,null," \r\n\t\xA0"]);S.push([G,/^@[a-z_$][a-z_$@0-9]*/i,null],[O,/^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\w+_t\b)/,null],[F,/^[a-z_$][a-z_$@0-9]*/i,null],[G,new RegExp("^(?:0x[a-f0-9]+|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)(?:e[+\\-]?\\d+)?)[a-z]*","i"),null,"0123456789"],[F,/^\\[\s\S]?/,null],[L,/^.[^\s\w\.$@\'\"\`\/\#\\]*/,null]);return g(W,S)}var K=i({keywords:A,hashComments:true,cStyleComments:true,multiLineStrings:true,regexLiterals:true});function Q(V,ag){var U=/(?:^|\s)nocode(?:\s|$)/;var ab=/\r\n?|\n/;var ac=V.ownerDocument;var S;if(V.currentStyle){S=V.currentStyle.whiteSpace}else{if(window.getComputedStyle){S=ac.defaultView.getComputedStyle(V,null).getPropertyValue("white-space")}}var Z=S&&"pre"===S.substring(0,3);var af=ac.createElement("LI");while(V.firstChild){af.appendChild(V.firstChild)}var W=[af];function ae(al){switch(al.nodeType){case 1:if(U.test(al.className)){break}if("BR"===al.nodeName){ad(al);if(al.parentNode){al.parentNode.removeChild(al)}}else{for(var an=al.firstChild;an;an=an.nextSibling){ae(an)}}break;case 3:case 4:if(Z){var am=al.nodeValue;var aj=am.match(ab);if(aj){var ai=am.substring(0,aj.index);al.nodeValue=ai;var ah=am.substring(aj.index+aj[0].length);if(ah){var ak=al.parentNode;ak.insertBefore(ac.createTextNode(ah),al.nextSibling)}ad(al);if(!ai){al.parentNode.removeChild(al)}}}break}}function ad(ak){while(!ak.nextSibling){ak=ak.parentNode;if(!ak){return}}function ai(al,ar){var aq=ar?al.cloneNode(false):al;var ao=al.parentNode;if(ao){var ap=ai(ao,1);var an=al.nextSibling;ap.appendChild(aq);for(var am=an;am;am=an){an=am.nextSibling;ap.appendChild(am)}}return aq}var ah=ai(ak.nextSibling,0);for(var aj;(aj=ah.parentNode)&&aj.nodeType===1;){ah=aj}W.push(ah)}for(var Y=0;Y=S){ah+=2}if(V>=ap){Z+=2}}}var t={};function c(U,V){for(var S=V.length;--S>=0;){var T=V[S];if(!t.hasOwnProperty(T)){t[T]=U}else{if(window.console){console.warn("cannot override language handler %s",T)}}}}function q(T,S){if(!(T&&t.hasOwnProperty(T))){T=/^\s*]*(?:>|$)/],[j,/^<\!--[\s\S]*?(?:-\->|$)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],[L,/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]),["default-markup","htm","html","mxml","xhtml","xml","xsl"]);c(g([[F,/^[\s]+/,null," \t\r\n"],[n,/^(?:\"[^\"]*\"?|\'[^\']*\'?)/,null,"\"'"]],[[m,/^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],[P,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/],[L,/^[=<>\/]+/],["lang-js",/^on\w+\s*=\s*\"([^\"]+)\"/i],["lang-js",/^on\w+\s*=\s*\'([^\']+)\'/i],["lang-js",/^on\w+\s*=\s*([^\"\'>\s]+)/i],["lang-css",/^style\s*=\s*\"([^\"]+)\"/i],["lang-css",/^style\s*=\s*\'([^\']+)\'/i],["lang-css",/^style\s*=\s*([^\"\'>\s]+)/i]]),["in.tag"]);c(g([],[[n,/^[\s\S]+/]]),["uq.val"]);c(i({keywords:l,hashComments:true,cStyleComments:true,types:e}),["c","cc","cpp","cxx","cyc","m"]);c(i({keywords:"null,true,false"}),["json"]);c(i({keywords:R,hashComments:true,cStyleComments:true,verbatimStrings:true,types:e}),["cs"]);c(i({keywords:x,cStyleComments:true}),["java"]);c(i({keywords:H,hashComments:true,multiLineStrings:true}),["bsh","csh","sh"]);c(i({keywords:I,hashComments:true,multiLineStrings:true,tripleQuotedStrings:true}),["cv","py"]);c(i({keywords:s,hashComments:true,multiLineStrings:true,regexLiterals:true}),["perl","pl","pm"]);c(i({keywords:f,hashComments:true,multiLineStrings:true,regexLiterals:true}),["rb"]);c(i({keywords:w,cStyleComments:true,regexLiterals:true}),["js"]);c(i({keywords:r,hashComments:3,cStyleComments:true,multilineStrings:true,tripleQuotedStrings:true,regexLiterals:true}),["coffee"]);c(g([],[[C,/^[\s\S]+/]]),["regex"]);function d(V){var U=V.langExtension;try{var S=a(V.sourceNode);var T=S.sourceCode;V.sourceCode=T;V.spans=S.spans;V.basePos=0;q(U,T)(V);D(V)}catch(W){if("console" in window){console.log(W&&W.stack?W.stack:W)}}}function y(W,V,U){var S=document.createElement("PRE");S.innerHTML=W;if(U){Q(S,U)}var T={langExtension:V,numberLines:U,sourceNode:S};d(T);return S.innerHTML}function b(ad){function Y(af){return document.getElementsByTagName(af)}var ac=[Y("pre"),Y("code"),Y("xmp")];var T=[];for(var aa=0;aa=0){var ah=ai.match(ab);var am;if(!ah&&(am=o(aj))&&"CODE"===am.tagName){ah=am.className.match(ab)}if(ah){ah=ah[1]}var al=false;for(var ak=aj.parentNode;ak;ak=ak.parentNode){if((ak.tagName==="pre"||ak.tagName==="code"||ak.tagName==="xmp")&&ak.className&&ak.className.indexOf("prettyprint")>=0){al=true;break}}if(!al){var af=aj.className.match(/\blinenums\b(?::(\d+))?/);af=af?af[1]&&af[1].length?+af[1]:true:false;if(af){Q(aj,af)}S={langExtension:ah,sourceNode:aj,numberLines:af};d(S)}}}if(X]*(?:>|$)/],[PR.PR_COMMENT,/^<\!--[\s\S]*?(?:-\->|$)/],[PR.PR_PUNCTUATION,/^(?:<[%?]|[%?]>)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],["lang-",/^]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-handlebars",/^]*type\s*=\s*['"]?text\/x-handlebars-template['"]?\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-js",/^]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i],[PR.PR_DECLARATION,/^{{[#^>/]?\s*[\w.][^}]*}}/],[PR.PR_DECLARATION,/^{{&?\s*[\w.][^}]*}}/],[PR.PR_DECLARATION,/^{{{>?\s*[\w.][^}]*}}}/],[PR.PR_COMMENT,/^{{![^}]*}}/]]),["handlebars","hbs"]);PR.registerLangHandler(PR.createSimpleLexer([[PR.PR_PLAIN,/^[ \t\r\n\f]+/,null," \t\r\n\f"]],[[PR.PR_STRING,/^\"(?:[^\n\r\f\\\"]|\\(?:\r\n?|\n|\f)|\\[\s\S])*\"/,null],[PR.PR_STRING,/^\'(?:[^\n\r\f\\\']|\\(?:\r\n?|\n|\f)|\\[\s\S])*\'/,null],["lang-css-str",/^url\(([^\)\"\']*)\)/i],[PR.PR_KEYWORD,/^(?:url|rgb|\!important|@import|@page|@media|@charset|inherit)(?=[^\-\w]|$)/i,null],["lang-css-kw",/^(-?(?:[_a-z]|(?:\\[0-9a-f]+ ?))(?:[_a-z0-9\-]|\\(?:\\[0-9a-f]+ ?))*)\s*:/i],[PR.PR_COMMENT,/^\/\*[^*]*\*+(?:[^\/*][^*]*\*+)*\//],[PR.PR_COMMENT,/^(?:)/],[PR.PR_LITERAL,/^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i],[PR.PR_LITERAL,/^#(?:[0-9a-f]{3}){1,2}/i],[PR.PR_PLAIN,/^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i],[PR.PR_PUNCTUATION,/^[^\s\w\'\"]+/]]),["css"]);PR.registerLangHandler(PR.createSimpleLexer([],[[PR.PR_KEYWORD,/^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i]]),["css-kw"]);PR.registerLangHandler(PR.createSimpleLexer([],[[PR.PR_STRING,/^[^\)\"\']+/]]),["css-str"]); diff --git a/packages/modules/index/coverage/lcov-report/sort-arrow-sprite.png b/packages/modules/index/coverage/lcov-report/sort-arrow-sprite.png deleted file mode 100644 index 6ed68316eb3f65dec9063332d2f69bf3093bbfab..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 138 zcmeAS@N?(olHy`uVBq!ia0vp^>_9Bd!3HEZxJ@+%Qh}Z>jv*C{$p!i!8j}?a+@3A= zIAGwzjijN=FBi!|L1t?LM;Q;gkwn>2cAy-KV{dn nf0J1DIvEHQu*n~6U}x}qyky7vi4|9XhBJ7&`njxgN@xNA8m%nc diff --git a/packages/modules/index/coverage/lcov-report/sorter.js b/packages/modules/index/coverage/lcov-report/sorter.js deleted file mode 100644 index 2bb296a8ca8e4..0000000000000 --- a/packages/modules/index/coverage/lcov-report/sorter.js +++ /dev/null @@ -1,196 +0,0 @@ -/* eslint-disable */ -var addSorting = (function() { - 'use strict'; - var cols, - currentSort = { - index: 0, - desc: false - }; - - // returns the summary table element - function getTable() { - return document.querySelector('.coverage-summary'); - } - // returns the thead element of the summary table - function getTableHeader() { - return getTable().querySelector('thead tr'); - } - // returns the tbody element of the summary table - function getTableBody() { - return getTable().querySelector('tbody'); - } - // returns the th element for nth column - function getNthColumn(n) { - return getTableHeader().querySelectorAll('th')[n]; - } - - function onFilterInput() { - const searchValue = document.getElementById('fileSearch').value; - const rows = document.getElementsByTagName('tbody')[0].children; - for (let i = 0; i < rows.length; i++) { - const row = rows[i]; - if ( - row.textContent - .toLowerCase() - .includes(searchValue.toLowerCase()) - ) { - row.style.display = ''; - } else { - row.style.display = 'none'; - } - } - } - - // loads the search box - function addSearchBox() { - var template = document.getElementById('filterTemplate'); - var templateClone = template.content.cloneNode(true); - templateClone.getElementById('fileSearch').oninput = onFilterInput; - template.parentElement.appendChild(templateClone); - } - - // loads all columns - function loadColumns() { - var colNodes = getTableHeader().querySelectorAll('th'), - colNode, - cols = [], - col, - i; - - for (i = 0; i < colNodes.length; i += 1) { - colNode = colNodes[i]; - col = { - key: colNode.getAttribute('data-col'), - sortable: !colNode.getAttribute('data-nosort'), - type: colNode.getAttribute('data-type') || 'string' - }; - cols.push(col); - if (col.sortable) { - col.defaultDescSort = col.type === 'number'; - colNode.innerHTML = - colNode.innerHTML + ''; - } - } - return cols; - } - // attaches a data attribute to every tr element with an object - // of data values keyed by column name - function loadRowData(tableRow) { - var tableCols = tableRow.querySelectorAll('td'), - colNode, - col, - data = {}, - i, - val; - for (i = 0; i < tableCols.length; i += 1) { - colNode = tableCols[i]; - col = cols[i]; - val = colNode.getAttribute('data-value'); - if (col.type === 'number') { - val = Number(val); - } - data[col.key] = val; - } - return data; - } - // loads all row data - function loadData() { - var rows = getTableBody().querySelectorAll('tr'), - i; - - for (i = 0; i < rows.length; i += 1) { - rows[i].data = loadRowData(rows[i]); - } - } - // sorts the table using the data for the ith column - function sortByIndex(index, desc) { - var key = cols[index].key, - sorter = function(a, b) { - a = a.data[key]; - b = b.data[key]; - return a < b ? -1 : a > b ? 1 : 0; - }, - finalSorter = sorter, - tableBody = document.querySelector('.coverage-summary tbody'), - rowNodes = tableBody.querySelectorAll('tr'), - rows = [], - i; - - if (desc) { - finalSorter = function(a, b) { - return -1 * sorter(a, b); - }; - } - - for (i = 0; i < rowNodes.length; i += 1) { - rows.push(rowNodes[i]); - tableBody.removeChild(rowNodes[i]); - } - - rows.sort(finalSorter); - - for (i = 0; i < rows.length; i += 1) { - tableBody.appendChild(rows[i]); - } - } - // removes sort indicators for current column being sorted - function removeSortIndicators() { - var col = getNthColumn(currentSort.index), - cls = col.className; - - cls = cls.replace(/ sorted$/, '').replace(/ sorted-desc$/, ''); - col.className = cls; - } - // adds sort indicators for current column being sorted - function addSortIndicators() { - getNthColumn(currentSort.index).className += currentSort.desc - ? ' sorted-desc' - : ' sorted'; - } - // adds event listeners for all sorter widgets - function enableUI() { - var i, - el, - ithSorter = function ithSorter(i) { - var col = cols[i]; - - return function() { - var desc = col.defaultDescSort; - - if (currentSort.index === i) { - desc = !currentSort.desc; - } - sortByIndex(i, desc); - removeSortIndicators(); - currentSort.index = i; - currentSort.desc = desc; - addSortIndicators(); - }; - }; - for (i = 0; i < cols.length; i += 1) { - if (cols[i].sortable) { - // add the click event handler on the th so users - // dont have to click on those tiny arrows - el = getNthColumn(i).querySelector('.sorter').parentElement; - if (el.addEventListener) { - el.addEventListener('click', ithSorter(i)); - } else { - el.attachEvent('onclick', ithSorter(i)); - } - } - } - } - // adds sorting functionality to the UI - return function() { - if (!getTable()) { - return; - } - cols = loadColumns(); - loadData(); - addSearchBox(); - addSortIndicators(); - enableUI(); - }; -})(); - -window.addEventListener('load', addSorting); diff --git a/packages/modules/index/coverage/lcov.info b/packages/modules/index/coverage/lcov.info deleted file mode 100644 index eab832ccd7710..0000000000000 --- a/packages/modules/index/coverage/lcov.info +++ /dev/null @@ -1,26 +0,0 @@ -TN: -SF:src/utils/flatten-object-keys.ts -FN:22,flattenObjectKeys -FN:25,flatten -FNF:2 -FNH:2 -FNDA:1,flattenObjectKeys -FNDA:2,flatten -DA:22,1 -DA:23,1 -DA:26,2 -DA:27,5 -DA:28,1 -DA:29,1 -DA:31,4 -DA:36,1 -DA:37,1 -LF:9 -LH:9 -BRDA:27,0,0,1 -BRDA:27,0,1,4 -BRDA:28,1,0,0 -BRDA:28,1,1,1 -BRF:4 -BRH:3 -end_of_record From e0153c303a4479b9b6f6c33073adf5e2f645d578 Mon Sep 17 00:00:00 2001 From: adrien2p Date: Thu, 19 Sep 2024 12:12:26 +0200 Subject: [PATCH 03/10] update package.json --- integration-tests/modules/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/integration-tests/modules/package.json b/integration-tests/modules/package.json index 52f626f3060b6..d3af78cd227cb 100644 --- a/integration-tests/modules/package.json +++ b/integration-tests/modules/package.json @@ -5,7 +5,7 @@ "license": "MIT", "private": true, "scripts": { - "test:integration": "NODE_OPTIONS=--experimental-vm-modules jest --no-cache --maxWorkers=50% --bail --detectOpenHandles --forceExit --logHeapUsage -- __tests__/index/*.spec.ts", + "test:integration": "NODE_OPTIONS=--experimental-vm-modules jest --no-cache --maxWorkers=50% --bail --detectOpenHandles --forceExit --logHeapUsage", "test:integration:chunk": "NODE_OPTIONS=--experimental-vm-modules jest --silent --no-cache --bail --maxWorkers=50% --forceExit --testPathPattern=$(echo $CHUNKS | jq -r \".[${CHUNK}] | .[]\")", "build": "tsc --allowJs --outDir ./dist" }, From 1c75fb6e673c1f92393ab9f8af1e54edf0f5098e Mon Sep 17 00:00:00 2001 From: adrien2p Date: Thu, 19 Sep 2024 14:00:15 +0200 Subject: [PATCH 04/10] Add typings support over the API --- .../modules/__tests__/index/search.spec.ts | 11 ++- .../src/utils/gql-schema-to-types.ts | 20 +++-- .../index-service-entry-points.ts | 63 +++++++++++++++ .../types/src/index/__tests__/index.spec.ts | 59 ++++++++++++++ .../src/index/index-service-entry-points.ts | 4 + packages/core/types/src/index/index.ts | 3 + packages/core/types/src/index/operator-map.ts | 12 +++ .../types/src/index/query-config/common.ts | 9 +++ .../types/src/index/query-config/index.ts | 4 + .../query-config/query-input-config-fields.ts | 58 ++++++++++++++ .../query-input-config-filters.ts | 66 +++++++++++++++ .../query-input-config-order-by.ts | 67 ++++++++++++++++ .../index/query-config/query-input-config.ts | 22 +++++ packages/core/types/src/index/service.ts | 25 ++---- packages/framework/framework/package.json | 2 +- packages/medusa/src/commands/start.ts | 1 + packages/modules/index/.gitignore | 1 + .../__tests__/index-engine-module.spec.ts | 5 +- packages/modules/index/package.json | 4 +- .../src/services/index-module-service.ts | 12 ++- .../index/src/services/postgres-provider.ts | 8 +- packages/modules/index/src/types/index.ts | 8 +- .../modules/index/src/utils/build-config.ts | 2 +- .../modules/index/src/utils/default-schema.ts | 2 +- .../index/src/utils/flatten-object-keys.ts | 38 ++++----- .../modules/index/src/utils/gql-to-types.ts | 80 +++++++++++++++++++ packages/modules/index/tsconfig.build.json | 2 +- packages/modules/index/tsconfig.json | 4 +- packages/modules/index/tsconfig.spec.json | 8 ++ 29 files changed, 530 insertions(+), 70 deletions(-) create mode 100644 packages/core/types/src/index/__fixtures__/index-service-entry-points.ts create mode 100644 packages/core/types/src/index/__tests__/index.spec.ts create mode 100644 packages/core/types/src/index/index-service-entry-points.ts create mode 100644 packages/core/types/src/index/operator-map.ts create mode 100644 packages/core/types/src/index/query-config/common.ts create mode 100644 packages/core/types/src/index/query-config/index.ts create mode 100644 packages/core/types/src/index/query-config/query-input-config-fields.ts create mode 100644 packages/core/types/src/index/query-config/query-input-config-filters.ts create mode 100644 packages/core/types/src/index/query-config/query-input-config-order-by.ts create mode 100644 packages/core/types/src/index/query-config/query-input-config.ts create mode 100644 packages/modules/index/src/utils/gql-to-types.ts create mode 100644 packages/modules/index/tsconfig.spec.json diff --git a/integration-tests/modules/__tests__/index/search.spec.ts b/integration-tests/modules/__tests__/index/search.spec.ts index 72aa0e2066c37..c16cf7646a8f5 100644 --- a/integration-tests/modules/__tests__/index/search.spec.ts +++ b/integration-tests/modules/__tests__/index/search.spec.ts @@ -58,7 +58,7 @@ medusaIntegrationTestRunner({ // Timeout to allow indexing to finish await setTimeout(2000) - const [results, count] = await indexEngine.queryAndCount({ + const [results, count] = await indexEngine.queryAndCount<"product">({ fields: [ "product.*", "product.variants.*", @@ -128,7 +128,7 @@ medusaIntegrationTestRunner({ // Timeout to allow indexing to finish await setTimeout(2000) - const [results, count] = await indexEngine.queryAndCount({ + const [results, count] = await indexEngine.queryAndCount<"product">({ fields: [ "product.*", "product.variants.*", @@ -228,11 +228,10 @@ medusaIntegrationTestRunner({ }, } - await indexEngine.queryAndCount(queryArgs) + await indexEngine.queryAndCount<"product">(queryArgs) - const [results, count, perf] = await indexEngine.queryAndCount( - queryArgs - ) + const [results, count, perf] = + await indexEngine.queryAndCount<"product">(queryArgs) console.log(perf) }) diff --git a/packages/core/modules-sdk/src/utils/gql-schema-to-types.ts b/packages/core/modules-sdk/src/utils/gql-schema-to-types.ts index d1a464bb2ee44..dd7cbffd2ec07 100644 --- a/packages/core/modules-sdk/src/utils/gql-schema-to-types.ts +++ b/packages/core/modules-sdk/src/utils/gql-schema-to-types.ts @@ -1,5 +1,5 @@ import { MedusaModule } from "../medusa-module" -import { FileSystem } from "@medusajs/utils" +import { FileSystem, toCamelCase } from "@medusajs/utils" import { GraphQLSchema } from "graphql/type" import { parse, printSchema } from "graphql" import { codegen } from "@graphql-codegen/core" @@ -21,13 +21,13 @@ function buildEntryPointsTypeMap( return aliases.flatMap((alias) => { const names = Array.isArray(alias.name) ? alias.name : [alias.name] - const entity = alias.args?.["entity"] + const entity = alias?.["entity"] return names.map((aliasItem) => { return { entryPoint: aliasItem, entityType: entity ? schema.includes(`export type ${entity} `) - ? alias.args?.["entity"] + ? alias?.["entity"] : "any" : "any", } @@ -39,9 +39,11 @@ function buildEntryPointsTypeMap( async function generateTypes({ outputDir, + filename, config, }: { outputDir: string + filename: string config: Parameters[0] }) { const fileSystem = new FileSystem(outputDir) @@ -49,9 +51,11 @@ async function generateTypes({ let output = await codegen(config) const entryPoints = buildEntryPointsTypeMap(output) + const interfaceName = toCamelCase(filename) + const remoteQueryEntryPoints = ` declare module '@medusajs/types' { - interface RemoteQueryEntryPoints { + interface ${interfaceName} { ${entryPoints .map((entry) => ` ${entry.entryPoint}: ${entry.entityType}`) .join("\n")} @@ -60,19 +64,21 @@ ${entryPoints output += remoteQueryEntryPoints - await fileSystem.create("remote-query-types.d.ts", output) + await fileSystem.create(filename + ".d.ts", output) await fileSystem.create( "index.d.ts", - "export * as RemoteQueryTypes from './remote-query-types'" + `export * as ${interfaceName}Types from './${filename}'` ) } export async function gqlSchemaToTypes({ schema, outputDir, + filename, }: { schema: GraphQLSchema outputDir: string + filename: string }) { const config = { documents: [], @@ -98,5 +104,5 @@ export async function gqlSchemaToTypes({ }, } - await generateTypes({ outputDir, config }) + await generateTypes({ outputDir, filename, config }) } diff --git a/packages/core/types/src/index/__fixtures__/index-service-entry-points.ts b/packages/core/types/src/index/__fixtures__/index-service-entry-points.ts new file mode 100644 index 0000000000000..42aec29043a3c --- /dev/null +++ b/packages/core/types/src/index/__fixtures__/index-service-entry-points.ts @@ -0,0 +1,63 @@ +export type Maybe = T | null +export type InputMaybe = Maybe +export type Exact = { + [K in keyof T]: T[K] +} +export type MakeOptional = Omit & { + [SubKey in K]?: Maybe +} +export type MakeMaybe = Omit & { + [SubKey in K]: Maybe +} +export type MakeEmpty< + T extends { [key: string]: unknown }, + K extends keyof T +> = { [_ in K]?: never } +export type Incremental = + | T + | { + [P in keyof T]?: P extends " $fragmentName" | "__typename" ? T[P] : never + } +/** All built-in and custom scalars, mapped to their actual values */ +export type Scalars = { + ID: { input: string; output: string } + String: { input: string; output: string } + Boolean: { input: boolean; output: boolean } + Int: { input: number; output: number } + Float: { input: number; output: number } +} + +export type Product = { + __typename?: "Product" + id?: Maybe + title?: Maybe + variants?: Maybe>> +} + +export type ProductVariant = { + __typename?: "ProductVariant" + id?: Maybe + product_id?: Maybe + sku?: Maybe + prices?: Maybe>> +} + +export type Price = { + __typename?: "Price" + amount?: Maybe +} + +export interface FixtureEntryPoints { + product_variant: ProductVariant + product_variants: ProductVariant + variant: ProductVariant + variants: ProductVariant + product: Product + products: Product + price: Price + prices: Price +} + +declare module "../index-service-entry-points" { + interface IndexServiceEntryPoints extends FixtureEntryPoints {} +} diff --git a/packages/core/types/src/index/__tests__/index.spec.ts b/packages/core/types/src/index/__tests__/index.spec.ts new file mode 100644 index 0000000000000..f3500dc929d2d --- /dev/null +++ b/packages/core/types/src/index/__tests__/index.spec.ts @@ -0,0 +1,59 @@ +import { expectTypeOf } from "expect-type" +import "../__fixtures__/index-service-entry-points" +import { OperatorMap } from "../operator-map" +import { IndexQueryConfig, OrderBy } from "../query-config" + +describe("IndexQueryConfig", () => { + it("should infer the config types properly", async () => { + type IndexConfig = IndexQueryConfig<"product"> + + expectTypeOf().toEqualTypeOf< + ( + | "id" + | "title" + | "variants.*" + | "variants.id" + | "variants.product_id" + | "variants.sku" + | "variants.prices.*" + | "variants.prices.amount" + )[] + >() + + expectTypeOf().toEqualTypeOf< + | { + id?: string | string[] | OperatorMap + title?: string | string[] | OperatorMap + variants?: { + id?: string | string[] | OperatorMap + product_id?: string | string[] | OperatorMap + sku?: string | string[] | OperatorMap + prices?: { + amount?: number | number[] | OperatorMap + } + } + } + | undefined + >() + + expectTypeOf().toEqualTypeOf< + | { + skip?: number + take?: number + orderBy?: { + id?: OrderBy + title?: OrderBy + variants?: { + id?: OrderBy + product_id?: OrderBy + sku?: OrderBy + prices?: { + amount?: OrderBy + } + } + } + } + | undefined + >() + }) +}) diff --git a/packages/core/types/src/index/index-service-entry-points.ts b/packages/core/types/src/index/index-service-entry-points.ts new file mode 100644 index 0000000000000..fb524e53f2b60 --- /dev/null +++ b/packages/core/types/src/index/index-service-entry-points.ts @@ -0,0 +1,4 @@ +/** + * Bucket filled with map of entry point -> types that are autogenerated by the codegen from the config schema + */ +export interface IndexServiceEntryPoints {} diff --git a/packages/core/types/src/index/index.ts b/packages/core/types/src/index/index.ts index 9376fea807351..21cc028ad5890 100644 --- a/packages/core/types/src/index/index.ts +++ b/packages/core/types/src/index/index.ts @@ -1 +1,4 @@ export * from "./service" +export * from "./index-service-entry-points" +export * from "./query-config" +export * from "./operator-map" diff --git a/packages/core/types/src/index/operator-map.ts b/packages/core/types/src/index/operator-map.ts new file mode 100644 index 0000000000000..d1e0ddb8bf7a0 --- /dev/null +++ b/packages/core/types/src/index/operator-map.ts @@ -0,0 +1,12 @@ +export type OperatorMap = { + $eq: T + $lt: T + $lte: T + $gt: T + $gte: T + $ne: T + $in: T + $is: T + $like: T + $ilike: T +} diff --git a/packages/core/types/src/index/query-config/common.ts b/packages/core/types/src/index/query-config/common.ts new file mode 100644 index 0000000000000..f357af314487d --- /dev/null +++ b/packages/core/types/src/index/query-config/common.ts @@ -0,0 +1,9 @@ +import { Prettify } from "../../common" + +export type ExcludedProps = "__typename" +export type Depth = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] +export type CleanupObject = Prettify, ExcludedProps>> +export type OmitNever = { + [K in keyof T as TypeOnly extends never ? never : K]: T[K] +} +export type TypeOnly = Required> diff --git a/packages/core/types/src/index/query-config/index.ts b/packages/core/types/src/index/query-config/index.ts new file mode 100644 index 0000000000000..f0add4110b0c5 --- /dev/null +++ b/packages/core/types/src/index/query-config/index.ts @@ -0,0 +1,4 @@ +export * from "./query-input-config" +export * from "./query-input-config-fields" +export * from "./query-input-config-filters" +export * from "./query-input-config-order-by" diff --git a/packages/core/types/src/index/query-config/query-input-config-fields.ts b/packages/core/types/src/index/query-config/query-input-config-fields.ts new file mode 100644 index 0000000000000..5def2e1e49283 --- /dev/null +++ b/packages/core/types/src/index/query-config/query-input-config-fields.ts @@ -0,0 +1,58 @@ +import { ExcludedProps, TypeOnly } from "./common" + +type Marker = [never, 0, 1, 2, 3, 4] + +type RawBigNumberPrefix = "raw_" + +type ExpandStarSelector< + T extends object, + Depth extends number, + Exclusion extends string[] +> = ObjectToIndexFields + +/** + * Output an array of strings representing the path to each leaf node in an object + */ +export type ObjectToIndexFields< + MaybeT, + Depth extends number = 2, + Exclusion extends string[] = [], + T = TypeOnly +> = Depth extends never + ? never + : T extends object + ? { + [K in keyof T]: K extends // handle big number + `${RawBigNumberPrefix}${string}` + ? Exclude + : // Special props that should be excluded + K extends ExcludedProps + ? never + : // Prevent recursive reference to itself + K extends Exclusion[number] + ? never + : TypeOnly extends Array + ? TypeOnly extends Date + ? Exclude + : TypeOnly extends { __typename: any } + ? `${Exclude}.${ExpandStarSelector< + TypeOnly, + Marker[Depth], + [K & string, ...Exclusion] + >}` + : TypeOnly extends object + ? Exclude + : never + : TypeOnly extends Date + ? Exclude + : TypeOnly extends { __typename: any } + ? `${Exclude}.${ExpandStarSelector< + TypeOnly, + Marker[Depth], + [K & string, ...Exclusion] + >}` + : T[K] extends object + ? Exclude + : Exclude + }[keyof T] + : never diff --git a/packages/core/types/src/index/query-config/query-input-config-filters.ts b/packages/core/types/src/index/query-config/query-input-config-filters.ts new file mode 100644 index 0000000000000..d26a49a0f1250 --- /dev/null +++ b/packages/core/types/src/index/query-config/query-input-config-filters.ts @@ -0,0 +1,66 @@ +import { Prettify } from "../../common" +import { IndexServiceEntryPoints } from "../index-service-entry-points" +import { OperatorMap } from "../operator-map" +import { + CleanupObject, + Depth, + ExcludedProps, + OmitNever, + TypeOnly, +} from "./common" + +type ExtractFiltersOperators< + MaybeT, + Lim extends number = Depth[2], + Exclusion extends string[] = [], + T = TypeOnly +> = { + [Key in keyof T]?: Key extends Exclusion[number] + ? never + : Key extends ExcludedProps + ? never + : TypeOnly extends string | number | boolean | Date + ? TypeOnly | TypeOnly[] | OperatorMap> + : TypeOnly extends Array + ? TypeOnly extends { __typename: any } + ? IndexFilters + : TypeOnly extends object + ? CleanupObject> + : never + : TypeOnly extends { __typename: any } + ? IndexFilters< + Key & string, + T[Key], + [Key & string, ...Exclusion], + Depth[Lim] + > + : TypeOnly extends object + ? CleanupObject> + : never +} + +/** + * Extract all available filters from an index entry point deeply + */ +export type IndexFilters< + TEntry extends string, + IndexEntryPointsLevel = IndexServiceEntryPoints, + Exclusion extends string[] = [], + Lim extends number = Depth[3] +> = Lim extends number + ? TEntry extends keyof IndexEntryPointsLevel + ? TypeOnly extends Array + ? Prettify< + OmitNever> + > + : Prettify< + OmitNever< + ExtractFiltersOperators< + IndexEntryPointsLevel[TEntry], + Lim, + [TEntry, ...Exclusion] + > + > + > + : Record + : never diff --git a/packages/core/types/src/index/query-config/query-input-config-order-by.ts b/packages/core/types/src/index/query-config/query-input-config-order-by.ts new file mode 100644 index 0000000000000..d106b7b49de14 --- /dev/null +++ b/packages/core/types/src/index/query-config/query-input-config-order-by.ts @@ -0,0 +1,67 @@ +import { Prettify } from "../../common" +import { IndexServiceEntryPoints } from "../index-service-entry-points" +import { + CleanupObject, + Depth, + ExcludedProps, + OmitNever, + TypeOnly, +} from "./common" + +export type OrderBy = "ASC" | "DESC" | 1 | -1 | true | false + +type ExtractOrderByOperators< + MaybeT, + Lim extends number = Depth[2], + Exclusion extends string[] = [], + T = TypeOnly +> = { + [Key in keyof T]?: Key extends Exclusion[number] + ? never + : Key extends ExcludedProps + ? never + : TypeOnly extends string | number | boolean | Date + ? OrderBy + : TypeOnly extends Array + ? TypeOnly extends { __typename: any } + ? IndexOrderBy + : TypeOnly extends object + ? CleanupObject> + : never + : TypeOnly extends { __typename: any } + ? IndexOrderBy< + Key & string, + T[Key], + [Key & string, ...Exclusion], + Depth[Lim] + > + : TypeOnly extends object + ? CleanupObject> + : never +} + +/** + * Extract all available orderBy from a remote entry point deeply + */ +export type IndexOrderBy< + TEntry extends string, + IndexEntryPointsLevel = IndexServiceEntryPoints, + Exclusion extends string[] = [], + Lim extends number = Depth[3] +> = Lim extends number + ? TEntry extends keyof IndexEntryPointsLevel + ? TypeOnly extends Array + ? Prettify< + OmitNever> + > + : Prettify< + OmitNever< + ExtractOrderByOperators< + IndexEntryPointsLevel[TEntry], + Lim, + [TEntry, ...Exclusion] + > + > + > + : Record + : never diff --git a/packages/core/types/src/index/query-config/query-input-config.ts b/packages/core/types/src/index/query-config/query-input-config.ts new file mode 100644 index 0000000000000..a9d1382299cd5 --- /dev/null +++ b/packages/core/types/src/index/query-config/query-input-config.ts @@ -0,0 +1,22 @@ +import { ObjectToIndexFields } from "./query-input-config-fields" +import { IndexFilters } from "./query-input-config-filters" +import { IndexOrderBy } from "./query-input-config-order-by" +import { IndexServiceEntryPoints } from "../index-service-entry-points" + +export type IndexQueryConfig = { + fields: ObjectToIndexFields< + IndexServiceEntryPoints[TEntry & keyof IndexServiceEntryPoints] + > extends never + ? string[] + : ObjectToIndexFields< + IndexServiceEntryPoints[TEntry & keyof IndexServiceEntryPoints] + >[] + filters?: IndexFilters + joinFilters?: IndexFilters + pagination?: { + skip?: number + take?: number + orderBy?: IndexOrderBy + } + keepFilteredEntities?: boolean +} diff --git a/packages/core/types/src/index/service.ts b/packages/core/types/src/index/service.ts index d66d47f5293b4..e8b212151bbc7 100644 --- a/packages/core/types/src/index/service.ts +++ b/packages/core/types/src/index/service.ts @@ -1,24 +1,11 @@ import { IModuleService } from "../modules-sdk" - -type OrderBy = { - [key: string]: OrderBy | "ASC" | "DESC" | 1 | -1 | true | false -} - -export type IndexQueryConfig = { - fields: string[] - filters?: Record - joinFilters?: Record - pagination?: { - skip?: number - take?: number - orderBy?: OrderBy - } - keepFilteredEntities?: boolean -} +import { IndexQueryConfig } from "./query-config" export interface IIndexService extends IModuleService { - query(config: IndexQueryConfig): Promise - queryAndCount( - config: IndexQueryConfig + query( + config: IndexQueryConfig + ): Promise + queryAndCount( + config: IndexQueryConfig ): Promise<[any[], number, PerformanceMeasure]> } diff --git a/packages/framework/framework/package.json b/packages/framework/framework/package.json index fa3288ea5e69e..de83acc01e091 100644 --- a/packages/framework/framework/package.json +++ b/packages/framework/framework/package.json @@ -33,7 +33,7 @@ "scripts": { "watch": "tsc --watch -p ./tsconfig.build.json", "watch:test": "tsc --build tsconfig.spec.json --watch", - "build": "rimraf dist && tsc --noEmit && tsc -p ./tsconfig.build.json && tsc-alias -p ./tsconfig.build.json", + "build": "rimraf dist && tsc -p ./tsconfig.spec.json --noEmit && tsc -p ./tsconfig.build.json && tsc-alias -p ./tsconfig.build.json", "test": "jest --runInBand --bail --passWithNoTests --forceExit -- src", "test:integration": "jest --forceExit -- integration-tests/**/__tests__/**/*.ts" }, diff --git a/packages/medusa/src/commands/start.ts b/packages/medusa/src/commands/start.ts index bfdbdf312fc26..014bdcde67237 100644 --- a/packages/medusa/src/commands/start.ts +++ b/packages/medusa/src/commands/start.ts @@ -64,6 +64,7 @@ async function start({ port, directory, types }) { const outputDirGeneratedTypes = path.join(directory, ".medusa") await gqlSchemaToTypes({ outputDir: outputDirGeneratedTypes, + filename: "remote-query-entry-points", schema: gqlSchema, }) logger.info("Geneated modules types") diff --git a/packages/modules/index/.gitignore b/packages/modules/index/.gitignore index 874c6c69d3341..093a7e7910313 100644 --- a/packages/modules/index/.gitignore +++ b/packages/modules/index/.gitignore @@ -4,3 +4,4 @@ node_modules .env* .env *.sql +**/.generated \ No newline at end of file diff --git a/packages/modules/index/integration-tests/__tests__/index-engine-module.spec.ts b/packages/modules/index/integration-tests/__tests__/index-engine-module.spec.ts index c240f6a3b8369..2bbda759d0ef7 100644 --- a/packages/modules/index/integration-tests/__tests__/index-engine-module.spec.ts +++ b/packages/modules/index/integration-tests/__tests__/index-engine-module.spec.ts @@ -1,8 +1,8 @@ import { - MedusaAppLoader, configLoader, container, logger, + MedusaAppLoader, } from "@medusajs/framework" import { MedusaAppOutput, MedusaModule } from "@medusajs/modules-sdk" import { EventBusTypes } from "@medusajs/types" @@ -34,6 +34,7 @@ const linkId = "link_id_1" const sendEvents = async (eventDataToEmit) => { let a = 0 + remoteQueryMock.mockImplementation((query) => { query = query.__value if (query.product) { @@ -235,7 +236,7 @@ describe("IndexModuleService", function () { afterEach(afterEach_) - it("should create the corresponding index entries and index relation entries", async function () { + it.only("should create the corresponding index entries and index relation entries", async function () { expect(remoteQueryMock).toHaveBeenCalledTimes(6) /** diff --git a/packages/modules/index/package.json b/packages/modules/index/package.json index 929c79a2a983e..e984bd236f22e 100644 --- a/packages/modules/index/package.json +++ b/packages/modules/index/package.json @@ -23,9 +23,9 @@ "scripts": { "watch": "tsc --build --watch", "watch:test": "tsc --build tsconfig.spec.json --watch", - "build": "rimraf dist && tsc --noEmit && tsc -p ./tsconfig.build.json && tsc-alias -p ./tsconfig.build.json", + "build": "rimraf dist && tsc -p ./tsconfig.spec.json --noEmit && tsc -p ./tsconfig.build.json && tsc-alias -p ./tsconfig.build.json", "test": "jest --passWithNoTests ./src", - "test:integration": "jest --runInBand --forceExit -- integration-tests/**/__tests__/**/*.ts", + "test:integration": "jest --runInBand --forceExit -- integration-tests/__tests__/index-engine-module.spec.ts", "migration:generate": " MIKRO_ORM_CLI=./mikro-orm.config.dev.ts mikro-orm migration:generate", "migration:initial": " MIKRO_ORM_CLI=./mikro-orm.config.dev.ts mikro-orm migration:create --initial", "migration:create": " MIKRO_ORM_CLI=./mikro-orm.config.dev.ts mikro-orm migration:create", diff --git a/packages/modules/index/src/services/index-module-service.ts b/packages/modules/index/src/services/index-module-service.ts index 5654dc2d83ec7..6329b296fa348 100644 --- a/packages/modules/index/src/services/index-module-service.ts +++ b/packages/modules/index/src/services/index-module-service.ts @@ -17,6 +17,7 @@ import { } from "@types" import { buildSchemaObjectRepresentation } from "../utils/build-config" import { defaultSchema } from "../utils/default-schema" +import { gqlSchemaToTypes } from "../utils/gql-to-types" type InjectedDependencies = { [Modules.EVENT_BUS]: IEventBusModuleService @@ -93,16 +94,22 @@ export default class IndexModuleService implements IndexTypes.IIndexService { if (this.storageProvider_.onApplicationStart) { await this.storageProvider_.onApplicationStart() } + + await gqlSchemaToTypes(this.moduleOptions_.schema ?? defaultSchema) } catch (e) { console.log(e) } } - async query(config: IndexTypes.IndexQueryConfig) { + async query( + config: IndexTypes.IndexQueryConfig + ) { return await this.storageProvider_.query(config) } - async queryAndCount(config: IndexTypes.IndexQueryConfig) { + async queryAndCount( + config: IndexTypes.IndexQueryConfig + ) { return await this.storageProvider_.queryAndCount(config) } @@ -133,6 +140,7 @@ export default class IndexModuleService implements IndexTypes.IIndexService { const [objectRepresentation, entityMap] = buildSchemaObjectRepresentation( this.moduleOptions_.schema ?? defaultSchema ) + this.schemaObjectRepresentation_ = objectRepresentation this.schemaEntitiesMap_ = entityMap diff --git a/packages/modules/index/src/services/postgres-provider.ts b/packages/modules/index/src/services/postgres-provider.ts index 2edc76d1dae63..8da0d216de512 100644 --- a/packages/modules/index/src/services/postgres-provider.ts +++ b/packages/modules/index/src/services/postgres-provider.ts @@ -196,8 +196,8 @@ export class PostgresProvider { } @InjectManager("baseRepository_") - async query( - config: IndexTypes.IndexQueryConfig, + async query( + config: IndexTypes.IndexQueryConfig, @MedusaContext() sharedContext: Context = {} ) { await this.#isReady_ @@ -265,8 +265,8 @@ export class PostgresProvider { } @InjectManager("baseRepository_") - async queryAndCount( - config: IndexTypes.IndexQueryConfig, + async queryAndCount( + config: IndexTypes.IndexQueryConfig, @MedusaContext() sharedContext: Context = {} ): Promise<[Record[], number, PerformanceEntry]> { await this.#isReady_ diff --git a/packages/modules/index/src/types/index.ts b/packages/modules/index/src/types/index.ts index 3b6edf949badb..597605302c47d 100644 --- a/packages/modules/index/src/types/index.ts +++ b/packages/modules/index/src/types/index.ts @@ -120,10 +120,12 @@ export interface StorageProvider { onApplicationStart?(): Promise - query(config: IndexTypes.IndexQueryConfig): Promise + query( + config: IndexTypes.IndexQueryConfig + ): Promise - queryAndCount( - config: IndexTypes.IndexQueryConfig + queryAndCount( + config: IndexTypes.IndexQueryConfig ): Promise<[any[], number, PerformanceMeasure]> consumeEvent( diff --git a/packages/modules/index/src/utils/build-config.ts b/packages/modules/index/src/utils/build-config.ts index f62f2546a960a..2c75ba8fbed51 100644 --- a/packages/modules/index/src/utils/build-config.ts +++ b/packages/modules/index/src/utils/build-config.ts @@ -27,7 +27,7 @@ export const CustomDirectives = { }, } -function makeSchemaExecutable(inputSchema: string) { +export function makeSchemaExecutable(inputSchema: string) { const { schema: cleanedSchema } = cleanGraphQLSchema(inputSchema) return makeExecutableSchema({ typeDefs: cleanedSchema }) diff --git a/packages/modules/index/src/utils/default-schema.ts b/packages/modules/index/src/utils/default-schema.ts index 5602901a53539..d788375ff3721 100644 --- a/packages/modules/index/src/utils/default-schema.ts +++ b/packages/modules/index/src/utils/default-schema.ts @@ -1,5 +1,5 @@ export const defaultSchema = ` - type Product @Listeners(values: ["Product.product.created", "Product.product.updated", "Product.product.deleted"]) { + type Product @Listeners(values: ["Product.product.created", "Product.product.updated", "Product.product.deleted"]) { id: String title: String variants: [ProductVariant] diff --git a/packages/modules/index/src/utils/flatten-object-keys.ts b/packages/modules/index/src/utils/flatten-object-keys.ts index c0c0e8f0ad076..3f7387e7503e0 100644 --- a/packages/modules/index/src/utils/flatten-object-keys.ts +++ b/packages/modules/index/src/utils/flatten-object-keys.ts @@ -19,41 +19,41 @@ import { OPERATOR_MAP } from "./query-builder" * e: 4, * } * - * @param where + * @param input */ -export function flattenObjectKeys(where: Record) { +export function flattenObjectKeys(input: Record) { const result: Record = {} function flatten(obj: Record, path?: string) { for (const key in obj) { const isOperatorMap = !!OPERATOR_MAP[key] - if (!isOperatorMap) { - const newPath = path ? `${path}.${key}` : key - - if (obj[key] === null) { - result[newPath] = null - continue - } + if (isOperatorMap) { + result[path ?? key] = obj + continue + } - if (Array.isArray(obj[key])) { - result[newPath] = obj[key] - continue - } + const newPath = path ? `${path}.${key}` : key - if (typeof obj[key] === "object" && !isOperatorMap) { - flatten(obj[key], newPath) - continue - } + if (obj[key] === null) { + result[newPath] = null + continue + } + if (Array.isArray(obj[key])) { result[newPath] = obj[key] continue } - result[path ?? key] = obj + if (typeof obj[key] === "object" && !isOperatorMap) { + flatten(obj[key], newPath) + continue + } + + result[newPath] = obj[key] } } - flatten(where) + flatten(input) return result } diff --git a/packages/modules/index/src/utils/gql-to-types.ts b/packages/modules/index/src/utils/gql-to-types.ts new file mode 100644 index 0000000000000..8569910e86020 --- /dev/null +++ b/packages/modules/index/src/utils/gql-to-types.ts @@ -0,0 +1,80 @@ +import { join } from "path" +import { CustomDirectives, makeSchemaExecutable } from "./build-config" +import { + gqlSchemaToTypes as ModulesSdkGqlSchemaToTypes, + MedusaModule, +} from "@medusajs/modules-sdk" +import { FileSystem } from "@medusajs/utils" + +export async function gqlSchemaToTypes(schema: string) { + const augmentedSchema = CustomDirectives.Listeners.definition + schema + const executableSchema = makeSchemaExecutable(augmentedSchema) + const filename = "index-service-entry-points" + const filenameWithExt = filename + ".d.ts" + + await ModulesSdkGqlSchemaToTypes({ + schema: executableSchema, + filename, + outputDir: join(__dirname, "../.generated"), + }) + + const fileSystem = new FileSystem(join(__dirname, "../.generated")) + let content = await fileSystem.contents(filenameWithExt) + + await fileSystem.remove(filenameWithExt) + + const entryPoints = buildEntryPointsTypeMap(content) + + const indexEntryPoints = ` +declare module '@medusajs/types' { + interface IndexServiceEntryPoints { +${entryPoints + .map((entry) => ` ${entry.entryPoint}: ${entry.entityType}`) + .join("\n")} + } +}` + + const contentToReplaceMatcher = new RegExp( + `declare\\s+module\\s+['"][^'"]+['"]\\s*{([^}]*?)}\\s+}`, + "gm" + ) + content = content.replace(contentToReplaceMatcher, indexEntryPoints) + + await fileSystem.create(filenameWithExt, content) +} + +function buildEntryPointsTypeMap( + schema: string +): { entryPoint: string; entityType: any }[] { + // build map entry point to there type to be merged and used by the remote query + + const joinerConfigs = MedusaModule.getAllJoinerConfigs() + return joinerConfigs + .flatMap((config) => { + const aliases = Array.isArray(config.alias) + ? config.alias + : config.alias + ? [config.alias] + : [] + + return aliases.flatMap((alias) => { + const names = Array.isArray(alias.name) ? alias.name : [alias.name] + const entity = alias?.["entity"] + return names.map((aliasItem) => { + if (!schema.includes(`export type ${entity} `)) { + return + } + + return { + entryPoint: aliasItem, + entityType: entity + ? schema.includes(`export type ${entity} `) + ? alias?.["entity"] + : "any" + : "any", + } + }) + }) + }) + .filter(Boolean) as { entryPoint: string; entityType: any }[] +} diff --git a/packages/modules/index/tsconfig.build.json b/packages/modules/index/tsconfig.build.json index 2ce34105bc7bc..0b60e58d9e28d 100644 --- a/packages/modules/index/tsconfig.build.json +++ b/packages/modules/index/tsconfig.build.json @@ -7,5 +7,5 @@ "src/**/__mocks__", "src/**/__fixtures__", "node_modules" - ], + ] } diff --git a/packages/modules/index/tsconfig.json b/packages/modules/index/tsconfig.json index d2d0a73270b36..973ab438309fc 100644 --- a/packages/modules/index/tsconfig.json +++ b/packages/modules/index/tsconfig.json @@ -27,9 +27,9 @@ "@types": ["./src/types"] } }, - "include": ["src", "integration-tests"], + "include": ["src", "**/.generated"], "exclude": [ "dist", "node_modules" - ] + ], } diff --git a/packages/modules/index/tsconfig.spec.json b/packages/modules/index/tsconfig.spec.json new file mode 100644 index 0000000000000..48e47e8cbb3be --- /dev/null +++ b/packages/modules/index/tsconfig.spec.json @@ -0,0 +1,8 @@ +{ + "extends": "./tsconfig.json", + "include": ["src", "integration-tests"], + "exclude": ["node_modules", "dist"], + "compilerOptions": { + "sourceMap": true + } +} From 722c25c4c817c8e4f19528e3da55d467bcf7d838 Mon Sep 17 00:00:00 2001 From: adrien2p Date: Thu, 19 Sep 2024 14:07:16 +0200 Subject: [PATCH 05/10] Add typings support over the API --- packages/core/types/src/index/service.ts | 2 +- packages/modules/index/tsconfig.json | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/packages/core/types/src/index/service.ts b/packages/core/types/src/index/service.ts index e8b212151bbc7..083ed4db82fac 100644 --- a/packages/core/types/src/index/service.ts +++ b/packages/core/types/src/index/service.ts @@ -5,7 +5,7 @@ export interface IIndexService extends IModuleService { query( config: IndexQueryConfig ): Promise - queryAndCount( + queryAndCount>( config: IndexQueryConfig ): Promise<[any[], number, PerformanceMeasure]> } diff --git a/packages/modules/index/tsconfig.json b/packages/modules/index/tsconfig.json index 973ab438309fc..0a17220a30dd0 100644 --- a/packages/modules/index/tsconfig.json +++ b/packages/modules/index/tsconfig.json @@ -20,6 +20,9 @@ "downlevelIteration": true, // to use ES5 specific tooling "baseUrl": ".", "resolveJsonModule": true, + "types": [ + "dist/.generated/index-service-entry-points.d.ts" + ], "paths": { "@models": ["./src/models"], "@services": ["./src/services"], @@ -27,7 +30,7 @@ "@types": ["./src/types"] } }, - "include": ["src", "**/.generated"], + "include": ["src", "dist/.generated"], "exclude": [ "dist", "node_modules" From 64c16e1398a8acaf0c7eb6a44a8370443d83d0d2 Mon Sep 17 00:00:00 2001 From: adrien2p Date: Thu, 19 Sep 2024 14:33:26 +0200 Subject: [PATCH 06/10] Add typings support over the API --- integration-tests/modules/.gitignore | 2 +- integration-tests/modules/package.json | 2 +- integration-tests/modules/tsconfig.json | 2 +- .../src/utils/gql-schema-to-types.ts | 18 ++++++++++++++---- packages/modules/index/.gitignore | 2 +- .../modules/index/src/utils/gql-to-types.ts | 6 ++++-- packages/modules/index/tsconfig.json | 5 +---- 7 files changed, 23 insertions(+), 14 deletions(-) diff --git a/integration-tests/modules/.gitignore b/integration-tests/modules/.gitignore index a2c424c8764fd..6393d4a090705 100644 --- a/integration-tests/modules/.gitignore +++ b/integration-tests/modules/.gitignore @@ -1,4 +1,4 @@ dist/ node_modules *yarn-error.log - +.medusa diff --git a/integration-tests/modules/package.json b/integration-tests/modules/package.json index d3af78cd227cb..884e377718731 100644 --- a/integration-tests/modules/package.json +++ b/integration-tests/modules/package.json @@ -5,7 +5,7 @@ "license": "MIT", "private": true, "scripts": { - "test:integration": "NODE_OPTIONS=--experimental-vm-modules jest --no-cache --maxWorkers=50% --bail --detectOpenHandles --forceExit --logHeapUsage", + "test:integration": "NODE_OPTIONS=--experimental-vm-modules jest --no-cache --maxWorkers=50% --bail --detectOpenHandles --forceExit --logHeapUsage -- __tests__/index/search.spec.ts", "test:integration:chunk": "NODE_OPTIONS=--experimental-vm-modules jest --silent --no-cache --bail --maxWorkers=50% --forceExit --testPathPattern=$(echo $CHUNKS | jq -r \".[${CHUNK}] | .[]\")", "build": "tsc --allowJs --outDir ./dist" }, diff --git a/integration-tests/modules/tsconfig.json b/integration-tests/modules/tsconfig.json index 13e3b455220bc..c17aadfdd5e3e 100644 --- a/integration-tests/modules/tsconfig.json +++ b/integration-tests/modules/tsconfig.json @@ -19,7 +19,7 @@ "skipLibCheck": true, "downlevelIteration": true // to use ES5 specific tooling }, - "include": ["src"], + "include": ["src", "./medusa/**/*"], "exclude": [ "./dist/**/*", "__tests__", diff --git a/packages/core/modules-sdk/src/utils/gql-schema-to-types.ts b/packages/core/modules-sdk/src/utils/gql-schema-to-types.ts index dd7cbffd2ec07..675a4c8dbb5ca 100644 --- a/packages/core/modules-sdk/src/utils/gql-schema-to-types.ts +++ b/packages/core/modules-sdk/src/utils/gql-schema-to-types.ts @@ -65,10 +65,20 @@ ${entryPoints output += remoteQueryEntryPoints await fileSystem.create(filename + ".d.ts", output) - await fileSystem.create( - "index.d.ts", - `export * as ${interfaceName}Types from './${filename}'` - ) + + const doesBarrelExists = await fileSystem.exists("index.d.ts") + if (!doesBarrelExists) { + await fileSystem.create( + "index.d.ts", + `export * as ${interfaceName}Types from './${filename}'` + ) + } else { + const content = await fileSystem.contents("index.d.ts") + if (!content.includes(`${interfaceName}Types`)) { + const newContent = `export * as ${interfaceName}Types from './${filename}'\n${content}` + await fileSystem.create("index.d.ts", newContent) + } + } } export async function gqlSchemaToTypes({ diff --git a/packages/modules/index/.gitignore b/packages/modules/index/.gitignore index 093a7e7910313..dbbe8014f159c 100644 --- a/packages/modules/index/.gitignore +++ b/packages/modules/index/.gitignore @@ -4,4 +4,4 @@ node_modules .env* .env *.sql -**/.generated \ No newline at end of file +.medusa \ No newline at end of file diff --git a/packages/modules/index/src/utils/gql-to-types.ts b/packages/modules/index/src/utils/gql-to-types.ts index 8569910e86020..51f996d0cdffb 100644 --- a/packages/modules/index/src/utils/gql-to-types.ts +++ b/packages/modules/index/src/utils/gql-to-types.ts @@ -5,20 +5,22 @@ import { MedusaModule, } from "@medusajs/modules-sdk" import { FileSystem } from "@medusajs/utils" +import * as process from "process" export async function gqlSchemaToTypes(schema: string) { const augmentedSchema = CustomDirectives.Listeners.definition + schema const executableSchema = makeSchemaExecutable(augmentedSchema) const filename = "index-service-entry-points" const filenameWithExt = filename + ".d.ts" + const dir = join(process.cwd(), ".medusa") await ModulesSdkGqlSchemaToTypes({ schema: executableSchema, filename, - outputDir: join(__dirname, "../.generated"), + outputDir: dir, }) - const fileSystem = new FileSystem(join(__dirname, "../.generated")) + const fileSystem = new FileSystem(dir) let content = await fileSystem.contents(filenameWithExt) await fileSystem.remove(filenameWithExt) diff --git a/packages/modules/index/tsconfig.json b/packages/modules/index/tsconfig.json index 0a17220a30dd0..3965587692e3a 100644 --- a/packages/modules/index/tsconfig.json +++ b/packages/modules/index/tsconfig.json @@ -20,9 +20,6 @@ "downlevelIteration": true, // to use ES5 specific tooling "baseUrl": ".", "resolveJsonModule": true, - "types": [ - "dist/.generated/index-service-entry-points.d.ts" - ], "paths": { "@models": ["./src/models"], "@services": ["./src/services"], @@ -30,7 +27,7 @@ "@types": ["./src/types"] } }, - "include": ["src", "dist/.generated"], + "include": ["src"], "exclude": [ "dist", "node_modules" From a76d9be5ec2fc641f96203b870a5eba8ad9eeacf Mon Sep 17 00:00:00 2001 From: adrien2p Date: Thu, 19 Sep 2024 14:34:43 +0200 Subject: [PATCH 07/10] rm specific file --- integration-tests/modules/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/integration-tests/modules/package.json b/integration-tests/modules/package.json index 884e377718731..d3af78cd227cb 100644 --- a/integration-tests/modules/package.json +++ b/integration-tests/modules/package.json @@ -5,7 +5,7 @@ "license": "MIT", "private": true, "scripts": { - "test:integration": "NODE_OPTIONS=--experimental-vm-modules jest --no-cache --maxWorkers=50% --bail --detectOpenHandles --forceExit --logHeapUsage -- __tests__/index/search.spec.ts", + "test:integration": "NODE_OPTIONS=--experimental-vm-modules jest --no-cache --maxWorkers=50% --bail --detectOpenHandles --forceExit --logHeapUsage", "test:integration:chunk": "NODE_OPTIONS=--experimental-vm-modules jest --silent --no-cache --bail --maxWorkers=50% --forceExit --testPathPattern=$(echo $CHUNKS | jq -r \".[${CHUNK}] | .[]\")", "build": "tsc --allowJs --outDir ./dist" }, From 2bb9c603e94819fc1b5944f66141d770f1483409 Mon Sep 17 00:00:00 2001 From: adrien2p Date: Thu, 19 Sep 2024 14:50:14 +0200 Subject: [PATCH 08/10] rename order by to order --- integration-tests/modules/__tests__/index/search.spec.ts | 6 +++--- .../core/types/src/index/query-config/query-input-config.ts | 2 +- .../index/integration-tests/__tests__/query-builder.spec.ts | 2 +- packages/modules/index/src/services/postgres-provider.ts | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/integration-tests/modules/__tests__/index/search.spec.ts b/integration-tests/modules/__tests__/index/search.spec.ts index c16cf7646a8f5..f8f70d58b5a96 100644 --- a/integration-tests/modules/__tests__/index/search.spec.ts +++ b/integration-tests/modules/__tests__/index/search.spec.ts @@ -74,7 +74,7 @@ medusaIntegrationTestRunner({ }, }, pagination: { - orderBy: { + order: { product: { variants: { prices: { @@ -144,7 +144,7 @@ medusaIntegrationTestRunner({ }, }, pagination: { - orderBy: { + order: { product: { variants: { prices: { @@ -216,7 +216,7 @@ medusaIntegrationTestRunner({ }, }, pagination: { - orderBy: { + order: { product: { variants: { prices: { diff --git a/packages/core/types/src/index/query-config/query-input-config.ts b/packages/core/types/src/index/query-config/query-input-config.ts index a9d1382299cd5..93fe9f930951b 100644 --- a/packages/core/types/src/index/query-config/query-input-config.ts +++ b/packages/core/types/src/index/query-config/query-input-config.ts @@ -16,7 +16,7 @@ export type IndexQueryConfig = { pagination?: { skip?: number take?: number - orderBy?: IndexOrderBy + order?: IndexOrderBy } keepFilteredEntities?: boolean } diff --git a/packages/modules/index/integration-tests/__tests__/query-builder.spec.ts b/packages/modules/index/integration-tests/__tests__/query-builder.spec.ts index f328207e51f9f..2cf3871019655 100644 --- a/packages/modules/index/integration-tests/__tests__/query-builder.spec.ts +++ b/packages/modules/index/integration-tests/__tests__/query-builder.spec.ts @@ -290,7 +290,7 @@ describe("IndexModuleService query", function () { const [result, count] = await module.queryAndCount({ fields: ["product.*", "product.variants.*", "product.variants.prices.*"], pagination: { - orderBy: { + order: { product: { variants: { sku: "DESC", diff --git a/packages/modules/index/src/services/postgres-provider.ts b/packages/modules/index/src/services/postgres-provider.ts index 8da0d216de512..03dc1e92c0794 100644 --- a/packages/modules/index/src/services/postgres-provider.ts +++ b/packages/modules/index/src/services/postgres-provider.ts @@ -208,7 +208,7 @@ export class PostgresProvider { filters = {}, joinFilters = {}, } = config - const { take, skip, orderBy: inputOrderBy = {} } = config.pagination ?? {} + const { take, skip, order: inputOrderBy = {} } = config.pagination ?? {} const select = normalizeFieldsSelection(fields) const where = flattenObjectKeys(filters) @@ -277,7 +277,7 @@ export class PostgresProvider { filters = {}, joinFilters = {}, } = config - const { take, skip, orderBy: inputOrderBy = {} } = config.pagination ?? {} + const { take, skip, order: inputOrderBy = {} } = config.pagination ?? {} const select = normalizeFieldsSelection(fields) const where = flattenObjectKeys(filters) From 605d46097b798393b87db47bd5744620b8f70a25 Mon Sep 17 00:00:00 2001 From: adrien2p Date: Thu, 19 Sep 2024 14:51:09 +0200 Subject: [PATCH 09/10] rename order by to order --- packages/core/types/src/index/__tests__/index.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/core/types/src/index/__tests__/index.spec.ts b/packages/core/types/src/index/__tests__/index.spec.ts index f3500dc929d2d..3e2b387e12b13 100644 --- a/packages/core/types/src/index/__tests__/index.spec.ts +++ b/packages/core/types/src/index/__tests__/index.spec.ts @@ -40,7 +40,7 @@ describe("IndexQueryConfig", () => { | { skip?: number take?: number - orderBy?: { + order?: { id?: OrderBy title?: OrderBy variants?: { From 631166372acdb43eec9401798c3cb9105182196d Mon Sep 17 00:00:00 2001 From: adrien2p Date: Thu, 19 Sep 2024 14:59:24 +0200 Subject: [PATCH 10/10] fix integration --- .../modules/__tests__/index/search.spec.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/integration-tests/modules/__tests__/index/search.spec.ts b/integration-tests/modules/__tests__/index/search.spec.ts index f8f70d58b5a96..23e2be07e40d5 100644 --- a/integration-tests/modules/__tests__/index/search.spec.ts +++ b/integration-tests/modules/__tests__/index/search.spec.ts @@ -143,13 +143,13 @@ medusaIntegrationTestRunner({ }, }, }, - pagination: { - order: { - product: { - variants: { - prices: { - amount: "DESC", - }, + }, + pagination: { + order: { + product: { + variants: { + prices: { + amount: "DESC", }, }, },