convert-schema-to-indexed.mjs
2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* Convert schema fixture { version, list } → config-center indexed map { "0": field, ... }
*
* 用法:node packageDynamicForm/scripts/convert-schema-to-indexed.mjs
*/
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'
import { createRequire } from 'module'
const pkgRoot = path.join(path.dirname(fileURLToPath(import.meta.url)), '..')
const require = createRequire(import.meta.url)
function listToIndexedMap(schemaRoot) {
const list = Array.isArray(schemaRoot?.list) ? schemaRoot.list : []
const sorted = [...list].sort((a, b) => {
const na = Number(a?.sortNum ?? 0)
const nb = Number(b?.sortNum ?? 0)
return na - nb
})
const indexed = {}
sorted.forEach((field, index) => {
indexed[String(index)] = field
})
return indexed
}
function writeJsModule(filePath, indexed) {
const content = `/** Config-center indexed schema (auto-generated) */\nmodule.exports = ${JSON.stringify(indexed, null, 2)}\n`
fs.writeFileSync(filePath, content, 'utf8')
}
function writeJson(filePath, indexed) {
fs.writeFileSync(filePath, `${JSON.stringify(indexed, null, 2)}\n`, 'utf8')
}
const targets = [
{
js: 'fixtures/schema-staff-daily-full.js',
json: ['fixtures/schema-staff-daily-full.json']
},
{
js: 'fixtures/schema-store-daily-full.js',
json: ['fixtures/schema-store-daily-full.json']
},
{
js: 'fixtures/schema-negotiation-full.js',
json: ['fixtures/schema-negotiation-full.json']
}
]
for (const { js, json } of targets) {
const jsPath = path.join(pkgRoot, js)
if (!fs.existsSync(jsPath)) {
console.warn('skip missing', js)
continue
}
delete require.cache[require.resolve(jsPath)]
const schemaRoot = require(jsPath)
const indexed =
schemaRoot.list != null ? listToIndexedMap(schemaRoot) : schemaRoot
writeJsModule(jsPath, indexed)
for (const j of json || []) {
const jsonPath = path.join(pkgRoot, j)
if (fs.existsSync(jsonPath)) {
fs.mkdirSync(path.dirname(jsonPath), { recursive: true })
writeJson(jsonPath, indexed)
}
}
console.log('converted', js, `(${Object.keys(indexed).length} fields)`)
}