rajt 0.0.57 → 0.0.58

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.
@@ -0,0 +1,206 @@
1
+ import esbuild from 'esbuild'
2
+ import TOML from '@iarna/toml'
3
+ import { Miniflare } from 'miniflare'
4
+ import { fileURLToPath } from 'node:url'
5
+ import { mkdirSync, existsSync, readdirSync, rmSync, copyFileSync } from 'node:fs'
6
+ import { readFile, stat, writeFile } from 'node:fs/promises'
7
+ import { basename, dirname, join, relative } from 'node:path'
8
+
9
+ const __dirname = join(dirname(fileURLToPath(import.meta.url)), '../../../../../../')
10
+ const __rajt = join(__dirname, 'node_modules/rajt/src')
11
+
12
+ export const formatSize = (bytes: number) => {
13
+ if (bytes < 1024) return `${bytes}b`
14
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)}kb`
15
+ return `${(bytes / (1024 * 1024)).toFixed(2)}mb`
16
+ }
17
+
18
+ export const formatTime = (ms: number) => {
19
+ if (ms < 1000) return `${ms}ms`
20
+ return `${(ms / 1000).toFixed(2)}s`
21
+ }
22
+
23
+ export const build = async (platform: 'aws' | 'cf' | 'node') => {
24
+ const startTime = Date.now()
25
+
26
+ const isCF = platform == 'cf'
27
+ const distDir = join(__dirname, 'dist')
28
+
29
+ existsSync(distDir)
30
+ ? readdirSync(distDir).forEach(file => rmSync(join(distDir, file), { recursive: true, force: true }))
31
+ : mkdirSync(distDir, { recursive: true })
32
+
33
+ if (isCF) {
34
+ for (let file of [
35
+ 'wrangler.toml',
36
+ ]) {
37
+ file = join(__dirname, file)
38
+ if (existsSync(file))
39
+ copyFileSync(file, join(__dirname, 'dist', basename(file)))
40
+ }
41
+ }
42
+
43
+ const opts = {
44
+ entryPoints: [join(__rajt, `prod-${platform}.ts`)],
45
+ bundle: true,
46
+ minify: false,
47
+ outfile: join(__dirname, 'dist/index.js'),
48
+ format: 'esm',
49
+ target: isCF ? 'es2022' : 'node20',
50
+ // platform: 'neutral',
51
+ platform: isCF ? 'browser' : 'node',
52
+ conditions: isCF ? ['worker', 'browser'] : [],
53
+ treeShaking: true,
54
+ legalComments: 'none',
55
+ external: [
56
+ '@aws-sdk', '@smithy',
57
+ ...(isCF ? [
58
+ 'cloudflare:workers',
59
+ 'node:crypto', 'crypto',
60
+ 'node:buffer', 'buffer',
61
+ ] : []),
62
+ ],
63
+ metafile: true,
64
+ write: false,
65
+ // define: {
66
+ // 'process.env.NODE_ENV': '"development"'
67
+ // },
68
+ // loader: {
69
+ // '.ts': 'ts',
70
+ // '.js': 'js'
71
+ // },
72
+ // tsconfig: join(__dirname, 'tsconfig.json'),
73
+ // sourcemap: true,
74
+ // logLevel: 'info',
75
+ plugins: [
76
+ {
77
+ name: 'preserve-class-names',
78
+ setup(build) {
79
+ build.onLoad(
80
+ { filter: /(actions|features)\/.*\.ts$/ },
81
+ async (args) => {
82
+ const contents = await readFile(args.path, 'utf8')
83
+ const result = await esbuild.transform(contents, {
84
+ loader: 'ts',
85
+ minify: true,
86
+ keepNames: true
87
+ })
88
+ return { contents: result.code, loader: 'ts' }
89
+ }
90
+ )
91
+ },
92
+ },
93
+ {
94
+ name: 'remove-use-strict',
95
+ setup(build) {
96
+ build.onEnd(async (result) => {
97
+ if (!result.outputFiles) return
98
+
99
+ const files = result.outputFiles.filter(file => file.path.endsWith('.js'))
100
+ await Promise.all(files.map(async file => {
101
+ if (!file.path.endsWith('.js')) return
102
+
103
+ await writeFile(
104
+ file.path,
105
+ new TextDecoder()
106
+ .decode(file.contents)
107
+ .replace(/(["'`])\s*use strict\s*\1;?|`use strict`;?/g, '')
108
+ )
109
+ }))
110
+ })
111
+ }
112
+ },
113
+ ],
114
+ }
115
+
116
+ const result = await esbuild.build(opts)
117
+ if (!result?.metafile) throw Error('build fail')
118
+
119
+ logger.step('Build completed successfully')
120
+
121
+ const stats = await stat(opts.outfile)
122
+ const size = formatSize(stats.size)
123
+
124
+ logger.step(
125
+ `Build done in ${formatTime(Date.now() - startTime)}`,
126
+ `${relative(join(__dirname, 'node_modules/rajt/src'), opts.entryPoints[0])} → ${relative(__dirname, opts.outfile)}`,
127
+ `Size: ${size}`,
128
+ `Files: ${Object.keys(result.metafile.outputs).length}`
129
+ )
130
+ }
131
+
132
+ async function parseWranglerConfig(file: string) {
133
+ try {
134
+ return TOML.parse(await readFile(join(__dirname, file), 'utf-8'))
135
+ } catch (e) {
136
+ logger.warn(`Could not parse ${file}, using defaults`)
137
+ return {}
138
+ }
139
+ }
140
+
141
+ export async function createMiniflare(options = {}, configPath = 'wrangler.toml') {
142
+ const config = await parseWranglerConfig(configPath)
143
+
144
+ return new Miniflare({
145
+ host: options.host || 'localhost',
146
+ port: options.port || 8787,
147
+ https: options.https || false,
148
+ httpsKey: options.httpsKey,
149
+ httpsCert: options.httpsCert,
150
+ liveReload: options.liveReload !== false,
151
+ updateCheck: false,
152
+
153
+ scriptPath: join(__dirname, 'dist/index.js'),
154
+ compatibilityDate: config.compatibility_date || '2024-11-01',
155
+ compatibilityFlags: config.compatibility_flags || [
156
+ 'nodejs_compat',
157
+ ],
158
+
159
+ bindings: {
160
+ // MY_VARIABLE: 'value',
161
+ // ENVIRONMENT: 'development',
162
+ ...config.vars,
163
+ },
164
+
165
+ d1Databases: Object.fromEntries(config.d1_databases.map(db => [db.binding, db.database_id])),
166
+
167
+ modules: true,
168
+ modulesRules: [
169
+ { type: 'ESModule', include: ['**/*.js', '**/*.ts'] },
170
+ ],
171
+
172
+ kvPersist: join(__dirname, '.wrangler/state/v3/kv'),
173
+ cachePersist: join(__dirname, '.wrangler/state/v3/cache'),
174
+ d1Persist: join(__dirname, '.wrangler/state/v3/d1'),
175
+ r2Persist: join(__dirname, '.wrangler/state/v3/r2'),
176
+ durablesPersist: join(__dirname, '.wrangler/state/v3/durable_objects'),
177
+
178
+ verbose: false,
179
+
180
+ // Logging
181
+ // log: new console.Console({
182
+ // stdout: process.stdout,
183
+ // stderr: process.stderr,
184
+ // inspectOptions: { depth: 3 }
185
+ // }),
186
+
187
+ cfFetch: false, // disable cf requests
188
+ upstream: config.upstream || 'https://example.com',
189
+
190
+ sitePath: config.site?.bucket ?
191
+ join(__dirname, config.site.bucket) : undefined,
192
+ siteInclude: config.site?.include || ['**/*'],
193
+ siteExclude: config.site?.exclude || [],
194
+
195
+ globalAsyncIO: true,
196
+ globalTimers: true,
197
+ globalRandom: true,
198
+
199
+ inspectorPort: options.inspectorPort || 9229,
200
+
201
+ cache: true,
202
+ cacheWarnUsage: true,
203
+
204
+ ...options
205
+ })
206
+ }
@@ -0,0 +1,69 @@
1
+ import { defineCommand, runMain, renderUsage } from 'citty'
2
+ import type { ArgsDef, CommandDef } from 'citty'
3
+ import colors from 'picocolors'
4
+ import { createConsola } from 'consola'
5
+
6
+ import { version as rajtVersion } from '../../package.json'
7
+
8
+ import logger, { type ILogger } from '../utils/logger'
9
+
10
+ import dev from './commands/dev'
11
+
12
+ // Prevent non-internal logs
13
+ (globalThis as any).logger = logger // Make it global in Node.js and browser
14
+ declare global { var logger: ILogger }
15
+
16
+ // console.log = () => {}
17
+ console.info = () => {}
18
+ console.warn = () => {}
19
+ console.error = () => {}
20
+
21
+ /**
22
+ * The main entrypoint for the CLI.
23
+ * main only gets called when the script is run directly, not when it's imported as a module.
24
+ */
25
+ const directly = () => {
26
+ try {
27
+ // @ts-ignore
28
+ return typeof vitest == 'undefined'
29
+ && (
30
+ ![typeof require, typeof module].includes('undefined') && require.main == module
31
+ || import.meta.url == `file://${process.argv[1]}`
32
+ )
33
+ } catch {
34
+ return false
35
+ }
36
+ }
37
+
38
+ const name = 'Rajt CLI'
39
+ const version = [name, colors.isColorSupported ? colors.gray('v'+rajtVersion) : rajtVersion].join(' ')
40
+
41
+ if (directly()) {
42
+ const _args = process.argv.slice(2)
43
+ if (_args.length == 1 && ['-v', '--version', '--v', '-version'].includes(_args[0])) {
44
+ console.log(version)
45
+ process.exit(0)
46
+ }
47
+
48
+ const consola = createConsola({ formatOptions: {date: false} })
49
+ async function showUsage<T extends ArgsDef = ArgsDef>(cmd: CommandDef<T>, parent?: CommandDef<T>) {
50
+ try {
51
+ consola.log((await renderUsage(cmd, parent)).split('\n').slice(1).join('\n') + '\n')
52
+ } catch (error) {
53
+ consola.error(error)
54
+ }
55
+ }
56
+
57
+ const main = defineCommand({
58
+ meta: {
59
+ name: 'rajt',
60
+ version: rajtVersion,
61
+ description: name,
62
+ },
63
+ subCommands: {
64
+ dev,
65
+ },
66
+ })
67
+
68
+ runMain(main, { rawArgs: _args?.length ? undefined : ['-h'], showUsage })
69
+ }
@@ -0,0 +1 @@
1
+ export type ChokidarEventName = 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir'
package/src/create-app.ts CHANGED
@@ -1,15 +1,18 @@
1
1
  /* eslint-disable @typescript-eslint/no-explicit-any */
2
2
  import { Hono } from 'hono'
3
+ import { logger } from 'hono/logger'
3
4
  import type { Env, Context, ErrorHandler, NotFoundHandler, Next } from 'hono'
4
5
  // import type { MiddlewareHandler } from 'hono'
5
6
  // import { createMiddleware } from 'hono/factory'
6
7
  // import type { H, Handler, HandlerResponse } from 'hono/types'
7
8
  import type { HTTPResponseError } from 'hono/types'
9
+ import colors from 'picocolors'
8
10
  import type { Routes } from './types'
9
11
  import { BadRequest, Unauthorized } from './exceptions'
10
12
  import { resolve, resolveMiddleware } from './utils/resolve'
11
13
  import { getMiddlewares, getHandler } from './register'
12
14
  import { isDev } from './utils/environment'
15
+ import localDate from './utils/local-date'
13
16
  import { Auth } from './auth'
14
17
  import response from './response'
15
18
  import cx from './context'
@@ -31,11 +34,11 @@ const EHandler = async (e: Error | HTTPResponseError) => {
31
34
 
32
35
  switch (true) {
33
36
  case e instanceof Unauthorized:
34
- case 'status' in e && e.status === 401:
37
+ case 'status' in e && e.status == 401:
35
38
  return response.unauthorized()
36
39
 
37
40
  case e instanceof BadRequest:
38
- case 'status' in e && e.status === 400:
41
+ case 'status' in e && e.status == 400:
39
42
  // @ts-ignore
40
43
  return response.badRequest(undefined, e?.message)
41
44
 
@@ -78,6 +81,9 @@ export const createApp = <E extends Env>(options?: ServerOptions<E>) => {
78
81
  // const root = options?.root ?? '/'
79
82
  const app = options?.app ?? new Hono<E>()
80
83
 
84
+ if (isDev())
85
+ app.use('*', logger((...args: any[]) => console.log(colors.gray(localDate()), ...args)))
86
+
81
87
  app.use(async (c: Context, next: Next) => {
82
88
  cx.setContext(c)
83
89
  Auth.resolve()
package/src/dev.ts CHANGED
@@ -1,16 +1,20 @@
1
+ import { fileURLToPath } from 'node:url'
2
+ import { dirname, join } from 'node:path'
1
3
  import { config } from 'dotenv'
2
- import { serve } from '@hono/node-server'
4
+ import { serve, type ServerType } from '@hono/node-server'
3
5
  import createApp from './create-app'
4
6
  import { getRoutes, getMiddlewares } from './routes'
5
7
  import { registerHandler, registerMiddleware } from './register'
6
8
  import { Ability } from './auth'
7
- import { getAvailablePort } from './utils/port'
8
9
  import jsonImport from './utils/json-import'
9
10
  import { setEnv, detectEnvironment } from './utils/environment'
11
+ import shutdown from './utils/shutdown'
10
12
 
11
13
  setEnv(detectEnvironment())
12
14
 
13
- config({ path: '../../.env.dev' })
15
+ const __dirname = join(dirname(fileURLToPath(import.meta.url)), '../../../')
16
+
17
+ config({ path: join(__dirname, '.env.dev') })
14
18
 
15
19
  let routes = await getRoutes()
16
20
  routes.forEach(r => registerHandler(r.name, r.handle))
@@ -20,18 +24,17 @@ const middlewares = await getMiddlewares()
20
24
  middlewares.forEach(mw => registerMiddleware(mw.handle))
21
25
 
22
26
  Ability.fromRoutes(routes)
23
- Ability.roles = jsonImport('../../../../roles.json')
27
+ Ability.roles = jsonImport(join(__dirname, 'roles.json'))
24
28
 
25
29
  const fetch = createApp({ routes }).fetch
26
30
 
27
- const desiredPort = process.env?.PORT ? Number(process.env.PORT) : 3000
28
- getAvailablePort(desiredPort)
29
- .then(port => {
30
- if (port != desiredPort)
31
- console.warn(`🟠 Port ${desiredPort} was in use, using ${port} as a fallback`)
32
-
33
- console.log(`🚀 API running on http://localhost:${port}`)
34
- serve({ fetch, port })
35
- }).catch(err => {
36
- console.error('Error finding available port:', err)
37
- })
31
+ const port = process.env?.PORT ? Number(process.env.PORT) : 3000
32
+
33
+ let server: ServerType | null = serve({ fetch, port })
34
+
35
+ shutdown(() => {
36
+ if (server) {
37
+ server?.close()
38
+ server = null
39
+ }
40
+ })
@@ -1,6 +1,6 @@
1
- import type { SchemaStructure } from './types'
2
- import getLength from '../utils/lenght'
1
+ import { getLength } from 't0n'
3
2
  import { isArraySchema } from './schema'
3
+ import type { SchemaStructure } from './types'
4
4
 
5
5
  export default class Compact {
6
6
  static #typeRegex: RegExp
@@ -89,7 +89,7 @@ export default class Compact {
89
89
  if (this.#cantZip(obj)) return obj
90
90
 
91
91
  return schema.map(key => {
92
- if (typeof key === 'string')
92
+ if (typeof key == 'string')
93
93
  return this.memo(obj[key], seen)
94
94
 
95
95
  const mainKey = Object.keys(key)[0]
@@ -1,4 +1,4 @@
1
- import plur from 'plur'
1
+ import pluralize from 'pluralize'
2
2
  import type { ModelMetadata, ModelOpts } from './types'
3
3
 
4
4
  export function getModelMetadata(target: Function | any): ModelMetadata {
@@ -9,7 +9,7 @@ export function getModelMetadata(target: Function | any): ModelMetadata {
9
9
  return {
10
10
  table: target.m[0],
11
11
  // @ts-ignore
12
- keys: typeKeys !== 'undefined' ? (typeKeys === 'string' ? { PK: target.m[1] } : { PK: target.m[1][0], SK: target.m[1][1] }) : undefined,
12
+ keys: typeKeys != 'undefined' ? (typeKeys == 'string' ? { PK: target.m[1] } : { PK: target.m[1][0], SK: target.m[1][1] }) : undefined,
13
13
  defaultSK: target?.defaultSK || undefined,
14
14
  zip: target.m[2] || false,
15
15
  fields: target.m[3] || [],
@@ -18,9 +18,9 @@ export function getModelMetadata(target: Function | any): ModelMetadata {
18
18
 
19
19
  function _table(target: Function | any, opt?: ModelOpts) {
20
20
  if (!target?.m) target.m = []
21
- const table = opt ? (typeof opt === 'string' ? opt : opt?.table) : undefined
21
+ const table = opt ? (typeof opt == 'string' ? opt : opt?.table) : undefined
22
22
 
23
- target.m[0] = table || plur(target.name.toLocaleUpperCase())
23
+ target.m[0] = table || pluralize(target.name.toLocaleUpperCase())
24
24
  }
25
25
 
26
26
  function _zip(target: Function | any) {
@@ -38,7 +38,7 @@ export function _model(target: any, opt?: ModelOpts) {
38
38
  _table(target, opt)
39
39
  const notStr = typeof opt !== 'string'
40
40
 
41
- if (!opt || !notStr || (typeof opt?.zip === undefined || opt?.zip))
41
+ if (!opt || !notStr || (opt?.zip === undefined || opt?.zip))
42
42
  _zip(target)
43
43
 
44
44
  const pk = opt && notStr ? opt?.partitionKey : undefined
@@ -68,7 +68,7 @@ function _sk(target: any, prop: string) {
68
68
  export function Entity(target: Function): void
69
69
  export function Entity(opt?: ModelOpts): ClassDecorator
70
70
  export function Entity(...args: any[]): void | ClassDecorator {
71
- if (args.length === 1 && typeof args[0] === 'function')
71
+ if (args.length == 1 && typeof args[0] == 'function')
72
72
  return _table(args[0])
73
73
 
74
74
  return (target: any) => _table(target, ...args)
@@ -77,7 +77,7 @@ export function Entity(...args: any[]): void | ClassDecorator {
77
77
  export function Model(target: Function): void
78
78
  export function Model(opt?: ModelOpts): ClassDecorator
79
79
  export function Model(...args: any[]): void | ClassDecorator {
80
- if (args.length === 1 && typeof args[0] === 'function')
80
+ if (args.length == 1 && typeof args[0] == 'function')
81
81
  return _model(args[0])
82
82
 
83
83
  return (target: any) => _model(target, ...args)
@@ -86,7 +86,7 @@ export function Model(...args: any[]): void | ClassDecorator {
86
86
  export function Zip(target: Function): void
87
87
  export function Zip(): ClassDecorator
88
88
  export function Zip(...args: any[]): void | ClassDecorator {
89
- if (args.length === 1 && typeof args[0] === 'function')
89
+ if (args.length == 1 && typeof args[0] == 'function')
90
90
  return _zip(args[0])
91
91
 
92
92
  return (target: any) => _zip(target)
@@ -105,10 +105,10 @@ export function PartitionKey(target: any, propertyKey: string | undefined, param
105
105
  export function PartitionKey(...args: any[]): void | PropertyDecorator {
106
106
  if (!args.length) return
107
107
 
108
- if (typeof args[0] === 'function' && typeof args[1] === 'string' && args[1])
108
+ if (typeof args[0] == 'function' && typeof args[1] == 'string' && args[1])
109
109
  return _pk(args[0], args[1])
110
110
 
111
- if (args.length === 1 && args[0])
111
+ if (args.length == 1 && args[0])
112
112
  return (target: any) => _pk(target, args[0])
113
113
  }
114
114
 
@@ -118,9 +118,9 @@ export function SortKey(target: any, propertyKey: string | undefined, parameterI
118
118
  export function SortKey(...args: any[]): void | PropertyDecorator {
119
119
  if (!args.length) return
120
120
 
121
- if (typeof args[0] === 'function' && typeof args[1] === 'string' && args[1])
121
+ if (typeof args[0] == 'function' && typeof args[1] == 'string' && args[1])
122
122
  return _sk(args[0], args[1])
123
123
 
124
- if (args.length === 1 && args[0])
124
+ if (args.length == 1 && args[0])
125
125
  return (target: any) => _sk(target, args[0])
126
126
  }
@@ -4,7 +4,7 @@ import QueryBuilder from './query-builder'
4
4
  import Compact from './compact'
5
5
  import { RawClient } from './client'
6
6
  import { isArraySchema } from './schema'
7
- import getLength from '../utils/lenght'
7
+ import { getLength } from 't0n'
8
8
 
9
9
  export default class AbstractModel<T extends object> {
10
10
  #meta: ModelMetadata
@@ -21,7 +21,7 @@ export default class AbstractModel<T extends object> {
21
21
  this.#queryBuilder = queryBuilder
22
22
  this.#model = model
23
23
 
24
- if (typeof (cls as ModelMetadata).table === 'string') {
24
+ if (typeof (cls as ModelMetadata).table == 'string') {
25
25
  this.#meta = cls as ModelMetadata
26
26
  this.cls = model?.cls
27
27
  return
@@ -12,7 +12,7 @@ export function Repository<
12
12
  base?: B | ModelOpts,
13
13
  opts?: ModelOpts
14
14
  ) {
15
- const isClass = typeof base === 'function'
15
+ const isClass = typeof base == 'function'
16
16
  type M = z.infer<S>
17
17
 
18
18
  const Repo = Schema(schema, isClass ? base : undefined)
package/src/esbuild.mjs CHANGED
@@ -34,7 +34,7 @@ const buildOptions = {
34
34
  bundle: true,
35
35
  minify: true,
36
36
  outfile: join(__dirname, '../../../dist/index.js'),
37
- platform: isCF ? 'browser' : 'node20',
37
+ platform: isCF ? 'browser' : 'node',
38
38
  target: isCF ? 'es2022' : 'node20',
39
39
  conditions: isCF ? ['worker', 'browser'] : [],
40
40
  format: 'esm',
@@ -44,8 +44,8 @@ const buildOptions = {
44
44
  '@aws-sdk', '@smithy',
45
45
  ...(isCF ? [
46
46
  'cloudflare:workers',
47
- 'node:crypto',
48
- 'crypto',
47
+ 'node:crypto', 'crypto',
48
+ 'node:buffer', 'buffer',
49
49
  ] : []),
50
50
  ],
51
51
  metafile: true,
@@ -102,12 +102,14 @@ existsSync(distDir)
102
102
  for (const file of await readdirSync(distDir))
103
103
  await rmSync(join(distDir, file))
104
104
 
105
- for (let file of [
106
- 'wrangler.toml',
107
- ]) {
108
- file = join(cwd, file)
109
- if (existsSync(file))
110
- copyFileSync(file, join(cwd, 'dist', basename(file)))
105
+ if (isCF) {
106
+ for (let file of [
107
+ 'wrangler.toml',
108
+ ]) {
109
+ file = join(cwd, file)
110
+ if (existsSync(file))
111
+ copyFileSync(file, join(cwd, 'dist', basename(file)))
112
+ }
111
113
  }
112
114
 
113
115
  esbuild.build(buildOptions)
package/src/http.ts CHANGED
@@ -5,10 +5,10 @@ import { Ability, Auth as Gate } from './auth'
5
5
  import mergeMiddleware from './utils/merge-middleware'
6
6
 
7
7
  function method(method: string, ...args: any[]): void | ClassDecorator {
8
- if (args.length === 1 && typeof args[0] === 'function')
8
+ if (args.length == 1 && typeof args[0] == 'function')
9
9
  return _method(method, '/', args[0])
10
10
 
11
- const path = typeof args[0] === 'string' ? args[0] : '/'
11
+ const path = typeof args[0] == 'string' ? args[0] : '/'
12
12
  return (target: Function) => _method(method, path, target)
13
13
  }
14
14
 
@@ -93,7 +93,7 @@ export function Middlewares(...handlers: MiddlewareType[]) {
93
93
  export function Auth(target: Function): void
94
94
  export function Auth(): ClassDecorator
95
95
  export function Auth(...args: any[]): void | ClassDecorator {
96
- if (args.length === 1 && typeof args[0] === 'function')
96
+ if (args.length == 1 && typeof args[0] == 'function')
97
97
  return _auth(args[0])
98
98
 
99
99
  return (target: any) => _auth(target)
package/src/index.ts CHANGED
@@ -3,4 +3,4 @@ export { Auth, Auth as Gate } from './auth/auth'
3
3
  export { default as Middleware } from './middleware'
4
4
  export { default as Request } from './request'
5
5
  export { default as Response } from './response'
6
- export { default as Enum } from './enum'
6
+ export { Enum } from 't0n'
package/src/prod-aws.ts CHANGED
@@ -1,19 +1,4 @@
1
1
  import { handle } from 'hono/aws-lambda'
2
- import createApp from './create-app'
3
- import { Ability } from './auth'
2
+ import { app } from './prod'
4
3
 
5
- // @ts-ignore
6
- await import('../../../tmp/import-routes.mjs')
7
-
8
- // @ts-ignore
9
- const routes = (await import('../../../tmp/routes.json')).default
10
-
11
- // @ts-ignore
12
- Ability.roles = (await import('../../../roles.json')).default
13
- // @ts-ignore
14
- Ability.fromRoutes(routes)
15
-
16
- // @ts-ignore
17
- const app = createApp({ routes })
18
-
19
- export const handler = handle(app) // AWS Lambda (LLRT)
4
+ export const handler = handle(app)
package/src/prod-cf.ts CHANGED
@@ -1,18 +1 @@
1
- import createApp from './create-app'
2
- import { Ability } from './auth'
3
-
4
- // @ts-ignore
5
- await import('../../../tmp/import-routes.mjs')
6
-
7
- // @ts-ignore
8
- const routes = (await import('../../../tmp/routes.json')).default
9
-
10
- // @ts-ignore
11
- Ability.roles = (await import('../../../roles.json')).default
12
- // @ts-ignore
13
- Ability.fromRoutes(routes)
14
-
15
- // @ts-ignore
16
- const app = createApp({ routes })
17
-
18
- export default app
1
+ export { app as default } from './prod'
package/src/prod.ts ADDED
@@ -0,0 +1,16 @@
1
+ import createApp from './create-app'
2
+ import { Ability } from './auth'
3
+
4
+ // @ts-ignore
5
+ await import('../../../tmp/import-routes.mjs')
6
+
7
+ // @ts-ignore
8
+ const routes = (await import('../../../tmp/routes.json')).default
9
+
10
+ // @ts-ignore
11
+ Ability.roles = (await import('../../../roles.json')).default
12
+ // @ts-ignore
13
+ Ability.fromRoutes(routes)
14
+
15
+ // @ts-ignore
16
+ export const app = createApp({ routes })
@@ -34,7 +34,7 @@ try {
34
34
  const handlers = {${routes.map(r => r.name).join()}}
35
35
 
36
36
  for (const [name, handler] of Object.entries(handlers)) {
37
- if (typeof handler === 'function' || handler.prototype?.handle) {
37
+ if (typeof handler == 'function' || handler.prototype?.handle) {
38
38
  registerHandler(name, handler)
39
39
  }
40
40
  }
@@ -10,15 +10,16 @@ export function detectEnvironment() {
10
10
  try {
11
11
  if (
12
12
  process.env?.npm_lifecycle_event == 'dev'
13
+ || process.env?.npm_lifecycle_script == 'rajt'
13
14
  || process.env?.AWS_SAM_LOCAL
14
15
  // || process?.argv?.includes('--dev')
15
- || process?.argv?.some(arg => ['--dev', '--development', '--watch'].includes(arg))
16
+ || process?.argv?.some(arg => ['-port', '-platform', '--dev', '--development', '--watch'].includes(arg))
16
17
  || process?.execArgv?.includes('--watch')
17
18
  || import.meta.url?.includes('localhost')
18
19
  ) {
19
20
  return dev
20
21
  }
21
- } catch (e) { }
22
+ } catch (e) {}
22
23
 
23
24
  return prd
24
25
  }