monetdb 2.0.1 → 2.0.2

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 (60) hide show
  1. package/README.md +2 -1
  2. package/dist/PrepareStatement.d.ts +12 -0
  3. package/dist/PrepareStatement.js +29 -0
  4. package/dist/PrepareStatement.js.map +1 -0
  5. package/dist/QueryStream.d.ts +7 -0
  6. package/dist/QueryStream.js +13 -0
  7. package/dist/QueryStream.js.map +1 -0
  8. package/dist/connection.d.ts +25 -0
  9. package/dist/connection.js +104 -0
  10. package/dist/connection.js.map +1 -0
  11. package/dist/connections.d.ts +1 -0
  12. package/dist/connections.js +49 -0
  13. package/dist/connections.js.map +1 -0
  14. package/dist/defaults.d.ts +10 -0
  15. package/dist/defaults.js +13 -0
  16. package/dist/defaults.js.map +1 -0
  17. package/dist/file-transfer.d.ts +34 -0
  18. package/dist/file-transfer.js +194 -0
  19. package/dist/file-transfer.js.map +1 -0
  20. package/dist/index.d.ts +2 -0
  21. package/dist/index.js +9 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/mapi.d.ts +148 -0
  24. package/dist/mapi.js +851 -0
  25. package/dist/mapi.js.map +1 -0
  26. package/dist/monetize.d.ts +2 -0
  27. package/dist/monetize.js +57 -0
  28. package/dist/monetize.js.map +1 -0
  29. package/dist/tsconfig.tsbuildinfo +1 -0
  30. package/package.json +7 -2
  31. package/.github/workflows/Linux.yml +0 -45
  32. package/.github/workflows/docs.yml +0 -79
  33. package/.github/workflows/macos.yml +0 -43
  34. package/.github/workflows/monetdb-versions.yml +0 -43
  35. package/docs/components/alert.tsx +0 -10
  36. package/docs/components/info.tsx +0 -6
  37. package/docs/next.config.js +0 -24
  38. package/docs/package-lock.json +0 -5069
  39. package/docs/package.json +0 -22
  40. package/docs/pages/_app.js +0 -9
  41. package/docs/pages/_meta.json +0 -18
  42. package/docs/pages/apis/_meta.json +0 -4
  43. package/docs/pages/apis/connection.mdx +0 -60
  44. package/docs/pages/apis/result.mdx +0 -39
  45. package/docs/pages/filetransfer.mdx +0 -43
  46. package/docs/pages/index.mdx +0 -27
  47. package/docs/pages/prepstmt.mdx +0 -13
  48. package/docs/pages/result.mdx +0 -41
  49. package/docs/theme.config.js +0 -35
  50. package/docs/v0/README.v0.md +0 -138
  51. package/docs/v1/MapiConnection.md +0 -53
  52. package/docs/v1/README.md +0 -532
  53. package/docs/v1/v1-notes.md +0 -173
  54. package/test/connection.ts +0 -43
  55. package/test/exec-queries.ts +0 -112
  56. package/test/filetransfer.ts +0 -94
  57. package/test/prepare-statement.ts +0 -27
  58. package/test/query-stream.ts +0 -41
  59. package/test/tmp/.gitignore +0 -4
  60. package/tsconfig.json +0 -24
package/dist/mapi.js ADDED
@@ -0,0 +1,851 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.QueryStream = exports.HandShakeOption = exports.createMapiConfig = exports.parseMapiUri = exports.MapiConnection = void 0;
16
+ const node_net_1 = require("node:net");
17
+ const events_1 = require("events");
18
+ const buffer_1 = require("buffer");
19
+ const node_crypto_1 = require("node:crypto");
20
+ const defaults_1 = __importDefault(require("./defaults"));
21
+ const node_url_1 = require("node:url");
22
+ const file_transfer_1 = require("./file-transfer");
23
+ const MAPI_BLOCK_SIZE = 1024 * 8 - 2;
24
+ const MAPI_HEADER_SIZE = 2;
25
+ const MSG_PROMPT = "";
26
+ const MSG_MORE = "\x01\x02\n";
27
+ const MSG_FILETRANS = "\x01\x03\n";
28
+ const MSG_INFO = "#";
29
+ const MSG_ERROR = "!";
30
+ const MSG_Q = "&";
31
+ const MSG_QTABLE = "&1";
32
+ const MSG_QUPDATE = "&2";
33
+ const MSG_QSCHEMA = "&3";
34
+ const MSG_QTRANS = "&4";
35
+ const MSG_QPREPARE = "&5";
36
+ const MSG_QBLOCK = "&6";
37
+ const MSG_HEADER = "%";
38
+ const MSG_TUPLE = "[";
39
+ const MSG_TUPLE_NOSLICE = "=";
40
+ const MSG_REDIRECT = "^";
41
+ const MSG_OK = "=OK";
42
+ const MAX_REDIRECTS = 10;
43
+ const MAX_BUFF_SIZE = buffer_1.constants.MAX_LENGTH;
44
+ var MAPI_STATE;
45
+ (function (MAPI_STATE) {
46
+ MAPI_STATE[MAPI_STATE["INIT"] = 1] = "INIT";
47
+ MAPI_STATE[MAPI_STATE["CONNECTED"] = 2] = "CONNECTED";
48
+ MAPI_STATE[MAPI_STATE["READY"] = 3] = "READY";
49
+ })(MAPI_STATE || (MAPI_STATE = {}));
50
+ var MAPI_LANGUAGE;
51
+ (function (MAPI_LANGUAGE) {
52
+ MAPI_LANGUAGE["SQL"] = "sql";
53
+ MAPI_LANGUAGE["MAPI"] = "mapi";
54
+ MAPI_LANGUAGE["CONTROL"] = "control";
55
+ })(MAPI_LANGUAGE || (MAPI_LANGUAGE = {}));
56
+ class HandShakeOption {
57
+ constructor(level, name, value, fallback, sent = false) {
58
+ this.level = level;
59
+ this.name = name;
60
+ this.value = value;
61
+ this.fallback = fallback;
62
+ this.sent = sent;
63
+ }
64
+ }
65
+ exports.HandShakeOption = HandShakeOption;
66
+ function isMapiUri(uri) {
67
+ const regx = new RegExp("^mapi:monetdb://*", "i");
68
+ return regx.test(uri);
69
+ }
70
+ function parseMapiUri(uri) {
71
+ if (isMapiUri(uri)) {
72
+ const url = new node_url_1.URL(uri.substring(5));
73
+ if (url.hostname) {
74
+ const host = url.hostname;
75
+ const port = parseInt(url.port);
76
+ const username = url.username;
77
+ const password = url.password;
78
+ const database = url.pathname.split("/")[1];
79
+ return {
80
+ host,
81
+ port,
82
+ username,
83
+ password,
84
+ database,
85
+ };
86
+ }
87
+ }
88
+ throw new Error(`Invalid MAPI URI ${uri}!`);
89
+ }
90
+ exports.parseMapiUri = parseMapiUri;
91
+ // validates and sets defaults on missing properties
92
+ function createMapiConfig(params) {
93
+ const database = params && params.database ? params.database : defaults_1.default.database;
94
+ if (typeof database != "string") {
95
+ throw new Error("database name must be string");
96
+ }
97
+ const username = params && params.username ? params.username : defaults_1.default.username;
98
+ const password = params && params.password ? params.password : defaults_1.default.password;
99
+ let host = params && params.host;
100
+ const unixSocket = params && params.unixSocket;
101
+ if (!unixSocket && !host)
102
+ host = defaults_1.default.host;
103
+ if (typeof host != "string") {
104
+ throw new TypeError(`${host} is not valid hostname`);
105
+ }
106
+ const port = params && params.port ? Number(params.port) : Number(defaults_1.default.port);
107
+ if (isNaN(port)) {
108
+ throw new TypeError(`${port} is not valid port`);
109
+ }
110
+ const timeout = params && params.timeout ? Number(params.timeout) : undefined;
111
+ if (timeout && isNaN(timeout)) {
112
+ throw new TypeError("timeout must be number");
113
+ }
114
+ const language = params && params.language ? params.language : MAPI_LANGUAGE.SQL;
115
+ const autoCommit = params.autoCommit || defaults_1.default.autoCommit;
116
+ const replySize = params.replySize || defaults_1.default.replySize;
117
+ return {
118
+ database,
119
+ username,
120
+ password,
121
+ language,
122
+ host,
123
+ port,
124
+ timeout,
125
+ unixSocket,
126
+ autoCommit,
127
+ replySize,
128
+ };
129
+ }
130
+ exports.createMapiConfig = createMapiConfig;
131
+ class Column {
132
+ constructor(table, name, type, index, length) {
133
+ this.table = table;
134
+ this.name = name;
135
+ this.type = type;
136
+ this.index = index;
137
+ this.length = length;
138
+ }
139
+ }
140
+ class QueryStream extends events_1.EventEmitter {
141
+ constructor() {
142
+ super();
143
+ }
144
+ end(res) {
145
+ this.emit("end", res);
146
+ }
147
+ }
148
+ exports.QueryStream = QueryStream;
149
+ function parseHeaderLine(hdrLine) {
150
+ if (hdrLine.startsWith(MSG_HEADER)) {
151
+ const [head, tail] = hdrLine.substring(1).trim().split("#");
152
+ let res = {};
153
+ const vals = head.trim().split(",\t");
154
+ switch (tail.trim()) {
155
+ case "table_name":
156
+ res = { tableNames: vals };
157
+ break;
158
+ case "name":
159
+ res = { columnNames: vals };
160
+ break;
161
+ case "type":
162
+ res = { columnTypes: vals };
163
+ break;
164
+ default:
165
+ res = {};
166
+ }
167
+ return res;
168
+ }
169
+ throw TypeError("Invalid header format!");
170
+ }
171
+ function parseTupleLine(line, types) {
172
+ if (line.startsWith(MSG_TUPLE) && line.endsWith("]")) {
173
+ var resultline = [];
174
+ var cCol = 0;
175
+ var curtok = "";
176
+ var state = "INCRAP";
177
+ let endQuotes = 0;
178
+ /* mostly adapted from clients/R/MonetDB.R/src/mapisplit.c */
179
+ for (var curPos = 2; curPos < line.length - 1; curPos++) {
180
+ var chr = line.charAt(curPos);
181
+ switch (state) {
182
+ case "INCRAP":
183
+ if (chr != "\t" && chr != "," && chr != " ") {
184
+ if (chr == '"') {
185
+ state = "INQUOTES";
186
+ }
187
+ else {
188
+ state = "INTOKEN";
189
+ curtok += chr;
190
+ }
191
+ }
192
+ break;
193
+ case "INTOKEN":
194
+ if (chr == "," || curPos == line.length - 2) {
195
+ if (curtok == "NULL" && endQuotes === 0) {
196
+ resultline.push(null);
197
+ }
198
+ else {
199
+ switch (types[cCol]) {
200
+ case "boolean":
201
+ resultline.push(curtok == "true");
202
+ break;
203
+ case "tinyint":
204
+ case "smallint":
205
+ case "int":
206
+ case "wrd":
207
+ case "bigint":
208
+ resultline.push(parseInt(curtok));
209
+ break;
210
+ case "real":
211
+ case "double":
212
+ case "decimal":
213
+ resultline.push(parseFloat(curtok));
214
+ break;
215
+ case "json":
216
+ try {
217
+ resultline.push(JSON.parse(curtok));
218
+ }
219
+ catch (e) {
220
+ resultline.push(curtok);
221
+ }
222
+ break;
223
+ default:
224
+ // we need to unescape double quotes
225
+ //valPtr = valPtr.replace(/[^\\]\\"/g, '"');
226
+ resultline.push(curtok);
227
+ break;
228
+ }
229
+ }
230
+ cCol++;
231
+ state = "INCRAP";
232
+ curtok = "";
233
+ endQuotes = 0;
234
+ }
235
+ else {
236
+ curtok += chr;
237
+ }
238
+ break;
239
+ case "ESCAPED":
240
+ state = "INQUOTES";
241
+ switch (chr) {
242
+ case "t":
243
+ curtok += "\t";
244
+ break;
245
+ case "n":
246
+ curtok += "\n";
247
+ break;
248
+ case "r":
249
+ curtok += "\r";
250
+ break;
251
+ default:
252
+ curtok += chr;
253
+ }
254
+ break;
255
+ case "INQUOTES":
256
+ if (chr == '"') {
257
+ state = "INTOKEN";
258
+ endQuotes++;
259
+ break;
260
+ }
261
+ if (chr == "\\") {
262
+ state = "ESCAPED";
263
+ break;
264
+ }
265
+ curtok += chr;
266
+ break;
267
+ }
268
+ }
269
+ return resultline;
270
+ }
271
+ throw TypeError("Invalid tuple format!");
272
+ }
273
+ class Response {
274
+ constructor(opt = {}) {
275
+ this.buff = buffer_1.Buffer.allocUnsafe(MAPI_BLOCK_SIZE).fill(0);
276
+ this.offset = 0;
277
+ this.parseOffset = 0;
278
+ this.segments = [];
279
+ this.settled = false;
280
+ this.stream = opt.stream;
281
+ this.callbacks = opt.callbacks;
282
+ this.fileHandler = opt.fileHandler;
283
+ if (opt.stream) {
284
+ this.queryStream = new QueryStream();
285
+ if (opt.callbacks && opt.callbacks.resolve)
286
+ opt.callbacks.resolve(this.queryStream);
287
+ }
288
+ }
289
+ append(data) {
290
+ let srcStartIndx = 0;
291
+ let srcEndIndx = srcStartIndx + data.length;
292
+ const l = this.segments.length;
293
+ let segment = (l > 0 && this.segments[l - 1]) || undefined;
294
+ let bytesCopied = 0;
295
+ let bytesProcessed = 0;
296
+ if (!this.complete()) {
297
+ // check if out of space
298
+ if (this.buff.length - this.offset < data.length) {
299
+ const bytes = this.expand(MAPI_BLOCK_SIZE);
300
+ console.log(`expanding by ${bytes} bytes!`);
301
+ }
302
+ if (segment === undefined || (segment && segment.isFull())) {
303
+ const hdr = data.readUInt16LE(0);
304
+ const last = (hdr & 1) === 1;
305
+ const bytes = hdr >> 1;
306
+ srcStartIndx = MAPI_HEADER_SIZE;
307
+ srcEndIndx = srcStartIndx + Math.min(bytes, data.length);
308
+ bytesCopied = data.copy(this.buff, this.offset, srcStartIndx, srcEndIndx);
309
+ segment = new Segment(bytes, last, this.offset, bytesCopied);
310
+ this.segments.push(segment);
311
+ this.offset += bytesCopied;
312
+ bytesProcessed = MAPI_HEADER_SIZE + bytesCopied;
313
+ }
314
+ else {
315
+ const byteCntToRead = segment.bytes - segment.bytesOffset;
316
+ srcEndIndx = srcStartIndx + byteCntToRead;
317
+ bytesCopied = data.copy(this.buff, this.offset, srcStartIndx, srcEndIndx);
318
+ this.offset += bytesCopied;
319
+ segment.bytesOffset += bytesCopied;
320
+ // console.log(`segment is full ${segment.bytesOffset === segment.bytes}`);
321
+ bytesProcessed = bytesCopied;
322
+ }
323
+ if (this.isQueryResponse()) {
324
+ const tuples = [];
325
+ const firstPackage = this.parseOffset === 0;
326
+ this.parseOffset += this.parse(this.toString(this.parseOffset), tuples);
327
+ if (tuples.length > 0) {
328
+ if (this.queryStream) {
329
+ // emit header once
330
+ if (firstPackage && this.result && this.result.columns) {
331
+ this.queryStream.emit("header", this.result.columns);
332
+ }
333
+ // emit tuples
334
+ this.queryStream.emit("data", tuples);
335
+ }
336
+ else {
337
+ this.result.data = this.result.data || [];
338
+ for (let t of tuples) {
339
+ this.result.data.push(t);
340
+ }
341
+ }
342
+ }
343
+ }
344
+ }
345
+ return bytesProcessed;
346
+ }
347
+ complete() {
348
+ const l = this.segments.length;
349
+ if (l > 0) {
350
+ const segment = this.segments[l - 1];
351
+ return segment.last && segment.isFull();
352
+ }
353
+ return false;
354
+ }
355
+ seekOffset() {
356
+ const len = this.segments.length;
357
+ if (len) {
358
+ const last = this.segments[len - 1];
359
+ if (last.isFull())
360
+ return last.offset + last.bytes;
361
+ return last.offset;
362
+ }
363
+ return 0;
364
+ }
365
+ expand(byteCount) {
366
+ if (this.buff.length + byteCount > MAX_BUFF_SIZE &&
367
+ this.fileHandler instanceof file_transfer_1.FileDownloader) {
368
+ const offset = this.seekOffset();
369
+ if (offset) {
370
+ this.fileHandler.writeChunk(this.buff.subarray(0, offset));
371
+ this.buff = this.buff.subarray(offset);
372
+ this.offset -= offset;
373
+ }
374
+ }
375
+ const buff = buffer_1.Buffer.allocUnsafe(this.buff.length + byteCount).fill(0);
376
+ const bytesCopied = this.buff.copy(buff);
377
+ this.buff = buff;
378
+ // should be byteCount
379
+ return this.buff.length - bytesCopied;
380
+ }
381
+ firstCharacter() {
382
+ return this.buff.toString("utf8", 0, 1);
383
+ }
384
+ errorMessage() {
385
+ if (this.firstCharacter() === MSG_ERROR) {
386
+ return this.buff.toString("utf8", 1);
387
+ }
388
+ return "";
389
+ }
390
+ isFileTransfer() {
391
+ return this.toString().startsWith(MSG_FILETRANS);
392
+ }
393
+ isPrompt() {
394
+ // perhaps use toString
395
+ return this.complete() && this.firstCharacter() === "\x00";
396
+ }
397
+ isRedirect() {
398
+ return this.firstCharacter() === MSG_REDIRECT;
399
+ }
400
+ isQueryResponse() {
401
+ if (this.result && this.result.type) {
402
+ return this.result.type.startsWith(MSG_Q);
403
+ }
404
+ return this.firstCharacter() === MSG_Q;
405
+ }
406
+ isMsgMore() {
407
+ // server wants more ?
408
+ return this.toString().startsWith(MSG_MORE);
409
+ }
410
+ toString(start) {
411
+ const res = this.buff.toString("utf8", 0, this.offset);
412
+ if (start)
413
+ return res.substring(start);
414
+ return res;
415
+ }
416
+ settle(res) {
417
+ if (this.settled === false && this.complete()) {
418
+ const errMsg = this.errorMessage();
419
+ const err = errMsg ? new Error(errMsg) : null;
420
+ if (this.queryStream) {
421
+ if (err)
422
+ this.queryStream.emit("error", err);
423
+ this.queryStream.end();
424
+ }
425
+ else {
426
+ if (this.callbacks) {
427
+ if (err) {
428
+ this.callbacks.reject(err);
429
+ }
430
+ else {
431
+ this.callbacks.resolve(res || this.result);
432
+ }
433
+ }
434
+ else if (this.fileHandler && this.isQueryResponse()) {
435
+ this.fileHandler.resolve(this.result);
436
+ }
437
+ else if (this.fileHandler && (err || this.fileHandler.err)) {
438
+ this.fileHandler.reject(err || this.fileHandler.err);
439
+ }
440
+ }
441
+ this.settled = true;
442
+ }
443
+ }
444
+ parse(data, res) {
445
+ let offset = 0;
446
+ const lines = data.split("\n").length;
447
+ if (this.isQueryResponse()) {
448
+ let eol = data.indexOf("\n");
449
+ this.result = this.result || {};
450
+ if (this.result.type === undefined &&
451
+ data.startsWith(MSG_Q) &&
452
+ lines > 0) {
453
+ // process 1st line
454
+ const line = data.substring(0, eol);
455
+ this.result.type = line.substring(0, 2);
456
+ const rest = line.substring(3).trim().split(" ");
457
+ if (this.result.type === MSG_QTABLE) {
458
+ const [id, rowCnt, columnCnt, rows, queryId, queryTime, malOptimizerTime, sqlOptimizerTime,] = rest;
459
+ this.result.id = parseInt(id);
460
+ this.result.rowCnt = parseInt(rowCnt);
461
+ this.result.columnCnt = parseInt(columnCnt);
462
+ this.result.queryId = parseInt(queryId);
463
+ this.result.queryTime = parseInt(queryTime);
464
+ this.result.malOptimizerTime = parseInt(malOptimizerTime);
465
+ this.result.sqlOptimizerTime = parseInt(sqlOptimizerTime);
466
+ }
467
+ else if (this.result.type === MSG_QUPDATE) {
468
+ const [affectedRowCnt, autoIncrementId, queryId, queryTime, malOptimizerTime, sqlOptimizerTime,] = rest;
469
+ this.result.affectedRows = parseInt(affectedRowCnt);
470
+ this.result.queryId = parseInt(queryId);
471
+ this.result.queryTime = parseInt(queryTime);
472
+ this.result.malOptimizerTime = parseInt(malOptimizerTime);
473
+ this.result.sqlOptimizerTime = parseInt(sqlOptimizerTime);
474
+ }
475
+ else if (this.result.type === MSG_QSCHEMA) {
476
+ const [queryTime, malOptimizerTime] = rest;
477
+ this.result.queryTime = parseInt(queryTime);
478
+ this.result.malOptimizerTime = parseInt(malOptimizerTime);
479
+ }
480
+ else if (this.result.type === MSG_QTRANS) {
481
+ // skip
482
+ }
483
+ else if (this.result.type === MSG_QPREPARE) {
484
+ const [id, rowCnt, columnCnt, rows] = rest;
485
+ this.result.id = parseInt(id);
486
+ this.result.rowCnt = parseInt(rowCnt);
487
+ this.result.columnCnt = parseInt(columnCnt);
488
+ }
489
+ // end 1st line
490
+ if (this.headers === undefined &&
491
+ data.charAt(eol + 1) === MSG_HEADER &&
492
+ lines > 5) {
493
+ let headers = {};
494
+ while (data.charAt(eol + 1) === MSG_HEADER) {
495
+ const hs = eol + 1;
496
+ eol = data.indexOf("\n", hs);
497
+ headers = Object.assign(Object.assign({}, headers), parseHeaderLine(data.substring(hs, eol)));
498
+ }
499
+ this.headers = headers;
500
+ const colums = [];
501
+ for (let i = 0; i < this.result.columnCnt; i++) {
502
+ const table = headers.tableNames && headers.tableNames[i];
503
+ const name = headers.columnNames && headers.columnNames[i];
504
+ const type = headers.columnTypes && headers.columnTypes[i];
505
+ colums.push({
506
+ table,
507
+ name,
508
+ type,
509
+ index: i,
510
+ });
511
+ }
512
+ this.result.columns = colums;
513
+ }
514
+ }
515
+ offset = eol + 1;
516
+ let ts = undefined; // tuple index
517
+ if (data.startsWith(MSG_TUPLE)) {
518
+ ts = 0;
519
+ }
520
+ else if (data.charAt(eol + 1) === MSG_TUPLE) {
521
+ ts = eol + 1;
522
+ eol = data.indexOf("\n", ts);
523
+ }
524
+ if (ts !== undefined && eol > 0) {
525
+ // we have a data row
526
+ do {
527
+ offset = eol + 1;
528
+ const tuple = parseTupleLine(data.substring(ts, eol), this.headers.columnTypes);
529
+ res.push(tuple);
530
+ if (data.charAt(eol + 1) === MSG_TUPLE) {
531
+ ts = eol + 1;
532
+ eol = data.indexOf("\n", ts);
533
+ }
534
+ else {
535
+ ts = undefined;
536
+ }
537
+ } while (ts && eol > -1);
538
+ }
539
+ }
540
+ return offset;
541
+ }
542
+ }
543
+ class Segment {
544
+ constructor(bytes, last, offset, bytesOffset) {
545
+ this.bytes = bytes;
546
+ this.last = last;
547
+ this.offset = offset;
548
+ this.bytesOffset = bytesOffset;
549
+ }
550
+ isFull() {
551
+ return this.bytes === this.bytesOffset;
552
+ }
553
+ }
554
+ class MapiConnection extends events_1.EventEmitter {
555
+ constructor(config) {
556
+ super();
557
+ this.createSocket = (timeout) => {
558
+ const socket = new node_net_1.Socket();
559
+ if (timeout)
560
+ socket.setTimeout(timeout);
561
+ socket.addListener("data", this.recv.bind(this));
562
+ socket.addListener("error", this.handleSocketError.bind(this));
563
+ socket.addListener("timeout", this.handleTimeout.bind(this));
564
+ socket.addListener("close", () => {
565
+ console.log("socket close event");
566
+ this.emit("end");
567
+ });
568
+ return socket;
569
+ };
570
+ this.state = MAPI_STATE.INIT;
571
+ this.socket = this.createSocket(config.timeout);
572
+ // this.socket = new Socket();
573
+ // if (config.timeout) this.socket.setTimeout(config.timeout);
574
+ // this.socket.addListener("data", this.recv.bind(this));
575
+ // this.socket.addListener("error", this.handleSocketError.bind(this));
576
+ // this.socket.addListener("timeout", this.handleTimeout.bind(this));
577
+ // this.socket.addListener("close", () => {
578
+ // console.log("socket close event");
579
+ // this.emit("end");
580
+ // });
581
+ this.redirects = 0;
582
+ this.queue = [];
583
+ this.database = config.database;
584
+ this.language = config.language || MAPI_LANGUAGE.SQL;
585
+ this.unixSocket = config.unixSocket;
586
+ this.host = config.host;
587
+ this.port = config.port;
588
+ this.username = config.username;
589
+ this.password = config.password;
590
+ this.timeout = config.timeout;
591
+ }
592
+ connect(handShakeOptions = []) {
593
+ this.handShakeOptions = handShakeOptions;
594
+ // TODO unix socket
595
+ const opt = {
596
+ port: this.port,
597
+ host: this.host,
598
+ noDelay: true,
599
+ };
600
+ const socket = this.socket && !this.socket.destroyed
601
+ ? this.socket
602
+ : this.createSocket(this.timeout);
603
+ socket.connect(opt, () => {
604
+ this.state = MAPI_STATE.CONNECTED;
605
+ this.socket.setKeepAlive(true);
606
+ });
607
+ this.socket = socket;
608
+ return (0, events_1.once)(this, "ready");
609
+ }
610
+ ready() {
611
+ return this.state === MAPI_STATE.READY;
612
+ }
613
+ disconnect() {
614
+ return new Promise((resolve, reject) => {
615
+ this.socket.end(() => {
616
+ this.redirects = 0;
617
+ this.state = MAPI_STATE.INIT;
618
+ this.socket.destroy();
619
+ resolve(this.state === MAPI_STATE.INIT);
620
+ });
621
+ });
622
+ }
623
+ login(challenge) {
624
+ const challengeParts = challenge.split(":");
625
+ const [salt, identity, protocol, hashes, endian, algo, opt_level] = challengeParts;
626
+ let password;
627
+ try {
628
+ password = (0, node_crypto_1.createHash)(algo).update(this.password).digest("hex");
629
+ }
630
+ catch (err) {
631
+ console.error(err);
632
+ this.emit("error", new TypeError(`Algorithm ${algo} not supported`));
633
+ return;
634
+ }
635
+ let pwhash = null;
636
+ // try hash algorithms in the order provided by the server
637
+ for (const algo of hashes.split(",")) {
638
+ try {
639
+ const hash = (0, node_crypto_1.createHash)(algo);
640
+ pwhash = `{${algo}}` + hash.update(password + salt).digest("hex");
641
+ break;
642
+ }
643
+ catch (_a) { }
644
+ }
645
+ if (pwhash) {
646
+ let counterResponse = `LIT:${this.username}:${pwhash}:${this.language}:${this.database}:`;
647
+ if (opt_level && opt_level.startsWith("sql=")) {
648
+ let level = 0;
649
+ counterResponse += "FILETRANS:";
650
+ try {
651
+ level = Number(opt_level.substring(4));
652
+ }
653
+ catch (err) {
654
+ this.emit("error", new TypeError("Invalid handshake options level in server challenge"));
655
+ return;
656
+ }
657
+ // process handshake options
658
+ const options = [];
659
+ for (const opt of this.handShakeOptions) {
660
+ if (opt.level < level) {
661
+ options.push(`${opt.name}=${Number(opt.value)}`);
662
+ opt.sent = true;
663
+ }
664
+ }
665
+ if (options)
666
+ counterResponse += options.join(",") + ":";
667
+ }
668
+ this.send(buffer_1.Buffer.from(counterResponse))
669
+ .then(() => this.queue.push(new Response()))
670
+ .catch((err) => this.emit("error", err));
671
+ }
672
+ else {
673
+ this.emit("error", new TypeError(`None of the hashes ${hashes} are supported`));
674
+ }
675
+ }
676
+ /**
677
+ * Raise exception on server by sending bad packet
678
+ */
679
+ requestAbort() {
680
+ return new Promise((resolve, reject) => {
681
+ const header = buffer_1.Buffer.allocUnsafe(2).fill(0);
682
+ // larger than allowed and not final message
683
+ header.writeUint16LE(((2 * MAPI_BLOCK_SIZE) << 1) | 0, 0);
684
+ // invalid utf8 and too small
685
+ const badBody = buffer_1.Buffer.concat([
686
+ buffer_1.Buffer.from("ERROR"),
687
+ buffer_1.Buffer.from([0x80]),
688
+ ]);
689
+ const outBuff = buffer_1.Buffer.concat([header, badBody]);
690
+ this.socket.write(outBuff, (err) => __awaiter(this, void 0, void 0, function* () {
691
+ if (err)
692
+ reject(err);
693
+ resolve();
694
+ }));
695
+ });
696
+ }
697
+ send(buff) {
698
+ return new Promise((resolve, reject) => {
699
+ let last = 0;
700
+ let offset = 0;
701
+ while (last === 0) {
702
+ const seg = buff.subarray(offset, offset + MAPI_BLOCK_SIZE);
703
+ last = seg.length < MAPI_BLOCK_SIZE ? 1 : 0;
704
+ const header = buffer_1.Buffer.allocUnsafe(2).fill(0);
705
+ header.writeUint16LE((seg.length << 1) | last, 0);
706
+ const outBuff = buffer_1.Buffer.concat([header, seg]);
707
+ this.socket.write(outBuff, (err) => {
708
+ if (err)
709
+ reject(err);
710
+ if (last)
711
+ resolve();
712
+ });
713
+ offset += seg.length;
714
+ }
715
+ });
716
+ }
717
+ handleTimeout() {
718
+ this.emit("error", new Error("Timeout"));
719
+ }
720
+ handleSocketError(err) {
721
+ console.error(err);
722
+ }
723
+ request(sql, stream = false) {
724
+ return __awaiter(this, void 0, void 0, function* () {
725
+ if (this.ready() === false)
726
+ throw new Error("Not Connected");
727
+ yield this.send(buffer_1.Buffer.from(sql));
728
+ return new Promise((resolve, reject) => {
729
+ const resp = new Response({
730
+ stream,
731
+ callbacks: { resolve, reject },
732
+ });
733
+ this.queue.push(resp);
734
+ });
735
+ });
736
+ }
737
+ requestFileTransfer(buff, fileHandler) {
738
+ return __awaiter(this, void 0, void 0, function* () {
739
+ yield this.send(buff);
740
+ const resp = new Response({ fileHandler });
741
+ this.queue.push(resp);
742
+ });
743
+ }
744
+ requestFileTransferError(err, fileHandler) {
745
+ return __awaiter(this, void 0, void 0, function* () {
746
+ yield this.send(buffer_1.Buffer.from(err));
747
+ const resp = new Response({ fileHandler });
748
+ this.queue.push(resp);
749
+ });
750
+ }
751
+ recv(data) {
752
+ let bytesLeftOver;
753
+ let resp;
754
+ // process queue left to right, find 1st uncomplete response
755
+ // remove responses that are completed
756
+ while (this.queue.length) {
757
+ const next = this.queue[0];
758
+ if (next.complete() || next.settled) {
759
+ this.queue.shift();
760
+ }
761
+ else {
762
+ resp = next;
763
+ break;
764
+ }
765
+ }
766
+ if (resp === undefined && this.queue.length === 0) {
767
+ // challenge message
768
+ // or direct call to send has being made
769
+ // e.g. request api appends Response to the queue
770
+ resp = new Response();
771
+ this.queue.push(resp);
772
+ }
773
+ const offset = resp.append(data);
774
+ if (resp.complete())
775
+ this.handleResponse(resp);
776
+ bytesLeftOver = data.length - offset;
777
+ if (bytesLeftOver) {
778
+ const msg = `some ${bytesLeftOver} bytes left over!`;
779
+ console.warn(msg);
780
+ this.recv(data.subarray(offset));
781
+ }
782
+ }
783
+ handleResponse(resp) {
784
+ const err = resp.errorMessage();
785
+ if (this.state == MAPI_STATE.CONNECTED) {
786
+ if (err) {
787
+ this.emit("error", new Error(err));
788
+ return;
789
+ }
790
+ if (resp.isRedirect()) {
791
+ this.redirects += 1;
792
+ if (this.redirects > MAX_REDIRECTS)
793
+ this.emit("error", new Error(`Exceeded max number of redirects ${MAX_REDIRECTS}`));
794
+ return;
795
+ }
796
+ if (resp.isPrompt()) {
797
+ console.log("login OK");
798
+ this.state = MAPI_STATE.READY;
799
+ this.emit("ready", this.state);
800
+ return;
801
+ }
802
+ return this.login(resp.toString());
803
+ }
804
+ if (resp.isFileTransfer()) {
805
+ console.log("file transfer");
806
+ let fhandler;
807
+ const msg = resp.toString(MSG_FILETRANS.length).trim();
808
+ let mode, offset, file;
809
+ if (msg.startsWith("r ")) {
810
+ [mode, offset, file] = msg.split(" ");
811
+ fhandler =
812
+ resp.fileHandler || new file_transfer_1.FileUploader(this, file, parseInt(offset));
813
+ return resp.settle(fhandler.upload());
814
+ }
815
+ else if (msg.startsWith("rb")) {
816
+ [mode, file] = msg.split(" ");
817
+ fhandler = resp.fileHandler || new file_transfer_1.FileUploader(this, file, 0);
818
+ return resp.settle(fhandler.upload());
819
+ }
820
+ else if (msg.startsWith("w")) {
821
+ [mode, file] = msg.split(" ");
822
+ fhandler = resp.fileHandler || new file_transfer_1.FileDownloader(this, file);
823
+ return resp.settle(fhandler.download());
824
+ }
825
+ else {
826
+ // no msg end of transfer
827
+ const fileHandler = resp.fileHandler;
828
+ // we do expect a final response from server
829
+ this.queue.push(new Response({ fileHandler }));
830
+ return resp.settle(fileHandler.close());
831
+ }
832
+ }
833
+ if (resp.isMsgMore()) {
834
+ // console.log("server wants more");
835
+ if (resp.fileHandler instanceof file_transfer_1.FileUploader)
836
+ return resp.settle(resp.fileHandler.upload());
837
+ }
838
+ if (resp.fileHandler instanceof file_transfer_1.FileDownloader &&
839
+ resp.fileHandler.ready()) {
840
+ // end of download
841
+ const fileHandler = resp.fileHandler;
842
+ fileHandler.writeChunk(resp.buff);
843
+ // we do expect a final response from server
844
+ this.queue.push(new Response({ fileHandler }));
845
+ return resp.settle(fileHandler.close());
846
+ }
847
+ resp.settle();
848
+ }
849
+ }
850
+ exports.MapiConnection = MapiConnection;
851
+ //# sourceMappingURL=mapi.js.map