@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.
@@ -11,13 +11,21 @@ import { build } from 'esbuild';
11
11
  import { parse } from '@babel/parser';
12
12
  import Ajv2020 from 'ajv/dist/2020.js';
13
13
  import { validateTriggerDeclarations } from './trigger-validation.js';
14
- import { fileURLToPath, pathToFileURL } from 'node:url';
14
+ import { fileURLToPath } from 'node:url';
15
15
  import { driveLocalDurable } from './durable-runner.js';
16
- import { buildProject } from './app-builder/core.mjs';
16
+ import { buildProject, defineFunctionCall, isDefineFunctionSource, } from './app-builder/core.mjs';
17
+ import { extractContract } from './contract-extractor.js';
17
18
  import { runSDKCodegen, SDKCodegenError } from './sdk-codegen.js';
18
19
  import { resolveSDKCodegenEntry } from './sdk-codegen-resolution.js';
20
+ import { parsePackageDependencyPolicy, validateWorkspacePackageDependencies, validateWorkspaceLockRegistries, validateDependencyLock, } from './dependency-policy.js';
21
+ import { projectLayout } from './project-layout.js';
22
+ import { sourceArchiveEntryIgnored } from './source-archive-inputs.js';
19
23
  import { inspectPage } from './page-inspection.js';
20
24
  import { parse as parseJSONC } from 'jsonc-parser';
25
+ import { namedSQLParamSchema, sqlParamSchema as positionalSQLSchema, deriveSQLInputSchema, normalizeFunctionInputSchema, checkFaaSInputSchemaContract, } from './function-schema.js';
26
+ import { checkDeclaredParameters, sqlEnumType, mutationEnumType, } from './function-params.js';
27
+ import { validateFunctionDescription, functionDescriptionHint, } from './function-description.js';
28
+ import { readMutationMetaItem } from './mutation.js';
21
29
  import { bindFunctionBatchSnapshot, withFunctionBatchCapability, batchClientWarning, } from './function-batch.js';
22
30
  export async function runCompiler(request) {
23
31
  if (request.protocolVersion !== 1)
@@ -25,8 +33,20 @@ export async function runCompiler(request) {
25
33
  if (!path.isAbsolute(request.root) ||
26
34
  !['server', 'server-functions'].includes(request.server))
27
35
  throw Error('Invalid compiler project layout');
36
+ if (request.operation === 'validate-dependencies') {
37
+ const policy = parsePackageDependencyPolicy(request.dependencyPolicy);
38
+ validateWorkspacePackageDependencies(request.root, policy);
39
+ validateWorkspaceLockRegistries(request.root, policy);
40
+ return;
41
+ }
42
+ if (request.operation === 'validate-locks') {
43
+ for (const directory of projectLayout(request.root).dependencies)
44
+ validateDependencyLock(path.join(request.root, directory), directory, '10.9.2');
45
+ return;
46
+ }
28
47
  const triggerIDs = new Set();
29
48
  const warnings = [];
49
+ const functionHints = [];
30
50
  const localSQLSources = Object.create(null);
31
51
  const triggerLocations = [];
32
52
  let triggerCount = 0;
@@ -37,6 +57,25 @@ export async function runCompiler(request) {
37
57
  const serverRoot = path.join(root, server);
38
58
  const stateRoot = safe(request.stateDirectory);
39
59
  const requireProject = createRequire(path.join(serverRoot, 'package.json'));
60
+ let collectWrites = operation === 'contracts';
61
+ const pendingWrites = new Map();
62
+ const generatedFiles = [];
63
+ const generatedContractIds = new Set();
64
+ function contractReport(functions, inputs) {
65
+ return {
66
+ protocolVersion: 1,
67
+ warnings,
68
+ functionHints,
69
+ functions: generatedContractIds.size,
70
+ functionInputs: {
71
+ sql: inputs.filter((f) => f.functionType === 1).length,
72
+ faas: inputs.filter((f) => f.functionType === 2).length,
73
+ mutation: inputs.filter((f) => f.functionType === 5).length,
74
+ },
75
+ files: generatedFiles,
76
+ };
77
+ }
78
+ const initialInputs = collectWrites ? contractInputsFingerprint() : undefined;
40
79
  const readJSON = (file) => JSON.parse(fs.readFileSync(file, 'utf8'));
41
80
  const writeJSON = (file, data) => save(file, JSON.stringify(data, null, 2) + '\n');
42
81
  const digest = (data) => createHash('sha256').update(data).digest('hex');
@@ -54,11 +93,70 @@ export async function runCompiler(request) {
54
93
  }
55
94
  function save(file, content) {
56
95
  file = safe(file);
96
+ if (collectWrites) {
97
+ if (!file.startsWith(stateRoot + path.sep) &&
98
+ (!fs.existsSync(file) ||
99
+ !fs.readFileSync(file).equals(Buffer.from(content))))
100
+ generatedFiles.push(path.relative(root, file).split(path.sep).join('/'));
101
+ pendingWrites.set(file, content);
102
+ return;
103
+ }
57
104
  fs.mkdirSync(path.dirname(file), { recursive: true });
58
105
  const temporary = file + '.' + randomUUID() + '.tmp';
59
106
  fs.writeFileSync(temporary, content, { flag: 'wx', mode: 0o600 });
60
107
  fs.renameSync(temporary, file);
61
108
  }
109
+ function contractInputsFingerprint() {
110
+ const hash = createHash('sha256');
111
+ let count = 0, bytes = 0;
112
+ const visit = (relative) => {
113
+ const file = safe(relative);
114
+ const stat = fs.lstatSync(file, { throwIfNoEntry: false });
115
+ if (!stat)
116
+ return;
117
+ if (++count > 20000 || stat.isSymbolicLink())
118
+ throw Error('Invalid contract source inputs');
119
+ hash.update(relative + '\0');
120
+ if (stat.isDirectory()) {
121
+ hash.update('directory\0');
122
+ for (const child of fs
123
+ .readdirSync(file, { withFileTypes: true })
124
+ .sort((a, b) => a.name.localeCompare(b.name)))
125
+ if (child.name !== '.lark-cli' &&
126
+ !sourceArchiveEntryIgnored(child.name, child.isDirectory()))
127
+ visit(path.join(relative, child.name));
128
+ }
129
+ else {
130
+ if (!stat.isFile() ||
131
+ stat.size > 64 * 1024 * 1024 ||
132
+ (bytes += stat.size) > 512 * 1024 * 1024)
133
+ throw Error('Contract source input budget exceeded');
134
+ hash.update(String(stat.size) + '\0');
135
+ hash.update(fs.readFileSync(file));
136
+ }
137
+ };
138
+ for (const input of [
139
+ 'page',
140
+ 'server',
141
+ 'server-functions',
142
+ 'contract',
143
+ 'contracts',
144
+ 'database-functions',
145
+ 'sql',
146
+ 'mutations',
147
+ 'ai',
148
+ 'skill',
149
+ 'base-database.jsonc',
150
+ 'catalog.json',
151
+ 'agent-tools.json',
152
+ 'package.json',
153
+ 'package-lock.json',
154
+ 'pnpm-lock.yaml',
155
+ 'tsconfig.json',
156
+ ])
157
+ visit(input);
158
+ return hash.digest('hex');
159
+ }
62
160
  function entries(directory) {
63
161
  if (!fs.existsSync(directory))
64
162
  return [];
@@ -88,131 +186,27 @@ export async function runCompiler(request) {
88
186
  return node;
89
187
  }
90
188
  function definition(entry) {
91
- const ast = parse(fs.readFileSync(entry, 'utf8'), {
189
+ const source = fs.readFileSync(safe(entry), 'utf8');
190
+ const ast = parse(source, {
92
191
  sourceType: 'module',
93
192
  plugins: ['typescript', 'jsx'],
94
193
  });
95
- const names = new Map(), namespaces = new Set();
96
- for (const s of ast.program.body)
97
- if (s.type === 'ImportDeclaration') {
98
- for (const item of s.specifiers) {
99
- if (item.type === 'ImportSpecifier')
100
- names.set(item.local.name, {
101
- from: s.source.value,
102
- name: item.imported.name,
103
- });
104
- if (item.type === 'ImportNamespaceSpecifier' &&
105
- s.source.value === '@lark-base-open/base-database-app-sdk/server')
106
- namespaces.add(item.local.name);
107
- }
108
- }
109
- let exp = unwrap(ast.program.body.find((s) => s.type === 'ExportDefaultDeclaration')
110
- ?.declaration);
111
- if (exp?.type === 'Identifier') {
112
- exp = unwrap(ast.program.body
113
- .flatMap((s) => s.type === 'VariableDeclaration' ? s.declarations : [])
114
- .find((d) => d.id.name === exp.name)?.init);
115
- }
116
- if (exp?.type !== 'CallExpression')
194
+ const durable = !!defineFunctionCall(ast, 'defineDurableFunction');
195
+ if (!durable && !isDefineFunctionSource(source))
117
196
  return null;
118
- const callee = exp.callee.type === 'MemberExpression' &&
119
- !exp.callee.computed &&
120
- namespaces.has(exp.callee.object.name)
121
- ? {
122
- from: '@lark-base-open/base-database-app-sdk/server',
123
- name: exp.callee.property.name,
124
- }
125
- : names.get(exp.callee.name);
126
- if (callee?.from !== '@lark-base-open/base-database-app-sdk/server' ||
127
- !['defineFunction', 'defineDurableFunction'].includes(callee.name))
128
- return null;
129
- const argument = exp.arguments[0];
130
- if (exp.arguments.length !== 1 || argument?.type !== 'ObjectExpression')
131
- throw Error('Function must have one literal declaration');
132
- const fields = {};
133
- for (const p of argument.properties) {
134
- const key = p.key?.name ?? p.key?.value;
135
- if (['input', 'output', 'events'].includes(key)) {
136
- const imported = names.get(p.value?.name);
137
- if (!imported || !/^\.\/contract(?:\.ts|\.js)?$/.test(imported.from))
138
- throw Error('Schemas must be imported from ./contract');
139
- fields[key] = imported.name;
140
- }
141
- }
142
- if (!fields.input || !fields.output)
143
- throw Error('Function requires input and output schemas');
144
- return { kind: callee.name, fields };
145
- }
146
- // Parameter projections preserve the SQL and Mutation input contracts.
147
- function sqlScalarSchema(kind, index) {
148
- const members = {
149
- USER: { id: 'string', name: 'string', avatarUrl: 'string' },
150
- CHAT: { id: 'string', name: 'string' },
151
- FILE: {
152
- token: 'string',
153
- name: 'string',
154
- mime_type: 'string',
155
- size: 'integer',
156
- },
157
- OPTION: { id: 'string', name: 'string' },
158
- URL: { text: 'string', link: 'string' },
159
- LOCATION: { address: 'string', lng: 'number', lat: 'number' },
160
- };
161
- const limit = {
162
- minimum: -Number.MAX_SAFE_INTEGER,
163
- maximum: Number.MAX_SAFE_INTEGER,
197
+ const contract = extractContract(entry, durable);
198
+ return {
199
+ kind: durable ? 'defineDurableFunction' : 'defineFunction',
200
+ fields: Object.fromEntries(['input', 'output', 'events']
201
+ .filter((key) => contract[key])
202
+ .map((key) => [key, contract[key]])),
164
203
  };
165
- switch (kind) {
166
- case 'TEXT':
167
- case 'INTERVAL':
168
- return { type: ['string', 'null'] };
169
- case 'INT':
170
- return { type: ['integer', 'null'], ...limit };
171
- case 'DOUBLE':
172
- return { type: ['number', 'null'] };
173
- case 'BOOL':
174
- return { type: ['boolean', 'null'] };
175
- case 'TIMESTAMP':
176
- return { type: ['string', 'integer', 'null'], ...limit };
177
- default:
178
- if (!members[kind])
179
- throw Error('Unsupported SQL parameter kind at index ' + index + ': ' + kind);
180
- return {
181
- type: ['object', 'null'],
182
- properties: Object.fromEntries(Object.entries(members[kind]).map(([name, type]) => [
183
- name,
184
- {
185
- type: [type, 'null'],
186
- ...(kind === 'FILE' && name === 'size' ? limit : {}),
187
- },
188
- ])),
189
- additionalProperties: false,
190
- };
191
- }
192
204
  }
205
+ // Parameter projections preserve the SQL and Mutation input contracts.
193
206
  function parameterSchema(param, type, index) {
194
207
  let schema;
195
208
  if (type === 1) {
196
- const array = param.kind.endsWith('[]'), kind = array ? param.kind.slice(0, -2) : param.kind;
197
- let scalar = sqlScalarSchema(kind, index);
198
- const nullable = param.nullable !== false;
199
- if (!nullable) {
200
- const types = scalar.type.filter((t) => t !== 'null');
201
- scalar.type = types.length === 1 ? types[0] : types;
202
- }
203
- for (const key of ['minimum', 'maximum'])
204
- if (param[key] !== undefined)
205
- scalar[key] = param[key];
206
- if (Array.isArray(param.enum)) {
207
- if (Array.isArray(scalar.type))
208
- scalar.type = scalar.type.filter((t) => t !== 'null');
209
- scalar.enum = param.enum;
210
- if (nullable)
211
- scalar = { anyOf: [{ type: 'null' }, scalar] };
212
- }
213
- schema = array
214
- ? { type: nullable ? ['array', 'null'] : 'array', items: scalar }
215
- : scalar;
209
+ return namedSQLParamSchema(param, index);
216
210
  }
217
211
  else {
218
212
  const kind = param.kind;
@@ -245,40 +239,6 @@ export async function runCompiler(request) {
245
239
  schema.description = param.description;
246
240
  return schema;
247
241
  }
248
- function validateParameter(p, type, id, params) {
249
- if (typeof p.name !== 'string' ||
250
- !/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(p.name) ||
251
- typeof p.description !== 'string' ||
252
- !p.description.trim() ||
253
- params.filter((v) => v.name === p.name).length !== 1)
254
- throw Error('Unique parameter names and nonblank descriptions are required: ' + id);
255
- if (typeof p.kind !== 'string')
256
- throw Error('Parameter kind is required: ' + id + '.' + p.name);
257
- if (p.enum !== undefined) {
258
- const kind = type === 1 ? p.kind.replace(/\[\]$/, '') : p.kind;
259
- const primitive = [
260
- 'TEXT',
261
- 'INT',
262
- 'DOUBLE',
263
- 'BOOL',
264
- ...(type === 5 ? ['USER_ID', 'GROUP_ID', 'RECORD_ID'] : []),
265
- ];
266
- if (!primitive.includes(kind) ||
267
- !Array.isArray(p.enum) ||
268
- p.enum.length < 1 ||
269
- p.enum.length > 100 ||
270
- new Set(p.enum.map((v) => JSON.stringify(v))).size !== p.enum.length ||
271
- p.enum.some((v) => v === null ||
272
- !((kind === 'BOOL' && typeof v === 'boolean') ||
273
- (kind === 'INT' && Number.isSafeInteger(v)) ||
274
- (kind === 'DOUBLE' &&
275
- typeof v === 'number' &&
276
- Number.isFinite(v)) ||
277
- (!['BOOL', 'INT', 'DOUBLE'].includes(kind) &&
278
- typeof v === 'string'))))
279
- throw Error('Invalid parameter enum: ' + id + '.' + p.name);
280
- }
281
- }
282
242
  function legacyContracts(functions, inputs, bindBatch) {
283
243
  for (const [directory, type] of [
284
244
  [
@@ -291,7 +251,11 @@ export async function runCompiler(request) {
291
251
  ]) {
292
252
  for (const id of entries(path.join(root, directory))) {
293
253
  const metadata = readJSON(path.join(root, directory, id, 'meta.json'));
294
- if (type === 1 && bindBatch) {
254
+ validateFunctionDescription(metadata.description, metadata.name, path.join(directory, id, 'meta.json'));
255
+ const descriptionHint = functionDescriptionHint(metadata.description, path.join(directory, id, 'meta.json'));
256
+ if (descriptionHint)
257
+ functionHints.push({ ...descriptionHint, functionId: id });
258
+ if (type === 1) {
295
259
  let meta = metadata.meta;
296
260
  if (meta === undefined)
297
261
  meta = { params: [] };
@@ -299,18 +263,36 @@ export async function runCompiler(request) {
299
263
  throw Error('SQL meta must be an object: ' + id);
300
264
  else if (!Object.hasOwn(meta, 'params'))
301
265
  meta = { ...meta, params: [] };
302
- const sql = fs.readFileSync(safe(path.join(root, directory, id, 'main.sql')), 'utf8');
303
- localSQLSources[id] =
304
- 'sha256:' + digest(JSON.stringify({ sql, meta }));
266
+ const sqlPath = safe(path.join(root, directory, id, 'main.sql'));
267
+ // Metadata-only codegen can run before SQL is authored. The Go
268
+ // project check requires complete declarations before any upload.
269
+ if (fs.existsSync(sqlPath) || bindBatch) {
270
+ const sql = fs.readFileSync(sqlPath, 'utf8');
271
+ deriveSQLInputSchema(meta, sql);
272
+ if (bindBatch)
273
+ localSQLSources[id] =
274
+ 'sha256:' + digest(JSON.stringify({ sql, meta }));
275
+ }
276
+ }
277
+ else {
278
+ readMutationMetaItem(safe(path.join(root, directory, id, 'meta.json')), root);
305
279
  }
306
280
  const params = type === 1
307
281
  ? (metadata.meta?.params ?? [])
308
282
  : (readJSON(path.join(root, directory, id, 'spec.json')).params ??
309
283
  []);
284
+ const declared = checkDeclaredParameters(params, {
285
+ label: type === 1 ? 'meta.params' : 'spec.params',
286
+ pointer: type === 1 ? '/meta/params' : '/params',
287
+ file: path.join(directory, id, type === 1 ? 'meta.json' : 'spec.json'),
288
+ enumType: type === 1 ? sqlEnumType : mutationEnumType,
289
+ });
290
+ if (declared.problems.length)
291
+ throw Error(declared.problems.join('; '));
292
+ functionHints.push(...declared.hints.map((hint) => ({ ...hint, functionId: id })));
310
293
  const input = {
311
294
  type: 'object',
312
295
  properties: Object.fromEntries(params.map((p, index) => {
313
- validateParameter(p, type, id, params);
314
296
  return [p.name, parameterSchema(p, type, index)];
315
297
  })),
316
298
  required: params
@@ -362,19 +344,6 @@ export async function runCompiler(request) {
362
344
  return 'unknown';
363
345
  }
364
346
  }
365
- function positionalSQLSchema(param, index) {
366
- const array = param.kind.endsWith('[]'), kind = array ? param.kind.slice(0, -2) : param.kind;
367
- const scalar = sqlScalarSchema(kind, index);
368
- const values = Array.isArray(param.enum)
369
- ? { enum: [...param.enum, null] }
370
- : {};
371
- const schema = array
372
- ? { type: ['array', 'null'], items: { ...scalar, ...values } }
373
- : { ...scalar, ...values };
374
- if (param.description)
375
- schema.description = param.description;
376
- return schema;
377
- }
378
347
  function writeLegacyInputs(inputs, write) {
379
348
  const members = inputs.map((item) => {
380
349
  let schema = item.inputSchema;
@@ -387,7 +356,7 @@ export async function runCompiler(request) {
387
356
  };
388
357
  return `${JSON.stringify(item.functionId)}: ${schemaType(schema)}`;
389
358
  });
390
- generatedFile('page/src/lib/database-function-inputs.generated.ts', '// Generated by lark-cli.\nexport type DatabaseFunctionInputMap = {\n' +
359
+ generatedFile('page/src/lib/database-function-inputs.generated.ts', '// Generated by base-database-toolchain.\nexport type DatabaseFunctionInputMap = {\n' +
391
360
  members.join(';\n') +
392
361
  '\n};\n', write);
393
362
  }
@@ -395,16 +364,35 @@ export async function runCompiler(request) {
395
364
  return runSDKCodegen(root, input, server);
396
365
  }
397
366
  function checkSchema(schema) {
398
- if (!schema ||
399
- typeof schema !== 'object' ||
400
- Array.isArray(schema) ||
401
- Buffer.byteLength(JSON.stringify(schema)) > 32768)
402
- throw Error('Invalid or oversized Function schema');
403
- let count = 0;
404
- function walk(value, depth) {
405
- if (!value || typeof value !== 'object')
367
+ if (Buffer.byteLength(JSON.stringify(schema)) > 32 * 1024)
368
+ throw Error('Function schema exceeds byte budget');
369
+ let nodes = 0;
370
+ const maps = new Set([
371
+ 'properties',
372
+ 'patternProperties',
373
+ '$defs',
374
+ 'definitions',
375
+ 'dependentSchemas',
376
+ ]);
377
+ const singles = new Set([
378
+ 'items',
379
+ 'additionalProperties',
380
+ 'contains',
381
+ 'propertyNames',
382
+ 'not',
383
+ 'if',
384
+ 'then',
385
+ 'else',
386
+ 'unevaluatedProperties',
387
+ 'unevaluatedItems',
388
+ ]);
389
+ const lists = new Set(['prefixItems', 'anyOf', 'oneOf', 'allOf']);
390
+ function walk(value, depth = 0) {
391
+ if (typeof value === 'boolean')
406
392
  return;
407
- if (++count > 256 || depth > 16)
393
+ if (!value || typeof value !== 'object' || Array.isArray(value))
394
+ throw Error('Invalid Function schema node');
395
+ if (++nodes > 256 || depth > 16)
408
396
  throw Error('Function schema exceeds depth or node budget');
409
397
  for (const [key, child] of Object.entries(value)) {
410
398
  if (key === '$ref' &&
@@ -412,18 +400,28 @@ export async function runCompiler(request) {
412
400
  throw Error('External schema reference');
413
401
  if (['$dynamicRef', '$recursiveRef', 'tsType', 'tsEnumNames'].includes(key))
414
402
  throw Error('Unsupported schema extension');
415
- walk(child, depth + 1);
403
+ if (maps.has(key) && child && typeof child === 'object')
404
+ for (const schema of Object.values(child))
405
+ walk(schema, depth + 1);
406
+ else if (lists.has(key) || (key === 'items' && Array.isArray(child))) {
407
+ if (!Array.isArray(child))
408
+ throw Error('Invalid schema list');
409
+ for (const schema of child)
410
+ walk(schema, depth + 1);
411
+ }
412
+ else if (singles.has(key))
413
+ walk(child, depth + 1);
416
414
  }
417
415
  }
418
- walk(schema, 0);
416
+ walk(schema);
419
417
  }
420
- function validateFunctionInput(schema, id) {
418
+ function validateFunctionInput(schema, id, file = path.join(serverRoot, 'functions', id, 'meta.json')) {
421
419
  checkSchema(schema);
422
- if (schema.type !== 'object')
423
- throw Error('FaaS input must be an object: ' + id);
424
- for (const [name, value] of Object.entries(schema.properties ?? {}))
425
- if (typeof value.description !== 'string' || !value.description.trim())
426
- throw Error('FaaS parameter description is required: ' + id + '.' + name);
420
+ normalizeFunctionInputSchema(schema, file);
421
+ const declared = checkFaaSInputSchemaContract(schema, file);
422
+ if (declared.problems.length)
423
+ throw Error(`${file}: ${declared.problems.join('; ')}. Fix descriptions in this source and regenerate contracts.`);
424
+ functionHints.push(...declared.hints.map((hint) => ({ ...hint, functionId: id })));
427
425
  const ajv = new Ajv2020({ strict: false, validateFormats: false });
428
426
  if (!ajv.validateSchema(schema))
429
427
  throw Error('Invalid Function schema: ' + id + ': ' + ajv.errorsText());
@@ -465,6 +463,7 @@ export async function runCompiler(request) {
465
463
  env: {},
466
464
  encoding: 'utf8',
467
465
  timeout: 5000,
466
+ killSignal: 'SIGKILL',
468
467
  maxBuffer: 4 << 20,
469
468
  }));
470
469
  for (const key of ['input', 'output'])
@@ -479,7 +478,7 @@ export async function runCompiler(request) {
479
478
  }
480
479
  }
481
480
  function stale() {
482
- throw Error('CONTRACT_STALE: run base +site-contract-generate');
481
+ throw Error('CONTRACT_STALE: regenerate Function contracts with the current CLI');
483
482
  }
484
483
  function equal(a, b) {
485
484
  const canonical = (value) => Array.isArray(value)
@@ -520,6 +519,7 @@ export async function runCompiler(request) {
520
519
  const inputs = [];
521
520
  const durable = [];
522
521
  const durableTypes = [];
522
+ const durableCommonJSTypes = [];
523
523
  triggerIDs.clear();
524
524
  triggerLocations.length = 0;
525
525
  triggerCount = 0;
@@ -530,6 +530,12 @@ export async function runCompiler(request) {
530
530
  const directory = path.join(serverRoot, kind, id), entry = path.join(directory, 'index.ts');
531
531
  if (!fs.existsSync(entry))
532
532
  throw Error('Missing Function entry ' + id);
533
+ const metaFile = path.join(directory, 'meta.json');
534
+ const declaredMeta = readJSON(safe(metaFile));
535
+ validateFunctionDescription(declaredMeta.description, declaredMeta.name, metaFile);
536
+ const descriptionHint = functionDescriptionHint(declaredMeta.description, metaFile);
537
+ if (descriptionHint)
538
+ functionHints.push({ ...descriptionHint, functionId: id });
533
539
  const decl = definition(entry);
534
540
  if (!decl) {
535
541
  const meta = readJSON(path.join(directory, 'meta.json'));
@@ -552,6 +558,8 @@ export async function runCompiler(request) {
552
558
  continue;
553
559
  }
554
560
  sdkDeclarations++;
561
+ if (kind === 'functions')
562
+ generatedContractIds.add(id);
555
563
  const converted = await schemas(directory, decl);
556
564
  const metaPath = path.join(directory, 'meta.json'), meta = readJSON(metaPath);
557
565
  if (kind === 'durable')
@@ -600,7 +608,7 @@ export async function runCompiler(request) {
600
608
  if (kind === 'durable')
601
609
  validateTriggers(meta.triggers, converted.input, directory);
602
610
  else if (!runtimeOnly)
603
- validateFunctionInput(converted.input, id);
611
+ validateFunctionInput(converted.input, id, path.join(directory, 'contract.ts'));
604
612
  if (write)
605
613
  changes.push([metaPath, next]);
606
614
  if (kind === 'durable') {
@@ -611,7 +619,9 @@ export async function runCompiler(request) {
611
619
  events: converted.events,
612
620
  });
613
621
  const source = `typeof import(${JSON.stringify(`../../durable/${id}/contract.js`)})`;
614
- 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]> }` : '{}'} };`);
622
+ const registryEntry = (source) => `${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]> }` : '{}'} };`;
623
+ durableTypes.push(registryEntry(source));
624
+ durableCommonJSTypes.push(registryEntry(`typeof import(${JSON.stringify(`../../durable/${id}/contract.js`)}, { with: { "resolution-mode": "import" } })`));
615
625
  }
616
626
  else {
617
627
  functions.push({
@@ -653,8 +663,14 @@ export async function runCompiler(request) {
653
663
  status: 'not_run',
654
664
  declarations: triggerCount,
655
665
  locations: triggerLocations,
656
- reason: 'Local shape, IDs and input contracts checked. Calendar/timezone semantics, platform interval and Trigger quota are checked during deployment, not Function server validation.',
666
+ reason: 'Local shape, IDs, static input and map target contracts checked. Source bindings and Owner permissions, source field Schema, condition operators/values, actual map source types, calendar/timezone semantics, platform minimum interval and Trigger quota are checked during deployment. The server validates the final merged Record input at startup; Function server validation does not cover these rules.',
657
667
  });
668
+ const client = functions.some((item) => item.functionType === 2) ||
669
+ fs.existsSync(safe('page/src/generated/functions.ts'));
670
+ const augmentationPath = safe('page/src/lib/function-input-map.generated.ts');
671
+ const previousAugmentation = fs.existsSync(augmentationPath)
672
+ ? fs.readFileSync(augmentationPath, 'utf8')
673
+ : undefined;
658
674
  const generated = {
659
675
  contractFormatVersion: 1,
660
676
  version: 1,
@@ -664,8 +680,12 @@ export async function runCompiler(request) {
664
680
  functions,
665
681
  ...(durable.length ? { durable } : {}),
666
682
  inputs,
667
- client: true,
668
- augmentation: 'none',
683
+ client,
684
+ augmentation: client
685
+ ? previousAugmentation === undefined
686
+ ? 'none'
687
+ : 'client'
688
+ : 'compat',
669
689
  };
670
690
  if (write)
671
691
  for (const [file, data] of changes)
@@ -682,31 +702,37 @@ export async function runCompiler(request) {
682
702
  if (warning)
683
703
  warnings.push(warning);
684
704
  writeLegacyInputs(inputs, write);
685
- writeJSON(path.join(stateRoot, 'lark-site-contract-report.json'), {
686
- protocolVersion: 1,
687
- warnings,
688
- });
705
+ writeJSON(path.join(stateRoot, 'lark-site-contract-report.json'), contractReport(functions, inputs));
689
706
  return;
690
707
  }
691
708
  const durableFile = path.join(serverRoot, 'src/generated/durable.d.ts');
692
- if (durable.length || fs.existsSync(safe(durableFile)))
693
- 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);
709
+ const durableCommonJSFile = path.join(serverRoot, 'src/generated/durable.d.cts');
710
+ if (durable.length ||
711
+ fs.existsSync(safe(durableFile)) ||
712
+ fs.existsSync(safe(durableCommonJSFile))) {
713
+ for (const [format, file, entries] of [
714
+ ['esm', durableFile, durableTypes],
715
+ ['cjs', durableCommonJSFile, durableCommonJSTypes],
716
+ ]) {
717
+ generatedFile(file, `/* Generated by base-database-toolchain. Do not edit. */\n/// <reference path="./durable.${format === 'cjs' ? 'd.ts' : 'd.cts'}" />\nimport '@lark-base-open/base-database-app-sdk/server';\n${durable.length ? (format === 'cjs' ? 'import type { z } from \'zod\' with { "resolution-mode": "import" };\n' : "import type { z } from 'zod';\n") : ''}declare module '@lark-base-open/base-database-app-sdk/server' {\n interface DurableFunctions {\n ${entries.join('\n ')}\n }\n}\n`, write);
718
+ }
719
+ }
694
720
  const { durable: workflowContracts, ...sdkContracts } = generated;
695
- const output = await isolatedCodegen(sdkContracts);
721
+ const output = await isolatedCodegen({
722
+ ...sdkContracts,
723
+ previousAugmentation,
724
+ });
696
725
  const warning = batchClientWarning(generated, output);
697
726
  if (warning)
698
727
  warnings.push(warning);
699
728
  for (const file of output) {
700
729
  if (typeof file.path !== 'string' || typeof file.content !== 'string')
701
730
  throw Error('Invalid SDK codegen result');
702
- generatedFile(file.path, file.content.replace(/(^\/\* Generated by )[^ .\r\n]+(?=[ .])/gm, '$1lark-cli'), write);
731
+ generatedFile(file.path, file.content, write);
703
732
  }
704
- writeJSON(path.join(stateRoot, 'lark-site-contract-report.json'), {
705
- protocolVersion: 1,
706
- warnings,
707
- });
733
+ writeJSON(path.join(stateRoot, 'lark-site-contract-report.json'), contractReport(functions, inputs));
708
734
  }
709
- function inspectServerEnvironment() {
735
+ function inspectServerEnvironment(built) {
710
736
  const environment = new Set();
711
737
  function visit(directory) {
712
738
  if (!fs.existsSync(directory))
@@ -727,7 +753,7 @@ export async function runCompiler(request) {
727
753
  sourceType: 'unambiguous',
728
754
  plugins: ['typescript', 'jsx'],
729
755
  });
730
- function walk(node) {
756
+ function walk(node, parent) {
731
757
  if (!node || typeof node !== 'object')
732
758
  return;
733
759
  if (node.type === 'MetaProperty' && node.meta?.name === 'import')
@@ -738,15 +764,21 @@ export async function runCompiler(request) {
738
764
  (node.arguments.length !== 1 ||
739
765
  node.arguments[0]?.type !== 'StringLiteral'))
740
766
  throw Error('Dynamic server imports must use a literal module name');
741
- if (node.type === 'MemberExpression' &&
742
- node.object?.type === 'MemberExpression' &&
743
- node.object.object?.name === 'process' &&
744
- node.object.property?.name === 'env') {
745
- const name = node.computed
746
- ? node.property?.value
747
- : node.property?.name;
767
+ const member = (value) => value?.type === 'MemberExpression' ||
768
+ value?.type === 'OptionalMemberExpression';
769
+ if (member(node) &&
770
+ node.object?.name === 'process' &&
771
+ (node.computed ? node.property?.value : node.property?.name) ===
772
+ 'env') {
773
+ const name = member(parent) && parent.object === node
774
+ ? parent.computed && parent.property?.type === 'StringLiteral'
775
+ ? parent.property.value
776
+ : !parent.computed
777
+ ? parent.property?.name
778
+ : undefined
779
+ : undefined;
748
780
  if (typeof name !== 'string')
749
- throw Error('Dynamic process.env access cannot be validated');
781
+ throw Error(`Unsupported dynamic or destructured process.env access at ${path.relative(root, file)}:${node.loc?.start.line ?? 1}:${(node.loc?.start.column ?? 0) + 1}`);
750
782
  if (name !== 'NODE_ENV' &&
751
783
  name !== 'PORT' &&
752
784
  !name.startsWith('BASE_SITE_') &&
@@ -757,9 +789,9 @@ export async function runCompiler(request) {
757
789
  if (key === 'loc' || key.includes('Comment'))
758
790
  continue;
759
791
  if (Array.isArray(value))
760
- value.forEach(walk);
792
+ value.forEach((child) => walk(child, node));
761
793
  else
762
- walk(value);
794
+ walk(value, node);
763
795
  }
764
796
  }
765
797
  walk(ast);
@@ -768,12 +800,21 @@ export async function runCompiler(request) {
768
800
  visit(serverRoot);
769
801
  writeJSON(path.join(stateRoot, 'lark-site-compiler-report.json'), {
770
802
  environmentVariables: [...environment].sort(),
803
+ ...(built
804
+ ? {
805
+ builderVersion: built.builderVersion,
806
+ stubbedModules: built.stubbedModules ?? [],
807
+ }
808
+ : {}),
771
809
  });
772
810
  }
773
811
  async function buildServer() {
774
812
  const roots = ['functions', 'durable'];
775
813
  const profilePath = path.join(serverRoot, 'generated/runtime-profile.ts');
776
- let profile = { platformEnv: 'online', brand: request.brand };
814
+ const expectedEnvironment = request.runtimeProfile || 'online';
815
+ if (!/^[a-z][a-z0-9_-]*$/.test(expectedEnvironment))
816
+ throw Error('Invalid build runtime profile');
817
+ let profile = { platformEnv: expectedEnvironment, brand: request.brand };
777
818
  if (fs.existsSync(profilePath)) {
778
819
  const ast = parse(fs.readFileSync(profilePath, 'utf8'), {
779
820
  sourceType: 'module',
@@ -793,9 +834,9 @@ export async function runCompiler(request) {
793
834
  profile[property.key.name ?? property.key.value] = property.value.value;
794
835
  }
795
836
  }
796
- if (profile.platformEnv !== 'online' ||
837
+ if (profile.platformEnv !== expectedEnvironment ||
797
838
  !['feishu', 'lark'].includes(profile.brand))
798
- throw Error('Runtime routing does not match a verified ONLINE brand');
839
+ throw Error('Runtime routing differs from the selected CLI environment or verified brand');
799
840
  if (request.brand && profile.brand !== request.brand)
800
841
  throw Error('Project runtime brand differs from the selected lark-cli profile');
801
842
  return buildProject(root, { profile });
@@ -807,19 +848,45 @@ export async function runCompiler(request) {
807
848
  }
808
849
  else if (operation === 'contracts' || operation === 'verify-contracts')
809
850
  await contracts(operation === 'contracts');
810
- else if (operation === 'build' || operation === 'durable-dev') {
851
+ else if (operation === 'build' ||
852
+ operation === 'build-server' ||
853
+ operation === 'durable-dev') {
854
+ let built;
811
855
  if (!request.legacyBuild) {
812
856
  const tsc = path.join(path.dirname(requireProject.resolve('typescript/package.json')), 'bin/tsc');
813
857
  if (entries(path.join(serverRoot, 'functions')).length ||
814
858
  entries(path.join(serverRoot, 'durable')).length)
815
859
  runNode(tsc, ['--noEmit', '--project', path.join(serverRoot, 'tsconfig.json')], root);
816
- await buildServer();
860
+ built = await buildServer();
817
861
  }
818
- inspectServerEnvironment();
862
+ inspectServerEnvironment(built);
819
863
  if (operation === 'durable-dev') {
820
864
  const options = request.durableDev;
821
865
  const entry = path.join(serverRoot, 'dist/durable', options.functionId, 'index.js');
822
- const module = await import(pathToFileURL(safe(entry)).href);
866
+ // Builds replace the complete CJS graph, including shared facades. Drop
867
+ // only this project's generated modules, preserving other host caches.
868
+ const output = fs.realpathSync(safe(path.join(serverRoot, 'dist')));
869
+ const generated = (file) => {
870
+ if (typeof file !== 'string')
871
+ return false;
872
+ const relative = path.relative(output, file);
873
+ return (relative === '' ||
874
+ (!path.isAbsolute(relative) &&
875
+ relative !== '..' &&
876
+ !relative.startsWith(`..${path.sep}`)));
877
+ };
878
+ for (const cached of Object.values(requireProject.cache)) {
879
+ if (!cached)
880
+ continue;
881
+ const children = cached.children.filter((child) => !generated(child.filename));
882
+ if (children.length !== cached.children.length)
883
+ cached.children = children;
884
+ }
885
+ for (const file of Object.keys(requireProject.cache)) {
886
+ if (generated(file))
887
+ delete requireProject.cache[file];
888
+ }
889
+ const module = requireProject(safe(entry));
823
890
  const fn = module.default?.default ?? module.default;
824
891
  const executor = fn?.[Symbol.for('base-site.durable')];
825
892
  if (executor?.v !== 1 || typeof executor.execute !== 'function')
@@ -841,5 +908,12 @@ export async function runCompiler(request) {
841
908
  }
842
909
  else
843
910
  throw Error('Unknown compiler operation');
911
+ if (collectWrites) {
912
+ if (contractInputsFingerprint() !== initialInputs)
913
+ throw Error('CONTRACT_SOURCE_CHANGED: project inputs changed during generation; retry from the current source');
914
+ collectWrites = false;
915
+ for (const [file, content] of pendingWrites)
916
+ save(file, content);
917
+ }
844
918
  return { ok: true, operation, ...(warnings.length ? { warnings } : {}) };
845
919
  }