@opengis/fcore 0.0.1-beta.8 → 0.0.1-beta.9

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 (97) 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.js +1 -1
  26. package/dist/modules/resource/schema.js +1 -1
  27. package/dist/modules/resource/services/add-note.js +1 -1
  28. package/dist/modules/resource/services/add-resource-file.js +1 -1
  29. package/dist/modules/resource/services/create-resource-relation.js +1 -1
  30. package/dist/modules/resource/services/create-resource.js +1 -1
  31. package/dist/modules/resource/services/delete-resource-relation.js +1 -1
  32. package/dist/modules/resource/services/delete-resource.js +1 -1
  33. package/dist/modules/resource/services/export-resource.js +1 -1
  34. package/dist/modules/resource/services/get-resource.js +1 -1
  35. package/dist/modules/resource/services/list-resource-relation.js +1 -1
  36. package/dist/modules/resource/services/list-resources.js +1 -1
  37. package/dist/modules/resource/services/search-resource.js +1 -1
  38. package/dist/modules/resource/services/suggest-resource.js +1 -1
  39. package/dist/modules/resource/services/update-resource-relation.js +1 -1
  40. package/dist/modules/resource/services/update-resource.js +1 -1
  41. package/dist/modules/resource/services/upload-resource-file.js +1 -1
  42. package/dist/modules/system/route.js +1 -1
  43. package/dist/modules/system/schema.js +1 -1
  44. package/dist/modules/system/services/check-system.js +1 -1
  45. package/dist/modules/system/services/get-access.js +1 -1
  46. package/dist/modules/system/services/get-api-list.js +1 -1
  47. package/dist/modules/system/services/get-audit-log.js +1 -1
  48. package/dist/modules/system/services/get-dictionary.js +1 -1
  49. package/dist/modules/system/services/get-system-log.js +1 -1
  50. package/dist/modules/system/services/get-system-settings.js +1 -1
  51. package/dist/modules/system/services/list-dictionaries.js +1 -1
  52. package/dist/modules/system/services/set-access.js +1 -1
  53. package/dist/modules/system/services/update-dictionary.js +1 -1
  54. package/dist/modules/system/services/update-system-settings.js +1 -1
  55. package/dist/modules/utils/require-admin.js +1 -1
  56. package/dist/modules/utils/safe-user.js +1 -1
  57. package/dist/modules/utils/unsupported.js +1 -1
  58. package/dist/plugins/audit/audit.js +1 -1
  59. package/dist/plugins/audit/services/write-audit.js +1 -1
  60. package/dist/plugins/auth/get-user-permissions.js +1 -1
  61. package/dist/plugins/auth/index.js +1 -1
  62. package/dist/plugins/auth/verifyUser.js +1 -1
  63. package/dist/plugins/dictionary.js +1 -1
  64. package/dist/plugins/file.js +1 -1
  65. package/dist/plugins/jwt.js +1 -1
  66. package/dist/plugins/logger/index.js +1 -1
  67. package/dist/plugins/logger/transport.js +1 -1
  68. package/dist/plugins/pg.js +1 -1
  69. package/dist/plugins/redis.js +1 -1
  70. package/dist/plugins/resource/resource.js +1 -1
  71. package/dist/plugins/resource/resource.registry.js +1 -1
  72. package/dist/plugins/resource/resource.types.d.ts +6 -4
  73. package/dist/plugins/resource/resource.types.d.ts.map +1 -1
  74. package/dist/plugins/resource/services/add-dictionary-lookup-data.js +1 -1
  75. package/dist/plugins/resource/services/add-file-token.js +1 -1
  76. package/dist/plugins/resource/services/add-table-lookup-data.d.ts.map +1 -1
  77. package/dist/plugins/resource/services/add-table-lookup-data.js +1 -1
  78. package/dist/plugins/resource/services/create-relation.js +1 -1
  79. package/dist/plugins/resource/services/create.js +1 -1
  80. package/dist/plugins/resource/services/delete-relation.js +1 -1
  81. package/dist/plugins/resource/services/delete.js +1 -1
  82. package/dist/plugins/resource/services/find-one.js +1 -1
  83. package/dist/plugins/resource/services/find-relation.js +1 -1
  84. package/dist/plugins/resource/services/find.js +1 -1
  85. package/dist/plugins/resource/services/update-relation.js +1 -1
  86. package/dist/plugins/resource/services/update.js +1 -1
  87. package/dist/plugins/resource/utils/auto-index.js +1 -1
  88. package/dist/plugins/resource/utils/fields.js +1 -1
  89. package/dist/plugins/resource/utils/filters.js +1 -1
  90. package/dist/plugins/resource/utils/permissions.js +1 -1
  91. package/dist/plugins/resource/utils/sort.js +1 -1
  92. package/dist/plugins/resource/utils/sql.js +1 -1
  93. package/dist/shared/getIP.js +1 -1
  94. package/migrations/20260903130000_move_notes_files_to_admin.sql +17 -17
  95. package/migrations/20260903140000_settings_nulls_not_distinct.sql +18 -18
  96. package/migrations/20260907090000_core_schema.sql +32 -2
  97. package/package.json +93 -93
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
- function U(){const M=['development','true','split','Ch7QR4e73Jg0wx0xOjm','parse','session_user_auth','strict','none','includes','auth'];U=function(){return M;};return U();}import'dotenv/config';const DEFAULT_LOG_RESPONSE_STATUS_CODES=[0x193,0x199,0x19d,0x19f,0x1ad];function required(z){const j=process.env[z];if(!j)throw new Error('Missing\x20environment\x20variable:\x20'+z);return j;}function A(z,j){z=z-0xd3;const c=U();let p=c[z];return p;}export function loadConfig(z={}){const p=A,j={'env':process.env.NODE_ENV??p(0xd3),'debug':process.env.DEBUG===p(0xd4),'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)},'storagePath':process.env.STORAGE_PATH??'./storage','redactionList':(process.env.REDACTION_LIST||'password')['split'](','),'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[p(0xd5)](',')['map'](c=>c-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||p(0xd6),'user':process.env.AUTH_USER?JSON[p(0xd7)](process.env.AUTH_USER):undefined,'sessionTimeout':+(process.env.AUTH_SESSION_TIMEOUT||0x258),'secret':process.env.AUTH_SECRET??'x5y30KBsEKCENT04tu6549Vxx3No1ztJ2q2K8r79S59420RaZ5','cookieName':process.env.AUTH_COOKIE_NAME??p(0xd8),'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||p(0xd4)),'secure':Boolean(process.env.AUTH_COOKIE_OPTIONS_SECURE||'true'),'sameSite':process.env.AUTH_COOKIE_OPTIONS_SAME_SITE&&['lax',p(0xd9),p(0xda)][p(0xdb)](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{...j,...z,'logger':{...j['logger'],...z['logger']},'pg':{...j['pg'],...z['pg']},'redis':{...j['redis'],...z['redis']},'s3':{...j['s3'],...z['s3']},'auth':{...j['auth'],...z[p(0xdc)]}};}export{required as requireEnv};
1
+ function c(J,e){J=J-0x8e;const p=L();let b=p[J];return b;}import'dotenv/config';const DEFAULT_LOG_RESPONSE_STATUS_CODES=[0x193,0x199,0x19d,0x19f,0x1ad];function L(){const F=['false','split','/log','Ch7QR4e73Jg0wx0xOjm','parse','x5y30KBsEKCENT04tu6549Vxx3No1ztJ2q2K8r79S59420RaZ5','none','logger','auth'];L=function(){return F;};return L();}function required(J){const e=process.env[J];if(!e)throw new Error('Missing\x20environment\x20variable:\x20'+J);return e;}export function loadConfig(J={}){const b=c,e={'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===b(0x8e),'max':+(process.env.RATE_LIMIT_MAX||0x64),'timeWindow':+(process.env.RATE_LIMIT_TIME_WINDOW||0xea60)},'storagePath':process.env.STORAGE_PATH??'./storage','redactionList':(process.env.REDACTION_LIST||'password')[b(0x8f)](','),'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'](p=>p-0x0):DEFAULT_LOG_RESPONSE_STATUS_CODES,'directory':process.env.LOG_DIRECTORY||process['cwd']()+b(0x90)},'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||b(0x91),'user':process.env.AUTH_USER?JSON[b(0x92)](process.env.AUTH_USER):undefined,'sessionTimeout':+(process.env.AUTH_SESSION_TIMEOUT||0x258),'secret':process.env.AUTH_SECRET??b(0x93),'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',b(0x94)]['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{...e,...J,'logger':{...e[b(0x95)],...J['logger']},'pg':{...e['pg'],...J['pg']},'redis':{...e['redis'],...J['redis']},'s3':{...e['s3'],...J['s3']},'auth':{...e['auth'],...J[b(0x96)]}};}export{required as requireEnv};
package/dist/context.js CHANGED
@@ -1 +1 @@
1
- function U(){const c=['allSettled'];U=function(){return c;};return U();}let defaultContext;function A(z,j){z=z-0x7e;const c=U();let p=c[z];return p;}export function setContext(z){defaultContext=z;}export function getContext(){if(!defaultContext)throw new Error('Application\x20context\x20is\x20not\x20initialized');return defaultContext;}export function createContext(z){return{...z,async 'close'(){const j=A;await Promise[j(0x7e)]([z['redis']?.['close'](),z['pg']?.['end']()]),await z['logger']['close']();}};}
1
+ let defaultContext;function L(){const p=['close'];L=function(){return p;};return L();}export function setContext(J){defaultContext=J;}export function getContext(){if(!defaultContext)throw new Error('Application\x20context\x20is\x20not\x20initialized');return defaultContext;}function c(J,e){J=J-0x1ca;const p=L();let b=p[J];return b;}export function createContext(J){return{...J,async 'close'(){const e=c;await Promise['allSettled']([J['redis']?.[e(0x1ca)](),J['pg']?.['end']()]),await J['logger'][e(0x1ca)]();}};}
package/dist/errors.js CHANGED
@@ -1 +1 @@
1
- var M=A;function U(){var b=['code','details','name','Access\x20denied','Conflict','CONFLICT'];U=function(){return b;};return U();}export class FCoreError extends Error{[M(0xca)];['statusCode'];['details'];constructor(z,j,c=0x1f4,p){var H=M;super(j),this[H(0xca)]=z,this['statusCode']=c,this[H(0xcb)]=p,this[H(0xcc)]=new.target.name;}}export class BadRequestError extends FCoreError{constructor(z,j){super('BAD_REQUEST_ERROR',z,0x190,j);}}export class UnauthorizedError extends FCoreError{constructor(z='Authentication\x20required'){super('UNAUTHORIZED',z,0x191);}}export class ForbiddenError extends FCoreError{constructor(z=M(0xcd)){super('FORBIDDEN',z,0x193);}}export class NotFoundError extends FCoreError{constructor(z='Not\x20found'){super('NOT_FOUND',z,0x194);}}export class ConflictError extends FCoreError{constructor(z=M(0xce)){var i=M;super(i(0xcf),z,0x199);}}export class ValidationError extends FCoreError{constructor(z,j){super('VALIDATION_ERROR',z,0x1a6,j);}}function A(z,j){z=z-0xca;var c=U();var p=c[z];return p;}export class UnsupportedError extends FCoreError{constructor(z='Operation\x20is\x20not\x20configured'){super('UNSUPPORTED',z,0x1f5);}}
1
+ var h=c;function L(){var u=['name','FORBIDDEN','Conflict'];L=function(){return u;};return L();}export class FCoreError extends Error{['code'];['statusCode'];['details'];constructor(J,e,p=0x1f4,b){var F=c;super(e),this['code']=J,this['statusCode']=p,this['details']=b,this[F(0x116)]=new.target.name;}}export class BadRequestError extends FCoreError{constructor(J,e){super('BAD_REQUEST_ERROR',J,0x190,e);}}export class UnauthorizedError extends FCoreError{constructor(J='Authentication\x20required'){super('UNAUTHORIZED',J,0x191);}}function c(J,e){J=J-0x116;var p=L();var b=p[J];return b;}export class ForbiddenError extends FCoreError{constructor(J='Access\x20denied'){var P=c;super(P(0x117),J,0x193);}}export class NotFoundError extends FCoreError{constructor(J='Not\x20found'){super('NOT_FOUND',J,0x194);}}export class ConflictError extends FCoreError{constructor(J=h(0x118)){super('CONFLICT',J,0x199);}}export class ValidationError extends FCoreError{constructor(J,e){super('VALIDATION_ERROR',J,0x1a6,e);}}export class UnsupportedError extends FCoreError{constructor(J='Operation\x20is\x20not\x20configured'){super('UNSUPPORTED',J,0x1f5);}}
package/dist/fastify.js CHANGED
@@ -1 +1 @@
1
- function U(){const g=['toString','addHook','onRoute','method','package','fcore','tags','description','access','public','raw','user','admin','permissions','code','logger','includes','file','register','buffer','url'];U=function(){return g;};return U();}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(z,j,c){const Z=A,p=decodeURIComponent(j[Z(0x1c3)]())['split']('&')['reduce']((M,H)=>{const [i,b]=H['split']('=');return{...M,[i]:b};},{});c(null,p);}function A(z,j){z=z-0x1c3;const c=U();let p=c[z];return p;}export default function fcoreFastify(z,j){return async c=>{const e=A;c['decorate']('ctx',z);const {config:p}=z,M=new Map();c[e(0x1c4)](e(0x1c5),i=>{const o=e;if(i['url']['startsWith']('/api/')){const b=i['schema'],n=Array['isArray'](i[o(0x1c6)])?i['method']:[i['method']];for(const v of n){if(v==='HEAD')continue;const r={'method':v,'endpoint':i['url'],'package':b?.[o(0x1c7)]??o(0x1c8),'tags':b?.[o(0x1c9)]??[],'summary':b?.['summary']??'','description':b?.[o(0x1ca)]??'','access':b?.[o(0x1cb)]??o(0x1cc),'permissions':b?.['permissions']??[]};M['set'](v+'\x20'+i['url'],r);}}}),c['addHook']('preHandler',async i=>{const P=e,b=M['get'](i['method']+'\x20'+i['routeOptions']['url']),n=i[P(0x1cd)]['headers']?.['authorization'],v=n?.['startsWith']('Bearer\x20')?n['slice'](0x7):null,r=i['user']??(v?await jwtVerifyToken(v):null);!i[P(0x1ce)]&&v&&process.env.AUTH_JWT_SECRET&&(i['user']=await jwtVerifyToken(v));if(!b?.[P(0x1cb)])throw new Error('Route\x20access\x20not\x20defined');if(b['access']==='public')return!![];if(!r)throw new ForbiddenError('User\x20required');if(b[P(0x1cb)]==='user'&&!b['permissions']?.['length'])return!![];if(r['type']==P(0x1cf))return!![];if(b['access']==='admin')throw new ForbiddenError('Admin\x20access\x20required');for(const q of b[P(0x1d0)]){if(!r[P(0x1d0)]?.['includes'](q))throw new ForbiddenError('Missing\x20permission:\x20'+q);}return!![];}),await createSessionStore(c,z),await c['register'](import('@fastify/multipart'),{'limits':{'fileSize':p['maxFileSize']*0x400*0x400}}),c['setErrorHandler']((i,b,n)=>{const t=e;if(i instanceof FCoreError||i['code']==='FST_ERR_VALIDATION')return n['code'](i['statusCode'])['send']({'error':i[t(0x1d1)],'message':i['message'],'details':i['details']});return z[t(0x1d2)]['error'](i),(p['debug']||process.env.NODE_ENV==='test'||process.env.VITEST)&&console['error'](i),n['code'](0x1f4)['send']({'error':'INTERNAL_ERROR','message':'Internal\x20server\x20error'});});const H=i=>!j||j[e(0x1d3)](i);if(H('auth'))await c['register'](authRoutes(z));if(H('resource'))await c['register'](resourceRoutes(z));if(H(e(0x1d4)))await c['register'](fileRoutes(z));if(H('system'))await c[e(0x1d5)](systemRoutes(z,M));c['addContentTypeParser']('application/x-www-form-urlencoded',{'parseAs':e(0x1d6)},urlencodedContentParser),!p['rateLimit']?.['disabled']?c['register'](import('@fastify/rate-limit'),{'max':p['rateLimit']?.['max']||0x64,'timeWindow':p['rateLimit']?.['timeWindow']||0xea60,'hook':'preHandler','global':!![],'keyGenerator':i=>(i['user']?.['id']||i['ip'])+'-'+i['raw'][e(0x1d7)]['split']('?')[0x0]}):console['log']('⚠️\x20rate\x20limit\x20is\x20disabled');};};
1
+ function L(){const a=['toString','isArray','method','package','public','addHook','preHandler','authorization','startsWith','Bearer\x20','access','Route\x20access\x20not\x20defined','User\x20required','user','permissions','includes','Missing\x20permission:\x20','register','code','logger','error','send','resource','buffer','disabled','@fastify/rate-limit','max'];L=function(){return a;};return L();}import{FCoreError}from'./errors.js';import{authRoutes}from'./modules/auth/route.js';import{fileRoutes}from'./modules/file/route.js';function c(J,e){J=J-0x152;const p=L();let b=p[J];return b;}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(J,e,p){const X=c,b=decodeURIComponent(e[X(0x152)]())['split']('&')['reduce']((F,P)=>{const [h,u]=P['split']('=');return{...F,[h]:u};},{});p(null,b);}export default function fcoreFastify(J,e){return async p=>{const Q=c;p['decorate']('ctx',J);const {config:b}=J,F=new Map();p['addHook']('onRoute',h=>{const E=c;if(h['url']['startsWith']('/api/')){const u=h['schema'],H=Array[E(0x153)](h[E(0x154)])?h[E(0x154)]:[h[E(0x154)]];for(const D of H){if(D==='HEAD')continue;const U={'method':D,'endpoint':h['url'],'package':u?.[E(0x155)]??'fcore','tags':u?.['tags']??[],'summary':u?.['summary']??'','description':u?.['description']??'','access':u?.['access']??E(0x156),'permissions':u?.['permissions']??[]};F['set'](D+'\x20'+h['url'],U);}}}),p[Q(0x157)](Q(0x158),async h=>{const T=Q,u=F['get'](h['method']+'\x20'+h['routeOptions']['url']),H=h['raw']['headers']?.[T(0x159)],D=H?.[T(0x15a)](T(0x15b))?H['slice'](0x7):null,U=h['user']??(D?await jwtVerifyToken(D):null);!h['user']&&D&&process.env.AUTH_JWT_SECRET&&(h['user']=await jwtVerifyToken(D));if(!u?.[T(0x15c)])throw new Error(T(0x15d));if(u[T(0x15c)]===T(0x156))return!![];if(!U)throw new ForbiddenError(T(0x15e));if(u[T(0x15c)]===T(0x15f)&&!u[T(0x160)]?.['length'])return!![];if(U['type']=='admin')return!![];if(u['access']==='admin')throw new ForbiddenError('Admin\x20access\x20required');for(const w of u[T(0x160)]){if(!U['permissions']?.[T(0x161)](w))throw new ForbiddenError(T(0x162)+w);}return!![];}),await createSessionStore(p,J),await p[Q(0x163)](import('@fastify/multipart'),{'limits':{'fileSize':b['maxFileSize']*0x400*0x400}}),p['setErrorHandler']((h,u,H)=>{const l=Q;if(h instanceof FCoreError||h['code']==='FST_ERR_VALIDATION')return H[l(0x164)](h['statusCode'])['send']({'error':h['code'],'message':h['message'],'details':h['details']});return J[l(0x165)]['error'](h),(b['debug']||process.env.NODE_ENV==='test'||process.env.VITEST)&&console[l(0x166)](h),H[l(0x164)](0x1f4)[l(0x167)]({'error':'INTERNAL_ERROR','message':'Internal\x20server\x20error'});});const P=h=>!e||e['includes'](h);if(P('auth'))await p['register'](authRoutes(J));if(P(Q(0x168)))await p[Q(0x163)](resourceRoutes(J));if(P('file'))await p['register'](fileRoutes(J));if(P('system'))await p['register'](systemRoutes(J,F));p['addContentTypeParser']('application/x-www-form-urlencoded',{'parseAs':Q(0x169)},urlencodedContentParser),!b['rateLimit']?.[Q(0x16a)]?p[Q(0x163)](import(Q(0x16b)),{'max':b['rateLimit']?.[Q(0x16c)]||0x64,'timeWindow':b['rateLimit']?.['timeWindow']||0xea60,'hook':Q(0x158),'global':!![],'keyGenerator':h=>(h['user']?.['id']||h['ip'])+'-'+h['raw']['url']['split']('?')[0x0]}):console['log']('⚠️\x20rate\x20limit\x20is\x20disabled');};};
package/dist/fcore.js CHANGED
@@ -1 +1 @@
1
- function U(){const q=['config','redis','endpoint','bucket','register'];U=function(){return q;};return U();}import{loadConfig}from'./config.js';import{createContext,setContext}from'./context.js';function A(z,j){z=z-0x10e;const c=U();let p=c[z];return p;}import{createAudit,createDatabase,createDictionary,createFileS3,createLogger,createRedis,createResource}from'./plugins/index.js';export async function createFCore(z={}){const r=A,j=loadConfig(z[r(0x10e)]),c=createRedis(j[r(0x10f)]),p=createLogger(),M=createDatabase(j['pg']),H=createFileS3({'endpoint':j['s3'][r(0x110)],'region':j['s3']['region'],'bucket':j['s3'][r(0x111)],'accessKey':j['s3']['accessKey'],'secretKey':j['s3']['secretKey'],'folder':j['s3']['folder'],'forcePathStyle':j['s3']['forcePathStyle'],'tokenSecret':j['s3']['tokenSecret'],'tokenTtl':j['s3']['tokenTtl']}),i=createAudit({'pg':M,'logger':p}),b=createDictionary({'pg':M,'dictionaries':z['dictionaries']}),n=createResource({'pg':M,'logger':p,'audit':i,'dictionary':b,'file':H});z['resources']?.['length']&&n[r(0x112)](z['resources']);const v=createContext({'config':j,'logger':p,'redis':c,'pg':M,'file':H,'resource':n,'audit':i,'dictionary':b});return setContext(v),v;}
1
+ import{loadConfig}from'./config.js';import{createContext,setContext}from'./context.js';function L(){const w=['config','redis','endpoint','bucket','accessKey','secretKey'];L=function(){return w;};return L();}function c(J,e){J=J-0xc7;const p=L();let b=p[J];return b;}import{createAudit,createDatabase,createDictionary,createFileS3,createLogger,createRedis,createResource}from'./plugins/index.js';export async function createFCore(J={}){const U=c,e=loadConfig(J[U(0xc7)]),p=createRedis(e[U(0xc8)]),b=createLogger(),F=createDatabase(e['pg']),P=createFileS3({'endpoint':e['s3'][U(0xc9)],'region':e['s3']['region'],'bucket':e['s3'][U(0xca)],'accessKey':e['s3'][U(0xcb)],'secretKey':e['s3'][U(0xcc)],'folder':e['s3']['folder'],'forcePathStyle':e['s3']['forcePathStyle'],'tokenSecret':e['s3']['tokenSecret'],'tokenTtl':e['s3']['tokenTtl']}),h=createAudit({'pg':F,'logger':b}),u=createDictionary({'pg':F,'dictionaries':J['dictionaries']}),H=createResource({'pg':F,'logger':b,'audit':h,'dictionary':u,'file':P});J['resources']?.['length']&&H['register'](J['resources']);const D=createContext({'config':e,'logger':b,'redis':p,'pg':F,'file':P,'resource':H,'audit':h,'dictionary':u});return setContext(D),D;}
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- const j=A;function A(z,j){z=z-0x1ef;const c=U();let p=c[z];return p;}function U(){const c=['log','status','SKIP'];U=function(){return c;};return U();}import{runMigrations}from'./runner.js';import{loadConfig}from'../config.js';try{const config=loadConfig();console['log']('Loaded\x20configuration:',config['pg']);for(const r of await runMigrations({'database':config['pg']}))console[j(0x1ef)]((r[j(0x1f0)]==='run'?'OK\x20\x20':j(0x1f1))+'\x20'+r['file']);}catch(z){console['error'](z),process['exitCode']=0x1;}
2
+ function L(){const p=['log','exitCode'];L=function(){return p;};return L();}const e=c;import{runMigrations}from'./runner.js';function c(J,e){J=J-0xb2;const p=L();let b=p[J];return b;}import{loadConfig}from'../config.js';try{const config=loadConfig();console['log']('Loaded\x20configuration:',config['pg']);for(const r of await runMigrations({'database':config['pg']}))console[e(0xb2)]((r['status']==='run'?'OK\x20\x20':'SKIP')+'\x20'+r['file']);}catch(J){console['error'](J),process[e(0xb3)]=0x1;}
@@ -1 +1 @@
1
- import z from'node:fs/promises';import j from'node:path';function U(){const P=['DATABASE_URL\x20or\x20database\x20config\x20is\x20required','query','map','.sql','sort','skip','readFile','INSERT\x20INTO\x20schema_migrations(version)\x20VALUES\x20($1)','ROLLBACK','run'];U=function(){return P;};return U();}function A(z,j){z=z-0x79;const c=U();let p=c[z];return p;}import{createDatabase}from'../plugins/pg.js';export async function runMigrations(c={}){const o=A,p=j['resolve'](c['dir']??'migrations'),M=c['database']??databaseFromUrl(c['databaseUrl']??process.env.DATABASE_URL);if(!M)throw new Error(o(0x79));const H=createDatabase(M);if(!H)throw new Error('empty\x20pg');const i=[];try{await H[o(0x7a)]('\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 b=await H['query']('SELECT\x20version\x20FROM\x20schema_migrations'),n=new Set(b['rows'][o(0x7b)](r=>r['version'])),v=(await z['readdir'](p))['filter'](r=>r['endsWith'](o(0x7c)))[o(0x7d)]();for(const r of v){if(n['has'](r)){i['push']({'file':r,'status':o(0x7e)});continue;}const q=await z[o(0x7f)](j['join'](p,r),'utf8'),Z=await H['connect']();try{await Z['query']('BEGIN'),await Z[o(0x7a)](q),await Z[o(0x7a)](o(0x80),[r]),await Z[o(0x7a)]('COMMIT');}catch(e){await Z[o(0x7a)](o(0x81));throw e;}finally{Z['release']();}i['push']({'file':r,'status':o(0x82)});}return i;}finally{await H['end']();}}function databaseFromUrl(c){if(!c)return undefined;const p=new URL(c);return{'host':p['hostname'],'port':Number(p['port']||0x1538),'database':p['pathname']['slice'](0x1),'user':decodeURIComponent(p['username']),'password':decodeURIComponent(p['password'])};}
1
+ import J from'node:fs/promises';import e from'node:path';import{createDatabase}from'../plugins/pg.js';export async function runMigrations(p={}){const Q=c,b=e[Q(0x86)](p['dir']??'migrations'),F=p['database']??databaseFromUrl(p['databaseUrl']??process.env.DATABASE_URL);if(!F)throw new Error(Q(0x87));const P=createDatabase(F);if(!P)throw new Error('empty\x20pg');const h=[];try{await P['query'](Q(0x88));const u=await P['query']('SELECT\x20version\x20FROM\x20schema_migrations'),H=new Set(u['rows']['map'](U=>U[Q(0x89)])),D=(await J['readdir'](b))[Q(0x8a)](U=>U['endsWith']('.sql'))['sort']();for(const U of D){if(H['has'](U)){h['push']({'file':U,'status':'skip'});continue;}const w=await J['readFile'](e['join'](b,U),'utf8'),X=await P['connect']();try{await X[Q(0x8b)]('BEGIN'),await X[Q(0x8b)](w),await X['query']('INSERT\x20INTO\x20schema_migrations(version)\x20VALUES\x20($1)',[U]),await X['query'](Q(0x8c));}catch(E){await X['query']('ROLLBACK');throw E;}finally{X[Q(0x8d)]();}h['push']({'file':U,'status':'run'});}return h;}finally{await P['end']();}}function c(J,e){J=J-0x86;const p=L();let b=p[J];return b;}function databaseFromUrl(p){if(!p)return undefined;const b=new URL(p);return{'host':b['hostname'],'port':Number(b['port']||0x1538),'database':b['pathname']['slice'](0x1),'user':decodeURIComponent(b['username']),'password':decodeURIComponent(b['password'])};}function L(){const T=['resolve','DATABASE_URL\x20or\x20database\x20config\x20is\x20required','\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','version','filter','query','COMMIT','release'];L=function(){return T;};return L();}
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- const c=A;import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';function U(){const p=['error','exitCode'];U=function(){return p;};return U();}import z from'./services/registration.js';const [user,password,type]=process['argv']['slice'](0x2);function A(z,j){z=z-0x11f;const c=U();let p=c[z];return p;}if(!user||!password)console[c(0x11f)]('Usage:\x20fcore-registration\x20<login>\x20<password>\x20[type]'),process['exitCode']=0x1;else{const pg=createDatabase(loadConfig()['pg']);try{const {user:data}=await z({'user':user,'password':password,'type':type},{'pg':pg});console['log']('Registered\x20user\x20'+data['id']+'\x20('+data['type']+')');}catch(j){console[c(0x11f)](j),process[c(0x120)]=0x1;}finally{await pg['end']();}}
2
+ const p=c;function c(J,e){J=J-0x1ea;const p=L();let b=p[J];return b;}import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';import J from'./services/registration.js';const [user,password,type]=process['argv']['slice'](0x2);function L(){const b=['Usage:\x20fcore-registration\x20<login>\x20<password>\x20[type]','exitCode','error','end'];L=function(){return b;};return L();}if(!user||!password)console['error'](p(0x1ea)),process[p(0x1eb)]=0x1;else{const pg=createDatabase(loadConfig()['pg']);try{const {user:data}=await J({'user':user,'password':password,'type':type},{'pg':pg});console['log']('Registered\x20user\x20'+data['id']+'\x20('+data['type']+')');}catch(e){console[p(0x1ec)](e),process['exitCode']=0x1;}finally{await pg[p(0x1ed)]();}}
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- const c=A;import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';import z from'./services/change-password.js';const [login,password]=process['argv']['slice'](0x2);function A(z,j){z=z-0x1a8;const c=U();let p=c[z];return p;}function U(){const p=['error','rows','exitCode','end'];U=function(){return p;};return U();}if(!login||!password)console[c(0x1a8)]('Usage:\x20fcore-password\x20<login>\x20<password>'),process['exitCode']=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[c(0x1a9)][0x0];if(!user)throw new Error('User\x20not\x20found');await z({'userId':user['id'],'password':password},{'pg':pg}),console['log']('Password\x20changed\x20for\x20'+login);}catch(j){console['error'](j),process[c(0x1aa)]=0x1;}finally{await pg[c(0x1ab)]();}}
2
+ const p=c;import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';import J from'./services/change-password.js';function L(){const b=['argv','slice','rows'];L=function(){return b;};return L();}const [login,password]=process[p(0xb3)][p(0xb4)](0x2);function c(J,e){J=J-0xb3;const p=L();let b=p[J];return b;}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['query']('SELECT\x20uid\x20AS\x20id\x20FROM\x20admin.users\x20WHERE\x20$1\x20IN\x20(login,\x20email,\x20phone)\x20LIMIT\x201',[login]),user=result[p(0xb5)][0x0];if(!user)throw new Error('User\x20not\x20found');await J({'userId':user['id'],'password':password},{'pg':pg}),console['log']('Password\x20changed\x20for\x20'+login);}catch(e){console['error'](e),process['exitCode']=0x1;}finally{await pg['end']();}}
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- const n=A;import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';const SYSTEM_ACTIONS=['logs','audit',n(0xf0),'check','access','settings',n(0xf1)],RESOURCE_ACTIONS=['read',n(0xf2),'create',n(0xf3)],[login,permissionArg]=process['argv']['slice'](0x2);function U(){const r=['list','dictionaries','update','delete','map','trim','filter','includes','system','Usage:\x20fcore-permission\x20<login>\x20<system|resource|resource:action[,...]|clear>','exitCode','query','DELETE\x20FROM\x20admin.role_access\x20WHERE\x20user_uid\x20=\x20$1\x20AND\x20role_id\x20IS\x20NULL','Permissions\x20cleared\x20for\x20','get','push','connect','actions','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)'];U=function(){return r;};return U();}function A(z,j){z=z-0xf0;const c=U();let p=c[z];return p;}function expandPermissions(z){const v=n,j=z['split'](',')[v(0xf4)](p=>p[v(0xf5)]())[v(0xf6)](Boolean),c=new Set();for(const p of j){if(p[v(0xf7)](':')){c['add'](p);continue;}const M=p===v(0xf8)?SYSTEM_ACTIONS:RESOURCE_ACTIONS;for(const H of M){c['add'](p+':'+H);}}return[...c];}if(!login||!permissionArg)console['error'](n(0xf9)),process[n(0xfa)]=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');if(permissionArg['trim']()==='clear')await pg[n(0xfb)](n(0xfc),[user['id']]),console['log'](n(0xfd)+login);else{const permissions=expandPermissions(permissionArg),byResource=new Map();for(const permission of permissions){const [resource,action]=permission['split'](':'),actions=byResource[n(0xfe)](resource)??[];actions[n(0xff)](action),byResource['set'](resource,actions);}const client=await pg[n(0x100)]();try{await client[n(0xfb)]('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[n(0x101)]??[],...actions])];await client['query']('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',[merged,user['id'],row[n(0x102)]]);}else await client[n(0xfb)](n(0x103),[resource,actions,user['id'],user['id']]);}await client['query']('COMMIT');}catch(i){await client['query']('ROLLBACK');throw i;}finally{client['release']();}console['log']('Granted\x20permissions\x20for\x20'+login+':\x20'+permissions['join'](',\x20'));}}catch(b){console['error'](b),process['exitCode']=0x1;}finally{await pg['end']();}}
2
+ const H=c;function L(){const U=['logs','list','check','argv','split','trim','filter','add','exitCode','clear','DELETE\x20FROM\x20admin.role_access\x20WHERE\x20user_uid\x20=\x20$1\x20AND\x20role_id\x20IS\x20NULL','query','rows','actions','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)','ROLLBACK','release','log','Granted\x20permissions\x20for\x20'];L=function(){return U;};return L();}import{loadConfig}from'../../config.js';import{createDatabase}from'../../plugins/pg.js';const SYSTEM_ACTIONS=[H(0x1ce),'audit',H(0x1cf),H(0x1d0),'access','settings','dictionaries'],RESOURCE_ACTIONS=['read','update','create','delete'],[login,permissionArg]=process[H(0x1d1)]['slice'](0x2);function c(J,e){J=J-0x1ce;const p=L();let b=p[J];return b;}function expandPermissions(J){const D=H,e=J[D(0x1d2)](',')['map'](b=>b[D(0x1d3)]())[D(0x1d4)](Boolean),p=new Set();for(const b of e){if(b['includes'](':')){p[D(0x1d5)](b);continue;}const F=b==='system'?SYSTEM_ACTIONS:RESOURCE_ACTIONS;for(const P of F){p['add'](b+':'+P);}}return[...p];}if(!login||!permissionArg)console['error']('Usage:\x20fcore-permission\x20<login>\x20<system|resource|resource:action[,...]|clear>'),process[H(0x1d6)]=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');if(permissionArg['trim']()===H(0x1d7))await pg['query'](H(0x1d8),[user['id']]),console['log']('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['push'](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[H(0x1d9)]('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[H(0x1da)][0x0];if(row){const merged=[...new Set([...row[H(0x1db)]??[],...actions])];await client['query']('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',[merged,user['id'],row['access_id']]);}else await client['query'](H(0x1dc),[resource,actions,user['id'],user['id']]);}await client['query']('COMMIT');}catch(h){await client['query'](H(0x1dd));throw h;}finally{client[H(0x1de)]();}console[H(0x1df)](H(0x1e0)+login+':\x20'+permissions['join'](',\x20'));}}catch(u){console['error'](u),process['exitCode']=0x1;}finally{await pg['end']();}}
@@ -1 +1 @@
1
- function U(){const g=['query','body','permissions','twoFactorRedirect','config','session','auth','Authenticates\x20a\x20user\x20and\x20returns\x20a\x20bearer\x20access\x20token.','post','Sign\x20in','Creates\x20a\x20regular\x20user\x20account.','user:create','credentials','fcore','Changes\x20the\x20password\x20for\x20the\x20current\x20user.','user','cookieName','Returns\x20the\x20authenticated\x20user\x27s\x20safe\x20profile.'];U=function(){return g;};return U();}import{getUserPermissions,verifyUser}from'../../plugins/auth/index.js';function A(z,j){z=z-0x15b;const c=U();let p=c[z];return p;}import z from'./services/get-current-user.js';import j from'./services/registration.js';import c from'./services/change-password.js';import{authSchemas}from'./schema.js';import p from'../../shared/getIP.js';import{UnauthorizedError}from'../../errors.js';export function authRoutes(M){return async H=>{const o=A,i=async b=>{const e=A,n=b['method']==='GET'?b[e(0x15b)]:b[e(0x15c)],v=p(b),r=await verifyUser({...n,'ip':v},M);r[e(0x15d)]=await getUserPermissions(r['id'],M);const q=r['twofa']?M['config']['auth'][e(0x15e)]:M['config']['auth']['redirect'];await b['login'](r);const Z=M[e(0x15f)]['auth']['sessionTimeout']*0x3e8*0x3c;return b[e(0x160)]?.['cookie']&&(b['session']['cookie']['maxAge']=Z),await b['session']['save'](),await M['audit']?.['write']?.({'module':e(0x161),'resource':'session','resourceId':b['session']['sessionId'],'action':'login','userId':r['id'],'ipAddress':v}),{'user':{'id':r['id'],'type':r['type'],'permissions':r['permissions']},'redirectUrl':q};};H['get']('/api/auth/login',{'schema':{'tags':['fcore','auth'],'summary':'Sign\x20in','description':o(0x162),'access':'public','permissions':[],'querystring':authSchemas['credentials']}},i),H[o(0x163)]('/api/auth/login',{'schema':{'tags':['fcore',o(0x161)],'summary':o(0x164),'description':'Authenticates\x20a\x20user\x20and\x20returns\x20a\x20bearer\x20access\x20token.','access':'public','permissions':[],'body':authSchemas['credentials']}},i),H[o(0x163)]('/api/auth/registration',{'schema':{'tags':['fcore','auth'],'summary':'Register','description':o(0x165),'access':'admin','permissions':[o(0x166)],'body':authSchemas[o(0x167)]}},async b=>j(b[o(0x15c)],M)),H['post']('/api/auth/password',{'schema':{'tags':[o(0x168),'auth'],'summary':'Change\x20password','description':o(0x169),'access':'user','permissions':[],'body':authSchemas['password']}},async b=>{const P=o;if(!b[P(0x16a)])throw new UnauthorizedError('Not\x20authorized');return await c({'userId':b[P(0x16a)]['id'],...b['body']},M),{'success':!![]};}),H['post']('/api/auth/logout',{'schema':{'tags':['fcore','auth'],'summary':'Sign\x20out','description':'Terminates\x20the\x20current\x20user\x20session.','access':'user','permissions':[]}},async(b,n)=>{const t=o,v={'redirectUrl':'/'};if(!b[t(0x16a)])return v;return await M['audit']?.['write']?.({'module':t(0x161),'resource':'session','resourceId':b['session']['sessionId'],'action':'logout','userId':b['user']?.['id']}),await b['session']['destroy'](),n['clearCookie'](M[t(0x15f)][t(0x161)][t(0x16b)]),Object['defineProperty'](b,'session',{'value':null,'writable':![],'configurable':![]}),v;}),H['get']('/api/auth/user',{'schema':{'tags':['fcore','auth'],'summary':'Get\x20current\x20user','description':o(0x16c),'access':'user','permissions':[],'querystring':authSchemas['query']}},async b=>z({'user':b[o(0x16a)],'token':b['query']['token']}));};}
1
+ function L(){const a=['GET','body','auth','redirect','session','cookie','sessionId','login','type','get','Sign\x20in','post','fcore','Register','/api/auth/password','Change\x20password','user','/api/auth/logout','Sign\x20out','defineProperty','token'];L=function(){return a;};return L();}import{getUserPermissions,verifyUser}from'../../plugins/auth/index.js';import J from'./services/get-current-user.js';import e from'./services/registration.js';import p from'./services/change-password.js';import{authSchemas}from'./schema.js';import b from'../../shared/getIP.js';import{UnauthorizedError}from'../../errors.js';function c(J,e){J=J-0x15a;const p=L();let b=p[J];return b;}export function authRoutes(F){return async P=>{const Q=c,h=async u=>{const E=c,H=u['method']===E(0x15a)?u['query']:u[E(0x15b)],D=b(u),U=await verifyUser({...H,'ip':D},F);U['permissions']=await getUserPermissions(U['id'],F);const w=U['twofa']?F['config'][E(0x15c)]['twoFactorRedirect']:F['config']['auth'][E(0x15d)];await u['login'](U);const X=F['config'][E(0x15c)]['sessionTimeout']*0x3e8*0x3c;return u[E(0x15e)]?.['cookie']&&(u[E(0x15e)][E(0x15f)]['maxAge']=X),await u['session']['save'](),await F['audit']?.['write']?.({'module':E(0x15c),'resource':E(0x15e),'resourceId':u['session'][E(0x160)],'action':E(0x161),'userId':U['id'],'ipAddress':D}),{'user':{'id':U['id'],'type':U[E(0x162)],'permissions':U['permissions']},'redirectUrl':w};};P[Q(0x163)]('/api/auth/login',{'schema':{'tags':['fcore','auth'],'summary':Q(0x164),'description':'Authenticates\x20a\x20user\x20and\x20returns\x20a\x20bearer\x20access\x20token.','access':'public','permissions':[],'querystring':authSchemas['credentials']}},h),P[Q(0x165)]('/api/auth/login',{'schema':{'tags':['fcore','auth'],'summary':'Sign\x20in','description':'Authenticates\x20a\x20user\x20and\x20returns\x20a\x20bearer\x20access\x20token.','access':'public','permissions':[],'body':authSchemas['credentials']}},h),P['post']('/api/auth/registration',{'schema':{'tags':[Q(0x166),'auth'],'summary':Q(0x167),'description':'Creates\x20a\x20regular\x20user\x20account.','access':'admin','permissions':['user:create'],'body':authSchemas['credentials']}},async u=>e(u[Q(0x15b)],F)),P[Q(0x165)](Q(0x168),{'schema':{'tags':[Q(0x166),'auth'],'summary':Q(0x169),'description':'Changes\x20the\x20password\x20for\x20the\x20current\x20user.','access':'user','permissions':[],'body':authSchemas['password']}},async u=>{const T=Q;if(!u[T(0x16a)])throw new UnauthorizedError('Not\x20authorized');return await p({'userId':u['user']['id'],...u[T(0x15b)]},F),{'success':!![]};}),P['post'](Q(0x16b),{'schema':{'tags':['fcore','auth'],'summary':Q(0x16c),'description':'Terminates\x20the\x20current\x20user\x20session.','access':'user','permissions':[]}},async(u,H)=>{const l=Q,D={'redirectUrl':'/'};if(!u[l(0x16a)])return D;return await F['audit']?.['write']?.({'module':'auth','resource':'session','resourceId':u['session']['sessionId'],'action':'logout','userId':u['user']?.['id']}),await u[l(0x15e)]['destroy'](),H['clearCookie'](F['config']['auth']['cookieName']),Object[l(0x16d)](u,'session',{'value':null,'writable':![],'configurable':![]}),D;}),P['get']('/api/auth/user',{'schema':{'tags':['fcore','auth'],'summary':'Get\x20current\x20user','description':'Returns\x20the\x20authenticated\x20user\x27s\x20safe\x20profile.','access':'user','permissions':[],'querystring':authSchemas['query']}},async u=>J({'user':u[Q(0x16a)],'token':u['query'][Q(0x16e)]}));};}
@@ -1 +1 @@
1
- function U(){const j=['Object','String'];U=function(){return j;};return U();}const z=A;function A(z,j){z=z-0x1ac;const c=U();let p=c[z];return p;}import{Type}from'@sinclair/typebox';export const authSchemas={'query':Type[z(0x1ac)]({'token':Type['Optional'](Type['Boolean']())}),'credentials':Type['Object']({'user':Type['String']({'minLength':0x1,'maxLength':0x64}),'password':Type[z(0x1ad)]({'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['Optional'](Type['String']({'minLength':0x1,'maxLength':0x64}))}),'twoFactor':Type[z(0x1ac)]({'code':Type['String']({'minLength':0x1})})};
1
+ const J=c;import{Type}from'@sinclair/typebox';function L(){const e=['String','Object'];L=function(){return e;};return L();}function c(J,e){J=J-0x6b;const p=L();let b=p[J];return b;}export const authSchemas={'query':Type['Object']({'token':Type['Optional'](Type['Boolean']())}),'credentials':Type['Object']({'user':Type[J(0x6b)]({'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[J(0x6b)]({'minLength':0x1,'maxLength':0x64}),'id':Type['Optional'](Type['String']({'minLength':0x1,'maxLength':0x64}))}),'twoFactor':Type[J(0x6c)]({'code':Type['String']({'minLength':0x1})})};
@@ -1 +1 @@
1
- import{hashPassword}from'../../../plugins/auth/index.js';export default async function changePassword({id:z,password:j,userId:c},{pg:p}){const M=await hashPassword(j);await p['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',[M,z||c,c]);}
1
+ import{hashPassword}from'../../../plugins/auth/index.js';export default async function changePassword({id:J,password:e,userId:p},{pg:b}){const F=await hashPassword(e);await b['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',[F,J||p,p]);}
@@ -1 +1 @@
1
- import{safeUser}from'../../utils/safe-user.js';export default async function getCurrentUser(z){const H=A,{user:j}=z;if(!j)return{};if(z['token']){const {jwtSignToken:c}=await import('../../../plugins/jwt.js'),p=await c(j);j['token']=p;}return j['resources']=[...new Set(j?.[H(0xd0)][H(0xd1)](M=>M[H(0xd2)](':')[0x0]))],safeUser(j);}function A(z,j){z=z-0xd0;const c=U();let p=c[z];return p;}function U(){const i=['permissions','map','split'];U=function(){return i;};return U();}
1
+ function c(J,e){J=J-0xf6;const p=L();let b=p[J];return b;}import{safeUser}from'../../utils/safe-user.js';export default async function getCurrentUser(J){const P=c,{user:e}=J;if(!e)return{};if(J[P(0xf6)]){const {jwtSignToken:p}=await import('../../../plugins/jwt.js'),b=await p(e);e['token']=b;}return e['resources']=[...new Set(e?.[P(0xf7)]['map'](F=>F['split'](':')[0x0]))],safeUser(e);}function L(){const h=['token','permissions'];L=function(){return h;};return L();}
@@ -1 +1 @@
1
- import{ConflictError}from'../../../errors.js';function U(){const n=['rows'];U=function(){return n;};return U();}function A(z,j){z=z-0xd7;const c=U();let p=c[z];return p;}import{hashPassword}from'../../../plugins/auth/index.js';export default async function registration({user:z,password:j,type:c},{pg:p}){const b=A,M=await hashPassword(j),H=await p['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',[z,M,c||'regular']),i=H[b(0xd7)][0x0];if(!i)throw new ConflictError('Login\x20is\x20already\x20in\x20use');return{'user':i};}
1
+ import{ConflictError}from'../../../errors.js';import{hashPassword}from'../../../plugins/auth/index.js';function c(J,e){J=J-0x1d9;const p=L();let b=p[J];return b;}export default async function registration({user:J,password:e,type:p},{pg:b}){const u=c,F=await hashPassword(e),P=await b['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',[J,F,p||u(0x1d9)]),h=P[u(0x1da)][0x0];if(!h)throw new ConflictError('Login\x20is\x20already\x20in\x20use');return{'user':h};}function L(){const H=['regular','rows'];L=function(){return H;};return L();}
@@ -1 +1 @@
1
- import{unsupported}from'../../utils/unsupported.js';export default async function verifyTwoFactor(z,j){return unsupported('Two-factor\x20provider');}
1
+ import{unsupported}from'../../utils/unsupported.js';function L(){var b=['Two-factor\x20provider'];L=function(){return b;};return L();}function c(J,e){J=J-0xaa;var p=L();var b=p[J];return b;}export default async function verifyTwoFactor(J,e){var p=c;return unsupported(p(0xaa));}
@@ -1 +1 @@
1
- function A(z,j){z=z-0x1b7;var c=U();var p=c[z];return p;}function U(){var j=['image/jpeg','image/gif','image/avif','application/msword','text/markdown','application/json','application/vnd.google-earth.kml+xml','application/zip','application/x-zip-compressed','application/vnd.rar','audio/webm','video/mpeg','video/quicktime','video/x-msvideo'];U=function(){return j;};return U();}var z=A;export default new Set([z(0x1b7),'image/png',z(0x1b8),'image/webp','image/bmp','image/tiff','image/svg+xml','image/x-icon',z(0x1b9),'application/pdf',z(0x1ba),'application/vnd.openxmlformats-officedocument.wordprocessingml.document','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',z(0x1bb),z(0x1bc),'application/xml','text/xml','application/geo+json',z(0x1bd),'application/vnd.google-earth.kmz',z(0x1be),z(0x1bf),'application/x-7z-compressed','application/x-rar-compressed',z(0x1c0),'application/gzip','application/x-gzip','application/x-tar','audio/mpeg','audio/wav','audio/ogg',z(0x1c1),'audio/mp4','video/mp4',z(0x1c2),'video/webm',z(0x1c3),z(0x1c4),'application/octet-stream']);
1
+ function L(){var e=['image/jpeg','image/svg+xml','image/x-icon','application/msword','application/vnd.openxmlformats-officedocument.wordprocessingml.document','application/vnd.openxmlformats-officedocument.presentationml.presentation','application/vnd.oasis.opendocument.text','application/vnd.oasis.opendocument.spreadsheet','text/plain','text/csv','application/vnd.rar','audio/mpeg','application/octet-stream'];L=function(){return e;};return L();}var J=c;function c(J,e){J=J-0x71;var p=L();var b=p[J];return b;}export default new Set([J(0x71),'image/png','image/gif','image/webp','image/bmp','image/tiff',J(0x72),J(0x73),'image/avif','application/pdf',J(0x74),J(0x75),'application/vnd.ms-excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','application/vnd.ms-powerpoint',J(0x76),J(0x77),J(0x78),'application/vnd.oasis.opendocument.presentation',J(0x79),J(0x7a),'text/markdown','application/json','application/xml','text/xml','application/geo+json','application/vnd.google-earth.kml+xml','application/vnd.google-earth.kmz','application/zip','application/x-zip-compressed','application/x-7z-compressed','application/x-rar-compressed',J(0x7b),'application/gzip','application/x-gzip','application/x-tar',J(0x7c),'audio/wav','audio/ogg','audio/webm','audio/mp4','video/mp4','video/mpeg','video/webm','video/quicktime','video/x-msvideo',J(0x7d)]);
@@ -1 +1 @@
1
- import{fileTypeFromBuffer}from'file-type';import{getFile}from'./services/get-file.js';import{uploadFile}from'./services/upload-file.js';function U(){const P=['fcore','verify','mime','file','type','public,\x20max-age=86400,\x20immutable','post','filename','fields','value','/api/file/:token/resize','Resize\x20file','files:read','resizeQuery'];U=function(){return P;};return U();}function A(z,j){z=z-0x10f;const c=U();let p=c[z];return p;}import{resizeFile}from'./services/resize-file.js';import{fileSchemas}from'./schema.js';export function fileRoutes(z){return async j=>{const q=A;j['get']('/api/file/:token',{'schema':{'tags':[q(0x10f),'file'],'summary':'Get\x20file\x20by\x20token','description':'Returns\x20a\x20file\x20after\x20verifying\x20its\x20signed\x20access\x20token.','access':'public','permissions':[],'params':fileSchemas['fileToken'],'querystring':fileSchemas['fileDownloadQuery']}},async(c,p)=>{const Z=q,M=z['file'][Z(0x110)](c['params']['token']),H=await getFile({'pathOrToken':M},z),i=await fileTypeFromBuffer(H),b=i?.[Z(0x111)]??'application/octet-stream',n=c['query']['download']===!![],v=b['startsWith']('image/')||b==='application/pdf',r=M['split']('/')['pop']()?.['replace'](/[^A-Za-z0-9._-]/g,'_')??Z(0x112);return p[Z(0x113)](b),p['header']('Content-Disposition',(n||!v?'attachment':'inline')+';\x20filename=\x22'+r+'\x22')['header']('Cache-Control',Z(0x114)),p['send'](H);}),j[q(0x115)]('/api/file/upload',{'schema':{'tags':[q(0x10f),'file'],'summary':'Upload\x20file','description':'Uploads\x20a\x20file\x20and\x20stores\x20its\x20metadata.','access':'user','permissions':['files:create']}},async c=>{const e=q,p=await c[e(0x112)]();if(!p)throw new Error('File\x20is\x20required');return uploadFile({'file':p,'metadata':{'name':p[e(0x116)],'path':p[e(0x117)]['path']?.['value'],'resource':p['fields']['resource']?.[e(0x118)],'resourceId':p['fields']['resourceId']?.['value']},'user':c['user']},z);}),j['get'](q(0x119),{'schema':{'tags':['fcore',q(0x112)],'summary':q(0x11a),'description':'Returns\x20a\x20resized\x20image\x20file.','access':'user','permissions':[q(0x11b)],'params':fileSchemas['fileToken'],'querystring':fileSchemas[q(0x11c)]}},async(c,p)=>{const o=q,M=await resizeFile({'pathOrToken':z['file']?.['verify'](c['params']['token']),...c['query']},z),H=await fileTypeFromBuffer(M);return p['type'](H?.['mime']??'image/png'),p['header']('Content-Disposition','inline')['header']('Cache-Control',o(0x114)),p['send'](M);});};}
1
+ import{fileTypeFromBuffer}from'file-type';import{getFile}from'./services/get-file.js';function L(){const T=['/api/file/:token','fileToken','file','verify','query','startsWith','split','header',';\x20filename=\x22','send','post','Uploads\x20a\x20file\x20and\x20stores\x20its\x20metadata.','fields','/api/file/:token/resize','fcore','Returns\x20a\x20resized\x20image\x20file.','mime'];L=function(){return T;};return L();}import{uploadFile}from'./services/upload-file.js';import{resizeFile}from'./services/resize-file.js';import{fileSchemas}from'./schema.js';function c(J,e){J=J-0xb4;const p=L();let b=p[J];return b;}export function fileRoutes(J){return async e=>{const w=c;e['get'](w(0xb4),{'schema':{'tags':['fcore','file'],'summary':'Get\x20file\x20by\x20token','description':'Returns\x20a\x20file\x20after\x20verifying\x20its\x20signed\x20access\x20token.','access':'public','permissions':[],'params':fileSchemas[w(0xb5)],'querystring':fileSchemas['fileDownloadQuery']}},async(p,b)=>{const X=w,F=J[X(0xb6)][X(0xb7)](p['params']['token']),P=await getFile({'pathOrToken':F},J),h=await fileTypeFromBuffer(P),u=h?.['mime']??'application/octet-stream',H=p[X(0xb8)]['download']===!![],D=u[X(0xb9)]('image/')||u==='application/pdf',U=F[X(0xba)]('/')['pop']()?.['replace'](/[^A-Za-z0-9._-]/g,'_')??X(0xb6);return b['type'](u),b[X(0xbb)]('Content-Disposition',(H||!D?'attachment':'inline')+X(0xbc)+U+'\x22')['header']('Cache-Control','public,\x20max-age=86400,\x20immutable'),b[X(0xbd)](P);}),e[w(0xbe)]('/api/file/upload',{'schema':{'tags':['fcore','file'],'summary':'Upload\x20file','description':w(0xbf),'access':'user','permissions':['files:create']}},async p=>{const E=w,b=await p[E(0xb6)]();if(!b)throw new Error('File\x20is\x20required');return uploadFile({'file':b,'metadata':{'name':b['filename'],'path':b[E(0xc0)]['path']?.['value'],'resource':b['fields']['resource']?.['value'],'resourceId':b['fields']['resourceId']?.['value']},'user':p['user']},J);}),e['get'](w(0xc1),{'schema':{'tags':[w(0xc2),w(0xb6)],'summary':'Resize\x20file','description':w(0xc3),'access':'user','permissions':['files:read'],'params':fileSchemas['fileToken'],'querystring':fileSchemas['resizeQuery']}},async(p,b)=>{const Q=w,F=await resizeFile({'pathOrToken':J['file']?.[Q(0xb7)](p['params']['token']),...p[Q(0xb8)]},J),P=await fileTypeFromBuffer(F);return b['type'](P?.[Q(0xc4)]??'image/png'),b['header']('Content-Disposition','inline')['header']('Cache-Control','public,\x20max-age=86400,\x20immutable'),b['send'](F);});};}
@@ -1 +1 @@
1
- const z=A;import{Type}from'@sinclair/typebox';function U(){const j=['String','Optional','Object','Integer','Literal','inside','outside'];U=function(){return j;};return U();}function A(z,j){z=z-0x116;const c=U();let p=c[z];return p;}export const fileSchemas={'fileId':Type['Object']({'id':Type[z(0x116)]({'minLength':0x1,'maxLength':0x80})}),'fileToken':Type['Object']({'token':Type[z(0x116)]({'minLength':0x1,'maxLength':0x800})}),'fileDownloadQuery':Type['Object']({'download':Type[z(0x117)](Type['Boolean']())}),'filePath':Type[z(0x118)]({'*':Type['String']({'minLength':0x1,'maxLength':0x400})}),'upload':Type[z(0x118)]({'file':Type['Any'](),'metadata':Type['Object']({'name':Type['Optional'](Type['String']({'minLength':0x1})),'path':Type['Optional'](Type[z(0x116)]({'minLength':0x1})),'entityType':Type['Optional'](Type['String']({'minLength':0x1})),'entityId':Type[z(0x117)](Type['String']({'minLength':0x1}))})}),'filePatch':Type[z(0x118)]({'entityType':Type['Optional'](Type['String']({'minLength':0x1})),'entityId':Type['Optional'](Type['String']({'minLength':0x1}))}),'resizeQuery':Type['Object']({'width':Type[z(0x117)](Type['Integer']({'minimum':0x1,'default':0xc8})),'height':Type['Optional'](Type[z(0x119)]({'minimum':0x1})),'fit':Type['Optional'](Type['Union']([Type[z(0x11a)]('cover'),Type['Literal']('contain'),Type['Literal']('fill'),Type['Literal'](z(0x11b)),Type[z(0x11a)](z(0x11c))]))})};
1
+ function L(){const e=['String','Object','Boolean','Optional','Union','Literal','cover','fill'];L=function(){return e;};return L();}function c(J,e){J=J-0x172;const p=L();let b=p[J];return b;}const J=c;import{Type}from'@sinclair/typebox';export const fileSchemas={'fileId':Type['Object']({'id':Type[J(0x172)]({'minLength':0x1,'maxLength':0x80})}),'fileToken':Type['Object']({'token':Type['String']({'minLength':0x1,'maxLength':0x800})}),'fileDownloadQuery':Type[J(0x173)]({'download':Type['Optional'](Type[J(0x174)]())}),'filePath':Type['Object']({'*':Type['String']({'minLength':0x1,'maxLength':0x400})}),'upload':Type[J(0x173)]({'file':Type['Any'](),'metadata':Type['Object']({'name':Type[J(0x175)](Type['String']({'minLength':0x1})),'path':Type[J(0x175)](Type['String']({'minLength':0x1})),'entityType':Type['Optional'](Type[J(0x172)]({'minLength':0x1})),'entityId':Type[J(0x175)](Type[J(0x172)]({'minLength':0x1}))})}),'filePatch':Type[J(0x173)]({'entityType':Type[J(0x175)](Type[J(0x172)]({'minLength':0x1})),'entityId':Type['Optional'](Type['String']({'minLength':0x1}))}),'resizeQuery':Type['Object']({'width':Type[J(0x175)](Type['Integer']({'minimum':0x1,'default':0xc8})),'height':Type['Optional'](Type['Integer']({'minimum':0x1})),'fit':Type['Optional'](Type[J(0x176)]([Type[J(0x177)](J(0x178)),Type[J(0x177)]('contain'),Type['Literal'](J(0x179)),Type['Literal']('inside'),Type['Literal']('outside')]))})};
@@ -1 +1 @@
1
- function A(z,j){z=z-0x177;var c=U();var p=c[z];return p;}function U(){var p=['file','exists','File\x20not\x20found','pathOrToken','get'];U=function(){return p;};return U();}import{NotFoundError}from'../../../errors.js';export async function getFile(z,j){var c=A;if(!j['file'])throw new Error('empty\x20file');if(!await j[c(0x177)][c(0x178)](z['pathOrToken']))throw new NotFoundError(c(0x179)+z[c(0x17a)]);return j[c(0x177)][c(0x17b)](z[c(0x17a)]);}
1
+ function c(J,e){J=J-0x1cf;var p=L();var b=p[J];return b;}import{NotFoundError}from'../../../errors.js';export async function getFile(J,e){var p=c;if(!e[p(0x1cf)])throw new Error('empty\x20file');if(!await e['file'][p(0x1d0)](J['pathOrToken']))throw new NotFoundError('File\x20not\x20found'+J['pathOrToken']);return e[p(0x1cf)]['get'](J[p(0x1d1)]);}function L(){var b=['file','exists','pathOrToken'];L=function(){return b;};return L();}
@@ -1 +1 @@
1
- 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 z from'node:path';function A(z,j){z=z-0x1c1;const c=U();let p=c[z];return p;}import j from'sharp';function U(){const P=['pathOrToken','path','File\x20path\x20is\x20required','sha256','digest','logs','resize','code','ENOENT','startsWith','toBuffer'];U=function(){return P;};return U();}export async function resizeFile(c,p){const o=A,M=c[o(0x1c1)]??c[o(0x1c2)];if(!M)throw new ValidationError(o(0x1c3));const H=parseDimension(c['width'],'width')??0xc8,i=parseDimension(c['height'],'height'),b=createHash(o(0x1c4))['update'](M+':'+H+':'+(i??'auto')+':'+(c['fit']??'cover'))[o(0x1c5)]('hex'),n=z['resolve'](o(0x1c6),o(0x1c7)),v=z['join'](n,b+'.jpg');try{return await readFile(v);}catch(e){if(e[o(0x1c8)]!==o(0x1c9))throw e;}if(!await p['file']['exists'](M))throw new NotFoundError('File\x20not\x20found');const r=await p['file']['get'](M),q=await fileTypeFromBuffer(r);if(!q?.['mime'][o(0x1ca)]('image/'))throw new ValidationError('Only\x20image\x20files\x20can\x20be\x20resized');const Z=await j(r)['resize']({'width':H,'height':i,'fit':c['fit']??'cover'})[o(0x1cb)]();return await mkdir(n,{'recursive':!![]}),await writeFile(v,Z),Z;}function parseDimension(c,p){if(c===undefined||c==='')return undefined;const M=Number(c);if(!Number['isInteger'](M)||M<=0x0)throw new ValidationError(p+'\x20must\x20be\x20a\x20positive\x20integer');return M;}
1
+ import{NotFoundError,ValidationError}from'../../../errors.js';import{fileTypeFromBuffer}from'file-type';function L(){const l=['pathOrToken','auto','cover','join','.jpg','file','get','Only\x20image\x20files\x20can\x20be\x20resized','isInteger'];L=function(){return l;};return L();}import{createHash}from'node:crypto';import{mkdir,readFile,writeFile}from'node:fs/promises';import J from'node:path';import e from'sharp';function c(J,e){J=J-0x102;const p=L();let b=p[J];return b;}export async function resizeFile(p,b){const Q=c,F=p[Q(0x102)]??p['path'];if(!F)throw new ValidationError('File\x20path\x20is\x20required');const P=parseDimension(p['width'],'width')??0xc8,h=parseDimension(p['height'],'height'),u=createHash('sha256')['update'](F+':'+P+':'+(h??Q(0x103))+':'+(p['fit']??Q(0x104)))['digest']('hex'),H=J['resolve']('logs','resize'),D=J[Q(0x105)](H,u+Q(0x106));try{return await readFile(D);}catch(E){if(E['code']!=='ENOENT')throw E;}if(!await b[Q(0x107)]['exists'](F))throw new NotFoundError('File\x20not\x20found');const U=await b[Q(0x107)][Q(0x108)](F),w=await fileTypeFromBuffer(U);if(!w?.['mime']['startsWith']('image/'))throw new ValidationError(Q(0x109));const X=await e(U)['resize']({'width':P,'height':h,'fit':p['fit']??'cover'})['toBuffer']();return await mkdir(H,{'recursive':!![]}),await writeFile(D,X),X;}function parseDimension(p,b){const T=c;if(p===undefined||p==='')return undefined;const F=Number(p);if(!Number[T(0x10a)](F)||F<=0x0)throw new ValidationError(b+'\x20must\x20be\x20a\x20positive\x20integer');return F;}
@@ -1 +1 @@
1
- import{fileTypeFromBuffer}from'file-type';function A(z,j){z=z-0x142;const c=U();let p=c[z];return p;}import z from'../mime.js';import{randomUUID}from'node:crypto';export async function uploadFile(j,c){const Z=A,p=(j['metadata']['name']??randomUUID())[Z(0x142)](/[^a-zA-Z0-9._-]/g,'_'),M=new Date(),H=String(M['getFullYear']())[Z(0x143)](-0x2),i=String(M['getMonth']()+0x1)['padStart'](0x2,'0'),b=String(M['getDate']())['padStart'](0x2,'0'),n=j['metadata']['path']??(j['metadata']['resource']?j['metadata'][Z(0x144)]+'/'+(j['metadata']['resourceId']??randomUUID())+'/'+p:null)??Z(0x145)+H+'/'+i+'-'+b+'/'+p,v=await j['file'][Z(0x146)](),r=await fileTypeFromBuffer(v);if(!z['has'](j['file']['mimetype'])&&(r?.['mime']?!z['has'](r['mime']):!![]))throw new Error('Unsupported\x20file\x20type:\x20'+j['file'][Z(0x147)]);await c['file'][Z(0x148)](n,v);const q=await c['pg']['query']('\x0a\x20\x20\x20\x20\x20\x20\x20\x20INSERT\x20INTO\x20admin.files\x20(resource,\x20resource_id,\x20file_path,\x20file_type,\x20size,uploaded_name,file_name,ext,created_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)\x0a\x20\x20\x20\x20\x20\x20\x20\x20RETURNING\x20*\x0a\x20\x20\x20\x20\x20\x20',[j[Z(0x149)]['resource']??null,j[Z(0x149)]['resourceId']??null,n,j['file']['mimetype'],j['file']['file']['bytesRead'],j['metadata'][Z(0x14a)],p,j['file']['mimetype']['split']('/')['pop']()??null,j['user']?.['id']??null]);return q['rows'][0x0];}function U(){const e=['replace','slice','resource','uploads/','toBuffer','mimetype','put','metadata','name'];U=function(){return e;};return U();}
1
+ import{fileTypeFromBuffer}from'file-type';import J from'../mime.js';import{randomUUID}from'node:crypto';function c(J,e){J=J-0x159;const p=L();let b=p[J];return b;}function L(){const E=['metadata','getMonth','padStart','resourceId','file','toBuffer','has','mimetype','mime','resource','rows'];L=function(){return E;};return L();}export async function uploadFile(e,p){const X=c,b=(e[X(0x159)]['name']??randomUUID())['replace'](/[^a-zA-Z0-9._-]/g,'_'),F=new Date(),P=String(F['getFullYear']())['slice'](-0x2),h=String(F[X(0x15a)]()+0x1)['padStart'](0x2,'0'),u=String(F['getDate']())[X(0x15b)](0x2,'0'),H=e['metadata']['path']??(e['metadata']['resource']?e['metadata']['resource']+'/'+(e['metadata'][X(0x15c)]??randomUUID())+'/'+b:null)??'uploads/'+P+'/'+h+'-'+u+'/'+b,D=await e[X(0x15d)][X(0x15e)](),U=await fileTypeFromBuffer(D);if(!J[X(0x15f)](e['file'][X(0x160)])&&(U?.[X(0x161)]?!J['has'](U['mime']):!![]))throw new Error('Unsupported\x20file\x20type:\x20'+e['file']['mimetype']);await p['file']['put'](H,D);const w=await p['pg']['query']('\x0a\x20\x20\x20\x20\x20\x20\x20\x20INSERT\x20INTO\x20admin.files\x20(resource,\x20resource_id,\x20file_path,\x20file_type,\x20size,uploaded_name,file_name,ext,created_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)\x0a\x20\x20\x20\x20\x20\x20\x20\x20RETURNING\x20*\x0a\x20\x20\x20\x20\x20\x20',[e['metadata'][X(0x162)]??null,e[X(0x159)][X(0x15c)]??null,H,e['file']['mimetype'],e['file'][X(0x15d)]['bytesRead'],e[X(0x159)]['name'],b,e['file']['mimetype']['split']('/')['pop']()??null,e['user']?.['id']??null]);return w[X(0x163)][0x0];}
@@ -1 +1 @@
1
- const i=A;import{ForbiddenError}from'../../errors.js';import{listResources}from'./services/list-resources.js';import{getResource}from'./services/get-resource.js';import{createResource}from'./services/create-resource.js';import{updateResource}from'./services/update-resource.js';import{deleteResource}from'./services/delete-resource.js';import{listResourceRelation}from'./services/list-resource-relation.js';import{createResourceRelation}from'./services/create-resource-relation.js';import{updateResourceRelation}from'./services/update-resource-relation.js';import{deleteResourceRelation}from'./services/delete-resource-relation.js';import{searchResource}from'./services/search-resource.js';import{exportResource}from'./services/export-resource.js';import{suggestResource}from'./services/suggest-resource.js';import{resourceSchemas}from'./schema.js';function A(z,j){z=z-0xc7;const c=U();let p=c[z];return p;}import{uploadFile}from'../file/services/upload-file.js';const user=z=>z[i(0xc7)];export function resourceRoutes(z){return async j=>{const b=A;j['get'](b(0xc8),{'schema':{'tags':['fcore','resource'],'summary':'Search\x20resource','description':b(0xc9),'access':b(0xc7),'permissions':[],'params':resourceSchemas['resource']}},async c=>searchResource({...c['query'],...c['params'],'user':user(c)},z)),j[b(0xca)]('/api/suggest/:resource/:field',{'schema':{'tags':['fcore',b(0xcb)],'summary':'Suggest\x20resource\x20values','description':'Returns\x20suggested\x20values\x20for\x20a\x20resource\x20field.','access':b(0xc7),'permissions':[],'params':resourceSchemas[b(0xcc)],'querystring':resourceSchemas['suggestQuery']}},async c=>suggestResource({...c['query'],...c['params'],'user':user(c)},z)),j[b(0xca)]('/api/resource/:resource/export',{'schema':{'tags':[b(0xcd),'resource'],'summary':'Export\x20resource\x20records','description':'Exports\x20readable\x20records\x20from\x20a\x20registered\x20resource.','access':b(0xc7),'permissions':['*:read'],'params':resourceSchemas['exportResource'],'querystring':resourceSchemas['exportResourceQuery']}},async c=>exportResource({...c['query'],...c['params'],'user':user(c)},z)),j[b(0xca)]('/api/resource/:resource',{'schema':{'tags':['fcore','resource'],'summary':'List\x20resource\x20records','description':'Returns\x20records\x20from\x20a\x20registered\x20resource.','access':'user','permissions':[],'params':resourceSchemas['resource']}},async c=>listResources({...c[b(0xce)],...c['params'],'user':user(c)},z)),j[b(0xcf)]('/api/resource/:resource',{'schema':{'tags':['fcore','resource'],'summary':'Create\x20resource\x20record','description':b(0xd0),'access':'user','permissions':[],'params':resourceSchemas['resource']}},async c=>createResource({...c[b(0xd1)],'data':c['body'],'user':user(c)},z)),j[b(0xca)]('/api/resource/:resource/:id',{'schema':{'tags':['fcore','resource'],'summary':'Get\x20resource\x20record','description':b(0xd2),'access':'user','permissions':[],'params':resourceSchemas['resourceId'],'querystring':resourceSchemas['resourceIncludeQuery']}},async c=>getResource({...c[b(0xce)],...c['params'],'user':user(c)},z)),j['put'](b(0xd3),{'schema':{'tags':['fcore',b(0xcb)],'summary':'Update\x20resource\x20record','description':b(0xd4),'access':'user','permissions':[],'params':resourceSchemas['resourceId']}},async c=>updateResource({...c['params'],'patch':c['body'],'user':user(c)},z)),j['delete']('/api/resource/:resource/:id',{'schema':{'tags':['fcore',b(0xcb)],'summary':b(0xd5),'description':b(0xd6),'access':'user','permissions':[],'params':resourceSchemas['resourceId']}},async c=>deleteResource({...c['params'],'user':user(c)},z)),j['post']('/api/resource/:resource/:id/upload',{'schema':{'tags':['fcore',b(0xcb)],'summary':'Upload\x20resource\x20file','description':'Uploads\x20a\x20file\x20to\x20a\x20Resource\x20record\x20and\x20stores\x20its\x20metadata.','access':'user','permissions':[],'params':resourceSchemas[b(0xd7)]}},async c=>{const n=b,p=await c['file']();if(!p)throw new Error('File\x20is\x20required');const M=c[n(0xd1)][n(0xcb)],H=c['params']['id'];if(c[n(0xc7)]?.[n(0xd8)]!==n(0xd9)&&!c['user']?.[n(0xda)][n(0xdb)](M+':update'))throw new ForbiddenError('Missing\x20permission:\x20'+M+n(0xdc));return uploadFile({'file':p,'metadata':{'name':p['filename'],'path':p[n(0xdd)]['path']?.['value'],'resource':M,'resourceId':H},'user':c[n(0xc7)]},z);}),j[b(0xca)](b(0xde),{'schema':{'tags':['fcore','resource'],'summary':b(0xdf),'description':'Returns\x20related\x20records\x20for\x20a\x20resource\x20record.','access':b(0xc7),'permissions':[],'schema':{'params':resourceSchemas['resourceIdRelation']}}},async c=>listResourceRelation({...c['query'],...c['params'],'user':user(c)},z)),j['post'](b(0xde),{'schema':{'tags':['fcore','resource'],'summary':'Create\x20resource\x20relation','description':'Creates\x20a\x20relation\x20for\x20a\x20resource\x20record.','access':b(0xc7),'permissions':[],'params':resourceSchemas['resourceIdRelation']}},async c=>createResourceRelation({...c['params'],'data':c['body'],'user':user(c)},z)),j['delete']('/api/resource/:resource/:id/:relation/:relationId',{'schema':{'tags':['fcore',b(0xcb)],'summary':b(0xe0),'description':'Deletes\x20a\x20relation\x20from\x20a\x20resource\x20record.','access':'user','permissions':[],'params':resourceSchemas['resourceIdRelationId']}},async c=>deleteResourceRelation({...c[b(0xd1)],'user':user(c)},z)),j['put']('/api/resource/:resource/:id/:relation/:relationId',{'schema':{'tags':['fcore','resource'],'summary':b(0xe1),'description':b(0xe2),'access':'user','permissions':[],'params':resourceSchemas[b(0xe3)]}},async c=>updateResourceRelation({...c[b(0xd1)],'data':c[b(0xe4)],'user':user(c)},z));};}function U(){const v=['user','/api/resource/:resource/search','Searches\x20records\x20in\x20a\x20registered\x20resource.','get','resource','resourceField','fcore','query','post','Creates\x20a\x20record\x20in\x20a\x20registered\x20resource.','params','Returns\x20one\x20record\x20from\x20a\x20registered\x20resource.','/api/resource/:resource/:id','Updates\x20a\x20record\x20in\x20a\x20registered\x20resource.','Delete\x20resource\x20record','Deletes\x20a\x20record\x20from\x20a\x20registered\x20resource.','uploadResourceFile','type','admin','permissions','includes',':update','fields','/api/resource/:resource/:id/:relation','List\x20resource\x20relations','Delete\x20resource\x20relation','Update\x20resource\x20relation','Updates\x20a\x20related\x20resource\x20record.','resourceIdRelationId','body'];U=function(){return v;};return U();}
1
+ const h=c;function L(){const D=['user','get','/api/resource/:resource/search','fcore','Search\x20resource','resource','query','/api/resource/:resource','/api/resource/:resource/:id','Returns\x20one\x20record\x20from\x20a\x20registered\x20resource.','resourceIncludeQuery','params','body','Deletes\x20a\x20record\x20from\x20a\x20registered\x20resource.','post','/api/resource/:resource/:id/upload','file','path','Returns\x20related\x20records\x20for\x20a\x20resource\x20record.','resourceIdRelation','delete','Deletes\x20a\x20relation\x20from\x20a\x20resource\x20record.','resourceIdRelationId','put','/api/resource/:resource/:id/:relation/:relationId','Update\x20resource\x20relation','Updates\x20a\x20related\x20resource\x20record.'];L=function(){return D;};return L();}import{ForbiddenError}from'../../errors.js';import{listResources}from'./services/list-resources.js';import{getResource}from'./services/get-resource.js';import{createResource}from'./services/create-resource.js';import{updateResource}from'./services/update-resource.js';import{deleteResource}from'./services/delete-resource.js';function c(J,e){J=J-0x1ef;const p=L();let b=p[J];return b;}import{listResourceRelation}from'./services/list-resource-relation.js';import{createResourceRelation}from'./services/create-resource-relation.js';import{updateResourceRelation}from'./services/update-resource-relation.js';import{deleteResourceRelation}from'./services/delete-resource-relation.js';import{searchResource}from'./services/search-resource.js';import{exportResource}from'./services/export-resource.js';import{suggestResource}from'./services/suggest-resource.js';import{resourceSchemas}from'./schema.js';import{uploadFile}from'../file/services/upload-file.js';const user=J=>J[h(0x1ef)];export function resourceRoutes(J){return async e=>{const u=c;e[u(0x1f0)](u(0x1f1),{'schema':{'tags':[u(0x1f2),'resource'],'summary':u(0x1f3),'description':'Searches\x20records\x20in\x20a\x20registered\x20resource.','access':'user','permissions':[],'params':resourceSchemas[u(0x1f4)]}},async p=>searchResource({...p['query'],...p['params'],'user':user(p)},J)),e['get']('/api/suggest/:resource/:field',{'schema':{'tags':[u(0x1f2),'resource'],'summary':'Suggest\x20resource\x20values','description':'Returns\x20suggested\x20values\x20for\x20a\x20resource\x20field.','access':'user','permissions':[],'params':resourceSchemas['resourceField'],'querystring':resourceSchemas['suggestQuery']}},async p=>suggestResource({...p[u(0x1f5)],...p['params'],'user':user(p)},J)),e[u(0x1f0)]('/api/resource/:resource/export',{'schema':{'tags':[u(0x1f2),u(0x1f4)],'summary':'Export\x20resource\x20records','description':'Exports\x20readable\x20records\x20from\x20a\x20registered\x20resource.','access':u(0x1ef),'permissions':['*:read'],'params':resourceSchemas['exportResource'],'querystring':resourceSchemas['exportResourceQuery']}},async p=>exportResource({...p['query'],...p['params'],'user':user(p)},J)),e[u(0x1f0)](u(0x1f6),{'schema':{'tags':[u(0x1f2),u(0x1f4)],'summary':'List\x20resource\x20records','description':'Returns\x20records\x20from\x20a\x20registered\x20resource.','access':'user','permissions':[],'params':resourceSchemas['resource']}},async p=>listResources({...p[u(0x1f5)],...p['params'],'user':user(p)},J)),e['post']('/api/resource/:resource',{'schema':{'tags':['fcore',u(0x1f4)],'summary':'Create\x20resource\x20record','description':'Creates\x20a\x20record\x20in\x20a\x20registered\x20resource.','access':'user','permissions':[],'params':resourceSchemas[u(0x1f4)]}},async p=>createResource({...p['params'],'data':p['body'],'user':user(p)},J)),e['get'](u(0x1f7),{'schema':{'tags':['fcore','resource'],'summary':'Get\x20resource\x20record','description':u(0x1f8),'access':'user','permissions':[],'params':resourceSchemas['resourceId'],'querystring':resourceSchemas[u(0x1f9)]}},async p=>getResource({...p[u(0x1f5)],...p[u(0x1fa)],'user':user(p)},J)),e['put'](u(0x1f7),{'schema':{'tags':['fcore','resource'],'summary':'Update\x20resource\x20record','description':'Updates\x20a\x20record\x20in\x20a\x20registered\x20resource.','access':'user','permissions':[],'params':resourceSchemas['resourceId']}},async p=>updateResource({...p['params'],'patch':p[u(0x1fb)],'user':user(p)},J)),e['delete']('/api/resource/:resource/:id',{'schema':{'tags':['fcore','resource'],'summary':'Delete\x20resource\x20record','description':u(0x1fc),'access':u(0x1ef),'permissions':[],'params':resourceSchemas['resourceId']}},async p=>deleteResource({...p['params'],'user':user(p)},J)),e[u(0x1fd)](u(0x1fe),{'schema':{'tags':[u(0x1f2),'resource'],'summary':'Upload\x20resource\x20file','description':'Uploads\x20a\x20file\x20to\x20a\x20Resource\x20record\x20and\x20stores\x20its\x20metadata.','access':'user','permissions':[],'params':resourceSchemas['uploadResourceFile']}},async p=>{const H=u,b=await p[H(0x1ff)]();if(!b)throw new Error('File\x20is\x20required');const F=p['params']['resource'],P=p['params']['id'];if(p['user']?.['type']!=='admin'&&!p['user']?.['permissions']['includes'](F+':update'))throw new ForbiddenError('Missing\x20permission:\x20'+F+':update');return uploadFile({'file':b,'metadata':{'name':b['filename'],'path':b['fields'][H(0x200)]?.['value'],'resource':F,'resourceId':P},'user':p['user']},J);}),e[u(0x1f0)]('/api/resource/:resource/:id/:relation',{'schema':{'tags':['fcore','resource'],'summary':'List\x20resource\x20relations','description':u(0x201),'access':'user','permissions':[],'schema':{'params':resourceSchemas[u(0x202)]}}},async p=>listResourceRelation({...p['query'],...p['params'],'user':user(p)},J)),e['post']('/api/resource/:resource/:id/:relation',{'schema':{'tags':['fcore','resource'],'summary':'Create\x20resource\x20relation','description':'Creates\x20a\x20relation\x20for\x20a\x20resource\x20record.','access':u(0x1ef),'permissions':[],'params':resourceSchemas['resourceIdRelation']}},async p=>createResourceRelation({...p['params'],'data':p[u(0x1fb)],'user':user(p)},J)),e[u(0x203)]('/api/resource/:resource/:id/:relation/:relationId',{'schema':{'tags':['fcore','resource'],'summary':'Delete\x20resource\x20relation','description':u(0x204),'access':'user','permissions':[],'params':resourceSchemas[u(0x205)]}},async p=>deleteResourceRelation({...p['params'],'user':user(p)},J)),e[u(0x206)](u(0x207),{'schema':{'tags':['fcore','resource'],'summary':u(0x208),'description':u(0x209),'access':u(0x1ef),'permissions':[],'params':resourceSchemas['resourceIdRelationId']}},async p=>updateResourceRelation({...p['params'],'data':p['body'],'user':user(p)},J));};}
@@ -1 +1 @@
1
- function U(){const j=['String','^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$','Optional','Object','Any','Record','Array'];U=function(){return j;};return U();}function A(z,j){z=z-0x16e;const c=U();let p=c[z];return p;}const z=A;import{Type}from'@sinclair/typebox';export const identifier=Type[z(0x16e)]({'minLength':0x1,'maxLength':0x80,'pattern':z(0x16f)});export const resourceSchemas={'dictionaryName':Type['Object']({'name':identifier}),'resource':Type['Object']({'resource':identifier}),'exportResource':Type['Object']({'resource':identifier}),'resourceField':Type['Object']({'resource':identifier,'field':identifier}),'suggestQuery':Type['Object']({'q':Type['Optional'](Type[z(0x16e)]()),'search':Type[z(0x170)](Type['String']()),'limit':Type['Optional'](Type['Integer']({'minimum':0x1,'maximum':0xc8}))}),'resourceId':Type['Object']({'resource':identifier,'id':identifier}),'resourceIncludeQuery':Type['Object']({'include':Type['Optional'](Type[z(0x16e)]({'minLength':0x1}))}),'resourceIdRelation':Type[z(0x171)]({'resource':identifier,'id':identifier,'relation':identifier}),'resourceIdRelationId':Type['Object']({'resource':identifier,'id':identifier,'relation':identifier,'relationId':identifier}),'uploadResourceFile':Type[z(0x171)]({'resource':identifier,'id':identifier}),'uploadResourceFileBody':Type['Object']({'file':Type[z(0x172)](),'fileName':Type['String']({'minLength':0x1,'maxLength':0xff})}),'exportResourceQuery':Type[z(0x171)]({'filter':Type['Optional'](Type[z(0x173)](Type[z(0x16e)](),Type['Unknown']())),'sort':Type['Optional'](Type[z(0x174)](Type['String']({'minLength':0x1}))),'search':Type[z(0x170)](Type[z(0x16e)]()),'limit':Type['Optional'](Type['Integer']({'minimum':0x1,'maximum':0xc8})),'offset':Type['Optional'](Type['Integer']({'minimum':0x0})),'fields':Type['Optional'](Type['Array'](identifier))})};
1
+ const J=c;import{Type}from'@sinclair/typebox';function c(J,e){J=J-0x19e;const p=L();let b=p[J];return b;}function L(){const e=['^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$','Object','Optional','String','Integer','Any','Unknown'];L=function(){return e;};return L();}export const identifier=Type['String']({'minLength':0x1,'maxLength':0x80,'pattern':J(0x19e)});export const resourceSchemas={'dictionaryName':Type['Object']({'name':identifier}),'resource':Type['Object']({'resource':identifier}),'exportResource':Type[J(0x19f)]({'resource':identifier}),'resourceField':Type['Object']({'resource':identifier,'field':identifier}),'suggestQuery':Type['Object']({'q':Type[J(0x1a0)](Type['String']()),'search':Type['Optional'](Type[J(0x1a1)]()),'limit':Type['Optional'](Type[J(0x1a2)]({'minimum':0x1,'maximum':0xc8}))}),'resourceId':Type['Object']({'resource':identifier,'id':identifier}),'resourceIncludeQuery':Type['Object']({'include':Type[J(0x1a0)](Type['String']({'minLength':0x1}))}),'resourceIdRelation':Type[J(0x19f)]({'resource':identifier,'id':identifier,'relation':identifier}),'resourceIdRelationId':Type[J(0x19f)]({'resource':identifier,'id':identifier,'relation':identifier,'relationId':identifier}),'uploadResourceFile':Type[J(0x19f)]({'resource':identifier,'id':identifier}),'uploadResourceFileBody':Type['Object']({'file':Type[J(0x1a3)](),'fileName':Type[J(0x1a1)]({'minLength':0x1,'maxLength':0xff})}),'exportResourceQuery':Type['Object']({'filter':Type[J(0x1a0)](Type['Record'](Type['String'](),Type[J(0x1a4)]())),'sort':Type['Optional'](Type['Array'](Type['String']({'minLength':0x1}))),'search':Type['Optional'](Type[J(0x1a1)]()),'limit':Type['Optional'](Type['Integer']({'minimum':0x1,'maximum':0xc8})),'offset':Type['Optional'](Type[J(0x1a2)]({'minimum':0x0})),'fields':Type[J(0x1a0)](Type['Array'](identifier))})};
@@ -1 +1 @@
1
- function A(z,j){z=z-0x74;const c=U();let p=c[z];return p;}export async function addNote(z,j){const p=A,c=await j['pg']['query']('INSERT\x20INTO\x20admin.notes(resource,resource_id,body)\x20VALUES\x20($1,$2,$3)\x20RETURNING\x20*',[z[p(0x74)],String(z['id']),z['body']]);return c['rows'][0x0];}function U(){const M=['resource'];U=function(){return M;};return U();}
1
+ function c(J,e){J=J-0x135;const p=L();let b=p[J];return b;}export async function addNote(J,e){const b=c,p=await e['pg']['query'](b(0x135),[J[b(0x136)],String(J['id']),J[b(0x137)]]);return p['rows'][0x0];}function L(){const F=['INSERT\x20INTO\x20admin.notes(resource,resource_id,body)\x20VALUES\x20($1,$2,$3)\x20RETURNING\x20*','resource','body'];L=function(){return F;};return L();}