@venizia/ignis-helpers 0.3.6 → 0.4.1

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 (246) hide show
  1. package/LICENSE.md +1 -1
  2. package/dist/cjs/common/redact.js +1 -1
  3. package/dist/cjs/common/redact.js.map +1 -1
  4. package/dist/cjs/modules/base.js +1 -1
  5. package/dist/cjs/modules/base.js.map +1 -1
  6. package/dist/cjs/modules/crypto/algorithms/aes.algorithm.js +1 -1
  7. package/dist/cjs/modules/crypto/algorithms/aes.algorithm.js.map +1 -1
  8. package/dist/cjs/modules/logger/common/constants.js +1 -1
  9. package/dist/cjs/modules/logger/common/constants.js.map +1 -1
  10. package/dist/cjs/modules/logger/factory.js +1 -1
  11. package/dist/cjs/modules/logger/factory.js.map +1 -1
  12. package/dist/cjs/modules/logger/formatting/deep-splat.js +1 -1
  13. package/dist/cjs/modules/logger/formatting/deep-splat.js.map +1 -1
  14. package/dist/cjs/modules/logger/formatting/error-prettier.js +4 -4
  15. package/dist/cjs/modules/logger/formatting/error-prettier.js.map +1 -1
  16. package/dist/cjs/modules/logger/hf/flusher.js +3 -3
  17. package/dist/cjs/modules/logger/hf/flusher.js.map +1 -1
  18. package/dist/cjs/modules/logger/resolver.js +3 -3
  19. package/dist/cjs/modules/logger/resolver.js.map +1 -1
  20. package/dist/cjs/modules/logger/winston/formatters/deep-splat.js +1 -1
  21. package/dist/cjs/modules/logger/winston/formatters/deep-splat.js.map +1 -1
  22. package/dist/cjs/modules/logger/winston/logger-factory.js +1 -1
  23. package/dist/cjs/modules/logger/winston/logger-factory.js.map +1 -1
  24. package/dist/cjs/modules/logger/winston/transports/dgram.transport.js +2 -2
  25. package/dist/cjs/modules/logger/winston/transports/dgram.transport.js.map +1 -1
  26. package/dist/cjs/modules/network/http-request/fetcher/axios-fetcher.js +1 -1
  27. package/dist/cjs/modules/network/http-request/fetcher/axios-fetcher.js.map +1 -1
  28. package/dist/cjs/modules/network/http-request/fetcher/base-fetcher.d.ts +17 -14
  29. package/dist/cjs/modules/network/http-request/fetcher/base-fetcher.d.ts.map +1 -1
  30. package/dist/cjs/modules/network/http-request/fetcher/base-fetcher.js +3 -0
  31. package/dist/cjs/modules/network/http-request/fetcher/base-fetcher.js.map +1 -1
  32. package/dist/cjs/modules/network/http-request/fetcher/node-fetcher.d.ts +13 -4
  33. package/dist/cjs/modules/network/http-request/fetcher/node-fetcher.d.ts.map +1 -1
  34. package/dist/cjs/modules/network/http-request/fetcher/node-fetcher.js +34 -11
  35. package/dist/cjs/modules/network/http-request/fetcher/node-fetcher.js.map +1 -1
  36. package/dist/cjs/modules/network/tcp-socket/base-tcp-client.helper.js +1 -1
  37. package/dist/cjs/modules/network/tcp-socket/base-tcp-client.helper.js.map +1 -1
  38. package/dist/cjs/modules/network/tcp-socket/base-tcp-server.helper.js +4 -4
  39. package/dist/cjs/modules/network/tcp-socket/base-tcp-server.helper.js.map +1 -1
  40. package/dist/cjs/modules/network/udp-socket/network-udp-client.helper.js +1 -1
  41. package/dist/cjs/modules/network/udp-socket/network-udp-client.helper.js.map +1 -1
  42. package/dist/cjs/modules/network/utilities/query-string.d.ts +27 -2
  43. package/dist/cjs/modules/network/utilities/query-string.d.ts.map +1 -1
  44. package/dist/cjs/modules/network/utilities/query-string.js +34 -2
  45. package/dist/cjs/modules/network/utilities/query-string.js.map +1 -1
  46. package/dist/cjs/modules/network/utilities/url-safety/ingest.js +1 -1
  47. package/dist/cjs/modules/network/utilities/url-safety/ingest.js.map +1 -1
  48. package/dist/cjs/modules/network/utilities/url-safety/policy.js +1 -1
  49. package/dist/cjs/modules/network/utilities/url-safety/policy.js.map +1 -1
  50. package/dist/cjs/modules/pool/abstract.js +4 -4
  51. package/dist/cjs/modules/pool/abstract.js.map +1 -1
  52. package/dist/cjs/modules/queue/bullmq/helper.js +2 -2
  53. package/dist/cjs/modules/queue/bullmq/helper.js.map +1 -1
  54. package/dist/cjs/modules/queue/kafka/bundler/platformatic-require.plugin.js.map +1 -1
  55. package/dist/cjs/modules/queue/kafka/bundler/platformatic-wasm.plugin.js +1 -1
  56. package/dist/cjs/modules/queue/kafka/bundler/platformatic-wasm.plugin.js.map +1 -1
  57. package/dist/cjs/modules/queue/kafka/consumer.js +2 -2
  58. package/dist/cjs/modules/queue/kafka/consumer.js.map +1 -1
  59. package/dist/cjs/modules/queue/mqtt/helper.js +4 -4
  60. package/dist/cjs/modules/queue/mqtt/helper.js.map +1 -1
  61. package/dist/cjs/modules/redis/base/abstract.helper.js +4 -4
  62. package/dist/cjs/modules/redis/base/abstract.helper.js.map +1 -1
  63. package/dist/cjs/modules/redis/cluster/cluster.helper.js +1 -1
  64. package/dist/cjs/modules/redis/cluster/cluster.helper.js.map +1 -1
  65. package/dist/cjs/modules/redis/sentinel/sentinel.helper.js +1 -1
  66. package/dist/cjs/modules/redis/sentinel/sentinel.helper.js.map +1 -1
  67. package/dist/cjs/modules/secrets/base/abstract.helper.js +2 -2
  68. package/dist/cjs/modules/secrets/base/abstract.helper.js.map +1 -1
  69. package/dist/cjs/modules/secrets/hashicorp/hashicorp.helper.js +2 -2
  70. package/dist/cjs/modules/secrets/hashicorp/hashicorp.helper.js.map +1 -1
  71. package/dist/cjs/modules/socket/socket-io/browser.d.ts +5 -0
  72. package/dist/cjs/modules/socket/socket-io/browser.d.ts.map +1 -0
  73. package/dist/cjs/modules/socket/socket-io/browser.js +21 -0
  74. package/dist/cjs/modules/socket/socket-io/browser.js.map +1 -0
  75. package/dist/cjs/modules/socket/socket-io/client/browser-helper.d.ts +61 -0
  76. package/dist/cjs/modules/socket/socket-io/client/browser-helper.d.ts.map +1 -0
  77. package/dist/cjs/modules/socket/socket-io/client/browser-helper.js +250 -0
  78. package/dist/cjs/modules/socket/socket-io/client/browser-helper.js.map +1 -0
  79. package/dist/cjs/modules/socket/socket-io/client/helper.d.ts +8 -51
  80. package/dist/cjs/modules/socket/socket-io/client/helper.d.ts.map +1 -1
  81. package/dist/cjs/modules/socket/socket-io/client/helper.js +12 -230
  82. package/dist/cjs/modules/socket/socket-io/client/helper.js.map +1 -1
  83. package/dist/cjs/modules/socket/socket-io/server/helper.js +5 -5
  84. package/dist/cjs/modules/socket/socket-io/server/helper.js.map +1 -1
  85. package/dist/cjs/modules/socket/websocket/server/delivery.js +2 -2
  86. package/dist/cjs/modules/socket/websocket/server/delivery.js.map +1 -1
  87. package/dist/cjs/modules/socket/websocket/server/helper.js +4 -4
  88. package/dist/cjs/modules/socket/websocket/server/helper.js.map +1 -1
  89. package/dist/cjs/modules/storage/base.js +3 -3
  90. package/dist/cjs/modules/storage/base.js.map +1 -1
  91. package/dist/cjs/modules/storage/bun-s3/helper.js +1 -1
  92. package/dist/cjs/modules/storage/bun-s3/helper.js.map +1 -1
  93. package/dist/cjs/modules/storage/bun-s3/utility.js +6 -6
  94. package/dist/cjs/modules/storage/bun-s3/utility.js.map +1 -1
  95. package/dist/cjs/modules/storage/common/errors.js +1 -1
  96. package/dist/cjs/modules/storage/common/errors.js.map +1 -1
  97. package/dist/cjs/modules/storage/minio/helper.js +4 -4
  98. package/dist/cjs/modules/storage/minio/helper.js.map +1 -1
  99. package/dist/cjs/modules/temporal/abstract.js +5 -5
  100. package/dist/cjs/modules/temporal/abstract.js.map +1 -1
  101. package/dist/cjs/modules/temporal/adapters/intl.d.ts.map +1 -1
  102. package/dist/cjs/modules/temporal/adapters/intl.js +3 -1
  103. package/dist/cjs/modules/temporal/adapters/intl.js.map +1 -1
  104. package/dist/cjs/modules/temporal/locale/locale.js +4 -4
  105. package/dist/cjs/modules/temporal/locale/locale.js.map +1 -1
  106. package/dist/cjs/modules/tree/builder.js +2 -2
  107. package/dist/cjs/modules/tree/builder.js.map +1 -1
  108. package/dist/cjs/modules/uid/opaque.js +2 -2
  109. package/dist/cjs/modules/uid/opaque.js.map +1 -1
  110. package/dist/cjs/modules/uid/uuid/v5.js +1 -1
  111. package/dist/cjs/modules/uid/uuid/v5.js.map +1 -1
  112. package/dist/cjs/modules/worker-thread/bus/base.js +4 -4
  113. package/dist/cjs/modules/worker-thread/bus/base.js.map +1 -1
  114. package/dist/cjs/modules/worker-thread/worker/base.js +4 -4
  115. package/dist/cjs/modules/worker-thread/worker/base.js.map +1 -1
  116. package/dist/cjs/utilities/parse.utility.js +4 -4
  117. package/dist/cjs/utilities/parse.utility.js.map +1 -1
  118. package/dist/cjs/utilities/promise.utility.js +1 -1
  119. package/dist/cjs/utilities/promise.utility.js.map +1 -1
  120. package/dist/cjs/utilities/request.utility.js +1 -1
  121. package/dist/cjs/utilities/request.utility.js.map +1 -1
  122. package/dist/cjs/utilities/sleep.utility.js +1 -1
  123. package/dist/cjs/utilities/sleep.utility.js.map +1 -1
  124. package/dist/esm/common/redact.js +1 -1
  125. package/dist/esm/common/redact.js.map +1 -1
  126. package/dist/esm/modules/base.js +1 -1
  127. package/dist/esm/modules/base.js.map +1 -1
  128. package/dist/esm/modules/crypto/algorithms/aes.algorithm.js +1 -1
  129. package/dist/esm/modules/crypto/algorithms/aes.algorithm.js.map +1 -1
  130. package/dist/esm/modules/logger/common/constants.js +1 -1
  131. package/dist/esm/modules/logger/common/constants.js.map +1 -1
  132. package/dist/esm/modules/logger/factory.js +1 -1
  133. package/dist/esm/modules/logger/factory.js.map +1 -1
  134. package/dist/esm/modules/logger/formatting/deep-splat.js +1 -1
  135. package/dist/esm/modules/logger/formatting/deep-splat.js.map +1 -1
  136. package/dist/esm/modules/logger/formatting/error-prettier.js +4 -4
  137. package/dist/esm/modules/logger/formatting/error-prettier.js.map +1 -1
  138. package/dist/esm/modules/logger/hf/flusher.js +3 -3
  139. package/dist/esm/modules/logger/hf/flusher.js.map +1 -1
  140. package/dist/esm/modules/logger/resolver.js +3 -3
  141. package/dist/esm/modules/logger/resolver.js.map +1 -1
  142. package/dist/esm/modules/logger/winston/formatters/deep-splat.js +1 -1
  143. package/dist/esm/modules/logger/winston/formatters/deep-splat.js.map +1 -1
  144. package/dist/esm/modules/logger/winston/logger-factory.js +1 -1
  145. package/dist/esm/modules/logger/winston/logger-factory.js.map +1 -1
  146. package/dist/esm/modules/logger/winston/transports/dgram.transport.js +2 -2
  147. package/dist/esm/modules/logger/winston/transports/dgram.transport.js.map +1 -1
  148. package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.js +1 -1
  149. package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.js.map +1 -1
  150. package/dist/esm/modules/network/http-request/fetcher/base-fetcher.d.ts +17 -14
  151. package/dist/esm/modules/network/http-request/fetcher/base-fetcher.d.ts.map +1 -1
  152. package/dist/esm/modules/network/http-request/fetcher/base-fetcher.js +3 -0
  153. package/dist/esm/modules/network/http-request/fetcher/base-fetcher.js.map +1 -1
  154. package/dist/esm/modules/network/http-request/fetcher/node-fetcher.d.ts +13 -4
  155. package/dist/esm/modules/network/http-request/fetcher/node-fetcher.d.ts.map +1 -1
  156. package/dist/esm/modules/network/http-request/fetcher/node-fetcher.js +36 -13
  157. package/dist/esm/modules/network/http-request/fetcher/node-fetcher.js.map +1 -1
  158. package/dist/esm/modules/network/tcp-socket/base-tcp-client.helper.js +1 -1
  159. package/dist/esm/modules/network/tcp-socket/base-tcp-client.helper.js.map +1 -1
  160. package/dist/esm/modules/network/tcp-socket/base-tcp-server.helper.js +4 -4
  161. package/dist/esm/modules/network/tcp-socket/base-tcp-server.helper.js.map +1 -1
  162. package/dist/esm/modules/network/udp-socket/network-udp-client.helper.js +1 -1
  163. package/dist/esm/modules/network/udp-socket/network-udp-client.helper.js.map +1 -1
  164. package/dist/esm/modules/network/utilities/query-string.d.ts +27 -2
  165. package/dist/esm/modules/network/utilities/query-string.d.ts.map +1 -1
  166. package/dist/esm/modules/network/utilities/query-string.js +31 -1
  167. package/dist/esm/modules/network/utilities/query-string.js.map +1 -1
  168. package/dist/esm/modules/network/utilities/url-safety/ingest.js +1 -1
  169. package/dist/esm/modules/network/utilities/url-safety/ingest.js.map +1 -1
  170. package/dist/esm/modules/network/utilities/url-safety/policy.js +1 -1
  171. package/dist/esm/modules/network/utilities/url-safety/policy.js.map +1 -1
  172. package/dist/esm/modules/pool/abstract.js +4 -4
  173. package/dist/esm/modules/pool/abstract.js.map +1 -1
  174. package/dist/esm/modules/queue/bullmq/helper.js +2 -2
  175. package/dist/esm/modules/queue/bullmq/helper.js.map +1 -1
  176. package/dist/esm/modules/queue/kafka/bundler/platformatic-require.plugin.js.map +1 -1
  177. package/dist/esm/modules/queue/kafka/bundler/platformatic-wasm.plugin.js +1 -1
  178. package/dist/esm/modules/queue/kafka/bundler/platformatic-wasm.plugin.js.map +1 -1
  179. package/dist/esm/modules/queue/kafka/consumer.js +2 -2
  180. package/dist/esm/modules/queue/kafka/consumer.js.map +1 -1
  181. package/dist/esm/modules/queue/mqtt/helper.js +4 -4
  182. package/dist/esm/modules/queue/mqtt/helper.js.map +1 -1
  183. package/dist/esm/modules/redis/base/abstract.helper.js +4 -4
  184. package/dist/esm/modules/redis/base/abstract.helper.js.map +1 -1
  185. package/dist/esm/modules/redis/cluster/cluster.helper.js +1 -1
  186. package/dist/esm/modules/redis/cluster/cluster.helper.js.map +1 -1
  187. package/dist/esm/modules/redis/sentinel/sentinel.helper.js +1 -1
  188. package/dist/esm/modules/redis/sentinel/sentinel.helper.js.map +1 -1
  189. package/dist/esm/modules/secrets/base/abstract.helper.js +2 -2
  190. package/dist/esm/modules/secrets/base/abstract.helper.js.map +1 -1
  191. package/dist/esm/modules/secrets/hashicorp/hashicorp.helper.js +2 -2
  192. package/dist/esm/modules/secrets/hashicorp/hashicorp.helper.js.map +1 -1
  193. package/dist/esm/modules/socket/socket-io/browser.d.ts +5 -0
  194. package/dist/esm/modules/socket/socket-io/browser.d.ts.map +1 -0
  195. package/dist/esm/modules/socket/socket-io/browser.js +5 -0
  196. package/dist/esm/modules/socket/socket-io/browser.js.map +1 -0
  197. package/dist/esm/modules/socket/socket-io/client/browser-helper.d.ts +61 -0
  198. package/dist/esm/modules/socket/socket-io/client/browser-helper.d.ts.map +1 -0
  199. package/dist/esm/modules/socket/socket-io/client/browser-helper.js +246 -0
  200. package/dist/esm/modules/socket/socket-io/client/browser-helper.js.map +1 -0
  201. package/dist/esm/modules/socket/socket-io/client/helper.d.ts +8 -51
  202. package/dist/esm/modules/socket/socket-io/client/helper.d.ts.map +1 -1
  203. package/dist/esm/modules/socket/socket-io/client/helper.js +12 -230
  204. package/dist/esm/modules/socket/socket-io/client/helper.js.map +1 -1
  205. package/dist/esm/modules/socket/socket-io/server/helper.js +5 -5
  206. package/dist/esm/modules/socket/socket-io/server/helper.js.map +1 -1
  207. package/dist/esm/modules/socket/websocket/server/delivery.js +2 -2
  208. package/dist/esm/modules/socket/websocket/server/delivery.js.map +1 -1
  209. package/dist/esm/modules/socket/websocket/server/helper.js +4 -4
  210. package/dist/esm/modules/socket/websocket/server/helper.js.map +1 -1
  211. package/dist/esm/modules/storage/base.js +3 -3
  212. package/dist/esm/modules/storage/base.js.map +1 -1
  213. package/dist/esm/modules/storage/bun-s3/helper.js +1 -1
  214. package/dist/esm/modules/storage/bun-s3/helper.js.map +1 -1
  215. package/dist/esm/modules/storage/bun-s3/utility.js +6 -6
  216. package/dist/esm/modules/storage/bun-s3/utility.js.map +1 -1
  217. package/dist/esm/modules/storage/common/errors.js +1 -1
  218. package/dist/esm/modules/storage/common/errors.js.map +1 -1
  219. package/dist/esm/modules/storage/minio/helper.js +4 -4
  220. package/dist/esm/modules/storage/minio/helper.js.map +1 -1
  221. package/dist/esm/modules/temporal/abstract.js +5 -5
  222. package/dist/esm/modules/temporal/abstract.js.map +1 -1
  223. package/dist/esm/modules/temporal/adapters/intl.d.ts.map +1 -1
  224. package/dist/esm/modules/temporal/adapters/intl.js +3 -1
  225. package/dist/esm/modules/temporal/adapters/intl.js.map +1 -1
  226. package/dist/esm/modules/temporal/locale/locale.js +4 -4
  227. package/dist/esm/modules/temporal/locale/locale.js.map +1 -1
  228. package/dist/esm/modules/tree/builder.js +2 -2
  229. package/dist/esm/modules/tree/builder.js.map +1 -1
  230. package/dist/esm/modules/uid/opaque.js +2 -2
  231. package/dist/esm/modules/uid/opaque.js.map +1 -1
  232. package/dist/esm/modules/uid/uuid/v5.js +1 -1
  233. package/dist/esm/modules/uid/uuid/v5.js.map +1 -1
  234. package/dist/esm/modules/worker-thread/bus/base.js +4 -4
  235. package/dist/esm/modules/worker-thread/bus/base.js.map +1 -1
  236. package/dist/esm/modules/worker-thread/worker/base.js +4 -4
  237. package/dist/esm/modules/worker-thread/worker/base.js.map +1 -1
  238. package/dist/esm/utilities/parse.utility.js +4 -4
  239. package/dist/esm/utilities/parse.utility.js.map +1 -1
  240. package/dist/esm/utilities/promise.utility.js +1 -1
  241. package/dist/esm/utilities/promise.utility.js.map +1 -1
  242. package/dist/esm/utilities/request.utility.js +1 -1
  243. package/dist/esm/utilities/request.utility.js.map +1 -1
  244. package/dist/esm/utilities/sleep.utility.js +1 -1
  245. package/dist/esm/utilities/sleep.utility.js.map +1 -1
  246. package/package.json +69 -64
@@ -1 +1 @@
1
- {"version":3,"file":"abstract.js","sourceRoot":"","sources":["../../../../src/modules/temporal/abstract.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAC/D,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,EACL,uBAAuB,EACvB,mBAAmB,IAAI,mBAAmB,EAC1C,aAAa,GACd,MAAM,oBAAoB,CAAC;AAgB5B,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAE1C,MAAM,gBAAgB,GAAG,UAAU,CAAC;AAEpC,6DAA6D;AAC7D,MAAM,WAAW,GAAG,CAAC,kB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AK,GAAG,CAAC,KAAK,GAAG,MAAM,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC;IACjD,CAAC;IAED,sGAAsG;IAC5F,eAAe,CAAC,IAIzB;QACC,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE,EAAE,GAAG,IAAI,CAAC;QACnC,MAAM,OAAO,GAAG,gBAAgB,CAAC,KAAK,CAAC;YACrC,KAAK,EAAE,gBAAgB,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,CAAC;YAC9C,MAAM,EAAE,MAAM;YACd,IAAI,EAAE,aAAa,CAAC,KAAK;SAC1B,CAAC,CAAC;QACH,OAAO,IAAI,CAAC,UAAU,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC,CAAC;IACjD,CAAC","sourcesContent":["import { HTTP } from '@/common/constants/http';\nimport { BaseHelper } from '@/modules/base';\nimport { getError, isApplicationError } from '@/modules/error';\nimport { IntlTemporalAdapter } from './adapters/intl';\nimport { NativeTemporalAdapter } from './adapters/native';\nimport { TemporalCalendar } from './calendar';\nimport {\n DEFAULT_TEMPORAL_LOCALE,\n DEFAULT_TEMPORAL_TZ as DEFAULT_TEMPORAL_TZ,\n TemporalUnits,\n} from './common/constants';\nimport type {\n TTemporalDurationStyle,\n TTemporalInclusivity,\n TTemporalUnit,\n} from './common/constants';\nimport type {\n ITemporalAdapter,\n ITemporalDurationParts,\n ITemporalLocaleNames,\n ITemporalParts,\n TTemporalFields,\n IZonedTemporalParts,\n TTemporalInput,\n ITemporalHelper,\n} from './common/types';\nimport { TemporalLocale } from './locale';\n\nconst DAY_MILLISECONDS = 86_400_000;\n\n/** 0001-01-01T00:00:00.000Z and 9999-12-31T23:59:59.999Z. */\nconst MIN_INSTANT = -62_135_596_800_000;\nconst MAX_INSTANT = 253_402_300_799_999;\n\nconst MAX_KNOWN_TIME_ZONES = 256;\n\n/** How many entries each `names` list must hold. */\nconst NAME_LENGTHS: Record<keyof ITemporalLocaleNames, number> = {\n months: 12,\n monthsShort: 12,\n weekdays: 7,\n weekdaysShort: 7,\n weekdaysMin: 7,\n meridiem: 2,\n};\n\nconst OUT_OF_RANGE = `outside the years ${TemporalCalendar.MIN_YEAR}-${TemporalCalendar.MAX_YEAR}`; /**\n * The machinery every temporal helper shares: the adapter, the zone and locale it holds, reading a\n * zone's offset, turning wall clocks into instants across daylight-saving gaps and repeats, and the\n * input checks. A helper extends this and supplies the operations in `ITemporalHelper`.\n */\nexport abstract class AbstractTemporalHelper extends BaseHelper implements ITemporalHelper {\n /** Validated once per process: `Intl` answers the same for a zone name every time. */\n protected static readonly knownTzs = new Set<string>();\n\n protected readonly adapter: ITemporalAdapter;\n protected readonly tz: string;\n protected readonly locale: string;\n protected readonly names: Record<string, ITemporalLocaleNames>;\n protected readonly fallback?: string;\n /** Which `names` entry each locale a call wrote in resolved to - `names` never changes after construction. */\n private readonly namesByLocale = new Map<string, ITemporalLocaleNames | undefined>();\n\n /**\n * `locale` (default `en-US`) spells month and weekday names, AM/PM, relative time and durations,\n * unless a call passes its own. `names` replaces `Intl`'s wording for a locale - month and weekday\n * names, the AM/PM marker - keyed by a locale tag; a call in another tag of the same language (`vi`\n * for a `vi-VN` entry) uses it too. `fallback` is what `format` and `formatIntl` write for a value\n * that is not a date when a call gives none; without it, such a value is a 400.\n */\n constructor(opts?: {\n adapter?: ITemporalAdapter;\n tz?: string;\n locale?: string;\n names?: Record<string, ITemporalLocaleNames>;\n fallback?: string;\n scope?: string;\n }) {\n super({ scope: opts?.scope ?? new.target.name });\n\n this.tz = AbstractTemporalHelper.ensureTz({\n tz: opts?.tz ?? DEFAULT_TEMPORAL_TZ,\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n });\n this.locale = AbstractTemporalHelper.ensureLocale({\n locale: opts?.locale ?? DEFAULT_TEMPORAL_LOCALE,\n });\n this.adapter = opts?.adapter ?? AbstractTemporalHelper.defaultAdapter();\n this.names = AbstractTemporalHelper.ensureNames({ names: opts?.names ?? {} });\n this.fallback = opts?.fallback;\n }\n\n /**\n * The zone a `Date`'s local getters use on this runtime - the browser's or the server's. The one\n * place this helper reads the host zone, and only when a wall-clock bridge is not given one.\n */\n static getHostTz(): string {\n return new Intl.DateTimeFormat().resolvedOptions().timeZone;\n }\n\n /** The instant whose wall clock in `to` reads what `value`'s wall clock reads in `from`. */\n protected moveWallClock(opts: { value: TTemporalInput; from: string; to: string }): Date {\n const from = this.resolveTz({ tz: opts.from });\n const to = this.resolveTz({ tz: opts.to });\n const date = this.toDate({ value: opts.value, tz: from });\n\n const wall = TemporalCalendar.wallClockOf({\n parts: this.zonedParts({ epoch: date.getTime(), tz: from }),\n });\n return AbstractTemporalHelper.ensureInstant({\n epoch: this.earliestOf({ parts: wall, tz: to }),\n });\n }\n\n /** Every list the right length, so a bad table fails when the helper is built, not on a screen. */\n protected static ensureNames(opts: {\n names: Record<string, ITemporalLocaleNames>;\n }): Record<string, ITemporalLocaleNames> {\n for (const [locale, names] of Object.entries(opts.names)) {\n AbstractTemporalHelper.ensureLocale({ locale });\n for (const [key, length] of Object.entries(NAME_LENGTHS)) {\n const list: unknown = Reflect.get(names, key);\n if (list === undefined) {\n continue;\n }\n if (\n !Array.isArray(list) ||\n list.length !== length ||\n !list.every(entry => typeof entry === 'string')\n ) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[TemporalHelper] names['${locale}'].${key} must hold ${length} strings`,\n });\n }\n }\n }\n return opts.names;\n }\n\n /** The wording this helper holds for `locale`, if any. */\n protected namesOf(opts: { locale: string }): ITemporalLocaleNames | undefined {\n const { locale } = opts;\n if (Object.hasOwn(this.names, locale)) {\n return this.names[locale];\n }\n\n if (this.namesByLocale.has(locale)) {\n return this.namesByLocale.get(locale);\n }\n // A malformed tag is the caller's 400, before it reaches `Intl.Locale`.\n AbstractTemporalHelper.ensureLocale({ locale });\n\n // No entry for the exact tag: one for the same language serves - `vi` reads a `vi-VN` entry.\n const language = new Intl.Locale(locale).language;\n const match = Object.keys(this.names).find(key => new Intl.Locale(key).language === language);\n const names = match === undefined ? undefined : this.names[match];\n this.namesByLocale.set(locale, names);\n return names;\n }\n\n /**\n * The value as a date for a writer: with a fallback - the call's, else the helper's - a value that\n * is not a date answers `null`; without one it is a 400, null included.\n */\n protected readDate(opts: {\n value: TTemporalInput | null | undefined;\n tz: string;\n fallback?: string;\n }): Date | null {\n const { value, tz } = opts;\n if ((opts.fallback ?? this.fallback) !== undefined) {\n return this.tryToDate({ value, tz });\n }\n if (value === null || value === undefined) {\n throw AbstractTemporalHelper.notADate({ value });\n }\n return this.toDate({ value, tz });\n }\n\n /** The runtime's `Temporal` where it has one; `Intl`, which every runtime has, everywhere else. */\n protected static defaultAdapter(): ITemporalAdapter {\n return NativeTemporalAdapter.isTemporalNamespace(Reflect.get(globalThis, 'Temporal'))\n ? new NativeTemporalAdapter()\n : new IntlTemporalAdapter();\n }\n\n protected static ensureLocale(opts: { locale: string }): string {\n TemporalLocale.of({ locale: opts.locale });\n return opts.locale;\n }\n\n /** A parse or input error the caller may treat as \"not a date\"; anything else is a bug and still throws. */\n protected static isRefusal(error: unknown): boolean {\n return isApplicationError(error) && error.statusCode === HTTP.ResultCodes.RS_4.BadRequest;\n }\n\n protected static ensureTz(opts: { tz: string; statusCode: number }): string {\n const { tz, statusCode } = opts;\n if (AbstractTemporalHelper.knownTzs.has(tz)) {\n return tz;\n }\n\n try {\n new Intl.DateTimeFormat('en-US', { timeZone: tz });\n } catch (error) {\n throw getError({\n statusCode,\n message: `[TemporalHelper] unknown time zone '${tz}' | ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n\n if (AbstractTemporalHelper.knownTzs.size < MAX_KNOWN_TIME_ZONES) {\n AbstractTemporalHelper.knownTzs.add(tz);\n }\n return tz;\n }\n\n protected static ensureUnit(opts: { unit: string; amount?: number }): void {\n const { unit, amount } = opts;\n if (!TemporalUnits.isValid(unit)) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: `[TemporalHelper] unknown unit '${unit}' | Supported: ${[...TemporalUnits.SCHEME_SET].join(', ')}`,\n });\n }\n if (amount === undefined) {\n return;\n }\n // Elapsed time takes a fraction (1.5 hours is 90 minutes); a calendar unit has no half.\n const isElapsed = TemporalCalendar.EXACT_UNIT_MILLISECONDS[unit] !== undefined;\n if (isElapsed ? !Number.isFinite(amount) : !Number.isInteger(amount)) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: isElapsed\n ? `[TemporalHelper] amount must be a finite number - received ${amount}`\n : `[TemporalHelper] amount must be an integer for '${unit}' - received ${amount}`,\n });\n }\n }\n\n /** Every result passes here: an overflowing `add` is refused, never an Invalid Date. */\n protected static ensureInstant(opts: { epoch: number }): Date {\n const { epoch } = opts;\n if (!(epoch >= MIN_INSTANT && epoch <= MAX_INSTANT)) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: `[TemporalHelper] ${Number.isNaN(epoch) ? 'invalid date' : OUT_OF_RANGE} - received ${epoch}`,\n });\n }\n return new Date(epoch);\n }\n\n protected static ensureYear(opts: { parts: ITemporalParts }): void {\n if (!TemporalCalendar.isSupportedYear({ year: opts.parts.year })) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: `[TemporalHelper] year ${opts.parts.year} is ${OUT_OF_RANGE}`,\n });\n }\n }\n\n protected resolveTz(opts: { tz?: string }): string {\n return opts.tz === undefined\n ? this.tz\n : AbstractTemporalHelper.ensureTz({\n tz: opts.tz,\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n });\n }\n\n /** The adapter's one answer, rounded: an offset is whole milliseconds, a library's float may not be. */\n protected offsetAt(opts: { epoch: number; tz: string }): number {\n return Math.round(\n this.adapter.getOffsetMilliseconds({ value: new Date(opts.epoch), tz: opts.tz }),\n );\n }\n\n protected zonedParts(opts: { epoch: number; tz: string }): IZonedTemporalParts {\n const parts = TemporalCalendar.wallClockAt({\n epoch: opts.epoch,\n offsetMilliseconds: this.offsetAt(opts),\n });\n AbstractTemporalHelper.ensureYear({ parts });\n return parts;\n }\n\n /**\n * Every instant whose wall clock reads `parts` in the zone, earliest first: one as a rule, two\n * when the clock goes back, none when it jumps forward. `forward` is where a skipped time lands -\n * read with the offset from before the jump, so it moves past the gap.\n */\n protected instantsOf(opts: { parts: ITemporalParts; tz: string }): {\n instants: Array<number>;\n forward: number;\n } {\n const { parts, tz } = opts;\n const local = TemporalCalendar.epochAtOffset({ parts, offsetMilliseconds: 0 });\n const before = this.offsetAt({ epoch: local - DAY_MILLISECONDS, tz });\n const after = this.offsetAt({ epoch: local + DAY_MILLISECONDS, tz });\n\n const offsets = before === after ? [before] : [before, after];\n const instants: Array<number> = [];\n for (const offset of offsets) {\n const candidate = local - offset;\n if (this.offsetAt({ epoch: candidate, tz }) === offset) {\n instants.push(candidate);\n }\n }\n instants.sort((left, right) => left - right);\n\n return { instants, forward: local - before };\n }\n\n /** The instant wall-clock `parts` name: a skipped time moves forward, a repeated one takes the earlier. */\n protected earliestOf(opts: { parts: ITemporalParts; tz: string }): number {\n const { instants, forward } = this.instantsOf(opts);\n return instants[0] ?? forward;\n }\n\n /**\n * `[start, end)` of the unit holding `epoch`. A day or longer starts at its first instant. An hour\n * or less repeats when the clock goes back, so it starts at the latest start not after `epoch`,\n * and ends where the wall clock next shows either the following unit or this one's start again.\n */\n protected unitBounds(opts: { epoch: number; unit: TTemporalUnit; tz: string }): {\n start: number;\n end: number;\n } {\n const { epoch, unit, tz } = opts;\n const startParts = TemporalCalendar.truncate({\n parts: this.zonedParts({ epoch, tz }),\n unit,\n });\n const nextParts = TemporalCalendar.shift({ parts: startParts, amount: 1, unit });\n AbstractTemporalHelper.ensureYear({ parts: nextParts });\n\n const starts = this.instantsOf({ parts: startParts, tz });\n if (TemporalCalendar.EXACT_UNIT_MILLISECONDS[unit] === undefined) {\n const start = starts.instants[0] ?? starts.forward;\n return { start, end: this.earliestOf({ parts: nextParts, tz }) };\n }\n\n const started = starts.instants.filter(instant => instant <= epoch);\n const start = started.at(-1) ?? starts.instants[0] ?? starts.forward;\n\n const nexts = this.instantsOf({ parts: nextParts, tz });\n const following = nexts.instants.find(instant => instant > start) ?? nexts.forward;\n const repeated = starts.instants.find(instant => instant > start);\n return { start, end: repeated === undefined ? following : Math.min(repeated, following) };\n }\n\n getTz(): string {\n return this.tz;\n }\n\n getLocale(): string {\n return this.locale;\n }\n\n now(): Date {\n return new Date();\n }\n\n /** The instant a value names. An ISO string without an offset is read as wall clock in the zone. */\n toDate(opts: { value: TTemporalInput; tz?: string }): Date {\n const { value } = opts;\n\n if (typeof value === 'string') {\n return this.parse({ value, tz: opts.tz });\n }\n if (value instanceof Date) {\n return AbstractTemporalHelper.ensureInstant({ epoch: value.getTime() });\n }\n if (typeof value === 'number') {\n return AbstractTemporalHelper.ensureInstant({ epoch: value });\n }\n\n // `null` above all: read as a number it would be 1970, a date nobody meant.\n throw AbstractTemporalHelper.notADate({ value });\n }\n\n protected static notADate(opts: { value: unknown }) {\n const { value } = opts;\n return getError({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: `[TemporalHelper] not a date - received ${value === null ? 'null' : typeof value}`,\n });\n }\n\n /** `toDate`, answering `null` where `toDate` refuses the value: null, undefined, bad text, NaN. */\n tryToDate(opts: { value: TTemporalInput | null | undefined; tz?: string }): Date | null {\n const { value } = opts;\n // Outside the try: a bad zone is the caller's bug, not an unreadable value.\n const tz = this.resolveTz({ tz: opts.tz });\n if (value === null || value === undefined) {\n return null;\n }\n\n try {\n return this.toDate({ value, tz });\n } catch (error) {\n if (AbstractTemporalHelper.isRefusal(error)) {\n return null;\n }\n throw error;\n }\n }\n\n /** The wall clock the value shows in the zone, with its ISO weekday and UTC offset. */\n parts(opts: { value: TTemporalInput; tz?: string }): IZonedTemporalParts {\n const tz = this.resolveTz({ tz: opts.tz });\n const date = this.toDate({ value: opts.value, tz });\n return this.zonedParts({ epoch: date.getTime(), tz });\n }\n\n /**\n * Fractional months from `other` to `value` (dayjs and moment's month difference): anchored on the\n * date with the later day of the month, whole months by `add`, the rest as a share of the month\n * it falls in.\n */\n protected monthGap(opts: { value: number; other: number; tz: string }): number {\n const { value, other, tz } = opts;\n const valueParts = this.zonedParts({ epoch: value, tz });\n const otherParts = this.zonedParts({ epoch: other, tz });\n if (valueParts.day < otherParts.day) {\n return -this.monthGap({ value: other, other: value, tz });\n }\n\n const whole = (otherParts.year - valueParts.year) * 12 + (otherParts.month - valueParts.month);\n const anchor = this.shiftMonthsFrom({ parts: valueParts, months: whole, tz });\n const isBelow = other - anchor < 0;\n const nextAnchor = this.shiftMonthsFrom({\n parts: valueParts,\n months: whole + (isBelow ? -1 : 1),\n tz,\n });\n const span = isBelow ? anchor - nextAnchor : nextAnchor - anchor;\n\n return -(whole + (other - anchor) / span) || 0;\n }\n\n /** `add` by months without the 1-9999 check: an anchor one month past the range is still a number. */\n protected shiftMonthsFrom(opts: {\n parts: IZonedTemporalParts;\n months: number;\n tz: string;\n }): number {\n const { parts, months, tz } = opts;\n const shifted = TemporalCalendar.shift({\n parts: TemporalCalendar.wallClockOf({ parts }),\n amount: months,\n unit: TemporalUnits.MONTH,\n });\n return this.earliestOf({ parts: shifted, tz });\n }\n\n abstract fromWallClock(opts: { value: TTemporalInput; sourceTz?: string; tz?: string }): Date;\n\n abstract toWallClock(opts: { value: TTemporalInput; targetTz?: string; tz?: string }): Date;\n\n abstract clone(opts: { locale?: string; tz?: string }): ITemporalHelper;\n\n abstract parse(opts: { value: string; pattern?: string; tz?: string }): Date;\n\n abstract tryParse(opts: { value: string; pattern?: string; tz?: string }): Date | null;\n\n abstract isValid(opts: {\n value: TTemporalInput | null | undefined;\n pattern?: string;\n tz?: string;\n }): boolean;\n\n abstract format(opts: {\n value: TTemporalInput | null | undefined;\n pattern?: string;\n tz?: string;\n locale?: string;\n fallback?: string;\n }): string;\n\n abstract formatIntl(opts: {\n value: TTemporalInput;\n options?: Omit<Intl.DateTimeFormatOptions, 'timeZone'>;\n tz?: string;\n locale?: string;\n }): string;\n\n abstract add(opts: {\n value: TTemporalInput;\n amount: number;\n unit: TTemporalUnit;\n tz?: string;\n }): Date;\n\n abstract subtract(opts: {\n value: TTemporalInput;\n amount: number;\n unit: TTemporalUnit;\n tz?: string;\n }): Date;\n\n abstract startOf(opts: { value: TTemporalInput; unit: TTemporalUnit; tz?: string }): Date;\n\n abstract endOf(opts: { value: TTemporalInput; unit: TTemporalUnit; tz?: string }): Date;\n\n abstract isWeekday(opts: { value: TTemporalInput; tz?: string }): boolean;\n\n abstract nextWeekday(opts: { value: TTemporalInput; tz?: string }): Date;\n\n abstract previousWeekday(opts: { value: TTemporalInput; tz?: string }): Date;\n\n abstract set(opts: { value: TTemporalInput; tz?: string } & TTemporalFields): Date;\n\n abstract isBefore(opts: {\n value: TTemporalInput;\n other: TTemporalInput;\n unit?: TTemporalUnit;\n tz?: string;\n }): boolean;\n\n abstract isAfter(opts: {\n value: TTemporalInput;\n other: TTemporalInput;\n unit?: TTemporalUnit;\n tz?: string;\n }): boolean;\n\n abstract isSame(opts: {\n value: TTemporalInput;\n other: TTemporalInput;\n unit?: TTemporalUnit;\n tz?: string;\n }): boolean;\n\n abstract isSameOrBefore(opts: {\n value: TTemporalInput;\n other: TTemporalInput;\n unit?: TTemporalUnit;\n tz?: string;\n }): boolean;\n\n abstract isSameOrAfter(opts: {\n value: TTemporalInput;\n other: TTemporalInput;\n unit?: TTemporalUnit;\n tz?: string;\n }): boolean;\n\n abstract isBetween(opts: {\n value: TTemporalInput;\n from: TTemporalInput;\n to: TTemporalInput;\n unit?: TTemporalUnit;\n inclusivity?: TTemporalInclusivity;\n tz?: string;\n }): boolean;\n\n abstract diff(opts: {\n value: TTemporalInput;\n other: TTemporalInput;\n unit: TTemporalUnit;\n tz?: string;\n }): number;\n\n abstract compare(opts: {\n value: TTemporalInput;\n other: TTemporalInput;\n unit?: TTemporalUnit;\n tz?: string;\n }): -1 | 0 | 1;\n\n abstract relative(opts: {\n value: TTemporalInput;\n base?: TTemporalInput;\n unit?: TTemporalUnit;\n numeric?: Intl.RelativeTimeFormatNumeric;\n style?: Intl.RelativeTimeFormatStyle;\n tz?: string;\n locale?: string;\n }): string;\n\n abstract durationParts(opts: { milliseconds: number }): ITemporalDurationParts;\n\n abstract formatDuration(opts: {\n milliseconds: number;\n style?: TTemporalDurationStyle;\n /** A clock face instead of words: `HH:mm:ss`, `mm:ss`, `D[d] HH:mm`. The largest token carries the rest. */\n pattern?: string;\n /** Only the largest units that are not zero: `1` writes `2 giờ` for 2 hours 5 minutes. */\n maxUnits?: number;\n locale?: string;\n }): string;\n}\n"]}
1
+ {"version":3,"file":"abstract.js","sourceRoot":"","sources":["../../../../src/modules/temporal/abstract.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAC/D,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,EACL,uBAAuB,EACvB,mBAAmB,IAAI,mBAAmB,EAC1C,aAAa,GACd,MAAM,oBAAoB,CAAC;AAgB5B,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAE1C,MAAM,gBAAgB,GAAG,UAAU,CAAC;AAEpC,6DAA6D;AAC7D,MAAM,WAAW,GAAG,CAAC,kBAAkB,CAAC;AACxC,MAAM,WAAW,GAAG,mBAAmB,CAAC;AAExC,MAAM,oBAAoB,GAAG,GAAG,CAAC;AAEjC,oDAAoD;AACpD,MAAM,YAAY,GAA+C;IAC/D,MAAM,EAAE,EAAE;IACV,WAAW,EAAE,EAAE;IACf,QAAQ,EAAE,CAAC;IAC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AE,GAAG,IAAI,CAAC;QACnC,MAAM,OAAO,GAAG,gBAAgB,CAAC,KAAK,CAAC;YACrC,KAAK,EAAE,gBAAgB,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,CAAC;YAC9C,MAAM,EAAE,MAAM;YACd,IAAI,EAAE,aAAa,CAAC,KAAK;SAC1B,CAAC,CAAC;QACH,OAAO,IAAI,CAAC,UAAU,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC,CAAC;IACjD,CAAC","sourcesContent":["import { HTTP } from '@/common/constants/http';\nimport { BaseHelper } from '@/modules/base';\nimport { getError, isApplicationError } from '@/modules/error';\nimport { IntlTemporalAdapter } from './adapters/intl';\nimport { NativeTemporalAdapter } from './adapters/native';\nimport { TemporalCalendar } from './calendar';\nimport {\n DEFAULT_TEMPORAL_LOCALE,\n DEFAULT_TEMPORAL_TZ as DEFAULT_TEMPORAL_TZ,\n TemporalUnits,\n} from './common/constants';\nimport type {\n TTemporalDurationStyle,\n TTemporalInclusivity,\n TTemporalUnit,\n} from './common/constants';\nimport type {\n ITemporalAdapter,\n ITemporalDurationParts,\n ITemporalLocaleNames,\n ITemporalParts,\n TTemporalFields,\n IZonedTemporalParts,\n TTemporalInput,\n ITemporalHelper,\n} from './common/types';\nimport { TemporalLocale } from './locale';\n\nconst DAY_MILLISECONDS = 86_400_000;\n\n/** 0001-01-01T00:00:00.000Z and 9999-12-31T23:59:59.999Z. */\nconst MIN_INSTANT = -62_135_596_800_000;\nconst MAX_INSTANT = 253_402_300_799_999;\n\nconst MAX_KNOWN_TIME_ZONES = 256;\n\n/** How many entries each `names` list must hold. */\nconst NAME_LENGTHS: Record<keyof ITemporalLocaleNames, number> = {\n months: 12,\n monthsShort: 12,\n weekdays: 7,\n weekdaysShort: 7,\n weekdaysMin: 7,\n meridiem: 2,\n};\n\nconst OUT_OF_RANGE = `outside the years ${TemporalCalendar.MIN_YEAR}-${TemporalCalendar.MAX_YEAR}`; /**\n * The machinery every temporal helper shares: the adapter, the zone and locale it holds, reading a\n * zone's offset, turning wall clocks into instants across daylight-saving gaps and repeats, and the\n * input checks. A helper extends this and supplies the operations in `ITemporalHelper`.\n */\nexport abstract class AbstractTemporalHelper extends BaseHelper implements ITemporalHelper {\n /** Validated once per process: `Intl` answers the same for a zone name every time. */\n protected static readonly knownTzs = new Set<string>();\n\n protected readonly adapter: ITemporalAdapter;\n protected readonly tz: string;\n protected readonly locale: string;\n protected readonly names: Record<string, ITemporalLocaleNames>;\n protected readonly fallback?: string;\n /** Which `names` entry each locale a call wrote in resolved to - `names` never changes after construction. */\n private readonly namesByLocale = new Map<string, ITemporalLocaleNames | undefined>();\n\n /**\n * `locale` (default `en-US`) spells month and weekday names, AM/PM, relative time and durations,\n * unless a call passes its own. `names` replaces `Intl`'s wording for a locale - month and weekday\n * names, the AM/PM marker - keyed by a locale tag; a call in another tag of the same language (`vi`\n * for a `vi-VN` entry) uses it too. `fallback` is what `format` and `formatIntl` write for a value\n * that is not a date when a call gives none; without it, such a value is a 400.\n */\n constructor(opts?: {\n adapter?: ITemporalAdapter;\n tz?: string;\n locale?: string;\n names?: Record<string, ITemporalLocaleNames>;\n fallback?: string;\n scope?: string;\n }) {\n super({ scope: opts?.scope ?? new.target.name });\n\n this.tz = AbstractTemporalHelper.ensureTz({\n tz: opts?.tz ?? DEFAULT_TEMPORAL_TZ,\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n });\n this.locale = AbstractTemporalHelper.ensureLocale({\n locale: opts?.locale ?? DEFAULT_TEMPORAL_LOCALE,\n });\n this.adapter = opts?.adapter ?? AbstractTemporalHelper.defaultAdapter();\n this.names = AbstractTemporalHelper.ensureNames({ names: opts?.names ?? {} });\n this.fallback = opts?.fallback;\n }\n\n /**\n * The zone a `Date`'s local getters use on this runtime - the browser's or the server's. The one\n * place this helper reads the host zone, and only when a wall-clock bridge is not given one.\n */\n static getHostTz(): string {\n return new Intl.DateTimeFormat().resolvedOptions().timeZone;\n }\n\n /** The instant whose wall clock in `to` reads what `value`'s wall clock reads in `from`. */\n protected moveWallClock(opts: { value: TTemporalInput; from: string; to: string }): Date {\n const from = this.resolveTz({ tz: opts.from });\n const to = this.resolveTz({ tz: opts.to });\n const date = this.toDate({ value: opts.value, tz: from });\n\n const wall = TemporalCalendar.wallClockOf({\n parts: this.zonedParts({ epoch: date.getTime(), tz: from }),\n });\n return AbstractTemporalHelper.ensureInstant({\n epoch: this.earliestOf({ parts: wall, tz: to }),\n });\n }\n\n /** Every list the right length, so a bad table fails when the helper is built, not on a screen. */\n protected static ensureNames(opts: {\n names: Record<string, ITemporalLocaleNames>;\n }): Record<string, ITemporalLocaleNames> {\n for (const [locale, names] of Object.entries(opts.names)) {\n AbstractTemporalHelper.ensureLocale({ locale });\n for (const [key, length] of Object.entries(NAME_LENGTHS)) {\n const list: unknown = Reflect.get(names, key);\n if (list === undefined) {\n continue;\n }\n if (\n !Array.isArray(list) ||\n list.length !== length ||\n !list.every((entry) => typeof entry === 'string')\n ) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[TemporalHelper] names['${locale}'].${key} must hold ${length} strings`,\n });\n }\n }\n }\n return opts.names;\n }\n\n /** The wording this helper holds for `locale`, if any. */\n protected namesOf(opts: { locale: string }): ITemporalLocaleNames | undefined {\n const { locale } = opts;\n if (Object.hasOwn(this.names, locale)) {\n return this.names[locale];\n }\n\n if (this.namesByLocale.has(locale)) {\n return this.namesByLocale.get(locale);\n }\n // A malformed tag is the caller's 400, before it reaches `Intl.Locale`.\n AbstractTemporalHelper.ensureLocale({ locale });\n\n // No entry for the exact tag: one for the same language serves - `vi` reads a `vi-VN` entry.\n const language = new Intl.Locale(locale).language;\n const match = Object.keys(this.names).find((key) => new Intl.Locale(key).language === language);\n const names = match === undefined ? undefined : this.names[match];\n this.namesByLocale.set(locale, names);\n return names;\n }\n\n /**\n * The value as a date for a writer: with a fallback - the call's, else the helper's - a value that\n * is not a date answers `null`; without one it is a 400, null included.\n */\n protected readDate(opts: {\n value: TTemporalInput | null | undefined;\n tz: string;\n fallback?: string;\n }): Date | null {\n const { value, tz } = opts;\n if ((opts.fallback ?? this.fallback) !== undefined) {\n return this.tryToDate({ value, tz });\n }\n if (value === null || value === undefined) {\n throw AbstractTemporalHelper.notADate({ value });\n }\n return this.toDate({ value, tz });\n }\n\n /** The runtime's `Temporal` where it has one; `Intl`, which every runtime has, everywhere else. */\n protected static defaultAdapter(): ITemporalAdapter {\n return NativeTemporalAdapter.isTemporalNamespace(Reflect.get(globalThis, 'Temporal'))\n ? new NativeTemporalAdapter()\n : new IntlTemporalAdapter();\n }\n\n protected static ensureLocale(opts: { locale: string }): string {\n TemporalLocale.of({ locale: opts.locale });\n return opts.locale;\n }\n\n /** A parse or input error the caller may treat as \"not a date\"; anything else is a bug and still throws. */\n protected static isRefusal(error: unknown): boolean {\n return isApplicationError(error) && error.statusCode === HTTP.ResultCodes.RS_4.BadRequest;\n }\n\n protected static ensureTz(opts: { tz: string; statusCode: number }): string {\n const { tz, statusCode } = opts;\n if (AbstractTemporalHelper.knownTzs.has(tz)) {\n return tz;\n }\n\n try {\n new Intl.DateTimeFormat('en-US', { timeZone: tz });\n } catch (error) {\n throw getError({\n statusCode,\n message: `[TemporalHelper] unknown time zone '${tz}' | ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n\n if (AbstractTemporalHelper.knownTzs.size < MAX_KNOWN_TIME_ZONES) {\n AbstractTemporalHelper.knownTzs.add(tz);\n }\n return tz;\n }\n\n protected static ensureUnit(opts: { unit: string; amount?: number }): void {\n const { unit, amount } = opts;\n if (!TemporalUnits.isValid(unit)) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: `[TemporalHelper] unknown unit '${unit}' | Supported: ${[...TemporalUnits.SCHEME_SET].join(', ')}`,\n });\n }\n if (amount === undefined) {\n return;\n }\n // Elapsed time takes a fraction (1.5 hours is 90 minutes); a calendar unit has no half.\n const isElapsed = TemporalCalendar.EXACT_UNIT_MILLISECONDS[unit] !== undefined;\n if (isElapsed ? !Number.isFinite(amount) : !Number.isInteger(amount)) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: isElapsed\n ? `[TemporalHelper] amount must be a finite number - received ${amount}`\n : `[TemporalHelper] amount must be an integer for '${unit}' - received ${amount}`,\n });\n }\n }\n\n /** Every result passes here: an overflowing `add` is refused, never an Invalid Date. */\n protected static ensureInstant(opts: { epoch: number }): Date {\n const { epoch } = opts;\n if (!(epoch >= MIN_INSTANT && epoch <= MAX_INSTANT)) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: `[TemporalHelper] ${Number.isNaN(epoch) ? 'invalid date' : OUT_OF_RANGE} - received ${epoch}`,\n });\n }\n return new Date(epoch);\n }\n\n protected static ensureYear(opts: { parts: ITemporalParts }): void {\n if (!TemporalCalendar.isSupportedYear({ year: opts.parts.year })) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: `[TemporalHelper] year ${opts.parts.year} is ${OUT_OF_RANGE}`,\n });\n }\n }\n\n protected resolveTz(opts: { tz?: string }): string {\n return opts.tz === undefined\n ? this.tz\n : AbstractTemporalHelper.ensureTz({\n tz: opts.tz,\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n });\n }\n\n /** The adapter's one answer, rounded: an offset is whole milliseconds, a library's float may not be. */\n protected offsetAt(opts: { epoch: number; tz: string }): number {\n return Math.round(\n this.adapter.getOffsetMilliseconds({ value: new Date(opts.epoch), tz: opts.tz }),\n );\n }\n\n protected zonedParts(opts: { epoch: number; tz: string }): IZonedTemporalParts {\n const parts = TemporalCalendar.wallClockAt({\n epoch: opts.epoch,\n offsetMilliseconds: this.offsetAt(opts),\n });\n AbstractTemporalHelper.ensureYear({ parts });\n return parts;\n }\n\n /**\n * Every instant whose wall clock reads `parts` in the zone, earliest first: one as a rule, two\n * when the clock goes back, none when it jumps forward. `forward` is where a skipped time lands -\n * read with the offset from before the jump, so it moves past the gap.\n */\n protected instantsOf(opts: { parts: ITemporalParts; tz: string }): {\n instants: Array<number>;\n forward: number;\n } {\n const { parts, tz } = opts;\n const local = TemporalCalendar.epochAtOffset({ parts, offsetMilliseconds: 0 });\n const before = this.offsetAt({ epoch: local - DAY_MILLISECONDS, tz });\n const after = this.offsetAt({ epoch: local + DAY_MILLISECONDS, tz });\n\n const offsets = before === after ? [before] : [before, after];\n const instants: Array<number> = [];\n for (const offset of offsets) {\n const candidate = local - offset;\n if (this.offsetAt({ epoch: candidate, tz }) === offset) {\n instants.push(candidate);\n }\n }\n instants.sort((left, right) => left - right);\n\n return { instants, forward: local - before };\n }\n\n /** The instant wall-clock `parts` name: a skipped time moves forward, a repeated one takes the earlier. */\n protected earliestOf(opts: { parts: ITemporalParts; tz: string }): number {\n const { instants, forward } = this.instantsOf(opts);\n return instants[0] ?? forward;\n }\n\n /**\n * `[start, end)` of the unit holding `epoch`. A day or longer starts at its first instant. An hour\n * or less repeats when the clock goes back, so it starts at the latest start not after `epoch`,\n * and ends where the wall clock next shows either the following unit or this one's start again.\n */\n protected unitBounds(opts: { epoch: number; unit: TTemporalUnit; tz: string }): {\n start: number;\n end: number;\n } {\n const { epoch, unit, tz } = opts;\n const startParts = TemporalCalendar.truncate({\n parts: this.zonedParts({ epoch, tz }),\n unit,\n });\n const nextParts = TemporalCalendar.shift({ parts: startParts, amount: 1, unit });\n AbstractTemporalHelper.ensureYear({ parts: nextParts });\n\n const starts = this.instantsOf({ parts: startParts, tz });\n if (TemporalCalendar.EXACT_UNIT_MILLISECONDS[unit] === undefined) {\n const start = starts.instants[0] ?? starts.forward;\n return { start, end: this.earliestOf({ parts: nextParts, tz }) };\n }\n\n const started = starts.instants.filter((instant) => instant <= epoch);\n const start = started.at(-1) ?? starts.instants[0] ?? starts.forward;\n\n const nexts = this.instantsOf({ parts: nextParts, tz });\n const following = nexts.instants.find((instant) => instant > start) ?? nexts.forward;\n const repeated = starts.instants.find((instant) => instant > start);\n return { start, end: repeated === undefined ? following : Math.min(repeated, following) };\n }\n\n getTz(): string {\n return this.tz;\n }\n\n getLocale(): string {\n return this.locale;\n }\n\n now(): Date {\n return new Date();\n }\n\n /** The instant a value names. An ISO string without an offset is read as wall clock in the zone. */\n toDate(opts: { value: TTemporalInput; tz?: string }): Date {\n const { value } = opts;\n\n if (typeof value === 'string') {\n return this.parse({ value, tz: opts.tz });\n }\n if (value instanceof Date) {\n return AbstractTemporalHelper.ensureInstant({ epoch: value.getTime() });\n }\n if (typeof value === 'number') {\n return AbstractTemporalHelper.ensureInstant({ epoch: value });\n }\n\n // `null` above all: read as a number it would be 1970, a date nobody meant.\n throw AbstractTemporalHelper.notADate({ value });\n }\n\n protected static notADate(opts: { value: unknown }) {\n const { value } = opts;\n return getError({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: `[TemporalHelper] not a date - received ${value === null ? 'null' : typeof value}`,\n });\n }\n\n /** `toDate`, answering `null` where `toDate` refuses the value: null, undefined, bad text, NaN. */\n tryToDate(opts: { value: TTemporalInput | null | undefined; tz?: string }): Date | null {\n const { value } = opts;\n // Outside the try: a bad zone is the caller's bug, not an unreadable value.\n const tz = this.resolveTz({ tz: opts.tz });\n if (value === null || value === undefined) {\n return null;\n }\n\n try {\n return this.toDate({ value, tz });\n } catch (error) {\n if (AbstractTemporalHelper.isRefusal(error)) {\n return null;\n }\n throw error;\n }\n }\n\n /** The wall clock the value shows in the zone, with its ISO weekday and UTC offset. */\n parts(opts: { value: TTemporalInput; tz?: string }): IZonedTemporalParts {\n const tz = this.resolveTz({ tz: opts.tz });\n const date = this.toDate({ value: opts.value, tz });\n return this.zonedParts({ epoch: date.getTime(), tz });\n }\n\n /**\n * Fractional months from `other` to `value` (dayjs and moment's month difference): anchored on the\n * date with the later day of the month, whole months by `add`, the rest as a share of the month\n * it falls in.\n */\n protected monthGap(opts: { value: number; other: number; tz: string }): number {\n const { value, other, tz } = opts;\n const valueParts = this.zonedParts({ epoch: value, tz });\n const otherParts = this.zonedParts({ epoch: other, tz });\n if (valueParts.day < otherParts.day) {\n return -this.monthGap({ value: other, other: value, tz });\n }\n\n const whole = (otherParts.year - valueParts.year) * 12 + (otherParts.month - valueParts.month);\n const anchor = this.shiftMonthsFrom({ parts: valueParts, months: whole, tz });\n const isBelow = other - anchor < 0;\n const nextAnchor = this.shiftMonthsFrom({\n parts: valueParts,\n months: whole + (isBelow ? -1 : 1),\n tz,\n });\n const span = isBelow ? anchor - nextAnchor : nextAnchor - anchor;\n\n return -(whole + (other - anchor) / span) || 0;\n }\n\n /** `add` by months without the 1-9999 check: an anchor one month past the range is still a number. */\n protected shiftMonthsFrom(opts: {\n parts: IZonedTemporalParts;\n months: number;\n tz: string;\n }): number {\n const { parts, months, tz } = opts;\n const shifted = TemporalCalendar.shift({\n parts: TemporalCalendar.wallClockOf({ parts }),\n amount: months,\n unit: TemporalUnits.MONTH,\n });\n return this.earliestOf({ parts: shifted, tz });\n }\n\n abstract fromWallClock(opts: { value: TTemporalInput; sourceTz?: string; tz?: string }): Date;\n\n abstract toWallClock(opts: { value: TTemporalInput; targetTz?: string; tz?: string }): Date;\n\n abstract clone(opts: { locale?: string; tz?: string }): ITemporalHelper;\n\n abstract parse(opts: { value: string; pattern?: string; tz?: string }): Date;\n\n abstract tryParse(opts: { value: string; pattern?: string; tz?: string }): Date | null;\n\n abstract isValid(opts: {\n value: TTemporalInput | null | undefined;\n pattern?: string;\n tz?: string;\n }): boolean;\n\n abstract format(opts: {\n value: TTemporalInput | null | undefined;\n pattern?: string;\n tz?: string;\n locale?: string;\n fallback?: string;\n }): string;\n\n abstract formatIntl(opts: {\n value: TTemporalInput;\n options?: Omit<Intl.DateTimeFormatOptions, 'timeZone'>;\n tz?: string;\n locale?: string;\n }): string;\n\n abstract add(opts: {\n value: TTemporalInput;\n amount: number;\n unit: TTemporalUnit;\n tz?: string;\n }): Date;\n\n abstract subtract(opts: {\n value: TTemporalInput;\n amount: number;\n unit: TTemporalUnit;\n tz?: string;\n }): Date;\n\n abstract startOf(opts: { value: TTemporalInput; unit: TTemporalUnit; tz?: string }): Date;\n\n abstract endOf(opts: { value: TTemporalInput; unit: TTemporalUnit; tz?: string }): Date;\n\n abstract isWeekday(opts: { value: TTemporalInput; tz?: string }): boolean;\n\n abstract nextWeekday(opts: { value: TTemporalInput; tz?: string }): Date;\n\n abstract previousWeekday(opts: { value: TTemporalInput; tz?: string }): Date;\n\n abstract set(opts: { value: TTemporalInput; tz?: string } & TTemporalFields): Date;\n\n abstract isBefore(opts: {\n value: TTemporalInput;\n other: TTemporalInput;\n unit?: TTemporalUnit;\n tz?: string;\n }): boolean;\n\n abstract isAfter(opts: {\n value: TTemporalInput;\n other: TTemporalInput;\n unit?: TTemporalUnit;\n tz?: string;\n }): boolean;\n\n abstract isSame(opts: {\n value: TTemporalInput;\n other: TTemporalInput;\n unit?: TTemporalUnit;\n tz?: string;\n }): boolean;\n\n abstract isSameOrBefore(opts: {\n value: TTemporalInput;\n other: TTemporalInput;\n unit?: TTemporalUnit;\n tz?: string;\n }): boolean;\n\n abstract isSameOrAfter(opts: {\n value: TTemporalInput;\n other: TTemporalInput;\n unit?: TTemporalUnit;\n tz?: string;\n }): boolean;\n\n abstract isBetween(opts: {\n value: TTemporalInput;\n from: TTemporalInput;\n to: TTemporalInput;\n unit?: TTemporalUnit;\n inclusivity?: TTemporalInclusivity;\n tz?: string;\n }): boolean;\n\n abstract diff(opts: {\n value: TTemporalInput;\n other: TTemporalInput;\n unit: TTemporalUnit;\n tz?: string;\n }): number;\n\n abstract compare(opts: {\n value: TTemporalInput;\n other: TTemporalInput;\n unit?: TTemporalUnit;\n tz?: string;\n }): -1 | 0 | 1;\n\n abstract relative(opts: {\n value: TTemporalInput;\n base?: TTemporalInput;\n unit?: TTemporalUnit;\n numeric?: Intl.RelativeTimeFormatNumeric;\n style?: Intl.RelativeTimeFormatStyle;\n tz?: string;\n locale?: string;\n }): string;\n\n abstract durationParts(opts: { milliseconds: number }): ITemporalDurationParts;\n\n abstract formatDuration(opts: {\n milliseconds: number;\n style?: TTemporalDurationStyle;\n /** A clock face instead of words: `HH:mm:ss`, `mm:ss`, `D[d] HH:mm`. The largest token carries the rest. */\n pattern?: string;\n /** Only the largest units that are not zero: `1` writes `2 giờ` for 2 hours 5 minutes. */\n maxUnits?: number;\n locale?: string;\n }): string;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"intl.d.ts","sourceRoot":"","sources":["../../../../../src/modules/temporal/adapters/intl.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAOxD;;;;GAIG;AACH,qBAAa,mBAAoB,YAAW,gBAAgB;IAC1D,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,UAAU,CAG9B;IAEJ,gIAAgI;IAChI,OAAO,CAAC,MAAM,CAAC,WAAW;IA4C1B,qBAAqB,CAAC,IAAI,EAAE;QAAE,KAAK,EAAE,IAAI,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,GAAG,MAAM;CA+BjE"}
1
+ {"version":3,"file":"intl.d.ts","sourceRoot":"","sources":["../../../../../src/modules/temporal/adapters/intl.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAOxD;;;;GAIG;AACH,qBAAa,mBAAoB,YAAW,gBAAgB;IAC1D,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,UAAU,CAG9B;IAEJ,gIAAgI;IAChI,OAAO,CAAC,MAAM,CAAC,WAAW;IA8C1B,qBAAqB,CAAC,IAAI,EAAE;QAAE,KAAK,EAAE,IAAI,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,GAAG,MAAM;CA+BjE"}
@@ -37,7 +37,9 @@ export class IntlTemporalAdapter {
37
37
  message: `[IntlTemporalAdapter] unknown time zone '${tz}' | ${error instanceof Error ? error.message : String(error)}`,
38
38
  });
39
39
  }
40
- const commonEra = formatter.formatToParts(new Date(0)).find(part => part.type === 'era')?.value;
40
+ const commonEra = formatter
41
+ .formatToParts(new Date(0))
42
+ .find((part) => part.type === 'era')?.value;
41
43
  // Full: the oldest zone makes room, so zone 257 is not rebuilt on every call.
42
44
  if (IntlTemporalAdapter.formatters.size >= MAX_CACHED_FORMATTERS) {
43
45
  const oldest = IntlTemporalAdapter.formatters.keys().next().value;
@@ -1 +1 @@
1
- {"version":3,"file":"intl.js","sourceRoot":"","sources":["../../../../../src/modules/temporal/adapters/intl.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC/C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAG3C,+FAA+F;AAC/F,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAElC,MAAM,mBAAmB,GAAG,IAAI,CAAC;AAEjC;;;;GAIG;AACH,MAAM,OAAO,mBAAmB;aACN,eAAU,GAAG,IAAI,GAAG,EAGzC,CAAC;IAEJ,gIAAgI;IACxH,MAAM,CAAC,WAAW,CAAC,IAAoB;QAI7C,MAAM,EAAE,EAAE,EAAE,GAAG,IAAI,CAAC;QACpB,MAAM,MAAM,GAAG,mBAAmB,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QACtD,IAAI,MAAM,EAAE,CAAC;YACX,OAAO,MAAM,CAAC;QAChB,CAAC;QAED,IAAI,SAA8B,CAAC;QACnC,IAAI,CAAC;YACH,SAAS,GAAG,IAAI,IAAI,CAAC,cAAc,CAAC,OAAO,EAAE;gBAC3C,QAAQ,EAAE,EAAE;gBACZ,SAAS,EAAE,KAAK;gBAChB,GAAG,EAAE,OAAO;gBACZ,IAAI,EAAE,SAAS;gBACf,KAAK,EAAE,SAAS;gBAChB,GAAG,EAAE,SAAS;gBACd,IAAI,EAAE,SAAS;gBACf,MAAM,EAAE,SAAS;gBACjB,MAAM,EAAE,SAAS;aAClB,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KA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AAG,mBAAmB,CAAC,GAAG,mBAAmB,CAAC,GAAG,mBAAmB,CAAC,CAAC;QACxF,OAAO,SAAS,CAAC,OAAO,EAAE,GAAG,WAAW,CAAC;IAC3C,CAAC","sourcesContent":["import { HTTP } from '@/common/constants/http';\nimport { getError } from '@/modules/error';\nimport type { ITemporalAdapter } from '../common/types';\n\n/** One formatter per zone: building an `Intl.DateTimeFormat` costs far more than using one. */\nconst MAX_CACHED_FORMATTERS = 256;\n\nconst SECOND_MILLISECONDS = 1000;\n\n/**\n * Time zones through `Intl.DateTimeFormat` alone - no `Temporal`, no polyfill, no date library - so\n * it runs in every browser and every server runtime. The offset is the zone's wall clock at the\n * instant, read field by field, minus the instant itself.\n */\nexport class IntlTemporalAdapter implements ITemporalAdapter {\n private static readonly formatters = new Map<\n string,\n { formatter: Intl.DateTimeFormat; commonEra: string | undefined }\n >();\n\n /** The zone's formatter, and how it spells the common era - so any other era is before year 1, whatever the engine calls it. */\n private static formatterOf(opts: { tz: string }): {\n formatter: Intl.DateTimeFormat;\n commonEra: string | undefined;\n } {\n const { tz } = opts;\n const cached = IntlTemporalAdapter.formatters.get(tz);\n if (cached) {\n return cached;\n }\n\n let formatter: Intl.DateTimeFormat;\n try {\n formatter = new Intl.DateTimeFormat('en-US', {\n timeZone: tz,\n hourCycle: 'h23',\n era: 'short',\n year: 'numeric',\n month: 'numeric',\n day: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n second: 'numeric',\n });\n } catch (error) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: `[IntlTemporalAdapter] unknown time zone '${tz}' | ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n\n const commonEra = formatter.formatToParts(new Date(0)).find(part => part.type === 'era')?.value;\n\n // Full: the oldest zone makes room, so zone 257 is not rebuilt on every call.\n if (IntlTemporalAdapter.formatters.size >= MAX_CACHED_FORMATTERS) {\n const oldest = IntlTemporalAdapter.formatters.keys().next().value;\n if (oldest !== undefined) {\n IntlTemporalAdapter.formatters.delete(oldest);\n }\n }\n const entry = { formatter, commonEra };\n IntlTemporalAdapter.formatters.set(tz, entry);\n return entry;\n }\n\n getOffsetMilliseconds(opts: { value: Date; tz: string }): number {\n const { value, tz } = opts;\n const epoch = value.getTime();\n\n const fields = { year: 0, month: 1, day: 1, hour: 0, minute: 0, second: 0 };\n let isBeforeCommonEra = false;\n const { formatter, commonEra } = IntlTemporalAdapter.formatterOf({ tz });\n for (const part of formatter.formatToParts(value)) {\n if (part.type === 'era') {\n isBeforeCommonEra = commonEra !== undefined && part.value !== commonEra;\n continue;\n }\n if (part.type in fields) {\n Reflect.set(fields, part.type, Number(part.value));\n }\n }\n\n // Before year 1 the formatter counts eras: 1 BC is year 0 on the proleptic calendar.\n const year = isBeforeCommonEra ? 1 - fields.year : fields.year;\n // Some engines still write midnight as hour 24 under h23.\n const hour = fields.hour === 24 ? 0 : fields.hour;\n\n const wallClock = new Date(0);\n wallClock.setUTCFullYear(year, fields.month - 1, fields.day);\n wallClock.setUTCHours(hour, fields.minute, fields.second, 0);\n\n // The formatter writes whole seconds: compare against the instant truncated the same way.\n const wholeSecond =\n epoch - (((epoch % SECOND_MILLISECONDS) + SECOND_MILLISECONDS) % SECOND_MILLISECONDS);\n return wallClock.getTime() - wholeSecond;\n }\n}\n"]}
1
+ {"version":3,"file":"intl.js","sourceRoot":"","sources":["../../../../../src/modules/temporal/adapters/intl.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC/C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAG3C,+FAA+F;AAC/F,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAElC,MAAM,mBAAmB,GAAG,IAAI,CAAC;AAEjC;;;;GAIG;AACH,MAAM,OAAO,mBAAmB;aACN,eAAU,GAAG,IAAI,GAAG,EAGzC,CAAC;IAEJ,gIAAgI;IACxH,MAAM,CAAC,WAAW,CAAC,IAAoB;QAI7C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,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC;QAC/D,0DAA0D;QAC1D,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC;QAElD,MAAM,SAAS,GAAG,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC;QAC9B,SAAS,CAAC,cAAc,CAAC,IAAI,EAAE,MAAM,CAAC,KAAK,GAAG,CAAC,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC;QAC7D,SAAS,CAAC,WAAW,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;QAE7D,0FAA0F;QAC1F,MAAM,WAAW,GACf,KAAK,GAAG,CAAC,CAAC,CAAC,KAAK,GAAG,mBAAmB,CAAC,GAAG,mBAAmB,CAAC,GAAG,mBAAmB,CAAC,CAAC;QACxF,OAAO,SAAS,CAAC,OAAO,EAAE,GAAG,WAAW,CAAC;IAC3C,CAAC","sourcesContent":["import { HTTP } from '@/common/constants/http';\nimport { getError } from '@/modules/error';\nimport type { ITemporalAdapter } from '../common/types';\n\n/** One formatter per zone: building an `Intl.DateTimeFormat` costs far more than using one. */\nconst MAX_CACHED_FORMATTERS = 256;\n\nconst SECOND_MILLISECONDS = 1000;\n\n/**\n * Time zones through `Intl.DateTimeFormat` alone - no `Temporal`, no polyfill, no date library - so\n * it runs in every browser and every server runtime. The offset is the zone's wall clock at the\n * instant, read field by field, minus the instant itself.\n */\nexport class IntlTemporalAdapter implements ITemporalAdapter {\n private static readonly formatters = new Map<\n string,\n { formatter: Intl.DateTimeFormat; commonEra: string | undefined }\n >();\n\n /** The zone's formatter, and how it spells the common era - so any other era is before year 1, whatever the engine calls it. */\n private static formatterOf(opts: { tz: string }): {\n formatter: Intl.DateTimeFormat;\n commonEra: string | undefined;\n } {\n const { tz } = opts;\n const cached = IntlTemporalAdapter.formatters.get(tz);\n if (cached) {\n return cached;\n }\n\n let formatter: Intl.DateTimeFormat;\n try {\n formatter = new Intl.DateTimeFormat('en-US', {\n timeZone: tz,\n hourCycle: 'h23',\n era: 'short',\n year: 'numeric',\n month: 'numeric',\n day: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n second: 'numeric',\n });\n } catch (error) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: `[IntlTemporalAdapter] unknown time zone '${tz}' | ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n\n const commonEra = formatter\n .formatToParts(new Date(0))\n .find((part) => part.type === 'era')?.value;\n\n // Full: the oldest zone makes room, so zone 257 is not rebuilt on every call.\n if (IntlTemporalAdapter.formatters.size >= MAX_CACHED_FORMATTERS) {\n const oldest = IntlTemporalAdapter.formatters.keys().next().value;\n if (oldest !== undefined) {\n IntlTemporalAdapter.formatters.delete(oldest);\n }\n }\n const entry = { formatter, commonEra };\n IntlTemporalAdapter.formatters.set(tz, entry);\n return entry;\n }\n\n getOffsetMilliseconds(opts: { value: Date; tz: string }): number {\n const { value, tz } = opts;\n const epoch = value.getTime();\n\n const fields = { year: 0, month: 1, day: 1, hour: 0, minute: 0, second: 0 };\n let isBeforeCommonEra = false;\n const { formatter, commonEra } = IntlTemporalAdapter.formatterOf({ tz });\n for (const part of formatter.formatToParts(value)) {\n if (part.type === 'era') {\n isBeforeCommonEra = commonEra !== undefined && part.value !== commonEra;\n continue;\n }\n if (part.type in fields) {\n Reflect.set(fields, part.type, Number(part.value));\n }\n }\n\n // Before year 1 the formatter counts eras: 1 BC is year 0 on the proleptic calendar.\n const year = isBeforeCommonEra ? 1 - fields.year : fields.year;\n // Some engines still write midnight as hour 24 under h23.\n const hour = fields.hour === 24 ? 0 : fields.hour;\n\n const wallClock = new Date(0);\n wallClock.setUTCFullYear(year, fields.month - 1, fields.day);\n wallClock.setUTCHours(hour, fields.minute, fields.second, 0);\n\n // The formatter writes whole seconds: compare against the instant truncated the same way.\n const wholeSecond =\n epoch - (((epoch % SECOND_MILLISECONDS) + SECOND_MILLISECONDS) % SECOND_MILLISECONDS);\n return wallClock.getTime() - wholeSecond;\n }\n}\n"]}
@@ -78,7 +78,7 @@ export class TemporalLocale {
78
78
  const table = this.tableOf({
79
79
  key: `month-${width}`,
80
80
  size: MONTHS,
81
- read: index => formatter.format(Date.UTC(2024, index, 15)),
81
+ read: (index) => formatter.format(Date.UTC(2024, index, 15)),
82
82
  });
83
83
  return table[month - 1];
84
84
  }
@@ -89,7 +89,7 @@ export class TemporalLocale {
89
89
  const table = this.tableOf({
90
90
  key: `weekday-${width}`,
91
91
  size: WEEKDAYS,
92
- read: index => formatter.format(MONDAY + index * DAY_MILLISECONDS),
92
+ read: (index) => formatter.format(MONDAY + index * DAY_MILLISECONDS),
93
93
  });
94
94
  return table[dayOfWeek - 1];
95
95
  }
@@ -99,9 +99,9 @@ export class TemporalLocale {
99
99
  const table = this.tableOf({
100
100
  key: 'day-period',
101
101
  size: 2,
102
- read: index => formatter
102
+ read: (index) => formatter
103
103
  .formatToParts(Date.UTC(2024, 0, 1, index === 0 ? 1 : NOON + 1))
104
- .find(part => part.type === 'dayPeriod')?.value ?? (index === 0 ? 'AM' : 'PM'),
104
+ .find((part) => part.type === 'dayPeriod')?.value ?? (index === 0 ? 'AM' : 'PM'),
105
105
  });
106
106
  const marker = (opts.meridiem ?? table)[opts.hour < NOON ? 0 : 1];
107
107
  return opts.isLowerCase ? marker.toLocaleLowerCase(this.locale) : marker;
@@ -1 +1 @@
1
- {"version":3,"file":"locale.js","sourceRoot":"","sources":["../../../../../src/modules/temporal/locale/locale.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC/C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAG3C,0FAA0F;AAC1F,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAE9B,MAAM,M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MAAM,IAAI,GAAG,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC;QACzB,IAAI,CAAC,cAAc,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,KAAK,GAAG,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;QAC5D,OAAO,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAChC,CAAC","sourcesContent":["import { HTTP } from '@/common/constants/http';\nimport { getError } from '@/modules/error';\nimport type { ITemporalParts } from '../common/types';\n\n/** A service writes a handful of locales; capped so caller-fed locales cannot grow it. */\nconst MAX_CACHED_LOCALES = 32;\n\nconst MONTHS = 12;\nconst WEEKDAYS = 7;\nconst NOON = 12;\n\n/** A Monday: ISO weekday `n` is this date plus `n - 1` days. */\nconst MONDAY = Date.UTC(2024, 0, 1);\nconst DAY_MILLISECONDS = 86_400_000;\n\n/**\n * Month and weekday names, the AM/PM marker and the written date of one locale, as `Intl` spells\n * them. Every table is read once, on first use, from a fixed UTC date: the names belong to the\n * calendar, not to a time zone, so the wall clock is formatted as if it were UTC.\n */\nexport class TemporalLocale {\n private static readonly locales = new Map<string, TemporalLocale>();\n\n private readonly locale: string;\n private readonly tables = new Map<string, Array<string>>();\n private readonly formatters = new Map<string, Intl.DateTimeFormat>();\n\n private constructor(opts: { locale: string }) {\n this.locale = opts.locale;\n }\n\n /** The locale's names; a malformed tag is a 400. */\n static of(opts: { locale: string }): TemporalLocale {\n const { locale } = opts;\n const cached = TemporalLocale.locales.get(locale);\n if (cached) {\n return cached;\n }\n\n try {\n Intl.getCanonicalLocales(locale);\n } catch (error) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: `[TemporalLocale] invalid locale '${locale}' | ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n\n // Full: the oldest locale makes room, so the 33rd locale is not rebuilt on every call.\n if (TemporalLocale.locales.size >= MAX_CACHED_LOCALES) {\n const oldest = TemporalLocale.locales.keys().next().value;\n if (oldest !== undefined) {\n TemporalLocale.locales.delete(oldest);\n }\n }\n const created = new TemporalLocale({ locale });\n TemporalLocale.locales.set(locale, created);\n return created;\n }\n\n private formatterOf(opts: Intl.DateTimeFormatOptions): Intl.DateTimeFormat {\n const key = JSON.stringify(opts);\n const cached = this.formatters.get(key);\n if (cached) {\n return cached;\n }\n\n // Gregorian always: the numeric tokens are, and a name from another calendar would sit beside them.\n const formatter = new Intl.DateTimeFormat(this.locale, {\n ...opts,\n calendar: 'gregory',\n timeZone: 'UTC',\n });\n this.formatters.set(key, formatter);\n return formatter;\n }\n\n private tableOf(opts: {\n key: string;\n size: number;\n read: (index: number) => string;\n }): Array<string> {\n const cached = this.tables.get(opts.key);\n if (cached) {\n return cached;\n }\n\n const table = Array.from({ length: opts.size }, (_, index) => opts.read(index));\n this.tables.set(opts.key, table);\n return table;\n }\n\n /** `month` is 1-12. */\n monthName(opts: { month: number; width: 'short' | 'long' }): string {\n const { month, width } = opts;\n const formatter = this.formatterOf({ month: width });\n const table = this.tableOf({\n key: `month-${width}`,\n size: MONTHS,\n read: index => formatter.format(Date.UTC(2024, index, 15)),\n });\n return table[month - 1];\n }\n\n /** `dayOfWeek` is ISO: 1 Monday - 7 Sunday. */\n weekdayName(opts: { dayOfWeek: number; width: 'narrow' | 'short' | 'long' }): string {\n const { dayOfWeek, width } = opts;\n const formatter = this.formatterOf({ weekday: width });\n const table = this.tableOf({\n key: `weekday-${width}`,\n size: WEEKDAYS,\n read: index => formatter.format(MONDAY + index * DAY_MILLISECONDS),\n });\n return table[dayOfWeek - 1];\n }\n\n /** The AM or PM marker the locale writes for `hour` (0-23), lower-cased by the locale's own rules when asked. */\n dayPeriod(opts: {\n hour: number;\n meridiem?: readonly [string, string];\n isLowerCase?: boolean;\n }): string {\n const formatter = this.formatterOf({ hour: 'numeric', hourCycle: 'h12' });\n const table = this.tableOf({\n key: 'day-period',\n size: 2,\n read: index =>\n formatter\n .formatToParts(Date.UTC(2024, 0, 1, index === 0 ? 1 : NOON + 1))\n .find(part => part.type === 'dayPeriod')?.value ?? (index === 0 ? 'AM' : 'PM'),\n });\n const marker = (opts.meridiem ?? table)[opts.hour < NOON ? 0 : 1];\n return opts.isLowerCase ? marker.toLocaleLowerCase(this.locale) : marker;\n }\n\n /** The wall-clock date the way the locale writes it: `numeric` is `10/14/2026`, `long` is `October 14, 2026`. */\n writtenDate(opts: { parts: ITemporalParts; style: 'numeric' | 'long' }): string {\n const { parts, style } = opts;\n const formatter =\n style === 'numeric'\n ? this.formatterOf({ year: 'numeric', month: '2-digit', day: '2-digit' })\n : this.formatterOf({ dateStyle: 'long' });\n\n const date = new Date(0);\n date.setUTCFullYear(parts.year, parts.month - 1, parts.day);\n return formatter.format(date);\n }\n}\n"]}
1
+ {"version":3,"file":"locale.js","sourceRoot":"","sources":["../../../../../src/modules/temporal/locale/locale.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC/C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAG3C,0FAA0F;AAC1F,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAE9B,MAAM,MAAM,GAAG,EAAE,CAAC;AAClB,MAAM,QAAQ,GAAG,CAAC,CAAC;AACnB,MAAM,IAAI,GAAG,EAAE,CAAC;AAEhB,gEAAgE;AAChE,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;AACpC,MAAM,gBAAgB,GAAG,UAAU,CAAC;AAEpC;;;;GAIG;AACH,MAAM,OAAO,cAAc;aACD,YAAO,GAAG,IAAI,GAAG,EAA0B,AAApC,CAAqC;IAMpE,YAAoB,IAAwB;QAH3B,WAAM,GAAG,IAAI,GAAG,EAAyB,CAAC;QAC1C,eAAU,GAAG,IAAI,GAAG,EAA+B,CAAC;QAGnE,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;IAC5B,CAAC;IAED,oDAAoD;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AC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;SACrF,CAAC,CAAC;QACH,MAAM,MAAM,GAAG,CAAC,IAAI,CAAC,QAAQ,IAAI,KAAK,CAAC,CAAC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QAClE,OAAO,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC,iBAAiB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;IAC3E,CAAC;IAED,iHAAiH;IACjH,WAAW,CAAC,IAA0D;QACpE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC;QAC9B,MAAM,SAAS,GACb,KAAK,KAAK,SAAS;YACjB,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,SAAS,EAAE,GAAG,EAAE,SAAS,EAAE,CAAC;YACzE,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC,CAAC;QAE9C,MAAM,IAAI,GAAG,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC;QACzB,IAAI,CAAC,cAAc,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,KAAK,GAAG,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;QAC5D,OAAO,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAChC,CAAC","sourcesContent":["import { HTTP } from '@/common/constants/http';\nimport { getError } from '@/modules/error';\nimport type { ITemporalParts } from '../common/types';\n\n/** A service writes a handful of locales; capped so caller-fed locales cannot grow it. */\nconst MAX_CACHED_LOCALES = 32;\n\nconst MONTHS = 12;\nconst WEEKDAYS = 7;\nconst NOON = 12;\n\n/** A Monday: ISO weekday `n` is this date plus `n - 1` days. */\nconst MONDAY = Date.UTC(2024, 0, 1);\nconst DAY_MILLISECONDS = 86_400_000;\n\n/**\n * Month and weekday names, the AM/PM marker and the written date of one locale, as `Intl` spells\n * them. Every table is read once, on first use, from a fixed UTC date: the names belong to the\n * calendar, not to a time zone, so the wall clock is formatted as if it were UTC.\n */\nexport class TemporalLocale {\n private static readonly locales = new Map<string, TemporalLocale>();\n\n private readonly locale: string;\n private readonly tables = new Map<string, Array<string>>();\n private readonly formatters = new Map<string, Intl.DateTimeFormat>();\n\n private constructor(opts: { locale: string }) {\n this.locale = opts.locale;\n }\n\n /** The locale's names; a malformed tag is a 400. */\n static of(opts: { locale: string }): TemporalLocale {\n const { locale } = opts;\n const cached = TemporalLocale.locales.get(locale);\n if (cached) {\n return cached;\n }\n\n try {\n Intl.getCanonicalLocales(locale);\n } catch (error) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message: `[TemporalLocale] invalid locale '${locale}' | ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n\n // Full: the oldest locale makes room, so the 33rd locale is not rebuilt on every call.\n if (TemporalLocale.locales.size >= MAX_CACHED_LOCALES) {\n const oldest = TemporalLocale.locales.keys().next().value;\n if (oldest !== undefined) {\n TemporalLocale.locales.delete(oldest);\n }\n }\n const created = new TemporalLocale({ locale });\n TemporalLocale.locales.set(locale, created);\n return created;\n }\n\n private formatterOf(opts: Intl.DateTimeFormatOptions): Intl.DateTimeFormat {\n const key = JSON.stringify(opts);\n const cached = this.formatters.get(key);\n if (cached) {\n return cached;\n }\n\n // Gregorian always: the numeric tokens are, and a name from another calendar would sit beside them.\n const formatter = new Intl.DateTimeFormat(this.locale, {\n ...opts,\n calendar: 'gregory',\n timeZone: 'UTC',\n });\n this.formatters.set(key, formatter);\n return formatter;\n }\n\n private tableOf(opts: {\n key: string;\n size: number;\n read: (index: number) => string;\n }): Array<string> {\n const cached = this.tables.get(opts.key);\n if (cached) {\n return cached;\n }\n\n const table = Array.from({ length: opts.size }, (_, index) => opts.read(index));\n this.tables.set(opts.key, table);\n return table;\n }\n\n /** `month` is 1-12. */\n monthName(opts: { month: number; width: 'short' | 'long' }): string {\n const { month, width } = opts;\n const formatter = this.formatterOf({ month: width });\n const table = this.tableOf({\n key: `month-${width}`,\n size: MONTHS,\n read: (index) => formatter.format(Date.UTC(2024, index, 15)),\n });\n return table[month - 1];\n }\n\n /** `dayOfWeek` is ISO: 1 Monday - 7 Sunday. */\n weekdayName(opts: { dayOfWeek: number; width: 'narrow' | 'short' | 'long' }): string {\n const { dayOfWeek, width } = opts;\n const formatter = this.formatterOf({ weekday: width });\n const table = this.tableOf({\n key: `weekday-${width}`,\n size: WEEKDAYS,\n read: (index) => formatter.format(MONDAY + index * DAY_MILLISECONDS),\n });\n return table[dayOfWeek - 1];\n }\n\n /** The AM or PM marker the locale writes for `hour` (0-23), lower-cased by the locale's own rules when asked. */\n dayPeriod(opts: {\n hour: number;\n meridiem?: readonly [string, string];\n isLowerCase?: boolean;\n }): string {\n const formatter = this.formatterOf({ hour: 'numeric', hourCycle: 'h12' });\n const table = this.tableOf({\n key: 'day-period',\n size: 2,\n read: (index) =>\n formatter\n .formatToParts(Date.UTC(2024, 0, 1, index === 0 ? 1 : NOON + 1))\n .find((part) => part.type === 'dayPeriod')?.value ?? (index === 0 ? 'AM' : 'PM'),\n });\n const marker = (opts.meridiem ?? table)[opts.hour < NOON ? 0 : 1];\n return opts.isLowerCase ? marker.toLocaleLowerCase(this.locale) : marker;\n }\n\n /** The wall-clock date the way the locale writes it: `numeric` is `10/14/2026`, `long` is `October 14, 2026`. */\n writtenDate(opts: { parts: ITemporalParts; style: 'numeric' | 'long' }): string {\n const { parts, style } = opts;\n const formatter =\n style === 'numeric'\n ? this.formatterOf({ year: 'numeric', month: '2-digit', day: '2-digit' })\n : this.formatterOf({ dateStyle: 'long' });\n\n const date = new Date(0);\n date.setUTCFullYear(parts.year, parts.month - 1, parts.day);\n return formatter.format(date);\n }\n}\n"]}
@@ -29,10 +29,10 @@ export class TreeBuilder extends BaseHelper {
29
29
  }
30
30
  /** `includePath: true` returns the chain from the root alongside each leaf - recomputing it from the tree afterward would cost a second full traversal. */
31
31
  static leaves(opts) {
32
- return TreeBuilder.collect({ ...opts, matches: node => node.children.length === 0 });
32
+ return TreeBuilder.collect({ ...opts, matches: (node) => node.children.length === 0 });
33
33
  }
34
34
  static nonLeaves(opts) {
35
- return TreeBuilder.collect({ ...opts, matches: node => node.children.length > 0 });
35
+ return TreeBuilder.collect({ ...opts, matches: (node) => node.children.length > 0 });
36
36
  }
37
37
  static collect(opts) {
38
38
  const { root, includePath, matches } = opts;
@@ -1 +1 @@
1
- {"version":3,"file":"builder.js","sourceRoot":"","sources":["../../../../src/modules/tree/builder.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAE5C;;;GAGG;AACH,MAAM,OAAO,WAAY,SAAQ,UAAU;IACzC;;;;OAIG;IACH,MAAM,CAAC,KAAK,CAAC,KAAK,CAAI,IAAsB;QAC1C,MAAM,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;QAChD,MAAM,IAAI,GAAG,IAAI,GAAG,CAAU,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;QAEnD,MAAM,SAAS,GAAG,KAAK,EAAE,KAAQ,EAAyB,EAAE;YAC1D,MAAM,WAAW,GAAG,MAAM,WAAW,CAAC,KAAK,CAAC,CAAC;YAC7C,MAAM,QAAQ,GAAmB,EAAE,CAAC;YAEpC,KAAK,MAAM,UAAU,IAAI,WAAW,EAAE,CAAC;gBACrC,MAAM,GAAG,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;gBAC/B,IAAI,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC;oBAClB,SAAS;gBACX,CAAC;gBAED,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;gBACd,QAAQ,CAAC,IAAI,CAAC,MAAM,SAAS,CAAC,U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CAAC;QACL,CAAC,CAAC;QAEF,IAAI,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;QACf,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC1B,CAAC;CACF","sourcesContent":["import type {\n IBuildOptions,\n ILeavesOptions,\n INodeWithPath,\n IPrintOptions,\n ITreeNode,\n} from './common/types';\nimport { BaseHelper } from '@/modules/base';\n\n/**\n * Static members call each other through the class name (`TreeBuilder.xxx`), never `this` - a\n * detached static method loses its `this` binding.\n */\nexport class TreeBuilder extends BaseHelper {\n /**\n * Always async, even if `getChildren` returns a plain array, since real fetchers hit a\n * repository. De-duplicates by `getKey` rather than tracking depth - see\n * {@link IBuildOptions.getKey} for why a repeated key skips silently instead of throwing.\n */\n static async build<T>(opts: IBuildOptions<T>): Promise<ITreeNode<T>> {\n const { rootValue, getChildren, getKey } = opts;\n const seen = new Set<unknown>([getKey(rootValue)]);\n\n const buildNode = async (value: T): Promise<ITreeNode<T>> => {\n const childValues = await getChildren(value);\n const children: ITreeNode<T>[] = [];\n\n for (const childValue of childValues) {\n const key = getKey(childValue);\n if (seen.has(key)) {\n continue;\n }\n\n seen.add(key);\n children.push(await buildNode(childValue));\n }\n\n return { value, children };\n };\n\n return buildNode(rootValue);\n }\n\n static leaves<T>(opts: { root: ITreeNode<T>; includePath: true }): INodeWithPath<T>[];\n static leaves<T>(opts: { root: ITreeNode<T>; includePath?: false }): ITreeNode<T>[];\n /** `includePath: true` returns the chain from the root alongside each leaf - recomputing it from the tree afterward would cost a second full traversal. */\n static leaves<T>(opts: ILeavesOptions<T>): ITreeNode<T>[] | INodeWithPath<T>[] {\n return TreeBuilder.collect({ ...opts, matches: node => node.children.length === 0 });\n }\n\n static nonLeaves<T>(opts: { root: ITreeNode<T>; includePath: true }): INodeWithPath<T>[];\n static nonLeaves<T>(opts: { root: ITreeNode<T>; includePath?: false }): ITreeNode<T>[];\n static nonLeaves<T>(opts: ILeavesOptions<T>): ITreeNode<T>[] | INodeWithPath<T>[] {\n return TreeBuilder.collect({ ...opts, matches: node => node.children.length > 0 });\n }\n\n private static collect<T>(opts: {\n root: ITreeNode<T>;\n includePath?: boolean;\n matches: (node: ITreeNode<T>) => boolean;\n }): ITreeNode<T>[] | INodeWithPath<T>[] {\n const { root, includePath, matches } = opts;\n\n if (!includePath) {\n const results: ITreeNode<T>[] = [];\n\n const walk = (node: ITreeNode<T>): void => {\n if (matches(node)) {\n results.push(node);\n }\n\n for (const child of node.children) {\n walk(child);\n }\n };\n\n walk(root);\n return results;\n }\n\n const results: INodeWithPath<T>[] = [];\n\n const walk = (node: ITreeNode<T>, path: T[]): void => {\n const nextPath = [...path, node.value];\n if (matches(node)) {\n results.push({ node, path: nextPath });\n }\n\n for (const child of node.children) {\n walk(child, nextPath);\n }\n };\n\n walk(root, []);\n return results;\n }\n\n /** Renders an ASCII tree, root on the first line, `├──`/`└──` branches below - useful for debug logs, not for parsing. */\n static print<T>(opts: IPrintOptions<T>): string {\n const { root, formatValue = (value: T) => String(value) } = opts;\n const lines: string[] = [formatValue(root.value)];\n\n const walk = (node: ITreeNode<T>, prefix: string): void => {\n node.children.forEach((child, index) => {\n const isLast = index === node.children.length - 1;\n lines.push(`${prefix}${isLast ? '└── ' : '├── '}${formatValue(child.value)}`);\n walk(child, `${prefix}${isLast ? ' ' : '│ '}`);\n });\n };\n\n walk(root, '');\n return lines.join('\\n');\n }\n}\n"]}
1
+ {"version":3,"file":"builder.js","sourceRoot":"","sources":["../../../../src/modules/tree/builder.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAE5C;;;GAGG;AACH,MAAM,OAAO,WAAY,SAAQ,UAAU;IACzC;;;;OAIG;IACH,MAAM,CAAC,KAAK,CAAC,KAAK,CAAI,IAAsB;QAC1C,MAAM,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;QAChD,MAAM,IAAI,GAAG,IAAI,GAAG,CAA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AG,CAAC,IAAkB,EAAE,MAAc,EAAQ,EAAE;YACxD,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;gBACrC,MAAM,MAAM,GAAG,KAAK,KAAK,IAAI,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC;gBAClD,KAAK,CAAC,IAAI,CAAC,GAAG,MAAM,GAAG,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,GAAG,WAAW,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;gBAC9E,IAAI,CAAC,KAAK,EAAE,GAAG,MAAM,GAAG,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC;YACtD,CAAC,CAAC,CAAC;QACL,CAAC,CAAC;QAEF,IAAI,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;QACf,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC1B,CAAC;CACF","sourcesContent":["import type {\n IBuildOptions,\n ILeavesOptions,\n INodeWithPath,\n IPrintOptions,\n ITreeNode,\n} from './common/types';\nimport { BaseHelper } from '@/modules/base';\n\n/**\n * Static members call each other through the class name (`TreeBuilder.xxx`), never `this` - a\n * detached static method loses its `this` binding.\n */\nexport class TreeBuilder extends BaseHelper {\n /**\n * Always async, even if `getChildren` returns a plain array, since real fetchers hit a\n * repository. De-duplicates by `getKey` rather than tracking depth - see\n * {@link IBuildOptions.getKey} for why a repeated key skips silently instead of throwing.\n */\n static async build<T>(opts: IBuildOptions<T>): Promise<ITreeNode<T>> {\n const { rootValue, getChildren, getKey } = opts;\n const seen = new Set<unknown>([getKey(rootValue)]);\n\n const buildNode = async (value: T): Promise<ITreeNode<T>> => {\n const childValues = await getChildren(value);\n const children: ITreeNode<T>[] = [];\n\n for (const childValue of childValues) {\n const key = getKey(childValue);\n if (seen.has(key)) {\n continue;\n }\n\n seen.add(key);\n children.push(await buildNode(childValue));\n }\n\n return { value, children };\n };\n\n return buildNode(rootValue);\n }\n\n static leaves<T>(opts: { root: ITreeNode<T>; includePath: true }): INodeWithPath<T>[];\n static leaves<T>(opts: { root: ITreeNode<T>; includePath?: false }): ITreeNode<T>[];\n /** `includePath: true` returns the chain from the root alongside each leaf - recomputing it from the tree afterward would cost a second full traversal. */\n static leaves<T>(opts: ILeavesOptions<T>): ITreeNode<T>[] | INodeWithPath<T>[] {\n return TreeBuilder.collect({ ...opts, matches: (node) => node.children.length === 0 });\n }\n\n static nonLeaves<T>(opts: { root: ITreeNode<T>; includePath: true }): INodeWithPath<T>[];\n static nonLeaves<T>(opts: { root: ITreeNode<T>; includePath?: false }): ITreeNode<T>[];\n static nonLeaves<T>(opts: ILeavesOptions<T>): ITreeNode<T>[] | INodeWithPath<T>[] {\n return TreeBuilder.collect({ ...opts, matches: (node) => node.children.length > 0 });\n }\n\n private static collect<T>(opts: {\n root: ITreeNode<T>;\n includePath?: boolean;\n matches: (node: ITreeNode<T>) => boolean;\n }): ITreeNode<T>[] | INodeWithPath<T>[] {\n const { root, includePath, matches } = opts;\n\n if (!includePath) {\n const results: ITreeNode<T>[] = [];\n\n const walk = (node: ITreeNode<T>): void => {\n if (matches(node)) {\n results.push(node);\n }\n\n for (const child of node.children) {\n walk(child);\n }\n };\n\n walk(root);\n return results;\n }\n\n const results: INodeWithPath<T>[] = [];\n\n const walk = (node: ITreeNode<T>, path: T[]): void => {\n const nextPath = [...path, node.value];\n if (matches(node)) {\n results.push({ node, path: nextPath });\n }\n\n for (const child of node.children) {\n walk(child, nextPath);\n }\n };\n\n walk(root, []);\n return results;\n }\n\n /** Renders an ASCII tree, root on the first line, `├──`/`└──` branches below - useful for debug logs, not for parsing. */\n static print<T>(opts: IPrintOptions<T>): string {\n const { root, formatValue = (value: T) => String(value) } = opts;\n const lines: string[] = [formatValue(root.value)];\n\n const walk = (node: ITreeNode<T>, prefix: string): void => {\n node.children.forEach((child, index) => {\n const isLast = index === node.children.length - 1;\n lines.push(`${prefix}${isLast ? '└── ' : '├── '}${formatValue(child.value)}`);\n walk(child, `${prefix}${isLast ? ' ' : '│ '}`);\n });\n };\n\n walk(root, '');\n return lines.join('\\n');\n }\n}\n"]}
@@ -203,7 +203,7 @@ export class OpaqueUidHelper extends BaseHelper {
203
203
  ? alphabet.toLowerCase()
204
204
  : alphabet;
205
205
  const removed = new Set(exclude);
206
- const resolved = [...new Set(folded)].filter(character => !removed.has(character)).join('');
206
+ const resolved = [...new Set(folded)].filter((character) => !removed.has(character)).join('');
207
207
  if (resolved.length < MIN_UID_ALPHABET_SIZE) {
208
208
  throw getError({
209
209
  statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
@@ -261,7 +261,7 @@ export class OpaqueUidHelper extends BaseHelper {
261
261
  message: `[${OpaqueUidHelper.name}] delimiter is enabled but carries no value`,
262
262
  });
263
263
  }
264
- const shared = [...new Set(value)].filter(character => alphabet.includes(character));
264
+ const shared = [...new Set(value)].filter((character) => alphabet.includes(character));
265
265
  if (shared.length > 0) {
266
266
  throw getError({
267
267
  statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
@@ -1 +1 @@
1
- {"version":3,"file":"opaque.js","sourceRoot":"","sources":["../../../../src/modules/uid/opaque.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAE1C,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AACpC,OAAO,EACL,qBAAqB,EACrB,kBAAkB,EAClB,wBAAwB,EACxB,qBAAqB,EACrB,YAAY,EACZ,YAAY,GACb,MAAM,oBAAoB,CAAC;AAI5B,uLAAuL;AACvL,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAE5B,oKAAoK;AACpK,MAAM,aAAa,GAAG,CAAC,KAAc,EAAiC,EAAE;IACtE,OAAO,OAAQ,KAAiD,EAAE,IA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EAAE,CAAC,kEAAkE;aAChL,CAAC,CAAC;QACL,CAAC;QAED,OAAO,KAAK,CAAC;IACf,CAAC;CACF","sourcesContent":["import { HTTP } from '@/common/constants';\nimport type { ValueOrPromise } from '@/common/types';\nimport { BaseHelper } from '../base';\nimport { getError } from '../error';\nimport {\n DEFAULT_UID_DELIMITER,\n DEFAULT_UID_LENGTH,\n DEFAULT_UID_MAX_ATTEMPTS,\n MIN_UID_ALPHABET_SIZE,\n UidAlphabets,\n UidCaseForms,\n} from './common/constants';\nimport type { TUidCaseForm } from './common/constants';\nimport type { INextOpaqueUidOptions, IOpaqueUidOptions, IUidSegment } from './common/types';\n\n/** How many random bytes to draw per refill, per remaining character. Rejection throws some away, so asking for exactly `length` would round-trip to the entropy source repeatedly. */\nconst SAMPLING_OVERDRAW = 2;\n\n/** Local, not `@/utilities/promise.utility`: that module imports the logger BARREL, which reaches `node:module` and would take this browser-pure module with it. */\nconst isPromiseLike = (value: unknown): value is PromiseLike<boolean> => {\n return typeof (value as PromiseLike<boolean> | null | undefined)?.then === 'function';\n};\n\n/**\n * Fixed-length opaque ids, optionally prefixed - the counterpart to `SnowflakeUidHelper`.\n *\n * OPAQUE is the difference that matters, not the randomness. A Snowflake id is TRANSPARENT: its own\n * `parseId()` reads back the exact millisecond it was minted and the worker that minted it. That is\n * what you want in a log and not what you want on an invoice. Nothing can be read out of an id from\n * here. The cost is the ordering, which a Snowflake gives an index for free.\n *\n * `length` counts the BODY only. A prefix and a delimiter sit in front of it, so the finished string\n * is `prefix + delimiter + length` characters.\n *\n * Read {@link DEFAULT_UID_LENGTH} before accepting the default: six characters is an airline record\n * locator, and it needs the same scoping and retry that airlines give one.\n */\nexport class OpaqueUidHelper extends BaseHelper {\n private readonly alphabet: string;\n private readonly length: number;\n private readonly prefix: string;\n private readonly delimiter: string;\n\n /** Rejection mask: the smallest `2^n - 1` that covers every alphabet index. A plain `byte % size` would favour the first `256 % size` characters, which is a bias a caller cannot see and cannot undo. */\n private readonly mask: number;\n\n constructor(opts?: IOpaqueUidOptions) {\n super({ scope: OpaqueUidHelper.name });\n\n const caseForm = opts?.caseForm ?? UidCaseForms.UPPER;\n OpaqueUidHelper.assertKnownCaseForm({ caseForm });\n\n this.alphabet = OpaqueUidHelper.resolveAlphabet({\n alphabet: opts?.alphabet ?? UidAlphabets.CROCKFORD,\n exclude: opts?.exclude ?? '',\n caseForm,\n });\n\n this.length = opts?.length ?? DEFAULT_UID_LENGTH;\n if (!Number.isInteger(this.length) || this.length < 1) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] length must be a positive integer | value: ${this.length}`,\n });\n }\n\n this.prefix = OpaqueUidHelper.resolvePrefix({ prefix: opts?.prefix, caseForm });\n this.delimiter = OpaqueUidHelper.resolveDelimiter({\n delimiter: opts?.delimiter,\n hasPrefix: this.prefix.length > 0,\n alphabet: this.alphabet,\n });\n\n this.mask = (1 << Math.ceil(Math.log2(this.alphabet.length))) - 1;\n }\n\n /**\n * `prefix` replaces the configured value for this call and turns the prefix on for it; the\n * delimiter follows its own switch.\n *\n * `isAvailable` redraws until it accepts an id, up to `maxAttempts`. It LOWERS the collision rate,\n * it does not remove it: against a database the check and the insert are two statements, and\n * another request can take the id in between. The column still needs a unique index, and the\n * insert still needs to regenerate on violation.\n */\n nextId(opts?: INextOpaqueUidOptions<boolean>): string;\n nextId(opts: INextOpaqueUidOptions<Promise<boolean>>): Promise<string>;\n nextId(opts: INextOpaqueUidOptions): ValueOrPromise<string>;\n nextId(opts?: INextOpaqueUidOptions): ValueOrPromise<string> {\n const head = this.resolveHead({ prefix: opts?.prefix });\n\n const isAvailable = opts?.isAvailable;\n if (!isAvailable) {\n // Refused rather than ignored: without a check there is exactly ONE draw, so a caller who set\n // `maxAttempts` has configured a retry that cannot happen and has no way to notice.\n if (opts?.maxAttempts !== undefined) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}][nextId] maxAttempts has no effect without \\`isAvailable\\` | Nothing rejects a draw, so there is only ever one`,\n });\n }\n\n return `${head}${this.randomBody()}`;\n }\n\n const maxAttempts = OpaqueUidHelper.resolveMaxAttempts({ maxAttempts: opts?.maxAttempts });\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n const id = `${head}${this.randomBody()}`;\n const verdict = isAvailable(id);\n\n // The first PENDING verdict decides the shape of the whole call. Everything before it already\n // resolved, so a synchronous check never allocates a promise and `nextId()` stays a string.\n if (isPromiseLike(verdict)) {\n return this.continueAsync({ head, isAvailable, maxAttempts, attempt, id, verdict });\n }\n\n if (verdict) {\n return id;\n }\n }\n\n throw this.buildExhaustedError({ maxAttempts });\n }\n\n /** Entered only once a verdict came back pending; every later draw is awaited from here. */\n private async continueAsync(opts: {\n head: string;\n isAvailable: (id: string) => ValueOrPromise<boolean>;\n maxAttempts: number;\n attempt: number;\n id: string;\n verdict: PromiseLike<boolean>;\n }): Promise<string> {\n const { head, isAvailable, maxAttempts, attempt, id, verdict } = opts;\n\n if (await verdict) {\n return id;\n }\n\n for (let next = attempt + 1; next <= maxAttempts; next++) {\n const candidate = `${head}${this.randomBody()}`;\n\n if (await isAvailable(candidate)) {\n return candidate;\n }\n }\n\n throw this.buildExhaustedError({ maxAttempts });\n }\n\n private resolveHead(opts: { prefix?: string }): string {\n const override = opts.prefix;\n\n if (override === '') {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}][nextId] An empty prefix is not how a prefix is turned off | Construct with \\`prefix: { enable: false }\\``,\n });\n }\n\n const prefix = override ?? this.prefix;\n return prefix.length > 0 ? `${prefix}${this.delimiter}` : '';\n }\n\n private static resolveMaxAttempts(opts: { maxAttempts?: number }): number {\n const maxAttempts = opts.maxAttempts ?? DEFAULT_UID_MAX_ATTEMPTS;\n\n if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}][nextId] maxAttempts must be a positive integer | value: ${maxAttempts}`,\n });\n }\n\n return maxAttempts;\n }\n\n /** Bounded rather than endless: repeated rejection means the space is full, and a caller waiting forever learns that far later than a caller holding this error. */\n private buildExhaustedError(opts: { maxAttempts: number }) {\n return getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}][nextId] No available id after ${opts.maxAttempts} attempts | length: ${this.length} | alphabet: ${this.alphabet.length} | The space is crowded - raise \\`length\\``,\n });\n }\n\n /** The alphabet actually in use, after the case fold and every exclusion - what `length` is measured against. */\n getAlphabet(): string {\n return this.alphabet;\n }\n\n private randomBody(): string {\n const size = this.alphabet.length;\n let body = '';\n\n while (body.length < this.length) {\n const bytes = OpaqueUidHelper.randomBytes({\n count: (this.length - body.length) * SAMPLING_OVERDRAW,\n });\n\n for (const byte of bytes) {\n const index = byte & this.mask;\n\n // Rejection, not wrap-around: an index past the alphabet is discarded so every character\n // stays equally likely.\n if (index >= size) {\n continue;\n }\n\n body += this.alphabet[index];\n if (body.length === this.length) {\n break;\n }\n }\n }\n\n return body;\n }\n\n /**\n * `crypto.getRandomValues`, never `Math.random`. Unlike `crypto.randomUUID`, this one is NOT\n * restricted to a secure context, so it works on a plain-http origin and inside a browser Worker.\n */\n private static randomBytes(opts: { count: number }): Uint8Array {\n const source = globalThis.crypto;\n\n if (typeof source?.getRandomValues !== 'function') {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] No Web Crypto available | \\`crypto.getRandomValues\\` is required and \\`Math.random\\` is not an acceptable substitute for an identifier`,\n });\n }\n\n return source.getRandomValues(new Uint8Array(opts.count));\n }\n\n private static hasBothCases(opts: { alphabet: string }): boolean {\n let hasUpper = false;\n let hasLower = false;\n\n for (const character of opts.alphabet) {\n hasUpper ||= character !== character.toLowerCase();\n hasLower ||= character !== character.toUpperCase();\n\n if (hasUpper && hasLower) {\n return true;\n }\n }\n\n return false;\n }\n\n private static assertKnownCaseForm(opts: { caseForm: TUidCaseForm }): void {\n if (UidCaseForms.isValid(opts.caseForm)) {\n return;\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] Unknown caseForm | value: ${opts.caseForm} | valid: ${[...UidCaseForms.SCHEME_SET].join(', ')}`,\n });\n }\n\n /**\n * Folds case FIRST, then excludes, then de-duplicates - folding after sampling would misreport the\n * entropy and undo the alphabet's own exclusions.\n *\n * Refuses to fold a two-case alphabet at all, because folding one puts back exactly what it took\n * out: uppercasing `BASE58` turns its lowercase letters into `I` and `O`, the two it drops to keep\n * `1` and `0` unambiguous, and lowercasing it brings back `l`. Measured - the result is 35\n * characters, not the 33 an entropy calculation would predict. A single-case alphabet folds\n * cleanly because there is nothing to collide with.\n */\n private static resolveAlphabet(opts: {\n alphabet: string;\n exclude: string;\n caseForm: TUidCaseForm;\n }): string {\n const { alphabet, exclude, caseForm } = opts;\n\n if (caseForm !== UidCaseForms.MIXED && OpaqueUidHelper.hasBothCases({ alphabet })) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] caseForm '${caseForm}' cannot fold a two-case alphabet | Folding reintroduces the characters the alphabet excluded | Use \\`UidAlphabets.CROCKFORD\\` for a single-case alphabet, or \\`caseForm: '${UidCaseForms.MIXED}'\\``,\n });\n }\n\n const folded =\n caseForm === UidCaseForms.UPPER\n ? alphabet.toUpperCase()\n : caseForm === UidCaseForms.LOWER\n ? alphabet.toLowerCase()\n : alphabet;\n\n const removed = new Set(exclude);\n const resolved = [...new Set(folded)].filter(character => !removed.has(character)).join('');\n\n if (resolved.length < MIN_UID_ALPHABET_SIZE) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] Alphabet too small | size: ${resolved.length} | minimum: ${MIN_UID_ALPHABET_SIZE} | Widen \\`alphabet\\` or shorten \\`exclude\\``,\n });\n }\n\n return resolved;\n }\n\n /** An enabled prefix in the wrong case defeats the reason for choosing one: an id meant to survive a case-insensitive column stops being one the moment its prefix disagrees. */\n private static resolvePrefix(opts: { prefix?: IUidSegment; caseForm: TUidCaseForm }): string {\n const { prefix, caseForm } = opts;\n\n if (!prefix?.enable) {\n return '';\n }\n\n const value = prefix.value ?? '';\n if (value.length === 0) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] prefix is enabled but carries no value`,\n });\n }\n\n const expected =\n caseForm === UidCaseForms.UPPER\n ? value.toUpperCase()\n : caseForm === UidCaseForms.LOWER\n ? value.toLowerCase()\n : value;\n\n if (value !== expected) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] prefix does not match caseForm | prefix: ${value} | caseForm: ${caseForm} | expected: ${expected}`,\n });\n }\n\n return value;\n }\n\n /**\n * Two refusals here, both because the alternative fails silently: a delimiter with no prefix is a\n * leading character that separates nothing, and a delimiter drawn from the alphabet makes the id\n * impossible to split back into prefix and body.\n */\n private static resolveDelimiter(opts: {\n delimiter?: IUidSegment;\n hasPrefix: boolean;\n alphabet: string;\n }): string {\n const { delimiter, hasPrefix, alphabet } = opts;\n\n if (!delimiter?.enable) {\n return '';\n }\n\n if (!hasPrefix) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] delimiter is enabled without a prefix | It would lead the id and separate nothing | Put the character in \\`prefix.value\\` if that is what you want`,\n });\n }\n\n const value = delimiter.value ?? DEFAULT_UID_DELIMITER;\n if (value.length === 0) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] delimiter is enabled but carries no value`,\n });\n }\n\n const shared = [...new Set(value)].filter(character => alphabet.includes(character));\n if (shared.length > 0) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] delimiter shares characters with the alphabet | shared: ${shared.join('')} | An id built with it cannot be split back into prefix and body`,\n });\n }\n\n return value;\n }\n}\n"]}
1
+ {"version":3,"file":"opaque.js","sourceRoot":"","sources":["../../../../src/modules/uid/opaque.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAE1C,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AACpC,OAAO,EACL,qBAAqB,EACrB,kBAAkB,EAClB,wBAAwB,EACxB,qBAAqB,EACrB,YAAY,EACZ,YAAY,GACb,MAAM,oBAAoB,CAAC;AAI5B,uLAAuL;AACvL,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAE5B,oKAAoK;AACpK,MAAM,aAAa,GAAG,CAAC,KAAc,EAAiC,EAAE;IACtE,OAAO,OAAQ,KAAiD,EAAE,IAAI,KAAK,UAAU,CAAC;AACxF,CAAC,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,MAAM,OAAO,eAAgB,SAAQ,UAAU;IAS7C,YAAY,IAAwB;QAClC,KAAK,CAAC,EAAE,KAAK,EAAE,eAAe,CAAC,IAAI,EAAE,CAAC,CAAC;QAEvC,MAAM,QAAQ,GAAG,IAAI,EAAE,QAAQ,IAAI,YAAY,CAAC,KAAK,CAAC;QACtD,eAAe,CAAC,mBAAmB,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC;QAElD,IAAI,CAAC,QAAQ,GAAG,eAAe,CAAC,eAAe,CAAC;YAC9C,QAAQ,EAAE,IAAI,EAAE,QAAQ,IAAI,YAAY,CAAC,SAAS;YAClD,OAAO,EAAE,IAAI,EAAE,OAAO,IAAI,EAAE;YAC5B,QAAQ;SACT,CAAC,CAAC;QAEH,IAAI,CAAC,MAAM,GAAG,IAAI,EAAE,MAAM,IAAI,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GAAG,SAAS,CAAC,KAAK,IAAI,qBAAqB,CAAC;QACvD,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACvB,MAAM,QAAQ,CAAC;gBACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;gBACrD,OAAO,EAAE,IAAI,eAAe,CAAC,IAAI,6CAA6C;aAC/E,CAAC,CAAC;QACL,CAAC;QAED,MAAM,MAAM,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC;QACvF,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACtB,MAAM,QAAQ,CAAC;gBACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;gBACrD,OAAO,EAAE,IAAI,eAAe,CAAC,IAAI,6DAA6D,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,kEAAkE;aAChL,CAAC,CAAC;QACL,CAAC;QAED,OAAO,KAAK,CAAC;IACf,CAAC;CACF","sourcesContent":["import { HTTP } from '@/common/constants';\nimport type { ValueOrPromise } from '@/common/types';\nimport { BaseHelper } from '../base';\nimport { getError } from '../error';\nimport {\n DEFAULT_UID_DELIMITER,\n DEFAULT_UID_LENGTH,\n DEFAULT_UID_MAX_ATTEMPTS,\n MIN_UID_ALPHABET_SIZE,\n UidAlphabets,\n UidCaseForms,\n} from './common/constants';\nimport type { TUidCaseForm } from './common/constants';\nimport type { INextOpaqueUidOptions, IOpaqueUidOptions, IUidSegment } from './common/types';\n\n/** How many random bytes to draw per refill, per remaining character. Rejection throws some away, so asking for exactly `length` would round-trip to the entropy source repeatedly. */\nconst SAMPLING_OVERDRAW = 2;\n\n/** Local, not `@/utilities/promise.utility`: that module imports the logger BARREL, which reaches `node:module` and would take this browser-pure module with it. */\nconst isPromiseLike = (value: unknown): value is PromiseLike<boolean> => {\n return typeof (value as PromiseLike<boolean> | null | undefined)?.then === 'function';\n};\n\n/**\n * Fixed-length opaque ids, optionally prefixed - the counterpart to `SnowflakeUidHelper`.\n *\n * OPAQUE is the difference that matters, not the randomness. A Snowflake id is TRANSPARENT: its own\n * `parseId()` reads back the exact millisecond it was minted and the worker that minted it. That is\n * what you want in a log and not what you want on an invoice. Nothing can be read out of an id from\n * here. The cost is the ordering, which a Snowflake gives an index for free.\n *\n * `length` counts the BODY only. A prefix and a delimiter sit in front of it, so the finished string\n * is `prefix + delimiter + length` characters.\n *\n * Read {@link DEFAULT_UID_LENGTH} before accepting the default: six characters is an airline record\n * locator, and it needs the same scoping and retry that airlines give one.\n */\nexport class OpaqueUidHelper extends BaseHelper {\n private readonly alphabet: string;\n private readonly length: number;\n private readonly prefix: string;\n private readonly delimiter: string;\n\n /** Rejection mask: the smallest `2^n - 1` that covers every alphabet index. A plain `byte % size` would favour the first `256 % size` characters, which is a bias a caller cannot see and cannot undo. */\n private readonly mask: number;\n\n constructor(opts?: IOpaqueUidOptions) {\n super({ scope: OpaqueUidHelper.name });\n\n const caseForm = opts?.caseForm ?? UidCaseForms.UPPER;\n OpaqueUidHelper.assertKnownCaseForm({ caseForm });\n\n this.alphabet = OpaqueUidHelper.resolveAlphabet({\n alphabet: opts?.alphabet ?? UidAlphabets.CROCKFORD,\n exclude: opts?.exclude ?? '',\n caseForm,\n });\n\n this.length = opts?.length ?? DEFAULT_UID_LENGTH;\n if (!Number.isInteger(this.length) || this.length < 1) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] length must be a positive integer | value: ${this.length}`,\n });\n }\n\n this.prefix = OpaqueUidHelper.resolvePrefix({ prefix: opts?.prefix, caseForm });\n this.delimiter = OpaqueUidHelper.resolveDelimiter({\n delimiter: opts?.delimiter,\n hasPrefix: this.prefix.length > 0,\n alphabet: this.alphabet,\n });\n\n this.mask = (1 << Math.ceil(Math.log2(this.alphabet.length))) - 1;\n }\n\n /**\n * `prefix` replaces the configured value for this call and turns the prefix on for it; the\n * delimiter follows its own switch.\n *\n * `isAvailable` redraws until it accepts an id, up to `maxAttempts`. It LOWERS the collision rate,\n * it does not remove it: against a database the check and the insert are two statements, and\n * another request can take the id in between. The column still needs a unique index, and the\n * insert still needs to regenerate on violation.\n */\n nextId(opts?: INextOpaqueUidOptions<boolean>): string;\n nextId(opts: INextOpaqueUidOptions<Promise<boolean>>): Promise<string>;\n nextId(opts: INextOpaqueUidOptions): ValueOrPromise<string>;\n nextId(opts?: INextOpaqueUidOptions): ValueOrPromise<string> {\n const head = this.resolveHead({ prefix: opts?.prefix });\n\n const isAvailable = opts?.isAvailable;\n if (!isAvailable) {\n // Refused rather than ignored: without a check there is exactly ONE draw, so a caller who set\n // `maxAttempts` has configured a retry that cannot happen and has no way to notice.\n if (opts?.maxAttempts !== undefined) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}][nextId] maxAttempts has no effect without \\`isAvailable\\` | Nothing rejects a draw, so there is only ever one`,\n });\n }\n\n return `${head}${this.randomBody()}`;\n }\n\n const maxAttempts = OpaqueUidHelper.resolveMaxAttempts({ maxAttempts: opts?.maxAttempts });\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n const id = `${head}${this.randomBody()}`;\n const verdict = isAvailable(id);\n\n // The first PENDING verdict decides the shape of the whole call. Everything before it already\n // resolved, so a synchronous check never allocates a promise and `nextId()` stays a string.\n if (isPromiseLike(verdict)) {\n return this.continueAsync({ head, isAvailable, maxAttempts, attempt, id, verdict });\n }\n\n if (verdict) {\n return id;\n }\n }\n\n throw this.buildExhaustedError({ maxAttempts });\n }\n\n /** Entered only once a verdict came back pending; every later draw is awaited from here. */\n private async continueAsync(opts: {\n head: string;\n isAvailable: (id: string) => ValueOrPromise<boolean>;\n maxAttempts: number;\n attempt: number;\n id: string;\n verdict: PromiseLike<boolean>;\n }): Promise<string> {\n const { head, isAvailable, maxAttempts, attempt, id, verdict } = opts;\n\n if (await verdict) {\n return id;\n }\n\n for (let next = attempt + 1; next <= maxAttempts; next++) {\n const candidate = `${head}${this.randomBody()}`;\n\n if (await isAvailable(candidate)) {\n return candidate;\n }\n }\n\n throw this.buildExhaustedError({ maxAttempts });\n }\n\n private resolveHead(opts: { prefix?: string }): string {\n const override = opts.prefix;\n\n if (override === '') {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}][nextId] An empty prefix is not how a prefix is turned off | Construct with \\`prefix: { enable: false }\\``,\n });\n }\n\n const prefix = override ?? this.prefix;\n return prefix.length > 0 ? `${prefix}${this.delimiter}` : '';\n }\n\n private static resolveMaxAttempts(opts: { maxAttempts?: number }): number {\n const maxAttempts = opts.maxAttempts ?? DEFAULT_UID_MAX_ATTEMPTS;\n\n if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}][nextId] maxAttempts must be a positive integer | value: ${maxAttempts}`,\n });\n }\n\n return maxAttempts;\n }\n\n /** Bounded rather than endless: repeated rejection means the space is full, and a caller waiting forever learns that far later than a caller holding this error. */\n private buildExhaustedError(opts: { maxAttempts: number }) {\n return getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}][nextId] No available id after ${opts.maxAttempts} attempts | length: ${this.length} | alphabet: ${this.alphabet.length} | The space is crowded - raise \\`length\\``,\n });\n }\n\n /** The alphabet actually in use, after the case fold and every exclusion - what `length` is measured against. */\n getAlphabet(): string {\n return this.alphabet;\n }\n\n private randomBody(): string {\n const size = this.alphabet.length;\n let body = '';\n\n while (body.length < this.length) {\n const bytes = OpaqueUidHelper.randomBytes({\n count: (this.length - body.length) * SAMPLING_OVERDRAW,\n });\n\n for (const byte of bytes) {\n const index = byte & this.mask;\n\n // Rejection, not wrap-around: an index past the alphabet is discarded so every character\n // stays equally likely.\n if (index >= size) {\n continue;\n }\n\n body += this.alphabet[index];\n if (body.length === this.length) {\n break;\n }\n }\n }\n\n return body;\n }\n\n /**\n * `crypto.getRandomValues`, never `Math.random`. Unlike `crypto.randomUUID`, this one is NOT\n * restricted to a secure context, so it works on a plain-http origin and inside a browser Worker.\n */\n private static randomBytes(opts: { count: number }): Uint8Array {\n const source = globalThis.crypto;\n\n if (typeof source?.getRandomValues !== 'function') {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] No Web Crypto available | \\`crypto.getRandomValues\\` is required and \\`Math.random\\` is not an acceptable substitute for an identifier`,\n });\n }\n\n return source.getRandomValues(new Uint8Array(opts.count));\n }\n\n private static hasBothCases(opts: { alphabet: string }): boolean {\n let hasUpper = false;\n let hasLower = false;\n\n for (const character of opts.alphabet) {\n hasUpper ||= character !== character.toLowerCase();\n hasLower ||= character !== character.toUpperCase();\n\n if (hasUpper && hasLower) {\n return true;\n }\n }\n\n return false;\n }\n\n private static assertKnownCaseForm(opts: { caseForm: TUidCaseForm }): void {\n if (UidCaseForms.isValid(opts.caseForm)) {\n return;\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] Unknown caseForm | value: ${opts.caseForm} | valid: ${[...UidCaseForms.SCHEME_SET].join(', ')}`,\n });\n }\n\n /**\n * Folds case FIRST, then excludes, then de-duplicates - folding after sampling would misreport the\n * entropy and undo the alphabet's own exclusions.\n *\n * Refuses to fold a two-case alphabet at all, because folding one puts back exactly what it took\n * out: uppercasing `BASE58` turns its lowercase letters into `I` and `O`, the two it drops to keep\n * `1` and `0` unambiguous, and lowercasing it brings back `l`. Measured - the result is 35\n * characters, not the 33 an entropy calculation would predict. A single-case alphabet folds\n * cleanly because there is nothing to collide with.\n */\n private static resolveAlphabet(opts: {\n alphabet: string;\n exclude: string;\n caseForm: TUidCaseForm;\n }): string {\n const { alphabet, exclude, caseForm } = opts;\n\n if (caseForm !== UidCaseForms.MIXED && OpaqueUidHelper.hasBothCases({ alphabet })) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] caseForm '${caseForm}' cannot fold a two-case alphabet | Folding reintroduces the characters the alphabet excluded | Use \\`UidAlphabets.CROCKFORD\\` for a single-case alphabet, or \\`caseForm: '${UidCaseForms.MIXED}'\\``,\n });\n }\n\n const folded =\n caseForm === UidCaseForms.UPPER\n ? alphabet.toUpperCase()\n : caseForm === UidCaseForms.LOWER\n ? alphabet.toLowerCase()\n : alphabet;\n\n const removed = new Set(exclude);\n const resolved = [...new Set(folded)].filter((character) => !removed.has(character)).join('');\n\n if (resolved.length < MIN_UID_ALPHABET_SIZE) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] Alphabet too small | size: ${resolved.length} | minimum: ${MIN_UID_ALPHABET_SIZE} | Widen \\`alphabet\\` or shorten \\`exclude\\``,\n });\n }\n\n return resolved;\n }\n\n /** An enabled prefix in the wrong case defeats the reason for choosing one: an id meant to survive a case-insensitive column stops being one the moment its prefix disagrees. */\n private static resolvePrefix(opts: { prefix?: IUidSegment; caseForm: TUidCaseForm }): string {\n const { prefix, caseForm } = opts;\n\n if (!prefix?.enable) {\n return '';\n }\n\n const value = prefix.value ?? '';\n if (value.length === 0) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] prefix is enabled but carries no value`,\n });\n }\n\n const expected =\n caseForm === UidCaseForms.UPPER\n ? value.toUpperCase()\n : caseForm === UidCaseForms.LOWER\n ? value.toLowerCase()\n : value;\n\n if (value !== expected) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] prefix does not match caseForm | prefix: ${value} | caseForm: ${caseForm} | expected: ${expected}`,\n });\n }\n\n return value;\n }\n\n /**\n * Two refusals here, both because the alternative fails silently: a delimiter with no prefix is a\n * leading character that separates nothing, and a delimiter drawn from the alphabet makes the id\n * impossible to split back into prefix and body.\n */\n private static resolveDelimiter(opts: {\n delimiter?: IUidSegment;\n hasPrefix: boolean;\n alphabet: string;\n }): string {\n const { delimiter, hasPrefix, alphabet } = opts;\n\n if (!delimiter?.enable) {\n return '';\n }\n\n if (!hasPrefix) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] delimiter is enabled without a prefix | It would lead the id and separate nothing | Put the character in \\`prefix.value\\` if that is what you want`,\n });\n }\n\n const value = delimiter.value ?? DEFAULT_UID_DELIMITER;\n if (value.length === 0) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] delimiter is enabled but carries no value`,\n });\n }\n\n const shared = [...new Set(value)].filter((character) => alphabet.includes(character));\n if (shared.length > 0) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] delimiter shares characters with the alphabet | shared: ${shared.join('')} | An id built with it cannot be split back into prefix and body`,\n });\n }\n\n return value;\n }\n}\n"]}
@@ -34,7 +34,7 @@ export const createUuidV5 = () => {
34
34
  }
35
35
  return bytes;
36
36
  };
37
- return opts => {
37
+ return (opts) => {
38
38
  const { namespace, name } = opts;
39
39
  const namespaceBytes = resolveNamespace({ namespace });
40
40
  // Encoding turns a lone surrogate into U+FFFD, so two different malformed names would share an id.
@@ -1 +1 @@
1
- {"version":3,"file":"v5.js","sourceRoot":"","sources":["../../../../../src/modules/uid/uuid/v5.ts"],"names":[],"mappings":"AAAA,+FAA+F;AAC/F,OAAO,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACpD,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC/C,OAAO,EAAE,qB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AAM,CAAC,MAAM,MAAM,GAA0D,YAAY,EAAE,CAAC","sourcesContent":["// Past the barrels: this module ships on the `./uuid` subpath and must not pull their surface.\nimport { getError } from '@venizia/ignis-inversion';\nimport { HTTP } from '@/common/constants/http';\nimport { MAX_CACHED_NAMESPACES, UUID_HEX_OCTETS, UUID_NAMESPACE_PATTERN } from './common/constants';\nimport { Sha1Digest } from './sha1';\n\n/** Fits a namespace plus a ~160-character name; a longer one allocates for its own call. */\nconst INPUT_SIZE = 512;\n\n/** Builds a v5 generator with its own namespace cache and buffer. */\nexport const createUuidV5 = (): ((opts: { namespace: string; name: string }) => string) => {\n const encoder = new TextEncoder();\n\n /** Parsed namespaces, capped so a caller-fed one cannot grow the map without bound. */\n const namespaces = new Map<string, Uint8Array>();\n\n const input = new Uint8Array(INPUT_SIZE);\n const nameView = input.subarray(16);\n\n const resolveNamespace = (opts: { namespace: string }): Uint8Array => {\n const { namespace } = opts;\n\n const cached = namespaces.get(namespace);\n if (cached) {\n return cached;\n }\n\n if (!UUID_NAMESPACE_PATTERN.test(namespace)) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[uuidV5] namespace must be a UUID - received: ${namespace}`,\n });\n }\n\n const bytes = new Uint8Array(16);\n const hex = namespace.replaceAll('-', '');\n for (let index = 0; index < 16; index++) {\n bytes[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16);\n }\n\n if (namespaces.size < MAX_CACHED_NAMESPACES) {\n namespaces.set(namespace, bytes);\n }\n\n return bytes;\n };\n\n return opts => {\n const { namespace, name } = opts;\n\n const namespaceBytes = resolveNamespace({ namespace });\n\n // Encoding turns a lone surrogate into U+FFFD, so two different malformed names would share an id.\n if (typeof name.isWellFormed === 'function' && !name.isWellFormed()) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message:\n '[uuidV5] name carries a lone surrogate - it is not well-formed UTF-16 and would collide with another name',\n });\n }\n\n // UTF-8 never exceeds 3 bytes per UTF-16 code unit. An oversized name gets a buffer of its own\n // for this call only, so one huge name does not pin its size for the life of the process.\n const required = 16 + name.length * 3;\n const target = required > input.length ? new Uint8Array(required) : input;\n const targetName = target === input ? nameView : target.subarray(16);\n\n target.set(namespaceBytes);\n const { written } = encoder.encodeInto(name, targetName);\n\n const digest = Sha1Digest.of({ bytes: target.subarray(0, 16 + written) });\n digest[6] = (digest[6] & 0x0f) | 0x50;\n digest[8] = (digest[8] & 0x3f) | 0x80;\n\n const hex = UUID_HEX_OCTETS;\n\n return (\n hex[digest[0]] +\n hex[digest[1]] +\n hex[digest[2]] +\n hex[digest[3]] +\n '-' +\n hex[digest[4]] +\n hex[digest[5]] +\n '-' +\n hex[digest[6]] +\n hex[digest[7]] +\n '-' +\n hex[digest[8]] +\n hex[digest[9]] +\n '-' +\n hex[digest[10]] +\n hex[digest[11]] +\n hex[digest[12]] +\n hex[digest[13]] +\n hex[digest[14]] +\n hex[digest[15]]\n );\n };\n};\n\n/**\n * Mints a deterministic UUID v5 from `namespace` and `name` - an idempotency key.\n *\n * Reproducible therefore NOT secret: never a share link, a reset token or an API key.\n */\nexport const uuidV5: (opts: { namespace: string; name: string }) => string = createUuidV5();\n"]}
1
+ {"version":3,"file":"v5.js","sourceRoot":"","sources":["../../../../../src/modules/uid/uuid/v5.ts"],"names":[],"mappings":"AAAA,+FAA+F;AAC/F,OAAO,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACpD,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC/C,OAAO,EAAE,qBAAqB,EAAE,eAAe,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AACpG,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AAEpC,4FAA4F;AAC5F,MAAM,UAAU,GAAG,GAAG,CAAC;AAEvB,qEAAqE;AACrE,MAAM,CAAC,MAAM,YAAY,GAAG,GAA4D,EAAE;IACxF,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,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CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC;QAEtC,MAAM,GAAG,GAAG,eAAe,CAAC;QAE5B,OAAO,CACL,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;YACd,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;YACd,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;YACd,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;YACd,GAAG;YACH,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;YACd,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;YACd,GAAG;YACH,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;YACd,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;YACd,GAAG;YACH,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;YACd,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;YACd,GAAG;YACH,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;YACf,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;YACf,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;YACf,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;YACf,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;YACf,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAChB,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC,CAAC;AAEF;;;;GAIG;AACH,MAAM,CAAC,MAAM,MAAM,GAA0D,YAAY,EAAE,CAAC","sourcesContent":["// Past the barrels: this module ships on the `./uuid` subpath and must not pull their surface.\nimport { getError } from '@venizia/ignis-inversion';\nimport { HTTP } from '@/common/constants/http';\nimport { MAX_CACHED_NAMESPACES, UUID_HEX_OCTETS, UUID_NAMESPACE_PATTERN } from './common/constants';\nimport { Sha1Digest } from './sha1';\n\n/** Fits a namespace plus a ~160-character name; a longer one allocates for its own call. */\nconst INPUT_SIZE = 512;\n\n/** Builds a v5 generator with its own namespace cache and buffer. */\nexport const createUuidV5 = (): ((opts: { namespace: string; name: string }) => string) => {\n const encoder = new TextEncoder();\n\n /** Parsed namespaces, capped so a caller-fed one cannot grow the map without bound. */\n const namespaces = new Map<string, Uint8Array>();\n\n const input = new Uint8Array(INPUT_SIZE);\n const nameView = input.subarray(16);\n\n const resolveNamespace = (opts: { namespace: string }): Uint8Array => {\n const { namespace } = opts;\n\n const cached = namespaces.get(namespace);\n if (cached) {\n return cached;\n }\n\n if (!UUID_NAMESPACE_PATTERN.test(namespace)) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[uuidV5] namespace must be a UUID - received: ${namespace}`,\n });\n }\n\n const bytes = new Uint8Array(16);\n const hex = namespace.replaceAll('-', '');\n for (let index = 0; index < 16; index++) {\n bytes[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16);\n }\n\n if (namespaces.size < MAX_CACHED_NAMESPACES) {\n namespaces.set(namespace, bytes);\n }\n\n return bytes;\n };\n\n return (opts) => {\n const { namespace, name } = opts;\n\n const namespaceBytes = resolveNamespace({ namespace });\n\n // Encoding turns a lone surrogate into U+FFFD, so two different malformed names would share an id.\n if (typeof name.isWellFormed === 'function' && !name.isWellFormed()) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n message:\n '[uuidV5] name carries a lone surrogate - it is not well-formed UTF-16 and would collide with another name',\n });\n }\n\n // UTF-8 never exceeds 3 bytes per UTF-16 code unit. An oversized name gets a buffer of its own\n // for this call only, so one huge name does not pin its size for the life of the process.\n const required = 16 + name.length * 3;\n const target = required > input.length ? new Uint8Array(required) : input;\n const targetName = target === input ? nameView : target.subarray(16);\n\n target.set(namespaceBytes);\n const { written } = encoder.encodeInto(name, targetName);\n\n const digest = Sha1Digest.of({ bytes: target.subarray(0, 16 + written) });\n digest[6] = (digest[6] & 0x0f) | 0x50;\n digest[8] = (digest[8] & 0x3f) | 0x80;\n\n const hex = UUID_HEX_OCTETS;\n\n return (\n hex[digest[0]] +\n hex[digest[1]] +\n hex[digest[2]] +\n hex[digest[3]] +\n '-' +\n hex[digest[4]] +\n hex[digest[5]] +\n '-' +\n hex[digest[6]] +\n hex[digest[7]] +\n '-' +\n hex[digest[8]] +\n hex[digest[9]] +\n '-' +\n hex[digest[10]] +\n hex[digest[11]] +\n hex[digest[12]] +\n hex[digest[13]] +\n hex[digest[14]] +\n hex[digest[15]]\n );\n };\n};\n\n/**\n * Mints a deterministic UUID v5 from `namespace` and `name` - an idempotency key.\n *\n * Reproducible therefore NOT secret: never a share link, a reset token or an API key.\n */\nexport const uuidV5: (opts: { namespace: string; name: string }) => string = createUuidV5();\n"]}
@@ -5,16 +5,16 @@ export class BaseWorkerBusHelper extends AbstractWorkerBusHelper {
5
5
  super({ scope: opts.scope, identifier: opts.scope });
6
6
  this.port = opts.port;
7
7
  this.handler = opts.busHandler;
8
- this.port.on('message', message => {
8
+ this.port.on('message', (message) => {
9
9
  this.invokeHook({ scope: 'onMessage', execution: () => this.handler.onMessage({ message }) });
10
10
  });
11
- this.port.on('error', error => {
11
+ this.port.on('error', (error) => {
12
12
  this.invokeHook({ scope: 'onError', execution: () => this.handler.onError({ error }) });
13
13
  });
14
- this.port.on('messageerror', error => {
14
+ this.port.on('messageerror', (error) => {
15
15
  this.invokeHook({ scope: 'onError', execution: () => this.handler.onError({ error }) });
16
16
  });
17
- this.port.on('exit', exitCode => {
17
+ this.port.on('exit', (exitCode) => {
18
18
  this.invokeHook({ scope: 'onExit', execution: () => this.handler.onExit({ exitCode }) });
19
19
  });
20
20
  this.port.on('close', () => {
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","sourceRoot":"","sources":["../../../../../src/modules/worker-thread/bus/base.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAG5D,OAAO,EAAE,uBAAuB,EAAE,MAA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WAAW,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,GAAG,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC;QAC9D,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACtC,CAAC;QAED,IAAI,CAAC,UAAU,CAAC;YACd,KAAK,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI;YAC5B,SAAS,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,kBAAkB,EAAE,CAAC,IAAI,CAAC;SACjD,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { type ValueOrPromise } from '@/common/types';\nimport { voidExecution } from '@/utilities/promise.utility';\nimport { type MessagePort, type Transferable } from 'node:worker_threads';\nimport { type IWorkerMessageBusHandler } from '../common';\nimport { AbstractWorkerBusHelper } from './abstract';\n\nexport class BaseWorkerBusHelper<IConsumePayload, IPublishPayload> extends AbstractWorkerBusHelper<\n IConsumePayload,\n IPublishPayload\n> {\n constructor(opts: {\n scope: string;\n port: MessagePort;\n busHandler: IWorkerMessageBusHandler<IConsumePayload>;\n }) {\n super({ scope: opts.scope, identifier: opts.scope });\n\n this.port = opts.port;\n this.handler = opts.busHandler;\n\n this.port.on('message', message => {\n this.invokeHook({ scope: 'onMessage', execution: () => this.handler.onMessage({ message }) });\n });\n\n this.port.on('error', error => {\n this.invokeHook({ scope: 'onError', execution: () => this.handler.onError({ error }) });\n });\n\n this.port.on('messageerror', error => {\n this.invokeHook({ scope: 'onError', execution: () => this.handler.onError({ error }) });\n });\n\n this.port.on('exit', exitCode => {\n this.invokeHook({ scope: 'onExit', execution: () => this.handler.onExit({ exitCode }) });\n });\n\n this.port.on('close', () => {\n this.invokeHook({ scope: 'onClose', execution: () => this.handler.onClose() });\n });\n }\n\n /** Bus handlers run inside MessagePort listeners; a sync throw there is uncaught and kills the worker thread, so wrap it - voidExecution alone can't catch a throw evaluated before it's called. */\n protected invokeHook(opts: { scope: string; execution: () => ValueOrPromise<void> }) {\n const { scope, execution } = opts;\n\n try {\n voidExecution({ logger: this.logger, scope, execution: execution() });\n } catch (error) {\n this.logger.for(scope).error('Hook execution FAILED | Error: %s', error);\n }\n }\n\n onBeforePostMessage?(opts: { message: IPublishPayload }): ValueOrPromise<void>;\n onAfterPostMessage?(opts: { message: IPublishPayload }): ValueOrPromise<void>;\n\n postMessage(opts: {\n message: IPublishPayload;\n transferList: readonly Transferable[] | undefined;\n }): ValueOrPromise<void> {\n if (!this.port) {\n this.logger\n .for(this.postMessage.name)\n .error('Failed to post message to main | Invalid parentPort!');\n return;\n }\n\n this.invokeHook({\n scope: this.postMessage.name,\n execution: () => this.onBeforePostMessage?.(opts),\n });\n\n if (opts.transferList) {\n this.port.postMessage(opts.message, [...opts.transferList]);\n } else {\n this.port.postMessage(opts.message);\n }\n\n this.invokeHook({\n scope: this.postMessage.name,\n execution: () => this.onAfterPostMessage?.(opts),\n });\n }\n}\n"]}
1
+ {"version":3,"file":"base.js","sourceRoot":"","sources":["../../../../../src/modules/worker-thread/bus/base.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAG5D,OAAO,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC;AAErD,MAAM,OAAO,mBAAsD,SAAQ,uBAG1E;IACC,YAAY,IAIX;QACC,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,UAAU,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;QAErD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;QACtB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,UAAU,CAAC;QAE/B,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,OAAO,EAAE,EAAE;YAClC,IAAI,CAAC,UAAU,CAAC,EAAE,KAAK,EAAE,WAAW,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC,IAAI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promise.utility';\nimport { type MessagePort, type Transferable } from 'node:worker_threads';\nimport { type IWorkerMessageBusHandler } from '../common';\nimport { AbstractWorkerBusHelper } from './abstract';\n\nexport class BaseWorkerBusHelper<IConsumePayload, IPublishPayload> extends AbstractWorkerBusHelper<\n IConsumePayload,\n IPublishPayload\n> {\n constructor(opts: {\n scope: string;\n port: MessagePort;\n busHandler: IWorkerMessageBusHandler<IConsumePayload>;\n }) {\n super({ scope: opts.scope, identifier: opts.scope });\n\n this.port = opts.port;\n this.handler = opts.busHandler;\n\n this.port.on('message', (message) => {\n this.invokeHook({ scope: 'onMessage', execution: () => this.handler.onMessage({ message }) });\n });\n\n this.port.on('error', (error) => {\n this.invokeHook({ scope: 'onError', execution: () => this.handler.onError({ error }) });\n });\n\n this.port.on('messageerror', (error) => {\n this.invokeHook({ scope: 'onError', execution: () => this.handler.onError({ error }) });\n });\n\n this.port.on('exit', (exitCode) => {\n this.invokeHook({ scope: 'onExit', execution: () => this.handler.onExit({ exitCode }) });\n });\n\n this.port.on('close', () => {\n this.invokeHook({ scope: 'onClose', execution: () => this.handler.onClose() });\n });\n }\n\n /** Bus handlers run inside MessagePort listeners; a sync throw there is uncaught and kills the worker thread, so wrap it - voidExecution alone can't catch a throw evaluated before it's called. */\n protected invokeHook(opts: { scope: string; execution: () => ValueOrPromise<void> }) {\n const { scope, execution } = opts;\n\n try {\n voidExecution({ logger: this.logger, scope, execution: execution() });\n } catch (error) {\n this.logger.for(scope).error('Hook execution FAILED | Error: %s', error);\n }\n }\n\n onBeforePostMessage?(opts: { message: IPublishPayload }): ValueOrPromise<void>;\n onAfterPostMessage?(opts: { message: IPublishPayload }): ValueOrPromise<void>;\n\n postMessage(opts: {\n message: IPublishPayload;\n transferList: readonly Transferable[] | undefined;\n }): ValueOrPromise<void> {\n if (!this.port) {\n this.logger\n .for(this.postMessage.name)\n .error('Failed to post message to main | Invalid parentPort!');\n return;\n }\n\n this.invokeHook({\n scope: this.postMessage.name,\n execution: () => this.onBeforePostMessage?.(opts),\n });\n\n if (opts.transferList) {\n this.port.postMessage(opts.message, [...opts.transferList]);\n } else {\n this.port.postMessage(opts.message);\n }\n\n this.invokeHook({\n scope: this.postMessage.name,\n execution: () => this.onAfterPostMessage?.(opts),\n });\n }\n}\n"]}