@geek-fun/serverlessinsight 0.9.4 → 0.9.6

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 (79) hide show
  1. package/AGENTS.md +5 -2
  2. package/CHANGELOG.md +44 -0
  3. package/README.md +26 -6
  4. package/README.zh-CN.md +26 -6
  5. package/codecov +0 -0
  6. package/codecov.SHA256SUM +1 -1
  7. package/codecov.SHA256SUM.sig +13 -13
  8. package/dist/package.json +1 -1
  9. package/dist/src/commands/deploy.js +7 -2
  10. package/dist/src/commands/destroy.js +6 -3
  11. package/dist/src/commands/forceUnlock.js +16 -21
  12. package/dist/src/commands/index.js +14 -4
  13. package/dist/src/commands/migrate.js +105 -132
  14. package/dist/src/commands/plan.js +2 -2
  15. package/dist/src/commands/show.js +17 -6
  16. package/dist/src/common/aggregateState.js +185 -0
  17. package/dist/src/common/aggregateStore.js +247 -0
  18. package/dist/src/common/apiClient.js +35 -12
  19. package/dist/src/common/constants.js +2 -1
  20. package/dist/src/common/context.js +22 -15
  21. package/dist/src/common/effectiveConfig.js +48 -0
  22. package/dist/src/common/iacHelper.js +2 -2
  23. package/dist/src/common/index.js +5 -0
  24. package/dist/src/common/jsonOutput.js +2 -13
  25. package/dist/src/common/migrationMarker.js +0 -7
  26. package/dist/src/common/nameBuilder.js +2 -3
  27. package/dist/src/common/regionalMigration.js +261 -0
  28. package/dist/src/common/saasProtocol.js +41 -0
  29. package/dist/src/common/stateBackend/cosStateBackend.js +88 -8
  30. package/dist/src/common/stateBackend/index.js +42 -18
  31. package/dist/src/common/stateBackend/localStateBackend.js +61 -26
  32. package/dist/src/common/stateBackend/ossStateBackend.js +62 -9
  33. package/dist/src/common/stateBackend/remoteStateBackend.js +94 -94
  34. package/dist/src/common/stateBackend/saasStateBackend.js +327 -92
  35. package/dist/src/common/stateBackend/types.js +9 -0
  36. package/dist/src/common/stateManager.js +38 -11
  37. package/dist/src/common/stateScope.js +34 -0
  38. package/dist/src/common/stateStorageIO.js +31 -0
  39. package/dist/src/lang/en.js +43 -2
  40. package/dist/src/lang/zh-CN.js +43 -2
  41. package/dist/src/parser/index.js +33 -8
  42. package/dist/src/parser/templateValues.js +31 -0
  43. package/dist/src/stack/aliyunStack/deployer.js +5 -5
  44. package/dist/src/stack/aliyunStack/destroyer.js +5 -5
  45. package/dist/src/stack/aliyunStack/fc3Planner.js +1 -1
  46. package/dist/src/stack/aliyunStack/fc3Resource.js +2 -2
  47. package/dist/src/stack/aliyunStack/planner.js +1 -1
  48. package/dist/src/stack/aliyunStack/sharedLogProject.js +2 -2
  49. package/dist/src/stack/ownershipTag.js +34 -26
  50. package/dist/src/stack/scfStack/deployer.js +5 -5
  51. package/dist/src/stack/scfStack/destroyer.js +5 -6
  52. package/dist/src/stack/scfStack/planner.js +1 -1
  53. package/dist/src/stack/scfStack/scfResource.js +1 -1
  54. package/dist/src/stack/scfStack/sharedLogset.js +5 -2
  55. package/dist/src/stack/volcengineStack/deployer.js +3 -3
  56. package/dist/src/stack/volcengineStack/destroyer.js +2 -3
  57. package/dist/src/stack/volcengineStack/planner.js +1 -1
  58. package/dist/src/stack/volcengineStack/sharedLogProject.js +4 -4
  59. package/dist/src/stack/volcengineStack/vefaasResource.js +1 -1
  60. package/dist/src/types/domains/state.js +28 -2
  61. package/dist/src/validator/index.js +3 -1
  62. package/dist/src/validator/rootSchema.js +8 -0
  63. package/dist/tsconfig.tsbuildinfo +1 -1
  64. package/package.json +1 -1
  65. package/release-notes.md +8 -36
  66. package/samples/README_TENCENT_COS.md +65 -23
  67. package/samples/README_TENCENT_SCF.md +44 -26
  68. package/.serverlessinsight/state-cdn-flow-app-cdn-flow-service.json.backup +0 -14
  69. package/.serverlessinsight/state-iam-test-app-iam-test-service.json.backup +0 -32
  70. package/.serverlessinsight/state-insight-poc-app-insight-poc-tencent.json.backup +0 -90
  71. package/.serverlessinsight/state-insight-poc-app-log-insight-poc-tencent-log.json.backup +0 -118
  72. package/.serverlessinsight/state-insight-poc-deploy-app-insight-poc-deploy.json.backup +0 -215
  73. package/.serverlessinsight/state-insight-poc-destroy-app-insight-poc-destroy.json.backup +0 -14
  74. package/.serverlessinsight/state-insight-poc-timer-app-insight-poc-timer.json.backup +0 -132
  75. package/.serverlessinsight/state-insight-volc-app-insight-volc.json.backup +0 -55
  76. package/.serverlessinsight/state-insight-volc-destroy-app-insight-volc-destroy.json.backup +0 -1
  77. package/.serverlessinsight/state-insight-volc-nested-app-insight-volc-nested.json.backup +0 -93
  78. package/.serverlessinsight/state-nested-drift-app-nested-drift-service.json.backup +0 -163
  79. package/.serverlessinsight/state-role-reconcile-test-app-role-reconcile-test-service.json.backup +0 -148
@@ -0,0 +1,247 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createAggregateStore = void 0;
4
+ const types_1 = require("../types");
5
+ const lang_1 = require("../lang");
6
+ const aggregateState_1 = require("./aggregateState");
7
+ const stateScope_1 = require("./stateScope");
8
+ const migrationMarker_1 = require("./migrationMarker");
9
+ const constants_1 = require("./constants");
10
+ const regionalMigration_1 = require("./regionalMigration");
11
+ const logger_1 = require("./logger");
12
+ const createAggregateStore = (io, selected, options) => {
13
+ const scope = (0, stateScope_1.normalizeScope)(selected);
14
+ const scopeKey = options.key;
15
+ const markerAction = options.markerAction;
16
+ let source = 'empty';
17
+ let plannedHash;
18
+ let legacyRegionBinding;
19
+ const validateDocument = (raw) => {
20
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
21
+ throw (0, aggregateState_1.aggregateStateCorruptError)(options.key);
22
+ }
23
+ const value = raw;
24
+ if (value.app !== scope.app || value.service !== scope.service) {
25
+ throw new types_1.StateScopeMismatchError(scope, {
26
+ app: String(value.app ?? ''),
27
+ service: String(value.service ?? ''),
28
+ provider: typeof value.provider === 'string' ? value.provider : scope.provider,
29
+ stage: scope.stage,
30
+ region: scope.region,
31
+ });
32
+ }
33
+ if (value.version === aggregateState_1.AGGREGATE_STATE_VERSION) {
34
+ return (0, aggregateState_1.readAggregateDocument)(value, scope, options.key);
35
+ }
36
+ if (value.version !== '3.0') {
37
+ throw new types_1.StateVersionError(String(value.version ?? ''), aggregateState_1.AGGREGATE_STATE_VERSION);
38
+ }
39
+ if (typeof value.provider !== 'string' ||
40
+ typeof value.stages !== 'object' ||
41
+ value.stages === null ||
42
+ Array.isArray(value.stages)) {
43
+ throw (0, aggregateState_1.aggregateStateCorruptError)(options.key);
44
+ }
45
+ return value;
46
+ };
47
+ const readStoredDocument = async () => {
48
+ let raw;
49
+ try {
50
+ raw = await io.read(options.key);
51
+ }
52
+ catch (error) {
53
+ if (!(error instanceof SyntaxError))
54
+ throw error;
55
+ const backup = await io.read(`${options.key}.backup`);
56
+ if (backup === null)
57
+ throw (0, aggregateState_1.aggregateStateCorruptError)(options.key, error);
58
+ return validateDocument(backup);
59
+ }
60
+ if (raw === null) {
61
+ const backup = await io.read(`${options.key}.backup`);
62
+ if (backup !== null)
63
+ return validateDocument(backup);
64
+ return null;
65
+ }
66
+ return validateDocument(raw);
67
+ };
68
+ const readDocument = async () => {
69
+ const migration = await io.read(`${options.key}${constants_1.REGIONAL_MIGRATION_SUFFIX}`);
70
+ if (migration !== null) {
71
+ if (typeof migration !== 'object' || !migration || !('phase' in migration))
72
+ throw (0, aggregateState_1.aggregateStateCorruptError)(options.key);
73
+ if (migration.phase !== 'complete') {
74
+ const opId = 'opId' in migration ? String(migration.opId) : options.key;
75
+ throw new Error(lang_1.lang.__('REGIONAL_MIGRATION_PENDING', { opId }));
76
+ }
77
+ }
78
+ const document = await readStoredDocument();
79
+ if (migration && !document)
80
+ throw (0, aggregateState_1.aggregateStateCorruptError)(scopeKey);
81
+ return document;
82
+ };
83
+ const isAggregate = (document) => document.version === aggregateState_1.AGGREGATE_STATE_VERSION;
84
+ const loadState = async (captureBase = true) => {
85
+ const document = await readDocument();
86
+ if (document && !isAggregate(document)) {
87
+ source = 'legacy';
88
+ (0, migrationMarker_1.enforceMigrationMarker)(document, options.markerAction);
89
+ if (document.managedBy === migrationMarker_1.MANAGED_BY_SAAS) {
90
+ return { ...document, resources: document.stages[scope.stage]?.resources ?? {} };
91
+ }
92
+ const empty = (0, aggregateState_1.projectAggregateScope)(null, scope);
93
+ const selected = document.stages[scope.stage];
94
+ const selectRegion = (resources) => Object.fromEntries(Object.entries(resources ?? {}).filter(([, resource]) => {
95
+ const region = resource.region?.trim() || legacyRegionBinding;
96
+ if (!region) {
97
+ throw new Error(lang_1.lang.__('REGIONAL_MIGRATION_UNKNOWN_REGION_REQUIRED'));
98
+ }
99
+ return (0, stateScope_1.canonicalizeRegion)(region) === scope.region;
100
+ }));
101
+ const resources = document.provider === scope.provider ? selectRegion(selected?.resources) : {};
102
+ const shared = document.provider === scope.provider ? selectRegion(selected?.shared) : {};
103
+ const metadata = Object.fromEntries(['orgId', 'appId', 'serviceId', 'managedBy']
104
+ .filter((key) => document[key] !== undefined)
105
+ .map((key) => [key, document[key]]));
106
+ return { ...empty, ...metadata, stages: { [scope.stage]: { resources, shared } }, resources };
107
+ }
108
+ source = (0, aggregateState_1.aggregatePartition)(document, scope) ? 'scoped' : 'empty';
109
+ const state = (0, aggregateState_1.projectAggregateScope)(document, scope);
110
+ (0, migrationMarker_1.enforceMigrationMarker)(state, options.markerAction);
111
+ if (captureBase && plannedHash === undefined)
112
+ plannedHash = (0, aggregateState_1.deploymentStateHash)(state);
113
+ return state;
114
+ };
115
+ const probeWriteReadiness = async () => {
116
+ const document = await readDocument();
117
+ if (document && !isAggregate(document)) {
118
+ source = 'legacy';
119
+ (0, migrationMarker_1.enforceMigrationMarker)(document, options.markerAction);
120
+ return {
121
+ ready: false,
122
+ source,
123
+ reason: lang_1.lang.__('STATE_STORE_UPGRADE_REQUIRED', { location: options.key }),
124
+ };
125
+ }
126
+ source = (0, aggregateState_1.aggregatePartition)(document, scope) ? 'scoped' : 'empty';
127
+ (0, migrationMarker_1.enforceMigrationMarker)((0, aggregateState_1.projectAggregateScope)(document, scope), options.markerAction);
128
+ return { ready: true, source };
129
+ };
130
+ const writableDocument = async () => {
131
+ const document = await readDocument();
132
+ if (document && !isAggregate(document)) {
133
+ throw new Error(lang_1.lang.__('STATE_STORE_UPGRADE_REQUIRED', { location: options.key }));
134
+ }
135
+ return document;
136
+ };
137
+ const writeDocument = async (previous, next) => {
138
+ if (previous && options.backupWrites)
139
+ await io.write(`${options.key}.backup`, previous);
140
+ await io.write(options.key, next);
141
+ source = 'scoped';
142
+ };
143
+ const upgradeLegacyState = async (options = {}) => {
144
+ const binding = options.bindUnknownRegion === undefined
145
+ ? undefined
146
+ : (0, stateScope_1.canonicalizeRegion)(options.bindUnknownRegion);
147
+ legacyRegionBinding = binding;
148
+ const paths = {
149
+ legacyKey: scopeKey,
150
+ backupKey: (opId) => `${scopeKey}.pre-upgrade-${opId}.json`,
151
+ reportKey: (opId) => `${scopeKey}.upgrade-report-${opId}.json`,
152
+ };
153
+ const pending = await (0, regionalMigration_1.readRegionalMigrationJournal)(io, paths);
154
+ if (pending &&
155
+ (!pending.plan ||
156
+ !pending.options ||
157
+ typeof pending.plan.opId !== 'string' ||
158
+ !['applying', 'complete'].includes(pending.phase))) {
159
+ throw (0, aggregateState_1.aggregateStateCorruptError)(scopeKey);
160
+ }
161
+ const document = await readStoredDocument();
162
+ if (pending?.phase === 'complete' && (!document || !isAggregate(document))) {
163
+ throw new Error(lang_1.lang.__('REGIONAL_MIGRATION_SOURCE_CHANGED'));
164
+ }
165
+ if (pending?.phase !== 'applying' && (!document || isAggregate(document)))
166
+ return;
167
+ const legacy = pending?.phase === 'applying'
168
+ ? await io.read(paths.backupKey(pending.plan.opId))
169
+ : document;
170
+ if (!legacy)
171
+ throw new Error(lang_1.lang.__('REGIONAL_MIGRATION_BACKUP_MISSING', { opId: pending?.plan.opId ?? scopeKey }));
172
+ if (isAggregate(legacy))
173
+ throw (0, aggregateState_1.aggregateStateCorruptError)(scopeKey);
174
+ validateDocument(legacy);
175
+ if (legacy.managedBy === migrationMarker_1.MANAGED_BY_SAAS) {
176
+ (0, migrationMarker_1.enforceMigrationMarker)(legacy, markerAction);
177
+ return;
178
+ }
179
+ if (pending &&
180
+ (pending.options.app !== scope.app ||
181
+ pending.options.service !== scope.service ||
182
+ (binding !== undefined && binding !== pending.options.bindUnknownRegion))) {
183
+ throw new Error(lang_1.lang.__('REGIONAL_MIGRATION_PENDING', { opId: pending.plan.opId }));
184
+ }
185
+ const migrationOptions = pending?.options ?? {
186
+ app: scope.app,
187
+ service: scope.service,
188
+ provider: legacy.provider,
189
+ ...(binding ? { bindUnknownRegion: binding } : {}),
190
+ };
191
+ const plan = pending?.plan ?? (0, regionalMigration_1.planRegionalMigration)(legacy, migrationOptions);
192
+ if (plan.unknown.length && !migrationOptions.bindUnknownRegion) {
193
+ plan.unknown.forEach((item) => logger_1.logger.warn(lang_1.lang.__('REGIONAL_MIGRATION_UNKNOWN_ITEM', item)));
194
+ throw new Error(lang_1.lang.__('REGIONAL_MIGRATION_UNKNOWN_REGION_REQUIRED'));
195
+ }
196
+ if (!options.dryRun)
197
+ await (0, regionalMigration_1.applyRegionalMigration)(io, legacy, paths, plan, migrationOptions);
198
+ };
199
+ return {
200
+ upgradeLegacyState,
201
+ loadState,
202
+ probeWriteReadiness,
203
+ readStateSource: () => source,
204
+ clearPlanBase: () => {
205
+ plannedHash = undefined;
206
+ },
207
+ verifyPlanBase: async () => {
208
+ const readiness = await probeWriteReadiness();
209
+ if (!readiness.ready)
210
+ throw new Error(readiness.reason);
211
+ if (plannedHash !== undefined &&
212
+ (0, aggregateState_1.deploymentStateHash)(await loadState(false)) !== plannedHash) {
213
+ throw new Error(lang_1.lang.__('STATE_PLAN_BASE_CHANGED'));
214
+ }
215
+ },
216
+ saveState: async (state) => {
217
+ const document = await writableDocument();
218
+ (0, migrationMarker_1.enforceMigrationMarker)((0, aggregateState_1.projectAggregateScope)(document, scope), options.markerAction);
219
+ await writeDocument(document, (0, aggregateState_1.mergeAggregateScope)(document, scope, state));
220
+ },
221
+ patchPersisted: async (patch) => {
222
+ const existing = await readDocument();
223
+ if (existing &&
224
+ !isAggregate(existing) &&
225
+ markerAction === 'off' &&
226
+ existing.managedBy === migrationMarker_1.MANAGED_BY_SAAS &&
227
+ Object.keys(patch).length === 1 &&
228
+ Object.prototype.hasOwnProperty.call(patch, 'managedBy') &&
229
+ patch.managedBy === undefined) {
230
+ const { managedBy: _owner, ...legacy } = existing;
231
+ if (options.backupWrites)
232
+ await io.write(`${scopeKey}.backup`, existing);
233
+ await io.write(scopeKey, { ...legacy, serial: (legacy.serial ?? 0) + 1 });
234
+ return;
235
+ }
236
+ const document = await writableDocument();
237
+ const current = document ?? {
238
+ version: aggregateState_1.AGGREGATE_STATE_VERSION,
239
+ app: scope.app,
240
+ service: scope.service,
241
+ stages: {},
242
+ };
243
+ await writeDocument(document, (0, aggregateState_1.patchAggregateScope)(current, scope, patch));
244
+ },
245
+ };
246
+ };
247
+ exports.createAggregateStore = createAggregateStore;
@@ -2,6 +2,12 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.validateApiKey = exports.createApiClient = exports.ApiError = void 0;
4
4
  const lang_1 = require("../lang");
5
+ const HTTP_ERROR_KEYS = {
6
+ 401: 'API_ERROR_401',
7
+ 403: 'API_ERROR_403',
8
+ 404: 'API_ERROR_404',
9
+ 409: 'API_ERROR_409',
10
+ };
5
11
  /**
6
12
  * API error carrying the HTTP status so callers can distinguish "not found"
7
13
  * (legitimate empty state on first deploy) from network/5xx failures, which
@@ -9,10 +15,12 @@ const lang_1 = require("../lang");
9
15
  */
10
16
  class ApiError extends Error {
11
17
  status;
18
+ code;
12
19
  constructor(message, status) {
13
20
  super(message);
14
21
  this.name = 'ApiError';
15
22
  this.status = status;
23
+ this.code = HTTP_ERROR_KEYS[status] ?? 'API_ERROR_UNKNOWN';
16
24
  }
17
25
  }
18
26
  exports.ApiError = ApiError;
@@ -40,18 +48,33 @@ const camelizeKeys = (value) => {
40
48
  }
41
49
  return result;
42
50
  };
43
- const handleHttpError = (response) => {
44
- const status = response.status;
45
- if (status === 401)
46
- throw new ApiError(lang_1.lang.__('API_ERROR_401'), 401);
47
- if (status === 403)
48
- throw new ApiError(lang_1.lang.__('API_ERROR_403'), 403);
49
- if (status === 404)
50
- throw new ApiError(lang_1.lang.__('API_ERROR_404'), 404);
51
- if (status === 409) {
52
- throw new ApiError(lang_1.lang.__('API_ERROR_409', { message: `HTTP Error ${status}` }), 409);
51
+ const readErrorMessages = async (response) => {
52
+ try {
53
+ const body = await response.json();
54
+ if (!body || typeof body !== 'object' || !('messages' in body) || !Array.isArray(body.messages))
55
+ return undefined;
56
+ return (body.messages
57
+ .filter((message) => typeof message === 'string' && !!message.trim())
58
+ .map((message) => message.trim())
59
+ .join('\n') || undefined);
60
+ }
61
+ catch {
62
+ return undefined;
63
+ }
64
+ };
65
+ const formatHttpError = (status, details) => {
66
+ const key = HTTP_ERROR_KEYS[status] ?? 'API_ERROR_UNKNOWN';
67
+ const message = details ?? `HTTP Error ${status}`;
68
+ if (key === 'API_ERROR_UNKNOWN') {
69
+ return lang_1.lang.__(key, { status: String(status), message });
53
70
  }
54
- throw new ApiError(lang_1.lang.__('API_ERROR_UNKNOWN', { status: String(status), message: `HTTP Error ${status}` }), status);
71
+ if (key === 'API_ERROR_409')
72
+ return lang_1.lang.__(key, { message });
73
+ return [lang_1.lang.__(key), details].filter(Boolean).join('\n');
74
+ };
75
+ const handleHttpError = async (response) => {
76
+ const details = await readErrorMessages(response);
77
+ throw new ApiError(formatHttpError(response.status, details), response.status);
55
78
  };
56
79
  const buildRequestInit = (method, headers, body) => ({
57
80
  method: method.toUpperCase(),
@@ -88,7 +111,7 @@ const createApiClient = (options) => {
88
111
  throw new Error(lang_1.lang.__('CREDENTIAL_NETWORK_ERROR'));
89
112
  }
90
113
  if (!response.ok) {
91
- handleHttpError(response);
114
+ await handleHttpError(response);
92
115
  }
93
116
  try {
94
117
  return unwrapResponse(await response.json());
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CLS_TOPIC_POLL_MAX_ATTEMPTS = exports.CLS_TOPIC_POLL_INTERVAL_MS = exports.SCF_STATUS_POLL_MAX_ATTEMPTS = exports.SCF_STATUS_POLL_INTERVAL_MS = exports.RAM_ROLE_PROPAGATION_DELAY_MS = exports.APIGW_DNS_PUBLIC_RESOLUTION_DELAY_MS = exports.APIGW_DNS_PUBLIC_RESOLUTION_MAX_ATTEMPTS = exports.APIGW_DOMAIN_BIND_RETRY_DELAY_MS = exports.APIGW_DOMAIN_BIND_MAX_RETRIES = exports.DNS_PROPAGATION_DELAY_MS = exports.DNS_PROPAGATION_MAX_ATTEMPTS = exports.DOMAIN_BIND_RETRY_DELAY_MS = exports.DOMAIN_BIND_MAX_RETRIES = exports.STALE_LOCK_THRESHOLD = exports.DEFAULT_LOCK_RETRY_DELAY = exports.DEFAULT_LOCK_TIMEOUT = exports.LOCK_FILE_SUFFIX = exports.OSS_STATE_REQUEST_TIMEOUT_MS = exports.OSS_STATE_CONNECT_TIMEOUT_MS = exports.FC3_CODE_INLINE_SIZE_LIMIT = exports.ALIYUN_QUERY_READ_TIMEOUT_MS = exports.ALIYUN_QUERY_CONNECT_TIMEOUT_MS = exports.ALIYUN_FC3_READ_TIMEOUT_MS = exports.ALIYUN_FC3_CONNECT_TIMEOUT_MS = exports.SI_LOCALSTACK_SERVER_PORT = exports.SI_BOOTSTRAP_BUCKET_PREFIX = exports.SI_BOOTSTRAP_FC_PREFIX = exports.OSS_DEPLOYMENT_TIMEOUT = exports.CODE_ZIP_SIZE_LIMIT = void 0;
3
+ exports.REGIONAL_MIGRATION_SUFFIX = exports.CLS_TOPIC_POLL_MAX_ATTEMPTS = exports.CLS_TOPIC_POLL_INTERVAL_MS = exports.SCF_STATUS_POLL_MAX_ATTEMPTS = exports.SCF_STATUS_POLL_INTERVAL_MS = exports.RAM_ROLE_PROPAGATION_DELAY_MS = exports.APIGW_DNS_PUBLIC_RESOLUTION_DELAY_MS = exports.APIGW_DNS_PUBLIC_RESOLUTION_MAX_ATTEMPTS = exports.APIGW_DOMAIN_BIND_RETRY_DELAY_MS = exports.APIGW_DOMAIN_BIND_MAX_RETRIES = exports.DNS_PROPAGATION_DELAY_MS = exports.DNS_PROPAGATION_MAX_ATTEMPTS = exports.DOMAIN_BIND_RETRY_DELAY_MS = exports.DOMAIN_BIND_MAX_RETRIES = exports.STALE_LOCK_THRESHOLD = exports.DEFAULT_LOCK_RETRY_DELAY = exports.DEFAULT_LOCK_TIMEOUT = exports.LOCK_FILE_SUFFIX = exports.OSS_STATE_REQUEST_TIMEOUT_MS = exports.OSS_STATE_CONNECT_TIMEOUT_MS = exports.FC3_CODE_INLINE_SIZE_LIMIT = exports.ALIYUN_QUERY_READ_TIMEOUT_MS = exports.ALIYUN_QUERY_CONNECT_TIMEOUT_MS = exports.ALIYUN_FC3_READ_TIMEOUT_MS = exports.ALIYUN_FC3_CONNECT_TIMEOUT_MS = exports.SI_LOCALSTACK_SERVER_PORT = exports.SI_BOOTSTRAP_BUCKET_PREFIX = exports.SI_BOOTSTRAP_FC_PREFIX = exports.OSS_DEPLOYMENT_TIMEOUT = exports.CODE_ZIP_SIZE_LIMIT = void 0;
4
4
  exports.CODE_ZIP_SIZE_LIMIT = 300 * 1000; // 300 KB - code package size limit for inline deployment
5
5
  exports.OSS_DEPLOYMENT_TIMEOUT = 3000; // in seconds
6
6
  exports.SI_BOOTSTRAP_FC_PREFIX = 'si-bootstrap-api';
@@ -49,3 +49,4 @@ exports.SCF_STATUS_POLL_MAX_ATTEMPTS = 20; // up to 60 seconds
49
49
  // queryable via DescribeTopics until the platform finishes provisioning)
50
50
  exports.CLS_TOPIC_POLL_INTERVAL_MS = 3000; // 3 seconds
51
51
  exports.CLS_TOPIC_POLL_MAX_ATTEMPTS = 20; // up to 60 seconds
52
+ exports.REGIONAL_MIGRATION_SUFFIX = '.state-upgrade.json';
@@ -8,8 +8,9 @@ const node_fs_1 = __importDefault(require("node:fs"));
8
8
  const node_path_1 = __importDefault(require("node:path"));
9
9
  const credentials_1 = require("./credentials");
10
10
  const imsClient_1 = require("./imsClient");
11
- const providerEnum_1 = require("./providerEnum");
12
11
  const refreshCache_1 = require("./refreshCache");
12
+ const effectiveConfig_1 = require("./effectiveConfig");
13
+ const logger_1 = require("./logger");
13
14
  const lang_1 = require("../lang");
14
15
  let context;
15
16
  const DEFAULT_IAC_FILES = [
@@ -55,31 +56,37 @@ const getIacLocation = (location) => {
55
56
  };
56
57
  exports.getIacLocation = getIacLocation;
57
58
  const setContext = async (config, reaValToken = false) => {
58
- const region = config.region ??
59
- config.iacProvider?.region ??
60
- process.env.SI_REGION ??
61
- process.env.ALIYUN_REGION ??
62
- 'cn-hangzhou';
63
- if (process.env.ROS_REGION_ID && !process.env.SI_REGION) {
64
- console.warn(lang_1.lang.__('CONTEXT_REGION_DEPRECATED'));
59
+ const effective = (0, effectiveConfig_1.resolveEffectiveConfig)({
60
+ cli: { stage: config.stage, region: config.region, provider: config.provider },
61
+ iacProvider: {
62
+ name: config.iacProvider?.name,
63
+ region: config.iacProvider?.region,
64
+ },
65
+ });
66
+ if (!config.region &&
67
+ !config.iacProvider?.region &&
68
+ process.env.ROS_REGION_ID &&
69
+ !process.env.SI_REGION) {
70
+ logger_1.logger.warn(lang_1.lang.__('CONTEXT_REGION_DEPRECATED'));
65
71
  }
66
- const provider = (config.provider ??
67
- config.iacProvider?.name ??
68
- providerEnum_1.ProviderEnum.ALIYUN);
69
72
  const credentials = (0, credentials_1.getCredentials)({
70
73
  accessKeyId: config.accessKeyId,
71
74
  accessKeySecret: config.accessKeySecret,
72
75
  securityToken: config.securityToken,
73
- }, provider);
76
+ }, effective.provider);
74
77
  const newContext = {
75
- stage: config.stage ?? 'default',
78
+ stage: effective.stage,
76
79
  app: config.app,
77
80
  service: config.service,
78
- provider,
79
- region,
81
+ provider: effective.provider,
82
+ region: effective.region,
80
83
  accessKeyId: credentials.accessKeyId,
81
84
  accessKeySecret: credentials.accessKeySecret,
82
85
  securityToken: credentials.securityToken,
86
+ storage: (() => {
87
+ const defaults = (0, effectiveConfig_1.resolveEffectiveConfig)({ iacProvider: config.iacProvider });
88
+ return { provider: defaults.provider, region: defaults.region };
89
+ })(),
83
90
  iacLocation: (0, exports.getIacLocation)(config.location),
84
91
  parameters: Object.entries(config.parameters ?? {}).map(([key, value]) => ({ key, value })),
85
92
  stages: Object.entries(config.stages ?? {}).reduce((acc, [stage, parameters]) => ({
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveEffectiveConfig = void 0;
4
+ const providerEnum_1 = require("./providerEnum");
5
+ const stateScope_1 = require("./stateScope");
6
+ const lang_1 = require("../lang");
7
+ const DEFAULT_STAGE = 'default';
8
+ const DEFAULT_REGION = 'cn-hangzhou';
9
+ const parseCliProvider = (raw) => {
10
+ if (!raw)
11
+ return undefined;
12
+ const normalized = raw.trim().toLowerCase();
13
+ if (!Object.values(providerEnum_1.ProviderEnum).includes(normalized)) {
14
+ throw new Error(lang_1.lang.__('EFFECTIVE_CONFIG_UNKNOWN_PROVIDER', { provider: raw }));
15
+ }
16
+ return normalized;
17
+ };
18
+ const resolveEffectiveConfig = (input) => {
19
+ const cli = input.cli ?? {};
20
+ const iacProvider = input.iacProvider ?? {};
21
+ const cliRegion = cli.region?.trim() || undefined;
22
+ const cliProvider = parseCliProvider(cli.provider);
23
+ const region = cliRegion ??
24
+ iacProvider.region?.trim() ??
25
+ process.env.SI_REGION ??
26
+ process.env.ALIYUN_REGION ??
27
+ DEFAULT_REGION;
28
+ const provider = cliProvider ?? iacProvider.name ?? providerEnum_1.ProviderEnum.ALIYUN;
29
+ const stage = cli.stage?.trim() || DEFAULT_STAGE;
30
+ return {
31
+ provider,
32
+ region: canonicalRegion(region),
33
+ stage: (0, stateScope_1.validateScopeKeyPart)(stage, 'stage'),
34
+ overrides: {
35
+ region: !!cliRegion,
36
+ provider: !!cliProvider,
37
+ stage: !!cli.stage?.trim(),
38
+ },
39
+ };
40
+ };
41
+ exports.resolveEffectiveConfig = resolveEffectiveConfig;
42
+ const canonicalRegion = (region) => {
43
+ const canonical = region.trim().toLowerCase();
44
+ if (!canonical) {
45
+ throw new Error(lang_1.lang.__('EFFECTIVE_CONFIG_REGION_REQUIRED'));
46
+ }
47
+ return canonical;
48
+ };
@@ -51,7 +51,7 @@ const inferType = (value, wasTemplateRef) => {
51
51
  return value;
52
52
  };
53
53
  /* istanbul ignore next */
54
- const calcValue = (rawValue, ctx, iacVars) => {
54
+ const calcValue = (rawValue, ctx, iacVars, inferScalar = true) => {
55
55
  const containsStage = rawValue.match(/\$\{ctx.stage}/);
56
56
  const containsVar = rawValue.match(/\$\{vars.\w+}/);
57
57
  const containsMap = rawValue.match(/\$\{stages\.(\w+)}/);
@@ -89,7 +89,7 @@ const calcValue = (rawValue, ctx, iacVars) => {
89
89
  return stageValue || '';
90
90
  });
91
91
  }
92
- return inferType(value, isExactTemplateRef);
92
+ return inferType(value, inferScalar && isExactTemplateRef);
93
93
  };
94
94
  exports.calcValue = calcValue;
95
95
  /* istanbul ignore next */
@@ -47,3 +47,8 @@ __exportStar(require("./planCapabilities"), exports);
47
47
  __exportStar(require("./bucketPolicy"), exports);
48
48
  __exportStar(require("./functionDefinition"), exports);
49
49
  __exportStar(require("./planRedaction"), exports);
50
+ __exportStar(require("./stateScope"), exports);
51
+ __exportStar(require("./effectiveConfig"), exports);
52
+ __exportStar(require("./regionalMigration"), exports);
53
+ __exportStar(require("./stateStorageIO"), exports);
54
+ __exportStar(require("./saasProtocol"), exports);
@@ -3,20 +3,9 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.buildPlanJson = exports.buildPlanChange = exports.buildPlanSummary = exports.writeJson = exports.isJsonMode = exports.setJsonMode = exports.SHOW_JSON_VERSION = exports.VALIDATE_JSON_VERSION = exports.PLAN_JSON_VERSION = void 0;
4
4
  const planRedaction_1 = require("./planRedaction");
5
5
  const planFormatter_1 = require("./planFormatter");
6
- /**
7
- * Machine-readable output channel (issue #250): the `--json` surface of the CLI.
8
- *
9
- * Contract with agents:
10
- * - logs (pino) go to stderr, JSON results go to stdout — a pipe of stdout is
11
- * always a single JSON document (jq-parseable);
12
- * - every envelope carries a version field (`planVersion` / `validateVersion` /
13
- * `showVersion`) so consumers can pin a shape;
14
- * - failures emit `{ error: { code, message } }` where `code` is the stable
15
- * i18n key behind the message — locale changes never change the code.
16
- */
17
- exports.PLAN_JSON_VERSION = 1;
6
+ exports.PLAN_JSON_VERSION = 2;
18
7
  exports.VALIDATE_JSON_VERSION = 1;
19
- exports.SHOW_JSON_VERSION = 1;
8
+ exports.SHOW_JSON_VERSION = 2;
20
9
  let jsonMode = false;
21
10
  const setJsonMode = (enabled) => {
22
11
  jsonMode = enabled;
@@ -15,13 +15,6 @@ const isMigratedToSaas = (state) => {
15
15
  return state?.managedBy === exports.MANAGED_BY_SAAS;
16
16
  };
17
17
  exports.isMigratedToSaas = isMigratedToSaas;
18
- /**
19
- * Ownership handover check (decision D-4): after migration the Console is the
20
- * single source of truth. Mutating commands (deploy/destroy) pass 'refuse' so
21
- * a legacy-backend write attempt fails closed; read-only commands (plan/diff/
22
- * show) pass 'warn'; `si migrate` itself passes 'off' (it must be able to read
23
- * marked state for idempotent re-runs and --rollback).
24
- */
25
18
  const enforceMigrationMarker = (state, action) => {
26
19
  if (action === 'off' || !(0, exports.isMigratedToSaas)(state)) {
27
20
  return;
@@ -79,9 +79,8 @@ exports.CONSTRAINT_NAME_LIMITS = {
79
79
  VOLCENGINE_ROUTE_NAME: 63,
80
80
  FUNCTION_ROLE_NAME: 64,
81
81
  };
82
- /** Single source of truth for per-function execution role names across all providers. */
83
- const buildFunctionRoleName = (serviceName, stage, fnKey) => (0, exports.buildConstrainedName)({
84
- parts: [serviceName, stage, fnKey, 'role'],
82
+ const buildFunctionRoleName = (serviceName, stage, region, fnKey) => (0, exports.buildConstrainedName)({
83
+ parts: [serviceName, stage, region, fnKey, 'role'],
85
84
  maxLength: exports.CONSTRAINT_NAME_LIMITS.FUNCTION_ROLE_NAME,
86
85
  charset: 'hyphen',
87
86
  });