springnext 0.0.1 → 0.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.
package/dist/index.js CHANGED
@@ -1,2 +1,511 @@
1
- const squared = (n)=>n * n;
2
- export { squared };
1
+ import zod from "zod";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports, definition)=>{
5
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) Object.defineProperty(exports, key, {
6
+ enumerable: true,
7
+ get: definition[key]
8
+ });
9
+ };
10
+ })();
11
+ (()=>{
12
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
13
+ })();
14
+ (()=>{
15
+ __webpack_require__.r = (exports)=>{
16
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports, Symbol.toStringTag, {
17
+ value: 'Module'
18
+ });
19
+ Object.defineProperty(exports, '__esModule', {
20
+ value: true
21
+ });
22
+ };
23
+ })();
24
+ var store_namespaceObject = {};
25
+ __webpack_require__.r(store_namespaceObject);
26
+ __webpack_require__.d(store_namespaceObject, {
27
+ InRAM: ()=>InRAM,
28
+ methods: ()=>store_zod_utils_methods,
29
+ toModuleMetadata: ()=>toModuleMetadata
30
+ });
31
+ var value_objects_namespaceObject = {};
32
+ __webpack_require__.r(value_objects_namespaceObject);
33
+ __webpack_require__.d(value_objects_namespaceObject, {
34
+ Pagination: ()=>Pagination
35
+ });
36
+ var zod_controller_utils_namespaceObject = {};
37
+ __webpack_require__.r(zod_controller_utils_namespaceObject);
38
+ __webpack_require__.d(zod_controller_utils_namespaceObject, {
39
+ DefaultErrorCodes: ()=>zod_controller_utils_DefaultErrorCodes,
40
+ endpoints: ()=>endpoints
41
+ });
42
+ var zod_module_utils_namespaceObject = {};
43
+ __webpack_require__.r(zod_module_utils_namespaceObject);
44
+ __webpack_require__.d(zod_module_utils_namespaceObject, {
45
+ methods: ()=>methods
46
+ });
47
+ const isControllerError = (error)=>{
48
+ if (!error || 'object' != typeof error) return false;
49
+ const argKeys = Object.keys(error);
50
+ const requiredKeys = [
51
+ 'name',
52
+ 'message',
53
+ 'code',
54
+ 'module',
55
+ 'method',
56
+ 'timestamp',
57
+ 'statusCode'
58
+ ];
59
+ return requiredKeys.every((x)=>argKeys.includes(x));
60
+ };
61
+ const isModuleError = (arg)=>{
62
+ if ('object' != typeof arg || !arg) return false;
63
+ const argKeys = Object.keys(arg);
64
+ const requiredKeys = [
65
+ 'name',
66
+ 'message',
67
+ 'code',
68
+ 'module',
69
+ 'method',
70
+ 'timestamp'
71
+ ];
72
+ if (!requiredKeys.every((x)=>argKeys.includes(x))) return false;
73
+ return !argKeys.includes('statusCode');
74
+ };
75
+ const spawnBaseError = ({ error, code, details })=>{
76
+ let err = error instanceof Error ? error : new Error('unknown error');
77
+ if ('string' == typeof error || 'number' == typeof error) err = new Error(error?.toString());
78
+ if ('object' == typeof error && null !== error) if (error instanceof Error) err = error;
79
+ else {
80
+ const jsonRepresentation = JSON.stringify(error);
81
+ err = new Error(jsonRepresentation);
82
+ }
83
+ return {
84
+ message: err.message,
85
+ name: err.name,
86
+ timestamp: Date.now(),
87
+ code: code || err.name,
88
+ details: details || null
89
+ };
90
+ };
91
+ const spawnFromUnknownError = (error)=>{
92
+ const isErrorBase = (arg)=>{
93
+ if ('object' != typeof arg || !arg) return false;
94
+ const argKeys = Object.keys(arg);
95
+ const requiredKeys = [
96
+ 'name',
97
+ 'message',
98
+ 'code',
99
+ 'timestamp'
100
+ ];
101
+ return requiredKeys.every((x)=>argKeys.includes(x));
102
+ };
103
+ if (isModuleError(error)) return error;
104
+ if (isErrorBase(error)) return error;
105
+ return spawnBaseError({
106
+ error
107
+ });
108
+ };
109
+ const spawnModuleError = (moduleName)=>({
110
+ inMethod: (methodName)=>({
111
+ newError: (payload, cause)=>{
112
+ const errorBase = spawnBaseError(payload);
113
+ return {
114
+ ...errorBase,
115
+ cause: cause ? spawnFromUnknownError(cause) : null,
116
+ module: moduleName,
117
+ method: methodName
118
+ };
119
+ }
120
+ })
121
+ });
122
+ const spawnControllerError = (controllerName)=>({
123
+ inMethod: (methodName)=>({
124
+ newError: (payload, cause)=>{
125
+ const errorBase = spawnBaseError(payload);
126
+ const formattedCause = cause ? spawnFromUnknownError(cause) : null;
127
+ if (!payload.code && formattedCause?.code) errorBase.code = formattedCause.code;
128
+ return {
129
+ ...errorBase,
130
+ cause: formattedCause,
131
+ module: controllerName,
132
+ method: methodName,
133
+ statusCode: payload.statusCode
134
+ };
135
+ }
136
+ })
137
+ });
138
+ const methods = (metadata, sharedConfig = {})=>(methodName, handler, config = {})=>{
139
+ const { name, schemas } = metadata;
140
+ return async (payload)=>{
141
+ try {
142
+ const parsedPayload = schemas[methodName].payload.parse(payload);
143
+ const response = await handler(parsedPayload, {
144
+ methodError: (payload, cause)=>spawnModuleError(name).inMethod(methodName).newError('string' == typeof payload ? {
145
+ error: payload,
146
+ code: payload,
147
+ details: parsedPayload
148
+ } : payload, cause)
149
+ });
150
+ const parsedResponse = schemas[methodName].response.parse(response);
151
+ return parsedResponse;
152
+ } catch (error) {
153
+ if (isModuleError(error)) {
154
+ if (sharedConfig.onError) await sharedConfig.onError(error);
155
+ if (config.onError) await config.onError(error);
156
+ throw error;
157
+ }
158
+ const serviceErrorGenerator = spawnModuleError(name).inMethod(methodName);
159
+ const serviceError = serviceErrorGenerator.newError({
160
+ error
161
+ });
162
+ if (config.onError) await config.onError(serviceError);
163
+ throw serviceError;
164
+ }
165
+ };
166
+ };
167
+ function jsonResponse(data, init) {
168
+ return new Response(JSON.stringify(data), {
169
+ ...init,
170
+ headers: {
171
+ 'Content-Type': 'application/json',
172
+ ...init?.headers || {}
173
+ }
174
+ });
175
+ }
176
+ var zod_controller_utils_DefaultErrorCodes = /*#__PURE__*/ function(DefaultErrorCodes) {
177
+ DefaultErrorCodes["REQUEST_PARSING"] = "NZMT-CONTROLLER___REQUEST-PARSING";
178
+ DefaultErrorCodes["RESPONSE_PARSING"] = "NZMT-CONTROLLER___RESPONSE-PARSING";
179
+ return DefaultErrorCodes;
180
+ }({});
181
+ const endpoints = (metadata, sharedConfig = {})=>{
182
+ const endpointLogic = (method, handler, configuration = {})=>async (request)=>{
183
+ let requestPayload = {};
184
+ const errorFactory = spawnControllerError(metadata.name).inMethod(method);
185
+ try {
186
+ const endpointError = (payload, errorStatus, cause)=>{
187
+ if ('string' == typeof payload) return errorFactory.newError({
188
+ statusCode: errorStatus ?? 500,
189
+ code: payload,
190
+ error: payload,
191
+ details: requestPayload
192
+ }, cause);
193
+ return errorFactory.newError({
194
+ ...payload,
195
+ statusCode: errorStatus ?? 500
196
+ }, cause);
197
+ };
198
+ if (sharedConfig.guards) for (const sharedGuard of sharedConfig.guards){
199
+ const error = await sharedGuard({
200
+ request,
201
+ endpointError
202
+ });
203
+ if (error) throw error;
204
+ }
205
+ if (configuration.guards) for (const endpointGuard of configuration.guards){
206
+ const error = await endpointGuard({
207
+ request,
208
+ endpointError
209
+ });
210
+ if (error) throw error;
211
+ }
212
+ const endpointSchemas = metadata.schemas[method];
213
+ if (!endpointSchemas) throw errorFactory.newError({
214
+ error: 'No schemas were found for the endpoint',
215
+ statusCode: 500
216
+ });
217
+ if (endpointSchemas.query) {
218
+ const queryParamsAsObject = Object.fromEntries(request.nextUrl.searchParams.entries());
219
+ const queryParamsParsed = endpointSchemas.query.safeParse(queryParamsAsObject);
220
+ if (!queryParamsParsed.success) throw errorFactory.newError({
221
+ error: queryParamsParsed.error.message,
222
+ statusCode: 400,
223
+ code: "NZMT-CONTROLLER___REQUEST-PARSING",
224
+ details: zod.treeifyError(queryParamsParsed.error)
225
+ });
226
+ requestPayload = {
227
+ ...requestPayload,
228
+ ...queryParamsParsed.data
229
+ };
230
+ }
231
+ if (endpointSchemas.body) {
232
+ const body = await request.json();
233
+ const bodyParsed = endpointSchemas.body.safeParse(body);
234
+ if (!bodyParsed.success) throw errorFactory.newError({
235
+ error: bodyParsed.error.message,
236
+ statusCode: 400,
237
+ code: "NZMT-CONTROLLER___REQUEST-PARSING",
238
+ details: zod.treeifyError(bodyParsed.error)
239
+ });
240
+ requestPayload = {
241
+ ...requestPayload,
242
+ ...bodyParsed.data
243
+ };
244
+ }
245
+ const flags = {};
246
+ const result = await handler(requestPayload, {
247
+ request,
248
+ flags,
249
+ endpointError: (payload, errorStatus, cause)=>{
250
+ if ('string' == typeof payload) return errorFactory.newError({
251
+ statusCode: errorStatus ?? 500,
252
+ code: payload,
253
+ error: payload,
254
+ details: requestPayload
255
+ }, cause);
256
+ return errorFactory.newError({
257
+ ...payload,
258
+ statusCode: errorStatus ?? 500
259
+ }, cause);
260
+ }
261
+ });
262
+ if (endpointSchemas.response) {
263
+ const resultParsed = endpointSchemas.response.safeParse(result);
264
+ if (!resultParsed.success) throw errorFactory.newError({
265
+ error: resultParsed.error.message,
266
+ statusCode: 500,
267
+ code: "NZMT-CONTROLLER___RESPONSE-PARSING",
268
+ details: zod.treeifyError(resultParsed.error)
269
+ });
270
+ if (configuration.eventHandlers?.onSuccess) for (const onSuccessHandler of configuration.eventHandlers.onSuccess)onSuccessHandler({
271
+ request,
272
+ result: resultParsed.data,
273
+ requestPayload: requestPayload,
274
+ flags
275
+ });
276
+ if (configuration.customResponseLogic?.onSuccess) return await configuration.customResponseLogic.onSuccess({
277
+ req: request,
278
+ response: resultParsed.data
279
+ });
280
+ return jsonResponse(resultParsed.data, {
281
+ status: 200
282
+ });
283
+ }
284
+ if (configuration.eventHandlers?.onSuccess) for (const onSuccessHanlder of configuration.eventHandlers.onSuccess)await onSuccessHanlder({
285
+ request,
286
+ result: void 0,
287
+ requestPayload: requestPayload,
288
+ flags
289
+ });
290
+ if (configuration.customResponseLogic?.onSuccess) return await configuration.customResponseLogic.onSuccess({
291
+ req: request,
292
+ response: {}
293
+ });
294
+ return jsonResponse({}, {
295
+ status: 200
296
+ });
297
+ } catch (e) {
298
+ let controllerError = e;
299
+ if (isControllerError(e)) controllerError = errorFactory.newError({
300
+ error: 'Internal error',
301
+ statusCode: 500
302
+ }, e);
303
+ if (!controllerError.details || 'object' != typeof controllerError.details) controllerError.details = {};
304
+ if (sharedConfig.onErrorHandlers) try {
305
+ for (const sharedOnError of sharedConfig.onErrorHandlers)await sharedOnError({
306
+ error: controllerError,
307
+ req: request
308
+ });
309
+ } catch (errorFromOnErrorHandler) {
310
+ controllerError = errorFactory.newError({
311
+ error: 'onError handler error',
312
+ statusCode: 500
313
+ }, errorFromOnErrorHandler);
314
+ }
315
+ if (configuration.eventHandlers?.onError) try {
316
+ for (const onErrorHandler of configuration.eventHandlers.onError)await onErrorHandler({
317
+ error: controllerError,
318
+ req: request
319
+ });
320
+ } catch (errorFromOnErrorHandler) {
321
+ controllerError = errorFactory.newError({
322
+ error: 'onError handler error',
323
+ statusCode: 500
324
+ }, errorFromOnErrorHandler);
325
+ }
326
+ if (configuration.customResponseLogic?.onError) return await configuration.customResponseLogic.onError({
327
+ req: request,
328
+ error: controllerError
329
+ });
330
+ return jsonResponse({
331
+ message: controllerError.message,
332
+ details: controllerError.statusCode.toString().startsWith('4') ? controllerError.details : null,
333
+ code: controllerError.code
334
+ }, {
335
+ status: controllerError.statusCode
336
+ });
337
+ }
338
+ };
339
+ return endpointLogic;
340
+ };
341
+ class Pagination {
342
+ data;
343
+ static schema = zod.object({
344
+ zeroBasedIndex: zod.coerce.number().int().nonnegative(),
345
+ pageSize: zod.coerce.number().int().positive()
346
+ });
347
+ constructor(data){
348
+ this.data = data;
349
+ }
350
+ static create = (data)=>{
351
+ const parsedModel = Pagination.schema.parse(data);
352
+ return new Pagination(parsedModel);
353
+ };
354
+ get model() {
355
+ return this.data;
356
+ }
357
+ same = (pagination)=>pagination.model.pageSize === this.model.pageSize && pagination.model.zeroBasedIndex === this.model.zeroBasedIndex;
358
+ get nextPage() {
359
+ return Pagination.create({
360
+ pageSize: this.data.pageSize,
361
+ zeroBasedIndex: this.data.zeroBasedIndex + 1
362
+ });
363
+ }
364
+ get previousPage() {
365
+ if (0 === this.model.zeroBasedIndex) return Pagination.create(this.model);
366
+ return Pagination.create({
367
+ pageSize: this.model.pageSize,
368
+ zeroBasedIndex: this.model.zeroBasedIndex - 1
369
+ });
370
+ }
371
+ get previousPage_UNSAFE() {
372
+ return Pagination.create({
373
+ pageSize: this.model.pageSize,
374
+ zeroBasedIndex: this.model.zeroBasedIndex - 1
375
+ });
376
+ }
377
+ }
378
+ const toModuleMetadata = (schemas)=>({
379
+ name: schemas.name,
380
+ schemas: {
381
+ ...schemas.customOperations ?? {},
382
+ list: {
383
+ payload: zod.object({
384
+ filter: schemas.searchPayload.list,
385
+ pagination: Pagination.schema.optional()
386
+ }),
387
+ response: zod.array(schemas.models.list)
388
+ },
389
+ details: {
390
+ payload: zod.object({
391
+ filter: schemas.searchPayload.specific
392
+ }),
393
+ response: schemas.models.details.nullable()
394
+ },
395
+ create: {
396
+ payload: zod.object({
397
+ payload: schemas.actionsPayload.create
398
+ }),
399
+ response: zod.object({
400
+ id: zod.string()
401
+ })
402
+ },
403
+ updateOne: {
404
+ payload: zod.object({
405
+ filter: schemas.searchPayload.specific,
406
+ payload: schemas.actionsPayload.update
407
+ }),
408
+ response: zod.object({
409
+ success: zod.boolean()
410
+ })
411
+ },
412
+ deleteOne: {
413
+ payload: zod.object({
414
+ filter: schemas.searchPayload.specific
415
+ }),
416
+ response: zod.object({
417
+ success: zod.boolean()
418
+ })
419
+ }
420
+ }
421
+ });
422
+ const store_zod_utils_methods = (schemas)=>{
423
+ const data = toModuleMetadata(schemas);
424
+ return methods(data);
425
+ };
426
+ const InRAM = (schemas, options)=>{
427
+ class RAMStore {
428
+ ___data = [];
429
+ method = store_zod_utils_methods(schemas);
430
+ ___listSearchLogic = (entity, pattern)=>{
431
+ const patternKeys = Object.entries(pattern).filter(([_, value])=>!!value).map((x)=>x[0]);
432
+ const entityAsObject = entity;
433
+ return Object.entries(entityAsObject).filter(([key])=>patternKeys.includes(key)).every(([key, value])=>value === pattern[key] || value?.toString()?.includes(pattern[key]?.toString()));
434
+ };
435
+ ___specificSearchLogic = (entity, pattern)=>{
436
+ const patternKeys = Object.entries(pattern).filter(([_, value])=>!!value).map((x)=>x[0]);
437
+ const entityAsObject = entity;
438
+ return Object.entries(entityAsObject).filter(([key])=>patternKeys.includes(key)).every(([key, value])=>value === pattern[key] || value?.toString()?.includes(pattern[key]?.toString()));
439
+ };
440
+ ___mapDetailToList = (entity)=>entity;
441
+ ___mapCreatePayloadToDetail = (payload)=>({
442
+ ...payload,
443
+ id: Math.random().toString()
444
+ });
445
+ ___mapUpdatePayloadToDetail = (prevValue, rawUpdate)=>{
446
+ const update = Object.fromEntries(Object.entries(rawUpdate).filter(([, value])=>void 0 !== value));
447
+ return {
448
+ ...prevValue,
449
+ ...update
450
+ };
451
+ };
452
+ constructor(){
453
+ if (!options) return;
454
+ if (options.searchLogic) {
455
+ if (options.searchLogic.list) this.___listSearchLogic = options.searchLogic.list;
456
+ if (options.searchLogic.specific) this.___specificSearchLogic = options.searchLogic.specific;
457
+ }
458
+ if (options.mappers) {
459
+ if (options.mappers.detailToList) this.___mapDetailToList = options.mappers.detailToList;
460
+ if (options.mappers.createPayloadToDetail) this.___mapCreatePayloadToDetail = options.mappers.createPayloadToDetail;
461
+ if (options.mappers.updatePayloadToDetail) this.___mapUpdatePayloadToDetail = options.mappers.updatePayloadToDetail;
462
+ }
463
+ if (options.initialData) this.___data = [
464
+ ...options.initialData
465
+ ];
466
+ }
467
+ list = this.method('list', async ({ filter, pagination = {
468
+ pageSize: 1000,
469
+ zeroBasedIndex: 0
470
+ } })=>{
471
+ schemas.searchPayload.list.parse(filter);
472
+ Pagination.schema.parse(pagination);
473
+ const afterFiltration = this.___data.filter((x)=>this.___listSearchLogic(x, filter));
474
+ const afterPagination = afterFiltration.filter((_, i)=>i >= pagination.pageSize * pagination.zeroBasedIndex && i < (pagination.zeroBasedIndex + 1) * pagination.pageSize);
475
+ const result = afterPagination.map((x)=>this.___mapDetailToList(x));
476
+ zod.array(schemas.models.list).parse(result);
477
+ return result;
478
+ });
479
+ details = this.method('details', async ({ filter })=>{
480
+ const details = this.___data.find((x)=>this.___specificSearchLogic(x, filter));
481
+ if (!details) return null;
482
+ return details;
483
+ });
484
+ create = this.method('create', async ({ payload })=>{
485
+ const newItem = this.___mapCreatePayloadToDetail(payload);
486
+ this.___data = this.___data.concat(newItem);
487
+ return {
488
+ id: newItem.id
489
+ };
490
+ });
491
+ updateOne = this.method('updateOne', async ({ filter, payload })=>{
492
+ const index = this.___data.findIndex((x)=>this.___specificSearchLogic(x, filter));
493
+ this.___data = this.___data.map((x, i)=>{
494
+ if (i !== index) return x;
495
+ return this.___mapUpdatePayloadToDetail(x, payload);
496
+ });
497
+ return {
498
+ success: index > -1
499
+ };
500
+ });
501
+ deleteOne = this.method('deleteOne', async ({ filter })=>{
502
+ const index = this.___data.findIndex((x)=>this.___specificSearchLogic(x, filter));
503
+ this.___data = this.___data.filter((_x, i)=>i !== index);
504
+ return {
505
+ success: index > -1
506
+ };
507
+ });
508
+ }
509
+ return RAMStore;
510
+ };
511
+ export { store_namespaceObject as Store, value_objects_namespaceObject as ValueObjects, zod_controller_utils_namespaceObject as Controller, zod_module_utils_namespaceObject as Module };
@@ -0,0 +1,3 @@
1
+ export { type Types } from './store.shared-models.utils';
2
+ export * from './store.zod.utils';
3
+ export * from './store.ram.utils';
@@ -0,0 +1 @@
1
+ export {};