@lark-base-open/base-database-toolchain 1.2.0 → 1.3.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.
@@ -0,0 +1,490 @@
1
+ import { RE2JS } from 're2js';
2
+ import { checkParameterDescription, } from './function-params.js';
3
+ const JSON_SCHEMA_DRAFT_2020_12 = 'https://json-schema.org/draft/2020-12/schema';
4
+ const MAX_SCHEMA_BYTES = 32 * 1024;
5
+ const MAX_SCHEMA_DEPTH = 16;
6
+ const MAX_SCHEMA_NODES = 256;
7
+ const ALLOWED_TYPES = new Set([
8
+ 'object',
9
+ 'array',
10
+ 'string',
11
+ 'integer',
12
+ 'number',
13
+ 'boolean',
14
+ 'null',
15
+ ]);
16
+ const ALLOWED_KEYWORDS = new Set([
17
+ '$schema',
18
+ 'type',
19
+ 'description',
20
+ 'properties',
21
+ 'required',
22
+ 'additionalProperties',
23
+ 'items',
24
+ 'prefixItems',
25
+ 'minItems',
26
+ 'maxItems',
27
+ 'enum',
28
+ 'minimum',
29
+ 'maximum',
30
+ 'minLength',
31
+ 'maxLength',
32
+ 'oneOf',
33
+ 'anyOf',
34
+ 'pattern',
35
+ 'default',
36
+ ]);
37
+ const SQL_SCALAR_PARAM_KINDS = new Set([
38
+ 'TEXT',
39
+ 'INT',
40
+ 'DOUBLE',
41
+ 'BOOL',
42
+ 'TIMESTAMP',
43
+ 'INTERVAL',
44
+ 'USER',
45
+ 'CHAT',
46
+ 'FILE',
47
+ 'OPTION',
48
+ 'URL',
49
+ 'LOCATION',
50
+ ]);
51
+ // 复合参数按成员声明对象 schema,与服务端参数绑定一致;未知成员一律拒绝,
52
+ // 成员为 null 视为未提供(例如 USER/CHAT 的 name 由服务端补齐)。
53
+ const COMPOSITE_PARAM_MEMBERS = {
54
+ USER: { id: 'string', name: 'string', avatarUrl: 'string' },
55
+ CHAT: { id: 'string', name: 'string' },
56
+ FILE: {
57
+ token: 'string',
58
+ name: 'string',
59
+ mime_type: 'string',
60
+ size: 'integer',
61
+ },
62
+ OPTION: { id: 'string', name: 'string' },
63
+ URL: { text: 'string', link: 'string' },
64
+ LOCATION: { address: 'string', lng: 'number', lat: 'number' },
65
+ };
66
+ const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER;
67
+ function isRecord(value) {
68
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
69
+ }
70
+ function schemaError(path, message) {
71
+ throw new Error(`Invalid inputSchema at ${path}: ${message}`);
72
+ }
73
+ function schemaTypes(value, path) {
74
+ if (value.type === undefined &&
75
+ (value.oneOf !== undefined || value.anyOf !== undefined))
76
+ return [];
77
+ const rawType = value.type;
78
+ const types = typeof rawType === 'string' ? [rawType] : rawType;
79
+ if (!Array.isArray(types) || types.length === 0) {
80
+ schemaError(path, 'type must be a supported string or non-empty array');
81
+ }
82
+ const seen = new Set();
83
+ for (const type of types) {
84
+ if (typeof type !== 'string' || !ALLOWED_TYPES.has(type)) {
85
+ schemaError(path, 'type must contain only supported strings');
86
+ }
87
+ if (seen.has(type)) {
88
+ schemaError(path, `type contains duplicate ${JSON.stringify(type)}`);
89
+ }
90
+ seen.add(type);
91
+ }
92
+ return [...seen];
93
+ }
94
+ function validateNonNegativeInteger(schema, key, path) {
95
+ const value = schema[key];
96
+ if (value !== undefined &&
97
+ (typeof value !== 'number' || !Number.isInteger(value) || value < 0)) {
98
+ schemaError(path, `${key} must be a non-negative integer`);
99
+ }
100
+ }
101
+ function validateSchemaNode(value, path, depth, state) {
102
+ if (!isRecord(value))
103
+ schemaError(path, 'must be a schema object');
104
+ if (depth > MAX_SCHEMA_DEPTH) {
105
+ schemaError(path, `depth exceeds ${MAX_SCHEMA_DEPTH}`);
106
+ }
107
+ state.nodes += 1;
108
+ if (state.nodes > MAX_SCHEMA_NODES) {
109
+ schemaError(path, `nodes exceed ${MAX_SCHEMA_NODES}`);
110
+ }
111
+ for (const keyword of Object.keys(value)) {
112
+ if (!ALLOWED_KEYWORDS.has(keyword)) {
113
+ schemaError(path, `unsupported keyword ${JSON.stringify(keyword)}`);
114
+ }
115
+ }
116
+ if (value.$schema !== undefined &&
117
+ value.$schema !== JSON_SCHEMA_DRAFT_2020_12) {
118
+ schemaError(path, `$schema must be ${JSON.stringify(JSON_SCHEMA_DRAFT_2020_12)}`);
119
+ }
120
+ const types = schemaTypes(value, path);
121
+ for (const key of ['oneOf', 'anyOf']) {
122
+ const branches = value[key];
123
+ if (branches === undefined)
124
+ continue;
125
+ if (!Array.isArray(branches) || branches.length === 0)
126
+ schemaError(path, `${key} must be a non-empty schema array`);
127
+ branches.forEach((child, index) => validateSchemaNode(child, `${path}.${key}[${index}]`, depth + 1, state));
128
+ }
129
+ if (value.pattern !== undefined) {
130
+ if (typeof value.pattern !== 'string')
131
+ schemaError(path, 'pattern must be a string');
132
+ try {
133
+ RE2JS.compile(value.pattern);
134
+ }
135
+ catch {
136
+ schemaError(path, 'pattern must be a valid RE2 expression');
137
+ }
138
+ }
139
+ if (value.description !== undefined &&
140
+ typeof value.description !== 'string') {
141
+ schemaError(path, 'description must be a string');
142
+ }
143
+ if (value.enum !== undefined &&
144
+ (!Array.isArray(value.enum) || value.enum.length === 0)) {
145
+ schemaError(path, 'enum must be a non-empty array');
146
+ }
147
+ const objectKeywords = ['properties', 'required', 'additionalProperties'];
148
+ const arrayKeywords = ['items', 'prefixItems', 'minItems', 'maxItems'];
149
+ const stringKeywords = ['minLength', 'maxLength', 'pattern'];
150
+ const numberKeywords = ['minimum', 'maximum'];
151
+ for (const key of objectKeywords) {
152
+ if (value[key] !== undefined && !types.includes('object')) {
153
+ schemaError(path, `${key} requires type object`);
154
+ }
155
+ }
156
+ for (const key of arrayKeywords) {
157
+ if (value[key] !== undefined && !types.includes('array')) {
158
+ schemaError(path, `${key} requires type array`);
159
+ }
160
+ }
161
+ for (const key of stringKeywords) {
162
+ if (value[key] !== undefined && !types.includes('string')) {
163
+ schemaError(path, `${key} requires type string`);
164
+ }
165
+ }
166
+ for (const key of numberKeywords) {
167
+ if (value[key] !== undefined &&
168
+ !types.includes('integer') &&
169
+ !types.includes('number')) {
170
+ schemaError(path, `${key} requires numeric type`);
171
+ }
172
+ }
173
+ if (value.properties !== undefined) {
174
+ if (!isRecord(value.properties)) {
175
+ schemaError(path, 'properties must be an object');
176
+ }
177
+ for (const [name, child] of Object.entries(value.properties)) {
178
+ validateSchemaNode(child, `${path}.properties[${JSON.stringify(name)}]`, depth + 1, state);
179
+ }
180
+ }
181
+ if (value.required !== undefined) {
182
+ if (!Array.isArray(value.required)) {
183
+ schemaError(path, 'required must be an array');
184
+ }
185
+ const required = new Set();
186
+ for (const name of value.required) {
187
+ if (typeof name !== 'string' || name === '') {
188
+ schemaError(path, 'required entries must be non-empty strings');
189
+ }
190
+ if (required.has(name)) {
191
+ schemaError(path, `required contains duplicate ${JSON.stringify(name)}`);
192
+ }
193
+ required.add(name);
194
+ }
195
+ }
196
+ if (value.additionalProperties !== undefined &&
197
+ typeof value.additionalProperties !== 'boolean') {
198
+ schemaError(path, 'additionalProperties must be a boolean');
199
+ }
200
+ if (value.items !== undefined) {
201
+ validateSchemaNode(value.items, `${path}.items`, depth + 1, state);
202
+ }
203
+ if (value.prefixItems !== undefined) {
204
+ if (!Array.isArray(value.prefixItems)) {
205
+ schemaError(path, 'prefixItems must be an array');
206
+ }
207
+ value.prefixItems.forEach((child, index) => {
208
+ validateSchemaNode(child, `${path}.prefixItems[${index}]`, depth + 1, state);
209
+ });
210
+ }
211
+ for (const key of ['minItems', 'maxItems', 'minLength', 'maxLength']) {
212
+ validateNonNegativeInteger(value, key, path);
213
+ }
214
+ for (const key of ['minimum', 'maximum']) {
215
+ const number = value[key];
216
+ if (number !== undefined &&
217
+ (typeof number !== 'number' || !Number.isFinite(number))) {
218
+ schemaError(path, `${key} must be a finite number`);
219
+ }
220
+ }
221
+ for (const [minimumKey, maximumKey] of [
222
+ ['minItems', 'maxItems'],
223
+ ['minLength', 'maxLength'],
224
+ ]) {
225
+ const minimum = value[minimumKey];
226
+ const maximum = value[maximumKey];
227
+ if (typeof minimum === 'number' &&
228
+ typeof maximum === 'number' &&
229
+ minimum > maximum) {
230
+ schemaError(path, `${minimumKey} cannot exceed ${maximumKey}`);
231
+ }
232
+ }
233
+ if (typeof value.minimum === 'number' &&
234
+ typeof value.maximum === 'number' &&
235
+ value.minimum > value.maximum) {
236
+ schemaError(path, 'minimum cannot exceed maximum');
237
+ }
238
+ }
239
+ export function normalizeFunctionInputSchema(value, source) {
240
+ const schema = JSON.stringify(value);
241
+ validateSchemaNode(JSON.parse(schema), source, 1, { nodes: 0 });
242
+ if (Buffer.byteLength(schema, 'utf8') > MAX_SCHEMA_BYTES) {
243
+ schemaError(source, 'exceeds 32 KiB');
244
+ }
245
+ return schema;
246
+ }
247
+ function parseSQLParamKind(kind, index) {
248
+ const isArray = kind.endsWith('[]');
249
+ const scalarKind = isArray ? kind.slice(0, -2) : kind;
250
+ if (!SQL_SCALAR_PARAM_KINDS.has(scalarKind)) {
251
+ throw new Error(`Unsupported Database Function query parameter kind at index ${index}: ${kind}`);
252
+ }
253
+ return { scalarKind, isArray };
254
+ }
255
+ function sqlScalarParamSchema(kind, inputDescription, index) {
256
+ let schema;
257
+ let description = inputDescription;
258
+ switch (kind) {
259
+ case 'TEXT':
260
+ schema = { type: ['string', 'null'] };
261
+ break;
262
+ case 'INT':
263
+ schema = {
264
+ type: ['integer', 'null'],
265
+ minimum: -MAX_SAFE_INTEGER,
266
+ maximum: MAX_SAFE_INTEGER,
267
+ };
268
+ break;
269
+ case 'DOUBLE':
270
+ schema = { type: ['number', 'null'] };
271
+ break;
272
+ case 'BOOL':
273
+ schema = { type: ['boolean', 'null'] };
274
+ break;
275
+ case 'TIMESTAMP':
276
+ schema = {
277
+ type: ['string', 'integer', 'null'],
278
+ minimum: -MAX_SAFE_INTEGER,
279
+ maximum: MAX_SAFE_INTEGER,
280
+ };
281
+ description = description
282
+ ? `${description} (RFC 3339 string, local YYYY-MM-DD HH:mm:ss.SSS string in the Base execution time zone, or Unix epoch milliseconds)`
283
+ : `$${index + 1}, RFC 3339 string, local YYYY-MM-DD HH:mm:ss.SSS string in the Base execution time zone, or Unix epoch milliseconds`;
284
+ break;
285
+ case 'INTERVAL':
286
+ schema = { type: ['string', 'null'] };
287
+ description = description
288
+ ? `${description} (BaseSQL fixed interval string: <number> <unit>, unit = ms/millisecond(s)/second(s)/sec(s)/minute(s)/min(s)/hour(s)/day(s)/week(s), exactly representable as integer milliseconds)`
289
+ : `$${index + 1}, BaseSQL fixed interval string: <number> <unit>, unit = ms/millisecond(s)/second(s)/sec(s)/minute(s)/min(s)/hour(s)/day(s)/week(s), exactly representable as integer milliseconds`;
290
+ break;
291
+ default: {
292
+ const members = COMPOSITE_PARAM_MEMBERS[kind];
293
+ if (!members)
294
+ throw new Error(`Unsupported scalar parameter kind: ${kind}`);
295
+ schema = {
296
+ type: ['object', 'null'],
297
+ properties: Object.fromEntries(Object.entries(members).map(([name, type]) => [
298
+ name,
299
+ kind === 'FILE' && name === 'size'
300
+ ? {
301
+ type: [type, 'null'],
302
+ minimum: -MAX_SAFE_INTEGER,
303
+ maximum: MAX_SAFE_INTEGER,
304
+ }
305
+ : { type: [type, 'null'] },
306
+ ])),
307
+ additionalProperties: false,
308
+ };
309
+ }
310
+ }
311
+ return description ? { ...schema, description } : schema;
312
+ }
313
+ export function sqlParamSchema(param, index) {
314
+ const { scalarKind, isArray } = parseSQLParamKind(param.kind, index);
315
+ const description = param.description?.trim() ?? '';
316
+ // SQL scalars and elements stay nullable on the positional route; keep null beside the declared options.
317
+ const values = Array.isArray(param.enum)
318
+ ? { enum: [...param.enum, null] }
319
+ : {};
320
+ const scalarSchema = {
321
+ ...sqlScalarParamSchema(scalarKind, '', index),
322
+ ...(isArray ? values : {}),
323
+ };
324
+ if (!isArray) {
325
+ return {
326
+ ...sqlScalarParamSchema(scalarKind, description, index),
327
+ ...values,
328
+ };
329
+ }
330
+ return {
331
+ type: ['array', 'null'],
332
+ items: scalarSchema,
333
+ ...(description === '' ? {} : { description }),
334
+ };
335
+ }
336
+ /** Named-route declaration projection; mirrors the server's nullable/range/enum semantics. */
337
+ export function namedSQLParamSchema(param, index) {
338
+ const { scalarKind, isArray } = parseSQLParamKind(String(param.kind), index);
339
+ let scalar = sqlScalarParamSchema(scalarKind, '', index);
340
+ const nullable = param.nullable !== false;
341
+ if (!nullable && Array.isArray(scalar.type)) {
342
+ const types = scalar.type.filter((t) => t !== 'null');
343
+ scalar.type = types.length === 1 ? types[0] : types;
344
+ }
345
+ for (const key of ['minimum', 'maximum'])
346
+ if (param[key] !== undefined)
347
+ scalar[key] = param[key];
348
+ if (Array.isArray(param.enum)) {
349
+ if (Array.isArray(scalar.type))
350
+ scalar.type = scalar.type.filter((t) => t !== 'null');
351
+ scalar.enum = param.enum;
352
+ if (nullable)
353
+ scalar = { anyOf: [{ type: 'null' }, scalar] };
354
+ }
355
+ return {
356
+ ...(isArray
357
+ ? { type: nullable ? ['array', 'null'] : 'array', items: scalar }
358
+ : scalar),
359
+ ...(typeof param.description === 'string'
360
+ ? { description: param.description }
361
+ : {}),
362
+ };
363
+ }
364
+ function sqlPlaceholderIndexes(sql) {
365
+ const indexes = new Set();
366
+ let mode = 'normal';
367
+ for (let index = 0; index < sql.length; index += 1) {
368
+ const char = sql[index];
369
+ const next = sql[index + 1];
370
+ if (mode === 'line-comment') {
371
+ if (char === '\n')
372
+ mode = 'normal';
373
+ continue;
374
+ }
375
+ if (mode === 'block-comment') {
376
+ if (char === '*' && next === '/') {
377
+ mode = 'normal';
378
+ index += 1;
379
+ }
380
+ continue;
381
+ }
382
+ if (mode === 'single') {
383
+ if (char === "'" && next === "'") {
384
+ index += 1;
385
+ }
386
+ else if (char === "'") {
387
+ mode = 'normal';
388
+ }
389
+ continue;
390
+ }
391
+ if (mode === 'double') {
392
+ if (char === '"' && next === '"') {
393
+ index += 1;
394
+ }
395
+ else if (char === '"') {
396
+ mode = 'normal';
397
+ }
398
+ continue;
399
+ }
400
+ if (char === '-' && next === '-') {
401
+ mode = 'line-comment';
402
+ index += 1;
403
+ }
404
+ else if (char === '/' && next === '*') {
405
+ mode = 'block-comment';
406
+ index += 1;
407
+ }
408
+ else if (char === "'") {
409
+ mode = 'single';
410
+ }
411
+ else if (char === '"') {
412
+ mode = 'double';
413
+ }
414
+ else if (char === '$' && next !== undefined && /[0-9]/.test(next)) {
415
+ let end = index + 1;
416
+ while (end < sql.length && /[0-9]/.test(sql[end] ?? ''))
417
+ end += 1;
418
+ const placeholder = Number(sql.slice(index + 1, end));
419
+ if (!Number.isSafeInteger(placeholder) || placeholder < 1) {
420
+ throw new Error(`Invalid query placeholder: ${sql.slice(index, end)}`);
421
+ }
422
+ indexes.add(placeholder);
423
+ index = end - 1;
424
+ }
425
+ }
426
+ return indexes;
427
+ }
428
+ function validateSQLPlaceholders(sql, paramCount) {
429
+ const placeholders = sqlPlaceholderIndexes(sql);
430
+ if (placeholders.size !== paramCount) {
431
+ throw new Error(`Query placeholders and meta.params must both contain exactly ${paramCount} item(s)`);
432
+ }
433
+ for (let index = 1; index <= paramCount; index += 1) {
434
+ if (!placeholders.has(index)) {
435
+ throw new Error(`Query placeholder $${index} is missing`);
436
+ }
437
+ }
438
+ }
439
+ /**
440
+ * Local Page input contract for the positional `invoke_function` route.
441
+ * It is never uploaded: the service renders the Agent-facing named-object
442
+ * inputSchema from `meta.params` itself.
443
+ */
444
+ export function deriveSQLInputSchema(meta, sql) {
445
+ const rawParams = meta.params ?? [];
446
+ if (!Array.isArray(rawParams)) {
447
+ throw new Error('Database Function meta.params must be an array');
448
+ }
449
+ const params = rawParams.map((value, index) => {
450
+ if (!isRecord(value) || typeof value.kind !== 'string') {
451
+ throw new Error(`Database Function meta.params[${index}].kind must be a string`);
452
+ }
453
+ if (value.description !== undefined &&
454
+ typeof value.description !== 'string') {
455
+ throw new Error(`Database Function meta.params[${index}].description must be a string`);
456
+ }
457
+ return {
458
+ kind: value.kind,
459
+ description: value.description,
460
+ ...(Array.isArray(value.enum) ? { enum: value.enum } : {}),
461
+ };
462
+ });
463
+ validateSQLPlaceholders(sql, params.length);
464
+ return JSON.stringify({
465
+ $schema: JSON_SCHEMA_DRAFT_2020_12,
466
+ type: 'array',
467
+ description: 'Database Function parameters in $1, $2 order',
468
+ prefixItems: params.map(sqlParamSchema),
469
+ minItems: params.length,
470
+ maxItems: params.length,
471
+ });
472
+ }
473
+ /**
474
+ * FaaS discovery contract on top of the Schema subset: the root is an object and
475
+ * every top-level business property (its key is the parameter name) carries a
476
+ * non-blank description. Short descriptions are hints only.
477
+ */
478
+ export function checkFaaSInputSchemaContract(value, file) {
479
+ const result = { problems: [], hints: [] };
480
+ if (!isRecord(value) || value.type !== 'object') {
481
+ result.problems.push('inputSchema.type must be "object"');
482
+ return result;
483
+ }
484
+ const properties = isRecord(value.properties) ? value.properties : {};
485
+ for (const [key, child] of Object.entries(properties)) {
486
+ const label = `inputSchema.properties[${JSON.stringify(key)}]`;
487
+ checkParameterDescription(isRecord(child) ? child.description : undefined, label, `${file}#/inputSchema/properties/${key.replaceAll('~', '~0').replaceAll('/', '~1')}/description`, result);
488
+ }
489
+ return result;
490
+ }
@@ -8,4 +8,4 @@ export declare function runCompiler(request: any): Promise<{
8
8
  ok: boolean;
9
9
  operation: any;
10
10
  warnings?: any[] | undefined;
11
- }>;
11
+ } | undefined>;