@teleporthq/teleport-plugin-next-data-source 0.43.66 → 0.43.68

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (334) hide show
  1. package/__tests__/array-mapper-cache-wiring.test.ts +11 -0
  2. package/__tests__/array-overlap-sql.test.ts +53 -0
  3. package/__tests__/blog-post-page-enrichment.test.ts +214 -0
  4. package/__tests__/browser-row-policy.test.ts +503 -0
  5. package/__tests__/data-source-cache-wrapping.test.ts +18 -2
  6. package/__tests__/data-source-request-locale.test.ts +313 -0
  7. package/__tests__/ecommerce-product-options.test.ts +206 -0
  8. package/__tests__/ecommerce-product-pages.test.ts +82 -0
  9. package/__tests__/ecommerce-product-pre-options.golden.json +505 -0
  10. package/__tests__/ecommerce-product-storefront-contract.test.ts +293 -0
  11. package/__tests__/ecommerce-product-subscriptions.test.ts +121 -0
  12. package/__tests__/fetchers.test.ts +2 -2
  13. package/__tests__/gated-data-provider.test.ts +88 -0
  14. package/__tests__/items-path.test.ts +150 -0
  15. package/__tests__/localized-columns.test.ts +217 -0
  16. package/__tests__/numbered-pagination.test.ts +15 -0
  17. package/__tests__/product-filter-fields.ts +230 -0
  18. package/__tests__/product-filter-sql.fixture.json +7 -0
  19. package/__tests__/product-options-storefront.fixture.json +2510 -0
  20. package/__tests__/product-page-url-fixtures.json +25 -0
  21. package/__tests__/product-price-sort.ts +4 -2
  22. package/__tests__/raw-rows-mode.test.ts +111 -0
  23. package/__tests__/refetch-loading-state.test.ts +23 -0
  24. package/__tests__/rest-api-response-cache.test.ts +434 -0
  25. package/__tests__/search-clear-button.test.ts +122 -0
  26. package/__tests__/table-read-route-protected-tables.test.ts +493 -0
  27. package/dist/cjs/array-overlap-sql.d.ts +21 -0
  28. package/dist/cjs/array-overlap-sql.d.ts.map +1 -0
  29. package/dist/cjs/array-overlap-sql.js +25 -0
  30. package/dist/cjs/array-overlap-sql.js.map +1 -0
  31. package/dist/cjs/content-localization.d.ts +37 -0
  32. package/dist/cjs/content-localization.d.ts.map +1 -0
  33. package/dist/cjs/content-localization.js +29 -0
  34. package/dist/cjs/content-localization.js.map +1 -0
  35. package/dist/cjs/count-effect.d.ts +11 -1
  36. package/dist/cjs/count-effect.d.ts.map +1 -1
  37. package/dist/cjs/count-effect.js +30 -2
  38. package/dist/cjs/count-effect.js.map +1 -1
  39. package/dist/cjs/data-source-fetchers.d.ts.map +1 -1
  40. package/dist/cjs/data-source-fetchers.js +10 -4
  41. package/dist/cjs/data-source-fetchers.js.map +1 -1
  42. package/dist/cjs/fetchers/airtable.d.ts.map +1 -1
  43. package/dist/cjs/fetchers/airtable.js +1 -1
  44. package/dist/cjs/fetchers/airtable.js.map +1 -1
  45. package/dist/cjs/fetchers/clickhouse.d.ts.map +1 -1
  46. package/dist/cjs/fetchers/clickhouse.js +1 -1
  47. package/dist/cjs/fetchers/clickhouse.js.map +1 -1
  48. package/dist/cjs/fetchers/firestore.d.ts.map +1 -1
  49. package/dist/cjs/fetchers/firestore.js +1 -1
  50. package/dist/cjs/fetchers/firestore.js.map +1 -1
  51. package/dist/cjs/fetchers/javascript.d.ts.map +1 -1
  52. package/dist/cjs/fetchers/javascript.js +1 -1
  53. package/dist/cjs/fetchers/javascript.js.map +1 -1
  54. package/dist/cjs/fetchers/mariadb.d.ts.map +1 -1
  55. package/dist/cjs/fetchers/mariadb.js +1 -1
  56. package/dist/cjs/fetchers/mariadb.js.map +1 -1
  57. package/dist/cjs/fetchers/mongodb.d.ts.map +1 -1
  58. package/dist/cjs/fetchers/mongodb.js +1 -1
  59. package/dist/cjs/fetchers/mongodb.js.map +1 -1
  60. package/dist/cjs/fetchers/mysql.d.ts.map +1 -1
  61. package/dist/cjs/fetchers/mysql.js +1 -1
  62. package/dist/cjs/fetchers/mysql.js.map +1 -1
  63. package/dist/cjs/fetchers/postgresql.d.ts +1 -1
  64. package/dist/cjs/fetchers/postgresql.d.ts.map +1 -1
  65. package/dist/cjs/fetchers/postgresql.js +9 -4
  66. package/dist/cjs/fetchers/postgresql.js.map +1 -1
  67. package/dist/cjs/fetchers/raw-query.d.ts +8 -1
  68. package/dist/cjs/fetchers/raw-query.d.ts.map +1 -1
  69. package/dist/cjs/fetchers/raw-query.js +42 -4
  70. package/dist/cjs/fetchers/raw-query.js.map +1 -1
  71. package/dist/cjs/fetchers/redshift.d.ts.map +1 -1
  72. package/dist/cjs/fetchers/redshift.js +1 -1
  73. package/dist/cjs/fetchers/redshift.js.map +1 -1
  74. package/dist/cjs/fetchers/rest-api.d.ts.map +1 -1
  75. package/dist/cjs/fetchers/rest-api.js +7 -2
  76. package/dist/cjs/fetchers/rest-api.js.map +1 -1
  77. package/dist/cjs/fetchers/teleport.d.ts.map +1 -1
  78. package/dist/cjs/fetchers/teleport.js +16 -6
  79. package/dist/cjs/fetchers/teleport.js.map +1 -1
  80. package/dist/cjs/fetchers/turso.d.ts.map +1 -1
  81. package/dist/cjs/fetchers/turso.js +1 -1
  82. package/dist/cjs/fetchers/turso.js.map +1 -1
  83. package/dist/cjs/fetchers/utils/browser-row-policy.d.ts +43 -0
  84. package/dist/cjs/fetchers/utils/browser-row-policy.d.ts.map +1 -0
  85. package/dist/cjs/fetchers/utils/browser-row-policy.js +66 -0
  86. package/dist/cjs/fetchers/utils/browser-row-policy.js.map +1 -0
  87. package/dist/cjs/fetchers/utils/request-sql-guards.d.ts +8 -0
  88. package/dist/cjs/fetchers/utils/request-sql-guards.d.ts.map +1 -0
  89. package/dist/cjs/fetchers/utils/request-sql-guards.js +12 -0
  90. package/dist/cjs/fetchers/utils/request-sql-guards.js.map +1 -0
  91. package/dist/cjs/fetchers/utils/rest-api-response-cache.d.ts +40 -0
  92. package/dist/cjs/fetchers/utils/rest-api-response-cache.d.ts.map +1 -0
  93. package/dist/cjs/fetchers/utils/rest-api-response-cache.js +64 -0
  94. package/dist/cjs/fetchers/utils/rest-api-response-cache.js.map +1 -0
  95. package/dist/cjs/fetchers/utils/table-access-guard.d.ts +23 -0
  96. package/dist/cjs/fetchers/utils/table-access-guard.d.ts.map +1 -0
  97. package/dist/cjs/fetchers/utils/table-access-guard.js +34 -0
  98. package/dist/cjs/fetchers/utils/table-access-guard.js.map +1 -0
  99. package/dist/cjs/index.d.ts +5 -0
  100. package/dist/cjs/index.d.ts.map +1 -1
  101. package/dist/cjs/index.js +60 -8
  102. package/dist/cjs/index.js.map +1 -1
  103. package/dist/cjs/items-path.d.ts +10 -0
  104. package/dist/cjs/items-path.d.ts.map +1 -0
  105. package/dist/cjs/items-path.js +86 -0
  106. package/dist/cjs/items-path.js.map +1 -0
  107. package/dist/cjs/loading-state.d.ts +16 -1
  108. package/dist/cjs/loading-state.d.ts.map +1 -1
  109. package/dist/cjs/loading-state.js +69 -3
  110. package/dist/cjs/loading-state.js.map +1 -1
  111. package/dist/cjs/localized-columns.d.ts +56 -0
  112. package/dist/cjs/localized-columns.d.ts.map +1 -0
  113. package/dist/cjs/localized-columns.js +137 -0
  114. package/dist/cjs/localized-columns.js.map +1 -0
  115. package/dist/cjs/pagination-plugin.d.ts.map +1 -1
  116. package/dist/cjs/pagination-plugin.js +140 -50
  117. package/dist/cjs/pagination-plugin.js.map +1 -1
  118. package/dist/cjs/product-filter-fields.d.ts +87 -0
  119. package/dist/cjs/product-filter-fields.d.ts.map +1 -0
  120. package/dist/cjs/product-filter-fields.js +161 -0
  121. package/dist/cjs/product-filter-fields.js.map +1 -0
  122. package/dist/cjs/request-locale.d.ts +49 -0
  123. package/dist/cjs/request-locale.d.ts.map +1 -0
  124. package/dist/cjs/request-locale.js +130 -0
  125. package/dist/cjs/request-locale.js.map +1 -0
  126. package/dist/cjs/search-clear.d.ts +31 -0
  127. package/dist/cjs/search-clear.d.ts.map +1 -0
  128. package/dist/cjs/search-clear.js +103 -0
  129. package/dist/cjs/search-clear.js.map +1 -0
  130. package/dist/cjs/transformations/blog-adjacent-posts.d.ts +16 -0
  131. package/dist/cjs/transformations/blog-adjacent-posts.d.ts.map +1 -0
  132. package/dist/cjs/transformations/blog-adjacent-posts.js +25 -0
  133. package/dist/cjs/transformations/blog-adjacent-posts.js.map +1 -0
  134. package/dist/cjs/transformations/blog-comments.d.ts +30 -0
  135. package/dist/cjs/transformations/blog-comments.d.ts.map +1 -0
  136. package/dist/cjs/transformations/blog-comments.js +34 -0
  137. package/dist/cjs/transformations/blog-comments.js.map +1 -0
  138. package/dist/cjs/transformations/blog-post.d.ts +2 -0
  139. package/dist/cjs/transformations/blog-post.d.ts.map +1 -1
  140. package/dist/cjs/transformations/blog-post.js +4 -1
  141. package/dist/cjs/transformations/blog-post.js.map +1 -1
  142. package/dist/cjs/transformations/ecommerce-product.d.ts +9 -1
  143. package/dist/cjs/transformations/ecommerce-product.d.ts.map +1 -1
  144. package/dist/cjs/transformations/ecommerce-product.js +28 -1
  145. package/dist/cjs/transformations/ecommerce-product.js.map +1 -1
  146. package/dist/cjs/transformations/heading-anchors.d.ts +25 -0
  147. package/dist/cjs/transformations/heading-anchors.d.ts.map +1 -0
  148. package/dist/cjs/transformations/heading-anchors.js +29 -0
  149. package/dist/cjs/transformations/heading-anchors.js.map +1 -0
  150. package/dist/cjs/transformations/index.d.ts +61 -4
  151. package/dist/cjs/transformations/index.d.ts.map +1 -1
  152. package/dist/cjs/transformations/index.js +69 -19
  153. package/dist/cjs/transformations/index.js.map +1 -1
  154. package/dist/cjs/transformations/shared-utils.d.ts.map +1 -1
  155. package/dist/cjs/transformations/shared-utils.js +1 -1
  156. package/dist/cjs/transformations/shared-utils.js.map +1 -1
  157. package/dist/cjs/tsconfig.tsbuildinfo +1 -1
  158. package/dist/cjs/utils.d.ts +11 -1
  159. package/dist/cjs/utils.d.ts.map +1 -1
  160. package/dist/cjs/utils.js +60 -16
  161. package/dist/cjs/utils.js.map +1 -1
  162. package/dist/esm/array-overlap-sql.d.ts +21 -0
  163. package/dist/esm/array-overlap-sql.d.ts.map +1 -0
  164. package/dist/esm/array-overlap-sql.js +21 -0
  165. package/dist/esm/array-overlap-sql.js.map +1 -0
  166. package/dist/esm/content-localization.d.ts +37 -0
  167. package/dist/esm/content-localization.d.ts.map +1 -0
  168. package/dist/esm/content-localization.js +24 -0
  169. package/dist/esm/content-localization.js.map +1 -0
  170. package/dist/esm/count-effect.d.ts +11 -1
  171. package/dist/esm/count-effect.d.ts.map +1 -1
  172. package/dist/esm/count-effect.js +28 -1
  173. package/dist/esm/count-effect.js.map +1 -1
  174. package/dist/esm/data-source-fetchers.d.ts.map +1 -1
  175. package/dist/esm/data-source-fetchers.js +11 -5
  176. package/dist/esm/data-source-fetchers.js.map +1 -1
  177. package/dist/esm/fetchers/airtable.d.ts.map +1 -1
  178. package/dist/esm/fetchers/airtable.js +1 -1
  179. package/dist/esm/fetchers/airtable.js.map +1 -1
  180. package/dist/esm/fetchers/clickhouse.d.ts.map +1 -1
  181. package/dist/esm/fetchers/clickhouse.js +1 -1
  182. package/dist/esm/fetchers/clickhouse.js.map +1 -1
  183. package/dist/esm/fetchers/firestore.d.ts.map +1 -1
  184. package/dist/esm/fetchers/firestore.js +1 -1
  185. package/dist/esm/fetchers/firestore.js.map +1 -1
  186. package/dist/esm/fetchers/javascript.d.ts.map +1 -1
  187. package/dist/esm/fetchers/javascript.js +1 -1
  188. package/dist/esm/fetchers/javascript.js.map +1 -1
  189. package/dist/esm/fetchers/mariadb.d.ts.map +1 -1
  190. package/dist/esm/fetchers/mariadb.js +1 -1
  191. package/dist/esm/fetchers/mariadb.js.map +1 -1
  192. package/dist/esm/fetchers/mongodb.d.ts.map +1 -1
  193. package/dist/esm/fetchers/mongodb.js +1 -1
  194. package/dist/esm/fetchers/mongodb.js.map +1 -1
  195. package/dist/esm/fetchers/mysql.d.ts.map +1 -1
  196. package/dist/esm/fetchers/mysql.js +1 -1
  197. package/dist/esm/fetchers/mysql.js.map +1 -1
  198. package/dist/esm/fetchers/postgresql.d.ts +1 -1
  199. package/dist/esm/fetchers/postgresql.d.ts.map +1 -1
  200. package/dist/esm/fetchers/postgresql.js +9 -4
  201. package/dist/esm/fetchers/postgresql.js.map +1 -1
  202. package/dist/esm/fetchers/raw-query.d.ts +8 -1
  203. package/dist/esm/fetchers/raw-query.d.ts.map +1 -1
  204. package/dist/esm/fetchers/raw-query.js +42 -4
  205. package/dist/esm/fetchers/raw-query.js.map +1 -1
  206. package/dist/esm/fetchers/redshift.d.ts.map +1 -1
  207. package/dist/esm/fetchers/redshift.js +1 -1
  208. package/dist/esm/fetchers/redshift.js.map +1 -1
  209. package/dist/esm/fetchers/rest-api.d.ts.map +1 -1
  210. package/dist/esm/fetchers/rest-api.js +7 -2
  211. package/dist/esm/fetchers/rest-api.js.map +1 -1
  212. package/dist/esm/fetchers/teleport.d.ts.map +1 -1
  213. package/dist/esm/fetchers/teleport.js +16 -6
  214. package/dist/esm/fetchers/teleport.js.map +1 -1
  215. package/dist/esm/fetchers/turso.d.ts.map +1 -1
  216. package/dist/esm/fetchers/turso.js +1 -1
  217. package/dist/esm/fetchers/turso.js.map +1 -1
  218. package/dist/esm/fetchers/utils/browser-row-policy.d.ts +43 -0
  219. package/dist/esm/fetchers/utils/browser-row-policy.d.ts.map +1 -0
  220. package/dist/esm/fetchers/utils/browser-row-policy.js +60 -0
  221. package/dist/esm/fetchers/utils/browser-row-policy.js.map +1 -0
  222. package/dist/esm/fetchers/utils/request-sql-guards.d.ts +8 -0
  223. package/dist/esm/fetchers/utils/request-sql-guards.d.ts.map +1 -0
  224. package/dist/esm/fetchers/utils/request-sql-guards.js +8 -0
  225. package/dist/esm/fetchers/utils/request-sql-guards.js.map +1 -0
  226. package/dist/esm/fetchers/utils/rest-api-response-cache.d.ts +40 -0
  227. package/dist/esm/fetchers/utils/rest-api-response-cache.d.ts.map +1 -0
  228. package/dist/esm/fetchers/utils/rest-api-response-cache.js +59 -0
  229. package/dist/esm/fetchers/utils/rest-api-response-cache.js.map +1 -0
  230. package/dist/esm/fetchers/utils/table-access-guard.d.ts +23 -0
  231. package/dist/esm/fetchers/utils/table-access-guard.d.ts.map +1 -0
  232. package/dist/esm/fetchers/utils/table-access-guard.js +29 -0
  233. package/dist/esm/fetchers/utils/table-access-guard.js.map +1 -0
  234. package/dist/esm/index.d.ts +5 -0
  235. package/dist/esm/index.d.ts.map +1 -1
  236. package/dist/esm/index.js +55 -7
  237. package/dist/esm/index.js.map +1 -1
  238. package/dist/esm/items-path.d.ts +10 -0
  239. package/dist/esm/items-path.d.ts.map +1 -0
  240. package/dist/esm/items-path.js +58 -0
  241. package/dist/esm/items-path.js.map +1 -0
  242. package/dist/esm/loading-state.d.ts +16 -1
  243. package/dist/esm/loading-state.d.ts.map +1 -1
  244. package/dist/esm/loading-state.js +69 -3
  245. package/dist/esm/loading-state.js.map +1 -1
  246. package/dist/esm/localized-columns.d.ts +56 -0
  247. package/dist/esm/localized-columns.d.ts.map +1 -0
  248. package/dist/esm/localized-columns.js +132 -0
  249. package/dist/esm/localized-columns.js.map +1 -0
  250. package/dist/esm/pagination-plugin.d.ts.map +1 -1
  251. package/dist/esm/pagination-plugin.js +141 -51
  252. package/dist/esm/pagination-plugin.js.map +1 -1
  253. package/dist/esm/product-filter-fields.d.ts +87 -0
  254. package/dist/esm/product-filter-fields.d.ts.map +1 -0
  255. package/dist/esm/product-filter-fields.js +154 -0
  256. package/dist/esm/product-filter-fields.js.map +1 -0
  257. package/dist/esm/request-locale.d.ts +49 -0
  258. package/dist/esm/request-locale.d.ts.map +1 -0
  259. package/dist/esm/request-locale.js +98 -0
  260. package/dist/esm/request-locale.js.map +1 -0
  261. package/dist/esm/search-clear.d.ts +31 -0
  262. package/dist/esm/search-clear.d.ts.map +1 -0
  263. package/dist/esm/search-clear.js +74 -0
  264. package/dist/esm/search-clear.js.map +1 -0
  265. package/dist/esm/transformations/blog-adjacent-posts.d.ts +16 -0
  266. package/dist/esm/transformations/blog-adjacent-posts.d.ts.map +1 -0
  267. package/dist/esm/transformations/blog-adjacent-posts.js +21 -0
  268. package/dist/esm/transformations/blog-adjacent-posts.js.map +1 -0
  269. package/dist/esm/transformations/blog-comments.d.ts +30 -0
  270. package/dist/esm/transformations/blog-comments.d.ts.map +1 -0
  271. package/dist/esm/transformations/blog-comments.js +30 -0
  272. package/dist/esm/transformations/blog-comments.js.map +1 -0
  273. package/dist/esm/transformations/blog-post.d.ts +2 -0
  274. package/dist/esm/transformations/blog-post.d.ts.map +1 -1
  275. package/dist/esm/transformations/blog-post.js +4 -1
  276. package/dist/esm/transformations/blog-post.js.map +1 -1
  277. package/dist/esm/transformations/ecommerce-product.d.ts +9 -1
  278. package/dist/esm/transformations/ecommerce-product.d.ts.map +1 -1
  279. package/dist/esm/transformations/ecommerce-product.js +29 -2
  280. package/dist/esm/transformations/ecommerce-product.js.map +1 -1
  281. package/dist/esm/transformations/heading-anchors.d.ts +25 -0
  282. package/dist/esm/transformations/heading-anchors.d.ts.map +1 -0
  283. package/dist/esm/transformations/heading-anchors.js +25 -0
  284. package/dist/esm/transformations/heading-anchors.js.map +1 -0
  285. package/dist/esm/transformations/index.d.ts +61 -4
  286. package/dist/esm/transformations/index.d.ts.map +1 -1
  287. package/dist/esm/transformations/index.js +69 -19
  288. package/dist/esm/transformations/index.js.map +1 -1
  289. package/dist/esm/transformations/shared-utils.d.ts.map +1 -1
  290. package/dist/esm/transformations/shared-utils.js +1 -1
  291. package/dist/esm/transformations/shared-utils.js.map +1 -1
  292. package/dist/esm/tsconfig.tsbuildinfo +1 -1
  293. package/dist/esm/utils.d.ts +11 -1
  294. package/dist/esm/utils.d.ts.map +1 -1
  295. package/dist/esm/utils.js +60 -16
  296. package/dist/esm/utils.js.map +1 -1
  297. package/package.json +5 -5
  298. package/src/array-overlap-sql.ts +41 -0
  299. package/src/content-localization.ts +53 -0
  300. package/src/count-effect.ts +53 -2
  301. package/src/data-source-fetchers.ts +41 -5
  302. package/src/fetchers/airtable.ts +4 -2
  303. package/src/fetchers/clickhouse.ts +4 -2
  304. package/src/fetchers/firestore.ts +4 -2
  305. package/src/fetchers/javascript.ts +9 -1
  306. package/src/fetchers/mariadb.ts +4 -2
  307. package/src/fetchers/mongodb.ts +4 -2
  308. package/src/fetchers/mysql.ts +4 -2
  309. package/src/fetchers/postgresql.ts +53 -12
  310. package/src/fetchers/raw-query.ts +60 -5
  311. package/src/fetchers/redshift.ts +4 -2
  312. package/src/fetchers/rest-api.ts +27 -5
  313. package/src/fetchers/teleport.ts +85 -22
  314. package/src/fetchers/turso.ts +4 -2
  315. package/src/fetchers/utils/browser-row-policy.ts +212 -0
  316. package/src/fetchers/utils/request-sql-guards.ts +25 -0
  317. package/src/fetchers/utils/rest-api-response-cache.ts +188 -0
  318. package/src/fetchers/utils/table-access-guard.ts +39 -0
  319. package/src/index.ts +79 -11
  320. package/src/items-path.ts +74 -0
  321. package/src/loading-state.ts +134 -3
  322. package/src/localized-columns.ts +146 -0
  323. package/src/pagination-plugin.ts +206 -60
  324. package/src/product-filter-fields.ts +173 -0
  325. package/src/request-locale.ts +113 -0
  326. package/src/search-clear.ts +102 -0
  327. package/src/transformations/blog-adjacent-posts.ts +74 -0
  328. package/src/transformations/blog-comments.ts +132 -0
  329. package/src/transformations/blog-post.ts +38 -5
  330. package/src/transformations/ecommerce-product.ts +568 -5
  331. package/src/transformations/heading-anchors.ts +85 -0
  332. package/src/transformations/index.ts +191 -23
  333. package/src/transformations/shared-utils.ts +6 -0
  334. package/src/utils.ts +109 -19
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Filtering a products list on things that are not a plain column.
3
+ *
4
+ * The storefront's product filters ask questions the `teleport_products` row
5
+ * cannot answer with a single column comparison: "what does it cost right now"
6
+ * (`price` net of a live markdown), "how many stars" (an aggregate over the
7
+ * reviews table), "is it on sale", and "does it come in size XL" (a value
8
+ * inside the `variant_options` JSON). Like the discount-aware sort in
9
+ * `product-price-sort.ts`, these have to be answered by the DATABASE — the list
10
+ * is paginated, so filtering the fetched page would only filter 20 of N rows.
11
+ *
12
+ * The editor emits such a filter as an ordinary condition whose `source` is
13
+ * one of the VIRTUAL field names below. Every SQL builder that can receive a
14
+ * products filter rewrites them into the expressions here:
15
+ *
16
+ * - this file → the generated store's `teleport_products` API route
17
+ * (`fetchers/teleport.ts`, `fetchers/postgresql.ts`);
18
+ * - `database-provider-worker/src/lib/product-filter-fields.ts` → the editor
19
+ * canvas. ⛔ A byte-for-byte mirror of the SQL below; both repos pin the
20
+ * strings with a test, because a clause the canvas cannot build is an HTTP
21
+ * 500 the canvas draws as an EMPTY grid.
22
+ *
23
+ * ## The expressions cannot raise
24
+ *
25
+ * Same discipline as the sort: the JSON column is cast only when its text
26
+ * already looks like an array, the axis key is validated against a slug pattern
27
+ * before it is bound, and an unknown key filters to no rows instead of erroring
28
+ * — a filter that the database rejects would empty the whole products page.
29
+ */
30
+
31
+ import {
32
+ PRODUCTS_TABLE_NAME,
33
+ PRODUCT_PRICE_SORT_FIELD,
34
+ buildProductEffectivePriceSql,
35
+ supportsProductPriceSort,
36
+ } from './product-price-sort'
37
+
38
+ /** The reviews table the star-rating aggregate reads. Exists once reviews were enabled. */
39
+ export const PRODUCT_REVIEWS_TABLE_NAME = 'teleport_product_reviews'
40
+
41
+ /** Virtual field: the product's star bucket — `ROUND(AVG(approved rating))`, 1..5, NULL when unreviewed. */
42
+ export const PRODUCT_RATING_FILTER_FIELD = 'rating'
43
+
44
+ /** Virtual field: `'true'` while a markdown is live, else `'false'`. */
45
+ export const PRODUCT_ON_SALE_FILTER_FIELD = 'on_sale'
46
+
47
+ /**
48
+ * Virtual field family: `variant_options.<axisKey>` — the product offers the
49
+ * axis (e.g. `size`) in one of the given values (e.g. `xl`).
50
+ */
51
+ export const PRODUCT_VARIANT_AXIS_FILTER_PREFIX = 'variant_options.'
52
+
53
+ /**
54
+ * What an axis key may look like. Keys are produced by the editor's slug
55
+ * helper (`deriveOptionKey`), so this is what every real key matches; anything
56
+ * else is refused before it can reach the database.
57
+ */
58
+ export const PRODUCT_VARIANT_AXIS_KEY_PATTERN = '^[a-z0-9][a-z0-9_-]{0,63}$'
59
+
60
+ /** Generic multi-value operand: the column equals ANY of the destination values. */
61
+ export const IN_OPERAND = 'in'
62
+
63
+ /**
64
+ * `ROUND(AVG(rating))` over the product's APPROVED reviews. Only approved rows
65
+ * count — moderation is the merchant's veto — and the outer row is the
66
+ * unaliased `teleport_products` the fetchers select from.
67
+ */
68
+ export const buildProductRatingBucketSql = (): string =>
69
+ `(SELECT ROUND(AVG(r.rating)) FROM ${PRODUCT_REVIEWS_TABLE_NAME} r WHERE r.product_id = ${PRODUCTS_TABLE_NAME}.id AND r.status = 'approved' AND r.rating IS NOT NULL)`
70
+
71
+ /** `'true'` when the price paid today is below the list price, i.e. a markdown is live. */
72
+ export const buildProductOnSaleSql = (): string =>
73
+ `(CASE WHEN ${buildProductEffectivePriceSql()} < "price"::numeric THEN 'true' ELSE 'false' END)`
74
+
75
+ /**
76
+ * Only text that already looks like a JSON array is cast; NULL, empty or a
77
+ * hand-edited scalar reads as "no variant axes".
78
+ */
79
+ export const SAFE_VARIANT_OPTIONS_JSONB = `CASE
80
+ WHEN "variant_options" IS NULL OR btrim("variant_options") NOT LIKE '[%' THEN '[]'::jsonb
81
+ ELSE "variant_options"::jsonb
82
+ END`
83
+
84
+ /**
85
+ * True when the product declares the axis bound to `keyParam` with at least one
86
+ * of the values bound to `valuesParam` (a `text[]`). Both are PARAMETERS, never
87
+ * interpolated text.
88
+ */
89
+ export const buildProductVariantAxisExistsSql = (keyParam: string, valuesParam: string): string =>
90
+ `EXISTS (SELECT 1 FROM jsonb_array_elements(${SAFE_VARIANT_OPTIONS_JSONB}) AS ax, jsonb_array_elements(CASE WHEN jsonb_typeof(ax->'values') = 'array' THEN ax->'values' ELSE '[]'::jsonb END) AS v WHERE ax->>'key' = ${keyParam} AND v->>'value' = ANY(${valuesParam}::text[]))`
91
+
92
+ /**
93
+ * The complete `productFilterClause(field, operand, value, pushParam)` helper a
94
+ * SQL fetcher embeds in its generated route.
95
+ *
96
+ * Returns a finished WHERE clause for a virtual (or rewritten) products field,
97
+ * or `null` for anything else so the fetcher's ordinary branches run. `pushParam`
98
+ * binds a value and answers its `$n` placeholder. By the time it is called an
99
+ * `in` filter has been normalised to `=` with an ARRAY value (see
100
+ * `normalizeInOperand` in `utils.ts`), which reads as "any of". A virtual field
101
+ * never answers `null` once matched — an operand it cannot express filters to
102
+ * no rows rather than falling into a branch that would name a column the table
103
+ * does not have.
104
+ *
105
+ * Emitted through `JSON.stringify` and string concatenation only — no backtick
106
+ * and no `${` may appear in the output, which is interpolated into a fetcher's
107
+ * template literal. On a table that is not the products table the helper still
108
+ * exists and always answers `null`, so a fetcher can embed it unconditionally.
109
+ */
110
+ export const generateProductFilterClauseHelper = (tableName: string): string => {
111
+ if (!supportsProductPriceSort(tableName)) {
112
+ return [
113
+ '// Virtual products-table filter fields. This table has none, so every',
114
+ "// condition takes the fetcher's ordinary branches.",
115
+ 'function productFilterClause() {',
116
+ ' return null',
117
+ '}',
118
+ ].join('\n')
119
+ }
120
+
121
+ const lines = [
122
+ "// Rewrites the products table's virtual filter fields - the price paid",
123
+ '// today, the star-rating bucket, the on-sale flag and a variant axis - into',
124
+ '// SQL. Answers null for a plain column so the ordinary branches run. An',
125
+ '// "in" filter arrives here already normalised to "=" with an ARRAY value.',
126
+ 'function productFilterClause(field, operand, value, pushParam) {',
127
+ " var scalarOps = ['=', '!=', '>', '<', '>=', '<=']",
128
+ " var equalityOps = ['=', '!=']",
129
+ ' var compare = function (expression, allowedOps, virtual) {',
130
+ ' if (Array.isArray(value)) {',
131
+ " if (operand === '=') {",
132
+ " return expression + '::text = ANY(' + pushParam(value.map(String)) + '::text[])'",
133
+ ' }',
134
+ " if (operand === '!=') {",
135
+ " return expression + '::text <> ALL(' + pushParam(value.map(String)) + '::text[])'",
136
+ ' }',
137
+ " return virtual ? 'FALSE' : null",
138
+ ' }',
139
+ " if (allowedOps.indexOf(operand) === -1) return virtual ? 'FALSE' : null",
140
+ " return expression + ' ' + operand + ' ' + pushParam(value)",
141
+ ' }',
142
+ ` if (field === ${JSON.stringify(PRODUCT_PRICE_SORT_FIELD)}) {`,
143
+ ` return compare(${JSON.stringify(
144
+ '(' + buildProductEffectivePriceSql() + ')'
145
+ )}, scalarOps, false)`,
146
+ ' }',
147
+ ` if (field === ${JSON.stringify(PRODUCT_RATING_FILTER_FIELD)}) {`,
148
+ ` return compare(${JSON.stringify(buildProductRatingBucketSql())}, scalarOps, true)`,
149
+ ' }',
150
+ ` if (field === ${JSON.stringify(PRODUCT_ON_SALE_FILTER_FIELD)}) {`,
151
+ ` return compare(${JSON.stringify(buildProductOnSaleSql())}, equalityOps, true)`,
152
+ ' }',
153
+ ` if (field.indexOf(${JSON.stringify(PRODUCT_VARIANT_AXIS_FILTER_PREFIX)}) === 0) {`,
154
+ ` var axisKey = field.slice(${PRODUCT_VARIANT_AXIS_FILTER_PREFIX.length})`,
155
+ ` if (!new RegExp(${JSON.stringify(PRODUCT_VARIANT_AXIS_KEY_PATTERN)}).test(axisKey)) {`,
156
+ ' // Not a key the editor could have written: no rows, never an error.',
157
+ " return 'FALSE'",
158
+ ' }',
159
+ " if (operand !== '=') return 'FALSE'",
160
+ ' var values = (Array.isArray(value) ? value : [value]).map(String)',
161
+ ' var keyParam = pushParam(axisKey)',
162
+ ' var valuesParam = pushParam(values)',
163
+ ` return ${JSON.stringify(buildProductVariantAxisExistsSql('__KEY__', '__VALUES__'))}`,
164
+ // Function replacements: a "$1" inside a replacement STRING is a special
165
+ // pattern, so the placeholders are swapped by callback.
166
+ " .replace('__KEY__', function () { return keyParam })",
167
+ " .replace('__VALUES__', function () { return valuesParam })",
168
+ ' }',
169
+ ' return null',
170
+ '}',
171
+ ]
172
+ return lines.join('\n')
173
+ }
@@ -0,0 +1,113 @@
1
+ import * as types from '@babel/types'
2
+ import type { UIDLDependency } from '@teleporthq/teleport-types'
3
+
4
+ /**
5
+ * How a generated data-source fetch says which language it is for.
6
+ *
7
+ * A multi-language project stores a translatable column once per language
8
+ * (`name`, `es_name`, …) and the generated fetcher resolves each row against
9
+ * ONE of them (see `transformations/` and `localized-columns.ts`). Nothing
10
+ * about the API route knows the page it serves — an API route has no locale
11
+ * segment in its URL — so the page tells it, through this query parameter:
12
+ *
13
+ * - a client-side fetch (`DataProvider` `params`) sends `router.locale`;
14
+ * - a build-time fetch inside `getStaticProps` sends `context.locale`.
15
+ *
16
+ * Both are what Next.js resolved from the `/es/...` route, so the rows a page
17
+ * renders are in the language the page is in. The same name the details-page
18
+ * fetch (`teleport-plugin-next-static-props`) has always sent.
19
+ */
20
+ export const REQUEST_LOCALE_PARAM = 'locale'
21
+
22
+ /** The dependency behind the `router` every client-side locale read closes over. */
23
+ const USE_ROUTER_DEPENDENCY: UIDLDependency = {
24
+ type: 'library',
25
+ path: 'next/router',
26
+ version: '^12.1.10',
27
+ meta: { namedImport: true },
28
+ }
29
+
30
+ /**
31
+ * `router?.locale` — the client's current locale. Optional-chained like every
32
+ * other generated `router` read: `useRouter()` answers `null` during a static
33
+ * export's first paint.
34
+ */
35
+ export const buildClientLocaleExpression = (): types.Expression =>
36
+ types.optionalMemberExpression(
37
+ types.identifier('router'),
38
+ types.identifier('locale'),
39
+ false,
40
+ true
41
+ )
42
+
43
+ /** `locale: router?.locale` — the param of a client-side fetch. */
44
+ export const buildClientLocaleParam = (): types.ObjectProperty =>
45
+ types.objectProperty(types.identifier(REQUEST_LOCALE_PARAM), buildClientLocaleExpression())
46
+
47
+ /** `locale: context.locale` — the param of a fetch inside getStaticProps. */
48
+ export const buildServerLocaleParam = (): types.ObjectProperty =>
49
+ types.objectProperty(
50
+ types.identifier(REQUEST_LOCALE_PARAM),
51
+ types.memberExpression(types.identifier('context'), types.identifier('locale'))
52
+ )
53
+
54
+ /** Whether an object literal already carries the locale param. */
55
+ export const hasLocaleParam = (properties: types.ObjectExpression['properties']): boolean =>
56
+ properties.some(
57
+ (property) =>
58
+ property.type === 'ObjectProperty' &&
59
+ ((property.key.type === 'Identifier' && property.key.name === REQUEST_LOCALE_PARAM) ||
60
+ (property.key.type === 'StringLiteral' && property.key.value === REQUEST_LOCALE_PARAM))
61
+ )
62
+
63
+ /**
64
+ * Adds the client locale to a fetch's params, once, and to the `useMemo` deps
65
+ * that must rebuild them: a locale switch is a client-side transition on the
66
+ * SAME page instance, so only a dependency change refetches the rows in the
67
+ * new language.
68
+ */
69
+ export const appendClientLocaleParam = (
70
+ paramsProps: types.ObjectExpression['properties'],
71
+ memoDeps: types.Expression[]
72
+ ): void => {
73
+ if (!hasLocaleParam(paramsProps)) {
74
+ paramsProps.push(buildClientLocaleParam())
75
+ }
76
+ memoDeps.push(buildClientLocaleExpression())
77
+ }
78
+
79
+ /** Any declaration of `router` — a second one, however it is initialised, is a syntax error. */
80
+ const declaresRouter = (statement: types.Statement): boolean =>
81
+ statement.type === 'VariableDeclaration' &&
82
+ statement.declarations.some(
83
+ (declaration) => declaration.id.type === 'Identifier' && declaration.id.name === 'router'
84
+ )
85
+
86
+ /**
87
+ * Puts `const router = useRouter()` (and its import) in scope, once.
88
+ *
89
+ * Idempotent with every sibling plugin that declares the same hook — the i18n
90
+ * locale mapper, the URL search-params plugin and the base component plugin
91
+ * all guard on the same identifier, so whichever runs first wins and the rest
92
+ * find it in place. Unshifted to the top of the body: nothing reads it before
93
+ * an effect runs, and hooks must not sit below a conditional return.
94
+ */
95
+ export const ensureRouterDeclaration = (
96
+ body: types.Statement[],
97
+ dependencies: Record<string, UIDLDependency>
98
+ ): void => {
99
+ if (!dependencies.useRouter) {
100
+ dependencies.useRouter = { ...USE_ROUTER_DEPENDENCY }
101
+ }
102
+ if (body.some(declaresRouter)) {
103
+ return
104
+ }
105
+ body.unshift(
106
+ types.variableDeclaration('const', [
107
+ types.variableDeclarator(
108
+ types.identifier('router'),
109
+ types.callExpression(types.identifier('useRouter'), [])
110
+ ),
111
+ ])
112
+ )
113
+ }
@@ -0,0 +1,102 @@
1
+ import * as types from '@babel/types'
2
+ import { setJSXExpressionAttribute } from './pagination-controls'
3
+
4
+ /**
5
+ * The "clear search" button a listing's search field carries — marked
6
+ * `data-tq-search-clear` by the editor (`listing-search-field.ts`), the same
7
+ * marker the canvas renderer acts on. The search keyword is the mapper's own
8
+ * React state, which no authored workflow can reach, so the generator wires
9
+ * the button here: a click empties the query, and the button renders only
10
+ * while the query is non-empty.
11
+ *
12
+ * A button belongs to the search input it shares a parent with — the field
13
+ * wrapper — never to "the next search-enabled mapper": a page with two lists
14
+ * and one clear button would otherwise wire it to the wrong list.
15
+ */
16
+
17
+ export const SEARCH_CLEAR_ATTR = 'data-tq-search-clear'
18
+
19
+ // tslint:disable:no-any
20
+
21
+ export interface SearchClearButton {
22
+ node: any
23
+ parent: any
24
+ index: number
25
+ }
26
+
27
+ function hasSearchClearMarker(node: any): boolean {
28
+ return !!node?.openingElement?.attributes?.some(
29
+ (attr: any) => attr.type === 'JSXAttribute' && attr.name?.name === SEARCH_CLEAR_ATTR
30
+ )
31
+ }
32
+
33
+ /** Every marked button under `root`, with the JSX parent and child index it sits at. */
34
+ export function findAllSearchClearButtonsInJSX(root: any): SearchClearButton[] {
35
+ const results: SearchClearButton[] = []
36
+ const traverse = (node: any): void => {
37
+ if (!node) {
38
+ return
39
+ }
40
+ if (node.type === 'JSXElement' && Array.isArray(node.children)) {
41
+ node.children.forEach((child: any, index: number) => {
42
+ if (child?.type === 'JSXElement' && hasSearchClearMarker(child)) {
43
+ results.push({ node: child, parent: node, index })
44
+ }
45
+ traverse(child)
46
+ })
47
+ return
48
+ }
49
+ if (node.body) {
50
+ if (Array.isArray(node.body)) {
51
+ node.body.forEach((statement: any) => traverse(statement))
52
+ } else {
53
+ traverse(node.body)
54
+ }
55
+ }
56
+ if (node.consequent) {
57
+ traverse(node.consequent)
58
+ }
59
+ if (node.alternate) {
60
+ traverse(node.alternate)
61
+ }
62
+ if (node.expression) {
63
+ traverse(node.expression)
64
+ }
65
+ if (node.argument) {
66
+ traverse(node.argument)
67
+ }
68
+ }
69
+ traverse(root)
70
+ return results
71
+ }
72
+
73
+ /** The search input the button shares its parent with, or null. */
74
+ export function findSiblingSearchInput(button: SearchClearButton, searchInputs: any[]): any | null {
75
+ const siblings: any[] = button.parent.children ?? []
76
+ return siblings.find((sibling) => searchInputs.includes(sibling)) ?? null
77
+ }
78
+
79
+ /**
80
+ * Wires one button: `onClick` empties the query, and the element is replaced
81
+ * in its parent by `{query ? <button…/> : null}`.
82
+ */
83
+ export function wireSearchClearButton(
84
+ button: SearchClearButton,
85
+ vars: { searchQueryVar: string; setSearchQueryVar: string }
86
+ ): void {
87
+ setJSXExpressionAttribute(
88
+ button.node,
89
+ 'onClick',
90
+ types.arrowFunctionExpression(
91
+ [],
92
+ types.callExpression(types.identifier(vars.setSearchQueryVar), [types.stringLiteral('')])
93
+ )
94
+ )
95
+ button.parent.children[button.index] = types.jsxExpressionContainer(
96
+ types.conditionalExpression(
97
+ types.identifier(vars.searchQueryVar),
98
+ button.node,
99
+ types.nullLiteral()
100
+ )
101
+ )
102
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * How many posts each direction is read, so a neighbour that only REDIRECTS
3
+ * elsewhere can be stepped over without a second query.
4
+ */
5
+ const ADJACENT_POST_CANDIDATES = 5
6
+
7
+ /**
8
+ * Generates the code that finds a post's neighbours for its "previous / next"
9
+ * navigation: the published posts right before and after it in the order the
10
+ * blog listing shows them (`created_at`, then `id`, newest first). "Previous"
11
+ * is the older one.
12
+ *
13
+ * Only a post DETAILS fetch (a single record) asks. A neighbour whose row
14
+ * carries a redirect is skipped — linking to it would only bounce the reader
15
+ * somewhere else — which is read off the row in code rather than in SQL, so a
16
+ * table provisioned before the SEO columns still works.
17
+ *
18
+ * MUST mirror `findAdjacentBlogPosts` in teleport-gui
19
+ * `packages/renderer/src/utils/blog-adjacent-posts.ts` (the canvas).
20
+ */
21
+ export const generateAdjacentPostsCode = (): string => `
22
+ var BLOG_ADJACENT_CANDIDATES = ${ADJACENT_POST_CANDIDATES}
23
+
24
+ function blogAdjacentPostsSql(comparison, direction) {
25
+ return (
26
+ 'SELECT p.* FROM teleport_blog_posts p,' +
27
+ ' (SELECT created_at, id FROM teleport_blog_posts WHERE id = $1) cur' +
28
+ " WHERE p.status = 'published' AND (p.created_at, p.id) " + comparison + ' (cur.created_at, cur.id)' +
29
+ ' ORDER BY p.created_at ' + direction + ', p.id ' + direction +
30
+ ' LIMIT ' + BLOG_ADJACENT_CANDIDATES
31
+ )
32
+ }
33
+
34
+ function firstLinkableBlogPost(result) {
35
+ var rows = result && Array.isArray(result.rows) ? result.rows : []
36
+ for (var i = 0; i < rows.length; i++) {
37
+ var row = rows[i]
38
+ if (!row) continue
39
+ var redirect = pickFirst(row.redirect_url, row.redirectUrl)
40
+ if (typeof redirect === 'string' && redirect.trim() !== '') continue
41
+ // Through JSON, like the rows the fetcher itself hands the transform.
42
+ return JSON.parse(JSON.stringify(row))
43
+ }
44
+ return null
45
+ }
46
+
47
+ // { [postId]: { previous, next } } — raw rows or null — for a single-record
48
+ // fetch; {} otherwise and on any failure (the navigation then hides).
49
+ async function getAdjacentPostsMap(getClientFn, records) {
50
+ var map = {}
51
+ if (!Array.isArray(records) || records.length !== 1) return map
52
+ var postId = records[0] && records[0].id
53
+ if (postId === null || postId === undefined) return map
54
+
55
+ var client
56
+ try {
57
+ client = getClientFn()
58
+ await client.connect()
59
+ var older = await client.query(blogAdjacentPostsSql('<', 'DESC'), [String(postId)])
60
+ var newer = await client.query(blogAdjacentPostsSql('>', 'ASC'), [String(postId)])
61
+ map[String(postId)] = {
62
+ previous: firstLinkableBlogPost(older),
63
+ next: firstLinkableBlogPost(newer),
64
+ }
65
+ } catch (e) {
66
+ // Leaves the navigation hidden.
67
+ } finally {
68
+ if (client) {
69
+ try { await client.end() } catch (e) { /* ignore */ }
70
+ }
71
+ }
72
+ return map
73
+ }
74
+ `
@@ -0,0 +1,132 @@
1
+ /**
2
+ * How many TOP-LEVEL comments a post page carries: the newest ones, shown
3
+ * oldest-first, each with all of its replies. The count in the section's
4
+ * heading still counts every approved comment.
5
+ *
6
+ * ⛔ PAIRED with `BLOG_COMMENTS_RENDER_LIMIT` in teleport-gui
7
+ * `features/blog/constants/blog-comments.ts` (the canvas mirror).
8
+ */
9
+ export const BLOG_COMMENTS_RENDER_LIMIT = 200
10
+
11
+ /**
12
+ * Generates the code that loads and shapes a post's approved comments.
13
+ *
14
+ * Read server-side, with the post: only a post DETAILS fetch (a single record)
15
+ * asks, so a listing never pays for it, and the comments arrive in the page's
16
+ * HTML — rendered by SSR/ISR, carried along a client-side navigation to another
17
+ * post, no request of their own.
18
+ *
19
+ * Public columns only. `teleport_blog_comments` holds the commenters' email
20
+ * addresses and the comments still waiting for approval, which is why it is a
21
+ * customer-record table no browser may read (see teleport-shared's
22
+ * `table-access.ts`); nothing here selects either.
23
+ *
24
+ * Replies are one level deep: a reply whose parent is not among the rows (not
25
+ * approved, deleted) is dropped rather than promoted to the top level.
26
+ *
27
+ * MUST mirror `buildBlogComments` in teleport-gui
28
+ * `packages/renderer/src/utils/blog-comments.ts` (the canvas).
29
+ */
30
+ export const generateBlogCommentsCode = (): string => `
31
+ var BLOG_COMMENTS_RENDER_LIMIT = ${BLOG_COMMENTS_RENDER_LIMIT}
32
+
33
+ var BLOG_COMMENTS_SQL =
34
+ 'WITH top AS (' +
35
+ ' SELECT id FROM teleport_blog_comments' +
36
+ " WHERE post_id = $1 AND parent_id IS NULL AND status = 'approved'" +
37
+ ' ORDER BY created_at DESC, id DESC LIMIT ' + BLOG_COMMENTS_RENDER_LIMIT +
38
+ ')' +
39
+ ' SELECT c.id, c.parent_id, c.author_name, c.content, c.is_author_reply, c.created_at' +
40
+ ' FROM teleport_blog_comments c' +
41
+ " WHERE c.post_id = $1 AND c.status = 'approved'" +
42
+ ' AND (c.id IN (SELECT id FROM top) OR c.parent_id IN (SELECT id FROM top))' +
43
+ ' ORDER BY c.created_at ASC, c.id ASC'
44
+
45
+ // Every approved comment the page could show — a reply counts only while the
46
+ // comment it answers is approved too.
47
+ var BLOG_COMMENTS_COUNT_SQL =
48
+ 'SELECT COUNT(*) AS n FROM teleport_blog_comments c' +
49
+ " WHERE c.post_id = $1 AND c.status = 'approved'" +
50
+ ' AND (c.parent_id IS NULL OR EXISTS (' +
51
+ ' SELECT 1 FROM teleport_blog_comments p' +
52
+ " WHERE p.id = c.parent_id AND p.status = 'approved'))"
53
+
54
+ function blogAuthorInitials(name) {
55
+ if (typeof name !== 'string') return ''
56
+ var words = name.trim().split(' ').filter(function(word) { return word !== '' })
57
+ if (words.length === 0) return ''
58
+ // Code points, not UTF-16 units: an initial may be an emoji or a letter
59
+ // outside the BMP, and half of a surrogate pair renders as a box.
60
+ var first = Array.from(words[0])[0] || ''
61
+ var last = words.length > 1 ? Array.from(words[words.length - 1])[0] || '' : ''
62
+ return (first + last).toUpperCase()
63
+ }
64
+
65
+ function buildBlogComment(row) {
66
+ var name = typeof row.author_name === 'string' ? row.author_name.trim() : ''
67
+ var authorName = name || 'Reader'
68
+ return {
69
+ id: String(row.id),
70
+ authorName: authorName,
71
+ authorInitials: blogAuthorInitials(authorName),
72
+ content: typeof row.content === 'string' ? row.content : '',
73
+ createdAt: normalizeTimestamp(row.created_at),
74
+ isAuthorReply: coerceBoolean(row.is_author_reply, false),
75
+ }
76
+ }
77
+
78
+ function isTopLevelComment(row) {
79
+ return row.parent_id === null || row.parent_id === undefined || row.parent_id === ''
80
+ }
81
+
82
+ function buildBlogComments(rows) {
83
+ var comments = []
84
+ if (!Array.isArray(rows)) return comments
85
+ var byId = {}
86
+ for (var i = 0; i < rows.length; i++) {
87
+ var row = rows[i]
88
+ if (!row || row.id == null || !isTopLevelComment(row)) continue
89
+ var comment = buildBlogComment(row)
90
+ comment.replies = []
91
+ byId[comment.id] = comment
92
+ comments.push(comment)
93
+ }
94
+ for (var j = 0; j < rows.length; j++) {
95
+ var reply = rows[j]
96
+ if (!reply || reply.id == null || isTopLevelComment(reply)) continue
97
+ var parent = byId[String(reply.parent_id)]
98
+ if (parent) parent.replies.push(buildBlogComment(reply))
99
+ }
100
+ return comments
101
+ }
102
+
103
+ // { [postId]: { rows, count } } for a single-record (details) fetch; {} for
104
+ // anything else, and on any failure — a blog whose comments table does not
105
+ // exist yet renders its posts without comments rather than failing the page.
106
+ async function getBlogCommentsMap(getClientFn, records) {
107
+ var map = {}
108
+ if (!Array.isArray(records) || records.length !== 1) return map
109
+ var postId = records[0] && records[0].id
110
+ if (postId === null || postId === undefined) return map
111
+
112
+ var client
113
+ try {
114
+ client = getClientFn()
115
+ await client.connect()
116
+ var listed = await client.query(BLOG_COMMENTS_SQL, [String(postId)])
117
+ var counted = await client.query(BLOG_COMMENTS_COUNT_SQL, [String(postId)])
118
+ // Through JSON, like every other row the fetcher hands the transform: the
119
+ // driver returns timestamps as Date objects.
120
+ var rows = listed && Array.isArray(listed.rows) ? JSON.parse(JSON.stringify(listed.rows)) : []
121
+ var count = counted && counted.rows && counted.rows[0] ? Number(counted.rows[0].n) : NaN
122
+ map[String(postId)] = { rows: rows, count: isNaN(count) ? rows.length : count }
123
+ } catch (e) {
124
+ // Leaves the post without comments.
125
+ } finally {
126
+ if (client) {
127
+ try { await client.end() } catch (e) { /* ignore */ }
128
+ }
129
+ }
130
+ return map
131
+ }
132
+ `