@fgv/ts-utils 5.0.0-2 → 5.0.0-21

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 (311) hide show
  1. package/.vscode/launch.json +16 -0
  2. package/.vscode/settings.json +36 -0
  3. package/config/api-extractor.json +343 -0
  4. package/config/rig.json +16 -0
  5. package/dist/ts-utils.d.ts +20 -8
  6. package/dist/tsdoc-metadata.json +1 -1
  7. package/lib/packlets/base/result.d.ts +8 -0
  8. package/lib/packlets/base/result.js +11 -0
  9. package/lib/packlets/hash/crcNormalizer.js +3 -1
  10. package/lib/packlets/validation/array.d.ts +2 -1
  11. package/lib/packlets/validation/array.js +2 -1
  12. package/lib/packlets/validation/common.d.ts +0 -8
  13. package/lib/packlets/validation/field.d.ts +1 -1
  14. package/lib/packlets/validation/field.js +1 -1
  15. package/lib/packlets/validation/genericValidator.d.ts +1 -6
  16. package/lib/packlets/validation/genericValidator.js +11 -11
  17. package/lib/packlets/validation/object.d.ts +1 -1
  18. package/lib/packlets/validation/object.js +1 -1
  19. package/lib/packlets/validation/oneOf.d.ts +2 -1
  20. package/lib/packlets/validation/oneOf.js +2 -1
  21. package/lib/packlets/validation/typeGuard.d.ts +3 -2
  22. package/lib/packlets/validation/typeGuard.js +2 -1
  23. package/lib/packlets/validation/validator.d.ts +7 -0
  24. package/lib/packlets/validation/validatorBase.d.ts +2 -1
  25. package/lib/packlets/validation/validatorBase.js +1 -1
  26. package/lib/packlets/validation/validators.d.ts +2 -2
  27. package/lib/packlets/validation/validators.js +3 -3
  28. package/lib/test/helpers/jest/helpers/fsHelpers.d.ts +52 -0
  29. package/lib/test/helpers/jest/helpers/fsHelpers.js +180 -0
  30. package/lib/test/helpers/jest/helpers/index.d.ts +2 -0
  31. package/lib/test/helpers/jest/helpers/index.js +18 -0
  32. package/lib/test/helpers/jest/index.d.ts +3 -0
  33. package/lib/test/helpers/jest/index.js +27 -0
  34. package/lib/test/helpers/jest/matchers/index.d.ts +16 -0
  35. package/lib/test/helpers/jest/matchers/index.js +19 -0
  36. package/lib/test/helpers/jest/matchers/toFail/index.d.ts +16 -0
  37. package/lib/test/helpers/jest/matchers/toFail/index.js +25 -0
  38. package/lib/test/helpers/jest/matchers/toFail/predicate.d.ts +4 -0
  39. package/lib/test/helpers/jest/matchers/toFail/predicate.js +9 -0
  40. package/lib/test/helpers/jest/matchers/toFailTest/index.d.ts +16 -0
  41. package/lib/test/helpers/jest/matchers/toFailTest/index.js +30 -0
  42. package/lib/test/helpers/jest/matchers/toFailTest/predicate.d.ts +3 -0
  43. package/lib/test/helpers/jest/matchers/toFailTest/predicate.js +12 -0
  44. package/lib/test/helpers/jest/matchers/toFailTestAndMatchSnapshot/index.d.ts +17 -0
  45. package/lib/test/helpers/jest/matchers/toFailTestAndMatchSnapshot/index.js +26 -0
  46. package/lib/test/helpers/jest/matchers/toFailTestAndMatchSnapshot/predicate.d.ts +4 -0
  47. package/lib/test/helpers/jest/matchers/toFailTestAndMatchSnapshot/predicate.js +15 -0
  48. package/lib/test/helpers/jest/matchers/toFailTestWith/index.d.ts +18 -0
  49. package/lib/test/helpers/jest/matchers/toFailTestWith/index.js +31 -0
  50. package/lib/test/helpers/jest/matchers/toFailTestWith/predicate.d.ts +4 -0
  51. package/lib/test/helpers/jest/matchers/toFailTestWith/predicate.js +30 -0
  52. package/lib/test/helpers/jest/matchers/toFailWith/index.d.ts +18 -0
  53. package/lib/test/helpers/jest/matchers/toFailWith/index.js +29 -0
  54. package/lib/test/helpers/jest/matchers/toFailWith/predicate.d.ts +4 -0
  55. package/lib/test/helpers/jest/matchers/toFailWith/predicate.js +20 -0
  56. package/lib/test/helpers/jest/matchers/toFailWithDetail/index.d.ts +19 -0
  57. package/lib/test/helpers/jest/matchers/toFailWithDetail/index.js +29 -0
  58. package/lib/test/helpers/jest/matchers/toFailWithDetail/predicate.d.ts +4 -0
  59. package/lib/test/helpers/jest/matchers/toFailWithDetail/predicate.js +26 -0
  60. package/lib/test/helpers/jest/matchers/toSucceed/index.d.ts +16 -0
  61. package/lib/test/helpers/jest/matchers/toSucceed/index.js +25 -0
  62. package/lib/test/helpers/jest/matchers/toSucceed/predicate.d.ts +4 -0
  63. package/lib/test/helpers/jest/matchers/toSucceed/predicate.js +9 -0
  64. package/lib/test/helpers/jest/matchers/toSucceedAndMatchInlineSnapshot/index.d.ts +17 -0
  65. package/lib/test/helpers/jest/matchers/toSucceedAndMatchInlineSnapshot/index.js +26 -0
  66. package/lib/test/helpers/jest/matchers/toSucceedAndMatchSnapshot/index.d.ts +17 -0
  67. package/lib/test/helpers/jest/matchers/toSucceedAndMatchSnapshot/index.js +26 -0
  68. package/lib/test/helpers/jest/matchers/toSucceedAndSatisfy/index.d.ts +19 -0
  69. package/lib/test/helpers/jest/matchers/toSucceedAndSatisfy/index.js +55 -0
  70. package/lib/test/helpers/jest/matchers/toSucceedAndSatisfy/predicate.d.ts +4 -0
  71. package/lib/test/helpers/jest/matchers/toSucceedAndSatisfy/predicate.js +21 -0
  72. package/lib/test/helpers/jest/matchers/toSucceedWith/index.d.ts +18 -0
  73. package/lib/test/helpers/jest/matchers/toSucceedWith/index.js +29 -0
  74. package/lib/test/helpers/jest/matchers/toSucceedWith/predicate.d.ts +4 -0
  75. package/lib/test/helpers/jest/matchers/toSucceedWith/predicate.js +16 -0
  76. package/lib/test/helpers/jest/matchers/toSucceedWithDetail/index.d.ts +18 -0
  77. package/lib/test/helpers/jest/matchers/toSucceedWithDetail/index.js +29 -0
  78. package/lib/test/helpers/jest/matchers/toSucceedWithDetail/predicate.d.ts +4 -0
  79. package/lib/test/helpers/jest/matchers/toSucceedWithDetail/predicate.js +21 -0
  80. package/lib/test/helpers/jest/resolvers/cli.d.ts +5 -0
  81. package/lib/test/helpers/jest/resolvers/cli.js +48 -0
  82. package/lib/test/helpers/jest/resolvers/ide.d.ts +5 -0
  83. package/lib/test/helpers/jest/resolvers/ide.js +48 -0
  84. package/lib/test/helpers/jest/ts-utils.d.ts +2 -0
  85. package/lib/test/helpers/jest/ts-utils.js +18 -0
  86. package/lib/test/helpers/jest/types/index.d.ts +79 -0
  87. package/lib/test/helpers/jest/types/index.js +4 -0
  88. package/lib/test/helpers/jest/utils/matcherHelpers.d.ts +6 -0
  89. package/lib/test/helpers/jest/utils/matcherHelpers.js +53 -0
  90. package/lib/test/helpers/jest/utils/snapshotResolver.d.ts +4 -0
  91. package/lib/test/helpers/jest/utils/snapshotResolver.js +19 -0
  92. package/lib/test/unit/collections/collectible.test.d.ts +2 -0
  93. package/lib/test/unit/collections/collector.test.d.ts +2 -0
  94. package/lib/test/unit/collections/collectors.test.d.ts +2 -0
  95. package/lib/test/unit/collections/convertingCollector.test.d.ts +2 -0
  96. package/lib/test/unit/collections/helpers.d.ts +44 -0
  97. package/lib/test/unit/collections/helpers.js +115 -0
  98. package/lib/test/unit/collections/resultMap.test.d.ts +2 -0
  99. package/lib/test/unit/collections/validatingCollector.test.d.ts +2 -0
  100. package/lib/test/unit/collections/validatingConvertingCollector.test.d.ts +2 -0
  101. package/lib/test/unit/collections/validatingResultMap.test.d.ts +2 -0
  102. package/lib/test/unit/converter.test.d.ts +2 -0
  103. package/lib/test/unit/converters.test.d.ts +2 -0
  104. package/lib/test/unit/defaultingConverter.test.d.ts +2 -0
  105. package/lib/test/unit/file-tree/fileItem.test.d.ts +2 -0
  106. package/lib/test/unit/file-tree/fileTree.test.d.ts +2 -0
  107. package/lib/test/unit/file-tree/fsTree.test.d.ts +2 -0
  108. package/lib/test/unit/file-tree/inMemoryTree.test.d.ts +2 -0
  109. package/lib/test/unit/file-tree/sample/rootFile.json +1 -0
  110. package/lib/test/unit/file-tree/sample/some/other/path/file2.json +1 -0
  111. package/lib/test/unit/file-tree/sample/some/path/below/file4.json +1 -0
  112. package/lib/test/unit/file-tree/sample/some/path/file1.json +1 -0
  113. package/lib/test/unit/file-tree/sample/some/path/file3.json +1 -0
  114. package/lib/test/unit/hash.test.d.ts +2 -0
  115. package/lib/test/unit/logger.test.d.ts +2 -0
  116. package/lib/test/unit/mapResults.test.d.ts +3 -0
  117. package/lib/test/unit/messageAggregator.test.d.ts +3 -0
  118. package/lib/test/unit/normalize.test.d.ts +2 -0
  119. package/lib/test/unit/result.test.d.ts +3 -0
  120. package/lib/test/unit/utils.test.d.ts +3 -0
  121. package/lib/test/unit/validation/array.test.d.ts +2 -0
  122. package/lib/test/unit/validation/boolean.test.d.ts +2 -0
  123. package/lib/test/unit/validation/genericValidator.test.d.ts +2 -0
  124. package/lib/test/unit/validation/number.test.d.ts +2 -0
  125. package/lib/test/unit/validation/object.test.d.ts +2 -0
  126. package/lib/test/unit/validation/oneOf.test.d.ts +2 -0
  127. package/lib/test/unit/validation/recordOf.test.d.ts +2 -0
  128. package/lib/test/unit/validation/recursiveValidation.test.d.ts +2 -0
  129. package/lib/test/unit/validation/string.test.d.ts +2 -0
  130. package/lib/test/unit/validation/traits.test.d.ts +2 -0
  131. package/lib/test/unit/validation/typeGuard.test.d.ts +2 -0
  132. package/lib/test/unit/validation/validators.test.d.ts +2 -0
  133. package/package.json +9 -9
  134. package/src/index.ts +63 -0
  135. package/src/packlets/base/brand.ts +28 -0
  136. package/src/packlets/base/index.ts +31 -0
  137. package/src/packlets/base/logger.ts +156 -0
  138. package/src/packlets/base/mapResults.ts +302 -0
  139. package/src/packlets/base/messageAggregator.ts +120 -0
  140. package/src/packlets/base/normalize.ts +144 -0
  141. package/src/packlets/base/result.ts +961 -0
  142. package/src/packlets/base/utils.ts +236 -0
  143. package/src/packlets/collections/collectible.ts +238 -0
  144. package/src/packlets/collections/collector.ts +273 -0
  145. package/src/packlets/collections/collectorValidator.ts +178 -0
  146. package/src/packlets/collections/common.ts +27 -0
  147. package/src/packlets/collections/convertingCollector.ts +223 -0
  148. package/src/packlets/collections/convertingCollectorValidator.ts +164 -0
  149. package/src/packlets/collections/index.ts +39 -0
  150. package/src/packlets/collections/keyValueConverters.ts +142 -0
  151. package/src/packlets/collections/readonlyResultMap.ts +99 -0
  152. package/src/packlets/collections/resultMap.ts +322 -0
  153. package/src/packlets/collections/resultMapValidator.ts +188 -0
  154. package/src/packlets/collections/utils.ts +33 -0
  155. package/src/packlets/collections/validatingCollector.ts +123 -0
  156. package/src/packlets/collections/validatingConvertingCollector.ts +113 -0
  157. package/src/packlets/collections/validatingResultMap.ts +94 -0
  158. package/src/packlets/conversion/baseConverter.ts +330 -0
  159. package/src/packlets/conversion/converter.ts +260 -0
  160. package/src/packlets/conversion/converters.ts +1039 -0
  161. package/src/packlets/conversion/defaultingConverter.ts +188 -0
  162. package/src/packlets/conversion/index.ts +30 -0
  163. package/src/packlets/conversion/objectConverter.ts +259 -0
  164. package/src/packlets/conversion/stringConverter.ts +165 -0
  165. package/src/packlets/file-tree/directoryItem.ts +84 -0
  166. package/src/packlets/file-tree/fileItem.ts +119 -0
  167. package/src/packlets/file-tree/fileTree.ts +152 -0
  168. package/src/packlets/file-tree/fileTreeAccessors.ts +176 -0
  169. package/src/packlets/file-tree/fsTree.ts +118 -0
  170. package/src/packlets/file-tree/in-memory/inMemoryTree.ts +171 -0
  171. package/src/packlets/file-tree/in-memory/index.ts +23 -0
  172. package/src/packlets/file-tree/in-memory/treeBuilder.ts +203 -0
  173. package/src/packlets/file-tree/index.ts +31 -0
  174. package/src/packlets/hash/crcNormalizer.ts +81 -0
  175. package/src/packlets/hash/hashingNormalizer.ts +102 -0
  176. package/src/packlets/hash/index.ts +24 -0
  177. package/src/packlets/validation/array.ts +84 -0
  178. package/src/packlets/validation/boolean.ts +63 -0
  179. package/src/packlets/validation/classes.ts +38 -0
  180. package/src/packlets/validation/common.ts +28 -0
  181. package/src/packlets/validation/field.ts +99 -0
  182. package/src/packlets/validation/genericValidator.ts +204 -0
  183. package/src/packlets/validation/index.ts +31 -0
  184. package/src/packlets/validation/number.ts +66 -0
  185. package/src/packlets/validation/object.ts +208 -0
  186. package/src/packlets/validation/oneOf.ts +78 -0
  187. package/src/packlets/validation/string.ts +66 -0
  188. package/src/packlets/validation/traits.ts +113 -0
  189. package/src/packlets/validation/typeGuard.ts +83 -0
  190. package/src/packlets/validation/validator.ts +157 -0
  191. package/src/packlets/validation/validatorBase.ts +66 -0
  192. package/src/packlets/validation/validators.ts +254 -0
  193. package/CHANGELOG.md +0 -135
  194. package/lib/index.d.ts.map +0 -1
  195. package/lib/index.js.map +0 -1
  196. package/lib/packlets/base/brand.d.ts.map +0 -1
  197. package/lib/packlets/base/brand.js.map +0 -1
  198. package/lib/packlets/base/index.d.ts.map +0 -1
  199. package/lib/packlets/base/index.js.map +0 -1
  200. package/lib/packlets/base/logger.d.ts.map +0 -1
  201. package/lib/packlets/base/logger.js.map +0 -1
  202. package/lib/packlets/base/mapResults.d.ts.map +0 -1
  203. package/lib/packlets/base/mapResults.js.map +0 -1
  204. package/lib/packlets/base/messageAggregator.d.ts.map +0 -1
  205. package/lib/packlets/base/messageAggregator.js.map +0 -1
  206. package/lib/packlets/base/normalize.d.ts.map +0 -1
  207. package/lib/packlets/base/normalize.js.map +0 -1
  208. package/lib/packlets/base/result.d.ts.map +0 -1
  209. package/lib/packlets/base/result.js.map +0 -1
  210. package/lib/packlets/base/utils.d.ts.map +0 -1
  211. package/lib/packlets/base/utils.js.map +0 -1
  212. package/lib/packlets/collections/collectible.d.ts.map +0 -1
  213. package/lib/packlets/collections/collectible.js.map +0 -1
  214. package/lib/packlets/collections/collector.d.ts.map +0 -1
  215. package/lib/packlets/collections/collector.js.map +0 -1
  216. package/lib/packlets/collections/collectorValidator.d.ts.map +0 -1
  217. package/lib/packlets/collections/collectorValidator.js.map +0 -1
  218. package/lib/packlets/collections/common.d.ts.map +0 -1
  219. package/lib/packlets/collections/common.js.map +0 -1
  220. package/lib/packlets/collections/convertingCollector.d.ts.map +0 -1
  221. package/lib/packlets/collections/convertingCollector.js.map +0 -1
  222. package/lib/packlets/collections/convertingCollectorValidator.d.ts.map +0 -1
  223. package/lib/packlets/collections/convertingCollectorValidator.js.map +0 -1
  224. package/lib/packlets/collections/index.d.ts.map +0 -1
  225. package/lib/packlets/collections/index.js.map +0 -1
  226. package/lib/packlets/collections/keyValueConverters.d.ts.map +0 -1
  227. package/lib/packlets/collections/keyValueConverters.js.map +0 -1
  228. package/lib/packlets/collections/readonlyResultMap.d.ts.map +0 -1
  229. package/lib/packlets/collections/readonlyResultMap.js.map +0 -1
  230. package/lib/packlets/collections/resultMap.d.ts.map +0 -1
  231. package/lib/packlets/collections/resultMap.js.map +0 -1
  232. package/lib/packlets/collections/resultMapValidator.d.ts.map +0 -1
  233. package/lib/packlets/collections/resultMapValidator.js.map +0 -1
  234. package/lib/packlets/collections/utils.d.ts.map +0 -1
  235. package/lib/packlets/collections/utils.js.map +0 -1
  236. package/lib/packlets/collections/validatingCollector.d.ts.map +0 -1
  237. package/lib/packlets/collections/validatingCollector.js.map +0 -1
  238. package/lib/packlets/collections/validatingConvertingCollector.d.ts.map +0 -1
  239. package/lib/packlets/collections/validatingConvertingCollector.js.map +0 -1
  240. package/lib/packlets/collections/validatingResultMap.d.ts.map +0 -1
  241. package/lib/packlets/collections/validatingResultMap.js.map +0 -1
  242. package/lib/packlets/conversion/baseConverter.d.ts.map +0 -1
  243. package/lib/packlets/conversion/baseConverter.js.map +0 -1
  244. package/lib/packlets/conversion/converter.d.ts.map +0 -1
  245. package/lib/packlets/conversion/converter.js.map +0 -1
  246. package/lib/packlets/conversion/converters.d.ts.map +0 -1
  247. package/lib/packlets/conversion/converters.js.map +0 -1
  248. package/lib/packlets/conversion/defaultingConverter.d.ts.map +0 -1
  249. package/lib/packlets/conversion/defaultingConverter.js.map +0 -1
  250. package/lib/packlets/conversion/index.d.ts.map +0 -1
  251. package/lib/packlets/conversion/index.js.map +0 -1
  252. package/lib/packlets/conversion/objectConverter.d.ts.map +0 -1
  253. package/lib/packlets/conversion/objectConverter.js.map +0 -1
  254. package/lib/packlets/conversion/stringConverter.d.ts.map +0 -1
  255. package/lib/packlets/conversion/stringConverter.js.map +0 -1
  256. package/lib/packlets/file-tree/directoryItem.d.ts.map +0 -1
  257. package/lib/packlets/file-tree/directoryItem.js.map +0 -1
  258. package/lib/packlets/file-tree/fileItem.d.ts.map +0 -1
  259. package/lib/packlets/file-tree/fileItem.js.map +0 -1
  260. package/lib/packlets/file-tree/fileTree.d.ts.map +0 -1
  261. package/lib/packlets/file-tree/fileTree.js.map +0 -1
  262. package/lib/packlets/file-tree/fileTreeAccessors.d.ts.map +0 -1
  263. package/lib/packlets/file-tree/fileTreeAccessors.js.map +0 -1
  264. package/lib/packlets/file-tree/fsTree.d.ts.map +0 -1
  265. package/lib/packlets/file-tree/fsTree.js.map +0 -1
  266. package/lib/packlets/file-tree/in-memory/inMemoryTree.d.ts.map +0 -1
  267. package/lib/packlets/file-tree/in-memory/inMemoryTree.js.map +0 -1
  268. package/lib/packlets/file-tree/in-memory/index.d.ts.map +0 -1
  269. package/lib/packlets/file-tree/in-memory/index.js.map +0 -1
  270. package/lib/packlets/file-tree/in-memory/treeBuilder.d.ts.map +0 -1
  271. package/lib/packlets/file-tree/in-memory/treeBuilder.js.map +0 -1
  272. package/lib/packlets/file-tree/index.d.ts.map +0 -1
  273. package/lib/packlets/file-tree/index.js.map +0 -1
  274. package/lib/packlets/hash/crcNormalizer.d.ts.map +0 -1
  275. package/lib/packlets/hash/crcNormalizer.js.map +0 -1
  276. package/lib/packlets/hash/hashingNormalizer.d.ts.map +0 -1
  277. package/lib/packlets/hash/hashingNormalizer.js.map +0 -1
  278. package/lib/packlets/hash/index.d.ts.map +0 -1
  279. package/lib/packlets/hash/index.js.map +0 -1
  280. package/lib/packlets/validation/array.d.ts.map +0 -1
  281. package/lib/packlets/validation/array.js.map +0 -1
  282. package/lib/packlets/validation/boolean.d.ts.map +0 -1
  283. package/lib/packlets/validation/boolean.js.map +0 -1
  284. package/lib/packlets/validation/classes.d.ts.map +0 -1
  285. package/lib/packlets/validation/classes.js.map +0 -1
  286. package/lib/packlets/validation/common.d.ts.map +0 -1
  287. package/lib/packlets/validation/common.js.map +0 -1
  288. package/lib/packlets/validation/field.d.ts.map +0 -1
  289. package/lib/packlets/validation/field.js.map +0 -1
  290. package/lib/packlets/validation/genericValidator.d.ts.map +0 -1
  291. package/lib/packlets/validation/genericValidator.js.map +0 -1
  292. package/lib/packlets/validation/index.d.ts.map +0 -1
  293. package/lib/packlets/validation/index.js.map +0 -1
  294. package/lib/packlets/validation/number.d.ts.map +0 -1
  295. package/lib/packlets/validation/number.js.map +0 -1
  296. package/lib/packlets/validation/object.d.ts.map +0 -1
  297. package/lib/packlets/validation/object.js.map +0 -1
  298. package/lib/packlets/validation/oneOf.d.ts.map +0 -1
  299. package/lib/packlets/validation/oneOf.js.map +0 -1
  300. package/lib/packlets/validation/string.d.ts.map +0 -1
  301. package/lib/packlets/validation/string.js.map +0 -1
  302. package/lib/packlets/validation/traits.d.ts.map +0 -1
  303. package/lib/packlets/validation/traits.js.map +0 -1
  304. package/lib/packlets/validation/typeGuard.d.ts.map +0 -1
  305. package/lib/packlets/validation/typeGuard.js.map +0 -1
  306. package/lib/packlets/validation/validator.d.ts.map +0 -1
  307. package/lib/packlets/validation/validator.js.map +0 -1
  308. package/lib/packlets/validation/validatorBase.d.ts.map +0 -1
  309. package/lib/packlets/validation/validatorBase.js.map +0 -1
  310. package/lib/packlets/validation/validators.d.ts.map +0 -1
  311. package/lib/packlets/validation/validators.js.map +0 -1
@@ -0,0 +1,1039 @@
1
+ /*
2
+ * Copyright (c) 2020 Erik Fortune
3
+ *
4
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ * of this software and associated documentation files (the "Software"), to deal
6
+ * in the Software without restriction, including without limitation the rights
7
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ * copies of the Software, and to permit persons to whom the Software is
9
+ * furnished to do so, subject to the following conditions:
10
+ *
11
+ * The above copyright notice and this permission notice shall be included in all
12
+ * copies or substantial portions of the Software.
13
+ *
14
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ * SOFTWARE.
21
+ */
22
+
23
+ import { Result, fail, isKeyOf, succeed } from '../base';
24
+ import { TypeGuardWithContext, Validator } from '../validation';
25
+ import { BaseConverter, ConverterFunc } from './baseConverter';
26
+ import { Converter, OnError } from './converter';
27
+ import { FieldConverters, ObjectConverter, ObjectConverterOptions } from './objectConverter';
28
+ import { StringConverter } from './stringConverter';
29
+
30
+ /**
31
+ * Action to take on conversion failures (deprecated - use Conversion.OnError)
32
+ * @public
33
+ * @deprecated use Conversion.OnError.
34
+ */
35
+ export { OnError };
36
+
37
+ /**
38
+ * A converter to convert unknown to string. Values of type
39
+ * string succeed. Anything else fails.
40
+ * @public
41
+ */
42
+ export const string: StringConverter = new StringConverter();
43
+
44
+ /**
45
+ * Helper function to create a {@link Converter | Converter} which converts `unknown` to one of a set of supplied
46
+ * enumerated values. Anything else fails.
47
+ *
48
+ * @remarks
49
+ * Allowed enumerated values can also be supplied as context at conversion time.
50
+ * @param values - Array of allowed values.
51
+ * @returns A new {@link Converter | Converter} returning `<T>`.
52
+ * @public
53
+ */
54
+ export function enumeratedValue<T>(values: ReadonlyArray<T>): Converter<T, ReadonlyArray<T>> {
55
+ return new BaseConverter(
56
+ (from: unknown, __self: Converter<T, ReadonlyArray<T>>, context?: ReadonlyArray<T>): Result<T> => {
57
+ const v = context ?? values;
58
+ const index = v.indexOf(from as T);
59
+ return index >= 0 ? succeed(v[index]) : fail(`Invalid enumerated value ${JSON.stringify(from)}`);
60
+ }
61
+ );
62
+ }
63
+
64
+ /**
65
+ * Helper function to create a {@link Converter | Converter} which converts `unknown` to one of a set of supplied enumerated
66
+ * values, mapping any of multiple supplied values to the enumeration.
67
+ * @remarks
68
+ * Enables mapping of multiple input values to a consistent internal representation (so e.g. `'y'`, `'yes'`,
69
+ * `'true'`, `1` and `true` can all map to boolean `true`)
70
+ * @param map - An array of tuples describing the mapping. The first element of each tuple is the result
71
+ * value, the second is the set of values that map to the result. Tuples are evaluated in the order
72
+ * supplied and are not checked for duplicates.
73
+ * @param message - An optional error message.
74
+ * @returns A {@link Converter | Converter} which applies the mapping and yields `<T>` on success.
75
+ * @public
76
+ */
77
+ export function mappedEnumeratedValue<T, TC = unknown>(
78
+ map: ReadonlyArray<[T, ReadonlyArray<TC>]>,
79
+ message?: string
80
+ ): Converter<T, ReadonlyArray<TC>> {
81
+ return new BaseConverter(
82
+ (from: unknown, __self: Converter<T, ReadonlyArray<TC>>, __context?: ReadonlyArray<TC>) => {
83
+ for (const item of map) {
84
+ if (item[1].includes(from as TC)) {
85
+ return succeed(item[0]);
86
+ }
87
+ }
88
+ return fail(
89
+ message
90
+ ? `${JSON.stringify(from)}: ${message}`
91
+ : `Cannot map '${JSON.stringify(from)}' to a supported value`
92
+ );
93
+ }
94
+ );
95
+ }
96
+
97
+ /**
98
+ * Helper function to create a {@link Converter | Converter} which converts `unknown` to some supplied literal value. Succeeds with
99
+ * the supplied value if an identity comparison succeeds, fails otherwise.
100
+ * @param value - The value to be compared.
101
+ * @returns A {@link Converter | Converter} which returns the supplied value on success.
102
+ * @public
103
+ */
104
+ export function literal<T, TC = unknown>(value: T): Converter<T, TC> {
105
+ return new BaseConverter<T, TC>(
106
+ (from: unknown, __self: Converter<T, TC>, __context?: unknown): Result<T> => {
107
+ return from === value
108
+ ? succeed(value)
109
+ : fail(`${JSON.stringify(from)}: does not match ${JSON.stringify(value)}`);
110
+ }
111
+ );
112
+ }
113
+
114
+ /**
115
+ * Deprecated alias for @see literal
116
+ * @param value - The value to be compared.
117
+ * @deprecated Use {@link Converters.literal} instead.
118
+ * @internal
119
+ */
120
+ // eslint-disable-next-line @rushstack/typedef-var
121
+ export const value = literal;
122
+
123
+ /**
124
+ * A {@link Converter | Converter} which converts `unknown` to a `number`.
125
+ * @remarks
126
+ * Numbers and strings with a numeric format succeed. Anything else fails.
127
+ * @public
128
+ */
129
+ export const number: Converter<number, unknown> = new BaseConverter<number, unknown>((from: unknown) => {
130
+ if (typeof from !== 'number') {
131
+ const num: number = typeof from === 'string' ? Number(from) : NaN;
132
+ return isNaN(num) ? fail(`Not a number: ${JSON.stringify(from)}`) : succeed(num);
133
+ }
134
+ return succeed(from);
135
+ });
136
+
137
+ /**
138
+ * A {@link Converter | Converter} which converts `unknown` to `boolean`.
139
+ * @remarks
140
+ * Boolean values or the case-insensitive strings `'true'` and `'false'` succeed.
141
+ * Anything else fails.
142
+ * @public
143
+ */
144
+ export const boolean: Converter<boolean, unknown> = new BaseConverter<boolean, unknown>((from: unknown) => {
145
+ if (typeof from === 'boolean') {
146
+ return succeed(from as boolean);
147
+ } else if (typeof from === 'string') {
148
+ switch (from.toLowerCase()) {
149
+ case 'true':
150
+ return succeed(true);
151
+ case 'false':
152
+ return succeed(false);
153
+ }
154
+ }
155
+ return fail(`Not a boolean: ${JSON.stringify(from)}`);
156
+ });
157
+
158
+ /**
159
+ * A {@link Converter | Converter} which converts an optional `string` value. Values of type
160
+ * `string` are returned. Anything else returns {@link Success | Success} with value `undefined`.
161
+ * @public
162
+ */
163
+ export const optionalString: Converter<string | undefined, unknown> = string.optional();
164
+
165
+ /**
166
+ * Helper function to create a {@link Converter | Converter} which converts any `string` into an
167
+ * array of `string`, by separating at a supplied delimiter.
168
+ * @remarks
169
+ * Delimiter may also be supplied as context at conversion time.
170
+ * @param delimiter - The delimiter at which to split.
171
+ * @returns A new {@link Converter | Converter} returning `string[]`.
172
+ * @public
173
+ */
174
+ export function delimitedString(
175
+ delimiter: string,
176
+ options: 'filtered' | 'all' = 'filtered'
177
+ ): Converter<string[], string> {
178
+ return new BaseConverter<string[], string>(
179
+ (from: unknown, __self: Converter<string[], string>, context?: string) => {
180
+ const result = string.convert(from);
181
+ if (result.isSuccess()) {
182
+ let strings = result.value.split(context ?? delimiter);
183
+ if (options !== 'all') {
184
+ strings = strings.filter((s) => s.trim().length > 0);
185
+ }
186
+ return succeed(strings);
187
+ }
188
+ return fail(result.message);
189
+ }
190
+ );
191
+ }
192
+
193
+ /**
194
+ * Helper function to create a {@link Converter | Converter} from any {@link Validation.Validator}
195
+ * @param validator - the validator to be wrapped
196
+ * @returns A {@link Converter | Converter} which uses the supplied validator.
197
+ * @public
198
+ */
199
+ export function validated<T, TC = unknown>(validator: Validator<T, TC>): Converter<T, TC> {
200
+ return new BaseConverter((from: unknown, __self?: Converter<T, TC>, context?: TC) => {
201
+ return validator.validate(from, context);
202
+ });
203
+ }
204
+
205
+ /**
206
+ * Helper function to create a {@link Converter | Converter} from a supplied {@link Conversion.ConverterFunc | ConverterFunc}.
207
+ * @param convert - the function to be wrapped
208
+ * @returns A {@link Converter | Converter} which uses the supplied function.
209
+ * @public
210
+ */
211
+ export function generic<T, TC = unknown>(convert: ConverterFunc<T, TC>): Converter<T, TC> {
212
+ return new BaseConverter(convert);
213
+ }
214
+
215
+ /**
216
+ * Helper function to create a {@link Converter | Converter} from a supplied type guard function.
217
+ * @param description - a description of the thing to be validated for use in error messages
218
+ * @param guard - a {@link Validation.TypeGuardWithContext} which performs the validation.
219
+ * @returns A new {@link Converter | Converter} which validates the values using the supplied type guard
220
+ * and returns them in place.
221
+ * @public
222
+ */
223
+ export function isA<T, TC = unknown>(
224
+ description: string,
225
+ guard: TypeGuardWithContext<T, TC>
226
+ ): Converter<T, TC> {
227
+ return new BaseConverter((from: unknown, __self?: Converter<T, TC>, context?: TC) => {
228
+ if (guard(from, context)) {
229
+ return succeed(from);
230
+ }
231
+ return fail(`invalid ${description} (${JSON.stringify(from)})`);
232
+ });
233
+ }
234
+
235
+ /**
236
+ * A {@link Converter | Converter} which converts an optional `number` value.
237
+ * @remarks
238
+ * Values of type `number` or numeric strings are converted and returned.
239
+ * Anything else returns {@link Success | Success} with value `undefined`.
240
+ * @public
241
+ */
242
+ export const optionalNumber: Converter<number | undefined, unknown> = number.optional();
243
+
244
+ /**
245
+ * A {@link Converter | Converter} to convert an optional `boolean` value.
246
+ * @remarks
247
+ * Values of type `boolean` or strings that match (case-insensitive) `'true'`
248
+ * or `'false'` are converted and returned. Anything else returns {@link Success | Success}
249
+ * with value `undefined`.
250
+ * @public
251
+ */
252
+ export const optionalBoolean: Converter<boolean | undefined, unknown> = boolean.optional();
253
+
254
+ /**
255
+ * A helper function to create a {@link Converter | Converter} for polymorphic values.
256
+ * Returns a converter which invokes the wrapped converters in sequence, returning the
257
+ * first successful result. Returns an error if none of the supplied converters can
258
+ * convert the value.
259
+ * @remarks
260
+ * If `onError` is `ignoreErrors` (default), then errors from any of the
261
+ * converters are ignored provided that some converter succeeds. If
262
+ * onError is `failOnError`, then an error from any converter fails the entire
263
+ * conversion.
264
+ *
265
+ * @param converters - An ordered list of {@link Converter | converters} or {@link Validator | validators}
266
+ * to be considered.
267
+ * @param onError - Specifies treatment of unconvertible elements.
268
+ * @returns A new {@link Converter | Converter} which yields a value from the union of the types returned
269
+ * by the wrapped converters.
270
+ * @public
271
+ */
272
+ export function oneOf<T, TC = unknown>(
273
+ converters: Array<Converter<T, TC> | Validator<T, TC>>,
274
+ onError: OnError = 'ignoreErrors'
275
+ ): Converter<T, TC> {
276
+ return new BaseConverter((from: unknown, __self, context?: TC) => {
277
+ const errors: string[] = [];
278
+ for (const converter of converters) {
279
+ const result = converter.convert(from, context);
280
+ if (result.isSuccess() && result.value !== undefined) {
281
+ return result;
282
+ }
283
+
284
+ if (result.isFailure()) {
285
+ if (onError === 'failOnError') {
286
+ return result;
287
+ }
288
+ errors.push(result.message);
289
+ }
290
+ }
291
+ return fail(`No matching converter for ${JSON.stringify(from)}: ${errors.join('\n')}`);
292
+ });
293
+ }
294
+
295
+ /**
296
+ * A helper function to create a {@link Converter | Converter} which converts `unknown` to an array of `<T>`.
297
+ * @remarks
298
+ * If `onError` is `'failOnError'` (default), then the entire conversion fails if any element cannot
299
+ * be converted. If `onError` is `'ignoreErrors'`, then failing elements are silently ignored.
300
+ * @param converter - {@link Converter | Converter} or {@link Validator | Validator} used to convert each
301
+ * item in the array.
302
+ * @param ignoreErrors - Specifies treatment of unconvertible elements.
303
+ * @returns A {@link Converter | Converter} which returns an array of `<T>`.
304
+ * @public
305
+ */
306
+ export function arrayOf<T, TC = unknown>(
307
+ converter: Converter<T, TC> | Validator<T, TC>,
308
+ onError: OnError = 'failOnError'
309
+ ): Converter<T[], TC> {
310
+ return new BaseConverter((from: unknown, __self: Converter<T[], TC>, context?: TC) => {
311
+ if (!Array.isArray(from)) {
312
+ return fail(`Not an array: ${JSON.stringify(from)}`);
313
+ }
314
+
315
+ const successes: T[] = [];
316
+ const errors: string[] = [];
317
+ for (const item of from) {
318
+ const result = converter.convert(item, context);
319
+ if (result.isSuccess() && result.value !== undefined) {
320
+ successes.push(result.value);
321
+ } else if (result.isFailure()) {
322
+ errors.push(result.message);
323
+ }
324
+ }
325
+
326
+ return errors.length === 0 || onError === 'ignoreErrors' ? succeed(successes) : fail(errors.join('\n'));
327
+ });
328
+ }
329
+
330
+ /**
331
+ * {@link Converter | Converter} to convert an `unknown` to an array of `string`.
332
+ * @remarks
333
+ * Returns {@link Success | Success} with the the supplied value if it as an array
334
+ * of strings, returns {@link Failure | Failure} with an error message otherwise.
335
+ * @public
336
+ */
337
+ export const stringArray: Converter<string[], unknown> = arrayOf(string);
338
+
339
+ /**
340
+ * {@link Converter | Converter} to convert an `unknown` to an array of `number`.
341
+ * @remarks
342
+ * Returns {@link Success | Success} with the the supplied value if it as an array
343
+ * of numbers, returns {@link Failure | Failure} with an error message otherwise.
344
+ * @public
345
+ */
346
+ export const numberArray: Converter<number[], unknown> = arrayOf(number);
347
+
348
+ /**
349
+ * Options for {@link Converters.(recordOf:3) | Converters.recordOf} and
350
+ * {@link Converters.(mapOf:3) | Converters.mapOf}
351
+ * helper functions.
352
+ * @public
353
+ */
354
+ // eslint-disable-next-line @typescript-eslint/naming-convention
355
+ export interface KeyedConverterOptions<T extends string = string, TC = unknown> {
356
+ /**
357
+ * if `onError` is `'fail'` (default), then the entire conversion fails if any key or element
358
+ * cannot be converted. If `onError` is `'ignore'`, failing elements are silently ignored.
359
+ */
360
+ onError?: 'fail' | 'ignore';
361
+ /**
362
+ * If present, `keyConverter` is used to convert the source object property names to
363
+ * keys in the resulting map or record.
364
+ * @remarks
365
+ * Can be used to coerce key names to supported values and/or strong types.
366
+ */
367
+ keyConverter?: Converter<T, TC> | Validator<T, TC>;
368
+ }
369
+
370
+ /**
371
+ * A helper function to create a {@link Converter | Converter} which converts the `string`-keyed
372
+ * properties using a supplied {@link Converter | Converter<T, TC>} or {@link Validator | Validator<T>} to
373
+ * produce a `Record<string, T>`.
374
+ * @remarks
375
+ * The resulting converter fails conversion if any element cannot be converted.
376
+ * @param converter - {@link Converter | Converter} or {@link Validator | Validator} used for each
377
+ * item in the source object.
378
+ * @returns A {@link Converter | Converter} which returns `Record<string, T>`.
379
+ * {@label WITH_DEFAULT}
380
+ * @public
381
+ */
382
+ export function recordOf<T, TC = unknown, TK extends string = string>(
383
+ converter: Converter<T, TC> | Validator<T, TC>
384
+ ): Converter<Record<TK, T>, TC>;
385
+
386
+ /**
387
+ * A helper function to create a {@link Converter | Converter} which converts the `string`-keyed properties
388
+ * using a supplied {@link Converter | Converter<T, TC>} or {@link Validator | Validator<T>} to produce a
389
+ * `Record<string, T>` and optionally specified handling of elements that cannot be converted.
390
+ * @remarks
391
+ * if `onError` is `'fail'` (default), then the entire conversion fails if any key or element
392
+ * cannot be converted. If `onError` is `'ignore'`, failing elements are silently ignored.
393
+ * @param converter - {@link Converter | Converter} or {@link Validator | Validator} for each item in
394
+ * the source object.
395
+ * @returns A {@link Converter | Converter} which returns `Record<string, T>`.
396
+ * {@label WITH_ON_ERROR}
397
+ * @public
398
+ */
399
+ export function recordOf<T, TC = unknown, TK extends string = string>(
400
+ converter: Converter<T, TC> | Validator<T, TC>,
401
+ onError: 'fail' | 'ignore'
402
+ ): Converter<Record<TK, T>, TC>;
403
+
404
+ /**
405
+ * A helper function to create a {@link Converter | Converter} or which converts the `string`-keyed properties
406
+ * using a supplied {@link Converter | Converter<T, TC>} or {@link Validator | Validator<T>} to produce a
407
+ * `Record<TK, T>`.
408
+ * @remarks
409
+ * If present, the supplied {@link Converters.KeyedConverterOptions | options} can provide a strongly-typed
410
+ * converter for keys and/or control the handling of elements that fail conversion.
411
+ * @param converter - {@link Converter | Converter} or {@link Validator | Validator} used for each item in the source object.
412
+ * @param options - Optional {@link Converters.KeyedConverterOptions | KeyedConverterOptions<TK, TC>} which
413
+ * supplies a key converter and/or error-handling options.
414
+ * @returns A {@link Converter | Converter} which returns `Record<TK, T>`.
415
+ * {@label WITH_OPTIONS}
416
+ * @public
417
+ */
418
+ export function recordOf<T, TC = unknown, TK extends string = string>(
419
+ converter: Converter<T, TC> | Validator<T, TC>,
420
+ options: KeyedConverterOptions<TK, TC>
421
+ ): Converter<Record<TK, T>, TC>;
422
+
423
+ /**
424
+ * Concrete implementation of {@link Converters.(recordOf:1) | Converters.recordOf(Converter<T, TC>)},
425
+ * {@link Converters.(recordOf:2) | Converters.recordOf(Converter<T, TC>, 'fail' or 'ignore')}, and
426
+ * {@link Converters.(recordOf:3) | Converters.recordOf(Converter<T, TC>, KeyedConverterOptions)}.
427
+ * @internal
428
+ */
429
+ export function recordOf<T, TC = unknown, TK extends string = string>(
430
+ converter: Converter<T, TC> | Validator<T, TC>,
431
+ option: 'fail' | 'ignore' | KeyedConverterOptions<TK, TC> = 'fail'
432
+ ): Converter<Record<TK, T>, TC> {
433
+ const options: KeyedConverterOptions<TK, TC> =
434
+ typeof option === 'string' ? { onError: option } : { onError: 'fail', ...option };
435
+ return new BaseConverter((from: unknown, __self: Converter<Record<TK, T>, TC>, context?: TC) => {
436
+ if (typeof from !== 'object' || from === null || Array.isArray(from)) {
437
+ return fail(`Not a string-keyed object: ${JSON.stringify(from)}`);
438
+ }
439
+
440
+ const record: Record<string, T> = {};
441
+ const errors: string[] = [];
442
+
443
+ for (const key in from) {
444
+ if (isKeyOf(key, from)) {
445
+ const writeKeyResult = options.keyConverter?.convert(key, context) ?? succeed(key);
446
+
447
+ writeKeyResult
448
+ .onSuccess((writeKey) => {
449
+ return converter.convert(from[key] as unknown, context).onSuccess((value) => {
450
+ record[writeKey] = value;
451
+ return succeed(true);
452
+ });
453
+ })
454
+ .onFailure((message) => {
455
+ errors.push(message);
456
+ return fail(message);
457
+ });
458
+ }
459
+ }
460
+
461
+ return errors.length === 0 || options.onError === 'ignore' ? succeed(record) : fail(errors.join('\n'));
462
+ });
463
+ }
464
+
465
+ /**
466
+ * A helper function to create a {@link Converter | Converter} which converts the `string`-keyed properties
467
+ * using a supplied {@link Converter | Converter<T, TC>} or {@link Validator | Validator<T>} to produce a
468
+ * `Map<string, T>`.
469
+ * @remarks
470
+ * The resulting converter fails conversion if any element cannot be converted.
471
+ * @param converter - {@link Converter | Converter} | {@link Validator | Validator} used for each item in
472
+ * the source object.
473
+ * @returns A {@link Converter | Converter} which returns `Map<string, T>`.
474
+ * {@label WITH_DEFAULT}
475
+ * @public
476
+ */
477
+ export function mapOf<T, TC = unknown, TK extends string = string>(
478
+ converter: Converter<T, TC> | Validator<T, TC>
479
+ ): Converter<Map<TK, T>, TC>;
480
+
481
+ /**
482
+ * A helper function to create a {@link Converter | Converter} which converts the `string`-keyed properties
483
+ * using a supplied {@link Converter | Converter<T, TC>} or {@link Validator | Validator<T>} to produce a
484
+ * `Map<string, T>` and specified handling of elements that cannot be converted.
485
+ * @remarks
486
+ * if `onError` is `'fail'` (default), then the entire conversion fails if any key or element
487
+ * cannot be converted. If `onError` is `'ignore'`, failing elements are silently ignored.
488
+ * @param converter - {@link Converter | Converter} or {@link Validator | Validator} used for
489
+ * each item in the source object.
490
+ * @returns A {@link Converter | Converter} which returns `Map<string, T>`.
491
+ * {@label WITH_ON_ERROR}
492
+ * @public
493
+ */
494
+ export function mapOf<T, TC = unknown, TK extends string = string>(
495
+ converter: Converter<T, TC> | Validator<T, TC>,
496
+ onError: 'fail' | 'ignore'
497
+ ): Converter<Map<TK, T>, TC>;
498
+
499
+ /**
500
+ * A helper function to create a {@link Converter | Converter} which converts the `string`-keyed properties
501
+ * using a supplied {@link Converter | Converter<T, TC>} or {@link Validator | Validator<T>} to produce
502
+ * a `Map<TK,T>`.
503
+ * @remarks
504
+ * If present, the supplied {@link Converters.KeyedConverterOptions | options} can provide a strongly-typed
505
+ * converter for keys and/or control the handling of elements that fail conversion.
506
+ * @param converter - {@link Converter | Converter} or {@link Validator | Validator} used for each item
507
+ * in the source object.
508
+ * @param options - Optional {@link Converters.KeyedConverterOptions | KeyedConverterOptions<TK, TC>} which
509
+ * supplies a key converter and/or error-handling options.
510
+ * @returns A {@link Converter | Converter} which returns `Map<TK,T>`.
511
+ * {@label WITH_OPTIONS}
512
+ * @public
513
+ */
514
+ export function mapOf<T, TC = unknown, TK extends string = string>(
515
+ converter: Converter<T, TC> | Validator<T, TC>,
516
+ options: KeyedConverterOptions<TK, TC>
517
+ ): Converter<Map<TK, T>, TC>;
518
+
519
+ /**
520
+ * Concrete implementation of {@link Converters.(mapOf:1) | Converters.mapOf(Converter<T, TC>)},
521
+ * {@link Converters.(mapOf:2) | Converters.mapOf(Converter<T, TC>, 'fail' or 'ignore')}, and
522
+ * {@link Converters.(mapOf:3) | Converters.mapOf(Converter<T, TC>, KeyedConverterOptions)}.
523
+ * @internal
524
+ */
525
+ export function mapOf<T, TC = unknown, TK extends string = string>(
526
+ converter: Converter<T, TC> | Validator<T, TC>,
527
+ option: 'fail' | 'ignore' | KeyedConverterOptions<TK, TC> = 'fail'
528
+ ): Converter<Map<TK, T>, TC> {
529
+ const options = typeof option === 'string' ? { onError: option } : { onError: 'fail', ...option };
530
+ return new BaseConverter((from: unknown, __self: Converter<Map<TK, T>, TC>, context?: TC) => {
531
+ if (typeof from !== 'object' || from === null || Array.isArray(from)) {
532
+ return fail(`Not a string-keyed object: ${JSON.stringify(from)}`);
533
+ }
534
+
535
+ const map = new Map<TK, T>();
536
+ const errors: string[] = [];
537
+
538
+ for (const key in from) {
539
+ if (isKeyOf(key, from)) {
540
+ const writeKeyResult = options.keyConverter?.convert(key, context) ?? succeed(key);
541
+
542
+ writeKeyResult
543
+ .onSuccess((writeKey) => {
544
+ return converter.convert(from[key] as unknown, context).onSuccess((value) => {
545
+ map.set(writeKey, value);
546
+ return succeed(true);
547
+ });
548
+ })
549
+ .onFailure((message) => {
550
+ errors.push(message);
551
+ return fail(message);
552
+ });
553
+ }
554
+ }
555
+
556
+ return errors.length === 0 || options.onError === 'ignore' ? succeed(map) : fail(errors.join('\n'));
557
+ });
558
+ }
559
+
560
+ /**
561
+ * Helper function to create a {@link Converter | Converter} which validates that a supplied value is
562
+ * of a type validated by a supplied validator function and returns it.
563
+ * @remarks
564
+ * If `validator` succeeds, this {@link Converter | Converter} returns {@link Success | Success} with the supplied
565
+ * value of `from` coerced to type `<T>`. Returns a {@link Failure | Failure} with additional
566
+ * information otherwise.
567
+ * @param validator - A validator function to determine if the converted value is valid.
568
+ * @param description - A description of the validated type for use in error messages.
569
+ * @returns A new {@link Converter | Converter<T, TC>} which applies the supplied validation.
570
+ * @public
571
+ */
572
+ export function validateWith<T, TC = unknown>(
573
+ validator: (from: unknown) => from is T,
574
+ description?: string
575
+ ): Converter<T, TC> {
576
+ return new BaseConverter((from: unknown, __self: Converter<T, TC>, __context?: TC) => {
577
+ if (validator(from)) {
578
+ return succeed(from);
579
+ }
580
+ return fail(`${JSON.stringify(from)}: invalid ${description ?? 'value'}`);
581
+ });
582
+ }
583
+
584
+ /**
585
+ * A helper function to create a {@link Converter | Converter} which extracts and converts an element from an array.
586
+ * @remarks
587
+ * The returned {@link Converter | Converter} returns {@link Success | Success} with the converted value if the element exists
588
+ * in the supplied array and can be converted. Returns {@link Failure | Failure} with an error message otherwise.
589
+ * @param index - The index of the element to be extracted.
590
+ * @param converter - A {@link Converter | Converter} or {@link Validator | Validator} for the extracted element.
591
+ * @returns A {@link Converter | Converter<T, TC>} which extracts the specified element from an array.
592
+ * @public
593
+ */
594
+ export function element<T, TC = unknown>(
595
+ index: number,
596
+ converter: Converter<T, TC> | Validator<T, TC>
597
+ ): Converter<T, TC> {
598
+ return new BaseConverter((from: unknown, __self: Converter<T, TC>, context?: TC) => {
599
+ if (index < 0) {
600
+ return fail(`${index}: cannot convert for a negative element index`);
601
+ } else if (!Array.isArray(from)) {
602
+ return fail('element converter: source is not an array');
603
+ } else if (index >= from.length) {
604
+ return fail(`${index}: element converter index out of range (0..${from.length - 1})`);
605
+ }
606
+ return converter.convert(from[index], context);
607
+ });
608
+ }
609
+
610
+ /**
611
+ * A helper function to create a {@link Converter | Converter} which extracts and converts an optional element from an array.
612
+ * @remarks
613
+ * The resulting {@link Converter | Converter} returns {@link Success | Success} with the converted value if the element exists
614
+ * in the supplied array and can be converted. Returns {@link Success | Success} with value `undefined` if the parameter
615
+ * is an array but the index is out of range. Returns {@link Failure | Failure} with a message if the supplied parameter
616
+ * is not an array, if the requested index is negative, or if the element cannot be converted.
617
+ * @param index - The index of the element to be extracted.
618
+ * @param converter - A {@link Converter | Converter} or {@link Validator | Validator} used for the extracted element.
619
+ * @returns A {@link Converter | Converter<T, TC>} which extracts the specified element from an array.
620
+ * @public
621
+ */
622
+ export function optionalElement<T, TC = unknown>(
623
+ index: number,
624
+ converter: Converter<T, TC> | Validator<T, TC>
625
+ ): Converter<T | undefined, TC> {
626
+ return new BaseConverter((from: unknown, __self: Converter<T | undefined, TC>, context?: TC) => {
627
+ if (index < 0) {
628
+ return fail(`${index}: cannot convert for a negative element index`);
629
+ } else if (!Array.isArray(from)) {
630
+ return fail('element converter: source is not an array');
631
+ } else if (index >= from.length) {
632
+ return succeed(undefined);
633
+ }
634
+ return converter.convert(from[index], context);
635
+ });
636
+ }
637
+
638
+ /**
639
+ * A helper function to create a {@link Converter | Converter} which extracts and convert a property specified
640
+ * by name from an object.
641
+ * @remarks
642
+ * The resulting {@link Converter | Converter} returns {@link Success | Success} with the converted value of the corresponding
643
+ * object property if the field exists and can be converted. Returns {@link Failure | Failure} with an error message
644
+ * otherwise.
645
+ * @param name - The name of the field to be extracted.
646
+ * @param converter - {@link Converter | Converter} or {@link Validator | Validator} to use for the extracted
647
+ * field.
648
+ * @public
649
+ */
650
+ export function field<T, TC = unknown>(
651
+ name: string,
652
+ converter: Converter<T, TC> | Validator<T, TC>
653
+ ): Converter<T, TC> {
654
+ return new BaseConverter((from: unknown, __self: Converter<T, TC>, context?: TC) => {
655
+ if (typeof from === 'object' && !Array.isArray(from) && from !== null) {
656
+ if (isKeyOf(name, from)) {
657
+ return converter.convert(from[name], context).onFailure((message) => {
658
+ return fail(`Field ${name}: ${message}`);
659
+ });
660
+ }
661
+ return fail(`Field ${name} not found in: ${JSON.stringify(from)}`);
662
+ }
663
+ return fail(`Cannot convert field "${name}" from non-object ${JSON.stringify(from)}`);
664
+ });
665
+ }
666
+
667
+ /**
668
+ * A helper function to create a {@link Converter | Converter} which extracts and convert a property specified
669
+ * by name from an object.
670
+ * @remarks
671
+ * The resulting {@link Converter | Converter} returns {@link Success | Success} with the converted value of
672
+ * the corresponding object property if the field exists and can be converted. Returns {@link Success | Success}
673
+ * with `undefined` if the supplied parameter is an object but the named field is not present.
674
+ * Returns {@link Failure | Failure} with an error message otherwise.
675
+ * @param name - The name of the field to be extracted.
676
+ * @param converter - {@link Converter | Converter} or {@link Validator | Validator} to use for the extracted field.
677
+ * @public
678
+ */
679
+ export function optionalField<T, TC = unknown>(
680
+ name: string,
681
+ converter: Converter<T, TC> | Validator<T, TC>
682
+ ): Converter<T | undefined, TC> {
683
+ return new BaseConverter(
684
+ (from: unknown, __self: Converter<T | undefined, TC>, context?: TC) => {
685
+ if (typeof from === 'object' && !Array.isArray(from) && from !== null) {
686
+ if (isKeyOf(name, from)) {
687
+ const result = converter.convert(from[name], context).onFailure((message) => {
688
+ return fail(`${name}: ${message}`);
689
+ });
690
+
691
+ // if conversion was successful or input was undefined we
692
+ // succeed with 'undefined', but we propagate actual
693
+ // failures.
694
+ if (result.isSuccess() || from[name] !== undefined) {
695
+ return result;
696
+ }
697
+ }
698
+ return succeed(undefined);
699
+ }
700
+ return fail(`Cannot convert field "${name}" from non-object ${JSON.stringify(from)}`);
701
+ },
702
+ undefined,
703
+ { isOptional: true }
704
+ );
705
+ }
706
+
707
+ /**
708
+ * Helper function to create a {@link Conversion.ObjectConverter | ObjectConverter<T, TC>} which converts an object
709
+ * without changing shape, given a {@link Conversion.FieldConverters | FieldConverters<T, TC>} and an optional
710
+ * {@link Conversion.ObjectConverterOptions | ObjectConverterOptions<T>} to further refine conversion behavior.
711
+ * @remarks
712
+ * By default, if all of the requested fields exist and can be converted, returns {@link Success | Success}
713
+ * with a new object that contains the converted values under the original key names. If any required properties
714
+ * do not exist or cannot be converted, the entire conversion fails, returning {@link Failure | Failure} with additional
715
+ * error information.
716
+ *
717
+ * Fields that succeed but convert to undefined are omitted from the result object but do not
718
+ * fail the conversion.
719
+ * @param properties - An {@link Conversion.FieldConverters | FieldConverters<T, TC>} defining the shape of the
720
+ * source object and {@link Converter | converters} to be applied to each properties.
721
+ * @param options - An {@link Conversion.ObjectConverterOptions | ObjectConverterOptions<T>} containing options
722
+ * for the object converter.
723
+ * @returns A new {@link Conversion.ObjectConverter | ObjectConverter} which applies the specified conversions.
724
+ * {@label WITH_OPTIONS}
725
+ * @public
726
+ */
727
+ export function object<T, TC = unknown>(
728
+ properties: FieldConverters<T, TC>,
729
+ options?: ObjectConverterOptions<T>
730
+ ): ObjectConverter<T, TC>;
731
+
732
+ /**
733
+ * Helper function to create a {@link Conversion.ObjectConverter | ObjectConverter<T, TC>} which converts an object
734
+ * without changing shape, given a {@link Conversion.FieldConverters | FieldConverters<T, TC>} and a set of
735
+ * optional properties.
736
+ * @remarks
737
+ * By default, if all of the requested fields exist and can be converted, returns {@link Success | Success}
738
+ * with a new object that contains the converted values under the original key names. If any required properties
739
+ * do not exist or cannot be converted, the entire conversion fails, returning {@link Failure | Failure} with additional
740
+ * error information.
741
+ *
742
+ * Fields that succeed but convert to undefined are omitted from the result object but do not
743
+ * fail the conversion.
744
+ * @param properties - An {@link Conversion.FieldConverters | FieldConverters<T, TC>} defining the shape of the
745
+ * source object and {@link Converter | converters} to be applied to each properties.
746
+ * @param optional - An array of `(keyof T)` listing the keys to be considered optional.
747
+ * {@label WITH_KEYS}
748
+ * @returns A new {@link Conversion.ObjectConverter | ObjectConverter} which applies the specified conversions.
749
+ * @public
750
+ * @deprecated Use {@link Converters.(object:1) | Converters.object(fields, options)} instead.
751
+ */
752
+
753
+ export function object<T, TC = unknown>(
754
+ properties: FieldConverters<T, TC>,
755
+ optional: (keyof T)[]
756
+ ): ObjectConverter<T, TC>;
757
+
758
+ /**
759
+ * Concrete implementation of {@link Converters.(object:1) | Converters.object(fields, options)}
760
+ * and {@link Converters.(object:2) | Converters.objects(fields, optionalKeys)}.
761
+ * @internal
762
+ */
763
+ export function object<T, TC>(
764
+ properties: FieldConverters<T, TC>,
765
+ options?: (keyof T)[] | ObjectConverterOptions<T>
766
+ ): ObjectConverter<T, TC> {
767
+ return new ObjectConverter(properties, options as ObjectConverterOptions<T>);
768
+ }
769
+
770
+ /**
771
+ * Options for the {@link Converters.(strictObject:1)} helper function.
772
+ * @public
773
+ */
774
+ export type StrictObjectConverterOptions<T> = Omit<ObjectConverterOptions<T>, 'strict'>;
775
+
776
+ /**
777
+ * Helper function to create a {@link Conversion.ObjectConverter | ObjectConverter} which converts an object
778
+ * without changing shape, a {@link Conversion.FieldConverters | FieldConverters<T, TC>} and an optional
779
+ * {@link Converters.StrictObjectConverterOptions | StrictObjectConverterOptions<T>} to further refine
780
+ * conversion behavior.
781
+ *
782
+ * @remarks
783
+ * Fields that succeed but convert to undefined are omitted from the result object but do not
784
+ * fail the conversion.
785
+ *
786
+ * The conversion fails if any unexpected fields are encountered.
787
+ *
788
+ * @param properties - An object containing defining the shape and converters to be applied.
789
+ * @param options - An optional @see StrictObjectConverterOptions<T> containing options for the object converter.
790
+ * @returns A new {@link Conversion.ObjectConverter | ObjectConverter} which applies the specified conversions.
791
+ * {@label WITH_OPTIONS}
792
+ * @public
793
+ */
794
+ export function strictObject<T, TC = unknown>(
795
+ properties: FieldConverters<T, TC>,
796
+ options?: StrictObjectConverterOptions<T>
797
+ ): ObjectConverter<T, TC>;
798
+
799
+ /**
800
+ * Helper function to create a {@link Conversion.ObjectConverter | ObjectConverter} which converts an object
801
+ * without changing shape, a {@link Conversion.FieldConverters | FieldConverters<T, TC>} and an optional
802
+ * {@link Converters.StrictObjectConverterOptions | StrictObjectConverterOptions<T>} to further refine
803
+ * conversion behavior.
804
+ *
805
+ * @remarks
806
+ * Fields that succeed but convert to undefined are omitted from the result object but do not
807
+ * fail the conversion.
808
+ *
809
+ * The conversion fails if any unexpected fields are encountered.
810
+ *
811
+ * @param properties - An object containing defining the shape and converters to be applied.
812
+ * @param optional - An array of `keyof T` containing keys to be considered optional.
813
+ * @returns A new {@link Conversion.ObjectConverter | ObjectConverter} which applies the specified conversions.
814
+ * {@label WITH_KEYS}
815
+ * @deprecated Use {@link Converters.(strictObject:1) | Converters.strictObject(options)} instead.
816
+ * @public
817
+ */
818
+ export function strictObject<T, TC = unknown>(
819
+ properties: FieldConverters<T, TC>,
820
+ optional: (keyof T)[]
821
+ ): ObjectConverter<T, TC>;
822
+
823
+ /**
824
+ * Concrete implementation for {@link Converters.(strictObject:1) | Converters.strictObject(fields, options)}
825
+ * and {@link Converters.strictObject | Converters.strictObject(fields, optional)}.
826
+ * @internal
827
+ */
828
+ export function strictObject<T, TC = unknown>(
829
+ properties: FieldConverters<T, TC>,
830
+ opt?: (keyof T)[] | StrictObjectConverterOptions<T>
831
+ ): ObjectConverter<T, TC> {
832
+ /* c8 ignore next 2 */
833
+ const options: ObjectConverterOptions<T> =
834
+ opt && Array.isArray(opt) ? { strict: true, optionalFields: opt } : { ...(opt ?? {}), strict: true };
835
+ return new ObjectConverter<T, TC>(properties, options);
836
+ }
837
+
838
+ /**
839
+ * A string-keyed `Record<string, Converter>` which maps specific {@link Converter | converters} or
840
+ * {@link Validator | Validators} to the value of a discriminator property.
841
+ * @public
842
+ */
843
+ export type DiscriminatedObjectConverters<T, TD extends string = string, TC = unknown> = Record<
844
+ TD,
845
+ Converter<T, TC> | Validator<T, TC>
846
+ >;
847
+
848
+ /**
849
+ * Helper to create a {@link Converter | Converter} which converts a discriminated object without changing shape.
850
+ * @remarks
851
+ * Takes the name of the discriminator property and a
852
+ * {@link Converters.DiscriminatedObjectConverters | string-keyed Record of converters and validators}. During conversion,
853
+ * the resulting {@link Converter | Converter} invokes the converter from `converters` that corresponds to the value of
854
+ * the discriminator property in the source object.
855
+ *
856
+ * If the source is not an object, the discriminator property is missing, or the discriminator has
857
+ * a value not present in the converters, conversion fails and returns {@link Failure | Failure} with more information.
858
+ * @param discriminatorProp - Name of the property used to discriminate types.
859
+ * @param converters - {@link Converters.DiscriminatedObjectConverters | String-keyed record of converters and validators}
860
+ * to invoke, where each key corresponds to a value of the discriminator property.
861
+ * @returns A {@link Converter | Converter} which converts the corresponding discriminated object.
862
+ * @public
863
+ */
864
+ export function discriminatedObject<T, TD extends string = string, TC = unknown>(
865
+ discriminatorProp: string,
866
+ converters: DiscriminatedObjectConverters<T, TD>
867
+ ): Converter<T, TC> {
868
+ return new BaseConverter((from: unknown) => {
869
+ if (typeof from !== 'object' || Array.isArray(from) || from === null) {
870
+ return fail(`Not a discriminated object: "${JSON.stringify(from)}"`);
871
+ }
872
+ if (!isKeyOf(discriminatorProp, from) || !from[discriminatorProp]) {
873
+ return fail(`Discriminator property ${discriminatorProp} not present in "${JSON.stringify(from)}"`);
874
+ }
875
+
876
+ const discriminatorValue = from[discriminatorProp] as TD;
877
+ const converter = converters[discriminatorValue];
878
+ if (converter === undefined) {
879
+ return fail(`No converter for discriminator ${discriminatorProp}="${discriminatorValue}"`);
880
+ }
881
+ return converter.convert(from);
882
+ });
883
+ }
884
+
885
+ /**
886
+ * Helper to create a {@link Converter | Converter} which converts a source object to a new object with a
887
+ * different shape.
888
+ *
889
+ * @remarks
890
+ * On successful conversion, the resulting {@link Converter | Converter} returns {@link Success | Success} with a new
891
+ * object, which contains the converted values under the key names specified at initialization time.
892
+ * It returns {@link Failure | Failure} with an error message if any fields to be extracted do not exist
893
+ * or cannot be converted.
894
+ *
895
+ * Fields that succeed but convert to undefined are omitted from the result object but do not
896
+ * fail the conversion.
897
+ *
898
+ * @param properties - An object with key names that correspond to the target object and an
899
+ * appropriate {@link Conversion.FieldConverters | FieldConverter} which extracts and converts
900
+ * a single filed from the source object.
901
+ * @returns A {@link Converter | Converter} with the specified conversion behavior.
902
+ * @public
903
+ */
904
+ export function transform<T, TC = unknown>(properties: FieldConverters<T, TC>): Converter<T, TC> {
905
+ return new BaseConverter((from: unknown, __self, context?: TC) => {
906
+ // eslint bug thinks key is used before defined
907
+ // eslint-disable-next-line no-use-before-define
908
+ const converted = {} as { [key in keyof T]: T[key] };
909
+ const errors: string[] = [];
910
+
911
+ for (const key in properties) {
912
+ if (properties[key]) {
913
+ const result = properties[key].convert(from, context);
914
+ if (result.isSuccess() && result.value !== undefined) {
915
+ converted[key] = result.value;
916
+ } else if (result.isFailure()) {
917
+ errors.push(result.message);
918
+ }
919
+ }
920
+ }
921
+
922
+ return errors.length === 0 ? succeed(converted) : fail(errors.join('\n'));
923
+ });
924
+ }
925
+
926
+ /**
927
+ * Per-property converters and configuration for each field in the destination object of
928
+ * a {@link Converters.transformObject} call.
929
+ * @public
930
+ */
931
+ export type FieldTransformers<TSRC, TDEST, TC = unknown> = {
932
+ [key in keyof TDEST]: {
933
+ /**
934
+ * The name of the property in the source object to be converted.
935
+ */
936
+ from: keyof TSRC;
937
+ /**
938
+ * The converter or validator used to convert the property.
939
+ */
940
+ converter: Converter<TDEST[key], TC> | Validator<TDEST[key], TC>;
941
+ /**
942
+ * If `true` then a missing source property is ignored. If `false` or omitted
943
+ * then a missing source property causes an error.
944
+ */
945
+ optional?: boolean;
946
+ };
947
+ };
948
+
949
+ /**
950
+ * Options for a {@link Converters.transformObject} call.
951
+ * @public
952
+ */
953
+ // eslint-disable-next-line @typescript-eslint/naming-convention
954
+ export interface TransformObjectOptions<TSRC> {
955
+ /**
956
+ * If `strict` is `true` then unused properties in the source object cause
957
+ * an error, otherwise they are ignored.
958
+ */
959
+ strict: true;
960
+
961
+ /**
962
+ * An optional list of source properties to be ignored when strict mode
963
+ * is enabled.
964
+ */
965
+ ignore?: (keyof TSRC)[];
966
+
967
+ /**
968
+ * An optional description of this transform to be used for error messages.
969
+ */
970
+ description?: string;
971
+ }
972
+
973
+ /**
974
+ * Helper to create a strongly-typed {@link Converter | Converter} which converts a source object to a
975
+ * new object with a different shape.
976
+ *
977
+ * @remarks
978
+ * On successful conversion, the resulting {@link Converter | Converter} returns {@link Success | Success} with a new
979
+ * object, which contains the converted values under the key names specified at initialization time.
980
+ *
981
+ * It returns {@link Failure | Failure} with an error message if any fields to be extracted do not exist
982
+ * or cannot be converted.
983
+ *
984
+ * @param destinationFields - An object with key names that correspond to the target object and an
985
+ * appropriate {@link Converters.FieldTransformers | FieldTransformers} which specifies the name
986
+ * of the corresponding property in the source object, the converter or validator used for each source
987
+ * property and any other configuration to guide the conversion.
988
+ * @param options - Options which affect the transformation.
989
+ *
990
+ * @returns A {@link Converter | Converter} with the specified conversion behavior.
991
+ * @public
992
+ */
993
+ export function transformObject<TSRC, TDEST, TC = unknown>(
994
+ destinationFields: FieldTransformers<TSRC, TDEST, TC>,
995
+ options?: TransformObjectOptions<TSRC>
996
+ ): Converter<TDEST, TC> {
997
+ return new BaseConverter((from: unknown, __self, context?: TC) => {
998
+ // eslint bug thinks key is used before defined
999
+ // eslint-disable-next-line no-use-before-define
1000
+ const converted = {} as { [key in keyof TDEST]: TDEST[key] };
1001
+ const errors: string[] = [];
1002
+ const used: Set<keyof TSRC> = new Set(options?.ignore);
1003
+
1004
+ if (typeof from === 'object' && !Array.isArray(from) && from !== null) {
1005
+ for (const destinationKey in destinationFields) {
1006
+ if (destinationFields[destinationKey]) {
1007
+ const srcKey = destinationFields[destinationKey].from;
1008
+ const converter = destinationFields[destinationKey].converter;
1009
+
1010
+ if (isKeyOf(srcKey, from)) {
1011
+ const result = converter.convert(from[srcKey], context);
1012
+ if (result.isSuccess() && result.value !== undefined) {
1013
+ converted[destinationKey] = result.value;
1014
+ } else if (result.isFailure()) {
1015
+ errors.push(`${srcKey}->${destinationKey}: ${result.message}`);
1016
+ }
1017
+ used.add(srcKey);
1018
+ } else if (destinationFields[destinationKey].optional !== true) {
1019
+ errors.push(`${String(srcKey)}: required property missing in source object.`);
1020
+ }
1021
+ }
1022
+ }
1023
+
1024
+ if (options?.strict === true) {
1025
+ for (const key in from) {
1026
+ if (isKeyOf(key, from) && !used.has(key as keyof TSRC)) {
1027
+ errors.push(`${key}: unexpected property in source object`);
1028
+ }
1029
+ }
1030
+ }
1031
+ } else {
1032
+ errors.push('source is not an object');
1033
+ }
1034
+
1035
+ return errors.length === 0
1036
+ ? succeed(converted)
1037
+ : fail(options?.description ? `${options.description}:\n ${errors.join('\n ')}` : errors.join('\n'));
1038
+ });
1039
+ }