gatelight 0.0.0-stage → 0.18.0

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 (109) hide show
  1. package/.antigravity-plugin/plugin.json +9 -0
  2. package/.claude-plugin/plugin.json +11 -0
  3. package/.codex-plugin/plugin.json +18 -0
  4. package/.mcp.json +8 -0
  5. package/LICENSE +21 -0
  6. package/README.md +29 -2
  7. package/bin/modwall +8 -0
  8. package/bin/node.sh +14 -0
  9. package/bin/testcraft +8 -0
  10. package/bin/testpace +8 -0
  11. package/entry/command +44 -0
  12. package/hooks/antigravity.sh +24 -0
  13. package/hooks/codex.json +50 -0
  14. package/hooks/codex.sh +7 -0
  15. package/hooks/hooks.json +43 -0
  16. package/hooks/testpace.ts +25 -0
  17. package/hooks.json +16 -0
  18. package/mcp_config.json +8 -0
  19. package/package.json +23 -4
  20. package/setup.mjs +99 -0
  21. package/skills/merge/SKILL.md +42 -0
  22. package/skills/modular/SKILL.md +75 -0
  23. package/skills/setup/SKILL.md +101 -0
  24. package/skills/setup-modwall/SKILL.md +112 -0
  25. package/skills/setup-testcraft/SKILL.md +23 -0
  26. package/skills/setup-testcraft/checklist/dev-login.md +20 -0
  27. package/skills/write-tests/SKILL.md +153 -0
  28. package/src/base/agent.ts +100 -0
  29. package/src/base/baseline.ts +54 -0
  30. package/src/base/commandline.ts +40 -0
  31. package/src/base/commands.ts +94 -0
  32. package/src/base/confirm.ts +161 -0
  33. package/src/base/contract.ts +94 -0
  34. package/src/base/coverage.ts +46 -0
  35. package/src/base/entry.ts +90 -0
  36. package/src/base/excerpt.ts +46 -0
  37. package/src/base/execute.ts +70 -0
  38. package/src/base/exit.ts +6 -0
  39. package/src/base/format.ts +27 -0
  40. package/src/base/full.ts +160 -0
  41. package/src/base/gate.ts +251 -0
  42. package/src/base/git.ts +361 -0
  43. package/src/base/glob.ts +38 -0
  44. package/src/base/hook.ts +297 -0
  45. package/src/base/hookformat.ts +257 -0
  46. package/src/base/judging.ts +27 -0
  47. package/src/base/layermap.ts +69 -0
  48. package/src/base/module.ts +88 -0
  49. package/src/base/process-group.ts +101 -0
  50. package/src/base/records.ts +66 -0
  51. package/src/base/repo.ts +155 -0
  52. package/src/base/sessions.ts +55 -0
  53. package/src/base/shell.ts +176 -0
  54. package/src/base/stop.ts +100 -0
  55. package/src/base/store.ts +348 -0
  56. package/src/base/version.ts +24 -0
  57. package/src/cli.ts +186 -0
  58. package/src/craft/change.ts +24 -0
  59. package/src/craft/checklist.ts +157 -0
  60. package/src/craft/commands.ts +111 -0
  61. package/src/craft/config.ts +15 -0
  62. package/src/craft/full.ts +30 -0
  63. package/src/craft/index.ts +12 -0
  64. package/src/craft/session.ts +21 -0
  65. package/src/mcp.ts +79 -0
  66. package/src/modules.ts +10 -0
  67. package/src/modwall.ts +8 -0
  68. package/src/pace/commands.ts +281 -0
  69. package/src/pace/config.ts +103 -0
  70. package/src/pace/consent.ts +81 -0
  71. package/src/pace/focused.ts +208 -0
  72. package/src/pace/full.ts +38 -0
  73. package/src/pace/index.ts +16 -0
  74. package/src/pace/record.ts +84 -0
  75. package/src/pace/report.ts +335 -0
  76. package/src/pace/results.ts +243 -0
  77. package/src/pace/run/node-test-reporter.mjs +34 -0
  78. package/src/pace/run/node-test.ts +26 -0
  79. package/src/pace/run/playwright-reporter.mjs +48 -0
  80. package/src/pace/run/playwright.ts +34 -0
  81. package/src/pace/run/runner.ts +157 -0
  82. package/src/pace/run/targets.ts +130 -0
  83. package/src/pace/run/vitest-launcher.mjs +101 -0
  84. package/src/pace/run/vitest.ts +22 -0
  85. package/src/pace/session.ts +35 -0
  86. package/src/pace/testlist.ts +91 -0
  87. package/src/pace/tests.ts +22 -0
  88. package/src/pace/verify.ts +95 -0
  89. package/src/testcraft.ts +9 -0
  90. package/src/wall/check.ts +258 -0
  91. package/src/wall/commands.ts +279 -0
  92. package/src/wall/config.ts +394 -0
  93. package/src/wall/database.ts +136 -0
  94. package/src/wall/dbcheck.ts +389 -0
  95. package/src/wall/dbrules.ts +213 -0
  96. package/src/wall/edit.ts +64 -0
  97. package/src/wall/files.ts +35 -0
  98. package/src/wall/full.ts +30 -0
  99. package/src/wall/index.ts +15 -0
  100. package/src/wall/init.ts +149 -0
  101. package/src/wall/layermap.ts +124 -0
  102. package/src/wall/layout.ts +231 -0
  103. package/src/wall/loosen.ts +157 -0
  104. package/src/wall/miniprogram.ts +80 -0
  105. package/src/wall/project.ts +88 -0
  106. package/src/wall/rules.ts +400 -0
  107. package/src/wall/session.ts +198 -0
  108. package/src/wall/sql.ts +510 -0
  109. package/src/wall/store.ts +39 -0
@@ -0,0 +1,394 @@
1
+ // 项目约定 .modwall/config.json 的读取和校验。各项路径重叠要看实际的文件,在 layout.ts 里查。
2
+ // roots 模块根目录:下面每个子目录是一个模块(写目录,不用通配)
3
+ // shared 共享层,app 装配层,outside 不归 modwall 管的路径(路径规则)
4
+ // entry 模块对外入口的文件名(模块目录下第一层)
5
+ // map 框架要求放在固定目录的文件:路径规则 → 模块名
6
+ // allow 用户确认过的例外:一条被放过的 import,写到文件
7
+ // database 用 Postgres 时:每个模块放迁移的子目录名(migrations)、共享层的迁移目录(shared)、程序的登录账号(login)、跑迁移的账号(migrator),
8
+ // 可选的模块运行角色模板(runtime,比如 "<module>_app")。schema、模块的角色和运行角色按模块目录名算(database.ts)
9
+ // 一个仓库里有几个应用时按应用分组写:apps 每组一个应用(roots、shared、app、entry、map,用库的应用写 database),
10
+ // 外面一层只能有 apps、shared(几个应用共用的共享层)、outside、allow。两种写法不能混用。
11
+ // 规则都按 schemeOf 统一成"几个应用"来算:单应用就是一个没有名字的应用。
12
+
13
+ import { existsSync } from 'node:fs'
14
+ import { join, posix } from 'node:path'
15
+ import { hasFile } from '../base/git.ts'
16
+
17
+ export const MODWALL_DIR = '.modwall'
18
+ export const CONFIG_PATH = `${MODWALL_DIR}/config.json`
19
+
20
+ const RULES_WITH_EXCEPTIONS = ['R1', 'R2', 'R3'] as const
21
+ export type ExceptionRule = (typeof RULES_WITH_EXCEPTIONS)[number]
22
+
23
+ export interface AllowEntry {
24
+ rule: ExceptionRule
25
+ from: string
26
+ to: string
27
+ reason: string
28
+ }
29
+
30
+ /**
31
+ * 数据库:migrations 是每个模块放迁移的子目录(相对模块目录),shared 是共享层的迁移目录(相对仓库根目录);
32
+ * login 是程序连库用的账号,migrator 是跑迁移用的账号(都只能切成模块的角色,modwall db check 查它们)。
33
+ * runtime(可选)是模块运行角色的名字模板,<module> 换成模块的内部 schema 名:模块的代码切成它执行,它只有本模块的读写授权,
34
+ * 可以用本模块的内部 schema,不拥有对象、不能建对象。不写就是模块的代码直接切成模块的角色。
35
+ */
36
+ export interface DatabaseConfig {
37
+ migrations: string
38
+ shared: string
39
+ login: string
40
+ migrator: string
41
+ runtime?: string
42
+ }
43
+
44
+ /** 运行角色模板里代表模块的占位符。 */
45
+ export const MODULE_PLACEHOLDER = '<module>'
46
+
47
+ const DATABASE_SHAPE =
48
+ '{ "migrations": 模块里放迁移的子目录, "shared": 共享层的迁移目录, "login": 程序的登录账号, "migrator": 跑迁移的账号, "runtime": 模块运行角色的名字模板(可选,比如 "<module>_app") }'
49
+ const DATABASE_KEYS = ['migrations', 'shared', 'login', 'migrator', 'runtime']
50
+
51
+ /** 一个应用的划分:单应用写法的这几项,或者按应用分组时 apps 里的一组。database:这个应用用 Postgres 时才有。 */
52
+ export interface AppConfig {
53
+ roots: string[]
54
+ shared: string[]
55
+ app: string[]
56
+ entry: string[]
57
+ map: Record<string, string>
58
+ database?: DatabaseConfig
59
+ }
60
+
61
+ /** 单应用的写法:整个仓库一套模块。 */
62
+ export interface SingleConfig extends AppConfig {
63
+ outside: string[]
64
+ allow: AllowEntry[]
65
+ }
66
+
67
+ /** 按应用分组的写法:apps 每组一个应用;外面一层的 shared 是几个应用共用的共享层,outside、allow 只写在外面一层。 */
68
+ export interface GroupedConfig {
69
+ apps: Record<string, AppConfig>
70
+ shared: string[]
71
+ outside: string[]
72
+ allow: AllowEntry[]
73
+ }
74
+
75
+ /** 配置文件里写的样子(两种写法之一)。规则都按 schemeOf 统一成"几个应用"来算。 */
76
+ export type Config = SingleConfig | GroupedConfig
77
+
78
+ const APP_KEYS = ['roots', 'shared', 'app', 'entry', 'map', 'database'] as const
79
+ const SINGLE_KEYS = [...APP_KEYS, 'outside', 'allow'] as const
80
+ const GROUPED_KEYS = ['apps', 'shared', 'outside', 'allow'] as const
81
+
82
+ /** 一个应用。name:按应用分组时的应用名;单应用的写法是一个没有名字的应用。 */
83
+ export interface App extends AppConfig {
84
+ name?: string
85
+ }
86
+
87
+ /**
88
+ * 统一的划分:单应用 = 一个没有名字的应用、外面一层的 shared 为空。
89
+ * shared:外面一层的共享层(几个应用共用的);grouped:配置是按应用分组写的。
90
+ */
91
+ export interface Scheme {
92
+ grouped: boolean
93
+ apps: App[]
94
+ shared: string[]
95
+ outside: string[]
96
+ allow: AllowEntry[]
97
+ }
98
+
99
+ export function schemeOf(config: Config): Scheme {
100
+ if ('apps' in config) {
101
+ return { grouped: true, apps: Object.entries(config.apps).map(([name, app]) => ({ name, ...app })), shared: config.shared, outside: config.outside, allow: config.allow }
102
+ }
103
+ const { outside, allow, ...app } = config
104
+ return { grouped: false, apps: [app], shared: [], outside, allow }
105
+ }
106
+
107
+ /** 这个应用的某一项在配置里的写法:单应用就是字段名,按应用分组是 apps.<应用名>.<字段名>。 */
108
+ export const field = (app: App, key: string): string => (app.name === undefined ? key : `apps.${app.name}.${key}`)
109
+
110
+ /** 模块的名字:模块名只在应用内唯一,按应用分组时写成 应用名/模块名。 */
111
+ export const moduleId = (app: string | undefined, name: string): string => (app === undefined ? name : `${app}/${name}`)
112
+
113
+ export interface Parsed {
114
+ config?: Config
115
+ problems: string[]
116
+ }
117
+
118
+ /** 仓库里的相对路径:去掉开头的 ./ 和结尾的 /;不能是绝对路径,不能有 ..、空段。 */
119
+ function relativePath(value: string): string | undefined {
120
+ const plain = value.replace(/^(?:\.\/)+/, '').replace(/\/+$/, '')
121
+ if (plain === '' || plain.startsWith('/') || plain.includes('\\')) return undefined
122
+ if (plain.split('/').some(segment => segment === '' || segment === '.' || segment === '..')) return undefined
123
+ return posix.normalize(plain) === plain ? plain : undefined
124
+ }
125
+
126
+ export const GLOB_CHARS = /[*?[\]{}]/
127
+ /** 账号名、schema 名:不用加引号的 Postgres 名字。 */
128
+ export const PLAIN_NAME = /^[a-z_][a-z0-9_]*$/
129
+
130
+ /** 路径规则:和 relativePath 一样,但保留结尾的 /(表示整个目录)。 */
131
+ function pattern(value: string): string | undefined {
132
+ const dir = value.endsWith('/')
133
+ const plain = relativePath(value)
134
+ return plain === undefined ? undefined : dir ? `${plain}/` : plain
135
+ }
136
+
137
+ const CONTROL = /[\u0000-\u001f\u007f]/
138
+
139
+ /** 配置里带换行或控制字符的字符串(键和值)在哪里,比如 allow[0].reason。 */
140
+ function linesIn(value: unknown, where: string): string[] {
141
+ if (typeof value === 'string') return CONTROL.test(value) ? [where] : []
142
+ if (Array.isArray(value)) return value.flatMap((item, index) => linesIn(item, `${where}[${index}]`))
143
+ if (typeof value !== 'object' || value === null) return []
144
+ return Object.entries(value).flatMap(([key, item]) => {
145
+ const at = where ? `${where}.${JSON.stringify(key).slice(1, -1)}` : JSON.stringify(key).slice(1, -1)
146
+ return [...(CONTROL.test(key) ? [`${at}(键)`] : []), ...linesIn(item, at)]
147
+ })
148
+ }
149
+
150
+ const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)
151
+
152
+ /** 读一组字段时的上下文:prefix 是报错里字段名前面的部分(按应用分组时是 apps.<应用名>.)。 */
153
+ class Reader {
154
+ readonly record: Record<string, unknown>
155
+ readonly prefix: string
156
+ readonly problems: string[]
157
+
158
+ constructor(record: Record<string, unknown>, prefix: string, problems: string[]) {
159
+ this.record = record
160
+ this.prefix = prefix
161
+ this.problems = problems
162
+ }
163
+
164
+ strings(key: string, required: boolean): string[] | undefined {
165
+ const value = this.record[key]
166
+ const name = `${this.prefix}${key}`
167
+ if (value === undefined) {
168
+ if (required) this.problems.push(`${CONFIG_PATH} 缺少 "${name}"`)
169
+ return undefined
170
+ }
171
+ if (!Array.isArray(value) || value.some(item => typeof item !== 'string' || item.trim() === '')) {
172
+ this.problems.push(`${CONFIG_PATH} 的 "${name}" 应该是非空字符串的数组`)
173
+ return undefined
174
+ }
175
+ return value as string[]
176
+ }
177
+
178
+ /** shared、app、outside 这类路径规则的列表。 */
179
+ patterns(key: string): string[] {
180
+ const rules: string[] = []
181
+ const name = `${this.prefix}${key}`
182
+ for (const value of this.strings(key, false) ?? []) {
183
+ const rule = pattern(value)
184
+ if (rule === undefined) this.problems.push(`${name} 里的 "${value}" 要写仓库里的相对路径或路径规则`)
185
+ else if (rules.includes(rule)) this.problems.push(`${name} 里的 "${value}" 写了两次`)
186
+ else rules.push(rule)
187
+ }
188
+ return rules
189
+ }
190
+
191
+ /** 一个应用的 roots、shared、app、entry、map、database。 */
192
+ app(): AppConfig {
193
+ const { prefix, problems } = this
194
+ const config: AppConfig = { roots: [], shared: [], app: [], entry: [], map: {} }
195
+ for (const value of this.strings('roots', true) ?? []) {
196
+ const root = relativePath(value)
197
+ if (root === undefined || GLOB_CHARS.test(root)) problems.push(`${prefix}roots 里的 "${value}" 要写仓库里的目录(相对路径,不用通配)`)
198
+ else if (config.roots.includes(root)) problems.push(`${prefix}roots 里的 "${value}" 写了两次`)
199
+ else config.roots.push(root)
200
+ }
201
+ config.shared = this.patterns('shared')
202
+ config.app = this.patterns('app')
203
+
204
+ for (const value of this.strings('entry', true) ?? []) {
205
+ if (value.includes('/') || GLOB_CHARS.test(value) || value === '.' || value === '..') problems.push(`${prefix}entry 里的 "${value}" 要写文件名(模块目录下第一层的文件),不带目录和通配`)
206
+ else if (config.entry.includes(value)) problems.push(`${prefix}entry 里的 "${value}" 写了两次`)
207
+ else config.entry.push(value)
208
+ }
209
+
210
+ const map = this.record.map
211
+ if (map !== undefined) {
212
+ if (!isRecord(map)) problems.push(`${CONFIG_PATH} 的 "${prefix}map" 应该是"路径规则 → 模块名"的对象`)
213
+ else {
214
+ for (const [key, value] of Object.entries(map)) {
215
+ const rule = pattern(key)
216
+ if (rule === undefined) problems.push(`${prefix}map 里的 "${key}" 要写仓库里的相对路径或路径规则`)
217
+ else if (typeof value !== 'string' || value === '' || value.includes('/')) problems.push(`${prefix}map 里 "${key}" 的值要写模块名(模块根目录下的目录名)`)
218
+ else if (rule in config.map) problems.push(`${prefix}map 里的 "${key}" 写了两次`)
219
+ else config.map[rule] = value
220
+ }
221
+ }
222
+ }
223
+ const database = this.database()
224
+ if (database) config.database = database
225
+ return config
226
+ }
227
+
228
+ /** database:两个目录(写目录、不用通配)、两个账号名和可选的运行角色模板。 */
229
+ database(): DatabaseConfig | undefined {
230
+ const value = this.record.database
231
+ const name = `${this.prefix}database`
232
+ if (value === undefined) return undefined
233
+ if (!isRecord(value)) {
234
+ this.problems.push(`${CONFIG_PATH} 的 "${name}" 应该是 ${DATABASE_SHAPE}`)
235
+ return undefined
236
+ }
237
+ const extra = Object.keys(value).filter(key => !DATABASE_KEYS.includes(key))
238
+ if (extra.length) this.problems.push(`${CONFIG_PATH} 的 "${name}" 有未知字段 ${extra.map(key => `"${key}"`).join('、')}`)
239
+ const dir = (key: 'migrations' | 'shared', what: string): string | undefined => {
240
+ const raw = value[key]
241
+ const path = typeof raw === 'string' ? relativePath(raw) : undefined
242
+ if (path === undefined || GLOB_CHARS.test(path)) {
243
+ this.problems.push(`${CONFIG_PATH} 的 "${name}.${key}" 要写${what}(相对路径,不用通配)`)
244
+ return undefined
245
+ }
246
+ return path
247
+ }
248
+ const account = (key: 'login' | 'migrator', what: string): string | undefined => {
249
+ const raw = value[key]
250
+ if (typeof raw === 'string' && PLAIN_NAME.test(raw)) return raw
251
+ this.problems.push(`${CONFIG_PATH} 的 "${name}.${key}" 要写${what}的名字(小写字母、数字和下划线,不以数字开头)`)
252
+ return undefined
253
+ }
254
+ const migrations = dir('migrations', '每个模块放迁移的子目录(相对模块目录,比如 "migrations")')
255
+ const shared = dir('shared', '共享层的迁移目录(从仓库根目录写起)')
256
+ const login = account('login', '程序连库用的账号')
257
+ const migrator = account('migrator', '跑迁移用的账号')
258
+ // 模板里正好一个 <module>,换成模块的 schema 名后仍是普通的角色名;只写 <module> 就是模块的角色本身
259
+ const template = value.runtime
260
+ const runtimeOk =
261
+ template === undefined ||
262
+ (typeof template === 'string' && template !== MODULE_PLACEHOLDER && template.split(MODULE_PLACEHOLDER).length === 2 && PLAIN_NAME.test(template.replace(MODULE_PLACEHOLDER, 'm')))
263
+ if (!runtimeOk) {
264
+ this.problems.push(
265
+ `${CONFIG_PATH} 的 "${name}.runtime" 要写模块运行角色的名字模板:带一个 ${MODULE_PLACEHOLDER}(换成模块的内部 schema 名),其余是小写字母、数字和下划线,比如 "${MODULE_PLACEHOLDER}_app";不能只写 ${MODULE_PLACEHOLDER}(那是模块的角色本身)`,
266
+ )
267
+ }
268
+ if (migrations === undefined || shared === undefined || login === undefined || migrator === undefined || !runtimeOk) return undefined
269
+ return { migrations, shared, login, migrator, ...(typeof template === 'string' ? { runtime: template } : {}) }
270
+ }
271
+
272
+ allow(): AllowEntry[] {
273
+ const { problems } = this
274
+ const entries: AllowEntry[] = []
275
+ const allow = this.record.allow
276
+ if (allow === undefined) return entries
277
+ if (!Array.isArray(allow)) {
278
+ problems.push(`${CONFIG_PATH} 的 "allow" 应该是数组`)
279
+ return entries
280
+ }
281
+ const seen = new Set<string>()
282
+ allow.forEach((item, index) => {
283
+ const where = `allow 的第 ${index + 1} 条`
284
+ if (!isRecord(item)) {
285
+ problems.push(`${where} 应该是 { "rule", "from", "to", "reason" }`)
286
+ return
287
+ }
288
+ const entry = item
289
+ const extra = Object.keys(entry).filter(key => !['rule', 'from', 'to', 'reason'].includes(key))
290
+ if (extra.length) problems.push(`${where} 有未知字段 ${extra.map(key => `"${key}"`).join('、')}`)
291
+ if (typeof entry.rule !== 'string' || !(RULES_WITH_EXCEPTIONS as readonly string[]).includes(entry.rule)) {
292
+ problems.push(`${where} 的 rule 要写 ${RULES_WITH_EXCEPTIONS.join('、')} 之一(例外是一条被放过的 import)`)
293
+ return
294
+ }
295
+ const from = typeof entry.from === 'string' ? relativePath(entry.from) : undefined
296
+ const to = typeof entry.to === 'string' ? relativePath(entry.to) : undefined
297
+ if (from === undefined || to === undefined || GLOB_CHARS.test(from) || GLOB_CHARS.test(to)) {
298
+ problems.push(`${where} 的 from 和 to 要写到具体的文件(相对路径,不用通配)`)
299
+ return
300
+ }
301
+ if (typeof entry.reason !== 'string' || entry.reason.trim() === '') {
302
+ problems.push(`${where} 要写理由(reason)`)
303
+ return
304
+ }
305
+ const key = `${entry.rule}\0${from}\0${to}`
306
+ if (seen.has(key)) {
307
+ problems.push(`${where} 和前面的重复了(${entry.rule} ${from} → ${to})`)
308
+ return
309
+ }
310
+ seen.add(key)
311
+ entries.push({ rule: entry.rule as ExceptionRule, from, to, reason: entry.reason.trim() })
312
+ })
313
+ return entries
314
+ }
315
+ }
316
+
317
+ /** 模块根目录不能互相嵌套:一个应用里的,不同应用之间的都不行。 */
318
+ function nestedRoots(scheme: Scheme): string[] {
319
+ const all = scheme.apps.flatMap(app => app.roots.map(root => ({ root, at: scheme.grouped ? `${field(app, 'roots')} 的 ` : '' })))
320
+ const problems: string[] = []
321
+ all.forEach((a, i) => {
322
+ all.forEach((b, j) => {
323
+ if (i === j) return
324
+ if (b.root.startsWith(`${a.root}/`)) problems.push(`roots 重叠:${b.at}"${b.root}" 在 ${a.at}"${a.root}" 里面`)
325
+ else if (a.root === b.root && i < j) problems.push(`roots 重叠:${a.at}"${a.root}" 和 ${b.at}"${b.root}" 是同一个目录`)
326
+ })
327
+ })
328
+ return problems
329
+ }
330
+
331
+ export function parseConfig(text: string): Parsed {
332
+ let raw: unknown
333
+ try {
334
+ raw = JSON.parse(text)
335
+ } catch (error) {
336
+ return { problems: [`${CONFIG_PATH} 不是合法的 JSON:${(error as Error).message}`] }
337
+ }
338
+ if (!isRecord(raw)) return { problems: [`${CONFIG_PATH} 应该是一个对象`] }
339
+ const record = raw
340
+ // 路径、模块名、应用名、理由都会原样进放宽项的文字(弹窗里一项一行):带换行的会多出一行像另一项的文字,先拦下
341
+ const multiline = linesIn(record, '')
342
+ if (multiline.length) return { problems: multiline.map(where => `${CONFIG_PATH} 的 ${where} 带换行或控制字符:路径、模块名、理由都要写成一行`) }
343
+ const problems: string[] = []
344
+ const outer = new Reader(record, '', problems)
345
+ let config: Config
346
+ if ('apps' in record) {
347
+ for (const key of Object.keys(record)) {
348
+ if ((GROUPED_KEYS as readonly string[]).includes(key)) continue
349
+ if ((APP_KEYS as readonly string[]).includes(key)) problems.push(`${CONFIG_PATH} 写了 "apps"(按应用分组),外面一层就只能有 ${GROUPED_KEYS.join('、')}:"${key}" 要写进各个应用里,两种写法不能混用`)
350
+ else problems.push(`${CONFIG_PATH} 有未知字段 "${key}"`)
351
+ }
352
+ const apps: Record<string, AppConfig> = {}
353
+ if (!isRecord(record.apps)) problems.push(`${CONFIG_PATH} 的 "apps" 应该是"应用名 → 这个应用的 roots、shared、app、entry、map"的对象`)
354
+ else if (Object.keys(record.apps).length === 0) problems.push(`${CONFIG_PATH} 的 "apps" 里至少要有一个应用;只有一个应用就用单应用的写法`)
355
+ else {
356
+ for (const [name, value] of Object.entries(record.apps)) {
357
+ const prefix = `apps.${name}.`
358
+ if (name.trim() === '' || name.includes('/')) {
359
+ problems.push(`${CONFIG_PATH} 的 apps 里的应用名 "${name}" 要写成一段名字(不带 /)`)
360
+ continue
361
+ }
362
+ if (!isRecord(value)) {
363
+ problems.push(`${CONFIG_PATH} 的 "apps.${name}" 应该是这个应用的 roots、shared、app、entry、map、database`)
364
+ continue
365
+ }
366
+ for (const key of Object.keys(value)) {
367
+ if ((APP_KEYS as readonly string[]).includes(key)) continue
368
+ if (key === 'outside' || key === 'allow') problems.push(`${CONFIG_PATH} 的 "${prefix}${key}" 要写在外面一层:${key} 不分应用`)
369
+ else problems.push(`${CONFIG_PATH} 的 "apps.${name}" 有未知字段 "${key}"`)
370
+ }
371
+ apps[name] = new Reader(value, prefix, problems).app()
372
+ }
373
+ }
374
+ config = { apps, shared: outer.patterns('shared'), outside: outer.patterns('outside'), allow: outer.allow() }
375
+ } else {
376
+ for (const key of Object.keys(record)) {
377
+ if (!(SINGLE_KEYS as readonly string[]).includes(key)) problems.push(`${CONFIG_PATH} 有未知字段 "${key}"`)
378
+ }
379
+ const app = outer.app()
380
+ config = { ...app, outside: outer.patterns('outside'), allow: outer.allow() }
381
+ }
382
+ problems.push(...nestedRoots(schemeOf(config)))
383
+ return problems.length ? { problems } : { config, problems }
384
+ }
385
+
386
+ /** 一版配置(text 是配置文件的内容,经底座读来):exists 为 false 时就是没有配置文件。 */
387
+ export function readConfig(text: string | undefined): Parsed & { exists: boolean } {
388
+ return text === undefined ? { exists: false, problems: [] } : { exists: true, ...parseConfig(text) }
389
+ }
390
+
391
+ /** 接入了 modwall:分叉点或工作区里有 .modwall/。按分叉点也算,删掉目录躲不过检查。 */
392
+ export function joined(root: string, fork?: string): boolean {
393
+ return existsSync(join(root, MODWALL_DIR)) || (fork !== undefined && hasFile(root, fork, MODWALL_DIR))
394
+ }
@@ -0,0 +1,136 @@
1
+ // 数据库按模块分(设计方案第 4 节「数据库」):位置就是归属,不另外登记。
2
+ // 每个模块两个 schema:内部(模块目录名转成小写加下划线,adminAccess → admin_access)和入口(<内部>_api,只放视图和函数);
3
+ // 共享层用 shared;public 里不放对象(扩展自带的除外)。
4
+ // 每个模块一个角色,名字就是它的内部 schema 名;共享层的角色叫 shared。程序的登录账号、跑迁移的账号不能和它们同名。
5
+ // 配置写了运行角色模板(database.runtime)的,每个模块还有一个运行角色(模板里的 <module> 换成内部 schema 名),不能和上面这些角色、账号同名。
6
+ // 迁移放在每个模块目录下的 database.migrations 子目录、共享层的 database.shared 目录,文件名以 14 位的时间戳开头,不能重复(迁移只写正向,一个时间戳一个文件)。
7
+ // 这里只管划分:每个应用的库有哪些 schema、各归谁,迁移文件各归谁,以及这些算出来的配置错误。只看路径,layout.ts 用它。
8
+ // R6 的判定在 dbrules.ts(迁移文件那部分,modwall check)和 dbcheck.ts(库里的现状,modwall db check)。
9
+
10
+ import { type App, MODULE_PLACEHOLDER, PLAIN_NAME } from './config.ts'
11
+ import type { Module } from './layout.ts'
12
+
13
+ export const API_SUFFIX = '_api'
14
+ export const SHARED_SCHEMA = 'shared'
15
+ export const PUBLIC_SCHEMA = 'public'
16
+
17
+ /** 模块目录名转成 schema 名:驼峰和连字符都变成下划线,全小写。 */
18
+ export function schemaName(module: string): string {
19
+ return module
20
+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
21
+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
22
+ .replace(/[-\s.]+/g, '_')
23
+ .toLowerCase()
24
+ }
25
+
26
+ export type SchemaOwner = { kind: 'internal'; module: Module } | { kind: 'api'; module: Module } | { kind: 'shared' }
27
+
28
+ /** 迁移文件:owner 是它所在的模块,或者共享层(undefined)。 */
29
+ export interface Migration {
30
+ path: string
31
+ module?: Module
32
+ }
33
+
34
+ /** 一个应用的库。 */
35
+ export interface Database {
36
+ app: App
37
+ /** 模块的内部、入口 schema 和 shared 各归谁(public 不在里面)。 */
38
+ schemas: Map<string, SchemaOwner>
39
+ migrations: Migration[]
40
+ problems: string[]
41
+ }
42
+
43
+ export const internalOf = (module: Module): string => schemaName(module.name)
44
+ export const apiOf = (module: Module): string => `${schemaName(module.name)}${API_SUFFIX}`
45
+ /** 模块的运行角色:配置的模板里的 <module> 换成模块的内部 schema 名。 */
46
+ export const runtimeOf = (module: Module, template: string): string => template.replace(MODULE_PLACEHOLDER, internalOf(module))
47
+
48
+ /** 这个 schema 归谁的说法,比如 orders 模块的内部 schema。 */
49
+ export function schemaLabel(schema: string, owner: SchemaOwner): string {
50
+ if (owner.kind === 'shared') return `共享层的 schema ${schema}`
51
+ return `${owner.module.id} 模块的${owner.kind === 'internal' ? '内部' : '入口'} schema ${schema}`
52
+ }
53
+
54
+ const TIMESTAMP = /^(\d{14})(?!\d)/
55
+
56
+ /** 写了 database 的应用各一个库:schema 和迁移文件,以及配置错误(schema 名撞了、迁移文件名不对、时间戳重复)。 */
57
+ export function databasesOf(apps: readonly App[], modules: readonly Module[], files: readonly string[]): Database[] {
58
+ return apps.flatMap(app => {
59
+ const config = app.database
60
+ if (!config) return []
61
+ const own = modules.filter(module => module.app === app.name)
62
+ const problems: string[] = []
63
+ const where = app.name === undefined ? '' : `${app.name} 应用的`
64
+ const schemas = new Map<string, SchemaOwner>([[SHARED_SCHEMA, { kind: 'shared' }]])
65
+ for (const module of own) {
66
+ const internal = internalOf(module)
67
+ if (!PLAIN_NAME.test(internal)) {
68
+ problems.push(`${where}模块 ${module.dir} 的目录名转不成 schema 名(转出来是 "${internal}",只能有字母、数字和下划线,不以数字开头):给模块目录改个名字`)
69
+ continue
70
+ }
71
+ const owners: Array<[string, SchemaOwner & { module: Module }]> = [
72
+ [internal, { kind: 'internal', module }],
73
+ [apiOf(module), { kind: 'api', module }],
74
+ ]
75
+ for (const [schema, owner] of owners) {
76
+ const taken = schemas.get(schema)
77
+ const reserved = schema === PUBLIC_SCHEMA || schema === 'information_schema' || schema.startsWith('pg_')
78
+ if (taken || reserved) {
79
+ const other = taken ? schemaLabel(schema, taken) : 'Postgres 保留的 schema'
80
+ problems.push(`${where}${module.id} 模块的${owner.kind === 'internal' ? '内部' : '入口'} schema 叫 ${schema},和 ${other} 撞了:给模块目录改个名字`)
81
+ } else schemas.set(schema, owner)
82
+ }
83
+ }
84
+
85
+ // 模块的角色和内部 schema 同名,共享层的角色叫 shared
86
+ for (const key of ['login', 'migrator'] as const) {
87
+ const owner = schemas.get(config[key])
88
+ if (owner && owner.kind !== 'api') {
89
+ const role = owner.kind === 'shared' ? '共享层的角色' : `${owner.module.id} 模块的角色`
90
+ problems.push(`${where}database.${key} 的账号 ${config[key]} 和${role}同名:登录、迁移账号本身没有权限,只能切成模块的角色,换个名字`)
91
+ }
92
+ }
93
+ if (config.runtime !== undefined) {
94
+ for (const module of own) {
95
+ const runtime = runtimeOf(module, config.runtime)
96
+ const owner = schemas.get(runtime)
97
+ const clash =
98
+ owner && owner.kind !== 'api' ? (owner.kind === 'shared' ? '共享层的角色' : `${owner.module.id} 模块的角色`)
99
+ : runtime === config.login ? '程序的登录账号(database.login)'
100
+ : runtime === config.migrator ? '跑迁移的账号(database.migrator)'
101
+ : undefined
102
+ if (clash) problems.push(`${where}${module.id} 模块的运行角色 ${runtime}(database.runtime 是 ${config.runtime})和${clash}同名:运行角色只有本模块的读写授权,换个模板`)
103
+ }
104
+ }
105
+
106
+ const migrations: Migration[] = []
107
+ const inDir = (dir: string): string[] => files.filter(path => path.startsWith(`${dir}/`) && !path.slice(dir.length + 1).includes('/') && path.endsWith('.sql'))
108
+ for (const path of inDir(config.shared)) migrations.push({ path })
109
+ for (const module of own) for (const path of inDir(`${module.dir}/${config.migrations}`)) migrations.push({ path, module })
110
+
111
+ migrations.sort((a, b) => a.path.localeCompare(b.path))
112
+ const stamps = new Map<string, string>()
113
+ for (const { path } of migrations) {
114
+ const file = path.slice(path.lastIndexOf('/') + 1)
115
+ const stamp = TIMESTAMP.exec(file)?.[1]
116
+ if (stamp === undefined) {
117
+ problems.push(`迁移文件 ${path} 的文件名要以精确到秒的时间戳开头(14 位数字,比如 20261118093000_create_orders.sql):迁移按时间戳统一排序执行`)
118
+ continue
119
+ }
120
+ const other = stamps.get(stamp)
121
+ if (other) problems.push(`迁移的时间戳重复:${other} 和 ${path} 都是 ${stamp}(各模块和共享层的迁移按时间戳统一排序执行),改成不同的时间。迁移只写正向,一个时间戳一个文件:不写回滚迁移(.down.sql 这类),按文件名排序执行的工具会把它当正向迁移跑`)
122
+ else stamps.set(stamp, path)
123
+ }
124
+ return [{ app, schemas, migrations, problems }]
125
+ })
126
+ }
127
+
128
+ /** 迁移目录以外的 .sql(应用自己的查询等):在用库的应用的模块、共享层、装配层里,R6 不读。owner:按路径看文件归谁。 */
129
+ export function unreadSql(databases: readonly Database[], files: readonly string[], owner: (path: string) => { kind: string; app?: string }): string[] {
130
+ const migrations = new Set(databases.flatMap(database => database.migrations.map(migration => migration.path)))
131
+ return files.filter(path => {
132
+ if (!path.endsWith('.sql') || migrations.has(path)) return false
133
+ const at = owner(path)
134
+ return (at.kind === 'module' || at.kind === 'shared' || at.kind === 'app') && databases.some(database => database.app.name === at.app)
135
+ })
136
+ }