@lark-base-open/base-database-toolchain 1.4.0 → 2.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 CHANGED
@@ -1,5 +1,32 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.0.0] - 2026-11-30
4
+
5
+ ### Removed
6
+
7
+ - Remove classic/template v1 project layouts, legacy sql/ and server-functions/ roots, positional Page inputs, and legacyBuild=true from the JSON compiler interface. Use template v2 page/server workspaces with named inputs; existing projects must be migrated before switching to this version.
8
+ - Remove LEGACY_DATABASE_FUNCTIONS_DIRECTORY from the project-layout export.
9
+
10
+ ### Added
11
+
12
+ - Preserve discovered SQL BATCH limits above 200 groups for client generation by a compatible project SDK. Actual invocation limits remain enforced by the installed SDK and platform; SDK 0.10.0 still limits batch clients to 200 groups.
13
+
14
+ ### Fixed
15
+
16
+ - Keep Vite configuration and plugin logs out of the development worker JSON protocol, redact pairing tokens across split writes, and bound diagnostics on stderr.
17
+ - Report SQL parameter declaration mismatches with file paths, affected parameters and repair guidance.
18
+ - Validate workspace Function contracts consistently when generating and verifying named Page clients.
19
+
20
+ ### Security
21
+
22
+ - Update ajv and re2js dependencies to address high and critical advisories.
23
+
24
+ ## [1.4.1] - 2026-11-29
25
+
26
+ ### Fixed
27
+
28
+ - Accept SDK 0.10.x server and shared entries in the audited shared dependency range, while retaining SDK 0.8.x and 0.9.x support.
29
+
3
30
  ## [1.4.0] - 2026-11-26
4
31
 
5
32
  ### Added
package/README.md CHANGED
@@ -12,6 +12,8 @@ Authentication, platform API calls, project dependency installation, source uplo
12
12
 
13
13
  ## Node API
14
14
 
15
+ Version 2 requires `database-starter` template version 2 with `page`/`server` workspaces, named Page inputs and `database-functions/`. Migrate older layouts before upgrading; this version does not execute classic/v1 projects or expose `LEGACY_DATABASE_FUNCTIONS_DIRECTORY`. SQL BATCH capabilities above 200 are preserved for a compatible project SDK. Published SDK 0.10.0 still generates batch clients only up to 200 groups; increasing the toolchain version alone does not enable 500-group execution.
16
+
15
17
  ```js
16
18
  import {
17
19
  extractContract,
@@ -44,7 +46,7 @@ Run `base-database-toolchain` with one JSON object on stdin. It exits after one
44
46
  }
45
47
  ```
46
48
 
47
- Supported operations: `contracts`, `verify-contracts`, `build`, `build-server`, `durable-dev`, `validate-locks`, `validate-dependencies` and `inspect-page`. `validate-dependencies` requires the caller-provided `dependencyPolicy`; `build-server` skips Page builds. `inputMode`, `runtimeOnly`, `legacyBuild` and `durableDev` select project compatibility options. Page builds remain the caller's responsibility.
49
+ Supported operations: `contracts`, `verify-contracts`, `build`, `build-server`, `durable-dev`, `validate-locks`, `validate-dependencies` and `inspect-page`. `validate-dependencies` requires the caller-provided `dependencyPolicy`; `build-server` skips Page builds. `runtimeOnly` selects runtime metadata generation and `durableDev` carries local debug options. The worker requires template.version 2, page/server workspaces and named Page inputs; legacy server layouts, sql/ directories, legacyBuild=true and positional inputs are rejected before compilation. Page builds remain the caller's responsibility.
48
50
 
49
51
  For SQL batch clients, supply an authenticated, consistently discovered `batchSnapshot` with the siteToken, environment, versionId, skillHash and per-Function detail. The toolchain binds it to the actual project token, `runtimeProfile` (default online), and current local SQL source hashes. Verification reuses that bound observation; edited declarations lose the cached capability until a new discovery. An execution view is provenance, not a future lock. An older SDK can still generate single-call clients and returns a `BATCH_SDK_UNSUPPORTED` warning; no batch types are synthesized.
50
52
 
@@ -52,7 +54,7 @@ Successful contract operations write `lark-site-contract-report.json` under stat
52
54
 
53
55
  Success emits `{"ok":true,"operation":"contracts"}` on stdout. Failure emits a bounded JSON error on stderr and exits nonzero. Callers must not pass access tokens or application secrets to the process. SQL is not executed here; local Timer checks do not establish platform quota or calendar semantics. Durable local execution cannot invoke hosted Functions without a real host context.
54
56
 
55
- For `1.x`, compatible fixes increment patch, compatible features increment minor and incompatible APIs/protocols increment major. Published versions are immutable.
57
+ For stable versions, compatible fixes increment patch, compatible features increment minor and incompatible APIs/protocols increment major. Published versions are immutable.
56
58
 
57
59
  ## Page source inspection
58
60
 
@@ -66,14 +68,18 @@ These results do not prove that initialization executes successfully, that an ex
66
68
 
67
69
  Keep stdin open and send one startup line:
68
70
 
71
+ <!-- prettier-ignore -->
69
72
  ```json
70
73
  {"protocolVersion":1,"workspace":"/absolute/project","port":43100,"hostOrigin":"https://example.test","templateVersion":2}
71
74
  ```
72
75
 
73
76
  Only loopback ports 43100–43109 and an exact HTTPS host origin are accepted. Events on stdout include `snapshot`, `listening`, `ready`, `changed`, `error` and `stopped`, each with `protocolVersion: 1`. `ready` only reports that the SDK observed the local origin; it does not establish authentication or successful application behavior. Tokens are excluded from event payloads and redacted from errors.
74
77
 
78
+ The JSON worker reserves stdout for protocol events. Ordinary console and stream logs from project configuration and plugins are sent to stderr, with pairing tokens redacted across split writes. Diagnostic lines longer than 4,096 characters are omitted; each worker forwards at most 64 KiB plus a truncation notice. Callers should drain stderr separately from stdout. These diagnostics do not authorize publication or change protocol state.
79
+
75
80
  The backend snapshot excludes generated contract projections and observes source declarations, dependencies, bindings and authored Skill metadata. Individual input files are limited to 2 MiB, the tree to 20,000 entries and total content to 64 MiB. Changed-file lists have a byte/count budget; `filesTruncated: true` requires manual review rather than automatic publication. Request a fresh snapshot before a build or remote write:
76
81
 
82
+ <!-- prettier-ignore -->
77
83
  ```json
78
84
  {"protocolVersion":1,"command":"snapshot","requestId":"before-write"}
79
85
  ```
@@ -278,7 +278,7 @@ export function isSupportedSharedVersion(packageName, version) {
278
278
  if (packageName === 'zod')
279
279
  return major === 4;
280
280
  if (packageName === '@lark-base-open/base-database-app-sdk')
281
- return major === 0 && (minor === 8 || minor === 9);
281
+ return major === 0 && minor >= 8 && minor <= 10;
282
282
  return false;
283
283
  }
284
284
  function canonicalInput(root, file) {
@@ -1 +1 @@
1
- {"type":"module","version":"1.0.12"}
1
+ {"type":"module","version":"1.0.13"}
@@ -5,7 +5,8 @@
5
5
  "additionalProperties": false,
6
6
  "required": [
7
7
  "configVersion",
8
- "appToken"
8
+ "appToken",
9
+ "template"
9
10
  ],
10
11
  "properties": {
11
12
  "$schema": {
@@ -45,13 +46,10 @@
45
46
  "const": "database-starter"
46
47
  },
47
48
  "version": {
48
- "enum": [
49
- 1,
50
- 2
51
- ]
49
+ "const": 2
52
50
  }
53
51
  },
54
- "description": "Starter layout version. Omitted in legacy database-starter version 1 projects."
52
+ "description": "Workspace starter layout; only version 2 is supported."
55
53
  },
56
54
  "managedAgentDocs": {
57
55
  "type": "boolean",
@@ -59,37 +57,8 @@
59
57
  "description": "Maintain the base-app managed section in AGENTS.md and the CLAUDE.md reference. Set false to opt out."
60
58
  },
61
59
  "functionInputs": {
62
- "enum": [
63
- "named",
64
- "positional"
65
- ],
66
- "description": "Classic Page/helper input contract; defaults to positional when omitted. Workspace and SDK clients use named inputs."
67
- }
68
- },
69
- "allOf": [
70
- {
71
- "if": {
72
- "required": [
73
- "template"
74
- ],
75
- "properties": {
76
- "template": {
77
- "properties": {
78
- "version": {
79
- "const": 2
80
- }
81
- },
82
- "type": "object"
83
- }
84
- }
85
- },
86
- "then": {
87
- "properties": {
88
- "functionInputs": {
89
- "const": "named"
90
- }
91
- }
92
- }
60
+ "const": "named",
61
+ "description": "Workspace Page and SDK clients use named inputs."
93
62
  }
94
- ]
63
+ }
95
64
  }
@@ -0,0 +1,4 @@
1
+ export declare function isolateDevelopmentDiagnostics(token: any): {
2
+ emit: (value: any) => boolean;
3
+ flush: () => void;
4
+ };
@@ -0,0 +1,73 @@
1
+ import { StringDecoder } from 'node:string_decoder';
2
+ import { redactPairing } from './dev-redaction.js';
3
+ // The worker owns stdout as NDJSON. Project configuration and plugins share the
4
+ // process, so logLevel: silent alone cannot keep their console/direct writes out.
5
+ export function isolateDevelopmentDiagnostics(token) {
6
+ const protocolWrite = process.stdout.write.bind(process.stdout);
7
+ const diagnosticWrite = process.stderr.write.bind(process.stderr);
8
+ const lineLimit = 4096;
9
+ const outputLimit = 64 * 1024;
10
+ let written = 0;
11
+ let suppressed = false;
12
+ const output = (line) => {
13
+ if (suppressed)
14
+ return;
15
+ const safe = redactPairing(line, token) + '\n';
16
+ const size = Buffer.byteLength(safe);
17
+ if (written + size > outputLimit) {
18
+ suppressed = true;
19
+ diagnosticWrite('[development logs truncated]\n');
20
+ return;
21
+ }
22
+ written += size;
23
+ diagnosticWrite(safe);
24
+ };
25
+ const streams = [];
26
+ for (const stream of [process.stdout, process.stderr]) {
27
+ const decoder = new StringDecoder('utf8');
28
+ let pending = '';
29
+ let omitted = false;
30
+ const flushLine = () => {
31
+ output(omitted ? '[development log line omitted: too long]' : pending);
32
+ pending = '';
33
+ omitted = false;
34
+ };
35
+ const accept = (text) => {
36
+ for (const [index, part] of text.split('\n').entries()) {
37
+ if (index)
38
+ flushLine();
39
+ if (!omitted) {
40
+ if (pending.length + part.length > lineLimit) {
41
+ pending = '';
42
+ omitted = true;
43
+ }
44
+ else
45
+ pending += part;
46
+ }
47
+ }
48
+ };
49
+ stream.write = (chunk, encoding, callback) => {
50
+ const done = typeof encoding === 'function' ? encoding : callback;
51
+ const buffer = Buffer.isBuffer(chunk)
52
+ ? chunk
53
+ : Buffer.from(chunk, typeof encoding === 'string' ? encoding : undefined);
54
+ accept(decoder.write(buffer));
55
+ if (typeof done === 'function')
56
+ queueMicrotask(done);
57
+ // Diagnostics are bounded and excess output is dropped rather than
58
+ // applying backpressure to the control protocol or retaining more data.
59
+ return true;
60
+ };
61
+ streams.push(() => {
62
+ accept(decoder.end());
63
+ if (pending || omitted)
64
+ flushLine();
65
+ });
66
+ }
67
+ const flush = () => streams.forEach((finish) => finish());
68
+ process.once('exit', flush);
69
+ return {
70
+ emit: (value) => protocolWrite(JSON.stringify(value) + '\n'),
71
+ flush,
72
+ };
73
+ }
@@ -5,10 +5,12 @@ import { startVite } from './dev-vite-server.js';
5
5
  import { watchSnapshot, changedFiles, snapshotFingerprint, } from './dev-snapshot.js';
6
6
  import { DEVELOPMENT_PAIRING as protocol } from './development-pairing.generated.js';
7
7
  import { redactPairing } from './dev-redaction.js';
8
+ import { isolateDevelopmentDiagnostics } from './dev-diagnostics.mjs';
8
9
  export function runDevelopmentWorker() {
9
10
  const token = process.env[protocol.tokenEnv];
11
+ const diagnostics = isolateDevelopmentDiagnostics(token);
10
12
  const redact = (value) => redactPairing(String(value), token).slice(0, 4096);
11
- const emit = (value) => process.stdout.write(JSON.stringify({ protocolVersion: 1, ...value }) + '\n');
13
+ const emit = (value) => diagnostics.emit({ protocolVersion: 1, ...value });
12
14
  let server;
13
15
  let started = false;
14
16
  let stopping = false;
@@ -51,6 +53,7 @@ export function runDevelopmentWorker() {
51
53
  process.stdin.pause();
52
54
  await startup.catch(() => { });
53
55
  await server?.close();
56
+ diagnostics.flush();
54
57
  emit({ event: 'stopped' });
55
58
  process.exit(code);
56
59
  }
@@ -25,7 +25,10 @@ export interface BoundFunctionBatchSnapshot extends FunctionBatchSnapshot {
25
25
  runtimeProfile: string;
26
26
  localSources: Record<string, string>;
27
27
  }
28
- /** Closed published contract; generated types never establish runtime permission. */
28
+ /** Closed published contract; generated types never establish runtime permission.
29
+ * Limits above the current backend ceiling are not rejected here: SDK codegen caps them to the
30
+ * installed SDK, and devcenter, the Page SDK and the backend enforce group counts, so raising the
31
+ * backend limit later does not require a CLI release. */
29
32
  export declare function normalizeDMLBatchCapability(functionType: number, capability: unknown): DMLBatchCapability | undefined;
30
33
  /** Execution provenance describes the observed provider view, not a future lock. */
31
34
  export declare function normalizeFunctionExecutionSnapshot(value: unknown, environment: 'preview' | 'prod'): FunctionExecutionSnapshot | undefined;
@@ -1,7 +1,10 @@
1
1
  function record(value) {
2
2
  return !!value && typeof value === 'object' && !Array.isArray(value);
3
3
  }
4
- /** Closed published contract; generated types never establish runtime permission. */
4
+ /** Closed published contract; generated types never establish runtime permission.
5
+ * Limits above the current backend ceiling are not rejected here: SDK codegen caps them to the
6
+ * installed SDK, and devcenter, the Page SDK and the backend enforce group counts, so raising the
7
+ * backend limit later does not require a CLI release. */
5
8
  export function normalizeDMLBatchCapability(functionType, capability) {
6
9
  if (functionType !== 1 || !record(capability))
7
10
  return;
@@ -10,10 +13,8 @@ export function normalizeDMLBatchCapability(functionType, capability) {
10
13
  capability.maxRowsPerGroup !== 1 ||
11
14
  !Number.isSafeInteger(capability.maxGroups) ||
12
15
  capability.maxGroups < 1 ||
13
- capability.maxGroups > 200 ||
14
16
  !Number.isSafeInteger(capability.maxTotalRows) ||
15
- capability.maxTotalRows < 1 ||
16
- capability.maxTotalRows > 200)
17
+ capability.maxTotalRows < 1)
17
18
  return;
18
19
  return {
19
20
  version: 1,
@@ -8,7 +8,7 @@ export declare const AGENT_TOOL_DESIGN_REFERENCE = "references/agent-tool-design
8
8
  export declare const PARAMETER_NAME_PATTERN: RegExp;
9
9
  export declare const MAX_PARAMETER_DESCRIPTION = 500;
10
10
  export declare const SHORT_DESCRIPTION_THRESHOLD = 8;
11
- export type FunctionHintKind = 'short_description' | 'binding' | 'enum_unchecked' | 'function_description';
11
+ export type FunctionHintKind = 'short_description' | 'binding' | 'enum_unchecked' | 'function_description' | 'parameter_declaration';
12
12
  /** One non-blocking authoring hint; local hints and service `results[].hints[]` share this shape. */
13
13
  export interface FunctionHint {
14
14
  functionId?: string;
@@ -41,7 +41,7 @@ export function shortDescriptionHint(path, subject) {
41
41
  */
42
42
  export function checkParameterDescription(description, label, path, result) {
43
43
  if (typeof description !== 'string' || description.trim() === '') {
44
- result.problems.push(`${label}.description is required and must be a non-blank string`);
44
+ result.problems.push(`${label}.description is required and must be a non-blank string; describe its business meaning in 1 to ${MAX_PARAMETER_DESCRIPTION} characters`);
45
45
  return;
46
46
  }
47
47
  if (codePoints(description) > MAX_PARAMETER_DESCRIPTION) {
@@ -75,7 +75,7 @@ export function checkDeclaredParameters(params, options) {
75
75
  result.problems.push(`${label}.name must match ${PARAMETER_NAME_PATTERN.source}`);
76
76
  }
77
77
  else if (names.has(name)) {
78
- result.problems.push(`${label}.name duplicates ${JSON.stringify(name)}; names must be unique within one Function`);
78
+ result.problems.push(`${label}.name duplicates ${JSON.stringify(name)}; rename this entry so each position has a unique name within the Function`);
79
79
  }
80
80
  else {
81
81
  names.add(name);
@@ -84,11 +84,16 @@ export function checkDeclaredParameters(params, options) {
84
84
  if (param.enum === undefined)
85
85
  return;
86
86
  const values = param.enum;
87
+ const type = options.enumType(param);
88
+ const example = type === 'integer' || type === 'number'
89
+ ? '[1, 2]'
90
+ : type === 'boolean'
91
+ ? '[true, false]'
92
+ : '["open", "closed"]';
87
93
  if (!Array.isArray(values) || values.length === 0) {
88
- result.problems.push(`${label}.enum must be a non-empty array`);
94
+ result.problems.push(`${label}.enum must be a non-empty array; ${type ? `use a JSON ${type} array such as ${example}` : 'omit enum for an unsupported kind'}`);
89
95
  return;
90
96
  }
91
- const type = options.enumType(param);
92
97
  if (!type) {
93
98
  result.problems.push(`${label}.enum is only supported for string, integer, number or boolean kinds (kind ${JSON.stringify(param.kind)})`);
94
99
  return;
@@ -104,7 +109,7 @@ export function checkDeclaredParameters(params, options) {
104
109
  return;
105
110
  }
106
111
  if (!enumValueMatches(value, type)) {
107
- result.problems.push(`${valueLabel} must be a JSON ${type} to match kind ${JSON.stringify(param.kind)}`);
112
+ result.problems.push(`${valueLabel} must be a JSON ${type} to match kind ${JSON.stringify(param.kind)}; use values such as ${example}`);
108
113
  return;
109
114
  }
110
115
  if (typeof value === 'string' &&
@@ -20,6 +20,10 @@ export declare function sqlParamSchema(param: SQLParamMeta, index: number): {
20
20
  };
21
21
  /** Named-route declaration projection; mirrors the server's nullable/range/enum semantics. */
22
22
  export declare function namedSQLParamSchema(param: Record<string, unknown>, index: number): Record<string, unknown>;
23
+ /** Authoring diagnostics for the named SQL contract. Metadata-only codegen may
24
+ * run before main.sql exists, in which case there are no placeholders to check.
25
+ */
26
+ export declare function checkSQLFunctionParameters(params: unknown, sql: string | undefined, file: string): DeclaredParameterResult;
23
27
  /**
24
28
  * Local Page input contract for the positional `invoke_function` route.
25
29
  * It is never uploaded: the service renders the Agent-facing named-object
@@ -1,5 +1,5 @@
1
1
  import { RE2JS } from 're2js';
2
- import { checkParameterDescription, } from './function-params.js';
2
+ import { checkParameterDescription, checkDeclaredParameters, sqlEnumType, } from './function-params.js';
3
3
  const JSON_SCHEMA_DRAFT_2020_12 = 'https://json-schema.org/draft/2020-12/schema';
4
4
  const MAX_SCHEMA_BYTES = 32 * 1024;
5
5
  const MAX_SCHEMA_DEPTH = 16;
@@ -257,13 +257,20 @@ export function normalizeFunctionInputSchema(value, source) {
257
257
  }
258
258
  return schema;
259
259
  }
260
+ const allowedSQLKinds = `Allowed: ${[...SQL_SCALAR_PARAM_KINDS].join(', ')}, or any of these with one [] suffix (e.g. TEXT[]).`;
261
+ function sqlKindProblem(kind, index) {
262
+ if (typeof kind !== 'string')
263
+ return `meta.params[${index}].kind must be a string. ${allowedSQLKinds}`;
264
+ if (!SQL_SCALAR_PARAM_KINDS.has(kind.endsWith('[]') ? kind.slice(0, -2) : kind)) {
265
+ return `Unsupported Database Function query parameter kind at meta.params[${index}].kind: ${JSON.stringify(kind)}. ${allowedSQLKinds}`;
266
+ }
267
+ }
260
268
  function parseSQLParamKind(kind, index) {
269
+ const problem = sqlKindProblem(kind, index);
270
+ if (problem)
271
+ throw new Error(problem);
261
272
  const isArray = kind.endsWith('[]');
262
- const scalarKind = isArray ? kind.slice(0, -2) : kind;
263
- if (!SQL_SCALAR_PARAM_KINDS.has(scalarKind)) {
264
- throw new Error(`Unsupported Database Function query parameter kind at index ${index}: ${kind}`);
265
- }
266
- return { scalarKind, isArray };
273
+ return { scalarKind: isArray ? kind.slice(0, -2) : kind, isArray };
267
274
  }
268
275
  function sqlScalarParamSchema(kind, inputDescription, index) {
269
276
  let schema;
@@ -304,7 +311,7 @@ function sqlScalarParamSchema(kind, inputDescription, index) {
304
311
  default: {
305
312
  const members = COMPOSITE_PARAM_MEMBERS[kind];
306
313
  if (!members)
307
- throw new Error(`Unsupported scalar parameter kind: ${kind}`);
314
+ throw new Error(`Unsupported scalar parameter kind: ${kind}. ${allowedSQLKinds}`);
308
315
  schema = {
309
316
  type: ['object', 'null'],
310
317
  properties: Object.fromEntries(Object.entries(members).map(([name, type]) => [
@@ -374,7 +381,7 @@ export function namedSQLParamSchema(param, index) {
374
381
  : {}),
375
382
  };
376
383
  }
377
- function sqlPlaceholderIndexes(sql) {
384
+ function sqlPlaceholderIndexes(sql, problems) {
378
385
  const indexes = new Set();
379
386
  let mode = 'normal';
380
387
  for (let index = 0; index < sql.length; index += 1) {
@@ -430,24 +437,101 @@ function sqlPlaceholderIndexes(sql) {
430
437
  end += 1;
431
438
  const placeholder = Number(sql.slice(index + 1, end));
432
439
  if (!Number.isSafeInteger(placeholder) || placeholder < 1) {
433
- throw new Error(`Invalid query placeholder: ${sql.slice(index, end)}`);
440
+ problems.push(`Invalid query placeholder: ${sql.slice(index, end)}. Use a positive, safe integer starting at $1.`);
434
441
  }
435
- indexes.add(placeholder);
442
+ else
443
+ indexes.add(placeholder);
436
444
  index = end - 1;
437
445
  }
438
446
  }
439
447
  return indexes;
440
448
  }
441
- function validateSQLPlaceholders(sql, paramCount) {
442
- const placeholders = sqlPlaceholderIndexes(sql);
443
- if (placeholders.size !== paramCount) {
444
- throw new Error(`Query placeholders and meta.params must both contain exactly ${paramCount} item(s)`);
445
- }
446
- for (let index = 1; index <= paramCount; index += 1) {
447
- if (!placeholders.has(index)) {
448
- throw new Error(`Query placeholder $${index} is missing`);
449
+ function placeholderRange(first, last) {
450
+ return first === last ? `$${first}` : `$${first}..$${last}`;
451
+ }
452
+ function placeholderRanges(indexes) {
453
+ const ranges = [];
454
+ for (let start = 0; start < indexes.length; start++) {
455
+ let end = start;
456
+ while (end + 1 < indexes.length && indexes[end + 1] === indexes[end] + 1)
457
+ end++;
458
+ ranges.push(placeholderRange(indexes[start], indexes[end]));
459
+ start = end;
460
+ }
461
+ return ranges.join(', ') || '(none)';
462
+ }
463
+ function checkSQLPlaceholders(sql, params, problems) {
464
+ const used = sqlPlaceholderIndexes(sql, problems);
465
+ const indexes = [...used].sort((a, b) => a - b);
466
+ if (used.size === params.length && indexes.every((n, i) => n === i + 1))
467
+ return;
468
+ const names = params.map((p) => isRecord(p) && typeof p.name === 'string'
469
+ ? JSON.stringify(p.name)
470
+ : '<unnamed>');
471
+ const unused = names.flatMap((name, i) => used.has(i + 1) ? [] : [`$${i + 1} (${name})`]);
472
+ const undeclared = indexes.filter((i) => i > params.length);
473
+ const differences = [];
474
+ const gaps = [];
475
+ let next = 1;
476
+ for (const n of indexes) {
477
+ if (n > next)
478
+ gaps.push(placeholderRange(next, n - 1));
479
+ next = n + 1;
480
+ }
481
+ if (gaps.length)
482
+ differences.push(`Missing from the SQL sequence: ${gaps.join(', ')}.`);
483
+ if (unused.length)
484
+ differences.push(`Declared but unused in SQL: ${unused.join(', ')}.`);
485
+ if (undeclared.length)
486
+ differences.push(`Used in SQL without a declaration: ${placeholderRanges(undeclared)}.`);
487
+ problems.push(`main.sql uses ${placeholderRanges(indexes)}; meta.params declares ${params.length} in order: [${names.join(', ')}]. ${differences.join(' ')} Fix: align SQL placeholders and declarations by position: meta.params[i] supplies $(i+1), starting with meta.params[0] for $1; use consecutive positions without gaps.`);
488
+ }
489
+ /** Authoring diagnostics for the named SQL contract. Metadata-only codegen may
490
+ * run before main.sql exists, in which case there are no placeholders to check.
491
+ */
492
+ export function checkSQLFunctionParameters(params, sql, file) {
493
+ if (!Array.isArray(params))
494
+ return {
495
+ problems: [
496
+ 'meta.params must be an array of parameter objects; use [] for a function without parameters.',
497
+ ],
498
+ hints: [],
499
+ };
500
+ const result = checkDeclaredParameters(params, {
501
+ label: 'meta.params',
502
+ pointer: '/meta/params',
503
+ file,
504
+ enumType: sqlEnumType,
505
+ });
506
+ if (sql !== undefined)
507
+ checkSQLPlaceholders(sql, params, result.problems);
508
+ params.forEach((param, index) => {
509
+ if (!isRecord(param))
510
+ return;
511
+ // The existing metadata-only named projection coerces kind to a string.
512
+ const kind = sql === undefined ? String(param.kind) : param.kind;
513
+ const problem = sqlKindProblem(kind, index);
514
+ if (problem)
515
+ result.problems.push(problem);
516
+ const hint = (key, message) => result.hints.push({
517
+ kind: 'parameter_declaration',
518
+ path: `${file}#/meta/params/${index}/${key}`,
519
+ message: `meta.params[${index}].${key}: ${message}`,
520
+ });
521
+ if (param.nullable !== undefined && typeof param.nullable !== 'boolean')
522
+ hint('nullable', 'Allowed: true or false as a JSON boolean, or omit nullable.');
523
+ for (const key of ['minimum', 'maximum']) {
524
+ if (param[key] === undefined)
525
+ continue;
526
+ if (typeof param[key] !== 'number' ||
527
+ !Number.isFinite(param[key]) ||
528
+ !['INT', 'DOUBLE', 'TIMESTAMP'].includes(typeof kind === 'string' && kind.endsWith('[]')
529
+ ? kind.slice(0, -2)
530
+ : String(kind)))
531
+ hint(key, 'Allowed: a finite JSON number on numeric values (INT, DOUBLE, or TIMESTAMP epoch milliseconds, including array elements); otherwise omit this bound.');
449
532
  }
450
- }
533
+ });
534
+ return result;
451
535
  }
452
536
  /**
453
537
  * Local Page input contract for the positional `invoke_function` route.
@@ -461,7 +545,7 @@ export function deriveSQLInputSchema(meta, sql) {
461
545
  }
462
546
  const params = rawParams.map((value, index) => {
463
547
  if (!isRecord(value) || typeof value.kind !== 'string') {
464
- throw new Error(`Database Function meta.params[${index}].kind must be a string`);
548
+ throw new Error(`Database Function meta.params[${index}].kind must be a string. ${allowedSQLKinds}`);
465
549
  }
466
550
  if (value.description !== undefined &&
467
551
  typeof value.description !== 'string') {
@@ -473,7 +557,10 @@ export function deriveSQLInputSchema(meta, sql) {
473
557
  ...(Array.isArray(value.enum) ? { enum: value.enum } : {}),
474
558
  };
475
559
  });
476
- validateSQLPlaceholders(sql, params.length);
560
+ const problems = [];
561
+ checkSQLPlaceholders(sql, rawParams, problems);
562
+ if (problems.length)
563
+ throw new Error(problems.join(' '));
477
564
  return JSON.stringify({
478
565
  $schema: JSON_SCHEMA_DRAFT_2020_12,
479
566
  type: 'array',
@@ -23,8 +23,8 @@ import { projectLayout } from './project-layout.js';
23
23
  import { sourceArchiveEntryIgnored } from './source-archive-inputs.js';
24
24
  import { inspectPage } from './page-inspection.js';
25
25
  import { parse as parseJSONC } from 'jsonc-parser';
26
- import { namedSQLParamSchema, sqlParamSchema as positionalSQLSchema, deriveSQLInputSchema, normalizeFunctionInputSchema, checkFaaSInputSchemaContract, } from './function-schema.js';
27
- import { checkDeclaredParameters, sqlEnumType, mutationEnumType, } from './function-params.js';
26
+ import { namedSQLParamSchema, checkSQLFunctionParameters, normalizeFunctionInputSchema, checkFaaSInputSchemaContract, } from './function-schema.js';
27
+ import { checkDeclaredParameters, mutationEnumType, } from './function-params.js';
28
28
  import { validateFunctionDescription, functionDescriptionHint, } from './function-description.js';
29
29
  import { readMutationMetaItem } from './mutation.js';
30
30
  import { bindFunctionBatchSnapshot, withFunctionBatchCapability, batchClientWarning, } from './function-batch.js';
@@ -32,8 +32,10 @@ export async function runCompiler(request) {
32
32
  if (request.protocolVersion !== 1)
33
33
  throw Error('Unsupported compiler protocol version');
34
34
  if (!path.isAbsolute(request.root) ||
35
- !['server', 'server-functions'].includes(request.server))
36
- throw Error('Invalid compiler project layout');
35
+ request.server !== 'server' ||
36
+ request.legacyBuild === true)
37
+ throw Error('PROJECT_LAYOUT_UNSUPPORTED: compiler requires a version 2 workspace with named inputs');
38
+ projectLayout(request.root);
37
39
  if (request.operation === 'validate-dependencies') {
38
40
  const policy = parsePackageDependencyPolicy(request.dependencyPolicy);
39
41
  validateWorkspacePackageDependencies(request.root, policy);
@@ -42,7 +44,7 @@ export async function runCompiler(request) {
42
44
  }
43
45
  if (request.operation === 'validate-locks') {
44
46
  for (const directory of projectLayout(request.root).dependencies)
45
- validateDependencyLock(path.join(request.root, directory), directory, '10.9.2');
47
+ validateDependencyLock(path.join(request.root, directory), directory, '11.21.3');
46
48
  return;
47
49
  }
48
50
  const triggerIDs = new Set();
@@ -140,11 +142,9 @@ export async function runCompiler(request) {
140
142
  for (const input of [
141
143
  'page',
142
144
  'server',
143
- 'server-functions',
144
145
  'contract',
145
146
  'contracts',
146
147
  'database-functions',
147
- 'sql',
148
148
  'mutations',
149
149
  'ai',
150
150
  'skill',
@@ -241,14 +241,9 @@ export async function runCompiler(request) {
241
241
  schema.description = param.description;
242
242
  return schema;
243
243
  }
244
- function legacyContracts(functions, inputs, bindBatch) {
244
+ function collectDatabaseContracts(functions, inputs, bindBatch) {
245
245
  for (const [directory, type] of [
246
- [
247
- fs.existsSync(path.join(root, 'database-functions'))
248
- ? 'database-functions'
249
- : 'sql',
250
- 1,
251
- ],
246
+ ['database-functions', 1],
252
247
  ['mutations', 5],
253
248
  ]) {
254
249
  for (const id of entries(path.join(root, directory))) {
@@ -258,40 +253,48 @@ export async function runCompiler(request) {
258
253
  const descriptionHint = functionDescriptionHint(metadata.description, path.join(directory, id, 'meta.json'));
259
254
  if (descriptionHint)
260
255
  functionHints.push({ ...descriptionHint, functionId: id });
256
+ const file = path.join(directory, id, type === 1 ? 'meta.json' : 'spec.json');
257
+ let params, declared;
261
258
  if (type === 1) {
262
259
  let meta = metadata.meta;
263
260
  if (meta === undefined)
264
261
  meta = { params: [] };
265
262
  else if (!meta || typeof meta !== 'object' || Array.isArray(meta))
266
- throw Error('SQL meta must be an object: ' + id);
263
+ throw Error(file + ': meta must be an object containing a params array.');
267
264
  else if (!Object.hasOwn(meta, 'params'))
268
265
  meta = { ...meta, params: [] };
269
266
  const sqlPath = safe(path.join(root, directory, id, 'main.sql'));
270
267
  // Metadata-only codegen can run before SQL is authored. The Go
271
268
  // project check requires complete declarations before any upload.
269
+ let sql;
272
270
  if (fs.existsSync(sqlPath) || bindBatch) {
273
- const sql = fs.readFileSync(sqlPath, 'utf8');
274
- deriveSQLInputSchema(meta, sql);
271
+ sql = fs.readFileSync(sqlPath, 'utf8');
275
272
  if (bindBatch)
276
273
  localSQLSources[id] =
277
274
  'sha256:' + digest(JSON.stringify({ sql, meta }));
278
275
  }
276
+ params = meta.params ?? [];
277
+ declared = checkSQLFunctionParameters(params, sql, file);
279
278
  }
280
279
  else {
281
280
  readMutationMetaItem(safe(path.join(root, directory, id, 'meta.json')), root);
281
+ params =
282
+ readJSON(path.join(root, directory, id, 'spec.json')).params ?? [];
283
+ declared = checkDeclaredParameters(params, {
284
+ label: 'spec.params',
285
+ pointer: '/params',
286
+ file,
287
+ enumType: mutationEnumType,
288
+ });
289
+ }
290
+ if (declared.problems.length) {
291
+ if (type !== 1)
292
+ throw Error(declared.problems.join('; '));
293
+ const advice = declared.hints
294
+ .filter((h) => h.kind === 'parameter_declaration')
295
+ .map((h) => h.message);
296
+ throw Error(`${file}: ${[...declared.problems, ...advice].join(' ')}`);
282
297
  }
283
- const params = type === 1
284
- ? (metadata.meta?.params ?? [])
285
- : (readJSON(path.join(root, directory, id, 'spec.json')).params ??
286
- []);
287
- const declared = checkDeclaredParameters(params, {
288
- label: type === 1 ? 'meta.params' : 'spec.params',
289
- pointer: type === 1 ? '/meta/params' : '/params',
290
- file: path.join(directory, id, type === 1 ? 'meta.json' : 'spec.json'),
291
- enumType: type === 1 ? sqlEnumType : mutationEnumType,
292
- });
293
- if (declared.problems.length)
294
- throw Error(declared.problems.join('; '));
295
298
  functionHints.push(...declared.hints.map((hint) => ({ ...hint, functionId: id })));
296
299
  const input = {
297
300
  type: 'object',
@@ -314,71 +317,6 @@ export async function runCompiler(request) {
314
317
  }
315
318
  }
316
319
  }
317
- function sdkAt(directory) {
318
- const file = safe(path.join(directory, 'package.json'));
319
- if (fs.existsSync(file)) {
320
- const manifest = JSON.parse(fs.readFileSync(file, 'utf8'));
321
- if (manifest.dependencies?.['@lark-base-open/base-database-app-sdk'] ||
322
- manifest.devDependencies?.['@lark-base-open/base-database-app-sdk'])
323
- return true;
324
- }
325
- try {
326
- createRequire(file).resolve('@lark-base-open/base-database-app-sdk/page');
327
- return true;
328
- }
329
- catch {
330
- return false;
331
- }
332
- }
333
- function schemaType(schema) {
334
- if (!schema || typeof schema !== 'object')
335
- return 'unknown';
336
- if (Array.isArray(schema.enum))
337
- return schema.enum.map((v) => JSON.stringify(v)).join(' | ') || 'never';
338
- if (schema.anyOf || schema.oneOf)
339
- return (schema.anyOf ?? schema.oneOf).map(schemaType).join(' | ');
340
- if (Array.isArray(schema.type))
341
- return schema.type
342
- .map((type) => schemaType({ ...schema, type }))
343
- .join(' | ');
344
- switch (schema.type) {
345
- case 'string':
346
- case 'boolean':
347
- case 'null':
348
- return schema.type;
349
- case 'integer':
350
- case 'number':
351
- return 'number';
352
- case 'array':
353
- return schema.prefixItems
354
- ? '[' + schema.prefixItems.map(schemaType).join(', ') + ']'
355
- : 'Array<' + schemaType(schema.items) + '>';
356
- case 'object':
357
- return ('{' +
358
- Object.entries(schema.properties ?? {})
359
- .map(([name, value]) => `${JSON.stringify(name)}${schema.required?.includes(name) ? '' : '?'}: ${schemaType(value)}`)
360
- .join('; ') +
361
- '}');
362
- default:
363
- return 'unknown';
364
- }
365
- }
366
- function writeLegacyInputs(inputs, write) {
367
- const members = inputs.map((item) => {
368
- let schema = item.inputSchema;
369
- if (item.functionType !== 2 && request.inputMode !== 'named')
370
- schema = {
371
- type: 'array',
372
- prefixItems: item.functionType === 1
373
- ? item.parameters.map(positionalSQLSchema)
374
- : Object.values(item.inputSchema.properties ?? {}),
375
- };
376
- return `${JSON.stringify(item.functionId)}: ${schemaType(schema)}`;
377
- });
378
- generatedFile('page/src/lib/database-function-inputs.generated.ts', '// Generated by base-database-toolchain.\nexport type DatabaseFunctionInputMap = {\n' +
379
- members.join(';\n') +
380
- '\n};\n', write);
381
- }
382
320
  async function isolatedCodegen(input) {
383
321
  return runSDKCodegen(root, input, server);
384
322
  }
@@ -545,7 +483,6 @@ export async function runCompiler(request) {
545
483
  triggerLocations.length = 0;
546
484
  triggerCount = 0;
547
485
  const changes = [];
548
- let sdkDeclarations = 0;
549
486
  for (const kind of ['functions', 'durable'])
550
487
  for (const id of entries(path.join(serverRoot, kind))) {
551
488
  const directory = path.join(serverRoot, kind, id), entry = path.join(directory, 'index.ts');
@@ -578,7 +515,6 @@ export async function runCompiler(request) {
578
515
  }
579
516
  continue;
580
517
  }
581
- sdkDeclarations++;
582
518
  if (kind === 'functions')
583
519
  generatedContractIds.add(id);
584
520
  const converted = await schemas(directory, decl);
@@ -660,7 +596,7 @@ export async function runCompiler(request) {
660
596
  });
661
597
  }
662
598
  }
663
- legacyContracts(functions, inputs, !!(request.batchSnapshot || previous));
599
+ collectDatabaseContracts(functions, inputs, !!(request.batchSnapshot || previous));
664
600
  let batchSnapshot;
665
601
  if (request.batchSnapshot || previous) {
666
602
  const errors = [];
@@ -687,7 +623,7 @@ export async function runCompiler(request) {
687
623
  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.',
688
624
  });
689
625
  const clientPath = safe('page/src/generated/functions.ts');
690
- const pageSDK = server === 'server' || sdkAt('page');
626
+ const pageSDK = true;
691
627
  const hasFaaS = functions.some((item) => item.functionType === 2);
692
628
  const client = inputs.length > 0 && (hasFaaS || pageSDK);
693
629
  if (fs.existsSync(clientPath) &&
@@ -708,7 +644,7 @@ export async function runCompiler(request) {
708
644
  const generated = {
709
645
  contractFormatVersion: 1,
710
646
  version: 1,
711
- layout: server === 'server' ? 'workspace' : 'classic',
647
+ layout: 'workspace',
712
648
  schemaHash: 'sha256:' + digest(JSON.stringify(functions)),
713
649
  ...(batchSnapshot ? { batchSnapshot } : {}),
714
650
  functions,
@@ -730,12 +666,10 @@ export async function runCompiler(request) {
730
666
  !equal(readJSON(safe(manifest)), generated))
731
667
  stale();
732
668
  if (!resolveSDKCodegenEntry(root, server)) {
733
- if (sdkDeclarations)
734
- throw new SDKCodegenError('SDK_CODEGEN_UNAVAILABLE', 'Cannot resolve the installed SDK codegen entry for this project.');
735
- const warning = batchClientWarning(generated, []);
736
- if (warning)
737
- warnings.push(warning);
738
- writeLegacyInputs(inputs, write);
669
+ if (!request.runtimeOnly)
670
+ throw new SDKCodegenError('SDK_CODEGEN_UNAVAILABLE', 'Cannot resolve the installed SDK codegen entry for this workspace.');
671
+ // Runtime-only generation never fabricates a Page client or substitutes
672
+ // a CLI-maintained helper for the project's SDK code generator.
739
673
  writeJSON(path.join(stateRoot, 'lark-site-contract-report.json'), contractReport(functions, inputs));
740
674
  return;
741
675
  }
@@ -752,42 +686,12 @@ export async function runCompiler(request) {
752
686
  }
753
687
  }
754
688
  const { durable: workflowContracts, ...sdkContracts } = generated;
755
- // The Page SDK client always uses named transport. Classic helper maps
756
- // retain their configured calling convention in a separate generated file.
689
+ // The Page SDK client always uses named transport.
757
690
  const output = await isolatedCodegen({
758
691
  ...sdkContracts,
759
692
  layout: 'workspace',
760
693
  previousAugmentation,
761
694
  });
762
- if (server === 'server-functions') {
763
- const helperInputs = inputs.map((item) => {
764
- if (request.inputMode === 'named' || item.functionType === 2)
765
- return item;
766
- return {
767
- ...item,
768
- inputSchema: {
769
- $schema: 'https://json-schema.org/draft/2020-12/schema',
770
- type: 'array',
771
- prefixItems: item.functionType === 1
772
- ? item.parameters.map(positionalSQLSchema)
773
- : Object.values(item.inputSchema.properties ?? {}),
774
- minItems: item.functionType === 1
775
- ? item.parameters.length
776
- : item.parameters.reduce((last, p, i) => (p.required === false ? last : i + 1), 0),
777
- maxItems: item.parameters.length,
778
- },
779
- };
780
- });
781
- output.push(...(await isolatedCodegen({
782
- ...sdkContracts,
783
- layout: 'classic',
784
- inputs: helperInputs,
785
- functions: [],
786
- client: false,
787
- augmentation: 'none',
788
- previousAugmentation: undefined,
789
- })));
790
- }
791
695
  const warning = batchClientWarning(generated, output);
792
696
  if (warning)
793
697
  warnings.push(warning);
@@ -808,7 +712,7 @@ export async function runCompiler(request) {
808
712
  }
809
713
  writeJSON(path.join(stateRoot, 'lark-site-contract-report.json'), contractReport(functions, inputs));
810
714
  }
811
- function inspectServerEnvironment(built) {
715
+ function inspectServerEnvironment(built, inspectOnly = false) {
812
716
  const environment = new Set();
813
717
  function visit(directory) {
814
718
  if (!fs.existsSync(directory))
@@ -874,6 +778,8 @@ export async function runCompiler(request) {
874
778
  }
875
779
  }
876
780
  visit(serverRoot);
781
+ if (inspectOnly)
782
+ return;
877
783
  writeJSON(path.join(stateRoot, 'lark-site-compiler-report.json'), {
878
784
  environmentVariables: [...environment].sort(),
879
785
  ...(built
@@ -927,8 +833,9 @@ export async function runCompiler(request) {
927
833
  else if (operation === 'build' ||
928
834
  operation === 'build-server' ||
929
835
  operation === 'durable-dev') {
836
+ inspectServerEnvironment(undefined, true);
930
837
  let built;
931
- if (!request.legacyBuild) {
838
+ {
932
839
  const tsc = path.join(path.dirname(requireProject.resolve('typescript/package.json')), 'bin/tsc');
933
840
  if (entries(path.join(serverRoot, 'functions')).length ||
934
841
  entries(path.join(serverRoot, 'durable')).length)
@@ -1,13 +1,8 @@
1
1
  export declare const DATABASE_FUNCTIONS_DIRECTORY = "database-functions";
2
- export declare const LEGACY_DATABASE_FUNCTIONS_DIRECTORY = "sql";
3
- export declare function databaseFunctionsDirectory(workspace: string): typeof DATABASE_FUNCTIONS_DIRECTORY | typeof LEGACY_DATABASE_FUNCTIONS_DIRECTORY | undefined;
4
- export declare function requireDatabaseFunctionsDirectory(workspace: string): typeof DATABASE_FUNCTIONS_DIRECTORY | typeof LEGACY_DATABASE_FUNCTIONS_DIRECTORY;
2
+ export declare function databaseFunctionsDirectory(workspace: string): typeof DATABASE_FUNCTIONS_DIRECTORY | undefined;
3
+ export declare function requireDatabaseFunctionsDirectory(workspace: string): typeof DATABASE_FUNCTIONS_DIRECTORY;
5
4
  /** Explicit configuration selects the layout; dependencies never select it. */
6
5
  export declare function projectLayout(workspace: string): {
7
- version: 1;
8
- server: string;
9
- dependencies: string[];
10
- } | {
11
6
  version: 2;
12
7
  server: string;
13
8
  dependencies: string[];
@@ -2,24 +2,17 @@ import { parseProjectConfig } from './app-builder/core.mjs';
2
2
  import { existsSync, readFileSync, lstatSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  export const DATABASE_FUNCTIONS_DIRECTORY = 'database-functions';
5
- export const LEGACY_DATABASE_FUNCTIONS_DIRECTORY = 'sql';
6
5
  export function databaseFunctionsDirectory(workspace) {
7
- const canonical = existsSync(join(workspace, DATABASE_FUNCTIONS_DIRECTORY));
8
- const legacy = existsSync(join(workspace, LEGACY_DATABASE_FUNCTIONS_DIRECTORY));
9
- if (canonical && legacy) {
10
- throw new Error(`Project cannot contain both ${DATABASE_FUNCTIONS_DIRECTORY}/ and legacy ${LEGACY_DATABASE_FUNCTIONS_DIRECTORY}/ directories`);
11
- }
12
- if (canonical)
13
- return DATABASE_FUNCTIONS_DIRECTORY;
14
- if (legacy)
15
- return LEGACY_DATABASE_FUNCTIONS_DIRECTORY;
16
- return undefined;
6
+ if (existsSync(join(workspace, 'sql')))
7
+ throw new Error('PROJECT_LAYOUT_UNSUPPORTED: sql/ is not supported; use database-functions/');
8
+ return existsSync(join(workspace, DATABASE_FUNCTIONS_DIRECTORY))
9
+ ? DATABASE_FUNCTIONS_DIRECTORY
10
+ : undefined;
17
11
  }
18
12
  export function requireDatabaseFunctionsDirectory(workspace) {
19
13
  const directory = databaseFunctionsDirectory(workspace);
20
- if (!directory) {
14
+ if (!directory)
21
15
  throw new Error(`Required project directory is missing: ${DATABASE_FUNCTIONS_DIRECTORY}`);
22
- }
23
16
  return directory;
24
17
  }
25
18
  /** Explicit configuration selects the layout; dependencies never select it. */
@@ -28,25 +21,15 @@ export function projectLayout(workspace) {
28
21
  const config = existsSync(configPath)
29
22
  ? parseProjectConfig(readFileSync(configPath, 'utf8'), configPath)
30
23
  : {};
31
- const version = config?.template === undefined ? 1 : config.template?.version;
32
24
  const fail = (message) => {
33
25
  throw new Error(`TEMPLATE_LAYOUT_CONFLICT: ${message}`);
34
26
  };
35
- if (version !== 1 && version !== 2)
36
- fail(`Unsupported template version ${String(version)}`);
37
- if (version === 1) {
38
- if (existsSync(join(workspace, 'server')))
39
- fail('Template 1 cannot contain server/');
40
- const rootManifest = join(workspace, 'package.json');
41
- if (existsSync(rootManifest) &&
42
- JSON.parse(readFileSync(rootManifest, 'utf8')).workspaces)
43
- fail('Template 1 cannot contain root workspaces');
44
- return {
45
- version: 1,
46
- server: 'server-functions',
47
- dependencies: ['page', 'server-functions'],
48
- };
49
- }
27
+ if (config?.template?.version !== 2 ||
28
+ config.template.name !== 'database-starter')
29
+ fail('PROJECT_LAYOUT_UNSUPPORTED: only template.version 2 workspace projects are supported');
30
+ if (config.functionInputs !== undefined && config.functionInputs !== 'named')
31
+ fail('PROJECT_LAYOUT_UNSUPPORTED: workspace clients require named inputs');
32
+ databaseFunctionsDirectory(workspace);
50
33
  if (existsSync(join(workspace, 'server-functions')))
51
34
  fail('Template 2 cannot contain server-functions/');
52
35
  for (const directory of ['page', 'server']) {
@@ -21,28 +21,17 @@ export class SDKCodegenError extends Error {
21
21
  };
22
22
  }
23
23
  }
24
- function dependencyRecovery(root) {
25
- const layout = {
26
- version: existsSync(join(root, 'server')) ? 2 : 1,
27
- dependencies: ['page', 'server-functions'],
28
- };
29
- const install = layout.version === 2
30
- ? 'npm ci'
31
- : layout.dependencies
32
- .map((directory) => `npm ci --prefix ${directory}`)
33
- .join('; ');
24
+ function dependencyRecovery() {
34
25
  return [
35
- `From the project root, restore dependencies from the existing manifests and lockfiles: ${install}. Keep the declared SDK version unchanged.`,
26
+ `From the project root, restore dependencies from the existing manifests and lockfiles: npm ci. Keep the declared SDK version unchanged.`,
36
27
  'If dependencies are already installed but the SDK lacks codegen, keep the current SDK and upgrade only with user authorization; follow its Migration instructions.',
37
28
  'Once codegen is available, use the same CLI and environment to run contracts generate, then check --json.',
38
29
  ];
39
30
  }
40
- function unavailable(root, missingExport = false) {
31
+ function unavailable(_root, missingExport = false) {
41
32
  throw new SDKCodegenError('SDK_CODEGEN_UNAVAILABLE', missingExport
42
33
  ? 'The installed SDK codegen does not export generateFunctionClients.'
43
- : 'Cannot resolve the installed SDK codegen entry. Project dependencies may not be installed, or the installed SDK may not provide codegen.', missingExport
44
- ? dependencyRecovery(root).slice(1)
45
- : dependencyRecovery(root));
34
+ : 'Cannot resolve the installed SDK codegen entry. Project dependencies may not be installed, or the installed SDK may not provide codegen.', missingExport ? dependencyRecovery().slice(1) : dependencyRecovery());
46
35
  }
47
36
  // Node 24 removed the experimental spelling; early Node 22 releases only have it.
48
37
  const permissionFlag = process.allowedNodeEnvironmentFlags.has('--permission')
@@ -50,6 +39,12 @@ const permissionFlag = process.allowedNodeEnvironmentFlags.has('--permission')
50
39
  : '--experimental-permission';
51
40
  /** Resolve/snapshot reads package bytes only; project modules execute only in the restricted child. */
52
41
  export function runSDKCodegen(root, data, server = 'server') {
42
+ if (server !== 'server' ||
43
+ (data &&
44
+ typeof data === 'object' &&
45
+ 'layout' in data &&
46
+ data.layout !== 'workspace'))
47
+ throw new SDKCodegenError('PROJECT_LAYOUT_UNSUPPORTED', 'Code generation requires named workspace contracts.');
53
48
  const entry = resolveSDKCodegenEntry(root, server);
54
49
  if (!entry)
55
50
  unavailable(root);
@@ -75,6 +70,17 @@ globalThis.WebSocket = undefined;
75
70
  const input = JSON.parse(require('node:fs').readFileSync(__dirname + '/input.json','utf8'));
76
71
  const sdk = require('@lark-base-open/base-database-app-sdk/codegen');
77
72
  if (typeof sdk.generateFunctionClients !== 'function') throw Object.assign(new Error('SDK codegen export missing'),{code:'SDK_CODEGEN_UNAVAILABLE'});
73
+ // SDKs without DML_BATCH_LIMITS accept at most 200 groups at codegen and at runtime;
74
+ // cap the published value to the installed SDK so a raised backend limit keeps its batch clients.
75
+ const declared = sdk.DML_BATCH_LIMITS;
76
+ const limit = key => declared && Number.isSafeInteger(declared[key]) && declared[key] >= 1 ? declared[key] : 200;
77
+ for (const list of ['functions','inputs']) if (Array.isArray(input[list])) input[list] = input[list].map(fn => {
78
+ const c = fn && fn.batchCapability;
79
+ if (!c || typeof c !== 'object' || Array.isArray(c)) return fn;
80
+ const next = {...c};
81
+ for (const key of ['maxGroups','maxTotalRows']) if (Number.isSafeInteger(next[key]) && next[key] > limit(key)) next[key] = limit(key);
82
+ return {...fn, batchCapability: next};
83
+ });
78
84
  const files = await sdk.generateFunctionClients(input);
79
85
  process.stdout.write(JSON.stringify({ok:true,files}));
80
86
  } catch (error) {
@@ -1,21 +1,21 @@
1
1
  {
2
2
  "name": "@lark-base-open/base-database-toolchain",
3
- "version": "1.4.0",
3
+ "version": "2.0.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@lark-base-open/base-database-toolchain",
9
- "version": "1.4.0",
9
+ "version": "2.0.0",
10
10
  "license": "SEE LICENSE IN LICENSE",
11
11
  "dependencies": {
12
12
  "@babel/parser": "7.28.5",
13
13
  "@babel/traverse": "7.28.5",
14
- "ajv": "8.17.1",
14
+ "ajv": "8.20.0",
15
15
  "esbuild": "0.28.2",
16
16
  "jsonc-parser": "3.3.1",
17
17
  "parse5": "7.3.0",
18
- "re2js": "2.8.6"
18
+ "re2js": "2.10.0"
19
19
  },
20
20
  "bin": {
21
21
  "base-database-dev": "bin/base-database-dev.mjs",
@@ -978,9 +978,9 @@
978
978
  }
979
979
  },
980
980
  "node_modules/ajv": {
981
- "version": "8.17.1",
982
- "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz",
983
- "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
981
+ "version": "8.20.0",
982
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",
983
+ "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",
984
984
  "license": "MIT",
985
985
  "dependencies": {
986
986
  "fast-deep-equal": "^3.1.3",
@@ -1140,12 +1140,12 @@
1140
1140
  "license": "ISC"
1141
1141
  },
1142
1142
  "node_modules/re2js": {
1143
- "version": "2.8.6",
1144
- "resolved": "https://registry.npmjs.org/re2js/-/re2js-2.8.6.tgz",
1145
- "integrity": "sha512-xLgQil4kIUCrAzVk9fRSkxkFNwmygLFjVxXrLc65aE1F0+Zsb8rxumFBy4XKyvgMCTL6kilDq3EZ0piE2dP/Dg==",
1143
+ "version": "2.10.0",
1144
+ "resolved": "https://registry.npmjs.org/re2js/-/re2js-2.10.0.tgz",
1145
+ "integrity": "sha512-/P6FNnLbHjXJMRF1dPoZoVTyHvFcuVhbDpzml9DPMlbeErYlZ18GueAaG9GhYhAm/9AN7i7Y6crmDrLX0DeJ4Q==",
1146
1146
  "license": "MIT",
1147
1147
  "engines": {
1148
- "node": ">=18.0.0"
1148
+ "node": ">=20.0.0"
1149
1149
  }
1150
1150
  },
1151
1151
  "node_modules/require-from-string": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lark-base-open/base-database-toolchain",
3
- "version": "1.4.0",
3
+ "version": "2.0.0",
4
4
  "description": "Shared local development toolchain for Base Database application CLIs",
5
5
  "type": "module",
6
6
  "license": "SEE LICENSE IN LICENSE",
@@ -89,11 +89,11 @@
89
89
  "dependencies": {
90
90
  "@babel/parser": "7.28.5",
91
91
  "@babel/traverse": "7.28.5",
92
- "ajv": "8.17.1",
92
+ "ajv": "8.20.0",
93
93
  "esbuild": "0.28.2",
94
94
  "jsonc-parser": "3.3.1",
95
95
  "parse5": "7.3.0",
96
- "re2js": "2.8.6"
96
+ "re2js": "2.10.0"
97
97
  },
98
98
  "devDependencies": {
99
99
  "typescript": "7.0.2",