@adep/runtime 0.3.8 → 0.3.9
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/README.md +1 -0
- package/dist/functions/runtime/sandbox.d.ts +11 -3
- package/dist/functions/runtime/worker-executor.d.ts +13 -0
- package/dist/index.js +63 -7
- package/dist/shared/function-timeout.d.ts +29 -0
- package/dist/shared/function-timeout.js +42 -0
- package/dist/shared/multipart.d.ts +55 -0
- package/dist/shared/schema-diff.d.ts +32 -0
- package/dist/shared/schema-diff.js +219 -0
- package/dist/shared/sql-split.d.ts +22 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -17,6 +17,7 @@ pnpm add @adep/runtime
|
|
|
17
17
|
| 本地模拟运行时 | 让 `adep dev` 在本地跑出与线上一致的执行语义 |
|
|
18
18
|
| 依赖解析 | 函数依赖的 classify / manifest 解析 |
|
|
19
19
|
| 工具函数 | 下载签名 / 快照解析 / ProjectDriver 方言工厂等 |
|
|
20
|
+
| 共享判定原语 | `shared/function-timeout`(执行预算单一真相源,FN-054)、`shared/schema-diff`(schema 漂移差集,CLI-047)、`shared/sql-split` / `shared/multipart` 等子路径 |
|
|
20
21
|
|
|
21
22
|
## 用法
|
|
22
23
|
|
|
@@ -43,12 +43,20 @@ export interface SandboxFileSet {
|
|
|
43
43
|
}
|
|
44
44
|
/** 相对路径解析:./util → ./util.ts / ./util.js / ./util / ./util/index.ts。 */
|
|
45
45
|
export declare function resolveModulePath(fromDir: string, request: string, files: Readonly<Record<string, string>>): string | null;
|
|
46
|
+
/**
|
|
47
|
+
* `../` 越根判定(CORE-154 `--parity`):请求里的 `..` 段数超过起点目录深度即越根。
|
|
48
|
+
* 非严格模式下的历史行为是**静默绕回根**(`fn/index.ts` 里 `require('../../x')` 解析到根的
|
|
49
|
+
* `x`);容器形态(真实 fs)在函数目录外解析即「模块不存在」报错——严格模式与平台同形,
|
|
50
|
+
* 把「本地静默绕回、线上报错」的漂移提前到本地暴露。
|
|
51
|
+
*/
|
|
52
|
+
export declare function escapesFunctionRoot(fromDir: string, request: string): boolean;
|
|
46
53
|
/** 构造一个文件模块:返回其 exports(含入口的 default 处理器)。
|
|
47
54
|
* 导出:CF-036 状态对象加载器(state-objects/loader.ts)复用同一精简 require 沙箱。 */
|
|
48
|
-
export declare function loadModule(path: string, files: Readonly<Record<string, string>>, sandboxGlobals: Record<string, unknown>, cache: Map<string, Record<string, unknown>>, resolveBare?: BareSpecifierResolver, bareCache?: Map<string, unknown
|
|
55
|
+
export declare function loadModule(path: string, files: Readonly<Record<string, string>>, sandboxGlobals: Record<string, unknown>, cache: Map<string, Record<string, unknown>>, resolveBare?: BareSpecifierResolver, bareCache?: Map<string, unknown>, strictPaths?: boolean): Record<string, unknown>;
|
|
49
56
|
export interface LoadFunctionResult {
|
|
50
57
|
/** 入口的 default 处理器(假设为 async (ctx) => result)。 */
|
|
51
58
|
handler: (ctx: unknown) => unknown;
|
|
52
59
|
}
|
|
53
|
-
/** 装配入口函数:多文件 + 精简 require + 白名单全局;resolveBare 提供裸模块解析(FN-009,可选)。
|
|
54
|
-
|
|
60
|
+
/** 装配入口函数:多文件 + 精简 require + 白名单全局;resolveBare 提供裸模块解析(FN-009,可选)。
|
|
61
|
+
* strictPaths(CORE-154 `--parity`)= true 时 `../` 越根引用报错(缺省 false 行为不变)。 */
|
|
62
|
+
export declare function loadFunctionModule(files: Readonly<Record<string, string>>, entry: string, sandboxGlobals: Record<string, unknown>, resolveBare?: BareSpecifierResolver, strictPaths?: boolean): LoadFunctionResult;
|
|
@@ -20,10 +20,23 @@ export interface WorkerExecutorOptions {
|
|
|
20
20
|
timeoutMs: number;
|
|
21
21
|
maxResponseBytes?: number;
|
|
22
22
|
};
|
|
23
|
+
/**
|
|
24
|
+
* 平台沙箱严格同形(CORE-154 `--parity`):`process` 一律不注入、`../` 越根引用报错。
|
|
25
|
+
* 执行器级选项(构造期定死,非逐调用)——本地 serve 显式开启;平台装配不传(缺省语义不变)。
|
|
26
|
+
*/
|
|
27
|
+
parity?: boolean;
|
|
28
|
+
/**
|
|
29
|
+
* 执行预算上限(FN-054):平台上限 `FUNCTIONS_EXEC_TIMEOUT_MAX_MS`(缺省 60s)由组合根注入;
|
|
30
|
+
* 超上限的入口声明按上限钳制(钳制写进函数日志,可见面)。缺省 undefined = 不设限
|
|
31
|
+
* (CLI 本地形态:声明即权威,与平台差异见文档)。
|
|
32
|
+
*/
|
|
33
|
+
timeoutMaxMs?: number;
|
|
23
34
|
}
|
|
24
35
|
export declare class WorkerFunctionExecutor implements FunctionExecutor {
|
|
25
36
|
private readonly depsConfig;
|
|
26
37
|
private readonly fetchConfig;
|
|
38
|
+
private readonly parity;
|
|
39
|
+
private readonly timeoutMaxMs;
|
|
27
40
|
constructor(options?: WorkerExecutorOptions);
|
|
28
41
|
execute(input: ExecuteInput): Promise<ExecuteResult>;
|
|
29
42
|
dispose(): Promise<void>;
|
package/dist/index.js
CHANGED
|
@@ -194,6 +194,42 @@ function resolveExecutionDeps(config, projectId, manifestContent) {
|
|
|
194
194
|
};
|
|
195
195
|
}
|
|
196
196
|
|
|
197
|
+
// packages/runtime/src/shared/function-timeout.ts
|
|
198
|
+
var TIMEOUT_DECL_RE = /^export const timeoutMs = (\d+)$/;
|
|
199
|
+
function parseDeclaredTimeoutMs(entrySource) {
|
|
200
|
+
for (const rawLine of entrySource.split(/\r?\n/)) {
|
|
201
|
+
const line = rawLine.trim();
|
|
202
|
+
if (line.length === 0 || line.startsWith("//") || line.startsWith("*")) continue;
|
|
203
|
+
if (!line.startsWith("export const timeoutMs")) continue;
|
|
204
|
+
const match = TIMEOUT_DECL_RE.exec(line);
|
|
205
|
+
if (match === null) {
|
|
206
|
+
return {
|
|
207
|
+
value: void 0,
|
|
208
|
+
error: `timeoutMs \u58F0\u660E\u975E\u6CD5\uFF1A"${line}"\u3002\u552F\u4E00\u5408\u6CD5\u5F62\u6001\u662F\u5355\u884C "export const timeoutMs = <\u6B63\u6574\u6570\u6BEB\u79D2>"\uFF08\u65E0\u5F15\u53F7 / \u65E0\u4E0B\u5212\u7EBF\u5206\u9694 / \u65E0\u5355\u4F4D / \u65E0\u5C3E\u968F\u6CE8\u91CA\uFF09\uFF0C\u4F8B\u5982 "export const timeoutMs = 30000"`
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
const value = Number(match[1]);
|
|
212
|
+
if (!Number.isInteger(value) || value <= 0) {
|
|
213
|
+
return {
|
|
214
|
+
value: void 0,
|
|
215
|
+
error: `timeoutMs \u58F0\u660E\u975E\u6CD5\uFF1A"${line}"\uFF08\u987B\u4E3A\u6B63\u6574\u6570\u6BEB\u79D2\uFF09`
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
return { value, error: null };
|
|
219
|
+
}
|
|
220
|
+
return { value: void 0, error: null };
|
|
221
|
+
}
|
|
222
|
+
function resolveExecutionBudget(params) {
|
|
223
|
+
const declared = params.declaredMs;
|
|
224
|
+
const declaredField = declared === void 0 ? {} : { declaredMs: declared };
|
|
225
|
+
const base = params.inputTimeoutMs ?? declared ?? DEFAULT_TIMEOUT_MS;
|
|
226
|
+
const ceiling = params.ceilingMs;
|
|
227
|
+
if (ceiling === void 0 || base <= ceiling) {
|
|
228
|
+
return { timeoutMs: base, clamped: false, ...declaredField };
|
|
229
|
+
}
|
|
230
|
+
return { timeoutMs: ceiling, clamped: true, ...declaredField };
|
|
231
|
+
}
|
|
232
|
+
|
|
197
233
|
// packages/runtime/src/functions/runtime/worker-executor.ts
|
|
198
234
|
function resolveWorkerEntry(baseDir = fileURLToPath(new URL(".", import.meta.url))) {
|
|
199
235
|
const candidates = [
|
|
@@ -234,16 +270,35 @@ function rpcReply(worker, id, ok2, payload) {
|
|
|
234
270
|
var WorkerFunctionExecutor = class {
|
|
235
271
|
depsConfig;
|
|
236
272
|
fetchConfig;
|
|
273
|
+
parity;
|
|
274
|
+
timeoutMaxMs;
|
|
237
275
|
constructor(options = {}) {
|
|
238
276
|
this.depsConfig = options.deps;
|
|
239
277
|
this.fetchConfig = options.fetch;
|
|
278
|
+
this.parity = options.parity === true;
|
|
279
|
+
this.timeoutMaxMs = options.timeoutMaxMs;
|
|
240
280
|
}
|
|
241
281
|
async execute(input) {
|
|
242
|
-
const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
243
|
-
const memoryLimitMb = input.memoryLimitMb ?? DEFAULT_MEMORY_LIMIT_MB;
|
|
244
282
|
const entry = input.entry ?? resolveDraftEntry(input.fn.name, input.files) ?? "index.ts";
|
|
283
|
+
const declared = parseDeclaredTimeoutMs(input.files[entry] ?? "");
|
|
284
|
+
if (declared.error !== null) {
|
|
285
|
+
throw new ExecutorError(400, "FN_EXEC_TIMEOUT_DECL_INVALID", declared.error);
|
|
286
|
+
}
|
|
287
|
+
const budget = resolveExecutionBudget({
|
|
288
|
+
inputTimeoutMs: input.timeoutMs,
|
|
289
|
+
declaredMs: declared.value,
|
|
290
|
+
ceilingMs: this.timeoutMaxMs
|
|
291
|
+
});
|
|
292
|
+
const timeoutMs = budget.timeoutMs;
|
|
293
|
+
const memoryLimitMb = input.memoryLimitMb ?? DEFAULT_MEMORY_LIMIT_MB;
|
|
245
294
|
const deps = this.depsConfig === void 0 ? void 0 : resolveExecutionDeps(this.depsConfig, input.project.id, input.files["package.json"]);
|
|
295
|
+
const effectiveFetchConfig = this.fetchConfig === void 0 ? void 0 : input.fetchAllowlist === void 0 ? this.fetchConfig : { ...this.fetchConfig, allowlist: input.fetchAllowlist };
|
|
246
296
|
const logs = [];
|
|
297
|
+
if (budget.clamped) {
|
|
298
|
+
logs.push(
|
|
299
|
+
`[adep] timeoutMs \u58F0\u660E ${budget.declaredMs}ms \u8D85\u8FC7\u6267\u884C\u9884\u7B97\u4E0A\u9650 ${this.timeoutMaxMs}ms\uFF0C\u5DF2\u6309\u4E0A\u9650\u94B3\u5236\uFF08FN_EXEC_TIMEOUT_CLAMPED\uFF09`
|
|
300
|
+
);
|
|
301
|
+
}
|
|
247
302
|
return new Promise((resolve2, reject) => {
|
|
248
303
|
let worker;
|
|
249
304
|
try {
|
|
@@ -255,7 +310,8 @@ var WorkerFunctionExecutor = class {
|
|
|
255
310
|
capabilities: input.capabilities ?? [],
|
|
256
311
|
...input.env === void 0 ? {} : { env: input.env },
|
|
257
312
|
...deps === void 0 ? {} : { deps },
|
|
258
|
-
...this.
|
|
313
|
+
...this.parity ? { parity: true } : {},
|
|
314
|
+
...effectiveFetchConfig === void 0 ? {} : { fetch: effectiveFetchConfig }
|
|
259
315
|
},
|
|
260
316
|
resourceLimits: { maxOldGenerationSizeMb: memoryLimitMb }
|
|
261
317
|
});
|
|
@@ -399,10 +455,10 @@ function assertSafeStatement(sql) {
|
|
|
399
455
|
if (stripped.includes(";")) {
|
|
400
456
|
throw unsafeOperation("\u4EC5\u5141\u8BB8\u5355\u6761\u8BED\u53E5\uFF0C\u7981\u6B62\u591A\u8BED\u53E5\u5806\u53E0");
|
|
401
457
|
}
|
|
402
|
-
if (
|
|
458
|
+
if (/\b(ATTACH|DETACH)\b/.test(stripped.toUpperCase())) {
|
|
403
459
|
throw unsafeOperation("\u7981\u6B62\u8DE8\u5E93\u64CD\u4F5C\uFF08ATTACH / DETACH\uFF09");
|
|
404
460
|
}
|
|
405
|
-
if (
|
|
461
|
+
if (/\bSQLITE_\w+/i.test(stripped)) {
|
|
406
462
|
throw unsafeOperation("\u7981\u6B62\u8BBF\u95EE\u7CFB\u7EDF\u8868\uFF08sqlite_*\uFF09");
|
|
407
463
|
}
|
|
408
464
|
return sqlHead(stripped);
|
|
@@ -2483,10 +2539,10 @@ function assertReadOnly(sql) {
|
|
|
2483
2539
|
if (!head.startsWith("SELECT") && !head.startsWith("WITH")) {
|
|
2484
2540
|
throw new SimDbError("DB_UNSAFE_OP", "cloud.db.query \u4EC5\u5141\u8BB8\u53EA\u8BFB\u67E5\u8BE2\uFF08SELECT / WITH\uFF09");
|
|
2485
2541
|
}
|
|
2486
|
-
if (
|
|
2542
|
+
if (/\b(ATTACH|DETACH)\b/.test(stripped.toUpperCase())) {
|
|
2487
2543
|
throw new SimDbError("DB_UNSAFE_OP", "\u7981\u6B62\u8DE8\u5E93\u64CD\u4F5C\uFF08ATTACH / DETACH\uFF09");
|
|
2488
2544
|
}
|
|
2489
|
-
if (
|
|
2545
|
+
if (/\bSQLITE_\w+/i.test(stripped) && !/SQLITE_MASTER\b/i.test(stripped)) {
|
|
2490
2546
|
throw new SimDbError("DB_UNSAFE_OP", "\u7981\u6B62\u8BBF\u95EE\u7CFB\u7EDF\u8868\uFF08sqlite_*\uFF09");
|
|
2491
2547
|
}
|
|
2492
2548
|
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** 解析结果:`value` = 声明值(未声明 undefined);`error` 非空 = 声明形态非法(fail loud)。 */
|
|
2
|
+
export interface DeclaredTimeoutMs {
|
|
3
|
+
value: number | undefined;
|
|
4
|
+
error: string | null;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* 解析入口源码的 timeoutMs 声明。
|
|
8
|
+
*
|
|
9
|
+
* 只看入口文件(`files[entry]`)——声明是函数级的执行预算,放辅助文件里语义含糊;
|
|
10
|
+
* 匹配按「整行 trim 后全等正则」,`export const timeoutMs = "30s"` / `30_000` /
|
|
11
|
+
* 尾随注释等形态一律报错(错误信息给出唯一合法形态,作者当场改)。
|
|
12
|
+
*/
|
|
13
|
+
export declare function parseDeclaredTimeoutMs(entrySource: string): DeclaredTimeoutMs;
|
|
14
|
+
/** 执行预算判定产物:`timeoutMs` = 实际生效预算;`clamped` = 声明超上限被钳(日志可见面由执行器落)。 */
|
|
15
|
+
export interface ExecutionBudget {
|
|
16
|
+
timeoutMs: number;
|
|
17
|
+
clamped: boolean;
|
|
18
|
+
/** 生效的声明值(未声明 undefined)——钳制日志点名「声明了多少、被钳到多少」用。 */
|
|
19
|
+
declaredMs?: number;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* 预算取值(优先级):调用方显式 `input.timeoutMs` > 入口声明 > 缺省 10s;
|
|
23
|
+
* 再对平台上限取 min(上限缺省 = 不设限——CLI 本地形态无平台交集面,声明即权威)。
|
|
24
|
+
*/
|
|
25
|
+
export declare function resolveExecutionBudget(params: {
|
|
26
|
+
inputTimeoutMs?: number | undefined;
|
|
27
|
+
declaredMs?: number | undefined;
|
|
28
|
+
ceilingMs?: number | undefined;
|
|
29
|
+
}): ExecutionBudget;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// packages/runtime/src/shared/executor-runtime.ts
|
|
2
|
+
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
3
|
+
|
|
4
|
+
// packages/runtime/src/shared/function-timeout.ts
|
|
5
|
+
var TIMEOUT_DECL_RE = /^export const timeoutMs = (\d+)$/;
|
|
6
|
+
function parseDeclaredTimeoutMs(entrySource) {
|
|
7
|
+
for (const rawLine of entrySource.split(/\r?\n/)) {
|
|
8
|
+
const line = rawLine.trim();
|
|
9
|
+
if (line.length === 0 || line.startsWith("//") || line.startsWith("*")) continue;
|
|
10
|
+
if (!line.startsWith("export const timeoutMs")) continue;
|
|
11
|
+
const match = TIMEOUT_DECL_RE.exec(line);
|
|
12
|
+
if (match === null) {
|
|
13
|
+
return {
|
|
14
|
+
value: void 0,
|
|
15
|
+
error: `timeoutMs \u58F0\u660E\u975E\u6CD5\uFF1A"${line}"\u3002\u552F\u4E00\u5408\u6CD5\u5F62\u6001\u662F\u5355\u884C "export const timeoutMs = <\u6B63\u6574\u6570\u6BEB\u79D2>"\uFF08\u65E0\u5F15\u53F7 / \u65E0\u4E0B\u5212\u7EBF\u5206\u9694 / \u65E0\u5355\u4F4D / \u65E0\u5C3E\u968F\u6CE8\u91CA\uFF09\uFF0C\u4F8B\u5982 "export const timeoutMs = 30000"`
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
const value = Number(match[1]);
|
|
19
|
+
if (!Number.isInteger(value) || value <= 0) {
|
|
20
|
+
return {
|
|
21
|
+
value: void 0,
|
|
22
|
+
error: `timeoutMs \u58F0\u660E\u975E\u6CD5\uFF1A"${line}"\uFF08\u987B\u4E3A\u6B63\u6574\u6570\u6BEB\u79D2\uFF09`
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
return { value, error: null };
|
|
26
|
+
}
|
|
27
|
+
return { value: void 0, error: null };
|
|
28
|
+
}
|
|
29
|
+
function resolveExecutionBudget(params) {
|
|
30
|
+
const declared = params.declaredMs;
|
|
31
|
+
const declaredField = declared === void 0 ? {} : { declaredMs: declared };
|
|
32
|
+
const base = params.inputTimeoutMs ?? declared ?? DEFAULT_TIMEOUT_MS;
|
|
33
|
+
const ceiling = params.ceilingMs;
|
|
34
|
+
if (ceiling === void 0 || base <= ceiling) {
|
|
35
|
+
return { timeoutMs: base, clamped: false, ...declaredField };
|
|
36
|
+
}
|
|
37
|
+
return { timeoutMs: ceiling, clamped: true, ...declaredField };
|
|
38
|
+
}
|
|
39
|
+
export {
|
|
40
|
+
parseDeclaredTimeoutMs,
|
|
41
|
+
resolveExecutionBudget
|
|
42
|
+
};
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* multipart/form-data 解析(FN-047,esign 踩坑 B1):`ctx.files` 的唯一解析器。
|
|
3
|
+
*
|
|
4
|
+
* ## 为什么单点在这里
|
|
5
|
+
*
|
|
6
|
+
* 此前 `ctx.files` 类型存在、worker-entry 透传,但**没有任何解析器**——线上触发链
|
|
7
|
+
* (`server/domains/functions/runtime/forward.ts`)与本地触发链
|
|
8
|
+
* (`packages/cli/src/dev-shared.ts` 的 `bodyOf`)都只认 JSON/文本 ⇒ multipart 请求
|
|
9
|
+
* `ctx.files` 恒为空数组、无错误无日志。esign 被迫全站 base64 JSON。
|
|
10
|
+
* 静默空数组是最差的失败形态:开发者以为是自己的 bug。
|
|
11
|
+
*
|
|
12
|
+
* server 与 CLI 都 import `@adep/runtime/shared/*`(http-envelope / function-source 先例),
|
|
13
|
+
* 本文件落在 runtime/shared ⇒ **serve 与线上同批同源**,同一份字节两边解析结果逐字段一致
|
|
14
|
+
* (B2 一致性命题的解析层保证)。
|
|
15
|
+
*
|
|
16
|
+
* ## 解析语义(与浏览器 form 提交对齐)
|
|
17
|
+
*
|
|
18
|
+
* - 有 `filename` 的 part → 文件(`ctx.files`:name=客户端文件名、type=MIME 或
|
|
19
|
+
* `application/octet-stream` 缺省、size、data=原始字节);
|
|
20
|
+
* - 无 `filename` 的 part → 文本字段,聚合进 `ctx.body`(同名多值折叠为数组,与
|
|
21
|
+
* forward 的 query 折叠口径一致);
|
|
22
|
+
* - `filename=""`(浏览器「未选择文件」的 file input)→ **跳过**:既不进 files 也不进
|
|
23
|
+
* fields——语义就是「这个字段没有文件」。
|
|
24
|
+
*
|
|
25
|
+
* ## 诚实边界
|
|
26
|
+
*
|
|
27
|
+
* - 只认 `filename="..."` 引号形态(浏览器/标准客户端都发这个);`filename*=UTF-8''…`
|
|
28
|
+
* (RFC 5987)与裸 token 形态不识别——识别不到 filename 时按文本字段处理。
|
|
29
|
+
* - part 数据按 RFC 2046「CRLF--boundary」分隔:数据**自身**以 CRLF 结尾时这两个字节
|
|
30
|
+
* 归分隔符(所有服务端解析器同款语义,浏览器客户端不发送该差异)。
|
|
31
|
+
* - 大小上限沿用触发链既有口径(整包读取,无独立上限)——本文件不做截断判断。
|
|
32
|
+
*/
|
|
33
|
+
export declare class MultipartParseError extends Error {
|
|
34
|
+
constructor(message: string);
|
|
35
|
+
}
|
|
36
|
+
/** `ctx.files` 单文件(与 `@adep/types` 的 FunctionFile 同形状,此处避免类型反向依赖)。 */
|
|
37
|
+
export interface MultipartFile {
|
|
38
|
+
readonly name: string;
|
|
39
|
+
readonly type: string;
|
|
40
|
+
readonly size: number;
|
|
41
|
+
readonly data: Uint8Array;
|
|
42
|
+
}
|
|
43
|
+
export interface ParsedMultipart {
|
|
44
|
+
/** 文本字段聚合;无文本字段时 undefined(`ctx.body` 保持 undefined)。 */
|
|
45
|
+
readonly fields: Record<string, string | readonly string[]> | undefined;
|
|
46
|
+
readonly files: readonly MultipartFile[];
|
|
47
|
+
}
|
|
48
|
+
/** 从 Content-Type 提取 boundary(容忍引号包裹、参数顺序、大小写)。 */
|
|
49
|
+
export declare function extractBoundary(contentType: string): string;
|
|
50
|
+
/**
|
|
51
|
+
* 解析 multipart/form-data 请求体。失败抛 `MultipartParseError`(含人可读原因)——
|
|
52
|
+
* 调用侧(线上 forward / 本地 bodyWithFiles)把它转成 400 `FN_MULTIPART_INVALID`,
|
|
53
|
+
* **绝不静默回空数组**。
|
|
54
|
+
*/
|
|
55
|
+
export declare function parseMultipart(contentType: string, raw: Uint8Array): ParsedMultipart;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** schema.sql 解析出的单列定义。 */
|
|
2
|
+
export interface SchemaColumn {
|
|
3
|
+
name: string;
|
|
4
|
+
/** 规范化的类型文本(可能为空:SQLite 允许无类型列)。 */
|
|
5
|
+
type: string;
|
|
6
|
+
notNull: boolean;
|
|
7
|
+
/** DEFAULT 后的原始表达式;无默认值为 null。 */
|
|
8
|
+
defaultValue: string | null;
|
|
9
|
+
primaryKey: boolean;
|
|
10
|
+
}
|
|
11
|
+
/** schema.sql 解析出的单表定义。 */
|
|
12
|
+
export interface SchemaTable {
|
|
13
|
+
name: string;
|
|
14
|
+
columns: SchemaColumn[];
|
|
15
|
+
/** 原始 `CREATE TABLE` 语句(缺失表时整条执行,保留索引/约束)。 */
|
|
16
|
+
statement: string;
|
|
17
|
+
}
|
|
18
|
+
/** 缺列执行计划。 */
|
|
19
|
+
export interface MissingColumnPlan {
|
|
20
|
+
table: string;
|
|
21
|
+
column: SchemaColumn;
|
|
22
|
+
/** 自动执行的 `ALTER TABLE ... ADD COLUMN`。 */
|
|
23
|
+
sql: string;
|
|
24
|
+
/** 无法自动执行时的原因;null = 可自动执行。 */
|
|
25
|
+
blocked: string | null;
|
|
26
|
+
}
|
|
27
|
+
/** SQL 标识符引用(只用于**程序生成**的 DDL;用户值仍走绑定参数)。 */
|
|
28
|
+
export declare function quoteIdent(name: string): string;
|
|
29
|
+
/** 解析 schema.sql 里的所有 `CREATE TABLE`(其它语句忽略,仍由 apply 阶段原样执行)。 */
|
|
30
|
+
export declare function parseSchemaTables(sql: string): SchemaTable[];
|
|
31
|
+
/** 生成缺列计划;不可自动执行的列标 `blocked`。 */
|
|
32
|
+
export declare function planMissingColumn(table: string, column: SchemaColumn): MissingColumnPlan;
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
// packages/runtime/src/shared/sql-split.ts
|
|
2
|
+
function splitSqlStatements(source) {
|
|
3
|
+
const statements = [];
|
|
4
|
+
let buffer = "";
|
|
5
|
+
let inQuote = false;
|
|
6
|
+
const lines = source.split("\n");
|
|
7
|
+
for (const rawLine of lines) {
|
|
8
|
+
const trimmed = rawLine.trim();
|
|
9
|
+
if (!inQuote && (trimmed.length === 0 || trimmed.startsWith("--"))) continue;
|
|
10
|
+
const scanLine = inQuote ? rawLine : trimmed;
|
|
11
|
+
for (let i = 0; i < scanLine.length; i++) {
|
|
12
|
+
const ch = scanLine[i];
|
|
13
|
+
if (inQuote) {
|
|
14
|
+
if (ch === "'") {
|
|
15
|
+
if (scanLine[i + 1] === "'") {
|
|
16
|
+
buffer += ch + scanLine[i + 1];
|
|
17
|
+
i++;
|
|
18
|
+
continue;
|
|
19
|
+
}
|
|
20
|
+
inQuote = false;
|
|
21
|
+
}
|
|
22
|
+
buffer += ch;
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
if (ch === "'") {
|
|
26
|
+
inQuote = true;
|
|
27
|
+
buffer += ch;
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
if (ch === "-" && scanLine[i + 1] === "-") break;
|
|
31
|
+
if (ch === ";") {
|
|
32
|
+
const statement = buffer.trim();
|
|
33
|
+
if (statement.length > 0) statements.push(statement);
|
|
34
|
+
buffer = "";
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
buffer += ch;
|
|
38
|
+
}
|
|
39
|
+
if (inQuote) {
|
|
40
|
+
buffer += "\n";
|
|
41
|
+
} else if (buffer.length > 0 && !/\s$/.test(buffer)) {
|
|
42
|
+
buffer += " ";
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (inQuote) {
|
|
46
|
+
throw new Error(`SQL \u811A\u672C\u5F15\u53F7\u672A\u95ED\u5408\uFF1A${buffer.trim().slice(0, 80)}\u2026`);
|
|
47
|
+
}
|
|
48
|
+
const tail = buffer.trim();
|
|
49
|
+
if (tail.length > 0) statements.push(tail);
|
|
50
|
+
return statements;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// packages/runtime/src/shared/schema-diff.ts
|
|
54
|
+
function quoteIdent(name) {
|
|
55
|
+
return `"${name.replaceAll('"', '""')}"`;
|
|
56
|
+
}
|
|
57
|
+
function unquoteIdent(raw) {
|
|
58
|
+
const text = raw.trim();
|
|
59
|
+
if (text.length >= 2) {
|
|
60
|
+
const first = text[0];
|
|
61
|
+
const last = text[text.length - 1];
|
|
62
|
+
if (first === '"' && last === '"' || first === "`" && last === "`") {
|
|
63
|
+
return text.slice(1, -1).replaceAll(first + first, first);
|
|
64
|
+
}
|
|
65
|
+
if (first === "[" && last === "]") return text.slice(1, -1);
|
|
66
|
+
if (first === "'" && last === "'") return text.slice(1, -1).replaceAll("''", "'");
|
|
67
|
+
}
|
|
68
|
+
return text;
|
|
69
|
+
}
|
|
70
|
+
function splitTopLevel(body) {
|
|
71
|
+
const parts = [];
|
|
72
|
+
let depth = 0;
|
|
73
|
+
let quote = null;
|
|
74
|
+
let start = 0;
|
|
75
|
+
for (let index = 0; index < body.length; index += 1) {
|
|
76
|
+
const char = body[index];
|
|
77
|
+
if (quote !== null) {
|
|
78
|
+
if (char === quote) {
|
|
79
|
+
if (body[index + 1] === quote) index += 1;
|
|
80
|
+
else quote = null;
|
|
81
|
+
}
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
if (char === '"' || char === "`" || char === "'") {
|
|
85
|
+
quote = char;
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
if (char === "[") {
|
|
89
|
+
quote = "]";
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
if (char === "(") depth += 1;
|
|
93
|
+
else if (char === ")") depth -= 1;
|
|
94
|
+
else if (char === "," && depth === 0) {
|
|
95
|
+
parts.push(body.slice(start, index));
|
|
96
|
+
start = index + 1;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
parts.push(body.slice(start));
|
|
100
|
+
return parts.map((part) => part.trim()).filter((part) => part.length > 0);
|
|
101
|
+
}
|
|
102
|
+
function findTableBody(statement, openIndex) {
|
|
103
|
+
let depth = 0;
|
|
104
|
+
let quote = null;
|
|
105
|
+
for (let index = openIndex; index < statement.length; index += 1) {
|
|
106
|
+
const char = statement[index];
|
|
107
|
+
if (quote !== null) {
|
|
108
|
+
if (char === quote) {
|
|
109
|
+
if (statement[index + 1] === quote) index += 1;
|
|
110
|
+
else quote = null;
|
|
111
|
+
}
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
if (char === '"' || char === "`" || char === "'") {
|
|
115
|
+
quote = char;
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
if (char === "[") {
|
|
119
|
+
quote = "]";
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
if (char === "(") depth += 1;
|
|
123
|
+
else if (char === ")") {
|
|
124
|
+
depth -= 1;
|
|
125
|
+
if (depth === 0) return statement.slice(openIndex + 1, index);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
var TABLE_CONSTRAINTS = /* @__PURE__ */ new Set(["CONSTRAINT", "PRIMARY", "UNIQUE", "FOREIGN", "CHECK", "KEY", "EXCLUDE"]);
|
|
131
|
+
var COLUMN_CONSTRAINTS = [
|
|
132
|
+
"NOT",
|
|
133
|
+
"NULL",
|
|
134
|
+
"DEFAULT",
|
|
135
|
+
"PRIMARY",
|
|
136
|
+
"UNIQUE",
|
|
137
|
+
"CHECK",
|
|
138
|
+
"REFERENCES",
|
|
139
|
+
"COLLATE",
|
|
140
|
+
"GENERATED",
|
|
141
|
+
"AS",
|
|
142
|
+
"AUTOINCREMENT",
|
|
143
|
+
"CONSTRAINT"
|
|
144
|
+
];
|
|
145
|
+
function parseColumn(part) {
|
|
146
|
+
const nameMatch = /^("(?:[^"]|"")*"|`(?:[^`]|``)*`|\[[^\]]*\]|'[^']*'|[A-Za-z_][A-Za-z0-9_$]*)/.exec(
|
|
147
|
+
part.trim()
|
|
148
|
+
);
|
|
149
|
+
if (nameMatch === null) return null;
|
|
150
|
+
const name = unquoteIdent(nameMatch[1]);
|
|
151
|
+
const head = nameMatch[1].toUpperCase();
|
|
152
|
+
if (TABLE_CONSTRAINTS.has(head)) return null;
|
|
153
|
+
let rest = part.trim().slice(nameMatch[1].length).trim();
|
|
154
|
+
if (TABLE_CONSTRAINTS.has(name.toUpperCase()) && rest.startsWith("(")) return null;
|
|
155
|
+
const upperRest = rest.toUpperCase();
|
|
156
|
+
let typeEnd = rest.length;
|
|
157
|
+
for (const keyword of COLUMN_CONSTRAINTS) {
|
|
158
|
+
const match = new RegExp(`\\b${keyword}\\b`).exec(upperRest);
|
|
159
|
+
if (match !== null && match.index < typeEnd) typeEnd = match.index;
|
|
160
|
+
}
|
|
161
|
+
const type = rest.slice(0, typeEnd).trim();
|
|
162
|
+
rest = rest.slice(typeEnd).trim();
|
|
163
|
+
const notNull = /\bNOT\s+NULL\b/i.test(rest);
|
|
164
|
+
const primaryKey = /\bPRIMARY\s+KEY\b/i.test(rest);
|
|
165
|
+
const defaultMatch = /\bDEFAULT\s+(.+?)(?=\s+(?:NOT|PRIMARY|UNIQUE|CHECK|REFERENCES|COLLATE|GENERATED|AS|AUTOINCREMENT|CONSTRAINT)\b|$)/i.exec(
|
|
166
|
+
rest
|
|
167
|
+
);
|
|
168
|
+
return {
|
|
169
|
+
name,
|
|
170
|
+
type,
|
|
171
|
+
notNull,
|
|
172
|
+
primaryKey,
|
|
173
|
+
defaultValue: defaultMatch === null ? null : defaultMatch[1].trim()
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
function parseSchemaTables(sql) {
|
|
177
|
+
const tables = [];
|
|
178
|
+
const pattern = /CREATE\s+(?:TEMP|TEMPORARY\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?("(?:[^"]|"")*"|`(?:[^`]|``)*`|\[[^\]]*\]|'[^']*'|[A-Za-z_][A-Za-z0-9_$.]*)\s*\(/gi;
|
|
179
|
+
for (const statement of splitSqlStatements(sql)) {
|
|
180
|
+
const match = pattern.exec(statement);
|
|
181
|
+
pattern.lastIndex = 0;
|
|
182
|
+
if (match === null) continue;
|
|
183
|
+
const openIndex = match.index + match[0].length - 1;
|
|
184
|
+
const body = findTableBody(statement, openIndex);
|
|
185
|
+
if (body === null) continue;
|
|
186
|
+
const rawName = match[1];
|
|
187
|
+
const name = unquoteIdent(rawName.split(".").pop() ?? rawName);
|
|
188
|
+
const columns = [];
|
|
189
|
+
for (const part of splitTopLevel(body)) {
|
|
190
|
+
const column = parseColumn(part);
|
|
191
|
+
if (column !== null) columns.push(column);
|
|
192
|
+
}
|
|
193
|
+
tables.push({ name, columns, statement: statement.trim() });
|
|
194
|
+
}
|
|
195
|
+
return tables;
|
|
196
|
+
}
|
|
197
|
+
function planMissingColumn(table, column) {
|
|
198
|
+
const base = `ALTER TABLE ${quoteIdent(table)} ADD COLUMN ${quoteIdent(column.name)}`;
|
|
199
|
+
let blocked = null;
|
|
200
|
+
if (column.primaryKey) {
|
|
201
|
+
blocked = `\u5217 ${table}.${column.name} \u662F PRIMARY KEY\uFF1ASQLite / PG \u7684 ADD COLUMN \u4E0D\u80FD\u65B0\u589E\u4E3B\u952E\u5217\uFF0C\u9700\u8981\u91CD\u5EFA\u8868\uFF08\u5BFC\u51FA \u2192 \u5EFA\u65B0\u8868 \u2192 \u8FC1\u6570\u636E\uFF09\u3002`;
|
|
202
|
+
} else if (column.notNull && column.defaultValue === null) {
|
|
203
|
+
blocked = `\u5217 ${table}.${column.name} \u4E3A NOT NULL \u4E14\u65E0 DEFAULT\uFF1A\u65E2\u6709\u884C\u65E0\u6CD5\u81EA\u52A8\u586B\u5145\uFF0C\u8BF7\u5148 \`adep db exec --sql "ALTER TABLE ${table} ADD COLUMN ${column.name} <type> DEFAULT <value>"\` \u56DE\u586B\u540E\u518D\u52A0\u7EA6\u675F\u3002`;
|
|
204
|
+
}
|
|
205
|
+
const type = column.type.length === 0 ? "" : ` ${column.type}`;
|
|
206
|
+
const notNull = column.notNull && column.defaultValue !== null ? " NOT NULL" : "";
|
|
207
|
+
const fallback = column.defaultValue === null ? "" : ` DEFAULT ${column.defaultValue}`;
|
|
208
|
+
return {
|
|
209
|
+
table,
|
|
210
|
+
column,
|
|
211
|
+
sql: `${base}${type}${notNull}${fallback}`,
|
|
212
|
+
blocked
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
export {
|
|
216
|
+
parseSchemaTables,
|
|
217
|
+
planMissingColumn,
|
|
218
|
+
quoteIdent
|
|
219
|
+
};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `splitSqlStatements` 单点(CLI-040):`adep db migrate`(CLI)与 push 自动同步的
|
|
3
|
+
* schema 自动应用(server `migrate/apply.ts`)共用这一份实现——两份拷贝历史上已经
|
|
4
|
+
* 分叉过一次(CLI 侧行内注释截断没同步到平台侧 ⇒ 同一文件两种结论,DB-010),本次
|
|
5
|
+
* 消重后**任何一侧都不得再留本地副本**(回归用例钉住:全仓只剩本处定义)。
|
|
6
|
+
*
|
|
7
|
+
* 拆分规则(与平台 console/sql 单语句语义对齐):
|
|
8
|
+
* - `--` 开头的整行视为注释剔除——**仅引号外**:多行字符串字面量里以 `--` 开头的续行
|
|
9
|
+
* 是**数据**,无条件剔除会整行挖掉(轻则静默改数据,重则破坏引号配对报无关语法错;
|
|
10
|
+
* 实测复现:chenfei-travel 的 `site_settings.hero_slides`);
|
|
11
|
+
* - 引号外的 `--` 视为行内注释,截断到行尾(标准 SQL 语义:注释后的同语句内容由
|
|
12
|
+
* 后续行承接;若行内注释被并入语句,SQLite 会把其后所有内容当注释吞掉,多行语句
|
|
13
|
+
* 直接报 incomplete input——dgc 移植踩坑);
|
|
14
|
+
* - 语句以 `;` 结尾,一条语句可跨多行;
|
|
15
|
+
* - 单引号字符串内的 `;` / `--` 不处理(逐行累计时记录引号开合状态,`''` 为转义);
|
|
16
|
+
* - 逐字符扫描用**原始行**(不 trim):引号内行首缩进是数据,不得剥离;
|
|
17
|
+
* - 行间分隔符:引号内补换行(多行文本原样保留),引号外补空格(防相邻 token 粘连,
|
|
18
|
+
* `CREATE INDEX i` + `ON t(a)` → `CREATE INDEX iON t(a)`)——空白差异不影响执行语义;
|
|
19
|
+
* - 引号未闭合 → **抛错**而不是把残句交给驱动(残句要么静默少执行、要么报难懂的方言错)。
|
|
20
|
+
*/
|
|
21
|
+
/** 按行拆分 SQL 脚本为可执行语句序列(引号感知、注释剔除、失败抛错)。 */
|
|
22
|
+
export declare function splitSqlStatements(source: string): string[];
|
package/package.json
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
},
|
|
8
8
|
"homepage": "https://adep.top",
|
|
9
9
|
"bugs": "https://gitcode.com/yunqiang_wu/ai-yunke/issues",
|
|
10
|
-
"version": "0.3.
|
|
10
|
+
"version": "0.3.9",
|
|
11
11
|
"private": false,
|
|
12
12
|
"type": "module",
|
|
13
13
|
"sideEffects": false,
|
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
"dist"
|
|
33
33
|
],
|
|
34
34
|
"dependencies": {
|
|
35
|
-
"@adep/types": "0.4.
|
|
35
|
+
"@adep/types": "0.4.2"
|
|
36
36
|
},
|
|
37
37
|
"scripts": {
|
|
38
38
|
"test": "vitest run",
|