@miqro/core 1.6.1 → 1.7.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 (175) hide show
  1. package/README.md +101 -41
  2. package/dist/api-router.d.ts +1 -1
  3. package/dist/api-router.js +0 -1
  4. package/dist/app-utils.js +0 -1
  5. package/dist/app.js +2 -3
  6. package/dist/common/api-router-utils.d.ts +1 -1
  7. package/dist/common/api-router-utils.js +6 -22
  8. package/dist/common/api-router.d.ts +3 -16
  9. package/dist/common/api-router.js +0 -1
  10. package/dist/common/config/config.js +0 -1
  11. package/dist/common/config/featuretoggle.js +0 -1
  12. package/dist/common/config/index.js +0 -1
  13. package/dist/common/config/loader.js +0 -1
  14. package/dist/common/context.d.ts +1 -1
  15. package/dist/common/context.js +0 -1
  16. package/dist/common/error/badrequesterror.js +0 -1
  17. package/dist/common/error/configfilenotfound.js +0 -1
  18. package/dist/common/error/forbiddenerror.js +0 -1
  19. package/dist/common/error/index.js +0 -1
  20. package/dist/common/error/notfound.js +0 -1
  21. package/dist/common/error/notimplemented.js +0 -1
  22. package/dist/common/error/unauthorizederror.js +0 -1
  23. package/dist/common/helpers.js +0 -1
  24. package/dist/common/index.js +0 -1
  25. package/dist/common/logger/constants.d.ts +13 -0
  26. package/dist/common/logger/constants.js +25 -0
  27. package/dist/common/logger/factory.d.ts +2 -4
  28. package/dist/common/logger/factory.js +7 -4
  29. package/dist/common/logger/index.d.ts +5 -5
  30. package/dist/common/logger/index.js +5 -5
  31. package/dist/common/logger/{transport.d.ts → interfaces.d.ts} +6 -3
  32. package/dist/common/logger/interfaces.js +2 -0
  33. package/dist/common/logger/logger.d.ts +15 -7
  34. package/dist/common/logger/logger.js +35 -28
  35. package/dist/common/logger/transport/console.d.ts +5 -0
  36. package/dist/common/logger/transport/console.js +38 -0
  37. package/dist/common/logger/transport/file.d.ts +2 -0
  38. package/dist/common/logger/transport/file.js +28 -0
  39. package/dist/common/router-handler.js +0 -1
  40. package/dist/common/router-helpers.d.ts +1 -1
  41. package/dist/common/router-helpers.js +3 -4
  42. package/dist/common/router-utils.js +0 -1
  43. package/dist/common/session/common.js +0 -1
  44. package/dist/common/session/index.js +0 -1
  45. package/dist/common/session/service.js +0 -1
  46. package/dist/common/tokenize-match.js +0 -1
  47. package/dist/index.js +0 -1
  48. package/dist/middleware/buffer.js +0 -1
  49. package/dist/middleware/cookie.js +0 -1
  50. package/dist/middleware/cors.js +0 -1
  51. package/dist/middleware/form.js +0 -1
  52. package/dist/middleware/group.js +0 -1
  53. package/dist/middleware/index.js +0 -1
  54. package/dist/middleware/json.js +0 -1
  55. package/dist/middleware/logger.js +0 -1
  56. package/dist/middleware/parse.js +0 -1
  57. package/dist/middleware/result.js +0 -1
  58. package/dist/middleware/session.js +0 -1
  59. package/dist/middleware/tag.js +0 -1
  60. package/dist/middleware/text.js +0 -1
  61. package/dist/proxy.js +0 -1
  62. package/dist/router.d.ts +1 -1
  63. package/dist/router.js +2 -3
  64. package/dist/static.js +0 -1
  65. package/package.json +8 -10
  66. package/dist/api-router.js.map +0 -1
  67. package/dist/app-utils.js.map +0 -1
  68. package/dist/app.js.map +0 -1
  69. package/dist/common/api-router-utils.js.map +0 -1
  70. package/dist/common/api-router.js.map +0 -1
  71. package/dist/common/config/config.js.map +0 -1
  72. package/dist/common/config/featuretoggle.js.map +0 -1
  73. package/dist/common/config/index.js.map +0 -1
  74. package/dist/common/config/loader.js.map +0 -1
  75. package/dist/common/context.js.map +0 -1
  76. package/dist/common/error/badrequesterror.js.map +0 -1
  77. package/dist/common/error/configfilenotfound.js.map +0 -1
  78. package/dist/common/error/forbiddenerror.js.map +0 -1
  79. package/dist/common/error/index.js.map +0 -1
  80. package/dist/common/error/notfound.js.map +0 -1
  81. package/dist/common/error/notimplemented.js.map +0 -1
  82. package/dist/common/error/unauthorizederror.js.map +0 -1
  83. package/dist/common/helpers.js.map +0 -1
  84. package/dist/common/index.js.map +0 -1
  85. package/dist/common/logger/common.d.ts +0 -4
  86. package/dist/common/logger/common.js +0 -7
  87. package/dist/common/logger/common.js.map +0 -1
  88. package/dist/common/logger/factory.js.map +0 -1
  89. package/dist/common/logger/formatter.d.ts +0 -7
  90. package/dist/common/logger/formatter.js +0 -9
  91. package/dist/common/logger/formatter.js.map +0 -1
  92. package/dist/common/logger/index.js.map +0 -1
  93. package/dist/common/logger/logger.js.map +0 -1
  94. package/dist/common/logger/transport.js +0 -59
  95. package/dist/common/logger/transport.js.map +0 -1
  96. package/dist/common/router-handler.js.map +0 -1
  97. package/dist/common/router-helpers.js.map +0 -1
  98. package/dist/common/router-utils.js.map +0 -1
  99. package/dist/common/session/common.js.map +0 -1
  100. package/dist/common/session/index.js.map +0 -1
  101. package/dist/common/session/service.js.map +0 -1
  102. package/dist/common/tokenize-match.js.map +0 -1
  103. package/dist/index.js.map +0 -1
  104. package/dist/middleware/buffer.js.map +0 -1
  105. package/dist/middleware/cookie.js.map +0 -1
  106. package/dist/middleware/cors.js.map +0 -1
  107. package/dist/middleware/form.js.map +0 -1
  108. package/dist/middleware/group.js.map +0 -1
  109. package/dist/middleware/index.js.map +0 -1
  110. package/dist/middleware/json.js.map +0 -1
  111. package/dist/middleware/logger.js.map +0 -1
  112. package/dist/middleware/parse.js.map +0 -1
  113. package/dist/middleware/result.js.map +0 -1
  114. package/dist/middleware/session.js.map +0 -1
  115. package/dist/middleware/tag.js.map +0 -1
  116. package/dist/middleware/text.js.map +0 -1
  117. package/dist/proxy.js.map +0 -1
  118. package/dist/router.js.map +0 -1
  119. package/dist/static.js.map +0 -1
  120. package/src/api-router.ts +0 -60
  121. package/src/api-router.unit.test.js +0 -273
  122. package/src/app-utils.ts +0 -82
  123. package/src/app-utils.unit.test.js +0 -100
  124. package/src/app.ts +0 -51
  125. package/src/app.unit.test.js +0 -334
  126. package/src/common/api-router-utils.ts +0 -209
  127. package/src/common/api-router.ts +0 -32
  128. package/src/common/config/config.ts +0 -111
  129. package/src/common/config/featuretoggle.ts +0 -6
  130. package/src/common/config/index.ts +0 -3
  131. package/src/common/config/loader.ts +0 -80
  132. package/src/common/context.ts +0 -167
  133. package/src/common/context.unit.test.js +0 -288
  134. package/src/common/error/badrequesterror.ts +0 -6
  135. package/src/common/error/configfilenotfound.ts +0 -6
  136. package/src/common/error/forbiddenerror.ts +0 -6
  137. package/src/common/error/index.ts +0 -6
  138. package/src/common/error/notfound.ts +0 -6
  139. package/src/common/error/notimplemented.ts +0 -6
  140. package/src/common/error/unauthorizederror.ts +0 -6
  141. package/src/common/helpers.ts +0 -11
  142. package/src/common/index.ts +0 -7
  143. package/src/common/logger/common.ts +0 -6
  144. package/src/common/logger/factory.ts +0 -51
  145. package/src/common/logger/formatter.ts +0 -9
  146. package/src/common/logger/index.ts +0 -6
  147. package/src/common/logger/logger.ts +0 -114
  148. package/src/common/logger/transport.ts +0 -71
  149. package/src/common/router-handler.ts +0 -159
  150. package/src/common/router-helpers.ts +0 -20
  151. package/src/common/router-utils.ts +0 -95
  152. package/src/common/session/common.ts +0 -40
  153. package/src/common/session/index.ts +0 -2
  154. package/src/common/session/service.ts +0 -160
  155. package/src/common/tokenize-match.ts +0 -130
  156. package/src/index.ts +0 -7
  157. package/src/middleware/buffer.ts +0 -80
  158. package/src/middleware/cookie.ts +0 -20
  159. package/src/middleware/cors.ts +0 -96
  160. package/src/middleware/form.ts +0 -59
  161. package/src/middleware/group.ts +0 -70
  162. package/src/middleware/index.ts +0 -48
  163. package/src/middleware/json.ts +0 -55
  164. package/src/middleware/logger.ts +0 -18
  165. package/src/middleware/parse.ts +0 -93
  166. package/src/middleware/result.ts +0 -43
  167. package/src/middleware/session.ts +0 -136
  168. package/src/middleware/tag.ts +0 -15
  169. package/src/middleware/text.ts +0 -45
  170. package/src/proxy.ts +0 -77
  171. package/src/proxy.unit.test.js +0 -159
  172. package/src/router.ts +0 -112
  173. package/src/router.unit.test.js +0 -397
  174. package/src/setup-test.js +0 -5
  175. package/src/static.ts +0 -238
@@ -1,397 +0,0 @@
1
- const {fake, requireMock} = require("@miqro/test");
2
- const {resolve} = require("path");
3
- const {strictEqual} = require("assert");
4
- const {format} = require("util");
5
- const {distPath, basePath} = require("./setup-test.js");
6
-
7
- const testFilePath = resolve(distPath, "router.js");
8
-
9
- describe("router unit tests", () => {
10
-
11
- describe("this.run", () => {
12
- [
13
- {prePathTokens: undefined},
14
- {prePathTokens: ["prePathTokens1"]}
15
- ].forEach(({prePathTokens}) => {
16
- [
17
- {
18
- pathTokens: undefined
19
- },
20
- {
21
- pathTokens: "pathTokens"
22
- }
23
- ].forEach(({pathTokens}) => {
24
- let router, splitPath;
25
- const splitPathRet = "splitPathRet";
26
-
27
- function createFakeHandler({isMatch, invokeEnds, throws}) {
28
- return {
29
- invoke: fake((ctx) => {
30
- if (throws) {
31
- throw new Error("fakeHandlerError");
32
- }
33
- if (invokeEnds) {
34
- ctx.res.headersSent = true;
35
- }
36
- return invokeEnds ? false : true;
37
- }),
38
- isMatch: fake(() => {
39
- return {
40
- match: isMatch
41
- };
42
- })
43
- };
44
- }
45
-
46
- function createFakeContext() {
47
- return {
48
- method: "method",
49
- res: {
50
- headersSent: false
51
- }
52
- };
53
- }
54
-
55
-
56
- splitPath = fake(() => {
57
- return splitPathRet;
58
- });
59
- before(() => {
60
- splitPath.reset();
61
- const {Router} = requireMock(testFilePath, {
62
- "http": {},
63
- "uuid": {},
64
- "./common/logger": {},
65
- "./common/context": {},
66
- "./common/router-utils": {},
67
- "./common/router-helpers": {},
68
- "./common/router-handler": {},
69
- "./common/tokenize-match": {
70
- splitPath
71
- }
72
- }, distPath);
73
- router = new Router();
74
- });
75
- describe("some handlers match with " + prePathTokens + " " + pathTokens, () => {
76
- it("one handler ends response", async () => {
77
- router.handlers = [
78
- createFakeHandler({invokeEnds: false, isMatch: true}),
79
- createFakeHandler({invokeEnds: false, isMatch: true}),
80
- createFakeHandler({invokeEnds: false, isMatch: false}),
81
- createFakeHandler({invokeEnds: true, isMatch: true}),
82
- createFakeHandler({invokeEnds: true, isMatch: true})
83
- ];
84
- const context = createFakeContext();
85
- const ret = await router.run(context, pathTokens, prePathTokens);
86
- strictEqual(router.handlers.filter(r => r.isMatch.callCount === 1).length, router.handlers.length - 1);
87
- strictEqual(splitPath.callCount, pathTokens ? 0 : 1);
88
- strictEqual(router.handlers[0].isMatch.callArgs[0][0], context.method);
89
- strictEqual(router.handlers[0].isMatch.callArgs[0][1], pathTokens ? pathTokens : splitPathRet);
90
- strictEqual(router.handlers[0].isMatch.callArgs[0][2].length, prePathTokens ? prePathTokens.length : 0);
91
- if (prePathTokens) {
92
- strictEqual(router.handlers[0].isMatch.callArgs[0][2], prePathTokens);
93
- }
94
- strictEqual(router.handlers[0].invoke.callCount, 1);
95
- strictEqual(router.handlers[0].invoke.callArgs[0][0], context);
96
- strictEqual(router.handlers[0].invoke.callArgs[0][1], pathTokens ? pathTokens : splitPathRet);
97
- strictEqual(router.handlers[0].invoke.callArgs[0][2].length, prePathTokens ? prePathTokens.length : 0);
98
- if (prePathTokens) {
99
- strictEqual(router.handlers[0].invoke.callArgs[0][2], prePathTokens);
100
- }
101
- strictEqual(router.handlers[1].invoke.callCount, 1);
102
- strictEqual(router.handlers[2].invoke.callCount, 0);
103
- strictEqual(router.handlers[3].invoke.callCount, 1);
104
- strictEqual(router.handlers[4].invoke.callCount, 0);
105
- });
106
-
107
- it("no handler ends response", async () => {
108
- router.handlers = [
109
- createFakeHandler({invokeEnds: false, isMatch: true}),
110
- createFakeHandler({invokeEnds: false, isMatch: true}),
111
- createFakeHandler({invokeEnds: false, isMatch: false}),
112
- createFakeHandler({invokeEnds: false, isMatch: true}),
113
- createFakeHandler({invokeEnds: false, isMatch: true})
114
- ];
115
- const context = createFakeContext();
116
- const ret = await router.run(context, pathTokens, prePathTokens);
117
- strictEqual(router.handlers.filter(r => r.isMatch.callCount === 1).length, router.handlers.length);
118
- strictEqual(splitPath.callCount, pathTokens ? 0 : 1);
119
- strictEqual(router.handlers[0].invoke.callCount, 1);
120
- strictEqual(router.handlers[1].invoke.callCount, 1);
121
- strictEqual(router.handlers[2].invoke.callCount, 0);
122
- strictEqual(router.handlers[3].invoke.callCount, 1);
123
- strictEqual(router.handlers[4].invoke.callCount, 1);
124
- });
125
-
126
- it("one handler throws second errorHandler catches", async () => {
127
- router.handlers = [
128
- createFakeHandler({invokeEnds: false, isMatch: true}),
129
- createFakeHandler({invokeEnds: false, isMatch: true, throws: true}),
130
- createFakeHandler({invokeEnds: false, isMatch: false}),
131
- createFakeHandler({invokeEnds: true, isMatch: true}),
132
- createFakeHandler({invokeEnds: false, isMatch: true})
133
- ];
134
- const errorHandlerMisses = fake(() => {
135
-
136
- });
137
- const errorHandler = fake((e, ctx) => {
138
- ctx.res.headersSent = true;
139
- });
140
- const context = createFakeContext();
141
- router.catch([errorHandlerMisses, errorHandler]);
142
- const ret = await router.run(context, pathTokens, prePathTokens);
143
- strictEqual(router.handlers.filter(r => r.isMatch.callCount === 1).length, 2);
144
- strictEqual(splitPath.callCount, pathTokens ? 0 : 1);
145
- strictEqual(router.handlers[0].invoke.callCount, 1);
146
- strictEqual(router.handlers[1].invoke.callCount, 1);
147
- strictEqual(router.handlers[2].invoke.callCount, 0);
148
- strictEqual(router.handlers[3].invoke.callCount, 0);
149
- strictEqual(router.handlers[4].invoke.callCount, 0);
150
- strictEqual(errorHandlerMisses.callCount, 1);
151
- strictEqual(errorHandler.callCount, 1);
152
- });
153
-
154
- it("one handler throws first errorHandler catches", async () => {
155
- router.handlers = [
156
- createFakeHandler({invokeEnds: false, isMatch: true}),
157
- createFakeHandler({invokeEnds: false, isMatch: true, throws: true}),
158
- createFakeHandler({invokeEnds: false, isMatch: false}),
159
- createFakeHandler({invokeEnds: true, isMatch: true}),
160
- createFakeHandler({invokeEnds: false, isMatch: true})
161
- ];
162
- const errorHandlerMisses = fake(() => {
163
-
164
- });
165
- const errorHandler = fake((e, ctx) => {
166
- ctx.res.headersSent = true;
167
- });
168
- const context = createFakeContext();
169
- router.catch([errorHandler, errorHandlerMisses]);
170
- const ret = await router.run(context, pathTokens, prePathTokens);
171
- strictEqual(router.handlers.filter(r => r.isMatch.callCount === 1).length, 2);
172
- strictEqual(splitPath.callCount, pathTokens ? 0 : 1);
173
- strictEqual(router.handlers[0].invoke.callCount, 1);
174
- strictEqual(router.handlers[1].invoke.callCount, 1);
175
- strictEqual(router.handlers[2].invoke.callCount, 0);
176
- strictEqual(router.handlers[3].invoke.callCount, 0);
177
- strictEqual(router.handlers[4].invoke.callCount, 0);
178
- strictEqual(errorHandlerMisses.callCount, 0);
179
- strictEqual(errorHandler.callCount, 1);
180
- });
181
-
182
- it("one handler throws errorHandler doesn't catch", async () => {
183
- router.handlers = [
184
- createFakeHandler({invokeEnds: false, isMatch: true}),
185
- createFakeHandler({invokeEnds: false, isMatch: true, throws: true}),
186
- createFakeHandler({invokeEnds: false, isMatch: false}),
187
- createFakeHandler({invokeEnds: true, isMatch: true}),
188
- createFakeHandler({invokeEnds: false, isMatch: true})
189
- ];
190
- const context = createFakeContext();
191
- try {
192
- const ret = await router.run(context, pathTokens, prePathTokens);
193
- strictEqual(false, true);
194
- } catch (e) {
195
- strictEqual(e.message, "fakeHandlerError")
196
- }
197
- strictEqual(router.handlers.filter(r => r.isMatch.callCount === 1).length, 2);
198
- strictEqual(splitPath.callCount, pathTokens ? 0 : 1);
199
- strictEqual(router.handlers[0].invoke.callCount, 1);
200
- strictEqual(router.handlers[1].invoke.callCount, 1);
201
- strictEqual(router.handlers[2].invoke.callCount, 0);
202
- strictEqual(router.handlers[3].invoke.callCount, 0);
203
- strictEqual(router.handlers[4].invoke.callCount, 0);
204
- });
205
- });
206
- });
207
- });
208
- });
209
-
210
- [
211
- {method: "options"},
212
- {method: "put"},
213
- {method: "patch"},
214
- {method: "delete"},
215
- {method: "post"},
216
- {method: "get"}
217
- ].forEach(({method}) => {
218
- let router;
219
- before(() => {
220
- const {Router} = requireMock(testFilePath, {
221
- "http": {},
222
- "uuid": {},
223
- "./common/logger": {},
224
- "./common/context": {},
225
- "./common/router-utils": {},
226
- "./common/router-helpers": {},
227
- "./common/router-handler": {},
228
- "./common/tokenize-match": {}
229
- }, distPath);
230
- router = new Router();
231
- });
232
- it(method + " just alias for use", async () => {
233
- router.use = fake(() => {
234
- });
235
- const path = "path";
236
- const handler = "handler";
237
- const options = "options";
238
- router[method](path, handler, options);
239
- strictEqual(router.use.callCount, 1);
240
- strictEqual(router.use.callArgs[0][0], handler);
241
- strictEqual(router.use.callArgs[0][1], path);
242
- strictEqual(router.use.callArgs[0][2], method);
243
- strictEqual(router.use.callArgs[0][3], options);
244
- });
245
- });
246
-
247
- describe("this.catch", () => {
248
-
249
- let router;
250
- before(() => {
251
- const {Router} = requireMock(testFilePath, {
252
- "http": {},
253
- "uuid": {},
254
- "./common/logger": {},
255
- "./common/context": {},
256
- "./common/router-utils": {},
257
- "./common/router-helpers": {},
258
- "./common/router-handler": {},
259
- "./common/tokenize-match": {}
260
- }, distPath);
261
- router = new Router();
262
- });
263
- [
264
- {
265
- errorHandler: [
266
- () => {
267
- },
268
- () => {
269
- }
270
- ]
271
- },
272
- {
273
- errorHandler: () => {
274
- }
275
- },
276
- {
277
- errorHandler: undefined,
278
- throws: true,
279
- },
280
- {
281
- errorHandler: [
282
- () => {
283
- },
284
- undefined
285
- ],
286
- throws: true
287
- }
288
- ].forEach(({errorHandler, throws}) => {
289
- it(format("errorHandler %o throws %o", errorHandler, throws), () => {
290
- router.errorHandlers = {
291
- push: fake(() => {
292
-
293
- })
294
- };
295
- try {
296
- const ret = router.catch(errorHandler);
297
- strictEqual(undefined, throws);
298
- strictEqual(ret, router);
299
- } catch (e) {
300
- strictEqual(true, throws);
301
- } finally {
302
- const count = (!errorHandler ? [] : (errorHandler instanceof Array ? errorHandler : [errorHandler])).filter(m => typeof m === "function").length;
303
- strictEqual(router.errorHandlers.push.callCount, count);
304
- }
305
- });
306
- });
307
- });
308
-
309
- describe("this.use", () => {
310
- let RouterHandler, router, routerHandlerCtr, normalizePath, splitPath;
311
- const normalizePathRet = "normalizePathRet";
312
-
313
- before(() => {
314
- routerHandlerCtr = fake(() => {
315
-
316
- });
317
-
318
- normalizePath = fake(() => {
319
- return normalizePathRet;
320
- });
321
-
322
- splitPath = fake(() => {
323
-
324
- });
325
-
326
- RouterHandler = class {
327
- constructor() {
328
- routerHandlerCtr(...arguments);
329
- }
330
- }
331
-
332
- const {Router} = requireMock(testFilePath, {
333
- "http": {},
334
- "uuid": {},
335
- "./common/logger": {},
336
- "./common/context": {},
337
- "./common/router-utils": {},
338
- "./common/router-helpers": {},
339
- "./common/router-handler": {
340
- RouterHandler
341
- },
342
- "./common/tokenize-match": {
343
- normalizePath,
344
- splitPath
345
- }
346
- }, distPath);
347
- router = new Router();
348
- });
349
-
350
- [
351
- {handler: "handler"},
352
- {handler: undefined},
353
- {handler: ["handler1", "handler2"]}
354
- ].forEach(({handler}) => {
355
- [
356
- {options: "options"},
357
- {options: undefined}
358
- ].forEach(({options}) => {
359
- [
360
- {
361
- path: "path",
362
- method: "method"
363
- },
364
- {
365
- path: "path"
366
- },
367
- {}
368
- ].forEach(
369
- ({
370
- path,
371
- method
372
- }) => {
373
- it(`use with handler ${handler} path ${path} method ${method} options ${options}`, async () => {
374
- router.handlers = {
375
- push: fake(() => {
376
-
377
- })
378
- }
379
- const ret = router.use(handler, path, method, options);
380
- strictEqual(ret, router);
381
- strictEqual(normalizePath.callCount, path !== undefined ? 1 : 0);
382
- if (path) {
383
- strictEqual(normalizePath.callArgs[0][0], path);
384
- }
385
- strictEqual(routerHandlerCtr.callCount, 1);
386
- strictEqual(routerHandlerCtr.callArgs[0][0], handler);
387
- strictEqual(routerHandlerCtr.callArgs[0][1], path ? normalizePathRet : path);
388
- strictEqual(routerHandlerCtr.callArgs[0][2], method ? method.toUpperCase() : method);
389
- strictEqual(routerHandlerCtr.callArgs[0][3], options);
390
- strictEqual(router.handlers.push.callCount, 1);
391
- strictEqual(router.handlers.push.callArgs[0][0] instanceof RouterHandler, true);
392
- });
393
- });
394
- });
395
- });
396
- });
397
- });
package/src/setup-test.js DELETED
@@ -1,5 +0,0 @@
1
- const {resolve} = require("path");
2
-
3
- module.exports.basePath = resolve(__dirname, "..");
4
-
5
- module.exports.distPath = resolve(module.exports.basePath, "dist");
package/src/static.ts DELETED
@@ -1,238 +0,0 @@
1
- import {existsSync, readdirSync, readFileSync, statSync} from "fs";
2
- import {extname, resolve} from "path";
3
- import {Context} from "./common/context";
4
- import {parse} from "@miqro/parser";
5
- import {PathPartToken} from "./common/tokenize-match";
6
- import {Router, RouterOptions} from "./router";
7
-
8
- const outputFile = async (path: string, contentType: string, ctx: Context, allowGetJSON: boolean, status = 200) => {
9
- const buffer = readFileSync(path);
10
- return allowGetJSON && ctx.query.format && ctx.query.format === "json" ?
11
- ctx.json({
12
- buffer
13
- }) :
14
- ctx.end({
15
- status,
16
- headers: {
17
- ["Content-Type"]: contentType
18
- },
19
- body: buffer
20
- });
21
- }
22
-
23
- const generateList = async (path: string, ctx: Context, allowListJSON: boolean) => {
24
- const files = readdirSync(path);
25
- return allowListJSON && ctx.query.format && ctx.query.format === "json" ?
26
- ctx.json({files: files.map(f => `${ctx.path}${f}`)}) :
27
- ctx.html(`<html><body><ul>${files.map(f => `<li><a href="${ctx.path}${f}">${f}</a></li>`).join("")}</ul></body></html>`);
28
- }
29
-
30
- export interface StaticRouterOptions extends RouterOptions {
31
- directory: string;
32
- list?: boolean;
33
- allowListJSON?: boolean;
34
- allowGetJSON?: boolean;
35
- index?: string;
36
- index404?: string;
37
- index404Status?: number;
38
- contentTypes?: any;
39
- defaultContentType?: string;
40
- }
41
-
42
- export function Static(options: StaticRouterOptions): Router {
43
- return new StaticRouter(options);
44
- }
45
-
46
- class StaticRouter extends Router {
47
-
48
- private readonly staticOptions: {
49
- directory: string;
50
- list: boolean;
51
- allowListJSON: boolean;
52
- allowGetJSON: boolean;
53
- index: string;
54
- index404: string;
55
- index404Status: number;
56
- contentTypes: any;
57
- defaultContentType: string;
58
- };
59
-
60
- constructor(options: StaticRouterOptions) {
61
- super(options);
62
- this.staticOptions = parse(options, {
63
- loggerFactory: {
64
- required: false,
65
- type: "any"
66
- },
67
- directory: {
68
- type: "string",
69
- required: true
70
- },
71
- list: {
72
- type: "boolean",
73
- required: false,
74
- defaultValue: false
75
- },
76
- allowListJSON: {
77
- type: "boolean",
78
- required: false,
79
- defaultValue: false
80
- },
81
- allowGetJSON: {
82
- type: "boolean",
83
- required: false,
84
- defaultValue: false
85
- },
86
- index: {
87
- type: "string",
88
- required: false,
89
- defaultValue: "index.html"
90
- },
91
- index404: {
92
- type: "string",
93
- required: false
94
- },
95
- index404Status: {
96
- type: "number",
97
- required: false,
98
- defaultValue: 404
99
- },
100
- contentTypes: {
101
- type: "object",
102
- required: false,
103
- defaultValue: {
104
- ".aac": "audio/aac",
105
- ".abw": "application/x-abiword",
106
- ".arc": "application/x-freearc",
107
- ".avif": "image/avif",
108
- ".avi": "video/x-msvideo",
109
- ".azw": "application/vnd.amazon.ebook",
110
- ".bin": "application/octet-stream",
111
- ".bmp": "image/bmp",
112
- ".bz": "application/x-bzip",
113
- ".bz2": "application/x-bzip2",
114
- ".cda": "application/x-cdf",
115
- ".csh": "application/x-csh",
116
- ".css": "text/css",
117
- ".csv": "text/csv",
118
- ".doc": "application/msword",
119
- ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
120
- ".eot": "application/vnd.ms-fontobject",
121
- ".epub": "application/epub+zip",
122
- ".gz": "application/gzip",
123
- ".gif": "image/gif",
124
- ".htm": "text/html",
125
- ".html": "text/html",
126
- ".ico": "image/vnd.microsoft.icon",
127
- ".ics": "text/calendar",
128
- ".jar": "application/java-archive",
129
- ".jpeg": "image/jpeg",
130
- ".jpg": "image/jpeg",
131
- ".js": "text/javascript",
132
- ".json": "application/json",
133
- ".jsonld": "application/ld+json",
134
- ".mid": "audio/midi audio/x-midi",
135
- ".midi": "audio/midi audio/x-midi",
136
- ".mjs": "text/javascript",
137
- ".mp3": "audio/mpeg",
138
- ".mp4": "video/mp4",
139
- ".mpeg": "video/mpeg",
140
- ".mpkg": "application/vnd.apple.installer+xml",
141
- ".odp": "application/vnd.oasis.opendocument.presentation",
142
- ".ods": "application/vnd.oasis.opendocument.spreadsheet",
143
- ".odt": "application/vnd.oasis.opendocument.text",
144
- ".oga": "audio/ogg",
145
- ".ogv": "video/ogg",
146
- ".ogx": "application/ogg",
147
- ".opus": "audio/opus",
148
- ".otf": "font/otf",
149
- ".png": "image/png",
150
- ".pdf": "application/pdf",
151
- ".php": "application/x-httpd-php",
152
- ".ppt": "application/vnd.ms-powerpoint",
153
- ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
154
- ".rar": "application/vnd.rar",
155
- ".rtf": "application/rtf",
156
- ".sh": "application/x-sh",
157
- ".svg": "image/svg+xml",
158
- ".swf": "application/x-shockwave-flash",
159
- ".tar": "application/x-tar",
160
- ".tif": "image/tiff",
161
- ".tiff": "image/tiff",
162
- ".ts": "video/mp2t",
163
- ".ttf": "font/ttf",
164
- ".txt": "text/plain",
165
- ".vsd": "application/vnd.visio",
166
- ".wav": "audio/wav",
167
- ".weba": "audio/webm",
168
- ".webm": "video/webm",
169
- ".webp": "image/webp",
170
- ".woff": "font/woff",
171
- ".woff2": "font/woff2",
172
- ".xhtml": "application/xhtml+xml",
173
- ".xls": "application/vnd.ms-excel",
174
- ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
175
- ".xml": "application/xml",
176
- ".xul": "application/vnd.mozilla.xul+xml",
177
- ".zip": "application/zip",
178
- ".3gp": "video/3gpp; audio/3gpp",
179
- ".3g2": "video/3gpp2; audio/3gpp2",
180
- ".7z": "application/x-7z-compressed"
181
- }
182
- },
183
- defaultContentType: {
184
- type: "string",
185
- required: false,
186
- defaultValue: "application/octet-stream"
187
- }
188
- }, "no_extra", "options");
189
- if (!statSync(this.staticOptions.directory).isDirectory()) {
190
- throw new Error(`options.directory ${this.staticOptions.directory} not a directory`);
191
- }
192
- if (this.staticOptions.index404 && !existsSync(resolve(this.staticOptions.directory, this.staticOptions.index404))) {
193
- throw new Error(`options.index404 ${this.staticOptions.index404} not a found`);
194
- }
195
- }
196
-
197
- public async run(ctx: Context, pathTokens?: { value: string; lower: string; }[], prePathTokens: PathPartToken[] = []): Promise<boolean> {
198
- const {directory, allowGetJSON, allowListJSON, list, index, contentTypes, defaultContentType} = this.staticOptions;
199
- const level = prePathTokens.length;
200
- if (ctx.method === "GET") {
201
- const realPath = resolve(directory, ctx.path.split("/").map(s => s.trim()).filter(s => s).slice(level).join("/"));
202
- ctx.logger.debug("static get %s", realPath);
203
-
204
- if (existsSync(realPath)) {
205
- if (statSync(realPath).isDirectory()) {
206
- // directory
207
- const indexPath = resolve(realPath, index);
208
- if (index && existsSync(indexPath) && statSync(indexPath).isFile()) {
209
- // index file exists
210
- const ext = extname(indexPath);
211
- const contentType = contentTypes[ext] ? contentTypes[ext] : defaultContentType;
212
- await outputFile(indexPath, contentType, ctx, allowGetJSON);
213
- } else {
214
- // index doesn't exists
215
- if (list) {
216
- // generate list
217
- await generateList(realPath, ctx, allowListJSON);
218
- }
219
- }
220
- } else {
221
- // direct file access
222
- const ext = extname(realPath);
223
- const contentType = contentTypes[ext] ? contentTypes[ext] : defaultContentType;
224
- await outputFile(realPath, contentType, ctx, allowGetJSON);
225
- }
226
- }
227
- }
228
- if (this.staticOptions.index404) {
229
- const realPath = resolve(this.staticOptions.directory, this.staticOptions.index404);
230
- if (existsSync(realPath)) {
231
- const ext = extname(realPath);
232
- const contentType = contentTypes[ext] ? contentTypes[ext] : defaultContentType;
233
- await outputFile(realPath, contentType, ctx, allowGetJSON, this.staticOptions.index404Status);
234
- }
235
- }
236
- return !ctx.res.headersSent ? super.run(ctx, pathTokens, prePathTokens) : false;
237
- }
238
- }