@coze-arch/cli 0.0.36-alpha.fde2b5 → 0.0.36

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 (63) hide show
  1. package/README.md +0 -11
  2. package/lib/__templates__/nextjs/package.json +2 -2
  3. package/lib/__templates__/nextjs/pnpm-lock.yaml +258 -197
  4. package/lib/__templates__/nextjs/template.config.js +1 -3
  5. package/lib/__templates__/templates.json +0 -25
  6. package/lib/__templates__/vite/template.config.js +1 -3
  7. package/lib/cli.js +199 -3169
  8. package/package.json +3 -5
  9. package/docs/deploy.md +0 -164
  10. package/lib/__templates__/phaser/.coze +0 -13
  11. package/lib/__templates__/phaser/README.md +0 -37
  12. package/lib/__templates__/phaser/_gitignore +0 -23
  13. package/lib/__templates__/phaser/_npmrc +0 -14
  14. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0001.png +0 -0
  15. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0002.png +0 -0
  16. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0003.png +0 -0
  17. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0004.png +0 -0
  18. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0005.png +0 -0
  19. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0006.png +0 -0
  20. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0007.png +0 -0
  21. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0008.png +0 -0
  22. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0009.png +0 -0
  23. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0010.png +0 -0
  24. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0011.png +0 -0
  25. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0012.png +0 -0
  26. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0013.png +0 -0
  27. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0014.png +0 -0
  28. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0015.png +0 -0
  29. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0016.png +0 -0
  30. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0017.png +0 -0
  31. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0018.png +0 -0
  32. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0019.png +0 -0
  33. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0020.png +0 -0
  34. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0021.png +0 -0
  35. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0022.png +0 -0
  36. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0023.png +0 -0
  37. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/frame_0024.png +0 -0
  38. package/lib/__templates__/phaser/assets/image_sequence/coze-game-loading/manifest.json +0 -11
  39. package/lib/__templates__/phaser/debug-runtime/flow-graph.json +0 -20
  40. package/lib/__templates__/phaser/index.html +0 -12
  41. package/lib/__templates__/phaser/package.json +0 -31
  42. package/lib/__templates__/phaser/pnpm-lock.yaml +0 -661
  43. package/lib/__templates__/phaser/scripts/build.sh +0 -8
  44. package/lib/__templates__/phaser/scripts/dev.sh +0 -82
  45. package/lib/__templates__/phaser/scripts/prepare.sh +0 -7
  46. package/lib/__templates__/phaser/scripts/spawn-detached.cjs +0 -29
  47. package/lib/__templates__/phaser/scripts/start.sh +0 -82
  48. package/lib/__templates__/phaser/scripts/validate.sh +0 -7
  49. package/lib/__templates__/phaser/src/assets.ts +0 -15
  50. package/lib/__templates__/phaser/src/global.d.ts +0 -36
  51. package/lib/__templates__/phaser/src/main.ts +0 -28
  52. package/lib/__templates__/phaser/src/scene/BootScene.ts +0 -209
  53. package/lib/__templates__/phaser/src/scene/DevLoadingScene.ts +0 -66
  54. package/lib/__templates__/phaser/src/style.css +0 -28
  55. package/lib/__templates__/phaser/src/types.ts +0 -32
  56. package/lib/__templates__/phaser/src/utils/asset-loader.ts +0 -319
  57. package/lib/__templates__/phaser/src/utils/index.ts +0 -2
  58. package/lib/__templates__/phaser/src/utils/mark-editable.ts +0 -6
  59. package/lib/__templates__/phaser/template.config.js +0 -43
  60. package/lib/__templates__/phaser/tsconfig.json +0 -23
  61. package/lib/__templates__/phaser/vite.config.ts +0 -96
  62. package/lib/deploy/package-project.js +0 -220
  63. package/lib/deploy/package-project.py +0 -165
@@ -1,319 +0,0 @@
1
- import type Phaser from 'phaser';
2
-
3
- import { AUDIOS, IMAGES, IMAGE_SEQUENCES, VIDEOS } from '../assets';
4
- import type {
5
- AssetCollections,
6
- AssetSources,
7
- ImageSequenceManifest,
8
- LoadedAsset,
9
- } from '../types';
10
-
11
- const FRAME_KEY_MARKER = ':frame:';
12
- const MANIFEST_KEY_SUFFIX = ':manifest';
13
-
14
- const getFrameKey = (assetKey: string, frameIndex: number): string =>
15
- `${assetKey}${FRAME_KEY_MARKER}${String(frameIndex + 1).padStart(4, '0')}`;
16
-
17
- const getManifestKey = (assetKey: string): string =>
18
- `${assetKey}${MANIFEST_KEY_SUFFIX}`;
19
-
20
- const getFrameSource = (directory: string, frameIndex: number): string =>
21
- `${directory}/frame_${String(frameIndex + 1).padStart(4, '0')}.png`;
22
-
23
- export const resolveAssetUrl = (source: string): string =>
24
- new URL(source, document.baseURI).href;
25
-
26
- const isImageSequenceManifest = (
27
- value: unknown,
28
- ): value is ImageSequenceManifest => {
29
- if (!value || typeof value !== 'object') {
30
- return false;
31
- }
32
-
33
- const manifest = value as Partial<ImageSequenceManifest>;
34
- return (
35
- manifest.type === 'image_sequence' &&
36
- typeof manifest.name === 'string' &&
37
- typeof manifest.properties?.fps === 'number' &&
38
- typeof manifest.properties.frame_count === 'number' &&
39
- manifest.properties.frame_count > 0
40
- );
41
- };
42
-
43
- const getImageSequenceManifest = (
44
- scene: Phaser.Scene,
45
- assetKey: string,
46
- ): ImageSequenceManifest => {
47
- const manifest: unknown = scene.cache.json.get(getManifestKey(assetKey));
48
- if (!isImageSequenceManifest(manifest)) {
49
- throw new Error(`Invalid image sequence manifest: ${assetKey}`);
50
- }
51
-
52
- return manifest;
53
- };
54
-
55
- const queueImageSequenceFrames = (
56
- scene: Phaser.Scene,
57
- assetKey: string,
58
- directory: string,
59
- manifest: ImageSequenceManifest,
60
- ): void => {
61
- Array.from(
62
- { length: manifest.properties.frame_count },
63
- (_value, frameIndex) => {
64
- scene.load.image(
65
- getFrameKey(assetKey, frameIndex),
66
- resolveAssetUrl(getFrameSource(directory, frameIndex)),
67
- );
68
- },
69
- );
70
- };
71
-
72
- const queueImages = (scene: Phaser.Scene, images: AssetSources): number => {
73
- Object.entries(images).forEach(([assetKey, source]) => {
74
- scene.load.image(assetKey, resolveAssetUrl(source));
75
- });
76
- return Object.keys(images).length;
77
- };
78
-
79
- const queueVideos = (scene: Phaser.Scene, videos: AssetSources): number => {
80
- Object.entries(videos).forEach(([assetKey, source]) => {
81
- scene.load.video(assetKey, resolveAssetUrl(source));
82
- });
83
- return Object.keys(videos).length;
84
- };
85
-
86
- const queueAudios = (scene: Phaser.Scene, audios: AssetSources): number => {
87
- Object.entries(audios).forEach(([assetKey, source]) => {
88
- scene.load.audio(assetKey, resolveAssetUrl(source));
89
- });
90
- return Object.keys(audios).length;
91
- };
92
-
93
- const queueImageSequences = (
94
- scene: Phaser.Scene,
95
- imageSequences: AssetSources,
96
- ): number => {
97
- return Object.entries(imageSequences).reduce(
98
- (fileCount, [assetKey, directory]) => {
99
- const manifestKey = getManifestKey(assetKey);
100
- const cachedManifest: unknown = scene.cache.json.get(manifestKey);
101
-
102
- if (isImageSequenceManifest(cachedManifest)) {
103
- queueImageSequenceFrames(
104
- scene,
105
- assetKey,
106
- directory,
107
- cachedManifest,
108
- );
109
- return fileCount + cachedManifest.properties.frame_count;
110
- }
111
-
112
- scene.load.once(
113
- `filecomplete-json-${manifestKey}`,
114
- (_key: string, _type: string, data: unknown) => {
115
- if (!isImageSequenceManifest(data)) {
116
- throw new Error(`Invalid image sequence manifest: ${assetKey}`);
117
- }
118
-
119
- queueImageSequenceFrames(scene, assetKey, directory, data);
120
- },
121
- );
122
-
123
- scene.load.json(
124
- manifestKey,
125
- resolveAssetUrl(`${directory}/manifest.json`),
126
- );
127
- return fileCount + 1;
128
- },
129
- 0,
130
- );
131
- };
132
-
133
- export const loadAssets = (
134
- scene: Phaser.Scene,
135
- collections: AssetCollections,
136
- ): number =>
137
- queueImages(scene, collections.images ?? {}) +
138
- queueImageSequences(scene, collections.imageSequences ?? {}) +
139
- queueVideos(scene, collections.videos ?? {}) +
140
- queueAudios(scene, collections.audios ?? {});
141
-
142
- export const getImageSequenceRuntimeKeys = (
143
- assetKey: string,
144
- ): { texture: string; animation: string } => ({
145
- texture: getFrameKey(assetKey, 0),
146
- animation: `${assetKey}:animation`,
147
- });
148
-
149
- export const getAssetKeyFromFileKey = (fileKey: string): string =>
150
- fileKey.split(FRAME_KEY_MARKER)[0]?.replace(MANIFEST_KEY_SUFFIX, '') ??
151
- fileKey;
152
-
153
- export const getAssetLabelFromFileKey = (
154
- fileKey: string,
155
- collections: AssetCollections,
156
- ): string => {
157
- const assetKey = getAssetKeyFromFileKey(fileKey);
158
-
159
- if (assetKey in (collections.images ?? {})) {
160
- return `图片 ${assetKey}`;
161
- }
162
- if (assetKey in (collections.imageSequences ?? {})) {
163
- return `帧动画 ${assetKey}`;
164
- }
165
- if (assetKey in (collections.videos ?? {})) {
166
- return `视频 ${assetKey}`;
167
- }
168
- if (assetKey in (collections.audios ?? {})) {
169
- return `音频 ${assetKey}`;
170
- }
171
-
172
- return assetKey;
173
- };
174
-
175
- export const registerImageSequenceAnimations = (
176
- scene: Phaser.Scene,
177
- imageSequences: AssetSources,
178
- ): void => {
179
- Object.keys(imageSequences).forEach(assetKey => {
180
- const manifest = getImageSequenceManifest(scene, assetKey);
181
- const animationKey = getImageSequenceRuntimeKeys(assetKey).animation;
182
- if (scene.anims.exists(animationKey)) {
183
- return;
184
- }
185
-
186
- scene.anims.create({
187
- key: animationKey,
188
- frames: Array.from(
189
- { length: manifest.properties.frame_count },
190
- (_value, frameIndex) => ({ key: getFrameKey(assetKey, frameIndex) }),
191
- ),
192
- frameRate: manifest.properties.fps,
193
- repeat: -1,
194
- });
195
- });
196
- };
197
-
198
- const findAsset = (
199
- assetKey: string,
200
- ): { collections: AssetCollections; loadedAsset: LoadedAsset } => {
201
- const matches: Array<{
202
- collections: AssetCollections;
203
- loadedAsset: LoadedAsset;
204
- }> = [];
205
-
206
- if (Object.hasOwn(IMAGES, assetKey)) {
207
- matches.push({
208
- collections: { images: { [assetKey]: IMAGES[assetKey] } },
209
- loadedAsset: { kind: 'image', key: assetKey },
210
- });
211
- }
212
- if (Object.hasOwn(IMAGE_SEQUENCES, assetKey)) {
213
- matches.push({
214
- collections: {
215
- imageSequences: { [assetKey]: IMAGE_SEQUENCES[assetKey] },
216
- },
217
- loadedAsset: {
218
- kind: 'image-sequence',
219
- key: assetKey,
220
- ...getImageSequenceRuntimeKeys(assetKey),
221
- },
222
- });
223
- }
224
- if (Object.hasOwn(VIDEOS, assetKey)) {
225
- matches.push({
226
- collections: { videos: { [assetKey]: VIDEOS[assetKey] } },
227
- loadedAsset: { kind: 'video', key: assetKey },
228
- });
229
- }
230
- if (Object.hasOwn(AUDIOS, assetKey)) {
231
- matches.push({
232
- collections: { audios: { [assetKey]: AUDIOS[assetKey] } },
233
- loadedAsset: { kind: 'audio', key: assetKey },
234
- });
235
- }
236
-
237
- if (matches.length === 0) {
238
- throw new Error(`Asset not found: ${assetKey}`);
239
- }
240
- if (matches.length > 1) {
241
- throw new Error(`Duplicate asset key: ${assetKey}`);
242
- }
243
-
244
- return matches[0];
245
- };
246
-
247
- const isAssetLoaded = (
248
- scene: Phaser.Scene,
249
- loadedAsset: LoadedAsset,
250
- ): boolean => {
251
- switch (loadedAsset.kind) {
252
- case 'image':
253
- return scene.textures.exists(loadedAsset.key);
254
- case 'image-sequence':
255
- return scene.anims.exists(loadedAsset.animation);
256
- case 'video':
257
- return scene.cache.video.exists(loadedAsset.key);
258
- case 'audio':
259
- return scene.cache.audio.exists(loadedAsset.key);
260
- }
261
- };
262
-
263
- interface LoaderFileLike {
264
- key: string;
265
- }
266
-
267
- export const loadAsset = async (
268
- scene: Phaser.Scene,
269
- assetKey: string,
270
- ): Promise<LoadedAsset> => {
271
- const { collections, loadedAsset } = findAsset(assetKey);
272
- if (isAssetLoaded(scene, loadedAsset)) {
273
- return loadedAsset;
274
- }
275
-
276
- return new Promise<LoadedAsset>((resolve, reject) => {
277
- const cleanup = (): void => {
278
- scene.load.off('complete', onComplete);
279
- scene.load.off('loaderror', onLoadError);
280
- };
281
-
282
- const onComplete = (): void => {
283
- cleanup();
284
- try {
285
- if (loadedAsset.kind === 'image-sequence') {
286
- registerImageSequenceAnimations(
287
- scene,
288
- collections.imageSequences ?? {},
289
- );
290
- }
291
- resolve(loadedAsset);
292
- } catch (error) {
293
- reject(error);
294
- }
295
- };
296
-
297
- const onLoadError = (file: LoaderFileLike): void => {
298
- if (getAssetKeyFromFileKey(file.key) !== assetKey) {
299
- return;
300
- }
301
-
302
- cleanup();
303
- reject(new Error(`Failed to load asset: ${assetKey}`));
304
- };
305
-
306
- scene.load.once('complete', onComplete);
307
- scene.load.on('loaderror', onLoadError);
308
-
309
- try {
310
- loadAssets(scene, collections);
311
- if (!scene.load.isLoading()) {
312
- scene.load.start();
313
- }
314
- } catch (error) {
315
- cleanup();
316
- reject(error);
317
- }
318
- });
319
- };
@@ -1,2 +0,0 @@
1
- export * from './asset-loader';
2
- export * from './mark-editable';
@@ -1,6 +0,0 @@
1
- import type Phaser from 'phaser';
2
-
3
- export const markEditable = <T extends Phaser.GameObjects.GameObject>(
4
- locator: string,
5
- gameObject: T,
6
- ): T => window.PhaserBridge?.markEditable?.(locator, gameObject) ?? gameObject;
@@ -1,43 +0,0 @@
1
-
2
-
3
-
4
-
5
-
6
-
7
-
8
-
9
-
10
- export const paramsSchema = {
11
- type: 'object',
12
- properties: {
13
- appName: {
14
- type: 'string',
15
- minLength: 1,
16
- pattern: '^[a-z0-9-]+$',
17
- description:
18
- 'Application name (lowercase, alphanumeric and hyphens only)',
19
- },
20
- port: {
21
- type: 'number',
22
- default: 5000,
23
- minimum: 1024,
24
- maximum: 65535,
25
- description: 'Development and preview server port',
26
- },
27
- },
28
- required: [],
29
- additionalProperties: false,
30
- };
31
-
32
- const config = {
33
- description:
34
- 'Phaser(2D 游戏):`coze-dev init ${COZE_WORKSPACE_PATH} --template phaser`\n' +
35
- '- 适用:基于 Phaser 3、Vite 和 TypeScript 的 2D Web 游戏。',
36
- paramsSchema,
37
- defaultParams: {
38
- appName: 'phaser-game',
39
- port: 5000,
40
- },
41
- };
42
-
43
- export default config;
@@ -1,23 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2022",
4
- "useDefineForClassFields": true,
5
- "lib": ["ES2022", "DOM", "DOM.Iterable"],
6
- "module": "ESNext",
7
- "moduleResolution": "Bundler",
8
- "baseUrl": ".",
9
- "paths": {
10
- "@/*": ["src/*"]
11
- },
12
- "allowImportingTsExtensions": true,
13
- "isolatedModules": true,
14
- "moduleDetection": "force",
15
- "noEmit": true,
16
- "strict": true,
17
- "skipLibCheck": true,
18
- "esModuleInterop": true,
19
- "forceConsistentCasingInFileNames": true,
20
- "types": ["node"]
21
- },
22
- "include": ["src", "vite.config.ts"]
23
- }
@@ -1,96 +0,0 @@
1
- import { cp } from "node:fs/promises";
2
- import path from "node:path";
3
- import { defineConfig, type Plugin } from "vite";
4
- import serveStatic from "serve-static";
5
-
6
- const DEV_PHASER_BRIDGE_URL =
7
- "https://unpkg.byted-static.com/latest/coze-game/phaser-bridge/dist/index.js";
8
-
9
- function injectDevPhaserBridge(): Plugin {
10
- return {
11
- name: "phaser-dev-bridge",
12
- transformIndexHtml() {
13
- return [
14
- {
15
- tag: "script",
16
- attrs: { src: DEV_PHASER_BRIDGE_URL },
17
- injectTo: "head",
18
- },
19
- ];
20
- },
21
- };
22
- }
23
-
24
- function mountDevAssets(directory: string): Plugin {
25
- const serveAssets = serveStatic(directory, {
26
- cacheControl: false,
27
- dotfiles: "allow",
28
- fallthrough: false,
29
- index: false,
30
- redirect: false,
31
- setHeaders(response) {
32
- response.setHeader("Cache-Control", "no-cache");
33
- },
34
- });
35
-
36
- return {
37
- name: "phaser-dev-assets",
38
- configureServer(server) {
39
- server.middlewares.use("/assets", (request, response, next) => {
40
- const isRead = request.method === "GET" || request.method === "HEAD";
41
- if (!isRead || request.url?.includes("?")) {
42
- response.statusCode = 404;
43
- response.end("Not Found\n");
44
- return;
45
- }
46
- serveAssets(request, response, next);
47
- });
48
- },
49
- };
50
- }
51
-
52
- function copyGameAssets(directory: string): Plugin {
53
- return {
54
- name: "phaser-build-assets",
55
- async writeBundle(outputOptions) {
56
- const outputDirectory = path.resolve(
57
- import.meta.dirname,
58
- outputOptions.dir ?? "dist",
59
- );
60
-
61
- await cp(directory, path.join(outputDirectory, "assets"), {
62
- recursive: true,
63
- force: true,
64
- filter(source) {
65
- return path.basename(source) !== ".DS_Store";
66
- },
67
- });
68
- },
69
- };
70
- }
71
-
72
- export default defineConfig(() => {
73
- const isDev = process.env.COZE_PHASER_GAME_ENV === "DEV";
74
- const assetsDirectory = path.join(import.meta.dirname, "assets");
75
-
76
- return {
77
- resolve: {
78
- alias: {
79
- "@": path.resolve(import.meta.dirname, "src"),
80
- },
81
- },
82
- server: {
83
- // 游戏需用户手动刷新,防止游玩过程中丢失游戏状态
84
- hmr: false,
85
- },
86
- plugins: [
87
- copyGameAssets(assetsDirectory),
88
- ...(isDev
89
- ? [
90
- injectDevPhaserBridge(),
91
- mountDevAssets(assetsDirectory),
92
- ]
93
- : []),
94
- ],
95
- };
96
- });
@@ -1,220 +0,0 @@
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
-
40
- const parseArguments = argv => {
41
- const positional = [];
42
- let pages = false;
43
- for (const argument of argv) {
44
- if (argument === '--pages') {
45
- pages = true;
46
- } else if (argument.startsWith('-')) {
47
- throw new Error(`Unknown argument: ${argument}`);
48
- } else {
49
- positional.push(argument);
50
- }
51
- }
52
- if (positional.length !== 2) {
53
- throw new Error(
54
- 'Usage: package-project.js <source_dir> <output_path> [--pages]',
55
- );
56
- }
57
- return {
58
- sourceDir: path.resolve(positional[0]),
59
- outputPath: path.resolve(positional[1]),
60
- pages,
61
- };
62
- };
63
-
64
- const buildCommandEnv = () => {
65
- const env = { ...process.env };
66
- const cliBinDir = path.resolve(__dirname, '..', '..', 'node_modules', '.bin');
67
- env.PATH = env.PATH
68
- ? `${cliBinDir}${path.delimiter}${env.PATH}`
69
- : cliBinDir;
70
- return env;
71
- };
72
-
73
- const readCozeConfig = sourceDir => {
74
- const cozePath = path.join(sourceDir, '.coze');
75
- if (!existsSync(cozePath)) {
76
- return {};
77
- }
78
- return TOML.parse(readFileSync(cozePath, 'utf8'));
79
- };
80
-
81
- const readCommand = (config, section, key) => {
82
- const command = config[section]?.[key];
83
- if (command === undefined) {
84
- return undefined;
85
- }
86
- if (
87
- !Array.isArray(command) ||
88
- !command.every(part => typeof part === 'string' && part.length > 0)
89
- ) {
90
- throw new Error(`.coze ${section}.${key} must be a string array`);
91
- }
92
- return command;
93
- };
94
-
95
- const runCommand = (command, sourceDir, env) => {
96
- const result = spawnSync(command[0], command.slice(1), {
97
- cwd: sourceDir,
98
- env,
99
- stdio: 'inherit',
100
- });
101
- if (result.error) {
102
- throw result.error;
103
- }
104
- if (result.status !== 0) {
105
- throw new Error(
106
- `Command ${command.join(' ')} exited with code ${String(result.status)}`,
107
- );
108
- }
109
- };
110
-
111
- const runPackCommand = sourceDir => {
112
- const command = readCommand(readCozeConfig(sourceDir), 'dev', 'pack');
113
- if (command) {
114
- process.stderr.write(`[package] Running dev.pack: ${command.join(' ')}\n`);
115
- runCommand(command, sourceDir, buildCommandEnv());
116
- }
117
- };
118
-
119
- const hasIndexHtml = directory =>
120
- existsSync(path.join(directory, 'index.html')) &&
121
- statSync(path.join(directory, 'index.html')).isFile();
122
-
123
- const preparePagesOutput = sourceDir => {
124
- if (hasIndexHtml(sourceDir)) {
125
- process.stderr.write(`[package] Pages static source: ${sourceDir}\n`);
126
- return sourceDir;
127
- }
128
-
129
- const cozePath = path.join(sourceDir, '.coze');
130
- if (!existsSync(cozePath)) {
131
- throw new Error(
132
- 'Pages source contains neither index.html nor a .coze file. ' +
133
- 'Add index.html or configure a Next.js build in .coze.',
134
- );
135
- }
136
-
137
- const config = readCozeConfig(sourceDir);
138
- const template = config.project?.template;
139
- if (typeof template !== 'string' || template.trim().toLowerCase() !== 'nextjs') {
140
- throw new Error(
141
- 'Pages source contains no index.html; .coze project.template must be "nextjs"',
142
- );
143
- }
144
- if (!readCommand(config, 'deploy', 'build')) {
145
- throw new Error(
146
- 'Pages source contains no index.html; .coze deploy.build is required',
147
- );
148
- }
149
- process.stderr.write(`[package] Pages Next.js source: ${sourceDir}\n`);
150
- return sourceDir;
151
- };
152
-
153
- const shouldInclude = (archivePath, excludeCozeFile = false) => {
154
- const parts = archivePath.split(/[\\/]/u);
155
- if (
156
- parts.some(
157
- part =>
158
- LOCAL_METADATA_FILES.has(part) ||
159
- (part.startsWith(UPLOAD_SESSION_TEMP_PREFIX) && part.endsWith('.tmp')),
160
- )
161
- ) {
162
- return false;
163
- }
164
- if (parts.includes('.env')) {
165
- return false;
166
- }
167
- if (excludeCozeFile && parts.includes('.coze')) {
168
- return false;
169
- }
170
- if (parts.some(part => part.startsWith('.git'))) {
171
- return false;
172
- }
173
- return !parts.some(part => EXCLUDED_PARTS.has(part));
174
- };
175
-
176
- const createTarGzWithoutRoot = async (sourceDir, outputPath, excludeCozeFile = false) => {
177
- if (!existsSync(sourceDir) || !statSync(sourceDir).isDirectory()) {
178
- throw new Error(`source directory does not exist: ${sourceDir}`);
179
- }
180
- mkdirSync(path.dirname(outputPath), { recursive: true });
181
- process.stderr.write(`[package] Creating archive from: ${sourceDir}\n`);
182
- const resolvedOutputPath = path.resolve(outputPath);
183
- const entries = readdirSync(sourceDir)
184
- .filter(entry =>
185
- entry !== '.codegraph' &&
186
- path.resolve(sourceDir, entry) !== resolvedOutputPath,
187
- )
188
- .sort();
189
- await tar.create(
190
- {
191
- cwd: sourceDir,
192
- file: outputPath,
193
- filter: archivePath => shouldInclude(archivePath, excludeCozeFile),
194
- gzip: true,
195
- mtime: REPRODUCIBLE_ARCHIVE_MTIME,
196
- portable: true,
197
- },
198
- entries,
199
- );
200
- const size = statSync(outputPath).size;
201
- if (size <= 0) {
202
- throw new Error('source archive is empty');
203
- }
204
- process.stderr.write(`[package] Archive ready: ${String(size)} bytes\n`);
205
- return size;
206
- };
207
-
208
- const main = async () => {
209
- const { sourceDir, outputPath, pages } = parseArguments(process.argv.slice(2));
210
- const packageDir = pages
211
- ? preparePagesOutput(sourceDir)
212
- : (runPackCommand(sourceDir), sourceDir);
213
- const size = await createTarGzWithoutRoot(packageDir, outputPath, pages);
214
- process.stdout.write(`${String(size)}\n`);
215
- };
216
-
217
- main().catch(error => {
218
- process.stderr.write(`${error instanceof Error ? error.stack : String(error)}\n`);
219
- process.exitCode = 1;
220
- });