json-rest-api 1.0.22 → 1.0.24

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 (290) hide show
  1. package/CLAUDE.md +1 -2
  2. package/JSKIT_BACKEND_MIGRATION_TRACKER.txt +180 -0
  3. package/README.md +22 -1
  4. package/SINGLE_VALIDATION_CONTRACT_TODO.txt +172 -0
  5. package/docs/API.md +196 -38
  6. package/docs/COMPARISON.md +2 -2
  7. package/docs/GUIDE/GUIDE_1_Initial_Setup.md +111 -5
  8. package/docs/GUIDE/GUIDE_2_2_Manipulating_And_Searching_Tables.md +5 -1
  9. package/docs/GUIDE/GUIDE_2_7_Pagination_And_Ordering.md +3 -1
  10. package/docs/GUIDE/GUIDE_2_8_Effects_of_PUT_and_PATCH.md +12 -60
  11. package/docs/GUIDE/GUIDE_2_Data_And_Relations.md +2 -2
  12. package/docs/GUIDE/GUIDE_3_Field_Transformations.md +5 -1
  13. package/docs/GUIDE/GUIDE_7_Hooks_Data_Management_And_Plugins.md +2 -0
  14. package/docs/GUIDE/GUIDE_X_Autofiltering.md +355 -0
  15. package/docs/GUIDE/GUIDE_X_Fastify.md +78 -0
  16. package/docs/GUIDE/GUIDE_X_Knex_Schema_And_Migrations.md +370 -0
  17. package/docs/GUIDE/GUIDE_X_Query_Projections.md +159 -0
  18. package/docs/GUIDE/GUIDE_X_Writing_Plugins.md +199 -0
  19. package/docs/GUIDE/index.md +18 -9
  20. package/docs/QUICKSTART.md +5 -1
  21. package/docs/index.md +1 -1
  22. package/index.js +3 -2
  23. package/lib/enhanced-logger.js +1 -1
  24. package/package.json +6 -2
  25. package/plugins/core/bulk-operations-plugin.js +26 -34
  26. package/plugins/core/connectors/express-plugin.js +97 -190
  27. package/plugins/core/connectors/fastify-plugin.js +206 -0
  28. package/plugins/core/connectors/lib/busboy-detector.js +4 -4
  29. package/plugins/core/connectors/lib/connector-core.js +195 -0
  30. package/plugins/core/connectors/lib/transport-http-helpers.js +122 -0
  31. package/plugins/core/connectors/lib/transport-route-schemas.js +92 -0
  32. package/plugins/core/lib/anyapi/schema-utils.js +43 -4
  33. package/plugins/core/lib/anyapi/utils/descriptor-helpers.js +4 -1
  34. package/plugins/core/lib/dbIntrospection.js +1078 -0
  35. package/plugins/core/lib/dbTablesOperations.js +1111 -160
  36. package/plugins/core/lib/querying/knex-cross-table-search.js +0 -7
  37. package/plugins/core/lib/querying/knex-json-api-transformers-querying.js +5 -3
  38. package/plugins/core/lib/querying/knex-process-includes.js +3 -4
  39. package/plugins/core/lib/querying/knex-query-helpers.js +21 -76
  40. package/plugins/core/lib/querying/knex-relationship-includes.js +468 -215
  41. package/plugins/core/lib/querying/query-builder-utils.js +19 -0
  42. package/plugins/core/lib/querying/query-field-sort-helpers.js +135 -0
  43. package/plugins/core/lib/querying/sort-helpers.js +33 -0
  44. package/plugins/core/lib/querying/storage-adapter-utils.js +51 -0
  45. package/plugins/core/lib/querying/url-helpers.js +8 -2
  46. package/plugins/core/lib/querying-writing/compile-schemas.js +20 -5
  47. package/plugins/core/lib/querying-writing/knex-field-helpers.js +83 -14
  48. package/plugins/core/lib/querying-writing/knex-json-api-transformers.js +13 -12
  49. package/plugins/core/lib/querying-writing/query-field-helpers.js +88 -0
  50. package/plugins/core/lib/querying-writing/request-contracts.js +590 -0
  51. package/plugins/core/lib/querying-writing/resource-id-normalization.js +131 -0
  52. package/plugins/core/lib/querying-writing/schema-helpers.js +0 -2
  53. package/plugins/core/lib/querying-writing/simplified-helpers.js +4 -11
  54. package/plugins/core/lib/storage/canonical-storage-mapping.js +133 -0
  55. package/plugins/core/lib/storage/storage-adapter.js +82 -4
  56. package/plugins/core/lib/storage/storage-mapping.js +274 -0
  57. package/plugins/core/lib/writing/many-to-many-manipulations.js +4 -2
  58. package/plugins/core/rest-api-anyapi-knex-plugin.js +531 -312
  59. package/plugins/core/rest-api-autofilter-plugin.js +414 -0
  60. package/plugins/core/rest-api-knex-plugin.js +271 -226
  61. package/plugins/core/rest-api-plugin-hooks/register-relationship-routes.js +10 -5
  62. package/plugins/core/rest-api-plugin-hooks/register-scope-routes.js +12 -6
  63. package/plugins/core/rest-api-plugin-hooks/turn-scope-init-into-vars.js +1 -0
  64. package/plugins/core/rest-api-plugin-methods/apply-query-filters.js +41 -0
  65. package/plugins/core/rest-api-plugin-methods/common.js +148 -92
  66. package/plugins/core/rest-api-plugin-methods/delete-relationship.js +11 -2
  67. package/plugins/core/rest-api-plugin-methods/delete.js +6 -1
  68. package/plugins/core/rest-api-plugin-methods/enrich-attributes.js +6 -1
  69. package/plugins/core/rest-api-plugin-methods/get-related.js +7 -2
  70. package/plugins/core/rest-api-plugin-methods/get-relationship.js +7 -2
  71. package/plugins/core/rest-api-plugin-methods/get.js +29 -14
  72. package/plugins/core/rest-api-plugin-methods/patch-relationship.js +10 -3
  73. package/plugins/core/rest-api-plugin-methods/patch.js +56 -12
  74. package/plugins/core/rest-api-plugin-methods/post-relationship.js +11 -2
  75. package/plugins/core/rest-api-plugin-methods/post.js +21 -8
  76. package/plugins/core/rest-api-plugin-methods/put.js +73 -21
  77. package/plugins/core/rest-api-plugin-methods/query.js +15 -53
  78. package/plugins/core/rest-api-plugin-methods/release.js +0 -2
  79. package/plugins/core/rest-api-plugin.js +6 -0
  80. package/plugins/core/rest-api-positioning-plugin.js +2 -5
  81. package/plugins/core/rest-api-query-projections-plugin.js +130 -0
  82. package/plugins/core/socketio-plugin.js +1 -4
  83. package/plugins/storage/local-storage.js +1 -1
  84. package/plugins/storage/s3-storage.js +5 -2
  85. package/quickTest.js +1 -0
  86. package/scripts/run-docs.js +80 -84
  87. package/test-debug.js +1 -1
  88. package/tests/README.md +7 -0
  89. package/tests/anyapi-basic.test.js +3 -0
  90. package/tests/autofilter.test.js +463 -0
  91. package/tests/custom-id-mysql-returning-fallback.test.js +128 -0
  92. package/tests/custom-id-simplified-post.test.js +75 -0
  93. package/tests/custom-idproperty-relationships.test.js +33 -0
  94. package/tests/db-introspection.test.js +521 -0
  95. package/tests/db-table-operations.test.js +786 -0
  96. package/tests/fastify-plugin.test.js +156 -0
  97. package/tests/field-getters.test.js +1 -2
  98. package/tests/field-setters.test.js +0 -4
  99. package/tests/fixtures/api-configs.js +278 -176
  100. package/tests/helpers/fake-fastify.js +99 -0
  101. package/tests/http-connectors-parity.test.js +235 -0
  102. package/tests/id-normalization.test.js +444 -0
  103. package/tests/logical-id-write-validation.test.js +151 -0
  104. package/tests/pagination-cursor-multifield.test.js +11 -11
  105. package/tests/projected-fields.test.js +319 -0
  106. package/tests/relationships.test.js +3 -3
  107. package/tests/searchschema-knex-behavior.test.js +187 -0
  108. package/tests/searchschema-merge.test.js +21 -69
  109. package/tests/storage-mapping.test.js +259 -0
  110. package/audit/00-charter.md +0 -103
  111. package/audit/01-scope-map.md +0 -84
  112. package/audit/02-coverage-matrix.csv +0 -174
  113. package/audit/03-invariants.md +0 -123
  114. package/audit/04-standards-rubric.md +0 -56
  115. package/audit/05-competitor-rubric.md +0 -77
  116. package/audit/06-findings.md +0 -160
  117. package/audit/07-risk-register.csv +0 -10
  118. package/audit/08-remediation-roadmap.md +0 -177
  119. package/audit/09-signoff-check.md +0 -23
  120. package/audit/10-final-synthesis.md +0 -29
  121. package/audit/evidence/code/all-files-json-rest-api.txt +0 -168
  122. package/audit/evidence/code/all-files-json-rest-schema.txt +0 -12
  123. package/audit/evidence/code/boundary-leak-checks.txt +0 -72
  124. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__bulk-operations-plugin.js.txt +0 -480
  125. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__connectors__express-plugin.js.txt +0 -532
  126. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__connectors__lib__busboy-detector.js.txt +0 -175
  127. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__connectors__lib__formidable-detector.js.txt +0 -138
  128. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__connectors__lib__request-helpers.js.txt +0 -222
  129. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__file-handling-plugin.js.txt +0 -342
  130. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__lib__dbTablesOperations.js.txt +0 -304
  131. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__lib__fractional-positioning.js.txt +0 -188
  132. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__lib__querying-writing__compile-schemas.js.txt +0 -336
  133. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__lib__querying-writing__connectors-query-parser.js.txt +0 -165
  134. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__lib__querying-writing__database-capabilities.js.txt +0 -265
  135. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__lib__querying-writing__database-value-normalizers.js.txt +0 -369
  136. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__lib__querying-writing__default-data-helpers.js.txt +0 -72
  137. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__lib__querying-writing__field-utils.js.txt +0 -139
  138. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__lib__querying-writing__knex-constants.js.txt +0 -45
  139. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__lib__querying-writing__knex-field-helpers.js.txt +0 -396
  140. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__lib__querying-writing__knex-json-api-transformers.js.txt +0 -162
  141. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__lib__querying-writing__payload-validators.js.txt +0 -1314
  142. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__lib__querying-writing__schema-helpers.js.txt +0 -488
  143. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__lib__querying-writing__scope-validations.js.txt +0 -484
  144. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__lib__querying-writing__simplified-helpers.js.txt +0 -857
  145. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__lib__querying__knex-cross-table-search.js.txt +0 -565
  146. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__lib__querying__knex-json-api-transformers-querying.js.txt +0 -485
  147. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__lib__querying__knex-pagination-helpers.js.txt +0 -560
  148. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__lib__querying__knex-process-includes.js.txt +0 -167
  149. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__lib__querying__knex-query-helpers-base.js.txt +0 -109
  150. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__lib__querying__knex-query-helpers.js.txt +0 -1064
  151. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__lib__querying__knex-relationship-includes.js.txt +0 -1983
  152. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__lib__querying__knex-window-queries.js.txt +0 -328
  153. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__lib__querying__url-helpers.js.txt +0 -119
  154. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__lib__storage__storage-adapter.js.txt +0 -160
  155. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__lib__writing__many-to-many-manipulations.js.txt +0 -300
  156. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__lib__writing__relationship-processor.js.txt +0 -245
  157. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__rest-api-access.js.txt +0 -459
  158. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__rest-api-cors-plugin.js.txt +0 -237
  159. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__rest-api-knex-plugin.js.txt +0 -1135
  160. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__rest-api-multihome-plugin.js.txt +0 -314
  161. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__rest-api-plugin-hooks__compile-resource-schemas.js.txt +0 -7
  162. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__rest-api-plugin-hooks__register-relationship-routes.js.txt +0 -71
  163. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__rest-api-plugin-hooks__register-scope-routes.js.txt +0 -102
  164. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__rest-api-plugin-hooks__turn-scope-init-into-vars.js.txt +0 -49
  165. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__rest-api-plugin-hooks__validate-include-configurations.js.txt +0 -39
  166. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__rest-api-plugin-methods__add-route.js.txt +0 -23
  167. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__rest-api-plugin-methods__check-permissions.js.txt +0 -13
  168. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__rest-api-plugin-methods__common.js.txt +0 -639
  169. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__rest-api-plugin-methods__delete-relationship.js.txt +0 -117
  170. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__rest-api-plugin-methods__delete.js.txt +0 -104
  171. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__rest-api-plugin-methods__enrich-attributes.js.txt +0 -199
  172. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__rest-api-plugin-methods__get-related.js.txt +0 -353
  173. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__rest-api-plugin-methods__get-relationship.js.txt +0 -61
  174. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__rest-api-plugin-methods__get.js.txt +0 -184
  175. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__rest-api-plugin-methods__patch-relationship.js.txt +0 -55
  176. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__rest-api-plugin-methods__patch.js.txt +0 -191
  177. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__rest-api-plugin-methods__post-relationship.js.txt +0 -110
  178. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__rest-api-plugin-methods__post.js.txt +0 -168
  179. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__rest-api-plugin-methods__put.js.txt +0 -253
  180. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__rest-api-plugin-methods__query.js.txt +0 -207
  181. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__rest-api-plugin-methods__release.js.txt +0 -12
  182. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__rest-api-plugin.js.txt +0 -165
  183. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__rest-api-positioning-plugin.js.txt +0 -668
  184. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__core__socketio-plugin.js.txt +0 -621
  185. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__storage__local-storage.js.txt +0 -218
  186. package/audit/evidence/code/critical-pass1/json-rest-api__plugins__storage__s3-storage.js.txt +0 -124
  187. package/audit/evidence/code/critical-pass1/json-rest-schema__src__CorePlugin.js.txt +0 -269
  188. package/audit/evidence/code/critical-pass1/json-rest-schema__src__Schema.js.txt +0 -242
  189. package/audit/evidence/code/critical-pass1/json-rest-schema__src__index.js.txt +0 -77
  190. package/audit/evidence/code/critical-pass1-risk-keywords.txt +0 -238
  191. package/audit/evidence/code/critical-pass1-summary.csv +0 -67
  192. package/audit/evidence/code/critical-pass2-summary.csv +0 -67
  193. package/audit/evidence/code/early-silent-zones-no-test-token.txt +0 -57
  194. package/audit/evidence/code/error-model-signals.txt +0 -98
  195. package/audit/evidence/code/git-files-json-rest-api.txt +0 -171
  196. package/audit/evidence/code/git-files-json-rest-schema.txt +0 -27
  197. package/audit/evidence/code/hook-flow-signals.txt +0 -282
  198. package/audit/evidence/code/idproperty-signals.txt +0 -157
  199. package/audit/evidence/code/import-cycles-non-anyapi.txt +0 -3
  200. package/audit/evidence/code/import-hotspots-non-anyapi.txt +0 -96
  201. package/audit/evidence/code/imports-json-rest-api.txt +0 -354
  202. package/audit/evidence/code/imports-json-rest-schema.txt +0 -15
  203. package/audit/evidence/code/in-scope-files-json-rest-api.txt +0 -160
  204. package/audit/evidence/code/in-scope-files-json-rest-schema.txt +0 -13
  205. package/audit/evidence/code/non-anyapi-core-files.txt +0 -101
  206. package/audit/evidence/code/permission-signals.txt +0 -193
  207. package/audit/evidence/code/query-include-signals.txt +0 -687
  208. package/audit/evidence/code/transaction-signals.txt +0 -28
  209. package/audit/evidence/code/validation-signals.txt +0 -650
  210. package/audit/evidence/code/write-path-signals.txt +0 -61
  211. package/audit/evidence/docs/docs-claims-signals.txt +0 -1075
  212. package/audit/evidence/docs/schema-docs-claims-signals.txt +0 -179
  213. package/audit/evidence/external/corpus-freeze.md +0 -21
  214. package/audit/evidence/external/npm-competitor-metadata.txt +0 -70
  215. package/audit/evidence/external/npm-download-signals.txt +0 -23
  216. package/audit/evidence/external/npm-jsonapi-server.txt +0 -8
  217. package/audit/evidence/external/npm-modern-jsonapi-metadata.txt +0 -38
  218. package/audit/evidence/external/readme-fortune-signals.txt +0 -26
  219. package/audit/evidence/external/readme-fortune.md +0 -165
  220. package/audit/evidence/external/readme-json-api-serializer-signals.txt +0 -80
  221. package/audit/evidence/external/readme-json-api-serializer.md +0 -690
  222. package/audit/evidence/external/readme-jsonapi-serde-server-signals.txt +0 -0
  223. package/audit/evidence/external/readme-jsonapi-serde-server.md +0 -22
  224. package/audit/evidence/external/readme-jsonapi-serializer-signals.txt +0 -63
  225. package/audit/evidence/external/readme-jsonapi-serializer.md +0 -315
  226. package/audit/evidence/external/readme-jsonapi-server-signals.txt +0 -19
  227. package/audit/evidence/external/readme-jsonapi-server.md +0 -104
  228. package/audit/evidence/external/readme-nestjs-json-api-signals.txt +0 -4
  229. package/audit/evidence/external/readme-nestjs-json-api.md +0 -94
  230. package/audit/evidence/external/readme-yaser-json-api-nestjs-signals.txt +0 -47
  231. package/audit/evidence/external/readme-yaser-json-api-nestjs.md +0 -447
  232. package/audit/evidence/external/standard-jsonapi-snippets.txt +0 -84
  233. package/audit/evidence/external/standard-rfc-snippets.txt +0 -168
  234. package/audit/evidence/external/standards-sources.txt +0 -6
  235. package/audit/evidence/runtime/baseline-commits.txt +0 -2
  236. package/audit/evidence/runtime/db-adapter-assumptions.txt +0 -3
  237. package/audit/evidence/runtime/environment.txt +0 -4
  238. package/audit/evidence/runtime/invariant-runtime-mapping.md +0 -38
  239. package/audit/evidence/runtime/probe-patch-relationship-error.exitcode +0 -1
  240. package/audit/evidence/runtime/probe-patch-relationship-error.log +0 -76
  241. package/audit/evidence/runtime/probe-patch-relationship-error.mjs +0 -67
  242. package/audit/evidence/runtime/probe-patch-relationship-referenceerror.exitcode +0 -1
  243. package/audit/evidence/runtime/probe-patch-relationship-referenceerror.log +0 -62
  244. package/audit/evidence/runtime/probe-patch-relationship-referenceerror.mjs +0 -47
  245. package/audit/evidence/runtime/test-exitcodes.txt +0 -4
  246. package/audit/evidence/runtime/test-summary.md +0 -107
  247. package/audit/evidence/runtime/trace-anchors.txt +0 -61
  248. package/audit/evidence/tests/access-multitenancy-test-signals.txt +0 -125
  249. package/audit/evidence/tests/failing-tests-summary.txt +0 -25
  250. package/audit/evidence/tests/npm-test-json-rest-api.exitcode +0 -1
  251. package/audit/evidence/tests/npm-test-json-rest-api.log +0 -5885
  252. package/audit/evidence/tests/npm-test-json-rest-schema.exitcode +0 -1
  253. package/audit/evidence/tests/npm-test-json-rest-schema.log +0 -356
  254. package/audit/evidence/tests/query-include-test-signals.txt +0 -948
  255. package/audit/evidence/tests/relationship-test-signals.txt +0 -223
  256. package/audit/evidence/tests/skipped-tests.txt +0 -10
  257. package/audit/evidence/tests/test-suite-list-non-anyapi.txt +0 -30
  258. package/audit/evidence/tests/test-suite-list.txt +0 -32
  259. package/audit/subsystems/docs-drift.md +0 -49
  260. package/audit/subsystems/pass2-cross-review.md +0 -131
  261. package/audit/subsystems/plugins-access.md +0 -51
  262. package/audit/subsystems/plugins-bulk.md +0 -50
  263. package/audit/subsystems/plugins-cors.md +0 -48
  264. package/audit/subsystems/plugins-file.md +0 -53
  265. package/audit/subsystems/plugins-multihome.md +0 -50
  266. package/audit/subsystems/plugins-positioning.md +0 -54
  267. package/audit/subsystems/plugins-socketio.md +0 -50
  268. package/audit/subsystems/query-engine.md +0 -61
  269. package/audit/subsystems/relationships.md +0 -55
  270. package/audit/subsystems/rest-orchestration.md +0 -66
  271. package/audit/subsystems/schema-core.md +0 -64
  272. package/audit/subsystems/storage-knex.md +0 -57
  273. package/audit/subsystems/tests.md +0 -48
  274. package/audit/subsystems/transport-express.md +0 -55
  275. package/audit/traces/trace-read-get.md +0 -22
  276. package/audit/traces/trace-read-query.md +0 -25
  277. package/audit/traces/trace-relationship-endpoints.md +0 -31
  278. package/audit/traces/trace-write-delete.md +0 -17
  279. package/audit/traces/trace-write-patch.md +0 -26
  280. package/audit/traces/trace-write-post.md +0 -22
  281. package/audit/traces/trace-write-put.md +0 -23
  282. package/docs/GUIDE/GUIDE_4_Authentication_And_Permissions.md +0 -707
  283. package/docs/GUIDE/GUIDE_X_Multihome.md +0 -666
  284. package/plugins/core/lib/querying-writing/payload-validators.js +0 -1314
  285. package/plugins/core/rest-api-access.js +0 -459
  286. package/plugins/core/rest-api-multihome-plugin.js +0 -314
  287. package/tests/multihome.test.js +0 -553
  288. package/tests/multihome.test.js.bak +0 -550
  289. package/tests/ownership-optout.test.js +0 -76
  290. package/tests/rest-api-access.test.js +0 -206
@@ -0,0 +1,786 @@
1
+ import { describe, it, before, after, beforeEach, afterEach } from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import knexLib from 'knex'
4
+ import { Api } from 'hooked-api'
5
+ import { RestApiPlugin, RestApiKnexPlugin } from '../index.js'
6
+ import {
7
+ createKnexTable,
8
+ addKnexFields,
9
+ alterKnexFields,
10
+ generateKnexMigration,
11
+ generateKnexMigrationDiff
12
+ } from '../plugins/core/lib/dbTablesOperations.js'
13
+ import { introspectKnexTableSnapshot } from '../plugins/core/lib/dbIntrospection.js'
14
+
15
+ function makeSchemaInfo (tableName, idProperty = 'id') {
16
+ return { tableName, idProperty }
17
+ }
18
+
19
+ function makeTableSchema (structure, metadata = {}) {
20
+ return { structure, ...metadata }
21
+ }
22
+
23
+ let db
24
+
25
+ describe('dbTablesOperations.createKnexTable', () => {
26
+ beforeEach(() => {
27
+ db = knexLib({
28
+ client: 'better-sqlite3',
29
+ connection: {
30
+ filename: ':memory:'
31
+ },
32
+ useNullAsDefault: true
33
+ })
34
+ })
35
+
36
+ afterEach(async () => {
37
+ await db.destroy()
38
+ })
39
+
40
+ it('creates a simple table with string fields', async () => {
41
+ const schema = makeTableSchema({
42
+ name: { type: 'string', required: true, maxLength: 100 },
43
+ email: { type: 'string', unique: true },
44
+ bio: { type: 'string', nullable: true }
45
+ })
46
+
47
+ await createKnexTable(db, makeSchemaInfo('users'), schema)
48
+
49
+ const exists = await db.schema.hasTable('users')
50
+ assert.equal(exists, true)
51
+
52
+ const info = await db('users').columnInfo()
53
+ assert.ok(info.id)
54
+ assert.ok(info.name)
55
+ assert.ok(info.email)
56
+ assert.ok(info.bio)
57
+
58
+ await db('users').insert({
59
+ name: 'Test User',
60
+ email: 'test@example.com',
61
+ bio: null
62
+ })
63
+
64
+ const users = await db('users').select()
65
+ assert.equal(users.length, 1)
66
+ assert.equal(users[0].name, 'Test User')
67
+ })
68
+
69
+ it('handles number fields with precision and defaults', async () => {
70
+ const schema = makeTableSchema({
71
+ price: { type: 'number', precision: 10, scale: 2 },
72
+ quantity: { type: 'number', defaultTo: 0 },
73
+ rating: { type: 'number', nullable: true }
74
+ })
75
+
76
+ await createKnexTable(db, makeSchemaInfo('products'), schema)
77
+
78
+ await db('products').insert({
79
+ price: 99.99,
80
+ rating: 4.5
81
+ })
82
+
83
+ const products = await db('products').select()
84
+ assert.equal(products[0].price, 99.99)
85
+ assert.equal(products[0].quantity, 0)
86
+ assert.equal(products[0].rating, 4.5)
87
+ })
88
+
89
+ it('adds timestamps when requested', async () => {
90
+ const schema = makeTableSchema({
91
+ title: { type: 'string' }
92
+ })
93
+
94
+ await createKnexTable(db, makeSchemaInfo('posts'), schema, {
95
+ timestamps: true
96
+ })
97
+
98
+ const info = await db('posts').columnInfo()
99
+ assert.ok(info.created_at)
100
+ assert.ok(info.updated_at)
101
+ })
102
+
103
+ it('handles foreign key references', async () => {
104
+ const userSchema = makeTableSchema({
105
+ username: { type: 'string', unique: true }
106
+ })
107
+ await createKnexTable(db, makeSchemaInfo('users'), userSchema)
108
+
109
+ const postSchema = makeTableSchema({
110
+ title: { type: 'string', required: true },
111
+ userId: {
112
+ type: 'id',
113
+ required: true,
114
+ references: { table: 'users', onDelete: 'CASCADE' }
115
+ }
116
+ })
117
+ await createKnexTable(db, makeSchemaInfo('posts'), postSchema)
118
+
119
+ await db('users').insert({ username: 'testuser' })
120
+ const user = await db('users').where('username', 'testuser').first()
121
+ await db('posts').insert({ title: 'Test Post', user_id: user.id })
122
+
123
+ const posts = await db('posts')
124
+ .join('users', 'posts.user_id', 'users.id')
125
+ .select('posts.title', 'users.username')
126
+
127
+ assert.equal(posts.length, 1)
128
+ assert.equal(posts[0].title, 'Test Post')
129
+ assert.equal(posts[0].username, 'testuser')
130
+ })
131
+
132
+ it('respects a primary key defined in the schema', async () => {
133
+ const schema = makeTableSchema({
134
+ isbn: { type: 'string', primary: true, maxLength: 13 },
135
+ title: { type: 'string', required: true }
136
+ })
137
+
138
+ await createKnexTable(db, makeSchemaInfo('books'), schema, {
139
+ autoIncrement: false
140
+ })
141
+
142
+ const info = await db('books').columnInfo()
143
+ assert.ok(!info.id)
144
+ assert.ok(info.isbn)
145
+
146
+ await db('books').insert({
147
+ isbn: '9781234567890',
148
+ title: 'Test Book'
149
+ })
150
+
151
+ const books = await db('books').select()
152
+ assert.equal(books[0].isbn, '9781234567890')
153
+ })
154
+
155
+ it('enforces unique constraints', async () => {
156
+ const schema = makeTableSchema({
157
+ email: { type: 'string', unique: true },
158
+ username: { type: 'string', unique: true }
159
+ })
160
+
161
+ await createKnexTable(db, makeSchemaInfo('accounts'), schema)
162
+
163
+ await db('accounts').insert({
164
+ email: 'test@example.com',
165
+ username: 'testuser'
166
+ })
167
+
168
+ await assert.rejects(async () => {
169
+ await db('accounts').insert({
170
+ email: 'test@example.com',
171
+ username: 'otheruser'
172
+ })
173
+ })
174
+ })
175
+
176
+ it('defaults storage columns to snake_case and keeps per-field overrides', async () => {
177
+ const schema = makeTableSchema({
178
+ displayName: { type: 'string', required: true },
179
+ lastSeenAt: { type: 'dateTime' },
180
+ externalRef: { type: 'string', storage: { column: 'legacy_ref' } }
181
+ })
182
+
183
+ await createKnexTable(db, makeSchemaInfo('mapped_profiles'), schema)
184
+
185
+ const info = await db('mapped_profiles').columnInfo()
186
+ assert.ok(info.id)
187
+ assert.ok(info.display_name)
188
+ assert.ok(info.last_seen_at)
189
+ assert.ok(info.legacy_ref)
190
+ assert.equal(info.displayName, undefined)
191
+ assert.equal(info.external_ref, undefined)
192
+ })
193
+
194
+ it('supports logical id fields mapped to custom storage columns', async () => {
195
+ const schema = makeTableSchema({
196
+ id: { type: 'id', primary: true, storage: { column: 'book_id' } },
197
+ title: { type: 'string', required: true }
198
+ })
199
+
200
+ await createKnexTable(db, makeSchemaInfo('books', 'book_id'), schema)
201
+
202
+ const info = await db('books').columnInfo()
203
+ assert.ok(info.book_id)
204
+ assert.equal(info.id, undefined)
205
+
206
+ await db('books').insert({
207
+ book_id: 101,
208
+ title: 'Mapped ID Book'
209
+ })
210
+
211
+ const books = await db('books').select()
212
+ assert.equal(books.length, 1)
213
+ assert.equal(books[0].book_id, 101)
214
+ })
215
+
216
+ it('supports named composite indexes, foreign keys, checks, and enum columns', async () => {
217
+ await db.raw('PRAGMA foreign_keys = ON')
218
+ await db.raw(`
219
+ CREATE TABLE workspace_users (
220
+ workspace_id INTEGER NOT NULL,
221
+ user_id INTEGER NOT NULL,
222
+ PRIMARY KEY (workspace_id, user_id)
223
+ )
224
+ `)
225
+
226
+ const schema = makeTableSchema({
227
+ workspaceId: { type: 'id', required: true },
228
+ userId: { type: 'id', required: true },
229
+ role: { type: 'string', enum: ['owner', 'member'], required: true, defaultTo: 'member' },
230
+ noteCount: { type: 'number', defaultTo: 0 }
231
+ }, {
232
+ indexes: [
233
+ {
234
+ name: 'uq_memberships_workspace_user',
235
+ unique: true,
236
+ columns: ['workspaceId', 'userId']
237
+ }
238
+ ],
239
+ foreignKeys: [
240
+ {
241
+ name: 'fk_memberships_workspace_user',
242
+ columns: ['workspaceId', 'userId'],
243
+ referencedTableName: 'workspace_users',
244
+ referencedColumns: ['workspace_id', 'user_id'],
245
+ deleteRule: 'CASCADE',
246
+ updateRule: 'RESTRICT'
247
+ }
248
+ ],
249
+ checkConstraints: [
250
+ {
251
+ name: 'chk_memberships_note_count_non_negative',
252
+ clause: 'note_count >= 0'
253
+ }
254
+ ]
255
+ })
256
+
257
+ await createKnexTable(db, makeSchemaInfo('memberships'), schema)
258
+
259
+ const snapshot = await introspectKnexTableSnapshot(db, {
260
+ tableName: 'memberships',
261
+ idColumn: 'id'
262
+ })
263
+
264
+ const membershipIndex = snapshot.indexes.find((index) => index.name === 'uq_memberships_workspace_user')
265
+ assert.ok(membershipIndex)
266
+ assert.equal(membershipIndex.unique, true)
267
+ assert.deepEqual(membershipIndex.columns, ['workspace_id', 'user_id'])
268
+
269
+ const membershipForeignKey = snapshot.foreignKeys.find((foreignKey) => foreignKey.name === 'fk_memberships_workspace_user')
270
+ assert.ok(membershipForeignKey)
271
+ assert.equal(membershipForeignKey.referencedTableName, 'workspace_users')
272
+ assert.equal(membershipForeignKey.deleteRule, 'CASCADE')
273
+ assert.equal(membershipForeignKey.updateRule, 'RESTRICT')
274
+ assert.deepEqual(
275
+ membershipForeignKey.columns.map((entry) => [entry.name, entry.referencedName]),
276
+ [['workspace_id', 'workspace_id'], ['user_id', 'user_id']]
277
+ )
278
+
279
+ const membershipCheck = snapshot.checkConstraints.find((constraint) => constraint.name === 'chk_memberships_note_count_non_negative')
280
+ assert.ok(membershipCheck)
281
+ assert.equal(membershipCheck.clause, 'note_count >= 0')
282
+
283
+ const roleColumn = snapshot.columns.find((column) => column.name === 'role')
284
+ assert.ok(roleColumn)
285
+ assert.deepEqual(roleColumn.enumValues, ['owner', 'member'])
286
+ })
287
+ })
288
+
289
+ describe('dbTablesOperations.generateKnexMigration', () => {
290
+ beforeEach(() => {
291
+ db = knexLib({
292
+ client: 'better-sqlite3',
293
+ connection: {
294
+ filename: ':memory:'
295
+ },
296
+ useNullAsDefault: true
297
+ })
298
+ })
299
+
300
+ afterEach(async () => {
301
+ await db.destroy()
302
+ })
303
+
304
+ it('generates executable migrations', async () => {
305
+ const schema = makeTableSchema({
306
+ name: { type: 'string', required: true },
307
+ age: { type: 'number', min: 0 },
308
+ email: { type: 'string', unique: true }
309
+ })
310
+
311
+ const migration = generateKnexMigration('users', schema)
312
+ const migrationModule = {}
313
+ const migrationCode = migration
314
+ .replace(/exports\.up/g, 'migrationModule.up')
315
+ .replace(/exports\.down/g, 'migrationModule.down')
316
+
317
+ new Function('migrationModule', migrationCode)(migrationModule)
318
+
319
+ await migrationModule.up(db)
320
+
321
+ const exists = await db.schema.hasTable('users')
322
+ assert.equal(exists, true)
323
+
324
+ await db('users').insert({
325
+ name: 'Test User',
326
+ age: 25,
327
+ email: 'test@example.com'
328
+ })
329
+
330
+ await migrationModule.down(db)
331
+
332
+ const existsAfter = await db.schema.hasTable('users')
333
+ assert.equal(existsAfter, false)
334
+ })
335
+
336
+ it('includes the expected schema features in generated migrations', () => {
337
+ const schema = makeTableSchema({
338
+ id: { type: 'id', primary: true },
339
+ title: { type: 'string', required: true, maxLength: 200 },
340
+ price: { type: 'number', precision: 10, scale: 2 },
341
+ inStock: { type: 'boolean', defaultTo: true },
342
+ categoryId: {
343
+ type: 'id',
344
+ nullable: true,
345
+ references: { table: 'categories', onDelete: 'SET NULL' }
346
+ },
347
+ tags: { type: 'array', defaultTo: [] }
348
+ })
349
+
350
+ const migration = generateKnexMigration('products', schema, {
351
+ timestamps: true
352
+ })
353
+
354
+ assert.ok(migration.includes("table.integer('id').unsigned().primary()"))
355
+ assert.ok(migration.includes("table.string('title', 200).notNullable()"))
356
+ assert.ok(migration.includes("table.decimal('price', 10, 2)"))
357
+ assert.ok(migration.includes(".defaultTo(true)"))
358
+ assert.ok(migration.includes("table.foreign(['category_id'], 'products_category_id_foreign').references(['id']).inTable('categories').onDelete('SET NULL')"))
359
+ assert.ok(migration.includes('table.timestamps(true, true)'))
360
+ })
361
+
362
+ it('uses default snake_case columns in generated migrations and keeps per-field overrides', () => {
363
+ const schema = makeTableSchema({
364
+ displayName: { type: 'string', required: true },
365
+ loginCount: { type: 'number', defaultTo: 0 },
366
+ externalRef: { type: 'string', storage: { column: 'legacy_ref' } }
367
+ })
368
+
369
+ const migration = generateKnexMigration('mapped_profiles', schema)
370
+
371
+ assert.ok(migration.includes("table.string('display_name').notNullable()"))
372
+ assert.ok(migration.includes("table.float('login_count').defaultTo(0)"))
373
+ assert.ok(migration.includes("table.string('legacy_ref')"))
374
+ assert.ok(!migration.includes("table.string('displayName')"))
375
+ })
376
+
377
+ it('supports mapped logical id fields in generated migrations', () => {
378
+ const schema = makeTableSchema({
379
+ id: { type: 'id', primary: true, storage: { column: 'book_id' } },
380
+ title: { type: 'string', required: true }
381
+ })
382
+
383
+ const migration = generateKnexMigration('books', schema)
384
+
385
+ assert.ok(migration.includes("table.integer('book_id').unsigned().primary()"))
386
+ assert.ok(migration.includes("table.string('title').notNullable()"))
387
+ assert.equal((migration.match(/book_id/g) || []).length, 1)
388
+ })
389
+
390
+ it('includes named composite indexes, foreign keys, checks, enum, and set columns in generated migrations', () => {
391
+ const schema = makeTableSchema({
392
+ workspaceId: { type: 'id', required: true },
393
+ userId: { type: 'id', required: true },
394
+ role: { type: 'string', enum: ['owner', 'member'], required: true, defaultTo: 'member' },
395
+ flags: { type: 'string', setValues: ['featured', 'archived'] },
396
+ noteCount: { type: 'number', defaultTo: 0 }
397
+ }, {
398
+ indexes: [
399
+ {
400
+ name: 'uq_memberships_workspace_user',
401
+ unique: true,
402
+ columns: ['workspaceId', 'userId']
403
+ }
404
+ ],
405
+ foreignKeys: [
406
+ {
407
+ name: 'fk_memberships_workspace_user',
408
+ columns: ['workspaceId', 'userId'],
409
+ referencedTableName: 'workspace_users',
410
+ referencedColumns: ['workspace_id', 'user_id'],
411
+ deleteRule: 'CASCADE',
412
+ updateRule: 'RESTRICT'
413
+ }
414
+ ],
415
+ checkConstraints: [
416
+ {
417
+ name: 'chk_memberships_note_count_non_negative',
418
+ clause: 'note_count >= 0'
419
+ }
420
+ ]
421
+ })
422
+
423
+ const migration = generateKnexMigration('memberships', schema, {
424
+ dialect: 'mysql2'
425
+ })
426
+
427
+ assert.ok(migration.includes("table.enu('role', ['owner', 'member']).notNullable().defaultTo('member')"))
428
+ assert.ok(migration.includes("table.specificType('flags', 'set(\\'featured\\', \\'archived\\')')"))
429
+ assert.ok(migration.includes("table.unique(['workspace_id', 'user_id'], 'uq_memberships_workspace_user')"))
430
+ assert.ok(migration.includes("table.foreign(['workspace_id', 'user_id'], 'fk_memberships_workspace_user').references(['workspace_id', 'user_id']).inTable('workspace_users').onDelete('CASCADE').onUpdate('RESTRICT')"))
431
+ assert.ok(migration.includes("table.check('note_count >= 0', [], 'chk_memberships_note_count_non_negative')"))
432
+ })
433
+
434
+ it('includes indexType for non-unique indexes in generated migrations', () => {
435
+ const schema = makeTableSchema({
436
+ body: { type: 'string' }
437
+ }, {
438
+ indexes: [
439
+ {
440
+ name: 'idx_articles_body_fulltext',
441
+ columns: ['body'],
442
+ indexType: 'FULLTEXT'
443
+ }
444
+ ]
445
+ })
446
+
447
+ const migration = generateKnexMigration('articles', schema)
448
+
449
+ assert.ok(migration.includes("table.index(['body'], 'idx_articles_body_fulltext', { \"indexType\": 'FULLTEXT' })"))
450
+ })
451
+
452
+ it('rejects indexType on unique index metadata', () => {
453
+ const schema = makeTableSchema({
454
+ email: { type: 'string' }
455
+ }, {
456
+ indexes: [
457
+ {
458
+ name: 'uq_accounts_email',
459
+ unique: true,
460
+ columns: ['email'],
461
+ indexType: 'BTREE'
462
+ }
463
+ ]
464
+ })
465
+
466
+ assert.throws(
467
+ () => generateKnexMigration('accounts', schema),
468
+ /cannot define indexType/i
469
+ )
470
+ })
471
+ })
472
+
473
+ describe('dbTablesOperations.generateKnexMigrationDiff', () => {
474
+ beforeEach(() => {
475
+ db = knexLib({
476
+ client: 'better-sqlite3',
477
+ connection: {
478
+ filename: ':memory:'
479
+ },
480
+ useNullAsDefault: true
481
+ })
482
+ })
483
+
484
+ afterEach(async () => {
485
+ await db.destroy()
486
+ })
487
+
488
+ it('generates additive alter migrations from a live snapshot', async () => {
489
+ await db.raw('PRAGMA foreign_keys = ON')
490
+ await db.raw(`
491
+ CREATE TABLE workspace_users (
492
+ workspace_id INTEGER NOT NULL,
493
+ user_id INTEGER NOT NULL,
494
+ PRIMARY KEY (workspace_id, user_id)
495
+ )
496
+ `)
497
+ await db.raw(`
498
+ CREATE TABLE memberships (
499
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
500
+ workspace_id INTEGER NOT NULL,
501
+ user_id INTEGER NOT NULL
502
+ )
503
+ `)
504
+
505
+ const currentSnapshot = await introspectKnexTableSnapshot(db, {
506
+ tableName: 'memberships',
507
+ idColumn: 'id'
508
+ })
509
+ const desiredSchema = makeTableSchema({
510
+ workspaceId: { type: 'id', required: true },
511
+ userId: { type: 'id', required: true },
512
+ role: { type: 'string', enum: ['owner', 'member'], required: true, defaultTo: 'member' },
513
+ noteCount: { type: 'number', defaultTo: 0 }
514
+ }, {
515
+ indexes: [
516
+ {
517
+ name: 'uq_memberships_workspace_user',
518
+ unique: true,
519
+ columns: ['workspaceId', 'userId']
520
+ }
521
+ ],
522
+ foreignKeys: [
523
+ {
524
+ name: 'fk_memberships_workspace_user',
525
+ columns: ['workspaceId', 'userId'],
526
+ referencedTableName: 'workspace_users',
527
+ referencedColumns: ['workspace_id', 'user_id'],
528
+ deleteRule: 'CASCADE',
529
+ updateRule: 'RESTRICT'
530
+ }
531
+ ]
532
+ })
533
+
534
+ const diff = generateKnexMigrationDiff('memberships', currentSnapshot, desiredSchema, {
535
+ dialect: 'better-sqlite3'
536
+ })
537
+
538
+ assert.deepEqual(diff.warnings, [])
539
+ assert.equal(Object.hasOwn(diff.plan, 'dropCheckConstraints'), false)
540
+ assert.deepEqual(diff.plan.addColumns.map((column) => column.name), ['note_count', 'role'])
541
+ assert.deepEqual(diff.plan.addIndexes.map((index) => index.name), ['uq_memberships_workspace_user'])
542
+ assert.deepEqual(diff.plan.addForeignKeys.map((foreignKey) => foreignKey.name), ['fk_memberships_workspace_user'])
543
+ assert.ok(diff.migration.includes("table.float('note_count').defaultTo(0)"))
544
+ assert.ok(diff.migration.includes("table.enu('role', ['owner', 'member']).notNullable().defaultTo('member')"))
545
+
546
+ const migrationModule = {}
547
+ new Function('migrationModule', diff.migration
548
+ .replace(/exports\.up/g, 'migrationModule.up')
549
+ .replace(/exports\.down/g, 'migrationModule.down'))(migrationModule)
550
+
551
+ await migrationModule.up(db)
552
+
553
+ const afterSnapshot = await introspectKnexTableSnapshot(db, {
554
+ tableName: 'memberships',
555
+ idColumn: 'id'
556
+ })
557
+
558
+ const roleColumn = afterSnapshot.columns.find((column) => column.name === 'role')
559
+ assert.ok(roleColumn)
560
+ assert.deepEqual(roleColumn.enumValues, ['owner', 'member'])
561
+ assert.equal(roleColumn.defaultValue, 'member')
562
+ assert.ok(afterSnapshot.columns.some((column) => column.name === 'note_count'))
563
+ assert.ok(afterSnapshot.indexes.some((index) => index.name === 'uq_memberships_workspace_user'))
564
+ assert.ok(afterSnapshot.foreignKeys.some((foreignKey) => foreignKey.name === 'fk_memberships_workspace_user'))
565
+
566
+ const secondDiff = generateKnexMigrationDiff('memberships', afterSnapshot, desiredSchema, {
567
+ dialect: 'better-sqlite3'
568
+ })
569
+
570
+ assert.deepEqual(secondDiff.warnings, [])
571
+ assert.equal(secondDiff.plan.addColumns.length, 0)
572
+ assert.equal(secondDiff.plan.alterColumns.length, 0)
573
+ assert.equal(secondDiff.plan.dropColumns.length, 0)
574
+ assert.equal(secondDiff.plan.addIndexes.length, 0)
575
+ assert.equal(secondDiff.plan.dropIndexes.length, 0)
576
+ assert.equal(secondDiff.plan.addForeignKeys.length, 0)
577
+ assert.equal(secondDiff.plan.dropForeignKeys.length, 0)
578
+ })
579
+
580
+ it('recreates indexes when indexType changes', async () => {
581
+ await db.raw(`
582
+ CREATE TABLE articles (
583
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
584
+ body TEXT
585
+ )
586
+ `)
587
+
588
+ const currentSnapshot = await introspectKnexTableSnapshot(db, {
589
+ tableName: 'articles',
590
+ idColumn: 'id'
591
+ })
592
+ currentSnapshot.indexes.push({
593
+ name: 'idx_articles_body',
594
+ unique: false,
595
+ columns: ['body'],
596
+ indexType: ''
597
+ })
598
+
599
+ const desiredSchema = makeTableSchema({
600
+ body: { type: 'string' }
601
+ }, {
602
+ indexes: [
603
+ {
604
+ name: 'idx_articles_body',
605
+ columns: ['body'],
606
+ indexType: 'FULLTEXT'
607
+ }
608
+ ]
609
+ })
610
+
611
+ const diff = generateKnexMigrationDiff('articles', currentSnapshot, desiredSchema, {
612
+ dialect: 'mysql2'
613
+ })
614
+
615
+ assert.deepEqual(diff.plan.addIndexes.map((index) => index.name), ['idx_articles_body'])
616
+ assert.deepEqual(diff.plan.dropIndexes.map((index) => index.name), ['idx_articles_body'])
617
+ assert.ok(diff.migration.includes("table.dropIndex(['body'], 'idx_articles_body');"))
618
+ assert.ok(diff.migration.includes("table.index(['body'], 'idx_articles_body', { \"indexType\": 'FULLTEXT' });"))
619
+ })
620
+
621
+ it('warns about destructive column changes and skipped drops by default', async () => {
622
+ await db.raw(`
623
+ CREATE TABLE documents (
624
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
625
+ title VARCHAR(255),
626
+ legacy_code TEXT
627
+ )
628
+ `)
629
+
630
+ const currentSnapshot = await introspectKnexTableSnapshot(db, {
631
+ tableName: 'documents',
632
+ idColumn: 'id'
633
+ })
634
+ const desiredSchema = makeTableSchema({
635
+ title: { type: 'string', required: true, maxLength: 50 }
636
+ }, {
637
+ checkConstraints: [
638
+ {
639
+ name: 'chk_documents_title_non_empty',
640
+ clause: 'length(title) > 0'
641
+ }
642
+ ]
643
+ })
644
+
645
+ const diff = generateKnexMigrationDiff('documents', currentSnapshot, desiredSchema, {
646
+ dialect: 'sqlite'
647
+ })
648
+
649
+ assert.ok(diff.warnings.some((warning) => warning.includes("Column 'legacy_code' exists in the live table but not in the desired schema.")))
650
+ assert.ok(diff.warnings.some((warning) => warning.includes("Column 'title' changes from nullable to not-null")))
651
+ assert.ok(diff.warnings.some((warning) => warning.includes("Column 'title' reduces maxLength from 255 to 50")))
652
+ assert.ok(diff.warnings.some((warning) => warning.includes("Skipping check constraint 'chk_documents_title_non_empty'")))
653
+ assert.equal(diff.plan.dropColumns.length, 0)
654
+ assert.deepEqual(diff.plan.alterColumns.map((column) => column.name), ['title'])
655
+ })
656
+
657
+ it('warns when setValues are diffed on a non-MySQL dialect', async () => {
658
+ await db.raw(`
659
+ CREATE TABLE articles (
660
+ id INTEGER PRIMARY KEY AUTOINCREMENT
661
+ )
662
+ `)
663
+
664
+ const currentSnapshot = await introspectKnexTableSnapshot(db, {
665
+ tableName: 'articles',
666
+ idColumn: 'id'
667
+ })
668
+ const desiredSchema = makeTableSchema({
669
+ flags: { type: 'string', setValues: ['featured', 'archived'] }
670
+ })
671
+
672
+ const diff = generateKnexMigrationDiff('articles', currentSnapshot, desiredSchema, {
673
+ dialect: 'sqlite'
674
+ })
675
+
676
+ assert.ok(diff.warnings.some((warning) => warning.includes("Skipping setValues column 'flags'")))
677
+ assert.equal(diff.plan.addColumns.length, 0)
678
+ })
679
+ })
680
+
681
+ describe('dbTablesOperations field-only helpers', () => {
682
+ beforeEach(() => {
683
+ db = knexLib({
684
+ client: 'better-sqlite3',
685
+ connection: {
686
+ filename: ':memory:'
687
+ },
688
+ useNullAsDefault: true
689
+ })
690
+ })
691
+
692
+ afterEach(async () => {
693
+ await db.destroy()
694
+ })
695
+
696
+ it('rejects top-level metadata in addKnexFields', async () => {
697
+ await assert.rejects(
698
+ () => addKnexFields(db, 'accounts', makeTableSchema({
699
+ email: { type: 'string' }
700
+ }, {
701
+ indexes: [{ name: 'idx_accounts_email', columns: ['email'] }]
702
+ })),
703
+ /does not accept top-level indexes/i
704
+ )
705
+ })
706
+
707
+ it('rejects top-level metadata in alterKnexFields', async () => {
708
+ await assert.rejects(
709
+ () => alterKnexFields(db, 'accounts', makeTableSchema({
710
+ email: { type: 'string' }
711
+ }, {
712
+ checkConstraints: [{ name: 'chk_accounts_email', clause: "email <> ''" }]
713
+ })),
714
+ /does not accept top-level checkConstraints/i
715
+ )
716
+ })
717
+ })
718
+
719
+ describe('RestApiKnexPlugin migration scope methods', () => {
720
+ let api
721
+
722
+ before(async () => {
723
+ db = knexLib({
724
+ client: 'better-sqlite3',
725
+ connection: {
726
+ filename: ':memory:'
727
+ },
728
+ useNullAsDefault: true
729
+ })
730
+
731
+ api = new Api({
732
+ name: 'migration-scope-test-api',
733
+ log: { level: 'warn' }
734
+ })
735
+
736
+ await api.use(RestApiPlugin, {
737
+ simplifiedApi: false,
738
+ simplifiedTransport: false
739
+ })
740
+ await api.use(RestApiKnexPlugin, { knex: db })
741
+
742
+ await api.addResource('memberships', {
743
+ schema: {
744
+ id: { type: 'id' },
745
+ workspaceId: { type: 'id', required: true },
746
+ userId: { type: 'id', required: true },
747
+ role: { type: 'string', enum: ['owner', 'member'], required: true, defaultTo: 'member' }
748
+ },
749
+ indexes: [
750
+ {
751
+ name: 'uq_scope_memberships_workspace_user',
752
+ unique: true,
753
+ columns: ['workspaceId', 'userId']
754
+ }
755
+ ],
756
+ checkConstraints: [
757
+ {
758
+ name: 'chk_scope_memberships_workspace_positive',
759
+ clause: 'workspace_id > 0'
760
+ }
761
+ ],
762
+ tableName: 'scope_memberships'
763
+ })
764
+
765
+ await api.resources.memberships.createKnexTable()
766
+ })
767
+
768
+ after(async () => {
769
+ await db.destroy()
770
+ })
771
+
772
+ it('exposes create and diff migration helpers through table-backed resource scopes', async () => {
773
+ const createMigration = await api.resources.memberships.generateKnexMigration()
774
+
775
+ assert.ok(createMigration.includes("table.unique(['workspace_id', 'user_id'], 'uq_scope_memberships_workspace_user')"))
776
+ assert.ok(createMigration.includes("table.check('workspace_id > 0', [], 'chk_scope_memberships_workspace_positive')"))
777
+
778
+ const diff = await api.resources.memberships.generateKnexMigrationDiff()
779
+
780
+ assert.deepEqual(diff.warnings, [])
781
+ assert.equal(diff.plan.addColumns.length, 0)
782
+ assert.equal(diff.plan.alterColumns.length, 0)
783
+ assert.equal(diff.plan.addIndexes.length, 0)
784
+ assert.equal(diff.plan.addCheckConstraints.length, 0)
785
+ })
786
+ })