gatelight 0.19.2 → 0.39.1
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.
- package/.antigravity-plugin/plugin.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/README.md +2 -2
- package/package.json +1 -1
- package/skills/merge/SKILL.md +1 -1
- package/skills/modular/SKILL.md +6 -6
- package/skills/setup/SKILL.md +2 -2
- package/skills/setup-codekeep/SKILL.md +61 -17
- package/skills/setup-codekeep/frontend.eslint.mjs +285 -0
- package/skills/setup-modwall/SKILL.md +10 -11
- package/skills/setup-testcraft/SKILL.md +9 -3
- package/skills/setup-testcraft/checklist/dev-login.md +3 -3
- package/skills/setup-testcraft/checklist/same-number.md +26 -0
- package/skills/write-tests/SKILL.md +13 -12
- package/src/base/baseline.ts +2 -2
- package/src/base/commands.ts +2 -40
- package/src/base/execute.ts +1 -11
- package/src/base/exit.ts +1 -1
- package/src/base/full.ts +15 -11
- package/src/base/git.ts +34 -3
- package/src/base/hook.ts +71 -17
- package/src/base/hookformat.ts +16 -6
- package/src/base/module.ts +9 -7
- package/src/base/repo.ts +8 -34
- package/src/base/sessions.ts +45 -13
- package/src/base/shell.ts +18 -10
- package/src/base/stop.ts +20 -6
- package/src/base/store.ts +15 -30
- package/src/cli.ts +3 -16
- package/src/craft/commands.ts +7 -1
- package/src/craft/defaults.ts +59 -0
- package/src/craft/session.ts +8 -4
- package/src/keep/check.ts +78 -39
- package/src/keep/config.ts +56 -26
- package/src/keep/eslint.ts +130 -5
- package/src/keep/loosen.ts +11 -61
- package/src/keep/session.ts +19 -5
- package/src/keep/styles.ts +72 -0
- package/src/pace/commands.ts +9 -3
- package/src/pace/full.ts +16 -6
- package/src/pace/index.ts +3 -0
- package/src/pace/record.ts +12 -6
- package/src/pace/results.ts +43 -2
- package/src/pace/run/playwright-reporter.mjs +5 -4
- package/src/pace/run/runner.ts +13 -7
- package/src/pace/run/targets.ts +3 -2
- package/src/pace/session.ts +3 -3
- package/src/pace/unfinished.ts +87 -0
- package/src/pace/unmerged.ts +87 -0
- package/src/pace/verify.ts +2 -2
- package/src/wall/commands.ts +94 -26
- package/src/wall/database.ts +12 -1
- package/src/wall/dbcheck.ts +2 -2
- package/src/wall/dbrules.ts +60 -19
- package/src/wall/full.ts +6 -1
- package/src/wall/literals.ts +162 -0
- package/src/wall/migrate.ts +248 -0
- package/src/wall/project.ts +29 -9
- package/src/wall/receipt.ts +74 -0
- package/src/wall/session.ts +5 -5
- package/src/wall/store.ts +3 -1
package/src/wall/commands.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// modwall 的命令:init、check、db check、status。命令入口(src/modwall.ts)分发到这里。
|
|
1
|
+
// modwall 的命令:init、check、migrate、db bootstrap、db check、status。命令入口(src/modwall.ts)分发到这里。
|
|
2
2
|
// 找仓库、存记录、让用户确认、调 LayerMap 都用底座的;合并前的检查(check)是整组里的一段(见 full.ts),不用另外登记。
|
|
3
3
|
|
|
4
4
|
import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
|
|
@@ -11,11 +11,14 @@ import { LAYERMAP_COMMAND, LAYERMAP_MINIMUM, layermapVersion } from '../base/lay
|
|
|
11
11
|
import { openRepo, type Repo } from '../base/repo.ts'
|
|
12
12
|
import { analyze, exitCode, formatReport, logCheck, prepare, type Report, violationLines } from './check.ts'
|
|
13
13
|
import { CONFIG_PATH, MODWALL_DIR, schemeOf } from './config.ts'
|
|
14
|
+
import type { Database } from './database.ts'
|
|
14
15
|
import { catalogViolations, readCatalog } from './dbcheck.ts'
|
|
16
|
+
import { bootstrapScript, fileReader, migrateScript, runScript } from './migrate.ts'
|
|
17
|
+
import { leaveReceipt } from './receipt.ts'
|
|
15
18
|
import { draftConfig } from './init.ts'
|
|
16
19
|
import type { Module } from './layout.ts'
|
|
17
20
|
import { configText } from './loosen.ts'
|
|
18
|
-
import { contentKey, currentKey, layoutOf, openProject, type Project } from './project.ts'
|
|
21
|
+
import { checkPassed, contentKey, currentKey, layoutOf, openProject, passRecord, type Project } from './project.ts'
|
|
19
22
|
import { BLOCKING_RULES, unownedFiles } from './rules.ts'
|
|
20
23
|
import { openStore, type Store } from './store.ts'
|
|
21
24
|
|
|
@@ -23,10 +26,15 @@ const USAGE = `用法:
|
|
|
23
26
|
modwall init 按现有目录生成配置草稿(${CONFIG_PATH})
|
|
24
27
|
modwall check 检查整个项目:R1–R5、R6 里迁移文件那部分、放宽项是否经用户同意;通过时记一条通过记录。
|
|
25
28
|
接入了的仓库,testpace full 里自动跑它
|
|
29
|
+
modwall db bootstrap --psql "<执行 SQL 的命令>" | --print [--app <应用名>]
|
|
30
|
+
建库那一步:建程序的登录账号和跑迁移的账号,库只让这两个连(不设密码)。用超级用户连库
|
|
31
|
+
modwall migrate --psql "<执行 SQL 的命令>" | --print [--app <应用名>]
|
|
32
|
+
建各模块和共享层的角色、schema、权限,按时间戳跑还没跑过的迁移。用跑迁移的账号连库;
|
|
33
|
+
--print 只输出脚本(打包上线用,线上只用 psql 跑它)
|
|
26
34
|
modwall db check --psql "<执行 SQL 的命令>" [--app <应用名>]
|
|
27
|
-
查库里的现状(R6
|
|
28
|
-
--psql
|
|
29
|
-
|
|
35
|
+
查库里的现状(R6 里库的那部分),迁移跑完之后执行,用哪个账号连都行;
|
|
36
|
+
SQL 从标准输入交给 --psql 的命令,比如 --psql "psql \$DATABASE_URL"、
|
|
37
|
+
--psql "napbox exec postgres --temp \$ENV -- psql";几个应用都写了 database 时用 --app 指定哪个应用的库
|
|
30
38
|
modwall status 越界、例外和确认情况,LayerMap 和 testpace 有没有接上`
|
|
31
39
|
|
|
32
40
|
/** 退出码用底座的:0 通过;1 没通过;2 用法、配置或环境问题。 */
|
|
@@ -94,46 +102,62 @@ function check(): number {
|
|
|
94
102
|
const code = exitCode(report)
|
|
95
103
|
if (code !== EXIT.ok) return code
|
|
96
104
|
// 结论是按开始时的内容得出的:检查的过程中内容改过,这次不记、不算
|
|
97
|
-
if (!store.passes.saveChecked(key, () => currentKey(project.root) ?? '',
|
|
105
|
+
if (!store.passes.saveChecked(key, () => currentKey(project.root) ?? '', passRecord(project))) {
|
|
98
106
|
console.log('\n检查过程中内容改过(检查是按开始时的样子做的),这次的结论不算:代码不再改动时重跑 modwall check。')
|
|
99
107
|
return EXIT.fail
|
|
100
108
|
}
|
|
101
109
|
return EXIT.ok
|
|
102
110
|
}
|
|
103
111
|
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
112
|
+
interface DbArgs {
|
|
113
|
+
psql?: string
|
|
114
|
+
print: boolean
|
|
115
|
+
app?: string
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function dbArgs(command: string, args: string[], printable: boolean): DbArgs | undefined {
|
|
119
|
+
const parsed: DbArgs = { print: false }
|
|
108
120
|
for (let i = 0; i < args.length; i++) {
|
|
109
121
|
const arg = args[i]
|
|
110
122
|
if ((arg === '--psql' || arg === '--app') && args[i + 1] !== undefined) {
|
|
111
|
-
if (arg === '--psql') psql = args[++i]
|
|
112
|
-
else
|
|
113
|
-
} else
|
|
123
|
+
if (arg === '--psql') parsed.psql = args[++i]
|
|
124
|
+
else parsed.app = args[++i]
|
|
125
|
+
} else if (arg === '--print' && printable) parsed.print = true
|
|
126
|
+
else {
|
|
114
127
|
console.error(`不认识的参数:${arg}\n${USAGE}`)
|
|
115
|
-
return
|
|
128
|
+
return undefined
|
|
116
129
|
}
|
|
117
130
|
}
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
131
|
+
const psql = parsed.psql?.trim()
|
|
132
|
+
if (parsed.print && psql) {
|
|
133
|
+
console.error(`${command}:--psql 和 --print 只用一个。\n${USAGE}`)
|
|
134
|
+
return undefined
|
|
135
|
+
}
|
|
136
|
+
if (!parsed.print && !psql) {
|
|
137
|
+
const or = printable ? ',或者用 --print 只输出脚本' : ''
|
|
138
|
+
console.error(`${command} 要用 --psql 告诉它用什么命令执行 SQL(比如 --psql "psql \$DATABASE_URL")${or}。\n${USAGE}`)
|
|
139
|
+
return undefined
|
|
121
140
|
}
|
|
141
|
+
return parsed
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** 按 --app 找要用的库:只有一个写了 database 的应用时不用写。 */
|
|
145
|
+
function databaseOf(command: string, appName: string | undefined): { project: Project; database: Database } | number {
|
|
122
146
|
const opened = open()
|
|
123
147
|
if (typeof opened === 'number') return opened
|
|
124
148
|
const { project } = opened
|
|
125
149
|
const prepared = prepare(project)
|
|
126
150
|
if ('problems' in prepared) {
|
|
127
|
-
console.error(
|
|
151
|
+
console.error(`${command}:配置有问题(${CONFIG_PATH}),先改好:\n${prepared.problems.map(text => ` ✗ ${text}`).join('\n')}`)
|
|
128
152
|
return EXIT.usage
|
|
129
153
|
}
|
|
130
154
|
if ('removed' in prepared) {
|
|
131
|
-
console.error(
|
|
155
|
+
console.error(`${command}:工作区里没有 ${CONFIG_PATH},不知道模块怎么分。`)
|
|
132
156
|
return EXIT.usage
|
|
133
157
|
}
|
|
134
158
|
const { databases } = prepared.layout
|
|
135
159
|
if (databases.length === 0) {
|
|
136
|
-
console.error(
|
|
160
|
+
console.error(`${command}:${CONFIG_PATH} 里没有写 database(用 Postgres 的应用写 "database": { "migrations": …, "shared": … })。`)
|
|
137
161
|
return EXIT.usage
|
|
138
162
|
}
|
|
139
163
|
const named = databases.map(database => database.app.name)
|
|
@@ -141,11 +165,48 @@ function dbCheck(args: string[]): number {
|
|
|
141
165
|
if (!database) {
|
|
142
166
|
console.error(
|
|
143
167
|
appName === undefined
|
|
144
|
-
?
|
|
145
|
-
:
|
|
168
|
+
? `${command}:${named.join('、')} 几个应用都写了 database,用 --app 指定哪个应用的库。`
|
|
169
|
+
: `${command}:没有写了 database 的应用叫 ${appName}(写了的有:${named.filter(Boolean).join('、') || '单应用的写法,不用 --app'})。`,
|
|
146
170
|
)
|
|
147
171
|
return EXIT.usage
|
|
148
172
|
}
|
|
173
|
+
return { project, database }
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** modwall migrate、modwall db bootstrap:生成脚本,--print 输出,--psql 交给命令执行。脚本出错(psql 的退出码 3)算没通过,别的算没跑成。 */
|
|
177
|
+
function runDbScript(command: string, args: string[], script: (project: Project, database: Database) => string): number {
|
|
178
|
+
const parsed = dbArgs(command, args, true)
|
|
179
|
+
if (!parsed) return EXIT.usage
|
|
180
|
+
const found = databaseOf(command, parsed.app)
|
|
181
|
+
if (typeof found === 'number') return found
|
|
182
|
+
const { project, database } = found
|
|
183
|
+
const text = script(project, database)
|
|
184
|
+
if (parsed.print) {
|
|
185
|
+
process.stdout.write(text)
|
|
186
|
+
return EXIT.ok
|
|
187
|
+
}
|
|
188
|
+
const r = runScript(project.root, parsed.psql as string, text)
|
|
189
|
+
if (r.error !== undefined) {
|
|
190
|
+
console.error(`${command}:执行 SQL 的命令没跑起来(${parsed.psql}):${r.error}`)
|
|
191
|
+
return EXIT.usage
|
|
192
|
+
}
|
|
193
|
+
if (r.status === 0) return EXIT.ok
|
|
194
|
+
if (r.status === 3) {
|
|
195
|
+
console.error(`${command}:没做完,出错的那一步整步回滚了(错误见上面)。`)
|
|
196
|
+
return EXIT.fail
|
|
197
|
+
}
|
|
198
|
+
console.error(`${command}:执行 SQL 的命令失败(退出码 ${r.status},命令:${parsed.psql}):它要把标准输入的 SQL 交给 psql 执行。`)
|
|
199
|
+
return EXIT.usage
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** modwall db check --psql "<命令>" [--app <应用名>]:不通过时退出码 1,没查成是 2。 */
|
|
203
|
+
function dbCheck(args: string[]): number {
|
|
204
|
+
const parsed = dbArgs('modwall db check', args, false)
|
|
205
|
+
if (!parsed) return EXIT.usage
|
|
206
|
+
const psql = parsed.psql as string
|
|
207
|
+
const found = databaseOf('modwall db check', parsed.app)
|
|
208
|
+
if (typeof found === 'number') return found
|
|
209
|
+
const { project, database } = found
|
|
149
210
|
const catalog = readCatalog(project.root, psql)
|
|
150
211
|
if (!catalog.ok) {
|
|
151
212
|
console.error(`modwall db check:没查成,${catalog.problem}`)
|
|
@@ -153,11 +214,12 @@ function dbCheck(args: string[]): number {
|
|
|
153
214
|
}
|
|
154
215
|
const violations = catalogViolations(database, catalog.value)
|
|
155
216
|
const which = database.app.name === undefined ? '' : `(${database.app.name} 应用的库)`
|
|
217
|
+
leaveReceipt(database.app.name, violations.length === 0)
|
|
156
218
|
if (violations.length === 0) {
|
|
157
219
|
console.log(`modwall db check:通过${which}。库里没有越界。`)
|
|
158
220
|
return EXIT.ok
|
|
159
221
|
}
|
|
160
|
-
console.log([`modwall db check:没通过${which}。`, '', `库里越界 ${violations.length}
|
|
222
|
+
console.log([`modwall db check:没通过${which}。`, '', `库里越界 ${violations.length} 处(改迁移,或用 modwall db bootstrap、modwall migrate 重建;不要直接改库):`, ...violationLines(violations)].join('\n'))
|
|
161
223
|
return EXIT.fail
|
|
162
224
|
}
|
|
163
225
|
|
|
@@ -193,7 +255,7 @@ function status(): number {
|
|
|
193
255
|
else if (report.changesProblem) lines.push(`越界:${counts.join('、')};R4 和入口新增导出没查(这次改动增删的关系没读到)`)
|
|
194
256
|
else lines.push(`越界:${counts.join('、')};R4 提示 ${report.behavior.length}(详情跑 modwall check)`)
|
|
195
257
|
}
|
|
196
|
-
lines.push(`通过记录:${
|
|
258
|
+
lines.push(`通过记录:${checkPassed(project, store) ? '当前内容 modwall check 通过过' : '当前内容还没有通过记录(modwall check)'}`)
|
|
197
259
|
const version = layermapVersion()
|
|
198
260
|
lines.push(
|
|
199
261
|
version
|
|
@@ -239,7 +301,7 @@ function testpaceStatus(project: Project, hasDatabase: boolean): string[] {
|
|
|
239
301
|
/**
|
|
240
302
|
* 在 agent 的沙箱里跑不了的子命令和它要做的事(见 base/commandline.ts)。
|
|
241
303
|
* check、status 要 LayerMap 的地图:它存在项目外面,沙箱里更新不了,R1–R4 查不成,check 会给出假的"没通过"。
|
|
242
|
-
* db check
|
|
304
|
+
* db check、db bootstrap、migrate 跑的是项目给的命令,要连数据库(--print 只输出脚本,不连)。init 只读写项目里的文件,不在里面。
|
|
243
305
|
*/
|
|
244
306
|
export function outside(argv: string[]): string | undefined {
|
|
245
307
|
switch (argv[0]) {
|
|
@@ -247,8 +309,11 @@ export function outside(argv: string[]): string | undefined {
|
|
|
247
309
|
return '让 LayerMap 更新它的地图(存在项目外面)、写 .git/testpace/ 的记录'
|
|
248
310
|
case 'status':
|
|
249
311
|
return '让 LayerMap 更新它的地图(存在项目外面)'
|
|
312
|
+
case 'migrate':
|
|
313
|
+
return argv.includes('--print') ? undefined : '跑 --psql 给的命令连数据库、改库'
|
|
250
314
|
case 'db':
|
|
251
|
-
|
|
315
|
+
if (argv[1] === 'check') return '跑 --psql 给的命令连数据库'
|
|
316
|
+
return argv[1] === 'bootstrap' && !argv.includes('--print') ? '跑 --psql 给的命令连数据库、建账号' : undefined
|
|
252
317
|
default:
|
|
253
318
|
return undefined
|
|
254
319
|
}
|
|
@@ -260,8 +325,11 @@ export function main(argv: string[]): number {
|
|
|
260
325
|
return init()
|
|
261
326
|
case 'check':
|
|
262
327
|
return check()
|
|
328
|
+
case 'migrate':
|
|
329
|
+
return runDbScript('modwall migrate', argv.slice(1), (project, database) => migrateScript(database, fileReader(project.root)))
|
|
263
330
|
case 'db':
|
|
264
331
|
if (argv[1] === 'check') return dbCheck(argv.slice(2))
|
|
332
|
+
if (argv[1] === 'bootstrap') return runDbScript('modwall db bootstrap', argv.slice(2), (_, database) => bootstrapScript(database))
|
|
265
333
|
console.error(`不认识的命令:db ${argv[1] ?? ''}\n${USAGE}`)
|
|
266
334
|
return EXIT.usage
|
|
267
335
|
case 'status':
|
package/src/wall/database.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
//
|
|
1
|
+
// 数据库按模块分:位置就是归属,不另外登记。
|
|
2
2
|
// 每个模块两个 schema:内部(模块目录名转成小写加下划线,adminAccess → admin_access)和入口(<内部>_api,只放视图和函数);
|
|
3
3
|
// 共享层用 shared;public 里不放对象(扩展自带的除外)。
|
|
4
4
|
// 每个模块一个角色,名字就是它的内部 schema 名;共享层的角色叫 shared。程序的登录账号、跑迁移的账号不能和它们同名。
|
|
5
|
+
// 各模块的组角色叫 <登录账号>_modules,不能和上面这些同名。
|
|
5
6
|
// 配置写了运行角色模板(database.runtime)的,每个模块还有一个运行角色(模板里的 <module> 换成内部 schema 名),不能和上面这些角色、账号同名。
|
|
6
7
|
// 迁移放在每个模块目录下的 database.migrations 子目录、共享层的 database.shared 目录,文件名以 14 位的时间戳开头,不能重复(迁移只写正向,一个时间戳一个文件)。
|
|
7
8
|
// 这里只管划分:每个应用的库有哪些 schema、各归谁,迁移文件各归谁,以及这些算出来的配置错误。只看路径,layout.ts 用它。
|
|
@@ -44,6 +45,8 @@ export const internalOf = (module: Module): string => schemaName(module.name)
|
|
|
44
45
|
export const apiOf = (module: Module): string => `${schemaName(module.name)}${API_SUFFIX}`
|
|
45
46
|
/** 模块的运行角色:配置的模板里的 <module> 换成模块的内部 schema 名。 */
|
|
46
47
|
export const runtimeOf = (module: Module, template: string): string => template.replace(MODULE_PLACEHOLDER, internalOf(module))
|
|
48
|
+
/** 各模块(和运行角色)的组角色:入口 schema、shared 的使用权授给它。按登录账号起名:角色整个实例共用,各项目各用各的。 */
|
|
49
|
+
export const groupOf = (login: string): string => `${login}_modules`
|
|
47
50
|
|
|
48
51
|
/** 这个 schema 归谁的说法,比如 orders 模块的内部 schema。 */
|
|
49
52
|
export function schemaLabel(schema: string, owner: SchemaOwner): string {
|
|
@@ -102,6 +105,14 @@ export function databasesOf(apps: readonly App[], modules: readonly Module[], fi
|
|
|
102
105
|
if (clash) problems.push(`${where}${module.id} 模块的运行角色 ${runtime}(database.runtime 是 ${config.runtime})和${clash}同名:运行角色只有本模块的读写授权,换个模板`)
|
|
103
106
|
}
|
|
104
107
|
}
|
|
108
|
+
const group = groupOf(config.login)
|
|
109
|
+
const groupOwner = schemas.get(group)
|
|
110
|
+
const groupClash =
|
|
111
|
+
groupOwner && groupOwner.kind !== 'api' ? (groupOwner.kind === 'shared' ? '共享层的角色' : `${groupOwner.module.id} 模块的角色`)
|
|
112
|
+
: group === config.migrator ? '跑迁移的账号(database.migrator)'
|
|
113
|
+
: config.runtime !== undefined && own.some(module => runtimeOf(module, config.runtime as string) === group) ? '一个模块的运行角色'
|
|
114
|
+
: undefined
|
|
115
|
+
if (groupClash) problems.push(`${where}各模块的组角色 ${group}(按 database.login 起名)和${groupClash}同名:换个登录账号名或模块名`)
|
|
105
116
|
|
|
106
117
|
const migrations: Migration[] = []
|
|
107
118
|
const inDir = (dir: string): string[] => files.filter(path => path.startsWith(`${dir}/`) && !path.slice(dir.length + 1).includes('/') && path.endsWith('.sql'))
|
package/src/wall/dbcheck.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
// modwall db check:R6
|
|
1
|
+
// modwall db check:R6 里库的那部分,查迁移跑完之后库里的现状。
|
|
2
2
|
// 不连数据库、不装客户端库:把查系统目录的 SQL 从标准输入交给项目给的命令(psql $DATABASE_URL、napbox exec postgres -- psql),
|
|
3
3
|
// 读它输出的一行 JSON 再比对。查的是:
|
|
4
4
|
// 不对应任何模块的 schema;public 里的对象;入口 schema 里的表;跨模块的外键;函数的 search_path;
|
|
5
5
|
// 视图、函数跨模块引用内部 schema(视图和 BEGIN ATOMIC 的函数看 pg_depend,plpgsql 和 AS $$…$$ 的 sql 函数读正文);
|
|
6
6
|
// 视图、BEGIN ATOMIC 的函数硬依赖在别的模块入口里的视图、函数上(pg_depend 里有记录;用对方入口里的类型可以);函数正文直接写别的模块入口里的视图。
|
|
7
|
-
//
|
|
7
|
+
// 按模块的数据库角色:
|
|
8
8
|
// 每个模块有同名的角色,共享层有 shared 角色:不能登录、不是超级用户、不能绕过行级权限、不能建角色和库,不能在 public 里建对象、不能在库里建 schema;
|
|
9
9
|
// 模块两个 schema 和里面的对象归模块的角色,shared 的归 shared 角色;除了超级用户和 schema 的主人,没有角色(包括经继承)能用模块的内部 schema、
|
|
10
10
|
// 能在模块的两个 schema 和 shared 里建对象;函数都是 SECURITY DEFINER(函数里也就切不了身份),入口视图没有设 security_invoker;
|
package/src/wall/dbrules.ts
CHANGED
|
@@ -3,14 +3,15 @@
|
|
|
3
3
|
// 视图建在别的模块的入口上;直接写别的模块入口里的视图;在自己以外的 schema 里建、改、删对象(共享层也不建、删模块的);入口 schema 里建表;
|
|
4
4
|
// 函数没把 search_path 设成本模块的内部 schema 加 pg_temp、不是 SECURITY DEFINER;迁移、函数里改 search_path;迁移里切身份、建 schema;
|
|
5
5
|
// 别名、没起别名的表名和模块的 schema 同名(检查按名字认 schema,同名的会被当成跨模块引用)。
|
|
6
|
-
//
|
|
6
|
+
// 模块的代码里切身份(代码里字符串字面量写的整句 SQL)也在这里:应用代码里只有装配层和共享层可以切。
|
|
7
7
|
// 函数里切身份不用查文字:函数一律 SECURITY DEFINER,Postgres 不让 SECURITY DEFINER 的函数切身份。
|
|
8
8
|
|
|
9
9
|
import { apiOf, type Database, internalOf, SHARED_SCHEMA, type SchemaOwner, schemaLabel } from './database.ts'
|
|
10
10
|
import { isCode } from './files.ts'
|
|
11
11
|
import { label, type Module, type Owner } from './layout.ts'
|
|
12
|
+
import { type Literal, PLACEHOLDER, stringLiterals } from './literals.ts'
|
|
12
13
|
import type { Edge, Violation } from './rules.ts'
|
|
13
|
-
import { type Statement, statements } from './sql.ts'
|
|
14
|
+
import { type Statement, statements, type Token, tokenize } from './sql.ts'
|
|
14
15
|
|
|
15
16
|
/** 引用的 schema 怎么判:from 是写它的模块(undefined 是共享层)。 */
|
|
16
17
|
export type Crossing =
|
|
@@ -68,35 +69,35 @@ export const FIXES = {
|
|
|
68
69
|
foreignKey: (module: string) => `模块之间不建外键:只存 ${module} 的 id,存在性和删除规则由应用经 ${module} 的入口保证(删除一般改成软删除)。`,
|
|
69
70
|
searchPath: (expected: string) =>
|
|
70
71
|
`函数一律带 SET search_path = ${expected}:不写全名的就是本模块的对象,引用别的模块、shared 要写带 schema 的全名;pg_temp 放最后,别人建的同名临时表才骗不了以提供方身份执行的函数。`,
|
|
71
|
-
setsSearchPath: '迁移和函数里不改 search_path
|
|
72
|
+
setsSearchPath: '迁移和函数里不改 search_path:modwall migrate 已经把它设成本模块的内部 schema,函数用自己的 SET search_path。要用别的 schema 的对象,写带 schema 的全名。',
|
|
72
73
|
switchesRole:
|
|
73
|
-
"迁移里不切身份(SET ROLE、RESET ROLE、SET SESSION AUTHORIZATION、set_config('role', …),在角色、库上设 role
|
|
74
|
-
createsSchema: '迁移里不建 schema
|
|
74
|
+
"迁移里不切身份(SET ROLE、RESET ROLE、SET SESSION AUTHORIZATION、set_config('role', …),在角色、库上设 role 也算):modwall migrate 已经切成本模块的角色。要别的模块做事,在它的迁移里做,或者调用它入口里的函数(以它的角色执行)。",
|
|
75
|
+
createsSchema: '迁移里不建 schema:modwall migrate 按模块目录建好模块的角色和两个 schema(共享层的 shared 也由它建),迁移只在里面建对象。删掉这句。',
|
|
75
76
|
codeSwitchesRole:
|
|
76
|
-
"
|
|
77
|
+
"模块的代码不自己切身份:连接在事务开头由装配层或共享层里那个切身份的小函数切成本模块的角色。要别的模块的数据,经它的代码入口或数据库入口。",
|
|
77
78
|
missingRole: (role: string) =>
|
|
78
|
-
|
|
79
|
+
`模块的角色 ${role} 和它的两个 schema(共享层是 shared 角色和 shared schema)由 modwall migrate 按模块目录建:用迁移账号跑一次 modwall migrate。`,
|
|
79
80
|
roleAttributes: (role: string) =>
|
|
80
81
|
`模块和共享层的角色只用来切身份,本身不能登录、没有特权:ALTER ROLE ${role} NOLOGIN NOSUPERUSER NOBYPASSRLS NOCREATEROLE NOCREATEDB;能在库里建 schema 的,REVOKE CREATE ON DATABASE … FROM ${role}(授给 PUBLIC 的也要收回)。`,
|
|
81
82
|
runtimeRole: (role: string, owner: string) =>
|
|
82
83
|
`运行角色只用来跑模块的代码:本身没有特权,只有本模块内部 schema 的使用权和表上的读写授权(SELECT、INSERT、UPDATE、DELETE),不拥有对象、不能建对象,建表、改表结构归模块的角色 ${owner},在迁移里做:ALTER ROLE ${role} NOSUPERUSER NOCREATEROLE NOCREATEDB;能在库里、public 里建对象的,REVOKE CREATE ON DATABASE … FROM ${role}、REVOKE CREATE ON SCHEMA public FROM ${role}(授给 PUBLIC 的也收回);它拥有的对象用 ALTER … OWNER TO ${owner} 改归模块的角色。`,
|
|
83
84
|
runtimeCreate: (schema: string, role: string, owner: string) =>
|
|
84
85
|
`运行角色不建对象,建表、改表结构归模块的角色 ${owner},在迁移里做:REVOKE CREATE ON SCHEMA ${schema} FROM ${role}(授给 PUBLIC 的也收回);是 ${role} 经成员关系从 ${owner} 继承来的,把成员关系去掉,只授本模块表上的读写。`,
|
|
85
|
-
publicCreate: 'public 里不放对象:REVOKE CREATE ON SCHEMA public FROM PUBLIC(
|
|
86
|
+
publicCreate: 'public 里不放对象:REVOKE CREATE ON SCHEMA public FROM PUBLIC(modwall db bootstrap 会收回),授给这个角色的也收回。',
|
|
86
87
|
owner: (role: string) =>
|
|
87
|
-
`模块的两个 schema 和里面的对象归模块的角色,shared 的归 shared 角色:迁移切成这个角色执行,建出来的就归它;已有的用 ALTER … OWNER TO ${role}
|
|
88
|
+
`模块的两个 schema 和里面的对象归模块的角色,shared 的归 shared 角色:迁移切成这个角色执行,建出来的就归它;已有的用 ALTER … OWNER TO ${role} 改,再查迁移是不是用 modwall migrate 跑的。`,
|
|
88
89
|
createPrivilege: (schema: string, owner: string, role: string) =>
|
|
89
90
|
`只有 ${owner} 能在 ${schema} 里建对象,别的模块要什么让它在自己的迁移里加:REVOKE CREATE ON SCHEMA ${schema} FROM ${role}(授给 PUBLIC 的也收回);是经成员关系继承来的,把成员关系设成不继承或去掉。`,
|
|
90
91
|
internalPrivilege: (schema: string, role: string) =>
|
|
91
|
-
`内部 schema 只有模块自己能用,别的模块经入口:REVOKE ALL ON SCHEMA ${schema} FROM ${role}(授给 PUBLIC 的也收回);是 ${role} 经成员关系继承来的(比如登录账号),把成员关系设成不继承(
|
|
92
|
+
`内部 schema 只有模块自己能用,别的模块经入口:REVOKE ALL ON SCHEMA ${schema} FROM ${role}(授给 PUBLIC 的也收回);是 ${role} 经成员关系继承来的(比如登录账号),把成员关系设成不继承(GRANT … WITH INHERIT FALSE;modwall migrate 加的都不继承)或去掉。`,
|
|
92
93
|
securityDefiner:
|
|
93
94
|
'函数一律 SECURITY DEFINER:以所在模块(共享层)的角色执行,入口函数才碰得到内部的表,函数里也切不了身份(Postgres 不让)。建函数时写上(CREATE OR REPLACE 不写会改回按调用者执行),不用 SECURITY INVOKER;要 COMMIT 的过程拆开或放到应用代码里。',
|
|
94
95
|
securityInvoker: (module: Module) =>
|
|
95
96
|
`入口视图以 ${module.id} 的角色读它内部的表,别的模块的角色用不了 ${internalOf(module)}:去掉 security_invoker(ALTER VIEW … RESET (security_invoker))。`,
|
|
96
97
|
connect: (database: string, accounts: string[]) =>
|
|
97
|
-
`库只让本项目的两个账号连:角色是整个 Postgres
|
|
98
|
+
`库只让本项目的两个账号连:角色是整个 Postgres 实例共用的,同一个实例上别的项目有同名的模块角色时,它的登录账号连进这个库就能切成这个角色、读写这个模块。用超级用户跑一次 modwall db bootstrap,或者手动:REVOKE CONNECT ON DATABASE ${database} FROM PUBLIC;GRANT CONNECT ON DATABASE ${database} TO ${accounts.join(', ')}。`,
|
|
98
99
|
account: (role: string) =>
|
|
99
|
-
|
|
100
|
+
`程序的登录账号、跑迁移的账号要能登录,本身没有权限,只能切成模块的角色:不是超级用户(超级用户不受权限限制,越界查不出来),不拥有任何对象(拥有的对象改归所属模块的角色)。还没有就用超级用户跑一次 modwall db bootstrap 建,modwall migrate 再把它加成各模块角色的成员。`,
|
|
100
101
|
alias: '表、列的别名、CTE 的名字、函数里的变量不能和模块的 schema 同名,否则会被当成跨模块引用:换个名字。',
|
|
101
102
|
bareRelation: (name: string) => `表名 ${name} 和模块的 schema 同名:给它起个别名(FROM … AS 别名),用别名限定列,不用表名,否则 ${name}.列 会被当成跨模块引用。`,
|
|
102
103
|
internal: (module: Module, schema: string) =>
|
|
@@ -189,24 +190,64 @@ export function migrationViolations(databases: readonly Database[], read: (path:
|
|
|
189
190
|
return { violations, edges }
|
|
190
191
|
}
|
|
191
192
|
|
|
192
|
-
|
|
193
|
-
|
|
193
|
+
const word = (token: Token | undefined, ...texts: string[]): boolean => token?.kind === 'word' && !token.quoted && texts.includes(token.text)
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* 代码里一个字符串字面量里切身份的句子(按分号分句)。只认整句:
|
|
197
|
+
* SET [LOCAL|SESSION] ROLE 名字、SET [LOCAL|SESSION] SESSION AUTHORIZATION 名字、RESET ROLE、RESET SESSION AUTHORIZATION,
|
|
198
|
+
* 名字是一个词、带引号的名字或插值,后面不再有别的词;字面量以 ROLE、AUTHORIZATION 收尾又紧跟着 + 的,名字在拼接的后半截,也算。
|
|
199
|
+
* 句子里调用了 set_config('role', …) 的也算。
|
|
200
|
+
*/
|
|
201
|
+
function literalSwitches(literal: Literal): { line: number; text: string }[] {
|
|
202
|
+
const pieces = literal.text.split(';')
|
|
203
|
+
let line = literal.line
|
|
204
|
+
return pieces.flatMap((piece, index) => {
|
|
205
|
+
const start = line
|
|
206
|
+
line += piece.split('\n').length - 1
|
|
207
|
+
const tokens = tokenize(piece, start)
|
|
208
|
+
const found = [{ line: tokens[0]?.line ?? start, text: piece.trim().replace(/\s+/gu, ' ').replaceAll(PLACEHOLDER, '…') }]
|
|
209
|
+
if (tokens.some((token, k) => word(token, 'set_config') && tokens[k + 1]?.text === '(' && tokens[k + 2]?.kind === 'string' && tokens[k + 2]?.text.toLowerCase() === 'role')) return found
|
|
210
|
+
// 'Reset role' 这类首字母大写的是界面文字:SQL 的关键字要么全小写要么全大写
|
|
211
|
+
const lead = /^[A-Za-z]+/u.exec(piece.trimStart())?.[0] ?? ''
|
|
212
|
+
if (lead !== lead.toLowerCase() && lead !== lead.toUpperCase()) return []
|
|
213
|
+
if (word(tokens[0], 'reset')) {
|
|
214
|
+
const tail = tokens.slice(1)
|
|
215
|
+
const switches = (tail.length === 1 && word(tail[0], 'role')) || (tail.length === 2 && word(tail[0], 'session') && word(tail[1], 'authorization'))
|
|
216
|
+
return switches ? found : []
|
|
217
|
+
}
|
|
218
|
+
if (!word(tokens[0], 'set')) return []
|
|
219
|
+
const from = word(tokens[1], 'local') || (word(tokens[1], 'session') && !word(tokens[2], 'authorization')) ? 2 : 1
|
|
220
|
+
let name: Token[]
|
|
221
|
+
if (word(tokens[from], 'role')) name = tokens.slice(from + 1)
|
|
222
|
+
else if (word(tokens[from], 'session') && word(tokens[from + 1], 'authorization')) name = tokens.slice(from + 2)
|
|
223
|
+
else return []
|
|
224
|
+
const named = name.length === 1 && (name[0]?.kind === 'word' || name[0]?.kind === 'string')
|
|
225
|
+
const joined = name.length === 0 && literal.joined && index === pieces.length - 1
|
|
226
|
+
return named || joined ? found : []
|
|
227
|
+
})
|
|
228
|
+
}
|
|
194
229
|
|
|
195
230
|
/**
|
|
196
231
|
* 模块的代码里切身份:用库的应用里,归模块的代码文件和迁移目录以外的 .sql(应用自己的查询),测试文件不算。装配层、共享层可以切(那个切身份的小函数在这里)。
|
|
197
|
-
*
|
|
232
|
+
* 代码文件只看字符串字面量里的整句 SQL(注释、界面文字不算),在别处拼出来的认不出;.sql 按语句查。owner:按路径看文件归谁。read:读仓库里的文件。
|
|
198
233
|
*/
|
|
199
234
|
export function codeRoleSwitches(databases: readonly Database[], files: readonly string[], owner: (path: string) => Owner, read: (path: string) => string): Violation[] {
|
|
200
235
|
const violations: Violation[] = []
|
|
201
236
|
const migrations = new Set(databases.flatMap(database => database.migrations.map(migration => migration.path)))
|
|
202
237
|
for (const path of files) {
|
|
203
|
-
|
|
238
|
+
const sql = path.endsWith('.sql')
|
|
239
|
+
if (!isCode(path) && !(sql && !migrations.has(path))) continue
|
|
204
240
|
const at = owner(path)
|
|
205
241
|
if (at.kind !== 'module' || !databases.some(database => database.app.name === at.app)) continue
|
|
206
242
|
const text = read(path)
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
243
|
+
const found = sql
|
|
244
|
+
? statements(text)
|
|
245
|
+
.filter(statement => statement.switchesRole && !statement.inFunction)
|
|
246
|
+
.map(statement => ({ line: statement.line, text: (text.split('\n')[statement.line - 1] ?? '').trim() }))
|
|
247
|
+
: stringLiterals(path, text).flatMap(literalSwitches)
|
|
248
|
+
for (const item of found) {
|
|
249
|
+
const shown = item.text.length > 80 ? `${item.text.slice(0, 80)}…` : item.text
|
|
250
|
+
violations.push({ rule: 'R6', key: `R6 ${path} 切身份 ${item.line}`, where: [`${path}:${item.line}(${label(at)})切了数据库的身份:${shown}`], fix: FIXES.codeSwitchesRole })
|
|
210
251
|
}
|
|
211
252
|
}
|
|
212
253
|
return violations
|
package/src/wall/full.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// 整组里"模块边界"的部分(base/module.ts 的 fullPart):接入了的仓库在测试之前跑一次 modwall check。
|
|
2
2
|
// 它随插件一起装,不用在本机另外登记;没接入的仓库没有这一段。
|
|
3
|
-
// 库里的现状(modwall db check)不在这一段:要迁移跑完才能查,由项目写在自己的 full
|
|
3
|
+
// 库里的现状(modwall db check)不在这一段:要迁移跑完才能查,由项目写在自己的 full 命令里。整组跑完按它交回的凭据核对跑没跑(receipt.ts)。
|
|
4
4
|
|
|
5
5
|
import { fileURLToPath } from 'node:url'
|
|
6
6
|
import { quoted } from '../base/execute.ts'
|
|
@@ -8,6 +8,7 @@ import { forkPoint } from '../base/git.ts'
|
|
|
8
8
|
import type { FullPart } from '../base/module.ts'
|
|
9
9
|
import type { Repo } from '../base/repo.ts'
|
|
10
10
|
import { joined } from './config.ts'
|
|
11
|
+
import { DB_RECEIPTS_ENV, receiptProblems, receiptsFile } from './receipt.ts'
|
|
11
12
|
|
|
12
13
|
/** 这个插件里的 modwall 命令:用完整路径,不靠 PATH 上碰巧有哪一版。 */
|
|
13
14
|
const BIN = fileURLToPath(new URL('../../bin/modwall', import.meta.url))
|
|
@@ -15,7 +16,11 @@ const BIN = fileURLToPath(new URL('../../bin/modwall', import.meta.url))
|
|
|
15
16
|
export function fullPart(repo: Repo): FullPart {
|
|
16
17
|
// 按分叉点也算接入:删掉 .modwall/ 躲不过检查
|
|
17
18
|
if (!joined(repo.root, forkPoint(repo.root).commit)) return { steps: [] }
|
|
19
|
+
const receipts = receiptsFile()
|
|
18
20
|
return {
|
|
21
|
+
env: { [DB_RECEIPTS_ENV]: receipts.path },
|
|
22
|
+
finish: () => ({ problems: receiptProblems(repo.root, receipts.path) }),
|
|
23
|
+
dispose: () => receipts.dispose(),
|
|
19
24
|
steps: [
|
|
20
25
|
{
|
|
21
26
|
kind: 'wall',
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// 从代码文件(JS/TS、Python、Go、Java)里取出字符串字面量,跳过注释,给 R6 认代码里写的 SQL。
|
|
2
|
+
// 不解析语法,只切词:插值(`${…}`、Python 的 {…}、%s 这类格式占位)换成一个占位的名字。
|
|
3
|
+
// JS 的正则字面量按前一个字符猜(前面是运算符、括号、逗号或行首时算正则),猜错只会让个别字面量切歪。
|
|
4
|
+
|
|
5
|
+
export interface Literal {
|
|
6
|
+
text: string
|
|
7
|
+
line: number
|
|
8
|
+
/** 字面量后面紧跟着 +:拼接,后半截在别处。 */
|
|
9
|
+
joined: boolean
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** 插值、格式占位换成的名字:在 SQL 里当成一个普通的名字。 */
|
|
13
|
+
export const PLACEHOLDER = '__x'
|
|
14
|
+
|
|
15
|
+
type Language = 'js' | 'py' | 'go' | 'java'
|
|
16
|
+
|
|
17
|
+
const languageOf = (path: string): Language | undefined => {
|
|
18
|
+
if (/\.[cm]?[jt]sx?$/u.test(path)) return 'js'
|
|
19
|
+
if (/\.pyi?$/u.test(path)) return 'py'
|
|
20
|
+
if (path.endsWith('.go')) return 'go'
|
|
21
|
+
if (path.endsWith('.java')) return 'java'
|
|
22
|
+
return undefined
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const ESCAPED: Record<string, string> = { n: ' ', t: ' ', r: ' ' }
|
|
26
|
+
|
|
27
|
+
export function stringLiterals(path: string, source: string): Literal[] {
|
|
28
|
+
const language = languageOf(path)
|
|
29
|
+
if (!language) return []
|
|
30
|
+
const found: Literal[] = []
|
|
31
|
+
let i = 0
|
|
32
|
+
let line = 1
|
|
33
|
+
// 上一个不是空白的代码字符:猜 / 是除号还是正则
|
|
34
|
+
let previous = ''
|
|
35
|
+
// JS 模板字符串停在 ${ 里时,先记下已读的部分,插值读完再接着读
|
|
36
|
+
const suspended: { text: string; line: number; depth: number }[] = []
|
|
37
|
+
let depth = 0
|
|
38
|
+
|
|
39
|
+
const finish = (text: string, start: number): void => {
|
|
40
|
+
let k = i
|
|
41
|
+
while (k < source.length && /\s/u.test(source[k] as string)) k++
|
|
42
|
+
const placeheld = language === 'js' ? text : text.replace(/\{[^{}]*\}/gu, ` ${PLACEHOLDER} `)
|
|
43
|
+
found.push({ text: placeheld.replace(/%[sdvqIL]/gu, ` ${PLACEHOLDER} `), line: start, joined: source[k] === '+' })
|
|
44
|
+
previous = 'x'
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// 读到收尾的引号为止;escapes:反斜杠转义
|
|
48
|
+
const quoted = (close: string, escapes: boolean): string => {
|
|
49
|
+
let text = ''
|
|
50
|
+
while (i < source.length && !source.startsWith(close, i)) {
|
|
51
|
+
const char = source[i] as string
|
|
52
|
+
if (escapes && char === '\\') {
|
|
53
|
+
const next = source[i + 1] ?? ''
|
|
54
|
+
if (next === '\n') line++
|
|
55
|
+
text += ESCAPED[next] ?? next
|
|
56
|
+
i += 2
|
|
57
|
+
continue
|
|
58
|
+
}
|
|
59
|
+
if (char === '\n') line++
|
|
60
|
+
text += char
|
|
61
|
+
i++
|
|
62
|
+
}
|
|
63
|
+
i += close.length
|
|
64
|
+
return text
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// JS 模板字符串:读到 ` 收尾,或者停在 ${ 里
|
|
68
|
+
const template = (text: string, start: number): void => {
|
|
69
|
+
while (i < source.length) {
|
|
70
|
+
const char = source[i] as string
|
|
71
|
+
if (char === '\\') {
|
|
72
|
+
text += ESCAPED[source[i + 1] ?? ''] ?? source[i + 1] ?? ''
|
|
73
|
+
i += 2
|
|
74
|
+
} else if (char === '`') {
|
|
75
|
+
i++
|
|
76
|
+
finish(text, start)
|
|
77
|
+
return
|
|
78
|
+
} else if (char === '$' && source[i + 1] === '{') {
|
|
79
|
+
i += 2
|
|
80
|
+
suspended.push({ text: `${text} ${PLACEHOLDER} `, line: start, depth })
|
|
81
|
+
depth = 0
|
|
82
|
+
previous = '('
|
|
83
|
+
return
|
|
84
|
+
} else {
|
|
85
|
+
if (char === '\n') line++
|
|
86
|
+
text += char
|
|
87
|
+
i++
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
finish(text, start)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
while (i < source.length) {
|
|
94
|
+
const char = source[i] as string
|
|
95
|
+
const next = source[i + 1]
|
|
96
|
+
if (char === '\n') {
|
|
97
|
+
line++
|
|
98
|
+
i++
|
|
99
|
+
} else if (/\s/u.test(char)) {
|
|
100
|
+
i++
|
|
101
|
+
} else if (language === 'py' ? char === '#' : char === '/' && next === '/') {
|
|
102
|
+
while (i < source.length && source[i] !== '\n') i++
|
|
103
|
+
} else if (language !== 'py' && char === '/' && next === '*') {
|
|
104
|
+
const end = source.indexOf('*/', i + 2)
|
|
105
|
+
const stop = end === -1 ? source.length : end + 2
|
|
106
|
+
line += source.slice(i, stop).split('\n').length - 1
|
|
107
|
+
i = stop
|
|
108
|
+
} else if (language === 'js' && char === '`') {
|
|
109
|
+
i++
|
|
110
|
+
template('', line)
|
|
111
|
+
} else if (language === 'go' && char === '`') {
|
|
112
|
+
const start = line
|
|
113
|
+
i++
|
|
114
|
+
finish(quoted('`', false), start)
|
|
115
|
+
} else if (char === '"' || char === "'") {
|
|
116
|
+
const start = line
|
|
117
|
+
if (language === 'py') {
|
|
118
|
+
const prefix = /[A-Za-z]{1,2}$/u.exec(source.slice(Math.max(0, i - 2), i))?.[0] ?? ''
|
|
119
|
+
const raw = /r/iu.test(prefix)
|
|
120
|
+
const triple = source.startsWith(char.repeat(3), i)
|
|
121
|
+
i += triple ? 3 : 1
|
|
122
|
+
finish(quoted(triple ? char.repeat(3) : char, !raw), start)
|
|
123
|
+
} else if (language === 'java' && source.startsWith('"""', i)) {
|
|
124
|
+
i += 3
|
|
125
|
+
finish(quoted('"""', true), start)
|
|
126
|
+
} else if (char === "'" && language !== 'js') {
|
|
127
|
+
// Go、Java 的单引号是字符
|
|
128
|
+
i++
|
|
129
|
+
quoted("'", true)
|
|
130
|
+
previous = 'x'
|
|
131
|
+
} else {
|
|
132
|
+
i++
|
|
133
|
+
finish(quoted(char, true), start)
|
|
134
|
+
}
|
|
135
|
+
} else if (language === 'js' && char === '/' && (previous === '' || /[(,=:[!&|?{};+\-*%<>~^]/u.test(previous))) {
|
|
136
|
+
// 正则字面量:跳到收尾的 /(方括号里的 / 不算)
|
|
137
|
+
let inClass = false
|
|
138
|
+
i++
|
|
139
|
+
while (i < source.length && source[i] !== '\n') {
|
|
140
|
+
const c = source[i] as string
|
|
141
|
+
if (c === '\\') i++
|
|
142
|
+
else if (c === '[') inClass = true
|
|
143
|
+
else if (c === ']') inClass = false
|
|
144
|
+
else if (c === '/' && !inClass) break
|
|
145
|
+
i++
|
|
146
|
+
}
|
|
147
|
+
i++
|
|
148
|
+
previous = 'x'
|
|
149
|
+
} else if (language === 'js' && char === '}' && depth === 0 && suspended.length > 0) {
|
|
150
|
+
i++
|
|
151
|
+
const outer = suspended.pop() as { text: string; line: number; depth: number }
|
|
152
|
+
depth = outer.depth
|
|
153
|
+
template(outer.text, outer.line)
|
|
154
|
+
} else {
|
|
155
|
+
if (char === '{') depth++
|
|
156
|
+
if (char === '}') depth--
|
|
157
|
+
previous = char
|
|
158
|
+
i++
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return found
|
|
162
|
+
}
|