@coze-arch/cli 0.0.35 → 0.0.36-alpha.0a210b

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 (64) hide show
  1. package/README.md +11 -0
  2. package/docs/deploy.md +164 -0
  3. package/lib/__templates__/expo/.cozeproj/scripts/dev_run.sh +73 -18
  4. package/lib/__templates__/nextjs/scripts/dev.sh +10 -1
  5. package/lib/__templates__/nextjs/template.config.js +3 -1
  6. package/lib/__templates__/phaser/.coze +13 -0
  7. package/lib/__templates__/phaser/README.md +37 -0
  8. package/lib/__templates__/phaser/_gitignore +23 -0
  9. package/lib/__templates__/phaser/_npmrc +14 -0
  10. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0001.png +0 -0
  11. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0002.png +0 -0
  12. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0003.png +0 -0
  13. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0004.png +0 -0
  14. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0005.png +0 -0
  15. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0006.png +0 -0
  16. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0007.png +0 -0
  17. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0008.png +0 -0
  18. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0009.png +0 -0
  19. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0010.png +0 -0
  20. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0011.png +0 -0
  21. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0012.png +0 -0
  22. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0013.png +0 -0
  23. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0014.png +0 -0
  24. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0015.png +0 -0
  25. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0016.png +0 -0
  26. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0017.png +0 -0
  27. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0018.png +0 -0
  28. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0019.png +0 -0
  29. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0020.png +0 -0
  30. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0021.png +0 -0
  31. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0022.png +0 -0
  32. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0023.png +0 -0
  33. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0024.png +0 -0
  34. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/manifest.json +11 -0
  35. package/lib/__templates__/phaser/debug-runtime/flow-graph.json +20 -0
  36. package/lib/__templates__/phaser/index.html +12 -0
  37. package/lib/__templates__/phaser/package.json +31 -0
  38. package/lib/__templates__/phaser/pnpm-lock.yaml +661 -0
  39. package/lib/__templates__/phaser/scripts/build.sh +8 -0
  40. package/lib/__templates__/phaser/scripts/dev.sh +82 -0
  41. package/lib/__templates__/phaser/scripts/prepare.sh +7 -0
  42. package/lib/__templates__/phaser/scripts/spawn-detached.cjs +29 -0
  43. package/lib/__templates__/phaser/scripts/start.sh +82 -0
  44. package/lib/__templates__/phaser/scripts/validate.sh +7 -0
  45. package/lib/__templates__/phaser/src/assets.ts +15 -0
  46. package/lib/__templates__/phaser/src/global.d.ts +36 -0
  47. package/lib/__templates__/phaser/src/main.ts +28 -0
  48. package/lib/__templates__/phaser/src/scene/BootScene.ts +209 -0
  49. package/lib/__templates__/phaser/src/scene/DevLoadingScene.ts +66 -0
  50. package/lib/__templates__/phaser/src/style.css +28 -0
  51. package/lib/__templates__/phaser/src/types.ts +32 -0
  52. package/lib/__templates__/phaser/src/utils/asset-loader.ts +319 -0
  53. package/lib/__templates__/phaser/src/utils/index.ts +2 -0
  54. package/lib/__templates__/phaser/src/utils/mark-editable.ts +6 -0
  55. package/lib/__templates__/phaser/template.config.js +43 -0
  56. package/lib/__templates__/phaser/tsconfig.json +23 -0
  57. package/lib/__templates__/phaser/vite.config.ts +96 -0
  58. package/lib/__templates__/taro/.cozeproj/scripts/dev_run.sh +20 -14
  59. package/lib/__templates__/templates.json +25 -0
  60. package/lib/__templates__/vite/template.config.js +3 -1
  61. package/lib/cli.js +3176 -201
  62. package/lib/deploy/package-project.js +226 -0
  63. package/lib/deploy/package-project.py +168 -0
  64. package/package.json +5 -4
@@ -0,0 +1,226 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Create the source tar.gz consumed by CreateDeployHistoryV2.
5
+ *
6
+ * Keep this implementation behaviorally aligned with package-project.py, which
7
+ * remains in this directory as the Python reference/backup implementation.
8
+ */
9
+
10
+ 'use strict';
11
+
12
+ const {
13
+ existsSync,
14
+ mkdirSync,
15
+ readFileSync,
16
+ readdirSync,
17
+ statSync,
18
+ } = require('node:fs');
19
+ const path = require('node:path');
20
+ const { spawnSync } = require('node:child_process');
21
+
22
+ const TOML = require('@iarna/toml');
23
+ const tar = require('tar');
24
+
25
+ const EXCLUDED_PARTS = new Set([
26
+ '.codegraph',
27
+ '.next',
28
+ '.venv',
29
+ '__pycache__',
30
+ 'node_modules',
31
+ 'site-packages',
32
+ ]);
33
+ const LOCAL_METADATA_FILES = new Set([
34
+ '.coze-deploy-upload.json',
35
+ '.host.json',
36
+ ]);
37
+ const UPLOAD_SESSION_TEMP_PREFIX = '.coze-deploy-upload-';
38
+ const REPRODUCIBLE_ARCHIVE_MTIME = new Date(0);
39
+ const PROJECT_METADATA_FILE_MODE = 0o644;
40
+
41
+ const parseArguments = argv => {
42
+ const positional = [];
43
+ let pages = false;
44
+ for (const argument of argv) {
45
+ if (argument === '--pages') {
46
+ pages = true;
47
+ } else if (argument.startsWith('-')) {
48
+ throw new Error(`Unknown argument: ${argument}`);
49
+ } else {
50
+ positional.push(argument);
51
+ }
52
+ }
53
+ if (positional.length !== 2) {
54
+ throw new Error(
55
+ 'Usage: package-project.js <source_dir> <output_path> [--pages]',
56
+ );
57
+ }
58
+ return {
59
+ sourceDir: path.resolve(positional[0]),
60
+ outputPath: path.resolve(positional[1]),
61
+ pages,
62
+ };
63
+ };
64
+
65
+ const buildCommandEnv = () => {
66
+ const env = { ...process.env };
67
+ const cliBinDir = path.resolve(__dirname, '..', '..', 'node_modules', '.bin');
68
+ env.PATH = env.PATH
69
+ ? `${cliBinDir}${path.delimiter}${env.PATH}`
70
+ : cliBinDir;
71
+ return env;
72
+ };
73
+
74
+ const readCozeConfig = sourceDir => {
75
+ const cozePath = path.join(sourceDir, '.coze');
76
+ if (!existsSync(cozePath)) {
77
+ return {};
78
+ }
79
+ return TOML.parse(readFileSync(cozePath, 'utf8'));
80
+ };
81
+
82
+ const readCommand = (config, section, key) => {
83
+ const command = config[section]?.[key];
84
+ if (command === undefined) {
85
+ return undefined;
86
+ }
87
+ if (
88
+ !Array.isArray(command) ||
89
+ !command.every(part => typeof part === 'string' && part.length > 0)
90
+ ) {
91
+ throw new Error(`.coze ${section}.${key} must be a string array`);
92
+ }
93
+ return command;
94
+ };
95
+
96
+ const runCommand = (command, sourceDir, env) => {
97
+ const result = spawnSync(command[0], command.slice(1), {
98
+ cwd: sourceDir,
99
+ env,
100
+ stdio: 'inherit',
101
+ });
102
+ if (result.error) {
103
+ throw result.error;
104
+ }
105
+ if (result.status !== 0) {
106
+ throw new Error(
107
+ `Command ${command.join(' ')} exited with code ${String(result.status)}`,
108
+ );
109
+ }
110
+ };
111
+
112
+ const runPackCommand = sourceDir => {
113
+ const command = readCommand(readCozeConfig(sourceDir), 'dev', 'pack');
114
+ if (command) {
115
+ process.stderr.write(`[package] Running dev.pack: ${command.join(' ')}\n`);
116
+ runCommand(command, sourceDir, buildCommandEnv());
117
+ }
118
+ };
119
+
120
+ const hasIndexHtml = directory =>
121
+ existsSync(path.join(directory, 'index.html')) &&
122
+ statSync(path.join(directory, 'index.html')).isFile();
123
+
124
+ const preparePagesOutput = sourceDir => {
125
+ if (hasIndexHtml(sourceDir)) {
126
+ process.stderr.write(`[package] Pages static source: ${sourceDir}\n`);
127
+ return sourceDir;
128
+ }
129
+
130
+ const cozePath = path.join(sourceDir, '.coze');
131
+ if (!existsSync(cozePath)) {
132
+ throw new Error(
133
+ 'Pages source contains neither index.html nor a .coze file. ' +
134
+ 'Add index.html or configure a Next.js build in .coze.',
135
+ );
136
+ }
137
+
138
+ const config = readCozeConfig(sourceDir);
139
+ const template = config.project?.template;
140
+ if (typeof template !== 'string' || template.trim().toLowerCase() !== 'nextjs') {
141
+ throw new Error(
142
+ 'Pages source contains no index.html; .coze project.template must be "nextjs"',
143
+ );
144
+ }
145
+ if (!readCommand(config, 'deploy', 'build')) {
146
+ throw new Error(
147
+ 'Pages source contains no index.html; .coze deploy.build is required',
148
+ );
149
+ }
150
+ process.stderr.write(`[package] Pages Next.js source: ${sourceDir}\n`);
151
+ return sourceDir;
152
+ };
153
+
154
+ const shouldInclude = (archivePath, excludeCozeFile = false) => {
155
+ const parts = archivePath.split(/[\\/]/u);
156
+ if (
157
+ parts.some(
158
+ part =>
159
+ LOCAL_METADATA_FILES.has(part) ||
160
+ (part.startsWith(UPLOAD_SESSION_TEMP_PREFIX) && part.endsWith('.tmp')),
161
+ )
162
+ ) {
163
+ return false;
164
+ }
165
+ if (parts.includes('.env')) {
166
+ return false;
167
+ }
168
+ if (excludeCozeFile && parts.includes('.coze')) {
169
+ return false;
170
+ }
171
+ if (parts.some(part => part.startsWith('.git'))) {
172
+ return false;
173
+ }
174
+ return !parts.some(part => EXCLUDED_PARTS.has(part));
175
+ };
176
+
177
+ const createTarGzWithoutRoot = async (sourceDir, outputPath, excludeCozeFile = false) => {
178
+ if (!existsSync(sourceDir) || !statSync(sourceDir).isDirectory()) {
179
+ throw new Error(`source directory does not exist: ${sourceDir}`);
180
+ }
181
+ mkdirSync(path.dirname(outputPath), { recursive: true });
182
+ process.stderr.write(`[package] Creating archive from: ${sourceDir}\n`);
183
+ const resolvedOutputPath = path.resolve(outputPath);
184
+ const entries = readdirSync(sourceDir)
185
+ .filter(entry =>
186
+ entry !== '.codegraph' &&
187
+ path.resolve(sourceDir, entry) !== resolvedOutputPath,
188
+ )
189
+ .sort();
190
+ await tar.create(
191
+ {
192
+ cwd: sourceDir,
193
+ file: outputPath,
194
+ filter: archivePath => shouldInclude(archivePath, excludeCozeFile),
195
+ gzip: true,
196
+ mtime: REPRODUCIBLE_ARCHIVE_MTIME,
197
+ onWriteEntry: entry => {
198
+ if (entry.path === '.coze' && entry.stat?.isFile()) {
199
+ entry.stat.mode = PROJECT_METADATA_FILE_MODE;
200
+ }
201
+ },
202
+ portable: true,
203
+ },
204
+ entries,
205
+ );
206
+ const size = statSync(outputPath).size;
207
+ if (size <= 0) {
208
+ throw new Error('source archive is empty');
209
+ }
210
+ process.stderr.write(`[package] Archive ready: ${String(size)} bytes\n`);
211
+ return size;
212
+ };
213
+
214
+ const main = async () => {
215
+ const { sourceDir, outputPath, pages } = parseArguments(process.argv.slice(2));
216
+ const packageDir = pages
217
+ ? preparePagesOutput(sourceDir)
218
+ : (runPackCommand(sourceDir), sourceDir);
219
+ const size = await createTarGzWithoutRoot(packageDir, outputPath, pages);
220
+ process.stdout.write(`${String(size)}\n`);
221
+ };
222
+
223
+ main().catch(error => {
224
+ process.stderr.write(`${error instanceof Error ? error.stack : String(error)}\n`);
225
+ process.exitCode = 1;
226
+ });
@@ -0,0 +1,168 @@
1
+ #!/usr/bin/env python3
2
+ """Create the source tar.gz consumed by CreateDeployHistoryV2.
3
+
4
+ This is the standalone subset of coze-coding's devbox package.py. It keeps the
5
+ same archive layout and deployment exclusions without importing the devbox
6
+ service runtime (FastAPI, S3FS, project managers, and background tasks).
7
+ """
8
+
9
+ import argparse
10
+ import os
11
+ import subprocess
12
+ import sys
13
+ import tarfile
14
+ from pathlib import Path
15
+
16
+ try:
17
+ import tomllib
18
+ except ModuleNotFoundError as error: # pragma: no cover - depends on host Python
19
+ raise RuntimeError("Python 3.11 or newer is required to read .coze") from error
20
+
21
+
22
+ EXCLUDED_PARTS = {
23
+ ".codegraph",
24
+ ".next",
25
+ ".venv",
26
+ "__pycache__",
27
+ "node_modules",
28
+ "site-packages",
29
+ }
30
+ UPLOAD_SESSION_FILENAME = ".coze-deploy-upload.json"
31
+ UPLOAD_SESSION_TEMP_PREFIX = ".coze-deploy-upload-"
32
+ HOST_LINK_FILENAME = ".host.json"
33
+ PROJECT_METADATA_FILE_MODE = 0o644
34
+
35
+
36
+ def build_command_env():
37
+ env = os.environ.copy()
38
+ cli_bin_dir = Path(__file__).resolve().parent.parent / "node_modules" / ".bin"
39
+ path = env.get("PATH", "")
40
+ env["PATH"] = f"{cli_bin_dir}{os.pathsep}{path}" if path else str(cli_bin_dir)
41
+ return env
42
+
43
+
44
+ def read_coze_config(source_dir: Path):
45
+ coze_path = source_dir / ".coze"
46
+ if not coze_path.is_file():
47
+ return {}
48
+ with coze_path.open("rb") as file:
49
+ return tomllib.load(file)
50
+
51
+
52
+ def read_command(config, section: str, key: str):
53
+ command = (config.get(section) or {}).get(key)
54
+ if command is None:
55
+ return None
56
+ if not isinstance(command, list) or not all(
57
+ isinstance(part, str) and part for part in command
58
+ ):
59
+ raise ValueError(f".coze {section}.{key} must be a string array")
60
+ return command
61
+
62
+
63
+ def run_pack_command(source_dir: Path):
64
+ command = read_command(read_coze_config(source_dir), "dev", "pack")
65
+ if command:
66
+ print(f"[package] Running dev.pack: {' '.join(command)}", file=sys.stderr)
67
+ subprocess.run(command, cwd=source_dir, env=build_command_env(), check=True)
68
+
69
+
70
+ def has_index_html(directory: Path):
71
+ return (directory / "index.html").is_file()
72
+
73
+
74
+ def prepare_pages_output(source_dir: Path):
75
+ if has_index_html(source_dir):
76
+ print(f"[package] Pages static source: {source_dir}", file=sys.stderr)
77
+ return source_dir
78
+
79
+ coze_path = source_dir / ".coze"
80
+ if not coze_path.is_file():
81
+ raise ValueError(
82
+ "Pages source contains neither index.html nor a .coze file. "
83
+ "Add index.html or configure a Next.js build in .coze."
84
+ )
85
+
86
+ config = read_coze_config(source_dir)
87
+ template = (config.get("project") or {}).get("template")
88
+ if not isinstance(template, str) or template.strip().lower() != "nextjs":
89
+ raise ValueError(
90
+ 'Pages source contains no index.html; .coze project.template must be "nextjs"'
91
+ )
92
+ if not read_command(config, "deploy", "build"):
93
+ raise ValueError(
94
+ "Pages source contains no index.html; .coze deploy.build is required"
95
+ )
96
+ print(f"[package] Pages Next.js source: {source_dir}", file=sys.stderr)
97
+ return source_dir
98
+
99
+
100
+ def should_exclude(tar_info: tarfile.TarInfo, exclude_coze_file=False):
101
+ parts = Path(tar_info.name).parts
102
+
103
+ # Local deployment metadata is not application source. Including it can change
104
+ # the package digest on the next CLI invocation and make the resumable PreDeploy
105
+ # session look like a different artifact.
106
+ if any(
107
+ part in {UPLOAD_SESSION_FILENAME, HOST_LINK_FILENAME}
108
+ or (part.startswith(UPLOAD_SESSION_TEMP_PREFIX) and part.endswith(".tmp"))
109
+ for part in parts
110
+ ):
111
+ return None
112
+ if ".env" in parts:
113
+ return None
114
+ if exclude_coze_file and ".coze" in parts:
115
+ return None
116
+ if any(part.startswith(".git") for part in parts):
117
+ return None
118
+ if any(part in EXCLUDED_PARTS for part in parts):
119
+ return None
120
+ if parts == (".coze",) and tar_info.isfile():
121
+ tar_info.mode = PROJECT_METADATA_FILE_MODE
122
+ return tar_info
123
+
124
+
125
+ def create_tar_gz_without_root(source_dir: Path, output_path: Path, exclude_coze_file=False):
126
+ if not source_dir.is_dir():
127
+ raise ValueError(f"source directory does not exist: {source_dir}")
128
+ output_path.parent.mkdir(parents=True, exist_ok=True)
129
+ print(f"[package] Creating archive from: {source_dir}", file=sys.stderr)
130
+ with tarfile.open(output_path, "w:gz") as archive:
131
+ for entry in sorted(os.listdir(source_dir)):
132
+ if entry == ".codegraph":
133
+ continue
134
+ if (source_dir / entry).resolve() == output_path.resolve():
135
+ continue
136
+ archive.add(
137
+ source_dir / entry,
138
+ arcname=entry,
139
+ filter=lambda info: should_exclude(info, exclude_coze_file),
140
+ )
141
+ if not output_path.is_file() or output_path.stat().st_size <= 0:
142
+ raise RuntimeError("source archive is empty")
143
+ print(
144
+ f"[package] Archive ready: {output_path.stat().st_size} bytes",
145
+ file=sys.stderr,
146
+ )
147
+
148
+
149
+ def main():
150
+ parser = argparse.ArgumentParser()
151
+ parser.add_argument("source_dir")
152
+ parser.add_argument("output_path")
153
+ parser.add_argument("--pages", action="store_true")
154
+ args = parser.parse_args()
155
+
156
+ source_dir = Path(args.source_dir).resolve()
157
+ output_path = Path(args.output_path).resolve()
158
+ if args.pages:
159
+ package_dir = prepare_pages_output(source_dir)
160
+ else:
161
+ run_pack_command(source_dir)
162
+ package_dir = source_dir
163
+ create_tar_gz_without_root(package_dir, output_path, args.pages)
164
+ print(output_path.stat().st_size)
165
+
166
+
167
+ if __name__ == "__main__":
168
+ main()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coze-arch/cli",
3
- "version": "0.0.35",
3
+ "version": "0.0.36-alpha.0a210b",
4
4
  "private": false,
5
5
  "description": "coze coding devtools cli",
6
6
  "license": "MIT",
@@ -12,6 +12,7 @@
12
12
  "files": [
13
13
  "lib",
14
14
  "bin",
15
+ "docs/deploy.md",
15
16
  "lib/**/.npmrc",
16
17
  "!**/*.tsbuildinfo",
17
18
  "!**/*.map",
@@ -48,7 +49,9 @@
48
49
  "fast-glob": "^3.3.3",
49
50
  "js-yaml": "^4.2.0",
50
51
  "minimist": "^1.2.8",
51
- "shelljs": "^0.10.0"
52
+ "pnpm": "9.0.0",
53
+ "shelljs": "^0.10.0",
54
+ "tar": "^7.5.22"
52
55
  },
53
56
  "devDependencies": {
54
57
  "@coze-arch/cli-logger": "workspace:*",
@@ -60,7 +63,6 @@
60
63
  "@coze-arch/ts-config": "workspace:*",
61
64
  "@coze-arch/vitest-config": "workspace:*",
62
65
  "@coze-coding/lambda": "workspace:*",
63
- "@emnapi/runtime": "^1.11.1",
64
66
  "@inquirer/prompts": "^3.2.0",
65
67
  "@rollup/plugin-commonjs": "^28.0.2",
66
68
  "@rollup/plugin-json": "~6.1.0",
@@ -79,7 +81,6 @@
79
81
  "playwright": "~1.61.1",
80
82
  "rollup": "^4.60.1",
81
83
  "sucrase": "^3.35.1",
82
- "tree-kill": "^1.2.2",
83
84
  "tsx": "^4.23.11",
84
85
  "vitest": "~4.1.10"
85
86
  },