@adep/runtime 0.3.8 → 0.3.10
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 +128 -14
- 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 +61 -0
- package/dist/shared/schema-diff.js +316 -0
- package/dist/shared/sql-split.d.ts +22 -0
- package/dist/storage/driver.d.ts +12 -0
- package/dist/storage/signature.d.ts +40 -1
- 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);
|
|
@@ -1258,9 +1314,20 @@ var StorageError = class extends Error {
|
|
|
1258
1314
|
var STORAGE_CODES = {
|
|
1259
1315
|
invalidPath: "STORAGE_INVALID_PATH",
|
|
1260
1316
|
invalidData: "STORAGE_INVALID_DATA",
|
|
1317
|
+
invalidVisibility: "STORAGE_INVALID_VISIBILITY",
|
|
1318
|
+
invalidSignedUrlTtl: "STORAGE_SIGNED_URL_TTL_INVALID",
|
|
1319
|
+
signedUrlTtlExceeded: "STORAGE_SIGNED_URL_TTL_EXCEEDED",
|
|
1261
1320
|
notFound: "STORAGE_NOT_FOUND",
|
|
1262
1321
|
quotaExceeded: "STORAGE_QUOTA_EXCEEDED"
|
|
1263
1322
|
};
|
|
1323
|
+
function assertFileVisibility(value) {
|
|
1324
|
+
if (value === "public" || value === "private") return value;
|
|
1325
|
+
throw new StorageError(
|
|
1326
|
+
400,
|
|
1327
|
+
STORAGE_CODES.invalidVisibility,
|
|
1328
|
+
`\u975E\u6CD5\u7684\u6587\u4EF6\u53EF\u89C1\u6027 ${JSON.stringify(value)}\uFF08\u53EA\u652F\u6301 'public' / 'private'\uFF09`
|
|
1329
|
+
);
|
|
1330
|
+
}
|
|
1264
1331
|
function assertSafeStoragePath(path) {
|
|
1265
1332
|
if (typeof path !== "string" || path.length === 0) {
|
|
1266
1333
|
throw new StorageError(400, STORAGE_CODES.invalidPath, "\u5B58\u50A8\u8DEF\u5F84\u4E0D\u80FD\u4E3A\u7A7A");
|
|
@@ -1476,17 +1543,46 @@ function constantTimeEqual(a, b) {
|
|
|
1476
1543
|
|
|
1477
1544
|
// packages/runtime/src/storage/signature.ts
|
|
1478
1545
|
var DEFAULT_SIGN_TTL_SECONDS = 15 * 60;
|
|
1546
|
+
var MAX_SIGNED_URL_TTL_SECONDS = 7 * 24 * 60 * 60;
|
|
1479
1547
|
var SIGN_EXPIRES_KEY = "x-expires";
|
|
1480
1548
|
var SIGN_SIGNATURE_KEY = "x-signature";
|
|
1549
|
+
function resolveSignedUrlTtl(ttlSeconds, options) {
|
|
1550
|
+
if (ttlSeconds === void 0) return DEFAULT_SIGN_TTL_SECONDS;
|
|
1551
|
+
if (!Number.isInteger(ttlSeconds) || ttlSeconds <= 0) {
|
|
1552
|
+
throw new StorageError(
|
|
1553
|
+
400,
|
|
1554
|
+
STORAGE_CODES.invalidSignedUrlTtl,
|
|
1555
|
+
`\u7B7E\u540D\u6709\u6548\u671F\u5FC5\u987B\u662F\u6B63\u6574\u6570\u79D2\uFF08\u6536\u5230 ${ttlSeconds}\uFF09`
|
|
1556
|
+
);
|
|
1557
|
+
}
|
|
1558
|
+
if (ttlSeconds > MAX_SIGNED_URL_TTL_SECONDS && options?.force !== true) {
|
|
1559
|
+
throw new StorageError(
|
|
1560
|
+
400,
|
|
1561
|
+
STORAGE_CODES.signedUrlTtlExceeded,
|
|
1562
|
+
`\u7B7E\u540D URL \u6709\u6548\u671F\u6700\u957F ${MAX_SIGNED_URL_TTL_SECONDS / 86400} \u5929\uFF08\u6536\u5230 ${ttlSeconds} \u79D2\uFF09\u3002\u9700\u8981\u957F\u671F\u7A33\u5B9A\u7684\u94FE\u63A5\u8BF7\u628A\u6587\u4EF6\u4E0A\u4F20\u4E3A visibility: 'public' \u5E76\u7528 getUrl() \u53D6\u76F4\u94FE\uFF1B\u786E\u9700\u8D85\u957F\u79C1\u6709\u94FE\u63A5\u8BF7\u663E\u5F0F\u4F20 { force: true }\uFF08\u8FC7\u671F\u524D\u94FE\u63A5\u6CC4\u6F0F\u5373\u957F\u671F\u53EF\u8BFB\uFF09\u3002`
|
|
1563
|
+
);
|
|
1564
|
+
}
|
|
1565
|
+
return ttlSeconds;
|
|
1566
|
+
}
|
|
1481
1567
|
function sign(secret, projectId, path, expires) {
|
|
1482
1568
|
const payload = `${projectId}|${path}|${expires}`;
|
|
1483
1569
|
return hmacSha256Hex(secret, payload);
|
|
1484
1570
|
}
|
|
1485
|
-
function
|
|
1486
|
-
|
|
1487
|
-
|
|
1571
|
+
function publicDownloadUrl(config, projectId, path) {
|
|
1572
|
+
return `${config.baseUrl}/api/v1/projects/${encodeURIComponent(projectId)}/files/${encodeURIComponent(path)}`;
|
|
1573
|
+
}
|
|
1574
|
+
function signDownloadUrlWithExpiry(config, projectId, path, ttlSeconds = DEFAULT_SIGN_TTL_SECONDS, options) {
|
|
1575
|
+
const ttl = resolveSignedUrlTtl(ttlSeconds, options);
|
|
1576
|
+
const expires = Math.floor(Date.now() / 1e3) + ttl;
|
|
1577
|
+
const base = publicDownloadUrl(config, projectId, path);
|
|
1488
1578
|
const signature = sign(config.secret, projectId, path, expires);
|
|
1489
|
-
return
|
|
1579
|
+
return {
|
|
1580
|
+
url: `${base}?${SIGN_EXPIRES_KEY}=${expires}&${SIGN_SIGNATURE_KEY}=${signature}`,
|
|
1581
|
+
expires
|
|
1582
|
+
};
|
|
1583
|
+
}
|
|
1584
|
+
function signDownloadUrl(config, projectId, path, ttlSeconds = DEFAULT_SIGN_TTL_SECONDS, options) {
|
|
1585
|
+
return signDownloadUrlWithExpiry(config, projectId, path, ttlSeconds, options).url;
|
|
1490
1586
|
}
|
|
1491
1587
|
function verifyDownloadSignature(config, projectId, path, query, nowSeconds2 = Math.floor(Date.now() / 1e3)) {
|
|
1492
1588
|
const expiresRaw = query.expires;
|
|
@@ -1551,9 +1647,10 @@ function createStorageCapability(driver, signer, projectId) {
|
|
|
1551
1647
|
switch (method) {
|
|
1552
1648
|
case "upload": {
|
|
1553
1649
|
const [path, data, options] = args;
|
|
1650
|
+
const visibility = assertFileVisibility(options?.visibility ?? DEFAULT_VISIBILITY);
|
|
1554
1651
|
return toStoredFile(
|
|
1555
1652
|
await driver.put(projectId, path, asBytes(data), {
|
|
1556
|
-
visibility
|
|
1653
|
+
visibility,
|
|
1557
1654
|
...options?.contentType === void 0 ? {} : { contentType: options.contentType }
|
|
1558
1655
|
})
|
|
1559
1656
|
);
|
|
@@ -1571,9 +1668,26 @@ function createStorageCapability(driver, signer, projectId) {
|
|
|
1571
1668
|
const [prefix] = args;
|
|
1572
1669
|
return (await driver.list(projectId, prefix)).map(toStoredFile);
|
|
1573
1670
|
}
|
|
1671
|
+
case "getUrl": {
|
|
1672
|
+
const [path] = args;
|
|
1673
|
+
const meta = await driver.getMeta(projectId, path);
|
|
1674
|
+
if (meta.visibility === "public") {
|
|
1675
|
+
const result2 = {
|
|
1676
|
+
url: publicDownloadUrl(signer, projectId, path),
|
|
1677
|
+
expiresAt: null
|
|
1678
|
+
};
|
|
1679
|
+
return result2;
|
|
1680
|
+
}
|
|
1681
|
+
const signed = signDownloadUrlWithExpiry(signer, projectId, path);
|
|
1682
|
+
const result = {
|
|
1683
|
+
url: signed.url,
|
|
1684
|
+
expiresAt: new Date(signed.expires * 1e3).toISOString()
|
|
1685
|
+
};
|
|
1686
|
+
return result;
|
|
1687
|
+
}
|
|
1574
1688
|
case "getSignedUrl": {
|
|
1575
|
-
const [path, ttlSeconds] = args;
|
|
1576
|
-
return signDownloadUrl(signer, projectId, path, ttlSeconds);
|
|
1689
|
+
const [path, ttlSeconds, options] = args;
|
|
1690
|
+
return signDownloadUrl(signer, projectId, path, ttlSeconds, options);
|
|
1577
1691
|
}
|
|
1578
1692
|
default:
|
|
1579
1693
|
throw new StorageError(
|
|
@@ -2483,10 +2597,10 @@ function assertReadOnly(sql) {
|
|
|
2483
2597
|
if (!head.startsWith("SELECT") && !head.startsWith("WITH")) {
|
|
2484
2598
|
throw new SimDbError("DB_UNSAFE_OP", "cloud.db.query \u4EC5\u5141\u8BB8\u53EA\u8BFB\u67E5\u8BE2\uFF08SELECT / WITH\uFF09");
|
|
2485
2599
|
}
|
|
2486
|
-
if (
|
|
2600
|
+
if (/\b(ATTACH|DETACH)\b/.test(stripped.toUpperCase())) {
|
|
2487
2601
|
throw new SimDbError("DB_UNSAFE_OP", "\u7981\u6B62\u8DE8\u5E93\u64CD\u4F5C\uFF08ATTACH / DETACH\uFF09");
|
|
2488
2602
|
}
|
|
2489
|
-
if (
|
|
2603
|
+
if (/\bSQLITE_\w+/i.test(stripped) && !/SQLITE_MASTER\b/i.test(stripped)) {
|
|
2490
2604
|
throw new SimDbError("DB_UNSAFE_OP", "\u7981\u6B62\u8BBF\u95EE\u7CFB\u7EDF\u8868\uFF08sqlite_*\uFF09");
|
|
2491
2605
|
}
|
|
2492
2606
|
}
|
|
@@ -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,61 @@
|
|
|
1
|
+
/** schema.sql 解析出的单列定义。 */
|
|
2
|
+
export interface SchemaColumn {
|
|
3
|
+
name: string;
|
|
4
|
+
/** 规范化的类型文本(可能为空:SQLite 允许无类型列)。 */
|
|
5
|
+
type: string;
|
|
6
|
+
notNull: boolean;
|
|
7
|
+
/**
|
|
8
|
+
* 显式声明了 `NULL`(且不是 `NOT NULL`)。
|
|
9
|
+
*
|
|
10
|
+
* 与 `notNull === false` 不同:没写可空性只是「schema 不完整」,不能据此断言线上更严格
|
|
11
|
+
* (DB-025 的反向可空性只对显式 `NULL` 报 warn)。
|
|
12
|
+
*/
|
|
13
|
+
explicitNullable: boolean;
|
|
14
|
+
/** DEFAULT 后的原始表达式;无默认值为 null。 */
|
|
15
|
+
defaultValue: string | null;
|
|
16
|
+
primaryKey: boolean;
|
|
17
|
+
/** 列级 `UNIQUE`(表级 `UNIQUE(...)` 见 `SchemaTable.uniqueConstraints`)。 */
|
|
18
|
+
unique: boolean;
|
|
19
|
+
}
|
|
20
|
+
/** schema.sql 解析出的单表定义。 */
|
|
21
|
+
export interface SchemaTable {
|
|
22
|
+
name: string;
|
|
23
|
+
columns: SchemaColumn[];
|
|
24
|
+
/** 表级 `UNIQUE(...)` 约束的列组(列级 UNIQUE 在 `columns[].unique`)。 */
|
|
25
|
+
uniqueConstraints: string[][];
|
|
26
|
+
/** 原始 `CREATE TABLE` 语句(缺失表时整条执行,保留索引/约束)。 */
|
|
27
|
+
statement: string;
|
|
28
|
+
}
|
|
29
|
+
/** schema.sql 里的 `CREATE [UNIQUE] INDEX` 声明(DB-025)。 */
|
|
30
|
+
export interface SchemaIndex {
|
|
31
|
+
name: string;
|
|
32
|
+
table: string;
|
|
33
|
+
/** 索引列(按声明顺序;表达式索引解析不出普通列时为空数组)。 */
|
|
34
|
+
columns: string[];
|
|
35
|
+
unique: boolean;
|
|
36
|
+
/** 原始语句(计划展示与 `dataStatements` 去重)。 */
|
|
37
|
+
statement: string;
|
|
38
|
+
}
|
|
39
|
+
/** 缺列执行计划。 */
|
|
40
|
+
export interface MissingColumnPlan {
|
|
41
|
+
table: string;
|
|
42
|
+
column: SchemaColumn;
|
|
43
|
+
/** 自动执行的 `ALTER TABLE ... ADD COLUMN`。 */
|
|
44
|
+
sql: string;
|
|
45
|
+
/** 无法自动执行时的原因;null = 可自动执行。 */
|
|
46
|
+
blocked: string | null;
|
|
47
|
+
}
|
|
48
|
+
/** SQL 标识符引用(只用于**程序生成**的 DDL;用户值仍走绑定参数)。 */
|
|
49
|
+
export declare function quoteIdent(name: string): string;
|
|
50
|
+
/** 解析 schema.sql 里的所有 `CREATE TABLE`(其它语句忽略,仍由 apply 阶段原样执行)。 */
|
|
51
|
+
export declare function parseSchemaTables(sql: string): SchemaTable[];
|
|
52
|
+
/** 解析 schema.sql 里的 `CREATE [UNIQUE] INDEX`(表达式索引返回空 columns,由消费方跳过)。 */
|
|
53
|
+
export declare function parseSchemaIndexes(sql: string): SchemaIndex[];
|
|
54
|
+
/**
|
|
55
|
+
* 从一段索引 DDL(PG `pg_indexes.indexdef` / `pg_get_indexdef`)提取列名。
|
|
56
|
+
*
|
|
57
|
+
* 与 schema.sql 共用同一套列条目解析;表达式索引返回 null(调用方按「列未知」处理)。
|
|
58
|
+
*/
|
|
59
|
+
export declare function parseIndexDdlColumns(ddl: string): string[] | null;
|
|
60
|
+
/** 生成缺列计划;不可自动执行的列标 `blocked`。 */
|
|
61
|
+
export declare function planMissingColumn(table: string, column: SchemaColumn): MissingColumnPlan;
|
|
@@ -0,0 +1,316 @@
|
|
|
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 parsePlainIdent(raw) {
|
|
71
|
+
const text = raw.trim();
|
|
72
|
+
if (text.length === 0) return null;
|
|
73
|
+
const first = text[0];
|
|
74
|
+
if (first === '"' || first === "`" || first === "[" || first === "'") {
|
|
75
|
+
const unquoted = unquoteIdent(text);
|
|
76
|
+
return unquoted === text.trim() ? null : unquoted;
|
|
77
|
+
}
|
|
78
|
+
return /^[A-Za-z_][A-Za-z0-9_$]*$/.test(text) ? text : null;
|
|
79
|
+
}
|
|
80
|
+
function splitTopLevel(body) {
|
|
81
|
+
const parts = [];
|
|
82
|
+
let depth = 0;
|
|
83
|
+
let quote = null;
|
|
84
|
+
let start = 0;
|
|
85
|
+
for (let index = 0; index < body.length; index += 1) {
|
|
86
|
+
const char = body[index];
|
|
87
|
+
if (quote !== null) {
|
|
88
|
+
if (char === quote) {
|
|
89
|
+
if (body[index + 1] === quote) index += 1;
|
|
90
|
+
else quote = null;
|
|
91
|
+
}
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
if (char === '"' || char === "`" || char === "'") {
|
|
95
|
+
quote = char;
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
if (char === "[") {
|
|
99
|
+
quote = "]";
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
if (char === "(") depth += 1;
|
|
103
|
+
else if (char === ")") depth -= 1;
|
|
104
|
+
else if (char === "," && depth === 0) {
|
|
105
|
+
parts.push(body.slice(start, index));
|
|
106
|
+
start = index + 1;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
parts.push(body.slice(start));
|
|
110
|
+
return parts.map((part) => part.trim()).filter((part) => part.length > 0);
|
|
111
|
+
}
|
|
112
|
+
function findTableBody(statement, openIndex) {
|
|
113
|
+
let depth = 0;
|
|
114
|
+
let quote = null;
|
|
115
|
+
for (let index = openIndex; index < statement.length; index += 1) {
|
|
116
|
+
const char = statement[index];
|
|
117
|
+
if (quote !== null) {
|
|
118
|
+
if (char === quote) {
|
|
119
|
+
if (statement[index + 1] === quote) index += 1;
|
|
120
|
+
else quote = null;
|
|
121
|
+
}
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
if (char === '"' || char === "`" || char === "'") {
|
|
125
|
+
quote = char;
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
if (char === "[") {
|
|
129
|
+
quote = "]";
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
if (char === "(") depth += 1;
|
|
133
|
+
else if (char === ")") {
|
|
134
|
+
depth -= 1;
|
|
135
|
+
if (depth === 0) return statement.slice(openIndex + 1, index);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return null;
|
|
139
|
+
}
|
|
140
|
+
var TABLE_CONSTRAINTS = /* @__PURE__ */ new Set(["CONSTRAINT", "PRIMARY", "UNIQUE", "FOREIGN", "CHECK", "KEY", "EXCLUDE"]);
|
|
141
|
+
var COLUMN_CONSTRAINTS = [
|
|
142
|
+
"NOT",
|
|
143
|
+
"NULL",
|
|
144
|
+
"DEFAULT",
|
|
145
|
+
"PRIMARY",
|
|
146
|
+
"UNIQUE",
|
|
147
|
+
"CHECK",
|
|
148
|
+
"REFERENCES",
|
|
149
|
+
"COLLATE",
|
|
150
|
+
"GENERATED",
|
|
151
|
+
"AS",
|
|
152
|
+
"AUTOINCREMENT",
|
|
153
|
+
"CONSTRAINT"
|
|
154
|
+
];
|
|
155
|
+
function parseColumn(part) {
|
|
156
|
+
const nameMatch = /^("(?:[^"]|"")*"|`(?:[^`]|``)*`|\[[^\]]*\]|'[^']*'|[A-Za-z_][A-Za-z0-9_$]*)/.exec(
|
|
157
|
+
part.trim()
|
|
158
|
+
);
|
|
159
|
+
if (nameMatch === null) return null;
|
|
160
|
+
const name = unquoteIdent(nameMatch[1]);
|
|
161
|
+
const head = nameMatch[1].toUpperCase();
|
|
162
|
+
if (TABLE_CONSTRAINTS.has(head)) return null;
|
|
163
|
+
let rest = part.trim().slice(nameMatch[1].length).trim();
|
|
164
|
+
if (TABLE_CONSTRAINTS.has(name.toUpperCase()) && rest.startsWith("(")) return null;
|
|
165
|
+
const upperRest = rest.toUpperCase();
|
|
166
|
+
let typeEnd = rest.length;
|
|
167
|
+
for (const keyword of COLUMN_CONSTRAINTS) {
|
|
168
|
+
const match = new RegExp(`\\b${keyword}\\b`).exec(upperRest);
|
|
169
|
+
if (match !== null && match.index < typeEnd) typeEnd = match.index;
|
|
170
|
+
}
|
|
171
|
+
const type = rest.slice(0, typeEnd).trim();
|
|
172
|
+
rest = rest.slice(typeEnd).trim();
|
|
173
|
+
const defaultMatch = /\bDEFAULT\s+(.+?)(?=\s+(?:NOT|PRIMARY|UNIQUE|CHECK|REFERENCES|COLLATE|GENERATED|AS|AUTOINCREMENT|CONSTRAINT)\b|$)/i.exec(
|
|
174
|
+
rest
|
|
175
|
+
);
|
|
176
|
+
const constraintText = defaultMatch === null ? rest : rest.replace(defaultMatch[0], " ");
|
|
177
|
+
const declarationText = stripNonNullabilityClauses(constraintText);
|
|
178
|
+
const notNull = /\bNOT\s+NULL\b/i.test(declarationText);
|
|
179
|
+
const explicitNullable = !notNull && /\bNULL\b/i.test(declarationText);
|
|
180
|
+
const primaryKey = /\bPRIMARY\s+KEY\b/i.test(declarationText);
|
|
181
|
+
const unique = /\bUNIQUE\b/i.test(declarationText);
|
|
182
|
+
return {
|
|
183
|
+
name,
|
|
184
|
+
type,
|
|
185
|
+
notNull,
|
|
186
|
+
explicitNullable,
|
|
187
|
+
primaryKey,
|
|
188
|
+
unique,
|
|
189
|
+
defaultValue: defaultMatch === null ? null : defaultMatch[1].trim()
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
function stripNonNullabilityClauses(text) {
|
|
193
|
+
return text.replace(
|
|
194
|
+
/\bREFERENCES\s+\S+(?:\s*\([^)]*\))?(?:\s+ON\s+(?:DELETE|UPDATE)\s+(?:CASCADE|RESTRICT|SET\s+NULL|SET\s+DEFAULT|NO\s+ACTION))*/gi,
|
|
195
|
+
" "
|
|
196
|
+
).replace(/\bCHECK\s*\([^)]*\)/gi, " ").replace(/\bGENERATED\s+ALWAYS\s+AS\s*\([^)]*\)(?:\s+STORED|\s+VIRTUAL)?/gi, " ");
|
|
197
|
+
}
|
|
198
|
+
function parseTableUnique(part) {
|
|
199
|
+
const trimmed = part.trim();
|
|
200
|
+
const match = /^(?:CONSTRAINT\s+(?:"(?:[^"]|"")*"|`(?:[^`]|``)*`|\[[^\]]*\]|[A-Za-z_][A-Za-z0-9_$]*)\s+)?UNIQUE\s*\(/i.exec(
|
|
201
|
+
trimmed
|
|
202
|
+
);
|
|
203
|
+
if (match === null) return null;
|
|
204
|
+
const body = findTableBody(trimmed, match[0].lastIndexOf("("));
|
|
205
|
+
if (body === null) return null;
|
|
206
|
+
const columns = [];
|
|
207
|
+
for (const entry of splitTopLevel(body)) {
|
|
208
|
+
const column = parsePlainIdent(entry);
|
|
209
|
+
if (column === null) return null;
|
|
210
|
+
columns.push(column);
|
|
211
|
+
}
|
|
212
|
+
return columns.length === 0 ? null : columns;
|
|
213
|
+
}
|
|
214
|
+
function parseSchemaTables(sql) {
|
|
215
|
+
const tables = [];
|
|
216
|
+
const pattern = /CREATE\s+(?:TEMP|TEMPORARY\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?("(?:[^"]|"")*"|`(?:[^`]|``)*`|\[[^\]]*\]|'[^']*'|[A-Za-z_][A-Za-z0-9_$.]*)\s*\(/gi;
|
|
217
|
+
for (const statement of splitSqlStatements(sql)) {
|
|
218
|
+
const match = pattern.exec(statement);
|
|
219
|
+
pattern.lastIndex = 0;
|
|
220
|
+
if (match === null) continue;
|
|
221
|
+
const openIndex = match.index + match[0].length - 1;
|
|
222
|
+
const body = findTableBody(statement, openIndex);
|
|
223
|
+
if (body === null) continue;
|
|
224
|
+
const rawName = match[1];
|
|
225
|
+
const name = unquoteIdent(rawName.split(".").pop() ?? rawName);
|
|
226
|
+
const columns = [];
|
|
227
|
+
const uniqueConstraints = [];
|
|
228
|
+
for (const part of splitTopLevel(body)) {
|
|
229
|
+
const unique = parseTableUnique(part);
|
|
230
|
+
if (unique !== null) uniqueConstraints.push(unique);
|
|
231
|
+
const column = parseColumn(part);
|
|
232
|
+
if (column !== null) columns.push(column);
|
|
233
|
+
}
|
|
234
|
+
tables.push({ name, columns, uniqueConstraints, statement: statement.trim() });
|
|
235
|
+
}
|
|
236
|
+
return tables;
|
|
237
|
+
}
|
|
238
|
+
var CREATE_INDEX_PATTERN = /^\s*CREATE\s+(UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:(?:"(?:[^"]|"")*"|`(?:[^`]|``)*`|\[[^\]]*\]|[A-Za-z_][A-Za-z0-9_$]*)\s*\.\s*)?("(?:[^"]|"")*"|`(?:[^`]|``)*`|\[[^\]]*\]|[A-Za-z_][A-Za-z0-9_$]*)\s+ON\s+(?:(?:"(?:[^"]|"")*"|`(?:[^`]|``)*`|\[[^\]]*\]|[A-Za-z_][A-Za-z0-9_$]*)\s*\.\s*)?("(?:[^"]|"")*"|`(?:[^`]|``)*`|\[[^\]]*\]|[A-Za-z_][A-Za-z0-9_$]*)\s*(?:USING\s+[A-Za-z_][A-Za-z0-9_]*\s*)?\(/i;
|
|
239
|
+
function parseIndexColumn(raw) {
|
|
240
|
+
let text = raw.trim();
|
|
241
|
+
text = text.replace(/\s+NULLS\s+(?:FIRST|LAST)\s*$/i, "");
|
|
242
|
+
text = text.replace(/\s+(?:ASC|DESC)\s*$/i, "");
|
|
243
|
+
text = text.replace(
|
|
244
|
+
/\s+COLLATE\s+(?:"(?:[^"]|"")*"|`(?:[^`]|``)*`|\[[^\]]*\]|[A-Za-z_][A-Za-z0-9_$]*)\s*$/i,
|
|
245
|
+
""
|
|
246
|
+
);
|
|
247
|
+
return parsePlainIdent(text);
|
|
248
|
+
}
|
|
249
|
+
function parseSchemaIndexes(sql) {
|
|
250
|
+
const indexes = [];
|
|
251
|
+
for (const statement of splitSqlStatements(sql)) {
|
|
252
|
+
const match = CREATE_INDEX_PATTERN.exec(statement);
|
|
253
|
+
if (match === null) continue;
|
|
254
|
+
const openIndex = match.index + match[0].length - 1;
|
|
255
|
+
const body = findTableBody(statement, openIndex);
|
|
256
|
+
if (body === null) continue;
|
|
257
|
+
const columns = [];
|
|
258
|
+
let expression = false;
|
|
259
|
+
for (const part of splitTopLevel(body)) {
|
|
260
|
+
const column = parseIndexColumn(part);
|
|
261
|
+
if (column === null) {
|
|
262
|
+
expression = true;
|
|
263
|
+
break;
|
|
264
|
+
}
|
|
265
|
+
columns.push(column);
|
|
266
|
+
}
|
|
267
|
+
indexes.push({
|
|
268
|
+
name: unquoteIdent(match[2]),
|
|
269
|
+
table: unquoteIdent(match[3].split(".").pop() ?? match[3]),
|
|
270
|
+
columns: expression ? [] : columns,
|
|
271
|
+
unique: match[1] !== void 0,
|
|
272
|
+
statement: statement.trim()
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
return indexes;
|
|
276
|
+
}
|
|
277
|
+
function parseIndexDdlColumns(ddl) {
|
|
278
|
+
const onMatch = /\s+ON\s+/i.exec(ddl);
|
|
279
|
+
if (onMatch === null) return null;
|
|
280
|
+
const openIndex = ddl.indexOf("(", onMatch.index + onMatch[0].length);
|
|
281
|
+
if (openIndex < 0) return null;
|
|
282
|
+
const body = findTableBody(ddl, openIndex);
|
|
283
|
+
if (body === null) return null;
|
|
284
|
+
const columns = [];
|
|
285
|
+
for (const part of splitTopLevel(body)) {
|
|
286
|
+
const column = parseIndexColumn(part);
|
|
287
|
+
if (column === null) return null;
|
|
288
|
+
columns.push(column);
|
|
289
|
+
}
|
|
290
|
+
return columns.length === 0 ? null : columns;
|
|
291
|
+
}
|
|
292
|
+
function planMissingColumn(table, column) {
|
|
293
|
+
const base = `ALTER TABLE ${quoteIdent(table)} ADD COLUMN ${quoteIdent(column.name)}`;
|
|
294
|
+
let blocked = null;
|
|
295
|
+
if (column.primaryKey) {
|
|
296
|
+
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`;
|
|
297
|
+
} else if (column.notNull && column.defaultValue === null) {
|
|
298
|
+
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`;
|
|
299
|
+
}
|
|
300
|
+
const type = column.type.length === 0 ? "" : ` ${column.type}`;
|
|
301
|
+
const notNull = column.notNull && column.defaultValue !== null ? " NOT NULL" : "";
|
|
302
|
+
const fallback = column.defaultValue === null ? "" : ` DEFAULT ${column.defaultValue}`;
|
|
303
|
+
return {
|
|
304
|
+
table,
|
|
305
|
+
column,
|
|
306
|
+
sql: `${base}${type}${notNull}${fallback}`,
|
|
307
|
+
blocked
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
export {
|
|
311
|
+
parseIndexDdlColumns,
|
|
312
|
+
parseSchemaIndexes,
|
|
313
|
+
parseSchemaTables,
|
|
314
|
+
planMissingColumn,
|
|
315
|
+
quoteIdent
|
|
316
|
+
};
|
|
@@ -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/dist/storage/driver.d.ts
CHANGED
|
@@ -57,9 +57,21 @@ export declare class StorageError extends Error {
|
|
|
57
57
|
export declare const STORAGE_CODES: {
|
|
58
58
|
readonly invalidPath: "STORAGE_INVALID_PATH";
|
|
59
59
|
readonly invalidData: "STORAGE_INVALID_DATA";
|
|
60
|
+
readonly invalidVisibility: "STORAGE_INVALID_VISIBILITY";
|
|
61
|
+
readonly invalidSignedUrlTtl: "STORAGE_SIGNED_URL_TTL_INVALID";
|
|
62
|
+
readonly signedUrlTtlExceeded: "STORAGE_SIGNED_URL_TTL_EXCEEDED";
|
|
60
63
|
readonly notFound: "STORAGE_NOT_FOUND";
|
|
61
64
|
readonly quotaExceeded: "STORAGE_QUOTA_EXCEEDED";
|
|
62
65
|
};
|
|
66
|
+
/**
|
|
67
|
+
* 运行期可见性校验(ST-005)。
|
|
68
|
+
*
|
|
69
|
+
* 用户函数是 JS,TS 的 `FileVisibility` 在运行期被擦除;而项目文件路由把
|
|
70
|
+
* 「不等于 `private`」一律当 public 直连(`routes.ts` 的 `meta.visibility === 'private'` 分支)。
|
|
71
|
+
* 放过一个 `'PUBLIC'` / `'privte'` 拼写就等于**把私有文件变成公开**——必须在写入前拒绝,
|
|
72
|
+
* 不能靠下游「看起来像 public 就直连」的兜底。
|
|
73
|
+
*/
|
|
74
|
+
export declare function assertFileVisibility(value: unknown): FileVisibility;
|
|
63
75
|
/**
|
|
64
76
|
* 路径穿越防护(验收 Scenario 4):拒绝绝对路径、`..` 段、空路径、Windows 盘符、控制字符。
|
|
65
77
|
* 合法路径为单层或多层相对段(如 `a`、`a/b.png`),每段不能是 `.`/`..`、空或含路径分隔符。
|
|
@@ -6,10 +6,49 @@ export interface DownloadSignerConfig {
|
|
|
6
6
|
}
|
|
7
7
|
/** M1 签名有效期(PRD §2.4 / ST-001 任务单:15 分钟)。 */
|
|
8
8
|
export declare const DEFAULT_SIGN_TTL_SECONDS: number;
|
|
9
|
+
/**
|
|
10
|
+
* 私有签名 URL 的最长有效期(ST-005):7 天。
|
|
11
|
+
*
|
|
12
|
+
* 签名 URL 的语义是「临时访问」,不设上限时调用方传 1 年就得到 1 年有效的外链——
|
|
13
|
+
* 链接一旦进聊天记录 / 剪贴板 / 日志就是长期可读。长期展示应把文件设为 `public`
|
|
14
|
+
* 并走无签名直链(`getUrl`);确需超长私有链接必须显式 `force`。
|
|
15
|
+
*/
|
|
16
|
+
export declare const MAX_SIGNED_URL_TTL_SECONDS: number;
|
|
9
17
|
export declare const SIGN_EXPIRES_KEY = "x-expires";
|
|
10
18
|
export declare const SIGN_SIGNATURE_KEY = "x-signature";
|
|
19
|
+
/**
|
|
20
|
+
* 校验并归一私有签名 TTL。
|
|
21
|
+
*
|
|
22
|
+
* 非正整数一律拒绝(`0` / 负数此前会生成「一出生就过期」的链接,静默无效);
|
|
23
|
+
* 超过上限且未显式 `force` 拒绝,文案给出 public + getUrl 的替代路径。
|
|
24
|
+
*/
|
|
25
|
+
export declare function resolveSignedUrlTtl(ttlSeconds: number | undefined, options?: {
|
|
26
|
+
force?: boolean;
|
|
27
|
+
}): number;
|
|
28
|
+
/**
|
|
29
|
+
* 公共文件直链(无签名;下载端不校验)。路径整段编码(`/` → `%2F`),对齐 `:path` 单段路由。
|
|
30
|
+
*
|
|
31
|
+
* 这是**项目桶命名空间**的外壳;云应用桶的外壳是
|
|
32
|
+
* `/api/v1/cloud/storage/raw/:key`(`server/domains/cloud/storage.ts`),
|
|
33
|
+
* 两者签名各自绑定 `(bucket, path)`、不可互换——见 ADR-0034。
|
|
34
|
+
*/
|
|
35
|
+
export declare function publicDownloadUrl(config: DownloadSignerConfig, projectId: string, path: string): string;
|
|
36
|
+
/**
|
|
37
|
+
* 生成私有文件的外链(含签名查询参数),并返回签名内的过期时刻(unix 秒)。
|
|
38
|
+
*
|
|
39
|
+
* 与 `signDownloadUrl` 同一份计算:`getUrl` 需要把「URL 会何时失效」显式告诉调用方
|
|
40
|
+
* (`expiresAt`),不能另算一遍时间(两次 `Date.now()` 可能跨秒)。
|
|
41
|
+
*/
|
|
42
|
+
export declare function signDownloadUrlWithExpiry(config: DownloadSignerConfig, projectId: string, path: string, ttlSeconds?: number, options?: {
|
|
43
|
+
force?: boolean;
|
|
44
|
+
}): {
|
|
45
|
+
url: string;
|
|
46
|
+
expires: number;
|
|
47
|
+
};
|
|
11
48
|
/** 生成私有文件的外链(含签名查询参数)。 */
|
|
12
|
-
export declare function signDownloadUrl(config: DownloadSignerConfig, projectId: string, path: string, ttlSeconds?: number
|
|
49
|
+
export declare function signDownloadUrl(config: DownloadSignerConfig, projectId: string, path: string, ttlSeconds?: number, options?: {
|
|
50
|
+
force?: boolean;
|
|
51
|
+
}): string;
|
|
13
52
|
export type SignatureVerification = {
|
|
14
53
|
ok: true;
|
|
15
54
|
} | {
|
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.10",
|
|
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.3"
|
|
36
36
|
},
|
|
37
37
|
"scripts": {
|
|
38
38
|
"test": "vitest run",
|