@opengis/fcore 0.0.1-beta.26 → 0.0.1-beta.27

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 (139) hide show
  1. package/LICENSE +3 -3
  2. package/README.md +71 -71
  3. package/dist/config.js +1 -1
  4. package/dist/context.js +1 -1
  5. package/dist/errors.js +1 -1
  6. package/dist/fastify.js +1 -1
  7. package/dist/fcore.js +1 -1
  8. package/dist/migrations/cli.js +1 -1
  9. package/dist/migrations/runner.js +1 -1
  10. package/dist/modules/auth/adduser-cli.js +1 -1
  11. package/dist/modules/auth/passwd-cli.js +1 -1
  12. package/dist/modules/auth/permission-cli.js +1 -1
  13. package/dist/modules/auth/route.js +1 -1
  14. package/dist/modules/auth/schema.js +1 -1
  15. package/dist/modules/auth/services/change-password.js +1 -1
  16. package/dist/modules/auth/services/get-current-user.js +1 -1
  17. package/dist/modules/auth/services/registration.js +1 -1
  18. package/dist/modules/auth/services/verify-two-factor.js +1 -1
  19. package/dist/modules/file/mime.js +1 -1
  20. package/dist/modules/file/route.js +1 -1
  21. package/dist/modules/file/schema.js +1 -1
  22. package/dist/modules/file/services/get-file.js +1 -1
  23. package/dist/modules/file/services/resize-file.js +1 -1
  24. package/dist/modules/file/services/upload-file.js +1 -1
  25. package/dist/modules/resource/route.d.ts.map +1 -1
  26. package/dist/modules/resource/route.js +1 -1
  27. package/dist/modules/resource/schema.d.ts +13 -0
  28. package/dist/modules/resource/schema.d.ts.map +1 -1
  29. package/dist/modules/resource/schema.js +1 -1
  30. package/dist/modules/resource/services/add-note.js +1 -1
  31. package/dist/modules/resource/services/add-resource-file.js +1 -1
  32. package/dist/modules/resource/services/create-resource-relation.js +1 -1
  33. package/dist/modules/resource/services/create-resource.js +1 -1
  34. package/dist/modules/resource/services/delete-resource-relation.js +1 -1
  35. package/dist/modules/resource/services/delete-resource.js +1 -1
  36. package/dist/modules/resource/services/export-resource.js +1 -1
  37. package/dist/modules/resource/services/generate-resource-code.d.ts +16 -0
  38. package/dist/modules/resource/services/generate-resource-code.d.ts.map +1 -0
  39. package/dist/modules/resource/services/generate-resource-code.js +1 -0
  40. package/dist/modules/resource/services/get-resource-schema.d.ts +6 -0
  41. package/dist/modules/resource/services/get-resource-schema.d.ts.map +1 -0
  42. package/dist/modules/resource/services/get-resource-schema.js +1 -0
  43. package/dist/modules/resource/services/get-resource.js +1 -1
  44. package/dist/modules/resource/services/list-resource-as-user.d.ts +8 -0
  45. package/dist/modules/resource/services/list-resource-as-user.d.ts.map +1 -0
  46. package/dist/modules/resource/services/list-resource-as-user.js +1 -0
  47. package/dist/modules/resource/services/list-resource-list.d.ts +20 -0
  48. package/dist/modules/resource/services/list-resource-list.d.ts.map +1 -0
  49. package/dist/modules/resource/services/list-resource-list.js +1 -0
  50. package/dist/modules/resource/services/list-resource-relation.js +1 -1
  51. package/dist/modules/resource/services/list-resources.d.ts.map +1 -1
  52. package/dist/modules/resource/services/list-resources.js +1 -1
  53. package/dist/modules/resource/services/search-resource.js +1 -1
  54. package/dist/modules/resource/services/suggest-resource.js +1 -1
  55. package/dist/modules/resource/services/update-resource-relation.js +1 -1
  56. package/dist/modules/resource/services/update-resource.js +1 -1
  57. package/dist/modules/resource/services/upload-resource-file.js +1 -1
  58. package/dist/modules/system/route.d.ts.map +1 -1
  59. package/dist/modules/system/route.js +1 -1
  60. package/dist/modules/system/schema.d.ts +22 -0
  61. package/dist/modules/system/schema.d.ts.map +1 -1
  62. package/dist/modules/system/schema.js +1 -1
  63. package/dist/modules/system/services/check-system.js +1 -1
  64. package/dist/modules/system/services/get-access.js +1 -1
  65. package/dist/modules/system/services/get-api-list.js +1 -1
  66. package/dist/modules/system/services/get-audit-log.js +1 -1
  67. package/dist/modules/system/services/get-dictionary.js +1 -1
  68. package/dist/modules/system/services/get-resource-access.d.ts +23 -0
  69. package/dist/modules/system/services/get-resource-access.d.ts.map +1 -0
  70. package/dist/modules/system/services/get-resource-access.js +1 -0
  71. package/dist/modules/system/services/get-resource-scopes.d.ts +16 -0
  72. package/dist/modules/system/services/get-resource-scopes.d.ts.map +1 -0
  73. package/dist/modules/system/services/get-resource-scopes.js +1 -0
  74. package/dist/modules/system/services/get-system-log.js +1 -1
  75. package/dist/modules/system/services/get-system-settings.js +1 -1
  76. package/dist/modules/system/services/list-dictionaries.js +1 -1
  77. package/dist/modules/system/services/set-access.d.ts +1 -0
  78. package/dist/modules/system/services/set-access.d.ts.map +1 -1
  79. package/dist/modules/system/services/set-access.js +1 -1
  80. package/dist/modules/system/services/set-resource-access.d.ts +18 -0
  81. package/dist/modules/system/services/set-resource-access.d.ts.map +1 -0
  82. package/dist/modules/system/services/set-resource-access.js +1 -0
  83. package/dist/modules/system/services/set-resource-scopes.d.ts +10 -0
  84. package/dist/modules/system/services/set-resource-scopes.d.ts.map +1 -0
  85. package/dist/modules/system/services/set-resource-scopes.js +1 -0
  86. package/dist/modules/system/services/update-dictionary.js +1 -1
  87. package/dist/modules/system/services/update-system-settings.js +1 -1
  88. package/dist/modules/utils/require-admin.js +1 -1
  89. package/dist/modules/utils/safe-user.js +1 -1
  90. package/dist/modules/utils/unsupported.js +1 -1
  91. package/dist/plugins/audit/audit.js +1 -1
  92. package/dist/plugins/audit/services/write-audit.js +1 -1
  93. package/dist/plugins/auth/get-user-permissions.js +1 -1
  94. package/dist/plugins/auth/index.js +1 -1
  95. package/dist/plugins/auth/verifyUser.js +1 -1
  96. package/dist/plugins/dictionary.js +1 -1
  97. package/dist/plugins/file.js +1 -1
  98. package/dist/plugins/jwt.js +1 -1
  99. package/dist/plugins/logger/index.js +1 -1
  100. package/dist/plugins/logger/transport.js +1 -1
  101. package/dist/plugins/pg.js +1 -1
  102. package/dist/plugins/redis.js +1 -1
  103. package/dist/plugins/resource/resource.js +1 -1
  104. package/dist/plugins/resource/resource.registry.js +1 -1
  105. package/dist/plugins/resource/resource.types.d.ts +18 -0
  106. package/dist/plugins/resource/resource.types.d.ts.map +1 -1
  107. package/dist/plugins/resource/services/add-dictionary-lookup-data.js +1 -1
  108. package/dist/plugins/resource/services/add-file-token.js +1 -1
  109. package/dist/plugins/resource/services/add-table-lookup-data.js +1 -1
  110. package/dist/plugins/resource/services/create-relation.js +1 -1
  111. package/dist/plugins/resource/services/create.js +1 -1
  112. package/dist/plugins/resource/services/delete-relation.js +1 -1
  113. package/dist/plugins/resource/services/delete.js +1 -1
  114. package/dist/plugins/resource/services/find-one.d.ts.map +1 -1
  115. package/dist/plugins/resource/services/find-one.js +1 -1
  116. package/dist/plugins/resource/services/find-relation.js +1 -1
  117. package/dist/plugins/resource/services/find.d.ts.map +1 -1
  118. package/dist/plugins/resource/services/find.js +1 -1
  119. package/dist/plugins/resource/services/get-table-columns.js +1 -1
  120. package/dist/plugins/resource/services/update-relation.js +1 -1
  121. package/dist/plugins/resource/services/update.js +1 -1
  122. package/dist/plugins/resource/utils/auto-index.js +1 -1
  123. package/dist/plugins/resource/utils/fields.js +1 -1
  124. package/dist/plugins/resource/utils/filters.js +1 -1
  125. package/dist/plugins/resource/utils/permissions.js +1 -1
  126. package/dist/plugins/resource/utils/scope.d.ts +10 -0
  127. package/dist/plugins/resource/utils/scope.d.ts.map +1 -0
  128. package/dist/plugins/resource/utils/scope.js +1 -0
  129. package/dist/plugins/resource/utils/sort.js +1 -1
  130. package/dist/plugins/resource/utils/sql.js +1 -1
  131. package/dist/plugins/resource/utils/summary.d.ts +5 -1
  132. package/dist/plugins/resource/utils/summary.d.ts.map +1 -1
  133. package/dist/plugins/resource/utils/summary.js +1 -1
  134. package/dist/shared/getIP.js +1 -1
  135. package/migrations/20260903130000_move_notes_files_to_admin.sql +17 -17
  136. package/migrations/20260903140000_settings_nulls_not_distinct.sql +18 -18
  137. package/migrations/20260929120000_allow_user_only_role_scopes.sql +2 -0
  138. package/migrations/20260929_role_scope.sql +32 -0
  139. package/package.json +92 -92
package/LICENSE CHANGED
@@ -1,3 +1,3 @@
1
- Copyright (c) OpenGIS. All rights reserved.
2
-
3
- Proprietary and confidential.
1
+ Copyright (c) OpenGIS. All rights reserved.
2
+
3
+ Proprietary and confidential.
package/README.md CHANGED
@@ -1,72 +1,72 @@
1
- # @opengis/fcore
2
-
3
- Reusable backend foundation for OpenGIS Node.js applications: config, typed application context, PostgreSQL, Redis, S3 file storage, audit, trusted Resource CRUD, Core modules, Fastify integration and SQL migration runner.
4
-
5
- ## Install
6
-
7
- ```bash
8
- npm install @opengis/fcore
9
- ```
10
-
11
- ## Bootstrap
12
-
13
- ```ts
14
- import { createFCore } from '@opengis/fcore';
15
- import resources from './resources/index.js';
16
-
17
- export const ctx = await createFCore({ resources });
18
- ```
19
-
20
- ```ts
21
- import Fastify from 'fastify';
22
- import fcoreFastify from '@opengis/fcore/fastify';
23
- import { ctx } from './app.js';
24
-
25
- const app = Fastify();
26
- await app.register(fcoreFastify, { ctx });
27
- await app.listen({ port: ctx.config.port });
28
- ```
29
-
30
- ## Resource
31
-
32
- All dynamic table/column identifiers come from registered `ResourceContract` metadata. Values are SQL parameters.
33
-
34
- ## Migrations
35
-
36
- Project SQL files stay in `./migrations`. Build the package/application, then run `fcore-migrate` or import `runMigrations()`.
37
-
38
- ## Module service convention
39
-
40
- Module services are plain async functions with the canonical `service(params, ctx)` signature. `ctx` is passed explicitly from `fastify.ts` to each module `route.ts`; there is no `service.ts` or `createService()` factory.
41
-
42
- ## Structure
43
-
44
- ```bash
45
- @opengis/fcore
46
- ├── src/
47
- │ ├── plugins/
48
- │ │ ├── logger/
49
- │ │ ├── redis/
50
- │ │ ├── pg/
51
- │ │ ├── file/
52
- │ │ ├── audit/
53
- │ │ └── resource/
54
- │ ├── modules/
55
- │ │ ├── auth/
56
- │ │ ├── access/
57
- │ │ ├── resource/
58
- │ │ ├── file/
59
- │ │ ├── template/
60
- │ │ └── system/
61
- │ ├── migrations/
62
- │ ├── config.ts # loadConfig
63
- │ ├── context.ts # createContext, set, get
64
- │ ├── errors.ts # standard Errors
65
- │ ├── fastify.ts # fastify Plugins
66
- │ ├── fcore.ts # createFcore
67
- │ └── index.ts # export type, methods, etc
68
- ├── test/
69
- ├── engineering/
70
- ├── package.json
71
- └── tsconfig.json
1
+ # @opengis/fcore
2
+
3
+ Reusable backend foundation for OpenGIS Node.js applications: config, typed application context, PostgreSQL, Redis, S3 file storage, audit, trusted Resource CRUD, Core modules, Fastify integration and SQL migration runner.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @opengis/fcore
9
+ ```
10
+
11
+ ## Bootstrap
12
+
13
+ ```ts
14
+ import { createFCore } from '@opengis/fcore';
15
+ import resources from './resources/index.js';
16
+
17
+ export const ctx = await createFCore({ resources });
18
+ ```
19
+
20
+ ```ts
21
+ import Fastify from 'fastify';
22
+ import fcoreFastify from '@opengis/fcore/fastify';
23
+ import { ctx } from './app.js';
24
+
25
+ const app = Fastify();
26
+ await app.register(fcoreFastify, { ctx });
27
+ await app.listen({ port: ctx.config.port });
28
+ ```
29
+
30
+ ## Resource
31
+
32
+ All dynamic table/column identifiers come from registered `ResourceContract` metadata. Values are SQL parameters.
33
+
34
+ ## Migrations
35
+
36
+ Project SQL files stay in `./migrations`. Build the package/application, then run `fcore-migrate` or import `runMigrations()`.
37
+
38
+ ## Module service convention
39
+
40
+ Module services are plain async functions with the canonical `service(params, ctx)` signature. `ctx` is passed explicitly from `fastify.ts` to each module `route.ts`; there is no `service.ts` or `createService()` factory.
41
+
42
+ ## Structure
43
+
44
+ ```bash
45
+ @opengis/fcore
46
+ ├── src/
47
+ │ ├── plugins/
48
+ │ │ ├── logger/
49
+ │ │ ├── redis/
50
+ │ │ ├── pg/
51
+ │ │ ├── file/
52
+ │ │ ├── audit/
53
+ │ │ └── resource/
54
+ │ ├── modules/
55
+ │ │ ├── auth/
56
+ │ │ ├── access/
57
+ │ │ ├── resource/
58
+ │ │ ├── file/
59
+ │ │ ├── template/
60
+ │ │ └── system/
61
+ │ ├── migrations/
62
+ │ ├── config.ts # loadConfig
63
+ │ ├── context.ts # createContext, set, get
64
+ │ ├── errors.ts # standard Errors
65
+ │ ├── fastify.ts # fastify Plugins
66
+ │ ├── fcore.ts # createFcore
67
+ │ └── index.ts # export type, methods, etc
68
+ ├── test/
69
+ ├── engineering/
70
+ ├── package.json
71
+ └── tsconfig.json
72
72
  ```
package/dist/config.js CHANGED
@@ -1 +1 @@
1
- import'dotenv/config';const DEFAULT_LOG_RESPONSE_STATUS_CODES=[0x193,0x199,0x19d,0x19f,0x1ad];function required(w){const h=process.env[w];if(!h)throw new Error('Missing\x20environment\x20variable:\x20'+w);return h;}function z(){const Y=['false','./storage','split','includes','true','auth'];z=function(){return Y;};return z();}function G(w,h){w=w-0xe9;const S=z();let X=S[w];return X;}export function loadConfig(w={}){const X=G,h={'env':process.env.NODE_ENV??'development','debug':process.env.DEBUG==='true','port':Number(process.env.PORT??0xbb8),'maxFileSize':+(process.env.MAX_FILE_SIZE||0x200),'rateLimit':{'disabled':process.env.RATE_LIMIT===X(0xe9),'max':+(process.env.RATE_LIMIT_MAX||0x64),'timeWindow':+(process.env.RATE_LIMIT_TIME_WINDOW||0xea60)},'storageType':(process.env.STORAGE_TYPE??'s3')['toLowerCase']()==='local'||!process.env.S3_ENDPOINT?'local':'s3','storagePath':process.env.STORAGE_PATH??X(0xea),'redactionList':(process.env.REDACTION_LIST||'password')[X(0xeb)](','),'logger':{'level':process.env.LOG_LEVEL??'info','responses':process.env.LOG_RESPONSES==='true'?!![]:![],'responseCodes':process.env.LOG_RESPONSE_STATUS_CODES?process.env.LOG_RESPONSE_STATUS_CODES['split'](',')['map'](S=>S-0x0):DEFAULT_LOG_RESPONSE_STATUS_CODES,'directory':process.env.LOG_DIRECTORY||process['cwd']()+'/log'},'pg':{'host':process.env.PG_HOST??'localhost','port':Number(process.env.PG_PORT??0x1538),'database':process.env.PG_DATABASE??'','user':process.env.PG_USER??'','password':process.env.PG_PASSWORD??''},'redis':{'host':process.env.REDIS_HOST??'','port':Number(process.env.REDIS_PORT??0x18eb),'password':process.env.REDIS_PASSWORD,'lazyConnect':!![],'db':process.env.REDIS_DB?Number(process.env.REDIS_DB):undefined},'s3':{'endpoint':process.env.S3_ENDPOINT,'region':process.env.S3_REGION??'us-east-1','bucket':process.env.S3_BUCKET??'','accessKey':process.env.S3_ACCESS_KEY,'secretKey':process.env.S3_SECRET_KEY,'folder':process.env.S3_FOLDER,'forcePathStyle':process.env.S3_FORCE_PATH_STYLE!=='false','tokenSecret':process.env.FILE_TOKEN_SECRET,'tokenTtl':Number(process.env.FILE_TOKEN_TTL??0xe10)},'auth':{'accessToken':process.env.AUTH_ACCESS_TOKEN||'Ch7QR4e73Jg0wx0xOjm','user':process.env.AUTH_USER?JSON['parse'](process.env.AUTH_USER):undefined,'sessionTimeout':+(process.env.AUTH_SESSION_TIMEOUT||0x258),'secret':process.env.AUTH_SECRET??'x5y30KBsEKCENT04tu6549Vxx3No1ztJ2q2K8r79S59420RaZ5','cookieName':process.env.AUTH_COOKIE_NAME??'session_user_auth','jwtSecret':process.env.AUTH_JWT_SECRET??'0ua4b1Tz21m47z13U3EO0uN9e0WE7hqRFbcZ72cbdWqZBzemf9cAU865xan1s81TdNpUKKfF','redirect':process.env.AUTH_REDIRECT??'/','twoFactorRedirect':process.env.AUTH_TWOFACTOR_REDIRECT??'/','cookieOptions':process.env.AUTH_COOKIE_OPTIONS_DOMAIN?{'domain':process.env.AUTH_COOKIE_OPTIONS_DOMAIN,'path':process.env.AUTH_COOKIE_OPTIONS_PATH||'/','httpOnly':Boolean(process.env.AUTH_COOKIE_OPTIONS_HTTP_ONLY||'true'),'secure':Boolean(process.env.AUTH_COOKIE_OPTIONS_SECURE||'true'),'sameSite':process.env.AUTH_COOKIE_OPTIONS_SAME_SITE&&['lax','strict','none'][X(0xec)](process.env.AUTH_COOKIE_OPTIONS_SAME_SITE)?process.env.AUTH_COOKIE_OPTIONS_SAME_SITE:Boolean(process.env.AUTH_COOKIE_OPTIONS_SAME_SITE||X(0xed))}:{'path':'/','httpOnly':!![],'secure':![],'sameSite':!![]}}};return{...h,...w,'logger':{...h['logger'],...w['logger']},'pg':{...h['pg'],...w['pg']},'redis':{...h['redis'],...w['redis']},'s3':{...h['s3'],...w['s3']},'auth':{...h['auth'],...w[X(0xee)]}};}export{required as requireEnv};
1
+ import'dotenv/config';const DEFAULT_LOG_RESPONSE_STATUS_CODES=[0x193,0x199,0x19d,0x19f,0x1ad];function required(h){const n=process.env[h];if(!n)throw new Error('Missing\x20environment\x20variable:\x20'+h);return n;}function Q(){const f=['./storage','split','true','map','parse','x5y30KBsEKCENT04tu6549Vxx3No1ztJ2q2K8r79S59420RaZ5','session_user_auth','0ua4b1Tz21m47z13U3EO0uN9e0WE7hqRFbcZ72cbdWqZBzemf9cAU865xan1s81TdNpUKKfF','strict','auth'];Q=function(){return f;};return Q();}export function loadConfig(h={}){const G=k,n={'env':process.env.NODE_ENV??'development','debug':process.env.DEBUG==='true','port':Number(process.env.PORT??0xbb8),'maxFileSize':+(process.env.MAX_FILE_SIZE||0x200),'rateLimit':{'disabled':process.env.RATE_LIMIT==='false','max':+(process.env.RATE_LIMIT_MAX||0x64),'timeWindow':+(process.env.RATE_LIMIT_TIME_WINDOW||0xea60)},'storageType':(process.env.STORAGE_TYPE??'s3')['toLowerCase']()==='local'||!process.env.S3_ENDPOINT?'local':'s3','storagePath':process.env.STORAGE_PATH??G(0x19c),'redactionList':(process.env.REDACTION_LIST||'password')[G(0x19d)](','),'logger':{'level':process.env.LOG_LEVEL??'info','responses':process.env.LOG_RESPONSES===G(0x19e)?!![]:![],'responseCodes':process.env.LOG_RESPONSE_STATUS_CODES?process.env.LOG_RESPONSE_STATUS_CODES['split'](',')[G(0x19f)](B=>B-0x0):DEFAULT_LOG_RESPONSE_STATUS_CODES,'directory':process.env.LOG_DIRECTORY||process['cwd']()+'/log'},'pg':{'host':process.env.PG_HOST??'localhost','port':Number(process.env.PG_PORT??0x1538),'database':process.env.PG_DATABASE??'','user':process.env.PG_USER??'','password':process.env.PG_PASSWORD??''},'redis':{'host':process.env.REDIS_HOST??'','port':Number(process.env.REDIS_PORT??0x18eb),'password':process.env.REDIS_PASSWORD,'lazyConnect':!![],'db':process.env.REDIS_DB?Number(process.env.REDIS_DB):undefined},'s3':{'endpoint':process.env.S3_ENDPOINT,'region':process.env.S3_REGION??'us-east-1','bucket':process.env.S3_BUCKET??'','accessKey':process.env.S3_ACCESS_KEY,'secretKey':process.env.S3_SECRET_KEY,'folder':process.env.S3_FOLDER,'forcePathStyle':process.env.S3_FORCE_PATH_STYLE!=='false','tokenSecret':process.env.FILE_TOKEN_SECRET,'tokenTtl':Number(process.env.FILE_TOKEN_TTL??0xe10)},'auth':{'accessToken':process.env.AUTH_ACCESS_TOKEN||'Ch7QR4e73Jg0wx0xOjm','user':process.env.AUTH_USER?JSON[G(0x1a0)](process.env.AUTH_USER):undefined,'sessionTimeout':+(process.env.AUTH_SESSION_TIMEOUT||0x258),'secret':process.env.AUTH_SECRET??G(0x1a1),'cookieName':process.env.AUTH_COOKIE_NAME??G(0x1a2),'jwtSecret':process.env.AUTH_JWT_SECRET??G(0x1a3),'redirect':process.env.AUTH_REDIRECT??'/','twoFactorRedirect':process.env.AUTH_TWOFACTOR_REDIRECT??'/','cookieOptions':process.env.AUTH_COOKIE_OPTIONS_DOMAIN?{'domain':process.env.AUTH_COOKIE_OPTIONS_DOMAIN,'path':process.env.AUTH_COOKIE_OPTIONS_PATH||'/','httpOnly':Boolean(process.env.AUTH_COOKIE_OPTIONS_HTTP_ONLY||'true'),'secure':Boolean(process.env.AUTH_COOKIE_OPTIONS_SECURE||'true'),'sameSite':process.env.AUTH_COOKIE_OPTIONS_SAME_SITE&&['lax',G(0x1a4),'none']['includes'](process.env.AUTH_COOKIE_OPTIONS_SAME_SITE)?process.env.AUTH_COOKIE_OPTIONS_SAME_SITE:Boolean(process.env.AUTH_COOKIE_OPTIONS_SAME_SITE||'true')}:{'path':'/','httpOnly':!![],'secure':![],'sameSite':!![]}}};return{...n,...h,'logger':{...n['logger'],...h['logger']},'pg':{...n['pg'],...h['pg']},'redis':{...n['redis'],...h['redis']},'s3':{...n['s3'],...h['s3']},'auth':{...n[G(0x1a5)],...h['auth']}};}function k(h,n){h=h-0x19c;const B=Q();let G=B[h];return G;}export{required as requireEnv};
package/dist/context.js CHANGED
@@ -1 +1 @@
1
- let defaultContext;function G(w,h){w=w-0xf2;const S=z();let X=S[w];return X;}function z(){const X=['Application\x20context\x20is\x20not\x20initialized','close'];z=function(){return X;};return z();}export function setContext(w){defaultContext=w;}export function getContext(){const h=G;if(!defaultContext)throw new Error(h(0xf2));return defaultContext;}export function createContext(w){return{...w,async 'close'(){const S=G;await Promise['allSettled']([w['redis']?.[S(0xf3)](),w['pg']?.['end']()]),await w['logger']['close']();}};}
1
+ let defaultContext;function k(h,n){h=h-0x1e9;const B=Q();let G=B[h];return G;}function Q(){const B=['Application\x20context\x20is\x20not\x20initialized'];Q=function(){return B;};return Q();}export function setContext(h){defaultContext=h;}export function getContext(){const n=k;if(!defaultContext)throw new Error(n(0x1e9));return defaultContext;}export function createContext(h){return{...h,async 'close'(){await Promise['allSettled']([h['redis']?.['close'](),h['pg']?.['end']()]),await h['logger']['close']();}};}
package/dist/errors.js CHANGED
@@ -1 +1 @@
1
- function G(w,h){w=w-0x112;var S=z();var X=S[w];return X;}var Y=G;export class FCoreError extends Error{['code'];['statusCode'];[Y(0x112)];constructor(w,h,S=0x1f4,X){var v=Y;super(h),this[v(0x113)]=w,this[v(0x114)]=S,this['details']=X,this['name']=new.target.name;}}export class BadRequestError extends FCoreError{constructor(w,h){super('BAD_REQUEST_ERROR',w,0x190,h);}}export class UnauthorizedError extends FCoreError{constructor(w='Authentication\x20required'){super('UNAUTHORIZED',w,0x191);}}export class ForbiddenError extends FCoreError{constructor(w='Access\x20denied'){var D=Y;super(D(0x115),w,0x193);}}export class NotFoundError extends FCoreError{constructor(w='Not\x20found'){super('NOT_FOUND',w,0x194);}}export class ConflictError extends FCoreError{constructor(w='Conflict'){var o=Y;super(o(0x116),w,0x199);}}export class ValidationError extends FCoreError{constructor(w,h){super('VALIDATION_ERROR',w,0x1a6,h);}}export class UnsupportedError extends FCoreError{constructor(w='Operation\x20is\x20not\x20configured'){super('UNSUPPORTED',w,0x1f5);}}function z(){var q=['details','code','statusCode','FORBIDDEN','CONFLICT'];z=function(){return q;};return z();}
1
+ var f=k;export class FCoreError extends Error{[f(0x151)];['statusCode'];['details'];constructor(h,n,B=0x1f4,G){var j=f;super(n),this[j(0x151)]=h,this[j(0x152)]=B,this['details']=G,this[j(0x153)]=new.target.name;}}function Q(){var P=['code','statusCode','name','BAD_REQUEST_ERROR','FORBIDDEN','Not\x20found','Conflict','CONFLICT'];Q=function(){return P;};return Q();}export class BadRequestError extends FCoreError{constructor(h,n){var Z=f;super(Z(0x154),h,0x190,n);}}function k(h,n){h=h-0x151;var B=Q();var G=B[h];return G;}export class UnauthorizedError extends FCoreError{constructor(h='Authentication\x20required'){super('UNAUTHORIZED',h,0x191);}}export class ForbiddenError extends FCoreError{constructor(h='Access\x20denied'){var e=f;super(e(0x155),h,0x193);}}export class NotFoundError extends FCoreError{constructor(h=f(0x156)){super('NOT_FOUND',h,0x194);}}export class ConflictError extends FCoreError{constructor(h=f(0x157)){var b=f;super(b(0x158),h,0x199);}}export class ValidationError extends FCoreError{constructor(h,n){super('VALIDATION_ERROR',h,0x1a6,n);}}export class UnsupportedError extends FCoreError{constructor(h='Operation\x20is\x20not\x20configured'){super('UNSUPPORTED',h,0x1f5);}}
package/dist/fastify.js CHANGED
@@ -1 +1 @@
1
- import w from'fastify-plugin';import{FCoreError}from'./errors.js';import{authRoutes}from'./modules/auth/route.js';import{fileRoutes}from'./modules/file/route.js';import{resourceRoutes}from'./modules/resource/route.js';import{systemRoutes}from'./modules/system/route.js';import{createSessionStore}from'./plugins/auth/index.js';import{ForbiddenError}from'./errors.js';import{jwtVerifyToken}from'./plugins/jwt.js';function urlencodedContentParser(h,S,X){const H=G,Y=decodeURIComponent(S[H(0x12a)]())['split']('&')['reduce']((v,D)=>{const R=H,[o,q]=D[R(0x12b)]('=');return{...v,[o]:q};},{});X(null,Y);}function G(w,h){w=w-0x12a;const S=z();let X=S[w];return X;}function z(){const d=['toString','split','method','url','get','config','auth','headers','authorization','startsWith','user','access','permissions','type','admin','params','maxFileSize','setErrorHandler','FST_ERR_VALIDATION','statusCode','code','send','resource','system','addContentTypeParser','max'];z=function(){return d;};return z();}export default function fcoreFastify(h,S){return w(async X=>{const x=G;X['decorate']('ctx',h);const {config:Y}=h,v=new Map();X['addHook']('onRoute',o=>{const Q=G,q=o['schema'],e=Array['isArray'](o['method'])?o[Q(0x12c)]:[o['method']];for(const Z of e){if(Z==='HEAD')continue;const K={'method':Z,'endpoint':o['url'],'package':q?.['package']??'fcore','tags':q?.['tags']??[],'summary':q?.['summary']??'','description':q?.['description']??'','access':q?.['access']??'public','permissions':q?.['permissions']??[]};v['set'](Z+'\x20'+o['url'],K);}}),X['addHook']('preHandler',async o=>{const P=G;if(o['routeOptions'][P(0x12d)]==='*')return!![];const q=v[P(0x12e)](o[P(0x12c)]+'\x20'+o['routeOptions']['url']),e=!o['user']&&process['platform']==='win32'&&h[P(0x12f)]?.['auth']?.['user']?h['config']?.[P(0x130)]?.['user']:null,Z=o['raw'][P(0x131)]?.[P(0x132)],K=Z?.[P(0x133)]('Bearer\x20')?Z['slice'](0x7):null,y=o['user']??(K?await jwtVerifyToken(K):e);!o['user']&&K&&process.env.AUTH_JWT_SECRET&&(o[P(0x134)]=await jwtVerifyToken(K));if(!q?.['access'])throw new ForbiddenError('Route\x20access\x20not\x20defined');if(q['access']==='public')return!![];if(!y)throw new ForbiddenError('User\x20required');if(q[P(0x135)]==='user'&&!q[P(0x136)]?.['length'])return!![];if(y[P(0x137)]==P(0x138))return!![];if(q['access']===P(0x138))throw new ForbiddenError('Admin\x20access\x20required');for(const V of q[P(0x136)]){const O=V?.['replace']('$resource',o[P(0x139)]['resource']??'');if(!y[P(0x136)]?.['includes'](O))throw new ForbiddenError('Missing\x20permission:\x20'+O);}return!![];}),await createSessionStore(X,h),await X['register'](import('@fastify/multipart'),{'limits':{'fileSize':Y[x(0x13a)]*0x400*0x400}}),X[x(0x13b)]((o,q,e)=>{const c=x;if(o instanceof FCoreError||o['code']===c(0x13c)||o[c(0x13d)]<0x1f4)return o['statusCode']<0x1f4&&h['logger']['warn'](o),e[c(0x13e)](o['statusCode'])[c(0x13f)]({'error':o['code'],'message':o['message'],'details':o['details']});return h['logger']['error'](o),(Y['debug']||process.env.NODE_ENV==='test'||process.env.VITEST)&&console['error'](o),e[c(0x13e)](0x1f4)['send']({'error':'INTERNAL_ERROR','message':'Internal\x20server\x20error'});});const D=o=>!S||S['includes'](o);if(D('auth'))await X['register'](authRoutes(h));if(D(x(0x140)))await X['register'](resourceRoutes(h));if(D('file'))await X['register'](fileRoutes(h));if(D(x(0x141)))await X['register'](systemRoutes(h,v));X[x(0x142)]('application/x-www-form-urlencoded',{'parseAs':'buffer'},urlencodedContentParser),!Y['rateLimit']?.['disabled']?X['register'](import('@fastify/rate-limit'),{'max':Y['rateLimit']?.[x(0x143)]||0x64,'timeWindow':Y['rateLimit']?.['timeWindow']||0xea60,'hook':'preHandler','global':!![],'keyGenerator':o=>(o['user']?.['id']||o['ip'])+'-'+o['raw'][x(0x12d)][x(0x12b)]('?')[0x0]}):console['log']('⚠️\x20rate\x20limit\x20is\x20disabled');});}
1
+ import h from'fastify-plugin';import{FCoreError}from'./errors.js';function k(h,n){h=h-0x162;const B=Q();let G=B[h];return G;}import{authRoutes}from'./modules/auth/route.js';import{fileRoutes}from'./modules/file/route.js';import{resourceRoutes}from'./modules/resource/route.js';import{systemRoutes}from'./modules/system/route.js';import{createSessionStore}from'./plugins/auth/index.js';import{ForbiddenError}from'./errors.js';function Q(){const O=['reduce','onRoute','method','summary','description','url','win32','user','config','headers','authorization','startsWith','Bearer\x20','length','admin','$resource','maxFileSize','setErrorHandler','logger','message','details','error','code','send','auth','resource','register','application/x-www-form-urlencoded','buffer','disabled','@fastify/rate-limit','rateLimit','timeWindow','split','log'];Q=function(){return O;};return Q();}import{jwtVerifyToken}from'./plugins/jwt.js';function urlencodedContentParser(n,B,G){const z=k,f=decodeURIComponent(B['toString']())['split']('&')[z(0x162)]((j,Z)=>{const [e,b]=Z['split']('=');return{...j,[e]:b};},{});G(null,f);}export default function fcoreFastify(n,B){return h(async G=>{const t=k;G['decorate']('ctx',n);const {config:f}=n,j=new Map();G['addHook'](t(0x163),e=>{const m=t,b=e['schema'],P=Array['isArray'](e['method'])?e[m(0x164)]:[e[m(0x164)]];for(const u of P){if(u==='HEAD')continue;const X={'method':u,'endpoint':e['url'],'package':b?.['package']??'fcore','tags':b?.['tags']??[],'summary':b?.[m(0x165)]??'','description':b?.[m(0x166)]??'','access':b?.['access']??'public','permissions':b?.['permissions']??[]};j['set'](u+'\x20'+e['url'],X);}}),G['addHook']('preHandler',async e=>{const A=t;if(e['routeOptions']['url']==='*')return!![];const b=j['get'](e['method']+'\x20'+e['routeOptions'][A(0x167)]),P=!e['user']&&process['platform']===A(0x168)&&n['config']?.['auth']?.[A(0x169)]?n[A(0x16a)]?.['auth']?.['user']:null,u=e['raw'][A(0x16b)]?.[A(0x16c)],X=u?.[A(0x16d)](A(0x16e))?u['slice'](0x7):null,H=e[A(0x169)]??(X?await jwtVerifyToken(X):P);!e['user']&&X&&process.env.AUTH_JWT_SECRET&&(e[A(0x169)]=await jwtVerifyToken(X));if(!b?.['access'])throw new ForbiddenError('Route\x20access\x20not\x20defined');if(b['access']==='public')return!![];if(!H)throw new ForbiddenError('User\x20required');if(b['access']===A(0x169)&&!b['permissions']?.[A(0x16f)])return!![];if(H['type']==A(0x170))return!![];if(b['access']==='admin')throw new ForbiddenError('Admin\x20access\x20required');for(const i of b['permissions']){const p=i?.['replace'](A(0x171),e['params']['resource']??'');if(!H['permissions']?.['includes'](p))throw new ForbiddenError('Missing\x20permission:\x20'+p);}return!![];}),await createSessionStore(G,n),await G['register'](import('@fastify/multipart'),{'limits':{'fileSize':f[t(0x172)]*0x400*0x400}}),G[t(0x173)]((e,b,P)=>{const U=t;if(e instanceof FCoreError||e['code']==='FST_ERR_VALIDATION'||e['statusCode']<0x1f4)return e['statusCode']<0x1f4&&n[U(0x174)]['warn'](e),P['code'](e['statusCode'])['send']({'error':e['code'],'message':e[U(0x175)],'details':e[U(0x176)]});return n['logger'][U(0x177)](e),(f['debug']||process.env.NODE_ENV==='test'||process.env.VITEST)&&console[U(0x177)](e),P[U(0x178)](0x1f4)[U(0x179)]({'error':'INTERNAL_ERROR','message':'Internal\x20server\x20error'});});const Z=e=>!B||B['includes'](e);if(Z(t(0x17a)))await G['register'](authRoutes(n));if(Z(t(0x17b)))await G['register'](resourceRoutes(n));if(Z('file'))await G[t(0x17c)](fileRoutes(n));if(Z('system'))await G[t(0x17c)](systemRoutes(n,j));G['addContentTypeParser'](t(0x17d),{'parseAs':t(0x17e)},urlencodedContentParser),!f['rateLimit']?.[t(0x17f)]?G['register'](import(t(0x180)),{'max':f[t(0x181)]?.['max']||0x64,'timeWindow':f['rateLimit']?.[t(0x182)]||0xea60,'hook':'preHandler','global':!![],'keyGenerator':e=>(e['user']?.['id']||e['ip'])+'-'+e['raw'][t(0x167)][t(0x183)]('?')[0x0]}):console[t(0x184)]('⚠️\x20rate\x20limit\x20is\x20disabled');});}
package/dist/fcore.js CHANGED
@@ -1 +1 @@
1
- import{loadConfig}from'./config.js';function z(){const K=['local','tokenSecret','tokenTtl','endpoint','region','dictionaries','resources'];z=function(){return K;};return z();}import{createContext,setContext}from'./context.js';import{createAudit,createDatabase,createDictionary,createFileLocal,createFileS3,createLogger,createRedis,createResource}from'./plugins/index.js';function G(w,h){w=w-0x97;const S=z();let X=S[w];return X;}export async function createFCore(w={}){const Z=G,h=loadConfig(w['config']),S=createRedis(h['redis']),X=createLogger(),Y=createDatabase(h['pg']),v=h['storageType']===Z(0x97)?createFileLocal({'storagePath':h['storagePath'],'folder':h['s3']['folder'],'tokenSecret':h['s3'][Z(0x98)],'tokenTtl':h['s3'][Z(0x99)]}):createFileS3({'endpoint':h['s3'][Z(0x9a)],'region':h['s3'][Z(0x9b)],'bucket':h['s3']['bucket'],'accessKey':h['s3']['accessKey'],'secretKey':h['s3']['secretKey'],'folder':h['s3']['folder'],'forcePathStyle':h['s3']['forcePathStyle'],'tokenSecret':h['s3']['tokenSecret'],'tokenTtl':h['s3']['tokenTtl']}),D=createAudit({'pg':Y,'logger':X}),o=createDictionary({'pg':Y,'dictionaries':w[Z(0x9c)]}),q=createResource({'pg':Y,'logger':X,'audit':D,'dictionary':o,'file':v});w[Z(0x9d)]?.['length']&&q['register'](w[Z(0x9d)]);const e=createContext({'config':h,'logger':X,'redis':S,'pg':Y,'file':v,'resource':q,'audit':D,'dictionary':o});return setContext(e),e;}
1
+ function k(h,n){h=h-0x156;const B=Q();let G=B[h];return G;}import{loadConfig}from'./config.js';import{createContext,setContext}from'./context.js';function Q(){const X=['folder','tokenTtl','region','tokenSecret','dictionaries','length','register'];Q=function(){return X;};return Q();}import{createAudit,createDatabase,createDictionary,createFileLocal,createFileS3,createLogger,createRedis,createResource}from'./plugins/index.js';export async function createFCore(h={}){const u=k,n=loadConfig(h['config']),B=createRedis(n['redis']),G=createLogger(),f=createDatabase(n['pg']),j=n['storageType']==='local'?createFileLocal({'storagePath':n['storagePath'],'folder':n['s3'][u(0x156)],'tokenSecret':n['s3']['tokenSecret'],'tokenTtl':n['s3'][u(0x157)]}):createFileS3({'endpoint':n['s3']['endpoint'],'region':n['s3'][u(0x158)],'bucket':n['s3']['bucket'],'accessKey':n['s3']['accessKey'],'secretKey':n['s3']['secretKey'],'folder':n['s3']['folder'],'forcePathStyle':n['s3']['forcePathStyle'],'tokenSecret':n['s3'][u(0x159)],'tokenTtl':n['s3'][u(0x157)]}),Z=createAudit({'pg':f,'logger':G}),e=createDictionary({'pg':f,'dictionaries':h[u(0x15a)]}),b=createResource({'pg':f,'logger':G,'audit':Z,'dictionary':e,'file':j});h['resources']?.[u(0x15b)]&&b[u(0x15c)](h['resources']);const P=createContext({'config':n,'logger':G,'redis':B,'pg':f,'file':j,'resource':b,'audit':Z,'dictionary':e});return setContext(P),P;}
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- const q=G;import{runMigrations}from'./runner.js';import{loadConfig}from'../config.js';import w from'node:path';import{fileURLToPath}from'node:url';function G(w,h){w=w-0x116;const S=z();let X=S[w];return X;}const packageMigrations=fileURLToPath(new URL('../../migrations',import.meta.url));function migrationDirectory(h){const o=G,S=h['indexOf']('--dir');if(S>=0x0){const Y=h[S+0x1];if(!Y)throw new Error('--dir\x20requires\x20a\x20folder\x20path');return w['resolve'](Y);}if(h['includes']('--fcore'))return packageMigrations;const X=h[o(0x116)](v=>!v[o(0x117)]('--'));return w['resolve'](X??'migrations');}try{const config=loadConfig(),dir=migrationDirectory(process[q(0x118)]['slice'](0x2));console[q(0x119)]('Loaded\x20configuration:',{...config['pg'],'user':'****','password':'****'}),console[q(0x119)](q(0x11a),dir,process['argv'][q(0x11b)](0x2));for(const r of await runMigrations({'database':config['pg'],'dir':dir}))console['log']((r[q(0x11c)]==='run'?'OK\x20\x20':'SKIP')+'\x20'+r['file']);}catch(D){console['error'](D),process[q(0x11d)]=0x1;}function z(){const e=['find','startsWith','argv','log','Using\x20migration\x20directory:','slice','status','exitCode'];z=function(){return e;};return z();}
2
+ const e=k;function Q(){const P=['../../migrations','--dir','includes','startsWith','slice','log','Using\x20migration\x20directory:','run','error','exitCode'];Q=function(){return P;};return Q();}import{runMigrations}from'./runner.js';function k(h,n){h=h-0x119;const B=Q();let G=B[h];return G;}import{loadConfig}from'../config.js';import h from'node:path';import{fileURLToPath}from'node:url';const packageMigrations=fileURLToPath(new URL(e(0x119),import.meta.url));function migrationDirectory(n){const b=e,B=n['indexOf'](b(0x11a));if(B>=0x0){const f=n[B+0x1];if(!f)throw new Error('--dir\x20requires\x20a\x20folder\x20path');return h['resolve'](f);}if(n[b(0x11b)]('--fcore'))return packageMigrations;const G=n['find'](j=>!j[b(0x11c)]('--'));return h['resolve'](G??'migrations');}try{const config=loadConfig(),dir=migrationDirectory(process['argv'][e(0x11d)](0x2));console['log']('Loaded\x20configuration:',{...config['pg'],'user':'****','password':'****'}),console[e(0x11e)](e(0x11f),dir,process['argv'][e(0x11d)](0x2));for(const r of await runMigrations({'database':config['pg'],'dir':dir}))console['log']((r['status']===e(0x120)?'OK\x20\x20':'SKIP')+'\x20'+r['file']);}catch(Z){console[e(0x121)](Z),process[e(0x122)]=0x1;}
@@ -1 +1 @@
1
- import w from'node:fs/promises';import h from'node:path';import{createDatabase}from'../plugins/pg.js';export async function runMigrations(S={}){const O=G,X=h['resolve'](S['dir']??O(0x1a0)),Y=S[O(0x1a1)]??databaseFromUrl(S[O(0x1a2)]??process.env.DATABASE_URL);if(!Y)throw new Error('DATABASE_URL\x20or\x20database\x20config\x20is\x20required');const v=createDatabase(Y);if(!v)throw new Error('empty\x20pg');const D=[];try{await v[O(0x1a3)]('\x0a\x20\x20\x20\x20\x20\x20CREATE\x20TABLE\x20IF\x20NOT\x20EXISTS\x20schema_migrations\x20(\x0a\x20\x20\x20\x20\x20\x20\x20\x20version\x20varchar(255)\x20PRIMARY\x20KEY,\x0a\x20\x20\x20\x20\x20\x20\x20\x20applied_at\x20timestamptz\x20NOT\x20NULL\x20DEFAULT\x20now()\x0a\x20\x20\x20\x20\x20\x20)\x0a\x20\x20\x20\x20');const o=await v['query']('SELECT\x20version\x20FROM\x20schema_migrations'),q=new Set(o[O(0x1a4)][O(0x1a5)](Z=>Z[O(0x1a6)])),e=(await w['readdir'](X))[O(0x1a7)](Z=>Z['endsWith']('.sql'))['sort']();for(const Z of e){if(q['has'](Z)){D['push']({'file':Z,'status':O(0x1a8)});continue;}const K=await w['readFile'](h['join'](X,Z),'utf8'),y=await v[O(0x1a9)]();try{await y['query']('BEGIN'),await y['query'](K),await y[O(0x1a3)](O(0x1aa),[Z]),await y['query']('COMMIT');}catch(V){await y[O(0x1a3)]('ROLLBACK');throw V;}finally{y['release']();}D['push']({'file':Z,'status':'run'});}return D;}finally{await v[O(0x1ab)]();}}function G(w,h){w=w-0x1a0;const S=z();let X=S[w];return X;}function z(){const H=['migrations','database','databaseUrl','query','rows','map','version','filter','skip','connect','INSERT\x20INTO\x20schema_migrations(version)\x20VALUES\x20($1)','end'];z=function(){return H;};return z();}function databaseFromUrl(S){if(!S)return undefined;const X=new URL(S);return{'host':X['hostname'],'port':Number(X['port']||0x1538),'database':X['pathname']['slice'](0x1),'user':decodeURIComponent(X['username']),'password':decodeURIComponent(X['password'])};}
1
+ function Q(){const t=['resolve','migrations','empty\x20pg','query','rows','map','endsWith','has','readFile','join','connect','run','hostname'];Q=function(){return t;};return Q();}import h from'node:fs/promises';import n from'node:path';import{createDatabase}from'../plugins/pg.js';export async function runMigrations(B={}){const p=k,G=n[p(0x163)](B['dir']??p(0x164)),f=B['database']??databaseFromUrl(B['databaseUrl']??process.env.DATABASE_URL);if(!f)throw new Error('DATABASE_URL\x20or\x20database\x20config\x20is\x20required');const j=createDatabase(f);if(!j)throw new Error(p(0x165));const Z=[];try{await j[p(0x166)]('\x0a\x20\x20\x20\x20\x20\x20CREATE\x20TABLE\x20IF\x20NOT\x20EXISTS\x20schema_migrations\x20(\x0a\x20\x20\x20\x20\x20\x20\x20\x20version\x20varchar(255)\x20PRIMARY\x20KEY,\x0a\x20\x20\x20\x20\x20\x20\x20\x20applied_at\x20timestamptz\x20NOT\x20NULL\x20DEFAULT\x20now()\x0a\x20\x20\x20\x20\x20\x20)\x0a\x20\x20\x20\x20');const e=await j['query']('SELECT\x20version\x20FROM\x20schema_migrations'),b=new Set(e[p(0x167)][p(0x168)](u=>u['version'])),P=(await h['readdir'](G))['filter'](u=>u[p(0x169)]('.sql'))['sort']();for(const u of P){if(b[p(0x16a)](u)){Z['push']({'file':u,'status':'skip'});continue;}const X=await h[p(0x16b)](n[p(0x16c)](G,u),'utf8'),H=await j[p(0x16d)]();try{await H[p(0x166)]('BEGIN'),await H['query'](X),await H['query']('INSERT\x20INTO\x20schema_migrations(version)\x20VALUES\x20($1)',[u]),await H['query']('COMMIT');}catch(i){await H[p(0x166)]('ROLLBACK');throw i;}finally{H['release']();}Z['push']({'file':u,'status':p(0x16e)});}return Z;}finally{await j['end']();}}function k(h,n){h=h-0x163;const B=Q();let G=B[h];return G;}function databaseFromUrl(B){const z=k;if(!B)return undefined;const G=new URL(B);return{'host':G[z(0x16f)],'port':Number(G['port']||0x1538),'database':G['pathname']['slice'](0x1),'user':decodeURIComponent(G['username']),'password':decodeURIComponent(G['password'])};}
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- function G(w,h){w=w-0x100;const S=z();let X=S[w];return X;}function z(){const X=['argv','error'];z=function(){return X;};return z();}const S=G;import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';import w from'./services/registration.js';const [user,password,type]=process[S(0x100)]['slice'](0x2);if(!user||!password)console['error']('Usage:\x20fcore-registration\x20<login>\x20<password>\x20[type]'),process['exitCode']=0x1;else{const pg=createDatabase(loadConfig()['pg']);try{const {user:data}=await w({'user':user,'password':password,'type':type},{'pg':pg});console['log']('Registered\x20user\x20'+data['id']+'\x20('+data['type']+')');}catch(h){console[S(0x101)](h),process['exitCode']=0x1;}finally{await pg['end']();}}
2
+ const B=k;import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';import h from'./services/registration.js';const [user,password,type]=process['argv']['slice'](0x2);if(!user||!password)console['error']('Usage:\x20fcore-registration\x20<login>\x20<password>\x20[type]'),process[B(0xc5)]=0x1;else{const pg=createDatabase(loadConfig()['pg']);try{const {user:data}=await h({'user':user,'password':password,'type':type},{'pg':pg});console['log']('Registered\x20user\x20'+data['id']+'\x20('+data[B(0xc6)]+')');}catch(n){console[B(0xc7)](n),process['exitCode']=0x1;}finally{await pg['end']();}}function k(h,n){h=h-0xc5;const B=Q();let G=B[h];return G;}function Q(){const G=['exitCode','type','error'];Q=function(){return G;};return Q();}
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- function G(w,h){w=w-0x1b7;const S=z();let X=S[w];return X;}function z(){const X=['argv','query','SELECT\x20uid\x20AS\x20id\x20FROM\x20admin.users\x20WHERE\x20$1\x20IN\x20(login,\x20email,\x20phone)\x20LIMIT\x201','User\x20not\x20found','Password\x20changed\x20for\x20','error','end'];z=function(){return X;};return z();}const S=G;import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';import w from'./services/change-password.js';const [login,password]=process[S(0x1b7)]['slice'](0x2);if(!login||!password)console['error']('Usage:\x20fcore-password\x20<login>\x20<password>'),process['exitCode']=0x1;else{const pg=createDatabase(loadConfig()['pg']);try{const result=await pg[S(0x1b8)](S(0x1b9),[login]),user=result['rows'][0x0];if(!user)throw new Error(S(0x1ba));await w({'userId':user['id'],'password':password},{'pg':pg}),console['log'](S(0x1bb)+login);}catch(h){console[S(0x1bc)](h),process['exitCode']=0x1;}finally{await pg[S(0x1bd)]();}}
2
+ function Q(){const G=['exitCode','error','end'];Q=function(){return G;};return Q();}function k(h,n){h=h-0x1ec;const B=Q();let G=B[h];return G;}const B=k;import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';import h from'./services/change-password.js';const [login,password]=process['argv']['slice'](0x2);if(!login||!password)console['error']('Usage:\x20fcore-password\x20<login>\x20<password>'),process[B(0x1ec)]=0x1;else{const pg=createDatabase(loadConfig()['pg']);try{const result=await pg['query']('SELECT\x20uid\x20AS\x20id\x20FROM\x20admin.users\x20WHERE\x20$1\x20IN\x20(login,\x20email,\x20phone)\x20LIMIT\x201',[login]),user=result['rows'][0x0];if(!user)throw new Error('User\x20not\x20found');await h({'userId':user['id'],'password':password},{'pg':pg}),console['log']('Password\x20changed\x20for\x20'+login);}catch(n){console[B(0x1ed)](n),process[B(0x1ec)]=0x1;}finally{await pg[B(0x1ee)]();}}
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- const q=G;import{loadConfig}from'../../config.js';function G(w,h){w=w-0x1b6;const S=z();let X=S[w];return X;}function z(){const Z=['logs','create','argv','split','map','SELECT\x20uid\x20AS\x20id\x20FROM\x20admin.users\x20WHERE\x20$1\x20IN\x20(login,\x20email,\x20phone)\x20LIMIT\x201','User\x20not\x20found','trim','log','push','actions','UPDATE\x20admin.role_access\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20SET\x20actions\x20=\x20$1,\x20updated_by\x20=\x20$2,\x20updated_at\x20=\x20now()\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20WHERE\x20access_id\x20=\x20$3','access_id','INSERT\x20INTO\x20admin.role_access\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20(\x20resource,\x20actions,\x20user_uid,\x20created_by,\x20updated_by)\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20VALUES\x20($1,\x20$2,\x20$3,\x20$4,\x20$4)','query','release','Granted\x20permissions\x20for\x20'];z=function(){return Z;};return z();}import{createDatabase}from'../../plugins/pg.js';const SYSTEM_ACTIONS=[q(0x1b6),'audit','list','check','access','settings','dictionaries'],RESOURCE_ACTIONS=['read','update',q(0x1b7),'delete'],[login,permissionArg]=process[q(0x1b8)]['slice'](0x2);function expandPermissions(w){const e=q,h=w[e(0x1b9)](',')[e(0x1ba)](X=>X['trim']())['filter'](Boolean),S=new Set();for(const X of h){if(X['includes'](':')){S['add'](X);continue;}const Y=X==='system'?SYSTEM_ACTIONS:RESOURCE_ACTIONS;for(const v of Y){S['add'](X+':'+v);}}return[...S];}if(!login||!permissionArg)console['error']('Usage:\x20fcore-permission\x20<login>\x20<system|resource|resource:action[,...]|clear>'),process['exitCode']=0x1;else{const pg=createDatabase(loadConfig()['pg']);try{const result=await pg['query'](q(0x1bb),[login]),user=result['rows'][0x0];if(!user)throw new Error(q(0x1bc));if(permissionArg[q(0x1bd)]()==='clear')await pg['query']('DELETE\x20FROM\x20admin.role_access\x20WHERE\x20user_uid\x20=\x20$1\x20AND\x20role_id\x20IS\x20NULL',[user['id']]),console[q(0x1be)]('Permissions\x20cleared\x20for\x20'+login);else{const permissions=expandPermissions(permissionArg),byResource=new Map();for(const permission of permissions){const [resource,action]=permission['split'](':'),actions=byResource['get'](resource)??[];actions[q(0x1bf)](action),byResource['set'](resource,actions);}const client=await pg['connect']();try{await client['query']('BEGIN');for(const [resource,actions]of byResource){const existing=await client['query']('SELECT\x20access_id,\x20actions\x20FROM\x20admin.role_access\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20WHERE\x20user_uid\x20=\x20$1\x20AND\x20role_id\x20IS\x20NULL\x20AND\x20resource\x20=\x20$2',[user['id'],resource]),row=existing['rows'][0x0];if(row){const merged=[...new Set([...row[q(0x1c0)]??[],...actions])];await client['query'](q(0x1c1),[merged,user['id'],row[q(0x1c2)]]);}else await client['query'](q(0x1c3),[resource,actions,user['id'],user['id']]);}await client['query']('COMMIT');}catch(D){await client[q(0x1c4)]('ROLLBACK');throw D;}finally{client[q(0x1c5)]();}console['log'](q(0x1c6)+login+':\x20'+permissions['join'](',\x20'));}}catch(o){console['error'](o),process['exitCode']=0x1;}finally{await pg['end']();}}
2
+ const b=k;import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';function Q(){const u=['logs','check','settings','dictionaries','read','split','includes','system','query','rows','User\x20not\x20found','trim','log','get','set','BEGIN','UPDATE\x20admin.role_access\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20SET\x20actions\x20=\x20$1,\x20updated_by\x20=\x20$2,\x20updated_at\x20=\x20now()\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20WHERE\x20access_id\x20=\x20$3','access_id','Granted\x20permissions\x20for\x20','join','end'];Q=function(){return u;};return Q();}const SYSTEM_ACTIONS=[b(0x13b),'audit','list',b(0x13c),'access',b(0x13d),b(0x13e)],RESOURCE_ACTIONS=[b(0x13f),'update','create','delete'],[login,permissionArg]=process['argv']['slice'](0x2);function expandPermissions(h){const P=b,n=h[P(0x140)](',')['map'](G=>G['trim']())['filter'](Boolean),B=new Set();for(const G of n){if(G[P(0x141)](':')){B['add'](G);continue;}const f=G===P(0x142)?SYSTEM_ACTIONS:RESOURCE_ACTIONS;for(const j of f){B['add'](G+':'+j);}}return[...B];}function k(h,n){h=h-0x13b;const B=Q();let G=B[h];return G;}if(!login||!permissionArg)console['error']('Usage:\x20fcore-permission\x20<login>\x20<system|resource|resource:action[,...]|clear>'),process['exitCode']=0x1;else{const pg=createDatabase(loadConfig()['pg']);try{const result=await pg[b(0x143)]('SELECT\x20uid\x20AS\x20id\x20FROM\x20admin.users\x20WHERE\x20$1\x20IN\x20(login,\x20email,\x20phone)\x20LIMIT\x201',[login]),user=result[b(0x144)][0x0];if(!user)throw new Error(b(0x145));if(permissionArg[b(0x146)]()==='clear')await pg[b(0x143)]('DELETE\x20FROM\x20admin.role_access\x20WHERE\x20user_uid\x20=\x20$1\x20AND\x20role_id\x20IS\x20NULL',[user['id']]),console[b(0x147)]('Permissions\x20cleared\x20for\x20'+login);else{const permissions=expandPermissions(permissionArg),byResource=new Map();for(const permission of permissions){const [resource,action]=permission['split'](':'),actions=byResource[b(0x148)](resource)??[];actions['push'](action),byResource[b(0x149)](resource,actions);}const client=await pg['connect']();try{await client['query'](b(0x14a));for(const [resource,actions]of byResource){const existing=await client['query']('SELECT\x20access_id,\x20actions\x20FROM\x20admin.role_access\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20WHERE\x20user_uid\x20=\x20$1\x20AND\x20role_id\x20IS\x20NULL\x20AND\x20resource\x20=\x20$2',[user['id'],resource]),row=existing['rows'][0x0];if(row){const merged=[...new Set([...row['actions']??[],...actions])];await client['query'](b(0x14b),[merged,user['id'],row[b(0x14c)]]);}else await client[b(0x143)]('INSERT\x20INTO\x20admin.role_access\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20(\x20resource,\x20actions,\x20user_uid,\x20created_by,\x20updated_by)\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20VALUES\x20($1,\x20$2,\x20$3,\x20$4,\x20$4)',[resource,actions,user['id'],user['id']]);}await client['query']('COMMIT');}catch(Z){await client['query']('ROLLBACK');throw Z;}finally{client['release']();}console['log'](b(0x14d)+login+':\x20'+permissions[b(0x14e)](',\x20'));}}catch(e){console['error'](e),process['exitCode']=0x1;}finally{await pg[b(0x14f)]();}}
@@ -1 +1 @@
1
- import{getUserPermissions,verifyUser}from'../../plugins/auth/index.js';import w from'./services/get-current-user.js';import h from'./services/registration.js';import S from'./services/change-password.js';import{authSchemas}from'./schema.js';import X from'../../shared/getIP.js';function z(){const P=['GET','twofa','twoFactorRedirect','sessionTimeout','cookie','maxAge','audit','session','sessionId','login','Authenticates\x20a\x20user\x20and\x20returns\x20a\x20bearer\x20access\x20token.','public','/api/auth/login','auth','credentials','admin','user:create','Change\x20password','Changes\x20the\x20password\x20for\x20the\x20current\x20user.','user','Terminates\x20the\x20current\x20user\x20session.','destroy','config','Returns\x20the\x20authenticated\x20user\x27s\x20safe\x20profile.','query'];z=function(){return P;};return z();}import{UnauthorizedError}from'../../errors.js';function G(w,h){w=w-0xb8;const S=z();let X=S[w];return X;}export function authRoutes(Y){return async v=>{const O=G,D=async o=>{const V=G,q=o['method']===V(0xb8)?o['query']:o['body'],e=X(o),Z=await verifyUser({...q,'ip':e},Y);Z['permissions']=await getUserPermissions(Z['id'],Y);const K=Z[V(0xb9)]?Y['config']['auth'][V(0xba)]:Y['config']['auth']['redirect'];await o['login'](Z);const y=Y['config']['auth'][V(0xbb)]*0x3e8*0x3c;return o['session']?.[V(0xbc)]&&(o['session']['cookie'][V(0xbd)]=y),await o['session']['save'](),await Y[V(0xbe)]?.['write']?.({'module':'auth','resource':V(0xbf),'resourceId':o[V(0xbf)][V(0xc0)],'action':V(0xc1),'userId':Z['id'],'ipAddress':e}),{'user':{'id':Z['id'],'type':Z['type'],'permissions':Z['permissions']},'redirectUrl':K};};v['get']('/api/auth/login',{'schema':{'tags':['fcore','auth'],'summary':'Sign\x20in','description':O(0xc2),'access':O(0xc3),'permissions':[],'querystring':authSchemas['credentials']}},D),v['post'](O(0xc4),{'schema':{'tags':['fcore',O(0xc5)],'summary':'Sign\x20in','description':'Authenticates\x20a\x20user\x20and\x20returns\x20a\x20bearer\x20access\x20token.','access':'public','permissions':[],'body':authSchemas[O(0xc6)]}},D),v['post']('/api/auth/registration',{'schema':{'tags':['fcore','auth'],'summary':'Register','description':'Creates\x20a\x20regular\x20user\x20account.','access':O(0xc7),'permissions':[O(0xc8)],'body':authSchemas[O(0xc6)]}},async o=>h(o['body'],Y)),v['post']('/api/auth/password',{'schema':{'tags':['fcore','auth'],'summary':O(0xc9),'description':O(0xca),'access':'user','permissions':[],'body':authSchemas['password']}},async o=>{const H=O;if(!o['user'])throw new UnauthorizedError('Not\x20authorized');return await S({'userId':o[H(0xcb)]['id'],...o['body']},Y),{'success':!![]};}),v['post']('/api/auth/logout',{'schema':{'tags':['fcore','auth'],'summary':'Sign\x20out','description':O(0xcc),'access':O(0xcb),'permissions':[]}},async(o,q)=>{const R=O,e={'redirectUrl':'/'};if(!o['user'])return e;return await Y[R(0xbe)]?.['write']?.({'module':R(0xc5),'resource':R(0xbf),'resourceId':o['session'][R(0xc0)],'action':'logout','userId':o['user']?.['id']}),await o['session'][R(0xcd)](),q['clearCookie'](Y[R(0xce)]['auth']['cookieName']),Object['defineProperty'](o,'session',{'value':null,'writable':![],'configurable':![]}),e;}),v['get']('/api/auth/user',{'schema':{'tags':['fcore','auth'],'summary':'Get\x20current\x20user','description':O(0xcf),'access':'user','permissions':[],'querystring':authSchemas['query']}},async o=>{const Q=O;return w({'user':o['user'],'token':o[Q(0xd0)]['token'],'maxAge':o['session']?.['cookie']?.['maxAge'],'originalExpires':o['session']?.['cookie']?.['originalExpires']?.['toISOString']?.()});});};}
1
+ function k(h,n){h=h-0x112;const B=Q();let G=B[h];return G;}import{getUserPermissions,verifyUser}from'../../plugins/auth/index.js';import h from'./services/get-current-user.js';import n from'./services/registration.js';import B from'./services/change-password.js';import{authSchemas}from'./schema.js';import G from'../../shared/getIP.js';import{UnauthorizedError}from'../../errors.js';export function authRoutes(f){return async j=>{const p=k,Z=async e=>{const i=k,b=e[i(0x112)]==='GET'?e['query']:e['body'],P=G(e),u=await verifyUser({...b,'ip':P},f);u[i(0x113)]=await getUserPermissions(u['id'],f);const X=u[i(0x114)]?f['config'][i(0x115)][i(0x116)]:f['config'][i(0x115)][i(0x117)];await e['login'](u);const H=f['config']['auth']['sessionTimeout']*0x3e8*0x3c;return e[i(0x118)]?.['cookie']&&(e[i(0x118)]['cookie']['maxAge']=H),await e[i(0x118)]['save'](),await f['audit']?.['write']?.({'module':'auth','resource':i(0x118),'resourceId':e[i(0x118)]['sessionId'],'action':i(0x119),'userId':u['id'],'ipAddress':P}),{'user':{'id':u['id'],'type':u[i(0x11a)],'permissions':u[i(0x113)]},'redirectUrl':X};};j[p(0x11b)](p(0x11c),{'schema':{'tags':['fcore',p(0x115)],'summary':'Sign\x20in','description':p(0x11d),'access':'public','permissions':[],'querystring':authSchemas['credentials']}},Z),j[p(0x11e)](p(0x11c),{'schema':{'tags':['fcore','auth'],'summary':'Sign\x20in','description':p(0x11d),'access':p(0x11f),'permissions':[],'body':authSchemas['credentials']}},Z),j['post'](p(0x120),{'schema':{'tags':['fcore',p(0x115)],'summary':'Register','description':'Creates\x20a\x20regular\x20user\x20account.','access':'admin','permissions':[p(0x121)],'body':authSchemas['credentials']}},async e=>n(e[p(0x122)],f)),j['post']('/api/auth/password',{'schema':{'tags':['fcore','auth'],'summary':'Change\x20password','description':'Changes\x20the\x20password\x20for\x20the\x20current\x20user.','access':'user','permissions':[],'body':authSchemas['password']}},async e=>{const z=p;if(!e['user'])throw new UnauthorizedError('Not\x20authorized');return await B({'userId':e['user']['id'],...e[z(0x122)]},f),{'success':!![]};}),j['post'](p(0x123),{'schema':{'tags':['fcore','auth'],'summary':'Sign\x20out','description':p(0x124),'access':'user','permissions':[]}},async(e,b)=>{const t=p,P={'redirectUrl':'/'};if(!e['user'])return P;return await f[t(0x125)]?.[t(0x126)]?.({'module':t(0x115),'resource':'session','resourceId':e['session'][t(0x127)],'action':t(0x128),'userId':e[t(0x129)]?.['id']}),await e['session']['destroy'](),b[t(0x12a)](f['config'][t(0x115)][t(0x12b)]),Object['defineProperty'](e,'session',{'value':null,'writable':![],'configurable':![]}),P;}),j['get']('/api/auth/user',{'schema':{'tags':[p(0x12c),p(0x115)],'summary':p(0x12d),'description':'Returns\x20the\x20authenticated\x20user\x27s\x20safe\x20profile.','access':p(0x129),'permissions':[],'querystring':authSchemas['query']}},async e=>{const m=p;return h({'user':e[m(0x129)],'token':e['query'][m(0x12e)],'maxAge':e[m(0x118)]?.['cookie']?.[m(0x12f)],'originalExpires':e[m(0x118)]?.[m(0x130)]?.['originalExpires']?.[m(0x131)]?.()});});};}function Q(){const A=['method','permissions','twofa','auth','twoFactorRedirect','redirect','session','login','type','get','/api/auth/login','Authenticates\x20a\x20user\x20and\x20returns\x20a\x20bearer\x20access\x20token.','post','public','/api/auth/registration','user:create','body','/api/auth/logout','Terminates\x20the\x20current\x20user\x20session.','audit','write','sessionId','logout','user','clearCookie','cookieName','fcore','Get\x20current\x20user','token','maxAge','cookie','toISOString'];Q=function(){return A;};return Q();}
@@ -1 +1 @@
1
- function z(){const h=['Optional','Object','String'];z=function(){return h;};return z();}const w=G;function G(w,h){w=w-0x1b1;const S=z();let X=S[w];return X;}import{Type}from'@sinclair/typebox';export const authSchemas={'query':Type['Object']({'token':Type[w(0x1b1)](Type['Boolean']())}),'credentials':Type[w(0x1b2)]({'user':Type[w(0x1b3)]({'minLength':0x1,'maxLength':0x64}),'password':Type['String']({'minLength':0x1,'maxLength':0x64}),'type':Type['Optional'](Type['String']({'minLength':0x1,'maxLength':0x64}))}),'password':Type['Object']({'password':Type[w(0x1b3)]({'minLength':0x1,'maxLength':0x64}),'id':Type['Optional'](Type[w(0x1b3)]({'minLength':0x1,'maxLength':0x64}))}),'twoFactor':Type['Object']({'code':Type['String']({'minLength':0x1})})};
1
+ const h=k;import{Type}from'@sinclair/typebox';function k(h,n){h=h-0x81;const B=Q();let G=B[h];return G;}function Q(){const n=['Boolean','Object','String','Optional'];Q=function(){return n;};return Q();}export const authSchemas={'query':Type['Object']({'token':Type['Optional'](Type[h(0x81)]())}),'credentials':Type[h(0x82)]({'user':Type[h(0x83)]({'minLength':0x1,'maxLength':0x64}),'password':Type['String']({'minLength':0x1,'maxLength':0x64}),'type':Type['Optional'](Type['String']({'minLength':0x1,'maxLength':0x64}))}),'password':Type['Object']({'password':Type['String']({'minLength':0x1,'maxLength':0x64}),'id':Type[h(0x84)](Type[h(0x83)]({'minLength':0x1,'maxLength':0x64}))}),'twoFactor':Type['Object']({'code':Type['String']({'minLength':0x1})})};
@@ -1 +1 @@
1
- import{hashPassword}from'../../../plugins/auth/index.js';export default async function changePassword({id:w,password:h,userId:S},{pg:X}){const Y=await hashPassword(h);await X['query']('UPDATE\x20admin.users\x0a\x20\x20\x20\x20\x20SET\x20password_hash\x20=\x20$1,\x20updated_at\x20=\x20now(),\x20updated_by\x20=\x20$3\x0a\x20\x20\x20\x20\x20WHERE\x20uid\x20=\x20$2',[Y,w||S,S]);}
1
+ import{hashPassword}from'../../../plugins/auth/index.js';function Q(){const Z=['query'];Q=function(){return Z;};return Q();}function k(h,n){h=h-0x1e4;const B=Q();let G=B[h];return G;}export default async function changePassword({id:h,password:n,userId:B},{pg:G}){const j=k,f=await hashPassword(n);await G[j(0x1e4)]('UPDATE\x20admin.users\x0a\x20\x20\x20\x20\x20SET\x20password_hash\x20=\x20$1,\x20updated_at\x20=\x20now(),\x20updated_by\x20=\x20$3\x0a\x20\x20\x20\x20\x20WHERE\x20uid\x20=\x20$2',[f,h||B,B]);}
@@ -1 +1 @@
1
- function z(){const D=['token','permissions','maxAge'];z=function(){return D;};return z();}function G(w,h){w=w-0x1bb;const S=z();let X=S[w];return X;}import{safeUser}from'../../utils/safe-user.js';export default async function getCurrentUser(w){const v=G,{user:h}=w;if(!h)return{};if(w[v(0x1bb)]){const {jwtSignToken:S}=await import('../../../plugins/jwt.js'),X=await S(h);h['token']=X;}return h['resources']=[...new Set(h?.[v(0x1bc)]['map'](Y=>Y['split'](':')[0x0]))],{...safeUser(h),'session':{'maxAge':w['maxAge'],'originalExpires':w[v(0x1bd)]}};}
1
+ function Q(){const Z=['permissions','map','split'];Q=function(){return Z;};return Q();}import{safeUser}from'../../utils/safe-user.js';function k(h,n){h=h-0x123;const B=Q();let G=B[h];return G;}export default async function getCurrentUser(h){const j=k,{user:n}=h;if(!n)return{};if(h['token']){const {jwtSignToken:B}=await import('../../../plugins/jwt.js'),G=await B(n);n['token']=G;}return n['resources']=[...new Set(n?.[j(0x123)][j(0x124)](f=>f[j(0x125)](':')[0x0]))],{...safeUser(n),'session':{'maxAge':h['maxAge'],'originalExpires':h['maxAge']}};}
@@ -1 +1 @@
1
- import{ConflictError}from'../../../errors.js';import{hashPassword}from'../../../plugins/auth/index.js';function z(){const q=['query','regular'];z=function(){return q;};return z();}function G(w,h){w=w-0x181;const S=z();let X=S[w];return X;}export default async function registration({user:w,password:h,type:S},{pg:X}){const o=G,Y=await hashPassword(h),v=await X[o(0x181)]('INSERT\x20INTO\x20admin.users\x20(login,\x20password_hash,\x20user_type)\x0a\x20\x20\x20\x20\x20SELECT\x20$1,\x20$2,\x20$3\x0a\x20\x20\x20\x20\x20WHERE\x20NOT\x20EXISTS\x20(SELECT\x201\x20FROM\x20admin.users\x20WHERE\x20login\x20=\x20$1)\x0a\x20\x20\x20\x20\x20RETURNING\x20uid\x20AS\x20id,\x20user_type\x20AS\x20type',[w,Y,S||o(0x182)]),D=v['rows'][0x0];if(!D)throw new ConflictError('Login\x20is\x20already\x20in\x20use');return{'user':D};}
1
+ import{ConflictError}from'../../../errors.js';import{hashPassword}from'../../../plugins/auth/index.js';function k(h,n){h=h-0xc8;const B=Q();let G=B[h];return G;}export default async function registration({user:h,password:n,type:B},{pg:G}){const e=k,f=await hashPassword(n),j=await G['query']('INSERT\x20INTO\x20admin.users\x20(login,\x20password_hash,\x20user_type)\x0a\x20\x20\x20\x20\x20SELECT\x20$1,\x20$2,\x20$3\x0a\x20\x20\x20\x20\x20WHERE\x20NOT\x20EXISTS\x20(SELECT\x201\x20FROM\x20admin.users\x20WHERE\x20login\x20=\x20$1)\x0a\x20\x20\x20\x20\x20RETURNING\x20uid\x20AS\x20id,\x20user_type\x20AS\x20type',[h,f,B||e(0xc8)]),Z=j['rows'][0x0];if(!Z)throw new ConflictError('Login\x20is\x20already\x20in\x20use');return{'user':Z};}function Q(){const b=['regular'];Q=function(){return b;};return Q();}
@@ -1 +1 @@
1
- function z(){var X=['Two-factor\x20provider'];z=function(){return X;};return z();}function G(w,h){w=w-0xf0;var S=z();var X=S[w];return X;}import{unsupported}from'../../utils/unsupported.js';export default async function verifyTwoFactor(w,h){var S=G;return unsupported(S(0xf0));}
1
+ import{unsupported}from'../../utils/unsupported.js';export default async function verifyTwoFactor(h,n){return unsupported('Two-factor\x20provider');}
@@ -1 +1 @@
1
- var w=G;function G(w,h){w=w-0x1f3;var S=z();var X=S[w];return X;}function z(){var h=['image/bmp','application/vnd.openxmlformats-officedocument.wordprocessingml.document','application/x-zip-compressed','application/x-rar-compressed','audio/webm','audio/mp4'];z=function(){return h;};return z();}export default new Set(['image/jpeg','image/png','image/gif','image/webp',w(0x1f3),'image/tiff','image/svg+xml','image/x-icon','image/avif','application/pdf','application/msword',w(0x1f4),'application/vnd.ms-excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','application/vnd.ms-powerpoint','application/vnd.openxmlformats-officedocument.presentationml.presentation','application/vnd.oasis.opendocument.text','application/vnd.oasis.opendocument.spreadsheet','application/vnd.oasis.opendocument.presentation','text/plain','text/csv','text/markdown','application/json','application/xml','text/xml','application/geo+json','application/vnd.google-earth.kml+xml','application/vnd.google-earth.kmz','application/zip',w(0x1f5),'application/x-7z-compressed',w(0x1f6),'application/vnd.rar','application/gzip','application/x-gzip','application/x-tar','audio/mpeg','audio/wav','audio/ogg',w(0x1f7),w(0x1f8),'video/mp4','video/mpeg','video/webm','video/quicktime','video/x-msvideo','application/octet-stream']);
1
+ function k(h,n){h=h-0x1c0;var B=Q();var G=B[h];return G;}var h=k;function Q(){var n=['image/jpeg','image/png','image/webp','image/tiff','application/pdf','application/vnd.ms-powerpoint','application/vnd.openxmlformats-officedocument.presentationml.presentation','application/vnd.oasis.opendocument.text','text/csv','application/json','application/geo+json','application/x-7z-compressed','application/gzip','application/x-gzip','audio/wav','audio/ogg','audio/webm','video/quicktime'];Q=function(){return n;};return Q();}export default new Set([h(0x1c0),h(0x1c1),'image/gif',h(0x1c2),'image/bmp',h(0x1c3),'image/svg+xml','image/x-icon','image/avif',h(0x1c4),'application/msword','application/vnd.openxmlformats-officedocument.wordprocessingml.document','application/vnd.ms-excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',h(0x1c5),h(0x1c6),h(0x1c7),'application/vnd.oasis.opendocument.spreadsheet','application/vnd.oasis.opendocument.presentation','text/plain',h(0x1c8),'text/markdown',h(0x1c9),'application/xml','text/xml',h(0x1ca),'application/vnd.google-earth.kml+xml','application/vnd.google-earth.kmz','application/zip','application/x-zip-compressed',h(0x1cb),'application/x-rar-compressed','application/vnd.rar',h(0x1cc),h(0x1cd),'application/x-tar','audio/mpeg',h(0x1ce),h(0x1cf),h(0x1d0),'audio/mp4','video/mp4','video/mpeg','video/webm',h(0x1d1),'video/x-msvideo','application/octet-stream']);
@@ -1 +1 @@
1
- import{fileTypeFromBuffer}from'file-type';import{getFile}from'./services/get-file.js';import{uploadFile}from'./services/upload-file.js';function G(w,h){w=w-0x6a;const S=z();let X=S[w];return X;}import{resizeFile}from'./services/resize-file.js';import{fileSchemas}from'./schema.js';function z(){const H=['fcore','Returns\x20a\x20file\x20after\x20verifying\x20its\x20signed\x20access\x20token.','fileToken','params','mime','download','startsWith','header','post','Uploads\x20a\x20file\x20and\x20stores\x20its\x20metadata.','fields','file','resizeQuery','Cache-Control'];z=function(){return H;};return z();}export function fileRoutes(w){return async h=>{const K=G;h['get']('/api/file/:token',{'schema':{'tags':[K(0x6a),'file'],'summary':'Get\x20file\x20by\x20token','description':K(0x6b),'access':'public','permissions':[],'params':fileSchemas[K(0x6c)],'querystring':fileSchemas['fileDownloadQuery']}},async(S,X)=>{const y=K,Y=w['file']['verify'](S[y(0x6d)]['token']),v=await getFile({'pathOrToken':Y},w),D=await fileTypeFromBuffer(v),o=D?.[y(0x6e)]??'application/octet-stream',q=S['query'][y(0x6f)]===!![],e=o[y(0x70)]('image/')||o==='application/pdf',Z=Y['split']('/')['pop']()?.['replace'](/[^A-Za-z0-9._-]/g,'_')??'file';return X['type'](o),X['header']('Content-Disposition',(q||!e?'attachment':'inline')+';\x20filename=\x22'+Z+'\x22')[y(0x71)]('Cache-Control','public,\x20max-age=86400,\x20immutable'),X['send'](v);}),h[K(0x72)]('/api/file/upload',{'schema':{'tags':['fcore','file'],'summary':'Upload\x20file','description':K(0x73),'access':'user','permissions':['files:create']}},async S=>{const V=K,X=await S['file']();if(!X)throw new Error('File\x20is\x20required');return uploadFile({'file':X,'metadata':{'name':X['filename'],'path':X['fields']['path']?.['value'],'resource':X['fields']['resource']?.['value'],'resourceId':X[V(0x74)]['resourceId']?.['value']},'user':S['user']},w);}),h['get']('/api/file/:token/resize',{'schema':{'tags':[K(0x6a),K(0x75)],'summary':'Resize\x20file','description':'Returns\x20a\x20resized\x20image\x20file.','access':'user','permissions':['files:read'],'params':fileSchemas[K(0x6c)],'querystring':fileSchemas[K(0x76)]}},async(S,X)=>{const O=K,Y=await resizeFile({'pathOrToken':w['file']?.['verify'](S['params']['token']),...S['query']},w),v=await fileTypeFromBuffer(Y);return X['type'](v?.['mime']??'image/png'),X['header']('Content-Disposition','inline')['header'](O(0x77),'public,\x20max-age=86400,\x20immutable'),X['send'](Y);});};}
1
+ function k(h,n){h=h-0x12a;const B=Q();let G=B[h];return G;}import{fileTypeFromBuffer}from'file-type';function Q(){const z=['fileToken','verify','token','download','startsWith','image/','pop','file','Content-Disposition','header','Cache-Control','fcore','Uploads\x20a\x20file\x20and\x20stores\x20its\x20metadata.','fields','/api/file/:token/resize','user','type'];Q=function(){return z;};return Q();}import{getFile}from'./services/get-file.js';import{uploadFile}from'./services/upload-file.js';import{resizeFile}from'./services/resize-file.js';import{fileSchemas}from'./schema.js';export function fileRoutes(h){return async n=>{const X=k;n['get']('/api/file/:token',{'schema':{'tags':['fcore','file'],'summary':'Get\x20file\x20by\x20token','description':'Returns\x20a\x20file\x20after\x20verifying\x20its\x20signed\x20access\x20token.','access':'public','permissions':[],'params':fileSchemas[X(0x12a)],'querystring':fileSchemas['fileDownloadQuery']}},async(B,G)=>{const H=X,f=h['file'][H(0x12b)](B['params'][H(0x12c)]),j=await getFile({'pathOrToken':f},h),Z=await fileTypeFromBuffer(j),e=Z?.['mime']??'application/octet-stream',b=B['query'][H(0x12d)]===!![],P=e[H(0x12e)](H(0x12f))||e==='application/pdf',u=f['split']('/')[H(0x130)]()?.['replace'](/[^A-Za-z0-9._-]/g,'_')??H(0x131);return G['type'](e),G['header'](H(0x132),(b||!P?'attachment':'inline')+';\x20filename=\x22'+u+'\x22')[H(0x133)](H(0x134),'public,\x20max-age=86400,\x20immutable'),G['send'](j);}),n['post']('/api/file/upload',{'schema':{'tags':[X(0x135),X(0x131)],'summary':'Upload\x20file','description':X(0x136),'access':'user','permissions':['files:create']}},async B=>{const i=X,G=await B['file']();if(!G)throw new Error('File\x20is\x20required');return uploadFile({'file':G,'metadata':{'name':G['filename'],'path':G['fields']['path']?.['value'],'resource':G['fields']['resource']?.['value'],'resourceId':G[i(0x137)]['resourceId']?.['value']},'user':B['user']},h);}),n['get'](X(0x138),{'schema':{'tags':['fcore','file'],'summary':'Resize\x20file','description':'Returns\x20a\x20resized\x20image\x20file.','access':X(0x139),'permissions':['files:read'],'params':fileSchemas['fileToken'],'querystring':fileSchemas['resizeQuery']}},async(B,G)=>{const p=X,f=await resizeFile({'pathOrToken':h[p(0x131)]?.['verify'](B['params']['token']),...B['query']},h),j=await fileTypeFromBuffer(f);return G[p(0x13a)](j?.['mime']??'image/png'),G['header'](p(0x132),'inline')['header'](p(0x134),'public,\x20max-age=86400,\x20immutable'),G['send'](f);});};}
@@ -1 +1 @@
1
- const w=G;function G(w,h){w=w-0x14c;const S=z();let X=S[w];return X;}function z(){const h=['String','Object','Optional','Integer','cover','contain','Literal','outside'];z=function(){return h;};return z();}import{Type}from'@sinclair/typebox';export const fileSchemas={'fileId':Type['Object']({'id':Type[w(0x14c)]({'minLength':0x1,'maxLength':0x80})}),'fileToken':Type['Object']({'token':Type['String']({'minLength':0x1,'maxLength':0x800})}),'fileDownloadQuery':Type[w(0x14d)]({'download':Type['Optional'](Type['Boolean']())}),'filePath':Type[w(0x14d)]({'*':Type[w(0x14c)]({'minLength':0x1,'maxLength':0x400})}),'upload':Type['Object']({'file':Type['Any'](),'metadata':Type['Object']({'name':Type[w(0x14e)](Type['String']({'minLength':0x1})),'path':Type[w(0x14e)](Type['String']({'minLength':0x1})),'entityType':Type['Optional'](Type[w(0x14c)]({'minLength':0x1})),'entityId':Type['Optional'](Type['String']({'minLength':0x1}))})}),'filePatch':Type['Object']({'entityType':Type['Optional'](Type['String']({'minLength':0x1})),'entityId':Type['Optional'](Type['String']({'minLength':0x1}))}),'resizeQuery':Type[w(0x14d)]({'width':Type['Optional'](Type[w(0x14f)]({'minimum':0x1,'default':0xc8})),'height':Type[w(0x14e)](Type['Integer']({'minimum':0x1})),'fit':Type['Optional'](Type['Union']([Type['Literal'](w(0x150)),Type['Literal'](w(0x151)),Type['Literal']('fill'),Type[w(0x152)]('inside'),Type['Literal'](w(0x153))]))})};
1
+ const h=k;function Q(){const n=['Object','String','Any','Optional','Integer','Union','cover','Literal','contain','outside'];Q=function(){return n;};return Q();}function k(h,n){h=h-0x146;const B=Q();let G=B[h];return G;}import{Type}from'@sinclair/typebox';export const fileSchemas={'fileId':Type['Object']({'id':Type['String']({'minLength':0x1,'maxLength':0x80})}),'fileToken':Type[h(0x146)]({'token':Type[h(0x147)]({'minLength':0x1,'maxLength':0x800})}),'fileDownloadQuery':Type['Object']({'download':Type['Optional'](Type['Boolean']())}),'filePath':Type[h(0x146)]({'*':Type[h(0x147)]({'minLength':0x1,'maxLength':0x400})}),'upload':Type['Object']({'file':Type[h(0x148)](),'metadata':Type['Object']({'name':Type[h(0x149)](Type['String']({'minLength':0x1})),'path':Type['Optional'](Type['String']({'minLength':0x1})),'entityType':Type['Optional'](Type['String']({'minLength':0x1})),'entityId':Type['Optional'](Type['String']({'minLength':0x1}))})}),'filePatch':Type['Object']({'entityType':Type[h(0x149)](Type['String']({'minLength':0x1})),'entityId':Type[h(0x149)](Type[h(0x147)]({'minLength':0x1}))}),'resizeQuery':Type['Object']({'width':Type['Optional'](Type[h(0x14a)]({'minimum':0x1,'default':0xc8})),'height':Type[h(0x149)](Type['Integer']({'minimum':0x1})),'fit':Type['Optional'](Type[h(0x14b)]([Type['Literal'](h(0x14c)),Type[h(0x14d)](h(0x14e)),Type[h(0x14d)]('fill'),Type['Literal']('inside'),Type['Literal'](h(0x14f))]))})};
@@ -1 +1 @@
1
- function z(){var X=['pathOrToken','file','get'];z=function(){return X;};return z();}function G(w,h){w=w-0x10b;var S=z();var X=S[w];return X;}import{NotFoundError}from'../../../errors.js';export async function getFile(w,h){var S=G;if(!h['file'])throw new Error('empty\x20file');if(!await h['file']['exists'](w['pathOrToken']))throw new NotFoundError('File\x20not\x20found'+w[S(0x10b)]);return h[S(0x10c)][S(0x10d)](w['pathOrToken']);}
1
+ import{NotFoundError}from'../../../errors.js';function k(h,n){h=h-0x113;var B=Q();var G=B[h];return G;}export async function getFile(h,n){var B=k;if(!n['file'])throw new Error(B(0x113));if(!await n['file'][B(0x114)](h['pathOrToken']))throw new NotFoundError(B(0x115)+h['pathOrToken']);return n['file'][B(0x116)](h['pathOrToken']);}function Q(){var G=['empty\x20file','exists','File\x20not\x20found','get'];Q=function(){return G;};return Q();}
@@ -1 +1 @@
1
- import{NotFoundError,ValidationError}from'../../../errors.js';function G(w,h){w=w-0x18e;const S=z();let X=S[w];return X;}import{fileTypeFromBuffer}from'file-type';import{createHash}from'node:crypto';import{mkdir,readFile,writeFile}from'node:fs/promises';import w from'node:path';import h from'sharp';function z(){const H=['pathOrToken','path','File\x20path\x20is\x20required','width','update','auto','fit','resolve','code','startsWith','Only\x20image\x20files\x20can\x20be\x20resized','resize'];z=function(){return H;};return z();}export async function resizeFile(S,X){const O=G,Y=S[O(0x18e)]??S[O(0x18f)];if(!Y)throw new ValidationError(O(0x190));const v=parseDimension(S[O(0x191)],O(0x191))??0xc8,D=parseDimension(S['height'],'height'),o=createHash('sha256')[O(0x192)](Y+':'+v+':'+(D??O(0x193))+':'+(S[O(0x194)]??'cover'))['digest']('hex'),q=w[O(0x195)]('logs','resize'),e=w['join'](q,o+'.jpg');try{return await readFile(e);}catch(V){if(V[O(0x196)]!=='ENOENT')throw V;}if(!await X['file']['exists'](Y))throw new NotFoundError('File\x20not\x20found');const Z=await X['file']['get'](Y),K=await fileTypeFromBuffer(Z);if(!K?.['mime'][O(0x197)]('image/'))throw new ValidationError(O(0x198));const y=await h(Z)[O(0x199)]({'width':v,'height':D,'fit':S['fit']??'cover'})['toBuffer']();return await mkdir(q,{'recursive':!![]}),await writeFile(e,y),y;}function parseDimension(S,X){if(S===undefined||S==='')return undefined;const Y=Number(S);if(!Number['isInteger'](Y)||Y<=0x0)throw new ValidationError(X+'\x20must\x20be\x20a\x20positive\x20integer');return Y;}
1
+ function Q(){const z=['path','height','digest','join','file','mime','Only\x20image\x20files\x20can\x20be\x20resized','resize'];Q=function(){return z;};return Q();}import{NotFoundError,ValidationError}from'../../../errors.js';import{fileTypeFromBuffer}from'file-type';import{createHash}from'node:crypto';import{mkdir,readFile,writeFile}from'node:fs/promises';import h from'node:path';import n from'sharp';export async function resizeFile(B,G){const p=k,f=B['pathOrToken']??B[p(0xc0)];if(!f)throw new ValidationError('File\x20path\x20is\x20required');const j=parseDimension(B['width'],'width')??0xc8,Z=parseDimension(B['height'],p(0xc1)),e=createHash('sha256')['update'](f+':'+j+':'+(Z??'auto')+':'+(B['fit']??'cover'))[p(0xc2)]('hex'),b=h['resolve']('logs','resize'),P=h[p(0xc3)](b,e+'.jpg');try{return await readFile(P);}catch(i){if(i['code']!=='ENOENT')throw i;}if(!await G['file']['exists'](f))throw new NotFoundError('File\x20not\x20found');const u=await G[p(0xc4)]['get'](f),X=await fileTypeFromBuffer(u);if(!X?.[p(0xc5)]['startsWith']('image/'))throw new ValidationError(p(0xc6));const H=await n(u)[p(0xc7)]({'width':j,'height':Z,'fit':B['fit']??'cover'})['toBuffer']();return await mkdir(b,{'recursive':!![]}),await writeFile(P,H),H;}function k(h,n){h=h-0xc0;const B=Q();let G=B[h];return G;}function parseDimension(B,G){if(B===undefined||B==='')return undefined;const f=Number(B);if(!Number['isInteger'](f)||f<=0x0)throw new ValidationError(G+'\x20must\x20be\x20a\x20positive\x20integer');return f;}
@@ -1 +1 @@
1
- import{fileTypeFromBuffer}from'file-type';function G(w,h){w=w-0x1da;const S=z();let X=S[w];return X;}import w from'../mime.js';import{randomUUID}from'node:crypto';function z(){const H=['getFullYear','metadata','resourceId','has','put','mimetype','pop','user'];z=function(){return H;};return z();}import{ValidationError}from'../../../errors.js';export async function uploadFile(h,S){const O=G,X=(h['metadata']['name']??randomUUID())['replace'](/[^a-zA-Z0-9._-]/g,'_'),Y=new Date(),v=String(Y[O(0x1da)]())['slice'](-0x2),D=String(Y['getMonth']()+0x1)['padStart'](0x2,'0'),o=String(Y['getDate']())['padStart'](0x2,'0'),q=h['metadata']['path']??(h[O(0x1db)]['resource']?h['metadata']['resource']+'/'+(h['metadata'][O(0x1dc)]??randomUUID())+'/'+X:null)??'uploads/'+v+'/'+D+'-'+o+'/'+X,e=await h['file']['toBuffer'](),Z=await fileTypeFromBuffer(e);if(!w[O(0x1dd)](h['file']['mimetype'])&&(Z?.['mime']?!w['has'](Z['mime']):!![]))throw new Error('Unsupported\x20file\x20type:\x20'+h['file']['mimetype']);const K=Boolean(h['metadata']['resource']&&h['metadata']['resourceId']);if(K){const V=await S['pg']['query']('SELECT\x20file_id\x20FROM\x20admin.files\x0a\x20\x20\x20\x20\x20\x20\x20WHERE\x20resource\x20=\x20$1\x20AND\x20resource_id\x20=\x20$2\x20AND\x20file_name\x20=\x20$3\x0a\x20\x20\x20\x20\x20\x20\x20LIMIT\x201',[h[O(0x1db)]['resource'],String(h[O(0x1db)]['resourceId']),X]);if((V['rowCount']??0x0)>0x0)throw new ValidationError('File\x20with\x20name\x20\x22'+X+'\x22\x20already\x20exists\x20for\x20resource\x20\x22'+h['metadata']['resource']+'\x22\x20and\x20id\x20\x22'+h['metadata']['resourceId']+'\x22');}await S['file'][O(0x1de)](q,e);const y=await S['pg']['query']('\x0a\x20\x20\x20\x20\x20\x20\x20\x20INSERT\x20INTO\x20admin.files\x20(resource,\x20resource_id,\x20file_path,\x20file_type,\x20size,\x20uploaded_name,\x20file_name,\x20ext,\x20status,\x20created_by)\x0a\x20\x20\x20\x20\x20\x20\x20\x20VALUES\x20($1,\x20$2,\x20$3,\x20$4,\x20$5,\x20$6,\x20$7,\x20$8,\x20$9,\x20$10)\x0a\x20\x20\x20\x20\x20\x20\x20\x20RETURNING\x20*\x0a\x20\x20\x20\x20\x20\x20',[h[O(0x1db)]['resource']??null,h[O(0x1db)]['resourceId']??null,q,h['file']['mimetype'],h['file']['file']['bytesRead'],h[O(0x1db)]['name'],X,h['file'][O(0x1df)]['split']('/')[O(0x1e0)]()??null,K?'attached':'pending',h[O(0x1e1)]?.['id']??null]);return{...y['rows'][0x0],'token':S['file']['create'](q)};}
1
+ import{fileTypeFromBuffer}from'file-type';import h from'../mime.js';function Q(){const z=['name','slice','path','metadata','toBuffer','mimetype','SELECT\x20file_id\x20FROM\x20admin.files\x0a\x20\x20\x20\x20\x20\x20\x20WHERE\x20resource\x20=\x20$1\x20AND\x20resource_id\x20=\x20$2\x20AND\x20file_name\x20=\x20$3\x0a\x20\x20\x20\x20\x20\x20\x20LIMIT\x201','\x22\x20already\x20exists\x20for\x20resource\x20\x22','resource','resourceId','put','file','pop','attached','pending','rows'];Q=function(){return z;};return Q();}import{randomUUID}from'node:crypto';function k(h,n){h=h-0x188;const B=Q();let G=B[h];return G;}import{ValidationError}from'../../../errors.js';export async function uploadFile(n,B){const p=k,G=(n['metadata'][p(0x188)]??randomUUID())['replace'](/[^a-zA-Z0-9._-]/g,'_'),f=new Date(),j=String(f['getFullYear']())[p(0x189)](-0x2),Z=String(f['getMonth']()+0x1)['padStart'](0x2,'0'),e=String(f['getDate']())['padStart'](0x2,'0'),b=n['metadata'][p(0x18a)]??(n['metadata']['resource']?n['metadata']['resource']+'/'+(n[p(0x18b)]['resourceId']??randomUUID())+'/'+G:null)??'uploads/'+j+'/'+Z+'-'+e+'/'+G,P=await n['file'][p(0x18c)](),u=await fileTypeFromBuffer(P);if(!h['has'](n['file']['mimetype'])&&(u?.['mime']?!h['has'](u['mime']):!![]))throw new Error('Unsupported\x20file\x20type:\x20'+n['file'][p(0x18d)]);const X=Boolean(n['metadata']['resource']&&n['metadata']['resourceId']);if(X){const i=await B['pg']['query'](p(0x18e),[n['metadata']['resource'],String(n['metadata']['resourceId']),G]);if((i['rowCount']??0x0)>0x0)throw new ValidationError('File\x20with\x20name\x20\x22'+G+p(0x18f)+n['metadata'][p(0x190)]+'\x22\x20and\x20id\x20\x22'+n['metadata'][p(0x191)]+'\x22');}await B['file'][p(0x192)](b,P);const H=await B['pg']['query']('\x0a\x20\x20\x20\x20\x20\x20\x20\x20INSERT\x20INTO\x20admin.files\x20(resource,\x20resource_id,\x20file_path,\x20file_type,\x20size,\x20uploaded_name,\x20file_name,\x20ext,\x20status,\x20created_by)\x0a\x20\x20\x20\x20\x20\x20\x20\x20VALUES\x20($1,\x20$2,\x20$3,\x20$4,\x20$5,\x20$6,\x20$7,\x20$8,\x20$9,\x20$10)\x0a\x20\x20\x20\x20\x20\x20\x20\x20RETURNING\x20*\x0a\x20\x20\x20\x20\x20\x20',[n['metadata']['resource']??null,n[p(0x18b)]['resourceId']??null,b,n['file']['mimetype'],n['file'][p(0x193)]['bytesRead'],n['metadata'][p(0x188)],G,n['file']['mimetype']['split']('/')[p(0x194)]()??null,X?p(0x195):p(0x196),n['user']?.['id']??null]);return{...H[p(0x197)][0x0],'token':B['file']['create'](b)};}
@@ -1 +1 @@
1
- {"version":3,"file":"route.d.ts","sourceRoot":"","sources":["../../../src/modules/resource/route.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAoBnD,wBAAgB,cAAc,CAAC,GAAG,EAAE,UAAU,GAAG,kBAAkB,CA8VlE"}
1
+ {"version":3,"file":"route.d.ts","sourceRoot":"","sources":["../../../src/modules/resource/route.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAwBnD,wBAAgB,cAAc,CAAC,GAAG,EAAE,UAAU,GAAG,kBAAkB,CAoblE"}