@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,8 @@
1
+ export { extractContract, convertContract } from './contract-extractor.js';
2
+ export { convertLoadedContract } from './contract-conversion.js';
3
+ export { validateTriggerDeclarations } from './trigger-validation.js';
4
+ export { driveLocalDurable, parseDurableEvents } from './durable-runner.js';
5
+ export { runSDKCodegen, SDKCodegenError } from './sdk-codegen.js';
6
+ export { runCompiler } from './go-adapter.mjs';
7
+ export { inspectPage, inspectDevBootstrap, sdkPackageRoot, checkLinkGuard, type PageInspection, type DevBootstrapStatus, } from './page-inspection.js';
8
+ export { normalizeDMLBatchCapability, normalizeFunctionExecutionSnapshot, bindFunctionBatchSnapshot, withFunctionBatchCapability, batchClientWarning, type DMLBatchCapability, type FunctionBatchSnapshot, type FunctionExecutionSnapshot, type BoundFunctionBatchSnapshot, } from './function-batch.js';
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
1
+ export { extractContract, convertContract } from './contract-extractor.js';
2
+ export { convertLoadedContract } from './contract-conversion.js';
3
+ export { validateTriggerDeclarations } from './trigger-validation.js';
4
+ export { driveLocalDurable, parseDurableEvents } from './durable-runner.js';
5
+ export { runSDKCodegen, SDKCodegenError } from './sdk-codegen.js';
6
+ export { runCompiler } from './go-adapter.mjs';
7
+ export { inspectPage, inspectDevBootstrap, sdkPackageRoot, checkLinkGuard, } from './page-inspection.js';
8
+ export { normalizeDMLBatchCapability, normalizeFunctionExecutionSnapshot, bindFunctionBatchSnapshot, withFunctionBatchCapability, batchClientWarning, } from './function-batch.js';
@@ -0,0 +1,3 @@
1
+ export type DevBootstrapStatus = 'ready' | 'not-bootstrapped' | 'uncertain';
2
+ export declare function sdkPackageRoot(workspace: string): string | undefined;
3
+ export declare function inspectDevBootstrap(workspace: string): DevBootstrapStatus;
@@ -0,0 +1,178 @@
1
+ import { createRequire } from 'node:module';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import { existsSync, readFileSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { parse } from 'parse5';
6
+ import { parse as parseJavaScript } from '@babel/parser';
7
+ import { parseModule, walkAst } from './contract-extractor.js';
8
+ const sdkPackage = '@lark-base-open/base-database-app-sdk';
9
+ const registeredHmr = JSON.parse(readFileSync(new URL('./data/template-hmr-scripts.json', import.meta.url), 'utf8')).scripts.map(({ code }) => shape(parseJavaScript(code, { sourceType: 'module' }).program));
10
+ function isRegisteredHmr(code) {
11
+ try {
12
+ const ast = shape(parseJavaScript(code, { sourceType: 'module' }).program);
13
+ return registeredHmr.some((expected) => isDeepStrictEqual(ast, expected));
14
+ }
15
+ catch {
16
+ return false;
17
+ }
18
+ }
19
+ export function sdkPackageRoot(workspace) {
20
+ const require = createRequire(join(workspace, 'page/package.json'));
21
+ return require.resolve
22
+ .paths(sdkPackage)
23
+ ?.map((path) => join(path, sdkPackage))
24
+ .find((path) => existsSync(join(path, 'package.json')));
25
+ }
26
+ // Compare semantic AST fields, never comments/text fragments. This deliberately
27
+ // accepts only the known migrated starter, including its React mount and effect.
28
+ function shape(value) {
29
+ if (Array.isArray(value))
30
+ return value.map(shape);
31
+ if (!value || typeof value !== 'object')
32
+ return value;
33
+ return Object.fromEntries(Object.entries(value)
34
+ .filter(([key]) => ![
35
+ 'start',
36
+ 'end',
37
+ 'loc',
38
+ 'extra',
39
+ 'comments',
40
+ 'leadingComments',
41
+ 'trailingComments',
42
+ 'innerComments',
43
+ 'tokens',
44
+ ].includes(key))
45
+ .map(([key, child]) => [key, shape(child)]));
46
+ }
47
+ export function inspectDevBootstrap(workspace) {
48
+ const html = join(workspace, 'page/index.html');
49
+ if (!existsSync(html))
50
+ return 'uncertain';
51
+ let source;
52
+ try {
53
+ source = readFileSync(html, 'utf8');
54
+ }
55
+ catch {
56
+ return 'uncertain';
57
+ }
58
+ const scripts = [];
59
+ let inlineCount = 0, invalidInline = false;
60
+ const visitHtml = (node) => {
61
+ if (node.tagName === 'script') {
62
+ const attrs = new Map(node.attrs.map((a) => [a.name, a.value]));
63
+ if (attrs.get('type')?.toLowerCase() === 'module') {
64
+ if (attrs.has('src'))
65
+ scripts.push(attrs.get('src'));
66
+ else {
67
+ inlineCount++;
68
+ const code = node.childNodes
69
+ .map((child) => child.value ?? '')
70
+ .join('');
71
+ if (attrs.size !== 1 || !isRegisteredHmr(code))
72
+ invalidInline = true;
73
+ }
74
+ }
75
+ }
76
+ for (const child of node.childNodes ?? [])
77
+ visitHtml(child);
78
+ };
79
+ visitHtml(parse(source));
80
+ if (invalidInline ||
81
+ inlineCount > 1 ||
82
+ scripts.length !== 1 ||
83
+ !scripts[0] ||
84
+ !/^\/?src\/main\.[cm]?[jt]sx?$/.test(scripts[0]))
85
+ return 'uncertain';
86
+ const entry = join(workspace, 'page', scripts[0].replace(/^\//, ''));
87
+ if (!existsSync(entry))
88
+ return 'uncertain';
89
+ try {
90
+ const ast = parseModule(entry);
91
+ let dynamicImport = false;
92
+ walkAst(ast.program, (n) => {
93
+ if (n.type === 'ImportExpression' ||
94
+ (n.type === 'CallExpression' &&
95
+ n.callee?.type === 'Import'))
96
+ dynamicImport = true;
97
+ });
98
+ const bindings = new Set();
99
+ const namespaces = new Set();
100
+ const hasUnsupportedImport = ast.program.body.some((n) => n.type === 'ImportDeclaration' &&
101
+ ![
102
+ 'react',
103
+ 'react-dom/client',
104
+ '@lark-base-open/base-site-channel/runtime',
105
+ `${sdkPackage}/page`,
106
+ './App',
107
+ './components/database-runtime-ready',
108
+ './lib/database-runtime',
109
+ './index.css',
110
+ ].includes(String(n.source?.value)));
111
+ for (const item of ast.program.body) {
112
+ if (item.type !== 'ImportDeclaration')
113
+ continue;
114
+ const importSource = item.source;
115
+ if (importSource?.value !== `${sdkPackage}/page` ||
116
+ item.importKind === 'type')
117
+ continue;
118
+ for (const specifier of item.specifiers ?? []) {
119
+ const local = specifier.local;
120
+ const imported = specifier.imported;
121
+ if (specifier.type === 'ImportNamespaceSpecifier' && local?.name)
122
+ namespaces.add(String(local.name));
123
+ if (specifier.type === 'ImportSpecifier' &&
124
+ local?.name &&
125
+ (imported?.name ?? imported?.value) === 'startBaseApp' &&
126
+ specifier.importKind !== 'type')
127
+ bindings.add(String(local.name));
128
+ }
129
+ }
130
+ // Only direct top-level expression/initializer calls are provably executed.
131
+ // Calls under functions, conditionals, aliases or computed access fail closed.
132
+ const isStart = (node) => {
133
+ if (!node)
134
+ return false;
135
+ if (node.type === 'AwaitExpression' ||
136
+ (node.type === 'UnaryExpression' && node.operator === 'void'))
137
+ return isStart(node.argument);
138
+ if (node.type !== 'CallExpression' || node.optional)
139
+ return false;
140
+ const callee = node.callee;
141
+ if (callee.type === 'Identifier')
142
+ return bindings.has(String(callee.name));
143
+ return (callee.type === 'MemberExpression' &&
144
+ !callee.computed &&
145
+ callee.object?.type === 'Identifier' &&
146
+ namespaces.has(String(callee.object.name)) &&
147
+ callee.property?.name === 'startBaseApp');
148
+ };
149
+ for (const item of ast.program.body) {
150
+ if (item.type === 'ExpressionStatement' &&
151
+ isStart(item.expression))
152
+ return 'ready';
153
+ if (item.type === 'VariableDeclaration' &&
154
+ item.declarations.some((d) => isStart(d.init)))
155
+ return 'ready';
156
+ // Stop at control flow: later calls may never be reached. Imports/declarations
157
+ // do not execute their bodies, so shadowed parameters cannot count as calls.
158
+ if ([
159
+ 'ThrowStatement',
160
+ 'IfStatement',
161
+ 'TryStatement',
162
+ 'WhileStatement',
163
+ 'ForStatement',
164
+ 'SwitchStatement',
165
+ ].includes(String(item.type)))
166
+ break;
167
+ }
168
+ if (bindings.size ||
169
+ namespaces.size ||
170
+ hasUnsupportedImport ||
171
+ dynamicImport)
172
+ return 'uncertain';
173
+ return 'not-bootstrapped';
174
+ }
175
+ catch {
176
+ return 'uncertain';
177
+ }
178
+ }
@@ -0,0 +1,11 @@
1
+ import { type DevBootstrapStatus } from './page-bootstrap.js';
2
+ import { type LinkGuardWarning } from './page-link-guard.js';
3
+ export { inspectDevBootstrap, sdkPackageRoot, type DevBootstrapStatus, } from './page-bootstrap.js';
4
+ export { checkLinkGuard, type LinkGuardWarning } from './page-link-guard.js';
5
+ export interface PageInspection {
6
+ protocolVersion: 1;
7
+ bootstrap: DevBootstrapStatus;
8
+ warnings: LinkGuardWarning[];
9
+ }
10
+ /** Inspection never follows project links or executes application modules. */
11
+ export declare function inspectPage(workspace: string): PageInspection;
@@ -0,0 +1,49 @@
1
+ import { existsSync, lstatSync, readdirSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { inspectDevBootstrap, } from './page-bootstrap.js';
4
+ import { checkLinkGuard } from './page-link-guard.js';
5
+ export { inspectDevBootstrap, sdkPackageRoot, } from './page-bootstrap.js';
6
+ export { checkLinkGuard } from './page-link-guard.js';
7
+ /** Inspection never follows project links or executes application modules. */
8
+ export function inspectPage(workspace) {
9
+ const result = {
10
+ protocolVersion: 1,
11
+ bootstrap: 'uncertain',
12
+ warnings: [],
13
+ };
14
+ try {
15
+ let files = 0;
16
+ const inspect = (file) => {
17
+ if (++files > 20000)
18
+ throw Error('Page source inspection budget exceeded');
19
+ const info = lstatSync(file);
20
+ if (info.isSymbolicLink())
21
+ throw Error('Page source contains a link');
22
+ if (info.isFile() && info.size > 2 * 1024 * 1024)
23
+ throw Error('Page source file exceeds the inspection budget');
24
+ if (info.isDirectory()) {
25
+ for (const name of readdirSync(file)) {
26
+ if (!['node_modules', 'dist', '.git', '.lark-cli'].includes(name))
27
+ inspect(join(file, name));
28
+ }
29
+ }
30
+ };
31
+ const root = join(workspace, 'page');
32
+ if (existsSync(root))
33
+ inspect(root);
34
+ result.bootstrap = inspectDevBootstrap(workspace);
35
+ result.warnings = checkLinkGuard(workspace).map((warning) => ({
36
+ ...warning,
37
+ locations: warning.locations.slice(0, 100),
38
+ ...(warning.locations.length > 100 ? { locationsTruncated: true } : {}),
39
+ }));
40
+ }
41
+ catch {
42
+ result.warnings.push({
43
+ code: 'PAGE_LINK_GUARD_CHECK_SKIPPED',
44
+ message: 'Page source inspection is unavailable or includes unsupported file entries; inspect the project before relying on this syntax check.',
45
+ locations: [],
46
+ });
47
+ }
48
+ return result;
49
+ }
@@ -0,0 +1,12 @@
1
+ export interface LinkGuardWarning {
2
+ code: 'AI_AGENT_TOOLS_SKIPPED' | 'AI_FUNCTION_ROOT_ABSENT_PRESERVED' | 'FUNCTION_CONTRACT_WARNING' | 'FUNCTION_NEEDS_UPGRADE' | 'PAGE_LINK_GUARD_MISSING' | 'PAGE_LINK_GUARD_CHECK_SKIPPED';
3
+ message: string;
4
+ locations: {
5
+ file: string;
6
+ line: number;
7
+ column: number;
8
+ }[];
9
+ locationsTruncated?: boolean;
10
+ }
11
+ /** Best-effort syntax warning; does not resolve symbols or execute user code. */
12
+ export declare function checkLinkGuard(workspace: string): LinkGuardWarning[];
@@ -0,0 +1,137 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { extname, join, relative } from 'node:path';
3
+ import { parse } from '@babel/parser';
4
+ const channelPackage = '@lark-base-open/base-site-channel';
5
+ const extensions = new Set(['.ts', '.tsx', '.js', '.jsx']);
6
+ function isNode(value) {
7
+ return (value !== null &&
8
+ typeof value === 'object' &&
9
+ 'type' in value &&
10
+ typeof value.type === 'string');
11
+ }
12
+ // Visit only AST nodes, excluding locations, comments and other parser metadata.
13
+ function walk(value, visit) {
14
+ if (!isNode(value))
15
+ return;
16
+ visit(value);
17
+ for (const [key, child] of Object.entries(value)) {
18
+ if (key === 'comments' || key.endsWith('Comments') || key === 'tokens')
19
+ continue;
20
+ if (Array.isArray(child))
21
+ child.forEach((node) => walk(node, visit));
22
+ else if (isNode(child))
23
+ walk(child, visit);
24
+ }
25
+ }
26
+ function identifier(value, name) {
27
+ return isNode(value) && value.type === 'Identifier' && value.name === name;
28
+ }
29
+ function stringLiteral(value, text) {
30
+ return (isNode(value) && value.type === 'StringLiteral' && value.value === text);
31
+ }
32
+ /** Best-effort syntax warning; does not resolve symbols or execute user code. */
33
+ export function checkLinkGuard(workspace) {
34
+ const root = join(workspace, 'page/src');
35
+ if (!existsSync(root))
36
+ return [];
37
+ const files = [];
38
+ const collect = (directory) => {
39
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
40
+ const path = join(directory, entry.name);
41
+ if (entry.isDirectory() && entry.name !== 'node_modules')
42
+ collect(path);
43
+ else if (entry.isFile() && extensions.has(extname(path)))
44
+ files.push(path);
45
+ }
46
+ };
47
+ collect(root);
48
+ const locations = [];
49
+ let installed = false;
50
+ for (const path of files.sort()) {
51
+ let source;
52
+ try {
53
+ source = parse(readFileSync(path, 'utf8'), {
54
+ sourceType: 'unambiguous',
55
+ plugins: ['typescript', 'jsx'],
56
+ errorRecovery: true,
57
+ });
58
+ // Recovered syntax is also unreliable: discard this file's entire result.
59
+ if (source.errors?.length)
60
+ continue;
61
+ }
62
+ catch {
63
+ continue;
64
+ }
65
+ const guards = new Set();
66
+ const namespaces = new Set();
67
+ for (const statement of source.program.body) {
68
+ if (statement.type !== 'ImportDeclaration' ||
69
+ statement.source.value !== channelPackage ||
70
+ statement.importKind === 'type')
71
+ continue;
72
+ for (const specifier of statement.specifiers) {
73
+ if (specifier.type === 'ImportNamespaceSpecifier')
74
+ namespaces.add(specifier.local.name);
75
+ else if (specifier.type === 'ImportSpecifier' &&
76
+ specifier.importKind !== 'type' &&
77
+ (specifier.imported.type === 'Identifier'
78
+ ? specifier.imported.name
79
+ : specifier.imported.value) === 'installLinkGuard')
80
+ guards.add(specifier.local.name);
81
+ }
82
+ }
83
+ walk(source.program, (node) => {
84
+ if (node.type === 'CallExpression' ||
85
+ node.type === 'OptionalCallExpression') {
86
+ const callee = node.callee;
87
+ if (isNode(callee)) {
88
+ if (callee.type === 'Identifier' &&
89
+ typeof callee.name === 'string' &&
90
+ guards.has(callee.name))
91
+ installed = true;
92
+ if ((callee.type === 'MemberExpression' ||
93
+ callee.type === 'OptionalMemberExpression') &&
94
+ !callee.computed &&
95
+ identifier(callee.property, 'installLinkGuard') &&
96
+ isNode(callee.object) &&
97
+ callee.object.type === 'Identifier' &&
98
+ typeof callee.object.name === 'string' &&
99
+ namespaces.has(callee.object.name))
100
+ installed = true;
101
+ }
102
+ }
103
+ const windowOpen = (node.type === 'MemberExpression' ||
104
+ node.type === 'OptionalMemberExpression') &&
105
+ identifier(node.object, 'window') &&
106
+ (node.computed
107
+ ? stringLiteral(node.property, 'open')
108
+ : identifier(node.property, 'open'));
109
+ const blankTarget = node.type === 'JSXAttribute' &&
110
+ isNode(node.name) &&
111
+ node.name.type === 'JSXIdentifier' &&
112
+ node.name.name === 'target' &&
113
+ (stringLiteral(node.value, '_blank') ||
114
+ (isNode(node.value) &&
115
+ node.value.type === 'JSXExpressionContainer' &&
116
+ stringLiteral(node.value.expression, '_blank')));
117
+ if (windowOpen || blankTarget) {
118
+ // Every parsed source node has a location; metadata nodes are not visited.
119
+ const loc = node.loc;
120
+ locations.push({
121
+ file: relative(workspace, path),
122
+ line: loc.start.line,
123
+ column: loc.start.column + 1,
124
+ });
125
+ }
126
+ });
127
+ }
128
+ return installed || locations.length === 0
129
+ ? []
130
+ : [
131
+ {
132
+ code: 'PAGE_LINK_GUARD_MISSING',
133
+ message: 'Page uses window.open or target="_blank" without a statically detected installLinkGuard call. Follow the installed Channel SDK documentation for >=0.1.5 and initialize its guard in the entry; review any dependency upgrade before changing versions.',
134
+ locations,
135
+ },
136
+ ];
137
+ }
@@ -0,0 +1,16 @@
1
+ export interface CodegenFile {
2
+ path: string;
3
+ content: string;
4
+ }
5
+ export declare class SDKCodegenError extends Error {
6
+ readonly code: string;
7
+ readonly nextActions: string[];
8
+ constructor(code: string, message: string, nextActions?: string[]);
9
+ toJSON(): {
10
+ code: string;
11
+ message: string;
12
+ nextActions?: string[] | undefined;
13
+ };
14
+ }
15
+ /** Resolve/snapshot reads package bytes only; project modules execute only in the restricted child. */
16
+ export declare function runSDKCodegen(root: string, data: unknown, server?: string): CodegenFile[];
@@ -0,0 +1,208 @@
1
+ import { createRequire } from 'node:module';
2
+ import { execFileSync } from 'node:child_process';
3
+ import { existsSync, lstatSync, cpSync, mkdirSync, realpathSync, symlinkSync, mkdtempSync, readFileSync, rmSync, writeFileSync, } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { join, dirname, relative, isAbsolute, sep } from 'node:path';
6
+ const SDK = '@lark-base-open/base-database-app-sdk';
7
+ export class SDKCodegenError extends Error {
8
+ code;
9
+ nextActions;
10
+ constructor(code, message, nextActions = []) {
11
+ super(`${code}: ${message}`);
12
+ this.code = code;
13
+ this.nextActions = nextActions;
14
+ this.name = 'SDKCodegenError';
15
+ }
16
+ toJSON() {
17
+ return {
18
+ code: this.code,
19
+ message: this.message,
20
+ ...(this.nextActions.length ? { nextActions: this.nextActions } : {}),
21
+ };
22
+ }
23
+ }
24
+ const locations = (root, server) => ['page', server, ''].map((p) => join(root, p, 'package.json'));
25
+ function dependencyRecovery(root) {
26
+ const layout = {
27
+ version: existsSync(join(root, 'server')) ? 2 : 1,
28
+ dependencies: ['page', 'server-functions'],
29
+ };
30
+ const install = layout.version === 2
31
+ ? 'npm ci'
32
+ : layout.dependencies
33
+ .map((directory) => `npm ci --prefix ${directory}`)
34
+ .join('; ');
35
+ return [
36
+ `From the project root, restore dependencies from the existing manifests and lockfiles: ${install}. Keep the declared SDK version unchanged.`,
37
+ 'If dependencies are already installed but the SDK lacks codegen, keep the current SDK and upgrade only with user authorization; follow its Migration instructions.',
38
+ 'Once codegen is available, use the same CLI and environment to run contracts generate, then check --json.',
39
+ ];
40
+ }
41
+ function unavailable(root, missingExport = false) {
42
+ throw new SDKCodegenError('SDK_CODEGEN_UNAVAILABLE', missingExport
43
+ ? 'The installed SDK codegen does not export generateFunctionClients.'
44
+ : 'Cannot resolve the installed SDK codegen entry. Project dependencies may not be installed, or the installed SDK may not provide codegen.', missingExport
45
+ ? dependencyRecovery(root).slice(1)
46
+ : dependencyRecovery(root));
47
+ }
48
+ // Node 24 removed the experimental spelling; early Node 22 releases only have it.
49
+ const permissionFlag = process.allowedNodeEnvironmentFlags.has('--permission')
50
+ ? '--permission'
51
+ : '--experimental-permission';
52
+ /** Resolve/snapshot reads package bytes only; project modules execute only in the restricted child. */
53
+ export function runSDKCodegen(root, data, server = 'server') {
54
+ let entry;
55
+ for (const path of locations(root, server)) {
56
+ try {
57
+ entry = createRequire(path).resolve(`${SDK}/codegen`);
58
+ break;
59
+ }
60
+ catch { }
61
+ }
62
+ if (!entry)
63
+ unavailable(root);
64
+ const temp = realpathSync(mkdtempSync(join(tmpdir(), 'base-codegen-')));
65
+ try {
66
+ let packageRoot = dirname(entry);
67
+ while (!existsSync(join(packageRoot, 'package.json')) ||
68
+ JSON.parse(readFileSync(join(packageRoot, 'package.json'), 'utf8'))
69
+ .name !== SDK) {
70
+ const parent = dirname(packageRoot);
71
+ if (parent === packageRoot)
72
+ unavailable(root);
73
+ packageRoot = parent;
74
+ }
75
+ snapshotPackage(packageRoot, join(temp, 'node_modules', SDK), new Map());
76
+ writeFileSync(join(temp, 'input.json'), JSON.stringify(data));
77
+ writeFileSync(join(temp, 'worker.cjs'), `
78
+ 'use strict';
79
+ globalThis.fetch = () => { throw new Error('NETWORK_DISABLED'); };
80
+ globalThis.WebSocket = undefined;
81
+ (async () => {
82
+ try {
83
+ const input = JSON.parse(require('node:fs').readFileSync(__dirname + '/input.json','utf8'));
84
+ const sdk = require('@lark-base-open/base-database-app-sdk/codegen');
85
+ if (typeof sdk.generateFunctionClients !== 'function') throw Object.assign(new Error('SDK codegen export missing'),{code:'SDK_CODEGEN_UNAVAILABLE'});
86
+ const files = await sdk.generateFunctionClients(input);
87
+ process.stdout.write(JSON.stringify({ok:true,files}));
88
+ } catch (error) {
89
+ process.stdout.write(JSON.stringify({ok:false,code:typeof error.code === 'string' ? error.code : 'SDK_CODEGEN_FAILED',message:String(error.message).slice(0,4096)}));
90
+ }
91
+ })();
92
+ `);
93
+ let result;
94
+ try {
95
+ result = JSON.parse(execFileSync(process.execPath, [
96
+ permissionFlag,
97
+ `--allow-fs-read=${temp}`,
98
+ '--max-old-space-size=128',
99
+ join(temp, 'worker.cjs'),
100
+ ], {
101
+ cwd: temp,
102
+ env: {},
103
+ encoding: 'utf8',
104
+ timeout: 5000,
105
+ maxBuffer: 4 * 1024 * 1024,
106
+ stdio: ['ignore', 'pipe', 'pipe'],
107
+ }));
108
+ }
109
+ catch (error) {
110
+ const stderr = String(error.stderr ?? '')
111
+ .trim()
112
+ .slice(0, 1024);
113
+ throw new SDKCodegenError('SDK_CODEGEN_FAILED', `Isolated SDK codegen failed, timed out, or returned invalid JSON${stderr ? `: ${stderr}` : ''}`);
114
+ }
115
+ if (!result.ok &&
116
+ result.code === 'SDK_CODEGEN_UNAVAILABLE' &&
117
+ result.message === 'SDK codegen export missing')
118
+ unavailable(root, true);
119
+ if (!result.ok)
120
+ throw new SDKCodegenError(result.code ?? 'SDK_CODEGEN_FAILED', (result.message ?? 'SDK codegen failed') +
121
+ (result.code === 'CONTRACT_DATA_INVALID'
122
+ ? '; The installed SDK rejected the contract. Verify the CLI/SDK pairing and upgrade to an SDK with structural Schema validation before regenerating; do not rename valid business fields or hand-edit generated files.'
123
+ : ''));
124
+ const allowed = new Set([
125
+ 'page/src/generated/functions.ts',
126
+ 'page/src/generated/function-inputs.ts',
127
+ 'page/src/lib/database-function-inputs.generated.ts',
128
+ 'page/src/lib/function-input-map.generated.ts',
129
+ ]);
130
+ const seen = new Set();
131
+ if (!Array.isArray(result.files) ||
132
+ !result.files.length ||
133
+ result.files.length > 3)
134
+ throw new SDKCodegenError('SDK_CODEGEN_OUTPUT_INVALID', 'Invalid generated file list');
135
+ for (const file of result.files) {
136
+ if (!file ||
137
+ typeof file.path !== 'string' ||
138
+ !allowed.has(file.path) ||
139
+ seen.has(file.path) ||
140
+ typeof file.content !== 'string' ||
141
+ Buffer.byteLength(file.content) > 1024 * 1024)
142
+ throw new SDKCodegenError('SDK_CODEGEN_OUTPUT_INVALID', 'Invalid generated path or content');
143
+ const parts = file.path.split('/');
144
+ for (let i = 1; i <= parts.length; i++) {
145
+ const target = join(root, ...parts.slice(0, i));
146
+ if (existsSync(target) && lstatSync(target).isSymbolicLink())
147
+ throw new SDKCodegenError('SDK_CODEGEN_OUTPUT_INVALID', 'Generated destinations cannot be symbolic links');
148
+ }
149
+ seen.add(file.path);
150
+ }
151
+ return result.files;
152
+ }
153
+ finally {
154
+ rmSync(temp, { recursive: true, force: true });
155
+ }
156
+ }
157
+ function resolvePackage(name, from) {
158
+ if (!/^(?:@[A-Za-z0-9._-]+\/)?[A-Za-z0-9._-]+$/.test(name) ||
159
+ name === '.' ||
160
+ name === '..')
161
+ throw new SDKCodegenError('SDK_CODEGEN_UNAVAILABLE', 'Invalid SDK dependency name');
162
+ let directory = from;
163
+ while (true) {
164
+ const candidate = join(directory, 'node_modules', name);
165
+ if (existsSync(join(candidate, 'package.json')))
166
+ return realpathSync(candidate);
167
+ const parent = dirname(directory);
168
+ if (parent === directory)
169
+ throw new SDKCodegenError('SDK_CODEGEN_UNAVAILABLE', `Missing installed SDK dependency: ${name}. Restore this project's existing locked dependencies and keep the SDK version unchanged.`);
170
+ directory = parent;
171
+ }
172
+ }
173
+ function snapshotPackage(source, destination, copied) {
174
+ source = realpathSync(source);
175
+ mkdirSync(dirname(destination), { recursive: true });
176
+ const previous = copied.get(source);
177
+ if (previous) {
178
+ // Windows junctions reuse snapshot directories without symlink privileges.
179
+ symlinkSync(previous, destination, process.platform === 'win32' ? 'junction' : 'dir');
180
+ return;
181
+ }
182
+ copied.set(source, destination);
183
+ cpSync(source, destination, {
184
+ recursive: true,
185
+ dereference: true,
186
+ filter: (path) => {
187
+ const parts = relative(source, path).split(/[\\/]/);
188
+ if (parts.some((p) => [
189
+ 'node_modules',
190
+ '.git',
191
+ '.npmrc',
192
+ '.pnpmrc',
193
+ '.yarnrc',
194
+ '.yarnrc.yml',
195
+ ].includes(p) ||
196
+ p === '.env' ||
197
+ p.startsWith('.env.')))
198
+ return false;
199
+ const real = realpathSync(path), rel = relative(source, real);
200
+ if (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel))
201
+ throw new SDKCodegenError('SDK_CODEGEN_UNAVAILABLE', 'SDK package contains external symbolic links');
202
+ return true;
203
+ },
204
+ });
205
+ const pkg = JSON.parse(readFileSync(join(source, 'package.json'), 'utf8'));
206
+ for (const name of Object.keys(pkg.dependencies ?? {}))
207
+ snapshotPackage(resolvePackage(name, source), join(destination, 'node_modules', name), copied);
208
+ }