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