Skip to content

Commit baa0b12

Browse files
committed
feat(@sirutils/schema): added signature check to improve performance
1 parent e8fef7c commit baa0b12

File tree

16 files changed

+117
-93
lines changed

16 files changed

+117
-93
lines changed

bun.lockb

64 Bytes
Binary file not shown.

tools/builder/package.json

+6-3
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,23 @@
22
"name": "@sirutils/builder",
33
"type": "module",
44
"version": "0.0.1",
5-
65
"bin": {
76
"builder": "./command.js"
87
},
9-
108
"main": "dist/index.js",
119
"module": "dist/index.js",
1210
"types": "dist/index.d.ts",
1311
"files": ["dist", "./command.js", "src"],
1412

15-
"devDependencies": {},
13+
"devDependencies": {
14+
"@sirutils/schema": "workspace:*"
15+
},
1616
"dependencies": {
1717
"commander": "^12.0.0",
1818
"dts-bundle-generator": "^9.5.1",
1919
"get-tsconfig": "^4.7.4"
20+
},
21+
"peerDependencies": {
22+
"@sirutils/schema": "^0.0.0"
2023
}
2124
}

tools/builder/src/definitions.ts

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
export interface CommanderOptions {
2+
cwd: string
3+
watch: boolean
4+
externalAll: boolean
5+
schema: boolean
6+
schemaDir: string
7+
external: string[]
8+
}

tools/builder/src/index.ts

+8-4
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import { watch } from 'fs'
2+
import { join } from 'path'
23
import { Command } from 'commander'
34

45
import pkg from '../package.json'
6+
import type { CommanderOptions } from './definitions'
57
import { build, dependencies } from './utils'
68

79
const program = new Command()
@@ -14,19 +16,21 @@ program
1416
.option('-w --watch', 'watch', false)
1517
.option('--cwd <string>', 'cwd', process.cwd())
1618
.option('-a --external-all', 'externals', false)
17-
.option('-e --external <numbers...>', 'externals', [])
18-
.action(async (paths: string[], options) => {
19+
.option('-s --schema', 'schema', false)
20+
.option('-sd --schema-dir', 'schema directory', join(process.cwd(), 'schemas'))
21+
.option('-e --external <packages...>', 'externals', [])
22+
.action(async (paths: string[], options: CommanderOptions) => {
1923
const externals = [
2024
...(options.externalAll ? await dependencies(options.cwd) : []),
2125
...(options.external || []),
2226
]
2327

24-
await build(paths, options.cwd, externals)
28+
await build(paths, options, externals)
2529

2630
if (options.watch) {
2731
watch(options.cwd, { recursive: true }, async (event, filename) => {
2832
if (typeof filename === 'string' && !filename.includes('dist')) {
29-
await build(paths, options.cwd, externals)
33+
await build(paths, options, externals)
3034
}
3135
})
3236
}

tools/builder/src/utils.ts

+20-4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { join } from 'path'
22
import type { BunPlugin } from 'bun'
33

4+
import type { CommanderOptions } from './definitions'
45
import { definitionGeneratorPlugin } from './plugins'
56

67
export const dependencies = async (cwd = process.cwd()): Promise<string[]> => {
@@ -19,14 +20,29 @@ export const dependencies = async (cwd = process.cwd()): Promise<string[]> => {
1920

2021
export const build = async (
2122
paths: string[],
22-
cwd: string = process.cwd(),
23+
options: CommanderOptions,
2324
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
2425
external = [] as any[]
2526
) => {
26-
const entryPoints = paths.map(p => join(cwd, p))
27-
const outDir = join(cwd, './dist')
27+
const entryPoints = paths.map(p => join(options.cwd, p))
28+
const outDir = join(options.cwd, './dist')
2829
const plugins: BunPlugin[] = [definitionGeneratorPlugin]
2930

31+
if (options.schema) {
32+
try {
33+
const schemaGeneratorPlugin = await import('@sirutils/schema')
34+
35+
plugins.push(
36+
schemaGeneratorPlugin.schemaGeneratorPlugin({
37+
dir: options.schemaDir,
38+
})
39+
)
40+
} catch (err) {
41+
// biome-ignore lint/nursery/noConsole: <explanation>
42+
console.warn(`[@sirutils/builder] cannot build schemas: ${err}`)
43+
}
44+
}
45+
3046
await Bun.build({
3147
entrypoints: entryPoints,
3248
outdir: outDir,
@@ -36,5 +52,5 @@ export const build = async (
3652
})
3753

3854
// biome-ignore lint/nursery/noConsole: <explanation>
39-
console.log(`[@sirutils/builder] building: ${cwd.split('/').slice(-2).join('/')}`)
55+
console.log(`[@sirutils/builder] building: ${options.cwd.split('/').slice(-2).join('/')}`)
4056
}

tools/schema/command.js

-3
This file was deleted.

tools/schema/package.json

+3-1
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,12 @@
22
"name": "@sirutils/schema",
33
"version": "0.0.1",
44
"type": "module",
5+
56
"main": "dist/index.js",
67
"module": "dist/index.js",
8+
"types": "dist/index.d.ts",
79
"files": ["dist", "src"],
8-
"types": "src/index.ts",
10+
911
"devDependencies": {
1012
"@sirutils/builder": "workspace:*"
1113
},

tools/schema/src/definitions/index.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
/// <reference types="packages/core" />
2-
/// <reference types="packages/seql" />
1+
/// <reference types="@sirutils/core" />
2+
/// <reference types="@sirutils/seql" />
33

44
import './schema'

tools/schema/src/definitions/schema.ts

+22-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import type { BlobType } from '@sirutils/core'
2+
13
import type { SchemaTags } from '../tag'
24

35
declare global {
@@ -8,6 +10,25 @@ declare global {
810
}
911

1012
// biome-ignore lint/style/noNamespace: Redundant
11-
namespace Schema {}
13+
namespace Schema {
14+
export interface Normalized {
15+
name: string
16+
path: string
17+
checksum: string
18+
exists: boolean
19+
20+
importMaps: Record<string, Sirutils.Schema.Normalized>
21+
22+
fields: {
23+
name: string
24+
type: string
25+
[x: string]: BlobType
26+
}[]
27+
indexes: {
28+
name: string
29+
fields: string[]
30+
}[]
31+
}
32+
}
1233
}
1334
}

tools/schema/src/index.ts

+1
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,4 @@ import './definitions'
33
export * from './tag'
44

55
export * from './utils/traverse'
6+
export * from './utils/plugin'

tools/schema/src/internal/fs.ts

+5-14
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ export const readJsonFile = ResultAsync.fromThrowable(
1515
)
1616

1717
export const getFileChecksum = ResultAsync.fromThrowable(
18-
(path: string) => {
18+
(path: string): Promise<string> => {
1919
return new Promise((resolve, reject) => {
2020
const hasher = new Bun.CryptoHasher('blake2b512')
2121
const input = fs.createReadStream(path)
@@ -35,21 +35,12 @@ export const getFileChecksum = ResultAsync.fromThrowable(
3535
)
3636

3737
export const getChecksum = Result.fromThrowable(
38-
(path: string) => {
39-
return new Promise((resolve, reject) => {
40-
const hasher = new Bun.CryptoHasher('blake2b512')
41-
const input = fs.createReadStream(path)
38+
(data: Bun.BlobOrStringOrBuffer) => {
39+
const hasher = new Bun.CryptoHasher('blake2b512')
4240

43-
input.on('error', reject)
44-
45-
input.on('data', chunk => {
46-
hasher.update(chunk)
47-
})
41+
hasher.update(data)
4842

49-
input.on('close', () => {
50-
resolve(hasher.digest('hex'))
51-
})
52-
})
43+
return hasher.digest('hex')
5344
},
5445
e => ProjectError.create(schemaTags.getFileChecksum, `${e}`)
5546
)

tools/schema/src/utils/plugin.ts

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { existsSync, mkdirSync } from 'node:fs'
2+
import { join } from 'node:path'
3+
import { unwrap } from '@sirutils/core'
4+
import type { BunPlugin } from 'bun'
5+
6+
import { traverse } from './traverse'
7+
8+
export interface SchemaGeneratorPluginConfig {
9+
dir?: string
10+
}
11+
12+
export const schemaGeneratorPlugin = (config: SchemaGeneratorPluginConfig): BunPlugin => {
13+
return {
14+
name: 'schema-generator-plugin',
15+
async setup(build) {
16+
const outDir = build.config.outdir || './dist'
17+
if (!existsSync(outDir)) {
18+
mkdirSync(outDir)
19+
}
20+
21+
const missingFiles = unwrap(await traverse(config.dir ?? join(process.cwd(), 'schemas')))
22+
23+
// biome-ignore lint/nursery/noConsole: <explanation>
24+
console.log(missingFiles)
25+
},
26+
}
27+
}

tools/schema/src/utils/traverse.ts

+15-5
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,21 @@
1-
import path from 'node:path'
1+
import { join } from 'node:path'
22
import { ResultAsync, unwrap, wrapAsync } from '@sirutils/core/dist'
33

44
import { fetchJson, isURL } from '../internal/common'
5-
import { readJsonFile, readdir } from '../internal/fs'
5+
import { getFileChecksum, readJsonFile, readdir } from '../internal/fs'
66
import { schemaTags } from '../tag'
77

88
export const traverse = wrapAsync(async (dirPath: string) => {
9-
const filePaths = unwrap(await readdir(dirPath)).map(filePath => path.join(dirPath, filePath))
9+
const filePaths = unwrap(await readdir(dirPath)).map(filePath => join(dirPath, filePath))
1010
const files = unwrap(await ResultAsync.combine(filePaths.map(filePath => readJsonFile(filePath))))
1111

1212
for (const file of files) {
13+
const index = files.indexOf(file)
14+
15+
file.path = filePaths[index]
16+
file.checksum = unwrap(await getFileChecksum(file.path))
17+
file.exists = await Bun.file(join(dirPath, 'dist/generated', file.checksum)).exists()
18+
1319
if (file.importMaps) {
1420
for (const [name, extendedPath] of Object.entries(file.importMaps)) {
1521
const valid = isURL(extendedPath as string)
@@ -24,7 +30,7 @@ export const traverse = wrapAsync(async (dirPath: string) => {
2430
continue
2531
}
2632

27-
const relativeExtendedPath = path.join(dirPath, extendedPath as string)
33+
const relativeExtendedPath = join(dirPath, extendedPath as string)
2834
const foundIndex = filePaths.indexOf(relativeExtendedPath)
2935

3036
if (foundIndex === -1) {
@@ -33,8 +39,12 @@ export const traverse = wrapAsync(async (dirPath: string) => {
3339
file.importMaps[name] = files[foundIndex]
3440
}
3541
}
42+
43+
continue
3644
}
45+
46+
file.importMaps = {}
3747
}
3848

39-
return files
49+
return files as Sirutils.Schema.Normalized[]
4050
}, schemaTags.traverse)

tools/schema/test/index.ts

-9
This file was deleted.

tools/schema/test/schemas/blogs.json

-25
This file was deleted.

tools/schema/test/schemas/users.json

-22
This file was deleted.

0 commit comments

Comments
 (0)