@lark-base-open/base-database-toolchain 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/LICENSE +6 -0
- package/README.md +48 -2
- package/bin/base-database-toolchain.mjs +22 -0
- package/dist/app-builder/core.d.mts +37 -0
- package/dist/app-builder/core.mjs +716 -0
- package/dist/app-builder/package.json +1 -0
- package/dist/app-builder/schema.d.ts +3 -0
- package/dist/app-builder/schema.js +71 -0
- package/dist/contract-conversion.d.ts +41 -0
- package/dist/contract-conversion.js +116 -0
- package/dist/contract-extractor.d.ts +23 -0
- package/dist/contract-extractor.js +245 -0
- package/dist/durable-runner.d.ts +102 -0
- package/dist/durable-runner.js +128 -0
- package/dist/go-adapter.d.mts +4 -0
- package/dist/go-adapter.mjs +776 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -0
- package/dist/sdk-codegen.d.ts +16 -0
- package/dist/sdk-codegen.js +208 -0
- package/dist/trigger-validation.d.ts +75 -0
- package/dist/trigger-validation.js +73 -0
- package/npm-shrinkwrap.json +1167 -0
- package/package.json +73 -4
|
@@ -0,0 +1,776 @@
|
|
|
1
|
+
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
// This worker compiles application TypeScript and schemas. All API requests,
|
|
4
|
+
// authentication, source archives and publication state belong to the Go host.
|
|
5
|
+
import * as fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { createRequire } from 'node:module';
|
|
8
|
+
import { execFileSync } from 'node:child_process';
|
|
9
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
10
|
+
import { build } from 'esbuild';
|
|
11
|
+
import { parse } from '@babel/parser';
|
|
12
|
+
import Ajv2020 from 'ajv/dist/2020.js';
|
|
13
|
+
import { validateTriggerDeclarations } from './trigger-validation.js';
|
|
14
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
15
|
+
import { driveLocalDurable } from './durable-runner.js';
|
|
16
|
+
import { buildProject } from './app-builder/core.mjs';
|
|
17
|
+
import { runSDKCodegen } from './sdk-codegen.js';
|
|
18
|
+
export async function runCompiler(request) {
|
|
19
|
+
if (request.protocolVersion !== 1)
|
|
20
|
+
throw Error('Unsupported compiler protocol version');
|
|
21
|
+
if (!path.isAbsolute(request.root) ||
|
|
22
|
+
!['server', 'server-functions'].includes(request.server))
|
|
23
|
+
throw Error('Invalid compiler project layout');
|
|
24
|
+
const triggerIDs = new Set();
|
|
25
|
+
const triggerLocations = [];
|
|
26
|
+
let triggerCount = 0;
|
|
27
|
+
const permissionFlag = process.allowedNodeEnvironmentFlags.has('--permission')
|
|
28
|
+
? '--permission'
|
|
29
|
+
: '--experimental-permission';
|
|
30
|
+
const { root, server, operation } = request;
|
|
31
|
+
const serverRoot = path.join(root, server);
|
|
32
|
+
const stateRoot = safe(request.stateDirectory);
|
|
33
|
+
const requireProject = createRequire(path.join(serverRoot, 'package.json'));
|
|
34
|
+
const readJSON = (file) => JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
35
|
+
const writeJSON = (file, data) => save(file, JSON.stringify(data, null, 2) + '\n');
|
|
36
|
+
const digest = (data) => createHash('sha256').update(data).digest('hex');
|
|
37
|
+
function safe(file) {
|
|
38
|
+
const full = path.resolve(root, file);
|
|
39
|
+
if (full !== root && !full.startsWith(root + path.sep))
|
|
40
|
+
throw Error('Compiler output escapes project');
|
|
41
|
+
let part = full;
|
|
42
|
+
while (part.startsWith(root) && part !== root) {
|
|
43
|
+
if (fs.existsSync(part) && fs.lstatSync(part).isSymbolicLink())
|
|
44
|
+
throw Error('Compiler path is a link');
|
|
45
|
+
part = path.dirname(part);
|
|
46
|
+
}
|
|
47
|
+
return full;
|
|
48
|
+
}
|
|
49
|
+
function save(file, content) {
|
|
50
|
+
file = safe(file);
|
|
51
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
52
|
+
const temporary = file + '.' + randomUUID() + '.tmp';
|
|
53
|
+
fs.writeFileSync(temporary, content, { flag: 'wx', mode: 0o600 });
|
|
54
|
+
fs.renameSync(temporary, file);
|
|
55
|
+
}
|
|
56
|
+
function entries(directory) {
|
|
57
|
+
if (!fs.existsSync(directory))
|
|
58
|
+
return [];
|
|
59
|
+
return fs
|
|
60
|
+
.readdirSync(directory, { withFileTypes: true })
|
|
61
|
+
.filter((e) => e.isDirectory())
|
|
62
|
+
.map((e) => e.name)
|
|
63
|
+
.sort();
|
|
64
|
+
}
|
|
65
|
+
function runNode(file, args, cwd) {
|
|
66
|
+
execFileSync(process.execPath, [file, ...args], {
|
|
67
|
+
cwd,
|
|
68
|
+
env: process.env,
|
|
69
|
+
stdio: ['ignore', 2, 2],
|
|
70
|
+
timeout: 15 * 60 * 1000,
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
function unwrap(node) {
|
|
74
|
+
while (node &&
|
|
75
|
+
[
|
|
76
|
+
'TSAsExpression',
|
|
77
|
+
'TSSatisfiesExpression',
|
|
78
|
+
'TSNonNullExpression',
|
|
79
|
+
'ParenthesizedExpression',
|
|
80
|
+
].includes(node.type))
|
|
81
|
+
node = node.expression;
|
|
82
|
+
return node;
|
|
83
|
+
}
|
|
84
|
+
function definition(entry) {
|
|
85
|
+
const ast = parse(fs.readFileSync(entry, 'utf8'), {
|
|
86
|
+
sourceType: 'module',
|
|
87
|
+
plugins: ['typescript', 'jsx'],
|
|
88
|
+
});
|
|
89
|
+
const names = new Map(), namespaces = new Set();
|
|
90
|
+
for (const s of ast.program.body)
|
|
91
|
+
if (s.type === 'ImportDeclaration') {
|
|
92
|
+
for (const item of s.specifiers) {
|
|
93
|
+
if (item.type === 'ImportSpecifier')
|
|
94
|
+
names.set(item.local.name, {
|
|
95
|
+
from: s.source.value,
|
|
96
|
+
name: item.imported.name,
|
|
97
|
+
});
|
|
98
|
+
if (item.type === 'ImportNamespaceSpecifier' &&
|
|
99
|
+
s.source.value === '@lark-base-open/base-database-app-sdk/server')
|
|
100
|
+
namespaces.add(item.local.name);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
let exp = unwrap(ast.program.body.find((s) => s.type === 'ExportDefaultDeclaration')
|
|
104
|
+
?.declaration);
|
|
105
|
+
if (exp?.type === 'Identifier') {
|
|
106
|
+
exp = unwrap(ast.program.body
|
|
107
|
+
.flatMap((s) => s.type === 'VariableDeclaration' ? s.declarations : [])
|
|
108
|
+
.find((d) => d.id.name === exp.name)?.init);
|
|
109
|
+
}
|
|
110
|
+
if (exp?.type !== 'CallExpression')
|
|
111
|
+
return null;
|
|
112
|
+
const callee = exp.callee.type === 'MemberExpression' &&
|
|
113
|
+
!exp.callee.computed &&
|
|
114
|
+
namespaces.has(exp.callee.object.name)
|
|
115
|
+
? {
|
|
116
|
+
from: '@lark-base-open/base-database-app-sdk/server',
|
|
117
|
+
name: exp.callee.property.name,
|
|
118
|
+
}
|
|
119
|
+
: names.get(exp.callee.name);
|
|
120
|
+
if (callee?.from !== '@lark-base-open/base-database-app-sdk/server' ||
|
|
121
|
+
!['defineFunction', 'defineDurableFunction'].includes(callee.name))
|
|
122
|
+
return null;
|
|
123
|
+
const argument = exp.arguments[0];
|
|
124
|
+
if (exp.arguments.length !== 1 || argument?.type !== 'ObjectExpression')
|
|
125
|
+
throw Error('Function must have one literal declaration');
|
|
126
|
+
const fields = {};
|
|
127
|
+
for (const p of argument.properties) {
|
|
128
|
+
const key = p.key?.name ?? p.key?.value;
|
|
129
|
+
if (['input', 'output', 'events'].includes(key)) {
|
|
130
|
+
const imported = names.get(p.value?.name);
|
|
131
|
+
if (!imported || !/^\.\/contract(?:\.ts|\.js)?$/.test(imported.from))
|
|
132
|
+
throw Error('Schemas must be imported from ./contract');
|
|
133
|
+
fields[key] = imported.name;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
if (!fields.input || !fields.output)
|
|
137
|
+
throw Error('Function requires input and output schemas');
|
|
138
|
+
return { kind: callee.name, fields };
|
|
139
|
+
}
|
|
140
|
+
// Parameter projections preserve the SQL and Mutation input contracts.
|
|
141
|
+
function sqlScalarSchema(kind, index) {
|
|
142
|
+
const members = {
|
|
143
|
+
USER: { id: 'string', name: 'string', avatarUrl: 'string' },
|
|
144
|
+
CHAT: { id: 'string', name: 'string' },
|
|
145
|
+
FILE: {
|
|
146
|
+
token: 'string',
|
|
147
|
+
name: 'string',
|
|
148
|
+
mime_type: 'string',
|
|
149
|
+
size: 'integer',
|
|
150
|
+
},
|
|
151
|
+
OPTION: { id: 'string', name: 'string' },
|
|
152
|
+
URL: { text: 'string', link: 'string' },
|
|
153
|
+
LOCATION: { address: 'string', lng: 'number', lat: 'number' },
|
|
154
|
+
};
|
|
155
|
+
const limit = {
|
|
156
|
+
minimum: -Number.MAX_SAFE_INTEGER,
|
|
157
|
+
maximum: Number.MAX_SAFE_INTEGER,
|
|
158
|
+
};
|
|
159
|
+
switch (kind) {
|
|
160
|
+
case 'TEXT':
|
|
161
|
+
case 'INTERVAL':
|
|
162
|
+
return { type: ['string', 'null'] };
|
|
163
|
+
case 'INT':
|
|
164
|
+
return { type: ['integer', 'null'], ...limit };
|
|
165
|
+
case 'DOUBLE':
|
|
166
|
+
return { type: ['number', 'null'] };
|
|
167
|
+
case 'BOOL':
|
|
168
|
+
return { type: ['boolean', 'null'] };
|
|
169
|
+
case 'TIMESTAMP':
|
|
170
|
+
return { type: ['string', 'integer', 'null'], ...limit };
|
|
171
|
+
default:
|
|
172
|
+
if (!members[kind])
|
|
173
|
+
throw Error('Unsupported SQL parameter kind at index ' + index + ': ' + kind);
|
|
174
|
+
return {
|
|
175
|
+
type: ['object', 'null'],
|
|
176
|
+
properties: Object.fromEntries(Object.entries(members[kind]).map(([name, type]) => [
|
|
177
|
+
name,
|
|
178
|
+
{
|
|
179
|
+
type: [type, 'null'],
|
|
180
|
+
...(kind === 'FILE' && name === 'size' ? limit : {}),
|
|
181
|
+
},
|
|
182
|
+
])),
|
|
183
|
+
additionalProperties: false,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
function parameterSchema(param, type, index) {
|
|
188
|
+
let schema;
|
|
189
|
+
if (type === 1) {
|
|
190
|
+
const array = param.kind.endsWith('[]'), kind = array ? param.kind.slice(0, -2) : param.kind;
|
|
191
|
+
let scalar = sqlScalarSchema(kind, index);
|
|
192
|
+
const nullable = param.nullable !== false;
|
|
193
|
+
if (!nullable) {
|
|
194
|
+
const types = scalar.type.filter((t) => t !== 'null');
|
|
195
|
+
scalar.type = types.length === 1 ? types[0] : types;
|
|
196
|
+
}
|
|
197
|
+
for (const key of ['minimum', 'maximum'])
|
|
198
|
+
if (param[key] !== undefined)
|
|
199
|
+
scalar[key] = param[key];
|
|
200
|
+
if (Array.isArray(param.enum)) {
|
|
201
|
+
if (Array.isArray(scalar.type))
|
|
202
|
+
scalar.type = scalar.type.filter((t) => t !== 'null');
|
|
203
|
+
scalar.enum = param.enum;
|
|
204
|
+
if (nullable)
|
|
205
|
+
scalar = { anyOf: [{ type: 'null' }, scalar] };
|
|
206
|
+
}
|
|
207
|
+
schema = array
|
|
208
|
+
? { type: nullable ? ['array', 'null'] : 'array', items: scalar }
|
|
209
|
+
: scalar;
|
|
210
|
+
}
|
|
211
|
+
else {
|
|
212
|
+
const kind = param.kind;
|
|
213
|
+
const value = kind === 'BOOL'
|
|
214
|
+
? 'boolean'
|
|
215
|
+
: ['INT', 'DOUBLE', 'DURATION'].includes(kind)
|
|
216
|
+
? 'number'
|
|
217
|
+
: kind === 'ATTACHMENT'
|
|
218
|
+
? 'object'
|
|
219
|
+
: kind === 'TIMESTAMP'
|
|
220
|
+
? ['string', 'number']
|
|
221
|
+
: 'string';
|
|
222
|
+
schema = {
|
|
223
|
+
type: value,
|
|
224
|
+
...(Array.isArray(param.enum) ? { enum: param.enum } : {}),
|
|
225
|
+
};
|
|
226
|
+
if (param.list === true)
|
|
227
|
+
schema = {
|
|
228
|
+
type: 'array',
|
|
229
|
+
items: schema,
|
|
230
|
+
minItems: 0,
|
|
231
|
+
maxItems: param.maxItems ?? 200,
|
|
232
|
+
};
|
|
233
|
+
if (typeof param.description === 'string')
|
|
234
|
+
schema.description = param.description;
|
|
235
|
+
if (param.required === false)
|
|
236
|
+
schema = { anyOf: [schema, { type: 'null' }] };
|
|
237
|
+
}
|
|
238
|
+
if (typeof param.description === 'string')
|
|
239
|
+
schema.description = param.description;
|
|
240
|
+
return schema;
|
|
241
|
+
}
|
|
242
|
+
function validateParameter(p, type, id, params) {
|
|
243
|
+
if (typeof p.name !== 'string' ||
|
|
244
|
+
!/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(p.name) ||
|
|
245
|
+
typeof p.description !== 'string' ||
|
|
246
|
+
!p.description.trim() ||
|
|
247
|
+
params.filter((v) => v.name === p.name).length !== 1)
|
|
248
|
+
throw Error('Unique parameter names and nonblank descriptions are required: ' + id);
|
|
249
|
+
if (typeof p.kind !== 'string')
|
|
250
|
+
throw Error('Parameter kind is required: ' + id + '.' + p.name);
|
|
251
|
+
if (p.enum !== undefined) {
|
|
252
|
+
const kind = type === 1 ? p.kind.replace(/\[\]$/, '') : p.kind;
|
|
253
|
+
const primitive = [
|
|
254
|
+
'TEXT',
|
|
255
|
+
'INT',
|
|
256
|
+
'DOUBLE',
|
|
257
|
+
'BOOL',
|
|
258
|
+
...(type === 5 ? ['USER_ID', 'GROUP_ID', 'RECORD_ID'] : []),
|
|
259
|
+
];
|
|
260
|
+
if (!primitive.includes(kind) ||
|
|
261
|
+
!Array.isArray(p.enum) ||
|
|
262
|
+
p.enum.length < 1 ||
|
|
263
|
+
p.enum.length > 100 ||
|
|
264
|
+
new Set(p.enum.map((v) => JSON.stringify(v))).size !== p.enum.length ||
|
|
265
|
+
p.enum.some((v) => v === null ||
|
|
266
|
+
!((kind === 'BOOL' && typeof v === 'boolean') ||
|
|
267
|
+
(kind === 'INT' && Number.isSafeInteger(v)) ||
|
|
268
|
+
(kind === 'DOUBLE' &&
|
|
269
|
+
typeof v === 'number' &&
|
|
270
|
+
Number.isFinite(v)) ||
|
|
271
|
+
(!['BOOL', 'INT', 'DOUBLE'].includes(kind) &&
|
|
272
|
+
typeof v === 'string'))))
|
|
273
|
+
throw Error('Invalid parameter enum: ' + id + '.' + p.name);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
function legacyContracts(functions, inputs) {
|
|
277
|
+
for (const [directory, type] of [
|
|
278
|
+
[
|
|
279
|
+
fs.existsSync(path.join(root, 'database-functions'))
|
|
280
|
+
? 'database-functions'
|
|
281
|
+
: 'sql',
|
|
282
|
+
1,
|
|
283
|
+
],
|
|
284
|
+
['mutations', 5],
|
|
285
|
+
]) {
|
|
286
|
+
for (const id of entries(path.join(root, directory))) {
|
|
287
|
+
const metadata = readJSON(path.join(root, directory, id, 'meta.json'));
|
|
288
|
+
const params = type === 1
|
|
289
|
+
? (metadata.meta?.params ?? [])
|
|
290
|
+
: (readJSON(path.join(root, directory, id, 'spec.json')).params ??
|
|
291
|
+
[]);
|
|
292
|
+
const input = {
|
|
293
|
+
type: 'object',
|
|
294
|
+
properties: Object.fromEntries(params.map((p, index) => {
|
|
295
|
+
validateParameter(p, type, id, params);
|
|
296
|
+
return [p.name, parameterSchema(p, type, index)];
|
|
297
|
+
})),
|
|
298
|
+
required: params
|
|
299
|
+
.filter((p) => type === 1 || p.required !== false)
|
|
300
|
+
.map((p) => p.name),
|
|
301
|
+
additionalProperties: false,
|
|
302
|
+
};
|
|
303
|
+
functions.push({ functionId: id, functionType: type, input });
|
|
304
|
+
inputs.push({
|
|
305
|
+
functionId: id,
|
|
306
|
+
functionType: type,
|
|
307
|
+
inputSchema: input,
|
|
308
|
+
parameters: params,
|
|
309
|
+
parameterOptions: Object.fromEntries(params.filter((p) => p.enum).map((p) => [p.name, p.enum])),
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
function schemaType(schema) {
|
|
315
|
+
if (!schema || typeof schema !== 'object')
|
|
316
|
+
return 'unknown';
|
|
317
|
+
if (Array.isArray(schema.enum))
|
|
318
|
+
return schema.enum.map((v) => JSON.stringify(v)).join(' | ') || 'never';
|
|
319
|
+
if (schema.anyOf || schema.oneOf)
|
|
320
|
+
return (schema.anyOf ?? schema.oneOf).map(schemaType).join(' | ');
|
|
321
|
+
if (Array.isArray(schema.type))
|
|
322
|
+
return schema.type
|
|
323
|
+
.map((type) => schemaType({ ...schema, type }))
|
|
324
|
+
.join(' | ');
|
|
325
|
+
switch (schema.type) {
|
|
326
|
+
case 'string':
|
|
327
|
+
case 'boolean':
|
|
328
|
+
case 'null':
|
|
329
|
+
return schema.type;
|
|
330
|
+
case 'integer':
|
|
331
|
+
case 'number':
|
|
332
|
+
return 'number';
|
|
333
|
+
case 'array':
|
|
334
|
+
return schema.prefixItems
|
|
335
|
+
? '[' + schema.prefixItems.map(schemaType).join(', ') + ']'
|
|
336
|
+
: 'Array<' + schemaType(schema.items) + '>';
|
|
337
|
+
case 'object':
|
|
338
|
+
return ('{' +
|
|
339
|
+
Object.entries(schema.properties ?? {})
|
|
340
|
+
.map(([name, value]) => `${JSON.stringify(name)}${schema.required?.includes(name) ? '' : '?'}: ${schemaType(value)}`)
|
|
341
|
+
.join('; ') +
|
|
342
|
+
'}');
|
|
343
|
+
default:
|
|
344
|
+
return 'unknown';
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
function positionalSQLSchema(param, index) {
|
|
348
|
+
const array = param.kind.endsWith('[]'), kind = array ? param.kind.slice(0, -2) : param.kind;
|
|
349
|
+
const scalar = sqlScalarSchema(kind, index);
|
|
350
|
+
const values = Array.isArray(param.enum)
|
|
351
|
+
? { enum: [...param.enum, null] }
|
|
352
|
+
: {};
|
|
353
|
+
const schema = array
|
|
354
|
+
? { type: ['array', 'null'], items: { ...scalar, ...values } }
|
|
355
|
+
: { ...scalar, ...values };
|
|
356
|
+
if (param.description)
|
|
357
|
+
schema.description = param.description;
|
|
358
|
+
return schema;
|
|
359
|
+
}
|
|
360
|
+
function writeLegacyInputs(inputs, write) {
|
|
361
|
+
const members = inputs.map((item) => {
|
|
362
|
+
let schema = item.inputSchema;
|
|
363
|
+
if (item.functionType !== 2 && request.inputMode !== 'named')
|
|
364
|
+
schema = {
|
|
365
|
+
type: 'array',
|
|
366
|
+
prefixItems: item.functionType === 1
|
|
367
|
+
? item.parameters.map(positionalSQLSchema)
|
|
368
|
+
: Object.values(item.inputSchema.properties ?? {}),
|
|
369
|
+
};
|
|
370
|
+
return `${JSON.stringify(item.functionId)}: ${schemaType(schema)}`;
|
|
371
|
+
});
|
|
372
|
+
generatedFile('page/src/lib/database-function-inputs.generated.ts', '// Generated by lark-cli.\nexport type DatabaseFunctionInputMap = {\n' +
|
|
373
|
+
members.join(';\n') +
|
|
374
|
+
'\n};\n', write);
|
|
375
|
+
}
|
|
376
|
+
async function isolatedCodegen(input) {
|
|
377
|
+
return runSDKCodegen(root, input, server);
|
|
378
|
+
}
|
|
379
|
+
function checkSchema(schema) {
|
|
380
|
+
if (!schema ||
|
|
381
|
+
typeof schema !== 'object' ||
|
|
382
|
+
Array.isArray(schema) ||
|
|
383
|
+
Buffer.byteLength(JSON.stringify(schema)) > 32768)
|
|
384
|
+
throw Error('Invalid or oversized Function schema');
|
|
385
|
+
let count = 0;
|
|
386
|
+
function walk(value, depth) {
|
|
387
|
+
if (!value || typeof value !== 'object')
|
|
388
|
+
return;
|
|
389
|
+
if (++count > 256 || depth > 16)
|
|
390
|
+
throw Error('Function schema exceeds depth or node budget');
|
|
391
|
+
for (const [key, child] of Object.entries(value)) {
|
|
392
|
+
if (key === '$ref' &&
|
|
393
|
+
(typeof child !== 'string' || !child.startsWith('#/')))
|
|
394
|
+
throw Error('External schema reference');
|
|
395
|
+
if (['$dynamicRef', '$recursiveRef', 'tsType', 'tsEnumNames'].includes(key))
|
|
396
|
+
throw Error('Unsupported schema extension');
|
|
397
|
+
walk(child, depth + 1);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
walk(schema, 0);
|
|
401
|
+
}
|
|
402
|
+
function validateFunctionInput(schema, id) {
|
|
403
|
+
checkSchema(schema);
|
|
404
|
+
if (schema.type !== 'object')
|
|
405
|
+
throw Error('FaaS input must be an object: ' + id);
|
|
406
|
+
for (const [name, value] of Object.entries(schema.properties ?? {}))
|
|
407
|
+
if (typeof value.description !== 'string' || !value.description.trim())
|
|
408
|
+
throw Error('FaaS parameter description is required: ' + id + '.' + name);
|
|
409
|
+
const ajv = new Ajv2020({ strict: false, validateFormats: false });
|
|
410
|
+
if (!ajv.validateSchema(schema))
|
|
411
|
+
throw Error('Invalid Function schema: ' + id + ': ' + ajv.errorsText());
|
|
412
|
+
}
|
|
413
|
+
function validateTriggers(value, input, directory) {
|
|
414
|
+
validateTriggerDeclarations(value, input, directory + '/meta.json', triggerIDs);
|
|
415
|
+
if (value?.length) {
|
|
416
|
+
triggerCount += value.length;
|
|
417
|
+
triggerLocations.push(path.relative(root, directory) + '/meta.json');
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
async function schemas(directory, decl) {
|
|
421
|
+
const temporary = path.join(stateRoot, 'schema-' + randomUUID());
|
|
422
|
+
fs.mkdirSync(temporary, { recursive: true });
|
|
423
|
+
try {
|
|
424
|
+
const bundle = path.join(temporary, 'schema.cjs');
|
|
425
|
+
const imports = Object.entries(decl.fields)
|
|
426
|
+
.map(([key, name]) => `${name} as ${key}`)
|
|
427
|
+
.join(',');
|
|
428
|
+
const converter = fileURLToPath(new URL('./contract-conversion.js', import.meta.url));
|
|
429
|
+
const source = `import { ${imports} } from ${JSON.stringify(path.join(directory, 'contract.ts'))};import {z} from 'zod';import {convertLoadedContract} from ${JSON.stringify(converter)};export const converted=convertLoadedContract({${Object.keys(decl.fields).join(',')},z},{functionId:${JSON.stringify(path.basename(directory))},displayPath:${JSON.stringify(path.relative(root, directory) + '/contract.ts')}});`;
|
|
430
|
+
await build({
|
|
431
|
+
stdin: { contents: source, resolveDir: directory, loader: 'ts' },
|
|
432
|
+
bundle: true,
|
|
433
|
+
platform: 'node',
|
|
434
|
+
format: 'cjs',
|
|
435
|
+
outfile: bundle,
|
|
436
|
+
logLevel: 'silent',
|
|
437
|
+
});
|
|
438
|
+
const worker = path.join(temporary, 'convert.cjs');
|
|
439
|
+
fs.writeFileSync(worker, `global.fetch=()=>{throw Error('NETWORK_DISABLED')};global.WebSocket=undefined;const {converted}=require('./schema.cjs');process.stdout.write(JSON.stringify(converted));`);
|
|
440
|
+
const result = JSON.parse(execFileSync(process.execPath, [
|
|
441
|
+
permissionFlag,
|
|
442
|
+
`--allow-fs-read=${temporary}`,
|
|
443
|
+
'--max-old-space-size=128',
|
|
444
|
+
worker,
|
|
445
|
+
], {
|
|
446
|
+
cwd: temporary,
|
|
447
|
+
env: {},
|
|
448
|
+
encoding: 'utf8',
|
|
449
|
+
timeout: 5000,
|
|
450
|
+
maxBuffer: 4 << 20,
|
|
451
|
+
}));
|
|
452
|
+
for (const key of ['input', 'output'])
|
|
453
|
+
if (result[key])
|
|
454
|
+
checkSchema(result[key]);
|
|
455
|
+
for (const schema of Object.values(result.events ?? {}))
|
|
456
|
+
checkSchema(schema);
|
|
457
|
+
return result;
|
|
458
|
+
}
|
|
459
|
+
finally {
|
|
460
|
+
fs.rmSync(temporary, { recursive: true, force: true });
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
function stale() {
|
|
464
|
+
throw Error('CONTRACT_STALE: run base +site-contract-generate');
|
|
465
|
+
}
|
|
466
|
+
function equal(a, b) {
|
|
467
|
+
const canonical = (value) => Array.isArray(value)
|
|
468
|
+
? value.map(canonical)
|
|
469
|
+
: value && typeof value === 'object'
|
|
470
|
+
? Object.fromEntries(Object.keys(value)
|
|
471
|
+
.sort()
|
|
472
|
+
.map((key) => [key, canonical(value[key])]))
|
|
473
|
+
: value;
|
|
474
|
+
return JSON.stringify(canonical(a)) === JSON.stringify(canonical(b));
|
|
475
|
+
}
|
|
476
|
+
function generatedFile(file, content, write) {
|
|
477
|
+
if (write)
|
|
478
|
+
save(file, content);
|
|
479
|
+
else if (!fs.existsSync(safe(file)) ||
|
|
480
|
+
fs.readFileSync(safe(file), 'utf8') !== content)
|
|
481
|
+
stale();
|
|
482
|
+
}
|
|
483
|
+
async function contracts(write) {
|
|
484
|
+
const functions = [];
|
|
485
|
+
const inputs = [];
|
|
486
|
+
const durable = [];
|
|
487
|
+
const durableTypes = [];
|
|
488
|
+
triggerIDs.clear();
|
|
489
|
+
triggerLocations.length = 0;
|
|
490
|
+
triggerCount = 0;
|
|
491
|
+
const changes = [];
|
|
492
|
+
let sdkDeclarations = 0;
|
|
493
|
+
for (const kind of ['functions', 'durable'])
|
|
494
|
+
for (const id of entries(path.join(serverRoot, kind))) {
|
|
495
|
+
const directory = path.join(serverRoot, kind, id), entry = path.join(directory, 'index.ts');
|
|
496
|
+
if (!fs.existsSync(entry))
|
|
497
|
+
throw Error('Missing Function entry ' + id);
|
|
498
|
+
const decl = definition(entry);
|
|
499
|
+
if (!decl) {
|
|
500
|
+
const meta = readJSON(path.join(directory, 'meta.json'));
|
|
501
|
+
if (kind === 'durable')
|
|
502
|
+
throw Error('Durable entry must use defineDurableFunction: ' + id);
|
|
503
|
+
if (meta.inputSchema) {
|
|
504
|
+
validateFunctionInput(meta.inputSchema, id);
|
|
505
|
+
functions.push({
|
|
506
|
+
functionId: id,
|
|
507
|
+
functionType: 2,
|
|
508
|
+
input: meta.inputSchema,
|
|
509
|
+
});
|
|
510
|
+
inputs.push({
|
|
511
|
+
functionId: id,
|
|
512
|
+
functionType: 2,
|
|
513
|
+
inputSchema: meta.inputSchema,
|
|
514
|
+
parameterOptions: {},
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
continue;
|
|
518
|
+
}
|
|
519
|
+
sdkDeclarations++;
|
|
520
|
+
const converted = await schemas(directory, decl);
|
|
521
|
+
const metaPath = path.join(directory, 'meta.json'), meta = readJSON(metaPath);
|
|
522
|
+
if (kind === 'durable')
|
|
523
|
+
converted.events ??= {};
|
|
524
|
+
if (kind === 'durable' && (!converted.input || !converted.output))
|
|
525
|
+
throw Error('Durable contracts must be representable: ' +
|
|
526
|
+
converted.warnings.join('; '));
|
|
527
|
+
const runtimeOnly = kind !== 'durable' &&
|
|
528
|
+
((write
|
|
529
|
+
? request.runtimeOnly
|
|
530
|
+
: meta.contract?.mode === 'runtime-only') ||
|
|
531
|
+
!converted.input ||
|
|
532
|
+
!converted.output);
|
|
533
|
+
const contract = {
|
|
534
|
+
version: 1,
|
|
535
|
+
generatorVersion: 'lark-cli',
|
|
536
|
+
sdkVersion: null,
|
|
537
|
+
schemaVendor: 'zod',
|
|
538
|
+
schemaPackageVersion: null,
|
|
539
|
+
schemaHash: 'sha256:' + digest(JSON.stringify(converted)),
|
|
540
|
+
fidelity: runtimeOnly ? 'runtime-only' : 'complete',
|
|
541
|
+
mode: runtimeOnly ? 'runtime-only' : 'discovery',
|
|
542
|
+
warnings: converted.warnings,
|
|
543
|
+
};
|
|
544
|
+
const next = { ...meta, contract };
|
|
545
|
+
if (!runtimeOnly) {
|
|
546
|
+
next.inputSchema = converted.input;
|
|
547
|
+
next.outputSchema = converted.output;
|
|
548
|
+
}
|
|
549
|
+
else {
|
|
550
|
+
delete next.inputSchema;
|
|
551
|
+
delete next.outputSchema;
|
|
552
|
+
}
|
|
553
|
+
if (!write &&
|
|
554
|
+
(!equal(meta.inputSchema, next.inputSchema) ||
|
|
555
|
+
!equal(meta.outputSchema, next.outputSchema) ||
|
|
556
|
+
!equal(meta.contract, contract)))
|
|
557
|
+
stale();
|
|
558
|
+
if (kind === 'durable') {
|
|
559
|
+
next.events = converted.events;
|
|
560
|
+
if (!write && !equal(meta.events, next.events))
|
|
561
|
+
stale();
|
|
562
|
+
}
|
|
563
|
+
if (converted.warnings.length)
|
|
564
|
+
process.stderr.write(converted.warnings.join('\n') + '\n');
|
|
565
|
+
if (kind === 'durable')
|
|
566
|
+
validateTriggers(meta.triggers, converted.input, directory);
|
|
567
|
+
else if (!runtimeOnly)
|
|
568
|
+
validateFunctionInput(converted.input, id);
|
|
569
|
+
if (write)
|
|
570
|
+
changes.push([metaPath, next]);
|
|
571
|
+
if (kind === 'durable') {
|
|
572
|
+
durable.push({
|
|
573
|
+
functionId: id,
|
|
574
|
+
inputSchema: converted.input,
|
|
575
|
+
outputSchema: converted.output,
|
|
576
|
+
events: converted.events,
|
|
577
|
+
});
|
|
578
|
+
const source = `typeof import(${JSON.stringify(`../../durable/${id}/contract.js`)})`;
|
|
579
|
+
durableTypes.push(`${JSON.stringify(id)}: { input: z.input<${source}[${JSON.stringify(decl.fields.input)}]>; output: z.output<${source}[${JSON.stringify(decl.fields.output)}]>; events: ${decl.fields.events ? `{ [E in keyof ${source}[${JSON.stringify(decl.fields.events)}]]: z.input<${source}[${JSON.stringify(decl.fields.events)}][E]> }` : '{}'} };`);
|
|
580
|
+
}
|
|
581
|
+
else {
|
|
582
|
+
functions.push({
|
|
583
|
+
functionId: id,
|
|
584
|
+
functionType: 2,
|
|
585
|
+
input: converted.input ?? {},
|
|
586
|
+
output: converted.output ?? {},
|
|
587
|
+
contract,
|
|
588
|
+
});
|
|
589
|
+
inputs.push({
|
|
590
|
+
functionId: id,
|
|
591
|
+
functionType: 2,
|
|
592
|
+
inputSchema: converted.input ?? {},
|
|
593
|
+
parameterOptions: {},
|
|
594
|
+
});
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
legacyContracts(functions, inputs);
|
|
598
|
+
writeJSON(path.join(stateRoot, 'lark-site-trigger-validation.json'), {
|
|
599
|
+
local: 'passed',
|
|
600
|
+
status: 'not_run',
|
|
601
|
+
declarations: triggerCount,
|
|
602
|
+
locations: triggerLocations,
|
|
603
|
+
reason: 'Local shape, IDs and input contracts checked. Calendar/timezone semantics, platform interval and Trigger quota are checked during deployment, not Function server validation.',
|
|
604
|
+
});
|
|
605
|
+
const generated = {
|
|
606
|
+
contractFormatVersion: 1,
|
|
607
|
+
version: 1,
|
|
608
|
+
layout: server === 'server' ? 'workspace' : 'classic',
|
|
609
|
+
schemaHash: 'sha256:' + digest(JSON.stringify(functions)),
|
|
610
|
+
functions,
|
|
611
|
+
...(durable.length ? { durable } : {}),
|
|
612
|
+
inputs,
|
|
613
|
+
client: true,
|
|
614
|
+
augmentation: 'none',
|
|
615
|
+
};
|
|
616
|
+
if (write)
|
|
617
|
+
for (const [file, data] of changes)
|
|
618
|
+
writeJSON(file, data);
|
|
619
|
+
const manifest = path.join(serverRoot, 'contracts.generated.json');
|
|
620
|
+
if (write)
|
|
621
|
+
writeJSON(manifest, generated);
|
|
622
|
+
else if (!fs.existsSync(safe(manifest)) ||
|
|
623
|
+
!equal(readJSON(safe(manifest)), generated))
|
|
624
|
+
stale();
|
|
625
|
+
try {
|
|
626
|
+
requireProject.resolve('@lark-base-open/base-database-app-sdk/codegen');
|
|
627
|
+
}
|
|
628
|
+
catch (error) {
|
|
629
|
+
if (sdkDeclarations)
|
|
630
|
+
throw error;
|
|
631
|
+
writeLegacyInputs(inputs, write);
|
|
632
|
+
return;
|
|
633
|
+
}
|
|
634
|
+
const durableFile = path.join(serverRoot, 'src/generated/durable.d.ts');
|
|
635
|
+
if (durable.length || fs.existsSync(safe(durableFile)))
|
|
636
|
+
generatedFile(durableFile, `/* Generated by lark-cli. Do not edit. */\nimport '@lark-base-open/base-database-app-sdk/server';\nimport type { z } from 'zod';\ndeclare module '@lark-base-open/base-database-app-sdk/server' {\n interface DurableFunctions {\n ${durableTypes.join('\n ')}\n }\n}\n`, write);
|
|
637
|
+
const { durable: workflowContracts, ...sdkContracts } = generated;
|
|
638
|
+
const output = await isolatedCodegen(sdkContracts);
|
|
639
|
+
for (const file of output) {
|
|
640
|
+
if (typeof file.path !== 'string' || typeof file.content !== 'string')
|
|
641
|
+
throw Error('Invalid SDK codegen result');
|
|
642
|
+
generatedFile(file.path, file.content.replace(/(^\/\* Generated by )[^ .\r\n]+(?=[ .])/gm, '$1lark-cli'), write);
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
function inspectServerEnvironment() {
|
|
646
|
+
const environment = new Set();
|
|
647
|
+
function visit(directory) {
|
|
648
|
+
if (!fs.existsSync(directory))
|
|
649
|
+
return;
|
|
650
|
+
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
|
|
651
|
+
if (['node_modules', 'dist', '.lark-cli'].includes(entry.name))
|
|
652
|
+
continue;
|
|
653
|
+
const file = path.join(directory, entry.name);
|
|
654
|
+
if (entry.isSymbolicLink())
|
|
655
|
+
throw Error('Server source contains a link');
|
|
656
|
+
if (entry.isDirectory()) {
|
|
657
|
+
visit(file);
|
|
658
|
+
continue;
|
|
659
|
+
}
|
|
660
|
+
if (!/\.[cm]?[jt]sx?$/.test(file))
|
|
661
|
+
continue;
|
|
662
|
+
const ast = parse(fs.readFileSync(file, 'utf8'), {
|
|
663
|
+
sourceType: 'unambiguous',
|
|
664
|
+
plugins: ['typescript', 'jsx'],
|
|
665
|
+
});
|
|
666
|
+
function walk(node) {
|
|
667
|
+
if (!node || typeof node !== 'object')
|
|
668
|
+
return;
|
|
669
|
+
if (node.type === 'MetaProperty' && node.meta?.name === 'import')
|
|
670
|
+
throw Error('Server import.meta is unsupported');
|
|
671
|
+
if (node.type === 'CallExpression' &&
|
|
672
|
+
(node.callee?.name === 'require' ||
|
|
673
|
+
node.callee?.type === 'Import') &&
|
|
674
|
+
(node.arguments.length !== 1 ||
|
|
675
|
+
node.arguments[0]?.type !== 'StringLiteral'))
|
|
676
|
+
throw Error('Dynamic server imports must use a literal module name');
|
|
677
|
+
if (node.type === 'MemberExpression' &&
|
|
678
|
+
node.object?.type === 'MemberExpression' &&
|
|
679
|
+
node.object.object?.name === 'process' &&
|
|
680
|
+
node.object.property?.name === 'env') {
|
|
681
|
+
const name = node.computed
|
|
682
|
+
? node.property?.value
|
|
683
|
+
: node.property?.name;
|
|
684
|
+
if (typeof name !== 'string')
|
|
685
|
+
throw Error('Dynamic process.env access cannot be validated');
|
|
686
|
+
if (name !== 'NODE_ENV' &&
|
|
687
|
+
name !== 'PORT' &&
|
|
688
|
+
!name.startsWith('BASE_SITE_') &&
|
|
689
|
+
!name.startsWith('LARK_'))
|
|
690
|
+
environment.add(name);
|
|
691
|
+
}
|
|
692
|
+
for (const [key, value] of Object.entries(node)) {
|
|
693
|
+
if (key === 'loc' || key.includes('Comment'))
|
|
694
|
+
continue;
|
|
695
|
+
if (Array.isArray(value))
|
|
696
|
+
value.forEach(walk);
|
|
697
|
+
else
|
|
698
|
+
walk(value);
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
walk(ast);
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
visit(serverRoot);
|
|
705
|
+
writeJSON(path.join(stateRoot, 'lark-site-compiler-report.json'), {
|
|
706
|
+
environmentVariables: [...environment].sort(),
|
|
707
|
+
});
|
|
708
|
+
}
|
|
709
|
+
async function buildServer() {
|
|
710
|
+
const roots = ['functions', 'durable'];
|
|
711
|
+
const profilePath = path.join(serverRoot, 'generated/runtime-profile.ts');
|
|
712
|
+
let profile = { platformEnv: 'online', brand: request.brand };
|
|
713
|
+
if (fs.existsSync(profilePath)) {
|
|
714
|
+
const ast = parse(fs.readFileSync(profilePath, 'utf8'), {
|
|
715
|
+
sourceType: 'module',
|
|
716
|
+
plugins: ['typescript'],
|
|
717
|
+
});
|
|
718
|
+
const value = unwrap(ast.program.body.find((n) => n.type === 'ExportNamedDeclaration')
|
|
719
|
+
?.declaration?.declarations?.[0]?.init);
|
|
720
|
+
if (value?.type !== 'ObjectExpression')
|
|
721
|
+
throw Error('Invalid runtime-profile.ts');
|
|
722
|
+
profile = {};
|
|
723
|
+
for (const property of value.properties) {
|
|
724
|
+
if (property.type !== 'ObjectProperty' ||
|
|
725
|
+
property.computed ||
|
|
726
|
+
property.key.type !== 'Identifier' ||
|
|
727
|
+
property.value.type !== 'StringLiteral')
|
|
728
|
+
throw Error('Runtime profile must contain literal strings');
|
|
729
|
+
profile[property.key.name ?? property.key.value] = property.value.value;
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
if (profile.platformEnv !== 'online' ||
|
|
733
|
+
!['feishu', 'lark'].includes(profile.brand))
|
|
734
|
+
throw Error('Runtime routing does not match a verified ONLINE brand');
|
|
735
|
+
if (request.brand && profile.brand !== request.brand)
|
|
736
|
+
throw Error('Project runtime brand differs from the selected lark-cli profile');
|
|
737
|
+
return buildProject(root, { profile });
|
|
738
|
+
}
|
|
739
|
+
if (operation === 'contracts' || operation === 'verify-contracts')
|
|
740
|
+
await contracts(operation === 'contracts');
|
|
741
|
+
else if (operation === 'build' || operation === 'durable-dev') {
|
|
742
|
+
if (!request.legacyBuild) {
|
|
743
|
+
const tsc = path.join(path.dirname(requireProject.resolve('typescript/package.json')), 'bin/tsc');
|
|
744
|
+
if (entries(path.join(serverRoot, 'functions')).length ||
|
|
745
|
+
entries(path.join(serverRoot, 'durable')).length)
|
|
746
|
+
runNode(tsc, ['--noEmit', '--project', path.join(serverRoot, 'tsconfig.json')], root);
|
|
747
|
+
await buildServer();
|
|
748
|
+
}
|
|
749
|
+
inspectServerEnvironment();
|
|
750
|
+
if (operation === 'durable-dev') {
|
|
751
|
+
const options = request.durableDev;
|
|
752
|
+
const entry = path.join(serverRoot, 'dist/durable', options.functionId, 'index.js');
|
|
753
|
+
const module = await import(pathToFileURL(safe(entry)).href);
|
|
754
|
+
const fn = module.default?.default ?? module.default;
|
|
755
|
+
const executor = fn?.[Symbol.for('base-site.durable')];
|
|
756
|
+
if (executor?.v !== 1 || typeof executor.execute !== 'function')
|
|
757
|
+
throw Error('Durable Function must export a v1 executor');
|
|
758
|
+
const unavailable = () => {
|
|
759
|
+
throw Error('DURABLE_NO_CONTEXT: platform Function calls need a hosted request; use Preview');
|
|
760
|
+
};
|
|
761
|
+
const result = await driveLocalDurable(executor, options.functionId, options.input, {
|
|
762
|
+
fetch: globalThis.fetch,
|
|
763
|
+
invokeFunction: unavailable,
|
|
764
|
+
faasInvoke: unavailable,
|
|
765
|
+
}, {
|
|
766
|
+
fast: options.fast,
|
|
767
|
+
realSleep: options.realSleep,
|
|
768
|
+
events: options.events ?? [],
|
|
769
|
+
});
|
|
770
|
+
writeJSON(path.join(stateRoot, 'lark-site-durable-dev-result.json'), result);
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
else
|
|
774
|
+
throw Error('Unknown compiler operation');
|
|
775
|
+
return { ok: true, operation };
|
|
776
|
+
}
|