@ragestudio/scylla-odm 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (233) hide show
  1. package/batch/index.d.ts +24 -0
  2. package/batch/index.js +1 -0
  3. package/client.d.ts +3 -1
  4. package/client.js +1 -1
  5. package/cql_gen/create_keyspace.js +1 -1
  6. package/cql_gen/create_table.js +1 -1
  7. package/document/index.d.ts +2 -3
  8. package/document/index.js +1 -1
  9. package/driver/{lib/auth → auth}/index.d.ts +1 -13
  10. package/driver/auth/index.js +1 -0
  11. package/driver/auth/no-auth-provider.js +1 -0
  12. package/driver/auth/plain-text-auth-provider.js +1 -0
  13. package/driver/auth/provider.js +1 -0
  14. package/driver/client-options.js +1 -0
  15. package/driver/client.js +1 -0
  16. package/driver/concurrent/index.d.ts +1 -0
  17. package/driver/concurrent/index.js +1 -0
  18. package/driver/connection.js +1 -0
  19. package/driver/control-connection.js +1 -0
  20. package/driver/encoder.js +1 -0
  21. package/driver/errors.js +1 -0
  22. package/driver/execution-options.js +1 -0
  23. package/driver/execution-profile.js +1 -0
  24. package/driver/host-connection-pool.js +1 -0
  25. package/driver/host.js +1 -0
  26. package/driver/index.d.ts +8 -100
  27. package/driver/index.js +1 -1
  28. package/driver/mapping/cache.js +1 -0
  29. package/driver/mapping/doc-info-adapter.js +1 -0
  30. package/driver/{lib/mapping → mapping}/index.d.ts +2 -2
  31. package/driver/mapping/mapper.js +1 -0
  32. package/driver/mapping/mapping-handler.js +1 -0
  33. package/driver/mapping/model-batch-item.js +1 -0
  34. package/driver/mapping/model-batch-mapper.js +1 -0
  35. package/driver/mapping/model-mapper.js +1 -0
  36. package/driver/mapping/model-mapping-info.js +1 -0
  37. package/driver/mapping/object-selector.js +1 -0
  38. package/driver/mapping/q.js +1 -0
  39. package/driver/mapping/query-generator.js +9 -0
  40. package/driver/mapping/result-mapper.js +4 -0
  41. package/driver/mapping/result.js +1 -0
  42. package/driver/mapping/table-mappings.js +1 -0
  43. package/driver/mapping/tree.js +1 -0
  44. package/driver/metadata/aggregate.js +1 -0
  45. package/driver/metadata/client-state.js +1 -0
  46. package/driver/metadata/data-collection.js +1 -0
  47. package/driver/metadata/event-debouncer.js +1 -0
  48. package/driver/{lib/metadata → metadata}/index.d.ts +2 -2
  49. package/driver/metadata/index.js +1 -0
  50. package/driver/metadata/materialized-view.js +1 -0
  51. package/driver/metadata/schema-function.js +1 -0
  52. package/driver/metadata/schema-index.js +1 -0
  53. package/driver/metadata/schema-parser.js +1 -0
  54. package/driver/metadata/table-metadata.js +1 -0
  55. package/driver/operation-state.js +1 -0
  56. package/driver/policies/address-resolution.js +1 -0
  57. package/driver/{lib/policies → policies}/index.d.ts +2 -2
  58. package/driver/policies/index.js +1 -0
  59. package/driver/policies/load-balancing.js +1 -0
  60. package/driver/policies/reconnection.js +1 -0
  61. package/driver/policies/retry.js +1 -0
  62. package/driver/policies/speculative-execution.js +1 -0
  63. package/driver/policies/timestamp-generation.js +1 -0
  64. package/driver/prepare-handler.js +1 -0
  65. package/driver/promise-utils.js +1 -0
  66. package/driver/readers.js +1 -0
  67. package/driver/request-execution.js +1 -0
  68. package/driver/request-handler.js +1 -0
  69. package/driver/requests.js +1 -0
  70. package/driver/stream-id-stack.js +1 -0
  71. package/driver/streams.js +1 -0
  72. package/driver/token.js +1 -0
  73. package/driver/tokenizer.js +1 -0
  74. package/driver/types/big-decimal.js +1 -0
  75. package/driver/types/duration.js +1 -0
  76. package/driver/{lib/types → types}/index.d.ts +2 -2
  77. package/driver/types/index.js +1 -0
  78. package/driver/types/inet-address.js +1 -0
  79. package/driver/types/integer.js +1 -0
  80. package/driver/types/local-date.js +1 -0
  81. package/driver/types/local-time.js +1 -0
  82. package/driver/types/mutable-long.js +1 -0
  83. package/driver/types/result-set.js +1 -0
  84. package/driver/types/result-stream.js +1 -0
  85. package/driver/types/row.js +1 -0
  86. package/driver/types/time-uuid.js +1 -0
  87. package/driver/types/tuple.js +1 -0
  88. package/driver/types/uuid.js +1 -0
  89. package/driver/types/vector.js +1 -0
  90. package/driver/types/version-number.js +1 -0
  91. package/driver/utils.js +4 -0
  92. package/driver/writers.js +1 -0
  93. package/index.d.ts +2 -1
  94. package/index.js +1 -1
  95. package/logger/index.js +1 -1
  96. package/model/index.d.ts +37 -6
  97. package/model/index.js +1 -1
  98. package/operations/countAll.js +1 -1
  99. package/operations/delete.d.ts +4 -3
  100. package/operations/delete.js +1 -1
  101. package/operations/find.js +1 -1
  102. package/operations/findOne.js +1 -1
  103. package/operations/insert.d.ts +8 -0
  104. package/operations/insert.js +1 -0
  105. package/operations/sync.js +1 -1
  106. package/operations/tableExists.js +2 -2
  107. package/operations/update.d.ts +3 -2
  108. package/operations/update.js +1 -1
  109. package/package.js +1 -1
  110. package/package.json +1 -1
  111. package/schema/index.js +1 -1
  112. package/types.d.ts +18 -2
  113. package/utils/buildMapper.js +1 -1
  114. package/utils/delay.js +1 -1
  115. package/utils/fillDefaults.js +1 -1
  116. package/utils/isPlainObject.js +1 -1
  117. package/utils/loadModels.js +1 -1
  118. package/utils/queryParser.js +1 -1
  119. package/utils/typeChecker.js +1 -1
  120. package/_virtual/_rolldown/runtime.js +0 -1
  121. package/driver/lib/auth/base-dse-authenticator.js +0 -1
  122. package/driver/lib/auth/dse-gssapi-auth-provider.js +0 -1
  123. package/driver/lib/auth/dse-plain-text-auth-provider.js +0 -1
  124. package/driver/lib/auth/gssapi-client.js +0 -1
  125. package/driver/lib/auth/index.js +0 -1
  126. package/driver/lib/auth/no-auth-provider.js +0 -1
  127. package/driver/lib/auth/plain-text-auth-provider.js +0 -1
  128. package/driver/lib/auth/provider.js +0 -1
  129. package/driver/lib/client-options.js +0 -1
  130. package/driver/lib/client.js +0 -1
  131. package/driver/lib/concurrent/index.d.ts +0 -25
  132. package/driver/lib/concurrent/index.js +0 -1
  133. package/driver/lib/connection.js +0 -1
  134. package/driver/lib/control-connection.js +0 -1
  135. package/driver/lib/datastax/graph/complex-type-helper.js +0 -1
  136. package/driver/lib/datastax/graph/custom-type-serializers.js +0 -1
  137. package/driver/lib/datastax/graph/graph-executor.js +0 -1
  138. package/driver/lib/datastax/graph/graph-serializer.js +0 -1
  139. package/driver/lib/datastax/graph/index.d.ts +0 -63
  140. package/driver/lib/datastax/graph/index.js +0 -1
  141. package/driver/lib/datastax/graph/options.js +0 -1
  142. package/driver/lib/datastax/graph/result-set.js +0 -1
  143. package/driver/lib/datastax/graph/structure.js +0 -1
  144. package/driver/lib/datastax/graph/type-serializers.js +0 -1
  145. package/driver/lib/datastax/graph/wrappers.js +0 -1
  146. package/driver/lib/datastax/index.d.ts +0 -7
  147. package/driver/lib/datastax/search/date-range.js +0 -1
  148. package/driver/lib/datastax/search/index.d.ts +0 -49
  149. package/driver/lib/datastax/search/index.js +0 -1
  150. package/driver/lib/encoder.js +0 -1
  151. package/driver/lib/errors.js +0 -1
  152. package/driver/lib/execution-options.js +0 -1
  153. package/driver/lib/execution-profile.js +0 -1
  154. package/driver/lib/geometry/geometry.js +0 -1
  155. package/driver/lib/geometry/index.d.ts +0 -49
  156. package/driver/lib/geometry/index.js +0 -1
  157. package/driver/lib/geometry/line-string.js +0 -1
  158. package/driver/lib/geometry/point.js +0 -1
  159. package/driver/lib/geometry/polygon.js +0 -1
  160. package/driver/lib/host-connection-pool.js +0 -1
  161. package/driver/lib/host.js +0 -1
  162. package/driver/lib/insights-client.js +0 -1
  163. package/driver/lib/mapping/cache.js +0 -1
  164. package/driver/lib/mapping/doc-info-adapter.js +0 -1
  165. package/driver/lib/mapping/mapper.js +0 -1
  166. package/driver/lib/mapping/mapping-handler.js +0 -1
  167. package/driver/lib/mapping/model-batch-item.js +0 -1
  168. package/driver/lib/mapping/model-batch-mapper.js +0 -1
  169. package/driver/lib/mapping/model-mapper.js +0 -1
  170. package/driver/lib/mapping/model-mapping-info.js +0 -1
  171. package/driver/lib/mapping/object-selector.js +0 -1
  172. package/driver/lib/mapping/q.js +0 -1
  173. package/driver/lib/mapping/query-generator.js +0 -9
  174. package/driver/lib/mapping/result-mapper.js +0 -4
  175. package/driver/lib/mapping/result.js +0 -1
  176. package/driver/lib/mapping/table-mappings.js +0 -1
  177. package/driver/lib/mapping/tree.js +0 -1
  178. package/driver/lib/metadata/aggregate.js +0 -1
  179. package/driver/lib/metadata/client-state.js +0 -1
  180. package/driver/lib/metadata/data-collection.js +0 -1
  181. package/driver/lib/metadata/event-debouncer.js +0 -1
  182. package/driver/lib/metadata/index.js +0 -1
  183. package/driver/lib/metadata/materialized-view.js +0 -1
  184. package/driver/lib/metadata/schema-function.js +0 -1
  185. package/driver/lib/metadata/schema-index.js +0 -1
  186. package/driver/lib/metadata/schema-parser.js +0 -1
  187. package/driver/lib/metadata/table-metadata.js +0 -1
  188. package/driver/lib/metrics/client-metrics.js +0 -1
  189. package/driver/lib/metrics/default-metrics.js +0 -1
  190. package/driver/lib/metrics/index.d.ts +0 -44
  191. package/driver/lib/metrics/index.js +0 -1
  192. package/driver/lib/operation-state.js +0 -1
  193. package/driver/lib/policies/address-resolution.js +0 -1
  194. package/driver/lib/policies/index.js +0 -1
  195. package/driver/lib/policies/load-balancing.js +0 -1
  196. package/driver/lib/policies/reconnection.js +0 -1
  197. package/driver/lib/policies/retry.js +0 -1
  198. package/driver/lib/policies/speculative-execution.js +0 -1
  199. package/driver/lib/policies/timestamp-generation.js +0 -1
  200. package/driver/lib/prepare-handler.js +0 -1
  201. package/driver/lib/promise-utils.js +0 -1
  202. package/driver/lib/readers.js +0 -1
  203. package/driver/lib/request-execution.js +0 -1
  204. package/driver/lib/request-handler.js +0 -1
  205. package/driver/lib/requests.js +0 -1
  206. package/driver/lib/stream-id-stack.js +0 -1
  207. package/driver/lib/streams.js +0 -1
  208. package/driver/lib/token.js +0 -1
  209. package/driver/lib/tokenizer.js +0 -1
  210. package/driver/lib/tracker/index.d.ts +0 -45
  211. package/driver/lib/tracker/index.js +0 -1
  212. package/driver/lib/tracker/request-logger.js +0 -1
  213. package/driver/lib/tracker/request-tracker.js +0 -1
  214. package/driver/lib/types/big-decimal.js +0 -1
  215. package/driver/lib/types/duration.js +0 -1
  216. package/driver/lib/types/index.js +0 -1
  217. package/driver/lib/types/inet-address.js +0 -1
  218. package/driver/lib/types/integer.js +0 -1
  219. package/driver/lib/types/local-date.js +0 -1
  220. package/driver/lib/types/local-time.js +0 -1
  221. package/driver/lib/types/mutable-long.js +0 -1
  222. package/driver/lib/types/result-set.js +0 -1
  223. package/driver/lib/types/result-stream.js +0 -1
  224. package/driver/lib/types/row.js +0 -1
  225. package/driver/lib/types/time-uuid.js +0 -1
  226. package/driver/lib/types/tuple.js +0 -1
  227. package/driver/lib/types/uuid.js +0 -1
  228. package/driver/lib/types/vector.js +0 -1
  229. package/driver/lib/types/version-number.js +0 -1
  230. package/driver/lib/utils.js +0 -4
  231. package/driver/lib/writers.js +0 -1
  232. /package/driver/{lib/mapping → mapping}/index.js +0 -0
  233. /package/driver/{lib/types → types}/protocol-version.js +0 -0
@@ -0,0 +1 @@
1
+ import e from"../utils.js";import t from"./tree.js";import n from"./cache.js";import r from"./query-generator.js";import i from"./result-mapper.js";import a from"./result.js";import o from"./object-selector.js";import s from"./doc-info-adapter.js";var MappingHandler=class{constructor(e,n){this._client=e,this._cache={select:new t().on(`add`,e=>this._validateCacheLength(e)),selectAll:new t().on(`add`,e=>this._validateCacheLength(e)),insert:new t().on(`add`,e=>this._validateCacheLength(e)),update:new t().on(`add`,e=>this._validateCacheLength(e)),remove:new t().on(`add`,e=>this._validateCacheLength(e)),customQueries:new Map},this.info=n}getSelectExecutor(t,i,a){let c=Object.keys(t);if(c.length===0)return Promise.reject(Error(`Expected object with keys`));let l=n.getSelectKey(c,t,i),u=this._cache.select.getOrCreate(l,()=>({executor:null,resultAdapter:null}));if(u.executor!==null)return Promise.resolve(u.executor);let d=s.getPropertiesInfo(c,null,t,this.info),f=s.getPropertiesInfo(e.emptyArray,i,t,this.info),p=s.adaptOrderBy(i,this.info),m=i&&i.limit;return this._client.connect().then(()=>o.getForSelect(this._client,this.info,a,d,f,p)).then(e=>{let t=r.getSelect(e,this.info.keyspace,d,f,p,m),n=r.selectParamsGetter(d,m),i=this;return u.executor=function(e,r,a){return i._executeSelect(t,n,e,r,a,u)},u.executor})}getSelectAllExecutor(t){let i=n.getSelectAllKey(t),a=this._cache.selectAll.getOrCreate(i,()=>({executor:null,resultAdapter:null}));if(a.executor!==null)return a.executor;let c=s.getPropertiesInfo(e.emptyArray,t,e.emptyObject,this.info),l=s.adaptOrderBy(t,this.info),u=t&&t.limit,d=o.getForSelectAll(this.info),f=r.getSelect(d,this.info.keyspace,e.emptyArray,c,l,u),p=r.selectParamsGetter(e.emptyArray,u),m=this;return a.executor=function(e,t){return m._executeSelect(f,p,null,e,t,a)},a.executor}_executeSelect(e,t,n,r,o,c){let l=s.adaptAllOptions(o,!0);return this._client.execute(e,t(n,r,this.info),l).then(e=>(c.resultAdapter===null&&(c.resultAdapter=i.getSelectAdapter(this.info,e)),new a(e,this.info,c.resultAdapter)))}getInsertExecutor(e,t){let r=Object.keys(e);if(r.length===0)return Promise.reject(Error(`Expected object with keys`));let i=n.getInsertKey(r,t),a=this._cache.insert.getOrCreate(i,()=>({executor:null}));return a.executor===null?this.createInsertQueries(r,e,t).then(e=>e.length===1?this._setSingleExecutor(a,e[0]):this._setBatchExecutor(a,e)):Promise.resolve(a.executor)}createInsertQueries(e,t,n){let i=s.getPropertiesInfo(e,n,t,this.info),a=n&&n.ifNotExists;return this._client.connect().then(()=>o.getForInsert(this._client,this.info,i)).then(e=>{if(e.length>1&&a)throw Error(`Batch with ifNotExists conditions cannot span multiple tables`);return e.map(e=>r.getInsert(e,this.info.keyspace,i,n,a))})}getUpdateExecutor(e,t){let r=Object.keys(e);if(r.length===0)return Promise.reject(Error(`Expected object with keys`));let i=n.getUpdateKey(r,e,t),a=this._cache.update.getOrCreate(i,()=>({executor:null}));return a.executor===null?this.createUpdateQueries(r,e,t).then(e=>e.length===1?this._setSingleExecutor(a,e[0]):this._setBatchExecutor(a,e)):Promise.resolve(a.executor)}createUpdateQueries(t,n,i){let a=s.getPropertiesInfo(t,i,n,this.info),c=i&&i.ifExists,l=i&&i.when?s.getPropertiesInfo(Object.keys(i.when),null,i.when,this.info):e.emptyArray;if(l.length>0&&c)throw Error(`Both when and ifExists conditions can not be applied to the same statement`);return this._client.connect().then(()=>o.getForUpdate(this._client,this.info,a,l)).then(e=>{if(e.length>1&&(l.length>0||c))throw Error(`Batch with when or ifExists conditions cannot span multiple tables`);return e.map(e=>r.getUpdate(e,this.info.keyspace,a,i,l,c))})}getDeleteExecutor(e,t){let r=Object.keys(e);if(r.length===0)return Promise.reject(Error(`Expected object with keys`));let i=n.getRemoveKey(r,e,t),a=this._cache.remove.getOrCreate(i,()=>({executor:null}));return a.executor===null?this.createDeleteQueries(r,e,t).then(e=>e.length===1?this._setSingleExecutor(a,e[0]):this._setBatchExecutor(a,e)):Promise.resolve(a.executor)}createDeleteQueries(t,n,i){let a=s.getPropertiesInfo(t,i,n,this.info),c=i&&i.ifExists,l=i&&i.when?s.getPropertiesInfo(Object.keys(i.when),null,i.when,this.info):e.emptyArray;if(l.length>0&&c)throw Error(`Both when and ifExists conditions can not be applied to the same statement`);return this._client.connect().then(()=>o.getForDelete(this._client,this.info,a,l)).then(e=>{if(e.length>1&&(l.length>0||c))throw Error(`Batch with when or ifExists conditions cannot span multiple tables`);return e.map(e=>r.getDelete(e,this.info.keyspace,a,i,l,c))})}getExecutorFromQuery(e,t,n){let r=this,o=n?s.adaptAllOptions(n):null;return function(n,c){let l=o||s.adaptAllOptions(c);return r._client.execute(e,t(n),l).then(t=>{let n=r._cache.customQueries.get(e);if(n===void 0){let a=i.getCustomQueryAdapter(r.info,t);n=a.fn,a.canCache&&(r._cache.customQueries.set(e,n),r._cache.customQueries.size===100&&r._client.log(`warning`,`Custom queries cache reached 100 items, this could be caused by hard-coding parameter values inside the query, which should be avoided`))}return new a(t,r.info,n)})}}_setSingleExecutor(e,t){let n=this;return e.executor=function(e,r,o){let c=s.adaptOptions(o,t.isIdempotent);return n._client.execute(t.query,t.paramsGetter(e,r,n.info),c).then(e=>new a(e,n.info,i.getMutationAdapter(e)))},e.executor}_setBatchExecutor(e,t){let n=this,r=t.reduce((e,t)=>e&&t.isIdempotent,!0);return e.executor=function(e,o,c){let l=t.map(t=>({query:t.query,params:t.paramsGetter(e,o,n.info)})),u=s.adaptOptions(c,r);return n._client.batch(l,u).then(e=>new a(e,n.info,i.getMutationAdapter(e)))},e.executor}_validateCacheLength(e){e===100&&this._client.log(`warning`,`ModelMapper cache reached 100 items, this could be caused by building the object to map in different ways (with different shapes) each time. Use the same or few object structures for a model and represent unset values with undefined or types.unset`)}};export{MappingHandler as default};
@@ -0,0 +1 @@
1
+ import e from"./cache.js";var ModelBatchItem=class{constructor(e,t,n,r){this.doc=e,this.docInfo=t,this.handler=n,this.cache=r}getQueries(){let e=Object.keys(this.doc),t=this.cache.getOrCreate(this.getCacheKey(e),()=>({queries:null}));return t.queries===null&&(t.queries=this.createQueries(e)),t.queries}getCacheKey(e){throw Error(`getCacheKey must be implemented`)}createQueries(e){throw Error(`getCacheKey must be implemented`)}pushQueries(e){let t=!0,n;return this.getQueries().then(r=>(r.forEach(r=>{t&&=r.isIdempotent,n=r.isCounter,e.push({query:r.query,params:r.paramsGetter(this.doc,this.docInfo,this.getMappingInfo())})}),{isIdempotent:t,isCounter:n}))}getMappingInfo(){return this.handler.info}},InsertModelBatchItem=class extends ModelBatchItem{constructor(e,t,n,r){super(e,t,n,r)}getCacheKey(t){return e.getInsertKey(t,this.docInfo)}createQueries(e){return this.handler.createInsertQueries(e,this.doc,this.docInfo)}},UpdateModelBatchItem=class extends ModelBatchItem{constructor(e,t,n,r){super(e,t,n,r)}getCacheKey(t){return e.getUpdateKey(t,this.doc,this.docInfo)}createQueries(e){return this.handler.createUpdateQueries(e,this.doc,this.docInfo)}},RemoveModelBatchItem=class extends ModelBatchItem{constructor(e,t,n,r){super(e,t,n,r)}getCacheKey(t){return e.getRemoveKey(t,this.doc,this.docInfo)}createQueries(e){return this.handler.createDeleteQueries(e,this.doc,this.docInfo)}};export{InsertModelBatchItem,ModelBatchItem,RemoveModelBatchItem,UpdateModelBatchItem};
@@ -0,0 +1 @@
1
+ import e from"./tree.js";import{InsertModelBatchItem as t,RemoveModelBatchItem as n,UpdateModelBatchItem as r}from"./model-batch-item.js";var ModelBatchMapper=class{constructor(t){this._handler=t,this._cache={insert:new e,update:new e,remove:new e}}insert(e,n){return new t(e,n,this._handler,this._cache.insert)}update(e,t){return new r(e,t,this._handler,this._cache.update)}remove(e,t){return new n(e,t,this._handler,this._cache.update)}};export{ModelBatchMapper as default};
@@ -0,0 +1 @@
1
+ import e from"./model-batch-mapper.js";var ModelMapper=class{constructor(t,n){this.name=t,this._handler=n,this.batching=new e(this._handler)}get(e,t,n){return n===void 0&&typeof t==`string`&&(n=t,t=null),this._handler.getSelectExecutor(e,t,!0).then(r=>r(e,t,n)).then(e=>e.first())}find(e,t,n){return n===void 0&&typeof t==`string`&&(n=t,t=null),this._handler.getSelectExecutor(e,t,!1).then(r=>r(e,t,n))}findAll(e,t){return t===void 0&&typeof e==`string`&&(t=e,e=null),this._handler.getSelectAllExecutor(e)(e,t)}insert(e,t,n){return n===void 0&&typeof t==`string`&&(n=t,t=null),this._handler.getInsertExecutor(e,t).then(r=>r(e,t,n))}update(e,t,n){return n===void 0&&typeof t==`string`&&(n=t,t=null),this._handler.getUpdateExecutor(e,t).then(r=>r(e,t,n))}remove(e,t,n){return n===void 0&&typeof t==`string`&&(n=t,t=null),this._handler.getDeleteExecutor(e,t).then(r=>r(e,t,n))}mapWithQuery(e,t,n){return this._handler.getExecutorFromQuery(e,t,n)}};export{ModelMapper as default};
@@ -0,0 +1 @@
1
+ import{DefaultTableMappings as e,TableMappings as t}from"./table-mappings.js";var n=class ModelMappingInfo{constructor(e,t,n,r){this.keyspace=e,this.tables=t,this._mappings=n,this._columns=r,this._documentProperties=new Map;for(let e of r.values())this._documentProperties.set(e.propertyName,e)}getColumnName(e){let t=this._documentProperties.get(e);return t===void 0?this._mappings.getColumnName(e):t.columnName}getPropertyName(e){let t=this._columns.get(e);return t===void 0?this._mappings.getPropertyName(e):t.propertyName}getFromModelFn(e){let t=this._documentProperties.get(e);return t===void 0?null:t.fromModel}getToModelFn(e){let t=this._columns.get(e);return t===void 0?null:t.toModel}newInstance(){return this._mappings.newObjectInstance()}static parse(e,t){let n=new Map;return!e||!e.models||Object.keys(e.models).forEach(r=>{let i=e.models[r];n.set(r,ModelMappingInfo._create(r,t,i))}),n}static _create(n,i,a){if(!i&&(!a||!a.keyspace))throw Error(`You should specify the keyspace of the model in the MappingOptions when the Client is not using a keyspace`);if(!a)return ModelMappingInfo.createDefault(n,i);let o;if(o=a.tables&&a.tables.length>0?a.tables.map(e=>{let t={name:null,isView:!1};if(typeof e==`string`?t.name=e:e&&(t.name=e.name,t.isView=!!e.isView),!t.name)throw Error(`Table name not specified for model '${n}'`);return t}):[{name:n,isView:!1}],a.mappings&&!(a.mappings instanceof t))throw Error(`mappings should be an instance of TableMappings`);let s=new Map;return a.columns!==null&&typeof a.columns==`object`&&Object.keys(a.columns).forEach(e=>{s.set(e,r.parse(e,a.columns[e]))}),new ModelMappingInfo(a.keyspace||i,o,a.mappings||new e,s)}static createDefault(t,n){return new ModelMappingInfo(n,[{name:t,isView:!1}],new e,new Map)}},r=class ModelColumnInfo{constructor(e,t,n,r){if(this.columnName=e,this.propertyName=t,n&&typeof n!=`function`)throw TypeError(`toModel type for property '${t}' should be a function (obtained ${typeof n})`);if(r&&typeof r!=`function`)throw TypeError(`fromModel type for property '${t}' should be a function (obtained ${typeof r})`);this.toModel=n,this.fromModel=r}static parse(e,t){return t?typeof t==`string`?new ModelColumnInfo(e,t):new ModelColumnInfo(e,t.name||e,t.toModel,t.fromModel):new ModelColumnInfo(e,e)}};export{n as default};
@@ -0,0 +1 @@
1
+ const e={all:1,none:0,some:-1};var ObjectSelector=class{static getForSelect(t,n,r,i,a,o){return Promise.all(n.tables.map(e=>e.isView?t.metadata.getMaterializedView(n.keyspace,e.name):t.metadata.getTable(n.keyspace,e.name))).then(t=>{for(let s=0;s<t.length;s++){let c=t[s];if(c===null)throw Error(`Table "${n.tables[s].name}" could not be retrieved`);if(keysAreIncluded(c.partitionKeys,i)===e.all&&!(r&&keysAreIncluded(c.clusteringKeys,i)!==e.all)&&!(i.length>c.partitionKeys.length&&!i.reduce((e,t)=>e&&(contains(c.partitionKeys,e=>e.name===t.columnName)||contains(c.clusteringKeys,e=>e.name===t.columnName)),!0))&&a.reduce((e,t)=>e&&c.columnsByName[t.columnName]!==void 0,!0)&&o.reduce((e,t,n)=>{if(!e)return!1;let r=c.clusteringKeys[n];return r&&r.name===t[0]},!0))return c.name}let s=`No table matches the filter (${r?`all PKs have to be specified`:`PKs`}): [${i.map(e=>e.columnName)}]`;throw a.length>0&&(s+=`; fields: [${a.map(e=>e.columnName)}]`),o.length>0&&(s+=`; orderBy: [${o.map(e=>e[0])}]`),Error(s)})}static getForSelectAll(e){return e.tables[0].name}static getForInsert(t,n,r){return Promise.all(n.tables.filter(e=>!e.isView).map(e=>t.metadata.getTable(n.keyspace,e.name))).then(t=>{let i=t.filter((t,i)=>{if(t===null)throw Error(`Table "${n.tables[i].name}" could not be retrieved`);if(keysAreIncluded(t.partitionKeys,r)!==e.all)return!1;let a=keysAreIncluded(t.clusteringKeys,r);if(a===e.all)return!0;if(a===e.some)return!1;let o=staticColumnCount(t);return r.length===t.partitionKeys.length+o&&o>0});if(i.length===0)throw Error(`No table matches (all PKs have to be specified) fields: [${r.map(e=>e.columnName)}]`);return i})}static getForUpdate(t,n,r,i){return Promise.all(n.tables.filter(e=>!e.isView).map(e=>t.metadata.getTable(n.keyspace,e.name))).then(t=>{let a=t.filter((t,a)=>{if(t===null)throw Error(`Table "${n.tables[a].name}" could not be retrieved`);if(keysAreIncluded(t.partitionKeys,r)!==e.all)return!1;let o=keysAreIncluded(t.clusteringKeys,r);if(o===e.some||o===e.none&&!hasStaticColumn(t))return!1;let s=r.reduce((e,n)=>e+(t.columnsByName[n.columnName]===void 0?0:1),0);return s<=t.partitionKeys.length+t.clusteringKeys.length&&(!hasStaticColumn(t)||s<=t.partitionKeys.length)?!1:i.reduce((e,n)=>e&&t.columnsByName[n.columnName]!==void 0,!0)});if(a.length===0){let e=`No table matches (all PKs and columns to set have to be specified) fields: [${r.map(e=>e.columnName)}]`;throw i.length>0&&(e+=`; condition: [${i.map(e=>e.columnName)}]`),Error(e)}return a})}static getForDelete(e,t,n,r){return Promise.all(t.tables.filter(e=>!e.isView).map(n=>e.metadata.getTable(t.keyspace,n.name))).then(e=>{let i=e.filter((e,i)=>{if(e===null)throw Error(`Table "${t.tables[i].name}" could not be retrieved`);let a=e.partitionKeys.concat(e.clusteringKeys).map(e=>e.name),o=n.map(e=>e.columnName);for(let e=0;e<a.length;e++)if(o.indexOf(a[e])===-1)return!1;return r.reduce((t,n)=>t&&e.columnsByName[n.columnName]!==void 0,!0)});if(i.length===0){let e=`No table matches (all PKs have to be specified) fields: [${n.map(e=>e.columnName)}]`;throw r.length>0&&(e+=`; condition: [${r.map(e=>e.columnName)}]`),Error(e)}return i})}};function contains(e,t){return e.filter(t).length>0}function keysAreIncluded(t,n){if(t.length===0)return e.all;let r=n.reduce((e,n)=>e+ +!!contains(t,e=>n.columnName===e.name),0);return r===0?e.none:r===t.length?e.all:e.some}function hasStaticColumn(e){return staticColumnCount(e)>0}function staticColumnCount(e){return e.columns.reduce((e,t)=>e+ +!!t.isStatic,0)}export{ObjectSelector as default};
@@ -0,0 +1 @@
1
+ import e from"../errors.js";var QueryOperator=class{constructor(e,t,n,r){this.key=e,this.value=t,this.hasChildValues=n,this.isInOperator=r}},QueryAssignment=class{constructor(e,t,n){this.sign=e,this.value=t,this.inverted=!!n}};const t={in_:function(t){if(!Array.isArray(t))throw new e.ArgumentError(`IN operator supports only Array values`);return new QueryOperator(`IN`,t,!1,!0)},gt:function(e){return new QueryOperator(`>`,e)},gte:function(e){return new QueryOperator(`>=`,e)},lt:function(e){return new QueryOperator(`<`,e)},lte:function(e){return new QueryOperator(`<=`,e)},notEq:function(e){return new QueryOperator(`!=`,e)},and:function(e,t){return new QueryOperator(`AND`,[e,t],!0)},incr:function(e){return new QueryAssignment(`+`,e)},decr:function(e){return new QueryAssignment(`-`,e)},append:function(e){return new QueryAssignment(`+`,e)},prepend:function(e){return new QueryAssignment(`+`,e,!0)},remove:function(e){return new QueryAssignment(`-`,e)}};export{QueryAssignment,QueryOperator,t as q};
@@ -0,0 +1,9 @@
1
+ import e from"../types/index.js";import{QueryAssignment as t,QueryOperator as n}from"./q.js";import r from"vm";const i=e.dataTypes,a=`gen-param-getter`;var o=class QueryGenerator{static getSelect(e,t,n,r,i,a){let o=`SELECT `;return o+=r.length>0?r.map(e=>`"${e.columnName}"`).join(`, `):`*`,o+=` FROM ${t}.${e}`,n.length>0&&(o+=` WHERE `,o+=QueryGenerator._getConditionWithOperators(n)),i.length>0&&(o+=` ORDER BY `,o+=i.map(e=>`"${e[0]}" ${e[1]}`).join(`, `)),typeof a==`number`&&(o+=` LIMIT ?`),o}static selectParamsGetter(e,t){let n=`(function getParametersSelect(doc, docInfo, mappingInfo) {
2
+ `;return n+=` return [`,n+=QueryGenerator._valueGetterExpression(e),typeof t==`number`&&(e.length>0&&(n+=`, `),n+=`docInfo['limit']`),n+=`];
3
+ })`,new r.Script(n,{filename:a}).runInThisContext()}static getInsert(e,t,n,r,i){let a=r&&r.ttl,o=n.filter(t=>e.columnsByName[t.columnName]!==void 0);return{query:QueryGenerator._getInsertQuery(e.name,t,o,i,a),paramsGetter:QueryGenerator._insertParamsGetter(o,r),isIdempotent:!i}}static _getInsertQuery(e,t,n,r,i){let a=`INSERT INTO ${t}.${e} (`;return a+=n.map(e=>`"${e.columnName}"`).join(`, `),a+=`) VALUES (`,a+=n.map(()=>`?`).join(`, `),a+=`)`,r===!0&&(a+=` IF NOT EXISTS`),typeof i==`number`&&(a+=` USING TTL ?`),a}static _insertParamsGetter(e,t){let n=`(function getParametersInsert(doc, docInfo, mappingInfo) {
4
+ `;return n+=` return [`,n+=QueryGenerator._valueGetterExpression(e),t&&typeof t.ttl==`number`&&(n+=`, docInfo['ttl']`),n+=`];
5
+ })`,new r.Script(n,{filename:a}).runInThisContext()}static getUpdate(e,n,r,a,o,s){let c=a&&a.ttl,l=new Set(e.partitionKeys.concat(e.clusteringKeys).map(e=>e.name)),u=!0,d=!1,f=r.filter(n=>{let r=e.columnsByName[n.columnName];return r===void 0?!1:(r.type.code===i.list&&n.value instanceof t?u=!1:r.type.code===i.counter&&(u=!1,d=!0),!0)});return{query:QueryGenerator._getUpdateQuery(e.name,n,l,f,o,s,c),isIdempotent:u&&o.length===0&&!s,paramsGetter:QueryGenerator._updateParamsGetter(l,f,o,c),isCounter:d}}static _getUpdateQuery(e,n,r,i,a,o,s){let c=`UPDATE ${n}.${e} `;return typeof s==`number`&&(c+=`USING TTL ? `),c+=`SET `,c+=i.filter(e=>!r.has(e.columnName)).map(e=>e.value instanceof t?e.value.inverted?`"${e.columnName}" = ? ${e.value.sign} "${e.columnName}"`:`"${e.columnName}" = "${e.columnName}" ${e.value.sign} ?`:`"${e.columnName}" = ?`).join(`, `),c+=` WHERE `,c+=i.filter(e=>r.has(e.columnName)).map(e=>`"${e.columnName}" = ?`).join(` AND `),o===!0?c+=` IF EXISTS`:a.length>0&&(c+=` IF `+QueryGenerator._getConditionWithOperators(a)),c}static _updateParamsGetter(e,t,n,i){let o=`(function getParametersUpdate(doc, docInfo, mappingInfo) {
6
+ `;return o+=` return [`,typeof i==`number`&&(o+=`docInfo['ttl'], `),o+=QueryGenerator._assignmentGetterExpression(t.filter(t=>!e.has(t.columnName))),o+=`, `,o+=QueryGenerator._valueGetterExpression(t.filter(t=>e.has(t.columnName))),n.length>0&&(o+=`, `+QueryGenerator._valueGetterExpression(n,`docInfo.when`)),o+=`];
7
+ })`,new r.Script(o,{filename:a}).runInThisContext()}static getDelete(e,t,n,r,i,a){let o=r&&r.deleteOnlyColumns,s=new Set(e.partitionKeys.concat(e.clusteringKeys).map(e=>e.name)),c=n.filter(t=>e.columnsByName[t.columnName]!==void 0);return{query:QueryGenerator._getDeleteQuery(e.name,t,s,c,i,a,o),paramsGetter:QueryGenerator._deleteParamsGetter(s,c,i),isIdempotent:i.length===0&&!a}}static _getDeleteQuery(e,t,n,r,i,a,o){let s=`DELETE`;if(o){let e=r.filter(e=>!n.has(e.columnName)).map(e=>`"${e.columnName}"`).join(`, `);e!==``&&(s+=` `+e)}return s+=` FROM ${t}.${e} WHERE `,s+=r.filter(e=>n.has(e.columnName)).map(e=>`"${e.columnName}" = ?`).join(` AND `),a===!0?s+=` IF EXISTS`:i.length>0&&(s+=` IF `+QueryGenerator._getConditionWithOperators(i)),s}static _deleteParamsGetter(e,t,n){let i=`(function getParametersDelete(doc, docInfo, mappingInfo) {
8
+ `;return i+=` return [`,i+=QueryGenerator._valueGetterExpression(t.filter(t=>e.has(t.columnName))),n.length>0&&(i+=`, `+QueryGenerator._valueGetterExpression(n,`docInfo.when`)),i+=`];
9
+ })`,new r.Script(i,{filename:a}).runInThisContext()}static _valueGetterExpression(e,t){return t||=`doc`,e.map(e=>QueryGenerator._valueGetterSingle(`${t}['${e.propertyName}']`,e.propertyName,e.value,e.fromModel)).join(`, `)}static _valueGetterSingle(e,t,r,i){let a=e;if(r instanceof n){if(r.hasChildValues)return`${QueryGenerator._valueGetterSingle(`${e}.value[0]`,t,r.value[0],i)}, ${QueryGenerator._valueGetterSingle(`${e}.value[1]`,t,r.value[1],i)}`;if(a=`${e}.value`,r.isInOperator&&i)return`${a}.map(v => ${QueryGenerator._getMappingFunctionCall(t,`v`)})`}return i?QueryGenerator._getMappingFunctionCall(t,a):a}static _assignmentGetterExpression(e,n){return n||=`doc`,e.map(e=>{let r=`${n}['${e.propertyName}']${e.value instanceof t?`.value`:``}`;return e.fromModel?QueryGenerator._getMappingFunctionCall(e.propertyName,r):r}).join(`, `)}static _getConditionWithOperators(e){return e.map(e=>QueryGenerator._getSingleCondition(e.columnName,e.value)).join(` AND `)}static _getMappingFunctionCall(e,t){return`mappingInfo.getFromModelFn('${e}')(${t})`}static _getSingleCondition(e,t){return t instanceof n?t.hasChildValues?`${QueryGenerator._getSingleCondition(e,t.value[0])} ${t.key} ${QueryGenerator._getSingleCondition(e,t.value[1])}`:`"${e}" ${t.key} ?`:`"${e}" = ?`}};export{o as default};
@@ -0,0 +1,4 @@
1
+ import e from"../utils.js";import t from"../types/index.js";import n from"vm";var r=class ResultMapper{static getSelectAdapter(e,t){let r=t.columns;if(!r)throw Error(`Expected ROWS result obtained VOID`);let i=`(function rowAdapter(row, info) {
2
+ const item = info.newInstance();
3
+ `;for(let t of r)i+=` item['${e.getPropertyName(t.name)}'] = `,e.getToModelFn(t.name)?i+=`info.getToModelFn('${t.name}')(row['${t.name}']);\n`:i+=`row['${t.name}'];\n`;return i+=` return item;
4
+ })`,new n.Script(i,{filename:`gen-result-mapper`}).runInThisContext()}static getMutationAdapter(n){return n.columns===null||n.columns.length===1&&n.columns[0].name===`[applied]`&&n.columns[0].type.code===t.dataTypes.boolean?e.noop:ResultMapper._getConditionalRowAdapter(n)}static _getConditionalRowAdapter(e){return function(t,n){let r=n.newInstance();for(let i=1;i<e.columns.length;i++){let a=e.columns[i];r[n.getPropertyName(a.name)]=t[a.name]}return r}}static getCustomQueryAdapter(n,r){return r.columns===null||r.columns.length===0?{canCache:!0,fn:e.noop}:r.columns[0].name===`[applied]`&&r.columns[0].type.code===t.dataTypes.boolean?{canCache:!1,fn:ResultMapper._getConditionalRowAdapter(r)}:{canCache:!0,fn:ResultMapper.getSelectAdapter(n,r)}}};export{r as default};
@@ -0,0 +1 @@
1
+ import e from"../utils.js";import t from"util";const n=t.inspect.custom||`inspect`;var Result=class{constructor(e,t,n){this._rs=e,this._info=t,this._rowAdapter=n,this._isEmptyLwt=e.columns!==null&&e.columns.length===1&&this._rs.rowLength===1&&e.columns[0].name===`[applied]`,this.length=this._isEmptyLwt?0:e.rowLength||0,this.pageState=e.pageState}wasApplied(){return this._rs.wasApplied()}first(){return!this._rs.rowLength||this._isEmptyLwt?null:this._rowAdapter(this._rs.rows[0],this._info)}*[Symbol.iterator](){if(!this._isEmptyLwt)for(let e=0;e<this._rs.rows.length;e++)yield this._rowAdapter(this._rs.rows[e],this._info)}toArray(){return this._isEmptyLwt||!this._rs.rows?e.emptyArray:this._rs.rows.map(e=>this._rowAdapter(e,this._info))}forEach(e,t){let n=0;t||=this;for(let r of this)e.call(t,r,n++)}[n](){return this.toArray()}};export{Result as default};
@@ -0,0 +1 @@
1
+ var TableMappings=class{newObjectInstance(){return{}}getColumnName(e){return e}getPropertyName(e){return e}},UnderscoreCqlToCamelCaseMappings=class extends TableMappings{constructor(){super()}getColumnName(e){return e.replace(/[a-z][A-Z]/g,(e,t)=>e.charAt(0)+`_`+e.charAt(1)).toLowerCase()}getPropertyName(e){return e.replace(/_[a-z]/g,(e,t)=>t===0?e:e.substr(1).toUpperCase())}},DefaultTableMappings=class extends TableMappings{constructor(){super()}getColumnName(e){return super.getColumnName(e)}getPropertyName(e){return super.getPropertyName(e)}newObjectInstance(){return super.newObjectInstance()}};export{DefaultTableMappings,TableMappings,UnderscoreCqlToCamelCaseMappings};
@@ -0,0 +1 @@
1
+ import e from"events";var Node=class extends e{constructor(e,t,n){super(),this.key=e,this.value=t,this.edges=n||[]}},Tree=class extends Node{constructor(){super([],null),this.length=0}getOrCreate(e,t){typeof e.next!=`function`&&(e=e[Symbol.iterator]());let n=this,r=!1,i=e.next();for(;;){let a;for(let r=1;r<n.key.length;r++){if(i.done||n.key[r]!==i.value){a=this._createBranch(n,r,i.done,t);break}i=e.next()}if(i.done){r=!0;break}if(a!==void 0)break;let o=n.edges,s;for(let t=0;t<o.length;t++){let n=o[t];if(n.key[0]===i.value){s=n,i=e.next();break}}if(s===void 0)break;n=s}if(!r){let r=t();return n.edges.push(new Node(iteratorToArray(i.value,e),r)),this._onItemAdded(),r}return n.value===null&&n.edges.length>0&&(n.value=t()),n.value}_createBranch(e,t,n,r){let i=new Node(e.key.slice(t),e.value,e.edges);return e.key=e.key.slice(0,t),e.edges=[i],n?(e.value=r(),this._onItemAdded()):e.value=null,i}_onItemAdded(){this.length++,this.emit(`add`,this.length)}};function iteratorToArray(e,t){let n=[e],r=t.next();for(;!r.done;)n.push(r.value),r=t.next();return n}export{Tree as default};
@@ -0,0 +1 @@
1
+ function Aggregate(){this.name=null,this.keyspaceName=null,this.signature=null,this.argumentTypes=null,this.stateFunction=null,this.stateType=null,this.finalFunction=null,this.initConditionRaw=null,this.initCondition=null,this.returnType=null,this.deterministic=null}export{Aggregate as default};
@@ -0,0 +1 @@
1
+ import e from"../errors.js";import t from"util";var n=class ClientState{constructor(e,t,n){this._hosts=e,this._openConnections=t,this._inFlightQueries=n}getConnectedHosts(){return this._hosts}getOpenConnections(t){if(!t)throw new e.ArgumentError(`Host is not defined`);return this._openConnections[t.address]||0}getInFlightQueries(t){if(!t)throw new e.ArgumentError(`Host is not defined`);return this._inFlightQueries[t.address]||0}toString(){return t.format(`{"hosts": %j, "openConnections": %j, "inFlightQueries": %j}`,this._hosts.map(function(e){return e.address}),this._openConnections,this._inFlightQueries)}static from(e){let t={},n={},r=[];return e.hosts.forEach(e=>{e.pool.connections.length!==0&&(r.push(e),t[e.address]=e.pool.connections.length,n[e.address]=e.getInFlight())}),new ClientState(r,t,n)}};export{n as default};
@@ -0,0 +1 @@
1
+ import e from"util";import t from"events";function DataCollection(e){t.EventEmitter.call(this),this.setMaxListeners(0),Object.defineProperty(this,`loading`,{value:!1,enumerable:!1,writable:!0}),Object.defineProperty(this,`loaded`,{value:!1,enumerable:!1,writable:!0}),this.name=e,this.bloomFilterFalsePositiveChance=0,this.caching=null,this.comment=null,this.gcGraceSeconds=0,this.compactionClass=null,this.compactionOptions=null,this.compression=null,this.localReadRepairChance=0,this.readRepairChance=0,this.extensions=null,this.crcCheckChance=null,this.populateCacheOnFlush=!1,this.defaultTtl=0,this.speculativeRetry=`NONE`,this.minIndexInterval=128,this.maxIndexInterval=2048,this.columns=null,this.columnsByName=null,this.partitionKeys=[],this.clusteringKeys=[],this.clusteringOrder=[],this.nodesync=null}e.inherits(DataCollection,t.EventEmitter);export{DataCollection as default};
@@ -0,0 +1 @@
1
+ import e from"../promise-utils.js";import t from"../utils.js";import n from"util";const r=1e3;var EventDebouncer=class{constructor(e,t){this._delay=e,this._logger=t,this._queue=null,this._timeout=null}eventReceived(t,i){return new Promise((a,o)=>{t.callback=e.getCallback(a,o),this._queue=this._queue||{callbacks:[],keyspaces:{}};let s=i?0:this._delay;if(t.all&&(this._queue.mainEvent=t),this._queue.callbacks.length===r&&this._logger(`warn`,n.format(`Event debouncer queue exceeded %d events`,r)),this._queue.callbacks.push(t.callback),this._queue.mainEvent)return this._slideDelay(s);let c=this._queue.keyspaces[t.keyspace];c||=this._queue.keyspaces[t.keyspace]={events:[]},t.cqlObject===void 0&&(c.mainEvent=t),c.events.push(t),this._slideDelay(s)})}_slideDelay(e){let t=this;function process(){let e=t._queue;t._queue=null,t._timeout=null,processQueue(e)}if(e===0)return this._timeout&&clearTimeout(this._timeout),process();let n=this._timeout;this._timeout=setTimeout(process,e),n&&clearTimeout(n)}shutdown(){this._queue&&(this._queue.callbacks.forEach(function(e){e()}),this._queue=null,clearTimeout(this._timeout),this._timeout=null)}};function processQueue(n){if(n.mainEvent)return e.toCallback(n.mainEvent.handler(),e=>{for(let t=0;t<n.callbacks.length;t++)n.callbacks[t](e)});t.each(Object.keys(n.keyspaces),function(t,r){let i=n.keyspaces[t];if(i.mainEvent)return e.toCallback(i.mainEvent.handler(),function(e){for(let t=0;t<i.events.length;t++)i.events[t].callback(e);r()});i.events.forEach(e=>{e.handler(),e.callback()}),r()})}export{EventDebouncer as default};
@@ -1,7 +1,7 @@
1
1
  import { types } from "../types/index.js";
2
- import { EmptyCallback, Host, ValueCallback, token } from "../../index.js";
2
+ import { EmptyCallback, Host, ValueCallback, token } from "../index.js";
3
3
 
4
- //#region src/driver/lib/metadata/index.d.ts
4
+ //#region src/driver/metadata/index.d.ts
5
5
  declare namespace metadata {
6
6
  interface Aggregate {
7
7
  argumentTypes: Array<{
@@ -0,0 +1 @@
1
+ import e from"../errors.js";import t from"../promise-utils.js";import n from"../utils.js";import r from"../types/index.js";import{ExecutionOptions as i}from"../execution-options.js";import a from"../requests.js";import{TokenRange as o}from"../token.js";import s from"../tokenizer.js";import c from"./schema-parser.js";import l from"util";import u from"events";var Metadata=class{constructor(t,r){if(!t)throw new e.ArgumentError(`Options are not defined`);Object.defineProperty(this,`options`,{value:t,enumerable:!1,writable:!1}),Object.defineProperty(this,`controlConnection`,{value:r,enumerable:!1,writable:!1}),this.keyspaces={},this.initialized=!1,this._isDbaas=!1,this._schemaParser=c.getByVersion(t,r,this.getUdt.bind(this)),this.log=n.log,this._preparedQueries=new PreparedQueries(t.maxPrepared,(...e)=>this.log(...e))}setCassandraVersion(e){this._schemaParser=c.getByVersion(this.options,this.controlConnection,this.getUdt.bind(this),e,this._schemaParser)}isDbaas(){return this._isDbaas}setProductTypeAsDbaas(){this._isDbaas=!0}setPartitioner(e){return/RandomPartitioner$/.test(e)?this.tokenizer=new s.RandomTokenizer:/ByteOrderedPartitioner$/.test(e)?this.tokenizer=new s.ByteOrderedTokenizer:this.tokenizer=new s.Murmur3Tokenizer}buildTokens(e){if(!this.tokenizer)return this.log(`error`,`Tokenizer could not be determined`);let t=[],r={},i=e.values(),a=this.tokenizer.stringify,s={};i.forEach(e=>{if(!e.tokens)return;e.tokens.forEach(i=>{let o=this.tokenizer.parse(i);n.insertSorted(t,o,(e,t)=>e.compare(t)),r[a(o)]=e});let i=s[e.datacenter];i||=s[e.datacenter]={hostLength:0,racks:new n.HashSet},i.hostLength++,i.racks.add(e.rack)}),this.primaryReplicas=r,this.ring=t;let c=new Set;if(this.ring.length===1){let e=this.tokenizer.minToken();c.add(new o(e,e,this.tokenizer))}else for(let e=0;e<this.ring.length;e++){let t=this.ring[e],n=this.ring[(e+1)%this.ring.length];c.add(new o(t,n,this.tokenizer))}this.tokenRanges=c,this.ringTokensAsStrings=Array(t.length);for(let e=0;e<t.length;e++)this.ringTokensAsStrings[e]=a(t[e]);this.datacenters=s}refreshKeyspace(e,n){return t.optionalCallback(this._refreshKeyspace(e),n)}async _refreshKeyspace(e){if(!this.initialized)throw this._uninitializedError();this.log(`info`,l.format(`Retrieving keyspace %s metadata`,e));try{let t=await this._schemaParser.getKeyspace(e);return t?(this.keyspaces[t.name]=t,t):(delete this.keyspaces[e],null)}catch(e){throw this.log(`error`,`There was an error while trying to retrieve keyspace information`,e),e}}refreshKeyspaces(e,n){if((typeof e==`function`||e===void 0)&&(n=e,e=!0),!this.initialized){let e=this._uninitializedError();return n?n(e):Promise.reject(e)}return t.optionalCallback(this.refreshKeyspacesInternal(e),n)}async refreshKeyspacesInternal(e){this.log(`info`,`Retrieving keyspaces metadata`);try{return this.keyspaces=await this._schemaParser.getKeyspaces(e),this.keyspaces}catch(e){throw this.log(`error`,`There was an error while trying to retrieve keyspaces information`,e),e}}_getKeyspaceReplicas(e){return e.replicas||=e.tokenToReplica(this.tokenizer,this.ringTokensAsStrings,this.primaryReplicas,this.datacenters),e.replicas}getReplicas(e,t){if(!this.ring)return null;Buffer.isBuffer(t)&&(t=this.tokenizer.hash(t)),t instanceof o&&(t=t.end);let r;if(e&&(r=this.keyspaces[e],!r))return null;let i=n.binarySearch(this.ring,t,(e,t)=>e.compare(t));i<0&&(i=~i),i>=this.ring.length&&(i%=this.ring.length);let a=this.ringTokensAsStrings[i];return e?this._getKeyspaceReplicas(r)[a]:[this.primaryReplicas[a]]}getTokenRanges(){return this.tokenRanges}getTokenRangesForHost(e,t){if(!this.ring)return null;let n;if(e&&(n=this.keyspaces[e],!n))return null;if(this.ring.length===1)return this.getTokenRanges();let r=this._getKeyspaceReplicas(n),i=new Set;return this.tokenRanges.forEach(e=>{r[this.tokenizer.stringify(e.end)].indexOf(t)!==-1&&i.add(e)}),i}newToken(e){if(!this.tokenizer)throw Error(`Partitioner not established. This should only happen if metadata was disabled or you have not connected yet.`);return Array.isArray(e)?this.tokenizer.hash(Buffer.concat(e)):typeof e==`string`?this.tokenizer.parse(e):this.tokenizer.hash(e)}newTokenRange(e,t){if(!this.tokenizer)throw Error(`Partitioner not established. This should only happen if metadata was disabled or you have not connected yet.`);return new o(e,t,this.tokenizer)}getPreparedInfo(e,t){return this._preparedQueries.getOrAdd(e,t)}clearPrepared(){this._preparedQueries.clear()}getPreparedById(e){return this._preparedQueries.getById(e)}setPreparedById(e){return this._preparedQueries.setById(e)}getAllPrepared(){return this._preparedQueries.getAll()}_uninitializedError(){return Error(`Metadata has not been initialized. This could only happen if you have not connected yet.`)}getUdt(e,n,r){return t.optionalCallback(this._getUdt(e,n),r)}async _getUdt(e,t){if(!this.initialized)throw this._uninitializedError();let n;if(this.options.isMetadataSyncEnabled){let t=this.keyspaces[e];if(!t)return null;n=t.udts}return await this._schemaParser.getUdt(e,t,n)}getTable(e,n,r){return t.optionalCallback(this._getTable(e,n),r)}async _getTable(e,t){if(!this.initialized)throw this._uninitializedError();let n,r;if(this.options.isMetadataSyncEnabled){let t=this.keyspaces[e];if(!t)return null;n=t.tables,r=t.virtual}return await this._schemaParser.getTable(e,t,n,r)}getFunctions(e,n,r){return t.optionalCallback(this._getFunctionsWrapper(e,n),r)}async _getFunctionsWrapper(t,n){if(!t||!n)throw new e.ArgumentError(`You must provide the keyspace name and cql function name to retrieve the metadata`);let r=await this._getFunctions(t,n,!1);return Array.from(r.values())}getFunction(e,n,r,i){return t.optionalCallback(this._getSingleFunction(e,n,r,!1),i)}getAggregates(e,n,r){return t.optionalCallback(this._getAggregates(e,n),r)}async _getAggregates(t,n){if(!t||!n)throw new e.ArgumentError(`You must provide the keyspace name and cql aggregate name to retrieve the metadata`);let r=await this._getFunctions(t,n,!0);return Array.from(r.values())}getAggregate(e,n,r,i){return t.optionalCallback(this._getSingleFunction(e,n,r,!0),i)}getMaterializedView(e,n,r){return t.optionalCallback(this._getMaterializedView(e,n),r)}async _getMaterializedView(e,t){if(!this.initialized)throw this._uninitializedError();let n;if(this.options.isMetadataSyncEnabled){let t=this.keyspaces[e];if(!t)return null;n=t.views}return await this._schemaParser.getMaterializedView(e,t,n)}async _getFunctions(e,t,n){if(!this.initialized)throw this._uninitializedError();let r;if(this.options.isMetadataSyncEnabled){let t=this.keyspaces[e];if(!t)return new Map;r=n?t.aggregates:t.functions}return await this._schemaParser.getFunctions(e,t,n,r)}async _getSingleFunction(t,n,i,a){if(!t||!n)throw new e.ArgumentError(`You must provide the keyspace name and cql function name to retrieve the metadata`);if(!Array.isArray(i))throw new e.ArgumentError(`Signature must be an array of types`);return i=i.map(e=>typeof e==`string`?e:r.getDataTypeNameByCode(e)),(await this._getFunctions(t,n,a)).get(i.join(`,`))||null}getTrace(e,n,r){return!r&&typeof n==`function`&&(r=n,n=null),t.optionalCallback(this._getTrace(e,n),r)}async _getTrace(e,n){if(!this.initialized)throw this._uninitializedError();let r,o=0,s=i.empty();s.getConsistency=()=>n;let c=new a.QueryRequest(l.format(`SELECT * FROM system_traces.sessions WHERE session_id=%s`,e),null,s),u=new a.QueryRequest(l.format(`SELECT * FROM system_traces.events WHERE session_id=%s`,e),null,s);for(;!r&&o++<5;){let e=(await this.controlConnection.query(c)).rows[0];if(!e||typeof e.duration!=`number`){await t.delay(400);continue}r={requestType:e.request,coordinator:e.coordinator,parameters:e.parameters,startedAt:e.started_at,duration:e.duration,clientAddress:e.client,events:null};let n=await this.controlConnection.query(u);r.events=n.rows.map(e=>({id:e.event_id,activity:e.activity,source:e.source,elapsed:e.source_elapsed,thread:e.thread}))}if(!r)throw Error(`Trace ${e.toString()} could not fully retrieved after 5 attempts`);return r}checkSchemaAgreement(e){return t.optionalCallback(this._checkSchemaAgreement(),e)}async _checkSchemaAgreement(){let e=this.controlConnection.connection;if(!e)return!1;try{return await this.compareSchemaVersions(e)}catch{return!1}}async adaptUserHints(e,t){if(!Array.isArray(t))return;let n=[];for(let i=0;i<t.length;i++){let a=t[i];if(typeof a!=`string`)continue;let o=r.dataTypes.getByName(a);this._checkUdtTypes(n,o,e),t[i]=o}for(let e of n){let t=await this.getUdt(e.info.keyspace,e.info.name);if(!t)throw TypeError(`User defined type not found: `+e.info.keyspace+`.`+e.info.name);e.info=t}}_checkUdtTypes(e,t,n){if(t.code===r.dataTypes.udt){let r=t.info.split(`.`);if(t.info={keyspace:r[0],name:r[1]},!t.info.name){if(!n)throw TypeError(`No keyspace specified for udt: `+r.join(`.`));t.info.name=t.info.keyspace,t.info.keyspace=n}e.push(t);return}if(t.info){if(t.code===r.dataTypes.list||t.code===r.dataTypes.set)return this._checkUdtTypes(e,t.info,n);t.code===r.dataTypes.map&&(this._checkUdtTypes(e,t.info[0],n),this._checkUdtTypes(e,t.info[1],n))}}async compareSchemaVersions(e){let t=new Set,n=await e.send(new a.QueryRequest(`SELECT schema_version FROM system.local`),null);n&&n.rows&&n.rows.length===1&&t.add(n.rows[0].schema_version.toString());let r=await e.send(new a.QueryRequest(`SELECT schema_version FROM system.peers`),null);if(r&&r.rows)for(let e of r.rows){let n=e.schema_version;n&&t.add(n.toString())}return t.size===1}},PreparedQueries=class{constructor(e,t){this.length=0,this._maxPrepared=e,this._mapByKey=new Map,this._mapById=new Map,this._logger=t}_getKey(e,t){return(e||``)+t}getOrAdd(e,t){let n=this._getKey(e,t),r=this._mapByKey.get(n);return r||(this._validateOverflow(),r=new u.EventEmitter,r.setMaxListeners(0),r.query=t,r.keyspace=e,this._mapByKey.set(n,r),this.length++,r)}_validateOverflow(){if(this.length<this._maxPrepared)return;let e=[];this._logger(`warning`,`Prepared statements exceeded maximum. This could be caused by preparing queries that contain parameters`);let t=this.length-this._maxPrepared+1;for(let[n,r]of this._mapByKey)if(r.queryId&&e.push([n,r])>=t)break;for(let[t,n]of e)this._mapByKey.delete(t),this._mapById.delete(n.queryId.toString(`hex`)),this.length--}setById(e){this._mapById.set(e.queryId.toString(`hex`),e)}getById(e){return this._mapById.get(e.toString(`hex`))}clear(){this._mapByKey=new Map,this._mapById=new Map,this.length=0}getAll(){return Array.from(this._mapByKey.values()).filter(e=>!!e.queryId)}};export{Metadata as default};
@@ -0,0 +1 @@
1
+ import e from"./data-collection.js";import t from"util";function MaterializedView(t){e.call(this,t),this.tableName=null,this.whereClause=null,this.includeAllColumns=!1}t.inherits(MaterializedView,e);export{MaterializedView as default};
@@ -0,0 +1 @@
1
+ function SchemaFunction(){this.name=null,this.keyspaceName=null,this.signature=null,this.argumentNames=null,this.argumentTypes=null,this.body=null,this.calledOnNullInput=null,this.language=null,this.returnType=null,this.deterministic=null,this.monotonic=null,this.monotonicOn=null}export{SchemaFunction as default};
@@ -0,0 +1 @@
1
+ import e from"../utils.js";import t from"../types/index.js";import n from"util";const r={custom:0,keys:1,composites:2};function Index(e,t,n,r){this.name=e,this.target=t,this.kind=typeof n==`string`?getKindByName(n):n,this.options=r}Index.prototype.isCompositesKind=function(){return this.kind===r.composites},Index.prototype.isKeysKind=function(){return this.kind===r.keys},Index.prototype.isCustomKind=function(){return this.kind===r.custom},Index.fromRows=function(t){return!t||t.length===0?e.emptyArray:t.map(function(e){let t=e.options;return new Index(e.index_name,t.target,getKindByName(e.kind),t)})},Index.fromColumnRows=function(e,r){let i=[];for(let a=0;a<e.length;a++){let o=e[a],s=o.index_name;if(!s)continue;let c=r[o.column_name],l,u=JSON.parse(o.index_options);l=u!==null&&u.index_keys!==void 0?n.format(`keys(%s)`,c.name):u!==null&&u.index_keys_and_values!==void 0?n.format(`entries(%s)`,c.name):c.type.options.frozen&&(c.type.code===t.dataTypes.map||c.type.code===t.dataTypes.list||c.type.code===t.dataTypes.set)?n.format(`full(%s)`,c.name):c.name,i.push(new Index(s,l,getKindByName(o.index_type),u))}return i};function getKindByName(e){return e?r[e.toLowerCase()]:r.custom}export{Index as default};
@@ -0,0 +1 @@
1
+ import e from"../errors.js";import t from"../promise-utils.js";import n from"../utils.js";import r from"../types/index.js";import i from"./table-metadata.js";import a from"./aggregate.js";import o from"./schema-function.js";import s from"./schema-index.js";import c from"./materialized-view.js";import l from"util";import u from"events";const{format:d}=l,f=`SELECT * FROM system_schema.keyspaces`,p=`SELECT * FROM system_schema.keyspaces where keyspace_name = '%s'`,m=`SELECT * FROM system_virtual_schema.tables where keyspace_name = '%s' and table_name='%s'`;var SchemaParser=class{constructor(e,t){this.cc=t,this.encodingOptions=e.encoding,this.selectTable=null,this.selectColumns=null,this.selectIndexes=null,this.selectUdt=null,this.selectAggregates=null,this.selectFunctions=null,this.supportsVirtual=!1}_createKeyspace(e,t,n,r,i){return{name:e,durableWrites:t,strategy:n,strategyOptions:r,virtual:i===!0,udts:{},tables:{},functions:{},aggregates:{},views:{},tokenToReplica:getTokenToReplicaMapper(n,r),graphEngine:void 0}}getKeyspace(e){}getKeyspaces(e){}async getTable(e,n,r,a){let o=r&&r[n];if(o||(o=new i(n),r&&(r[n]=o)),o.loaded)return o;if(o.loading)return t.fromEvent(o,`load`);try{o.loading=!0;let t,r=a,i=r?m:this.selectTable,s=l.format(i,e,n),c=await this._getFirstRow(s);if(!c&&this.supportsVirtual&&r===void 0){let t=l.format(m,e,n);try{c=await this._getFirstRow(t)}catch{}c&&(r=!0)}if(!c)return o.loading=!1,o.emit(`load`,null,null),null;let u=r?`SELECT * FROM system_virtual_schema.columns where keyspace_name = '%s' and table_name='%s'`:this.selectColumns,d=await this._getRows(l.format(u,e,n));return this.selectIndexes&&!r&&(t=await this._getRows(l.format(this.selectIndexes,e,n))),await this._parseTableOrView(o,c,d,t,r),o.loaded=!0,o.emit(`load`,null,o),o}catch(e){throw o.emit(`load`,e,null),e}finally{o.loading=!1}}async _getFirstRow(e){return(await this._getRows(e))[0]}async _getRows(e){return(await this.cc.query(e)).rows}async getUdt(e,n,r){let i=r&&r[n];if(i||(i=new u.EventEmitter,r&&(r[n]=i),i.setMaxListeners(0),i.loading=!1,i.name=n,i.keyspace=e,i.fields=null),i.fields)return i;if(i.loading)return t.fromEvent(i,`load`);i.loading=!0;let a=d(this.selectUdt,e,n);try{let e=await this._getFirstRow(a);return e?(await this._parseUdt(i,e),i.emit(`load`,null,i),i):(i.loading=!1,i.emit(`load`,null,null),null)}catch(e){throw i.emit(`load`,e),e}finally{i.loading=!1}}_parseUdt(e,t){}async _parseTableOrView(e,t,n,r,i){}getMaterializedView(e,t,n){}async getFunctions(e,n,r,i){let a=this.selectFunctions,parser=e=>this._parseFunction(e);r&&(a=this.selectAggregates,parser=e=>this._parseAggregate(e));let o=i&&i[n];if(o||(o=new u.EventEmitter,i&&(i[n]=o),o.setMaxListeners(0)),o.values)return o.values;if(o.loading)return t.fromEvent(o,`load`);o.loading=!0;try{let t=await this._getRows(d(a,e,n)),r=await Promise.all(t.map(parser)),i=new Map;return t.length>0&&(o.values=i),r.forEach(e=>o.values.set(e.signature.join(`,`),e)),o.emit(`load`,null,i),i}catch(e){throw o.emit(`load`,e),e}finally{o.loading=!1}}_parseAggregate(e){}_parseFunction(e){}_asMap(e){return e?this.encodingOptions.map&&e instanceof this.encodingOptions.map?e:new Map(Object.keys(e).map(t=>[t,e[t]])):new Map}_mapAsObject(e){if(!e)return e;if(this.encodingOptions.map&&e instanceof this.encodingOptions.map){let t={};return e.forEach((e,n)=>t[n]=e),t}return e}},SchemaParserV1=class extends SchemaParser{constructor(e,t){super(e,t),this.selectTable=`SELECT * FROM system.schema_columnfamilies WHERE keyspace_name='%s' AND columnfamily_name='%s'`,this.selectColumns=`SELECT * FROM system.schema_columns WHERE keyspace_name='%s' AND columnfamily_name='%s'`,this.selectUdt=`SELECT * FROM system.schema_usertypes WHERE keyspace_name='%s' AND type_name='%s'`,this.selectAggregates=`SELECT * FROM system.schema_aggregates WHERE keyspace_name = '%s' AND aggregate_name = '%s'`,this.selectFunctions=`SELECT * FROM system.schema_functions WHERE keyspace_name = '%s' AND function_name = '%s'`}async getKeyspaces(e){let t={},n=await this.cc.query(`SELECT * FROM system.schema_keyspaces`,e);for(let e=0;e<n.rows.length;e++){let r=n.rows[e],i=this._createKeyspace(r.keyspace_name,r.durable_writes,r.strategy_class,JSON.parse(r.strategy_options||null));t[i.name]=i}return t}async getKeyspace(e){let t=await this._getFirstRow(d(`SELECT * FROM system.schema_keyspaces where keyspace_name = '%s'`,e));return t?this._createKeyspace(t.keyspace_name,t.durable_writes,t.strategy_class,JSON.parse(t.strategy_options)):null}async _parseTableOrView(e,t,r,i,a){let o,c,l,u=this.cc.getEncoder(),d={},f=[],p=[];e.bloomFilterFalsePositiveChance=t.bloom_filter_fp_chance,e.caching=t.caching,e.comment=t.comment,e.compactionClass=t.compaction_strategy_class,e.compactionOptions=JSON.parse(t.compaction_strategy_options),e.compression=JSON.parse(t.compression_parameters),e.gcGraceSeconds=t.gc_grace_seconds,e.localReadRepairChance=t.local_read_repair_chance,e.readRepairChance=t.read_repair_chance,e.populateCacheOnFlush=t.populate_io_cache_on_flush||e.populateCacheOnFlush,e.memtableFlushPeriod=t.memtable_flush_period_in_ms||e.memtableFlushPeriod,e.defaultTtl=t.default_time_to_live||e.defaultTtl,e.speculativeRetry=t.speculative_retry||e.speculativeRetry,e.indexInterval=t.index_interval||e.indexInterval,t.min_index_interval===void 0?(e.minIndexInterval=null,e.maxIndexInterval=null):(e.minIndexInterval=t.min_index_interval||e.minIndexInterval,e.maxIndexInterval=t.max_index_interval||e.maxIndexInterval),t.replicate_on_write!==void 0&&(e.replicateOnWrite=t.replicate_on_write),e.columns=[];for(let t=0;t<r.length;t++){let n=r[t],i=u.parseFqTypeName(n.validator);switch(o={name:n.column_name,type:i,isStatic:!1},e.columns.push(o),d[o.name]=o,n.type){case`partition_key`:f.push({c:o,index:n.component_index||0});break;case`clustering_key`:p.push({c:o,index:n.component_index||0,order:o.type.options.reversed?`DESC`:`ASC`});break;case`static`:o.isStatic=!0;break}}f.length>0&&(e.partitionKeys=f.sort(n.propCompare(`index`)).map(e=>e.c),p.sort(n.propCompare(`index`)),e.clusteringKeys=p.map(e=>e.c),e.clusteringOrder=p.map(e=>e.order));let m=e.partitionKeys.length===0;if(m&&t.key_aliases){f=JSON.parse(t.key_aliases),l=u.parseKeyTypes(t.key_validator).types;for(let t=0;t<f.length;t++)c=f[t],o=d[c],o||(o={name:c,type:l[t]},e.columns.push(o)),e.partitionKeys.push(o)}let h=u.parseKeyTypes(t.comparator);if(m&&t.column_aliases){p=JSON.parse(t.column_aliases);for(let t=0;t<p.length;t++)c=p[t],o=d[c],o||(o={name:c,type:h.types[t]},e.columns.push(o)),e.clusteringKeys.push(o),e.clusteringOrder.push(o.type.options.reversed?`DESC`:`ASC`)}e.isCompact=!!t.is_dense,e.isCompact||=!h.isComposite||!h.hasCollections&&e.clusteringKeys.length!==h.types.length-1,c=t.value_alias,e.isCompact&&c&&!d[c]&&(o={name:c,type:u.parseFqTypeName(t.default_validator)},e.columns.push(o),d[c]=o),e.columnsByName=d,e.indexes=s.fromColumnRows(r,e.columnsByName)}getMaterializedView(t,n,r){return Promise.reject(new e.NotSupportedError(`Materialized views are not supported on Cassandra versions below 3.0`))}async _parseAggregate(e){let t=this.cc.getEncoder(),r=new a;r.name=e.aggregate_name,r.keyspaceName=e.keyspace_name,r.signature=e.signature||n.emptyArray,r.stateFunction=e.state_func,r.finalFunction=e.final_func,r.initConditionRaw=e.initcond,r.argumentTypes=(e.argument_types||n.emptyArray).map(e=>t.parseFqTypeName(e)),r.stateType=t.parseFqTypeName(e.state_type);let i=t.decode(r.initConditionRaw,r.stateType);return i!=null&&(r.initCondition=i.toString()),r.returnType=t.parseFqTypeName(e.return_type),r}async _parseFunction(e){let t=this.cc.getEncoder(),r=new o;return r.name=e.function_name,r.keyspaceName=e.keyspace_name,r.signature=e.signature||n.emptyArray,r.argumentNames=e.argument_names||n.emptyArray,r.body=e.body,r.calledOnNullInput=e.called_on_null_input,r.language=e.language,r.argumentTypes=(e.argument_types||n.emptyArray).map(e=>t.parseFqTypeName(e)),r.returnType=t.parseFqTypeName(e.return_type),r}async _parseUdt(e,t){let n=this.cc.getEncoder(),r=t.field_names,i=t.field_types,a=Array(r.length);for(let e=0;e<r.length;e++)a[e]={name:r[e],type:n.parseFqTypeName(i[e])};return e.fields=a,e}},SchemaParserV2=class extends SchemaParser{constructor(e,t,n){super(e,t),this.udtResolver=n,this.selectTable=`SELECT * FROM system_schema.tables WHERE keyspace_name='%s' AND table_name='%s'`,this.selectColumns=`SELECT * FROM system_schema.columns WHERE keyspace_name='%s' AND table_name='%s'`,this.selectUdt=`SELECT * FROM system_schema.types WHERE keyspace_name='%s' AND type_name='%s'`,this.selectAggregates=`SELECT * FROM system_schema.aggregates WHERE keyspace_name = '%s' AND aggregate_name = '%s'`,this.selectFunctions=`SELECT * FROM system_schema.functions WHERE keyspace_name = '%s' AND function_name = '%s'`,this.selectIndexes=`SELECT * FROM system_schema.indexes WHERE keyspace_name='%s' AND table_name='%s'`}async getKeyspaces(e){let t={},n=await this.cc.query(f,e);for(let e=0;e<n.rows.length;e++){let r=this._parseKeyspace(n.rows[e]);t[r.name]=r}return t}async getKeyspace(e){let t=await this._getFirstRow(d(p,e));return t?this._parseKeyspace(t):null}async getMaterializedView(e,n,r){let i=r&&r[n];if(i||(i=new c(n),r&&(r[n]=i)),i.loaded)return i;if(i.loading)return t.fromEvent(i,`load`);i.loading=!0;try{let t=await this._getFirstRow(d(`SELECT * FROM system_schema.views WHERE keyspace_name = '%s' AND view_name = '%s'`,e,n));if(!t)return i.emit(`load`,null,null),i.loading=!1,null;let r=await this._getRows(d(this.selectColumns,e,n));return await this._parseTableOrView(i,t,r,null,!1),i.loaded=!0,i.emit(`load`,null,i),i}catch(e){throw i.emit(`load`,e),e}finally{i.loading=!1}}_parseKeyspace(e,t){let n=e.replication,r,i;if(n){r=n.class,i={};for(let e in n)!n.hasOwnProperty(e)||e===`class`||(i[e]=n[e])}let a=this._createKeyspace(e.keyspace_name,e.durable_writes,r,i,t);return a.graphEngine=e.graph_engine,a}async _parseTableOrView(e,t,r,i,a){let o=this.cc.getEncoder(),s={},l=[],u=[];if(e.columns=await Promise.all(r.map(async e=>{let n=await o.parseTypeName(t.keyspace_name,e.type,0,null,this.udtResolver),r={name:e.column_name,type:n,isStatic:!1};switch(s[r.name]=r,e.kind){case`partition_key`:l.push({c:r,index:e.position||0});break;case`clustering`:u.push({c:r,index:e.position||0,order:e.clustering_order===`desc`?`DESC`:`ASC`});break;case`static`:r.isStatic=!0;break}return r})),e.columnsByName=s,e.partitionKeys=l.sort(n.propCompare(`index`)).map(e=>e.c),u.sort(n.propCompare(`index`)),e.clusteringKeys=u.map(e=>e.c),e.clusteringOrder=u.map(e=>e.order),a){e.virtual=!0;return}let d=e instanceof c;e.bloomFilterFalsePositiveChance=t.bloom_filter_fp_chance,e.caching=JSON.stringify(t.caching),e.comment=t.comment;let f=this._asMap(t.compaction);if(f&&(e.compactionOptions={},e.compactionClass=f.get(`class`),f.forEach((t,n)=>{n!==`class`&&(e.compactionOptions[n]=f.get(n))})),e.compression=this._mapAsObject(t.compression),e.gcGraceSeconds=t.gc_grace_seconds,e.localReadRepairChance=t.dclocal_read_repair_chance,e.readRepairChance=t.read_repair_chance,e.extensions=this._mapAsObject(t.extensions),e.crcCheckChance=t.crc_check_chance,e.memtableFlushPeriod=t.memtable_flush_period_in_ms||e.memtableFlushPeriod,e.defaultTtl=t.default_time_to_live||e.defaultTtl,e.speculativeRetry=t.speculative_retry||e.speculativeRetry,e.minIndexInterval=t.min_index_interval||e.minIndexInterval,e.maxIndexInterval=t.max_index_interval||e.maxIndexInterval,e.nodesync=t.nodesync||e.nodesync,!d){let n=t.cdc;n!==void 0&&(e.cdc=n)}if(d){e.tableName=t.base_table_name,e.whereClause=t.where_clause,e.includeAllColumns=t.include_all_columns;return}e.indexes=this._getIndexes(i);let p=t.flags;Array.isArray(p)&&(p=new Set(p));let m=p.has(`dense`),h=p.has(`super`),g=p.has(`compound`);e.isCompact=h||m||!g,!h&&!m&&!g?pruneStaticCompactTableColumns(e):m&&pruneDenseTableColumns(e)}_getIndexes(e){return!e||e.length===0?n.emptyArray:e.map(e=>{let t=this._mapAsObject(e.options);return new s(e.index_name,t.target,e.kind,t)})}async _parseAggregate(e){let t=this.cc.getEncoder(),r=new a;return r.name=e.aggregate_name,r.keyspaceName=e.keyspace_name,r.signature=e.argument_types||n.emptyArray,r.stateFunction=e.state_func,r.finalFunction=e.final_func,r.initConditionRaw=e.initcond,r.initCondition=r.initConditionRaw,r.deterministic=e.deterministic||!1,r.argumentTypes=await Promise.all(r.signature.map(n=>t.parseTypeName(e.keyspace_name,n,0,null,this.udtResolver))),r.stateType=await t.parseTypeName(e.keyspace_name,e.state_type,0,null,this.udtResolver),r.returnType=await t.parseTypeName(e.keyspace_name,e.return_type,0,null,this.udtResolver),r}async _parseFunction(e){let t=this.cc.getEncoder(),r=new o;return r.name=e.function_name,r.keyspaceName=e.keyspace_name,r.signature=e.argument_types||n.emptyArray,r.argumentNames=e.argument_names||n.emptyArray,r.body=e.body,r.calledOnNullInput=e.called_on_null_input,r.language=e.language,r.deterministic=e.deterministic||!1,r.monotonic=e.monotonic||!1,r.monotonicOn=e.monotonic_on||n.emptyArray,r.argumentTypes=await Promise.all(r.signature.map(n=>t.parseTypeName(e.keyspace_name,n,0,null,this.udtResolver))),r.returnType=await t.parseTypeName(e.keyspace_name,e.return_type,0,null,this.udtResolver),r}async _parseUdt(e,t){let n=this.cc.getEncoder(),r=t.field_types,i=t.keyspace_name;return e.fields=await Promise.all(t.field_names.map(async(e,t)=>({name:e,type:await n.parseTypeName(i,r[t],0,null,this.udtResolver)}))),e}},SchemaParserV3=class extends SchemaParserV2{constructor(e,t,n){super(e,t,n),this.supportsVirtual=!0}async getKeyspaces(e){let t={},n=[{query:f,virtual:!1},{query:`SELECT * FROM system_virtual_schema.keyspaces`,virtual:!0}];return await Promise.all(n.map(async n=>{let r=null;try{r=await this.cc.query(n.query,e)}catch(e){if(n.virtual)return;throw e}for(let e=0;e<r.rows.length;e++){let i=this._parseKeyspace(r.rows[e],n.virtual);t[i.name]=i}})),t}async getKeyspace(e){return await this._getKeyspace(p,e,!1)||this._getKeyspace(`SELECT * FROM system_virtual_schema.keyspaces where keyspace_name = '%s'`,e,!0)}async _getKeyspace(e,t,n){try{let r=await this._getFirstRow(d(e,t));return r?this._parseKeyspace(r,n):null}catch(e){if(n)return null;throw e}}};function pruneStaticCompactTableColumns(e){let t,r;for(t=0;t<e.clusteringKeys.length;t++){r=e.clusteringKeys[t];let n=e.columns.indexOf(r);e.columns.splice(n,1),delete e.columnsByName[r.name]}for(e.clusteringKeys=n.emptyArray,e.clusteringOrder=n.emptyArray,t=e.columns.length;t--;){if(r=e.columns[t],!r.isStatic&&e.partitionKeys.indexOf(r)===-1){e.columns.splice(t,1),delete e.columnsByName[r.name];continue}r.isStatic=!1}}function pruneDenseTableColumns(e){let t=e.columns.length;for(;t--;){let n=e.columns[t];if(!n.isStatic&&n.type.code===r.dataTypes.custom&&n.type.info===`empty`){e.columns.splice(t,1),delete e.columnsByName[n.name];continue}n.isStatic=!1}}function getTokenToReplicaMapper(e,t){if(/SimpleStrategy$/.test(e)){let e=parseInt(t.replication_factor,10);if(e>1)return getTokenToReplicaSimpleMapper(e)}return/NetworkTopologyStrategy$/.test(e)?getTokenToReplicaNetworkMapper(t):function(e,t,n){let r={};for(let e in n)n.hasOwnProperty(e)&&(r[e]=[n[e]]);return r}}function getTokenToReplicaSimpleMapper(e){return function(t,n,r){let i=n.length,a=Math.min(e,i),o={};for(let e=0;e<i;e++){let t=n[e],s=[r[t]];for(let t=1;t<i&&s.length<a;t++){let a=e+t;a>=i&&(a%=i);let o=r[n[a]];s.indexOf(o)===-1&&s.push(o)}o[t]=s}return o}}function getTokenToReplicaNetworkMapper(e){return function(t,r,i,a){let o={},s=r.length;for(let t=0;t<s;t++){let c=r[t],l=[],u={},d={},f=[];for(let o=0;o<s;o++){let c=t+o;c>=s&&(c%=s);let p=i[r[c]];if(l.indexOf(p)!==-1)continue;let m=p.datacenter,h=parseInt(e[m],10);if(!h)continue;h=Math.min(h,a[m].hostLength);let g=u[m]||0;if(g>=h)continue;let _=d[m];if(_||=d[m]=new n.HashSet,p.rack&&_.contains(p.rack)&&_.length<a[m].racks.length){f.length<h-g&&f.push(p);continue}if(u[p.datacenter]=++g,l.push(p),p.rack&&_.add(p.rack)&&_.length===a[m].racks.length&&(u[m]+=addSkippedHosts(h,g,l,f)),isDoneForToken(e,a,u))break}o[c]=l}return o}}function addSkippedHosts(e,t,n,r){let i;for(i=0;i<e-t&&i<r.length;i++)n.push(r[i]);return i}function isDoneForToken(e,t,n){let r=Object.keys(e);for(let i=0;i<r.length;i++){let a=r[i],o=t[a];if(!o)continue;let s=Math.min(parseInt(e[a],10),o.hostLength);if(s>0&&(!n[a]||n[a]<s))return!1}return!0}function getByVersion(e,t,n,r,i){let a=SchemaParserV1;return r&&r[0]===3?a=SchemaParserV2:r&&r[0]>=4&&(a=SchemaParserV3),!i||!(i instanceof a)?new a(e,t,n):i}var h={getByVersion,isDoneForToken};export{h as default};
@@ -0,0 +1 @@
1
+ import e from"./data-collection.js";import t from"util";function TableMetadata(t){e.call(this,t),this.replicateOnWrite=!0,this.memtableFlushPeriod=0,this.indexInterval=null,this.isCompact=!1,this.indexes=null,this.cdc=null,this.virtual=!1}t.inherits(TableMetadata,e);export{TableMetadata as default};
@@ -0,0 +1 @@
1
+ import e from"./errors.js";import t from"./utils.js";import{ExecuteRequest as n,QueryRequest as r}from"./requests.js";import i from"util";const a={init:0,completed:1,timedOut:2,cancelled:3};var OperationState=class{constructor(e,t,n){this.request=e,this._rowCallback=t,this._callback=n,this._deadline=0,this._state=a.init,this._rowIndex=0,this.streamId=-1}cancel(){this._state===a.init&&(this._state=a.cancelled,this._callback=t.noop,this._deadline=0)}canBeWritten(){return this._state===a.init}isByRow(){return this._rowCallback&&(this.request instanceof n||this.request instanceof r)}setRequestTimeout(e,t,n,r,i){if(this._state!==a.init)return;let o=e.getReadTimeout()===void 0?t:e.getReadTimeout();o>0&&(this._deadline=Date.now()+o,this._timeoutMillis=o,this._onTimeoutCb=r,this._onResponseCb=i,this._address=n)}checkTimeout(t){if(this._state!==a.init||!this._deadline||this._deadline>t)return!1;this._onTimeoutCb();let n=i.format(`The host %s did not reply before timeout %d ms`,this._address,this._timeoutMillis);return this._markAsTimedOut(new e.OperationTimedOutError(n,this._address),this._onResponseCb),!0}setResultRow(t,n,r,i,a){if(this._markAsCompleted(),!this._rowCallback)return this.setResult(new e.DriverInternalError(`RowCallback not found for streaming frame handler`));this._rowCallback(this._rowIndex++,t,r),this._rowIndex===r&&this._swapCallbackAndInvoke(null,{rowLength:r,meta:n,flags:i},a.bodyLength)}_markAsTimedOut(e,t){this._state===a.init&&(this._state=a.timedOut,this._swapCallbackAndInvoke(e,null,null,t))}_markAsCompleted(){this._state===a.init&&(this._state=a.completed,this._deadline=0)}setResult(e,t,n){this._markAsCompleted(),this._swapCallbackAndInvoke(e,t,n)}_swapCallbackAndInvoke(e,n,r,i){let a=this._callback;this._callback=i||t.noop,a(e,n,r)}};export{OperationState as default};
@@ -0,0 +1 @@
1
+ import e from"../utils.js";import t from"util";import n from"dns";function AddressTranslator(){}AddressTranslator.prototype.translate=function(e,t,n){n(e+`:`+t)};function EC2MultiRegionTranslator(){}t.inherits(EC2MultiRegionTranslator,AddressTranslator),EC2MultiRegionTranslator.prototype.translate=function(t,r,i){let a=t,o=this,s;e.series([function(e){n.reverse(t,function(t,n){if(t)return e(t);if(!n)return e();s=n[0],e()})},function(e){if(!s)return e();n.lookup(s,function(t,n){if(t)return e(t);a=n,e()})}],function(e){e&&o.logError(t,e),i(a+`:`+r)})},EC2MultiRegionTranslator.prototype.logError=function(e,t){};var r={AddressTranslator,EC2MultiRegionTranslator};export{r as default};
@@ -1,7 +1,7 @@
1
1
  import { types } from "../types/index.js";
2
- import { Client, EmptyCallback, ExecutionOptions, Host, HostMap } from "../../index.js";
2
+ import { Client, EmptyCallback, ExecutionOptions, Host, HostMap } from "../index.js";
3
3
 
4
- //#region src/driver/lib/policies/index.d.ts
4
+ //#region src/driver/policies/index.d.ts
5
5
  declare namespace policies {
6
6
  function defaultAddressTranslator(): addressResolution.AddressTranslator;
7
7
  function defaultLoadBalancingPolicy(localDc?: string): loadBalancing.LoadBalancingPolicy;
@@ -0,0 +1 @@
1
+ import e from"./address-resolution.js";import t from"./load-balancing.js";import n from"./reconnection.js";import r from"./retry.js";import i from"./speculative-execution.js";import a from"./timestamp-generation.js";var o={addressResolution:e,loadBalancing:t,reconnection:n,retry:r,speculativeExecution:i,timestampGeneration:a,defaultAddressTranslator,defaultLoadBalancingPolicy,defaultRetryPolicy,defaultReconnectionPolicy,defaultSpeculativeExecutionPolicy,defaultTimestampGenerator};function defaultAddressTranslator(){return new e.AddressTranslator}function defaultLoadBalancingPolicy(e){return new t.DefaultLoadBalancingPolicy(e)}function defaultRetryPolicy(){return new r.RetryPolicy}function defaultReconnectionPolicy(){return new n.ExponentialReconnectionPolicy(1e3,600*1e3,!1)}function defaultSpeculativeExecutionPolicy(){return new i.NoSpeculativeExecutionPolicy}function defaultTimestampGenerator(){return new a.MonotonicTimestampGenerator}export{o as default};
@@ -0,0 +1 @@
1
+ import e from"../errors.js";import t from"../utils.js";import n from"../types/index.js";import r from"util";const i=Object.freeze({done:!0});function LoadBalancingPolicy(){}LoadBalancingPolicy.prototype.init=function(e,t,n){this.client=e,this.hosts=t,n()},LoadBalancingPolicy.prototype.getDistance=function(e){return n.distance.local},LoadBalancingPolicy.prototype.newQueryPlan=function(e,t,n){n(Error(`You must implement a query plan for the LoadBalancingPolicy class`))},LoadBalancingPolicy.prototype.getOptions=function(){return new Map};function RoundRobinPolicy(){this.index=0}r.inherits(RoundRobinPolicy,LoadBalancingPolicy),RoundRobinPolicy.prototype.newQueryPlan=function(e,n,r){if(!this.hosts)return r(Error(`Load balancing policy not initialized`));let a=this.hosts.values(),o=this,s=0,c=o.index%a.length;o.index+=1,o.index>=t.maxInt&&(o.index=0),r(null,{next:function(){return++s>a.length?i:{value:a[c++%a.length],done:!1}}})};function DCAwareRoundRobinPolicy(e){this.localDc=e,this.index=0,this.localHostsArray=null}r.inherits(DCAwareRoundRobinPolicy,LoadBalancingPolicy),DCAwareRoundRobinPolicy.prototype.init=function(e,t,n){this.client=e,this.hosts=t,t.on(`add`,this._cleanHostCache.bind(this)),t.on(`remove`,this._cleanHostCache.bind(this));try{setLocalDc(this,e,this.hosts)}catch(e){return n(e)}n()},DCAwareRoundRobinPolicy.prototype.getDistance=function(e){return e.datacenter===this.localDc?n.distance.local:n.distance.ignored},DCAwareRoundRobinPolicy.prototype._cleanHostCache=function(){this.localHostsArray=null},DCAwareRoundRobinPolicy.prototype._resolveLocalHosts=function(){let e=this.hosts.values();this.localHostsArray||(this.localHostsArray=[],e.forEach(function(e){e.datacenter&&e.datacenter===this.localDc&&this.localHostsArray.push(e)},this))},DCAwareRoundRobinPolicy.prototype.newQueryPlan=function(e,n,r){if(!this.hosts)return r(Error(`Load balancing policy not initialized`));this.index+=1,this.index>=t.maxInt&&(this.index=0),this._resolveLocalHosts();let a=this.localHostsArray,o=this.index,s=0;r(null,{next:function(){let e;return s++<a.length?(e=a[o++%a.length],{value:e,done:!1}):i}})},DCAwareRoundRobinPolicy.prototype.getOptions=function(){return new Map([[`localDataCenter`,this.localDc]])};function TokenAwarePolicy(e){if(!e)throw Error(`You must specify a child load balancing policy`);this.childPolicy=e}r.inherits(TokenAwarePolicy,LoadBalancingPolicy),TokenAwarePolicy.prototype.init=function(e,t,n){this.client=e,this.hosts=t,this.childPolicy.init(e,t,n)},TokenAwarePolicy.prototype.getDistance=function(e){return this.childPolicy.getDistance(e)},TokenAwarePolicy.prototype.newQueryPlan=function(e,t,n){let r;t&&(r=t.getRoutingKey(),t.getKeyspace()&&(e=t.getKeyspace()));let i;if(r&&(i=this.client.getReplicas(e,r)),!r||!i)return this.childPolicy.newQueryPlan(e,t,n);new TokenAwareIterator(e,t,i,this.childPolicy).iterate(n)};function TokenAwareIterator(e,t,r,i){this.keyspace=e,this.childPolicy=i,this.options=t,this.localReplicas=[],this.replicaIndex=0,this.replicaMap={},this.childIterator=null;for(let e=0;e<r.length;e++){let t=r[e];this.childPolicy.getDistance(t)===n.distance.local&&(this.replicaMap[t.address]=!0,this.localReplicas.push(t))}this.startIndex=Math.floor(Math.random()*this.localReplicas.length)}TokenAwareIterator.prototype.iterate=function(e){let t=this;this.childPolicy.newQueryPlan(this.keyspace,this.options,function(n,r){if(n)return e(n);t.childIterator=r,e(null,{next:function(){return t.computeNext()}})})},TokenAwareIterator.prototype.computeNext=function(){let e;if(this.replicaIndex<this.localReplicas.length)return e=this.localReplicas[(this.startIndex+ this.replicaIndex++)%this.localReplicas.length],{value:e,done:!1};let t;for(;(t=this.childIterator.next())&&!t.done;)if(!this.replicaMap[t.value.address])return t;return i},TokenAwarePolicy.prototype.getOptions=function(){let e=new Map([[`childPolicy`,this.childPolicy.constructor===void 0?null:this.childPolicy.constructor.name]]);return this.childPolicy instanceof DCAwareRoundRobinPolicy&&e.set(`localDataCenter`,this.childPolicy.localDc),e};function AllowListPolicy(e,t){if(!e)throw Error(`You must specify a child load balancing policy`);if(!Array.isArray(t))throw Error(`You must provide the list of allowed host addresses`);this.childPolicy=e,this.allowList=new Map(t.map(e=>[e,!0]))}r.inherits(AllowListPolicy,LoadBalancingPolicy),AllowListPolicy.prototype.init=function(e,t,n){this.childPolicy.init(e,t,n)},AllowListPolicy.prototype.getDistance=function(e){return this._contains(e)?this.childPolicy.getDistance(e):n.distance.ignored},AllowListPolicy.prototype._contains=function(e){return!!this.allowList.get(e.address)},AllowListPolicy.prototype.newQueryPlan=function(e,t,n){let r=this;this.childPolicy.newQueryPlan(e,t,function(e,t){if(e)return n(e);n(null,r._filter(t))})},AllowListPolicy.prototype._filter=function(e){let t=this;return{next:function(){let n=e.next();return!n.done&&!t._contains(n.value)?this.next():n}}},AllowListPolicy.prototype.getOptions=function(){return new Map([[`childPolicy`,this.childPolicy.constructor===void 0?null:this.childPolicy.constructor.name],[`allowList`,Array.from(this.allowList.keys())]])};function WhiteListPolicy(e,t){AllowListPolicy.call(this,e,t)}r.inherits(WhiteListPolicy,AllowListPolicy);var a=class DefaultLoadBalancingPolicy extends LoadBalancingPolicy{constructor(e){super(),typeof e==`string`?e={localDc:e}:e||=t.emptyObject,this._client=null,this._hosts=null,this._filteredHosts=null,this._preferredHost=null,this._index=0,this.localDc=e.localDc,this._filter=e.filter||this._defaultFilter,e.isHostNewlyUp&&(this._isHostNewlyUp=e.isHostNewlyUp),e.healthCheck&&(this._healthCheck=e.healthCheck),e.compare&&(this._compare=e.compare),e.getReplicas&&(this._getReplicas=e.getReplicas)}init(e,t,n){this._client=e,this._hosts=t,this._hosts.on(`add`,()=>this._filteredHosts=null),this._hosts.on(`remove`,()=>this._filteredHosts=null);try{setLocalDc(this,e,this._hosts)}catch(e){return n(e)}n()}getDistance(e){return this._preferredHost!==null&&e===this._preferredHost||this._filter(e)&&e.datacenter===this.localDc?n.distance.local:n.distance.ignored}newQueryPlan(e,t,n){let r,i;t&&(r=t.getRoutingKey(),t.getKeyspace()&&(e=t.getKeyspace()),i=t.getPreferredHost());let a;return a=!e||!r?this._getLocalHosts():this._getReplicasAndLocalHosts(e,r),i&&(this._preferredHost=i,a=DefaultLoadBalancingPolicy._getPreferredHostFirst(i,a)),n(null,a)}static*_getPreferredHostFirst(e,t){yield e;for(let n of t)n!==e&&(yield n)}*_getLocalHosts(e){let t=this._getFilteredLocalHosts(),n=this._getIndex(),r=e?t=>e.indexOf(t)===-1:e=>!0;for(let e=0;e<t.length;e++){let i=t[(e+n)%t.length];r(i)&&i.isUp()&&(yield i)}}_getReplicasAndLocalHosts(e,n){let r=this._getReplicas(e,n);if(r===null)return this._getLocalHosts();let i=[],a=null,o=-(2**53-1),s=0;for(let e=0;e<r.length;e++){let t=r[e];if(!this._filter(t)||t.datacenter!==this.localDc||!t.isUp())continue;let n=this._isHostNewlyUp(t);n!==null&&n>o&&(a=t,o=n),a===null&&!this._healthCheck(t)&&s++,i.push(t)}if(r=i,t.shuffleArray(r),r.length<3)return this.yieldReplicasFirst(r);let c;if(a===null)s>0&&s<Math.floor(r.length/2+1)&&this._sendUnhealthyToTheBack(r,s);else if((a===r[0]||a===r[1])&&Math.random()*4>=1){let e=a===r[0]?0:1;c=r[r.length-1],r[r.length-1]=r[e],r[e]=c}return this._compare(r[1],r[0])>0&&(c=r[0],r[0]=r[1],r[1]=c),this.yieldReplicasFirst(r)}*yieldReplicasFirst(e){for(let t=0;t<e.length;t++)yield e[t];yield*this._getLocalHosts(e)}_isHostNewlyUp(e){return e.isUpSince!==null&&Date.now()-e.isUpSince<6e4?e.isUpSince:null}_healthCheck(e){return!(e.getInFlight()>=10&&e.getResponseCount()<=1)}_compare(e,t){return e.getInFlight()<t.getInFlight()?1:-1}_getReplicas(e,t){return this._client.getReplicas(e,t)}_getFilteredLocalHosts(){return this._filteredHosts===null&&(this._filteredHosts=this._hosts.values().filter(e=>this._filter(e)&&e.datacenter===this.localDc)),this._filteredHosts}_getIndex(){let e=this._index++;return this._index===2147483647&&(this._index=0),e}_sendUnhealthyToTheBack(e,t){let n=0;for(let r=e.length-1;r>=0&&n<t;r--){let t=e[r];if(this._healthCheck(t))continue;let i=e.length-1-n;if(i!==r){let n=e[i];e[i]=t,e[r]=n}n++}}_defaultFilter(){return!0}getOptions(){return new Map([[`localDataCenter`,this.localDc],[`filterFunction`,this._filter!==this._defaultFilter]])}};function setLocalDc(t,n,r){if(!(t instanceof LoadBalancingPolicy))throw new e.DriverInternalError(`LoadBalancingPolicy instance was not provided`);n&&n.options&&(t.localDc&&!n.options.localDataCenter&&n.log(`info`,`Local data center '${t.localDc}' was provided as an argument to the load-balancing policy. It is preferable to specify the local data center using 'localDataCenter' in Client options instead when your application is targeting a single data center.`),t.localDc=t.localDc||n.options.localDataCenter);let i=getDataCenters(r);if(!t.localDc)throw new e.ArgumentError(`'localDataCenter' is not defined in Client options and also was not specified in constructor. At least one is required. Available DCs are: [${Array.from(i)}]`);if(!i.has(t.localDc))throw new e.ArgumentError(`Datacenter ${t.localDc} was not found. Available DCs are: [${Array.from(i)}]`)}function getDataCenters(e){return new Set(e.values().map(e=>e.datacenter))}var o={AllowListPolicy,DCAwareRoundRobinPolicy,DefaultLoadBalancingPolicy:a,LoadBalancingPolicy,RoundRobinPolicy,TokenAwarePolicy,WhiteListPolicy};export{o as default};
@@ -0,0 +1 @@
1
+ import e from"util";function ReconnectionPolicy(){}ReconnectionPolicy.prototype.newSchedule=function(){throw Error(`You must implement a new schedule for the Reconnection class`)},ReconnectionPolicy.prototype.getOptions=function(){return new Map};function ConstantReconnectionPolicy(e){this.delay=e}e.inherits(ConstantReconnectionPolicy,ReconnectionPolicy),ConstantReconnectionPolicy.prototype.newSchedule=function(){let e=this;return{next:function(){return{value:e.delay,done:!1}}}},ConstantReconnectionPolicy.prototype.getOptions=function(){return new Map([[`delay`,this.delay]])};function ExponentialReconnectionPolicy(e,t,n){this.baseDelay=e,this.maxDelay=t,this.startWithNoDelay=n}e.inherits(ExponentialReconnectionPolicy,ReconnectionPolicy),ExponentialReconnectionPolicy.prototype.newSchedule=function*(){let e=this.startWithNoDelay?-1:0;for(;;){let t=0;e>=64?t=this.maxDelay:e!==-1&&(t=Math.min(2**e*this.baseDelay,this.maxDelay)),e++,yield this._addJitter(t)}},ExponentialReconnectionPolicy.prototype._addJitter=function(e){if(e===0)return e;let t=.85,n=.3;return!this.startWithNoDelay&&e===this.baseDelay?(t=1,n=.15):e===this.maxDelay&&(n=.15),Math.floor(e*(Math.random()*n+t))},ExponentialReconnectionPolicy.prototype.getOptions=function(){return new Map([[`baseDelay`,this.baseDelay],[`maxDelay`,this.maxDelay],[`startWithNoDelay`,this.startWithNoDelay]])};var t={ReconnectionPolicy,ConstantReconnectionPolicy,ExponentialReconnectionPolicy};export{t as default};
@@ -0,0 +1 @@
1
+ import e from"util";function RetryPolicy(){}RetryPolicy.prototype.onUnavailable=function(e,t,n,r){return e.nbRetry>0?this.rethrowResult():this.retryResult(void 0,!1)},RetryPolicy.prototype.onReadTimeout=function(e,t,n,r,i){return e.nbRetry>0?this.rethrowResult():n>=r&&!i?this.retryResult():this.rethrowResult()},RetryPolicy.prototype.onWriteTimeout=function(e,t,n,r,i){return e.nbRetry>0?this.rethrowResult():i===`BATCH_LOG`?this.retryResult():this.rethrowResult()},RetryPolicy.prototype.onRequestError=function(e,t,n){return this.retryResult(void 0,!1)},RetryPolicy.prototype.retryResult=function(e,t){return{decision:RetryPolicy.retryDecision.retry,consistency:e,useCurrentHost:t!==!1}},RetryPolicy.prototype.rethrowResult=function(){return{decision:RetryPolicy.retryDecision.rethrow}},RetryPolicy.retryDecision={rethrow:0,retry:1,ignore:2};function IdempotenceAwareRetryPolicy(e){this._childPolicy=e||new RetryPolicy}e.inherits(IdempotenceAwareRetryPolicy,RetryPolicy),IdempotenceAwareRetryPolicy.prototype.onReadTimeout=function(e,t,n,r,i){return this._childPolicy.onReadTimeout(e,t,n,r,i)},IdempotenceAwareRetryPolicy.prototype.onRequestError=function(e,t,n){return e.executionOptions.isIdempotent()?this._childPolicy.onRequestError(e,t,n):this.rethrowResult()},IdempotenceAwareRetryPolicy.prototype.onUnavailable=function(e,t,n,r){return this._childPolicy.onUnavailable(e,t,n,r)},IdempotenceAwareRetryPolicy.prototype.onWriteTimeout=function(e,t,n,r,i){return e.executionOptions.isIdempotent()?this._childPolicy.onWriteTimeout(e,t,n,r,i):this.rethrowResult()};function FallthroughRetryPolicy(){}e.inherits(FallthroughRetryPolicy,RetryPolicy),FallthroughRetryPolicy.prototype.onReadTimeout=function(){return this.rethrowResult()},FallthroughRetryPolicy.prototype.onRequestError=function(){return this.rethrowResult()},FallthroughRetryPolicy.prototype.onUnavailable=function(){return this.rethrowResult()},FallthroughRetryPolicy.prototype.onWriteTimeout=function(){return this.rethrowResult()};var t={IdempotenceAwareRetryPolicy,FallthroughRetryPolicy,RetryPolicy};export{t as default};
@@ -0,0 +1 @@
1
+ import e from"../errors.js";import t from"util";function SpeculativeExecutionPolicy(){}SpeculativeExecutionPolicy.prototype.init=function(e){},SpeculativeExecutionPolicy.prototype.shutdown=function(){},SpeculativeExecutionPolicy.prototype.newPlan=function(e,t){throw Error(`You must implement newPlan() method in the SpeculativeExecutionPolicy`)},SpeculativeExecutionPolicy.prototype.getOptions=function(){return new Map};function NoSpeculativeExecutionPolicy(){this._plan={nextExecution:function(){return-1}}}t.inherits(NoSpeculativeExecutionPolicy,SpeculativeExecutionPolicy),NoSpeculativeExecutionPolicy.prototype.newPlan=function(){return this._plan};function ConstantSpeculativeExecutionPolicy(t,n){if(!(t>=0))throw new e.ArgumentError(`delay must be a positive number or zero`);if(!(n>0))throw new e.ArgumentError(`maxSpeculativeExecutions must be a positive number`);this._delay=t,this._maxSpeculativeExecutions=n}t.inherits(ConstantSpeculativeExecutionPolicy,SpeculativeExecutionPolicy),ConstantSpeculativeExecutionPolicy.prototype.newPlan=function(){let e=0,t=this;return{nextExecution:function(){return e++<t._maxSpeculativeExecutions?t._delay:-1}}},ConstantSpeculativeExecutionPolicy.prototype.getOptions=function(){return new Map([[`delay`,this._delay],[`maxSpeculativeExecutions`,this._maxSpeculativeExecutions]])};var n={NoSpeculativeExecutionPolicy,SpeculativeExecutionPolicy,ConstantSpeculativeExecutionPolicy};export{n as default};
@@ -0,0 +1 @@
1
+ import e from"../errors.js";import{Long as t}from"../types/index.js";import n from"util";const r=t.fromInt(1e3);function TimestampGenerator(){}TimestampGenerator.prototype.next=function(e){throw Error(`next() must be implemented`)};function MonotonicTimestampGenerator(t,n){if(t<0)throw new e.ArgumentError(`warningThreshold can not be lower than 0`);this._warningThreshold=t||1e3,this._minLogInterval=1e3,typeof n==`number`&&(this._minLogInterval=n),this._micros=-1,this._lastDate=0,this._lastLogDate=0}n.inherits(MonotonicTimestampGenerator,TimestampGenerator),MonotonicTimestampGenerator.prototype.getDate=function(){return Date.now()},MonotonicTimestampGenerator.prototype.next=function(e){let t=this.getDate(),r=0;if(t>this._lastDate)return this._micros=0,this._lastDate=t,this._generateMicroseconds();t<this._lastDate&&(r=this._lastDate-t,t=this._lastDate),++this._micros===1e3&&(this._micros=0,t===this._lastDate&&(t++,r++));let i=this._lastDate;this._lastDate=t;let a=this._generateMicroseconds();if(r>=this._warningThreshold){let t=Date.now();if(this._minLogInterval>0&&this._lastLogDate+this._minLogInterval<=t){let o=n.format(`Timestamp generated using current date was %d milliseconds behind the last generated timestamp (which millisecond portion was %d), the returned value (%s) is being artificially incremented to guarantee monotonicity.`,r,i,a);this._lastLogDate=t,e.log(`warning`,o)}}return a},MonotonicTimestampGenerator.prototype._generateMicroseconds=function(){return this._lastDate<9007199254740?this._lastDate*1e3+this._micros:t.fromNumber(this._lastDate).multiply(r).add(t.fromInt(this._micros))};var i={TimestampGenerator,MonotonicTimestampGenerator};export{i as default};
@@ -0,0 +1 @@
1
+ import e from"./errors.js";import t from"./promise-utils.js";import n from"./utils.js";import r from"./types/index.js";var i=class PrepareHandler{constructor(e,t){this._client=e,this._loadBalancing=t,this.logEmitter=e.options.logEmitter,this.log=n.log}static async getPrepared(e,n,r,i){let a=e.metadata.getPreparedInfo(i,r);return a.queryId?a:a.preparing?await t.fromEvent(a,`prepared`):await new PrepareHandler(e,n)._prepare(a,r,i)}static async getPreparedMultiple(t,r,i,a){let o=[];for(let s of i){let i;if(s&&(i=typeof s==`string`?s:s.query),typeof i!=`string`)throw new e.ArgumentError(`Query item should be a string`);let{queryId:c,meta:l}=await PrepareHandler.getPrepared(t,r,i,a);o.push({query:i,params:n.adaptNamedParamsPrepared(s.params,l.columns),queryId:c,meta:l})}return o}async _prepare(e,n,r){e.preparing=!0;let i;try{return i=await t.newQueryPlan(this._loadBalancing,r,null),await this._prepareWithQueryPlan(e,i,n,r)}catch(t){throw e.preparing=!1,t.query=n,e.emit(`prepared`,t),t}}async _prepareWithQueryPlan(t,n,r,i){let a={};for(;;){let o=PrepareHandler.getNextHost(n,this._client.profileManager,a);if(o===null)throw new e.NoHostAvailableError(a);try{let e=await(await PrepareHandler._borrowWithKeyspace(o,i)).prepareOnceAsync(r,i);return this._client.options.prepareOnAllHosts&&await this._prepareOnAllHosts(n,r,i),t.preparing=!1,t.queryId=e.id,t.meta=e.meta,this._client.metadata.setPreparedById(t),t.emit(`prepared`,null,t),t}catch(t){if(a[o.address]=t,!t.isSocketError&&!(t instanceof e.OperationTimedOutError))throw t}}}static getNextHost(e,t,n){let i;for(;;){let a=e.next();if(a.done)return null;if(i=a.value,t.getDistance(i)!==r.distance.ignored){if(i.isUp())break;n&&(n[i.address]=`Host considered as DOWN`)}}return i}static async prepareAllQueries(e,t){let n=[],r=new Map;t.forEach(e=>{let t;e.keyspace?(t=r.get(e.keyspace),t||(t=[],r.set(e.keyspace,t))):t=n,t.push(e.query)});for(let[t,n]of r)await PrepareHandler._borrowAndPrepare(e,t,n);await PrepareHandler._borrowAndPrepare(e,null,n)}static async _borrowAndPrepare(e,t,n){if(n.length===0)return;let r=await PrepareHandler._borrowWithKeyspace(e,t);for(let e of n)await r.prepareOnceAsync(e,t)}static async _borrowWithKeyspace(e,t){let n=e.borrowConnection();return t&&n.keyspace!==t&&await n.changeKeyspace(t),n}_prepareOnAllHosts(e,t,n){let r=[t],i,a=[];for(;(i=PrepareHandler.getNextHost(e,this._client.profileManager))!==null;)a.push(i);return Promise.all(a.map(e=>PrepareHandler._borrowAndPrepare(e,n,r).catch(n=>this.log(`verbose`,`Unexpected error while preparing query (${t}) on ${e.address}`,n))))}};export{i as default};
@@ -0,0 +1 @@
1
+ function delay(e){return new Promise(t=>setTimeout(t,e||0))}function fromEvent(e,t){return new Promise((n,r)=>e.once(t,(e,t)=>{e?r(e):n(t)}))}function fromCallback(e){return new Promise((t,n)=>e((e,r)=>{e?n(e):t(r)}))}function getCallback(e,t){return function(n,r){n?t(n):e(r)}}async function invokeSequentially(e,t,n){let r;for(;(r=e.counter++)<t;)await n(r)}function newQueryPlan(e,t,n){return new Promise((r,i)=>{e.newQueryPlan(t,n,(e,t)=>{e?i(e):r(t)})})}function optionalCallback(e,t){if(!t)return e;toCallback(e,t)}function times(e,t,n){t>e&&(t=e);let r=Array(t),i={counter:0};for(let a=0;a<t;a++)r[a]=invokeSequentially(i,e,n);return Promise.all(r)}function toBackground(e){e.catch(()=>{})}function toCallback(e,t){e.then(e=>process.nextTick(()=>t(null,e)),e=>process.nextTick(()=>t(e)))}var e={delay,fromCallback,fromEvent,getCallback,newQueryPlan,optionalCallback,times,toBackground,toCallback};export{e as default};
@@ -0,0 +1 @@
1
+ import e from"./errors.js";import t from"./utils.js";import n from"./types/index.js";import r from"util";const i={globalTablesSpec:1,hasMorePages:2,noMetadata:4,metadataChanged:8,continuousPaging:1073741824,lastContinuousPage:2147483648};var FrameReader=class{constructor(e,t,n){this.header=e,this.opcode=e.opcode,this.offset=n||0,this.buf=t}remainingLength(){return this.buf.length-this.offset}getBuffer(){return this.buf}slice(e,t){return t===void 0&&(t=this.buf.length),this.buf.slice(e,t)}unshift(e){if(this.offset>0)throw Error(`Can not modify the underlying buffer if already read`);this.buf=Buffer.concat([e,this.buf],e.length+this.buf.length)}read(e){let t=this.buf.length;e!==void 0&&this.offset+e<this.buf.length&&(t=this.offset+e);let n=this.slice(this.offset,t);return this.offset=t,n}toEnd(){this.offset=this.buf.length}readInt(){let e=this.buf.readInt32BE(this.offset);return this.offset+=4,e}readShort(){let e=this.buf.readUInt16BE(this.offset);return this.offset+=2,e}readByte(){let e=this.buf.readUInt8(this.offset);return this.offset+=1,e}readString(){let e=this.readShort();this.checkOffset(e);let t=this.buf.toString(`utf8`,this.offset,this.offset+e);return this.offset+=e,t}checkOffset(e){if(this.offset+e>this.buf.length){let t=RangeError(`Trying to access beyond buffer length`);throw t.expectedLength=e,t}}readStringList(){let e=this.readShort(),t=Array(e);for(let n=0;n<e;n++)t[n]=this.readString();return t}readBytes(){let e=this.readInt();return e<0?null:(this.checkOffset(e),this.read(e))}readShortBytes(){let e=this.readShort();return e<0?null:(this.checkOffset(e),this.read(e))}readMap(e,t,n){if(e<0)return null;let r={};for(let i=0;i<e;i++)r[t.call(this)]=n.call(this);return r}readStringMultiMap(){let e=this.readShort();if(e<0)return null;let t={};for(let n=0;n<e;n++)t[this.readString()]=this.readStringList();return t}readType(){let e,t={code:this.readShort(),type:null};switch(t.code){case n.dataTypes.custom:t.info=this.readString();break;case n.dataTypes.list:case n.dataTypes.set:t.info=this.readType();break;case n.dataTypes.map:t.info=[this.readType(),this.readType()];break;case n.dataTypes.udt:for(t.info={keyspace:this.readString(),name:this.readString(),fields:Array(this.readShort())},e=0;e<t.info.fields.length;e++)t.info.fields[e]={name:this.readString(),type:this.readType()};break;case n.dataTypes.tuple:for(t.info=Array(this.readShort()),e=0;e<t.info.length;e++)t.info[e]=this.readType();break}return t}readInet(){let e=this.readByte(),t=this.read(e);return{address:new n.InetAddress(t),port:this.readInt()}}readInetAddress(){let e=this.readByte();return new n.InetAddress(this.read(e))}readFlagsInfo(){if(this.header.flags===0)return t.emptyObject;let e={};return this.header.flags&n.frameFlags.tracing&&(this.checkOffset(16),e.traceId=new n.Uuid(t.copyBuffer(this.read(16)))),this.header.flags&n.frameFlags.warning&&(e.warnings=this.readStringList()),this.header.flags&n.frameFlags.customPayload&&(e.customPayload=this.readMap(this.readShort(),this.readString,this.readBytes)),e}readMetadata(e){let r,a=e===n.resultKind.prepared,o={};n.protocolVersion.supportsResultMetadataId(this.header.version)&&a&&(o.resultId=t.copyBuffer(this.readShortBytes()));let s=this.readInt(),c=this.readInt();if(n.protocolVersion.supportsPreparedPartitionKey(this.header.version)&&a)for(o.partitionKeys=Array(this.readInt()),r=0;r<o.partitionKeys.length;r++)o.partitionKeys[r]=this.readShort();for(s&i.hasMorePages&&(o.pageState=t.copyBuffer(this.readBytes())),s&i.metadataChanged&&(o.newResultId=t.copyBuffer(this.readShortBytes())),s&i.continuousPaging&&(o.continuousPageIndex=this.readInt(),o.lastContinuousPage=!!(s&i.lastContinuousPage)),s&i.globalTablesSpec&&(o.global_tables_spec=!0,o.keyspace=this.readString(),o.table=this.readString()),o.columns=Array(c),o.columnsByName=t.emptyObject,a&&(o.columnsByName={}),r=0;r<c;r++){let e={};o.global_tables_spec||(e.ksname=this.readString(),e.tablename=this.readString()),e.name=this.readString(),e.type=this.readType(),o.columns[r]=e,a&&(o.columnsByName[e.name]=r)}return o}readError(){let i=this.readInt(),a=this.readString(),o=new e.ResponseError(i,a);switch(i){case n.responseErrorCodes.unavailableException:o.consistencies=this.readShort(),o.required=this.readInt(),o.alive=this.readInt(),o.message=r.format(`Not enough replicas available for query at consistency %s (%d required but only %d alive)`,n.consistencyToString[o.consistencies],o.required,o.alive);break;case n.responseErrorCodes.readTimeout:case n.responseErrorCodes.readFailure:if(o.consistencies=this.readShort(),o.received=this.readInt(),o.blockFor=this.readInt(),i===n.responseErrorCodes.readFailure&&(n.protocolVersion.supportsFailureReasonMap(this.header.version)?(o.failures=this.readInt(),o.reasons=this.readMap(o.failures,this.readInetAddress,this.readShort)):o.failures=this.readInt()),o.isDataPresent=this.readByte(),i===n.responseErrorCodes.readTimeout){let e;e=o.received<o.blockFor?r.format(`%d replica(s) responded over %d required`,o.received,o.blockFor):o.isDataPresent?`timeout while waiting for repair of inconsistent replica`:`the replica queried for the data didn't respond`,o.message=r.format(`Server timeout during read query at consistency %s (%s)`,n.consistencyToString[o.consistencies],e)}else o.message=r.format(`Server failure during read query at consistency %s (%d responses were required but only %d replicas responded, %d failed)`,n.consistencyToString[o.consistencies],o.blockFor,o.received,o.failures);break;case n.responseErrorCodes.writeTimeout:case n.responseErrorCodes.writeFailure:if(o.consistencies=this.readShort(),o.received=this.readInt(),o.blockFor=this.readInt(),i===n.responseErrorCodes.writeFailure&&(n.protocolVersion.supportsFailureReasonMap(this.header.version)?(o.failures=this.readInt(),o.reasons=this.readMap(o.failures,this.readInetAddress,this.readShort)):o.failures=this.readInt()),o.writeType=this.readString(),i===n.responseErrorCodes.writeTimeout){let e=o.writeType===`BATCH_LOG`?`Server timeout during batchlog write at consistency %s (%d peer(s) acknowledged the write over %d required)`:`Server timeout during write query at consistency %s (%d peer(s) acknowledged the write over %d required)`;o.message=r.format(e,n.consistencyToString[o.consistencies],o.received,o.blockFor)}else o.message=r.format(`Server failure during write query at consistency %s (%d responses were required but only %d replicas responded, %d failed)`,n.consistencyToString[o.consistencies],o.blockFor,o.received,o.failures);break;case n.responseErrorCodes.unprepared:o.queryId=t.copyBuffer(this.readShortBytes());break;case n.responseErrorCodes.functionFailure:o.keyspace=this.readString(),o.functionName=this.readString(),o.argTypes=this.readStringList();break;case n.responseErrorCodes.alreadyExists:{o.keyspace=this.readString();let e=this.readString();e.length>0&&(o.table=e);break}}return o}readEvent(){let e=this.readString();switch(e){case n.protocolEvents.topologyChange:return{added:this.readString()===`NEW_NODE`,inet:this.readInet(),eventType:e};case n.protocolEvents.statusChange:return{up:this.readString()===`UP`,inet:this.readInet(),eventType:e};case n.protocolEvents.schemaChange:return this.parseSchemaChange()}return{eventType:e}}parseSchemaChange(){let e;if(!n.protocolVersion.supportsSchemaChangeFullMetadata(this.header.version))return e={eventType:n.protocolEvents.schemaChange,schemaChangeType:this.readString(),keyspace:this.readString(),table:this.readString()},e.isKeyspace=!e.table,e;switch(e={eventType:n.protocolEvents.schemaChange,schemaChangeType:this.readString(),target:this.readString(),keyspace:this.readString(),table:null,udt:null,signature:null},e.isKeyspace=e.target===`KEYSPACE`,e.target){case`TABLE`:e.table=this.readString();break;case`TYPE`:e.udt=this.readString();break;case`FUNCTION`:e.functionName=this.readString(),e.signature=this.readStringList();break;case`AGGREGATE`:e.aggregate=this.readString(),e.signature=this.readStringList()}return e}};export{FrameReader};
@@ -0,0 +1 @@
1
+ import e from"./errors.js";import t from"./promise-utils.js";import n from"./utils.js";import r from"./types/index.js";import i from"./policies/retry.js";import a from"./requests.js";const o=Object.freeze({decision:i.RetryPolicy.retryDecision.retry,useCurrentHost:!0,consistency:void 0}),s=Object.freeze({decision:i.RetryPolicy.retryDecision.rethrow}),c={none:0,socketError:1,socketErrorBeforeRequestWritten:2,clientTimeout:3,serverErrorUnprepared:4,serverErrorOverloaded:5,serverErrorReadTimeout:6,serverErrorUnavailable:7,serverErrorWriteTimeout:8,serverErrorOther:9},l=new Map([[c.none,(e,t,n)=>e.onSuccessfulResponse(n)],[c.socketError,(e,t)=>e.onConnectionError(t)],[c.clientTimeout,(e,t)=>e.onClientTimeoutError(t)],[c.serverErrorOverloaded,(e,t)=>e.onOtherError(t)],[c.serverErrorReadTimeout,(e,t)=>e.onReadTimeoutError(t)],[c.serverErrorUnavailable,(e,t)=>e.onUnavailableError(t)],[c.serverErrorWriteTimeout,(e,t)=>e.onWriteTimeoutError(t)],[c.serverErrorOther,(e,t)=>e.onOtherError(t)]]),u=new Map([[c.socketError,(e,t)=>e.onOtherErrorRetry(t)],[c.clientTimeout,(e,t)=>e.onClientTimeoutRetry(t)],[c.serverErrorOverloaded,(e,t)=>e.onOtherErrorRetry(t)],[c.serverErrorReadTimeout,(e,t)=>e.onReadTimeoutRetry(t)],[c.serverErrorUnavailable,(e,t)=>e.onUnavailableRetry(t)],[c.serverErrorWriteTimeout,(e,t)=>e.onWriteTimeoutRetry(t)],[c.serverErrorOther,(e,t)=>e.onOtherErrorRetry(t)]]);var d=class RequestExecution{constructor(e,t,n){this._parent=e,this._operation=null,this._host=t,this._connection=n,this._cancelled=!1,this._startTime=null,this._retryCount=0,this._request=this._parent.request,e.speculativeExecutions++}start(){this._sendOnConnection()}async restart(){try{let{host:e,connection:t}=this._parent.getNextConnection();this._connection=t,this._host=e}catch(e){return this._parent.handleNoHostAvailable(e,this)}let e=this._parent.client.keyspace;if(e&&e!==this._connection.keyspace)try{await this._connection.changeKeyspace(e)}catch(e){return this._handleError(RequestExecution._getErrorCode(e),e)}this._cancelled||this._sendOnConnection()}_sendOnConnection(){this._startTime=process.hrtime(),this._operation=this._connection.sendStream(this._request,this._parent.executionOptions,(e,n,r)=>{let i=RequestExecution._getErrorCode(e);if(this._trackResponse(process.hrtime(this._startTime),i,e,r),!this._cancelled){if(i!==c.none)return this._handleError(i,e);if(n.schemaChange)return t.toBackground(this._parent.client.handleSchemaAgreementAndRefresh(this._connection,n.schemaChange).then(e=>{this._cancelled||this._parent.setCompleted(null,this._getResultSet(n,e))}));if(n.keyspaceSet&&(this._parent.client.keyspace=n.keyspaceSet),n.meta&&n.meta.newResultId&&this._request.queryId){let e=this._parent.client.metadata.getPreparedById(this._request.queryId);e.meta.resultId=n.meta.newResultId}this._parent.setCompleted(null,this._getResultSet(n))}})}_trackResponse(e,t,n,r){RequestExecution._invokeMetricsHandler(t,this._parent.client.metrics,n,e);let i=this._parent.client.options.requestTracker;if(i===null)return;let a=this._request.query||this._request.queries,o=this._request.params,s=this._request.length;n?i.onError(this._host,a,o,this._parent.executionOptions,s,n,e):i.onSuccess(this._host,a,o,this._parent.executionOptions,s,r,e)}_getResultSet(e,t){let n=new r.ResultSet(e,this._host.address,this._parent.triedHosts,this._parent.speculativeExecutions,this._request.consistency,t===void 0||t);return n.rawPageState&&(n.nextPageAsync=this._parent.getNextPageHandler()),n}static _invokeMetricsHandler(t,n,r,i){let a=l.get(t);a!==void 0&&a(n,r,i),(!r||r instanceof e.ResponseError)&&n.onResponse(i)}static _invokeMetricsHandlerForRetry(e,t,n){let r=u.get(e);r!==void 0&&r(t,n)}cancel(){this._cancelled=!0,this._operation!==null&&this._operation.cancel()}wasCancelled(){return this._cancelled}_handleError(e,t){if(this._parent.triedHosts[this._host.address]=t,t.coordinator=this._host.address,e===c.serverErrorUnprepared)return this._prepareAndRetry(t.queryId);e===c.socketError||e===c.socketErrorBeforeRequestWritten?this._host.removeFromPool(this._connection):e===c.clientTimeout&&(this._parent.log(`warning`,t.message),this._host.checkHealth(this._connection));let r=this._getDecision(e,t);if(!r||r.decision===i.RetryPolicy.retryDecision.rethrow)return(this._request instanceof a.QueryRequest||this._request instanceof a.ExecuteRequest)&&(t.query=this._request.query),this._parent.setCompleted(t);let o=this._parent.client.metrics;return r.decision===i.RetryPolicy.retryDecision.ignore?(o.onIgnoreError(t),this._parent.setCompleted(null,this._getResultSet(n.emptyObject))):(RequestExecution._invokeMetricsHandlerForRetry(e,o,t),this._retry(r.consistency,r.useCurrentHost))}_getDecision(e,t){let n={query:this._request&&this._request.query,executionOptions:this._parent.executionOptions,nbRetry:this._retryCount},r=n.executionOptions.getRetryPolicy();switch(e){case c.socketErrorBeforeRequestWritten:return o;case c.socketError:case c.clientTimeout:case c.serverErrorOverloaded:return n.executionOptions.isIdempotent()?r.onRequestError(n,this._request.consistency,t):s;case c.serverErrorUnavailable:return r.onUnavailable(n,t.consistencies,t.required,t.alive);case c.serverErrorReadTimeout:return r.onReadTimeout(n,t.consistencies,t.received,t.blockFor,t.isDataPresent);case c.serverErrorWriteTimeout:return n.executionOptions.isIdempotent()?r.onWriteTimeout(n,t.consistencies,t.received,t.blockFor,t.writeType):s;default:return s}}static _getErrorCode(t){if(!t)return c.none;if(t.isSocketError)return t.requestNotWritten?c.socketErrorBeforeRequestWritten:c.socketError;if(t instanceof e.OperationTimedOutError)return c.clientTimeout;if(t instanceof e.ResponseError)switch(t.code){case r.responseErrorCodes.overloaded:case r.responseErrorCodes.isBootstrapping:case r.responseErrorCodes.truncateError:return c.serverErrorOverloaded;case r.responseErrorCodes.unavailableException:return c.serverErrorUnavailable;case r.responseErrorCodes.readTimeout:return c.serverErrorReadTimeout;case r.responseErrorCodes.writeTimeout:return c.serverErrorWriteTimeout;case r.responseErrorCodes.unprepared:return c.serverErrorUnprepared}return c.serverErrorOther}_retry(e,n,r){if(!this._cancelled){if(this._parent.log(`info`,`Retrying request`),this._retryCount++,(r||typeof e==`number`&&this._request.consistency!==e)&&(this._request=this._request.clone(),typeof e==`number`&&(this._request.consistency=e),r&&(this._request.meta=r)),n!==!1){try{this._connection=this._host.borrowConnection(this._connection)}catch{return t.toBackground(this.restart())}return this._sendOnConnection()}t.toBackground(this.restart())}}_prepareAndRetry(t){let n=this._connection;this._parent.log(`info`,`Query 0x${t.toString(`hex`)} not prepared on host ${n.endpointFriendlyName}, preparing and retrying`);let i=this._parent.client.metadata.getPreparedById(t);if(!i)return this._parent.setCompleted(new e.DriverInternalError(`Unprepared response invalid, id: 0x${t.toString(`hex`)}`));let a=this._connection.protocolVersion;if(!r.protocolVersion.supportsKeyspaceInRequest(a)&&i.keyspace&&i.keyspace!==n.keyspace)return this._parent.setCompleted(Error(`Query was prepared on keyspace ${i.keyspace}, can't execute it on ${n.keyspace} (${i.query})`));let o=this;this._connection.prepareOnce(i.query,i.keyspace,function(t,r){if(t)return!t.isSocketError&&t instanceof e.OperationTimedOutError&&o._parent.log(`warning`,`Unexpected timeout error when re-preparing query on host ${n.endpointFriendlyName}`),o._retry(void 0,!1);i.meta=r.meta,o._retry(void 0,!0,r.meta)})}};export{d as default};
@@ -0,0 +1 @@
1
+ import e from"./errors.js";import t from"./promise-utils.js";import n from"./utils.js";import r from"./types/index.js";import i from"./request-execution.js";import a from"util";var o=class RequestHandler{constructor(e,t,r){this.client=r,this._speculativeExecutionPlan=r.options.policies.speculativeExecution.newPlan(r.keyspace,e.query||e.queries),this.logEmitter=r.options.logEmitter,this.log=n.log,this.request=e,this.executionOptions=t,this.stackContainer=null,this.triedHosts={},this.speculativeExecutions=-1,this._hostIterator=null,this._resolveCallback=null,this._rejectCallback=null,this._newExecutionTimeout=null,this._executions=[]}static send(e,t,n){return new RequestHandler(e,t,n).send()}getNextConnection(){let t,n,i=this._hostIterator;for(;;){let a=i.next();if(a.done)throw new e.NoHostAvailableError(this.triedHosts);if(t=a.value,this.client.profileManager.getDistance(t)!==r.distance.ignored){if(!t.isUp()){this.triedHosts[t.address]=`Host considered as DOWN`;continue}try{n=t.borrowConnection(),this.triedHosts[t.address]=null;break}catch(e){this.triedHosts[t.address]=e}}}return{connection:n,host:t}}send(){return this.executionOptions.getCaptureStackTrace()&&Error.captureStackTrace(this.stackContainer={}),new Promise((e,r)=>{this._resolveCallback=e,this._rejectCallback=r;let i=this.executionOptions.getLoadBalancingPolicy(),a=this.executionOptions.getFixedHost();a?(this._hostIterator=n.arrayIterator([a]),t.toBackground(this._startNewExecution())):i.newQueryPlan(this.client.keyspace,this.executionOptions,(e,n)=>{if(e)return r(e);this._hostIterator=n,t.toBackground(this._startNewExecution())})})}async _startNewExecution(e){e&&this.client.metrics.onSpeculativeExecution();let t,n;try{({host:t,connection:n}=this.getNextConnection())}catch(e){return this.handleNoHostAvailable(e,null)}if(e&&this._executions.length>=0&&this._executions[0].wasCancelled())return;if(this.client.keyspace&&this.client.keyspace!==n.keyspace)try{await n.changeKeyspace(this.client.keyspace)}catch(n){return this.triedHosts[t.address]=n,this._startNewExecution(e)}let r=new i(this,t,n);this._executions.push(r),r.start(),this.executionOptions.isIdempotent()&&this._scheduleSpeculativeExecution(t)}_scheduleSpeculativeExecution(e){let n=this._speculativeExecutionPlan.nextExecution(e);if(!(typeof n!=`number`||n<0)){if(n===0)return process.nextTick(()=>{t.toBackground(this._startNewExecution(!0))});this._newExecutionTimeout=setTimeout(()=>t.toBackground(this._startNewExecution(!0)),n)}}static setKeyspace(t){let n;for(let e of t.hosts.values())if(n=e.getActiveConnection(),n)break;if(!n)throw new e.DriverInternalError(`No active connection found`);return n.changeKeyspace(t.keyspace)}setCompleted(e,t){this._newExecutionTimeout!==null&&clearTimeout(this._newExecutionTimeout);for(let e of this._executions)e.cancel();if(e)return this.executionOptions.getCaptureStackTrace()&&n.fixStack(this.stackContainer.stack,e),this._rejectCallback(e);t.info.warnings&&t.info.warnings.forEach(function(e,t,n){this.log(`warning`,a.format(`Received warning (%d of %d) "%s" for "%s"`,t+1,n.length,e,this.request.query||`batch`))},this),this._resolveCallback(t)}handleNoHostAvailable(e,t){if(t!==null){let e=this._executions.indexOf(t);this._executions.splice(e,1)}this._executions.length===0&&this.setCompleted(e)}getNextPageHandler(){let e=this.request,t=this.executionOptions,n=this.client;return function(r){return t.setPageState(r),new RequestHandler(e,t,n).send()}}};export{o as default};
@@ -0,0 +1 @@
1
+ import e from"./utils.js";import t from"./types/index.js";import{FrameWriter as n}from"./writers.js";import{ExecutionOptions as r}from"./execution-options.js";import{description as i,version as a}from"../package.js";import o from"util";const s={values:1,skipMetadata:2,pageSize:4,withPagingState:8,withSerialConsistency:16,withDefaultTimestamp:32,withNameForValues:64,withKeyspace:128,withPageSizeBytes:1073741824,withContinuousPaging:2147483648},c={withSerialConsistency:16,withDefaultTimestamp:32,withNameForValues:64,withKeyspace:128},l={withKeyspace:1},u={logged:0,unlogged:1,counter:2};var Request=class{constructor(){this.length=0}write(e,t){throw Error(`Method must be implemented`)}clone(){let e=new this.constructor,t=Object.keys(this);for(let n=0;n<t.length;n++){let r=t[n];e[r]=this[r]}return e}},ExecuteRequest=class extends Request{constructor(e,n,i,a,o){super(),this.query=e,this.queryId=n,this.params=i,this.meta=o,this.options=a||r.empty(),this.timestamp=this.options.getOrGenerateTimestamp(),this.consistency=this.options.getConsistency()||t.consistencies.one,this.namedParameters=!1}getParamType(e){let t=this.meta.columns[e];return t?t.type:null}write(e,r){let i=new n(t.opcodes.execute),a=this.options.isQueryTracing()?t.frameFlags.tracing:0;return this.options.getCustomPayload()&&(a|=t.frameFlags.customPayload,i.writeCustomPayload(this.options.getCustomPayload())),i.writeShortBytes(this.queryId),t.protocolVersion.supportsResultMetadataId(e.protocolVersion)&&i.writeShortBytes(this.meta.resultId),this.writeQueryParameters(i,e),this.length=i.bodyLength,i.write(e.protocolVersion,r,a)}writeQueryParameters(e,n,r){let i=0,a=this.timestamp;if(t.protocolVersion.supportsPaging(n.protocolVersion)){i|=this.params&&this.params.length?s.values:0,i|=this.options.getFetchSize()>0?s.pageSize:0,i|=this.options.getPageState()?s.withPagingState:0,i|=this.options.getSerialConsistency()?s.withSerialConsistency:0,i|=a==null?0:s.withDefaultTimestamp,i|=this.namedParameters?s.withNameForValues:0;let o=r&&t.protocolVersion.supportsKeyspaceInRequest(n.protocolVersion);i|=o&&this.options.getKeyspace()?s.withKeyspace:0,e.writeShort(this.consistency),t.protocolVersion.uses4BytesQueryFlags(n.protocolVersion)?e.writeInt(i):e.writeByte(i)}if(this.params&&this.params.length){e.writeShort(this.params.length);for(let t=0;t<this.params.length;t++){let r=this.params[t];i&s.withNameForValues&&(e.writeString(r.name),r=r.value),e.writeBytes(n.encode(r,this.getParamType(t)))}}if(!t.protocolVersion.supportsPaging(n.protocolVersion)){(!this.params||!this.params.length)&&e.writeShort(0),e.writeShort(this.consistency);return}i&s.pageSize&&e.writeInt(this.options.getFetchSize()),i&s.withPagingState&&e.writeBytes(this.options.getPageState()),i&s.withSerialConsistency&&e.writeShort(this.options.getSerialConsistency()),i&s.withDefaultTimestamp&&e.writeLong(a),i&s.withKeyspace&&e.writeString(this.options.getKeyspace())}},QueryRequest=class extends ExecuteRequest{constructor(t,n,r,i){super(t,null,n,r,null),this.hints=this.options.getHints()||e.emptyArray,this.namedParameters=i}getParamType(e){return this.hints[e]}write(e,r){let i=new n(t.opcodes.query),a=this.options.isQueryTracing()?t.frameFlags.tracing:0;return this.options.getCustomPayload()&&(a|=t.frameFlags.customPayload,i.writeCustomPayload(this.options.getCustomPayload())),i.writeLString(this.query),t.protocolVersion.supportsPaging(e.protocolVersion)?this.writeQueryParameters(i,e,!0):i.writeShort(this.consistency),this.length=i.bodyLength,i.write(e.protocolVersion,r,a)}},PrepareRequest=class extends Request{constructor(e,t){super(),this.query=e,this.keyspace=t}write(e,r){let i=new n(t.opcodes.prepare);if(i.writeLString(this.query),t.protocolVersion.supportsPrepareFlags(e.protocolVersion)){let n=this.keyspace&&t.protocolVersion.supportsKeyspaceInRequest(e.protocolVersion)?l.withKeyspace:0;i.writeInt(n),n&l.withKeyspace&&i.writeString(this.keyspace)}return i.write(e.protocolVersion,r)}},StartupRequest=class extends Request{constructor(e){super(),this.options=e||{}}write(e,r){let o=new n(t.opcodes.startup),s={CQL_VERSION:this.options.cqlVersion||`3.0.0`,DRIVER_NAME:i,DRIVER_VERSION:a};return this.options.noCompact&&(s.NO_COMPACT=`true`),this.options.clientId&&(s.CLIENT_ID=this.options.clientId.toString()),this.options.applicationName&&(s.APPLICATION_NAME=this.options.applicationName),this.options.applicationVersion&&(s.APPLICATION_VERSION=this.options.applicationVersion),o.writeStringMap(s),o.write(e.protocolVersion,r)}},RegisterRequest=class extends Request{constructor(e){super(),this.events=e}write(e,r){let i=new n(t.opcodes.register);return i.writeStringList(this.events),i.write(e.protocolVersion,r)}},AuthResponseRequest=class extends Request{constructor(e){super(),this.token=e}write(e,r){let i=new n(t.opcodes.authResponse);return i.writeBytes(this.token),i.write(e.protocolVersion,r)}},CredentialsRequest=class extends Request{constructor(e,t){super(),this.username=e,this.password=t}write(e,r){let i=new n(t.opcodes.credentials);return i.writeStringMap({username:this.username,password:this.password}),i.write(e.protocolVersion,r)}},d=class BatchRequest extends Request{constructor(t,n){super(),this.queries=t,this.options=n,this.timestamp=this.options.getOrGenerateTimestamp(),this.hints=n.getHints()||e.emptyArray,this.type=u.logged,n.isBatchCounter()?this.type=u.counter:n.isBatchLogged()||(this.type=u.unlogged)}write(r,i){if(!this.queries||!(this.queries.length>0))throw TypeError(o.format(`Invalid queries provided %s`,this.queries));let a=new n(t.opcodes.batch),s=this.options.isQueryTracing()?t.frameFlags.tracing:0;this.options.getCustomPayload()&&(s|=t.frameFlags.customPayload,a.writeCustomPayload(this.options.getCustomPayload())),a.writeByte(this.type),a.writeShort(this.queries.length);let l=this;if(this.queries.forEach(function(t,n){let i=l.hints[n],o=t.params||e.emptyArray,getParamType;t.queryId?(a.writeByte(1),a.writeShortBytes(t.queryId),getParamType=e=>t.meta.columns[e].type):(a.writeByte(0),a.writeLString(t.query),getParamType=i?e=>i[e]:()=>null),a.writeShort(o.length),o.forEach((e,t)=>a.writeBytes(r.encode(e,getParamType(t))))},this),a.writeShort(this.options.getConsistency()),t.protocolVersion.supportsTimestamp(r.protocolVersion)){let e=this.options.getSerialConsistency()?c.withSerialConsistency:0,n=this.timestamp;e|=n==null?0:c.withDefaultTimestamp,e|=this.options.getKeyspace()&&t.protocolVersion.supportsKeyspaceInRequest(r.protocolVersion)?c.withKeyspace:0,t.protocolVersion.uses4BytesQueryFlags(r.protocolVersion)?a.writeInt(e):a.writeByte(e),e&c.withSerialConsistency&&a.writeShort(this.options.getSerialConsistency()),e&c.withDefaultTimestamp&&a.writeLong(n),e&c.withKeyspace&&a.writeString(this.options.getKeyspace())}return this.length=a.bodyLength,a.write(r.protocolVersion,i,s)}clone(){return new BatchRequest(this.queries,this.options)}};function CancelRequest(e){this.streamId=null,this.operationId=e}o.inherits(CancelRequest,Request),CancelRequest.prototype.write=function(e,r){let i=new n(t.opcodes.cancel);return i.writeInt(1),i.writeInt(this.operationId),i.write(e.protocolVersion,r)};var f={AuthResponseRequest,BatchRequest:d,CancelRequest,CredentialsRequest,ExecuteRequest,options:new class extends Request{write(e,r){return new n(t.opcodes.options).write(e.protocolVersion,r,0)}clone(){return this}},PrepareRequest,QueryRequest,RegisterRequest,Request,StartupRequest};export{ExecuteRequest,QueryRequest,f as default};
@@ -0,0 +1 @@
1
+ import e from"./types/index.js";var StreamIdStack=class{constructor(e){this.currentGroup=generateGroup(0),this.groupIndex=0,this.groups=[this.currentGroup],this.releaseTimeout=null,this.setVersion(e),this.inUse=0,this.releaseDelay=5e3}setVersion(t){this.maxGroups=e.protocolVersion.uses2BytesStreamIds(t)?256:1}pop(){let e=this.currentGroup.pop();if(e!==void 0)return this.inUse++,e;for(;this.groupIndex<this.groups.length-1;)if(this.currentGroup=this.groups[++this.groupIndex],e=this.currentGroup.pop(),e!==void 0)return this.inUse++,e;return this._tryCreateGroup()}push(e){this.inUse--;let t=e>>7,n=this.groups[t];n.push(e),t<this.groupIndex&&(this.groupIndex=t,this.currentGroup=n),this._tryIssueRelease()}clear(){this.releaseTimeout&&=(clearTimeout(this.releaseTimeout),null)}_tryCreateGroup(){return this.groups.length===this.maxGroups?null:(this.groupIndex=this.groups.length,this.currentGroup=generateGroup(this.groupIndex<<7),this.groups.push(this.currentGroup),this.inUse++,this.currentGroup.pop())}_tryIssueRelease(){this.releaseTimeout||this.groups.length<=4||(this.releaseTimeout=setTimeout(()=>this._releaseGroups(),this.releaseDelay))}_releaseGroups(){let e=0,t=this.groups.length-1;for(;e++<4&&this.groups.length>4&&t>this.groupIndex&&this.groups[t].length===128;)this.groups.pop(),t--;this.releaseTimeout=null,this._tryIssueRelease()}};function generateGroup(e){let t=Array(128),n=e+128-1;for(let e=0;e<128;e++)t[e]=n-e;return t}export{StreamIdStack as default};
@@ -0,0 +1 @@
1
+ import e from"./errors.js";import t from"./utils.js";import n from"./types/index.js";import{FrameReader as r}from"./readers.js";import i from"util";import{Transform as a,Writable as o}from"stream";const{FrameHeader:s}=n,c=new Set([0,1,3,10,13]);function Protocol(e){a.call(this,e),this.header=null,this.bodyLength=0,this.clearHeaderChunks(),this.version=0,this.headerSize=0}i.inherits(Protocol,a),Protocol.prototype._transform=function(e,t,n){let r=null;try{this.readItems(e)}catch(e){r=e}n(r)},Protocol.prototype.readItems=function(e){if(!e||e.length===0)return;this.version===0&&(this.version=s.getProtocolVersion(e),this.headerSize=s.size(this.version));let t=0,n=this.header;if(this.header=null,this.headerChunks.byteLength!==0){if(this.headerChunks.parts.push(e),this.headerChunks.byteLength+e.length<this.headerSize){this.headerChunks.byteLength+=e.length;return}n=s.fromBuffer(Buffer.concat(this.headerChunks.parts,this.headerSize)),t=this.headerSize-this.headerChunks.byteLength,this.clearHeaderChunks()}let r=[];for(;;){if(!n){if(this.headerSize>e.length-t){if(e.length-t<=0)break;let n=e.slice(t,e.length);this.headerChunks.parts.push(n),this.headerChunks.byteLength=n.length;break}n=s.fromBuffer(e,t),t+=this.headerSize}let i=e.length-t;if(n.bodyLength<=i+this.bodyLength)r.push({header:n,chunk:e,offset:t,frameEnded:!0}),t+=n.bodyLength-this.bodyLength,this.bodyLength=0;else if(i>=0){this.header=n,this.bodyLength+=i,i>0&&r.push({header:n,chunk:e,offset:t,frameEnded:!1});break}n=null}for(let e=0;e<r.length;e++)this.push(r[e])},Protocol.prototype.clearHeaderChunks=function(){this.headerChunks={byteLength:0,parts:[]}};function Parser(e,t){a.call(this,e),this.frames={},this.encoder=t}i.inherits(Parser,a),Parser.prototype._transform=function(t,n,r){let i=this.frameState(t),a=null;try{this.parseBody(i,t)}catch(e){a=e}r(a),t.frameEnded&&(i.cellBuffer&&this.push({header:i.header,error:new e.DriverInternalError(`There was an problem while parsing streaming frame, opcode `+i.header.opcode)}),this.push({header:i.header,frameEnded:!0}))},Parser.prototype.parseBody=function(e,t){if(e.isStreaming=e.byRow&&t.header.opcode===n.opcodes.result,!this.handleFrameBuffers(e,t))return;let i=new r(t.header,t.chunk,t.offset);if(e.flagsInfo===void 0){let t=i.offset;try{e.flagsInfo=i.readFlagsInfo()}catch(n){return this.handleParsingError(n,e,i,t)}}switch(t.header.opcode){case n.opcodes.result:return this.parseResult(e,i);case n.opcodes.ready:case n.opcodes.authSuccess:return this.push({header:e.header,ready:!0});case n.opcodes.authChallenge:return this.push({header:e.header,authChallenge:!0,token:i.readBytes()});case n.opcodes.authenticate:return this.push({header:e.header,mustAuthenticate:!0,authenticatorName:i.readString()});case n.opcodes.error:return this.push({header:e.header,error:i.readError()});case n.opcodes.supported:return this.push({header:e.header,supported:i.readStringMultiMap()});case n.opcodes.event:return this.push({header:e.header,event:i.readEvent()});default:return this.push({header:e.header,error:Error(`Received invalid opcode: `+t.header.opcode)})}},Parser.prototype.handleFrameBuffers=function(t,n){if(!t.isStreaming)return(t.bufferLength||0)+n.chunk.length-n.offset<n.header.bodyLength?(this.addFrameBuffer(t,n),!1):(t.buffers&&(n.chunk=this.getFrameBuffer(t,n),n.offset=0),!0);if(t.cellBuffer){if(n.offset!==0)throw new e.DriverInternalError(`Following chunks can not have an offset greater than zero`);if(t.cellBuffer.parts.push(n.chunk),!t.cellBuffer.expectedLength){if(t.cellBuffer.parts.length!==2)throw new e.DriverInternalError(`Buffer for streaming frame can not contain more than 1 item`);return n.chunk=Buffer.concat(t.cellBuffer.parts,t.cellBuffer.byteLength+n.chunk.length),t.cellBuffer=null,!0}if(t.cellBuffer.expectedLength>t.cellBuffer.byteLength+n.chunk.length)return t.cellBuffer.byteLength+=n.chunk.length,!1;n.chunk=Buffer.concat(t.cellBuffer.parts,t.cellBuffer.byteLength+n.chunk.length),t.cellBuffer=null}return!0},Parser.prototype.addFrameBuffer=function(t,n){if(!t.buffers){t.buffers=[n.chunk.slice(n.offset)],t.bufferLength=n.chunk.length-n.offset;return}if(n.offset>0)throw new e.DriverInternalError(`Following chunks can not have an offset greater than zero`);t.buffers.push(n.chunk),t.bufferLength+=n.chunk.length},Parser.prototype.getFrameBuffer=function(e,t){e.buffers.push(t.chunk);let n=Buffer.concat(e.buffers,e.bodyLength);return e.buffers=null,n},Parser.prototype.parseResult=function(r,i){let a,o=i.offset;try{if(!r.meta)switch(r.kind=i.readInt(),r.kind){case n.resultKind.voidResult:a={header:r.header,flags:r.flagsInfo};break;case n.resultKind.rows:r.meta=i.readMetadata(r.kind);break;case n.resultKind.setKeyspace:a={header:r.header,keyspaceSet:i.readString(),flags:r.flagsInfo};break;case n.resultKind.prepared:{let e=t.copyBuffer(i.readShortBytes());r.meta=i.readMetadata(r.kind),a={header:r.header,id:e,meta:r.meta,flags:r.flagsInfo};break}case n.resultKind.schemaChange:a={header:r.header,schemaChange:i.parseSchemaChange(),flags:r.flagsInfo};break;default:throw e.DriverInternalError(`Unexpected result kind: `+r.kind)}}catch(e){return this.handleParsingError(e,r,i,o)}if(a)return r.emitted?void 0:(r.emitted=!0,this.push(a));i.remainingLength()>0&&this.parseRows(r,i)},Parser.prototype.parseRows=function(e,r){if(e.parsingError)return;if(e.rowLength===void 0)try{e.rowLength=r.readInt()}catch(t){return this.handleParsingError(t,e,r)}if(e.rowLength===0)return this.push({header:e.header,result:{rows:t.emptyArray,meta:e.meta,flags:e.flagsInfo}});let i=e.meta;if(e.rowIndex=e.rowIndex||0,!e._colDecoders){let t=Array(i.columns.length);for(let e=0;e<i.columns.length;e++){let n=i.columns[e].type.code;t[e]=this.encoder.decoders[n]}e._colDecoders=t}let a=e._colDecoders,o=i.columns,s=Math.min(e.rowIndex+100,e.rowLength);for(let t=e.rowIndex;t<s;t++){let s=r.offset,l=new n.Row(i.columns),u;for(let n=0;n<o.length;n++){let i=o[n];try{u=r.readBytes()}catch(n){return this.handleParsingError(n,e,r,s,t)}try{u===null||u.length===0&&!c.has(i.type.code)?l[i.name]=null:l[i.name]=a[n].call(this.encoder,u,i.type)}catch(t){return this.handleParsingError(t,e,null)}}this.push({header:e.header,row:l,meta:e.meta,byRow:e.byRow,length:e.rowLength,flags:e.flagsInfo})}if(e.rowIndex=s,s<e.rowLength){e._reader=r;let t=this;setImmediate(()=>t.parseRows(e,e._reader));return}e._colDecoders=null,e._reader=null,e.byRow&&this.push({header:e.header,byRowCompleted:!0,meta:e.meta,length:e.rowLength,flags:e.flagsInfo})},Parser.prototype.setOptions=function(e,t){if(this.frames[e.toString()])throw new n.DriverError(`There was already state for this frame`);this.frames[e.toString()]=t},Parser.prototype.clearOptions=function(e){delete this.frames[e.toString()]},Parser.prototype.frameState=function(e){let t=this.frames[e.header.streamId];return t?e.frameEnded&&delete this.frames[e.header.streamId]:(t={},e.frameEnded||(this.frames[e.header.streamId]=t)),t.header=e.header,t},Parser.prototype.handleParsingError=function(e,t,n,r,i){if(n&&t.isStreaming&&e instanceof RangeError)return this.bufferResultCell(t,n,r,i,e.expectedLength);t.parsingError=!0,t.cellBuffer=null,this.push({header:t.header,error:e})},Parser.prototype.bufferResultCell=function(e,t,n,r,i){!n&&n!==0&&(n=t.offset),e.rowIndex=r;let a=t.slice(n);e.cellBuffer={parts:[a],byteLength:a.length,expectedLength:i}};function ResultEmitter(e){o.call(this,e),this.rowBuffer={}}i.inherits(ResultEmitter,o),ResultEmitter.prototype._write=function(e,t,n){let r=null;try{this.each(e)}catch(e){r=e}n(r)},ResultEmitter.prototype.each=function(e){return e.error||e.result?this.emit(`result`,e.header,e.error,e.result):e.frameEnded?this.emit(`frameEnded`,e.header):e.lastContinuousPage?this.emit(`lastContinuousPage`,e.header):e.byRowCompleted?this.emit(`byRowCompleted`,e.header,e.row,e.meta,e.flags):e.byRow?this.emit(`row`,e.header,e.row,e.meta,e.length,e.flags):e.row?this.bufferAndEmit(e):e.event?this.emit(`nodeEvent`,e.header,e.event):this.emit(`result`,e.header,null,e)},ResultEmitter.prototype.bufferAndEmit=function(e){let t=this.rowBuffer[e.header.streamId];t||=this.rowBuffer[e.header.streamId]=[],t.push(e.row),t.length===e.length&&(this.emit(`result`,e.header,null,{rows:t,meta:e.meta,flags:e.flags}),delete this.rowBuffer[e.header.streamId])};var l={Protocol,Parser,ResultEmitter};export{l as default};
@@ -0,0 +1 @@
1
+ import e from"./types/index.js";import t from"util";const n=e.dataTypes.getByName(`bigint`),r=e.dataTypes.getByName(`varint`),i=e.dataTypes.getByName(`blob`);var Token=class{constructor(e){this._value=e}getType(){throw Error(`You must implement a getType function for this Token instance`)}getValue(){return this._value}toString(){return this._value.toString()}compare(e){return this._value.compare(e._value)}equals(e){return this.compare(e)===0}inspect(){return this.constructor.name+` { `+this.toString()+` }`}},Murmur3Token=class extends Token{constructor(e){super(e)}getType(){return n}},RandomToken=class extends Token{constructor(e){super(e)}getType(){return r}},ByteOrderedToken=class extends Token{constructor(e){super(e)}getType(){return i}toString(){return this._value.toString(`hex`).toUpperCase()}},a=class TokenRange{constructor(e,t,n){this.start=e,this.end=t,Object.defineProperty(this,`_tokenizer`,{value:n,enumerable:!1})}splitEvenly(e){if(e<1)throw Error(t.format(`numberOfSplits (%d) must be greater than 0.`,e));if(this.isEmpty())throw Error(`Can't split empty range `+this.toString());let n=[],r=this._tokenizer.split(this.start,this.end,e),i=this.start,a;for(let e=0;e<r.length;e++)a=r[e],n.push(new TokenRange(i,a,this._tokenizer)),i=a;return n.push(new TokenRange(i,this.end,this._tokenizer)),n}isEmpty(){return this.start.equals(this.end)&&!this.start.equals(this._tokenizer.minToken())}isWrappedAround(){return this.start.compare(this.end)>0&&!this.end.equals(this._tokenizer.minToken())}unwrap(){return this.isWrappedAround()?[new TokenRange(this.start,this._tokenizer.minToken(),this._tokenizer),new TokenRange(this._tokenizer.minToken(),this.end,this._tokenizer)]:[this]}contains(e){if(this.isEmpty())return!1;let t=this._tokenizer.minToken();if(this.end.equals(t))return this.start.equals(t)||e.equals(t)?!0:e.compare(this.start)>0;let n=e.compare(this.start)>0,r=e.compare(this.end)<=0;return this.isWrappedAround()?n||r:n&&r}equals(e){return e===this?!0:e instanceof TokenRange?this.compare(e)===0:!1}compare(e){let t=this.start.compare(e.start);return t===0?this.end.compare(e.end):t}toString(){return t.format(`]%s, %s]`,this.start.toString(),this.end.toString())}},o={Token,TokenRange:a,ByteOrderedToken,Murmur3Token,RandomToken};export{Token,a as TokenRange,o as default};
@@ -0,0 +1 @@
1
+ import e from"./utils.js";import t from"./types/index.js";import n from"./types/mutable-long.js";import r from"./token.js";import i from"crypto";const{Integer:a}=t,o=new n(21461,4418,31633,34755),s=new n(37759,10053,44355,19701),c=n.fromNumber(5),l=new n(36045,60757,45015,65361),u=new n(60499,6789,47614,50382),d=n.fromNumber(1390208809),f=n.fromNumber(944331445);var Tokenizer=class{constructor(){}hash(e){throw Error(`You must implement a hash function for the tokenizer`)}parse(e){throw Error(`You must implement a parse function for the tokenizer`)}minToken(){throw Error(`You must implement a minToken function for the tokenizer`)}split(e,t,n){throw Error(`You must implement a split function for the tokenizer`)}splitBase(e,t,n,r,i){let o=a.fromInt(i),s=t.divide(o),c=t.modulo(o),l=[],u=e,d=s.add(a.ONE);for(let e=1;e<i;e++)u=c.greaterThan(a.ZERO)?u.add(d):u.add(s),r&&u.greaterThan(n)&&(u=u.subtract(r)),l.push(u),c=c.subtract(a.ONE);return l}stringify(e){return e.getValue().toString()}},Murmur3Tokenizer=class extends Tokenizer{constructor(){super()}hash(e){let t=e,i=0,a=t.length,l=a>>4,u=new n,p=new n,m=new n,h=new n;for(let e=0;e<l;e++)m=this.getBlock(t,i,e*2),h=this.getBlock(t,i,e*2+1),m.multiply(o),this.rotl64(m,31),m.multiply(s),u.xor(m),this.rotl64(u,27),u.add(p),u.multiply(c).add(d),h.multiply(s),this.rotl64(h,33),h.multiply(o),p.xor(h),this.rotl64(p,31),p.add(u),p.multiply(c).add(f);switch(i+=l*16,m=new n,h=new n,a&15){case 15:h.xor(fromSignedByte(t[i+14]).shiftLeft(48));case 14:h.xor(fromSignedByte(t[i+13]).shiftLeft(40));case 13:h.xor(fromSignedByte(t[i+12]).shiftLeft(32));case 12:h.xor(fromSignedByte(t[i+11]).shiftLeft(24));case 11:h.xor(fromSignedByte(t[i+10]).shiftLeft(16));case 10:h.xor(fromSignedByte(t[i+9]).shiftLeft(8));case 9:h.xor(fromSignedByte(t[i+8])),h.multiply(s),this.rotl64(h,33),h.multiply(o),p.xor(h);case 8:m.xor(fromSignedByte(t[i+7]).shiftLeft(56));case 7:m.xor(fromSignedByte(t[i+6]).shiftLeft(48));case 6:m.xor(fromSignedByte(t[i+5]).shiftLeft(40));case 5:m.xor(fromSignedByte(t[i+4]).shiftLeft(32));case 4:m.xor(fromSignedByte(t[i+3]).shiftLeft(24));case 3:m.xor(fromSignedByte(t[i+2]).shiftLeft(16));case 2:m.xor(fromSignedByte(t[i+1]).shiftLeft(8));case 1:m.xor(fromSignedByte(t[i])),m.multiply(o),this.rotl64(m,31),m.multiply(s),u.xor(m)}return u.xor(n.fromNumber(a)),p.xor(n.fromNumber(a)),u.add(p),p.add(u),this.fmix(u),this.fmix(p),u.add(p),new r.Murmur3Token(u)}getBlock(e,t,r){let i=t+(r<<3);return new n(e[i]|e[i+1]<<8,e[i+2]|e[i+3]<<8,e[i+4]|e[i+5]<<8,e[i+6]|e[i+7]<<8)}rotl64(e,t){let n=e.clone().shiftLeft(t);e.shiftRightUnsigned(64-t).or(n)}fmix(e){e.xor(new n(e.getUint16(2)>>>1|e.getUint16(3)<<15&65535,e.getUint16(3)>>>1,0,0)),e.multiply(l);let t=new n(e.getUint16(2)>>>1|e.getUint16(3)<<15&65535,e.getUint16(3)>>>1,0,0);e.xor(t),e.multiply(u),e.xor(new n(e.getUint16(2)>>>1|e.getUint16(3)<<15&65535,e.getUint16(3)>>>1,0,0))}parse(e){return new r.Murmur3Token(n.fromString(e))}minToken(){return this._minToken||=this.parse(`-9223372036854775808`),this._minToken}maxToken(){return this._maxToken||=this.parse(`9223372036854775807`),this._maxToken}maxValue(){return this._maxValue||=a.fromString(`9223372036854775807`),this._maxValue}minValue(){return this._minValue||=a.fromString(`-9223372036854775808`),this._minValue}ringLength(){return this._ringLength||=this.maxValue().subtract(this.minValue()),this._ringLength}split(e,t,n){e.equals(t)&&e.equals(this.minToken())&&(t=this.maxToken());let r=a.fromString(e.getValue().toString()),i=a.fromString(t.getValue().toString()).subtract(r);return i.isNegative()&&(i=i.add(this.ringLength())),this.splitBase(r,i,this.maxValue(),this.ringLength(),n).map(e=>this.parse(e.toString()))}stringify(e){let t=e.getValue();return t.getUint16(0)+`,`+t.getUint16(1)+`,`+t.getUint16(2)+`,`+t.getUint16(3)}},RandomTokenizer=class extends Tokenizer{constructor(){super(),this._crypto=i}hash(t){Array.isArray(t)&&(t=e.allocBufferFromArray(t));let n=this._crypto.createHash(`md5`).update(t).digest();return new r.RandomToken(a.fromBuffer(n).abs())}parse(e){return new r.RandomToken(a.fromString(e))}minToken(){return this._minToken||=this.parse(`-1`),this._minToken}maxValue(){return this._maxValue||=a.fromNumber(2**127),this._maxValue}maxToken(){return this._maxToken||=new r.RandomToken(this.maxValue()),this._maxToken}ringLength(){return this._ringLength||=this.maxValue().add(a.ONE),this._ringLength}split(e,t,n){e.equals(t)&&e.equals(this.minToken())&&(t=this.maxToken());let i=e.getValue(),o=t.getValue().subtract(i);return o.lessThan(a.ZERO)&&(o=o.add(this.ringLength())),this.splitBase(i,o,this.maxValue(),this.ringLength(),n).map(e=>new r.RandomToken(e))}},ByteOrderedTokenizer=class extends Tokenizer{constructor(){super()}hash(t){Array.isArray(t)&&(t=e.allocBufferFromArray(t));let n=t.length;for(let e=t.length-1;e>0&&t[e]===0;e--)n=e;return new r.ByteOrderedToken(t.slice(0,n))}stringify(e){return e.getValue().toString(`hex`)}parse(t){return this.hash(e.allocBufferFromString(t,`hex`))}minToken(){return this._minToken||=this.hash([]),this._minToken}_toNumber(e,t){let n=e;e.length!==t&&(n=Buffer.alloc(t),e.copy(n));let r=Array(Math.ceil(n.length/4));for(let e=0;e<r.length;e++){let t=n.length-(e+1)*4,i;if(t<0){t+=4,i=0;for(let e=0;e<t;e++){let r=n[e];i|=r<<(t-e-1)*8}}else i=n.readInt32BE(t);r[e]=i}return new a(r,0)}_toBuffer(e,t){let n=a.toBuffer(e);if(n.length===t)return n;let r,i;n[0]===0?(r=1,i=n.length-1):(r=0,i=n.length);let o=Buffer.alloc(t);return n.copy(o,t-i,r,i+r),o}split(e,t,n){let i=e.compare(t);if(i===0&&e.equals(this.minToken()))throw Error(`Cannot split whole ring with ordered partitioner`);let o,s,c,l,u,d=a.fromNumber(n),f=Math.max(e.getValue().length,t.getValue().length);if(i<0){let n=0;for(;o=this._toNumber(e.getValue(),f),s=this._toNumber(t.getValue(),f),c=s.subtract(o),!(n===4||c.compare(d)>=0);)f+=1,n+=1}else{let n=0;for(;o=this._toNumber(e.getValue(),f),s=this._toNumber(t.getValue(),f),l=a.fromNumber(2**(f*8)),u=l.subtract(a.ONE),c=s.subtract(o).add(l),!(n===4||c.compare(d)>=0);)f+=1,n+=1}return this.splitBase(o,c,u,l,n).map(e=>new r.ByteOrderedToken(this._toBuffer(e,f)))}};function fromSignedByte(e){return e<128?new n(e,0,0,0):new n(e-256&65535,65535,65535,65535)}var p={Murmur3Tokenizer,RandomTokenizer,ByteOrderedTokenizer};export{p as default};
@@ -0,0 +1 @@
1
+ import e from"../utils.js";import t from"./integer.js";function BigDecimal(e,n){typeof e==`number`&&(e=t.fromNumber(e)),this._intVal=e,this._scale=n}BigDecimal.fromBuffer=function(e){let n=e.readInt32BE(0);return new BigDecimal(t.fromBuffer(e.slice(4)),n)},BigDecimal.toBuffer=function(n){let r=t.toBuffer(n._intVal),i=e.allocBufferUnsafe(4);return i.writeInt32BE(n._scale,0),Buffer.concat([i,r],i.length+r.length)},BigDecimal.fromString=function(e){if(!e)throw TypeError(`Invalid null or undefined value`);e=e.trim();let n=e.indexOf(`.`),r=0;return n>=0&&(r=e.length-1-n,e=e.substr(0,n)+e.substr(n+1)),new BigDecimal(t.fromString(e),r)},BigDecimal.fromNumber=function(e){if(isNaN(e))return new BigDecimal(t.ZERO,0);let n=e.toString();return n.indexOf(`e`)>=0&&(n=e.toFixed(20)),BigDecimal.fromString(n)},BigDecimal.prototype.equals=function(e){return e instanceof BigDecimal&&this.compare(e)===0},BigDecimal.prototype.inspect=function(){return this.constructor.name+`: `+this.toString()},BigDecimal.prototype.notEquals=function(e){return!this.equals(e)},BigDecimal.prototype.compare=function(e){let t=this.subtract(e);return t.isNegative()?-1:+!t.isZero()},BigDecimal.prototype.subtract=function(e){let n=this;if(n._scale===e._scale)return new BigDecimal(n._intVal.subtract(e._intVal),n._scale);let r,i;return n._scale<e._scale?(r=e._scale-n._scale,i=n._intVal.multiply(t.fromNumber(10**r)).subtract(e._intVal),new BigDecimal(i,e._scale)):(r=n._scale-e._scale,i=n._intVal.subtract(e._intVal.multiply(t.fromNumber(10**r))),new BigDecimal(i,n._scale))},BigDecimal.prototype.add=function(e){let n=this;if(n._scale===e._scale)return new BigDecimal(n._intVal.add(e._intVal),n._scale);let r,i;return n._scale<e._scale?(r=e._scale-n._scale,i=n._intVal.multiply(t.fromNumber(10**r)).add(e._intVal),new BigDecimal(i,e._scale)):(r=n._scale-e._scale,i=n._intVal.add(e._intVal.multiply(t.fromNumber(10**r))),new BigDecimal(i,n._scale))},BigDecimal.prototype.greaterThan=function(e){return this.compare(e)===1},BigDecimal.prototype.isNegative=function(){return this._intVal.isNegative()},BigDecimal.prototype.isZero=function(){return this._intVal.isZero()},BigDecimal.prototype.toString=function(){let t=this._intVal.toString();if(this._scale===0)return t;let n=``;t.charAt(0)===`-`&&(n=`-`,t=t.substr(1));let r=t.length-this._scale;return r<=0&&(t=e.stringRepeat(`0`,-r+1)+t,r=t.length-this._scale),n+t.substr(0,r)+`.`+t.substr(r)},BigDecimal.prototype.toNumber=function(){return parseFloat(this.toString())},BigDecimal.prototype.toJSON=function(){return this.toString()};export{BigDecimal as default};
@@ -0,0 +1 @@
1
+ import e from"../utils.js";import t from"util";import n from"long";const r=e.VIntCoding,i={months:e.allocBuffer(9),days:e.allocBuffer(9),nanoseconds:e.allocBuffer(9)},a=2147483647,o=n.fromInt(1e3),s=o,c=o.multiply(s),l=o.multiply(c),u=n.fromInt(60).multiply(l),d=n.fromInt(60).multiply(u),f=/(\d+)(y|mo|w|d|h|s|ms|us|µs|ns|m)/gi,p=/P((\d+)Y)?((\d+)M)?((\d+)D)?(T((\d+)H)?((\d+)M)?((\d+)S)?)?/,m=/P(\d+)W/,h=/P(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/;function Duration(e,t,r){this.months=e,this.days=t,this.nanoseconds=typeof r==`number`?n.fromNumber(r):r}Duration.prototype.equals=function(e){return e instanceof Duration?this.months===e.months&&this.days===e.days&&this.nanoseconds.equals(e.nanoseconds):!1},Duration.prototype.toBuffer=function(){let t=r.writeVInt(n.fromNumber(this.months),i.months),a=r.writeVInt(n.fromNumber(this.days),i.days),o=r.writeVInt(this.nanoseconds,i.nanoseconds),s=e.allocBufferUnsafe(t+a+o);i.months.copy(s,0,0,t);let c=t;return i.days.copy(s,c,0,a),c+=a,i.nanoseconds.copy(s,c,0,o),s},Duration.prototype.toString=function(){let e=``;function append(t,n,r){return t===0||t<n?t:(e+=(t/n).toFixed(0)+r,t%n)}function append64(t,r,i){return t.equals(n.ZERO)||t.lessThan(r)?t:(e+=t.divide(r).toString()+i,t.modulo(r))}(this.months<0||this.days<0||this.nanoseconds.isNegative())&&(e=`-`);let t=append(Math.abs(this.months),12,`y`);return append(t,1,`mo`),append(Math.abs(this.days),1,`d`),this.nanoseconds.equals(n.ZERO)||(t=append64(this.nanoseconds.isNegative()?this.nanoseconds.negate():this.nanoseconds,d,`h`),t=append64(t,u,`m`),t=append64(t,l,`s`),t=append64(t,c,`ms`),t=append64(t,s,`us`),append64(t,n.ONE,`ns`)),e},Duration.fromBuffer=function(e){let t={value:0};return new Duration(r.readVInt(e,t).toNumber(),r.readVInt(e,t).toNumber(),r.readVInt(e,t))},Duration.fromString=function(e){let t=e.charAt(0)===`-`,n=t?e.substr(1):e;return n.charAt(0)===`P`?n.charAt(n.length-1)===`W`?parseIso8601WeekFormat(t,n):n.indexOf(`-`)>0?parseIso8601AlternativeFormat(t,n):parseIso8601Format(t,n):parseStandardFormat(t,n)};function parseStandardFormat(e,t){let n=new Builder(e);f.lastIndex=0;let r;for(;(r=f.exec(t))&&r.length<=3;)n.add(r[1],r[2]);return n.build()}function parseIso8601Format(e,n){let r=p.exec(n);if(!r||r[0]!==n)throw TypeError(t.format(`Unable to convert '%s' to a duration`,n));let i=new Builder(e);return r[1]&&i.addYears(r[2]),r[3]&&i.addMonths(r[4]),r[5]&&i.addDays(r[6]),r[7]&&(r[8]&&i.addHours(r[9]),r[10]&&i.addMinutes(r[11]),r[12]&&i.addSeconds(r[13])),i.build()}function parseIso8601WeekFormat(e,n){let r=m.exec(n);if(!r||r[0]!==n)throw TypeError(t.format(`Unable to convert '%s' to a duration`,n));return new Builder(e).addWeeks(r[1]).build()}function parseIso8601AlternativeFormat(e,n){let r=h.exec(n);if(!r||r[0]!==n)throw TypeError(t.format(`Unable to convert '%s' to a duration`,n));return new Builder(e).addYears(r[1]).addMonths(r[2]).addDays(r[3]).addHours(r[4]).addMinutes(r[5]).addSeconds(r[6]).build()}function Builder(e){this._isNegative=e,this._unitIndex=0,this._months=0,this._days=0,this._nanoseconds=n.ZERO,this._addMethods={y:this.addYears,mo:this.addMonths,w:this.addWeeks,d:this.addDays,h:this.addHours,m:this.addMinutes,s:this.addSeconds,ms:this.addMillis,µs:this.addMicros,us:this.addMicros,ns:this.addNanos},this._unitByIndex=[null,`years`,`months`,`weeks`,`days`,`hours`,`minutes`,`seconds`,`milliseconds`,`microseconds`,`nanoseconds`]}Builder.prototype._validateOrder=function(e){if(e===this._unitIndex)throw TypeError(t.format(`Invalid duration. The %s are specified multiple times`,this._getUnitName(e)));if(e<=this._unitIndex)throw TypeError(t.format(`Invalid duration. The %s should be after %s`,this._getUnitName(this._unitIndex),this._getUnitName(e)));this._unitIndex=e},Builder.prototype._validateMonths=function(e,t){this._validate32(e,(a-this._months)/t,`months`)},Builder.prototype._validateDays=function(e,t){this._validate32(e,(a-this._days)/t,`days`)},Builder.prototype._validateNanos=function(e,t){this._validate64(e,n.MAX_VALUE.subtract(this._nanoseconds).divide(t),`nanoseconds`)},Builder.prototype._validate32=function(e,n,r){if(e>n)throw TypeError(t.format(`Invalid duration. The total number of %s must be less or equal to %s`,r,a))},Builder.prototype._validate64=function(e,r,i){if(e.greaterThan(r))throw TypeError(t.format(`Invalid duration. The total number of %s must be less or equal to %s`,i,n.MAX_VALUE.toString()))},Builder.prototype._getUnitName=function(e){let t=this._unitByIndex[+e];if(!t)throw Error(`unknown unit index: `+e);return t},Builder.prototype.add=function(e,n){let r=this._addMethods[n.toLowerCase()];if(!r)throw TypeError(t.format(`Unknown duration symbol '%s'`,n));return r.call(this,e)},Builder.prototype.addYears=function(e){let t=+e;return this._validateOrder(1),this._validateMonths(t,12),this._months+=t*12,this},Builder.prototype.addMonths=function(e){let t=+e;return this._validateOrder(2),this._validateMonths(t,1),this._months+=t,this},Builder.prototype.addWeeks=function(e){let t=+e;return this._validateOrder(3),this._validateDays(t,7),this._days+=t*7,this},Builder.prototype.addDays=function(e){let t=+e;return this._validateOrder(4),this._validateDays(t,1),this._days+=t,this},Builder.prototype.addHours=function(e){let t=typeof e==`string`?n.fromString(e):e;return this._validateOrder(5),this._validateNanos(t,d),this._nanoseconds=this._nanoseconds.add(t.multiply(d)),this},Builder.prototype.addMinutes=function(e){let t=typeof e==`string`?n.fromString(e):e;return this._validateOrder(6),this._validateNanos(t,u),this._nanoseconds=this._nanoseconds.add(t.multiply(u)),this},Builder.prototype.addSeconds=function(e){let t=typeof e==`string`?n.fromString(e):e;return this._validateOrder(7),this._validateNanos(t,l),this._nanoseconds=this._nanoseconds.add(t.multiply(l)),this},Builder.prototype.addMillis=function(e){let t=typeof e==`string`?n.fromString(e):e;return this._validateOrder(8),this._validateNanos(t,c),this._nanoseconds=this._nanoseconds.add(t.multiply(c)),this},Builder.prototype.addMicros=function(e){let t=typeof e==`string`?n.fromString(e):e;return this._validateOrder(9),this._validateNanos(t,s),this._nanoseconds=this._nanoseconds.add(t.multiply(s)),this},Builder.prototype.addNanos=function(e){let t=typeof e==`string`?n.fromString(e):e;return this._validateOrder(10),this._validateNanos(t,n.ONE),this._nanoseconds=this._nanoseconds.add(t),this},Builder.prototype.build=function(){return this._isNegative?new Duration(-this._months,-this._days,this._nanoseconds.negate()):new Duration(this._months,this._days,this._nanoseconds)};export{Duration as default};
@@ -1,8 +1,8 @@
1
- import { ValueCallback } from "../../index.js";
1
+ import { ValueCallback } from "../index.js";
2
2
  import _Long from "long";
3
3
  import * as stream from "stream";
4
4
 
5
- //#region src/driver/lib/types/index.d.ts
5
+ //#region src/driver/types/index.d.ts
6
6
  declare namespace types {
7
7
  class Long extends _Long {}
8
8
  enum consistencies {
@@ -0,0 +1 @@
1
+ import e from"../errors.js";import t from"../utils.js";import n from"./uuid.js";import r from"./time-uuid.js";import i from"./protocol-version.js";import a from"./integer.js";import o from"./big-decimal.js";import s from"./duration.js";import c from"./inet-address.js";import l from"./local-date.js";import u from"./local-time.js";import d from"./result-set.js";import f from"./result-stream.js";import p from"./row.js";import m from"./tuple.js";import h from"./vector.js";import g from"util";import _ from"long";const v={any:0,one:1,two:2,three:3,quorum:4,all:5,localQuorum:6,eachQuorum:7,serial:8,localSerial:9,localOne:10},y={};y[v.any]=`ANY`,y[v.one]=`ONE`,y[v.two]=`TWO`,y[v.three]=`THREE`,y[v.quorum]=`QUORUM`,y[v.all]=`ALL`,y[v.localQuorum]=`LOCAL_QUORUM`,y[v.eachQuorum]=`EACH_QUORUM`,y[v.serial]=`SERIAL`,y[v.localSerial]=`LOCAL_SERIAL`,y[v.localOne]=`LOCAL_ONE`;const b={custom:0,ascii:1,bigint:2,blob:3,boolean:4,counter:5,decimal:6,double:7,float:8,int:9,text:10,timestamp:11,uuid:12,varchar:13,varint:14,timeuuid:15,inet:16,date:17,time:18,smallint:19,tinyint:20,duration:21,list:32,map:33,set:34,udt:48,tuple:49,getByName:function(e){if(e=e.toLowerCase(),e.indexOf(`<`)>0){let t=/^(list|set)<(.+)>$/.exec(e);if(t)return{code:this[t[1]],info:this.getByName(t[2])};let n=/^(map)< *(.+) *, *(.+)>$/.exec(e);if(n)return{code:this[n[1]],info:[this.getByName(n[2]),this.getByName(n[3])]};let r=/^(udt)<(.+)>$/.exec(e);if(r)return{code:this[r[1]],info:r[2]};let i=/^(tuple)<(.+)>$/.exec(e);if(i)return{code:this[i[1]],info:i[2].split(`,`).map(function(e){return this.getByName(e.trim())},this)};let a=/^vector<\s*(.+)\s*,\s*(\d+)\s*>$/.exec(e);if(a)return{code:this.custom,customTypeName:`vector`,info:[this.getByName(a[1]),parseInt(a[2],10)]}}let t={code:this[e]};if(typeof t.code!=`number`)throw TypeError(`Data type with name `+e+` not valid`);return t}},x=(function(){let e={};for(let t in b){if(!b.hasOwnProperty(t))continue;let n=b[t];typeof n==`number`&&(e[n]=t)}return e})(),S={local:0,remote:1,ignored:2},C={error:0,startup:1,ready:2,authenticate:3,credentials:4,options:5,supported:6,query:7,result:8,prepare:9,execute:10,register:11,event:12,batch:13,authChallenge:14,authResponse:15,authSuccess:16,cancel:255,isInRange:function(e){return e>this.error&&e>this.event}},w={topologyChange:`TOPOLOGY_CHANGE`,statusChange:`STATUS_CHANGE`,schemaChange:`SCHEMA_CHANGE`},T={serverError:0,protocolError:10,badCredentials:256,unavailableException:4096,overloaded:4097,isBootstrapping:4098,truncateError:4099,writeTimeout:4352,readTimeout:4608,readFailure:4864,functionFailure:5120,writeFailure:5376,syntaxError:8192,unauthorized:8448,invalid:8704,configError:8960,alreadyExists:9216,unprepared:9472,clientWriteFailure:32768},E={voidResult:1,rows:2,setKeyspace:3,prepared:4,schemaChange:5},D={compression:1,tracing:2,customPayload:4,warning:8},O=Object.freeze({unset:!0}),k=_.fromInt(1e3);let A=0;function timeuuid(e,n,i){let a,o,s,c;e&&(typeof e.msecs==`number`&&(a=new Date(e.msecs)),e.msecs instanceof Date&&(a=e.msecs),Array.isArray(e.node)&&(s=t.allocBufferFromArray(e.node)),typeof e.clockseq==`number`&&(c=t.allocBufferUnsafe(2),c.writeUInt16BE(e.clockseq,0)),typeof e.nsecs==`number`&&(o=e.nsecs));let l=new r(a,o,s,c);return n instanceof Buffer?(l.getBuffer().copy(n,i||0),n):l.toString()}function uuid(e,r,i){let a;return e&&Array.isArray(e.random)&&(a=new n(t.allocBufferFromArray(e.random))),a||=n.random(),r instanceof Buffer?(a.getBuffer().copy(r,i||0),r):a.toString()}function getDataTypeNameByCode(t){if(!t||typeof t.code!=`number`)throw new e.ArgumentError(`Invalid signature type definition`);let n=x[t.code];if(!n)throw new e.ArgumentError(g.format(`Type with code %d not found`,t.code));return!(`info`in t)||!t.info?n:t.code===b.custom&&`customTypeName`in t&&t.customTypeName===`vector`?`vector<`+getDataTypeNameByCode(t.info[0])+`, `+t.info[1]+`>`:Array.isArray(t.info)?n+`<`+t.info.map(function(e){return getDataTypeNameByCode(e)}).join(`, `)+`>`:typeof t.info.code==`number`?n+`<`+getDataTypeNameByCode(t.info)+`>`:t.code===b.udt?t.info.name:n}function FrameHeader(e,t,n,r,i){this.version=e,this.flags=t,this.streamId=n,this.opcode=r,this.bodyLength=i}FrameHeader.size=function(e){return i.uses2BytesStreamIds(e)?9:8},FrameHeader.getProtocolVersion=function(e){return e[0]&127},FrameHeader.fromBuffer=function(e,t){let n=0;t||=0;let r=e[t++]&127,a=e.readUInt8(t++);return i.uses2BytesStreamIds(r)?(n=e.readInt16BE(t),t+=2):n=e.readInt8(t++),new FrameHeader(r,a,n,e.readUInt8(t++),e.readUInt32BE(t))},FrameHeader.prototype.toBuffer=function(){let e=t.allocBufferUnsafe(FrameHeader.size(this.version));e.writeUInt8(this.version,0),e.writeUInt8(this.flags,1);let n=3;return i.uses2BytesStreamIds(this.version)?(e.writeInt16BE(this.streamId,2),n=4):e.writeInt8(this.streamId,2),e.writeUInt8(this.opcode,n++),e.writeUInt32BE(this.bodyLength,n),e},_.fromBuffer=function(e){if(!(e instanceof Buffer))throw TypeError(`Expected Buffer, obtained `+g.inspect(e));return new _(e.readInt32BE(4),e.readInt32BE(0))},_.toBuffer=function(e){if(!(e instanceof _))throw TypeError(`Expected Long, obtained `+g.inspect(e));let n=t.allocBufferUnsafe(8);return n.writeUInt32BE(e.getHighBitsUnsigned(),0),n.writeUInt32BE(e.getLowBitsUnsigned(),4),n},_.prototype.inspect=function(){return`Long: `+this.toString()},_.prototype.toJSON=function(){return this.toString()};function generateTimestamp(e,t){e||=new Date;let n=_.ZERO;return typeof t==`number`&&t>=0&&t<1e3?n=_.fromInt(t):(A>999&&(A=0),n=_.fromInt(A),A++),_.fromNumber(e.getTime()).multiply(k).add(n)}function QueryParserError(e){QueryParserError.super_.call(this,e.message,this.constructor),this.internalError=e}g.inherits(QueryParserError,e.DriverError);function TimeoutError(e){TimeoutError.super_.call(this,e,this.constructor),this.info=`Represents an error that happens when the maximum amount of time for an operation passed.`}g.inherits(TimeoutError,e.DriverError);var j={opcodes:C,consistencies:v,consistencyToString:y,dataTypes:b,getDataTypeNameByCode,distance:S,frameFlags:D,protocolEvents:w,protocolVersion:i,responseErrorCodes:T,resultKind:E,timeuuid,uuid,BigDecimal:o,Duration:s,FrameHeader,InetAddress:c,Integer:a,LocalDate:l,LocalTime:u,Long:_,ResultSet:d,ResultStream:f,Row:p,DriverError:e.DriverError,TimeoutError,TimeUuid:r,Tuple:m,Vector:h,Uuid:n,unset:O,generateTimestamp};export{_ as Long,j as default};
@@ -0,0 +1 @@
1
+ import e from"../utils.js";function InetAddress(e){if(!(e instanceof Buffer)||e.length!==4&&e.length!==16)throw TypeError(`The ip address must contain 4 or 16 bytes`);this.buffer=e,this.length=e.length,this.version=e.length===4?4:6}InetAddress.fromString=function(t){if(!t)return new InetAddress(e.allocBufferFromArray([0,0,0,0]));let n=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,r=/^[\da-f:.]+$/i,i;if(n.test(t))return i=t.split(`.`),new InetAddress(e.allocBufferFromArray(i));if(!r.test(t)||(i=t.split(`:`),i.length<3))throw TypeError(`Value could not be parsed as InetAddress: `+t);let a=e.allocBufferUnsafe(16),o=8-i.length+1,s=!1,c=0,l=n.test(i[i.length-1]);l&&--o;function writeItem(e){a.writeUInt8(+e,c++)}for(let e=0;e<i.length;e++){let t=i[e];if(t){if(l&&e===i.length-1){t.split(`.`).forEach(writeItem);break}a.writeUInt16BE(parseInt(t,16),c),c+=2;continue}s&&(o=1),s=!0;for(let e=0;e<o;e++)a[c++]=0,a[c++]=0}if(l&&!isValidIPv4Mapped(a))throw TypeError(`Only IPv4-Mapped IPv6 addresses are allowed as IPv6 address with embedded IPv4 address`);return new InetAddress(a)},InetAddress.prototype.equals=function(e){return e instanceof InetAddress?this.buffer.length===e.buffer.length&&this.buffer.toString(`hex`)===e.buffer.toString(`hex`):!1},InetAddress.prototype.getBuffer=function(){return this.buffer},InetAddress.prototype.inspect=function(){return this.constructor.name+`: `+this.toString()},InetAddress.prototype.toString=function(e){if(e===`hex`)return this.buffer.toString(`hex`);if(this.buffer.length===4)return this.buffer[0]+`.`+this.buffer[1]+`.`+this.buffer[2]+`.`+this.buffer[3];let t=-1,n={length:0,start:-1};function checkLongest(e){if(t>=0){let r=e-t;r>n.length&&(n.length=r,n.start=t,t=-1)}}for(let e=0;e<this.buffer.length;e+=2){if(this.buffer[e]===0&&this.buffer[e+1]===0){t<0&&(t=e),e===this.buffer.length-2&&checkLongest(e+2);continue}checkLongest(e)}let r=``;for(let e=0;e<this.buffer.length;e+=2){if(e===n.start){r+=`:`;continue}e<n.start+n.length&&e>n.start||(r.length>0&&(r+=`:`),r+=(this.buffer[e]<<8|this.buffer[e+1]).toString(16))}return r.charAt(r.length-1)===`:`&&(r+=`:`),r},InetAddress.prototype.toJSON=function(){return this.toString()};function isValidIPv4Mapped(e){for(let t=0;t<e.length-6;t++)if(e[t]!==0)return!1;return!(e[10]!==255||e[11]!==255)}export{InetAddress as default};
@@ -0,0 +1 @@
1
+ import e from"../utils.js";function Integer(e,t){this.bits_=[],this.sign_=t;for(var n=!0,r=e.length-1;r>=0;r--){var i=e[r]|0;(!n||i!=t)&&(this.bits_[r]=i,n=!1)}}Integer.IntCache_={},Integer.fromInt=function(e){if(-128<=e&&e<128){var t=Integer.IntCache_[e];if(t)return t}var n=new Integer([e|0],e<0?-1:0);return-128<=e&&e<128&&(Integer.IntCache_[e]=n),n},Integer.fromNumber=function(e){if(isNaN(e)||!isFinite(e))return Integer.ZERO;if(e<0)return Integer.fromNumber(-e).negate();for(var t=[],n=1,r=0;e>=n;r++)t[r]=e/n|0,n*=Integer.TWO_PWR_32_DBL_;return new Integer(t,0)},Integer.fromBits=function(e){var t=e[e.length-1];return new Integer(e,t&1<<31?-1:0)},Integer.fromString=function(e,t){if(e.length==0)throw TypeError(`number format error: empty string`);var n=t||10;if(n<2||36<n)throw Error(`radix out of range: `+n);if(e.charAt(0)==`-`)return Integer.fromString(e.substring(1),n).negate();if(e.indexOf(`-`)>=0)throw TypeError(`number format error: interior "-" character`);for(var r=Integer.fromNumber(n**8),i=Integer.ZERO,a=0;a<e.length;a+=8){var o=Math.min(8,e.length-a),s=parseInt(e.substring(a,a+o),n);if(o<8){var c=Integer.fromNumber(n**+o);i=i.multiply(c).add(Integer.fromNumber(s))}else i=i.multiply(r),i=i.add(Integer.fromNumber(s))}return i},Integer.fromBuffer=function(e){for(var t=Array(Math.ceil(e.length/4)),n=e[0]&128?-1:0,r=0;r<t.length;r++){var i=e.length-(r+1)*4,a;if(i<0){i+=4,a=0;for(var o=0;o<i;o++){var s=e[o];n===-1&&(s=~s&255),a|=s<<(i-o-1)*8}n===-1&&(a=~a)}else a=e.readInt32BE(i);t[r]=a}return new Integer(t,n)},Integer.toBuffer=function(t){var n=t.sign_,r=t.bits_;if(r.length===0)return e.allocBufferFromArray([t.sign_]);var i=r[r.length-1];n===-1&&(i=~i);var a=[];i>>>24>0&&a.push(i>>24&255),i>>>16>0&&a.push(i>>16&255),i>>>8>0&&a.push(i>>8&255),a.push(i&255),a[0]>>7&&a.unshift(0);for(var o=e.allocBufferUnsafe(a.length+(r.length-1)*4),s=0;s<a.length;s++){var c=a[s];n===-1?o[s]=~c:o[s]=c}for(var l=0;l<r.length-1;l++){var u=r[r.length-2-l],d=a.length+l*4;o.writeInt32BE(u,d)}return o},Integer.TWO_PWR_32_DBL_=65536*65536,Integer.ZERO=Integer.fromInt(0),Integer.ONE=Integer.fromInt(1),Integer.TWO_PWR_24_=Integer.fromInt(1<<24),Integer.prototype.toInt=function(){return this.bits_.length>0?this.bits_[0]:this.sign_},Integer.prototype.toNumber=function(){if(this.isNegative())return-this.negate().toNumber();for(var e=0,t=1,n=0;n<this.bits_.length;n++)e+=this.getBitsUnsigned(n)*t,t*=Integer.TWO_PWR_32_DBL_;return e},Integer.prototype.toString=function(e){var t=e||10;if(t<2||36<t)throw Error(`radix out of range: `+t);if(this.isZero())return`0`;if(this.isNegative())return`-`+this.negate().toString(t);for(var n=Integer.fromNumber(t**6),r=this,i=``;;){var a=r.divide(n),o=r.subtract(a.multiply(n)).toInt().toString(t);if(r=a,r.isZero())return o+i;for(;o.length<6;)o=`0`+o;i=``+o+i}},Integer.prototype.getBits=function(e){return e<0?0:e<this.bits_.length?this.bits_[e]:this.sign_},Integer.prototype.getBitsUnsigned=function(e){var t=this.getBits(e);return t>=0?t:Integer.TWO_PWR_32_DBL_+t},Integer.prototype.getSign=function(){return this.sign_},Integer.prototype.isZero=function(){if(this.sign_!=0)return!1;for(var e=0;e<this.bits_.length;e++)if(this.bits_[e]!=0)return!1;return!0},Integer.prototype.isNegative=function(){return this.sign_==-1},Integer.prototype.isOdd=function(){return this.bits_.length==0&&this.sign_==-1||this.bits_.length>0&&(this.bits_[0]&1)!=0},Integer.prototype.equals=function(e){if(this.sign_!=e.sign_)return!1;for(var t=Math.max(this.bits_.length,e.bits_.length),n=0;n<t;n++)if(this.getBits(n)!=e.getBits(n))return!1;return!0},Integer.prototype.notEquals=function(e){return!this.equals(e)},Integer.prototype.greaterThan=function(e){return this.compare(e)>0},Integer.prototype.greaterThanOrEqual=function(e){return this.compare(e)>=0},Integer.prototype.lessThan=function(e){return this.compare(e)<0},Integer.prototype.lessThanOrEqual=function(e){return this.compare(e)<=0},Integer.prototype.compare=function(e){var t=this.subtract(e);return t.isNegative()?-1:+!t.isZero()},Integer.prototype.shorten=function(e){for(var t=e-1>>5,n=(e-1)%32,r=[],i=0;i<t;i++)r[i]=this.getBits(i);var a=n==31?4294967295:(1<<n+1)-1,o=this.getBits(t)&a;return o&1<<n?(o|=4294967295-a,r[t]=o,new Integer(r,-1)):(r[t]=o,new Integer(r,0))},Integer.prototype.negate=function(){return this.not().add(Integer.ONE)},Integer.prototype.add=function(e){for(var t=Math.max(this.bits_.length,e.bits_.length),n=[],r=0,i=0;i<=t;i++){var a=this.getBits(i)>>>16,o=this.getBits(i)&65535,s=e.getBits(i)>>>16,c=e.getBits(i)&65535,l=r+o+c,u=(l>>>16)+a+s;r=u>>>16,l&=65535,u&=65535,n[i]=u<<16|l}return Integer.fromBits(n)},Integer.prototype.subtract=function(e){return this.add(e.negate())},Integer.prototype.multiply=function(e){if(this.isZero()||e.isZero())return Integer.ZERO;if(this.isNegative())return e.isNegative()?this.negate().multiply(e.negate()):this.negate().multiply(e).negate();if(e.isNegative())return this.multiply(e.negate()).negate();if(this.lessThan(Integer.TWO_PWR_24_)&&e.lessThan(Integer.TWO_PWR_24_))return Integer.fromNumber(this.toNumber()*e.toNumber());for(var t=this.bits_.length+e.bits_.length,n=[],r=0;r<2*t;r++)n[r]=0;for(var r=0;r<this.bits_.length;r++)for(var i=0;i<e.bits_.length;i++){var a=this.getBits(r)>>>16,o=this.getBits(r)&65535,s=e.getBits(i)>>>16,c=e.getBits(i)&65535;n[2*r+2*i]+=o*c,Integer.carry16_(n,2*r+2*i),n[2*r+2*i+1]+=a*c,Integer.carry16_(n,2*r+2*i+1),n[2*r+2*i+1]+=o*s,Integer.carry16_(n,2*r+2*i+1),n[2*r+2*i+2]+=a*s,Integer.carry16_(n,2*r+2*i+2)}for(var r=0;r<t;r++)n[r]=n[2*r+1]<<16|n[2*r];for(var r=t;r<2*t;r++)n[r]=0;return new Integer(n,0)},Integer.carry16_=function(e,t){for(;(e[t]&65535)!=e[t];)e[t+1]+=e[t]>>>16,e[t]&=65535},Integer.prototype.divide=function(e){if(e.isZero())throw Error(`division by zero`);if(this.isZero())return Integer.ZERO;if(this.isNegative())return e.isNegative()?this.negate().divide(e.negate()):this.negate().divide(e).negate();if(e.isNegative())return this.divide(e.negate()).negate();for(var t=Integer.ZERO,n=this;n.greaterThanOrEqual(e);){for(var r=Math.max(1,Math.floor(n.toNumber()/e.toNumber())),i=Math.ceil(Math.log(r)/Math.LN2),a=i<=48?1:2**(i-48),o=Integer.fromNumber(r),s=o.multiply(e);s.isNegative()||s.greaterThan(n);)r-=a,o=Integer.fromNumber(r),s=o.multiply(e);o.isZero()&&(o=Integer.ONE),t=t.add(o),n=n.subtract(s)}return t},Integer.prototype.modulo=function(e){return this.subtract(this.divide(e).multiply(e))},Integer.prototype.not=function(){for(var e=this.bits_.length,t=[],n=0;n<e;n++)t[n]=~this.bits_[n];return new Integer(t,~this.sign_)},Integer.prototype.and=function(e){for(var t=Math.max(this.bits_.length,e.bits_.length),n=[],r=0;r<t;r++)n[r]=this.getBits(r)&e.getBits(r);return new Integer(n,this.sign_&e.sign_)},Integer.prototype.or=function(e){for(var t=Math.max(this.bits_.length,e.bits_.length),n=[],r=0;r<t;r++)n[r]=this.getBits(r)|e.getBits(r);return new Integer(n,this.sign_|e.sign_)},Integer.prototype.xor=function(e){for(var t=Math.max(this.bits_.length,e.bits_.length),n=[],r=0;r<t;r++)n[r]=this.getBits(r)^e.getBits(r);return new Integer(n,this.sign_^e.sign_)},Integer.prototype.shiftLeft=function(e){for(var t=e>>5,n=e%32,r=this.bits_.length+t+ +(n>0),i=[],a=0;a<r;a++)n>0?i[a]=this.getBits(a-t)<<n|this.getBits(a-t-1)>>>32-n:i[a]=this.getBits(a-t);return new Integer(i,this.sign_)},Integer.prototype.shiftRight=function(e){for(var t=e>>5,n=e%32,r=this.bits_.length-t,i=[],a=0;a<r;a++)n>0?i[a]=this.getBits(a+t)>>>n|this.getBits(a+t+1)<<32-n:i[a]=this.getBits(a+t);return new Integer(i,this.sign_)},Integer.prototype.inspect=function(){return this.constructor.name+`: `+this.toString()},Integer.prototype.abs=function(){return this.sign_===0?this:this.negate()},Integer.prototype.toJSON=function(){return this.toString()};export{Integer as default};
@@ -0,0 +1 @@
1
+ import e from"../utils.js";import t from"util";const n=864e5,r=2**31;function LocalDate(e,r,i){if(typeof e==`number`&&typeof r==`number`&&typeof i==`number`){if(this.date=new Date,this.date.setUTCHours(0,0,0,0),this.date.setUTCFullYear(e,r-1,i),isNaN(this.date.getTime()))throw Error(t.format(`%d-%d-%d does not form a valid ES5 date!`,e,r,i))}else if(r===void 0&&i===void 0&&typeof e==`number`){if(e<-2147483648||e>2147483647)throw Error(`You must provide a valid value for days since epoch (-2147483648 <= value <= 2147483647).`);this.date=new Date(e*n)}if(this.date===void 0)throw Error(`You must provide a valid year, month and day`);this._value=isNaN(this.date.getTime())?e:null,this.year=this.date.getUTCFullYear(),this.month=this.date.getUTCMonth()+1,this.day=this.date.getUTCDate()}LocalDate.now=function(){return LocalDate.fromDate(new Date)},LocalDate.utcNow=function(){return new LocalDate(Date.now())},LocalDate.fromDate=function(e){if(isNaN(e.getTime()))throw TypeError(`Invalid date: `+e);return new LocalDate(e.getFullYear(),e.getMonth()+1,e.getDate())},LocalDate.fromString=function(e){if((e.match(/-/g)||[]).length>=2){let t=1;e[0]===`-`&&(e=e.substring(1),t=-1);let n=e.split(`-`);return new LocalDate(t*parseInt(n[0],10),parseInt(n[1],10),parseInt(n[2],10))}if(e.match(/^-?\d+$/))return new LocalDate(parseInt(e,10));throw Error(`Invalid input '`+e+`'.`)},LocalDate.fromBuffer=function(e){return new LocalDate(e.readUInt32BE(0)-r)},LocalDate.prototype.compare=function(e){let t=(isNaN(this.date.getTime())?this._value*n:this.date.getTime())-(isNaN(e.date.getTime())?e._value*n:e.date.getTime());return t<0?-1:+(t>0)},LocalDate.prototype.equals=function(e){return e instanceof LocalDate&&this.compare(e)===0},LocalDate.prototype.inspect=function(){return this.constructor.name+`: `+this.toString()},LocalDate.prototype.toBuffer=function(){let t=(isNaN(this.date.getTime())?this._value:Math.floor(this.date.getTime()/n))+r,i=e.allocBufferUnsafe(4);return i.writeUInt32BE(t,0),i},LocalDate.prototype.toString=function(){let e;return isNaN(this.date.getTime())?this._value.toString():(e=this.year<0?`-`+fillZeros((this.year*-1).toString(),4):fillZeros(this.year.toString(),4),e+=`-`+fillZeros(this.month.toString(),2)+`-`+fillZeros(this.day.toString(),2),e)},LocalDate.prototype.toJSON=function(){return this.toString()};function fillZeros(t,n){return t.length>=n?t:e.stringRepeat(`0`,n-t.length)+t}export{LocalDate as default};
@@ -0,0 +1 @@
1
+ import e from"../utils.js";import t from"util";import n from"long";const r=n.fromString(`86399999999999`),i=n.fromNumber(1e9),a=n.fromNumber(1e6);function LocalTime(e){if(!(e instanceof n))throw Error(`You must specify a Long value as totalNanoseconds`);if(e.lessThan(n.ZERO)||e.greaterThan(r))throw Error(`Total nanoseconds out of range`);this.value=e,this.hour=this._getParts()[0],this.minute=this._getParts()[1],this.second=this._getParts()[2],this.nanosecond=this._getParts()[3]}LocalTime.fromString=function(n){if(typeof n!=`string`)throw Error(`Argument type invalid: `+t.inspect(n));let r=n.split(`:`),i=parseInt(r[0],10)*36e5+parseInt(r[1],10)*6e4,a;if(r.length===3){let t=r[2].split(`.`);i+=parseInt(t[0],10)*1e3,t.length===2&&(a=t[1],a+=e.stringRepeat(`0`,9-a.length))}return LocalTime.fromMilliseconds(i,parseInt(a,10)||0)},LocalTime.now=function(e){return LocalTime.fromDate(new Date,e)},LocalTime.fromDate=function(e,t){if(!(e instanceof Date))throw Error(`Not a valid date`);let n=(e.getTime()+e.getTimezoneOffset()*-6e4)%864e5;return LocalTime.fromMilliseconds(n,t)},LocalTime.fromMilliseconds=function(e,t){return typeof t!=`number`&&(t=0),new LocalTime(n.fromNumber(e).multiply(a).add(n.fromNumber(t)))},LocalTime.fromBuffer=function(e){if(!(e instanceof Buffer))throw TypeError(`Expected Buffer, obtained `+t.inspect(e));return new LocalTime(new n(e.readInt32BE(4),e.readInt32BE(0)))},LocalTime.prototype.compare=function(e){return this.value.compare(e.value)},LocalTime.prototype.equals=function(e){return e instanceof LocalTime&&this.compare(e)===0},LocalTime.prototype.getTotalNanoseconds=function(){return this.value},LocalTime.prototype.inspect=function(){return this.constructor.name+`: `+this.toString()},LocalTime.prototype.toBuffer=function(){let t=e.allocBufferUnsafe(8);return t.writeUInt32BE(this.value.getHighBitsUnsigned(),0),t.writeUInt32BE(this.value.getLowBitsUnsigned(),4),t},LocalTime.prototype.toString=function(){return formatTime(this._getParts())},LocalTime.prototype.toJSON=function(){return this.toString()},LocalTime.prototype._getParts=function(){if(!this._partsCache){let e=[0,0,0,0],t=this.value.div(i);e[3]=this.value.subtract(t.multiply(i)).toNumber(),e[2]=t.toNumber(),e[2]>=60&&(e[1]=Math.floor(e[2]/60),e[2]%=60),e[1]>=60&&(e[0]=Math.floor(e[1]/60),e[1]%=60),this._partsCache=e}return this._partsCache};function formatTime(t){let n;if(n=t[0]<10?`0`+t[0]+`:`:t[0]+`:`,t[1]<10?n+=`0`+t[1]+`:`:n+=t[1]+`:`,t[2]<10?n+=`0`+t[2]:n+=t[2],t[3]>0){let r=t[3].toString();r.length<9&&(r=e.stringRepeat(`0`,9-r.length)+r);let i;for(let e=r.length-1;e>0&&r[e]===`0`;e--)i=e;i&&(r=r.substring(0,i)),n+=`.`+r}return n}export{LocalTime as default};
@@ -0,0 +1 @@
1
+ import e from"long";const t=65536,n=t*t;var r=class MutableLong{constructor(e,t,n,r){this._arr=[e&65535,t&65535,n&65535,r&65535]}toString(){return this.toImmutable().toString()}compare(e){let t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this._compareBits(e)}_compareBits(e){for(let t=3;t>=0;t--){if(this._arr[t]>e._arr[t])return 1;if(this._arr[t]<e._arr[t])return-1}return 0}getUint16(e){return this._arr[e]}getLowBitsUnsigned(){return(this._arr[0]|(this._arr[1]&65535)<<16)>>>0}getHighBitsUnsigned(){return(this._arr[2]|this._arr[3]<<16)>>>0}toNumber(){return(this._arr[3]<<16|this._arr[2])*n+((this._arr[1]<<16|this._arr[0])>>>0)}not(){return this._arr[0]=~this._arr[0]&65535,this._arr[1]=~this._arr[1]&65535,this._arr[2]=~this._arr[2]&65535,this._arr[3]=~this._arr[3]&65535,this}add(e){let t=0,n=0,r=0,i=0;return i+=this._arr[0]+e._arr[0],this._arr[0]=i&65535,r+=i>>>16,r+=this._arr[1]+e._arr[1],this._arr[1]=r&65535,n+=r>>>16,n+=this._arr[2]+e._arr[2],this._arr[2]=n&65535,t+=n>>>16,t+=this._arr[3]+e._arr[3],this._arr[3]=t&65535,this}shiftLeft(e){if(e===0)return this;if(e>=64)return this.toZero();let t=e%16,n=Math.floor(e/16);return n>0&&(this._arr[3]=this._arr[3-n],this._arr[2]=n>2?0:this._arr[2-n],this._arr[1]=n>1?0:this._arr[0],this._arr[0]=0),t>0&&(this._arr[3]=(this._arr[3]<<t|this._arr[2]>>>16-t)&65535,this._arr[2]=(this._arr[2]<<t|this._arr[1]>>>16-t)&65535,this._arr[1]=(this._arr[1]<<t|this._arr[0]>>>16-t)&65535,this._arr[0]=this._arr[0]<<t&65535),this}shiftRightUnsigned(e){if(e===0)return this;if(e>=64)return this.toZero();let t=e%16,n=Math.floor(e/16);return n>0&&(this._arr[0]=this._arr[n],this._arr[1]=n>2?0:this._arr[1+n],this._arr[2]=n>1?0:this._arr[3],this._arr[3]=0),t>0&&(this._arr[0]=this._arr[0]>>>t|this._arr[1]<<16-t&65535,this._arr[1]=this._arr[1]>>>t|this._arr[2]<<16-t&65535,this._arr[2]=this._arr[2]>>>t|this._arr[3]<<16-t&65535,this._arr[3]=this._arr[3]>>>t),this}or(e){return this._arr[0]|=e._arr[0],this._arr[1]|=e._arr[1],this._arr[2]|=e._arr[2],this._arr[3]|=e._arr[3],this}xor(e){return this._arr[0]^=e._arr[0],this._arr[1]^=e._arr[1],this._arr[2]^=e._arr[2],this._arr[3]^=e._arr[3],this}clone(){return new MutableLong(this._arr[0],this._arr[1],this._arr[2],this._arr[3])}multiply(e){let t=!1;if(this.isZero()||e.isZero())return this.toZero();this.isNegative()&&(this.negate(),t=!t),e.isNegative()&&(e=e.clone().negate(),t=!t);let n=0,r=0,i=0,a=0;return a+=this._arr[0]*e._arr[0],i+=a>>>16,i+=this._arr[1]*e._arr[0],r+=i>>>16,i&=65535,i+=this._arr[0]*e._arr[1],r+=i>>>16,r+=this._arr[2]*e._arr[0],n+=r>>>16,r&=65535,r+=this._arr[1]*e._arr[1],n+=r>>>16,r&=65535,r+=this._arr[0]*e._arr[2],n+=r>>>16,n+=this._arr[3]*e._arr[0]+this._arr[2]*e._arr[1]+this._arr[1]*e._arr[2]+this._arr[0]*e._arr[3],this._arr[0]=a&65535,this._arr[1]=i&65535,this._arr[2]=r&65535,this._arr[3]=n&65535,t&&this.negate(),this}toZero(){return this._arr[3]=this._arr[2]=this._arr[1]=this._arr[0]=0,this}isZero(){return this._arr[3]===0&&this._arr[2]===0&&this._arr[1]===0&&this._arr[0]===0}isNegative(){return(this._arr[3]&32768)>0}negate(){return this.not().add(MutableLong.one)}equals(e){return e instanceof MutableLong?this._arr[0]===e._arr[0]&&this._arr[1]===e._arr[1]&&this._arr[2]===e._arr[2]&&this._arr[3]===e._arr[3]:!1}toImmutable(){return e.fromBits(this.getLowBitsUnsigned(),this.getHighBitsUnsigned(),!1)}static fromNumber(e){if(isNaN(e)||!isFinite(e))return new MutableLong;if(e<0)return MutableLong.fromNumber(-e).negate();let t=e%n,r=e/n;return MutableLong.fromBits(t,r)}static fromBits(e,t){return new MutableLong(e,e>>>16,t,t>>>16)}static fromString(e,t){if(typeof e!=`string`)throw Error(`String format is not valid: `+e);if(e.length===0)throw Error(`number format error: empty string`);if(e===`NaN`||e===`Infinity`||e===`+Infinity`||e===`-Infinity`)return new MutableLong;if(t||=10,t<2||t>36)throw Error(`radix out of range: `+t);let n;if((n=e.indexOf(`-`))>0)throw Error(`number format error: interior "-" character: `+e);if(n===0)return MutableLong.fromString(e.substring(1),t).negate();let r=MutableLong.fromNumber(t**8),i=new MutableLong;for(let n=0;n<e.length;n+=8){let a=Math.min(8,e.length-n),o=parseInt(e.substring(n,n+a),t);if(a<8){let e=MutableLong.fromNumber(t**+a);i.multiply(e).add(MutableLong.fromNumber(o));break}i.multiply(r),i.add(MutableLong.fromNumber(o))}return i}};r.one=new r(1,0,0,0);export{r as default};