@openstax/ts-utils 1.21.11 → 1.23.0

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 (252) hide show
  1. package/dist/cjs/assertions/index.d.ts +85 -0
  2. package/dist/cjs/assertions/index.js +157 -0
  3. package/dist/cjs/aws/ssmService.d.ts +5 -0
  4. package/dist/cjs/aws/ssmService.js +9 -0
  5. package/dist/cjs/config/awsParameterConfig.d.ts +10 -0
  6. package/dist/cjs/config/awsParameterConfig.js +26 -0
  7. package/dist/cjs/config/envConfig.d.ts +24 -0
  8. package/dist/cjs/config/envConfig.js +57 -0
  9. package/dist/cjs/config/index.d.ts +48 -0
  10. package/dist/cjs/config/index.js +35 -0
  11. package/dist/cjs/config/lambdaParameterConfig.d.ts +12 -0
  12. package/dist/cjs/config/lambdaParameterConfig.js +45 -0
  13. package/dist/cjs/config/replaceConfig.d.ts +14 -0
  14. package/dist/cjs/config/replaceConfig.js +22 -0
  15. package/dist/cjs/config/resolveConfigValue.d.ts +5 -0
  16. package/dist/cjs/config/resolveConfigValue.js +12 -0
  17. package/dist/cjs/errors/index.d.ts +77 -0
  18. package/dist/cjs/errors/index.js +109 -0
  19. package/dist/cjs/fetch/fetchStatusRetry.d.ts +7 -0
  20. package/dist/cjs/fetch/fetchStatusRetry.js +16 -0
  21. package/dist/cjs/fetch/index.d.ts +64 -0
  22. package/dist/cjs/fetch/index.js +55 -0
  23. package/dist/cjs/guards/index.d.ts +30 -0
  24. package/dist/cjs/guards/index.js +35 -0
  25. package/dist/cjs/index.d.ts +4 -0
  26. package/dist/cjs/index.js +20 -0
  27. package/dist/cjs/middleware/apiErrorHandler.d.ts +24 -0
  28. package/dist/cjs/middleware/apiErrorHandler.js +41 -0
  29. package/dist/cjs/middleware/apiSlowResponseMiddleware.d.ts +23 -0
  30. package/dist/cjs/middleware/apiSlowResponseMiddleware.js +54 -0
  31. package/dist/cjs/middleware/index.d.ts +47 -0
  32. package/dist/cjs/middleware/index.js +48 -0
  33. package/dist/cjs/middleware/lambdaCorsResponseMiddleware.d.ts +20 -0
  34. package/dist/cjs/middleware/lambdaCorsResponseMiddleware.js +42 -0
  35. package/dist/cjs/middleware/throwNotFoundMiddleware.d.ts +4 -0
  36. package/dist/cjs/middleware/throwNotFoundMiddleware.js +14 -0
  37. package/dist/cjs/misc/hashValue.d.ts +10 -0
  38. package/dist/cjs/misc/hashValue.js +17 -0
  39. package/dist/cjs/misc/helpers.d.ts +124 -0
  40. package/dist/cjs/misc/helpers.js +214 -0
  41. package/dist/cjs/misc/merge.d.ts +21 -0
  42. package/dist/cjs/misc/merge.js +45 -0
  43. package/dist/cjs/misc/partitionSequence.d.ts +35 -0
  44. package/dist/cjs/misc/partitionSequence.js +55 -0
  45. package/dist/cjs/pagination/index.d.ts +91 -0
  46. package/dist/cjs/pagination/index.js +83 -0
  47. package/dist/cjs/routing/helpers.d.ts +57 -0
  48. package/dist/cjs/routing/helpers.js +90 -0
  49. package/dist/cjs/routing/index.d.ts +272 -0
  50. package/dist/cjs/routing/index.js +270 -0
  51. package/dist/cjs/routing/validators/zod.d.ts +4 -0
  52. package/dist/cjs/routing/validators/zod.js +12 -0
  53. package/dist/cjs/services/accountsGateway/index.d.ts +85 -0
  54. package/dist/cjs/services/accountsGateway/index.js +118 -0
  55. package/dist/cjs/services/apiGateway/index.d.ts +63 -0
  56. package/dist/cjs/services/apiGateway/index.js +108 -0
  57. package/dist/cjs/services/authProvider/browser.d.ts +74 -0
  58. package/dist/cjs/services/authProvider/browser.js +154 -0
  59. package/dist/cjs/services/authProvider/decryption.d.ts +19 -0
  60. package/dist/cjs/services/authProvider/decryption.js +61 -0
  61. package/dist/cjs/services/authProvider/index.d.ts +61 -0
  62. package/dist/cjs/services/authProvider/index.js +26 -0
  63. package/dist/cjs/services/authProvider/subrequest.d.ts +16 -0
  64. package/dist/cjs/services/authProvider/subrequest.js +50 -0
  65. package/dist/cjs/services/authProvider/utils/decryptAndVerify.d.ts +29 -0
  66. package/dist/cjs/services/authProvider/utils/decryptAndVerify.js +91 -0
  67. package/dist/cjs/services/authProvider/utils/embeddedAuthProvider.d.ts +26 -0
  68. package/dist/cjs/services/authProvider/utils/embeddedAuthProvider.js +47 -0
  69. package/dist/cjs/services/authProvider/utils/userRoleValidator.d.ts +13 -0
  70. package/dist/cjs/services/authProvider/utils/userRoleValidator.js +37 -0
  71. package/dist/cjs/services/documentStore/dynamoEncoding.d.ts +10 -0
  72. package/dist/cjs/services/documentStore/dynamoEncoding.js +52 -0
  73. package/dist/cjs/services/documentStore/index.d.ts +14 -0
  74. package/dist/cjs/services/documentStore/index.js +2 -0
  75. package/dist/cjs/services/documentStore/unversioned/dynamodb.d.ts +16 -0
  76. package/dist/cjs/services/documentStore/unversioned/dynamodb.js +122 -0
  77. package/dist/cjs/services/documentStore/unversioned/file-system.d.ts +18 -0
  78. package/dist/cjs/services/documentStore/unversioned/file-system.js +121 -0
  79. package/dist/cjs/services/documentStore/unversioned/index.d.ts +2 -0
  80. package/dist/cjs/services/documentStore/unversioned/index.js +2 -0
  81. package/dist/cjs/services/documentStore/versioned/dynamodb.d.ts +22 -0
  82. package/dist/cjs/services/documentStore/versioned/dynamodb.js +135 -0
  83. package/dist/cjs/services/documentStore/versioned/file-system.d.ts +24 -0
  84. package/dist/cjs/services/documentStore/versioned/file-system.js +62 -0
  85. package/dist/cjs/services/documentStore/versioned/index.d.ts +17 -0
  86. package/dist/cjs/services/documentStore/versioned/index.js +2 -0
  87. package/dist/cjs/services/exercisesGateway/index.d.ts +71 -0
  88. package/dist/cjs/services/exercisesGateway/index.js +97 -0
  89. package/dist/cjs/services/fileServer/index.d.ts +17 -0
  90. package/dist/cjs/services/fileServer/index.js +19 -0
  91. package/dist/cjs/services/fileServer/localFileServer.d.ts +13 -0
  92. package/dist/cjs/services/fileServer/localFileServer.js +23 -0
  93. package/dist/cjs/services/fileServer/s3FileServer.d.ts +16 -0
  94. package/dist/cjs/services/fileServer/s3FileServer.js +25 -0
  95. package/dist/cjs/services/launchParams/index.d.ts +2 -0
  96. package/dist/cjs/services/launchParams/index.js +7 -0
  97. package/dist/cjs/services/launchParams/signer.d.ts +27 -0
  98. package/dist/cjs/services/launchParams/signer.js +58 -0
  99. package/dist/cjs/services/launchParams/verifier.d.ts +22 -0
  100. package/dist/cjs/services/launchParams/verifier.js +94 -0
  101. package/dist/cjs/services/logger/console.d.ts +4 -0
  102. package/dist/cjs/services/logger/console.js +12 -0
  103. package/dist/cjs/services/logger/index.d.ts +39 -0
  104. package/dist/cjs/services/logger/index.js +31 -0
  105. package/dist/cjs/services/lrsGateway/addStatementDefaultFields.d.ts +5 -0
  106. package/dist/cjs/services/lrsGateway/addStatementDefaultFields.js +21 -0
  107. package/dist/cjs/services/lrsGateway/attempt-utils.d.ts +70 -0
  108. package/dist/cjs/services/lrsGateway/attempt-utils.js +258 -0
  109. package/dist/cjs/services/lrsGateway/file-system.d.ts +17 -0
  110. package/dist/cjs/services/lrsGateway/file-system.js +140 -0
  111. package/dist/cjs/services/lrsGateway/index.d.ts +125 -0
  112. package/dist/cjs/services/lrsGateway/index.js +138 -0
  113. package/dist/cjs/services/lrsGateway/xapiUtils.d.ts +61 -0
  114. package/dist/cjs/services/lrsGateway/xapiUtils.js +94 -0
  115. package/dist/cjs/services/postgresConnection/index.d.ts +35 -0
  116. package/dist/cjs/services/postgresConnection/index.js +63 -0
  117. package/dist/cjs/services/searchProvider/index.d.ts +31 -0
  118. package/dist/cjs/services/searchProvider/index.js +2 -0
  119. package/dist/cjs/services/searchProvider/memorySearchTheBadWay.d.ts +14 -0
  120. package/dist/cjs/services/searchProvider/memorySearchTheBadWay.js +89 -0
  121. package/dist/cjs/tsconfig.without-specs.cjs.tsbuildinfo +1 -0
  122. package/dist/cjs/types.d.ts +31 -0
  123. package/dist/cjs/types.js +2 -0
  124. package/dist/esm/assertions/index.d.ts +85 -0
  125. package/dist/esm/assertions/index.js +146 -0
  126. package/dist/esm/aws/ssmService.d.ts +5 -0
  127. package/dist/esm/aws/ssmService.js +6 -0
  128. package/dist/esm/config/awsParameterConfig.d.ts +10 -0
  129. package/dist/esm/config/awsParameterConfig.js +22 -0
  130. package/dist/esm/config/envConfig.d.ts +24 -0
  131. package/dist/esm/config/envConfig.js +53 -0
  132. package/dist/esm/config/index.d.ts +48 -0
  133. package/dist/esm/config/index.js +17 -0
  134. package/dist/esm/config/lambdaParameterConfig.d.ts +12 -0
  135. package/dist/esm/config/lambdaParameterConfig.js +38 -0
  136. package/dist/esm/config/replaceConfig.d.ts +14 -0
  137. package/dist/esm/config/replaceConfig.js +18 -0
  138. package/dist/esm/config/resolveConfigValue.d.ts +5 -0
  139. package/dist/esm/config/resolveConfigValue.js +8 -0
  140. package/dist/esm/errors/index.d.ts +77 -0
  141. package/dist/esm/errors/index.js +99 -0
  142. package/dist/esm/fetch/fetchStatusRetry.d.ts +7 -0
  143. package/dist/esm/fetch/fetchStatusRetry.js +12 -0
  144. package/dist/esm/fetch/index.d.ts +64 -0
  145. package/dist/esm/fetch/index.js +46 -0
  146. package/dist/esm/guards/index.d.ts +30 -0
  147. package/dist/esm/guards/index.js +28 -0
  148. package/dist/esm/index.d.ts +4 -0
  149. package/dist/esm/index.js +4 -0
  150. package/dist/esm/middleware/apiErrorHandler.d.ts +24 -0
  151. package/dist/esm/middleware/apiErrorHandler.js +37 -0
  152. package/dist/esm/middleware/apiSlowResponseMiddleware.d.ts +23 -0
  153. package/dist/esm/middleware/apiSlowResponseMiddleware.js +50 -0
  154. package/dist/esm/middleware/index.d.ts +47 -0
  155. package/dist/esm/middleware/index.js +44 -0
  156. package/dist/esm/middleware/lambdaCorsResponseMiddleware.d.ts +20 -0
  157. package/dist/esm/middleware/lambdaCorsResponseMiddleware.js +38 -0
  158. package/dist/esm/middleware/throwNotFoundMiddleware.d.ts +4 -0
  159. package/dist/esm/middleware/throwNotFoundMiddleware.js +10 -0
  160. package/dist/esm/misc/hashValue.d.ts +10 -0
  161. package/dist/esm/misc/hashValue.js +13 -0
  162. package/dist/esm/misc/helpers.d.ts +124 -0
  163. package/dist/esm/misc/helpers.js +199 -0
  164. package/dist/esm/misc/merge.d.ts +21 -0
  165. package/dist/esm/misc/merge.js +40 -0
  166. package/dist/esm/misc/partitionSequence.d.ts +35 -0
  167. package/dist/esm/misc/partitionSequence.js +48 -0
  168. package/dist/esm/pagination/index.d.ts +91 -0
  169. package/dist/esm/pagination/index.js +77 -0
  170. package/dist/esm/routing/helpers.d.ts +57 -0
  171. package/dist/esm/routing/helpers.js +83 -0
  172. package/dist/esm/routing/index.d.ts +272 -0
  173. package/dist/esm/routing/index.js +232 -0
  174. package/dist/esm/routing/validators/zod.d.ts +4 -0
  175. package/dist/esm/routing/validators/zod.js +8 -0
  176. package/dist/esm/services/accountsGateway/index.d.ts +85 -0
  177. package/dist/esm/services/accountsGateway/index.js +111 -0
  178. package/dist/esm/services/apiGateway/index.d.ts +63 -0
  179. package/dist/esm/services/apiGateway/index.js +77 -0
  180. package/dist/esm/services/authProvider/browser.d.ts +74 -0
  181. package/dist/esm/services/authProvider/browser.js +150 -0
  182. package/dist/esm/services/authProvider/decryption.d.ts +19 -0
  183. package/dist/esm/services/authProvider/decryption.js +57 -0
  184. package/dist/esm/services/authProvider/index.d.ts +61 -0
  185. package/dist/esm/services/authProvider/index.js +18 -0
  186. package/dist/esm/services/authProvider/subrequest.d.ts +16 -0
  187. package/dist/esm/services/authProvider/subrequest.js +43 -0
  188. package/dist/esm/services/authProvider/utils/decryptAndVerify.d.ts +29 -0
  189. package/dist/esm/services/authProvider/utils/decryptAndVerify.js +85 -0
  190. package/dist/esm/services/authProvider/utils/embeddedAuthProvider.d.ts +26 -0
  191. package/dist/esm/services/authProvider/utils/embeddedAuthProvider.js +40 -0
  192. package/dist/esm/services/authProvider/utils/userRoleValidator.d.ts +13 -0
  193. package/dist/esm/services/authProvider/utils/userRoleValidator.js +33 -0
  194. package/dist/esm/services/documentStore/dynamoEncoding.d.ts +10 -0
  195. package/dist/esm/services/documentStore/dynamoEncoding.js +45 -0
  196. package/dist/esm/services/documentStore/index.d.ts +14 -0
  197. package/dist/esm/services/documentStore/index.js +1 -0
  198. package/dist/esm/services/documentStore/unversioned/dynamodb.d.ts +16 -0
  199. package/dist/esm/services/documentStore/unversioned/dynamodb.js +118 -0
  200. package/dist/esm/services/documentStore/unversioned/file-system.d.ts +18 -0
  201. package/dist/esm/services/documentStore/unversioned/file-system.js +91 -0
  202. package/dist/esm/services/documentStore/unversioned/index.d.ts +2 -0
  203. package/dist/esm/services/documentStore/unversioned/index.js +1 -0
  204. package/dist/esm/services/documentStore/versioned/dynamodb.d.ts +22 -0
  205. package/dist/esm/services/documentStore/versioned/dynamodb.js +131 -0
  206. package/dist/esm/services/documentStore/versioned/file-system.d.ts +24 -0
  207. package/dist/esm/services/documentStore/versioned/file-system.js +58 -0
  208. package/dist/esm/services/documentStore/versioned/index.d.ts +17 -0
  209. package/dist/esm/services/documentStore/versioned/index.js +1 -0
  210. package/dist/esm/services/exercisesGateway/index.d.ts +71 -0
  211. package/dist/esm/services/exercisesGateway/index.js +70 -0
  212. package/dist/esm/services/fileServer/index.d.ts +17 -0
  213. package/dist/esm/services/fileServer/index.js +13 -0
  214. package/dist/esm/services/fileServer/localFileServer.d.ts +13 -0
  215. package/dist/esm/services/fileServer/localFileServer.js +16 -0
  216. package/dist/esm/services/fileServer/s3FileServer.d.ts +16 -0
  217. package/dist/esm/services/fileServer/s3FileServer.js +21 -0
  218. package/dist/esm/services/launchParams/index.d.ts +2 -0
  219. package/dist/esm/services/launchParams/index.js +2 -0
  220. package/dist/esm/services/launchParams/signer.d.ts +27 -0
  221. package/dist/esm/services/launchParams/signer.js +51 -0
  222. package/dist/esm/services/launchParams/verifier.d.ts +22 -0
  223. package/dist/esm/services/launchParams/verifier.js +67 -0
  224. package/dist/esm/services/logger/console.d.ts +4 -0
  225. package/dist/esm/services/logger/console.js +8 -0
  226. package/dist/esm/services/logger/index.d.ts +39 -0
  227. package/dist/esm/services/logger/index.js +27 -0
  228. package/dist/esm/services/lrsGateway/addStatementDefaultFields.d.ts +5 -0
  229. package/dist/esm/services/lrsGateway/addStatementDefaultFields.js +14 -0
  230. package/dist/esm/services/lrsGateway/attempt-utils.d.ts +70 -0
  231. package/dist/esm/services/lrsGateway/attempt-utils.js +236 -0
  232. package/dist/esm/services/lrsGateway/file-system.d.ts +17 -0
  233. package/dist/esm/services/lrsGateway/file-system.js +110 -0
  234. package/dist/esm/services/lrsGateway/index.d.ts +125 -0
  235. package/dist/esm/services/lrsGateway/index.js +111 -0
  236. package/dist/esm/services/lrsGateway/xapiUtils.d.ts +61 -0
  237. package/dist/esm/services/lrsGateway/xapiUtils.js +84 -0
  238. package/dist/esm/services/postgresConnection/index.d.ts +35 -0
  239. package/dist/esm/services/postgresConnection/index.js +56 -0
  240. package/dist/esm/services/searchProvider/index.d.ts +31 -0
  241. package/dist/esm/services/searchProvider/index.js +1 -0
  242. package/dist/esm/services/searchProvider/memorySearchTheBadWay.d.ts +14 -0
  243. package/dist/esm/services/searchProvider/memorySearchTheBadWay.js +85 -0
  244. package/dist/esm/tsconfig.without-specs.esm.tsbuildinfo +1 -0
  245. package/dist/esm/types.d.ts +31 -0
  246. package/dist/esm/types.js +1 -0
  247. package/package.json +16 -16
  248. package/script/bin/deploy.bash +8 -0
  249. package/script/bin/get-env-param.bash +3 -3
  250. package/script/bin/init-params-script.bash +10 -1
  251. package/script/bin/upload-params.bash +3 -3
  252. package/dist/tsconfig.tsbuildinfo +0 -1
@@ -0,0 +1,124 @@
1
+ import type { Logger } from '../services/logger';
2
+ /**
3
+ * Returns a function that gets the value of the given key from an object
4
+ *
5
+ * @param key
6
+ * @example
7
+ * const getAuthor = getKeyValue('author');
8
+ * const author = getAuthor(book);
9
+ */
10
+ export declare const getKeyValue: <K extends string>(key: K) => <O extends { [key in K]?: any; }>(obj: O) => O[K];
11
+ /**
12
+ * Returns a function that gets the value of the given key from an object, or the given default
13
+ * value if the key is not present.
14
+ *
15
+ * @param key
16
+ * @param defaultValue a default value matching the type of the value at the given key
17
+ * @example
18
+ * const getAuthorOrNope = getKeyValueOr('author', 'nope');
19
+ * const authorOrNope = getAuthorOrNope(book);
20
+ */
21
+ export declare const getKeyValueOr: <K extends string, V, Od extends { [key in K]?: any; } = { [key_1 in K]?: any; }>(key: K, defaultValue: V) => <O extends Od extends undefined ? { [key_2 in K]?: any; } : Od>(obj: O) => V | NonNullable<O[K]>;
22
+ /**
23
+ * Returns a function that sets the value of the given key on an object.
24
+ *
25
+ * @param key
26
+ * @example
27
+ * const putAuthor = putKeyValue('author');
28
+ * const newBook = putAuthor(book, 'tom');
29
+ */
30
+ export declare const putKeyValue: <K extends string>(key: K) => <O extends { [key in K]?: any; }>(obj: O, value: O[K]) => O;
31
+ /**
32
+ * Coerces a value into an array. If the value is already an array, it is returned as-is.
33
+ * If the value is undefined, an empty array is returned.
34
+ *
35
+ * @param thing the value
36
+ * @returns an array
37
+ */
38
+ export declare const coerceArray: <T>(thing: T | T[] | undefined) => T[];
39
+ declare type FlowFn<A, R> = (...args: [A]) => R;
40
+ declare type AnyFlowFn = FlowFn<any, any>;
41
+ declare type FlowFnResult<F, A> = F extends FlowFn<A, infer R> ? R : never;
42
+ declare type FlowResult<C, A> = C extends [infer F1, ...infer Cr] ? F1 extends AnyFlowFn ? Cr extends never[] ? FlowFnResult<F1, A> : FlowResult<Cr, FlowFnResult<F1, A>> : never : never;
43
+ declare type FlowChainArg<C> = C extends [infer F1, ...infer _] ? F1 extends FlowFn<infer A, any> ? A : never : never;
44
+ /**
45
+ * this is like lodash/flow but it uses a recursive type instead of hard-coding parameters
46
+ */
47
+ export declare const flow: <C extends AnyFlowFn[]>(...chain: C) => (param: FlowChainArg<C>) => FlowResult<C, FlowChainArg<C>>;
48
+ export declare type RetryOptions = {
49
+ logger?: Logger;
50
+ wait?: number;
51
+ splay?: number;
52
+ retries?: number;
53
+ n?: number;
54
+ };
55
+ /**
56
+ * Retries a function with a delay between retries.
57
+ * @param fn The function to retry
58
+ * @param [options] retry options
59
+ * @param [options.wait=100] base wait of first retry (number), further retries are: t=n*wait,
60
+ * default: 100
61
+ * @param [options.splay=0.5] percentage to modify t by. 0.5 is 50%, which would make
62
+ * t=n*wait+rand(wait*splay*-1, wait*splay), default: 0.5
63
+ * @param [options.retries=2] number of times to retry. (2 retries means it'll try a max of 3 times),
64
+ * default: 2
65
+ * @param [options.n=0] the starting retry index. probably don't set this. unless you really want a very steep
66
+ * initial wait cliff with incremental increases, then maybe you'd set this. default: 0
67
+ * @returns A promise that resolves with the result of the function, or rejects with the last error.
68
+ */
69
+ export declare const retryWithDelay: <R>(fn: (abort?: ((e: Error) => never) | undefined) => Promise<R>, options?: RetryOptions | undefined) => Promise<R>;
70
+ /**
71
+ * a shameful helper to avoid needing to test code coverage of branches
72
+ */
73
+ export declare const fnIf: <T1, T2>(condition: boolean, trueValue: T1, falseValue: T2) => T1 | T2;
74
+ /**
75
+ * maps the array and returns the first result that matches the predicate
76
+ * avoids processing extra elements that would happen with .map().find() or .reduce
77
+ *
78
+ * eg the third element of the array is never processed:
79
+ * const result = mapFind([1,2,3], x => 'hello'.charAt(x), x => x === 'l');
80
+ */
81
+ export declare const mapFind: <I, R>(array: I[], mapper: (item: I) => R, predicate?: (result: R) => boolean) => R | undefined;
82
+ /**
83
+ * returns a function that will only ever call the given function once, returning the first result for every subsequent call
84
+ *
85
+ * does not cache rejected promises, to avoid cache poisoning on failed async requests
86
+ *
87
+ * eg:
88
+ * const heavyFunction = () => 'hello';
89
+ * const butOnlyOnce = once(() => 'hello');
90
+ *
91
+ * heavyFunction() // returns `hello`;
92
+ * butOnlyOnce() // returns `hello`;
93
+ */
94
+ export declare const once: <F extends (...args: any[]) => any>(fn: F) => F;
95
+ /**
96
+ * memoizes a function with any number of arguments
97
+ *
98
+ * does not cache rejected promises, to avoid cache poisoning on failed async requests
99
+ */
100
+ export declare const memoize: <F extends (...args: any[]) => any>(fn: F) => F;
101
+ /**
102
+ * rounds number to given number of places
103
+ *
104
+ * eg:
105
+ * roundToPrecision(1234.123, 2); // returns 1200
106
+ * roundToPrecision(1234.123, -2); // returns 1234.12
107
+ * roundToPrecision(1234.125, -2); // returns 1234.13
108
+ */
109
+ export declare const roundToPrecision: (num: number, places: number) => number;
110
+ /**
111
+ * a silly utility to help typescript realize an array is a tuple
112
+ *
113
+ * eg:
114
+ * const a = [5, 'string'] // type is `Array<string | number>`
115
+ * const t = tuple(5, 'string') type is `[5, 'string']`
116
+ *
117
+ * both have the same javascript value, but one is forced to be a tuple, which
118
+ * is nice if its structure is important. examples are like the React.useState
119
+ * pattern where there are two return values in a tuple, or if you're feeding
120
+ * Object.fromEntries
121
+ *
122
+ */
123
+ export declare const tuple: <A extends any[]>(...args: A) => A;
124
+ export {};
@@ -0,0 +1,199 @@
1
+ /*
2
+ * there was a reason i made these instead of using lodash/fp but i forget what it was. i think maybe
3
+ * these do more validation that the second function gets a compatible object.
4
+ */
5
+ /**
6
+ * Returns a function that gets the value of the given key from an object
7
+ *
8
+ * @param key
9
+ * @example
10
+ * const getAuthor = getKeyValue('author');
11
+ * const author = getAuthor(book);
12
+ */
13
+ export const getKeyValue = (key) => (obj) => obj[key];
14
+ /**
15
+ * Returns a function that gets the value of the given key from an object, or the given default
16
+ * value if the key is not present.
17
+ *
18
+ * @param key
19
+ * @param defaultValue a default value matching the type of the value at the given key
20
+ * @example
21
+ * const getAuthorOrNope = getKeyValueOr('author', 'nope');
22
+ * const authorOrNope = getAuthorOrNope(book);
23
+ */
24
+ export const getKeyValueOr = (key, defaultValue) => (obj) => obj[key] || defaultValue;
25
+ /**
26
+ * Returns a function that sets the value of the given key on an object.
27
+ *
28
+ * @param key
29
+ * @example
30
+ * const putAuthor = putKeyValue('author');
31
+ * const newBook = putAuthor(book, 'tom');
32
+ */
33
+ export const putKeyValue = (key) => (obj, value) => ({ ...obj, [key]: value });
34
+ /**
35
+ * Coerces a value into an array. If the value is already an array, it is returned as-is.
36
+ * If the value is undefined, an empty array is returned.
37
+ *
38
+ * @param thing the value
39
+ * @returns an array
40
+ */
41
+ export const coerceArray = (thing) => thing instanceof Array ? thing : thing !== undefined ? [thing] : [];
42
+ /**
43
+ * this is like lodash/flow but it uses a recursive type instead of hard-coding parameters
44
+ */
45
+ export const flow = (...chain) => (param) => {
46
+ let result = param;
47
+ for (const fn of chain) {
48
+ result = fn(result);
49
+ }
50
+ return result;
51
+ };
52
+ /**
53
+ * Retries a function with a delay between retries.
54
+ * @param fn The function to retry
55
+ * @param [options] retry options
56
+ * @param [options.wait=100] base wait of first retry (number), further retries are: t=n*wait,
57
+ * default: 100
58
+ * @param [options.splay=0.5] percentage to modify t by. 0.5 is 50%, which would make
59
+ * t=n*wait+rand(wait*splay*-1, wait*splay), default: 0.5
60
+ * @param [options.retries=2] number of times to retry. (2 retries means it'll try a max of 3 times),
61
+ * default: 2
62
+ * @param [options.n=0] the starting retry index. probably don't set this. unless you really want a very steep
63
+ * initial wait cliff with incremental increases, then maybe you'd set this. default: 0
64
+ * @returns A promise that resolves with the result of the function, or rejects with the last error.
65
+ */
66
+ export const retryWithDelay = (fn, options) => {
67
+ const { wait, splay, retries, n } = { wait: 100, splay: 0.5, retries: 2, n: 0, ...options };
68
+ if (n >= retries) {
69
+ return fn();
70
+ }
71
+ let aborted = false;
72
+ const timeout = (n + 1) * wait + (Math.random() * 2 - 1) * splay * wait;
73
+ const retry = (e) => new Promise((resolve, reject) => {
74
+ var _a;
75
+ if (aborted) {
76
+ reject(e);
77
+ }
78
+ else {
79
+ (_a = options === null || options === void 0 ? void 0 : options.logger) === null || _a === void 0 ? void 0 : _a.log(`failed try ${n + 1} of ${retries}. ${e.message}`);
80
+ setTimeout(() => retryWithDelay(fn, { ...options, n: n + 1 }).then(resolve, reject), timeout);
81
+ }
82
+ });
83
+ const abort = (e) => {
84
+ aborted = true;
85
+ throw e;
86
+ };
87
+ return fn(abort).catch(retry);
88
+ };
89
+ /**
90
+ * a shameful helper to avoid needing to test code coverage of branches
91
+ */
92
+ export const fnIf = (condition, trueValue, falseValue) => condition ? trueValue : falseValue;
93
+ /**
94
+ * maps the array and returns the first result that matches the predicate
95
+ * avoids processing extra elements that would happen with .map().find() or .reduce
96
+ *
97
+ * eg the third element of the array is never processed:
98
+ * const result = mapFind([1,2,3], x => 'hello'.charAt(x), x => x === 'l');
99
+ */
100
+ export const mapFind = (array, mapper, predicate = (r) => !!r) => {
101
+ for (const item of array) {
102
+ const mapped = mapper(item);
103
+ if (predicate(mapped)) {
104
+ return mapped;
105
+ }
106
+ }
107
+ };
108
+ /**
109
+ * returns a function that will only ever call the given function once, returning the first result for every subsequent call
110
+ *
111
+ * does not cache rejected promises, to avoid cache poisoning on failed async requests
112
+ *
113
+ * eg:
114
+ * const heavyFunction = () => 'hello';
115
+ * const butOnlyOnce = once(() => 'hello');
116
+ *
117
+ * heavyFunction() // returns `hello`;
118
+ * butOnlyOnce() // returns `hello`;
119
+ */
120
+ export const once = (fn) => {
121
+ const initialValue = {};
122
+ let result = initialValue;
123
+ return ((...args) => {
124
+ if (result !== initialValue) {
125
+ return result;
126
+ }
127
+ result = fn(...args);
128
+ if (typeof result === 'object' && result instanceof Promise) {
129
+ // Clear the result when possible but do not return a Promise that resolves to the initialValue
130
+ result.catch(() => result = initialValue);
131
+ }
132
+ // If this is a rejected Promise, it should be returned before catch() actually overwrites it
133
+ return result;
134
+ });
135
+ };
136
+ /**
137
+ * memoizes a function with any number of arguments
138
+ *
139
+ * does not cache rejected promises, to avoid cache poisoning on failed async requests
140
+ */
141
+ export const memoize = (fn) => {
142
+ const cache = {};
143
+ const resolveCache = (cacheLayer, [first, ...rest]) => {
144
+ if (!first) {
145
+ return cacheLayer;
146
+ }
147
+ const layers = first instanceof Object
148
+ ? (cacheLayer.weakLayers = (cacheLayer.weakLayers || (typeof WeakMap === 'undefined' ? undefined : new WeakMap())))
149
+ : (cacheLayer.strongLayers = (cacheLayer.strongLayers || new Map()));
150
+ // argument is an object and WeakMap is not supported
151
+ if (!layers) {
152
+ return {};
153
+ }
154
+ const layer = layers.get(first) || {};
155
+ if (!layers.has(first)) {
156
+ layers.set(first, layer);
157
+ }
158
+ return resolveCache(layer, rest);
159
+ };
160
+ return ((...args) => {
161
+ const thisCache = resolveCache(cache, args);
162
+ if ('result' in thisCache) {
163
+ return thisCache.result;
164
+ }
165
+ thisCache.result = fn(...args);
166
+ if (typeof thisCache.result === 'object' && thisCache.result instanceof Promise) {
167
+ // Clear the result when possible but do not return a Promise that resolves to the initialValue
168
+ thisCache.result.catch(() => delete thisCache.result);
169
+ }
170
+ return thisCache.result;
171
+ });
172
+ };
173
+ /**
174
+ * rounds number to given number of places
175
+ *
176
+ * eg:
177
+ * roundToPrecision(1234.123, 2); // returns 1200
178
+ * roundToPrecision(1234.123, -2); // returns 1234.12
179
+ * roundToPrecision(1234.125, -2); // returns 1234.13
180
+ */
181
+ export const roundToPrecision = (num, places) => {
182
+ const multiplier = Math.pow(10, -1 * places);
183
+ // https://stackoverflow.com/a/11832950/14809536
184
+ return Math.round((num + Number.EPSILON) * multiplier) / multiplier;
185
+ };
186
+ /**
187
+ * a silly utility to help typescript realize an array is a tuple
188
+ *
189
+ * eg:
190
+ * const a = [5, 'string'] // type is `Array<string | number>`
191
+ * const t = tuple(5, 'string') type is `[5, 'string']`
192
+ *
193
+ * both have the same javascript value, but one is forced to be a tuple, which
194
+ * is nice if its structure is important. examples are like the React.useState
195
+ * pattern where there are two return values in a tuple, or if you're feeding
196
+ * Object.fromEntries
197
+ *
198
+ */
199
+ export const tuple = (...args) => args;
@@ -0,0 +1,21 @@
1
+ import type { UnionToIntersection } from '../types';
2
+ /**
3
+ * Takes two objects and returns an array of the keys that are common to both, with a type
4
+ * limited to those keys.
5
+ *
6
+ * @param thing1 some object
7
+ * @param thing2 another object
8
+ * @returns an array of keys, type-limited to those keys
9
+ */
10
+ export declare const getCommonProperties: <T1 extends {}, T2 extends {}>(thing1: T1, thing2: T2) => (keyof T1 & keyof T2)[];
11
+ /**
12
+ * recursive merge properties of inputs. values are merged if they are
13
+ * plain objects or arrays, otherwise if the same property exists in both
14
+ * objects the value from the second argument will win.
15
+ *
16
+ * unlike lodash merge, this will not change object references for values that
17
+ * exist only in one parameter.
18
+ *
19
+ * @example merge({thing: 'one'}, {thing: 'two', otherKey: 'one'}, {coolKey: 'coolValue'});
20
+ */
21
+ export declare const merge: <T extends {}[]>(...[thing1, ...tail]: T) => UnionToIntersection<T[number]>;
@@ -0,0 +1,40 @@
1
+ import { isPlainObject } from '../guards';
2
+ /**
3
+ * Takes two objects and returns an array of the keys that are common to both, with a type
4
+ * limited to those keys.
5
+ *
6
+ * @param thing1 some object
7
+ * @param thing2 another object
8
+ * @returns an array of keys, type-limited to those keys
9
+ */
10
+ export const getCommonProperties = (thing1, thing2) => Object.keys(thing1).filter((key) => Object.keys(thing2).includes(key));
11
+ /**
12
+ * recursive merge properties of inputs. values are merged if they are
13
+ * plain objects or arrays, otherwise if the same property exists in both
14
+ * objects the value from the second argument will win.
15
+ *
16
+ * unlike lodash merge, this will not change object references for values that
17
+ * exist only in one parameter.
18
+ *
19
+ * @example merge({thing: 'one'}, {thing: 'two', otherKey: 'one'}, {coolKey: 'coolValue'});
20
+ */
21
+ export const merge = (...[thing1, ...tail]) => {
22
+ const mergedTail = tail.length > 0
23
+ ? merge(...tail)
24
+ : null;
25
+ if (!mergedTail) {
26
+ return thing1;
27
+ }
28
+ return {
29
+ ...thing1,
30
+ ...mergedTail,
31
+ ...getCommonProperties(thing1, mergedTail).reduce((result, property) => ({
32
+ ...result,
33
+ ...(isPlainObject(thing1[property]) && isPlainObject(mergedTail[property])
34
+ ? { [property]: merge(thing1[property], mergedTail[property]) }
35
+ : (Array.isArray(thing1[property]) && Array.isArray(mergedTail[property]))
36
+ ? { [property]: [...thing1[property], ...mergedTail[property]] }
37
+ : {}),
38
+ }), {}),
39
+ };
40
+ };
@@ -0,0 +1,35 @@
1
+ /**
2
+ * partitions a sequence based on a partition function returning {value: any; matches?: boolean}
3
+ * - if the function returns `matches` explicitly then adjacent matching elements will
4
+ * be grouped and the predicate value in the result will be from the last item in the group
5
+ * - if the function returns only a value then matching will be evaluated based on the deep
6
+ * equality of the value with its neighbors
7
+ *
8
+ * this is different from lodash/partition and lodash/groupBy because:
9
+ * - it preserves the order of the items, items will only be grouped if they are already adjacent
10
+ * - there can be any number of groups
11
+ * - it tells you the partition value
12
+ * - the partition value can be reduced, if you care (so you can like, partition on sequential values)
13
+ *
14
+ * simple predicate:
15
+ * returns: [[0, [1,2]], [1, [3,4,5]]]
16
+ * partitionSequence((n: number) => ({value: Math.floor(n / 3)}), [1,2,3,4,5])
17
+ *
18
+ * mutating partition:
19
+ * returns: [
20
+ * [{min: 1,max: 3}, [1,2,3]],
21
+ * [{min: 5,max: 6}, [5,6]],
22
+ * [{min: 8,max: 8}, [8]],
23
+ * ]
24
+ * partitionSequence(
25
+ * (n: number, p?: {min: number; max: number}) =>
26
+ * p && p.max + 1 === n
27
+ * ? {value: {...p, max: n}, matches: true}
28
+ * : {value: {min: n, max: n}, matches: false}
29
+ * , [1,2,3,5,6,8]
30
+ * )
31
+ */
32
+ export declare const partitionSequence: <T, P>(getPartition: (thing: T, previous?: P | undefined) => {
33
+ matches?: boolean | undefined;
34
+ value: P;
35
+ }, sequence: T[]) => [P, T[]][];
@@ -0,0 +1,48 @@
1
+ import deepEqual from 'deep-equal';
2
+ /**
3
+ * partitions a sequence based on a partition function returning {value: any; matches?: boolean}
4
+ * - if the function returns `matches` explicitly then adjacent matching elements will
5
+ * be grouped and the predicate value in the result will be from the last item in the group
6
+ * - if the function returns only a value then matching will be evaluated based on the deep
7
+ * equality of the value with its neighbors
8
+ *
9
+ * this is different from lodash/partition and lodash/groupBy because:
10
+ * - it preserves the order of the items, items will only be grouped if they are already adjacent
11
+ * - there can be any number of groups
12
+ * - it tells you the partition value
13
+ * - the partition value can be reduced, if you care (so you can like, partition on sequential values)
14
+ *
15
+ * simple predicate:
16
+ * returns: [[0, [1,2]], [1, [3,4,5]]]
17
+ * partitionSequence((n: number) => ({value: Math.floor(n / 3)}), [1,2,3,4,5])
18
+ *
19
+ * mutating partition:
20
+ * returns: [
21
+ * [{min: 1,max: 3}, [1,2,3]],
22
+ * [{min: 5,max: 6}, [5,6]],
23
+ * [{min: 8,max: 8}, [8]],
24
+ * ]
25
+ * partitionSequence(
26
+ * (n: number, p?: {min: number; max: number}) =>
27
+ * p && p.max + 1 === n
28
+ * ? {value: {...p, max: n}, matches: true}
29
+ * : {value: {min: n, max: n}, matches: false}
30
+ * , [1,2,3,5,6,8]
31
+ * )
32
+ */
33
+ export const partitionSequence = (getPartition, sequence) => {
34
+ const appendItem = (result, item) => {
35
+ const current = result[result.length - 1];
36
+ const itemPartition = getPartition(item, current === null || current === void 0 ? void 0 : current[0]);
37
+ if (current && ((itemPartition.matches === undefined && deepEqual(current[0], itemPartition.value))
38
+ || itemPartition.matches)) {
39
+ current[0] = itemPartition.value;
40
+ current[1].push(item);
41
+ }
42
+ else {
43
+ result.push([itemPartition.value, [item]]);
44
+ }
45
+ return result;
46
+ };
47
+ return sequence.reduce(appendItem, []);
48
+ };
@@ -0,0 +1,91 @@
1
+ import { QueryParams, RouteMatchRecord } from '../routing';
2
+ export declare type PaginationHandler<Pa, Q extends QueryParams> = <R>(queryParams: Q, match: RouteMatchRecord<R>) => Pa & {
3
+ getUnusedQueryParams: () => Q;
4
+ };
5
+ /**
6
+ * helper to create middleware with the given paginator. aside from taking care of annoying to write pagination logic, these helpers also make
7
+ * sure that all item list responses have the same formatting.
8
+ *
9
+ * eg:
10
+ * const getQueryParams = getKeyValueOr('queryStringParameters', {} as QueryParams);
11
+ * const setUnusedQueryParams = putKeyValue('queryStringParameters');
12
+ *
13
+ * export const loadMorePaginationMiddleware = createPaginationMiddleware<ApiRouteRequest>()({getQueryParams, setUnusedQueryParams, paginator: loadMorePagination});
14
+ * export const pageNumberPaginationMiddleware = createPaginationMiddleware<ApiRouteRequest>()({getQueryParams, setUnusedQueryParams, paginator: pageNumberPagination});
15
+ *
16
+ * eg the pagination middleware then provides your necessary inputs (getPageToken... in this case) and formats the response:
17
+ * const result = await services.myDocumentStore.getVersions(key, services.pagination.getPageTokenNumber());
18
+ *
19
+ * if (!result) {
20
+ * throw new NotFoundError('requested item not found');
21
+ * }
22
+ *
23
+ * return apiJsonResponse(200, services.pagination.getPaginationResponse(result));
24
+ */
25
+ export declare const createPaginationMiddleware: <Ri, Q extends QueryParams = {
26
+ [key: string]: string | undefined;
27
+ }, R = any>() => <Pa>({ getQueryParams, setUnusedQueryParams, paginator }: {
28
+ getQueryParams: (request: Ri) => Q;
29
+ setUnusedQueryParams: (request: Ri, query: Q) => Ri;
30
+ paginator: PaginationHandler<Pa, Q>;
31
+ }) => <M extends {
32
+ request: Ri;
33
+ }>() => (middleware: M, match: RouteMatchRecord<R>) => M & {
34
+ pagination: Pa & {
35
+ getUnusedQueryParams: () => Q;
36
+ };
37
+ };
38
+ export declare const loadMorePagination: <R, Q extends QueryParams>(queryParams: Q, { route, params }: RouteMatchRecord<R>) => {
39
+ getUnusedQueryParams: () => Omit<Q, "pageToken">;
40
+ getPageTokenString: () => string | string[] | null | undefined;
41
+ getPageTokenNumber: () => number | undefined;
42
+ getPaginationResponse: <T>({ items, ...meta }: LoadMorePaginationResultInput<T>) => {
43
+ items: T[];
44
+ meta: {
45
+ nextPageToken: string | number | undefined;
46
+ };
47
+ links: {
48
+ nextPage: string | undefined;
49
+ };
50
+ };
51
+ };
52
+ /**
53
+ * if you're writing a data loader, this is what you need to return to be compatible with the loadMore style paginator.
54
+ * this is how the response formatter knows the token for the next page to put in the response metadata.
55
+ * */
56
+ export interface LoadMorePaginationResultInput<T> {
57
+ items: T[];
58
+ nextPageToken: string | number | undefined;
59
+ }
60
+ export declare const pageNumberPagination: <R, Q extends QueryParams>(queryParams: Q, { route, params }: RouteMatchRecord<R>) => {
61
+ getUnusedQueryParams: () => Omit<Q, "page">;
62
+ getPaginationParams: () => {
63
+ page: number | undefined;
64
+ };
65
+ getPaginationResponse: <T>({ items, ...meta }: PageNumberPaginationResultInput<T>) => {
66
+ items: T[];
67
+ meta: {
68
+ pageSize: number;
69
+ currentPage: number;
70
+ totalItems: number;
71
+ totalPages: number;
72
+ };
73
+ links: {
74
+ firstPage: string;
75
+ lastPage: string;
76
+ nextPage: string | undefined;
77
+ prevPage: string | undefined;
78
+ };
79
+ };
80
+ };
81
+ /**
82
+ * if you're writing a data loader, this is what you need to return to be compatible with the pageNumber style paginator.
83
+ * this is how the response formatter knows the information to put in the response metadata.
84
+ * */
85
+ export interface PageNumberPaginationResultInput<T> {
86
+ items: T[];
87
+ pageSize: number;
88
+ currentPage: number;
89
+ totalItems: number;
90
+ totalPages: number;
91
+ }
@@ -0,0 +1,77 @@
1
+ import { notNaN } from '../assertions';
2
+ import { InvalidRequestError } from '../errors';
3
+ import { renderAnyRouteUrl } from '../routing';
4
+ /**
5
+ * helper to create middleware with the given paginator. aside from taking care of annoying to write pagination logic, these helpers also make
6
+ * sure that all item list responses have the same formatting.
7
+ *
8
+ * eg:
9
+ * const getQueryParams = getKeyValueOr('queryStringParameters', {} as QueryParams);
10
+ * const setUnusedQueryParams = putKeyValue('queryStringParameters');
11
+ *
12
+ * export const loadMorePaginationMiddleware = createPaginationMiddleware<ApiRouteRequest>()({getQueryParams, setUnusedQueryParams, paginator: loadMorePagination});
13
+ * export const pageNumberPaginationMiddleware = createPaginationMiddleware<ApiRouteRequest>()({getQueryParams, setUnusedQueryParams, paginator: pageNumberPagination});
14
+ *
15
+ * eg the pagination middleware then provides your necessary inputs (getPageToken... in this case) and formats the response:
16
+ * const result = await services.myDocumentStore.getVersions(key, services.pagination.getPageTokenNumber());
17
+ *
18
+ * if (!result) {
19
+ * throw new NotFoundError('requested item not found');
20
+ * }
21
+ *
22
+ * return apiJsonResponse(200, services.pagination.getPaginationResponse(result));
23
+ */
24
+ export const createPaginationMiddleware = () => ({ getQueryParams, setUnusedQueryParams, paginator }) => () => (middleware, match) => {
25
+ const queryParams = getQueryParams(middleware.request);
26
+ const pagination = paginator(queryParams, match);
27
+ // remove pagination params from downstream logic
28
+ middleware.request = setUnusedQueryParams(middleware.request, pagination.getUnusedQueryParams());
29
+ return { ...middleware, pagination };
30
+ };
31
+ export const loadMorePagination = (queryParams, { route, params }) => {
32
+ const { pageToken, ...otherParams } = queryParams;
33
+ return {
34
+ getUnusedQueryParams: () => otherParams,
35
+ getPageTokenString: () => pageToken,
36
+ getPageTokenNumber: () => pageToken && typeof pageToken === 'string'
37
+ ? notNaN(parseInt(pageToken, 10), () => { throw new InvalidRequestError(); })
38
+ : undefined,
39
+ getPaginationResponse: ({ items, ...meta }) => {
40
+ return {
41
+ items,
42
+ meta,
43
+ links: {
44
+ nextPage: meta.nextPageToken
45
+ ? renderAnyRouteUrl(route, params, { ...queryParams, pageToken: meta.nextPageToken.toString() })
46
+ : undefined,
47
+ }
48
+ };
49
+ },
50
+ };
51
+ };
52
+ export const pageNumberPagination = (queryParams, { route, params }) => {
53
+ const { page, ...otherParams } = queryParams;
54
+ const numberPage = page && typeof page === 'string'
55
+ ? notNaN(parseInt(page, 10), () => { throw new InvalidRequestError(); })
56
+ : undefined;
57
+ return {
58
+ getUnusedQueryParams: () => otherParams,
59
+ getPaginationParams: () => ({ page: numberPage }),
60
+ getPaginationResponse: ({ items, ...meta }) => {
61
+ return {
62
+ items,
63
+ meta,
64
+ links: {
65
+ firstPage: renderAnyRouteUrl(route, params, { ...queryParams, page: '1' }),
66
+ lastPage: renderAnyRouteUrl(route, params, { ...queryParams, page: meta.totalPages.toString() }),
67
+ nextPage: meta.currentPage < meta.totalPages
68
+ ? renderAnyRouteUrl(route, params, { ...queryParams, page: (meta.currentPage + 1).toString() })
69
+ : undefined,
70
+ prevPage: meta.currentPage > 1
71
+ ? renderAnyRouteUrl(route, params, { ...queryParams, page: (meta.currentPage - 1).toString() })
72
+ : undefined
73
+ }
74
+ };
75
+ },
76
+ };
77
+ };