joist-codegen 2.3.0-next.42 → 2.3.0-next.43

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 (337) hide show
  1. package/build/EntityDbMetadata.cjs +608 -0
  2. package/build/EntityDbMetadata.cjs.map +1 -0
  3. package/build/EntityDbMetadata.d.cts +274 -0
  4. package/build/EntityDbMetadata.d.cts.map +1 -0
  5. package/build/EntityDbMetadata.d.mts +274 -0
  6. package/build/EntityDbMetadata.d.mts.map +1 -0
  7. package/build/EntityDbMetadata.js +485 -664
  8. package/build/EntityDbMetadata.js.map +1 -1
  9. package/build/_virtual/_rolldown/runtime.cjs +23 -0
  10. package/build/_virtual/_rolldown/runtime.js +5 -0
  11. package/build/assignTags.cjs +45 -0
  12. package/build/assignTags.cjs.map +1 -0
  13. package/build/{assignTags.d.ts → assignTags.d.cts} +8 -3
  14. package/build/assignTags.d.cts.map +1 -0
  15. package/build/assignTags.d.mts +16 -0
  16. package/build/assignTags.d.mts.map +1 -0
  17. package/build/assignTags.js +37 -59
  18. package/build/assignTags.js.map +1 -1
  19. package/build/codemods/Codemod.cjs +2 -0
  20. package/build/codemods/Codemod.d.cts +17 -0
  21. package/build/codemods/Codemod.d.cts.map +1 -0
  22. package/build/codemods/Codemod.d.mts +17 -0
  23. package/build/codemods/Codemod.d.mts.map +1 -0
  24. package/build/codemods/Codemod.js +2 -3
  25. package/build/codemods/JscodeshiftMod.cjs +42 -0
  26. package/build/codemods/JscodeshiftMod.cjs.map +1 -0
  27. package/build/codemods/JscodeshiftMod.d.cts +14 -0
  28. package/build/codemods/JscodeshiftMod.d.cts.map +1 -0
  29. package/build/codemods/JscodeshiftMod.d.mts +14 -0
  30. package/build/codemods/JscodeshiftMod.d.mts.map +1 -0
  31. package/build/codemods/JscodeshiftMod.js +33 -33
  32. package/build/codemods/JscodeshiftMod.js.map +1 -1
  33. package/build/codemods/codemod_0001-rename_has_async_property.cjs +30 -0
  34. package/build/codemods/codemod_0001-rename_has_async_property.cjs.map +1 -0
  35. package/build/codemods/codemod_0001-rename_has_async_property.d.cts +9 -0
  36. package/build/codemods/codemod_0001-rename_has_async_property.d.cts.map +1 -0
  37. package/build/codemods/codemod_0001-rename_has_async_property.d.mts +9 -0
  38. package/build/codemods/codemod_0001-rename_has_async_property.d.mts.map +1 -0
  39. package/build/codemods/codemod_0001-rename_has_async_property.js +21 -25
  40. package/build/codemods/codemod_0001-rename_has_async_property.js.map +1 -1
  41. package/build/codemods/codemod_0002-rename_async_query_fields.cjs +50 -0
  42. package/build/codemods/codemod_0002-rename_async_query_fields.cjs.map +1 -0
  43. package/build/codemods/codemod_0002-rename_async_query_fields.d.cts +9 -0
  44. package/build/codemods/codemod_0002-rename_async_query_fields.d.cts.map +1 -0
  45. package/build/codemods/codemod_0002-rename_async_query_fields.d.mts +9 -0
  46. package/build/codemods/codemod_0002-rename_async_query_fields.d.mts.map +1 -0
  47. package/build/codemods/codemod_0002-rename_async_query_fields.js +38 -46
  48. package/build/codemods/codemod_0002-rename_async_query_fields.js.map +1 -1
  49. package/build/codemods/codemod_0003-rename_find_paginated.cjs +25 -0
  50. package/build/codemods/codemod_0003-rename_find_paginated.cjs.map +1 -0
  51. package/build/codemods/codemod_0003-rename_find_paginated.d.cts +9 -0
  52. package/build/codemods/codemod_0003-rename_find_paginated.d.cts.map +1 -0
  53. package/build/codemods/codemod_0003-rename_find_paginated.d.mts +9 -0
  54. package/build/codemods/codemod_0003-rename_find_paginated.d.mts.map +1 -0
  55. package/build/codemods/codemod_0003-rename_find_paginated.js +17 -26
  56. package/build/codemods/codemod_0003-rename_find_paginated.js.map +1 -1
  57. package/build/codemods/index.cjs +49 -0
  58. package/build/codemods/index.cjs.map +1 -0
  59. package/build/codemods/index.d.cts +12 -0
  60. package/build/codemods/index.d.cts.map +1 -0
  61. package/build/codemods/index.d.mts +12 -0
  62. package/build/codemods/index.d.mts.map +1 -0
  63. package/build/codemods/index.js +34 -42
  64. package/build/codemods/index.js.map +1 -1
  65. package/build/config.cjs +377 -0
  66. package/build/config.cjs.map +1 -0
  67. package/build/config.d.cts +181 -0
  68. package/build/config.d.cts.map +1 -0
  69. package/build/config.d.mts +181 -0
  70. package/build/config.d.mts.map +1 -0
  71. package/build/config.js +300 -382
  72. package/build/config.js.map +1 -1
  73. package/build/docs/cache.cjs +62 -0
  74. package/build/docs/cache.cjs.map +1 -0
  75. package/build/docs/cache.d.cts +17 -0
  76. package/build/docs/cache.d.cts.map +1 -0
  77. package/build/docs/cache.d.mts +17 -0
  78. package/build/docs/cache.d.mts.map +1 -0
  79. package/build/docs/cache.js +52 -53
  80. package/build/docs/cache.js.map +1 -1
  81. package/build/docs/generate-metadata-docs.cjs +32 -0
  82. package/build/docs/generate-metadata-docs.cjs.map +1 -0
  83. package/build/docs/generate-metadata-docs.d.cts +9 -0
  84. package/build/docs/generate-metadata-docs.d.cts.map +1 -0
  85. package/build/docs/generate-metadata-docs.d.mts +9 -0
  86. package/build/docs/generate-metadata-docs.d.mts.map +1 -0
  87. package/build/docs/generate-metadata-docs.js +18 -20
  88. package/build/docs/generate-metadata-docs.js.map +1 -1
  89. package/build/docs/index.cjs +90 -0
  90. package/build/docs/index.cjs.map +1 -0
  91. package/build/docs/index.d.cts +16 -0
  92. package/build/docs/index.d.cts.map +1 -0
  93. package/build/docs/index.d.mts +16 -0
  94. package/build/docs/index.d.mts.map +1 -0
  95. package/build/docs/index.js +72 -91
  96. package/build/docs/index.js.map +1 -1
  97. package/build/docs/markdown.cjs +181 -0
  98. package/build/docs/markdown.cjs.map +1 -0
  99. package/build/docs/{markdown.d.ts → markdown.d.cts} +14 -11
  100. package/build/docs/markdown.d.cts.map +1 -0
  101. package/build/docs/markdown.d.mts +32 -0
  102. package/build/docs/markdown.d.mts.map +1 -0
  103. package/build/docs/markdown.js +152 -220
  104. package/build/docs/markdown.js.map +1 -1
  105. package/build/docs/parsing.cjs +117 -0
  106. package/build/docs/parsing.cjs.map +1 -0
  107. package/build/docs/parsing.d.cts +48 -0
  108. package/build/docs/parsing.d.cts.map +1 -0
  109. package/build/docs/parsing.d.mts +48 -0
  110. package/build/docs/parsing.d.mts.map +1 -0
  111. package/build/docs/parsing.js +86 -91
  112. package/build/docs/parsing.js.map +1 -1
  113. package/build/findEntityScopes.cjs +119 -0
  114. package/build/findEntityScopes.cjs.map +1 -0
  115. package/build/findEntityScopes.d.cts +14 -0
  116. package/build/findEntityScopes.d.cts.map +1 -0
  117. package/build/findEntityScopes.d.mts +14 -0
  118. package/build/findEntityScopes.d.mts.map +1 -0
  119. package/build/findEntityScopes.js +79 -121
  120. package/build/findEntityScopes.js.map +1 -1
  121. package/build/foreignKeyOrdering.cjs +52 -0
  122. package/build/foreignKeyOrdering.cjs.map +1 -0
  123. package/build/foreignKeyOrdering.d.cts +8 -0
  124. package/build/foreignKeyOrdering.d.cts.map +1 -0
  125. package/build/foreignKeyOrdering.d.mts +8 -0
  126. package/build/foreignKeyOrdering.d.mts.map +1 -0
  127. package/build/foreignKeyOrdering.js +46 -55
  128. package/build/foreignKeyOrdering.js.map +1 -1
  129. package/build/generate.cjs +127 -0
  130. package/build/generate.cjs.map +1 -0
  131. package/build/generate.d.cts +17 -0
  132. package/build/generate.d.cts.map +1 -0
  133. package/build/generate.d.mts +17 -0
  134. package/build/generate.d.mts.map +1 -0
  135. package/build/generate.js +109 -129
  136. package/build/generate.js.map +1 -1
  137. package/build/generateEntitiesFile.cjs +46 -0
  138. package/build/generateEntitiesFile.cjs.map +1 -0
  139. package/build/generateEntitiesFile.d.cts +11 -0
  140. package/build/generateEntitiesFile.d.cts.map +1 -0
  141. package/build/generateEntitiesFile.d.mts +11 -0
  142. package/build/generateEntitiesFile.d.mts.map +1 -0
  143. package/build/generateEntitiesFile.js +28 -25
  144. package/build/generateEntitiesFile.js.map +1 -1
  145. package/build/generateEntityCodegenFile.cjs +936 -0
  146. package/build/generateEntityCodegenFile.cjs.map +1 -0
  147. package/build/generateEntityCodegenFile.d.cts +16 -0
  148. package/build/generateEntityCodegenFile.d.cts.map +1 -0
  149. package/build/generateEntityCodegenFile.d.mts +16 -0
  150. package/build/generateEntityCodegenFile.d.mts.map +1 -0
  151. package/build/generateEntityCodegenFile.js +707 -852
  152. package/build/generateEntityCodegenFile.js.map +1 -1
  153. package/build/generateEntityFile.cjs +23 -0
  154. package/build/generateEntityFile.cjs.map +1 -0
  155. package/build/generateEntityFile.d.cts +9 -0
  156. package/build/generateEntityFile.d.cts.map +1 -0
  157. package/build/generateEntityFile.d.mts +9 -0
  158. package/build/generateEntityFile.d.mts.map +1 -0
  159. package/build/generateEntityFile.js +11 -8
  160. package/build/generateEntityFile.js.map +1 -1
  161. package/build/generateEntityTestFile.cjs +25 -0
  162. package/build/generateEntityTestFile.cjs.map +1 -0
  163. package/build/generateEntityTestFile.d.cts +9 -0
  164. package/build/generateEntityTestFile.d.cts.map +1 -0
  165. package/build/generateEntityTestFile.d.mts +9 -0
  166. package/build/generateEntityTestFile.d.mts.map +1 -0
  167. package/build/generateEntityTestFile.js +10 -7
  168. package/build/generateEntityTestFile.js.map +1 -1
  169. package/build/generateEnumFile.cjs +73 -0
  170. package/build/generateEnumFile.cjs.map +1 -0
  171. package/build/generateEnumFile.d.cts +9 -0
  172. package/build/generateEnumFile.d.cts.map +1 -0
  173. package/build/generateEnumFile.d.mts +9 -0
  174. package/build/generateEnumFile.d.mts.map +1 -0
  175. package/build/generateEnumFile.js +33 -43
  176. package/build/generateEnumFile.js.map +1 -1
  177. package/build/generateFactoriesFiles.cjs +28 -0
  178. package/build/generateFactoriesFiles.cjs.map +1 -0
  179. package/build/generateFactoriesFiles.d.cts +7 -0
  180. package/build/generateFactoriesFiles.d.cts.map +1 -0
  181. package/build/generateFactoriesFiles.d.mts +7 -0
  182. package/build/generateFactoriesFiles.d.mts.map +1 -0
  183. package/build/generateFactoriesFiles.js +21 -16
  184. package/build/generateFactoriesFiles.js.map +1 -1
  185. package/build/generateFlushFunction.cjs +61 -0
  186. package/build/generateFlushFunction.cjs.map +1 -0
  187. package/build/{generateFlushFunction.d.ts → generateFlushFunction.d.cts} +8 -4
  188. package/build/generateFlushFunction.d.cts.map +1 -0
  189. package/build/generateFlushFunction.d.mts +23 -0
  190. package/build/generateFlushFunction.d.mts.map +1 -0
  191. package/build/generateFlushFunction.js +32 -73
  192. package/build/generateFlushFunction.js.map +1 -1
  193. package/build/generateMetadataFile.cjs +290 -0
  194. package/build/generateMetadataFile.cjs.map +1 -0
  195. package/build/generateMetadataFile.d.cts +8 -0
  196. package/build/generateMetadataFile.d.cts.map +1 -0
  197. package/build/generateMetadataFile.d.mts +8 -0
  198. package/build/generateMetadataFile.d.mts.map +1 -0
  199. package/build/generateMetadataFile.js +111 -142
  200. package/build/generateMetadataFile.js.map +1 -1
  201. package/build/generatePgEnumFile.cjs +21 -0
  202. package/build/generatePgEnumFile.cjs.map +1 -0
  203. package/build/generatePgEnumFile.d.cts +9 -0
  204. package/build/generatePgEnumFile.d.cts.map +1 -0
  205. package/build/generatePgEnumFile.d.mts +9 -0
  206. package/build/generatePgEnumFile.d.mts.map +1 -0
  207. package/build/generatePgEnumFile.js +12 -9
  208. package/build/generatePgEnumFile.js.map +1 -1
  209. package/build/index.cjs +135 -0
  210. package/build/index.cjs.map +1 -0
  211. package/build/index.d.cts +12 -0
  212. package/build/index.d.cts.map +1 -0
  213. package/build/index.d.mts +12 -0
  214. package/build/index.d.mts.map +1 -0
  215. package/build/index.js +105 -147
  216. package/build/index.js.map +1 -1
  217. package/build/inheritance.cjs +213 -0
  218. package/build/inheritance.cjs.map +1 -0
  219. package/build/inheritance.d.cts +12 -0
  220. package/build/inheritance.d.cts.map +1 -0
  221. package/build/inheritance.d.mts +12 -0
  222. package/build/inheritance.d.mts.map +1 -0
  223. package/build/inheritance.js +193 -247
  224. package/build/inheritance.js.map +1 -1
  225. package/build/installSkills.cjs +68 -0
  226. package/build/installSkills.cjs.map +1 -0
  227. package/build/{installSkills.d.ts → installSkills.d.cts} +5 -1
  228. package/build/installSkills.d.cts.map +1 -0
  229. package/build/installSkills.d.mts +16 -0
  230. package/build/installSkills.d.mts.map +1 -0
  231. package/build/installSkills.js +55 -57
  232. package/build/installSkills.js.map +1 -1
  233. package/build/keywords.cjs +7 -0
  234. package/build/keywords.cjs.map +1 -0
  235. package/build/keywords.d.cts +5 -0
  236. package/build/keywords.d.cts.map +1 -0
  237. package/build/keywords.d.mts +5 -0
  238. package/build/keywords.d.mts.map +1 -0
  239. package/build/keywords.js +5 -4
  240. package/build/keywords.js.map +1 -1
  241. package/build/loadMetadata.cjs +39 -0
  242. package/build/loadMetadata.cjs.map +1 -0
  243. package/build/loadMetadata.d.cts +31 -0
  244. package/build/loadMetadata.d.cts.map +1 -0
  245. package/build/loadMetadata.d.mts +31 -0
  246. package/build/loadMetadata.d.mts.map +1 -0
  247. package/build/loadMetadata.js +32 -39
  248. package/build/loadMetadata.js.map +1 -1
  249. package/build/logger.cjs +28 -0
  250. package/build/logger.cjs.map +1 -0
  251. package/build/logger.d.cts +13 -0
  252. package/build/logger.d.cts.map +1 -0
  253. package/build/logger.d.mts +13 -0
  254. package/build/logger.d.mts.map +1 -0
  255. package/build/logger.js +17 -16
  256. package/build/logger.js.map +1 -1
  257. package/build/scanEntityFiles.cjs +46 -0
  258. package/build/scanEntityFiles.cjs.map +1 -0
  259. package/build/scanEntityFiles.d.cts +8 -0
  260. package/build/scanEntityFiles.d.cts.map +1 -0
  261. package/build/scanEntityFiles.d.mts +8 -0
  262. package/build/scanEntityFiles.d.mts.map +1 -0
  263. package/build/scanEntityFiles.js +37 -42
  264. package/build/scanEntityFiles.js.map +1 -1
  265. package/build/sortForeignKeys.cjs +99 -0
  266. package/build/sortForeignKeys.cjs.map +1 -0
  267. package/build/{sortForeignKeys.d.ts → sortForeignKeys.d.cts} +8 -4
  268. package/build/sortForeignKeys.d.cts.map +1 -0
  269. package/build/sortForeignKeys.d.mts +35 -0
  270. package/build/sortForeignKeys.d.mts.map +1 -0
  271. package/build/sortForeignKeys.js +88 -117
  272. package/build/sortForeignKeys.js.map +1 -1
  273. package/build/symbols.cjs +226 -0
  274. package/build/symbols.cjs.map +1 -0
  275. package/build/symbols.d.cts +114 -0
  276. package/build/symbols.d.cts.map +1 -0
  277. package/build/symbols.d.mts +114 -0
  278. package/build/symbols.d.mts.map +1 -0
  279. package/build/symbols.js +115 -116
  280. package/build/symbols.js.map +1 -1
  281. package/build/tsdoc.cjs +22 -0
  282. package/build/tsdoc.cjs.map +1 -0
  283. package/build/tsdoc.d.cts +15 -0
  284. package/build/tsdoc.d.cts.map +1 -0
  285. package/build/tsdoc.d.mts +15 -0
  286. package/build/tsdoc.d.mts.map +1 -0
  287. package/build/tsdoc.js +18 -15
  288. package/build/tsdoc.js.map +1 -1
  289. package/build/utils.cjs +173 -0
  290. package/build/utils.cjs.map +1 -0
  291. package/build/utils.d.cts +34 -0
  292. package/build/utils.d.cts.map +1 -0
  293. package/build/utils.d.mts +34 -0
  294. package/build/utils.d.mts.map +1 -0
  295. package/build/utils.js +112 -166
  296. package/build/utils.js.map +1 -1
  297. package/build/write-json-schema.cjs +23 -0
  298. package/build/write-json-schema.cjs.map +1 -0
  299. package/build/write-json-schema.d.cts +1 -0
  300. package/build/write-json-schema.d.mts +1 -0
  301. package/build/write-json-schema.js +19 -13
  302. package/build/write-json-schema.js.map +1 -1
  303. package/package.json +28 -5
  304. package/build/EntityDbMetadata.d.ts +0 -271
  305. package/build/codemods/Codemod.d.ts +0 -13
  306. package/build/codemods/Codemod.js.map +0 -1
  307. package/build/codemods/JscodeshiftMod.d.ts +0 -10
  308. package/build/codemods/codemod_0001-rename_has_async_property.d.ts +0 -6
  309. package/build/codemods/codemod_0002-rename_async_query_fields.d.ts +0 -6
  310. package/build/codemods/codemod_0003-rename_find_paginated.d.ts +0 -6
  311. package/build/codemods/index.d.ts +0 -8
  312. package/build/config.d.ts +0 -178
  313. package/build/docs/cache.d.ts +0 -13
  314. package/build/docs/generate-metadata-docs.d.ts +0 -5
  315. package/build/docs/index.d.ts +0 -13
  316. package/build/docs/parsing.d.ts +0 -45
  317. package/build/findEntityScopes.d.ts +0 -10
  318. package/build/foreignKeyOrdering.d.ts +0 -2
  319. package/build/generate.d.ts +0 -11
  320. package/build/generateEntitiesFile.d.ts +0 -6
  321. package/build/generateEntityCodegenFile.d.ts +0 -11
  322. package/build/generateEntityFile.d.ts +0 -5
  323. package/build/generateEntityTestFile.d.ts +0 -5
  324. package/build/generateEnumFile.d.ts +0 -4
  325. package/build/generateFactoriesFiles.d.ts +0 -3
  326. package/build/generateMetadataFile.d.ts +0 -4
  327. package/build/generatePgEnumFile.d.ts +0 -4
  328. package/build/index.d.ts +0 -11
  329. package/build/inheritance.d.ts +0 -9
  330. package/build/keywords.d.ts +0 -1
  331. package/build/loadMetadata.d.ts +0 -25
  332. package/build/logger.d.ts +0 -9
  333. package/build/scanEntityFiles.d.ts +0 -4
  334. package/build/symbols.d.ts +0 -110
  335. package/build/tsdoc.d.ts +0 -11
  336. package/build/utils.d.ts +0 -30
  337. package/build/write-json-schema.d.ts +0 -1
@@ -1,158 +1,116 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.findAllEntityScopes = findAllEntityScopes;
7
- const promises_1 = require("fs/promises");
8
- const path_1 = require("path");
9
- const change_case_1 = require("change-case");
10
- const jscodeshift_1 = __importDefault(require("jscodeshift"));
11
- const j = jscodeshift_1.default.withParser("ts");
1
+ import "./config.js";
2
+ import "./EntityDbMetadata.js";
3
+ import { camelCase } from "change-case";
4
+ import { join } from "path";
5
+ import jscodeshift from "jscodeshift";
6
+ import { readFile } from "fs/promises";
7
+ import "ast-types";
8
+ //#region src/findEntityScopes.ts
9
+ const j = jscodeshift.withParser("ts");
12
10
  /** Finds static scope declarations for all entity files. */
13
11
  async function findAllEntityScopes(config, entities) {
14
- return Object.fromEntries(await Promise.all(entities.map((entity) => findEntityScopes(config, entity))));
12
+ return Object.fromEntries(await Promise.all(entities.map((entity) => findEntityScopes(config, entity))));
15
13
  }
16
14
  /** Finds static scope declarations a given entity file. */
17
15
  async function findEntityScopes(config, entity) {
18
- const { name: entityName, scopeName: scopeTypeName } = entity;
19
- // i.e. `authorScope`, the conventional renamed-to-`scope` import users put in their entity files.
20
- const scopeFnName = `${(0, change_case_1.camelCase)(entityName)}Scope`;
21
- // i.e. `packages/tests/integration/src/entities/Author.ts` when `entityName` is "Author".
22
- const fileName = (0, path_1.join)(config.entitiesDirectory, `${entityName}.ts`);
23
- const contents = await readEntityFile(fileName);
24
- if (contents === undefined)
25
- return [entityName, []];
26
- if (contents.indexOf(scopeFnName) === -1)
27
- return [entityName, []];
28
- const program = j(contents).find(j.Program).nodes()[0];
29
- for (const statement of program.body) {
30
- const declaration = j.ExportNamedDeclaration.check(statement) || j.ExportDefaultDeclaration.check(statement)
31
- ? statement.declaration
32
- : statement;
33
- // i.e. `export class Author extends AuthorCodegen { ... }`.
34
- if (declaration && j.ClassDeclaration.check(declaration) && declaration.id?.name === entityName) {
35
- return [
36
- entityName,
37
- declaration.body.body.flatMap((member) => maybeScopeMember(member, entityName, scopeTypeName)),
38
- ];
39
- }
40
- }
41
- return [entityName, []];
16
+ const { name: entityName, scopeName: scopeTypeName } = entity;
17
+ const scopeFnName = `${camelCase(entityName)}Scope`;
18
+ const contents = await readEntityFile(join(config.entitiesDirectory, `${entityName}.ts`));
19
+ if (contents === void 0) return [entityName, []];
20
+ if (contents.indexOf(scopeFnName) === -1) return [entityName, []];
21
+ const program = j(contents).find(j.Program).nodes()[0];
22
+ for (const statement of program.body) {
23
+ const declaration = j.ExportNamedDeclaration.check(statement) || j.ExportDefaultDeclaration.check(statement) ? statement.declaration : statement;
24
+ if (declaration && j.ClassDeclaration.check(declaration) && declaration.id?.name === entityName) return [entityName, declaration.body.body.flatMap((member) => maybeScopeMember(member, entityName, scopeTypeName))];
25
+ }
26
+ return [entityName, []];
42
27
  }
43
28
  /** Reads an entity file if it already exists. */
44
29
  async function readEntityFile(fileName) {
45
- try {
46
- return await (0, promises_1.readFile)(fileName, "utf8");
47
- }
48
- catch (e) {
49
- if (isNoSuchFileError(e))
50
- return undefined;
51
- throw e;
52
- }
30
+ try {
31
+ return await readFile(fileName, "utf8");
32
+ } catch (e) {
33
+ if (isNoSuchFileError(e)) return void 0;
34
+ throw e;
35
+ }
53
36
  }
54
37
  /** Returns true for a missing user-owned entity file. */
55
38
  function isNoSuchFileError(e) {
56
- return typeof e === "object" && e !== null && "code" in e && e.code === "ENOENT";
39
+ return typeof e === "object" && e !== null && "code" in e && e.code === "ENOENT";
57
40
  }
58
41
  /** Converts a static property declaration into a generated scope member. */
59
42
  function maybeScopeMember(member, entityName, scopeTypeName) {
60
- if (!j.ClassProperty.check(member) || !member.static)
61
- return [];
62
- // i.e. accept `static adult = scope(...)`, but skip methods/getters/unsupported fields.
63
- if (!member.value || !j.Identifier.check(member.key))
64
- return [];
65
- if (!isScopeInitializer(member.value, entityName))
66
- return [];
67
- if (member.typeAnnotation) {
68
- if (!j.TSTypeAnnotation.check(member.typeAnnotation))
69
- return [];
70
- const type = member.typeAnnotation.typeAnnotation;
71
- if (!isScopeType(type, scopeTypeName))
72
- return [];
73
- return [{ name: member.key.name, type: j(type).toSource() }];
74
- }
75
- const type = inferScopeType(member.value, scopeTypeName);
76
- return type ? [{ name: member.key.name, type }] : [];
43
+ if (!j.ClassProperty.check(member) || !member.static) return [];
44
+ if (!member.value || !j.Identifier.check(member.key)) return [];
45
+ if (!isScopeInitializer(member.value, entityName)) return [];
46
+ if (member.typeAnnotation) {
47
+ if (!j.TSTypeAnnotation.check(member.typeAnnotation)) return [];
48
+ const type = member.typeAnnotation.typeAnnotation;
49
+ if (!isScopeType(type, scopeTypeName)) return [];
50
+ return [{
51
+ name: member.key.name,
52
+ type: j(type).toSource()
53
+ }];
54
+ }
55
+ const type = inferScopeType(member.value, scopeTypeName);
56
+ return type ? [{
57
+ name: member.key.name,
58
+ type
59
+ }] : [];
77
60
  }
78
61
  /** Infers a generated scope member type from an untyped static scope initializer. */
79
62
  function inferScopeType(initializer, scopeTypeName) {
80
- return isParameterizedScopeInitializer(initializer)
81
- ? maybeParameterizedScope(initializer, scopeTypeName)
82
- : scopeTypeName;
63
+ return isParameterizedScopeInitializer(initializer) ? maybeParameterizedScope(initializer, scopeTypeName) : scopeTypeName;
83
64
  }
84
65
  /** Returns true for `scope.fn(...)` initializers. */
85
66
  function isParameterizedScopeInitializer(initializer) {
86
- return (j.CallExpression.check(initializer) &&
87
- j.MemberExpression.check(initializer.callee) &&
88
- !initializer.callee.computed &&
89
- j.Identifier.check(initializer.callee.property) &&
90
- initializer.callee.property.name === "fn");
67
+ return j.CallExpression.check(initializer) && j.MemberExpression.check(initializer.callee) && !initializer.callee.computed && j.Identifier.check(initializer.callee.property) && initializer.callee.property.name === "fn";
91
68
  }
92
69
  /** Returns a function type for `scope.fn((prefix: string) => ...)` initializers. */
93
70
  function maybeParameterizedScope(initializer, scopeTypeName) {
94
- if (!j.CallExpression.check(initializer))
95
- return undefined;
96
- if (!j.MemberExpression.check(initializer.callee))
97
- return undefined;
98
- if (initializer.callee.computed || !j.Identifier.check(initializer.callee.property))
99
- return undefined;
100
- if (initializer.callee.property.name !== "fn")
101
- return undefined;
102
- const fn = initializer.arguments[0];
103
- if (!fn || (!j.ArrowFunctionExpression.check(fn) && !j.FunctionExpression.check(fn)))
104
- return undefined;
105
- const params = fn.params.map(parameterType);
106
- if (params.some((param) => param === undefined))
107
- return undefined;
108
- return `(${params.join(", ")}) => ${scopeTypeName}`;
71
+ if (!j.CallExpression.check(initializer)) return void 0;
72
+ if (!j.MemberExpression.check(initializer.callee)) return void 0;
73
+ if (initializer.callee.computed || !j.Identifier.check(initializer.callee.property)) return void 0;
74
+ if (initializer.callee.property.name !== "fn") return void 0;
75
+ const fn = initializer.arguments[0];
76
+ if (!fn || !j.ArrowFunctionExpression.check(fn) && !j.FunctionExpression.check(fn)) return void 0;
77
+ const params = fn.params.map(parameterType);
78
+ if (params.some((param) => param === void 0)) return void 0;
79
+ return `(${params.join(", ")}) => ${scopeTypeName}`;
109
80
  }
110
81
  /** Returns a function-type parameter, i.e. `prefix: string`, when syntax-only inference is safe. */
111
82
  function parameterType(param) {
112
- if (j.Identifier.check(param)) {
113
- if (!param.typeAnnotation || !j.TSTypeAnnotation.check(param.typeAnnotation))
114
- return undefined;
115
- const optional = param.optional ? "?" : "";
116
- return `${param.name}${optional}: ${j(param.typeAnnotation.typeAnnotation).toSource()}`;
117
- }
118
- if (j.RestElement.check(param) && j.Identifier.check(param.argument)) {
119
- const typeAnnotation = param.typeAnnotation ?? param.argument.typeAnnotation;
120
- if (!typeAnnotation || !j.TSTypeAnnotation.check(typeAnnotation))
121
- return undefined;
122
- return `...${param.argument.name}: ${j(typeAnnotation.typeAnnotation).toSource()}`;
123
- }
124
- return undefined;
83
+ if (j.Identifier.check(param)) {
84
+ if (!param.typeAnnotation || !j.TSTypeAnnotation.check(param.typeAnnotation)) return void 0;
85
+ const optional = param.optional ? "?" : "";
86
+ return `${param.name}${optional}: ${j(param.typeAnnotation.typeAnnotation).toSource()}`;
87
+ }
88
+ if (j.RestElement.check(param) && j.Identifier.check(param.argument)) {
89
+ const typeAnnotation = param.typeAnnotation ?? param.argument.typeAnnotation;
90
+ if (!typeAnnotation || !j.TSTypeAnnotation.check(typeAnnotation)) return void 0;
91
+ return `...${param.argument.name}: ${j(typeAnnotation.typeAnnotation).toSource()}`;
92
+ }
125
93
  }
126
94
  /** Returns true for `EntityScope` and function types returning `EntityScope`. */
127
95
  function isScopeType(type, scopeTypeName) {
128
- // i.e. `AuthorScope`.
129
- if (j.TSTypeReference.check(type) && j.Identifier.check(type.typeName))
130
- return type.typeName.name === scopeTypeName;
131
- // i.e. `(prefix: string) => AuthorScope`.
132
- if (j.TSFunctionType.check(type) && type.typeAnnotation && j.TSTypeAnnotation.check(type.typeAnnotation)) {
133
- return isScopeType(type.typeAnnotation.typeAnnotation, scopeTypeName);
134
- }
135
- if (j.TSParenthesizedType.check(type))
136
- return isScopeType(type.typeAnnotation, scopeTypeName);
137
- return false;
96
+ if (j.TSTypeReference.check(type) && j.Identifier.check(type.typeName)) return type.typeName.name === scopeTypeName;
97
+ if (j.TSFunctionType.check(type) && type.typeAnnotation && j.TSTypeAnnotation.check(type.typeAnnotation)) return isScopeType(type.typeAnnotation.typeAnnotation, scopeTypeName);
98
+ if (j.TSParenthesizedType.check(type)) return isScopeType(type.typeAnnotation, scopeTypeName);
99
+ return false;
138
100
  }
139
101
  /** Returns true for scope initializers, I.e. `scope(...)`, `scope(...).orderBy(...)`, or `Author.adult...`. */
140
102
  function isScopeInitializer(initializer, entityName) {
141
- if (!j.CallExpression.check(initializer) && !j.MemberExpression.check(initializer))
142
- return false;
143
- return isScopeRootedExpression(initializer, entityName);
103
+ if (!j.CallExpression.check(initializer) && !j.MemberExpression.check(initializer)) return false;
104
+ return isScopeRootedExpression(initializer, entityName);
144
105
  }
145
106
  /** Returns true for a call/property expression chain rooted at `scope` or the current entity. */
146
107
  function isScopeRootedExpression(expression, entityName) {
147
- // i.e. `scope({ age: { gte: 18 } })`.
148
- if (j.Identifier.check(expression))
149
- return expression.name === "scope" || expression.name === entityName;
150
- if (j.CallExpression.check(expression))
151
- return isScopeRootedExpression(expression.callee, entityName);
152
- // i.e. `scope.fn((prefix) => (a) => a.firstName.like(`${prefix}%`))` or `Author.adult.orderBy(...)`.
153
- if (j.MemberExpression.check(expression) && !expression.computed) {
154
- return isScopeRootedExpression(expression.object, entityName);
155
- }
156
- return false;
108
+ if (j.Identifier.check(expression)) return expression.name === "scope" || expression.name === entityName;
109
+ if (j.CallExpression.check(expression)) return isScopeRootedExpression(expression.callee, entityName);
110
+ if (j.MemberExpression.check(expression) && !expression.computed) return isScopeRootedExpression(expression.object, entityName);
111
+ return false;
157
112
  }
113
+ //#endregion
114
+ export { findAllEntityScopes };
115
+
158
116
  //# sourceMappingURL=findEntityScopes.js.map
@@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B,CAAC,UAAU,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;IACtG,qGAAqG;IACrG,IAAI,CAAC,CAAC,gBAAgB,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,UAAU,CAAC,QAAQ,EAAE,CAAC;QACjE,OAAO,uBAAuB,CAAC,UAAU,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;IAChE,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC"}
1
+ {"version":3,"file":"findEntityScopes.js","names":[],"sources":["../src/findEntityScopes.ts"],"sourcesContent":["import { readFile } from \"fs/promises\";\nimport { join } from \"path\";\n\nimport { type namedTypes } from \"ast-types\";\nimport { camelCase } from \"change-case\";\nimport jscodeshift from \"jscodeshift\";\n\nimport { type Config } from \"./config.ts\";\nimport { type Entity } from \"./EntityDbMetadata.ts\";\n\nconst j = jscodeshift.withParser(\"ts\");\n\ntype Expression = NonNullable<namedTypes.ClassProperty[\"value\"]>;\ntype Parameter = namedTypes.ArrowFunctionExpression[\"params\"][number];\ntype TypeNode = namedTypes.TSTypeAnnotation[\"typeAnnotation\"];\n\n/** Each `static active = ...` scope in an entity. */\nexport interface ScopeMember {\n // I.e. \"adult\" from `static adult: AuthorScope = scope(...)`.\n name: string;\n // I.e. \"AuthorScope\" or \"(prefix: string) => AuthorScope\".\n type: string;\n}\n\nexport type ScopeMembersByEntity = Record<string, ScopeMember[]>;\n\n/** Finds static scope declarations for all entity files. */\nexport async function findAllEntityScopes(config: Config, entities: Entity[]): Promise<ScopeMembersByEntity> {\n return Object.fromEntries(await Promise.all(entities.map((entity) => findEntityScopes(config, entity))));\n}\n\n/** Finds static scope declarations a given entity file. */\nasync function findEntityScopes(config: Config, entity: Entity): Promise<[string, ScopeMember[]]> {\n const { name: entityName, scopeName: scopeTypeName } = entity;\n // i.e. `authorScope`, the conventional renamed-to-`scope` import users put in their entity files.\n const scopeFnName = `${camelCase(entityName)}Scope`;\n\n // i.e. `packages/tests/integration/src/entities/Author.ts` when `entityName` is \"Author\".\n const fileName = join(config.entitiesDirectory, `${entityName}.ts`);\n const contents = await readEntityFile(fileName);\n if (contents === undefined) return [entityName, []];\n if (contents.indexOf(scopeFnName) === -1) return [entityName, []];\n\n const program = j(contents).find(j.Program).nodes()[0];\n for (const statement of program.body) {\n const declaration =\n j.ExportNamedDeclaration.check(statement) || j.ExportDefaultDeclaration.check(statement)\n ? statement.declaration\n : statement;\n // i.e. `export class Author extends AuthorCodegen { ... }`.\n if (declaration && j.ClassDeclaration.check(declaration) && declaration.id?.name === entityName) {\n return [\n entityName,\n declaration.body.body.flatMap((member) => maybeScopeMember(member, entityName, scopeTypeName)),\n ];\n }\n }\n return [entityName, []];\n}\n\n/** Reads an entity file if it already exists. */\nasync function readEntityFile(fileName: string): Promise<string | undefined> {\n try {\n return await readFile(fileName, \"utf8\");\n } catch (e) {\n if (isNoSuchFileError(e)) return undefined;\n throw e;\n }\n}\n\n/** Returns true for a missing user-owned entity file. */\nfunction isNoSuchFileError(e: unknown): boolean {\n return typeof e === \"object\" && e !== null && \"code\" in e && e.code === \"ENOENT\";\n}\n\n/** Converts a static property declaration into a generated scope member. */\nfunction maybeScopeMember(member: namedTypes.Node, entityName: string, scopeTypeName: string): ScopeMember[] {\n if (!j.ClassProperty.check(member) || !member.static) return [];\n // i.e. accept `static adult = scope(...)`, but skip methods/getters/unsupported fields.\n if (!member.value || !j.Identifier.check(member.key)) return [];\n if (!isScopeInitializer(member.value, entityName)) return [];\n if (member.typeAnnotation) {\n if (!j.TSTypeAnnotation.check(member.typeAnnotation)) return [];\n const type = member.typeAnnotation.typeAnnotation;\n if (!isScopeType(type, scopeTypeName)) return [];\n return [{ name: member.key.name, type: j(type).toSource() }];\n }\n const type = inferScopeType(member.value, scopeTypeName);\n return type ? [{ name: member.key.name, type }] : [];\n}\n\n/** Infers a generated scope member type from an untyped static scope initializer. */\nfunction inferScopeType(initializer: Expression, scopeTypeName: string): string | undefined {\n return isParameterizedScopeInitializer(initializer)\n ? maybeParameterizedScope(initializer, scopeTypeName)\n : scopeTypeName;\n}\n\n/** Returns true for `scope.fn(...)` initializers. */\nfunction isParameterizedScopeInitializer(initializer: Expression): boolean {\n return (\n j.CallExpression.check(initializer) &&\n j.MemberExpression.check(initializer.callee) &&\n !initializer.callee.computed &&\n j.Identifier.check(initializer.callee.property) &&\n initializer.callee.property.name === \"fn\"\n );\n}\n\n/** Returns a function type for `scope.fn((prefix: string) => ...)` initializers. */\nfunction maybeParameterizedScope(initializer: Expression, scopeTypeName: string): string | undefined {\n if (!j.CallExpression.check(initializer)) return undefined;\n if (!j.MemberExpression.check(initializer.callee)) return undefined;\n if (initializer.callee.computed || !j.Identifier.check(initializer.callee.property)) return undefined;\n if (initializer.callee.property.name !== \"fn\") return undefined;\n const fn = initializer.arguments[0];\n if (!fn || (!j.ArrowFunctionExpression.check(fn) && !j.FunctionExpression.check(fn))) return undefined;\n const params = fn.params.map(parameterType);\n if (params.some((param) => param === undefined)) return undefined;\n return `(${params.join(\", \")}) => ${scopeTypeName}`;\n}\n\n/** Returns a function-type parameter, i.e. `prefix: string`, when syntax-only inference is safe. */\nfunction parameterType(param: Parameter): string | undefined {\n if (j.Identifier.check(param)) {\n if (!param.typeAnnotation || !j.TSTypeAnnotation.check(param.typeAnnotation)) return undefined;\n const optional = param.optional ? \"?\" : \"\";\n return `${param.name}${optional}: ${j(param.typeAnnotation.typeAnnotation).toSource()}`;\n }\n if (j.RestElement.check(param) && j.Identifier.check(param.argument)) {\n const typeAnnotation = param.typeAnnotation ?? param.argument.typeAnnotation;\n if (!typeAnnotation || !j.TSTypeAnnotation.check(typeAnnotation)) return undefined;\n return `...${param.argument.name}: ${j(typeAnnotation.typeAnnotation).toSource()}`;\n }\n return undefined;\n}\n\n/** Returns true for `EntityScope` and function types returning `EntityScope`. */\nfunction isScopeType(type: TypeNode, scopeTypeName: string): boolean {\n // i.e. `AuthorScope`.\n if (j.TSTypeReference.check(type) && j.Identifier.check(type.typeName)) return type.typeName.name === scopeTypeName;\n // i.e. `(prefix: string) => AuthorScope`.\n if (j.TSFunctionType.check(type) && type.typeAnnotation && j.TSTypeAnnotation.check(type.typeAnnotation)) {\n return isScopeType(type.typeAnnotation.typeAnnotation, scopeTypeName);\n }\n if (j.TSParenthesizedType.check(type)) return isScopeType(type.typeAnnotation, scopeTypeName);\n return false;\n}\n\n/** Returns true for scope initializers, I.e. `scope(...)`, `scope(...).orderBy(...)`, or `Author.adult...`. */\nfunction isScopeInitializer(initializer: Expression, entityName: string): boolean {\n if (!j.CallExpression.check(initializer) && !j.MemberExpression.check(initializer)) return false;\n return isScopeRootedExpression(initializer, entityName);\n}\n\n/** Returns true for a call/property expression chain rooted at `scope` or the current entity. */\nfunction isScopeRootedExpression(expression: Expression, entityName: string): boolean {\n // i.e. `scope({ age: { gte: 18 } })`.\n if (j.Identifier.check(expression)) return expression.name === \"scope\" || expression.name === entityName;\n if (j.CallExpression.check(expression)) return isScopeRootedExpression(expression.callee, entityName);\n // i.e. `scope.fn((prefix) => (a) => a.firstName.like(`${prefix}%`))` or `Author.adult.orderBy(...)`.\n if (j.MemberExpression.check(expression) && !expression.computed) {\n return isScopeRootedExpression(expression.object, entityName);\n }\n return false;\n}\n"],"mappings":";;;;;;;;AAUA,MAAM,IAAI,YAAY,WAAW,IAAI;;AAiBrC,eAAsB,oBAAoB,QAAgB,UAAmD;CAC3G,OAAO,OAAO,YAAY,MAAM,QAAQ,IAAI,SAAS,KAAK,WAAW,iBAAiB,QAAQ,MAAM,CAAC,CAAC,CAAC;AACzG;;AAGA,eAAe,iBAAiB,QAAgB,QAAkD;CAChG,MAAM,EAAE,MAAM,YAAY,WAAW,kBAAkB;CAEvD,MAAM,cAAc,GAAG,UAAU,UAAU,EAAE;CAI7C,MAAM,WAAW,MAAM,eADN,KAAK,OAAO,mBAAmB,GAAG,WAAW,IACjB,CAAC;CAC9C,IAAI,aAAa,KAAA,GAAW,OAAO,CAAC,YAAY,CAAC,CAAC;CAClD,IAAI,SAAS,QAA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AAiB,MAAM,UAAU,KAAK,CAAC,WAAW,UACtD,OAAO,wBAAwB,WAAW,QAAQ,UAAU;CAE9D,OAAO;AACT"}
@@ -0,0 +1,52 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_utils = require("./utils.cjs");
3
+ const require_logger = require("./logger.cjs");
4
+ const require_sortForeignKeys = require("./sortForeignKeys.cjs");
5
+ require("./index.cjs");
6
+ require("./EntityDbMetadata.cjs");
7
+ let fs = require("fs");
8
+ //#region src/foreignKeyOrdering.ts
9
+ async function maybeSetForeignKeyOrdering(config, entities) {
10
+ if (!entities.some((e) => e.nonDeferredFks.length > 0)) {
11
+ for (const entity of entities) entity.nonDeferredFkOrder = 0;
12
+ return;
13
+ }
14
+ const { notNullCycles } = require_sortForeignKeys.sortByNonDeferredForeignKeys(entities);
15
+ const { nonDeferredForeignKeys: setting = "warn" } = config;
16
+ const nonDeferredFks = entities.flatMap((e) => e.nonDeferredFks.map((m2o) => ({
17
+ entity: e,
18
+ m2o
19
+ })));
20
+ if (setting === "error" || setting === "warn") {
21
+ require_logger.logger[setting](`Found ${nonDeferredFks.length} foreign keys that are not DEFERRABLE/INITIALLY DEFERRED`);
22
+ for (const { entity, m2o } of nonDeferredFks) console.log(`${entity.tableName}.${m2o.columnName}`);
23
+ console.log("");
24
+ console.log("Please either:");
25
+ console.log(" - Alter your migration to create the FKs as deferred (ideal)");
26
+ console.log(" - Execute the generated alter-foreign-keys.sql file (one-time fix)");
27
+ console.log(" - Set 'nonDeferredFks: ignore' in joist-config.json");
28
+ console.log("");
29
+ console.log("See https://joist-orm.io/getting-started/schema-assumptions#deferred-constraints");
30
+ console.log("");
31
+ await writeAlterTables(nonDeferredFks);
32
+ } else if (setting === "ignore") {} else require_utils.assertNever(setting);
33
+ if (notNullCycles.length > 0) {
34
+ require_logger.logger.error(`Found a schema cycle of not-null foreign keys:`);
35
+ notNullCycles.forEach((cycle) => console.log(cycle));
36
+ console.log("");
37
+ console.log("These cycles can cause fatal em.flush & flush_test_database errors.");
38
+ console.log("");
39
+ console.log("Please make one of the FKs involved in the cycle nullable.");
40
+ console.log("");
41
+ }
42
+ }
43
+ async function writeAlterTables(nonDeferredFks) {
44
+ const queries = nonDeferredFks.map(({ entity, m2o }) => {
45
+ return `ALTER TABLE ${entity.tableName} ALTER CONSTRAINT ${m2o.constraintName} DEFERRABLE INITIALLY DEFERRED;`;
46
+ });
47
+ await fs.promises.writeFile("./alter-foreign-keys.sql", queries.join("\n"));
48
+ }
49
+ //#endregion
50
+ exports.maybeSetForeignKeyOrdering = maybeSetForeignKeyOrdering;
51
+
52
+ //# sourceMappingURL=foreignKeyOrdering.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"foreignKeyOrdering.cjs","names":["sortByNonDeferredForeignKeys"],"sources":["../src/foreignKeyOrdering.ts"],"sourcesContent":["import { promises as fs } from \"fs\";\n\nimport { type ManyToOneField, type PolymorphicFieldComponent } from \"./EntityDbMetadata.ts\";\nimport { type Config, type EntityDbMetadata } from \"./index.ts\";\nimport { logger } from \"./logger.ts\";\nimport { sortByNonDeferredForeignKeys } from \"./sortForeignKeys.ts\";\nimport { assertNever } from \"./utils.ts\";\n\nexport async function maybeSetForeignKeyOrdering(config: Config, entities: EntityDbMetadata[]): Promise<void> {\n // Hopefully all FKs are deferred, but if not...\n const hasAnyNonDeferredFks = entities.some((e) => e.nonDeferredFks.length > 0);\n if (!hasAnyNonDeferredFks) {\n // Great, nothing to do\n for (const entity of entities) entity.nonDeferredFkOrder = 0;\n return;\n }\n\n // Topo sort the non-deferred FKs into a DAG to establish insert/flush order\n const { notNullCycles } = sortByNonDeferredForeignKeys(entities);\n\n const { nonDeferredForeignKeys: setting = \"warn\" } = config;\n const nonDeferredFks = entities.flatMap((e) => e.nonDeferredFks.map((m2o) => ({ entity: e, m2o })));\n\n if (setting === \"error\" || setting === \"warn\") {\n logger[setting](`Found ${nonDeferredFks.length} foreign keys that are not DEFERRABLE/INITIALLY DEFERRED`);\n for (const { entity, m2o } of nonDeferredFks) console.log(`${entity.tableName}.${m2o.columnName}`);\n console.log(\"\");\n\n console.log(\"Please either:\");\n console.log(\" - Alter your migration to create the FKs as deferred (ideal)\");\n console.log(\" - Execute the generated alter-foreign-keys.sql file (one-time fix)\");\n console.log(\" - Set 'nonDeferredFks: ignore' in joist-config.json\");\n console.log(\"\");\n\n console.log(\"See https://joist-orm.io/getting-started/schema-assumptions#deferred-constraints\");\n console.log(\"\");\n\n await writeAlterTables(nonDeferredFks);\n } else if (setting === \"ignore\") {\n // We trust the user to know what they're doing\n } else {\n assertNever(setting);\n }\n\n // Always treat these as errors, even if `ignore` is set; maybe we need a `ignore-even-not-null-cycles`?\n // But they would still probably break flush_test_database. Unless we tell it to disable constraints,\n // like `ALTER TABLE your_table_name DISABLE TRIGGER ALL;`. But still unsure how we'd insert new rows.\n if (notNullCycles.length > 0) {\n logger.error(`Found a schema cycle of not-null foreign keys:`);\n notNullCycles.forEach((cycle) => console.log(cycle));\n console.log(\"\");\n console.log(\"These cycles can cause fatal em.flush & flush_test_database errors.\");\n console.log(\"\");\n console.log(\"Please make one of the FKs involved in the cycle nullable.\");\n console.log(\"\");\n }\n}\n\nasync function writeAlterTables(\n nonDeferredFks: Array<{\n entity: EntityDbMetadata;\n m2o: ManyToOneField | PolymorphicFieldComponent;\n }>,\n): Promise<void> {\n const queries = nonDeferredFks.map(({ entity, m2o }) => {\n return `ALTER TABLE ${entity.tableName} ALTER CONSTRAINT ${m2o.constraintName} DEFERRABLE INITIALLY DEFERRED;`;\n });\n await fs.writeFile(\"./alter-foreign-keys.sql\", queries.join(\"\\n\"));\n}\n"],"mappings":";;;;;;;;AAQA,eAAsB,2BAA2B,QAAgB,UAA6C;CAG5G,IAAI,CADyB,SAAS,MAAM,MAAM,EAAE,eAAe,SAAS,CACpD,GAAG;EAEzB,KAAK,MAAM,UAAU,UAAU,OAAO,qBAAqB;EAC3D;CACF;CAGA,MAAM,EAAE,kBAAkBA,wBAAAA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Ordering.d.ts
5
+ declare function maybeSetForeignKeyOrdering(config: Config, entities: EntityDbMetadata[]): Promise<void>;
6
+ //#endregion
7
+ export { maybeSetForeignKeyOrdering };
8
+ //# sourceMappingURL=foreignKeyOrdering.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"foreignKeyOrdering.d.cts","names":[],"sources":["../src/foreignKeyOrdering.ts"],"mappings":";;;;iBAQsB,2BAA2B,QAAQ,QAAQ,UAAU,qBAAqB"}
@@ -0,0 +1,8 @@
1
+ import { Config } from "./config.mjs";
2
+ import "./index.mjs";
3
+ import { EntityDbMetadata } from "./EntityDbMetadata.mjs";
4
+ //#region src/foreignKeyOrdering.d.ts
5
+ declare function maybeSetForeignKeyOrdering(config: Config, entities: EntityDbMetadata[]): Promise<void>;
6
+ //#endregion
7
+ export { maybeSetForeignKeyOrdering };
8
+ //# sourceMappingURL=foreignKeyOrdering.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"foreignKeyOrdering.d.mts","names":[],"sources":["../src/foreignKeyOrdering.ts"],"mappings":";;;;iBAQsB,2BAA2B,QAAQ,QAAQ,UAAU,qBAAqB"}
@@ -1,60 +1,51 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.maybeSetForeignKeyOrdering = maybeSetForeignKeyOrdering;
4
- const fs_1 = require("fs");
5
- const logger_1 = require("./logger");
6
- const sortForeignKeys_1 = require("./sortForeignKeys");
7
- const utils_1 = require("./utils");
1
+ import { assertNever } from "./utils.js";
2
+ import { logger } from "./logger.js";
3
+ import { sortByNonDeferredForeignKeys } from "./sortForeignKeys.js";
4
+ import "./index.js";
5
+ import "./EntityDbMetadata.js";
6
+ import { promises } from "fs";
7
+ //#region src/foreignKeyOrdering.ts
8
8
  async function maybeSetForeignKeyOrdering(config, entities) {
9
- // Hopefully all FKs are deferred, but if not...
10
- const hasAnyNonDeferredFks = entities.some((e) => e.nonDeferredFks.length > 0);
11
- if (!hasAnyNonDeferredFks) {
12
- // Great, nothing to do
13
- for (const entity of entities)
14
- entity.nonDeferredFkOrder = 0;
15
- return;
16
- }
17
- // Topo sort the non-deferred FKs into a DAG to establish insert/flush order
18
- const { notNullCycles } = (0, sortForeignKeys_1.sortByNonDeferredForeignKeys)(entities);
19
- const { nonDeferredForeignKeys: setting = "warn" } = config;
20
- const nonDeferredFks = entities.flatMap((e) => e.nonDeferredFks.map((m2o) => ({ entity: e, m2o })));
21
- if (setting === "error" || setting === "warn") {
22
- logger_1.logger[setting](`Found ${nonDeferredFks.length} foreign keys that are not DEFERRABLE/INITIALLY DEFERRED`);
23
- for (const { entity, m2o } of nonDeferredFks)
24
- console.log(`${entity.tableName}.${m2o.columnName}`);
25
- console.log("");
26
- console.log("Please either:");
27
- console.log(" - Alter your migration to create the FKs as deferred (ideal)");
28
- console.log(" - Execute the generated alter-foreign-keys.sql file (one-time fix)");
29
- console.log(" - Set 'nonDeferredFks: ignore' in joist-config.json");
30
- console.log("");
31
- console.log("See https://joist-orm.io/getting-started/schema-assumptions#deferred-constraints");
32
- console.log("");
33
- await writeAlterTables(nonDeferredFks);
34
- }
35
- else if (setting === "ignore") {
36
- // We trust the user to know what they're doing
37
- }
38
- else {
39
- (0, utils_1.assertNever)(setting);
40
- }
41
- // Always treat these as errors, even if `ignore` is set; maybe we need a `ignore-even-not-null-cycles`?
42
- // But they would still probably break flush_test_database. Unless we tell it to disable constraints,
43
- // like `ALTER TABLE your_table_name DISABLE TRIGGER ALL;`. But still unsure how we'd insert new rows.
44
- if (notNullCycles.length > 0) {
45
- logger_1.logger.error(`Found a schema cycle of not-null foreign keys:`);
46
- notNullCycles.forEach((cycle) => console.log(cycle));
47
- console.log("");
48
- console.log("These cycles can cause fatal em.flush & flush_test_database errors.");
49
- console.log("");
50
- console.log("Please make one of the FKs involved in the cycle nullable.");
51
- console.log("");
52
- }
9
+ if (!entities.some((e) => e.nonDeferredFks.length > 0)) {
10
+ for (const entity of entities) entity.nonDeferredFkOrder = 0;
11
+ return;
12
+ }
13
+ const { notNullCycles } = sortByNonDeferredForeignKeys(entities);
14
+ const { nonDeferredForeignKeys: setting = "warn" } = config;
15
+ const nonDeferredFks = entities.flatMap((e) => e.nonDeferredFks.map((m2o) => ({
16
+ entity: e,
17
+ m2o
18
+ })));
19
+ if (setting === "error" || setting === "warn") {
20
+ logger[setting](`Found ${nonDeferredFks.length} foreign keys that are not DEFERRABLE/INITIALLY DEFERRED`);
21
+ for (const { entity, m2o } of nonDeferredFks) console.log(`${entity.tableName}.${m2o.columnName}`);
22
+ console.log("");
23
+ console.log("Please either:");
24
+ console.log(" - Alter your migration to create the FKs as deferred (ideal)");
25
+ console.log(" - Execute the generated alter-foreign-keys.sql file (one-time fix)");
26
+ console.log(" - Set 'nonDeferredFks: ignore' in joist-config.json");
27
+ console.log("");
28
+ console.log("See https://joist-orm.io/getting-started/schema-assumptions#deferred-constraints");
29
+ console.log("");
30
+ await writeAlterTables(nonDeferredFks);
31
+ } else if (setting === "ignore") {} else assertNever(setting);
32
+ if (notNullCycles.length > 0) {
33
+ logger.error(`Found a schema cycle of not-null foreign keys:`);
34
+ notNullCycles.forEach((cycle) => console.log(cycle));
35
+ console.log("");
36
+ console.log("These cycles can cause fatal em.flush & flush_test_database errors.");
37
+ console.log("");
38
+ console.log("Please make one of the FKs involved in the cycle nullable.");
39
+ console.log("");
40
+ }
53
41
  }
54
42
  async function writeAlterTables(nonDeferredFks) {
55
- const queries = nonDeferredFks.map(({ entity, m2o }) => {
56
- return `ALTER TABLE ${entity.tableName} ALTER CONSTRAINT ${m2o.constraintName} DEFERRABLE INITIALLY DEFERRED;`;
57
- });
58
- await fs_1.promises.writeFile("./alter-foreign-keys.sql", queries.join("\n"));
43
+ const queries = nonDeferredFks.map(({ entity, m2o }) => {
44
+ return `ALTER TABLE ${entity.tableName} ALTER CONSTRAINT ${m2o.constraintName} DEFERRABLE INITIALLY DEFERRED;`;
45
+ });
46
+ await promises.writeFile("./alter-foreign-keys.sql", queries.join("\n"));
59
47
  }
48
+ //#endregion
49
+ export { maybeSetForeignKeyOrdering };
50
+
60
51
  //# sourceMappingURL=foreignKeyOrdering.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"foreignKeyOrdering.js","sourceRoot":"","sources":["../src/foreignKeyOrdering.ts"],"names":[],"mappings":";;;AAAA,2BAAoC;AAIpC,qCAAkC;AAClC,uDAAiE;AACjE,mCAAsC;AAE/B,KAAK,qCAAqC,MAAc,EAAE,QAA4B;IAC3F,gDAAgD;IAChD,MAAM,oBAAoB,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,cAAc,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAC/E,IAAI,CAAC,oBAAoB,EAAE,CAAC;QAC1B,uBAAuB;QACvB,KAAK,MAAM,MAAM,IAAI,QAAQ;YAAE,MAAM,CAAC,kBAAkB,GAAG,CAAC,CAAC;QAC7D,OAAO;IACT,CAAC;IAED,4EAA4E;IAC5E,MAAM,EAAE,aAAa,EAAE,GAAG,IAAA,8CAA4B,EAAC,QAAQ,CAAC,CAAC;IAEjE,MAAM,EAAE,sBAAsB,EAAE,OAAO,GAAG,MAAM,EAAE,GAAG,MAAM,CAAC;IAC5D,MAAM,cAAc,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC;IAEpG,IAAI,OAAO,KAAK,OAAO,IAAI,OAAO,KAAK,MAAM,EAAE,CAAC;QAC9C,eAAM,CAAC,OAAO,CAAC,CAAC,SAAS,cAAc,CAAC,MAAM,0DAA0D,CAAC,CAAC;QAC1G,KAAK,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,IAAI,cAAc;YAAE,OAAO,CAAC,GAAG,CAAC,GAAG,MA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AAO,GAAG,cAAc,CAAC,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,EAAE,EAAE;QACrD,OAAO,eAAe,MAAM,CAAC,SAAS,qBAAqB,GAAG,CAAC,cAAc,iCAAiC,CAAC;IACjH,CAAC,CAAC,CAAC;IACH,MAAM,aAAE,CAAC,SAAS,CAAC,0BAA0B,EAAE,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;AACrE,CAAC"}
1
+ {"version":3,"file":"foreignKeyOrdering.js","names":["fs"],"sources":["../src/foreignKeyOrdering.ts"],"sourcesContent":["import { promises as fs } from \"fs\";\n\nimport { type ManyToOneField, type PolymorphicFieldComponent } from \"./EntityDbMetadata.ts\";\nimport { type Config, type EntityDbMetadata } from \"./index.ts\";\nimport { logger } from \"./logger.ts\";\nimport { sortByNonDeferredForeignKeys } from \"./sortForeignKeys.ts\";\nimport { assertNever } from \"./utils.ts\";\n\nexport async function maybeSetForeignKeyOrdering(config: Config, entities: EntityDbMetadata[]): Promise<void> {\n // Hopefully all FKs are deferred, but if not...\n const hasAnyNonDeferredFks = entities.some((e) => e.nonDeferredFks.length > 0);\n if (!hasAnyNonDeferredFks) {\n // Great, nothing to do\n for (const entity of entities) entity.nonDeferredFkOrder = 0;\n return;\n }\n\n // Topo sort the non-deferred FKs into a DAG to establish insert/flush order\n const { notNullCycles } = sortByNonDeferredForeignKeys(entities);\n\n const { nonDeferredForeignKeys: setting = \"warn\" } = config;\n const nonDeferredFks = entities.flatMap((e) => e.nonDeferredFks.map((m2o) => ({ entity: e, m2o })));\n\n if (setting === \"error\" || setting === \"warn\") {\n logger[setting](`Found ${nonDeferredFks.length} foreign keys that are not DEFERRABLE/INITIALLY DEFERRED`);\n for (const { entity, m2o } of nonDeferredFks) console.log(`${entity.tableName}.${m2o.columnName}`);\n console.log(\"\");\n\n console.log(\"Please either:\");\n console.log(\" - Alter your migration to create the FKs as deferred (ideal)\");\n console.log(\" - Execute the generated alter-foreign-keys.sql file (one-time fix)\");\n console.log(\" - Set 'nonDeferredFks: ignore' in joist-config.json\");\n console.log(\"\");\n\n console.log(\"See https://joist-orm.io/getting-started/schema-assumptions#deferred-constraints\");\n console.log(\"\");\n\n await writeAlterTables(nonDeferredFks);\n } else if (setting === \"ignore\") {\n // We trust the user to know what they're doing\n } else {\n assertNever(setting);\n }\n\n // Always treat these as errors, even if `ignore` is set; maybe we need a `ignore-even-not-null-cycles`?\n // But they would still probably break flush_test_database. Unless we tell it to disable constraints,\n // like `ALTER TABLE your_table_name DISABLE TRIGGER ALL;`. But still unsure how we'd insert new rows.\n if (notNullCycles.length > 0) {\n logger.error(`Found a schema cycle of not-null foreign keys:`);\n notNullCycles.forEach((cycle) => console.log(cycle));\n console.log(\"\");\n console.log(\"These cycles can cause fatal em.flush & flush_test_database errors.\");\n console.log(\"\");\n console.log(\"Please make one of the FKs involved in the cycle nullable.\");\n console.log(\"\");\n }\n}\n\nasync function writeAlterTables(\n nonDeferredFks: Array<{\n entity: EntityDbMetadata;\n m2o: ManyToOneField | PolymorphicFieldComponent;\n }>,\n): Promise<void> {\n const queries = nonDeferredFks.map(({ entity, m2o }) => {\n return `ALTER TABLE ${entity.tableName} ALTER CONSTRAINT ${m2o.constraintName} DEFERRABLE INITIALLY DEFERRED;`;\n });\n await fs.writeFile(\"./alter-foreign-keys.sql\", queries.join(\"\\n\"));\n}\n"],"mappings":";;;;;;;AAQA,eAAsB,2BAA2B,QAAgB,UAA6C;CAG5G,IAAI,CADyB,SAAS,MAAM,MAAM,EAAE,eAAe,SAAS,CACpD,GAAG;EAEzB,KAAK,MAAM,UAAU,UAAU,OAAO,qBAAqB;EAC3D;CACF;CAGA,MAAM,EAAE,kBAAkB,6BAA6B,QAAQ;CAE/D,MAAM,EAAE,wBAAwB,UAAU,WAAW;CACrD,MAAM,iBAAiB,SAAS,SAAS,MAAM,EAAE,eAAe,KAAK,SAAS;EAAE,QAAQ;EAAG;CAAI,EAAE,CAAC;CAElG,IAAI,YAA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