@coderich/sandman 0.0.5 → 0.0.6

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coderich/sandman",
3
- "version": "0.0.5",
3
+ "version": "0.0.6",
4
4
  "main": "index.js",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -15,7 +15,7 @@
15
15
  "dev": "coderich-dev"
16
16
  },
17
17
  "dependencies": {
18
- "@coderich/config": "2.2.4",
18
+ "@coderich/config": "2.2.5",
19
19
  "@coderich/util": "2.1.3",
20
20
  "chokidar": "4.0.3",
21
21
  "lodash.clonedeep": "4.5.0",
@@ -1,13 +1,107 @@
1
- // const FS = require('fs');
2
- // const Path = require('path');
3
- const cloneDeep = require('lodash.clonedeep');
1
+ const Path = require('path');
2
+ const Chokidar = require('chokidar');
4
3
  const Config = require('@coderich/config');
4
+ const Util = require('@coderich/util');
5
+
6
+ const dataSymbol = Symbol('dataSymbol');
5
7
 
6
8
  module.exports = class ConfigClient extends Config {
7
- get(...args) {
8
- return cloneDeep(super.get(...args));
9
+ #configDir; #mergeData = {};
10
+
11
+ constructor(configDir) {
12
+ super();
13
+ this.#configDir = configDir;
14
+ this.mergeDir();
15
+ }
16
+
17
+ get(key, ...args) {
18
+ const data = super.get(key, ...args);
19
+ const flatData = key === undefined ? Util.flatten(data) : Util.flatten({ [key]: data });
20
+ const apiKeys = Array.from(new Set(Object.keys(flatData).map(k => k.substring(0, Math.max(k.indexOf('.request'), 0))).filter(Boolean)));
21
+
22
+ apiKeys.forEach((apiKey) => {
23
+ Reflect.ownKeys(this.#mergeData).forEach((mergeKey) => {
24
+ if (mergeKey === dataSymbol) flatData[apiKey] = { ...this.#mergeData[dataSymbol], ...flatData[apiKey] };
25
+ else if (apiKey.startsWith(mergeKey)) flatData[apiKey] = { ...this.#mergeData[mergeKey][dataSymbol], ...flatData[apiKey] };
26
+ });
27
+ });
28
+
29
+ const unflatData = Util.unflatten(flatData);
30
+ const rawData = key === undefined ? unflatData : Util.get(unflatData, key);
31
+ super.set(dataSymbol, rawData);
32
+ return super.get(dataSymbol);
33
+ }
34
+
35
+ mergeDir(dir = this.#configDir) {
36
+ return this.merge(Config.parseDir(dir, (...args) => this.#ignore(...args)));
37
+ }
38
+
39
+ watch(dir = this.#configDir) {
40
+ const watcher = Chokidar.watch(dir, {
41
+ awaitWriteFinish: true,
42
+ ignoreInitial: true,
43
+ ignored: filepath => this.#ignore(this.#normalizeWatcherPath(filepath)),
44
+ });
45
+
46
+ watcher.on('all', (event, path) => {
47
+ const { key } = this.#normalizeWatcherPath(path);
48
+
49
+ if (['add', 'change'].includes(event)) {
50
+ const api = Config.parseFile(path);
51
+ if (key) this.set(key, api);
52
+ else this.merge(api); // index.yaml
53
+ // if (api.request) this.emit('save', { key, api });
54
+ } else if (['unlink', 'unlinkDir'].includes(event)) {
55
+ this.del(key);
56
+ }
57
+ });
9
58
  }
10
59
 
60
+ #ignore({ name, filepath, paths }) {
61
+ if (name.startsWith('.')) return true;
62
+
63
+ if (name.startsWith('+')) {
64
+ const path = paths.slice(0, -1).join('.');
65
+ const request = Util.flatten(Config.parseFile(filepath));
66
+ if (path) this.#mergeData[path] = { [dataSymbol]: request };
67
+ else this.#mergeData[dataSymbol] = request;
68
+ return true;
69
+ }
70
+
71
+ return false;
72
+ }
73
+
74
+ #normalizeWatcherPath = (filepath) => {
75
+ const parsed = Path.parse(filepath);
76
+ const folder = filepath.substring(this.#configDir.length + 1, filepath.length - parsed.ext.length);
77
+ const paths = folder.split('/').filter(el => el && el !== 'index');
78
+ const key = paths.join('.');
79
+ return { ...parsed, filepath, paths, key };
80
+ };
81
+
82
+ // exports.decorateRequest = (mergeData, key, request) => {
83
+ // const toMerge = key.split('.').reduce((prev, k, i, arr) => {
84
+ // const $key = arr.slice(0, i).join('.');
85
+ // return Merge({}, prev, mergeData[$key]?.request);
86
+ // }, Merge({}, mergeData.request));
87
+
88
+ // return Merge({}, toMerge, request);
89
+ // };
90
+
91
+ // #get(key, ...rest) {
92
+ // const { config } = this.#configClient.toObject();
93
+ // const value = get(config, key);
94
+
95
+ // if (value?.request) {
96
+ // const $request = FetchService.decorateRequest(this.#mergeData, key, value.request);
97
+ // const request = this.#configClient.resolve({ vars: value.request.vars }).set(resolveSymbol, $request).get(resolveSymbol);
98
+ // this.#configClient.del(resolveSymbol);
99
+ // return Merge({}, value, { request });
100
+ // }
101
+
102
+ // return this.#configClient.get(key, ...rest);
103
+ // }
104
+
11
105
  // mergeConfigDir(dir) {
12
106
  // const ignored = (parsed) => {
13
107
  // if (parsed.name.startsWith('.')) return true;
@@ -1,7 +1,3 @@
1
- const Merge = require('lodash.merge');
2
-
3
- function shq(s) { return `'${String(s).replace(/'/g, `'"'"'`)}'`; }
4
-
5
1
  exports.fetch = (request) => {
6
2
  return fetch(request).then(async (response) => {
7
3
  const ct = response.headers.get('content-type') || '';
@@ -28,10 +24,8 @@ exports.normalizeRequest = (req) => {
28
24
  }
29
25
  case 'multipart/form-data': {
30
26
  delete req.headers['content-type'];
31
- req.body = Object.entries(req.data).reduce((form, [key, value]) => {
32
- form.append(key, value);
33
- return form;
34
- }, new FormData());
27
+ req.body = new FormData();
28
+ Object.entries(req.data).forEach(([key, value]) => req.body.append(key, value));
35
29
  break;
36
30
  }
37
31
  default: {
@@ -46,14 +40,7 @@ exports.normalizeRequest = (req) => {
46
40
  return new Request(url, params);
47
41
  };
48
42
 
49
- exports.decorateRequest = (mergeData, key, request) => {
50
- const toMerge = key.split('.').reduce((prev, k, i, arr) => {
51
- const $key = arr.slice(0, i).join('.');
52
- return Merge({}, prev, mergeData[$key]?.request);
53
- }, Merge({}, mergeData.request));
54
-
55
- return Merge({}, toMerge, request);
56
- };
43
+ exports.shq = s => `'${String(s).replace(/'/g, "'\\''")}'`;
57
44
 
58
45
  exports.toCURL = (request, { pretty = true, redactAuth = false } = {}) => {
59
46
  if (!request) return '<no request>';
@@ -84,18 +71,17 @@ exports.toCURL = (request, { pretty = true, redactAuth = false } = {}) => {
84
71
  // body (skip for GET)
85
72
  if (data != null && !/^GET$/i.test(method)) {
86
73
  if (typeof data === 'string') {
87
- parts.push('--data-raw', shq(data));
74
+ parts.push('--data-raw', exports.shq(data));
88
75
  } else if (data instanceof URLSearchParams) {
89
- parts.push('-H', shq('Content-Type: application/x-www-form-urlencoded'));
90
- parts.push('--data', shq(data.toString()));
76
+ parts.push('-H', exports.shq('Content-Type: application/x-www-form-urlencoded'));
77
+ parts.push('--data', exports.shq(data.toString()));
91
78
  } else if (typeof data === 'object') {
92
- // JSON by default
93
79
  const hasCT = Object.keys(hdrs).some(h => /^content-type$/i.test(h));
94
- if (!hasCT) parts.push('-H', shq('Content-Type: application/json'));
95
- parts.push('--data-raw', shq(JSON.stringify(data)));
80
+ if (!hasCT) parts.push('-H', exports.shq('Content-Type: application/json'));
81
+ parts.push('--data-raw', exports.shq(JSON.stringify(data)));
96
82
  }
97
83
  }
98
84
 
99
- parts.push(shq(full.toString()));
85
+ parts.push(exports.shq(full.toString()));
100
86
  return pretty ? parts.join(' \\\n ') : parts.join(' ');
101
87
  };
@@ -0,0 +1,85 @@
1
+ const Readline = require('readline');
2
+ const { get, flatten } = require('@coderich/util');
3
+
4
+ exports.createInterface = (cli, configClient) => {
5
+ const captureInfo = {
6
+ line: '',
7
+ lastToken: '',
8
+ candidates: [],
9
+ tabCounter: 0,
10
+ candidateIndex: -1,
11
+ captureCandidates: false,
12
+ };
13
+
14
+ const readline = Readline.createInterface({
15
+ input: process.stdin,
16
+ output: process.stdout,
17
+ terminal: true,
18
+ completer: (line) => {
19
+ // Show available CLI commands
20
+ if (!line) return [Object.keys(cli), line];
21
+
22
+ const tokens = line.split(' ');
23
+ const lastToken = tokens.at(-1);
24
+ const paths = lastToken.split('.');
25
+ const path = paths.at(-1);
26
+
27
+ // Specific request.data selector
28
+ if (lastToken.startsWith('.')) {
29
+ const api = configClient.get(tokens.at(-2));
30
+ if (!api?.request) return [[], path];
31
+ const dataPath = ['request'].concat(paths.slice(1, -1)).join('.');
32
+ const data = get(api, dataPath, {});
33
+ return [Object.keys(data).filter(k => k.toLowerCase().startsWith(path.toLowerCase())), path];
34
+ }
35
+
36
+ //
37
+ const flatKeys = Object.keys(flatten(configClient.get()));
38
+
39
+ // These keys follow the typing of the user
40
+ const startsWithCandidates = Array.from(new Set(flatKeys.map((flatKey) => {
41
+ return flatKey.split('.').slice(0, paths.length).join('.');
42
+ }))).filter((c) => {
43
+ return c.toLowerCase().startsWith(lastToken.toLowerCase());
44
+ }); // .map(p => p.split('.').at(-1)); // Here!
45
+
46
+ // These are shortcut keys to requests
47
+ const requestKeyCandidates = Array.from(new Set(flatKeys.map((flatKey) => {
48
+ const keys = flatKey.split('.');
49
+ const index = keys.indexOf('request');
50
+ return index && flatKey.split('.').slice(0, index).join('.');
51
+ // const typedPath = keys.slice(0, paths.length - 1).join('.');
52
+ // const autocompletePath = keys.slice(paths.length - 1, index).join('.');
53
+ // return index > 0 && lastToken.toLowerCase().startsWith(typedPath.toLowerCase()) && autocompletePath;
54
+ }).filter(Boolean))).filter((c) => {
55
+ return c.toLowerCase().includes(lastToken.toLowerCase());
56
+ // return c.toLowerCase().includes(path.toLowerCase());
57
+ });
58
+
59
+ const candidates = Array.from(new Set(startsWithCandidates.concat(requestKeyCandidates)));
60
+ if (captureInfo.captureCandidates) { captureInfo.candidates = candidates; captureInfo.line = line; captureInfo.lastToken = lastToken; captureInfo.candidateIndex = -1; }
61
+ if (candidates.length === 1 && candidates[0] === lastToken) return [[], lastToken];
62
+ return [candidates, lastToken];
63
+ },
64
+ });
65
+
66
+ process.stdin.on('keypress', (ch, key) => {
67
+ if (key && key.name === 'tab') captureInfo.tabCounter++; else captureInfo.tabCounter = 0;
68
+ captureInfo.captureCandidates = captureInfo.tabCounter === 2;
69
+
70
+ if (key && key.name === 'escape') {
71
+ readline.line = '';
72
+ Readline.cursorTo(process.stdout, 0);
73
+ Readline.clearLine(process.stdout, 0);
74
+ readline.prompt();
75
+ } else if (captureInfo.tabCounter > 2 && captureInfo.candidates.length) {
76
+ const candidate = captureInfo.candidates[captureInfo.candidateIndex = ++captureInfo.candidateIndex % captureInfo.candidates.length];
77
+ const value = captureInfo.line.replace(captureInfo.lastToken, candidate);
78
+ readline.line = value;
79
+ readline.cursor = value.length;
80
+ readline.prompt(true);
81
+ }
82
+ });
83
+
84
+ return readline;
85
+ };
package/src/Sandman.js CHANGED
@@ -1,27 +1,17 @@
1
- const Path = require('path');
2
- const Merge = require('lodash.merge');
3
- const Readline = require('readline');
4
- const Chokidar = require('chokidar');
5
1
  const EventEmitter = require('events');
6
- const { get, flatten } = require('@coderich/util');
2
+ const ReadlineService = require('./ReadlineService');
7
3
  const FetchService = require('./FetchService');
8
4
  const ConfigClient = require('./ConfigClient');
9
5
 
10
- const resolveSymbol = Symbol('resolve');
11
-
12
6
  module.exports = class Sandman extends EventEmitter {
13
- #configClient; #configDir; #options; #watcher; #readline; #mergeData = {}; #cli; #cliCounter = 0;
14
- #captureCandidates = false; #candidates = []; #tabCounter = 0; #candidateIndex; #line; #lastToken;
7
+ #configClient; #options; #readline; #cli; #cliCounter = 0;
15
8
 
16
9
  constructor(configDir, options) {
17
10
  super();
18
- this.#configDir = configDir;
19
11
  this.#options = options;
20
- this.#configClient = new ConfigClient().merge(ConfigClient.parseDir(configDir, arg => this.#ignore(arg)));
21
- this.#createInterface();
22
- this.#createWatcher();
12
+ this.#configClient = new ConfigClient(configDir);
23
13
  this.#createCLI();
24
- this.#prompt();
14
+ this.#readline = ReadlineService.createInterface(this.#cli, this.#configClient);
25
15
 
26
16
  this.#readline.on('line', async (line) => {
27
17
  if (!line) return this.#readline.prompt();
@@ -30,6 +20,8 @@ module.exports = class Sandman extends EventEmitter {
30
20
  const value = await Promise.resolve(this.#cli[info.cmd](...info.args)).catch(e => e);
31
21
  return this.emit(cmd, value);
32
22
  });
23
+
24
+ this.#prompt();
33
25
  }
34
26
 
35
27
  cli() {
@@ -45,7 +37,7 @@ module.exports = class Sandman extends EventEmitter {
45
37
  }
46
38
 
47
39
  #run(key) {
48
- const api = this.#get(key, {});
40
+ const api = this.#configClient.get(key, {});
49
41
  if (!api?.request) return this.emit('error', { key, error: `Request "${key}" Not Found` });
50
42
  this.emit('api', { api, key });
51
43
  const request = FetchService.normalizeRequest(api.request);
@@ -68,29 +60,15 @@ module.exports = class Sandman extends EventEmitter {
68
60
  return this;
69
61
  }
70
62
 
71
- #get(key, ...rest) {
72
- const { config } = this.#configClient.toObject();
73
- const value = get(config, key);
74
-
75
- if (value?.request) {
76
- const $request = FetchService.decorateRequest(this.#mergeData, key, value.request);
77
- const request = this.#configClient.set(resolveSymbol, $request).get(resolveSymbol);
78
- this.#configClient.del(resolveSymbol);
79
- return Merge({}, value, { request });
80
- }
81
-
82
- return this.#configClient.get(key, ...rest);
83
- }
84
-
85
63
  #createCLI() {
86
64
  const self = this;
87
65
 
88
66
  this.#cli = new Proxy({
89
67
  run: (...args) => this.#run(...args),
90
- get: (...args) => this.#get(...args),
68
+ get: (...args) => this.#configClient.get(...args),
91
69
  set: (key = '', value = null) => this.#configClient.set(key, value),
92
70
  del: (key = '') => this.#configClient.del(key),
93
- curl: key => FetchService.toCURL(this.#get(key, {}).request),
71
+ curl: key => FetchService.toCURL(this.#configClient.get(key, {}).request),
94
72
  quit: () => process.exit(),
95
73
  }, {
96
74
  get(obj, prop, receiver) {
@@ -112,121 +90,4 @@ module.exports = class Sandman extends EventEmitter {
112
90
  },
113
91
  });
114
92
  }
115
-
116
- #createInterface() {
117
- this.#readline = Readline.createInterface({
118
- input: process.stdin,
119
- output: process.stdout,
120
- terminal: true,
121
- completer: (line) => {
122
- // Show available CLI commands
123
- if (!line) return [Object.keys(this.#cli), line];
124
-
125
- const tokens = line.split(' ');
126
- const lastToken = tokens.at(-1);
127
- const paths = lastToken.split('.');
128
- const path = paths.at(-1);
129
-
130
- // Specific request.data selector
131
- if (lastToken.startsWith('.')) {
132
- const api = this.#get(tokens.at(-2));
133
- if (!api?.request) return [[], path];
134
- const dataPath = ['request'].concat(paths.slice(1, -1)).join('.');
135
- const data = get(api, dataPath, {});
136
- return [Object.keys(data).filter(k => k.toLowerCase().startsWith(path.toLowerCase())), path];
137
- }
138
-
139
- //
140
- const flatKeys = Object.keys(flatten(this.#configClient.get()));
141
-
142
- // These keys follow the typing of the user
143
- const startsWithCandidates = Array.from(new Set(flatKeys.map((flatKey) => {
144
- return flatKey.split('.').slice(0, paths.length).join('.');
145
- }))).filter((c) => {
146
- return c.toLowerCase().startsWith(lastToken.toLowerCase());
147
- }); // .map(p => p.split('.').at(-1)); // Here!
148
-
149
- // These are shortcut keys to requests
150
- const requestKeyCandidates = Array.from(new Set(flatKeys.map((flatKey) => {
151
- const keys = flatKey.split('.');
152
- const index = keys.indexOf('request');
153
- return index && flatKey.split('.').slice(0, index).join('.');
154
- // const typedPath = keys.slice(0, paths.length - 1).join('.');
155
- // const autocompletePath = keys.slice(paths.length - 1, index).join('.');
156
- // return index > 0 && lastToken.toLowerCase().startsWith(typedPath.toLowerCase()) && autocompletePath;
157
- }).filter(Boolean))).filter((c) => {
158
- return c.toLowerCase().includes(lastToken.toLowerCase());
159
- // return c.toLowerCase().includes(path.toLowerCase());
160
- });
161
-
162
- const candidates = Array.from(new Set(startsWithCandidates.concat(requestKeyCandidates)));
163
- if (this.#captureCandidates) { this.#candidates = candidates; this.#line = line; this.#lastToken = lastToken; this.#candidateIndex = -1; }
164
- if (candidates.length === 1 && candidates[0] === lastToken) return [[], lastToken];
165
- return [candidates, lastToken];
166
- },
167
- });
168
-
169
- process.stdin.on('keypress', (ch, key) => {
170
- if (key && key.name === 'tab') this.#tabCounter++; else this.#tabCounter = 0;
171
- this.#captureCandidates = this.#tabCounter === 2;
172
-
173
- if (key && key.name === 'escape') {
174
- this.#readline.line = '';
175
- Readline.cursorTo(process.stdout, 0);
176
- Readline.clearLine(process.stdout, 0);
177
- this.#readline.prompt();
178
- } else if (this.#tabCounter > 2 && this.#candidates.length) {
179
- const candidate = this.#candidates[this.#candidateIndex = ++this.#candidateIndex % this.#candidates.length];
180
- const value = this.#line.replace(this.#lastToken, candidate);
181
- this.#readline.line = value;
182
- this.#readline.cursor = value.length;
183
- this.#readline.prompt(true);
184
- }
185
- });
186
- }
187
-
188
- #createWatcher() {
189
- this.#watcher = Chokidar.watch(this.#configDir, {
190
- awaitWriteFinish: true,
191
- ignoreInitial: true,
192
- ignored: filepath => this.#ignore(this.#normalizeWatcherPath(filepath)),
193
- });
194
-
195
- this.#watcher.on('all', (event, path) => {
196
- const { key } = this.#normalizeWatcherPath(path);
197
-
198
- if (['add', 'change'].includes(event)) {
199
- const api = ConfigClient.parseFile(path);
200
- if (key) this.#configClient.set(key, api);
201
- else this.#configClient.merge(api); // index.yaml
202
- if (api.request) this.emit('save', { key, api });
203
- this.#prompt();
204
- } else if (['unlink', 'unlinkDir'].includes(event)) {
205
- this.#configClient.del(key);
206
- this.#prompt();
207
- }
208
- });
209
- }
210
-
211
- #ignore({ name, filepath, paths }) {
212
- if (name.startsWith('.')) return true;
213
-
214
- if (name.startsWith('+')) {
215
- const request = ConfigClient.parseFile(filepath);
216
- const key = paths.slice(0, -1).join('.');
217
- if (key) this.#mergeData[key] = { request };
218
- else this.#mergeData.request = request;
219
- return true;
220
- }
221
-
222
- return false;
223
- }
224
-
225
- #normalizeWatcherPath = (filepath) => {
226
- const parsed = Path.parse(filepath);
227
- const folder = filepath.substring(this.#configDir.length + 1, filepath.length - parsed.ext.length);
228
- const paths = folder.split('/').filter(el => el && el !== 'index');
229
- const key = paths.join('.');
230
- return { ...parsed, filepath, paths, key };
231
- };
232
93
  };