@geek-fun/serverlessinsight 0.5.1 → 0.5.3

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 (47) hide show
  1. package/dist/package.json +1 -1
  2. package/dist/src/commands/deploy.js +12 -6
  3. package/dist/src/commands/destroy.js +13 -8
  4. package/dist/src/commands/forceUnlock.js +60 -4
  5. package/dist/src/commands/index.js +40 -21
  6. package/dist/src/commands/local.js +5 -27
  7. package/dist/src/commands/plan.js +12 -4
  8. package/dist/src/commands/template.js +3 -3
  9. package/dist/src/commands/validate.js +4 -2
  10. package/dist/src/common/context.js +2 -1
  11. package/dist/src/common/lockManager.js +5 -3
  12. package/dist/src/common/stateBackend/cosStateBackend.js +215 -0
  13. package/dist/src/common/stateBackend/index.js +55 -0
  14. package/dist/src/common/stateBackend/localStateBackend.js +33 -0
  15. package/dist/src/common/stateBackend/ossStateBackend.js +196 -0
  16. package/dist/src/common/stateBackend/types.js +2 -0
  17. package/dist/src/common/stateManager.js +45 -18
  18. package/dist/src/lang/en.js +2 -2
  19. package/dist/src/lang/zh-CN.js +2 -2
  20. package/dist/src/parser/index.js +34 -5
  21. package/dist/src/parser/tagParser.js +4 -1
  22. package/dist/src/stack/aliyunStack/deployer.js +6 -7
  23. package/dist/src/stack/aliyunStack/destroyer.js +12 -8
  24. package/dist/src/stack/aliyunStack/fc3Resource.js +2 -2
  25. package/dist/src/stack/aliyunStack/planner.js +2 -2
  26. package/dist/src/stack/deploy.js +9 -9
  27. package/dist/src/stack/localStack/aliyunFc.js +2 -2
  28. package/dist/src/stack/rfsStack/index.js +1 -1
  29. package/dist/src/stack/scfStack/deployer.js +6 -7
  30. package/dist/src/stack/scfStack/destroyer.js +6 -7
  31. package/dist/src/stack/scfStack/planner.js +2 -2
  32. package/dist/src/types/domains/backend.js +8 -0
  33. package/dist/src/types/domains/state.js +1 -1
  34. package/dist/src/types/index.js +1 -0
  35. package/dist/src/validator/rootSchema.js +20 -3
  36. package/dist/tsconfig.tsbuildinfo +1 -1
  37. package/package.json +1 -1
  38. package/samples/aliyun-poc-api.yml +2 -1
  39. package/samples/aliyun-poc-bucket.yml +2 -1
  40. package/samples/aliyun-poc-domain.yml +2 -1
  41. package/samples/aliyun-poc-es.yml +2 -1
  42. package/samples/aliyun-poc-fc-gpu.yml +2 -1
  43. package/samples/aliyun-poc-rds.yml +2 -1
  44. package/samples/aliyun-poc-table.yml +2 -1
  45. package/samples/huawei-poc-fc.yml +3 -1
  46. package/samples/tencent-poc-cos.yml +2 -1
  47. package/samples/tencent-poc-scf.yml +2 -1
@@ -0,0 +1,215 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createCosStateBackend = void 0;
7
+ const cos_nodejs_sdk_v5_1 = __importDefault(require("cos-nodejs-sdk-v5"));
8
+ const node_crypto_1 = __importDefault(require("node:crypto"));
9
+ const node_os_1 = __importDefault(require("node:os"));
10
+ const node_child_process_1 = require("node:child_process");
11
+ const types_1 = require("../../types");
12
+ const constants_1 = require("../constants");
13
+ const lockManager_1 = require("../lockManager");
14
+ const LOCK_KEY_SUFFIX = '.si-lock';
15
+ const getUserEmail = () => {
16
+ try {
17
+ const email = (0, node_child_process_1.execSync)('git config user.email', {
18
+ encoding: 'utf-8',
19
+ stdio: ['pipe', 'pipe', 'ignore'],
20
+ }).trim();
21
+ if (email)
22
+ return email;
23
+ }
24
+ catch {
25
+ // noop
26
+ }
27
+ const username = node_os_1.default.userInfo().username || 'unknown';
28
+ const hostname = node_os_1.default.hostname() || 'unknown';
29
+ return `${username}@${hostname}`;
30
+ };
31
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
32
+ const isLockStale = (lock) => {
33
+ const acquiredAt = new Date(lock.acquiredAt).getTime();
34
+ return Date.now() - acquiredAt > constants_1.STALE_LOCK_THRESHOLD;
35
+ };
36
+ const promisifyGet = (cosClient, bucket, region, key) => {
37
+ return new Promise((resolve, reject) => {
38
+ cosClient.getObject({ Bucket: bucket, Region: region, Key: key }, (err, data) => {
39
+ if (err) {
40
+ if (err.statusCode === 404) {
41
+ resolve(null);
42
+ }
43
+ else {
44
+ reject(err);
45
+ }
46
+ }
47
+ else {
48
+ resolve(data.Body);
49
+ }
50
+ });
51
+ });
52
+ };
53
+ const promisifyPut = (cosClient, bucket, region, key, body) => {
54
+ return new Promise((resolve, reject) => {
55
+ cosClient.putObject({ Bucket: bucket, Region: region, Key: key, Body: body }, (err) => {
56
+ if (err)
57
+ reject(err);
58
+ else
59
+ resolve();
60
+ });
61
+ });
62
+ };
63
+ const promisifyDelete = (cosClient, bucket, region, key) => {
64
+ return new Promise((resolve, reject) => {
65
+ cosClient.deleteObject({ Bucket: bucket, Region: region, Key: key }, (err) => {
66
+ if (err && err.statusCode !== 404)
67
+ reject(err);
68
+ else
69
+ resolve();
70
+ });
71
+ });
72
+ };
73
+ const createCosStateBackend = (config) => {
74
+ const cosClient = new cos_nodejs_sdk_v5_1.default({
75
+ SecretId: config.accessKeyId,
76
+ SecretKey: config.accessKeySecret,
77
+ SecurityToken: config.securityToken,
78
+ });
79
+ const lockKey = `${config.key}${LOCK_KEY_SUFFIX}`;
80
+ const readObject = async (key) => {
81
+ const body = await promisifyGet(cosClient, config.bucket, config.region, key);
82
+ if (!body)
83
+ return null;
84
+ return JSON.parse(body.toString('utf-8'));
85
+ };
86
+ const writeObject = async (key, data) => {
87
+ await promisifyPut(cosClient, config.bucket, config.region, key, JSON.stringify(data, null, 2));
88
+ };
89
+ const deleteObject = async (key) => {
90
+ await promisifyDelete(cosClient, config.bucket, config.region, key);
91
+ };
92
+ const readLockObject = async () => {
93
+ return readObject(lockKey);
94
+ };
95
+ const acquireLockObject = async (operation, options = {}) => {
96
+ const timeout = options.timeout ?? constants_1.DEFAULT_LOCK_TIMEOUT;
97
+ const retryDelay = options.retryDelay ?? constants_1.DEFAULT_LOCK_RETRY_DELAY;
98
+ const maxRetries = options.maxRetries ?? Math.ceil(timeout / retryDelay);
99
+ const metadata = {
100
+ id: node_crypto_1.default.randomBytes(16).toString('hex'),
101
+ user: getUserEmail(),
102
+ processId: process.pid,
103
+ hostname: node_os_1.default.hostname(),
104
+ operation,
105
+ acquiredAt: new Date().toISOString(),
106
+ path: `cos://${config.bucket}/${config.key}`,
107
+ };
108
+ const startTime = Date.now();
109
+ let attempt = 0;
110
+ while (attempt <= maxRetries) {
111
+ const existingLock = await readLockObject();
112
+ if (!existingLock) {
113
+ await writeObject(lockKey, metadata);
114
+ const verify = await readLockObject();
115
+ if (verify && verify.id === metadata.id) {
116
+ return metadata;
117
+ }
118
+ }
119
+ else {
120
+ if (isLockStale(existingLock)) {
121
+ throw new lockManager_1.LockError(`State is currently locked (stale lock detected).\n${(0, lockManager_1.formatLockInfo)(existingLock)}\nThis lock appears to be stale. If you are certain no other operation is running, use:\n si force-unlock ${existingLock.id}`, existingLock);
122
+ }
123
+ if (Date.now() - startTime >= timeout) {
124
+ throw new lockManager_1.LockError(`Failed to acquire lock after ${timeout / 1000} seconds.\n${(0, lockManager_1.formatLockInfo)(existingLock)}\nIf you are certain no other operation is running, use:\n si force-unlock ${existingLock.id}`, existingLock);
125
+ }
126
+ }
127
+ const delay = Math.min(retryDelay * Math.pow(2, attempt), 30000);
128
+ await sleep(delay);
129
+ attempt++;
130
+ }
131
+ const existingLock = await readLockObject();
132
+ throw new lockManager_1.LockError(`Failed to acquire lock.\n${existingLock ? (0, lockManager_1.formatLockInfo)(existingLock) : ''}\nIf you are certain no other operation is running, use:\n si force-unlock ${existingLock?.id || 'unknown'}`, existingLock || undefined);
133
+ };
134
+ return {
135
+ loadState: async (provider, app, service, stage) => {
136
+ const state = await readObject(config.key);
137
+ if (state) {
138
+ const stageResources = state.stages?.[stage]?.resources ?? {};
139
+ return { ...state, resources: stageResources };
140
+ }
141
+ return { version: types_1.CURRENT_STATE_VERSION, provider, app, service, stages: {}, resources: {} };
142
+ },
143
+ saveState: async (state, app, service, stage) => {
144
+ let existing = {
145
+ version: types_1.CURRENT_STATE_VERSION,
146
+ provider: state.provider,
147
+ app,
148
+ service,
149
+ stages: {},
150
+ resources: {},
151
+ };
152
+ try {
153
+ const raw = await readObject(config.key);
154
+ if (raw)
155
+ existing = raw;
156
+ }
157
+ catch {
158
+ // noop
159
+ }
160
+ const stateToSave = {
161
+ ...existing,
162
+ version: types_1.CURRENT_STATE_VERSION,
163
+ app,
164
+ service,
165
+ provider: state.provider,
166
+ stages: {
167
+ ...existing.stages,
168
+ [stage]: { resources: state.resources },
169
+ },
170
+ resources: state.resources,
171
+ };
172
+ await writeObject(config.key, stateToSave);
173
+ },
174
+ acquireLock: async (operation, options) => {
175
+ const meta = await acquireLockObject(operation, options);
176
+ return meta.id;
177
+ },
178
+ releaseLock: async (lockId) => {
179
+ const existing = await readLockObject();
180
+ if (existing && existing.id === lockId) {
181
+ await deleteObject(lockKey);
182
+ }
183
+ },
184
+ forceUnlock: async (lockId) => {
185
+ const existing = await readLockObject();
186
+ if (!existing)
187
+ return false;
188
+ if (existing.id !== lockId) {
189
+ throw new Error(`Lock ID mismatch. Current lock ID is ${existing.id}, but you provided ${lockId}`);
190
+ }
191
+ await deleteObject(lockKey);
192
+ return true;
193
+ },
194
+ readLock: async () => {
195
+ return readLockObject();
196
+ },
197
+ withLock: async (operation, fn, options) => {
198
+ let lockId = null;
199
+ try {
200
+ const meta = await acquireLockObject(operation, options);
201
+ lockId = meta.id;
202
+ return await fn();
203
+ }
204
+ finally {
205
+ if (lockId) {
206
+ const existing = await readLockObject();
207
+ if (existing && existing.id === lockId) {
208
+ await deleteObject(lockKey);
209
+ }
210
+ }
211
+ }
212
+ },
213
+ };
214
+ };
215
+ exports.createCosStateBackend = createCosStateBackend;
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.createStateBackend = void 0;
18
+ const types_1 = require("../../types");
19
+ const providerEnum_1 = require("../providerEnum");
20
+ const localStateBackend_1 = require("./localStateBackend");
21
+ const ossStateBackend_1 = require("./ossStateBackend");
22
+ const cosStateBackend_1 = require("./cosStateBackend");
23
+ __exportStar(require("./types"), exports);
24
+ __exportStar(require("./localStateBackend"), exports);
25
+ __exportStar(require("./ossStateBackend"), exports);
26
+ __exportStar(require("./cosStateBackend"), exports);
27
+ const createStateBackend = (backendConfig, context) => {
28
+ if (!backendConfig || backendConfig.type === types_1.StateBackendType.LOCAL) {
29
+ return (0, localStateBackend_1.createLocalStateBackend)(context.app, context.service, context.baseDir);
30
+ }
31
+ const bucketConfig = backendConfig;
32
+ const region = context.region;
33
+ const accessKeyId = context.accessKeyId;
34
+ const accessKeySecret = context.accessKeySecret;
35
+ const securityToken = context.securityToken;
36
+ if (context.provider === providerEnum_1.ProviderEnum.TENCENT) {
37
+ return (0, cosStateBackend_1.createCosStateBackend)({
38
+ bucket: bucketConfig.bucket,
39
+ key: bucketConfig.key,
40
+ region,
41
+ accessKeyId,
42
+ accessKeySecret,
43
+ securityToken,
44
+ });
45
+ }
46
+ return (0, ossStateBackend_1.createOssStateBackend)({
47
+ bucket: bucketConfig.bucket,
48
+ key: bucketConfig.key,
49
+ region,
50
+ accessKeyId,
51
+ accessKeySecret,
52
+ securityToken,
53
+ });
54
+ };
55
+ exports.createStateBackend = createStateBackend;
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createLocalStateBackend = void 0;
4
+ const stateManager_1 = require("../stateManager");
5
+ const lockManager_1 = require("../lockManager");
6
+ const createLocalStateBackend = (app, service, baseDir = process.cwd()) => {
7
+ const statePath = (0, stateManager_1.getStatePath)(app, service, baseDir);
8
+ return {
9
+ loadState: async (provider, loadApp, loadService, stage) => {
10
+ return (0, stateManager_1.loadState)(provider, loadApp, loadService, stage, baseDir);
11
+ },
12
+ saveState: async (state, saveApp, saveService, stage) => {
13
+ (0, stateManager_1.saveState)(state, saveApp, saveService, stage, baseDir);
14
+ },
15
+ acquireLock: async (operation, options) => {
16
+ const lockMeta = await (0, lockManager_1.acquireLockInternal)(statePath, operation, options);
17
+ return lockMeta.id;
18
+ },
19
+ releaseLock: async (lockId) => {
20
+ (0, lockManager_1.releaseLockInternal)(statePath, lockId);
21
+ },
22
+ forceUnlock: async (lockId) => {
23
+ return (0, lockManager_1.forceUnlock)(statePath, lockId);
24
+ },
25
+ readLock: async () => {
26
+ return (0, lockManager_1.readLockFileForCommand)(statePath);
27
+ },
28
+ withLock: async (operation, fn, options) => {
29
+ return (0, lockManager_1.withLock)(statePath, operation, fn, options);
30
+ },
31
+ };
32
+ };
33
+ exports.createLocalStateBackend = createLocalStateBackend;
@@ -0,0 +1,196 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createOssStateBackend = void 0;
7
+ const ali_oss_1 = __importDefault(require("ali-oss"));
8
+ const node_crypto_1 = __importDefault(require("node:crypto"));
9
+ const node_os_1 = __importDefault(require("node:os"));
10
+ const node_child_process_1 = require("node:child_process");
11
+ const types_1 = require("../../types");
12
+ const constants_1 = require("../constants");
13
+ const lockManager_1 = require("../lockManager");
14
+ const LOCK_KEY_SUFFIX = '.si-lock';
15
+ const getUserEmail = () => {
16
+ try {
17
+ const email = (0, node_child_process_1.execSync)('git config user.email', {
18
+ encoding: 'utf-8',
19
+ stdio: ['pipe', 'pipe', 'ignore'],
20
+ }).trim();
21
+ if (email)
22
+ return email;
23
+ }
24
+ catch {
25
+ // noop
26
+ }
27
+ const username = node_os_1.default.userInfo().username || 'unknown';
28
+ const hostname = node_os_1.default.hostname() || 'unknown';
29
+ return `${username}@${hostname}`;
30
+ };
31
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
32
+ const isLockStale = (lock) => {
33
+ const acquiredAt = new Date(lock.acquiredAt).getTime();
34
+ return Date.now() - acquiredAt > constants_1.STALE_LOCK_THRESHOLD;
35
+ };
36
+ const createOssStateBackend = (config) => {
37
+ const ossClient = new ali_oss_1.default({
38
+ accessKeyId: config.accessKeyId,
39
+ accessKeySecret: config.accessKeySecret,
40
+ region: `oss-${config.region}`,
41
+ bucket: config.bucket,
42
+ stsToken: config.securityToken,
43
+ });
44
+ const lockKey = `${config.key}${LOCK_KEY_SUFFIX}`;
45
+ const readObject = async (key) => {
46
+ try {
47
+ const result = await ossClient.get(key);
48
+ const content = result.content.toString('utf-8');
49
+ return JSON.parse(content);
50
+ }
51
+ catch (err) {
52
+ if (err && typeof err === 'object' && 'code' in err) {
53
+ const code = err.code;
54
+ if (code === 'NoSuchKey' || code === 'NoSuchBucket') {
55
+ return null;
56
+ }
57
+ }
58
+ throw err;
59
+ }
60
+ };
61
+ const writeObject = async (key, data) => {
62
+ const content = JSON.stringify(data, null, 2);
63
+ await ossClient.put(key, Buffer.from(content, 'utf-8'));
64
+ };
65
+ const deleteObject = async (key) => {
66
+ try {
67
+ await ossClient.delete(key);
68
+ }
69
+ catch {
70
+ // noop
71
+ }
72
+ };
73
+ const readLockObject = async () => {
74
+ return readObject(lockKey);
75
+ };
76
+ const acquireLockObject = async (operation, options = {}) => {
77
+ const timeout = options.timeout ?? constants_1.DEFAULT_LOCK_TIMEOUT;
78
+ const retryDelay = options.retryDelay ?? constants_1.DEFAULT_LOCK_RETRY_DELAY;
79
+ const maxRetries = options.maxRetries ?? Math.ceil(timeout / retryDelay);
80
+ const metadata = {
81
+ id: node_crypto_1.default.randomBytes(16).toString('hex'),
82
+ user: getUserEmail(),
83
+ processId: process.pid,
84
+ hostname: node_os_1.default.hostname(),
85
+ operation,
86
+ acquiredAt: new Date().toISOString(),
87
+ path: `oss://${config.bucket}/${config.key}`,
88
+ };
89
+ const startTime = Date.now();
90
+ let attempt = 0;
91
+ while (attempt <= maxRetries) {
92
+ const existingLock = await readLockObject();
93
+ if (!existingLock) {
94
+ await writeObject(lockKey, metadata);
95
+ const verify = await readLockObject();
96
+ if (verify && verify.id === metadata.id) {
97
+ return metadata;
98
+ }
99
+ }
100
+ else {
101
+ if (isLockStale(existingLock)) {
102
+ throw new lockManager_1.LockError(`State is currently locked (stale lock detected).\n${(0, lockManager_1.formatLockInfo)(existingLock)}\nThis lock appears to be stale. If you are certain no other operation is running, use:\n si force-unlock ${existingLock.id}`, existingLock);
103
+ }
104
+ if (Date.now() - startTime >= timeout) {
105
+ throw new lockManager_1.LockError(`Failed to acquire lock after ${timeout / 1000} seconds.\n${(0, lockManager_1.formatLockInfo)(existingLock)}\nIf you are certain no other operation is running, use:\n si force-unlock ${existingLock.id}`, existingLock);
106
+ }
107
+ }
108
+ const delay = Math.min(retryDelay * Math.pow(2, attempt), 30000);
109
+ await sleep(delay);
110
+ attempt++;
111
+ }
112
+ const existingLock = await readLockObject();
113
+ throw new lockManager_1.LockError(`Failed to acquire lock.\n${existingLock ? (0, lockManager_1.formatLockInfo)(existingLock) : ''}\nIf you are certain no other operation is running, use:\n si force-unlock ${existingLock?.id || 'unknown'}`, existingLock || undefined);
114
+ };
115
+ return {
116
+ loadState: async (provider, app, service, stage) => {
117
+ const state = await readObject(config.key);
118
+ if (state) {
119
+ const stageResources = state.stages?.[stage]?.resources ?? {};
120
+ return { ...state, resources: stageResources };
121
+ }
122
+ return { version: types_1.CURRENT_STATE_VERSION, provider, app, service, stages: {}, resources: {} };
123
+ },
124
+ saveState: async (state, app, service, stage) => {
125
+ let existing = {
126
+ version: types_1.CURRENT_STATE_VERSION,
127
+ provider: state.provider,
128
+ app,
129
+ service,
130
+ stages: {},
131
+ resources: {},
132
+ };
133
+ try {
134
+ const raw = await readObject(config.key);
135
+ if (raw)
136
+ existing = raw;
137
+ }
138
+ catch {
139
+ // noop
140
+ }
141
+ const stateToSave = {
142
+ ...existing,
143
+ version: types_1.CURRENT_STATE_VERSION,
144
+ app,
145
+ service,
146
+ provider: state.provider,
147
+ stages: {
148
+ ...existing.stages,
149
+ [stage]: { resources: state.resources },
150
+ },
151
+ resources: state.resources,
152
+ };
153
+ await writeObject(config.key, stateToSave);
154
+ },
155
+ acquireLock: async (operation, options) => {
156
+ const meta = await acquireLockObject(operation, options);
157
+ return meta.id;
158
+ },
159
+ releaseLock: async (lockId) => {
160
+ const existing = await readLockObject();
161
+ if (existing && existing.id === lockId) {
162
+ await deleteObject(lockKey);
163
+ }
164
+ },
165
+ forceUnlock: async (lockId) => {
166
+ const existing = await readLockObject();
167
+ if (!existing)
168
+ return false;
169
+ if (existing.id !== lockId) {
170
+ throw new Error(`Lock ID mismatch. Current lock ID is ${existing.id}, but you provided ${lockId}`);
171
+ }
172
+ await deleteObject(lockKey);
173
+ return true;
174
+ },
175
+ readLock: async () => {
176
+ return readLockObject();
177
+ },
178
+ withLock: async (operation, fn, options) => {
179
+ let lockId = null;
180
+ try {
181
+ const meta = await acquireLockObject(operation, options);
182
+ lockId = meta.id;
183
+ return await fn();
184
+ }
185
+ finally {
186
+ if (lockId) {
187
+ const existing = await readLockObject();
188
+ if (existing && existing.id === lockId) {
189
+ await deleteObject(lockKey);
190
+ }
191
+ }
192
+ }
193
+ },
194
+ };
195
+ };
196
+ exports.createOssStateBackend = createOssStateBackend;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -9,9 +9,8 @@ const node_path_1 = __importDefault(require("node:path"));
9
9
  const types_1 = require("../types");
10
10
  const lockManager_1 = require("./lockManager");
11
11
  const STATE_DIR = '.serverlessinsight';
12
- const STATE_FILE = 'state.json';
13
- const getStatePath = (baseDir = process.cwd()) => {
14
- return node_path_1.default.join(baseDir, STATE_DIR, STATE_FILE);
12
+ const getStatePath = (app, service, baseDir = process.cwd()) => {
13
+ return node_path_1.default.join(baseDir, STATE_DIR, `state-${app}-${service}.json`);
15
14
  };
16
15
  exports.getStatePath = getStatePath;
17
16
  const ensureStateDir = (baseDir = process.cwd()) => {
@@ -22,31 +21,59 @@ const ensureStateDir = (baseDir = process.cwd()) => {
22
21
  };
23
22
  exports.ensureStateDir = ensureStateDir;
24
23
  /**
25
- * Load state file.
24
+ * Load state file, scoped to the given stage.
25
+ * The returned StateFile has `resources` populated from `stages[stage].resources`.
26
26
  */
27
- const loadState = (provider, baseDir = process.cwd()) => {
28
- const statePath = (0, exports.getStatePath)(baseDir);
27
+ const loadState = (provider, app, service, stage, baseDir = process.cwd()) => {
28
+ const statePath = (0, exports.getStatePath)(app, service, baseDir);
29
29
  try {
30
30
  if (node_fs_1.default.existsSync(statePath)) {
31
31
  const content = node_fs_1.default.readFileSync(statePath, 'utf-8');
32
- const state = JSON.parse(content);
33
- return state;
32
+ const raw = JSON.parse(content);
33
+ // Populate in-memory resources from the stage slice
34
+ const stageResources = raw.stages?.[stage]?.resources ?? {};
35
+ return { ...raw, resources: stageResources };
34
36
  }
35
- // If file doesn't exist or is invalid, return empty state
36
37
  }
37
38
  catch {
38
- // Ignore error
39
+ // Ignore error, fall through to empty state
39
40
  }
40
- return { version: types_1.CURRENT_STATE_VERSION, provider, resources: {} };
41
+ return { version: types_1.CURRENT_STATE_VERSION, provider, app, service, stages: {}, resources: {} };
41
42
  };
42
43
  exports.loadState = loadState;
43
- const saveState = (state, baseDir = process.cwd()) => {
44
+ const saveState = (state, app, service, stage, baseDir = process.cwd()) => {
44
45
  (0, exports.ensureStateDir)(baseDir);
45
- const statePath = (0, exports.getStatePath)(baseDir);
46
- // Ensure we always save with current version
46
+ const statePath = (0, exports.getStatePath)(app, service, baseDir);
47
+ // Read the existing file to preserve other stages
48
+ let existing = {
49
+ version: types_1.CURRENT_STATE_VERSION,
50
+ provider: state.provider,
51
+ app,
52
+ service,
53
+ stages: {},
54
+ resources: {},
55
+ };
56
+ try {
57
+ if (node_fs_1.default.existsSync(statePath)) {
58
+ const content = node_fs_1.default.readFileSync(statePath, 'utf-8');
59
+ existing = JSON.parse(content);
60
+ }
61
+ }
62
+ catch {
63
+ // use default
64
+ }
65
+ // Write updated stage resources, preserve all other stages
47
66
  const stateToSave = {
48
- ...state,
67
+ ...existing,
49
68
  version: types_1.CURRENT_STATE_VERSION,
69
+ app,
70
+ service,
71
+ provider: state.provider,
72
+ stages: {
73
+ ...existing.stages,
74
+ [stage]: { resources: state.resources },
75
+ },
76
+ resources: state.resources,
50
77
  };
51
78
  node_fs_1.default.writeFileSync(statePath, JSON.stringify(stateToSave, null, 2), 'utf-8');
52
79
  };
@@ -55,10 +82,10 @@ exports.saveState = saveState;
55
82
  * Save state with automatic locking.
56
83
  * This should be used by high-level operations like deploy/destroy.
57
84
  */
58
- const saveStateWithLock = async (state, operation, baseDir = process.cwd(), options) => {
59
- const statePath = (0, exports.getStatePath)(baseDir);
85
+ const saveStateWithLock = async (state, app, service, stage, operation, baseDir = process.cwd(), options) => {
86
+ const statePath = (0, exports.getStatePath)(app, service, baseDir);
60
87
  await (0, lockManager_1.withLock)(statePath, operation, async () => {
61
- (0, exports.saveState)(state, baseDir);
88
+ (0, exports.saveState)(state, app, service, stage, baseDir);
62
89
  }, options);
63
90
  };
64
91
  exports.saveStateWithLock = saveStateWithLock;
@@ -28,7 +28,7 @@ exports.en = {
28
28
  STACK_NOT_EXISTS_SKIPPED: 'Stack: {{stackName}} not exists, skipped! 🚫',
29
29
  STACK_DELETED: 'Stack: {{stackName}} deleted!🗑 ',
30
30
  STACK_DELETE_FAILED: 'Stack: {{stackName}} delete failed! ❌, error: {{error}}',
31
- DESTROYING_STACK: 'Destroying stack: {{stackName}}, provider: {{provider}}, region: {{region}}...',
31
+ DESTROYING_STACK: 'Destroying stack: provider: {{provider}}, region: {{region}}...',
32
32
  // Asset messages
33
33
  FOLDER_COMPRESSED_TO: 'Folder compressed to: {{zipPath}}',
34
34
  FAILED_TO_COMPRESS_FOLDER: 'Failed to compress folder: {{error}}',
@@ -48,7 +48,7 @@ exports.en = {
48
48
  LOCAL_SERVER_STOPPED: 'localServer stopped',
49
49
  LOCAL_GATEWAY_ERROR: 'Local gateway error',
50
50
  ERROR_STOPPING_LOCAL_SERVER: 'Error stopping localServer',
51
- RUN_LOCAL_STARTING: 'run-local starting: stack={{stackName}} stage={{stage}} port={{port}} debug={{debug}} watch={{watch}}',
51
+ RUN_LOCAL_STARTING: 'run-local starting: stage={{stage}} port={{port}} debug={{debug}} watch={{watch}}',
52
52
  // Function execution
53
53
  FUNCTION_REQUEST_RECEIVED: 'Function request received by local server -> {{method}} {{identifier}} ',
54
54
  INVOKING_WORKER_WITH_EVENT_TYPE: 'Invoking worker with event type: {{eventType}} and context',
@@ -28,7 +28,7 @@ exports.zhCN = {
28
28
  STACK_NOT_EXISTS_SKIPPED: '资源栈: {{stackName}} 不存在,已跳过! 🚫',
29
29
  STACK_DELETED: '资源栈: {{stackName}} 已删除!🗑 ',
30
30
  STACK_DELETE_FAILED: '资源栈: {{stackName}} 删除失败! ❌, 错误: {{error}}',
31
- DESTROYING_STACK: '正在销毁资源栈: {{stackName}}, 供应商: {{provider}}, 地区: {{region}}...',
31
+ DESTROYING_STACK: '正在销毁资源栈: 供应商: {{provider}}, 地区: {{region}}...',
32
32
  // Asset messages
33
33
  FOLDER_COMPRESSED_TO: '文件夹已压缩至: {{zipPath}}',
34
34
  FAILED_TO_COMPRESS_FOLDER: '压缩文件夹失败: {{error}}',
@@ -48,7 +48,7 @@ exports.zhCN = {
48
48
  LOCAL_SERVER_STOPPED: '本地服务器已停止',
49
49
  LOCAL_GATEWAY_ERROR: '本地网关错误',
50
50
  ERROR_STOPPING_LOCAL_SERVER: '停止本地服务器时出错',
51
- RUN_LOCAL_STARTING: '启动本地运行: stack={{stackName}} stage={{stage}} port={{port}} debug={{debug}} watch={{watch}}',
51
+ RUN_LOCAL_STARTING: '启动本地运行: stage={{stage}} port={{port}} debug={{debug}} watch={{watch}}',
52
52
  // Function execution
53
53
  FUNCTION_REQUEST_RECEIVED: '本地服务器收到函数请求 -> {{method}} {{identifier}} ',
54
54
  INVOKING_WORKER_WITH_EVENT_TYPE: '使用事件类型调用工作进程: {{eventType}} 和上下文',