convert-schema-to-indexed.mjs 2.04 KB
/**
 * 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)`)
}