@web-auto/camo 0.2.0 → 0.2.2

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 (114) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +586 -586
  3. package/bin/browser-service.mjs +11 -11
  4. package/bin/camo.mjs +22 -22
  5. package/package.json +48 -48
  6. package/scripts/build.mjs +19 -19
  7. package/scripts/bump-version.mjs +34 -34
  8. package/scripts/check-file-size.mjs +80 -80
  9. package/scripts/file-size-policy.json +12 -2
  10. package/scripts/install.mjs +76 -76
  11. package/scripts/release.sh +54 -54
  12. package/src/autoscript/action-providers/index.mjs +6 -6
  13. package/src/autoscript/impact-engine.mjs +78 -78
  14. package/src/autoscript/runtime.mjs +1017 -1017
  15. package/src/autoscript/schema.mjs +376 -376
  16. package/src/cli.mjs +405 -405
  17. package/src/commands/attach.mjs +141 -141
  18. package/src/commands/autoscript.mjs +1011 -1011
  19. package/src/commands/browser.mjs +1255 -1255
  20. package/src/commands/container.mjs +401 -401
  21. package/src/commands/cookies.mjs +69 -69
  22. package/src/commands/create.mjs +98 -98
  23. package/src/commands/devtools.mjs +349 -349
  24. package/src/commands/events.mjs +152 -152
  25. package/src/commands/highlight-mode.mjs +24 -24
  26. package/src/commands/init.mjs +68 -68
  27. package/src/commands/lifecycle.mjs +275 -275
  28. package/src/commands/mouse.mjs +45 -45
  29. package/src/commands/profile.mjs +46 -46
  30. package/src/commands/record.mjs +115 -115
  31. package/src/commands/system.mjs +14 -14
  32. package/src/commands/window.mjs +123 -123
  33. package/src/container/change-notifier.mjs +362 -362
  34. package/src/container/element-filter.mjs +143 -143
  35. package/src/container/index.mjs +3 -3
  36. package/src/container/runtime-core/checkpoint.mjs +209 -209
  37. package/src/container/runtime-core/index.mjs +21 -21
  38. package/src/container/runtime-core/operations/index.mjs +774 -774
  39. package/src/container/runtime-core/operations/selector-scripts.mjs +277 -277
  40. package/src/container/runtime-core/operations/tab-pool.mjs +746 -746
  41. package/src/container/runtime-core/operations/viewport.mjs +189 -189
  42. package/src/container/runtime-core/search.mjs +190 -190
  43. package/src/container/runtime-core/subscription.mjs +224 -224
  44. package/src/container/runtime-core/utils.mjs +94 -94
  45. package/src/container/runtime-core/validation.mjs +127 -127
  46. package/src/container/runtime-core.mjs +1 -1
  47. package/src/container/subscription-registry.mjs +459 -459
  48. package/src/core/actions.mjs +561 -561
  49. package/src/core/browser.mjs +266 -266
  50. package/src/core/index.mjs +52 -52
  51. package/src/core/utils.mjs +91 -91
  52. package/src/events/daemon-entry.mjs +33 -33
  53. package/src/events/daemon.mjs +80 -80
  54. package/src/events/progress-log.mjs +109 -109
  55. package/src/events/ws-server.mjs +239 -239
  56. package/src/lib/client.mjs +200 -200
  57. package/src/lifecycle/cleanup.mjs +83 -83
  58. package/src/lifecycle/lock.mjs +126 -126
  59. package/src/lifecycle/session-registry.mjs +279 -279
  60. package/src/lifecycle/session-view.mjs +76 -76
  61. package/src/lifecycle/session-watchdog.mjs +281 -281
  62. package/src/services/browser-service/index.js +671 -671
  63. package/src/services/browser-service/internal/BrowserSession.input.test.js +389 -389
  64. package/src/services/browser-service/internal/BrowserSession.js +325 -304
  65. package/src/services/browser-service/internal/ElementRegistry.js +60 -60
  66. package/src/services/browser-service/internal/ProfileLock.js +84 -84
  67. package/src/services/browser-service/internal/SessionManager.js +184 -184
  68. package/src/services/browser-service/internal/SessionManager.test.js +39 -39
  69. package/src/services/browser-service/internal/browser-session/cookies.js +144 -144
  70. package/src/services/browser-service/internal/browser-session/input-ops.js +222 -222
  71. package/src/services/browser-service/internal/browser-session/input-pipeline.js +144 -144
  72. package/src/services/browser-service/internal/browser-session/logging.js +46 -46
  73. package/src/services/browser-service/internal/browser-session/navigation.js +38 -38
  74. package/src/services/browser-service/internal/browser-session/page-hooks.js +442 -442
  75. package/src/services/browser-service/internal/browser-session/page-management.js +302 -302
  76. package/src/services/browser-service/internal/browser-session/page-management.test.js +148 -148
  77. package/src/services/browser-service/internal/browser-session/recording.js +198 -198
  78. package/src/services/browser-service/internal/browser-session/runtime-events.js +61 -61
  79. package/src/services/browser-service/internal/browser-session/session-core.js +84 -84
  80. package/src/services/browser-service/internal/browser-session/session-state.js +38 -38
  81. package/src/services/browser-service/internal/browser-session/types.js +14 -14
  82. package/src/services/browser-service/internal/browser-session/utils.js +95 -95
  83. package/src/services/browser-service/internal/browser-session/viewport-manager.js +46 -46
  84. package/src/services/browser-service/internal/browser-session/viewport.js +215 -215
  85. package/src/services/browser-service/internal/container-matcher.js +851 -851
  86. package/src/services/browser-service/internal/container-registry.js +182 -182
  87. package/src/services/browser-service/internal/engine-manager.js +259 -259
  88. package/src/services/browser-service/internal/fingerprint.js +203 -203
  89. package/src/services/browser-service/internal/heartbeat.js +137 -137
  90. package/src/services/browser-service/internal/logging.js +46 -46
  91. package/src/services/browser-service/internal/page-runtime/runtime.js +1317 -1317
  92. package/src/services/browser-service/internal/pageRuntime.js +28 -28
  93. package/src/services/browser-service/internal/runtimeInjector.js +31 -31
  94. package/src/services/browser-service/internal/service-process-logger.js +140 -140
  95. package/src/services/browser-service/internal/state-bus.js +45 -45
  96. package/src/services/browser-service/internal/storage-paths.js +42 -42
  97. package/src/services/browser-service/internal/ws-server.js +1194 -1194
  98. package/src/services/browser-service/internal/ws-server.test.js +58 -58
  99. package/src/services/browser-service/server.mjs +6 -6
  100. package/src/services/controller/cli-bridge.js +93 -93
  101. package/src/services/controller/container-index.js +50 -50
  102. package/src/services/controller/container-storage.js +36 -36
  103. package/src/services/controller/controller-actions.js +207 -207
  104. package/src/services/controller/controller.js +1138 -1138
  105. package/src/services/controller/selectors.js +54 -54
  106. package/src/services/controller/transport.js +125 -125
  107. package/src/utils/args.mjs +26 -26
  108. package/src/utils/browser-service.mjs +544 -544
  109. package/src/utils/command-log.mjs +64 -64
  110. package/src/utils/config.mjs +214 -214
  111. package/src/utils/fingerprint.mjs +181 -181
  112. package/src/utils/help.mjs +216 -216
  113. package/src/utils/js-policy.mjs +13 -13
  114. package/src/utils/ws-client.mjs +30 -30
@@ -1,59 +1,59 @@
1
- import test from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { BrowserWsServer } from './ws-server.js';
4
- function createServer() {
5
- const fakeSessionManager = {
6
- getSession() {
7
- return {};
8
- },
9
- };
10
- return new BrowserWsServer({ sessionManager: fakeSessionManager });
11
- }
12
- test('rejects legacy selector actions in node_execute', async () => {
13
- const server = createServer();
14
- const clickResult = await server.handleNodeExecute('profile-a', {
15
- command_type: 'node_execute',
16
- node_type: 'click',
17
- parameters: { selector: '#submit' },
18
- });
19
- const typeResult = await server.handleNodeExecute('profile-a', {
20
- command_type: 'node_execute',
21
- node_type: 'type',
22
- parameters: { selector: '#search', text: 'hello' },
23
- });
24
- assert.equal(clickResult.success, false);
25
- assert.equal(clickResult.code, 'LEGACY_ACTION_DISABLED');
26
- assert.match(clickResult.error, /node_execute/);
27
- assert.match(clickResult.error, /mouse:\*/);
28
- assert.equal(typeResult.success, false);
29
- assert.equal(typeResult.code, 'LEGACY_ACTION_DISABLED');
30
- assert.match(typeResult.error, /node_execute/);
31
- assert.match(typeResult.error, /keyboard:\*/);
32
- });
33
- test('rejects legacy selector actions in user_action.operation', async () => {
34
- const server = createServer();
35
- const clickResult = await server.handleUserAction('profile-a', {
36
- command_type: 'user_action',
37
- action: 'operation',
38
- parameters: {
39
- operation_type: 'click',
40
- target: { selector: '#submit' },
41
- },
42
- });
43
- const typeResult = await server.handleUserAction('profile-a', {
44
- command_type: 'user_action',
45
- action: 'operation',
46
- parameters: {
47
- operation_type: 'type',
48
- target: { selector: '#search' },
49
- text: 'hello',
50
- },
51
- });
52
- assert.equal(clickResult.success, false);
53
- assert.equal(clickResult.code, 'LEGACY_ACTION_DISABLED');
54
- assert.match(clickResult.error, /user_action\.operation/);
55
- assert.equal(typeResult.success, false);
56
- assert.equal(typeResult.code, 'LEGACY_ACTION_DISABLED');
57
- assert.match(typeResult.error, /user_action\.operation/);
58
- });
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { BrowserWsServer } from './ws-server.js';
4
+ function createServer() {
5
+ const fakeSessionManager = {
6
+ getSession() {
7
+ return {};
8
+ },
9
+ };
10
+ return new BrowserWsServer({ sessionManager: fakeSessionManager });
11
+ }
12
+ test('rejects legacy selector actions in node_execute', async () => {
13
+ const server = createServer();
14
+ const clickResult = await server.handleNodeExecute('profile-a', {
15
+ command_type: 'node_execute',
16
+ node_type: 'click',
17
+ parameters: { selector: '#submit' },
18
+ });
19
+ const typeResult = await server.handleNodeExecute('profile-a', {
20
+ command_type: 'node_execute',
21
+ node_type: 'type',
22
+ parameters: { selector: '#search', text: 'hello' },
23
+ });
24
+ assert.equal(clickResult.success, false);
25
+ assert.equal(clickResult.code, 'LEGACY_ACTION_DISABLED');
26
+ assert.match(clickResult.error, /node_execute/);
27
+ assert.match(clickResult.error, /mouse:\*/);
28
+ assert.equal(typeResult.success, false);
29
+ assert.equal(typeResult.code, 'LEGACY_ACTION_DISABLED');
30
+ assert.match(typeResult.error, /node_execute/);
31
+ assert.match(typeResult.error, /keyboard:\*/);
32
+ });
33
+ test('rejects legacy selector actions in user_action.operation', async () => {
34
+ const server = createServer();
35
+ const clickResult = await server.handleUserAction('profile-a', {
36
+ command_type: 'user_action',
37
+ action: 'operation',
38
+ parameters: {
39
+ operation_type: 'click',
40
+ target: { selector: '#submit' },
41
+ },
42
+ });
43
+ const typeResult = await server.handleUserAction('profile-a', {
44
+ command_type: 'user_action',
45
+ action: 'operation',
46
+ parameters: {
47
+ operation_type: 'type',
48
+ target: { selector: '#search' },
49
+ text: 'hello',
50
+ },
51
+ });
52
+ assert.equal(clickResult.success, false);
53
+ assert.equal(clickResult.code, 'LEGACY_ACTION_DISABLED');
54
+ assert.match(clickResult.error, /user_action\.operation/);
55
+ assert.equal(typeResult.success, false);
56
+ assert.equal(typeResult.code, 'LEGACY_ACTION_DISABLED');
57
+ assert.match(typeResult.error, /user_action\.operation/);
58
+ });
59
59
  //# sourceMappingURL=ws-server.test.js.map
@@ -1,6 +1,6 @@
1
- #!/usr/bin/env node
2
- import { parseArgs, startBrowserService } from './index.js';
3
-
4
- if (import.meta.url === `file://${process.argv[1]}`) {
5
- await startBrowserService(parseArgs(process.argv));
6
- }
1
+ #!/usr/bin/env node
2
+ import { parseArgs, startBrowserService } from './index.js';
3
+
4
+ if (import.meta.url === `file://${process.argv[1]}`) {
5
+ await startBrowserService(parseArgs(process.argv));
6
+ }
@@ -1,93 +1,93 @@
1
- import { spawn } from 'node:child_process';
2
-
3
- export function createCliBridge({ cliTargets = {}, repoRoot = process.cwd(), env = process.env, logger = null } = {}) {
4
- const runCliCommand = (target, args = []) => new Promise((resolve, reject) => {
5
- const script = cliTargets[target];
6
- if (!script) {
7
- reject(new Error(`Unknown CLI target: ${target}`));
8
- return;
9
- }
10
- const isJs = script.endsWith('.js');
11
- const npxCmd = process.platform === 'win32' ? 'npx.cmd' : 'npx';
12
- const cmd = isJs ? 'node' : npxCmd;
13
- const cmdArgs = isJs ? [script, ...args] : ['tsx', script, ...args];
14
- logger?.info?.('runCliCommand', { target, script, args: args.join(' ') });
15
- const child = spawn(cmd, cmdArgs, {
16
- cwd: repoRoot,
17
- env,
18
- windowsHide: true,
19
- });
20
- let stdout = '';
21
- let stderr = '';
22
- child.stdout.on('data', (chunk) => { stdout += chunk.toString(); });
23
- child.stderr.on('data', (chunk) => { stderr += chunk.toString(); });
24
- child.on('error', (err) => {
25
- logger?.warn?.('cli spawn error', { target, error: err?.message || String(err) });
26
- reject(err);
27
- });
28
- child.on('close', (code) => {
29
- logger?.info?.('cli exit', { target, code });
30
- if (stdout.trim()) logger?.info?.('cli stdout', { target, stdout: stdout.trim() });
31
- if (stderr.trim()) logger?.warn?.('cli stderr', { target, stderr: stderr.trim() });
32
- if (code === 0) {
33
- resolve(normalizeCliResult(parseCliJson(stdout)));
34
- } else {
35
- reject(new Error(stderr.trim() || `CLI(${target}) exited with code ${code}`));
36
- }
37
- });
38
- });
39
-
40
- const parseCliJson = (output = '') => {
41
- const trimmed = output.trim();
42
- if (!trimmed) return {};
43
- const match = trimmed.match(/(\{[\s\S]*\})\s*$/);
44
- if (match) {
45
- try {
46
- return JSON.parse(match[1]);
47
- } catch {
48
- // ignore
49
- }
50
- }
51
- try {
52
- return JSON.parse(trimmed);
53
- } catch {
54
- return { raw: trimmed };
55
- }
56
- };
57
-
58
- const normalizeCliResult = (result) => {
59
- if (result && typeof result === 'object' && 'data' in result && result.success) {
60
- return result.data;
61
- }
62
- return result;
63
- };
64
-
65
- const fetchSessions = async () => {
66
- try {
67
- const res = await runCliCommand('session-manager', ['list']);
68
- const sessions = res?.sessions || res?.data?.sessions || res?.data || [];
69
- return Array.isArray(sessions) ? sessions : [];
70
- } catch {
71
- return [];
72
- }
73
- };
74
-
75
- const findSessionByProfile = (sessions, profile) => {
76
- if (!profile) return null;
77
- return (
78
- sessions.find(
79
- (session) =>
80
- session?.profileId === profile
81
- || session?.profile_id === profile
82
- || session?.session_id === profile
83
- || session?.sessionId === profile,
84
- ) || null
85
- );
86
- };
87
-
88
- return {
89
- runCliCommand,
90
- fetchSessions,
91
- findSessionByProfile,
92
- };
93
- }
1
+ import { spawn } from 'node:child_process';
2
+
3
+ export function createCliBridge({ cliTargets = {}, repoRoot = process.cwd(), env = process.env, logger = null } = {}) {
4
+ const runCliCommand = (target, args = []) => new Promise((resolve, reject) => {
5
+ const script = cliTargets[target];
6
+ if (!script) {
7
+ reject(new Error(`Unknown CLI target: ${target}`));
8
+ return;
9
+ }
10
+ const isJs = script.endsWith('.js');
11
+ const npxCmd = process.platform === 'win32' ? 'npx.cmd' : 'npx';
12
+ const cmd = isJs ? 'node' : npxCmd;
13
+ const cmdArgs = isJs ? [script, ...args] : ['tsx', script, ...args];
14
+ logger?.info?.('runCliCommand', { target, script, args: args.join(' ') });
15
+ const child = spawn(cmd, cmdArgs, {
16
+ cwd: repoRoot,
17
+ env,
18
+ windowsHide: true,
19
+ });
20
+ let stdout = '';
21
+ let stderr = '';
22
+ child.stdout.on('data', (chunk) => { stdout += chunk.toString(); });
23
+ child.stderr.on('data', (chunk) => { stderr += chunk.toString(); });
24
+ child.on('error', (err) => {
25
+ logger?.warn?.('cli spawn error', { target, error: err?.message || String(err) });
26
+ reject(err);
27
+ });
28
+ child.on('close', (code) => {
29
+ logger?.info?.('cli exit', { target, code });
30
+ if (stdout.trim()) logger?.info?.('cli stdout', { target, stdout: stdout.trim() });
31
+ if (stderr.trim()) logger?.warn?.('cli stderr', { target, stderr: stderr.trim() });
32
+ if (code === 0) {
33
+ resolve(normalizeCliResult(parseCliJson(stdout)));
34
+ } else {
35
+ reject(new Error(stderr.trim() || `CLI(${target}) exited with code ${code}`));
36
+ }
37
+ });
38
+ });
39
+
40
+ const parseCliJson = (output = '') => {
41
+ const trimmed = output.trim();
42
+ if (!trimmed) return {};
43
+ const match = trimmed.match(/(\{[\s\S]*\})\s*$/);
44
+ if (match) {
45
+ try {
46
+ return JSON.parse(match[1]);
47
+ } catch {
48
+ // ignore
49
+ }
50
+ }
51
+ try {
52
+ return JSON.parse(trimmed);
53
+ } catch {
54
+ return { raw: trimmed };
55
+ }
56
+ };
57
+
58
+ const normalizeCliResult = (result) => {
59
+ if (result && typeof result === 'object' && 'data' in result && result.success) {
60
+ return result.data;
61
+ }
62
+ return result;
63
+ };
64
+
65
+ const fetchSessions = async () => {
66
+ try {
67
+ const res = await runCliCommand('session-manager', ['list']);
68
+ const sessions = res?.sessions || res?.data?.sessions || res?.data || [];
69
+ return Array.isArray(sessions) ? sessions : [];
70
+ } catch {
71
+ return [];
72
+ }
73
+ };
74
+
75
+ const findSessionByProfile = (sessions, profile) => {
76
+ if (!profile) return null;
77
+ return (
78
+ sessions.find(
79
+ (session) =>
80
+ session?.profileId === profile
81
+ || session?.profile_id === profile
82
+ || session?.session_id === profile
83
+ || session?.sessionId === profile,
84
+ ) || null
85
+ );
86
+ };
87
+
88
+ return {
89
+ runCliCommand,
90
+ fetchSessions,
91
+ findSessionByProfile,
92
+ };
93
+ }
@@ -1,50 +1,50 @@
1
- import fs from 'node:fs';
2
-
3
- export function loadContainerIndex(indexPath, errorHandler = null) {
4
- if (!indexPath) {
5
- throw new Error('CAMO_CONTAINER_INDEX is required; internal container index is not bundled.');
6
- }
7
- if (!fs.existsSync(indexPath)) {
8
- throw new Error(`Container index not found: ${indexPath}`);
9
- }
10
- try {
11
- return JSON.parse(fs.readFileSync(indexPath, 'utf-8')) || {};
12
- } catch (err) {
13
- if (errorHandler?.debug) {
14
- errorHandler.debug('controller', 'read container index failed', { error: err?.message || String(err) });
15
- }
16
- throw err;
17
- }
18
- }
19
-
20
- export function resolveSiteKeyFromUrl(url, index) {
21
- if (!url) return null;
22
- let host = '';
23
- try {
24
- host = new URL(url).hostname.toLowerCase();
25
- } catch {
26
- return null;
27
- }
28
- let bestKey = null;
29
- let bestLen = -1;
30
- for (const [key, meta] of Object.entries(index || {})) {
31
- const domain = (meta?.website || '').toLowerCase();
32
- if (!domain) continue;
33
- if (host === domain || host.endsWith(`.${domain}`)) {
34
- if (domain.length > bestLen) {
35
- bestKey = key;
36
- bestLen = domain.length;
37
- }
38
- }
39
- }
40
- return bestKey;
41
- }
42
-
43
- export function inferSiteFromContainerId(containerId) {
44
- if (!containerId) return null;
45
- const dotIdx = containerId.indexOf('.');
46
- if (dotIdx > 0) return containerId.slice(0, dotIdx);
47
- const underscoreIdx = containerId.indexOf('_');
48
- if (underscoreIdx > 0) return containerId.slice(0, underscoreIdx);
49
- return null;
50
- }
1
+ import fs from 'node:fs';
2
+
3
+ export function loadContainerIndex(indexPath, errorHandler = null) {
4
+ if (!indexPath) {
5
+ throw new Error('CAMO_CONTAINER_INDEX is required; internal container index is not bundled.');
6
+ }
7
+ if (!fs.existsSync(indexPath)) {
8
+ throw new Error(`Container index not found: ${indexPath}`);
9
+ }
10
+ try {
11
+ return JSON.parse(fs.readFileSync(indexPath, 'utf-8')) || {};
12
+ } catch (err) {
13
+ if (errorHandler?.debug) {
14
+ errorHandler.debug('controller', 'read container index failed', { error: err?.message || String(err) });
15
+ }
16
+ throw err;
17
+ }
18
+ }
19
+
20
+ export function resolveSiteKeyFromUrl(url, index) {
21
+ if (!url) return null;
22
+ let host = '';
23
+ try {
24
+ host = new URL(url).hostname.toLowerCase();
25
+ } catch {
26
+ return null;
27
+ }
28
+ let bestKey = null;
29
+ let bestLen = -1;
30
+ for (const [key, meta] of Object.entries(index || {})) {
31
+ const domain = (meta?.website || '').toLowerCase();
32
+ if (!domain) continue;
33
+ if (host === domain || host.endsWith(`.${domain}`)) {
34
+ if (domain.length > bestLen) {
35
+ bestKey = key;
36
+ bestLen = domain.length;
37
+ }
38
+ }
39
+ }
40
+ return bestKey;
41
+ }
42
+
43
+ export function inferSiteFromContainerId(containerId) {
44
+ if (!containerId) return null;
45
+ const dotIdx = containerId.indexOf('.');
46
+ if (dotIdx > 0) return containerId.slice(0, dotIdx);
47
+ const underscoreIdx = containerId.indexOf('_');
48
+ if (underscoreIdx > 0) return containerId.slice(0, underscoreIdx);
49
+ return null;
50
+ }
@@ -1,36 +1,36 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { promises as fsPromises } from 'node:fs';
4
-
5
- export function buildContainerPath(baseDir, containerId) {
6
- if (!baseDir || !containerId) return null;
7
- const parts = containerId.split('.').filter(Boolean);
8
- if (!parts.length) return null;
9
- return path.join(baseDir, ...parts, 'container.json');
10
- }
11
-
12
- export async function readUserContainerDefinition({ rootDir, siteKey, containerId, errorHandler }) {
13
- if (!rootDir || !siteKey || !containerId) return null;
14
- const userBase = path.join(rootDir, siteKey);
15
- const userFile = buildContainerPath(userBase, containerId);
16
- if (!userFile || !fs.existsSync(userFile)) return null;
17
- try {
18
- const raw = await fsPromises.readFile(userFile, 'utf-8');
19
- return JSON.parse(raw);
20
- } catch (err) {
21
- if (errorHandler?.debug) {
22
- errorHandler.debug('controller', 'read container file failed', { error: err?.message || String(err) });
23
- }
24
- return null;
25
- }
26
- }
27
-
28
- export async function writeUserContainerDefinition({ rootDir, siteKey, containerId, definition }) {
29
- if (!rootDir || !siteKey || !containerId) return;
30
- const parts = containerId.split('.').filter(Boolean);
31
- const targetDir = path.join(rootDir, siteKey, ...parts);
32
- await fsPromises.mkdir(targetDir, { recursive: true });
33
- const filePath = path.join(targetDir, 'container.json');
34
- const payload = { ...definition, id: containerId };
35
- await fsPromises.writeFile(filePath, JSON.stringify(payload, null, 2), 'utf-8');
36
- }
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { promises as fsPromises } from 'node:fs';
4
+
5
+ export function buildContainerPath(baseDir, containerId) {
6
+ if (!baseDir || !containerId) return null;
7
+ const parts = containerId.split('.').filter(Boolean);
8
+ if (!parts.length) return null;
9
+ return path.join(baseDir, ...parts, 'container.json');
10
+ }
11
+
12
+ export async function readUserContainerDefinition({ rootDir, siteKey, containerId, errorHandler }) {
13
+ if (!rootDir || !siteKey || !containerId) return null;
14
+ const userBase = path.join(rootDir, siteKey);
15
+ const userFile = buildContainerPath(userBase, containerId);
16
+ if (!userFile || !fs.existsSync(userFile)) return null;
17
+ try {
18
+ const raw = await fsPromises.readFile(userFile, 'utf-8');
19
+ return JSON.parse(raw);
20
+ } catch (err) {
21
+ if (errorHandler?.debug) {
22
+ errorHandler.debug('controller', 'read container file failed', { error: err?.message || String(err) });
23
+ }
24
+ return null;
25
+ }
26
+ }
27
+
28
+ export async function writeUserContainerDefinition({ rootDir, siteKey, containerId, definition }) {
29
+ if (!rootDir || !siteKey || !containerId) return;
30
+ const parts = containerId.split('.').filter(Boolean);
31
+ const targetDir = path.join(rootDir, siteKey, ...parts);
32
+ await fsPromises.mkdir(targetDir, { recursive: true });
33
+ const filePath = path.join(targetDir, 'container.json');
34
+ const payload = { ...definition, id: containerId };
35
+ await fsPromises.writeFile(filePath, JSON.stringify(payload, null, 2), 'utf-8');
36
+ }